code
stringlengths
1
13.8M
context('Check list_nm_tables') simtab_test <- structure( dplyr::tibble(problem = 1, level = c(19, 20, 20, 21), subroutine = c('sig', rep('tab', 3)), code = c('0.3', 'ID OCC DOSE AMT SS II TIME TAD IPRED CWRES CPRED IWRES', 'EVID ONEHEADER NOPRINT FILE =my_sdtab-001a.tab', 'ID KA CL V ALAG1 ETAS(1:LAST) ONEHEADER NOPRINT FILE= some-tab_001.csv'), comment = ''), file = 'run001.mod', dir = 'data', class = c('nm_model', 'tbl_df', 'tbl', 'data.frame')) fail_test1 <- structure(simtab_test[1, ], file = 'run001.mod', dir = 'data', class = c('nm_model', 'tbl_df', 'tbl', 'data.frame')) fail_test2 <- structure(simtab_test[1:2, ], file = 'run001.mod', dir = 'data', class = c('nm_model', 'tbl_df', 'tbl', 'data.frame')) sdtab_test <- read_nm_model(file = 'run001.lst', dir = 'data') null_object <- as.nm.table.list(dplyr::tibble(problem = -1, file = '', firstonly = NA, simtab = NA)) test_that('error is returned when missing nm_model argument', { expect_error(list_nm_tables()) }) test_that('error is returned when input is not a nm_model', { expect_error(list_nm_tables(nm_model = dplyr::tibble(problem = 1, level = 10, subroutine = 'tab', code = 'FILE=sdtab001', comment = ''))) }) test_that('null object is returned no $TABLE are listed in the code', { expect_equal(list_nm_tables(nm_model = fail_test1), null_object) }) test_that('null object is returned no valid file names are found under $TABLE', { expect_equal(list_nm_tables(nm_model = fail_test2), null_object) }) test_that('works with simulation problems', { simtab_out <- list_nm_tables(nm_model = simtab_test) expect_true(is.nm.table.list(simtab_out)) expect_false(any(simtab_out$firstonly)) expect_true(all(simtab_out$simtab)) expect_equal(simtab_out$file, file.path('data', c('my_sdtab-001a.tab', 'some-tab_001.csv'))) }) test_that('works with estimation problems', { sdtab_out <- list_nm_tables(nm_model = sdtab_test) expect_true(is.nm.table.list(sdtab_out)) expect_equal(sdtab_out$firstonly, c(FALSE, FALSE, TRUE, TRUE, FALSE)) expect_equal(sdtab_out$simtab, c(FALSE, FALSE, FALSE, FALSE, TRUE)) expect_equal(sdtab_out$file, file.path('data', c('sdtab001', 'catab001.csv', 'cotab001', 'patab001', 'simtab001'))) })
library(testthat) library(CNAIM) context("matrix_adjusted_intervals") test_that("Default case", { risk_data_matrix <- risk_matrix_structure(2,3,NA) set.seed(2) risk_data_matrix$value <- sample(1:30,size=nrow(risk_data_matrix),replace = T) y_intervals = c(0.25, 0.25, 0.25, 0.25) x_intervals = c(0.2, 0.2, 0.2, 0.2, 0.2) res <- matrix_adjusted_intervals(risk_data_matrix,x_intervals,y_intervals) expected_df <- data.frame(x = c(1,2,1,2,1,2), y = c(1,1,2,2,3,3), value = c(21, 15, 6, 6, 8, 17), id = c(1,2,3,4,5,6), x_intervals = c("0.2","0.2","0.2","0.2","0.2", "na"), y_intervals = c("0.25","0.25","0.25","0.25","na", "na")) attr(res, "out.attrs") <- NULL expect_equal(res, expected_df) }) context("matrix_adjusted_circles") test_that("Default case", { matrix_structure <- risk_matrix_structure(2,1,NA) risk_coordinates <- risk_calculation(matrix_dimensions = matrix_structure, id = "Transformer1", pof = 0.08, cof = 18232, asset_type = "6.6/11kV Transformer (GM)") res <- matrix_adjusted_circles(matrix_structure, dots_vector = risk_coordinates, dot_radius = 4) attr(res, "out.attrs") <- NULL expected_df <- data.frame(x = c(1,2), y = c(1,1), value = c("na", "na"), id = c(1,2), point_x = c("20", "na"), point_y = c("22.7513227513227", "na"), dot_radius = c("4", "na")) expect_equal(res, expected_df) })
age_ldv <- function (x, name = "age", a = 1.698, b = -0.2, agemin = 1, agemax = 50, k = 1, bystreet = F, net, verbose = FALSE, namerows, time){ x[is.na(x)] <- 0 x <- as.numeric(x) if(length(k) > 1 & length(k) < length(x)){ stop("length of 'k' must be 1 ore equal to length of 'x'") } if(agemax < 1) stop("Agemax should be bigger than 1") if (bystreet == T){ if(length(x) != length(a)){ stop("Lengths of veh and age must be the same") } d <- suca <- list() for (i in seq_along(x)) { suca[[i]] <- function (t) {1 - exp(-exp(a[i] + b[i]*t))} anos <- seq(agemin,agemax) d[[i]] <- (-1)*diff(suca[[i]](anos)) d[[i]][length(d[[i]])+1] <- d[[i]][length(d[[i]])] d[[i]] <- d[[i]] + (1 - sum(d[[i]]))/length(d[[i]]) d[[i]] <- d[[i]]*x[i] } df <- as.data.frame(matrix(0,ncol=length(anos), nrow=1)) for (i in seq_along(x)) { df[i,] <- d[[i]] } df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df, na.rm = T)/sum(df, na.rm = T)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T)/1000, 2), "* 10^3 veh", sep=" ") ) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df*k, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df*k), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df*k, time = time)) } else { return(Vehicles(df*k)) } } } else { suca <- function (t) {1 - exp(-exp(a + b*t))} anos <- seq(agemin,agemax) d <- (-1)*diff(suca(anos)) d[length(d)+1] <- d[length(d)] d <- d + (1 - sum(d))/length(d) df <- as.data.frame(as.matrix(x) %*%matrix(d,ncol=length(anos), nrow=1)) df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df, na.rm = T)/sum(df, na.rm = T)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T), 3), " [veh]", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df, time = time)) } else { return(Vehicles(df)) } } } }
test_that('antecedents', { expect_equal(antecedents(list(c('a', 'b', 'c'), c('d'), c('a', 'e'))), list(c('b', 'c'), character(0), c('e'))) expect_error(antecedents(list(c(1, 2, 3)))) expect_error(antecedents(list(character()))) }) test_that('antecedents (single rule)', { expect_equal(antecedents(list(c('a', 'b', 'c'))), list(c('b', 'c'))) }) test_that('antecedents (empty list)', { expect_equal(antecedents(list()), list()) }) test_that('antecedents (farules)', { f <- farules(list(letters[1:3], letters[2:5]), matrix(0, nrow=2, ncol=3)) expect_equal(antecedents(f), list(letters[2:3], letters[3:5])) })
quantContig <- function(df, cloneCall = "gene+nt", chain = "both", scale=FALSE, group.by = NULL, split.by = NULL, exportTable = FALSE) { if (length(group.by) > 1) { stop("Only one item in the group.by variable can be listed.") } df <- list.input.return(df, split.by) cloneCall <- theCall(cloneCall) df <- checkBlanks(df, cloneCall) if (chain != "both") { for(i in seq_along(df)) { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } } if (!is.null(group.by)) { x <- group.by labs <- group.by Con.df <- data.frame(matrix(NA, length(df), 4)) colnames(Con.df) <- c("contigs","values", "total", group.by) for (i in seq_along(df)) { Con.df[i,1] <- length(unique(df[[i]][,cloneCall])) Con.df[i,2] <- names(df)[i] Con.df[i,3] <- length(df[[i]][,cloneCall]) location <- which(colnames(df[[i]]) == group.by) Con.df[i,4] <- df[[i]][1,location] } col <- length(unique(Con.df[,group.by])) if (scale == TRUE) { y <- "scaled" Con.df$scaled <- Con.df$contigs/Con.df$total*100 ylab <- "Percent of Unique Clonotype" } else { y <- "contigs" x <- group.by ylab <- "Unique Clonotypes"} } else { x <- "values" labs <- "Samples" Con.df <- data.frame(matrix(NA, length(df), 3)) colnames(Con.df) <- c("contigs","values", "total") for (i in seq_along(df)) { Con.df[i,1] <- length(unique(df[[i]][,cloneCall])) Con.df[i,2] <- names(df)[i] Con.df[i,3] <- length(df[[i]][,cloneCall]) } col <- length(unique(Con.df$values)) if (scale == TRUE) { y <- "scaled" Con.df$scaled <- Con.df$contigs/Con.df$total*100 ylab <- "Percent of Unique Clonotype" } else { y <- "contigs" ylab <- "Unique Clonotypes" } } if (exportTable == TRUE) { return(Con.df) } plot <- ggplot(aes(x=Con.df[,x], y=Con.df[,y], fill=as.factor(Con.df[,x])), data = Con.df) + stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge", width=.5) + labs(fill = labs) + stat_summary(fun=mean, geom="bar", color="black", lwd=0.25)+ theme_classic() + xlab("Samples") + ylab(ylab) + scale_fill_manual(values = colorblind_vector(col)) return(plot) } abundanceContig <- function(df, cloneCall = "gene+nt", chain = "both", scale=FALSE, group.by = NULL, split.by = NULL, exportTable = FALSE) { df <- list.input.return(df,split.by) Con.df <- NULL xlab <- "Abundance" cloneCall <- theCall(cloneCall) df <- checkBlanks(df, cloneCall) names <- names(df) if (!is.null(group.by)) { for (i in seq_along(df)) { if (chain != "both") { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } data1 <- parseContigs(df, i, names, cloneCall) label <- df[[i]][1,group.by] data1[,paste(group.by)] <- label Con.df<- rbind.data.frame(Con.df, data1) } Con.df <- data.frame(Con.df) col <- length(unique(Con.df[,group.by])) fill <- group.by if (scale == TRUE) { ylab <- "Density of Clonotypes" plot <- ggplot(Con.df, aes(x=Abundance, fill=Con.df[,group.by])) + geom_density(aes(y=..scaled..), alpha=0.5, lwd=0.25, color="black", bw=0.5) + scale_fill_manual(values = colorblind_vector(col)) + labs(fill = fill) } else { ylab <- "Number of Clonotypes" plot <- ggplot(Con.df, aes(x=Abundance, group.by = values, color = Con.df[,group.by])) + geom_line(stat="count") + scale_color_manual(values = colorblind_vector(col)) + labs(color = fill)} } else{ for (i in seq_along(df)) { if (chain != "both") { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } data1 <- parseContigs(df, i, names, cloneCall) Con.df<- rbind.data.frame(Con.df, data1) } col <- length(unique(Con.df$values)) fill <- "Samples" if (scale == TRUE) { ylab <- "Density of Clonotypes" plot <- ggplot(Con.df, aes(Abundance, fill=values)) + geom_density(aes(y=..scaled..), alpha=0.5, lwd=0.25, color="black", bw=0.5) + scale_fill_manual(values = colorblind_vector(col)) + labs(fill = fill) } else { ylab <- "Number of Clonotypes" plot <- ggplot(Con.df, aes(x=Abundance, group = values, color = values)) + geom_line(stat="count") + scale_color_manual(values = colorblind_vector(col)) + labs(color = fill)} } if (exportTable == TRUE) { return(Con.df)} plot <- plot + scale_x_log10() + ylab(ylab) + xlab(xlab) + theme_classic() return(plot) } lengthContig <- function(df, cloneCall = "aa", group.by = NULL, split.by = NULL, scale = FALSE, chain = "both", exportTable = FALSE) { if(cloneCall == "nt") { cloneCall <- "CTnt" ylab <- "CDR3 (NT)" } else if (cloneCall == "aa") { cloneCall <- "CTaa" ylab <- "CDR3 (AA)" } else { stop("Please make a selection of the type of CDR3 sequence to analyze by using `cloneCall`") } AB <- grep("TRA", df[[1]]$TCR1) IG <- grep("IGH", df[[1]]$TCR1) if (length(AB) > 1 && length(IG) == 0) { c1 <- "TRA" c2 <- "TRB" } else if (length(AB) > 1) { c1 <- "IGH" c2 <- "IGL" } else { c1 <- "TRD" c2 <- "TRG" } xlab <- "Length" Con.df <- NULL df <- list.input.return(df, split.by) Con.df <- lengthDF(df, cloneCall, chain, group.by, c1, c2) names <- names(df) if (!is.null(group.by)) { fill = group.by col <- length(unique(Con.df[,group.by])) if (scale == TRUE) { yplus <- "Percent of " plot <- ggplot(Con.df, aes(fill=Con.df[,group.by], length,(..count..)/sum(..count..)*100)) + geom_density(aes(y=..scaled..),alpha=.5,lwd=.25,color="black") } else { yplus <- "Number of " plot<-ggplot(Con.df,aes(as.factor(length),fill=Con.df[,group.by]))+ geom_bar(position = position_dodge2(preserve = "single"), color="black", lwd=0.25, width=0.9) + scale_x_discrete(breaks = round(seq(min(Con.df$length), max(Con.df$length), by = 5),10)) } } else if (is.null(group.by)){ fill <- "Samples" col <- length(unique(Con.df$values)) if (scale == TRUE) { yplus <- "Percent of " plot <- ggplot(Con.df, aes(length, (..count..)/sum(..count..)*100, fill=values)) + geom_density(aes(y=..scaled..), alpha=0.5, lwd=0.25, color="black") } else { yplus <- "Number of " plot <- ggplot(Con.df, aes(as.factor(length), fill=values)) + geom_bar(position = position_dodge2(preserve = "single"), color="black", lwd=0.25) + scale_x_discrete(breaks = round(seq(min(Con.df$length), max(Con.df$length), by = 5),10))} } plot <- plot + scale_fill_manual(values = colorblind_vector(col)) + labs(fill = fill) + ylab(paste(yplus, ylab, sep="")) + xlab(xlab) + theme_classic() if (exportTable == TRUE) { return(Con.df) } return(plot)} compareClonotypes <- function(df, cloneCall = "gene+nt", chain = "both", samples = NULL, clonotypes = NULL, numbers = NULL, split.by = NULL, graph = "alluvial", exportTable = FALSE){ df <- list.input.return(df, split.by) cloneCall <- theCall(cloneCall) df <- checkBlanks(df, cloneCall) if (!is.null(numbers) & !is.null(clonotypes)) { stop("Make sure your inputs are either numbers or clonotype sequences.") } Con.df <- NULL for (i in seq_along(df)) { if (chain != "both") { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } tbl <- as.data.frame(table(df[[i]][,cloneCall])) tbl[,2] <- tbl[,2]/sum(tbl[,2]) colnames(tbl) <- c("Clonotypes", "Proportion") tbl$Sample <- names(df[i]) Con.df <- rbind.data.frame(Con.df, tbl) } if (!is.null(samples)) { Con.df <- Con.df[Con.df$Sample %in% samples,] } if (!is.null(clonotypes)) { Con.df <- Con.df[Con.df$Clonotypes %in% clonotypes,] } if (!is.null(numbers)) { top <- Con.df %>% top_n(n = numbers, wt = Proportion) Con.df <- Con.df[Con.df$Clonotypes %in% top$Clonotypes,] } if (nrow(Con.df) < length(unique(Con.df$Sample))) { stop("Reasses the filtering strategies here, there is not enough clonotypes to examine.") } if (exportTable == TRUE) { return(Con.df)} plot <- ggplot(Con.df, aes(x = Sample, fill = Clonotypes, group = Clonotypes, stratum = Clonotypes, alluvium = Clonotypes, y = Proportion, label = Clonotypes)) + theme_classic() + theme(axis.title.x = element_blank()) if (graph == "alluvial") { plot = plot + geom_stratum() + geom_flow(stat = "alluvium") } else if (graph == "area") { plot = plot + geom_area(aes(group = Clonotypes), color = "black") } return(plot) } scatterClonotype <- function(df, cloneCall ="gene+nt", x.axis = NULL, y.axis = NULL, chain = "both", dot.size = "total", split.by = NULL, graph = "proportion", exportTable = FALSE) { df <- list.input.return(df, split.by) cloneCall <- theCall(cloneCall) axes <- which(names(df) %in% c(x.axis, y.axis, dot.size)) if (chain != "both") { for (i in axes) { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } } x.df <- as.data.frame(table(df[[x.axis]][,cloneCall])) colnames(x.df)[2] <- x.axis y.df <- as.data.frame(table(df[[y.axis]][,cloneCall])) colnames(y.df)[2] <- y.axis combined.df <- merge(x.df, y.df, by = "Var1", all = TRUE) if (dot.size != "total") { if (dot.size %!in% colnames(combined.df)) { size.df <- as.data.frame(table(df[[dot.size]][,cloneCall])) colnames(size.df)[2] <- dot.size combined.df <- merge(combined.df, size.df, by = "Var1", all = TRUE) } combined.df[is.na(combined.df)] <- 0 combined.df[,paste0("size", ".fraction")] <- combined.df[,dot.size]/sum(combined.df[,dot.size]) labeling <- unique(c(x.axis, y.axis, dot.size)) } else { combined.df[is.na(combined.df)] <- 0 labeling <- unique(c(x.axis, y.axis)) } combined.df[,"class"] <- NA combined.df[,"sum"] <- rowSums(combined.df[,labeling]) for (i in seq_along(labeling)) { if (length(labeling) > 2) { combined.df[,"class"] <- ifelse(combined.df[,labeling[i]] == 1 & rowSums(combined.df[,labeling[which(labeling != labeling[i])]]) == 0, paste0(labeling[i], ".singlet"), combined.df[,"class"]) combined.df[,"class"] <- ifelse(combined.df[,labeling[i]] > 1 & rowSums(combined.df[,labeling[which(labeling != labeling[i])]]) == 0, paste0(labeling[i], ".multiplet"), combined.df[,"class"]) } else if (length(labeling) == 2) { combined.df[,"class"] <- ifelse(combined.df[,labeling[i]] == 1 & combined.df[,labeling[which(labeling != labeling[i])]] == 0, paste0(labeling[i], ".singlet"), combined.df[,"class"]) combined.df[,"class"] <- ifelse(combined.df[,labeling[i]] > 1 & combined.df[,labeling[which(labeling != labeling[i])]] == 0, paste0(labeling[i], ".multiplet"), combined.df[,"class"]) }} combined.df[,"class"] <- ifelse(combined.df[,y.axis] >= 1 & combined.df[,x.axis] >= 1, paste0("dual.expanded"), combined.df[,"class"]) combined.df[,paste0(x.axis, ".fraction")] <- combined.df[,x.axis]/sum(combined.df[,x.axis]) combined.df[,paste0(y.axis, ".fraction")] <- combined.df[,y.axis]/sum(combined.df[,y.axis]) if (graph == "proportion") { x <- combined.df[,paste0(x.axis, ".fraction")] y <- combined.df[,paste0(y.axis, ".fraction")] } else if (graph == "count") { x <- combined.df[,x.axis] y <- combined.df[,y.axis] } if (dot.size != "total") { size <- combined.df[,dot.size] } else { size <- combined.df[,"sum"] } if (exportTable == TRUE) { return(combined.df) } plot <- ggplot(combined.df, aes(x=x, y = y, color = class)) + theme_classic() + scale_color_manual(values = colorblind_vector(length(unique(combined.df$class)))) + xlab(x.axis) + ylab(y.axis) + labs(size = "Total n") if (graph == "proportion") { plot <- plot + geom_abline(slope = 1, intercept = 0, alpha = 0.4, lty=2) + scale_y_sqrt() + scale_x_sqrt() } else if (graph == "count") { plot <- plot + ylim(0, max(x,y)) + xlim(0, max(x,y)) } plot <- plot + geom_jitter(aes(size = size)) return(plot) } clonesizeDistribution <- function(df, cloneCall ="gene+nt", chain = "both", method = "ward.D2", threshold = 1, split.by = NULL, exportTable = FALSE) { df <- list.input.return(df, split.by) cloneCall <- theCall(cloneCall) df <- checkBlanks(df, cloneCall) data <- bind_rows(df) unique_df <- unique(data[,cloneCall]) Con.df <- data.frame(matrix(NA, length(unique_df), length(df))) Con.df <- data.frame(unique_df, Con.df, stringsAsFactors = FALSE) colnames(Con.df)[1] <- "clonotype" for (i in seq_along(df)) { if (chain != "both") { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } data <- df[[i]] data <- data.frame(table(data[,cloneCall]), stringsAsFactors = FALSE) colnames(data) <- c(cloneCall, "Freq") for (y in seq_along(unique_df)){ clonotype.y <- Con.df$clonotype[y] location.y <- which(clonotype.y == data[,cloneCall]) Con.df[y,i+1] <- data[location.y[1],"Freq"] } } colnames(Con.df)[2:(length(df)+1)] <- names(df) Con.df[is.na(Con.df)] <- 0 list <- list() for (i in seq_along(df)) { list[[i]] <- Con.df[,i+1] list[[i]] <- suppressWarnings(fdiscgammagpd(list[[i]], useq = threshold)) } names(list) <- names(df) grid <- 0:10000 distances <- get_distances(list, grid, modelType="Spliced") hclust <- hclust(as.dist(distances), method = method) hcd <- as.dendrogram(hclust) plot <- plot(hcd) if (exportTable == TRUE) { return(distances) } return(plot) } colorblind_vector <- colorRampPalette(rev(c(" " makingLodes <- function(meta2, color, alpha, facet, set.axes) { if (!is.null(color) & !is.null(alpha) & !is.null(facet)) { lodes <- to_lodes_form(meta2,key="x",value="stratum",id="alluvium", axes=set.axes,diffuse=c(as.name(color),as.name(alpha),as.name(facet))) } else if (!is.null(color) & !is.null(alpha) & is.null(facet)) { lodes <- to_lodes_form(meta2,key="x",value="stratum",id="alluvium", axes = set.axes, diffuse = c(as.name(color), as.name(alpha))) } else if (!is.null(color) & is.null(alpha) & !is.null(facet)) { lodes <- to_lodes_form(meta2,key="x",value="stratum",id ="alluvium", axes =set.axes, diffuse = c(as.name(color), as.name(facet))) } else if (is.null(color) & is.null(alpha) & !is.null(facet)) { lodes <- to_lodes_form(meta2, key = "x", value = "stratum", id="alluvium",axes=set.axes,diffuse=c(as.name(alpha),as.name(facet))) } else if (is.null(color) & is.null(alpha) & !is.null(facet)) { lodes <- to_lodes_form(meta2, key = "x", value = "stratum", id = "alluvium", axes = set.axes, diffuse = c(as.name(facet))) } else if (!is.null(color) & is.null(alpha) & is.null(facet)) { lodes <- to_lodes_form(meta2, key = "x", value = "stratum", id = "alluvium", axes = set.axes, diffuse = c(as.name(color))) } else if (is.null(color) & !is.null(alpha) & is.null(facet)) { lodes <- to_lodes_form(meta2, key = "x", value = "stratum", id = "alluvium", axes = set.axes, diffuse = c(as.name(alpha))) } else { lodes <- to_lodes_form(meta2, key = "x", value = "stratum", id = "alluvium", axes = set.axes)} return(lodes) } vizGenes <- function(df, gene = "V", chain = "TRA", plot = "heatmap", y.axis = "sample", order = "gene", scale = TRUE, exportTable = FALSE) { for(i in seq_along(df)) { df[[i]] <- off.the.chain(df[[i]], chain, "CTgene") } df <- bound.input.return(df) if (y.axis %!in% colnames(df) | is.null(y.axis)) { if (y.axis %!in% c("V", "D", "J", "C")) { y.axis <- "element.names" } else { df <- select.gene(df, chain, y.axis) colnames(df)[ncol(df)] <- y.axis } } df <- select.gene(df, chain, gene) df <- subset(df, !is.na(df[,ncol(df)])) df <- subset(df, df[,ncol(df)] != "NA") df <- subset(df, df[,ncol(df)] != "") if (!is.null(y.axis) && y.axis != "element.names") { df <- df %>% group_by(df[,ncol(df)], df[,y.axis], element.names) %>% count() } else { df <- df %>% group_by(df[,ncol(df)], element.names) %>% count() } df <- df %>% group_by(element.names) %>% mutate(sum = sum(n)) col.lab <- "Total n" if (scale == TRUE) { df[,"n"] <- df[,"n"]/df[,"sum"] col.lab <- "Scaled Values" } colnames(df)[1:2] <- c("Var1", "Var2") df <- df %>% group_by(Var1, Var2) %>% mutate(varcount = sum(n), sd = sd(n, na.rm = TRUE), mean = mean(n)) if (order == "variance") { varOrder <- order(df$varcount, decreasing = TRUE) df$Var1 <- factor(df$Var1, levels = unique(df$Var1[varOrder])) } if (plot == "bar") { df2 <- unique(df[,c("Var1", "Var2", "sd", "mean")]) plot <- ggplot(df2, aes(x=Var1, y = mean)) + geom_bar(stat = "identity") + geom_errorbar(aes(ymin=mean, ymax=mean+sd), width=.2, position=position_dodge(.9)) + theme_classic() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size=rel(0.5))) + facet_grid(Var2~.) } else if (plot == "heatmap") { plot <- ggplot(df, aes(x=Var1, y = Var2, fill = n)) + geom_tile() + theme_classic() + labs(fill = col.lab) + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size=rel(0.5)), axis.title.y = element_blank(), axis.text.y = element_text(size=rel(0.5))) + scale_fill_gradientn(colors = rev(colorblind_vector(5))) } if (exportTable == TRUE) { return(df) } return(plot) }
anovaRMNPOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMNPOptions", inherit = jmvcore::Options, public = list( initialize = function( measures = NULL, pairs = FALSE, desc = FALSE, plots = FALSE, plotType = "means", ...) { super$initialize( package="jmv", name="anovaRMNP", requiresData=TRUE, ...) private$..measures <- jmvcore::OptionVariables$new( "measures", measures, suggested=list( "continuous"), permitted=list( "numeric")) private$..pairs <- jmvcore::OptionBool$new( "pairs", pairs, default=FALSE) private$..desc <- jmvcore::OptionBool$new( "desc", desc, default=FALSE) private$..plots <- jmvcore::OptionBool$new( "plots", plots, default=FALSE) private$..plotType <- jmvcore::OptionList$new( "plotType", plotType, options=list( "means", "medians"), default="means") self$.addOption(private$..measures) self$.addOption(private$..pairs) self$.addOption(private$..desc) self$.addOption(private$..plots) self$.addOption(private$..plotType) }), active = list( measures = function() private$..measures$value, pairs = function() private$..pairs$value, desc = function() private$..desc$value, plots = function() private$..plots$value, plotType = function() private$..plotType$value), private = list( ..measures = NA, ..pairs = NA, ..desc = NA, ..plots = NA, ..plotType = NA) ) anovaRMNPResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMNPResults", inherit = jmvcore::Group, active = list( table = function() private$.items[["table"]], comp = function() private$.items[["comp"]], desc = function() private$.items[["desc"]], plot = function() private$.items[["plot"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Repeated Measures ANOVA (Non-parametric)") self$add(jmvcore::Table$new( options=options, name="table", title="Friedman", rows=1, clearWith=list( "measures"), columns=list( list( `name`="stat", `title`="\u03C7\u00B2", `type`="number"), list( `name`="df", `title`="df", `type`="integer"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue")))) self$add(jmvcore::Table$new( options=options, name="comp", title="Pairwise Comparisons (Durbin-Conover)", refs="PMCMR", visible="(pairs)", clearWith=list( "measures"), columns=list( list( `name`="i1", `title`="", `type`="text"), list( `name`="sep", `title`="", `content`="-", `type`="text", `format`="narrow"), list( `name`="i2", `title`="", `type`="text"), list( `name`="stat", `title`="Statistic", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue")))) self$add(jmvcore::Table$new( options=options, name="desc", title="Descriptives", visible="(desc)", clearWith=list( "measures"), columns=list( list( `name`="level", `title`="", `type`="text"), list( `name`="mean", `title`="Mean", `type`="number"), list( `name`="median", `title`="Median", `type`="number")))) self$add(jmvcore::Image$new( options=options, name="plot", title="Descriptive Plot", visible="(plots)", renderFun=".plot", clearWith=list( "plotType", "measures")))})) anovaRMNPBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "anovaRMNPBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "jmv", name = "anovaRMNP", version = c(1,0,0), options = options, results = anovaRMNPResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = TRUE, requiresMissings = FALSE) })) anovaRMNP <- function( data, measures, pairs = FALSE, desc = FALSE, plots = FALSE, plotType = "means") { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("anovaRMNP requires jmvcore to be installed (restart may be required)") if ( ! missing(measures)) measures <- jmvcore::resolveQuo(jmvcore::enquo(measures)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(measures), measures, NULL)) options <- anovaRMNPOptions$new( measures = measures, pairs = pairs, desc = desc, plots = plots, plotType = plotType) analysis <- anovaRMNPClass$new( options = options, data = data) analysis$run() analysis$results }
algos <- eval(formals(ml_fit)$algorithm) test_that("success = TRUE", { minitoy <- readRDS(toy_example("Tiny")) for (algo in algos) { fit <- ml_fit(minitoy, algo) expect_true(fit$success, info = algo) expect_equal(length(fit$residuals), 5, info = algo) expect_lt(max(abs(fit$residuals)), 1e-3) expect_equal(length(fit$rel_residuals), 5, info = algo) expect_lt(max(abs(fit$rel_residuals)), 1e-6) expect_equal(length(fit$flat_weighted_values), 5, info = algo) expect_equal(length(fit$weights), 23, info = algo) expect_equal(length(fit$flat_weights), 8, info = algo) expect_equal(fit$tol, 1e-6, info = algo) expect_type(fit$iterations, "integer") } }) test_that("success = FALSE", { bad_problem <- readRDS(toy_example("Conflict")) for (algo in algos) { fit <- ml_fit(bad_problem, algo) expect_false(fit$success, info = algo) } })
context('alluvial_long') test_that('alluvial_long' ,{ data = quarterly_flights p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill = carrier ) expect_doppelganger('long_fill_carrier', p) p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill_by = 'last_variable' ) expect_doppelganger('long_fill_last', p) p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill_by = 'first_variable' ) expect_doppelganger('long_fill_first', p) p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill_by = 'all_flows' ) expect_doppelganger('long_fill_value', p) p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill_by = 'value' ) p = alluvial_long( data, key = 'qu', value = 'mean_arr_delay', id = 'tailnum', fill = 'carrier' ) p = alluvial_long( data, qu, mean_arr_delay, tailnum, fill_by = 'value' , col_vector_flow = palette_qualitative() %>% palette_filter(greys = F, bright = F) , col_vector_value = palette_qualitative() %>% palette_filter(greys = F, bright = F) ) expect_doppelganger('long_sprecify_color', p) p = alluvial_long( data, qu, mean_arr_delay, tailnum, carrier ,fill_right = F ) expect_doppelganger('long_fill_to_right', p) p = alluvial_long( data, qu, mean_arr_delay, tailnum, fill_by = 'first_variable' , order_levels_value = c('on_time', 'late') ) expect_doppelganger('long_reorder_y_levels', p) p = alluvial_long( data, qu, mean_arr_delay, tailnum, fill_by = 'first_variable' , order_levels_key = c('Q4', 'Q3', 'Q2', 'Q1') ) expect_doppelganger('long_reorder_x_levels', p) order_by_carrier_size = data %>% group_by(carrier) %>% count() %>% arrange( desc(n) ) %>% .[['carrier']] p = alluvial_long( data, qu, mean_arr_delay, tailnum, carrier , order_levels_fill = order_by_carrier_size ) expect_doppelganger('long_reorder_carrier_by_size', p) expect_equivalent( unique(data$tailnum), levels( p$data_key$tailnum ) ) data = quarterly_flights %>% select(tailnum, qu, mean_arr_delay, carrier) %>% sample_frac(0.9) p = alluvial_long( data, qu, mean_arr_delay, tailnum, carrier , NA_label = 'none' , order_levels_value = 'none') p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill = carrier , stratum_labels = FALSE, stratum_width = 1/20) p = alluvial_long( data, key = qu, value = mean_arr_delay, id = tailnum, fill = carrier , auto_rotate_xlabs = F ) suppressWarnings({ data_highflow = ggplot2::diamonds %>% mutate( id = as.factor( row_number() ) ) %>% manip_bin_numerics() %>% gather( key = 'key', value = 'value', -id) }) expect_warning( alluvial_long( data_highflow, key, value, id ) ) p = alluvial_long( group_by(data, carrier), key = qu, value = mean_arr_delay, id = tailnum) expect_true( all( c('data_key', 'alluvial_type', 'alluvial_params') %in% names(p) ) ) p = alluvial_long(quarterly_sunspots, key = qu, value = spots, id = year) expect_doppelganger('long_all_nums', p) p = alluvial_long(quarterly_sunspots, key = qu, value = spots, id = year, fill = mean_spots_per_year) expect_doppelganger('long_all_nums_plus_fill', p) })
time_calc <- function(time_event, time_obs, units=NULL) UseMethod("time_calc") time_calc.numeric <- function(time_event, time_obs, units=NULL) { if (length(time_event) == 0) { warning("No events provided") time_event <- NA_real_ } else if (any(order(stats::na.omit(time_event)) != seq_along(stats::na.omit(time_event)))) { stop("`time_event` must be sorted.") } if (!is.numeric(time_obs)) { stop("Both `time_event` and `time_obs` must be the same class (numeric).") } ret <- data.frame( event_number_before= sapply( X=time_obs, FUN=function(x) max_zero_len( which(time_event <= x), zero_length=NA_integer_ ) ), event_number_after= sapply( X=time_obs, FUN=function(x) min_zero_len( which(time_event >= x), zero_length=NA_integer_ ) ) ) ret$time_after_event <- time_obs - time_event[ret$event_number_before] ret$time_before_event <- time_obs - time_event[ret$event_number_after] ret$time_after_first <- if (all(is.na(time_event))) { NA_real_ } else { time_obs - min(time_event, na.rm=TRUE) } ret } time_calc.POSIXt <- function(time_event, time_obs, units=NULL) { if (is.null(units)) { stop("`units` must be provided.") } if (!("POSIXt" %in% class(time_obs))) { stop("Both `time_event` and `time_obs` must be the same class (POSIXt).") } first_event <- min(time_event, na.rm=TRUE) time_calc( time_event=difftime(time_event, first_event, units=units), time_obs=difftime(time_obs, first_event, units=units), units=units ) } time_calc.difftime <- function(time_event, time_obs, units=NULL) { if (is.null(units)) { stop("`units` must be provided.") } if (!("difftime" %in% class(time_obs))) { stop("Both `time_event` and `time_obs` must be the same class (difftime).") } time_calc( time_event=as.numeric(time_event, units=units), time_obs=as.numeric(time_obs, units=units) ) }
test_that("find_y works with mlr", { require("mlr") data(cars, package = "datasets") tsk <- makeRegrTask(data = cars, target = "dist") lrn <- makeLearner("regr.rpart") mod <- mlr::train(lrn, tsk) expect_equal(find_y(mod), "dist") }) test_that("find_y works with caret", { require("caret") data(cars, package = "caret") mod <- caret::train(Price ~ ., data = cars, method = "rf", ntree = 1) expect_equal(find_y(mod), "Price") }) test_that("find_y works with lm", { data(cars, package = "datasets") mod <- lm(speed ~ ., data = cars) expect_equal(find_y(mod), "speed") }) test_that("find_y works with rpart", { require("rpart") data(cars, package = "datasets") mod <- rpart(speed ~ ., data = cars) expect_equal(find_y(mod), "speed") })
event_range <- function(e) { as_events(range(e$from, e$to)) } event_coverage <- function(e, closed = TRUE) { e.range <- event_range(e) e.gaps <- event_gaps(e, closed = closed) e.coverage <- event_gaps(e.gaps, closed = FALSE, range = e.range) add <- e.range != event_range(e.coverage) if (!closed) { add[1] <- add[1] || any(rowSums(e[c("from", "to")] == e.range[[1]]) == 2) add[2] <- add[2] || any(rowSums(e[c("from", "to")] == e.range[[2]]) == 2) } if (any(add)) { e.coverage <- rbind(if_else(add[[1]], rep(e.range[[1]], 2), NULL), e.coverage, if_else(add[[2]], rep(e.range[[2]], 2), NULL)) } e.coverage } event_gaps <- function(e, closed = TRUE, range = NULL) { if (!is.null(range)) { range <- event_range(range) if (!nrow(e)) { return(range) } e.range <- event_range(e) if (!(range$from <= e.range$from && range$to >= e.range$to)) { e <- crop_events(e, range) } if (range$from < e.range$from) { e <- rbind(rep(range$from, 2), e[c("from", "to")]) } if (range$to > e.range$to) { e <- rbind(e[c("from", "to")], rep(range$to, 2)) } } if (is_unsorted_events(e)) { e <- sort_events(e) } e$to <- cummax(e$to) if (closed) { isgap <- which(e$from[-1] > e$to[-nrow(e)]) } else { isgap <- which(e$from[-1] >= e$to[-nrow(e)]) } unique(events(e$to[isgap], e$from[isgap + 1])) } event_overlaps <- function(e) { if (is_unsorted_events(e)) { e <- sort_events(e) } e.cut <- cut_events(e, c(e$from, e$to)) temp <- stats::aggregate(e.cut$from, by = e.cut[c("from","to")], FUN = length) names(temp)[3] <- "n" temp } event_midpoints <- function(e) { rowMeans(e[c("from", "to")]) }
set.seed(1) x <- 1L:30L x2 <- as.numeric(1:30) x3 <- sample(letters, 30, replace = TRUE) x4 <- sample(c(TRUE, FALSE), 30, replace = TRUE) lag <- sample(-10:10, 30, replace = TRUE) idx <- cumsum(sample(seq_len(5), 30, replace = TRUE)) lag_run2 <- function(x, lag = 1, idx = seq_along(x), nearest = FALSE) { fun <- function(x, k, idx, nearest, i) { res <- if (nearest) { window <- if (k > 0) { x[idx %in% seq(idx[i] - k, idx[i] - 1, by = 1)] } else if (k < 0) { x[idx %in% seq(idx[i] + 1, idx[i] - k, by = 1)] } else { return(x[i]); } if (length(window) > 0) { if (k > 0) window[1] else rev(window)[1] } else { NA } } else if (!nearest) { window <- if (k != 0) { x[idx == (idx[i] - k)] } else { return(x[i]); } res <- if (length(window) > 0) { if (k > 0) window[1] else rev(window)[1] } else { NA } } return(res) } sapply(seq_along(x), function(i) { if (length(lag) == 1) { fun(x, lag[1], idx, nearest, i) } else { fun(x, lag[i], idx, nearest, i) } }) } expect_identical( lag_run(x), c(NA, x[-30]) ) expect_identical( lag_run(as.character(x)), as.character(c(NA_character_, x[-30])) ) expect_identical( lag_run(as.factor(letters)), c(NA_integer_, 1:25) ) expect_identical( lag_run(as.integer(round(x))), as.integer(round(c(NA_integer_, x[-30]))) ) expect_identical( lag_run(as.complex(x)), as.complex(c(NA_complex_, x[-30])) ) expect_identical( lag_run(x > 15), c(NA, x[-30] > 15) ) expect_identical(lag_run(x, lag = 3), c(rep(NA, 3), head(x, -3))) expect_identical(lag_run(x2, lag = 3), c(rep(NA, 3), head(x2, -3))) expect_identical(lag_run(x3, lag = 3), c(rep(NA, 3), head(x3, -3))) expect_identical(lag_run(x4, lag = 3), c(rep(NA, 3), head(x4, -3))) expect_identical(lag_run(x, lag = lag), lag_run2(x, lag = lag)) expect_identical(lag_run(x, lag = lag, nearest = FALSE), lag_run2(x, lag = lag, nearest = FALSE)) expect_identical(lag_run(x2, lag = lag), lag_run2(x2, lag = lag)) expect_identical(lag_run(x2, lag = lag, nearest = FALSE), lag_run2(x2, lag = lag, nearest = FALSE)) expect_identical(lag_run(x3, lag = lag), lag_run2(x3, lag = lag)) expect_identical(lag_run(x3, lag = lag, nearest = FALSE), lag_run2(x3, lag = lag, nearest = FALSE)) expect_identical(lag_run(x4, lag = lag), lag_run2(x4, lag = lag)) expect_identical(lag_run(x4, lag = lag, nearest = FALSE), lag_run2(x4, lag = lag, nearest = FALSE)) expect_identical(lag_run(x, lag = 3, idx = idx, nearest = TRUE), lag_run2(x, lag = 3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x, lag = 3, idx = idx, nearest = FALSE), lag_run2(x, lag = 3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x, lag = -3, idx = idx, nearest = TRUE), lag_run2(x, lag = -3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x, lag = -3, idx = idx, nearest = FALSE), lag_run2(x, lag = -3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x, lag = lag, idx = idx, nearest = TRUE), lag_run2(x, lag = lag, idx = idx, nearest = TRUE)) expect_identical(lag_run(x, lag = lag, idx = idx, nearest = FALSE), lag_run2(x, lag = lag, idx = idx, nearest = FALSE)) expect_identical(lag_run(x2, lag = 3, idx = idx, nearest = TRUE), lag_run2(x2, lag = 3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x2, lag = 3, idx = idx, nearest = FALSE), lag_run2(x2, lag = 3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x2, lag = -3, idx = idx, nearest = TRUE), lag_run2(x2, lag = -3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x2, lag = -3, idx = idx, nearest = FALSE), lag_run2(x2, lag = -3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x2, lag = lag, idx = idx, nearest = TRUE), lag_run2(x2, lag = lag, idx = idx, nearest = TRUE)) expect_identical(lag_run(x2, lag = lag, idx = idx, nearest = FALSE), lag_run2(x2, lag = lag, idx = idx, nearest = FALSE)) expect_identical(lag_run(x3, lag = 3, idx = idx, nearest = TRUE), lag_run2(x3, lag = 3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x3, lag = 3, idx = idx, nearest = FALSE), lag_run2(x3, lag = 3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x3, lag = -3, idx = idx, nearest = TRUE), lag_run2(x3, lag = -3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x3, lag = -3, idx = idx, nearest = FALSE), lag_run2(x3, lag = -3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x3, lag = lag, idx = idx, nearest = TRUE), lag_run2(x3, lag = lag, idx = idx, nearest = TRUE)) expect_identical(lag_run(x3, lag = lag, idx = idx, nearest = FALSE), lag_run2(x3, lag = lag, idx = idx, nearest = FALSE)) expect_identical(lag_run(x4, lag = 3, idx = idx, nearest = TRUE), lag_run2(x4, lag = 3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x4, lag = 3, idx = idx, nearest = FALSE), lag_run2(x4, lag = 3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x4, lag = -3, idx = idx, nearest = TRUE), lag_run2(x4, lag = -3, idx = idx, nearest = TRUE)) expect_identical(lag_run(x4, lag = -3, idx = idx, nearest = FALSE), lag_run2(x4, lag = -3, idx = idx, nearest = FALSE)) expect_identical(lag_run(x4, lag = lag, idx = idx, nearest = TRUE), lag_run2(x4, lag = lag, idx = idx, nearest = TRUE)) expect_identical(lag_run(x4, lag = lag, idx = idx, nearest = FALSE), lag_run2(x4, lag = lag, idx = idx, nearest = FALSE)) expect_error(lag_run(x, lag = (1:9)), "length of lag and length of x differs") expect_error(min_run(x, lag = c(NA, lag[-1])), "Function doesn't accept NA values in lag vector") expect_error(lag_run(x, idx = (1:9)), "length of idx and length of x differs") expect_error(lag_run(x, idx = c(NA, 1:29)), "Function doesn't accept NA values in idx vector") expect_error(lag_run(x, idx = sample(1:30)), "idx have to be in ascending order")
"travel_insurance"
.onLoad <- function(libname, pkgname) { reticulate::configure_environment(pkgname) }
library(httr) nouns_app <- oauth_app("noun_project", key = rstudioapi::askForPassword(), secret = rstudioapi::askForPassword() ) url <- "http://api.thenounproject.com/icon/15" signature <- oauth_signature(url, method = "GET", app = nouns_app) res <- GET(url, oauth_header(signature)) stop_for_status(res) content(res) get_nouns_api <- function(endpoint, baseurl = "http://api.thenounproject.com/", app = nouns_app, ...) { url <- modify_url(baseurl, path = endpoint) info <- oauth_signature(url, app = app) header_oauth <- oauth_header(info) GET(url, header_oauth, ...) } res <- get_nouns_api("collections") stop_for_status(res) content(res) url <- "http://api.thenounproject.com/notify/publish?test=1" signature <- oauth_signature(url, method = "POST", app = nouns_app) res <- POST(url, oauth_header(signature), body = list(icons = 15), encode = "json") stop_for_status(res) content(res)
library("lorentz") u <- as.3vel(c(0.6,0,0)) u as.4vel(u) (B <- boost(u)) B %*% c(1,0,0,0) B %*% c(4,6,-8,9) B %*% c(1,1,0,0) B %*% c(1,-1,0,0) (B <- boost(as.3vel(c(0.8,0,0)))) solve(B) %*% c(1,0,0,0) u <- as.3vel(c(0.3,-0.4,+0.8)) v <- as.3vel(c(0.4,+0.2,-0.1)) L <- boost(u) %*% boost(v) L (P <- pureboost(L)) P - t(P) (U <- orthog(L)) U[2:4,2:4] round(crossprod(U) - diag(4),10) sol(299792458) sol() u <- as.3vel(c(100,200,300)) as.4vel(u) gam(u) gam(u)-1 gamm1(u) boost(u) sol(299792458) disp <- c(1,1,0,0) ptm(to_natural=TRUE) %*% disp ptm(to_natural=TRUE,change_time=FALSE) %*% disp sol(1) B1 <- boost((2:4)/10) %*% boost(c(-5,1,3)/10) orthog(B1)[2:4,2:4] sol(10) B2 <- boost(2:4) %*% boost(c(-5,1,3)) orthog(B2)[2:4,2:4] sol(Inf) u <- as.3vel(1:3) v <- as.3vel(c(-6,8,3)) u+v boost(u) gamm1(1e100) set.seed(0) options(digits=3) (B <- rboost(1)) orthog(B) pureboost(B) sol(10) u <- as.3vel(c(5,-6,4)) (U <- as.4vel(u)) B <- boost(U) B %*% as.vector(U) u <- 1:7 jj <- cbind(gam(u),gam(u)*u,0,0) (U <- as.4vel(jj)) (B <- boost(as.3vel(c(6,0,0)))) U %*% t(B) is.consistent.4vel(U %*% t(B)) tcrossprod(U,B) solve(B) tcrossprod(U,solve(B)) is.consistent.4vel(tcrossprod(U,solve(B))) sol(100) B1 <- boost(r3vel(1)) %*% boost(r3vel(1)) B2 <- boost(r3vel(1)) %*% boost(r3vel(1)) (U <- r4vel(5)) U %*% t(B1) %*% t(B2) U %*% t(B2 %*% B1) tcrossprod(U, B2 %*% B1) U %>% tcrossprod(B2 %*% B1) U %*% B sol(1) D <- dust(1) D B <- boost(as.3vel(c(0.0,0.8,0.0))) transform_uu(D,B) pg <- photongas(3) pg transform_uu(pg,B) raise(transform_dd(lower(pg),lower(B))) raise(transform_dd(lower(pg),lower(B))) - transform_uu(pg,B) B1 <- boost(as.3vel(c(0.5,-0.4,0.6))) B2 <- boost(as.3vel(c(0.1,-0.1,0.3))) pf <- perfectfluid(4,1) pf pf %>% transform_uu(B1) %>% transform_uu(B2) pf %>% transform_uu(B2 %*% B1) lower(pf) %>% transform_dd(lower(B1) %*% lower(B2)) %>% raise() sol(10) pf_rest <- perfectfluid(1,4) pf_rest u <- as.3vel(3:5) pf_moving <- perfectfluid(1,4,u) pf_moving transform_uu(perfectfluid(1,4,u),boost(u)) sol(1) (A <- as.photon(as.3vel(cbind(0.9,1:5/40,5:1/40)))) inner4(A) tcrossprod(A,boost(as.3vel(c(0.7,0,0)))) tcrossprod(A,boost(as.3vel(c(-0.7,0,0)))) tcrossprod(A,solve(boost(as.3vel(c(0.7,0,0))))) m <- c(1,1,1) B <- boost(as.3vel(c(0.5,0,0))) A (A <- as.4mom(A %*% t(B))) (A <- reflect(A,m)) (A <- as.4mom(A %*% solve(t(B)))) A <- as.photon(as.3vel(cbind(0.9,1:5/40,5:1/40))) A %>% tcrossprod(B) %>% reflect(m) %>% tcrossprod(solve(B)) %>% as.4mom disco <- matrix(rnorm(3000),ncol=3) %>% sweep(1, sqrt(rowSums(.^2)),`/`) head(disco) p <- as.photon(c(1,0,0)) reflect(p,head(disco)) table(reflect(p,disco)[,2]>0) B <- boost(as.3vel(c(0.5,0,0))) p %>% tcrossprod(B) %>% reflect(head(disco)) %>% tcrossprod(solve(B)) sol(1) light_start <- as.photon(as.3vel(cbind(0.9,1:5/40,5:1/40))) m <- c(1,0,0) B1 <- boost(as.3vel(c(-0.5, 0.1, 0.0))) B2 <- boost(as.3vel(c( 0.2, 0.0, 0.0))) B3 <- boost(as.3vel(c( 0.0, 0.0, 0.6))) B <- B1 %*% B2 %*% B3 light <- light_start %*% t(B) light <- reflect(light,m) light <- as.4mom(light %*% solve(t(B))) light light_start %>% tcrossprod(B) %>% reflect(m) %>% tcrossprod(solve(B)) %>% as.4mom sol(Inf) light_start <- as.photon(as.3vel(cbind(0.9,1:5/40,5:1/40))) B1 <- boost(as.3vel(c(-0.5, 0.1, 0.0))) B2 <- boost(as.3vel(c( 0.2, 0.0, 0.0))) B3 <- boost(as.3vel(c( 0.0, 0.0, 0.6))) B <- B1 %*% B2 %*% B3 light_start light_start %>% tcrossprod(B) %>% reflect(m) %>% tcrossprod(solve(B)) %>% as.4mom sol(1) u <- as.3vel(c(-0.7,+0.2,-0.3)) v <- as.3vel(c(+0.3,+0.3,+0.4)) w <- as.3vel(c(+0.1,+0.3,+0.8)) x <- as.3vel(c(-0.2,-0.1,-0.9)) u u+v v+u (u+v)-gyr(u,v,v+u) f <- gyrfun(u,v) (u+v)-f(v+u) u9 <- r3vel(9) u9 f <- gyrfun(u9,v) f(x) u9+x (u+v)+w u+(v+w) (u+(v+w)) - ((u+v)+gyr(u,v,w)) ((u+v)+w) - (u+(v+gyr(v,u,w))) u <- as.3vel(c(0.4,0,0)) v <- seq(as.3vel(c(0.4,-0.2,0)), as.3vel(c(-0.3,0.9,0)),len=20) w <- as.3vel(c(0.8,-0.4,0)) comm_fail1(u=u, v=v) comm_fail2(u=u, v=v) ass_fail(u=u, v=v, w=w, bold=10) u <- as.3vel(c(+0.5,0.1,-0.2)) v <- as.3vel(c(+0.4,0.3,-0.2)) w <- as.3vel(c(-0.3,0.2,+0.2)) jj1 <- u %>% add(v) jj2 <- u+v speed(jj1-jj2) jj1 <- u %>% add(v) %>% add(w) jj2 <- (u+v)+w speed(jj1-jj2) jj1 <- u %>% add(v %>% add(w)) jj2 <- u+(v+w) speed(jj1-jj2) x <- as.3vel(c(0.7, 0.0, -0.7)) y <- as.3vel(c(0.1, 0.3, -0.6)) u <- as.3vel(c(0.0, 0.8, +0.1)) v <- r3vel(5,0.9) w <- r3vel(5,0.8) f <- gyrfun(u,v) g <- gyrfun(v,u) max(speed((u+v) - f(v+u))) max(abs(prod3(f(x),f(y)) - prod3(x,y))) max(speed(f(x+y) - (f(x)+f(y)))) max(speed(f(g(x)) - g(f(x)))) max(speed((u+(v+w)) - ((u+v)+f(w)))) max(speed(((u+v)+w) - (u+(v+g(w)))))
context("Aug nb families") test_that("graph 2 families nominal", { g <- test_dag() f <- graphNEL2families(dag = g, class = 'A') expect_equal(names(f), c('B', 'A')) }) test_that("graph 2 families class not in dag ", { g <- test_dag() expect_error(graphNEL2families(dag = g, class = 'C'), 'last not found') }) test_that("graph 2 families class length > 1 ", { g <- test_dag() expect_error(graphNEL2families(dag = g, class = LETTERS[1:2]), 'string') }) test_that("graph 2 families Undirected graph" , { e <- list(A = 'B', B = 'A') edges <- graph_from_to_to_edges(c('A', 'B'), c('B', 'A')) g <- graph_internal(nodes = LETTERS[1:2], edges, weights = NULL, edgemode = "directed") if (!skip_testing()) expect_error(graphNEL2families(dag = g, class = LETTERS[1]), 'is_dag_graph') g <- graph_internal(nodes = LETTERS[1:2], edges, weights = NULL, edgemode = "undirected") if (!skip_testing()) expect_error(graphNEL2families(dag = g, class = LETTERS[1]), 'is_dag_graph') }) test_that("check families", { tvars <- setNames(nm = letters[1:6]) tfams <- lapply(tvars[-6], function(x) c(x, 'f')) tfams <- append(tfams, list(f = 'f')) check_anb_families(tfams, 'f') tvars <- setNames(nm = letters[1:6]) tfams <- lapply(tvars[-6], function(x) c(x, 'f')) tfams <- append(tfams, list(f = 'f')) tfams$b <- 'b' if (!skip_assert()) expect_error(check_anb_families(tfams, 'f'), 'fams_ok') tvars <- setNames(nm = letters[1:6]) tfams <- lapply(tvars[-6], function(x) c(x, 'f')) tfams <- append(tfams, list(f='f')) tfams <- tfams[6:1] if (!skip_assert()) expect_error(check_anb_families(tfams, 'f'), 'last') }) test_that("is is family nominal", { f <- letters[1:6] expect_true(is_anb_family(f, 'a', 'f')) }) test_that("is is family wrong var", { f <- letters[1:6] expect_true(!is_anb_family(f, 'b', 'f')) }) test_that("is is family wrong class", { f <- letters[1:6] expect_true(!is_anb_family(f, 'a', 'e')) }) test_that("is is family missing values", { f <- c(letters[1:6], NA, 'g') expect_true(!is_anb_family(f, 'a', 'g')) }) test_that("Unique families some in common", { a <- families(nbcar()) b <- families(nbcarp(car[, 4:7])) fams <- unique_families(list(a, b)) expect_equal(length(fams), 7) expect_equivalent(fams, a) }) test_that("Unique families none in common", { cr <- families(nbcar()) vt <- families(nbvote()) fams <- unique_families(list(cr, vt)) expect_equal(length(fams), 7 + 17) }) test_that("Tag families nominal", { cr <- families(nbcar()) fms <- make_families_ids(cr) expect_equal(length(fms), 7) expect_equal(fms[['persons']], "personsclass") }) test_that("Acyclic order nominal", { n <- nbcar() o <- order_acyclic(families(n)) expect_equal(o, c('class', colnames(car)[1:6])) }) test_that("Acyclic order a cycle", { n <- nbcar() n <- add_feature_parents('safety', 'lug_boot', n) n <- add_feature_parents('lug_boot', 'doors', n) f <- families(n) f[['safety']] <- c('safety', 'doors', 'class') o <- order_acyclic(f) expect_null(o) }) test_that("Acyclic order 0 node is a DAG", { o <- order_acyclic(list()) expect_equal(o, character()) }) test_that("Find ancestors not in graph nominal", { a <- tan_cl('class', car) b <- get_ancestors('doors', families(a)) expect_true(is_perm(b, c('lug_boot', 'safety', 'buying', 'class'))) b <- get_ancestors('safety', families(a)) expect_true(is_perm(b, c('buying', 'class'))) b <- get_ancestors('class', families(a)) expect_equal(b, character()) }) test_that("Find ancestors", { a <- nbcarclass() b <- get_ancestors('class', families(a)) expect_equal(b, character()) }) test_that("Find ancestors not in graph", { a <- nbcarclass() expect_error(get_ancestors('p', families(a)), "families") })
scale_color_see <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { pal <- palette_see(palette = palette, reverse = reverse) if (discrete) { discrete_scale("colour", paste0("see_", palette), palette = pal, ...) } else { scale_color_gradientn(colours = pal(256), ...) } } scale_color_see_d <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { scale_color_see( palette = palette, discrete = discrete, reverse = reverse, ... ) } scale_color_see_c <- function(palette = "contrast", discrete = FALSE, reverse = FALSE, ...) { scale_color_see( palette = palette, discrete = discrete, reverse = reverse, ... ) } scale_colour_see <- scale_color_see scale_colour_see_c <- scale_color_see_c scale_colour_see_d <- scale_color_see_d scale_fill_see <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { pal <- palette_see(palette = palette, reverse = reverse) if (discrete) { discrete_scale("fill", paste0("see_", palette), palette = pal, ...) } else { scale_fill_gradientn(colours = pal(256), ...) } } scale_fill_see_d <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { scale_fill_see( palette = palette, discrete = discrete, reverse = reverse, ... ) } scale_fill_see_c <- function(palette = "contrast", discrete = FALSE, reverse = FALSE, ...) { scale_fill_see( palette = palette, discrete = discrete, reverse = reverse, ... ) } see_colors_list <- c( `red` = " `pink` = " `purple` = " `deep purple` = " `indigo` = " `blue` = " `light blue` = " `cyan` = " `green` = " `light green` = " `lime` = " `yellow` = " `amber` = " `orange` = " `grey` = " `blue grey` = " ) see_colors <- function(...) { cols <- c(...) if (is.null(cols)) { return(see_colors_list) } see_colors_list[cols] } see_palettes <- list( `full` = see_colors(), `ice` = see_colors("indigo", "blue", "blue grey", "cyan", "light blue"), `rainbow` = see_colors("purple", "deep purple", "indigo", "blue", "light blue", "green", "light green", "lime", "amber", "orange", "red", "pink"), `contrast` = see_colors("blue", "orange", "yellow", "green", "red"), `complement` = see_colors("blue", "blue grey", "green", "light green", "yellow", "amber", "red"), `light` = see_colors("light blue", "pink", "lime", "light green", "orange") ) palette_see <- function(palette = "contrast", reverse = FALSE, ...) { pal <- see_palettes[[palette]] if (reverse) pal <- rev(pal) grDevices::colorRampPalette(pal, ...) }
count_target <- function(df, col.target = Target, add.df = TRUE) { df_count <- df %>% dplyr::add_count({{col.target}}) %>% dplyr::arrange(desc(n)) %>% dplyr::rename("Target_count" = n) %>% dplyr::select({{col.target}}, Target_count) %>% dplyr::distinct() if (add.df == FALSE) { return(df_count) } else { df_merged <- dplyr::left_join(df, df_count) return(df_merged) } } count_target_helper <- function(df, threshold = NULL, top = NULL, col.target = Target) { if(is.null(top) & is.null(threshold)) { top <- 5 } if(!is.null(top) & !is.null(threshold)) { stop("'top' and 'threshold' cannot be specified at the same time. Please specify either 'top' or 'threshold'.") } df_count <- df %>% dplyr::count({{col.target}}, name = "Target_count") %>% dplyr::arrange(desc(Target_count)) if(!is.null(threshold)) { df_count <- df_count %>% dplyr::filter(Target_count >= threshold) } else if(!is.null(top)) { df_count <- df_count %>% dplyr::top_n(n = top, wt = Target_count) } return(df_count) } plot_target_count <- function(df, top = NULL, threshold = NULL, colour = "steelblue3", col.target = Target, title = NULL) { if(is.null(top) & is.null(threshold)) { top <- 5 } if(!is.null(top) & !is.null(threshold)) { stop("'top' and 'threshold' cannot be specified at the same time. Please specify either 'top' or 'threshold'.") } if(is.null(title)) { title <- "Top validated targets" } df_count <- count_target_helper(df, top = top, threshold = threshold, col.target = {{col.target}}) %>% dplyr::mutate(Target = forcats::fct_reorder(Target, Target_count)) plot <- ggplot(df_count, aes(x = Target, y = Target_count)) + geom_col(show.legend = FALSE, fill = colour) + coord_flip() + xlab("Target") + ylab("Validated in at least theme_classic() + ggtitle(title) plot <- pretty_breaks_miretrieve(plot, df_count$Target_count) return(plot) } plot_target_mir_scatter <- function(df, mir = NULL, target = NULL, top = NULL, threshold = NULL, filter_for = "target", col.target = Target, col.mir = miRNA, col.topic = Topic, col.pmid = PMID, title = NULL, height = 0.05, width = 0.05, alpha = 0.6) { filter_for <- stringr::str_to_lower(filter_for) if(is.null(title)) { title <- "miRNA-target interaction" } if(is.null(top) & is.null(threshold)) { top <- 5 } if(!is.null(top) & !is.null(threshold)) { stop("'top' and 'threshold' cannot be specified at the same time. Please specify either 'top' or 'threshold'.") } if(filter_for != "target" & filter_for != "mirna") { stop("'filter_for' must be either 'Target'/'target' or 'miRNA'.") } if(!"Topic" %in% colnames(df)) { df <- df %>% dplyr::mutate(Topic = "NA") } df <- df %>% dplyr::mutate({{col.target}}:= stringr::str_to_upper({{col.target}})) if(!is.null(mir)) { df <- df %>% dplyr::filter({{col.mir}} %in% mir) } if(!is.null(target)) { df <- df %>% dplyr::filter({{col.target}} %in% target) } if(filter_for == "mirna") { df <- df %>% tidyr::drop_na({{col.mir}}) } else { df <- df %>% tidyr::drop_na({{col.target}}) } df_count <- df %>% dplyr::select({{col.target}}, {{col.mir}}, {{col.topic}}, {{col.pmid}}) %>% dplyr::add_count({{col.target}}, name = "Target_count") %>% dplyr::add_count({{col.mir}}, name = "miRNA_count") %>% dplyr::mutate(miRNA = forcats::fct_reorder({{col.mir}}, miRNA_count)) %>% dplyr::mutate(Target = forcats::fct_reorder({{col.target}}, Target_count)) if(filter_for == "target") { df_count <- df_count %>% dplyr::select(Target, miRNA, Target_count, {{col.topic}}, {{col.pmid}}) %>% dplyr::rename(n = 3) } else if(filter_for == "mirna") { df_count <- df_count %>% dplyr::select(Target, miRNA, miRNA_count, {{col.topic}}, {{col.pmid}}) %>% dplyr::rename(n = 3) } if(!is.null(threshold)) { df_count <- df_count %>% dplyr::filter(n >= threshold) } else if(!is.null(top)) { if(filter_for == "mirna") { vector <- df_count %>% dplyr::select(-Target, -{{col.pmid}}, -{{col.topic}}) %>% dplyr::distinct() %>% dplyr::top_n(n = top, wt = n) %>% dplyr::select(miRNA) %>% dplyr::pull() %>% unique() df_count <- df_count %>% dplyr::filter(miRNA %in% vector) } else { vector <- df_count %>% dplyr::select(-miRNA, -{{col.pmid}}, -{{col.topic}}) %>% dplyr::distinct() %>% dplyr::top_n(n = top, wt = n) %>% dplyr::select(Target) %>% dplyr::pull() %>% unique() df_count <- df_count %>% dplyr::filter(Target %in% vector) } } df_count <- df_count %>% dplyr::distinct({{col.pmid}}, miRNA, Target, {{col.topic}}) plot <- ggplot(df_count, aes(x = Target, y = miRNA, color = {{col.topic}})) + geom_jitter(height = height, width = width, alpha = alpha, size = 2, show.legend = TRUE) + theme_minimal() + theme(axis.text.x = element_text(angle = 60, hjust = 1)) + xlab("Target") + ylab("miRNA") + ggtitle(title) return(plot) }
anemia_df <- function(env = parent.frame()) { tibble::tribble( ~Hb, ~age, ~male, 12.5, 20, TRUE, 13.5, 20, TRUE, 11.5, 20, FALSE, 12.5, 20, FALSE, 11.5, 13, TRUE, 12.5, 13, TRUE, 11.0, 7, TRUE, 12.0, 7, TRUE, 10.5, 3, TRUE, 11.5, 3, TRUE, ) %>% dplyr::mutate( Hb = units::set_units(Hb, "g/dl"), age = units::set_units(age, "years") ) } anemia_ep <- function(env = parent.frame()) { rep(c(TRUE, FALSE), 5) } test_that("anemia() for data.frame", { expect_identical( anemia(anemia_df(), "Hb", "age", "male"), anemia_ep() ) expect_identical( anemia(anemia_df(), Hb, age, male), anemia_ep() ) expect_identical( anemia_df() %>% anemia(Hb, age, male), anemia_ep() ) }) test_that("anemia() for units vector", { expect_identical( anemia( anemia_df()$Hb, anemia_df()$age, anemia_df()$male ), anemia_ep() ) }) test_that("anemia() for dplyr::mutate on units", { expect_identical( anemia_df() %>% dplyr::mutate(anemia = anemia(Hb, age, male)) %>% dplyr::pull(anemia), anemia_ep() ) }) test_that("anemia() for dplyr::mutate on numeric", { expect_identical( anemia_df() %>% dplyr::mutate(dplyr::across(c(Hb, age), as.numeric)) %>% dplyr::mutate(anemia = anemia(Hb, age, male)) %>% dplyr::pull(anemia), anemia_ep() ) })
med.filter <- function(y, width, minNonNAs = 5, online=FALSE, extrapolate=TRUE) {return(robreg.filter(y=y, width=width, minNonNAs=minNonNAs, method="MED", online=online, extrapolate=extrapolate))}
PresentationModel.default = function(...) { args = list(...) if (length(args) > 0) { stop("Presentation Model doesn't know how to deal with the parameters") } else { presentationmodel = structure( list(project = list(username = "[Unknown User]", title = "[Unknown title]", description = "[No description]"), section.by = NULL, subsection.by = NULL, table.by = NULL, custom.label = NULL), class = "PresentationModel") } return(presentationmodel) }
findMultiLims<-function(...){ .Defunct(msg="This function is defunct. See Esarey and Sumner, \"Corrigendum to 'Marginal Effects in Interaction Models: Determining and Controlling the False Positive Rate.'\" for details.") }
fixedCalib <- function(data, model = 1, old_mod, PAU = 'MWU', NEMC = "MEM", technical = list(), ...){ stopifnot(PAU %in% c('NWU', 'OWU', 'MWU')) stopifnot(NEMC %in% c("OEM", "MEM")) global_prior <- NULL custom_den_const <- function(obj, Theta) global_prior custom_den_EH <- function(obj, Theta) { ret <- if(length(obj@rr) == 0L) global_prior else obj@rr / sum(obj@rr) ret } nfact <- extract.mirt(old_mod, 'nfact') stopifnot(nfact == 1L) old_itemnames <- extract.mirt(old_mod, 'itemnames') stopifnot(all(old_itemnames %in% colnames(data))) olddata <- extract.mirt(old_mod, 'data') tmp <- t(data.frame(rep(NA, ncol(data) - ncol(olddata)))) rownames(tmp) <- NULL olddata <- data.frame(olddata, tmp) colnames(olddata) <- c(old_itemnames, colnames(data)[!(colnames(data) %in% old_itemnames)]) fulldata <- rbind(olddata, data) sv <- mod2values(old_mod) sv$est <- FALSE sv2 <- mirt(fulldata, model, pars='values', ...) for(item in c(old_itemnames, 'GROUP')){ pick1 <- sv$item == item pick2 <- sv2$item == item sv2$value[pick2] <- sv$value[pick1] sv2$est[pick2] <- FALSE } if(is.null(technical$NCYCLES)) if(NEMC == 'OEM') technical$NCYCLES <- 1L technical$message <- FALSE if(PAU %in% c('OWU', 'MWU')){ FC_mod_den <- mirt(data=extract.mirt(old_mod, 'data'), model=extract.mirt(old_mod, 'model'), pars=sv, dentype = 'EH', verbose=FALSE, technical = list(NCYCLES = 1L, message = FALSE), ...) global_prior <- FC_mod_den@Internals$Prior[[1L]] den <- if(PAU == 'OWU') custom_den_const else custom_den_EH par <- c(MEAN_1 = 0, COV_11 = 1) est <- c(FALSE, FALSE) grp <- createGroup(par, est, den, nfact = 1L) } mod <- if(PAU == "NWU"){ mirt(fulldata, model, pars=sv2, technical=technical, ...) } else if(PAU %in% c("OWU", "MWU")){ mirt(fulldata, model, pars=sv2, customGroup=grp, dentype='EH', technical=technical, ...) } sv_final <- mod2values(mod) FC_mod_den <- mirt(fulldata, model, pars=sv_final, dentype='EH', TOL=NaN, ...) FC_mod_den }
gbm2sas <- function( gbmobject, data=NULL, sasfile=NULL, ntrees=NULL, mysasdata="mysasdata", treeval="treeval", prefix="do_" ) { if(is.null(ntrees)) ntrees<-gbmobject$n.trees maxhmmt<-0 hasprefix<-prefix!="do_" hasmysasdata<-mysasdata!="mysasdata" hastreeval<-treeval!="treeval" prepwords<-"data mysasdata; set mysasdata;" if(hasmysasdata) prepwords<-gsub("mysasdata", mysasdata, prepwords) write.table(prepwords, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE) numtrees<-ntrees for(treeloop in 1:numtrees) { pgt<-pretty.gbm.tree(gbmobject,i.tree = treeloop)[1:7] hmmt<-dim(pgt)[1] maxhmmt<-max(maxhmmt, hmmt) wordsa<-"do_x=0;" for(loop in 0:(hmmt-1)) { if(loop>0) { wordsb<-gsub("x", loop, wordsa) } else { wordsb<-"do_0=1;" } if(hasprefix) wordsb<-gsub("do_", prefix, wordsb) write.table(wordsb, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } words0<-"if missing(V A R1) then do_V A R5=1; else do;" words1<-"if V A R1 lt V A R2 then do_V A R3=1; else do_V A R4=1; end;" words2<-"if V A R1 in (V A R2) then do_V A R3=1; else do_V A R4=1; end;" words2b<-"do_V A R4=1; end;" words3<-"end;" if(hasprefix) { words0<-gsub("do_", prefix, words0) words1<-gsub("do_", prefix, words1) words2<-gsub("do_", prefix, words2) words2b<-gsub("do_", prefix, words2b) words3<-gsub("do_", prefix, words3) } thevarnames<-gbmobject$var.names types<-lapply (lapply(data[,gbmobject$var.names],class), function(i) ifelse (strsplit(i[1]," ")[1]=="ordered","ordered",i)) levels<-lapply(data[,gbmobject$var.names],levels) for(loop in 1:hmmt) { prepwords<-paste("if do_", (loop-1), ">0 then do;", sep="") if(hasprefix) prepwords<-gsub("do_", prefix, prepwords) write.table(prepwords, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) splitvar<-1+as.numeric(as.vector(pgt[loop,]$SplitVar)) splitcodepred<-as.numeric(as.vector(pgt[loop,]$SplitCodePred)) leftnode<-as.numeric(as.vector(pgt[loop,]$LeftNode)) rightnode<-as.numeric(as.vector(pgt[loop,]$RightNode)) missingnode<-as.numeric(as.vector(pgt[loop,]$MissingNode)) if(splitvar>0) { words0a<-gsub("V A R1", thevarnames[splitvar], words0) words1a<-gsub("V A R1", thevarnames[splitvar], words1) words2a<-gsub("V A R1", thevarnames[splitvar], words2) words0a<-gsub("V A R5", missingnode, words0a) words1a<-gsub("V A R3", leftnode, words1a) words2a<-gsub("V A R3", leftnode, words2a) words1a<-gsub("V A R4", rightnode, words1a) words2a<-gsub("V A R4", rightnode, words2a) words2ab<-gsub("V A R4", rightnode, words2b) thistype<-types[[splitvar]] leftstring<-" " rightstring<-" " write.table(words0a, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) if(thistype=="numeric") { words1a<-gsub("V A R2", splitcodepred, words1a) write.table(words1a, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } else { if(thistype=="ordered") { splitcodepred<-ceiling(splitcodepred) if(splitcodepred>=1) { theleft<-c(levels[[splitvar]][1:splitcodepred], NA) } else { theleft<-rep(NA, 2) } } else { describer<-unlist(gbmobject$c.splits[1+splitcodepred]) theleft<-c(levels[[splitvar]][describer==-1], NA) } logic<-!is.na(theleft) if(sum(as.numeric(logic))>0) { theleft<-theleft[logic] hmmt2<-length(theleft) leftstring<-NULL for(loop2 in 1:hmmt2) { leftstring<-paste(leftstring, "'", theleft[loop2], "'", sep="") if(loop2<hmmt2) leftstring<-paste(leftstring, ", ", sep="") } } else { leftstring<-"blah" } if(leftstring!="blah") { words2a<-gsub("V A R2", leftstring, words2a) write.table(words2a, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } else { write.table(words2ab, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } } } else { prepwords<-paste("treeval", treeloop, "=", splitcodepred, ";", sep="") if(hastreeval) prepwords<-gsub("treeval", treeval, prepwords) write.table(prepwords, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } write.table(words3, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } } wordsa<-"drop do_x;" for(loop in 0:(maxhmmt-1)) { if(loop>0) { wordsb<-gsub("x", loop, wordsa) } else { wordsb<-"drop do_0;" } if(hasprefix) wordsb<-gsub("do_", prefix, wordsb) write.table(wordsb, sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) } write.table("run;", sasfile, row.names=FALSE, col.names=FALSE, quote=FALSE, append=TRUE) }
context("Print functions") test_that("print.dcm", { param <- param.dcm(inf.prob = 0.2, act.rate = 0.25) init <- init.dcm(s.num = 500, i.num = 1) control <- control.dcm(type = "SI", nsteps = 500) mod <- dcm(param, init, control) expect_output(print(mod), "EpiModel Simulation") expect_output(print(mod), "Model class: dcm") expect_output(print(mod), "Model type: SI") expect_output(print(mod), "inf.prob = 0.2") expect_output(print(mod), "act.rate = 0.25") expect_output(print(mod), "Variables: s.num i.num si.flow num") }) test_that("print.icm", { param <- param.icm(inf.prob = 0.2, act.rate = 0.25) init <- init.icm(s.num = 500, i.num = 1) control <- control.icm(type = "SI", nsteps = 10, nsims = 2, verbose = FALSE) mod <- icm(param, init, control) expect_output(print(mod), "EpiModel Simulation") expect_output(print(mod), "Model class: icm") expect_output(print(mod), "Model type: SI") expect_output(print(mod), "inf.prob = 0.2") expect_output(print(mod), "act.rate = 0.25") expect_output(print(mod), "Variables: s.num i.num num si.flow") }) test_that("print.netest", { nw <- network_initialize(n = 100) formation <- ~edges target.stats <- 50 coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 10) est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE) expect_output(print(est), "EpiModel Network Estimation") expect_output(print(est), "Model class: netest") expect_output(print(est), "Estimation Method: ERGM with Edges Approximation") expect_output(print(est), "Formation: ~edges") expect_output(print(est), "Target Statistics: 50") expect_output(print(est), "Target Statistics: 10") }) test_that("print.netsim", { nw <- network_initialize(n = 100) nw <- set_vertex_attribute(nw, "group", rep(c(1, 2), each = 50)) formation <- ~edges target.stats <- 50 coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20) est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE) param <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15) init <- init.net(i.num = 10, i.num.g2 = 10) control <- control.net(type = "SI", nsteps = 10, nsims = 1, verbose = FALSE) mod <- netsim(est, param, init, control) expect_output(print(mod), "EpiModel Simulation") expect_output(print(mod), "Model class: netsim") expect_output(print(mod), "Model type: SI") expect_output(print(mod), "No. NW groups: 2") expect_output(print(mod), "Variables: s.num i.num num s.num.g2 i.num.g2 num.g2") }) test_that("print.disscoefs", { o <- dissolution_coefs(dissolution = ~offset(edges), duration = 25) expect_output(print(o), "Dissolution Coefficients") expect_output(print(o), "Crude Coefficient: 3.178054") expect_output(print(o), "Mortality/Exit Rate: 0") o <- dissolution_coefs(dissolution = ~offset(edges), duration = 25, d.rate = 0.001) expect_is(o, "disscoef") expect_output(print(o), "Mortality/Exit Rate: 0.001") o <- dissolution_coefs(dissolution = ~offset(edges) + offset(nodematch("race")), duration = c(20, 10)) expect_output(print(o), "2.944439 -0.7472144") expect_output(print(o), "Mortality/Exit Rate: 0") expect_output(print(o), "Target Statistics: 20 10") o <- dissolution_coefs(dissolution = ~offset(edges) + offset(nodematch("race")), duration = c(20, 10), d.rate = 0.001) expect_output(print(o), "Crude Coefficient: 2.944439 -0.7472144") expect_output(print(o), "Adjusted Coefficient: 2.98524 -0.7678231") }) test_that("print.param", { p <- param.dcm(inf.prob = 0.1, rec.rate = 0.1) expect_output(print(p), "DCM Parameters") p <- param.icm(inf.prob = 0.1, rec.rate = 0.1) expect_output(print(p), "ICM Parameters") p <- param.net(inf.prob = 0.1, rec.rate = 0.1) expect_output(print(p), "Fixed Parameters") expect_output(print(p), "act.rate = 1") }) test_that("print.init", { i <- init.dcm(s.num = 10, i.num = 10) expect_output(print(i), "DCM Initial Conditions") i <- init.icm(s.num = 10, i.num = 10) expect_output(print(i), "ICM Initial Conditions") i <- init.net(s.num = 10, i.num = 10) expect_output(print(i), "Network Model Initial Conditions") }) test_that("print.control", { co <- control.dcm(type = "SI", nsteps = 10) expect_output(print(co), "DCM Control Settings") expect_output(print(co), "odemethod = rk4") co <- control.icm(type = "SI", nsteps = 10) expect_output(print(co), "ICM Control Settings") expect_output(print(co), "Base Modules: initialize.FUN") co <- control.net(type = "SI", nsteps = 10) expect_output(print(co), "Network Model Control Settings") })
print.regtest <- function(x, digits=x$digits, ret.fit=x$ret.fit, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(x), must="regtest") digits <- .get.digits(digits=digits, xdigits=x$digits, dmiss=FALSE) if (!exists(".rmspace")) cat("\n") cat(mstyle$section("Regression Test for Funnel Plot Asymmetry")) cat("\n\n") if (x$model == "lm") { cat(mstyle$text("Model: weighted regression with multiplicative dispersion")) } else { cat(mstyle$text(paste("Model: ", ifelse(is.element(x$method, c("FE","EE","CE")), "fixed-effects", "mixed-effects"), "meta-regression model"))) } cat("\n") if (x$predictor == "sei") cat(mstyle$text("Predictor: standard error")) if (x$predictor == "vi") cat(mstyle$text("Predictor: sampling variance")) if (x$predictor == "ni") cat(mstyle$text("Predictor: sample size")) if (x$predictor == "ninv") cat(mstyle$text("Predictor: inverse of the sample size")) if (x$predictor == "sqrtni") cat(mstyle$text("Predictor: square root sample size")) if (x$predictor == "sqrtninv") cat(mstyle$text("Predictor: inverse of the square root sample size")) cat("\n") if (ret.fit) { if (exists(".rmspace")) cat("\n") if (x$model == "lm") { print(summary(x$fit)) } else { print(x$fit) } if (exists(".rmspace")) cat("\n") } else { cat("\n") } cat(mstyle$text("Test for Funnel Plot Asymmetry: ")) if (is.na(x$ddf)) { cat(mstyle$result(paste0("z = ", .fcf(x$zval, digits[["test"]]), ", p ", .pval(x$pval, digits[["pval"]], showeq=TRUE, sep=" ")))) } else { cat(mstyle$result(paste0("t = ", .fcf(x$zval, digits[["test"]]), ", df = ", x$ddf, ", p ", .pval(x$pval, digits[["pval"]], showeq=TRUE, sep=" ")))) } cat("\n") if (!is.null(x$est)) { if (x$predictor == "sei") cat(mstyle$text("Limit Estimate (as sei -> 0): ")) if (x$predictor == "vi") cat(mstyle$text("Limit Estimate (as vi -> 0): ")) if (x$predictor %in% c("ninv", "sqrtninv")) cat(mstyle$text("Limit Estimate (as ni -> inf): ")) cat(mstyle$result(paste0("b = ", .fcf(x$est, digits[["est"]]), " (CI: ", .fcf(x$ci.lb, digits[["est"]]), ", ", .fcf(x$ci.ub, digits[["est"]]), ")"))) cat("\n") } if (!exists(".rmspace")) cat("\n") invisible() }
cholInv <- function (mat, eliminate = numeric(0), onlyFirstCol = FALSE, onlyNonElim = FALSE) { .Deprecated(msg = paste("'cholInv' is deprecated as it is no longer used ", "by gnm.")) m <- nrow(mat) n <- ncol(mat) if (length(eliminate) == 0) { if (!is.matrix(mat)) stop("mat is not a matrix") Rownames <- rownames(mat) Colnames <- colnames(mat) result <- chol2inv(chol(mat)) if (!is.null(Rownames)) colnames(result) <- Rownames if (!is.null(Colnames)) rownames(result) <- Colnames if (onlyFirstCol) result <- result[, 1, drop = FALSE] return(result) } if (m != n) stop("mat must be a symmetric matrix") n <- nrow(mat) elim <- 1:n %in% eliminate diag.indices <- (n * (0:(n - 1)) + 1:n) Tmat <- mat[diag.indices[eliminate]] if (any(Tmat == 0)) stop("an eliminated submatrix must have all diagonal entries non-zero.") W <- mat[!elim, !elim, drop = FALSE] U <- mat[elim, !elim, drop = FALSE] Ti <- 1/Tmat k <- length(Tmat) Ti.U <- Ti * U V.Ti <- t(Ti.U) Qmat <- W - crossprod(Ti.U, U) Qi <- cholInv(Qmat) result <- matrix(NA, if (onlyNonElim) n - k else n, if (onlyFirstCol) 1 else if (onlyNonElim) n - k else n) cols.notElim <- if (onlyFirstCol) 1 else if (onlyNonElim) 1:(n - k) else !elim rows.notElim <- if (onlyNonElim) 1:(n - k) else !elim if (onlyFirstCol) Qi <- Qi[, 1, drop = FALSE] result[rows.notElim, cols.notElim] <- Qi if (!onlyNonElim) { temp <- -crossprod(Qi, V.Ti) result[elim, cols.notElim] <- t(temp) } if (!onlyFirstCol && !onlyNonElim) { result[!elim, elim] <- temp temp <- crossprod(V.Ti, Qi) %*% V.Ti diag.indices <- k * (0:(k - 1)) + 1:k temp[diag.indices] <- Ti + temp[diag.indices] result[elim, elim] <- temp } theNames <- colnames(mat) rownames(result) <- if (onlyNonElim) theNames[!elim] else theNames colnames(result) <- if (onlyFirstCol) theNames[!elim][1] else if (onlyNonElim) theNames[!elim] else theNames result }
directFeatureSelection <- function(data, class, directSearcher, evaluator){ if(!class%in%colnames(data)){ stop('The dependent variable does not exist in the dataset.') } if((ncol(data)-1)<2){ stop('The feature selection process requires more than 1 feature') } if( any( apply(data, 2, function(x) { any(is.na(x)) } ) ) ){ stop('Feature selection cannot be performed with missing values. Try to impute them previously with the preProcces function of the caret package') } t <- proc.time() dfsp <- directSearcher(data, class, evaluator) time <- proc.time()-t res <- list() res[[1]] <- dfsp$bestFeatures res[[2]] <- dfsp$featuresSelected res[[3]] <- dfsp$valuePerFeature aux <- attr(evaluator,"name") auxSeparate <- strsplit(aux, " ") if(auxSeparate[[1]][length(auxSeparate[[1]])]=="Wrapper"){ res[[4]] <- "Wrapper" res[[5]] <- auxSeparate[[1]][1] }else{ res[[4]] <- "Filter" res[[5]] <- aux } res[[6]] <- attr(directSearcher,"name") res[[7]] <- attr(evaluator,"target") res[[8]] <- ncol(data)-1 column.names <- names(data) class.position <- which(column.names == class) res[[9]] <- column.names[-class.position] res[[10]] <- column.names[class.position] res[[11]] <- time names(res) <- c("bestFeatures", "featuresSelected", "valuePerFeature", "evaluationType", "evaluationMethod", "searchMethod", "target", "numFeatures", "xNames", "yName", "time") return(res) }
library(knitr) knit( "vignettes/articles/_dates-and-times.Rmd.orig.Rmd", "vignettes/articles/dates-and-times.Rmd" )
NULL if(getRversion() >= "2.15.1") utils::globalVariables(c(".")) .onAttach <- function(libname, pkgname) { packageStartupMessage("\nSupport women in science: 500womenscientists.org") } .onUnload <- function (libpath) { library.dynam.unload("CENFA", libpath) }
loss_h_gradient = function(Y, Theta_h, mean_coefs, knots, beta.inner, family = "gaussian", t_min, t_max){ Di = length(Y) Kh = dim(Theta_h)[2] beta = c(t_min, beta.inner, t_max) Theta_h = cbind(1, Theta_h) hinv_tstar = Theta_h %*% beta mean_coefs = matrix(mean_coefs, ncol = 1) Theta_phi = bs(hinv_tstar, knots = knots, intercept = TRUE) Theta_phi_deriv = bs_deriv(hinv_tstar, knots) if(family == "binomial"){ varphi = 1 b_g_deriv = plogis(Theta_phi %*% mean_coefs) }else if (family == "gaussian"){ varphi = 1 b_g_deriv = Theta_phi %*% mean_coefs }else{ stop("Package currently handles only 'binomial' or 'gaussian' families.") } gradient_mat = matrix(NA, Kh + 1, Di) for(j in 1:Di){ gradient_mat[, j] = (Y - b_g_deriv)[j] * (Theta_phi_deriv %*% mean_coefs)[j] * Theta_h[j,] } grad = 1/varphi * rowSums(gradient_mat) grad.last = length(grad) grad.inner = grad[-c(1, grad.last)] return(-1 * grad.inner) }
mdp_Q_learning <- function(P, R, discount, N) { if ( discount <= 0 | discount > 1 ) { print('--------------------------------------------------------') print('MDP Toolbox ERROR: Discount rate must be in ]0; 1]') print('--------------------------------------------------------') } else if ( nargs() >= 4 & ifelse(!missing(N), N < 10000, F) ) { print('--------------------------------------------------------') print('MDP Toolbox ERROR: N must be upper than 10000') print('--------------------------------------------------------') } else { if (nargs() < 4) { N <- 10000 } if (is.list(P)) { S <- dim(P[[1]])[1] A <- length(P) } else { S <- dim(P)[1] A <- dim(P)[3] } Q <- matrix(0,S,A) dQ <- matrix(0,S,A) mean_discrepancy <- NULL discrepancy <- NULL state <- sample(1:S, 1, replace=T) for (n in 1:N) { if ( n %% 100 == 0 ) { state <- sample(1:S, 1, replace=T) } pn <- runif(1) if ( pn < (1-(1/log(n+2))) ) { optimal_action <- max(Q[state,]) a <- which.max(Q[state,]) } else { a <- sample(1:A, 1, replace=T) } p_s_new <- runif(1) p <- 0 s_new <- 0 while ((p < p_s_new) & (s_new < S)) { s_new <- s_new + 1 if (is.list(P)) { p <- p + P[[a]][state,s_new] } else { p <- p + P[state,s_new,a] } } if (is.list(R)) { r <- R[[a]][state,s_new] } else { if(length(dim(R)) == 3) { r <- R[state,s_new,a] } else { r <- R[state,a] } } delta <- r + discount*max(Q[s_new,]) - Q[state,a] dQ <- (1/sqrt(n+2))*delta Q[state,a] <- Q[state,a] + dQ state <- s_new discrepancy[(n %% 100) + 1] = abs(dQ) if(length(discrepancy) == 100) { mean_discrepancy <- c(mean_discrepancy, mean(discrepancy)) discrepancy <- NULL } } V <- apply(Q, 1, max) policy <- apply(Q, 1, which.max) } return(list("Q"=Q, "V"=V, "policy"=policy, "mean_discrepancy"=mean_discrepancy)) }
TEX.sde <- function(object, ...) UseMethod("TEX.sde") TEX.sde.default <- function(object, ...) { greek <- c("alpha", "theta", "tau", "beta", "vartheta", "pi", "upsilon", "gamma", "varpi", "phi", "delta", "kappa", "rho","iota", "varphi", "epsilon", "lambda", "varrho", "chi", "varepsilon", "mu", "sigma", "psi", "zeta", "nu", "varsigma", "omega", "eta", "xi", "Gamma", "Lambda", "Sigma", "Psi", "Delta", "Xi", "Upsilon", "Omega", "Theta", "Pi", "Phi") greek0 <- c(paste0(greek,"0")) greek1 <- c(paste0(greek,"1")) greek2 <- c(paste0(greek,"2")) greek3 <- c(paste0(greek,"3")) greek4 <- c(paste0(greek,"4")) greek5 <- c(paste0(greek,"5")) greek6 <- c(paste0(greek,"6")) greek7 <- c(paste0(greek,"7")) greek8 <- c(paste0(greek,"8")) greek9 <- c(paste0(greek,"9")) greek10 <- c(paste0(greek,"10")) greek11 <- c(paste0(greek,"11")) greek12 <- c(paste0(greek,"12")) greek13 <- c(paste0(greek,"13")) greek14 <- c(paste0(greek,"14")) greek15 <- c(paste0(greek,"15")) greek16 <- c(paste0(greek,"16")) greek17 <- c(paste0(greek,"17")) greek18 <- c(paste0(greek,"18")) greek19 <- c(paste0(greek,"19")) greek20 <- c(paste0(greek,"20")) greek21 <- c(paste0(greek,"21")) greek22 <- c(paste0(greek,"22")) greek23 <- c(paste0(greek,"23")) greek24 <- c(paste0(greek,"24")) greek25 <- c(paste0(greek,"25")) greek26 <- c(paste0(greek,"26")) greek27 <- c(paste0(greek,"27")) greek28 <- c(paste0(greek,"28")) greek29 <- c(paste0(greek,"29")) greek30 <- c(paste0(greek,"30")) greek_list <- setNames(paste0("\\", greek),greek) greek_list0 <- setNames(paste0("\\", greek,"_","{0}"), greek0) greek_list1 <- setNames(paste0("\\", greek,"_","{1}"), greek1) greek_list2 <- setNames(paste0("\\", greek,"_","{2}"), greek2) greek_list3 <- setNames(paste0("\\", greek,"_","{3}"), greek3) greek_list4 <- setNames(paste0("\\", greek,"_","{4}"), greek4) greek_list5 <- setNames(paste0("\\", greek,"_","{5}"), greek5) greek_list6 <- setNames(paste0("\\", greek,"_","{6}"), greek6) greek_list7 <- setNames(paste0("\\", greek,"_","{7}"), greek7) greek_list8 <- setNames(paste0("\\", greek,"_","{8}"), greek8) greek_list9 <- setNames(paste0("\\", greek,"_","{9}"), greek9) greek_list10 <- setNames(paste0("\\", greek,"_","{10}"), greek10) greek_list11 <- setNames(paste0("\\", greek,"_","{11}"), greek11) greek_list12 <- setNames(paste0("\\", greek,"_","{12}"), greek12) greek_list13 <- setNames(paste0("\\", greek,"_","{13}"), greek13) greek_list14 <- setNames(paste0("\\", greek,"_","{14}"), greek14) greek_list15 <- setNames(paste0("\\", greek,"_","{15}"), greek15) greek_list16 <- setNames(paste0("\\", greek,"_","{16}"), greek16) greek_list17 <- setNames(paste0("\\", greek,"_","{17}"), greek17) greek_list18 <- setNames(paste0("\\", greek,"_","{18}"), greek18) greek_list19 <- setNames(paste0("\\", greek,"_","{19}"), greek19) greek_list20 <- setNames(paste0("\\", greek,"_","{20}"), greek20) greek_list21 <- setNames(paste0("\\", greek,"_","{21}"), greek21) greek_list22 <- setNames(paste0("\\", greek,"_","{22}"), greek22) greek_list23 <- setNames(paste0("\\", greek,"_","{23}"), greek23) greek_list24 <- setNames(paste0("\\", greek,"_","{24}"), greek24) greek_list25 <- setNames(paste0("\\", greek,"_","{25}"), greek25) greek_list26 <- setNames(paste0("\\", greek,"_","{26}"), greek26) greek_list27 <- setNames(paste0("\\", greek,"_","{27}"), greek27) greek_list28 <- setNames(paste0("\\", greek,"_","{28}"), greek28) greek_list29 <- setNames(paste0("\\", greek,"_","{29}"), greek29) greek_list30 <- setNames(paste0("\\", greek,"_","{30}"), greek30) mem_sde <- c("m","S","m1","m2","m3","S1","S2","S3","C12","C13","C23") mem_sde_tex <- c("m(t)","S(t)","m_{1}(t)","m_{2}(t)","m_{3}(t)","S_{1}(t)","S_{2}(t)","S_{3}(t)","C_{12}(t)","C_{13}(t)","C_{23}(t)") mem_sde_list <- setNames(mem_sde_tex, mem_sde) var_sde <- c("x","y","z","w","w1","w2","w3","X","Y","Z","W","W1","W2","W3") var_sde_tex <- c("X_{t}","Y_{t}","Z_{t}","W_{t}","W_{1,t}","W_{2,t}", "W_{3,t}","X_{t}","Y_{t}","Z_{t}","W_{t}","W_{1,t}","W_{2,t}", "W_{3,t}") var_sde_list <- setNames(var_sde_tex, var_sde) greek_env <- list2env(as.list(c(greek_list,greek_list0,greek_list1,greek_list2,greek_list3,greek_list4,greek_list5, greek_list6,greek_list7,greek_list8,greek_list9,greek_list10,greek_list11,greek_list12, greek_list13,greek_list14,greek_list15,greek_list16,greek_list17,greek_list18,greek_list19, greek_list20,greek_list21,greek_list22,greek_list23,greek_list24,greek_list25,greek_list26, greek_list27,greek_list28,greek_list29,greek_list30, mem_sde_list,var_sde_list)), parent = emptyenv()) unary_op <- function(left, right) { force(left) force(right) function(e1) { paste0(left, e1, right) } } binary_op <- function(sep) { force(sep) function(e1, e2) { if(missing(e2)){ paste0(" - ", e1) }else{ paste0(e1,sep,e2)} } } f_env <- new.env(parent = emptyenv()) f_env$"+" <- binary_op(" + ") f_env$"-" <- binary_op(" - ") f_env$"*" <- binary_op(" \\, ") f_env$"/" <- binary_op(" / ") f_env$"^" <- binary_op("^") f_env$"[" <- binary_op("_") f_env$"==" <- binary_op("=") f_env$"<=" <- binary_op(" \\leq ") f_env$">=" <- binary_op(" \\geq ") f_env$"&" <- binary_op(" \\,\\&\\, ") f_env$"|" <- binary_op(" \\mid ") f_env$"," <- binary_op(" \\, ") f_env$"{" <- unary_op("\\left{ ", " \\right}") f_env$"(" <- unary_op("\\left( ", " \\right)") f_env$sin <- unary_op("\\sin(", ")") f_env$cos <- unary_op("\\cos(", ")") f_env$tan <- unary_op("\\tan(", ")") f_env$exp <- unary_op("\\exp(", ")") f_env$expm1 <- unary_op("\\left(\\exp(", ")-1\\right)") f_env$sqrt <- unary_op("\\sqrt{", "}") f_env$log <- unary_op("\\log(", ")") f_env$log1p <- unary_op("\\log\\left(1+","\\right)") f_env$abs <- unary_op("\\left| ", "\\right| ") f_env$sign <- unary_op("\\mathop{\\mathrm{sgn}}(", ")") f_env$"/" <- function(a, b) { paste0("\\frac{", a, "}{", b, "}") } f_env$"P" <- unary_op(" \\mathsf{P}(",")") f_env$"F" <- unary_op(" \\mathsf{F}(",")") f_env$"f" <- unary_op(" \\mathsf{f}(",")") f_env$"S" <- unary_op(" \\mathsf{S}(",")") f_env$"H" <- unary_op(" \\mathsf{H}(",")") f_env$"h" <- unary_op(" \\mathsf{h}(",")") f_env$"E" <- unary_op(" \\mathsf{E}(",")") f_env$"V" <- unary_op(" \\mathsf{V}(",")") f_env$"COV" <- unary_op(" \\mathsf{COV}(",")") clone_env <- function(env, parent = parent.env(env)) { list2env(as.list(env), parent = parent) } latex_env <- function(expr) { greek_env } if (class(object) == "data.frame"){ cat("%%% LaTeX table generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method", "\n") cat("%%% Copy and paste the following output in your LaTeX file", "\n\n") cat(knitr::kable(object, format = "latex",...), "\n") }else if (class(object) == "MCM.sde"){ tab <- object$MC expr <- parse(text = rownames(tab)) names <- all.names(expr ) greek_env <- list2env(as.list(c(greek_list,greek_list1,greek_list2,greek_list3,greek_list4,greek_list5, greek_list6,greek_list7,greek_list8,greek_list9,greek_list10, mem_sde_list)), parent = emptyenv()) symbol_list <- setNames(as.list(names), names) symbol_env <- list2env(symbol_list, parent = f_env) greek_env <- clone_env(greek_env, parent = symbol_env) rownames(tab) <- sapply(1:length(expr),function(i) eval(expr[i], latex_env(expr[i]))) greek_test <- as.list(c(mem_sde,mem_sde_tex, greek,greek1,greek2,greek3,greek4,greek5, greek6,greek7,greek8,greek9,greek10,greek_list, greek_list1,greek_list2,greek_list3,greek_list4,greek_list5, greek_list6,greek_list7,greek_list8,greek_list9,greek_list10)) rownames(tab) <- sapply(1:length(expr),function(i) ifelse(rownames(tab)[i]%in%greek_test,paste0("$", rownames(tab)[i],"$") ,rownames(tab)[i]) ) colnames(tab)[length(names(tab))] <- "CI( 2.5 \\% , 97.5 \\% )" cat("%%% LaTeX table generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method", "\n") cat("%%% Copy and paste the following output in your LaTeX file", "\n\n") cat(knitr::kable(tab, format = "latex", escape = FALSE,...), "\n") }else if (class(object) == "expression"){ expr <- object names <- all.names(expr) symbol_list <- setNames(as.list(names), names) symbol_env <- list2env(symbol_list, parent = f_env) greek_env <- clone_env(greek_env, parent = symbol_env) if (length(expr)== 2){ dr = eval(expr[[1]], latex_env(expr[[1]])) df = eval(expr[[2]], latex_env(expr[[2]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body,paste("dX_{t} =",dr,"\\:dt + ",df,"\\:dW_{t}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex")} else if (length(expr)== 4){ dr1 = eval(expr[[1]], latex_env(expr[[1]])) dr2 = eval(expr[[2]], latex_env(expr[[2]])) df1 = eval(expr[[3]], latex_env(expr[[3]])) df2 = eval(expr[[4]], latex_env(expr[[4]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body, paste("\\begin{cases}")) body <- c(body, paste("\\begin{split}")) body <- c(body,paste("dX_{t} &=",dr1,"\\:dt + ",df1,"\\:dW_{1,t}","\\\\")) body <- c(body,paste("dY_{t} &=",dr2,"\\:dt + ",df2,"\\:dW_{2,t}")) body <- c(body, paste("\\end{split}")) body <- c(body, paste("\\end{cases}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex")} else if (length(expr)== 6){ dr1 = eval(expr[[1]], latex_env(expr[[1]])) dr2 = eval(expr[[2]], latex_env(expr[[2]])) dr3 = eval(expr[[3]], latex_env(expr[[3]])) df1 = eval(expr[[4]], latex_env(expr[[4]])) df2 = eval(expr[[5]], latex_env(expr[[5]])) df3 = eval(expr[[6]], latex_env(expr[[6]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body, paste("\\begin{cases}")) body <- c(body, paste("\\begin{split}")) body <- c(body,paste("dX_{t} &=",dr1,"\\:dt + ",df1,"\\:dW_{1,t}","\\\\")) body <- c(body,paste("dY_{t} &=",dr2,"\\:dt + ",df2,"\\:dW_{2,t}","\\\\")) body <- c(body,paste("dZ_{t} &=",dr3,"\\:dt + ",df3,"\\:dW_{3,t}")) body <- c(body, paste("\\end{split}")) body <- c(body, paste("\\end{cases}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex")} }else if (class(object) == "MEM.sde"){ if (object$dim==1){ expr <- c(parse(text = deparse(object$Means)),parse(text = deparse(object$Var))) names <- all.names(expr) symbol_list <- setNames(as.list(names), names) symbol_env <- list2env(symbol_list, parent = f_env) greek_env <- clone_env(greek_env, parent = symbol_env) dm = eval(expr[[1]], latex_env(expr[[1]])) dS = eval(expr[[2]], latex_env(expr[[2]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body, paste("\\begin{cases}")) body <- c(body, paste("\\begin{split}")) body <- c(body,paste("\\frac{d}{dt} m(t) &=",dm,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S(t) &=",dS)) body <- c(body, paste("\\end{split}")) body <- c(body, paste("\\end{cases}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex") } else if (object$dim==2){ expr <- c(parse(text = deparse(object$Means[[1]])),parse(text = deparse(object$Means[[2]])), parse(text = deparse(object$Var[[1]])),parse(text = deparse(object$Var[[2]])), parse(text = deparse(object$Var[[3]]))) names <- all.names(expr) symbol_list <- setNames(as.list(names), names) symbol_env <- list2env(symbol_list, parent = f_env) greek_env <- clone_env(greek_env, parent = symbol_env) dm1 = eval(expr[[1]], latex_env(expr[[1]])) dm2 = eval(expr[[2]], latex_env(expr[[2]])) dS1 = eval(expr[[3]], latex_env(expr[[3]])) dS2 = eval(expr[[4]], latex_env(expr[[4]])) dC12 = eval(expr[[5]], latex_env(expr[[5]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body, paste("\\begin{cases}")) body <- c(body, paste("\\begin{split}")) body <- c(body,paste("\\frac{d}{dt} m_{1}(t) ~&=",dm1,"\\\\")) body <- c(body,paste("\\frac{d}{dt} m_{2}(t) ~&=",dm2,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S_{1}(t) ~&=",dS1,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S_{2}(t) ~&=",dS2,"\\\\")) body <- c(body,paste("\\frac{d}{dt} C_{12}(t) &=",dC12)) body <- c(body, paste("\\end{split}")) body <- c(body, paste("\\end{cases}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex") } else if (object$dim==3){ expr <- c(parse(text = deparse(object$Means[[1]])),parse(text = deparse(object$Means[[2]])),parse(text =deparse(object$Means[[3]])), parse(text = deparse(object$Var[[1]])),parse(text = deparse(object$Var[[2]])),parse(text = deparse(object$Var[[3]])), parse(text = deparse(object$Var[[4]])),parse(text = deparse(object$Var[[5]])),parse(text =deparse(object$Var[[6]]))) names <- all.names(expr) symbol_list <- setNames(as.list(names), names) symbol_env <- list2env(symbol_list, parent = f_env) greek_env <- clone_env(greek_env, parent = symbol_env) dm1 = eval(expr[[1]], latex_env(expr[[1]])) dm2 = eval(expr[[2]], latex_env(expr[[2]])) dm3 = eval(expr[[3]], latex_env(expr[[3]])) dS1 = eval(expr[[4]], latex_env(expr[[4]])) dS2 = eval(expr[[5]], latex_env(expr[[5]])) dS3 = eval(expr[[6]], latex_env(expr[[6]])) dC12 = eval(expr[[7]], latex_env(expr[[7]])) dC13 = eval(expr[[8]], latex_env(expr[[8]])) dC23 = eval(expr[[9]], latex_env(expr[[9]])) body <- paste("%%% LaTeX equation generated in R",strsplit(version[['version.string']], ' ')[[1]][3],"by TEX.sde() method") body <- c(body,paste("%%% Copy and paste the following output in your LaTeX file\n")) body <- c(body, paste("\\begin{equation}\\label{eq:}")) body <- c(body, paste("\\begin{cases}")) body <- c(body, paste("\\begin{split}")) body <- c(body,paste("\\frac{d}{dt} m_{1}(t) ~&=",dm1,"\\\\")) body <- c(body,paste("\\frac{d}{dt} m_{2}(t) ~&=",dm2,"\\\\")) body <- c(body,paste("\\frac{d}{dt} m_{3}(t) ~&=",dm3,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S_{1}(t) ~&=",dS1,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S_{2}(t) ~&=",dS2,"\\\\")) body <- c(body,paste("\\frac{d}{dt} S_{3}(t) ~&=",dS3,"\\\\")) body <- c(body,paste("\\frac{d}{dt} C_{12}(t) &=",dC12,"\\\\")) body <- c(body,paste("\\frac{d}{dt} C_{13}(t) &=",dC13,"\\\\")) body <- c(body,paste("\\frac{d}{dt} C_{23}(t) &=",dC23)) body <- c(body, paste("\\end{split}")) body <- c(body, paste("\\end{cases}")) body <- c(body, paste("\\end{equation}")) structure(body, class = "Latex") } }else {return(paste0("TEX.sde() function not available for this class."))} }
test_that( desc = "checking ggcorrmat - without NAs - pearson's r", code = { skip_if_not_installed("ggcorrplot") set.seed(123) p <- ggcorrmat( data = iris, cor.vars.names = "x", type = "p", title = "Iris dataset", subtitle = "By Edgar Anderson", sig.level = 0.001, matrix.type = "full", p.adjust.method = "fdr", colors = NULL, k = 4, ggcorrplot.args = list( lab_col = "white", pch.col = "white" ) ) pb <- ggplot2::ggplot_build(p) p_legend_title <- pb$plot$plot_env$legend.title set.seed(123) expect_snapshot(pb$data) expect_snapshot(list(p$labels, pb$plot$plot_env$legend.title)) } ) test_that( desc = "checking ggcorrmat - without NAs - robust r", code = { skip_if_not_installed("ggcorrplot") set.seed(123) p <- ggcorrmat( data = anscombe, type = "r", partial = TRUE, cor.vars.names = names(anscombe) ) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(pb$data) expect_snapshot(list(p$labels, pb$plot$plot_env$legend.title)) } ) test_that( desc = "checking ggcorrmat - with NAs - robust r - partial", code = { skip_if_not_installed("ggcorrplot") skip_on_ci() set.seed(123) p <- ggcorrmat( data = ggplot2::msleep, type = "r", sig.level = 0.01, partial = TRUE, p.adjust.method = "hommel", matrix.type = "upper" ) + labs(caption = NULL) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(pb$data) expect_snapshot(list(p$labels, pb$plot$plot_env$legend.title)) } ) test_that( desc = "checking ggcorrmat - with NAs - spearman's rho", code = { skip_if_not_installed("ggcorrplot") set.seed(123) p <- suppressWarnings(ggcorrmat( data = ggplot2::msleep, cor.vars = sleep_total:awake, cor.vars.names = "sleep_total", type = "np", sig.level = 0.01, matrix.type = "full", p.adjust.method = "hommel", caption.default = FALSE, colors = NULL, package = "wesanderson", palette = "Rushmore1" )) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(pb$data) expect_snapshot(list(p$labels, pb$plot$plot_env$legend.title)) } ) test_that( desc = "checking Bayesian pearson (with NA)", code = { skip_if_not_installed("ggcorrplot") set.seed(123) p <- suppressWarnings(ggcorrmat(dplyr::select(ggplot2::msleep, brainwt, bodywt), type = "bayes" )) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(list(p$labels, pb$plot$plot_env$legend.title)) } ) test_that( desc = "checking all dataframe outputs", code = { skip_on_cran() options(tibble.width = Inf) skip_if_not(.Platform$OS.type == "windows") set.seed(123) expect_snapshot(suppressWarnings(purrr::pmap( .l = list( data = list(dplyr::select(ggplot2::msleep, brainwt, sleep_rem, bodywt)), type = list("p", "p", "np", "np", "r", "r", "bf", "bayes"), output = list("dataframe"), partial = list(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE) ), .f = ggcorrmat ))) } )
fetch_hook_gh_description <- function(key, namespace) { if (!isTRUE(unname(capabilities("libcurl")))) { stop("This vignette requires libcurl support in R to run") } fmt <- "https://raw.githubusercontent.com/%s/master/DESCRIPTION" path <- tempfile("gh_description_") on.exit(file.remove(path)) code <- download.file(sprintf(fmt, key), path, mode = "wb") if (code != 0L) { stop("Error downloading file") } as.list(read.dcf(path)[1, ]) } st <- storr::storr_external(storr::driver_environment(), fetch_hook_gh_description) st$list() d <- st$get("richfitz/storr") identical(st$get("richfitz/storr"), d) st$list() tryCatch(st$get("richfitz/no_such_repo"), KeyErrorExternal = function(e) message(sprintf("** Repository %s not found", e$key))) st_rds <- st$export(storr::storr_rds(tempfile(), mangle_key = TRUE)) st_rds$list() st_rds$get("richfitz/storr")$Version st_rds$destroy() f <- function(a, b) { message(sprintf("Computing f(%.3f, %.3f)", a, b)) list(a, b) } pars <- data.frame(id = as.character(1:10), a = runif(10), b = runif(10), stringsAsFactors = FALSE) hook <- function(key, namespace) { p <- pars[match(key, pars$id), -1] f(p$a, p$b) } st <- storr::storr_external(storr::driver_environment(), hook) x <- st$get("1") identical(st$get("1"), x) st <- storr::storr_environment() st$set("experiment1", pars, namespace = "parameters") st$set("experiment1", f, namespace = "functions") hook2 <- function(key, namespace) { f <- st$get(namespace, namespace = "functions") pars <- st$get(namespace, namespace = "parameters") p <- pars[match(key, pars$id), -1] f(p$a, p$b) } st_use <- storr::storr_external(st$driver, hook2) x1 <- st_use$get("1", "experiment1") x2 <- st_use$get("1", "experiment1") memoise <- function(f, driver = storr::driver_environment()) { force(f) st <- storr::storr(driver) function(...) { key <- digest::digest(list(...)) tryCatch( st$get(key), KeyError = function(e) { ans <- f(...) st$set(key, ans) ans }) } } f <- function(x) { message("computing...") x * 2 } g <- memoise(f) g(1) g(1)
cwres.vs.cov <- function(object, ylb = "CWRES", smooth=TRUE, type="p", main="Default", ...) { if(is.null(check.vars(c("covariates","cwres"), object,silent=FALSE))) { return() } number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 for (j in xvardef("covariates", object)) { xplot <- xpose.plot.default(j, xvardef("cwres",object), object, main=NULL, ylb = ylb, smooth=smooth, type=type, pass.plot.list=TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste(xlabel(xvardef("cwres",object),object), " vs ", "Covariates", sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
.onLoad <- function(libname, pkgname) { onLoadSetCenterOnScalar() onLoadSetCenterOnUse() onLoadSetVarsFormulaFreq() onLoadSetVarsFormulaOnMistake() action <- Sys.getenv("R_MATRIXSTATS_VALIDATEINDICES", NA_character_) if (!is.na(action)) { action <- match.arg(action, choices = c("deprecated", "defunct")) options(matrixStats.validateIndices = action) } } .onUnload <- function(libpath) { library.dynam.unload("matrixStats", libpath) }
aa.compare <- function(x, seqlength){ specimen = nrow(x) aa <- c("A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y") VLF.count = mat.or.vec(nr = 20, nc = seqlength) single <- rep(0,216) shared <- rep(0,216) for(i in 1:seqlength){ for(n in 1:nrow(x)){ if(is.na(x[n,i+2]) == FALSE){ z = 1 match = FALSE while(match == FALSE && z <= length(aa)){ if(x[n, i+2] == aa[z]){ VLF.count[z,i] = VLF.count[z,i] + 1 match = TRUE } else{ z = z + 1 } } } } } for(i in 1:seqlength){ for(z in 1:20){ if(VLF.count[z,i] == 1) { single[i] = single[i] + 1 } else{ if(VLF.count[z,i] > 1){ shared[i] = shared[i] + VLF.count[z,i] } } } } return(rbind(single,shared)) }
qreg.hit = function(DATA1, DATA2, vecA) { Tsize = nrow(DATA1) p1 = ncol(DATA1) p2 = ncol(DATA2) qfit1 = rq(DATA1[,1] ~ DATA1[,2:p1], vecA[1]) qfit2 = rq(DATA2[,1] ~ DATA2[,2:p2], vecA[2]) vecRes1 = qfit1$residuals vecRes2 = qfit2$residuals matRes = data.matrix( cbind(vecRes1, vecRes2) ) vecI = matrix(1, Tsize, 1) mat0 = matrix(0, nrow = Tsize, 2) matQhit = (matRes <= mat0 ) - vecI %*% t(vecA) return(matQhit) }
library(soundgen) s1 = soundgen(sylLen = 900, temperature = 0.001, pitch = list(time = c(0, .3, .8, 1), value = c(300, 900, 400, 1300)), noise = c(-40, -20), subFreq = 100, subDep = 20, jitterDep = 0.5, plot = TRUE, ylim = c(0, 4)) osc(s1, samplingRate = 16000, dB = TRUE) seewave::meanspec(s1, f = 16000, dB = 'max0', main = 'Spectrum') spectrogram( s1, samplingRate = 16000, osc = 'dB', heights = c(2, 1), noiseReduction = .5, brightness = -1, contrast = .5, colorTheme = 'heat.colors', cex.lab = .75, cex.axis = .75, grid = 5, ylim = c(0, 5), main = 'Spectrogram' ) audSpectrogram(s1, samplingRate = 16000, nFilters = 128, step = 5, colorTheme = 'terrain.colors', main = 'Auditory spectrogram') modulationSpectrum(s1, samplingRate = 16000, colorTheme = 'seewave', plot = TRUE, main = 'Modulation spectrum') ssm(s1, samplingRate = 16000, main = 'Self-similarity matrix') a1 = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 4)) median(a1$detailed$pitch, na.rm = TRUE) spec = seewave::spec(s1, f = 16000, plot = FALSE) avSpec = seewave::meanspec(s1, f = 16000, plot = FALSE) head(avSpec) spgm = spectrogram(s1, samplingRate = 16000, output = 'original', plot = FALSE) str(spgm) spgm_norm = apply(spgm, 2, function(x) x / sum(x)) out = data.frame(skew = rep(NA, ncol(spgm)), quantile66 = NA, ratio500 = NA) for (i in 1:ncol(spgm_norm)) { df = data.frame( freq = as.numeric(rownames(spgm_norm)), d = spgm_norm[, i] ) m = sum(df$freq * df$d) out$skew[i] = sum((df$freq - m)^3 * df$d) out$quantile66[i] = df$freq[min(which(cumsum(df$d) >= 2/3))] out$ratio500[i] = sum(df$d[df$freq >= .5]) / sum(df$d[df$freq < .5]) } summary(out) a = analyze(s1, samplingRate = 16000, priorSD = 24, pitchMethods = c('autocor', 'cep', 'dom', 'spec', 'hps', 'zc'), plot = TRUE, ylim = c(0, 4)) par(mfrow = c(1, 2)) getPrior(priorMean = 300, priorSD = 6) getPrior(priorMean = 2000, priorSD = 1) par(mfrow = c(1, 1)) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'autocor', pitchAutocor = list(autocorThres = .45, col = 'green'), nCands = 3) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'dom', pitchDom = list(domThres = .1, domSmooth = 500, cex = 1.5)) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'cep', pitchCep = list(cepThres = .6), nCands = 3) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'spec', pitchSpec = list()) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'hps', pitchHps = list(hpsNum = 2, hpsThres = .2)) a = analyze(s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 2), osc = FALSE, priorMean = NA, priorAdapt = FALSE, pitchMethods = 'zc', pitchCeiling = 600, pitchZc = list(zcWin = 3, zcThres = 0)) s_withoutf0 = soundgen(sylLen = 600, pitch = 300, rolloffExact = c(0, 1, 1, 1), formants = NULL, lipRad = 0) seewave::meanspec(s_withoutf0, f = 16000, dB = 'max0', flim = c(0, 3)) a_withoutf0 = analyze(s_withoutf0, 16000, priorMean = NA, priorAdapt = FALSE, pitchMethods = c('autocor', 'dom', 'cep', 'spec', 'hps', 'zc'), pitchSpec = list(specMethod = 'BaNa'), plot = TRUE, ylim = c(0, 2), dynamicRange = 60, osc = FALSE) a = analyze( s1, samplingRate = 16000, plot = TRUE, ylim = c(0, 4), priorMean = NA, shortestSyl = 0, interpol = NULL, pathfinding = 'none', snakeStep = 0, smooth = 0 ) a1 = analyze(s1, samplingRate = 16000, step = 10, priorMean = NA, pitchMethods = 'cep', pitchCep = list(cepThres = .8), interpol = NULL, pathfinding = 'none', snakeStep = 0, smooth = 0, plot = FALSE) a2 = analyze(s1, samplingRate = 16000, step = 10, priorMean = NA, pitchMethods = 'cep', pitchCep = list(cepThres = .8), interpol = list(win = 100, tol = .1), pathfinding = 'none', snakeStep = 0, smooth = 0, plot = FALSE) plot(a1$detailed$time, a1$detailed$pitch, type = 'l', main = 'Interpolation', xlab = 'Time, ms', ylab = 'Pitch, Hz') points(a2$detailed$time, a2$detailed$pitch, type = 'l', col = 'red', lty = 3) a1 = analyze(s1, samplingRate = 16000, priorMean = NA, pitchMethods = 'cep', pitchCep = list(cepThres = .7), nCands = 3, pathfinding = 'none', snakeStep = 0, interpolTol = Inf, smooth = 0, summaryFun = NULL, plot = FALSE) a1$detailed$medianSmooth = soundgen:::medianSmoother( data.frame(pitch = a1$detailed$pitch), smoothing_ww = 3, smoothingThres = 1 )$pitch plot(pitch ~ time, data = a1$detailed, type = 'l', main = 'Median smoothing', xlab = 'Time, ms', ylab = 'Pitch, Hz') points(medianSmooth ~ time, data = a1$detailed, type = 'l', col = 'red', lty = 3, lwd = 2) a1$detailed$ps = pitchSmoothPraat( a1$detailed$pitch, bandwidth = 5, samplingRate = 1000/25) plot(pitch ~ time, data = a1$detailed, type = 'l', main = 'Low-pass smoothing', xlab = 'Time, ms', ylab = 'Pitch, Hz') points(ps ~ time, data = a1$detailed, type = 'l', col = 'red', lty = 3, lwd = 2) a = analyze( s1, samplingRate = 16000, plot = TRUE, priorMean = NA, xlab = 'Time (ms)', main = 'My spectrogram', dynamicRange = 90, contrast = .5, brightness = -0.3, colorTheme = 'seewave', ylim = c(0, 4), osc = 'dB', heights = c(3, 1), pitchPlot = list( col = 'black', lwd = 5, lty = 3 ), pitchAutocor = list(col = rgb(0, 1, 0, .5), pch = 16, cex = 2), pitchDom = list(col = 'red', cex = 4) ) pd = pitchDescriptives( a1$detailed$pitch, step = a1$detailed$time[2] - a1$detailed$time[1], timeUnit = 'ms', smoothBW = c(10, 1), inflThres = .2, plot = TRUE ) colnames(pd) s2 = soundgen(nSyl = 8, sylLen = 50, pauseLen = 70, temperature = 0, pitch = c(368, 284), amplGlobal = c(0, -20)) s2 = s2 + runif(length(s2), -10 ^ (-20 / 20), 10 ^ (-20 / 20)) a = segment(s2, samplingRate = 16000, plot = TRUE) a1 = segment(s2, samplingRate = 16000, plot = TRUE, SNR = 0.1, main = 'SNR very low') a2 = suppressWarnings(segment(s2, samplingRate = 16000, plot = TRUE, SNR = 14, main = 'SNR very high')) a1 = segment(s2, samplingRate = 16000, plot = TRUE, windowLength = 40, overlap = 0, main = 'overlap too low') a2 = suppressWarnings(segment(s2, samplingRate = 16000, plot = TRUE, windowLength = 5, overlap = 80, main = 'window too short')) a3 = segment(s2, samplingRate = 16000, plot = TRUE, windowLength = 150, overlap = 80, main = 'window too long') a1 = segment(s2, samplingRate = 16000, plot = TRUE, shortestSyl = 80, main = 'shortestSyl too long') a2 = segment(s2, samplingRate = 16000, plot = TRUE, shortestPause = 80, main = 'shortestPause too long') dur = .5 samplingRate = 16000 f0 = getSmoothContour(c(70, 8000), len = samplingRate * dur, thisIsPitch = TRUE) sweep = sin(2 * pi * cumsum(f0) / samplingRate) a = analyze(sweep, samplingRate = samplingRate, pitchMethods = NULL, plot = FALSE) par(mfrow = c(1, 2)) plot(a$detailed$time, a$detailed$ampl, type = 'l', ylim = c(0, 1), main = 'RMS') plot(a$detailed$time, a$detailed$loudness, type = 'l', main = 'Loudness') par(mfrow = c(1, 1)) l = getLoudness(sweep, samplingRate = 16000) s = soundgen(pitch = 70, amFreq = 25, amDep = 80, rolloff = -15) ms = modulationSpectrum(s, samplingRate = 16000, logWarp = NULL, windowLength = 25, step = 25, amRes = NULL) ms = modulationSpectrum(s, samplingRate = 16000, logWarp = NULL, windowLength = 40, step = 10, amRes = NULL) ms = modulationSpectrum( s, samplingRate = 16000, windowLength = 15, step = 5, amRes = NULL, logSpec = FALSE, power = 2, roughRange = c(30, 150), amRange = c(10, 70), logWarp = 2, kernelSize = 7, quantiles = c(.5, .8, .95, .99), colorTheme = 'terrain.colors' ) ms[c('roughness', 'amFreq', 'amDep')] s3 = c(soundgen(), soundgen(nSyl = 4, sylLen = 50, pauseLen = 70, formants = NA, pitch = c(500, 330))) m = ssm(s3, samplingRate = 16000) par(mfrow = c(2, 1)) m1 = ssm(s3, samplingRate = 16000, input = 'melspec', simil = 'cor', norm = FALSE, ssmWin = 10, kernelLen = 150) m2 = ssm(s3, samplingRate = 16000, input = 'mfcc', simil = 'cosine', norm = TRUE, ssmWin = 50, kernelLen = 600) par(mfrow = c(1, 1))
"ucedergreen" <- function( fixed = c(NA, NA, NA, NA, NA), names = c("b", "c", "d", "e", "f"), method = c("1", "2", "3", "4"), ssfct = NULL, alpha) { numParm <- 5 if (!is.character(names) | !(length(names) == numParm)) {stop("Not correct 'names' argument")} if (!(length(fixed) == numParm)) {stop("Not correct 'fixed' argument")} if (missing(alpha)) {stop("'alpha' argument must be specified")} notFixed <- is.na(fixed) parmVec <- rep(0, numParm) parmVec[!notFixed] <- fixed[!notFixed] parmVec1 <- parmVec parmVec2 <- parmVec fct <- function(dose, parm) { parmMat <- matrix(parmVec, nrow(parm), numParm, byrow = TRUE) parmMat[, notFixed] <- parm numTerm <- parmMat[, 3] - parmMat[, 2] + parmMat[, 5]*exp(-1/dose^alpha) denTerm <- 1 + exp(parmMat[, 1]*(log(dose) - log(parmMat[, 4]))) parmMat[, 3] - numTerm/denTerm } if (!is.null(ssfct)) { ssfct <- ssfct } else { ssfct <- function(dframe) { initval <- llogistic()$ssfct(dframe) initval[1] <- -initval[1] initval[5] <- 0 return(initval[notFixed]) } } deriv1 <- function(dose, parm) { parmMat <- matrix(parmVec, nrow(parm), numParm, byrow=TRUE) parmMat[, notFixed] <- parm t0 <- exp(-1/(dose^alpha)) t1 <- parmMat[, 3] - parmMat[, 2] + parmMat[, 5]*t0 t2 <- exp(parmMat[, 1]*(log(dose) - log(parmMat[, 4]))) t3 <- 1 + t2 t4 <- (1 + t2)^(-2) cbind( t1*xlogx(dose/parmMat[, 4], parmMat[, 1])*t4, 1/t3, 1 - 1/t3, -t1*t2*(parmMat[, 1]/parmMat[, 4])*t4, -t0/t3 )[, notFixed] } deriv2 <- NULL edfct <- function(parm, p, lower = 1e-4, upper = 10000, ...) { cedergreen(fixed = fixed, names = names, alpha = alpha)$edfct(parm, 100 - p, lower, upper, ...) } maxfct <- function(parm, upper, interval) { retVal <- cedergreen(fixed = fixed, names = names, alpha = alpha)$maxfct(parm, upper, interval) retVal[2] <- (parm[2] + parm[3]) - retVal[2] return(retVal) } returnList <- list(fct = fct, ssfct = ssfct, names = names[notFixed], edfct = edfct, maxfct = maxfct, name = "ucedergreen", text = "U-shaped Cedergreen-Ritz-Streibig", noParm = sum(is.na(fixed))) class(returnList) <- "UCRS" invisible(returnList) } "UCRS.4a" <- function(names = c("b", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 4)) {stop("Not correct 'names' argument")} return(ucedergreen(names = c(names[1], "c", names[2:4]), fixed = c(NA, 0, NA, NA, NA), alpha = 1, ...)) } uml3a <- UCRS.4a "UCRS.4b" <- function(names = c("b", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 4)) {stop("Not correct 'names' argument")} return(ucedergreen(names = c(names[1], "c", names[2:4]), fixed = c(NA, 0, NA, NA, NA), alpha = 0.5, ...)) } uml3b <- UCRS.4b "UCRS.4c" <- function(names = c("b", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 4)) {stop("Not correct 'names' argument")} return(ucedergreen(names = c(names[1], "c", names[2:4]), fixed = c(NA, 0, NA, NA, NA), alpha = 0.25, ...)) } uml3c <- UCRS.4c "UCRS.5a" <- function(names = c("b", "c", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 5)) {stop("Not correct 'names' argument")} return(ucedergreen(names = names, fixed = c(NA, NA, NA, NA, NA), alpha = 1, ...)) } uml4a <- UCRS.5a "UCRS.5b" <- function(names = c("b", "c", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 5)) {stop("Not correct 'names' argument")} return(ucedergreen(names = names, fixed = c(NA, NA, NA, NA, NA), alpha = 0.5, ...)) } uml4b <- UCRS.5b "UCRS.5c" <- function(names = c("b", "c", "d", "e", "f"), ...) { if (!is.character(names) | !(length(names) == 5)) {stop("Not correct 'names' argument")} return(ucedergreen(names = names, fixed = c(NA, NA, NA, NA, NA), alpha = 0.25, ...)) } uml4c <- UCRS.5c
context("test-color-spaces") hex_codes <- c(" " " test_that("Colour space conversions pass without error", { expect_equal(sum(is.na(hex_to_lab(hex_codes))), 0) expect_equal(sum(is.na(hex_to_rgb(hex_codes))), 0) expect_equal(sum(is.na(hex_to_lab(hex_codes, transformation = "Adobe"))), 0) expect_equal(sum(is.na(rgb_to_hex(hex_to_rgb(hex_codes)))), 0) expect_equal(sum(is.na(lab_to_hex(hex_to_lab(hex_codes)))), 0) expect_equal(sum(is.na(lab_to_hex(hex_to_lab(hex_codes, transformation = "Adobe"), transformation = "Adobe"))), 0) }) test_that("Colour space conversions and back again with sRGB", { expect_equal(rgb_to_hex(hex_to_rgb(hex_codes)), tolower(hex_codes)) expect_equal(xyz_to_hex(hex_to_xyz(hex_codes)), tolower(hex_codes)) expect_equal(lab_to_hex(hex_to_lab(hex_codes)), tolower(hex_codes)) }) test_that("Colour space conversions and back again with sRGB", { expect_equal(xyz_to_hex(hex_to_xyz(hex_codes, transformation = "Adobe"), transformation = "Adobe"), tolower(hex_codes)) expect_equal(lab_to_hex(hex_to_lab(hex_codes, transformation = "Adobe"), transformation = "Adobe"), tolower(hex_codes)) })
csPlot <- function(cs1, cs2, group = NULL, data = NULL, ylab = "CRs", col = c("black", "grey"), legend = c("cs1", "cs2")) { if (!is.null(data)) { cs1 <- data[, deparse(substitute(cs1))] cs2 <- data[, deparse(substitute(cs2))] if (deparse(substitute(group)) != "NULL") { group <- as.factor(data[, deparse(substitute(group))]) } } if (!is.null(group)) { ng <- length(unique(stats::na.omit(group))) if (ng %in% c(0, 1)) { group <- NULL } else { if (ng > 2) { stop("You can define up to two groups. Number of groups defined: ", as.character(ng)) } } } if (!is.null(group)) { desc <- by( data.frame(cs1, cs2, stringsAsFactors = FALSE), group, psych::describe, skew = FALSE, ranges = FALSE ) } else { desc <- psych::describe( data.frame(cs1, cs2, stringsAsFactors = FALSE), skew = FALSE, ranges = FALSE ) } opmar <- graphics::par()$mar opmgp <- graphics::par()$mgp on.exit(graphics::par(mar = opmar, mgp = opmgp)) graphics::par(mar = c(6, 10, 4.1, 8.1), mgp = c(2, 1, .5)) if (length(col) != length(legend)) { warning( "The length of the color argument, (i.e., ", length(col), "), is different than the length of the legend argument, (i.e.,", length(legend), "). The plotted legends may not correspond to the right bars." ) } if (!is.null(group)) { meanz <- c(desc[[1]]["mean"], desc[[2]]["mean"]) sdz <- c(desc[[1]]["se"], desc[[2]]["se"]) graphics::barplot( matrix(unlist(meanz), 2, 2), col = col, beside = TRUE, names.arg = unlist(attr(table(group), "dimnames")), cex.names = 1.5, cex.main = 1.5, las = 1, cex.lab = 2, cex.axis = 1, bty = "n", lwd = 1, xpd = TRUE, pch = 19 ) graphics::mtext(ylab, 2, line = 3, cex = 1.5, las = 0) graphics::legend( x = "topright", legend = legend, inset = c(-0.2, 0), title = "Stimulus", bty = "n", pch = 15, bg = "black", col = col, cex = 1.5, xpd = TRUE ) } else { meanz <- desc["mean"] sdz <- desc["se"] graphics::barplot( as.numeric(unlist(meanz)), col = col, names.arg = NULL, cex.main = 1.5, las = 1, cex.lab = 2, cex.axis = 1, bty = "n", lwd = 1, xpd = TRUE, pch = 19 ) graphics::mtext(ylab, 2, line = 3, cex = 1.5, las = 0) graphics::legend( x = "topright", legend = legend, inset = c(-0.2, 0), title = "Stimulus", bty = "n", pch = 15, bg = "black", col = col, cex = 1.5, xpd = TRUE ) } }
generateJAGSlhd.gamma <- function(jags.model.args, mean.model, dispersion.model, rounding, residuals, include.checks){ string <- c("\t\t "\t\t y[i] ~ dgamma(ry[i], lambday[i])\n\n") if(rounding){ string <- c(string, generateJAGSrounding(jags.model.args)) } string <- c(string, "\t\t if(is.null(dispersion.model$weights)) string <- c(string, "\t\t lambday[i] <- weights[i]/phi[i]\n", "\t\t ry[i] <- weights[i] * muy[i] * lambday[i]\n") else string <- c(string, "\t\t lambday[i] <- 1/phi[i]\n", "\t\t ry[i] <- muy[i] * lambday[i]\n") string <- c(string, "\t\t vary[i] <- phi[i] * muy[i]\n", "\t\t sdy[i] <- sqrt(vary[i])\n\n") if(include.checks){ string <- c(string, generateJAGSchecks(jags.model.args, "(muy[i] > 0)", "(phi[i] > 0)")) } if(residuals){ string <- c(string, "\t\t "\t\t resid[i] <- (y[i] - muy[i])/sdy[i]\n\n") } string }
library(xpectr) context("element descriptors") test_that("num_total_elements() works", { l <- list(list(list(1, 2, 3), list(2, list(3, 2))), list(1, list(list(2, 4), list(7, 1, list(3, 8)))), list(list(2, 7, 8), list(10, 2, list(18, 1, 4)))) expect_equal(num_total_elements(l), 21) expect_equal(num_total_elements(l, deduplicated = TRUE), 8) l <- list(list(list("1", "2", "3"), list("2", list("3", "2"))), list("1", list(list("2", "4"), list("7", "1", list("3", "8")))), list(list("2", "7", "8"), list("10", "2", list("18", "1", "4")))) expect_equal(num_total_elements(l), 21) expect_equal(num_total_elements(l, deduplicated = TRUE), 8) }) test_that("element_lengths() works", { l <- list(list(list(1, 2, 3), list(2, list(3, 2))), list(1, list(list(2, 4), list(7, 1, list(3, 8)))), list(list(2, 7, 8), list(10, 2, list(18, 1, 4)))) expect_equal(element_lengths(l), c(2, 2, 2)) expect_equal(element_lengths(l, keep_names = TRUE), c(2, 2, 2)) l <- list("x" = list(list(1, 2, 3), list(2, list(3, 2))), "y" = list(1, list(list(2, 4), list(7, 1, list(3, 8)))), "z" = list(list(2, 7, 8), list(10, 2, list(18, 1, 4)))) expect_equal(element_lengths(l), c(2, 2, 2)) expect_equal(element_lengths(l, keep_names = TRUE), c(x = 2L, y = 2L, z = 2L)) vec <- list("a" = c(1,2,3), "b" = c(4,3,2), "c" = c(7,6,5,4,3,2)) expect_equal(element_lengths(vec), c(3, 3, 6)) }) test_that("element_types() works", { l <- list("a" = c(1,2,3), "b" = "a", "c" = NULL, "d" = NA, "e" = formula(x ~ b)) expect_equal(element_types(l), c("double", "character", "NULL", "logical", "language")) expect_equal(element_types(l, keep_names = TRUE), c(a = "double", b = "character", c = "NULL", d = "logical", e = "language")) }) test_that("element_classes() works", { l <- list("a" = c(1,2,3), "b" = "a", "c" = NULL, "d" = NA, "e" = formula(x ~ b)) expect_equal(element_classes(l), c("numeric", "character", "NULL", "logical", "formula")) expect_equal(element_classes(l, keep_names = TRUE), c(a = "numeric", b = "character", c = "NULL", d = "logical", e = "formula")) })
install.python = function (page_with_download_url = "https://www.python.org/downloads/windows/", version_number = 3, x64 = TRUE, ...) { page <- readLines(page_with_download_url, warn = FALSE) pat <- paste0("Latest Python ",version_number," Release") pat_exact_version <- paste0("Python ",version_number,"[0-9.]+") target_line <- grep(pat, page, value = TRUE) m <- regexpr(pat_exact_version, target_line) VersionNo <- regmatches(target_line, m)[1] VersionNo <- gsub("Python ", "", VersionNo) file_extension <- switch(as.character(version_number), "2" = "msi", "3" = "exe") URL <- paste0("https://www.python.org/ftp/python/",VersionNo, "/python-",VersionNo , ".", file_extension)[1] if(x64){ URL <- sub(".exe", "-amd64.exe", URL) URL <- sub(".msi", ".amd64.msi", URL) } install.URL(URL, ...) }
kolmogorov.unif.test<-function(x, nrepl=2000,k=0) { DNAME <- deparse(substitute(x)) l<-0 n<-length(x) if (k==1) { d<-max(c(1:n)/(n+1)-x) for(i in 1:nrepl) { z<-runif(n) D<-max(c(1:n)/(n+1)-z) if (D>d) l=l+1 } } if (k==0) { d<-max(abs(c(1:n)/(n+1)-x)) for(i in 1:nrepl) { z<-runif(n) D<-max(abs(c(1:n)/(n+1)-z)) if (D>d) l=l+1 } } if (k==-1) { d<-max(x-c(1:n)/(n+1)) for(i in 1:nrepl) { z<-runif(n) D<-max(z-c(1:n)/(n+1)) if (D>d) l=l+1 } } p.value<-l/nrepl RVAL<-list(statistic=c(D=d), p.value=p.value, method="Kolmogorov-Smirnov test for uniformity",data.name = DNAME) class(RVAL)<-"htest" return(RVAL) }
rfNews <- function() { newsfile <- file.path(system.file(package="randomForest"), "NEWS") file.show(newsfile) }
diferencia_cuadrada <- function(x, y=2) { x^2 - y^2 }
conditional_did_pretest <- function(yname, tname, idname=NULL, gname, xformla=NULL, data, panel=TRUE, allow_unbalanced_panel=FALSE, control_group=c("nevertreated","notyettreated"), weightsname=NULL, alp=0.05, bstrap=TRUE, cband=TRUE, biters=1000, clustervars=NULL, est_method="ipw", print_details=FALSE, pl=FALSE, cores=1) { message("We are no longer updating this function. It should continue to work, but most users find the pre-tests already reported by the `att_gt` function to be sufficient for most empirical applications.") dp <- pre_process_did(yname=yname, tname=tname, idname=idname, gname=gname, xformla=xformla, data=data, panel=panel, allow_unbalanced_panel=allow_unbalanced_panel, control_group=control_group, weightsname=weightsname, alp=alp, bstrap=bstrap, cband=cband, biters=biters, clustervars=clustervars, est_method=est_method, print_details=print_details, pl=pl, cores=cores ) data <- dp$data tlist <- dp$tlist glist <- dp$glist n <- dp$n if ( max(glist) <= tlist[2] ) { stop("There are no pre-treatment periods to use to conduct test.") } weightfun <- indicator if (allow_unbalanced_panel) { stop("Conditional pre-test not currently supported for unbalanced panel.") } ifelse(panel & (allow_unbalanced_panel==FALSE), dta <- data[ data[,tname]==tlist[1], ], dta <- data ) X <- model.matrix(xformla, dta) X1 <- X cat("Step 1 of 2: Computing test statistic....\n") out <- pbapply::pblapply(1:nrow(X), function(i) { www <- as.numeric(weightfun(X1, X[i,])) rightids <- dta[,idname][www==1] thisdata <- data thisdata[,yname] <- 0 thisdata[ thisdata[,idname] %in% rightids,yname] <- data[ thisdata[,idname] %in% rightids,yname] thisdata$y <- thisdata[,yname] thisdp <- dp thisdp$data <- thisdata thisdp$print_details <- FALSE Jres <- compute.att_gt(thisdp) J.results <- process_attgt(Jres$attgt.list) group <- J.results$group att <- J.results$att tt <- J.results$tt inf.func <- Jres$inffunc list(J=att, group=group, t=tt, inf.func=inf.func) }, cl=cores) out <- lapply(out, function(Js) { keepers <- Js$group > Js$t this.group <- Js$group[keepers] this.t <- Js$t[keepers] this.J <- as.matrix(Js$J[keepers]) this.inf.func <- as.matrix(Js$inf.func[,keepers]) list(J=this.J, group=this.group, t=this.t, inf.func=this.inf.func) }) Jinf.func <- simplify2array(BMisc::getListElement(out, "inf.func")) J.inner <- sapply(out, function(o) o$J) ifelse(class(J.inner)=="matrix", J <- t(J.inner), J <- as.matrix(J.inner)) CvM <- n*sum(apply(J^2, 2, mean)) cat("Step 2 of 2: Simulating limiting distribution of test statistic....\n") boot.res <- test.mboot(Jinf.func, dp, cores=cores) CvMb <- boot.res$bres CvM.crit.val <- boot.res$crit.val CvMpval <- 1-ecdf(CvMb)(CvM) out <- MP.TEST(CvM=CvM, CvMb=CvMb, CvMcval=CvM.crit.val, CvMpval=CvMpval, clustervars=clustervars, xformla=xformla) out } indicator <- function(X, u) { cond <- t(apply( X, 1, function(x) x <= u)) 1*apply(cond, 1, all) } test.mboot <- function(inf.func, DIDparams, cores=1) { data <- DIDparams$data idname <- DIDparams$idname clustervars <- DIDparams$clustervars biters <- DIDparams$biters tname <- DIDparams$tname tlist <- unique(data[,tname])[order(unique(data[,tname]))] alp <- DIDparams$alp panel <- DIDparams$panel ifelse(panel, dta <- data[ data[,tname]==tlist[1], ], dta <- data) n <- nrow(dta) if (idname %in% clustervars) { clustervars <- clustervars[-which(clustervars==idname)] } if (length(clustervars) > 1) { stop("can't handle that many cluster variables") } bout <- pbapply::pbsapply(1:biters, FUN=function(b) { if (length(clustervars) > 0) { n1 <- length(unique(dta[,clustervars])) Vb <- matrix(sample(c(-1,1), n1, replace=T)) Vb <- cbind.data.frame(unique(dta[,clustervars]), Vb) Ub <- data.frame(dta[,clustervars]) Ub <- Vb[match(Ub[,1], Vb[,1]),] Ub <- Ub[,-1] } else { Ub <- sample(c(-1,1), n, replace=T) } Jb <- t(apply(Ub*inf.func, c(2,3), mean)) CvMb <- n*sum(apply(Jb^2, 2, mean)) CvMb }, cl=cores) crit.val <- quantile(bout, 1-alp, type=1) list(bres=bout, crit.val=crit.val) }
summary.cover <- function(object, ...) { summary(cover2incidence(object)) }
grid_legend <- function (x, y, pch = NA, col = par('col'), labels, frame = TRUE, hgap = unit(0.8, "lines"), vgap = unit(0.8, "lines"), default_units = "lines", gp = gpar(), draw = TRUE, title = NULL, just = 'center', lwd = NA, lty = NA, size = 1, gp_title = NULL, gp_labels = NULL, gp_frame = gpar(fill = "transparent"), inset = c(0, 0)) { inset <- rep(inset, length.out = 2) if((length(x) > 1) && missing(y)) { y <- x[2] x <- x[1] } if(is.character(x)) switch(x, left = {x = unit(0 + inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("left","center")}, topleft = {x = unit(0 + inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c(0,1)}, top = {x = unit(0.5 + inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c("center", "top")}, topright = {x = unit(1 - inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c(1,1)}, center = {x = unit(0.5 + inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("center","center")}, bottom = {x = unit(0.5 - inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c("center","bottom")}, bottomright = {x = unit(1 - inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c(1,0)}, right = {x = unit(1 - inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("right","center")}, bottomleft = {x = unit(0 + inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c(0,0)}) labels <- as.character(labels) nlabs <- length(labels) if(length(pch) == 1) pch <- rep(pch, nlabs) if(length(lwd) == 1) lwd <- rep(lwd, nlabs) if(length(lty) == 1) lty <- rep(lty, nlabs) if(length(col) == 1) col <- rep(col, nlabs) if(length(gp_labels) == 1) gp_labels <- rep(list(gp_labels), nlabs) if (is.logical(title) && !title) title <- NULL if(is.null(title)) tit <- 0 else tit <- 1 if (!is.unit(hgap)) hgap <- unit(hgap, default_units) if (length(hgap) != 1) stop("hgap must be single unit") if (!is.unit(vgap)) vgap <- unit(vgap, default_units) if (length(vgap) != 1) stop("vgap must be single unit") if(tit) legend.layout <- grid.layout(nlabs + tit, 3, widths = unit.c(unit(2, "lines"), max(unit(rep(1, nlabs), "strwidth", as.list(c(labels))), unit(1, "strwidth", title) - unit(2, "lines")), hgap), heights = unit.pmax(unit(1, "lines"), vgap + unit(rep(1, nlabs + tit ), "strheight", as.list(c(labels,title))))) else legend.layout <- grid.layout(nlabs, 3, widths = unit.c(unit(2, "lines"), max(unit(rep(1, nlabs), "strwidth", as.list(labels))), hgap), heights = unit.pmax(unit(1, "lines"), vgap + unit(rep(1, nlabs), "strheight", as.list(labels)))) fg <- frameGrob(layout = legend.layout, gp = gp) if (frame) fg <- placeGrob(fg, rectGrob(gp = gp_frame)) if (tit) fg <- placeGrob(fg, textGrob(title, x = .2, y = 0.5, just = c("left", "center"), gp = gp_title), col = 1, row = 1) for (i in 1:nlabs) { if(!is.na(pch[i])) fg <- placeGrob(fg, pointsGrob(0.5, 0.5, pch = pch[i], size = unit(size, "char"), gp = gpar(col = col[i])), col = 1, row = i + tit) else if(!is.na(lwd[i]) || !is.na(lty[i])) fg <- placeGrob(fg, linesGrob( unit(c(0.2, .8), "npc"), unit(c(.5), "npc"), gp = gpar(col = col[i], lwd = lwd[i], lty=lty[i])), col = 1, row = i + tit) fg <- placeGrob(fg, textGrob(labels[i], x = .1, y = 0.5, just = c("left", "center"), gp = gp_labels[[i]]), col = 2, row = i + tit) } pushViewport(viewport(x, y, height = grobHeight(fg), width = grobWidth(fg), just = just )) if (draw) grid.draw(fg) popViewport(1) invisible(fg) }
NULL LiftCurvePlot = function(frame, xvar, truthVar, title, ..., large_count = 1000, include_wizard = TRUE, truth_target = NULL, model_color='darkblue', wizard_color='darkgreen') { frame <- check_frame_args_list(..., frame = frame, name_var_list = list(xvar = xvar, truthVar = truthVar), title = title, funname = "WVPlots::LiftCurvePlot") pct_outcome <- pctpop <- sort_criterion <- NULL if(!is.null(truth_target)) { truthcol <- as.numeric(frame[[truthVar]]==truth_target) } else { truthcol <- as.numeric(frame[[truthVar]]) } predcol <- as.numeric(frame[[xvar]]) d = data.frame(predcol = predcol, truthcol = truthcol) n <- nrow(d) predord = order(d[['predcol']], sample.int(n, n, replace = FALSE), decreasing = TRUE) wizard = order(d[['truthcol']], sample.int(n, n, replace = FALSE), decreasing = TRUE) npop = dim(d)[1] results = data.frame( pctpop = (1:npop) / npop, model = cumsum(d[predord, 'truthcol']) / sum(d[['truthcol']]), wizard = cumsum(d[wizard, 'truthcol']) / sum(d[['truthcol']]) ) results$model_lift <- results$model/results$pctpop results$wizard_lift <- results$wizard/results$pctpop r1 <- data.frame(pctpop = results$pctpop, pct_outcome = results$model_lift, sort_criterion = "model", stringsAsFactors = FALSE) r2 <- data.frame(pctpop = results$pctpop, pct_outcome = results$wizard_lift, sort_criterion = "wizard", stringsAsFactors = FALSE) results <- rbind(r1, r2, stringsAsFactors = FALSE) msort_str <- paste('model: sort by', xvar) sortKeyM <- c('model' = msort_str, 'wizard' = paste('wizard: sort by', truthVar)) results$sort_criterion <- sortKeyM[results$sort_criterion] colorKey = as.character(sortKeyM) %:=% c(model_color, wizard_color) names(colorKey) = c(paste('model: sort by', xvar), paste('wizard: sort by', truthVar)) modelKey = names(colorKey)[[1]] if(!include_wizard) { results <- results[results$sort_criterion==msort_str, , drop=FALSE] } results <- thin_frame_by_orders(results, c("pctpop", "pct_outcome"), "sort_criterion", large_count) gplot = ggplot2::ggplot(data = results) + ggplot2::geom_point( mapping = ggplot2::aes( x = pctpop, y = pct_outcome, color = sort_criterion, shape = sort_criterion ), alpha = 0.5 ) + ggplot2::geom_line( mapping = ggplot2::aes( x = pctpop, y = pct_outcome, color = sort_criterion, linetype = sort_criterion ) ) + ggplot2::ggtitle( title, subtitle = paste0( truthVar, '~', xvar)) + ggplot2::xlab("fraction items in sort order") + ggplot2::ylab("lift") + ggplot2::geom_hline(yintercept=1) + ggplot2::scale_x_continuous(breaks = seq(0, 1, 0.1)) + ggplot2::scale_color_manual(values = colorKey) + ggplot2::theme(legend.position = "bottom") gplot } LiftCurvePlotList = function(frame, xvars, truthVar, title, ..., truth_target = NULL, palette = 'Dark2') { frame <- check_frame_args_list(..., frame = frame, name_var_list = c(xvars = xvars, truthVar = truthVar), title = title, funname = "WVPlots::LiftCurvePlot") curve <- lift <- percent_total <- NULL pct_outcome <- pctpop <- sort_criterion <- NULL if(!is.null(truth_target)) { truthcol <- as.numeric(frame[[truthVar]]==truth_target) } else { truthcol <- as.numeric(frame[[truthVar]]) } n <- nrow(frame) results <- data.frame( pctpop = (1:n) / n ) for(xvar in xvars) { predcol <- as.numeric(frame[[xvar]]) d = data.frame(predcol = predcol, truthcol = truthcol) predord <- order(d$predcol, sample.int(n, n, replace = FALSE), decreasing = TRUE) gain <- cumsum(d[predord, 'truthcol']) / sum(d[['truthcol']]) results[[xvar]] <- gain/results$pctpop } results <- cdata::pivot_to_blocks(results, nameForNewKeyColumn = 'curve', nameForNewValueColumn = 'lift', columnsToTakeFrom = setdiff(colnames(results), 'pctpop')) gplot = ggplot2::ggplot( data = results, mapping = ggplot2::aes( x = pctpop, y = lift, color = curve)) + ggplot2::geom_point(alpha = 0.5) + ggplot2::geom_line() + ggplot2::scale_color_brewer(palette = palette) + ggplot2::xlab("fraction items in sort order") + ggplot2::ylab("lift") + ggplot2::geom_hline(yintercept=1, alpha=0.5) + ggplot2::theme(legend.position = "bottom") gplot } LiftCurveListPlot <- LiftCurvePlotList
surplusSectors <- function(x, sectors = c("thermal", "renewable"), timeStep = "annual", synthesis = FALSE, groupByDistrict = FALSE, clusterDesc = NULL, opts = NULL) { .checkAttrs(x, timeStep = "hourly", synthesis = FALSE) x <- .checkColumns(x, list(areas = "MRG. PRICE")) if(is.null(opts)) { opts <- simOptions(x) } if (any(sectors == "renewable")) { sectors <- sectors[!sectors == "renewable"] sectors <- union(sectors, pkgEnv$ren) } fatalProdVars <- intersect(sectors, names(x$areas)) idVars <- .idCols(x$areas) if (length(fatalProdVars) > 0) { x <- .checkColumns(x, list(areas = c(fatalProdVars))) res <- x$areas[, c(idVars, fatalProdVars, "MRG. PRICE"), with = FALSE] for (v in fatalProdVars) res[, c(v) := get(v) * `MRG. PRICE`] res$`MRG. PRICE` <- NULL res <- melt(res, id.vars = idVars, variable.name = "sector", value.name = "surplus") res$cost <- 0 } else { res <- NULL } if("thermal" %in% sectors) { surplusThermal <- surplusClusters(x, "hourly") if (is.null(clusterDesc)) clusterDesc <- readClusterDesc(opts) surplusThermal <- merge(surplusThermal, clusterDesc[, .(area, cluster, sector = group)], by = c("area", "cluster")) surplusThermal <- surplusThermal[,.(surplus = sum(totalSurplus), cost = sum(variableCost + fixedCost + startupCost)), by = c(idVars, "sector")] if (is.null(res)) res <- surplusThermal else res <- rbind(res, surplusThermal) } if (groupByDistrict) res <- .groupByDistrict(res, opts) res <- .addClassAndAttributes(res, FALSE, "hourly", opts, type = "surplusSectors") res <- changeTimeStep(res, timeStep) if (synthesis) res <- synthesize(res) res }
source("ESEUR_config.r") library(gamlss) library(gamlss.tr) library("plyr") plot_layout(2, 1) pal_col=rainbow(2) get_node_uptimes=function(nodes) { t.order=order(as.numeric(strptime(nodes$Prob.Started, format=time.format))) t=nodes[t.order, ] uptime=as.numeric(strptime(t$Prob.Started[-1], format=time.format))- as.numeric(strptime(t$Prob.Fixed[1:(nrow(t)-1)], format=time.format)) t=t[-1, ] t$Uptime=uptime return(t) } get_system_uptimes=function(sys.num) { t=subset(fail.rec, System == sys.num) uptimes=ddply(t, "nodenumz", function(df) get_node_uptimes(df)) return(uptimes) } profile.sys=function(sys.num) { sys.n=get_system_uptimes(sys.num) sys.n=subset(sys.n, Uptime > 0) return(sys.n) } plot.data=function(sys.body, sys.num) { ct=subset(sys.body, Uptime >= 0)$Uptime %/% 3600 ct=ct %/% 10 c=table(ct) plot(as.vector(c)+0.1, col=point_col, xlim=c(1, 1000), ylim=c(1, max(c)), log="xy", xlab="10 hour bins", ylab="Occurrences\n") legend(x="topright", legend=paste("system", sys.num), bty="n", cex=1.2) } fit.data=function(sys.body, distr.str, col.str) { ct=subset(sys.body, Uptime >= 0)$Uptime %/% 3600 ct=ct %/% 10 fd=fitdist(ct, distr=distr.str, method="mle") if (distr.str == "nbinom") { size.ct=fd$estimate[1] mu.ct=fd$estimate[2] distr.vals=dnbinom(1:1000, size=size.ct, mu=mu.ct)*length(ct) } else { rate.ct=fd$estimate[1] distr.vals=dexp(1:1000, rate=rate.ct)*length(ct) } lines(distr.vals, col=col.str) } fit_NBII=function(sys_body, sys_num) { ct=subset(sys_body, Uptime >= 0)$Uptime %/% 3600 ct=1+(ct %/% 10) c_nodes=as.vector(table(ct)) g_NBIItr=gamlss(ct ~ 1, family=NBIItr) NBII_mu=exp(coef(g_NBIItr, "mu")) NBII_sigma=exp(coef(g_NBIItr, "sigma")) plot(c_nodes, log="xy", type="p", col=pal_col[2], xlab="10 hour bins", ylab="Occurrences\n") lines(dNBIItr(1:1e3, mu=NBII_mu, sigma=NBII_sigma)*length(ct), col=pal_col[1]) legend(x="topright", legend=paste("system", sys_num), bty="n", cex=1.2) return(g_NBIItr) } time.format="%m/%d/%Y %H:%M" day.start=as.integer(as.Date("04/06/1996 00:01", format=time.format)) fail.rec=read.csv(paste0(ESEUR_dir, "reliability/LA-UR-05-7318-failure-data-1996-2005.csv.xz"), as.is=TRUE) plot_and_fit=function(sys.body, sys.num) { plot.data(sys.body, sys.num) fit.data(sys.body, "nbinom", "red") } sys.2=profile.sys(2) sys.18=profile.sys(18) gen.trun(par=0, family=NBII) dummy=fit_NBII(sys.2, 2) dummy=fit_NBII(sys.18, 18)
mod_medidas_repetidas_Ui <- function(id){ ns <- NS(id) tagList( uiOutput(ns("medidas_repetidas_ui_sided")) %>% shinycssloaders::withSpinner(type = 5) ) } mod_medidas_repetidas_server <- function(id, tipo){ shiny::moduleServer( id, function(input, output, session){ ns <- session$ns text_input_to_vector <- function(input_text){ input_text %>% strsplit(",") %>% unlist() %>% strsplit("\\n") %>% unlist() %>% as.numeric() %>% na.omit() } check_text_input_to_vector <- function(id){ paste0("observeEvent(input$", id, ", { vetor_teste <- text_input_to_vector(input$", id, ") if(length(vetor_teste) == 0){ shinyFeedback::showFeedbackWarning( inputId = '", id, "', text = 'Entrada inválida.', color = 'red') } else { shinyFeedback::hideFeedback('", id, "') } }) " ) } warning_prop <- function(id, entre0e1 = FALSE){ if(!entre0e1){ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id, '") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser fornecido um valor para o %.", color = "red" ) } else if (input$', id,' >= 100) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser menor do que 100%.", color = "red" ) } else if (input$', id,' <= 0) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser maior do que 0%.", color = "red" ) } }) ' ) } else{ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id, '") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser fornecido um valor entre 0 e 1.", color = "red" ) } else if (input$', id,' > 1) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser menor do que 1.", color = "red" ) } else if (input$', id,' < 0) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser maior do que 0.", color = "red" ) } }) ' ) } } warning_numero_positivo <- function(id){ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id, '") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser fornecido um valor.", color = "red" ) } else if (input$', id,' <= 0) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser maior do que 0.", color = "red" ) } }) ' ) } warning_numero <- function(id){ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id, '") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser fornecido um valor.", color = "red" ) } }) ' ) } warning_inteiro <- function(id){ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id,'") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id,'", text = "Deve ser um número.", color = "red" ) } else if(input$', id,'%%1 != 0 | input$', id,' < 1){ shinyFeedback::showFeedbackWarning( inputId = "', id,'", text = "Deve ser um número inteiro positivo.", color = "red" ) } })' ) } warning_perdas <- function(id){ paste0( 'observeEvent(input$', id,', { shinyFeedback::hideFeedback("', id, '") if(is.na(input$', id,')){ shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Tem certeza que não considerarás perdas?" ) } else if (input$', id,' >= 100) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Deve ser menor do que 100%." ) } else if (input$', id,' <= 0) { shinyFeedback::showFeedbackWarning( inputId = "', id, '", text = "Tem certeza que não considerarás perdas?" ) } }) ' ) } n_perdas <- function(n, perdas){ ceiling(n/(1 - perdas/100)) } observeEvent(input$show_th_rep, { showModal( modalDialog( title = "Ajustes", fluidPage( HTML("<b>Preencha os campos abaixo de acordo com seu estudo para que sirvam de guia no preenchimento dos demais campos</b>."), br(), br(), textInput(inputId = ns("rep_nome_desfecho"), label = "Descreva o nome do desfecho", value = ifelse(input$show_th_rep == 0, "Y", rep_nome_desfecho())), HTML(paste0("<i>", str_remove_all(.txt_desfecho, "<br><br>"), "</i>")), br(), br(), textInput(inputId = ns("rep_grupoTratamento"), label = "Descreva um nome para o grupo Tratamento", value = ifelse(input$show_th_rep == 0, "Tratamento", rep_grupoTratamento())), HTML("<i>Em alguns estudos o grupo Tratamento também pode ser chamadado de grupo Intervenção ou grupo Exposto.</i><br><br>"), textInput(inputId = ns("rep_grupoControle"), label = "Descreva um nome para o grupo Controle", value = ifelse(input$show_th_rep == 0, "Controle", rep_grupoControle())), HTML("<i>Em alguns estudos o grupo Controle também pode ser chamadado de grupo Placebo/ Sham ou grupo Não exposto.</i>"), ), easyClose = TRUE, footer = NULL ) ) }) rep_grupoControle <- reactive({ ifelse(is.null(input$rep_grupoControle), "Controle", input$rep_grupoControle) }) rep_grupoTratamento <- reactive({ ifelse(is.null(input$rep_grupoTratamento), "Tratamento", input$rep_grupoTratamento) }) rep_nome_desfecho <- reactive({ ifelse(is.null(input$rep_nome_desfecho), "Y", input$rep_nome_desfecho) }) output$rep_formula1 <- renderUI({ withMathJax( paste0("$$H_0: \\mu_{", rep_grupoTratamento(), "} = \\mu_{", rep_grupoControle(), "} $$")) }) output$rep_formula2 <- renderUI({ withMathJax( paste0("$$H_1: \\mu_{", rep_grupoTratamento(), "} \\neq \\mu_{", rep_grupoControle(), "} $$")) }) observeEvent(input$rep_n_tempos, { shinyFeedback::hideFeedback("rep_n_tempos") if(is.na(input$rep_n_tempos)){ shinyFeedback::showFeedbackWarning( inputId = ns("rep_n_tempos"), text = "Deve ser fornecido um valor.", color = "red" ) } else if (input$rep_n_tempos < 2) { shinyFeedback::showFeedbackWarning( inputId = ns("rep_n_tempos"), text = "Devem haver pelo menos 2 momentos.", color = "red" ) } else if(input$rep_n_tempos%%1 != 0){ shinyFeedback::showFeedbackWarning( inputId = ns("rep_n_tempos"), text = "Deve ser um número inteiro positivo.", color = "red" ) } }) eval(parse(text = warning_numero("rep_dif_medias"))) eval(parse(text = warning_numero_positivo("rep_sigma1"))) eval(parse(text = warning_numero_positivo("rep_sigma2"))) eval(parse(text = warning_numero_positivo("rep_ratio"))) eval(parse(text = warning_prop("rep_ar1_rho1", entre0e1 = TRUE))) eval(parse(text = warning_prop("rep_ar1_rho2", entre0e1 = TRUE))) eval(parse(text = warning_prop("rep_cs_rho1", entre0e1 = TRUE))) eval(parse(text = warning_prop("rep_cs_rho2", entre0e1 = TRUE))) eval(parse(text = warning_prop("rep_power"))) eval(parse(text = warning_prop("rep_sig"))) eval(parse(text = warning_perdas("rep_perdas_recusa"))) correlation_R1 <- reactiveValues(mcor = data.frame(a = 1)) observeEvent(input$rep_n_tempos, { req(!is.na(input$rep_n_tempos)) req(input$rep_n_tempos%%1 == 0 & input$rep_n_tempos > 1) tempos <- ifelse(is.null(input$rep_n_tempos), 4, input$rep_n_tempos) exponent <- abs(matrix(1:tempos - 1, nrow = tempos, ncol = tempos, byrow = TRUE) - (1:tempos - 1)) M_correlation <- as.data.frame(0.9^exponent) colnames(M_correlation) <- paste0("Momento ", 1:tempos) rownames(M_correlation) <- paste0("Momento ", 1:tempos) correlation_R1$mcor <- M_correlation }) output$rep_cor_grupo1 <- DT::renderDT({ temp <- input$rep_cor_grupo1_cell_edit DT::datatable(correlation_R1$mcor, editable = "cell", extensions = c('FixedColumns'), rownames = TRUE, filter = "none", options = list(autoWidth = FALSE, searching = FALSE, ordering = FALSE, pageLength = 15, dom = 't', columnDefs = list(list(className = 'dt-center', targets = "_all")))) }) observeEvent(input$rep_cor_grupo1_cell_edit, { cell <- input$rep_cor_grupo1_cell_edit newdf <- correlation_R1$mcor new_value <- cell$value %>% as.character() %>% str_replace(",", ".") %>% gsub("[^0-9.-]", "", .) %>% as.numeric() newdf[cell$row, cell$col] <- new_value newdf[cell$col, cell$row] <- new_value correlation_R1$mcor <- newdf }) rep_problemas_matriz_correlacao1 <- reactive({ problemas <- "" if(any(is.na(correlation_R1$mcor))){ problemas <- paste0('<font color = "red"><b>Todas as células devem ser preenchidas.</b></font><br/>') } else if(any(abs(correlation_R1$mcor) > 1)){ problemas <- paste0('<font color = "red"><b>Todas as correlações devem estar entre -1 e 1.</b></font><br/>') } else if(any(abs(correlation_R1$mcor) > 1)){ problemas <- paste0('<font color = "red"><b>Os valores da diagonal devem ser igual a 1.</b></font><br/>') } problemas }) correlation_R2 <- reactiveValues(mcor = data.frame(a = 1)) observeEvent(input$rep_n_tempos, { req(!is.na(input$rep_n_tempos)) req(input$rep_n_tempos%%1 == 0 & input$rep_n_tempos > 1) tempos <- ifelse(is.null(input$rep_n_tempos), 4, input$rep_n_tempos) exponent <- abs(matrix(1:tempos - 1, nrow = tempos, ncol = tempos, byrow = TRUE) - (1:tempos - 1)) M_correlation <- as.data.frame(0.9^exponent) colnames(M_correlation) <- paste0("Momento ", 1:tempos) rownames(M_correlation) <- paste0("Momento ", 1:tempos) correlation_R2$mcor <- M_correlation }) output$rep_cor_grupo2 <- DT::renderDT({ temp <- input$rep_cor_grupo2_cell_edit DT::datatable(correlation_R2$mcor, editable = "cell", extensions = c('FixedColumns'), rownames = TRUE, filter = "none", options = list(autoWidth = FALSE, searching = FALSE, ordering = FALSE, pageLength = 15, dom = 't', columnDefs = list(list(className = 'dt-center', targets = "_all")))) }) observeEvent(input$rep_cor_grupo2_cell_edit, { cell <- input$rep_cor_grupo2_cell_edit newdf <- correlation_R2$mcor new_value <- cell$value %>% as.character() %>% str_replace(",", ".") %>% gsub("[^0-9.-]", "", .) %>% as.numeric() newdf[cell$row, cell$col] <- new_value newdf[cell$col, cell$row] <- new_value correlation_R2$mcor <- newdf }) rep_problemas_matriz_correlacao2 <- reactive({ problemas <- "" if(any(is.na(correlation_R2$mcor))){ problemas <- paste0('<font color = "red"><b>Todas as células devem ser preenchidas.</b></font><br/>') } else if(any(abs(correlation_R2$mcor) > 1)){ problemas <- paste0('<font color = "red"><b>Todas as correlações devem estar entre -1 e 1.</b></font><br/>') } else if(any(abs(correlation_R2$mcor) > 1)){ problemas <- paste0('<font color = "red"><b>Os valores da diagonal devem ser igual a 1.</b></font><br/>') } problemas }) output$rep_print_matriz_cor <- renderUI({ req(input$rep_tipo_matriz_cor == 'Não estruturada') fluidPage(fluidRow(wellPanel( if(rep_problemas_matriz_correlacao1() != ""){ HTML(paste0('<font size = "+0.1"><font color = "red">', "<b>Matriz de correlação do grupo ", rep_grupoTratamento(), ":</b>", '</font></font><br/>')) } else{ HTML(paste0("<b>Matriz de correlação do grupo ", rep_grupoTratamento()), ":</b>") }, DT::dataTableOutput(ns("rep_cor_grupo1")), if(rep_problemas_matriz_correlacao1() != ""){ HTML(rep_problemas_matriz_correlacao1()) }, br(), br(), if(rep_problemas_matriz_correlacao2() != ""){ HTML(paste0('<font size = "+0.1"><font color = "red">', "<b>Matriz de correlação do grupo ", rep_grupoTratamento(), ":</b>", '</font></font><br/>')) } else{ HTML(paste0("<b>Matriz de correlação do grupo ", rep_grupoControle()), ":</b>") }, DT::dataTableOutput(ns("rep_cor_grupo2")), if(rep_problemas_matriz_correlacao2() != ""){ HTML(rep_problemas_matriz_correlacao2()) }, br(), br() ))) }) output$rep_retencao1 <- renderUI({ len <- as.integer(input$rep_n_tempos) lapply(2:len, function(i) { div( numericInput( inputId = ns(paste0("retencao1_", i)), label = paste0("Momento ", i), value = 100 + 1 - i ) ) }) }) output$rep_retencao2 <- renderUI({ len <- as.integer(input$rep_n_tempos) lapply(2:len, function(i) { div( numericInput( inputId = ns(paste0("retencao2_", i)), label = paste0("Momento ", i), value = 100 + 1 - i ) ) }) }) observe({ req(!is.null(input$rep_n_tempos)) req(!is.na(input$rep_n_tempos)) len <- as.integer(input$rep_n_tempos) req(!is.null(input[[ns(paste0("retencao1_", len))]])) lapply(2:len, function(i) { shinyFeedback::hideFeedback(paste0("retencao1_", i)) if(is.na(input[[paste0("retencao1_", i)]])){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao1_", i), text = "Deve ser fornecido um valor.", color = "red" ) } else if(input[[paste0("retencao1_", i)]] > 100){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao1_", i), text = "Deve ser fornecido um valor menor do que 100%", color = "red" ) } else if(input[[paste0("retencao1_", i)]] < 0){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao1_", i), text = "Deve ser fornecido um valor maior do que 0%", color = "red" ) } }) }) observe({ req(!is.null(input$rep_n_tempos)) req(!is.na(input$rep_n_tempos)) len <- as.integer(input$rep_n_tempos) req(!is.null(input[[paste0("retencao2_", len)]])) lapply(2:len, function(i) { shinyFeedback::hideFeedback(paste0("retencao2_", i)) if(is.na(input[[paste0("retencao2_", i)]])){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao2_", i), text = "Deve ser fornecido um valor.", color = "red" ) } else if(input[[paste0("retencao2_", i)]] > 100){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao2_", i), text = "Deve ser fornecido um valor menor do que 100%", color = "red" ) } else if(input[[paste0("retencao2_", i)]] <= 0){ shinyFeedback::showFeedbackWarning( inputId = paste0("retencao2_", i), text = "Deve ser fornecido um valor maior do que 0%", color = "red" ) } }) }) output$chamada_matriz_correlacao <- renderUI({ selectInput( ns('rep_tipo_matriz_cor'), "Selecione o tipo de matriz de correlação", choices = c("AR(1)", "Componente permutável", "Não estruturada"), selected = 'AR(1)' ) %>% .help_buttom( body = paste0( "Indique a correlação esperada entre as medidas nos diferentes momentos. As opções disponíveis são: <br><br>", "<ul>", "<li><b>Componente permutável:</b> a correlação entre as medidas é sempre a mesma em todos os momentos);</li><br>", "<li><b>AR(1) - Auto-Regressiva de 1\u00AA Ordem:</b> a correlação entre medidas de momentos adjacentes é mais forte e vai enfraquecendo de acordo com o aumento da distância entre as mesmas;</li><br>", "<li><b>Não estruturada:</b> as correlações entre as medidas de diferentes momentos podem assumir qualquer valor.</li>", "</ul>", .txt_definido_pesquisador_OU_literatura), title = "Matriz de correlação entre as medidas") }) output$tipo_matriz_correlcao <- renderUI({ req(!is.null(input$rep_tipo_matriz_cor)) if (input$rep_tipo_matriz_cor == 'Não estruturada') { HTML("<i><b>ATENÇÃO!</b> Edite as matrizes de correlação no painel principal ao lado. As matrizes são editáveis, basta clicar duas vezes sobre a célula --> </i><br><br>") } else if (input$rep_tipo_matriz_cor == 'AR(1)') { fluidPage(fluidRow( HTML(paste0("<b><font size = '2.95'>Parâmetro autorregressivo no grupo</font></b><br>")), div(style = "display: inline-block;vertical-align:bottom;vertical-align:bottom; width: 49%;", numericInput(ns("rep_ar1_rho1"), rep_grupoTratamento(), value = 0.4, min = 0, max = 1, step = .1 ) ), div(style = "display: inline-block;vertical-align:top; width: 49%;", numericInput( ns("rep_ar1_rho2"), rep_grupoControle(), value = 0.2, min = 0, max = 1, step = .1 ) ) )) } else { fluidPage(fluidRow( HTML(paste0("<b><font size = '2.95'>Valor da correlação entre as medidas no grupo</font></b><br>")), div(style = "display: inline-block;vertical-align:bottom;vertical-align:bottom; width: 49%;", numericInput( ns("rep_cs_rho1"), rep_grupoTratamento(), value = 0.7, min = -1, max = 1, step = .1 ) ), div(style = "display: inline-block;vertical-align:top; width: 49%;", numericInput(ns( "rep_cs_rho2"), rep_grupoControle(), value = 0.7, min = -1, max = 1, step = .1 ) ) )) } }) output$medidas_repetidas_ui_sided <- renderUI({ fluidPage(fluidRow( sidebarLayout( sidebarPanel( wellPanel( HTML("<b><font size = '2.8'>Hipóteses a serem testadas*</font></b>"), uiOutput(ns("rep_formula1")), uiOutput(ns("rep_formula2")), HTML("<i><font size = '2.8'>*Resposta média no último tempo</font></i>"), ), actionLink(ns("show_th_rep"), "Mudar nomes"), br(), br(), numericInput( ns("rep_n_tempos"), "Número de momentos a ser avaliado", value = 4, min = 2, max = Inf, step = 1 ), numericInput(ns("rep_dif_medias"), paste0("Diferença do ", rep_nome_desfecho(), " a ser detectada no último tempo de avaliação: (Média do ", rep_grupoTratamento(), ") - (Média do grupo ", rep_grupoControle(), ")"), value = 0.5, min = -Inf, max = Inf, step = .5 ) %>% .help_buttom(body = paste0("É a menor diferença considerada clinicamente relevante (que tenha algum valor clínico) no último tempo de internação.", .txt_definido_pesquisador)), if (tipo == "poder") { fluidPage(fluidRow( HTML(paste0("<b><font size = '2.95'>Tamanho amostral do grupo no último momento</font></b><br>")), div(style = "display: inline-block;vertical-align:bottom;vertical-align:bottom; width: 49%;", numericInput( ns("n1"), rep_grupoTratamento(), value = 50, min = 0, max = Inf, step = 1 ) ), div(style = "display: inline-block;vertical-align:top; width: 49%;", numericInput( ns("n2"), rep_grupoControle(), value = 60, min = 0, max = Inf, step = 1 ) %>% .help_buttom(body = "Tamanho amostral", title = "Tamanho amostral") ) )) }, HTML(paste0("<b><font size = '2.95'>Desvio padrão esperado de ", rep_nome_desfecho(), " no grupo</font></b><br>")), div(style = "display: inline-block;vertical-align:bottom;vertical-align:bottom; width: 49%;", numericInput( ns("rep_sigma1"), rep_grupoTratamento(), value = 1, min = 0, max = Inf, step = 1 ) ), div(style = "display: inline-block;vertical-align:top; width: 49%;", numericInput( ns("rep_sigma2"), rep_grupoControle(), value = 1, min = 0, max = Inf, step = 1 ) %>% .help_buttom(body = .txt_dp, title = "Desvio padrão esperado") ), wellPanel( uiOutput(ns("chamada_matriz_correlacao")), uiOutput(ns("tipo_matriz_correlcao")) ), wellPanel( HTML(paste0("<b>Retenção esperada (%) no grupo</b><br><br>")) %>% .help_buttom(body = paste0("Percentual de indivíduos que é esperado ter naquele momento. ", .txt_definido_pesquisador_OU_literatura), title = "Retenção esperada"), fluidPage(fluidRow( div(style = "display: inline-block;vertical-align:top; width: 49%;", wellPanel( HTML(paste0("<b>", rep_grupoTratamento(), ":</b>")), br(), br(), uiOutput(ns("rep_retencao1")) )), div(style = "display: inline-block;vertical-align:top; width: 49%;", wellPanel( HTML(paste0("<b>", rep_grupoControle(), ":</b>")), br(), br(), uiOutput(ns("rep_retencao2")) )) )) ), if (tipo == "tamanho_amostral") { fluidPage(fluidRow( numericInput( ns("rep_ratio"), paste0("Balanceamento (", rep_grupoTratamento(), ":", rep_grupoControle(), ")"), value = 1, min = 0, max = Inf, step = 0.5 ) %>% .help_buttom(body = .txt_balanceamento, title = "Balanceamento"), numericInput( ns("rep_power"), "Poder (%)", value = 80, min = 0, max = 100, step = 1 ) %>% .help_buttom(body = .txt_power, title = "Poder (%)") )) }, numericInput( ns("rep_sig"), "Nível de significância (%)", value = 5, min = 0, max = 100, step = 1 ) %>% .help_buttom(body = .txt_significancia, title = "Nível de significância (%)"), numericInput( ns("rep_perdas_recusa"), "Perdas/ Recusa (%)", value = 10, min = 0, max = 100, step = 1 ) %>% .help_buttom(body = .txt_perdas_recusas, title = "Perdas/ Recusas (%)") ), mainPanel( uiOutput(ns("rep_print_matriz_cor")) %>% shinycssloaders::withSpinner(type = 5), shinycssloaders::withSpinner(htmlOutput(ns("rep_outout_text")), type = 5), shinycssloaders::withSpinner(uiOutput(ns("rep_corr_matrix_out")), type = 5), shinycssloaders::withSpinner(htmlOutput(ns("rep_out_codigo")), type = 5), uiOutput(ns("cenarios_medidas_rep_thUi")) ) ) )) }) correlation_Ra <- reactive({ req(!is.null(input$rep_tipo_matriz_cor)) if(input$rep_tipo_matriz_cor == 'Não estruturada'){ correlation_Ra_v <- unlist(c(correlation_R1$mcor)) } else if(input$rep_tipo_matriz_cor == 'AR(1)'){ tempos <- input$rep_n_tempos exponent <- abs(matrix(1:tempos - 1, nrow = tempos, ncol = tempos, byrow = TRUE) - (1:tempos - 1)) correlation_Ra_v <- c(input$rep_ar1_rho1^exponent) } else if(input$rep_tipo_matriz_cor == 'Componente permutável'){ tempos <- input$rep_n_tempos exponent <- matrix(1, nrow = tempos, ncol = tempos, byrow = TRUE) diag(exponent) <- 0 correlation_Ra_v <- c(input$rep_cs_rho1^exponent) } correlation_Ra_v }) correlation_Rb <- reactive({ if(input$rep_tipo_matriz_cor == 'Não estruturada'){ correlation_Rb_v <- unlist(c(correlation_R2$mcor)) } else if (input$rep_tipo_matriz_cor == 'AR(1)'){ tempos <- input$rep_n_tempos exponent <- abs(matrix(1:tempos - 1, nrow = tempos, ncol = tempos, byrow = TRUE) - (1:tempos - 1)) correlation_Rb_v <- c(input$rep_ar1_rho2^exponent) } else if(input$rep_tipo_matriz_cor == 'Componente permutável'){ tempos <- input$rep_n_tempos exponent <- matrix(1, nrow = tempos, ncol = tempos, byrow = TRUE) diag(exponent) <- 0 correlation_Rb_v <- c(input$rep_cs_rho2^exponent) } correlation_Rb_v }) rep_retencao_A <- reactive({ req(!is.null(input$retencao1_2)) rete <- lapply(2:input$rep_n_tempos, function(i) { input[[paste0("retencao1_", i)]] }) %>% unlist() c(100, rete) }) rep_retencao_B <- reactive({ req(!is.null(input$retencao2_2)) rete <- lapply(2:input$rep_n_tempos, function(i) { input[[paste0("retencao2_", i)]] }) %>% unlist() c(100, rete) }) rep_n_calc <- reactive({ req(!is.null(input$rep_n_tempos)) req(rep_problemas_matriz_correlacao1() == "") if (tipo == "tamanho_amostral"){ n <- longpower::power.mmrm( Ra = matrix(data = correlation_Ra(), nrow = input$rep_n_tempos, byrow = TRUE), ra = rep_retencao_A()/100, sigmaa = input$rep_sigma1, Rb = matrix(data = correlation_Rb(), nrow = input$rep_n_tempos, byrow = TRUE), rb = rep_retencao_B()/100, sigmab = input$rep_sigma2, delta = input$rep_dif_medias, lambda = input$rep_ratio, sig.level = input$rep_sig/100, power = input$rep_power/100 ) } else { n <- longpower::power.mmrm( N = input$n1 + input$n2, Ra = matrix(data = correlation_Ra(), nrow = input$rep_n_tempos, byrow = TRUE), ra = rep_retencao_A()/100, sigmaa = input$rep_sigma1, Rb = matrix(data = correlation_Rb(), nrow = input$rep_n_tempos, byrow = TRUE), rb = rep_retencao_B()/100, sigmab = input$rep_sigma2, delta = input$rep_dif_medias, lambda = input$n1/input$n2, sig.level = input$rep_sig/100 ) } validate(need(!is.na(n$n1), 'Não foi possível calcular sua solicitação. Verifique as entradas no painel lateral. Se o erro persistir, por favor, envie um e-mail para [email protected].')) n }) rep_erro_inputs <- reactive({ req(!is.null(input$rep_n_tempos)) erros <- input$rep_n_tempos != sqrt(length(correlation_Ra())) | input$rep_n_tempos != sqrt(length(correlation_Rb())) | !all(diff(rep_retencao_A()) <= 0) | !all(rep_retencao_A() > 0) | !all(rep_retencao_A() <= 100) | !all(diff(rep_retencao_B()) <= 0) | !all(rep_retencao_B() > 0) | !all(rep_retencao_B() <= 100) | input$rep_sigma1 <= 0 | input$rep_sigma2 <= 0 | input$rep_sig <= 0 | input$rep_sig >= 100 | input$rep_ar1_rho2 <= 0 | input$rep_ar1_rho2 >= 1 | rep_problemas_matriz_correlacao1() != "" | input$rep_n_tempos%%1 != 0 | input$rep_n_tempos < 1 if (tipo == "tamanho_amostral") { erros | input$rep_ratio <= 0 | input$rep_power <= 0 | input$rep_power >= 100 } else { erros | input$n1 <= 0 | input$n2 <= 0 } }) eval(parse(text = warning_inteiro("rep_n_tempos"))) output$rep_outout_text <- renderText({ validate(need(!rep_erro_inputs(), "Não foi possível calcular sua solicitação. Verifique as entradas no painel lateral. Se o erro persistir, por favor, envie um e-mail para [email protected].")) if (tipo == "tamanho_amostral"){ n <- rep_n_calc() n1 <- ceiling(n$n1) n2 <- ceiling(n$n2) n <- n1 + n2 nperdas1 <- n_perdas(n1, input$rep_perdas_recusa) nperdas2 <- n_perdas(n2, input$rep_perdas_recusa) } else { poder <- rep_n_calc() poder <- round(poder$power*100, 1) } retencaoA <- paste0(rep_retencao_A()[-1], "%", collapse = ", ") %>% stringi::stri_replace_last_fixed(",", " e ") %>% stringr::str_trim() %>% stringr::str_squish() retencaoB <- paste0(rep_retencao_B()[-1], "%", collapse = ", ") %>% stringi::stri_replace_last_fixed(",", " e ") %>% stringr::str_trim() %>% stringr::str_squish() momentos <- paste0(1:input$rep_n_tempos, collapse = ", ") %>% stringi::stri_replace_last_fixed(",", " e ") %>% stringr::str_trim() %>% stringr::str_squish() momentos2 <- paste0(2:input$rep_n_tempos, collapse = ", ") %>% stringi::stri_replace_last_fixed(",", " e ") %>% stringr::str_trim() %>% stringr::str_squish() paste0( if (tipo == "tamanho_amostral") { paste0( "<b><font size = '5'>Tamanho amostral calculado: ", n, " (<i>", n1, " no grupo ", rep_grupoTratamento(), " e ", n2, " no grupo ", rep_grupoControle(),"</i>)" ) } else { paste0( "<b><font size = '5'>Poder calculado: ", poder, "%" ) }, "</font></b></br></br><i>Sugestão de texto:</i></br></br>", "Tendo em vista um estudo longitudinal que avaliará o (a) <b>", rep_nome_desfecho(), "</b> entre os grupos ", rep_grupoTratamento(), " e ", rep_grupoControle(), " em <b>", input$rep_n_tempos, "</b> momentos, ", if (tipo == "tamanho_amostral") { "foi calculado o tamanho de amostra " } else { "foi calculado o poder " }, "para detectar diferenças na resposta média de <b>", rep_nome_desfecho(), "</b> entre esses grupos no tempo final (momento ", input$rep_n_tempos, "), tendo uma diferença de <b>", input$rep_dif_medias, " u.m.</b> como relevante para o estudo. ", "Para isso foi utilizado a ", .txt_citacao_tap, ". ", "Considerando os seguintes valores esperados para o grupo ", rep_grupoControle(), ":", "<ul>", if (tipo == "poder") { paste0( "<li> tamanho amostral de <b>", input$n2, "</b> no momento ", input$rep_n_tempos, ",</li>" ) }, "<li> desvio padrão de <b>", input$rep_sigma2, " u.m.</b>,</li>", "<li> retenção de ", retencaoB, " nos momentos ", momentos2,", respectivamente,</li>", if(input$rep_tipo_matriz_cor == 'Não estruturada'){ paste0("<li> matriz de correlação não estruturada (definida abaixo),</li>") } else if(input$rep_tipo_matriz_cor == 'AR(1)'){ paste0("<li> matriz de correlação autorregressiva de parâmetro ", input$rep_ar1_rho2, " (definida abaixo),</li>") } else if(input$rep_tipo_matriz_cor == 'Componente permutável'){ paste0("<li> matriz de correlação permutável com correlação ", input$rep_cs_rho2, " (definida abaixo),</li>") }, "</ul>", "e para o grupo ", rep_grupoTratamento(), " (dados de Fulano (1900)):", "<ul>", if (tipo == "poder") { paste0( "<li> tamanho amostral de <b>", input$n1, "</b> no momento ", input$rep_n_tempos, ",</li>" ) }, "<li> desvio padrão de <b>", input$rep_sigma1, " u.m.</b>,</li>", "<li> retenção de ", retencaoA, " nos momentos ", momentos2,", respectivamente,</li>", if(input$rep_tipo_matriz_cor == 'Não estruturada'){ "<li> matriz de correlação não estruturada (definida abaixo),</li>" } else if(input$rep_tipo_matriz_cor == 'AR(1)'){ paste0("<li> matriz de correlação autorregressiva de parâmetro ", input$rep_ar1_rho1, " (definida abaixo),</li>") } else if(input$rep_tipo_matriz_cor == 'Componente permutável'){ paste0("<li> matriz de correlação permutável com correlação ", input$rep_cs_rho1, " (definida abaixo),</li>") }, "</ul>", if (tipo == "tamanho_amostral") { paste0("poder de <b>", input$rep_power, "%</b> ") } , " e nível de significância de <b>", input$rep_sig, "%</b>, ", if (tipo == "tamanho_amostral") { ifelse(input$rep_ratio == 1, paste0( "chegou-se ao tamanho de amostra total de <b>", n , "</b> sujeitos, sendo <b>", n1, "</b> em cada grupo.", " Acrescentando <b>", input$rep_perdas_recusa, "%</b> para possíveis perdas e recusas o tamanho de amostra ", "deverá ser <b>", nperdas1 + nperdas2, "</b> (", nperdas1, " em cada grupo)." ), paste0( "chegou-se ao tamanho de amostra total de <b>", n , "</b> sujeitos, sendo <b>", n1, "</b> no ", rep_grupoTratamento(), " e <b>", n2, "</b> no ", rep_grupoControle(), ".", " Acrescentando <b>", input$rep_perdas_recusa, "%</b> para possíveis perdas e recusas o tamanho de amostra ", "deverá ser <b>", nperdas1 + nperdas2, "</b> (", nperdas1, " no ", rep_grupoTratamento(), " e ", nperdas2, " no ", rep_grupoControle(), ")." ) ) } else { paste0("chegou-se ao poder de <b>", poder , "%</b>.") }, "<br>", "<br>" ) }) output$rep_corr_matrix_out <- renderUI({ req(!rep_erro_inputs()) fluidPage( HTML(paste0("Matriz de correlação do grupo ", rep_grupoTratamento(), ":<br>")), renderTable({ df_ <- matrix(data = correlation_Ra(), nrow = input$rep_n_tempos, byrow = TRUE) %>% as.data.frame() rownames(df_) <- paste0("Momento ", 1:input$rep_n_tempos) colnames(df_) <- paste0("Momento ", 1:input$rep_n_tempos) df_ }, rownames = TRUE, colnames = TRUE ), HTML(paste0("Matriz de correlação do grupo ", rep_grupoControle(), ":<br>")), renderTable({ df2_ <- matrix(data = correlation_Rb(), nrow = input$rep_n_tempos, byrow = TRUE) %>% as.data.frame() rownames(df2_) <- paste0("Momento ", 1:input$rep_n_tempos) colnames(df2_) <- paste0("Momento ", 1:input$rep_n_tempos) df2_ }, rownames = TRUE, colnames = TRUE ) ) }) output$rep_out_codigo <- renderText({ req(!rep_erro_inputs()) if (tipo == "tamanho_amostral") { code <- paste0( "longpower::power.mmrm(", "Ra = Ra, ", "ra = c(", paste0(rep_retencao_A(), collapse = ", "), ")/100, ", "sigmaa = ", input$rep_sigma1, ", ", "Rb = Rb, ", "rb = c(", paste0(rep_retencao_B(), collapse = ", "), ")/100, ", "sigmab = ", input$rep_sigma2, ", ", "delta = ", input$rep_dif_medias, ", ", "lambda = ", input$rep_ratio, ", ", "sig.level = ", input$rep_sig, "/100, ", "power = ", input$rep_power, "/100)" ) } else { code <- paste0( "longpower::power.mmrm(", "N = ", input$n1, " + ", input$n2, ", ", "Ra = Ra, ", "ra = c(", paste0(rep_retencao_A(), collapse = ", "), ")/100, ", "sigmaa = ", input$rep_sigma1, ", ", "Rb = Rb, ", "rb = c(", paste0(rep_retencao_B(), collapse = ", "), ")/100, ", "sigmab = ", input$rep_sigma2, ", ", "delta = ", input$rep_dif_medias, ", ", "lambda = ", input$n1, "/ ", input$n2, ", ", "sig.level = ", input$rep_sig, "/100)" ) } paste0( .txt_referencia_tap, "</br></br>", "<i>Comando R utilizado:</i><br>", "<p style=\"font-family:'Courier New';font-size:100% \">", code(paste0("Ra <- matrix(data = c(", paste0(correlation_Ra(), collapse = ", "), "), nrow = ", input$rep_n_tempos, ", byrow = TRUE)")), "<br>", code(paste0("Rb <- matrix(data = c(", paste0(correlation_Rb(), collapse = ", "), "), nrow = ", input$rep_n_tempos, ", byrow = TRUE)")), "<br>", code(code), "</p>" ) }) output$cenarios_medidas_rep_thUi <- renderUI({ req(tipo == "tamanho_amostral") req(!rep_erro_inputs()) if(input$rep_dif_medias > 0){ dif_start <- input$rep_dif_medias dif_end <- input$rep_dif_medias + 2 dif_by <- 0.4 } else{ dif_start <- input$rep_dif_medias - 2 dif_end <- input$rep_dif_medias dif_by <- 0.4 } fluidPage(fluidRow( br(), HTML('<hr style="color: black;">'), br(),br(), titlePanel("Construção de cenários"), br(), wellPanel(paste0( "Utilize os argumentos abaixo para construir diferentes cenários. ", "Você pode definir um intervalo de diferença a ser detectada no último tempo de avaliação e especificar diferentes valores para o desvio padrão do grupo ", rep_grupoTratamento(), ". ", "Demais informações serão recuperadas do painel lateral.")), HTML("<b>Defina a sequência de valores para a diferença a ser detectada no último tempo de avaliação:</b>"), br(), div(style = "display: inline-block;vertical-align:bottom;vertical-align:bottom; width: 80px;", numericInput(ns("rep_th_from"), "Mínimo", value = dif_start, step = 1) ), div(style = "display: inline-block;vertical-align:top; width: 80px;", numericInput(ns("rep_th_to"), "Máximo", value = dif_end, step = 1) ), div(style = "display: inline-block;vertical-align:top; width: 80px;", numericInput(ns("rep_th_by"), "Intervalo", value = dif_by, min = 0, step = 0.5) %>% .help_buttom(body = "Defina a sequência de margem de erro absoluta. Essa sequência será utilizada para compor o eixo x do gráfico. A sequência irá do valor <b>Mínimo</b> até o valor <b>Máximo</b> em intervalos definidos no <b>Intervalo</b>.", title = "Sequência da margem de erro absoluta") ), fluidRow( column(6, textInput(inputId = ns("rep_sd_plot"), label = paste0("Digite valores de desvio padrão (DP) do grupo ", rep_grupoTratamento(), " para fazer o gráfico:"), value = paste0(c(input$rep_sigma1, input$rep_sigma1 + 0.2, input$rep_sigma1 + 0.5), collapse = ", "), width = "100%") %>% .help_buttom(body = "Defina os valores de desvio padrão. Esses valores serão utilizados para criar diferentes linhas no gráfico. Separe os valores por vírgula ',' e utilize ponto '.' como decimal.") ) ), plotly::plotlyOutput(ns("rep_th_plot"), width = "80%") %>% shinycssloaders::withSpinner(type = 5), br(), br(), downloadButton(ns("download_rep_th_tab"),"Download tabela"), DT::dataTableOutput(ns("rep_th_tab"), width = "100%") %>% shinycssloaders::withSpinner(type = 5) )) }) eval(parse(text = check_text_input_to_vector("rep_sd_plot"))) tab_rep_th_cenarios <- reactive({ desvios_plot <- text_input_to_vector(input$rep_sd_plot) req(length(desvios_plot) > 0) grid <- expand.grid(`Diferença a ser detectada` = seq(from = input$rep_th_from, to = input$rep_th_to, by = input$rep_th_by), `Desvio padrão 1` = desvios_plot, `Desvio padrão 2` = input$rep_sigma2, `Nível de significância (%)` = input$rep_sig, `Poder (%)` = input$rep_power, `Balanceamento` = input$rep_ratio) grid_n <- grid %$% purrr::pmap_dfr( .l = list(`Diferença a ser detectada`, `Desvio padrão 1`, `Desvio padrão 2`, `Nível de significância (%)`, `Poder (%)`, `Balanceamento`), .f = function(delta, sigmaa, sigmab, sig.level, power, lambda){ tryCatch({ n <- longpower::power.mmrm( Ra = matrix(data = correlation_Ra(), nrow = input$rep_n_tempos, byrow = TRUE), ra = rep_retencao_A()/100, sigmaa = sigmaa, Rb = matrix(data = correlation_Rb(), nrow = input$rep_n_tempos, byrow = TRUE), rb = rep_retencao_B()/100, sigmab = sigmab, delta = delta, lambda = lambda, sig.level = sig.level/100, power = power/100 ) tibble(`n Tratamento` = ceiling(n$n1), `n Controle` = ceiling(n$n2)) }, warning = function(warning_condition) { NA }, error = function(error_condition) { NA }) }) bind_cols(grid, grid_n) %>% mutate(`Tamanho da amostra` = `n Tratamento` + `n Controle`, `Matriz correlação Tratamento` = paste0("matrix(data = c(", paste0(correlation_Ra(), collapse = ", "),"), nrow = ", input$rep_n_tempos, ", byrow = TRUE)"), `Matriz correlação Controle` = paste0("matrix(data = c(", paste0(correlation_Rb(), collapse = ", "),"), nrow = ", input$rep_n_tempos, ", byrow = TRUE)") ) }) output$rep_th_plot <- plotly::renderPlotly({ req(!is.null(tab_rep_th_cenarios())) g1 <- tab_rep_th_cenarios() %>% mutate(DP = factor(`Desvio padrão 1`)) %>% ggplot(aes(x = `Diferença a ser detectada`, y = `Tamanho da amostra`, color = DP, `n Tratamento` = `n Tratamento`, `n Controle` = `n Controle`)) + geom_line() + geom_point() + scale_x_continuous(breaks = seq(from = input$rep_th_from, to = input$rep_th_to, by = input$rep_th_by)) + xlab("Diferença a ser detectada") + ylab("Tamanho total da amostra*") + theme_bw() + theme(axis.text = element_text(colour = "black")) + scale_color_brewer(palette = "Set1") plotly::ggplotly(g1, tooltip = c("x", "colour", "y", "n Tratamento", "n Controle")) %>% plotly::layout(annotations = list(x = 1, y = -0.1, text = "* sem considerar perdas/ recusas.", showarrow = F, xref='paper', yref='paper', xanchor='right', yanchor='auto', xshift=0, yshift=0, font=list(size=10))) }) output$rep_th_tab <- DT::renderDataTable({ req(!is.null(tab_rep_th_cenarios())) tab_rep_th_cenarios() %>% DT::datatable( rownames = FALSE, filter = "none", class = "display nowrap", options = list(pageLength = 10, scrollX = TRUE, scrollY = TRUE, searching = FALSE, dom = 'B<"dwnld">frtip')) }) output$download_rep_th_tab <- downloadHandler( filename = function() { "Cenarios_tamanho_amostra_medidas_repetidas.xlsx"}, content = function(file) {writexl::write_xlsx(tab_rep_th_cenarios(), path = file)} ) } ) }
knitr::opts_chunk$set(echo = TRUE, eval = TRUE, cache = TRUE, fig.pos = 'H') library(data.table) library(ggplot2) library(knitr) library(kableExtra) options(width=50) theme_set(theme_gray(base_size = 9)) update_geom_defaults("point", list(size = 0.5)) update_geom_defaults("boxplot", list(outlier.size = 0.5)) op <- options() options(datatable.print.topn=3, width=50) include_graphics("figures/RStudio-Screenshot.png") apropos("mean") options(prompt="> ") example(mean) options(prompt="R> ") height <- 173 height age <- 10 AgE <- 50 age AgE Name <- "Leo"; Age <- 25; City <- "Lisbon" Name; Age; City City 2 + 3 (5*11)/4 - 7 7^3 sqrt(2) floor(8.6178) round(8.6178, 2) roomLength <- 7.8 roomWidth <- 6.4 roomArea <- roomLength * roomWidth roomArea Greeting <- "Hello World!" Greeting x1 <- c(26, 10, 4, 7, 41, 19) x1 x2 <- c("Peru", "Italy", "Cuba", "Ghana") x2 r1 <- rep(c(2, 6, 7, 4), times=3) r1 s1 <- seq(from=-2, to=3, by=0.5) s1 x1 * 2 round(sqrt(x1*2.6), 2) x2 <- c(3, -7, NA, 5, 1, 1) x2 x3 <- c("Rat", NA, "Mouse", "Hamster") x3 ls() rm(x, x1, x2, x3, xm, r1, s1, AgE, age) ls() seq(from = 5, to = 8, by = 0.4) seq(from = 5, to = 8, length.out = 16) CW <- data.table(ChickWeight) if (!file.exists("ChickWeight.csv")) fwrite(CW[, .(Chick, Diet, Time, weight)], file="ChickWeight.csv") suppressMessages(library(data.table)) cw <- fread("ChickWeight.csv") cw str <- function(object, ...) { if (!is.data.frame(object)) { warning("str.data.frame() called with non-data.frame -- coercing to one.") object <- data.frame(object) } cl <- oldClass(object) cl <- cl[cl != "data.frame"] if (0 < length(cl)) cat("Classes", paste(sQuote(cl), collapse = ", "), "and ") cat("'data.frame':\n ", nrow(object), " obs. of ", (p <- length(object)), " variable", if (p != 1) "s", if (p > 0) ":", "\n", sep = "") utils:::str.default(object, vec.len=2, strict.width="wrap", ...) } options(digits=5,width=45) str(cw) summary(cw) options(digits=6,width=50) suppressMessages(library(ggplot2)) ggplot(cw, aes(Time, weight)) ggplot(cw, aes(Time, weight)) + geom_point() ggplot(cw, aes(Time,weight,colour=factor(Diet))) + geom_point() options(digits=2) cw[, Diet := factor(Diet)] cw[, Time := factor(Time)] summary(cw) options(digits=6) ggplot(cw, aes(Time, weight, colour=Diet)) + geom_point() + facet_wrap(~ Diet) + theme(legend.position = "bottom") ggplot(cw, aes(Time, weight, group=Diet, colour=Diet)) + stat_summary(fun.y="mean", geom="line") ggplot(cw, aes(Time, weight, colour=Diet)) + facet_wrap(~ Diet) + geom_boxplot() + theme(legend.position = "none") + ggtitle("Chick Weight over Time by Diet") ggplot(cw, aes(Time, weight, group=Diet, colour=Diet)) + facet_wrap(~ Diet) + geom_jitter() + stat_summary(fun.y="mean", geom="line", colour="black") + theme(legend.position = "none") + ggtitle("Chick Weight over Time by Diet") + xlab("Time (days)") + ylab("Weight (grams)") cw[, weightKg := weight/1000 ] cw cw[, Diet := paste0("Diet_", Diet)] cw cw[, .(Chick, Time, Diet, weightKg)] cw[, .(Mean=mean(weight),SDev=sd(weight)),by=Diet] setnames(cw, c("Diet", "weight"), c("Group", "Weight")) cw cw[ Time == 21 & Weight > 300, ] cw[order(Weight), ] setkey(cw, Chick, Time) cw cw <- fread("ChickWeight.csv") cw[Time %in% c(0,21),][ , Weight := weight][ , Group := factor(paste0("Diet_", Diet))][ , .(Chick,Group,Time,Weight)][ order(Chick,Time)][ 1:5,] cw[, .(N = .N, Mean = mean(weight)), by=.(Diet, Time)][ 1:5, ] options(digits=3) cws <- cw[Time %in% c(0,21), .(N = .N, Mean = mean(weight), SDev = sd(weight), Median = median(weight), Min = min(weight), Max = max(weight) ), by=.(Diet, Time)] cws cws[, Mean_SD := paste0(format(Mean,digits=1), " (", format(SDev,digits=2), ")")] cws[, Range := paste(Min, "-", Max)] prettySum <- cws[ , .(Diet, Time, N, Mean_SD, Median, Range)][ order(Diet, Time)] prettySum tbl <- kable(prettySum[Time %in% c(0,21), ], "latex", booktabs = TRUE, linesep = "", align = "crrrrr") tbl <- kable_styling(tbl, position = "center") tbl <- row_spec(tbl, 0, bold = TRUE) tbl <- row_spec(tbl, c(2, 4, 6, 8), background = "lightgray") tbl options(op)
met2model.MAESPA <- function(in.path, in.prefix, outfolder, start_date, end_date, overwrite = FALSE, verbose = FALSE, ...) { print("START met2model.MAESPA") start.date <- as.POSIXlt(start_date, tz = "GMT") end.date <- as.POSIXlt(end_date, tz = "GMT") out.file <- paste(in.prefix, strptime(start.date, "%Y-%m-%d"), strptime(end.date, "%Y-%m-%d"), "dat", sep = ".") out.file.full <- file.path(outfolder, out.file) results <- data.frame(file = out.file.full, host = PEcAn.remote::fqdn(), mimetype = "text/plain", formatname = "maespa.met", startdate = start_date, enddate = end_date, dbfile.name = out.file, stringsAsFactors = FALSE) print("internal results") print(results) if (file.exists(out.file.full) && !overwrite) { PEcAn.logger::logger.debug("File '", out.file.full, "' already exists, skipping to next file.") return(invisible(results)) } if (!file.exists(outfolder)) { dir.create(outfolder) } out <- NULL start_year <- lubridate::year(start.date) end_year <- lubridate::year(end.date) for (year in start_year:end_year) { print(year) old.file <- file.path(in.path, paste(in.prefix, year, "nc", sep = ".")) if (file.exists(old.file)) { nc <- ncdf4::nc_open(old.file) sec <- nc$dim$time$vals sec <- udunits2::ud.convert(sec, unlist(strsplit(nc$dim$time$units, " "))[1], "seconds") dt <- PEcAn.utils::seconds_in_year(year) / length(sec) tstep <- round(86400 / dt) dt <- 86400 / tstep lat <- ncdf4::ncvar_get(nc, "latitude") lon <- ncdf4::ncvar_get(nc, "longitude") RAD <- ncdf4::ncvar_get(nc, "surface_downwelling_shortwave_flux_in_air") PAR <- try(ncdf4::ncvar_get(nc, "surface_downwelling_photosynthetic_photon_flux_in_air")) TAIR <- ncdf4::ncvar_get(nc, "air_temperature") QAIR <- ncdf4::ncvar_get(nc, "specific_humidity") PPT <- ncdf4::ncvar_get(nc, "precipitation_flux") CA <- try(ncdf4::ncvar_get(nc, "mole_fraction_of_carbon_dioxide_in_air")) PRESS <- ncdf4::ncvar_get(nc, "air_pressure") RH <- PEcAn.data.atmosphere::qair2rh(QAIR, TAIR, PRESS) if (!is.numeric(PAR)) { PAR <- PEcAn.data.atmosphere::sw2par(RAD) } else { PAR <- udunits2::ud.convert(PAR, "mol", "umol") } TAIR <- udunits2::ud.convert(TAIR, "kelvin", "celsius") defaultCO2 <- 400 if (!is.numeric(CA)) { print("Atmospheric CO2 concentration will be set to constant value set in ENVIRON namelist ") rm(CA) } else { CA <- CA * 1e+06 } ncdf4::nc_close(nc) } else { print("Skipping to next year") next } if (exists("CA")) { tmp <- cbind(TAIR, PPT, RAD, PRESS, PAR, RH, CA) } else { tmp <- cbind(TAIR, PPT, RAD, PRESS, PAR, RH) } if (is.null(out)) { out <- tmp } else { out <- rbind(out, tmp) } } if (anyNA(out)) { PEcAn.logger::logger.debug("NA introduced in met data. Maespa will not be able to run properly. Please change Met Data Source or Site") } else { PEcAn.logger::logger.debug("No NA values contained in data") } columnnames <- colnames(out) timesteps <- tstep difsky <- 0.5 startdate <- paste0(format(as.Date(start_date), "%d/%m/%y")) enddate <- paste0(format(as.Date(end_date), "%d/%m/%y")) if (nc$dim$latitude$units == "degree_north") { latunits <- "N" } else { latunits <- "S" } if (nc$dim$longitude$units == "degree_east") { lonunits <- "E" } else { lonunits <- "W" } metfile <- system.file("met.dat", package = "PEcAn.MAESPA") met.dat <- Maeswrap::replacemetdata(out, oldmetfile = metfile, newmetfile = out.file.full) Maeswrap::replacePAR(out.file.full, "difsky", "environ", newval = difsky, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "ca", "environ", newval = defaultCO2, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "lat", "latlong", newval = lat, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "long", "latlong", newval = lon, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "lonhem", "latlong", newval = lonunits, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "lathem", "latlong", newval = latunits, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "startdate", "metformat", newval = startdate, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "enddate", "metformat", newval = enddate, noquotes = TRUE) Maeswrap::replacePAR(out.file.full, "columns", "metformat", newval = columnnames, noquotes = TRUE) return(invisible(results)) }
is.lconnect <- function(x) inherits(x, "lconnect")
context("layout_with_sugiyama") test_that("layout_with_sugiyama does not demote matrices to vectors in res$layout.dummy", { ex <- graph.formula( A -+ B:C, B -+ C:D) layex <- layout.sugiyama(ex, layers=NULL) expect_that(nrow(layex$layout.dummy), equals(1)) })
PSEkNUCdi_RNA<-function(seqs,selectedIdx=c("Rise (RNA)", "Roll (RNA)", "Shift (RNA)", "Slide (RNA)", "Tilt (RNA)","Twist (RNA)"),lambda=3,w = 0.05,l=2,ORF=FALSE,reverseORF=TRUE,threshold=1,label=c()){ path.pack=system.file("extdata",package="ftrCOOL") if(length(seqs)==1&&file.exists(seqs)){ seqs<-fa.read(seqs,alphabet="rna") seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else if(is.vector(seqs)){ seqs<-sapply(seqs,toupper) seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else { stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.") } flag=0 if(ORF==TRUE){ if(length(label)==length(seqs)){ names(label)=names(seqs) flag=1 } seqs=maxORF_RNA(seqs,reverse=reverseORF) if(flag==1) label=label[names(seqs)] } dict<-list("A"=1,"C"=2,"G"=3,"U"=4) numSeqs<-length(seqs) aaIdxAD<-paste0(path.pack,"/DI_RNA.csv") aaIdx<-read.csv(aaIdxAD) row.names(aaIdx)<-aaIdx[,1] aaIdx<-aaIdx[selectedIdx,-1] aaIdx<-as.matrix(aaIdx) aaIdx<-type.convert(aaIdx) if(threshold!=1){ aaIdx<-t(aaIdx) corr<-cor(aaIdx) corr2<-corr^2 tmp<-corr2 tmp[upper.tri(tmp)]<-0 for(i in 1:ncol(tmp)){ tmp[i,i]=0 } aaIdx<- aaIdx[,!apply(tmp,2,function(x) any(x > threshold))] aaIdx<- t(aaIdx) } minFea<-apply(aaIdx, 1, min) maxFea<-apply(aaIdx, 1, max) aaIdx<-(aaIdx-minFea)/(maxFea-minFea) numFea<-nrow(aaIdx) start<-4^l+1 end<-4^l+lambda featureMatrix<-matrix(0,nrow = numSeqs,ncol = ((4^l)+lambda)) for(n in 1:numSeqs){ seq<-seqs[n] N<-nchar(seq) if (lambda>N || lambda<=0){ stop("Error: lambda should be between [1,N]. N is the minimum of sequence lengths") } small_theta<-vector(mode = "numeric", length = lambda) chars<-unlist(strsplit(seq,NULL)) temp1<-chars[1:(N-1)] temp2<-chars[2:N] dimers<-paste0(temp1,temp2) lenDimer=N-1 for(k in 1:lambda){ vecti=1:(lenDimer-k) vectj=vecti+k tempMat<-matrix(0,nrow = numFea,ncol = (lenDimer-k)) for(m in 1:numFea){ tempMat[m,]=(aaIdx[m,dimers[vecti]]-aaIdx[m,dimers[vectj]])^2 } bigThetaVect<-apply(tempMat, 2, sum) sumbigThetas<-sum(bigThetaVect) small_theta[k]<-(1/(N-k))*sumbigThetas } sum_small_th<-sum(small_theta) NUC<-kNUComposition_RNA(seq,rng=l,normalized = FALSE,upto = FALSE) featureVector <- vector(mode = "numeric", length = (length(NUC)+lambda)) featureVector[1:length(NUC)]<-(NUC)/(N+w*(sum_small_th)) featureVector[start:end]<- (w*small_theta)/(N+w*(sum_small_th)) featureMatrix[n,]=featureVector } namNUC<-nameKmer(k=l,type = "rna") temp=1:lambda colnam=c(namNUC,paste("lambda",temp,sep="")) colnames(featureMatrix)=colnam if(length(label)==numSeqs){ featureMatrix<-as.data.frame(featureMatrix) featureMatrix<-cbind(featureMatrix,label) } row.names(featureMatrix)<-names(seqs) return(featureMatrix) }
gamVineStructureSelect <- function(udata, lin.covs = NULL, smooth.covs = NULL, simplified = TRUE, type = 0, familyset = NA, rotations = TRUE, familycrit = "AIC", treecrit = "tau", level = 0.05, trunclevel = NA, tau = TRUE, method = "FS", tol.rel = 0.001, n.iters = 10, parallel = FALSE, verbose = FALSE, select.once = TRUE) { tmp <- valid.gamVineStructureSelect( udata, lin.covs, smooth.covs, simplified, type, familyset, rotations, familycrit, treecrit, level, trunclevel, tau, method, tol.rel, n.iters, parallel, verbose, select.once ) if (tmp != TRUE) { stop(tmp) } tmp <- prepare.data2( udata, lin.covs, smooth.covs, trunclevel, familyset, rotations ) n <- tmp$n d <- tmp$d l <- tmp$l nn <- tmp$nn data <- tmp$data covariates <- tmp$covariates trunclevel <- tmp$trunclevel familyset <- tmp$familyset if (type == 0) { type <- "RVine" } else { type <- "CVine" } out <- list(Tree = vector("list", d - 1), Graph = vector("list", d - 1)) if (is.null(colnames(udata))) { colnames(udata) <- paste0("V", 1:ncol(udata)) } graph <- initFirstGraph(udata, treecrit) mst <- findMST(graph, type) tree <- fitFirstTree( mst, udata, lin.covs, smooth.covs, l, covariates, familyset, familycrit, treecrit, level, tau, method, tol.rel, n.iters, parallel, verbose ) out$Tree[[1]] <- tree out$Graph[[1]] <- graph oldtree <- tree for (i in 2:(d - 1)) { if (trunclevel == i - 1) { familyset <- 0 } graph <- buildNextGraph( tree, udata, l, lin.covs, smooth.covs, simplified, treecrit ) mst <- findMST(graph, type) tree <- fitTree( mst, tree, udata, l, lin.covs, smooth.covs, simplified, familyset, familycrit, treecrit, level, tau, method, tol.rel, n.iters, parallel, verbose ) out$Tree[[i]] <- tree out$Graph[[i]] <- graph } return(as.GVC(out, covariates)) } initFirstGraph <- function(data, treecrit) { if (treecrit == "tau") { C <- TauMatrix(data) } if (treecrit == "rho") { C <- cor(data, method = "spearman") } rownames(C) <- colnames(C) <- colnames(data) g <- graph.adjacency(C, mode = "lower", weighted = TRUE, diag = FALSE) E(g)$tau <- E(g)$weight E(g)$weight <- 1 - abs(E(g)$weight) E(g)$name <- paste(get.edgelist(g)[, 1], get.edgelist(g)[, 2], sep = ",") for (i in 1:ecount(g)) { E(g)$conditionedSet[[i]] <- ends(g, i, FALSE) } return(g) } findMST <- function(g, mode = "RVine") { if (mode == "RVine") { return(minimum.spanning.tree(g, weights = E(g)$weight)) } else { M <- abs(get.adjacency(g, attr = "weight", sparse = 0)) root <- which.min(rowSums(M)) Ecken <- ends(g, 1:ecount(g), FALSE) pos <- Ecken[, 2] == root | Ecken[, 1] == root return(delete.edges(g, E(g)[!pos])) } } fitFirstTree <- function(mst, udata, lin.covs, smooth.covs, l, covariates, familyset, familycrit, treecrit, level, tau, method, tol.rel, n.iters, parallel, verbose) { d <- ecount(mst) parameterForACopula <- vector("list", d) for (i in 1:d) { a <- ends(mst, i, FALSE) if (is.null(V(mst)[a[1]]$name)) { E(mst)[i]$CondName1 <- a[1] } else { E(mst)[i]$CondName1 <- V(mst)[a[1]]$name } if (is.null(V(mst)[a[2]]$name)) { E(mst)[i]$CondName2 <- a[2] } else { E(mst)[i]$CondName2 <- V(mst)[a[2]]$name } if (is.null(V(mst)[a[1]]$name) || is.null(V(mst)[a[2]]$name)) { E(mst)[i]$Name <- paste(a[1], a[2], sep = " , ") } else { E(mst)[i]$Name <- paste(V(mst)[a[1]]$name, V(mst)[a[2]]$name, sep = " , " ) } if (l == 0) { parameterForACopula[[i]] <- list() parameterForACopula[[i]]$zr1 <- udata[, a[1]] parameterForACopula[[i]]$zr2 <- udata[, a[2]] } else { parameterForACopula[[i]] <- list( cbind( as.numeric(udata[, a[1]]), as.numeric(udata[, a[2]]) ), lin.covs, smooth.covs ) } } if (l == 0) { outForACopula <- lapply( parameterForACopula, wrapper.fitACopula, familyset, familycrit, level ) } else { outForACopula <- lapply( parameterForACopula, wrapper.fitACopula, familyset, familycrit, level, tau, method, tol.rel, n.iters, parallel ) } for (i in 1:d) { E(mst)[i]$model <- list(outForACopula[[i]]$model) E(mst)[i]$CondData1 <- list(outForACopula[[i]]$CondOn1) E(mst)[i]$CondData2 <- list(outForACopula[[i]]$CondOn2) } return(mst) } fitTree <- function(mst, oldVineGraph, udata, l, lin.covs, smooth.covs, simplified, familyset, familycrit, treecrit, level, tau, method, tol.rel, n.iters, parallel, verbose) { d <- ecount(mst) parameterForACopula <- list() for (i in 1:d) { con <- ends(mst, i, FALSE) tmp <- ends(oldVineGraph, con, FALSE) if ((tmp[1, 1] == tmp[2, 1]) || (tmp[1, 2] == tmp[2, 1])) { same <- tmp[2, 1] } else { if ((tmp[1, 1] == tmp[2, 2]) || (tmp[1, 2] == tmp[2, 2])) { same <- tmp[2, 2] } } other1 <- tmp[1, tmp[1, ] != same] other2 <- tmp[2, tmp[2, ] != same] if (tmp[1, 1] == same) { zr1 <- E(oldVineGraph)[con[1]]$CondData2 n1 <- E(oldVineGraph)[con[1]]$CondName2 } else { zr1 <- E(oldVineGraph)[con[1]]$CondData1 n1 <- E(oldVineGraph)[con[1]]$CondName1 } if (tmp[2, 1] == same) { zr2 <- E(oldVineGraph)[con[2]]$CondData2 n2 <- E(oldVineGraph)[con[2]]$CondName2 } else { zr2 <- E(oldVineGraph)[con[2]]$CondData1 n2 <- E(oldVineGraph)[con[2]]$CondName1 } if (is.list(zr1)) { zr1a <- as.vector(zr1[[1]]) zr2a <- as.vector(zr2[[1]]) n1a <- as.vector(n1[[1]]) n2a <- as.vector(n2[[1]]) } else { zr1a <- zr1 zr2a <- zr2 n1a <- n1 n2a <- n2 } if (verbose == TRUE) message(n1a, " + ", n2a, " --> ", E(mst)[i]$name) E(mst)[i]$CondName2 <- n1a E(mst)[i]$CondName1 <- n2a tmp <- E(mst)$conditioningSet[[i]] if (simplified) { if (l == 0) { parameterForACopula[[i]] <- list() parameterForACopula[[i]]$zr1 <- as.numeric(zr1a) parameterForACopula[[i]]$zr2 <- as.numeric(zr2a) } else { parameterForACopula[[i]] <- list( cbind( as.numeric(zr1a), as.numeric(zr2a) ), lin.covs, smooth.covs ) } } else { temp <- as.data.frame(udata[, tmp]) colnames(temp) <- colnames(udata)[tmp] if (!is.null(smooth.covs)) { temp <- cbind(temp, smooth.covs) } parameterForACopula[[i]] <- list( cbind( as.numeric(zr1a), as.numeric(zr2a) ), lin.covs, temp ) } } outForACopula <- lapply( parameterForACopula, wrapper.fitACopula, familyset, familycrit, level, tau, method, tol.rel, n.iters, parallel ) for (i in 1:d) { E(mst)[i]$model <- list(outForACopula[[i]]$model) E(mst)[i]$CondData2 <- list(outForACopula[[i]]$CondOn2) E(mst)[i]$CondData1 <- list(outForACopula[[i]]$CondOn1) } return(mst) } buildNextGraph <- function(graph, udata, l, lin.covs, smooth.covs, simplified, treecrit) { EL <- get.edgelist(graph) d <- ecount(graph) g <- graph.full(d) V(g)$name <- E(graph)$name V(g)$conditionedSet <- E(graph)$conditionedSet if (!is.null(E(graph)$conditioningSet)) { V(g)$conditioningSet <- E(graph)$conditioningSet } for (i in 1:ecount(g)) { con <- ends(g, i, FALSE) tmp <- ends(graph, con, FALSE) ok <- FALSE if ((tmp[1, 1] == tmp[2, 1]) || (tmp[1, 2] == tmp[2, 1])) { ok <- TRUE same <- tmp[2, 1] } else { if ((tmp[1, 1] == tmp[2, 2]) || (tmp[1, 2] == tmp[2, 2])) { ok <- TRUE same <- tmp[2, 2] } } if (ok) { other1 <- tmp[1, tmp[1, ] != same] other2 <- tmp[2, tmp[2, ] != same] if (tmp[1, 1] == same) { zr1 <- E(graph)[con[1]]$CondData2 } else { zr1 <- E(graph)[con[1]]$CondData1 } if (tmp[2, 1] == same) { zr2 <- E(graph)[con[2]]$CondData2 } else { zr2 <- E(graph)[con[2]]$CondData1 } if (is.list(zr1)) { zr1a <- as.vector(zr1[[1]]) zr2a <- as.vector(zr2[[1]]) } else { zr1a <- zr1 zr2a <- zr2 } noNAs <- !(is.na(zr1a) | is.na(zr2a)) name.node1 <- strsplit(V(g)[con[1]]$name, split = " *[,|] *")[[1]] name.node2 <- strsplit(V(g)[con[2]]$name, split = " *[,|] *")[[1]] intersection <- c() for (j in 1:length(name.node1)) { for (k in 1:length(name.node2)) { if (name.node1[j] == name.node2[k]) { intersection <- c(intersection, name.node1[j]) name.node1[j] <- "" name.node2[k] <- "" break } } } difference <- c() for (j in 1:length(name.node1)) { if (name.node1[j] != "") { difference <- c(difference, name.node1[j]) } } for (j in 1:length(name.node2)) { if (name.node2[j] != "") { difference <- c(difference, name.node2[j]) } } E(g)[i]$name <- paste(paste(difference, collapse = ","), paste(intersection, collapse = ","), sep = " | " ) if (is.list(V(g)[con[1]]$conditionedSet)) { l1 <- c( as.vector(V(g)[con[1]]$conditionedSet[[1]]), as.vector(V(g)[con[1]]$conditioningSet[[1]]) ) l2 <- c( as.vector(V(g)[con[2]]$conditionedSet[[1]]), as.vector(V(g)[con[2]]$conditioningSet[[1]]) ) } else { l1 <- c(V(g)[con[1]]$conditionedSet, V(g)[con[1]]$conditioningSet) l2 <- c(V(g)[con[2]]$conditionedSet, V(g)[con[2]]$conditioningSet) } out <- intersectDifference(l1, l2) suppressWarnings({ E(g)$conditionedSet[i] <- list(out$difference) }) suppressWarnings({ E(g)$conditioningSet[i] <- list(out$intersection) }) if (treecrit == "tau") { E(g)[i]$weight <- 1 - abs(fasttau(zr1a[noNAs], zr2a[noNAs])) } else if (treecrit == "rho") { E(g)[i]$weight <- 1 - abs(cor(zr1a[noNAs], zr2a[noNAs], method = "spearman")) } } E(g)[i]$todel <- !ok } E(g)$tau <- E(g)$weight g <- delete.edges(g, E(g)[E(g)$todel]) return(g) } wrapper.fitACopula <- function(parameterForACopula, ...) { if (length(parameterForACopula) == 2) { return(fitACopula(parameterForACopula$zr1, parameterForACopula$zr2, ...)) } else { return(fitAGAMCopula(parameterForACopula, ...)) } } intersectDifference <- function(liste1, liste2) { out <- list() out$intersection <- c() out$difference <- c() for (j in 1:length(liste1)) { for (k in 1:length(liste2)) { if (!is.na(liste2[k]) && liste1[j] == liste2[k]) { out$intersection <- c(out$intersection, liste1[j]) liste1[j] <- NA liste2[k] <- NA break } } } for (j in 1:length(liste1)) { if (!is.na(liste1[j])) { out$difference <- c(out$difference, liste1[j]) } } for (j in 1:length(liste2)) { if (!is.na(liste2[j])) { out$difference <- c(out$difference, liste2[j]) } } return(out) } fitACopula <- function(u1, u2, familyset = NA, familycrit = "AIC", level = 0.05, rotation = TRUE) { fams <- famTrans(familyset, inv = FALSE, set = TRUE) out <- BiCopSelect(u1, u2, fams, familycrit, indeptest = TRUE, level = level, rotations = FALSE ) fam <- famTrans(out$family, inv = TRUE, par = cor(u1, u2), familyset = familyset ) if (rotation == TRUE) { if (fam %in% c(301, 303, 401, 403)) { fam <- fam + 1 } else if (fam %in% c(302, 304, 402, 404)) { fam <- fam - 1 } } out$family <- fam tmp <- bicoppd1d2(cbind(u1, u2, out$par, out$par2), out$family, p = FALSE, h = TRUE) model <- list(family = out$family, par = out$par, par2 = out$par2) out <- list(model = model, CondOn1 = tmp[2, ], CondOn2 = tmp[1, ]) return(out) } fitAGAMCopula <- function(data, familyset, familycrit, level, tau, method, tol.rel, n.iters, parallel, rotation = TRUE, select.once = TRUE, ...) { out <- list() u1 <- data[[1]][, 1] u2 <- data[[1]][, 2] udata <- cbind(u1, u2) lin.covs <- data[[2]] smooth.covs <- data[[3]] data <- do.call(cbind, data[!(sapply(data, is.null))]) if (length(familyset) == 1 && familyset == 0) { out$model <- list(family = 0, par = 0, par2 = 0) par <- rep(0, length(u1)) fam <- 0 par2 <- 0 } else { fams <- famTrans(familyset, inv = FALSE, set = TRUE) tmp <- gamBiCopSelect(udata, lin.covs, smooth.covs, familyset, FALSE, familycrit, level, 1.5, tau, method, tol.rel, n.iters, parallel, select.once = select.once, FALSE, ... ) if (!is.character(tmp)) { nvar <- unique(all.vars(tmp$res@model$pred.formula)) } if (!is.character(tmp) && length(nvar) > 0) { out$model <- tmp$res par <- gamBiCopPredict(out$model, target = "par")$par fam <- out$model@family par2 <- out$model@par2 } else { tmp <- BiCopSelect(u1, u2, fams, selectioncrit = familycrit, indeptest = TRUE, level = level, rotations = FALSE ) par <- rep(tmp$par, length(u1)) out$model$par <- tmp$par out$model$family <- fam <- tmp$family out$model$par2 <- par2 <- tmp$par2 } fam <- famTrans(fam, inv = TRUE, par = cor(u1, u2), familyset = familyset) if (rotation == TRUE) { if (fam %in% c(301, 303, 401, 403)) { fam <- fam + 1 } else if (fam %in% c(302, 304, 402, 404)) { fam <- fam - 1 } } if (isS4(out$model)) { attr(out$model, "family") <- fam } else { out$model$family <- fam } } fams <- vapply(1:length(par), function(j) famTrans(fam, inv = FALSE, par = par[j]), numeric(1)) out$CondOn1 <- BiCopHfunc(u1, u2, fams, par, par2, check.pars = FALSE)$hfunc2 out$CondOn2 <- BiCopHfunc(u1, u2, fams, par, par2, check.pars = FALSE)$hfunc1 return(out) } as.GVC <- function(GVC, covariates) { n <- length(GVC$Tree) + 1 con <- list() nam <- V(GVC$Tree[[1]])$name conditionedSets <- NULL correspondingModel <- NULL if (is.list(E(GVC$Tree[[n - 1]])$conditionedSet)) { conditionedSets[[n - 1]][[1]] <- (E(GVC$Tree[[n - 1]])$conditionedSet[[1]]) } else { conditionedSets[[n - 1]][[1]] <- (E(GVC$Tree[[n - 1]])$conditionedSet) } for (k in 1:(n - 2)) { conditionedSets[[k]] <- E(GVC$Tree[[k]])$conditionedSet correspondingModel[[k]] <- as.list(E(GVC$Tree[[k]])$model) } correspondingModel[[n - 1]] <- E(GVC$Tree[[n - 1]])$model model.count <- get.modelCount(n) model <- vector("list", n * (n - 1) / 2) M <- matrix(NA, n, n) for (k in 1:(n - 1)) { w <- conditionedSets[[n - k]][[1]][1] M[k, k] <- w M[(k + 1), k] <- conditionedSets[[n - k]][[1]][2] model[[model.count[(k + 1), k]]] <- correspondingModel[[n - k]][[1]] if (k == (n - 1)) { M[(k + 1), (k + 1)] <- conditionedSets[[n - k]][[1]][2] } else { for (i in (k + 2):n) { for (j in 1:length(conditionedSets[[n - i + 1]])) { cs <- conditionedSets[[n - i + 1]][[j]] tmp <- correspondingModel[[n - i + 1]][[j]] if (cs[1] == w) { M[i, k] <- cs[2] model[[model.count[i, k]]] <- tmp break } else if (cs[2] == w) { M[i, k] <- cs[1] if (isS4(tmp)) { fam <- attr(tmp, "family") } else { fam <- tmp$family } if (fam %in% c(301, 303, 401, 403)) { fam <- fam + 1 } else if (fam %in% c(302, 304, 402, 404)) { fam <- fam - 1 } if (isS4(tmp)) { attr(tmp, "family") <- fam } else { tmp$family <- fam } model[[model.count[i, k]]] <- tmp break } } conditionedSets[[n - i + 1]][[j]] <- NULL correspondingModel[[n - i + 1]][[j]] <- NULL } } } M[is.na(M)] <- 0 return(gamVine(M, model, nam, covariates)) } valid.gamVineStructureSelect <- function(data, lin.covs, smooth.covs, simplified, type, familyset, rotations, familycrit, treecrit, level, trunclevel, tau, method, tol.rel, n.iters, parallel, verbose, select.once) { if (!is.matrix(data) && !is.data.frame(data)) { return("data has to be either a matrix or a data frame") } tmp <- valid.gamBiCopSelect( data[, 1:2], lin.covs, smooth.covs, rotations, familyset, familycrit, level, 2, tau, method, tol.rel, n.iters, parallel, verbose, select.once ) if (tmp != TRUE) { return(tmp) } n <- dim(data)[1] d <- dim(data)[2] if (d < 2) { return("Number of dimensions has to be at least 2.") } if (n < 2) { return("Number of observations has to be at least 2.") } if (any(data[, 1:d] > 1) || any(data[, 1:d] < 0)) { return("Data has be in the interval [0,1].") } if (!valid.logical(simplified)) { return(msg.logical(var2char(simplified))) } if (is.null(lin.covs) && is.null(smooth.covs) && simplified == TRUE) { return("When there are no covariates, the vine can't be simplified.") } if (is.null(type) || length(type) != 1 || !is.element(type, c(0, 1))) { return("Vine model not implemented.") } if (length(treecrit) != 1 || (treecrit != "tau" && treecrit != "rho")) { return("Selection criterion for the pair selection not implemented.") } if (!is.na(trunclevel) && !valid.posint(trunclevel)) { return("'trunclevel' should be a positive integer or NA.") } if (!is.logical(select.once)) { return("'select.once' must be logical") } return(TRUE) }
ABlineD <- function(behavior){ targetindex<-dev.cur() targetindex<-recordPlot() writeLines("-------------------------------------------------------------------------------------") writeLines("Click the mouse in the gap between the phases you want the line in.") writeLines("-------------------------------------------------------------------------------------") l<-locator(1) ymin=min(behavior,na.rm = TRUE) ymax=max(behavior,na.rm = TRUE) ymax=ymax+1 segments(x0=l$x,y0=ymin,y1=rep(ymin:ymax),lty=2) u<-readline("accept line? (y/n) ") if (u=="n") {replayPlot(targetindex)} }
context("getPossibleCols") library(testthat) library(stringi) cols <- c("id", "sire", "dam", "sex", "gen", "birth", "exit", "age", "ancestry", "population", "origin", "status", "condition", "spf", "vasxOvx", "pedNum", "first", "second", "first_name", "second_name", "recordStatus") cols <- c("id", "sire", "dam", "sex", "gen", "birth", "exit", "death", "age", "ancestry", "population", "origin", "status", "condition", "departure", "spf", "vasxOvx", "pedNum", "first", "second", "first_name", "second_name", "recordStatus") test_that("getPossibleCols returns the right columns", { expect_equal(getPossibleCols(), cols) })
ZoonModuleParse <- function(modulePath) { lines <- readLines(modulePath, -1) roc <- roxygen2::rd_roclet() rd <- roxygen2::roc_proc_text(roc, lines)[[1]] if(packageVersion("roxygen2") >= "7.0.0"){ rds <- rd$sections res <- lapply( names(rds), function(field, x) x[[field]]$value, x = rds ) names(res) <- names(rd$sections) if ("section" %in% names(res)) { sections <- paste0(res$section$title, ":", res$section$content) names(sections) <- rep("section", length(sections)) res[["section"]] <- NULL res <- append(res, sections) } } else { if ("fields" %in% names(rd)) { field_fun <- function (field, x) { if ("values" %in% names(x[[field]])) { named_tag <- list(x[[field]]$values) names(named_tag) <- field return (unlist(named_tag)) } else { list_tag <- list() for (i in seq_along(x[[field]]$title)) { list_tag <- c(list_tag, list(list(name = x[[field]]$title[i], content = x[[field]]$content[i]))) } return (list_tag) } } res <- lapply(names(rd$fields), field_fun, rd$fields) names(res) <- names(rd$fields) if ("param" %in% names(res)) names(res$param) <- gsub("^param.", "", names(res$param)) } else if(length(rd)==1){ res <- lapply( names(rd), function(field, x) x[[1]][[field]]$values, rd ) } else { res <- lapply( names(rd), function(field, x) x[field]$values, x = rd ) } if ("section" %in% names(res)) { sections <- lapply( res$section, function (x) { paste0(x$name, ":", x$content) } ) names(sections) <- rep("section", length(sections)) res[["section"]] <- NULL res <- append(res, sections) } } if ("param" %in% names(res)) { params <- lapply( names(res$param), function (field, x) { list(name = field, description = as.character(x[field])) }, res$param ) names(params) <- rep("param", length(params)) res[["param"]] <- NULL res <- append(params, res) } return(res) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(logisticRR) n <- 500 set.seed(1234) X <- rbinom(n, 1, 0.3) W <- rbinom(n, 1, 0.3); W[sample(1:n, n/3)] = 2 Z <- rep(0, n) Z[sample(1:n, n/2)] <- "female"; Z <- ifelse(Z == 0, "male", Z) dummyZ <- ifelse(Z == "female", 1, 0) Y <- rbinom(n, 1, plogis(X - W + 2*dummyZ)) dat <- as.data.frame(cbind(Y, X, W, Z)) dat$X <- as.numeric(dat$X); dat$X <- ifelse(dat$X == 2, 1, 0) dat$Y <- as.numeric(dat$Y); dat$Y <- ifelse(dat$Y == 2, 1, 0) dat$W <- as.factor(dat$W) dat$Z <- as.factor(dat$Z) head(dat)
"Psi2phi" <- function(z){Psi(z)^2*dnorm(z)}
revolution <- c(CRAN = "https://cloud.r-project.org") revolution pkgs <- c("foreach") pkgTypes <- c("source", "win.binary") if (interactive()) { if (!is.online()) { message("MRAN seems to be not available. Check your internet connection.") } else { pdb <- pkgAvail(repos = revolution, type = "source") } } else { pdb <- cranJuly2014 } if (interactive()) { if (!is.online()) { message("MRAN seems to be not available. Check your internet connection.") } else { pkgList <- pkgDep(pkgs, availPkgs = pdb, repos = revolution, type = "source", suggests = FALSE) pkgList } } if (interactive()) { if (!is.online()) { message("MRAN seems to be not available. Check your internet connection.") } else { dir.create(pth <- file.path(tempdir(), "miniCRAN")) makeRepo(pkgList, path = pth, repos = revolution, type = pkgTypes) oldVers <- data.frame( package = c("foreach", "codetools", "iterators"), version = c("1.4.0", "0.2-7", "1.0.5"), stringsAsFactors = FALSE ) pkgs <- oldVers$package addOldPackage(pkgs, path = pth, vers = oldVers$version, repos = revolution, type = "source") pkgVersionsSrc <- checkVersions(pkgs, path = pth, type = "source") pkgVersionsBin <- checkVersions(pkgs, path = pth, type = "win.binary") basename(pkgVersionsSrc$source) basename(pkgVersionsBin$win.binary) file.remove(c(pkgVersionsSrc$source[1], pkgVersionsBin$win.binary[1])) updateRepoIndex(pth, type = pkgTypes, Rversion = R.version) pkgAvail(pth, type = "source") addPackage("Matrix", path = pth, repos = revolution, type = pkgTypes) unlink(pth, recursive = TRUE) } }
library(shiny) library(plotly) ui <- fluidPage( h3("R Plotly demo - disabling the Plolty tool bar"), br(), plotlyOutput("myplot") ) server <- function(input, output, session) { output$myplot <- renderPlotly( plot_ly(data = pressure, x=~temperature, y=~pressure, type = "scatter", mode=c("line", "points"), marker = list(color = " line = list(width = 2, color="red"), hoverinfo = "text", text = paste("Temperature ", pressure$temperature, "<br>", "Pressure ", pressure$pressure)) %>% layout(title = "Pressure vs Temperature Plotly", xaxis = list(title="Temperature", range=c(0,400), showgrid=F), yaxis=list(title="Pressure", showgrid=F, titlefont=list(family="Arial", size=18, color="brown")), annotations = list(xref = "Temperature", yref = "Pressure", x = 350, y = 100, align = "right", text = "Temperature vs Pressure <br> Source : Pressure dataset ", showarrow = F, ax = 0, ay = 0) ) %>% config(displayModeBar=FALSE) ) } shinyApp(ui, server)
setPosteriorPredictiveCheckOptions = function(estimatePPMC = TRUE, PPMCsamples = 1000, PPMCtypes = c("mean", "covariance", "univariate", "bivariate", "tetrachoric", "pearson"), lowPPMCpercentile = c(.025, .025, 0, 0, .025, .025), highPPMCpercentile = c(.975, .975, 1, 1, .975, .975) ){ defaultPosteriorPredictiveChecks = list(estimatePPMC = estimatePPMC, PPMCsamples = PPMCsamples, PPMCtypes = PPMCtypes, lowPPMCpercentile = lowPPMCpercentile, highPPMCpercentile = highPPMCpercentile) return(defaultPosteriorPredictiveChecks) }
uncondPower2x2<-function(n1,n2, theta1, theta2, alpha, ...){ pval<-as.vector( uncondExact2x2Pvals(n1,n2,...) ) f1<- dbinom(0:n1,n1, theta1) f2<- dbinom(0:n2, n2, theta2) f<- rep(f1,n2+1)*rep(f2, each=n1+1) power<- sum(f[pval<=alpha]) power } Power2x2<-function(n1,n2, theta1, theta2, alpha, pvalFunc, ...){ allx<-rep(0:n1,n2+1) ally<-rep(0:n2, each=n1+1) pvals<-rep(NA, length(allx)) for (i in 1:length(allx)){ pvals[i]<-pvalFunc(allx[i],n1, ally[i], n2) } f1<- dbinom(0:n1,n1, theta1) f2<- dbinom(0:n2, n2, theta2) f<- rep(f1,n2+1)*rep(f2, each=n1+1) power<- sum(f[pvals<=alpha]) power } SS2x2<-function(theta1, theta2, alpha, pvalFunc, power=0.90, n1start=10, increaseby=1, n2.over.n1=1, maxiter=50, printSteps=TRUE, ...){ n1<-n1start n2<- round(n2.over.n1*n1) pow<- Power2x2(n1,n2, theta1,theta2, alpha, pvalFunc, ...) if (printSteps){ message("n1=",n1,"n2=",n2,"power=",pow) } if (pow>power){ warning("power calculated at n1start is greater than 'power', there may be a smaller sample size") } else { for (i in 1:maxiter){ n1<- n1+increaseby n2<- round(n2.over.n1*n1) pow<- Power2x2(n1,n2, theta1,theta2, alpha, pvalFunc, ...) if (printSteps){ message("n1=",n1,"n2=",n2,"power=",pow) } if (pow>power){ break() } if (i==maxiter) warning("reached maxiter without achieving desired power") } } out<-list(power=pow,theta1=theta1,theta2=theta2, n1=n1,n2=n2, sig.level=alpha, method="rejection determined by pvalFunc") class(out)<-"power.htest" out }
pitch2 <- function(x,y,z,roll){ pitch = atan((-x)/((y*sin(roll))+(z*cos(roll))) ) return(pitch) }
mon_num_wrapper <- function(op, var, thld, infile, outfile, nc34, overwrite, verbose, p = NULL, nc = NULL) { calc_time_start <- Sys.time() check_variable(var) check_constant(thld) if(is.null(nc)) check_infile(infile) check_outfile(outfile) outfile <- correct_filename(outfile) check_overwrite(outfile, overwrite) check_nc_version(nc34) file_data <- read_file(infile, var, nc = nc) date_time <- get_date_time(file_data$dimension_data$t, file_data$time_info$units) months_all <- date_time$months months_unique <- sort(unique(months_all)) years_all <- date_time$years years_unique <- sort(unique(years_all)) nmonmeans <- length(years_unique) * length(months_unique) mul <- months_all * years_all testnum <- mul test_count <- 0 test <- -999 for (i in seq_along(mul)) { if (sum(testnum == mul[i]) >= 1) { test_count <- test_count + 1 test <- cbind(test, mul[i]) testnum[testnum == mul[i]] <- -999 } } data_placeholder <- array( file_data$variable$attributes$missing_value, dim = c(length(file_data$dimension_data$x), length(file_data$dimension_data$y), test_count) ) time_bnds <- get_time_bounds_mul( file_data$dimension_data$t, test, test_count, mul ) vars_data <- list(result = data_placeholder, time_bounds = time_bnds) nc_format <- get_nc_version(nc34) cmsaf_info <- switch( op, paste0("cmsafops::mon_num_above for variable ", file_data$variable$name), paste0("cmsafops::mon_num_below for variable ", file_data$variable$name), paste0("cmsafops::mon_num_equal for variable ", file_data$variable$name), ) time_data <- time_bnds[1, ] global_att_list <- names(file_data$global_att) global_att_list <- global_att_list[toupper(global_att_list) %in% toupper(GLOBAL_ATT_DEFAULT)] global_attributes <- file_data$global_att[global_att_list] dims <- define_dims(file_data$grid$is_regular, file_data$dimension_data$x, file_data$dimension_data$y, time_data, NB2, file_data$time_info$units) vars <- define_vars(file_data$variable, dims, nc_format$compression) write_output_file( outfile, nc_format$force_v4, vars, vars_data, file_data$variable$name, file_data$grid$vars, file_data$grid$vars_data, cmsaf_info, file_data$time_info$calendar, file_data$variable$attributes, global_attributes ) nc_out <- nc_open(outfile, write = TRUE) dummy_vec <- seq_along(months_all) count <- 1 for (j in seq_len(test_count)) { mon_dummy <- which(mul == test[j + 1]) if (length(mon_dummy) < 1) { if (verbose) message(paste0("length of month ", j, " not sufficient")) next() } startt <- min(dummy_vec[mon_dummy]) countt <- length(mon_dummy) if (!is.null(nc)) nc_in <- nc else nc_in <- nc_open(infile) dum_dat <- ncvar_get(nc_in, file_data$variable$name, start = c(1, 1, startt), count = c(-1, -1, countt), collapse_degen = FALSE) dum_dat <- switch(op, dum_dat >= thld, dum_dat <= thld, dum_dat == thld ) switch(op, { if (verbose) message(paste0("apply monthly number above threshold ", count)) data <- rowSums(dum_dat, dims = 2, na.rm = TRUE) }, { if (verbose) message(paste0("apply monthly number below threshold ", count)) data <- rowSums(dum_dat, dims = 2, na.rm = TRUE) }, { if (verbose) message(paste0("apply monthly number equal threshold ", count)) data <- rowSums(dum_dat, dims = 2, na.rm = TRUE) } ) data[is.na(data)] <- file_data$variable$attributes$missing_value ncvar_put(nc_out, vars[[1]], data, start = c(1, 1, count), count = c(-1, -1, 1)) count <- count + 1 if (is.null(nc)) nc_close(nc_in) } nc_close(nc_out) calc_time_end <- Sys.time() if (verbose) message(get_processing_time_string(calc_time_start, calc_time_end)) }
library(Polychrome) try( memberPlot( rep(0:1, 20))) try( memberPlot(matrix(LETTERS, ncol = 2 )) ) try( memberPlot(matrix(1:30, ncol = 5), pal = palette()) ) temp <- t(data.frame( A = c(rep(1, 500), rep(0, 100)), B = c(rep(1, 500), rep(0, 100)), C = c(rep(1, 300), rep(0, 300)), D = c(rep(1, 300), rep(0, 300)), E = c(rep(1, 300), rep(0, 300)), F = c(rep(1, 180), rep(0, 320), rep(1, 40), rep(0, 60)), G = c(rep(1, 180), rep(0, 320), rep(1, 40), rep(0, 60)), H = c(rep(1, 180), rep(0, 320), rep(1, 40), rep(0, 60)) )) set.seed(54321) noise <- matrix(rbinom(prod(dim(temp)), 1, 0.05), ncol = ncol(temp)) meme <- 1*(temp | noise) memberPlot(meme)
oadmin.install_package <- function(opal, pkg, repos=NULL, profile = NULL) { if(is.list(opal)){ lapply(opal, function(o){oadmin.install_package(o, pkg, repos)}) } else if (opal.version_compare(opal, "4.0")<0) { defaultrepos <- c(getOption("repos"), "http://cran.obiba.org", "http://cloud.r-project.org") if (getOption("repos") != "@CRAN@") { defaultrepos <- append(defaultrepos, getOption("repos")) } repostr <- paste('"', append(defaultrepos, repos),'"',collapse=',',sep='') cmd <- paste('install.packages("', pkg, '", repos=c(', repostr ,'), dependencies=TRUE)', sep='') resp <- opal.execute(opal, cmd, FALSE) oadmin.installed_package(opal, pkg) } else { oadmin.install_cran_package(opal, pkg, profile = profile) oadmin.installed_package(opal, pkg, profile = profile) } } oadmin.remove_package <- function(opal, pkg, profile = NULL) { if (opal.version_compare(opal, "4.0")<0) ignore <- tryCatch(opal.execute(opal, paste('remove.packages("', pkg, '")', sep=''), FALSE), error=function(e){}) else { cluster <- .toSafeProfile(opal, profile) ignore <- opal.delete(opal, "service", "r", "cluster", cluster, "package", pkg) } } oadmin.installed_package <- function(opal, pkg, profile = NULL) { if (opal.version_compare(opal, "4.0")<0) opal.execute(opal, paste('require("', pkg, '", character.only=TRUE)', sep=''), FALSE) else { cluster <- .toSafeProfile(opal, profile) dto <- tryCatch(opal.get(opal, "service", "r", "cluster", cluster, "package", pkg), error = function(e) { NULL }) !is.null(dto) } } oadmin.installed_packages <- function(opal, profile = NULL) { if (opal.version_compare(opal, "4.0")<0) opal.execute(opal, "installed.packages()") else { cluster <- .toSafeProfile(opal, profile) dtos <- opal.get(opal, "service", "r", "cluster", cluster, "packages") n <- length(dtos) name <- replicate(n, NA) cluster <- replicate(n, NA) rserver <- replicate(n, NA) fields <- list() if (n>0) { for (i in 1:n) { for (fieldName in sapply(dtos[[i]]$description, function(f) f$key)) if (!(fieldName %in% names(fields))) fields[[fieldName]] <- replicate(n, NA) } for (i in 1:n) { name[i] <- dtos[[i]]$name cluster[i] <- dtos[[i]]$cluster rserver[i] <- dtos[[i]]$rserver for (field in dtos[[i]]$description) fields[[field$key]][i] <- .nullToNA(field$value) } } df <- data.frame(name = name, cluster = cluster, rserver = rserver, stringsAsFactors = FALSE) for (fieldName in names(fields)) df[[fieldName]] <- fields[[fieldName]] df } } oadmin.package_description <- function(opal, pkg, fields=NULL, profile = NULL) { if(is.list(opal)){ lapply(opal, function(o){oadmin.package_description(o, pkg, fields=fields)}) } else if (opal.version_compare(opal, "4.0")<0) { fields <- append(c("Title","Description","Author","Maintainer","Date/Publication","AggregateMethods","AssignMethods"), fields) inst <- opal.execute(opal, paste('installed.packages(fields=c("', paste(fields, collapse='","') ,'"))', sep=''), FALSE) desc <- NULL for (i in 1:nrow(inst)) { if(inst[i]==pkg) { desc <- strsplit(inst[i,],"\n") break } } return(desc) } else { cluster <- .toSafeProfile(opal, profile) dto <- opal.get(opal, "service", "r", "cluster", cluster, "package", pkg) description <- list() for (entry in dto$description) { description[[entry$key]] <- .nullToNA(entry$value) } description } } oadmin.install_devtools <- function(opal, profile = NULL) { oadmin.install_cran_package(opal, 'devtools', profile = profile) } oadmin.installed_devtools <- function(opal, profile = NULL) { oadmin.installed_package(opal, 'devtools', profile = profile) } oadmin.install_cran_package <- function(opal, pkg, profile = NULL) { if (opal.version_compare(opal, "4.0")<0) opal.post(opal, "service", "r", "packages", query = list(name = pkg, manager = "cran")) else { cluster <- .toSafeProfile(opal, profile) opal.post(opal, "service", "r", "cluster", cluster, "packages", query = list(name = pkg, manager = "cran")) } oadmin.installed_package(opal, pkg, profile = profile) } oadmin.install_github_package <- function(opal, pkg , username=getOption("github.user"), ref="master", profile = NULL) { if (opal.version_compare(opal, "4.0")<0) opal.post(opal, "service", "r", "packages", query = list(name = paste0(username, "%2F", pkg), ref = ref, manager = "gh")) else { cluster <- .toSafeProfile(opal, profile) opal.post(opal, "service", "r", "cluster", cluster, "packages", query = list(name = paste0(username, "%2F", pkg), ref = ref, manager = "gh")) } oadmin.installed_package(opal, pkg, profile = profile) } oadmin.install_bioconductor_package <- function(opal, pkg, profile = NULL) { if (opal.version_compare(opal, "4.0")<0) opal.post(opal, "service", "r", "packages", query = list(name = pkg, manager = "bioc")) else { cluster <- .toSafeProfile(opal, profile) opal.post(opal, "service", "r", "cluster", cluster, "packages", query = list(name = pkg, manager = "bioc")) } oadmin.installed_package(opal, pkg, profile = profile) } oadmin.install_local_package <- function(opal, path, profile = NULL) { if (!file.exists(path)) { stop("Package archive file cannot be found at: ", path) } filename <- basename(path) if (!endsWith(filename, ".tar.gz")) { stop("Not a package archive file: ", filename) } pkg <- strsplit(filename, "\\.")[[1]][1] pkg <- strsplit(pkg, "_")[[1]][1] tmp <- opal.file_mkdir_tmp(opal) opal.file_upload(opal, path, tmp) if (opal.version_compare(opal, "4.2")<0) { opal.file_write(opal, paste0(tmp, filename)) opal.execute(opal, paste0("install.packages('", filename, "', repos = NULL, type ='source')")) } else { cluster <- .toSafeProfile(opal, profile) opal.post(opal, "service", "r", "cluster", cluster, "packages", query = list(name = paste0(tmp, filename), manager = "local")) } opal.file_rm(opal, tmp) oadmin.installed_package(opal, pkg, profile = .toSafeProfile(opal, profile)) } oadmin.r_perm_add <- function(opal, subject, type = "user", permission = 'use') { if (!(tolower(type) %in% c("user", "group"))) { stop("Not a valid subject type: ", type) } perms <- list('use' = 'R_USE') perm <- perms[[permission]] if (is.null(perm)) { stop("Not a valid R permission name: ", permission) } oadmin.r_perm_delete(opal, subject, type) for (i in 1:length(subject)) { ignore <- opal.post(opal, "system", "permissions", "r", query = list(principal = subject[i], type = toupper(type), permission = perm)) } } oadmin.r_perm <- function(opal) { perms <- list('R_USE' = 'use') acls <- opal.get(opal, "system", "permissions", "r") .aclsToDataFrame(perms, acls) } oadmin.r_perm_delete <- function(opal, subject, type = "user") { if (!(tolower(type) %in% c("user", "group"))) { stop("Not a valid subject type: ", type) } if (length(subject)<1) { stop("At least one subject is required") } for (i in 1:length(subject)) { ignore <- opal.delete(opal, "system", "permissions", "r", query = list(principal = subject[i], type = toupper(type))) } } oadmin.system_metrics <- function(opal) { opal.get(opal, "system", "status") } oadmin.system_perm_add <- function(opal, subject, type = "user", permission) { if (!(tolower(type) %in% c("user", "group"))) { stop("Not a valid subject type: ", type) } perms <- list('project_add' = 'PROJECT_ADD', 'administrate' = 'SYSTEM_ALL') perm <- perms[[permission]] if (is.null(perm)) { stop("Not a valid system permission name: ", permission) } oadmin.system_perm_delete(opal, subject, type) for (i in 1:length(subject)) { ignore <- opal.post(opal, "system", "permissions", "administration", query = list(principal = subject[i], type = toupper(type), permission = perm)) } } oadmin.system_perm <- function(opal) { perms <- list('PROJECT_ADD' = 'project_add', 'SYSTEM_ALL' = 'administrate') acls <- opal.get(opal, "system", "permissions", "administration") .aclsToDataFrame(perms, acls) } oadmin.system_perm_delete <- function(opal, subject, type = "user") { if (!(tolower(type) %in% c("user", "group"))) { stop("Not a valid subject type: ", type) } if (length(subject)<1) { stop("At least one subject is required") } for (i in 1:length(subject)) { ignore <- opal.delete(opal, "system", "permissions", "administration", query = list(principal = subject[i], type = toupper(type))) } } oadmin.perm_add <- function(opal, subject, type = "user", permission) { warning("Deprecated: use oadmin.r_perm_add()") oadmin.r_perm_add(opal, subject, type, permission) } oadmin.perm <- function(opal) { warning("Deprecated: use oadmin.r_perm()") oadmin.r_perm(opal) } oadmin.perm_delete <- function(opal, subject, type = "user") { oadmin.perm_delete(opal, subject, type) }
config_params <- function(conn, name, param = NULL, set = NULL, unset = NULL, update = NULL, ...) { conn$config_params(name, param, set, unset, update, ...) } name_by <- function(x, y) { if (is.null(x)) { NULL } else { stats::setNames(list(y = x), y) } }
addWaterYear <- function(rawData){ allowedDateColNames <- c("dateTime", "Date", "ActivityStartDate", "ActivityEndDate") allowedWYColNames <- c("waterYear", "waterYear", "ActivityStartWaterYear", "ActivityEndWaterYear") names(allowedWYColNames) <- allowedDateColNames if(all(!allowedDateColNames %in% names(rawData))){ stop("specified date column does not exist in supplied data frame") } dateColNames <- names(rawData)[names(rawData) %in% allowedDateColNames] dateColNames <- dateColNames[!allowedWYColNames[dateColNames] %in% names(rawData)] for(dateCol in dateColNames){ dateColWY <- allowedWYColNames[dateCol] rawData[[dateColWY]] <- calcWaterYear(rawData[[dateCol]]) dateCol_i <- which(names(rawData) == dateCol) dateColWY_i <- which(names(rawData) == dateColWY) everything_else <- which(!(names(rawData) %in% c(dateCol,dateColWY))) everything_else <- everything_else[!everything_else %in% c(1:dateCol_i, dateColWY_i)] rawData <- rawData[, c(1:dateCol_i, dateColWY_i, everything_else)] } return(rawData) } calcWaterYear <- function(dateVec){ if(is.numeric(dateVec)){ message("dateVec is numeric, with insufficient information to determine water year.") return(rep(NA, length(dateVec))) } dateTimeVec <- tryCatch({ as.POSIXlt(dateVec) }, error = function(e){ date_vec <- tryCatch({ as.Date(dateVec) }, error = function(e){ return(rep(NA, length(dateVec))) }) if(any(is.na(date_vec))){ dateVec <- as.character(dateVec) dateVec[grep("^(\\d{4}-\\d{2}$)", dateVec)] <- paste0(dateVec[grep("^(\\d{4}-\\d{2}$)", dateVec)],"-01") dateVec <- as.Date(dateVec) } dateTimeVec <- as.POSIXlt(dateVec) return(dateTimeVec) }) calYear <- dateTimeVec$year + 1900 calMon <- dateTimeVec$mon + 1 whichPastOct <- calMon >= 10 whichPastOct[is.na(whichPastOct)] <- FALSE waterYear <- calYear waterYear[whichPastOct] <- calYear[whichPastOct] + 1 return(waterYear) }
data(sysdata, envir=environment()) horn.outliers = function (data) { boxcox = car::powerTransform(data); lambda = boxcox$lambda; transData = data^lambda; descriptives = summary(transData); Q1 = descriptives[[2]]; Q3 = descriptives[[5]]; IQR = Q3 - Q1; out = transData[transData <= (Q1 - 1.5*IQR) | transData >= (Q3 + 1.5*IQR)]; sub = transData[transData > (Q1 - 1.5*IQR) & transData < (Q3 + 1.5*IQR)]; return(list(outliers = out^(1/lambda), subset = sub^(1/lambda))); } dixon.outliers = function (data) { d = sort(data); dixResult = outliers::dixon.test(data); pResult = dixResult[[3]]; result = strsplit(dixResult[[2]], " "); if(pResult <= 0.05) { out = result[[1]][3]; if(result[[1]][1] == "highest") { sub = data[data < d[length(d)]]; } else { sub = data[data > d[1]]; } } else { out = as.numeric(c()); sub = data; } return(list(outliers = out, subset = sub)); } cook.outliers = function (data) { fit = lm(data ~ 1); cooks_dist = cooks.distance(fit); out = data[as.numeric(names(cooks_dist[cooks_dist > (4/length(cooks_dist)) | cooks_dist > 1]))]; sub = data[as.numeric(names(cooks_dist[cooks_dist <= (4/length(cooks_dist)) & cooks_dist <= 1]))]; return(list(outliers = out, subset = sub)); } vanderLoo.outliers = function (data) { result = extremevalues::getOutliers(data, method = "I"); indices = c(result$iLeft, result$iRight); out = data[indices]; sub = data[!data %in% out]; return(list(outliers = out, subset = sub)); } robust = function (data, indices = c(1:length(data)), refConf = 0.95) { data = sort(data[indices]); n = length(data); median = summary(data)[[3]]; Tbi = median; TbiNew = 10000; c = 3.7; MAD = summary(abs(data - median))[[3]]; MAD = MAD / 0.6745; smallDiff = FALSE; repeat { ui = (data - Tbi) / (c * MAD); ui[ui < -1] = 1; ui[ui > 1] = 1; wi = (1 - ui^2)^2; TbiNew = (sum(data * wi) / sum(wi)); if(!is.finite(TbiNew) | (abs(TbiNew - Tbi)) < 0.000001){ break; } Tbi = TbiNew; }; ui = NULL; ui = (data - median) / (205.6 * MAD); sbi205.6 = 205.6 * MAD * sqrt((n * sum(((1-ui[ui>-1 & ui<1]^2)^4)*ui[ui>-1 & ui<1]^2)) / (sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)) * max(c(1, -1 + sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)))))); ui = NULL; ui = (data - median) / (3.7 * MAD); sbi3.7 = 3.7 * MAD * sqrt((n * sum(((1-ui[ui>-1 & ui<1]^2)^4)*ui[ui>-1 & ui<1]^2)) / (sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)) * max(c(1, -1 + sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)))))); ui = NULL; ui = (data - Tbi) / (3.7 * sbi3.7); St3.7 = 3.7 * sbi3.7 * sqrt((sum(((1-ui[ui>-1 & ui<1]^2)^4)*ui[ui>-1 & ui<1]^2)) / (sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)) * max(c(1, -1 + sum((1-ui[ui>-1 & ui<1]^2)*(1-5*ui[ui>-1 & ui<1]^2)))))); tStatistic = qt(1 - ((1 - refConf)/2), (n-1)); margin = tStatistic * sqrt(sbi205.6^2 + St3.7^2); robustLower = Tbi - margin; robustUpper = Tbi + margin; RefInterval = c(robustLower, robustUpper); return (RefInterval); } nonparRI = function(data, indices = 1:length(data), refConf = 0.95) { d = data[indices]; results = c(quantile(d, (1 - refConf)/2, type = 6), quantile(d, 1-((1 - refConf)/2), type = 6)); return (results); } refLimit = function(data, out.method = "horn", out.rm = FALSE, RI = "p", CI = "p", refConf = 0.95, limitConf = 0.90, bootStat = "basic"){ cl = class(data); if(cl == "data.frame"){ frameLabels = colnames(data); dname = deparse(substitute(data)); result = lapply(data, singleRefLimit, dname, out.method, out.rm, RI, CI, refConf, limitConf, bootStat); for(i in 1:length(data)){ result[[i]]$dname = frameLabels[i]; } class(result) = "interval"; } else{ frameLabels = NULL; dname = deparse(substitute(data)); result = singleRefLimit(data, dname, out.method, out.rm, RI, CI, refConf, limitConf, bootStat); } return(result); } singleRefLimit = function(data, dname = "default", out.method = "horn", out.rm = FALSE, RI = "p", CI = "p", refConf = 0.95, limitConf = 0.90, bootStat = "basic") { if(out.method == "dixon"){ output = dixon.outliers(data); } else if(out.method == "cook"){ output = cook.outliers(data); } else if(out.method == "vanderLoo"){ output = vanderLoo.outliers(data); } else{ output = horn.outliers(data); } if(out.rm == TRUE){ data = output$subset; } if(!bootStat %in% c("basic", "norm", "perc", "stud", "bca")) { bootStat = "basic"; } outliers = output$outliers; n = length(data); mean = mean(data, na.rm = TRUE); sd = sd(data, na.rm = TRUE); norm = NULL; if(RI == "n"){ methodRI = "Reference Interval calculated nonparametrically"; data = sort(data); holder = nonparRI(data, indices = 1:length(data), refConf); lowerRefLimit = holder[1]; upperRefLimit = holder[2]; if(CI == "p"){ CI = "n"; } } if(RI == "r"){ methodRI = "Reference Interval calculated using Robust algorithm"; holder = robust(data, 1:length(data), refConf); lowerRefLimit = holder[1]; upperRefLimit = holder[2]; CI = "boot"; } if(RI == "p"){ methodRI = "Reference Interval calculated parametrically"; methodCI = "Confidence Intervals calculated parametrically"; refZ = qnorm(1 - ((1 - refConf) / 2)); limitZ = qnorm(1 - ((1 - limitConf) / 2)); lowerRefLimit = mean - refZ * sd; upperRefLimit = mean + refZ * sd; se = sqrt(((sd^2)/n) + (((refZ^2)*(sd^2))/(2*n))); lowerRefLowLimit = lowerRefLimit - limitZ * se; lowerRefUpperLimit = lowerRefLimit + limitZ * se; upperRefLowLimit = upperRefLimit - limitZ * se; upperRefUpperLimit = upperRefLimit + limitZ * se; shap_normalcy = shapiro.test(data); shap_output = paste(c("Shapiro-Wilk: W = ", format(shap_normalcy$statistic, digits = 6), ", p-value = ", format(shap_normalcy$p.value, digits = 6)), collapse = ""); ks_normalcy = suppressWarnings(ks.test(data, "pnorm", m = mean, sd = sd)); ks_output = paste(c("Kolmorgorov-Smirnov: D = ", format(ks_normalcy$statistic, digits = 6), ", p-value = ", format(ks_normalcy$p.value, digits = 6)), collapse = ""); if(shap_normalcy$p.value < 0.05 | ks_normalcy$p.value < 0.05){ norm = list(shap_output, ks_output); } else{ norm = list(shap_output, ks_output); } } if(CI == "n"){ if(n < 120){ cat("\nSample size too small for non-parametric confidence intervals, bootstrapping instead\n"); CI = "boot"; } else{ methodCI = "Confidence Intervals calculated nonparametrically"; ranks = nonparRanks[which(nonparRanks$SampleSize == n),]; lowerRefLowLimit = data[ranks$Lower]; lowerRefUpperLimit = data[ranks$Upper]; upperRefLowLimit = data[(n+1) - ranks$Upper]; upperRefUpperLimit = data[(n+1) - ranks$Lower]; } } if(CI == "boot" & (RI == "n" | RI == "r")){ methodCI = "Confidence Intervals calculated by bootstrapping, R = 5000"; if(RI == "n"){ bootresult = boot::boot(data = data, statistic = nonparRI, refConf = refConf, R = 5000); } if(RI == "r"){ bootresult = boot::boot(data = data, statistic = robust, refConf = refConf, R = 5000); } bootresultlower = boot::boot.ci(bootresult, conf = limitConf, type=bootStat, index = c(1,2)); bootresultupper = boot::boot.ci(bootresult, conf = limitConf, type=bootStat, index = c(2,2)); bootresultlength = length(bootresultlower[[4]]); lowerRefLowLimit = bootresultlower[[4]][bootresultlength - 1]; lowerRefUpperLimit = bootresultlower[[4]][bootresultlength]; upperRefLowLimit = bootresultupper[[4]][bootresultlength - 1]; upperRefUpperLimit = bootresultupper[[4]][bootresultlength]; } RVAL = list(size = n, dname = dname, out.method = out.method, out.rm = out.rm, outliers = outliers, methodRI = methodRI, methodCI = methodCI, norm = norm, refConf = refConf, limitConf = limitConf, Ref_Int = c(lowerRefLimit = lowerRefLimit, upperRefLimit = upperRefLimit), Conf_Int = c(lowerRefLowLimit = lowerRefLowLimit, lowerRefUpperLimit = lowerRefUpperLimit, upperRefLowLimit = upperRefLowLimit, upperRefUpperLimit = upperRefUpperLimit)); class(RVAL) = "interval"; return(RVAL); } print.interval = function (x, digits = 4L, quote = TRUE, prefix = "", ...) { if(class(x[[1]]) == "interval"){ lapply(x, print.interval.sub); } else{ print.interval.sub(x); } } print.interval.sub = function (x, digits = 4L, quote = TRUE, prefix = "", ...) { cat("\n"); cat(strwrap(x$methodRI, prefix = "\t"), sep = "\n"); cat(strwrap(x$methodCI, prefix = "\t"), sep = "\n"); cat("\n"); cat("data: ", x$dname, "\n", sep = ""); cat("N: ", x$size, "\n", sep = ""); if (!is.null(x$refConf)) { cat(format(100 * x$refConf), "% Reference Interval", "\n", sep = ""); } if (!is.null(x$limitConf)) { cat(format(100 * x$limitConf), "% Confidence Intervals\n", "\n", sep = ""); } if (!is.null(x$out.method)) { cat("Outlier detection method:", x$out.method, "\n"); } if (!is.null(x$outliers) & length(x$outliers) > 0) { if(x$out.rm){ cat("Removed outliers: "); } else{ cat("Suspected outliers: "); } cat(strwrap(paste(format(x$outliers, digits = 6), collapse = ", ")), sep = "\n"); } else { cat("No outliers detected\n"); } if (!is.null(x$norm)) { cat(strwrap(x$norm, prefix = "\n"), "\n\n"); } if (!is.null(x$Ref_Int)) { cat("\nReference Interval: "); cat(strwrap(paste(format(x$Ref_Int, digits = 6), collapse = ", ")), sep = "\n"); } if (!is.null(x$Conf_Int)) { cat("Lower Confidence Interval: "); cat(strwrap(paste(format(x$Conf_Int[1:2], digits = 6), collapse = ", ")), sep = "\n"); cat("Upper Confidence Interval: "); cat(strwrap(paste(format(x$Conf_Int[3:4], digits = 6), collapse = ", ")), sep = "\n"); } cat("\n"); invisible(x); } plot.interval = function (x, main = NULL, ...) { original.parameters = par(); if(class(x[[1]]) != "interval"){ range = max(x[["Conf_Int"]][[4]]) - min(x[["Conf_Int"]][[1]]); y_low = min(x[["Conf_Int"]][[1]]) - 0.05 * range; y_high = max(x[["Conf_Int"]][[4]]) + 0.05 * range; plot.new(); plot.window(xlim=c(0,2), ylim=c(y_low,y_high)); segments(1, min(x[["Ref_Int"]]), 1, max(x[["Ref_Int"]]), col = "red"); segments(1-0.05, x[["Conf_Int"]][[1]], 1+0.05, x[["Conf_Int"]][[1]], col = "blue"); segments(1-0.05, x[["Conf_Int"]][[2]], 1+0.05, x[["Conf_Int"]][[2]], col = "blue"); segments(1-0.05, x[["Conf_Int"]][[3]], 1+0.05, x[["Conf_Int"]][[3]], col = "blue"); segments(1-0.05, x[["Conf_Int"]][[4]], 1+0.05, x[["Conf_Int"]][[4]], col = "blue"); axis(1, at=1:1, labels=x[["dname"]]); axis(2); if(!is.null(main)){ title(main = main); } else { title(main="Reference Range"); } title(xlab="Parameter"); title(ylab="Units"); legend("topright", col = c("red", "blue"), lty = 1, inset = c(0, -0.09), legend = c("Reference Interval", "Confidence Interval"), cex = 0.6, xpd = TRUE); box(); } if(class(x[[1]]) == "interval"){ numRanges = length(x); intervals = unlist(sapply(x, "[", "Conf_Int")); labels = unlist(sapply(x, "[", "dname")); range = max(intervals) - min(intervals); y_low = min(intervals) - 0.05 * range; y_high = max(intervals) + 0.05 * range; plot.new(); plot.window(xlim=c(0,numRanges + 1), ylim=c(y_low,y_high)); for(i in 1:numRanges){ segments(i, x[[i]]$Ref_Int[1], i, x[[i]]$Ref_Int[2], col = "red"); segments(i-0.05, x[[i]]$Conf_Int[[1]], i+0.05, x[[i]]$Conf_Int[[1]], col = "blue"); segments(i-0.05, x[[i]]$Conf_Int[[2]], i+0.05, x[[i]]$Conf_Int[[2]], col = "blue"); segments(i-0.05, x[[i]]$Conf_Int[[3]], i+0.05, x[[i]]$Conf_Int[[3]], col = "blue"); segments(i-0.05, x[[i]]$Conf_Int[[4]], i+0.05, x[[i]]$Conf_Int[[4]], col = "blue"); } axis(1, at=1:numRanges, labels = FALSE); text(x = seq(1, numRanges, by=1), par("usr")[3] - 0.2, labels = labels, cex = 0.75, srt = 90, pos = 1, offset = 2, xpd = TRUE); axis(2); if(!is.null(main)){ title(main = main); } else { title(main="Reference Range"); } title(xlab="Parameter"); title(ylab="Units"); legend("topright", col = c("red", "blue"), lty = 1, inset = c(0, -0.09), legend = c("Reference Interval", "Confidence Interval"), cex = 0.6, xpd = TRUE); box(); } par(original.parameters[-c(13, 19, 21:23, 54)]); }
context("Base image helper functions") test_that("Installed packages can be read from a Docker image", { skip_if_not(stevedore::docker_available()) output <- capture_output(pkgs <- get_installed_packages(image = "rocker/geospatial:3.4.4")) expect_equal(dim(pkgs), c(257,2)) expect_true("sf" %in% pkgs$pkg) expect_true("maps" %in% pkgs$pkg) expect_true("rgeos" %in% pkgs$pkg) expect_true("maptools" %in% pkgs$pkg) expect_false("adehabitatLT" %in% pkgs$pkg) expect_false("cshapes" %in% pkgs$pkg) }) test_that("Installed packages are a data.frame with the image as an attribute", { skip_if_not(stevedore::docker_available()) .image <- "rocker/geospatial:3.4.4" output <- capture_output(pkgs <- get_installed_packages(image = .image)) expect_s3_class(pkgs, "data.frame") expect_true("image" %in% names(attributes(pkgs))) expect_equal(.image, attributes(pkgs)$image) }) packages_df <- data.frame(name = c("sp", "ggplot2", "rgdal", "coxrobust"), version = c("10.10.10", "tidyverse/ggplot2@abcdef", "3", "0"), source = c("CRAN", "github", "CRAN", "CRAN"), stringsAsFactors = FALSE) test_that("List of installed packages can be filtered when creating a Dockerfile", { skip_if_not(stevedore::docker_available()) output <- capture_output(the_dockerfile <- dockerfile(from = "package_markdown/sfr/", maintainer = "o2r", image = "rocker/geospatial:3.6.0", filter_baseimage_pkgs = TRUE)) the_dockerfile_string <- toString(the_dockerfile) expect_true(object = any(grepl(" expect_true(object = any(grepl("^ unlink("package_markdown/sfr/nc1.*") unlink("package_markdown/sfr/*.html") unlink("package_markdown/sfr/sf2_files", recursive = TRUE) }) test_that("Filtered list of installed packages does not filter GitHub packages", { skip_if_not(stevedore::docker_available()) output <- capture_output(the_dockerfile <- dockerfile(from = packages_df, maintainer = "o2r", image = "rocker/geospatial:3.5.1", filter_baseimage_pkgs = TRUE)) the_dockerfile_string <- toString(the_dockerfile) expect_false(object = any(grepl("^ expect_true(object = any(grepl("^RUN.*installGithub.*tidyverse/ggplot2", x = the_dockerfile_string)), info = "ggplot is in installGithub command") }) test_that("Filtered list of installed packages is alphabetical", { skip_if_not(stevedore::docker_available()) output <- capture_output(the_dockerfile <- dockerfile(from = packages_df, maintainer = "o2r", image = "rocker/geospatial:3.5.1", filter_baseimage_pkgs = TRUE)) expect_true(object = any(grepl("^ }) test_that("System dependencies of filtered packages are not installed", { skip_if_not(stevedore::docker_available()) output <- capture_output(the_dockerfile <- dockerfile(from = packages_df, maintainer = "o2r", image = "rocker/geospatial:3.6.0", filter_baseimage_pkgs = TRUE)) expect_false(object = any(grepl(".*gdal-bin.*", x = toString(the_dockerfile)))) })
is.claiminfo <- function(x) { inherits(x, 'claiminfo') }
trainMaxnet <- function(data, reg = 1, fc = "lqph") { result <- SDMmodel(data = data) x <- data@data p <- data@pa model <- maxnet::maxnet(p, x, f = maxnet::maxnet.formula(p, x, classes = fc), regmult = reg, addsamplestobackground = FALSE) model_object <- Maxnet(reg = reg, fc = fc, model = model) result@model <- model_object return(result) }
downloadTau <- function(subtype="paper") { settings <- list( paper = list( title = "Tau Factor (cellular, crop-specific)", description = "Cellular (0.5deg), crop-specific land use intensity (tau) for 1995 and 2000", url = "https://zenodo.org/record/4282581/files/tau-paper.zip", doi = "10.5281/zenodo.4282581"), historical = list( title = "Tau Factor (historic trends)", description = "Historic land use intensity (tau) development", url = "https://zenodo.org/record/4282548/files/tau-historical.zip", doi = "10.5281/zenodo.4282548")) meta <- toolSubtypeSelect(subtype,settings) download.file(meta$url, destfile = "tau.zip", quiet = testthat::is_testing()) unzip("tau.zip") unlink("tau.zip") return(list(url = meta$url, doi = meta$doi, title = meta$title, description = meta$description, author = person("Jan Philipp","Dietrich", email="[email protected]", comment="https://orcid.org/0000-0002-4309-6431"), unit = "1", version = "1.0", release_date = "2012-05-10", license = "Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0)", reference = bibentry("Article", title="Measuring agricultural land-use intensity - A global analysis using a model-assisted approach", author=c(person("Jan Philipp","Dietrich", email="[email protected]", comment="https://orcid.org/0000-0002-4309-6431"), person("Christoph","Schmitz"), person("Christoph","Mueller"), person("Marianela","Fader"), person("Hermann","Lotze-Campen"), person("Alexander","Popp")), year="2012", journal="Ecological Modelling", volume="232", pages="109-118", url="https://doi.org/10.1016/j.ecolmodel.2012.03.002", doi="10.1016/j.ecolmodel.2012.03.002")) ) }
k <- function(z,h=1,type="gaussian") { u <- z/h if (type=="gaussian") { dnorm(u)*(abs(u)<=1) } else if (type=="epanechnikov") { 0.75*(1-u^2)*(abs(u)<=1) } } G <- function(z) { vapply(z, FUN=function(x) { if (exp(x) == Inf) { return(1) } else { exp(x)/(1+exp(x)) } }, 1.0) } dg <- function(z) { exp(z)/((1+exp(z))^2) } wll <- function(bet,y,x,thisx,h) { idx <- bet[1] + bet[2]*x -sum( (y*log(G(idx)) + log((1-G(idx)))*(1-y)) * k(x-thisx,h) ) } wscore <- function(bet,y,x,thisx,h) { idx <- bet[1] + bet[2]*x X <- cbind(1,x) kh <- k(x-thisx,h) ( ( as.numeric(y*(dg(idx)/G(idx))) - (1-y)*(dg(idx)/(1-G(idx))) )*kh )*X } wgr <- function(bet,y,x,thisx,h) { colSums(-wscore(bet,y,x,thisx,h)) } F.Y1 <- function(ytmin1, y.seq, Y1t, Y0tmin1, h=NULL, method="level") { n <- length(Y1t) if (method=="rank") { Y0tmin1 <- order(Y0tmin1)/n } X <- cbind(1, Y0tmin1-ytmin1) if (is.null(h)) { h <- 1.06*sd(Y0tmin1)*n^(-1/4) } K <- diag(k(Y0tmin1 - ytmin1,h), n, n) Fy1tcondy0tmin1.vals <- vapply(y.seq, FUN=function(y) { IY <- 1*(Y1t <= y) o <- optim(c(0,0), wll, gr=wgr, y=IY, x=(Y0tmin1-ytmin1), thisx=0, h=h, control=list(maxit=1000, reltol=1e-2), method="BFGS") thet <- o$par G(thet[1]) } , 1.0) Fy1tcondy0tmin1.vals <- Fy1tcondy0tmin1.vals[order(Fy1tcondy0tmin1.vals)] BMisc::makeDist(y.seq, Fy1tcondy0tmin1.vals, TRUE) } F.Y0 <- function(ytmin1, y.seq, Y0tmin1, Y0tmin2, Y0tqteobj, h=NULL, method="level") { ddid <- Y0tqteobj n <- length(Y0tmin1) if (method=="rank") { Y0tmin2 <- order(Y0tmin2)/n xtmin1 <- ytmin1 } else { xtmin1 <- quantile(ddid$F.treated.tmin2, probs=ddid$F.treated.tmin1(ytmin1), type=1) } X <- cbind(1, Y0tmin2-xtmin1) if (is.null(h)) { h <- 1.06*sd(Y0tmin2)*n^(-1/4) } K <- diag(k(Y0tmin2-xtmin1, h), n, n) Fy0tcondy0tmin1.vals <- vapply(y.seq, FUN=function(y) { Z <- 1*(Y0tmin1 <= quantile(ddid$F.treated.tmin1, probs=ddid$F.treated.t.cf(y), type=1)) o <- optim(c(0,0), wll, gr=wgr, y=Z, x=(Y0tmin2-xtmin1), thisx=0, h=h, control=list(maxit=1000, reltol=1e-2), method="BFGS") thet <- o$par G(thet[1]) } , 1.0) Fy0tcondy0tmin1.vals <- Fy0tcondy0tmin1.vals[order(Fy0tcondy0tmin1.vals)] BMisc::makeDist(y.seq, Fy0tcondy0tmin1.vals, TRUE) } l.inner <- function(y, ytmin1, delt, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { i <- which(ytmin1.seq==ytmin1)[1] max(F.y1[[i]](y) - F.y0[[i]](y-delt),0) } l.ytmin1 <- function(ytmin1, delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { max(vapply(y.seq, l.inner, 1.0, ytmin1, delt, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0)) } l <- function(delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { mean(vapply(Y0tmin1, l.ytmin1, 1.0, delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0)) } u.inner <- function(y, ytmin1, delt, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { i <- which(ytmin1.seq==ytmin1)[1] 1 + min((F.y1[[i]](y) - F.y0[[i]](y-delt)),0) } u.ytmin1 <- function(ytmin1, delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { min(vapply(y.seq, u.inner, 1.0, ytmin1, delt, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0)) } u <- function(delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0) { mean(vapply(Y0tmin1, u.ytmin1, 1.0, delt, y.seq, ytmin1.seq, Y1t, Y0tmin1, Y0tmin2, Y0tqteobj, F.y1, F.y0)) } wd.l.inner <- function(y, delt, Y1t, Y0tqteobj) { max(ecdf(Y1t)(y) - Y0tqteobj$F.treated.t.cf(y-delt),0) } wd.l <- function(delt, y.seq, Y1t, ddid) { max(vapply(y.seq, wd.l.inner, 1.0, delt, Y1t, ddid)) } wd.u.inner <- function(y, delt, Y1t, ddid) { 1 + min(ecdf(Y1t)(y) - ddid$F.treated.t.cf(y-delt),0) } wd.u <- function(delt, y.seq, Y1t, ddid) { min(vapply(y.seq, wd.u.inner, 1.0, delt, Y1t, ddid)) } csa.bounds <- function(formla, t, tmin1, tmin2, tname, idname, data, delt.seq, y.seq, Y0tqteobj, F.y0=NULL, F.y1=NULL, h=NULL, method=c("level","rank"), cl=1) { form <- as.formula(formla) dta <- model.frame(terms(form,data=data),data=data) colnames(dta) <- c("y","treat") data <- cbind.data.frame(dta,data) data <- subset(data, treat==1) Y1t <- data[data[,tname]==t,]$y Y0tmin1 <- data[data[,tname]==tmin1,]$y Y0tmin2 <- data[data[,tname]==tmin2,]$y n <- length(Y1t) ytmin1.seq <- Y0tmin1 ytmin1.seq <- ytmin1.seq[order(ytmin1.seq)] if (method=="rank") { ytmin1.seq <- order(ytmin1.seq)/length(ytmin1.seq) } print("Step 1 of 4: Calculating conditional distribution of treated potential outcomes...") if (is.null(F.y1)) { F.y1 <- pbapply::pblapply(ytmin1.seq, F.Y1, y.seq, Y1t, Y0tmin1, h=h, method=method, cl=cl) } print("Step 2 of 4: Calculating conditional distribution of untreated potential outcomes...") if (is.null(F.y0)) { F.y0 <- pbapply::pblapply(ytmin1.seq, F.Y0, y.seq, Y0tmin1, Y0tmin2, Y0tqteobj, h=h, method=method, cl=cl) } if (method=="rank") { Y0tmin1r <- order(Y0tmin1)/length(Y0tmin1) } else { Y0tmin1r <- Y0tmin1 } print("Step 3 of 4: Calculating lower bound") l.vec <- pbapply::pblapply(delt.seq, l, y.seq, ytmin1.seq, Y1t, Y0tmin1r, Y0tmin2, Y0tqteobj, F.y1, F.y0, cl=cl) l.vec <- unlist(l.vec) print("Step 4 of 4: Calculating upper bound") u.vec <- pbapply::pblapply(delt.seq, u, y.seq, ytmin1.seq, Y1t, Y0tmin1r, Y0tmin2, Y0tqteobj, F.y1, F.y0, cl=cl) u.vec <- unlist(u.vec) F.l <- BMisc::makeDist(delt.seq, l.vec) F.u <- BMisc::makeDist(delt.seq, u.vec) wd.l.vec <- vapply(delt.seq, wd.l, 1.0, y.seq, Y1t, Y0tqteobj) wd.u.vec <- vapply(delt.seq, wd.u, 1.0, y.seq, Y1t, Y0tqteobj) F.wd.l <- BMisc::makeDist(delt.seq, wd.l.vec) F.wd.u <- BMisc::makeDist(delt.seq, wd.u.vec) return(list(F.l=F.l, F.u=F.u, F.wd.l=F.wd.l, F.wd.u=F.wd.u)) } ggCSABounds <- function(csaboundsobj, tau=seq(.05,.95,.05), wdbounds=FALSE, otherdist1=NULL, otherdist2=NULL) { tau <- seq(0.05, 0.95, .05) c <- csaboundsobj qu <- quantile(c$F.l, tau, type=1) ql <- quantile(c$F.u, tau, type=1) qwdu <- quantile(c$F.wd.l, tau, type=1) qwdl <- quantile(c$F.wd.u, tau, type=1) cmat <- data.frame(tau=tau, qu=qu, ql=ql, group="CSA Bounds") cmat2 <- data.frame(tau=tau, qu=qwdu, ql=qwdl, group="WD Bounds") if (wdbounds) { cmat <- rbind.data.frame(cmat2, cmat) } if (!is.null(otherdist1)) { cmat3 <- data.frame(tau=tau, qu=quantile(otherdist1, tau, type=1), ql=ql, group="CS PPD") cmat <- rbind.data.frame(cmat3, cmat) } if (!is.null(otherdist2)) { cmat4 <- data.frame(tau=tau, qu=quantile(otherdist2, tau, type=1), ql=ql, group="Panel PPD") cmat <- rbind.data.frame(cmat4, cmat) } p <- ggplot(data=cmat) + geom_line(aes(x=tau, y=qu, color=factor(group)), size=1) + geom_line(aes(x=tau, y=ql, color=factor(group)), size=1) + scale_x_continuous(limits=c(0,1)) + theme_bw() + theme(legend.title=element_blank()) p }
NULL reduce_common <- function(x, msg = "Objects must be identical", operator = identical) { reduce(x, function(.x, .y) { if (!operator(.x, .y)) { stop(msg, call. = FALSE) } .y }) } has_name <- function(x) { nms <- names(x) if (is.null(nms)) { rep(FALSE, length(x)) } else { !(is.na(nms) | nms == "") } } big_mark <- function(x, ...) { mark <- if (identical(getOption("OutDec"), ",")) "." else "," formatC(x, big.mark = mark, ...) } id <- function(n) { width <- nchar(n) sprintf(paste0("%0", width, "d"), seq_len(n)) }
setMethod(f='get.problemInstance', signature=c('problemInstance', 'character'), definition=function(object, type) { if ( !type %in% c('strID', 'nrVars', 'freq', 'w', 'numVars', 'sdcStatus', 'lb', 'ub', 'LPL', 'SPL', 'UPL', 'primSupps', 'secondSupps', 'forcedCells', 'hasPrimSupps', 'hasSecondSupps', 'hasForcedCells', 'weight', 'suppPattern') ) { stop("get.problemInstance:: argument 'type' is not valid!\n") } if ( type == 'strID' ) { return(g_strID(object)) } if ( type == 'nrVars' ) { return(g_nrVars(object)) } if ( type == 'freq' ) { return(g_freq(object)) } if ( type == 'w' ) { return(g_w(object)) } if ( type == 'numVars' ) { return(g_numVars(object)) } if ( type == 'sdcStatus' ) { return(g_sdcStatus(object)) } if ( type == 'lb' ) { return(g_lb(object)) } if ( type == 'ub' ) { return(g_ub(object)) } if ( type == 'LPL' ) { return(g_LPL(object)) } if ( type == 'UPL' ) { return(g_UPL(object)) } if ( type == 'SPL' ) { return(g_SPL(object)) } if ( type == 'primSupps' ) { return(g_primSupps(object)) } if ( type == 'secondSupps' ) { return(g_secondSupps(object)) } if ( type == 'forcedCells' ) { return(g_forcedCells(object)) } if ( type == 'hasPrimSupps' ) { return(g_hasPrimSupps(object)) } if ( type == 'hasSecondSupps' ) { return(g_hasSecondSupps(object)) } if ( type == 'hasForcedCells' ) { return(g_hasForcedCells(object)) } if ( type == 'weight' ) { return(g_weight(object)) } if ( type == 'suppPattern' ) { return(g_suppPattern(object)) } } ) setMethod(f='set.problemInstance', signature=c('problemInstance', 'character', 'list'), definition=function(object, type, input) { index <- input[[1]] values <- input[[2]] if ( !type %in% c('lb', 'ub', 'LPL', 'UPL', 'SPL', 'sdcStatus') ) { stop("set.problemInstance:: check argument 'type'!\n" ) } if ( !is.null(index) & length(values) != length(index) ) { stop("set.problemInstance:: arguments 'values' and 'index' differ in length!\n") } if ( !all(index %in% 1:g_nrVars(object)) ) { stop("set.problemInstance:: argument 'index' does not fit to given problem!\n") } if ( type == 'lb' ) { s_lb(object) <- list(index=index, vals=values) } if ( type == 'ub' ) { s_ub(object) <- list(index=index, vals=values) } if ( type == 'LPL' ) { s_LPL(object) <- list(index=index, vals=values) } if ( type == 'UPL' ) { s_UPL(object) <- list(index=index, vals=values) } if ( type == 'SPL' ) { s_SPL(object) <- list(index=index, vals=values) } if ( type == 'sdcStatus' ) { s_sdcStatus(object) <- list(index=index, vals=values) } object } ) setMethod(f='calc.problemInstance', signature=c('problemInstance', 'character','list'), definition=function(object, type, input) { if ( !type %in% c('makeMasterProblem', 'isProtectedSolution') ) { stop("calc.problemInstance:: check argument 'type'!\n" ) } if ( type == 'makeMasterProblem' ) { return(c_make_masterproblem(object, input)) } if ( type == 'isProtectedSolution' ) { return(c_is_protected_solution(object, input)) } } ) setMethod("g_sdcStatus", signature="problemInstance", definition=function(object) { object@sdcStatus }) setMethod("g_primSupps", signature="problemInstance", definition=function(object) { which(g_sdcStatus(object)=="u") }) setMethod("g_secondSupps", signature="problemInstance", definition=function(object) { which(g_sdcStatus(object)=="x") }) setMethod("g_forcedCells", signature="problemInstance", definition=function(object) { which(g_sdcStatus(object)=="z") }) setMethod("g_type", signature="problemInstance", definition=function(object) { object@type }) setMethod("g_freq", signature="problemInstance", definition=function(object) { object@Freq }) setMethod("g_strID", signature="problemInstance", definition=function(object) { object@strID }) setMethod("g_UPL", signature="problemInstance", definition=function(object) { object@UPL }) setMethod("g_LPL", signature="problemInstance", definition=function(object) { object@LPL }) setMethod("g_SPL", signature="problemInstance", definition=function(object) { object@SPL }) setMethod("g_nrVars", signature="problemInstance", definition=function(object) { length(g_strID(object)) }) setMethod("g_lb", signature="problemInstance", definition=function(object) { object@lb }) setMethod("g_ub", signature="problemInstance", definition=function(object) { object@ub }) setMethod("g_w", signature="problemInstance", definition=function(object) { object@w }) setMethod("g_numVars", signature="problemInstance", definition=function(object) { object@numVars }) setMethod("g_hasPrimSupps", signature="problemInstance", definition=function(object) { return(length(g_primSupps(object)) > 0) }) setMethod("g_hasSecondSupps", signature="problemInstance", definition=function(object) { return(length(g_secondSupps(object)) > 0) }) setMethod("g_hasForcedCells", signature="problemInstance", definition=function(object) { return(length(g_forcedCells(object)) > 0) }) setMethod("g_weight", signature="problemInstance", definition=function(object) { wg <- g_w(object) if ( !is.null(wg) ) { return(wg) } else { return(g_freq(object)) } }) setMethod("g_suppPattern", signature="problemInstance", definition=function(object) { suppPattern <- rep(0, g_nrVars(object)) if ( g_hasPrimSupps(object) ) { suppPattern[g_primSupps(object)] <- 1 } secondSupps <- g_secondSupps(object) if ( length(secondSupps) > 0 ) { suppPattern[secondSupps] <- 1 } return(suppPattern) }) setReplaceMethod("s_sdcStatus", signature=c("problemInstance", "list"), definition=function(object, value) { sdcStatus <- g_sdcStatus(object) index <- value$index values <- value$vals if ( length(values) > length(sdcStatus) ) { stop("s_sdcStatus:: length of 'sdcVec' must be <=",length(sdcStatus),"\n") } if ( is.null(index) ) { indexVec <- 1:length(sdcStatus) if ( length(values) != length(sdcStatus) ) { stop("s_sdcStatus:: length of 'values' must be ==",length(sdcStatus), "if 'index' is NULL!\n") } object@sdcStatus[indexVec] <- values } if ( !is.null(index) ) { if ( !all(index %in% 1:length(sdcStatus)) ) { stop("s_sdcStatus:: elements of 'index' must be in 1:",length(sdcStatus),"!\n") } object@sdcStatus[index] <- values } validObject(object) object }) setReplaceMethod("s_lb", signature=c("problemInstance", "list"), definition=function(object, value) { object@lb[value$index] <- value$vals validObject(object) object }) setReplaceMethod("s_ub", signature=c("problemInstance", "list"), definition=function(object, value) { object@ub[value$index] <- value$vals validObject(object) object }) setReplaceMethod("s_LPL", signature=c("problemInstance", "list"), definition=function(object, value) { object@LPL[value$index] <- value$vals validObject(object) object }) setReplaceMethod("s_UPL", signature=c("problemInstance", "list"), definition=function(object, value) { object@UPL[value$index] <- value$vals validObject(object) object }) setReplaceMethod("s_SPL", signature=c("problemInstance", "list"), definition=function(object, value) { object@SPL[value$index] <- value$vals validObject(object) object }) setMethod("c_make_masterproblem", signature=c("problemInstance", "list"), definition=function(object, input) { mProb <- NULL if ( g_hasPrimSupps(object) ) { objective <- g_weight(object) primSupps <- g_primSupps(object) nrVars <- g_nrVars(object) M <- init.simpleTriplet(type='simpleTriplet', input=list(mat=matrix(0, nrow=0, ncol=nrVars))) direction <- rep("==", g_nr_rows(M)) rhs <- rep(1, g_nr_rows(M)) if ( g_hasForcedCells(object) ) { forcedCells <- g_forcedCells(object) if ( length(forcedCells) > 0 ) { for ( i in seq_along(forcedCells) ) { M <- c_add_row(M, input=list(index=forcedCells[i], values=1)) } direction <- c(direction, rep("==", length(forcedCells))) rhs <- c(rhs, rep(0, length(forcedCells))) } } types <- rep("C", nrVars) boundsLower <- list(ind=1:nrVars, val=rep(0, nrVars)) boundsUpper <- list(ind=1:nrVars, val=rep(1, nrVars)) if ( length(primSupps) > 0 ) { boundsLower$val[primSupps] <- 1 } mProb <- new("linProb", objective=objective, constraints=M, direction=direction, rhs=rhs, boundsLower=boundsLower, boundsUpper=boundsUpper, types=types) } return(mProb) }) setMethod("c_is_protected_solution", signature=c("problemInstance", "list"), definition=function(object, input) { input1 <- input$input1 input2 <- input$input2 primSupps <- g_primSupps(object) if ( length(input1) != length(input2) ) { stop("c_is_protected_solution:: parameters 'input1 (~limitsDown)' and 'input2 (~limitsUp)' differ in length!\n") } if ( length(input1) != length(primSupps) ) { stop("c_is_protected_solution:: parameter 'limits.x' and length of primary suppressed cells differ!\n") } protected <- TRUE weights <- g_weight(object)[primSupps] limits <- list() limits$LPL <- g_LPL(object)[primSupps] limits$UPL <- g_UPL(object)[primSupps] limits$SPL <- g_SPL(object)[primSupps] if ( any(weights - input1 < limits[[1]]) == TRUE ) { protected <- FALSE } if ( any(input2 - weights < limits[[2]]) == TRUE ) { protected <- FALSE } if ( any(input2 - input1 < limits[[3]]) == TRUE ) { protected <- FALSE } return(protected) })
rboTopics = function(topics, k, p, progress = TRUE, pm.backend, ncpus){ assert_matrix(topics, mode = "integerish", any.missing = FALSE, col.names = "strict", min.cols = 2, min.rows = 2) assert_integerish(topics, lower = 0, any.missing = FALSE) assert_flag(progress) assert_number(p, lower = .Machine$double.eps, upper = 1 - .Machine$double.eps) assert_int(k, lower = 0, upper = nrow(topics)) if (missing(ncpus)) ncpus = NULL if (!missing(pm.backend) && !is.null(pm.backend)){ rboTopics.parallel(topics = topics, k = k, p = p, pm.backend = pm.backend, ncpus = ncpus) }else{ rboTopics.serial(topics = topics, k = k, p = p, progress = progress) } } rboTopics.parallel = function(topics, k, p, pm.backend, ncpus){ assert_choice(pm.backend, choices = c("multicore", "socket", "mpi")) if (missing(ncpus) || is.null(ncpus)) ncpus = future::availableCores() assert_int(ncpus, lower = 1) N = ncol(topics) if(ncpus > N-2){ ncpus = N-2 message("The selected number of cores exceeds the parallelizable complexity of the task, set ncpus to ", ncpus, ".") } if(ncpus == 1){ message("There is only one core on the running system or one core selected, falling back to serial version.") rboTopics.serial(topics = topics, k = k, p = p) } ranks = apply(-topics, 2, frank, ties.method = "min") parallelMap::parallelStart(mode = pm.backend, cpus = ncpus) fun = function(s){ lapply(s, function(i){ tmp = do.call(rbind, lapply(1:k, function(d){ tmp1 = ranks[,i] < d+1 tmp2 = ranks[,(i+1):N] < d+1 2 * colSums(tmp1&tmp2) / (sum(tmp1)+colSums(tmp2)) * p^d })) tmp[k,] + colSums(tmp) * (1-p) / p }) } parallelMap::parallelExport("ranks", "N") sequences = lapply(seq_len(max(ncpus, 2)), function(x) seq(x, N-2, max(ncpus, 2))) val = parallelMap::parallelMap(fun = fun, sequences) parallelMap::parallelStop() rearrangedlist = list() for (i in seq_along(sequences)){ rearrangedlist[sequences[[i]]] = val[[i]] } rm(val) sims = matrix(nrow = N, ncol = N) colnames(sims) = rownames(sims) = colnames(topics) tmp = sapply(1:k, function(d){ tmp1 = ranks[,N-1] < d+1 tmp2 = ranks[,N] < d+1 2 * sum(tmp1&tmp2) / (sum(tmp1)+sum(tmp2)) * p^d }) sims[lower.tri(sims)] = c(unlist(rearrangedlist), tmp[k] + sum(tmp) * (1-p) / p) wordsconsidered = colSums(ranks < k+1) res = list(sims = sims, wordslimit = wordsconsidered, wordsconsidered = wordsconsidered, param = list(type = "RBO Similarity", k = k, p = p)) class(res) = "TopicSimilarity" res } rboTopics.serial = function(topics, k, p, progress = TRUE){ N = ncol(topics) ranks = apply(-topics, 2, frank, ties.method = "min") sims = matrix(nrow = N, ncol = N) colnames(sims) = rownames(sims) = colnames(topics) pb = .makeProgressBar(progress = progress, total = N-1, format = "Calculate Similarities [:bar] :percent eta: :eta") for(i in seq_len(N - 2)){ tmp = do.call(rbind, lapply(1:k, function(d){ tmp1 = ranks[,i] < d+1 tmp2 = ranks[,(i+1):N] < d+1 2 * colSums(tmp1&tmp2) / (sum(tmp1)+colSums(tmp2)) * p^d })) sims[(i+1):N,i] = tmp[k,] + colSums(tmp) * (1-p) / p pb$tick() } tmp = sapply(1:k, function(d){ tmp1 = ranks[,N-1] < d+1 tmp2 = ranks[,N] < d+1 2 * sum(tmp1&tmp2) / (sum(tmp1)+sum(tmp2)) * p^d }) sims[N, N-1] = tmp[k] + sum(tmp) * (1-p) / p pb$tick() wordsconsidered = colSums(ranks < k+1) res = list(sims = sims, wordslimit = wordsconsidered, wordsconsidered = wordsconsidered, param = list(type = "RBO Similarity", k = k, p = p)) class(res) = "TopicSimilarity" res }
REaptU<-function(custo,nand,aptand){ resultado=custo/(nand*aptand) return(resultado) }
context("test-editions") test_that("editions works", { skip_on_cran() options("gu.API.key" = "test") eds <- gu_editions() expect_true(tibble::is_tibble(eds)) expect_true("AU" %in% eds$edition) uk_ed <- gu_editions("UK") expect_true(tibble::is_tibble(uk_ed)) expect_true("UK" %in% uk_ed$edition) expect_equal(nrow(uk_ed), 1) uk_ed2 <- gu_editions("uk") expect_equal(uk_ed, uk_ed2) int_ed <- gu_editions("international") expect_true(tibble::is_tibble(int_ed)) expect_true("International" %in% int_ed$edition) expect_equal(nrow(int_ed), 1) })
AutoH2oGBMClassifier <- function(OutputSelection = c("EvalMetrics", "PDFs", "Score_TrainData"), data = NULL, TrainOnFull = FALSE, ValidationData = NULL, TestData = NULL, TargetColumnName = NULL, FeatureColNames = NULL, WeightsColumn = NULL, MaxMem = {gc();paste0(as.character(floor(as.numeric(system("awk '/MemFree/ {print $2}' /proc/meminfo", intern=TRUE)) / 1000000)),"G")}, NThreads = max(1L, parallel::detectCores()-2L), model_path = NULL, metadata_path = NULL, ModelID = "FirstModel", NumOfParDepPlots = 3L, ReturnModelObjects = TRUE, SaveModelObjects = FALSE, SaveInfoToPDF = FALSE, IfSaveModel = "mojo", H2OShutdown = FALSE, H2OStartUp = TRUE, DebugMode = FALSE, GridStrategy = "Cartesian", MaxRunTimeSecs = 60*60*24, StoppingRounds = 10, MaxModelsInGrid = 2, eval_metric = "auc", CostMatrixWeights = c(1,0,0,1), Trees = 50L, GridTune = FALSE, LearnRate = 0.10, LearnRateAnnealing = 1, Distribution = "bernoulli", MaxDepth = 20, SampleRate = 0.632, ColSampleRate = 1, ColSampleRatePerTree = 1, ColSampleRatePerTreeLevel = 1, MinRows = 1, NBins = 20, NBinsCats = 1024, NBinsTopLevel = 1024, HistogramType = "AUTO", CategoricalEncoding = "AUTO") { if(DebugMode) print("Args check ----") Decreasing <- H2OArgsCheck(ModelType="gbm", TargetType = "classification", model_path.=model_path, metadata_path.=metadata_path, eval_metric.=eval_metric, MaxModelsInGrid.=MaxModelsInGrid, ModelID.=ModelID, NumOfParDepPlots.=NumOfParDepPlots, ReturnModelObjects.=ReturnModelObjects, SaveModelObjects.=SaveModelObjects, GridTune.=GridTune, GridStrategy.=GridStrategy, CostMatrixWeights.=CostMatrixWeights, IfSaveModel.=IfSaveModel, Trees.=Trees, MaxDepth.=MaxDepth, SampleRate.=SampleRate, MTries.=MTries, ColSampleRatePerTree.=ColSampleRatePerTree, ColSampleRatePerTreeLevel.=ColSampleRatePerTreeLevel, MinRows.=MinRows, NBins.=NBins, NBinsCats.=NBinsCats, NBinsTopLevel.=NBinsTopLevel, HistogramType.=HistogramType, CategoricalEncoding.=CategoricalEncoding) ArgsList <- c(as.list(environment())) ArgsList[['data']] <- NULL ArgsList[['ValidationData']] <- NULL ArgsList[['TestData']] <- NULL if(SaveModelObjects) { if(!is.null(metadata_path)) { save(ArgsList, file = file.path(metadata_path, paste0(ModelID, "_ArgsList.Rdata"))) } else if(!is.null(model_path)) { save(ArgsList, file = file.path(model_path, paste0(ModelID, "_ArgsList.Rdata"))) } } if(DebugMode) print("Data Prepare ----") Output <- H2ODataPrep(TargetType.="classifier", TargetColumnName.=TargetColumnName, data.=data, ValidationData.=ValidationData, TestData.=TestData, TrainOnFull.=TrainOnFull, FeatureColNames.=FeatureColNames, SaveModelObjects.=SaveModelObjects, model_path.=model_path, ModelID.=ModelID) TargetColumnName <- Output$TargetColumnName; Output$TargetColumnName <- NULL dataTrain <- Output$dataTrain; Output$dataTrain <- NULL dataTest <- Output$dataTest; Output$dataTest <- NULL TestData <- Output$TestData; Output$TestData <- NULL Names <- Output$Names; rm(Output) if(GridTune & !TrainOnFull) { if(DebugMode) print("Grid tune ----") if(H2OStartUp) localHost <- h2o::h2o.init(nthreads = NThreads, max_mem_size = MaxMem, enable_assertions = FALSE) datatrain <- h2o::as.h2o(dataTrain) if(!TrainOnFull) datavalidate <- h2o::as.h2o(dataTest, use_datatable = TRUE) else datavalidate <- NULL if(!is.null(TestData)) datatest <- h2o::as.h2o(TestData, use_datatable = TRUE) else datatest <- NULL search_criteria <- list( strategy = GridStrategy, max_runtime_secs = MaxRunTimeSecs, max_models = MaxModelsInGrid, seed = 1234, stopping_rounds = StoppingRounds, stopping_metric = toupper(eval_metric), stopping_tolerance = 1e-3) hyper_params <- list() hyper_params[["ntrees"]] <- Trees hyper_params[["max_depth"]] <- MaxDepth hyper_params[["learn_rate"]] <- LearnRate hyper_params[["learn_rate_annealing"]] <- LearnRateAnnealing hyper_params[["sample_rate"]] <- SampleRate hyper_params[["col_sample_rate"]] <- ColSampleRate hyper_params[["col_sample_rate_per_tree"]] <- ColSampleRatePerTree hyper_params[["col_sample_rate_change_per_level"]] <- ColSampleRatePerTreeLevel hyper_params[["min_rows"]] <- MinRows hyper_params[["nbins"]] <- NBins hyper_params[["nbins_cats"]] <- NBinsCats hyper_params[["histogram_type"]] <- HistogramType hyper_params[["nbins_top_level"]] <- NBinsTopLevel hyper_params[["categorical_encoding"]] <- CategoricalEncoding hyper_params[["distribution"]] <- Distribution grid <- h2o::h2o.grid( hyper_params = hyper_params, search_criteria = search_criteria, is_supervised = TRUE, algorithm = "gbm", grid_id = paste0(ModelID, "_Grid"), x = FeatureColNames, y = TargetColumnName, training_frame = datatrain, validation_frame = datavalidate, max_runtime_secs = 3600 * 24 * 7, stopping_rounds = 10L, stopping_tolerance = 1e-3, stopping_metric = eval_metric, score_tree_interval = 10L, seed = 1234) Grid_Out <- h2o::h2o.getGrid(grid_id = paste0(ModelID, "_Grid"), sort_by = eval_metric, decreasing = Decreasing) base_model <- h2o::h2o.getModel(Grid_Out@model_ids[[1L]]) } if(!GridTune) { if(DebugMode) print("Build Model ----") if(H2OStartUp) localHost <- h2o::h2o.init(nthreads = NThreads, max_mem_size = MaxMem, enable_assertions = FALSE) datatrain <- h2o::as.h2o(dataTrain, use_datatable = TRUE) if(!TrainOnFull) datavalidate <- h2o::as.h2o(dataTest, use_datatable = TRUE) else datavalidate <- NULL if(!is.null(TestData)) datatest <- h2o::as.h2o(TestData, use_datatable = TRUE) else datatest <- NULL H2OArgs <- list() H2OArgs[["x"]] <- FeatureColNames H2OArgs[["y"]] <- TargetColumnName H2OArgs[["weights_column"]] <- WeightsColumn[1L] H2OArgs[["training_frame"]] <- datatrain H2OArgs[["validation_frame"]] <- datavalidate H2OArgs[["distribution"]] <- Distribution[1L] H2OArgs[["model_id"]] <- ModelID[1L] H2OArgs[["ntrees"]] <- Trees[1L] H2OArgs[["max_depth"]] <- MaxDepth[1L] H2OArgs[["learn_rate"]] <- LearnRate[1L] H2OArgs[["learn_rate_annealing"]] <- LearnRateAnnealing[1L] H2OArgs[["sample_rate"]] <- SampleRate[1L] H2OArgs[["col_sample_rate"]] <- ColSampleRate[1L] H2OArgs[["col_sample_rate_per_tree"]] <- ColSampleRatePerTree[1L] H2OArgs[["col_sample_rate_change_per_level"]] <- ColSampleRatePerTreeLevel[1L] H2OArgs[["min_rows"]] <- MinRows[1L] H2OArgs[["nbins"]] <- NBins[1L] H2OArgs[["nbins_cats"]] <- NBinsCats[1L] H2OArgs[["nbins_top_level"]] <- NBinsTopLevel[1L] H2OArgs[["histogram_type"]] <- HistogramType[1L] H2OArgs[["categorical_encoding"]] <- CategoricalEncoding[1L] base_model <- do.call(h2o::h2o.gbm, H2OArgs) } if(DebugMode) print("Save Final Model ----") H2OSaveModel(SaveModelObjects.=SaveModelObjects, IfSaveModel.=IfSaveModel, base_model.=base_model, model_path.=model_path, ModelID.=ModelID) if(DebugMode) print("Score Final Test Data ----") if("score_traindata" %chin% tolower(OutputSelection) && !TrainOnFull) { Predict <- data.table::as.data.table(h2o::h2o.predict(object = base_model, newdata = datatrain)) } if(DebugMode) print("Create Validation Data ----") if("score_traindata" %chin% tolower(OutputSelection) && !TrainOnFull) { Output <- H2OValidationData(Predict.=Predict, TestData.=NULL, dataTest.=NULL, dataTrain.=dataTrain, TrainOnFull.=TRUE, SaveModelObjects.=SaveModelObjects, metadata_path.=metadata_path, model_path.=model_path, ModelID.=ModelID, TransformNumericColumns.=NULL, TransformationResults.=NULL, TargetColumnName.=NULL, data.=NULL) TrainData <- Output$ValidationData; rm(Output) } Predict <- data.table::as.data.table(h2o::h2o.predict(object = base_model, newdata = if(!is.null(TestData)) datatest else if(!TrainOnFull) datavalidate else datatrain)) data.table::set(Predict, j = "p0", value = NULL) Output <- H2OValidationData(Predict.=Predict, TestData.=TestData, dataTest.=dataTest, dataTrain.=dataTrain, TrainOnFull.=TrainOnFull, SaveModelObjects.=SaveModelObjects, metadata_path.=metadata_path, model_path.=model_path, ModelID.=ModelID, TransformNumericColumns.=NULL, TransformationResults.=NULL, TargetColumnName.=NULL, data.=NULL) ValidationData <- Output$ValidationData; rm(Output) if(DebugMode) print("Variable Importance ----") VariableImportance <- H2OVariableImportance(TrainOnFull.=TrainOnFull, base_model.=base_model, SaveModelObjects.=SaveModelObjects, metadata_path.=metadata_path, model_path.=model_path, ModelID.=ModelID) if(DebugMode) print("H2O Explain TrainData ----") ExplainList <- list() if("score_traindata" %chin% tolower(OutputSelection) && !TrainOnFull) { ExplainList[["Train_Explain"]] <- h2o::h2o.explain(base_model, newdata = datatrain) } if(DebugMode) print("H2O Explain ValidationData ----") if(!TrainOnFull) { ExplainList[["Test_Explain"]] <- h2o::h2o.explain(base_model, newdata = if(!is.null(TestData)) datatest else if(!is.null(ValidationData) && !TrainOnFull) datavalidate else datatrain) } if(DebugMode) print("H2O Shutdown ----") if(H2OShutdown) h2o::h2o.shutdown(prompt = FALSE) if(DebugMode) print("Running BinaryMetrics()") EvalMetricsList <- list() EvalMetrics2List <- list() if("evalmetrics" %chin% tolower(OutputSelection)) { if("score_traindata" %chin% tolower(OutputSelection) && !TrainOnFull) { EvalMetricsList[["TrainData"]] <- BinaryMetrics(ClassWeights.=NULL, CostMatrixWeights.=CostMatrixWeights, SaveModelObjects.=FALSE, ValidationData.=TrainData, TrainOnFull.=TrainOnFull, TargetColumnName.=TargetColumnName, ModelID.=ModelID, model_path.=model_path, metadata_path.=metadata_path, Method = "threshold") EvalMetrics2List[["TrainData"]] <- BinaryMetrics(ClassWeights.=NULL, CostMatrixWeights.=CostMatrixWeights, SaveModelObjects.=FALSE, ValidationData.=TrainData, TrainOnFull.=TrainOnFull, TargetColumnName.=TargetColumnName, ModelID.=ModelID, model_path.=model_path, metadata_path.=metadata_path, Method = "bins") if(SaveModelObjects) { if(!is.null(metadata_path)) { data.table::fwrite(EvalMetricsList[['TestData']], file = file.path(metadata_path, paste0(ModelID, "_Test_EvaluationMetrics.csv"))) } else if(!is.null(model_path)) { data.table::fwrite(EvalMetricsList[['TestData']], file = file.path(model_path, paste0(ModelID, "_Test_EvaluationMetrics.csv"))) } } } EvalMetricsList[["TestData"]] <- BinaryMetrics(ClassWeights.=NULL, CostMatrixWeights.=CostMatrixWeights, SaveModelObjects.=FALSE, ValidationData.=ValidationData, TrainOnFull.=TrainOnFull, TargetColumnName.=TargetColumnName, ModelID.=ModelID, model_path.=model_path, metadata_path.=metadata_path, Method = "threshold") EvalMetrics2List[["TestData"]] <- BinaryMetrics(ClassWeights.=NULL, CostMatrixWeights.=CostMatrixWeights, SaveModelObjects.=FALSE, ValidationData.=ValidationData, TrainOnFull.=TrainOnFull, TargetColumnName.=TargetColumnName, ModelID.=ModelID, model_path.=model_path, metadata_path.=metadata_path, Method = "bins") if(SaveModelObjects) { if(!is.null(metadata_path)) { data.table::fwrite(EvalMetricsList[['TestData']], file = file.path(metadata_path, paste0(ModelID, "_Test_EvaluationMetrics.csv"))) } else if(!is.null(model_path)) { data.table::fwrite(EvalMetricsList[['TestData']], file = file.path(model_path, paste0(ModelID, "_Test_EvaluationMetrics.csv"))) } } } if(DebugMode) print("Running CatBoostPDF()") if("pdfs" %chin% tolower(OutputSelection) && SaveModelObjects) { CatBoostPDF(ModelClass = "h2o", ModelType="classification", TrainOnFull.=TrainOnFull, SaveInfoToPDF.=SaveInfoToPDF, PlotList.=NULL, VariableImportance.=VariableImportance, EvalMetricsList.=EvalMetricsList, Interaction.=NULL, model_path.=model_path, metadata_path.=metadata_path) } if(DebugMode) print("Return Objects ----") if(ReturnModelObjects) { return(list( Model = base_model, TrainData = if(exists("TrainData") && !is.null(TrainData)) TrainData else NULL, TestData = if(exists("ValidationData") && !is.null(ValidationData)) ValidationData else NULL, H2OExplain = if(exists("ExplainList")) ExplainList else NULL, EvaluationMetrics = if(exists("EvalMetricsList")) EvalMetricsList else NULL, EvaluationMetrics2 = if(exists("EvalMetrics2List")) EvalMetrics2List else NULL, VariableImportance = if(exists("VariableImportance")) VariableImportance else NULL, ColNames = if(exists("Names")) Names else NULL)) } }
resource_frequency_log <- function(eventlog) { freq <- NULL eventlog %>% group_by(!!resource_id_(eventlog), !!activity_instance_id_(eventlog)) %>% summarize() %>% summarize(freq = n()) -> raw output <- raw %>% pull(freq) %>% summary_statistics() attr(output, "raw") <- raw return(output) }
md_bayes_draw_lambda <- function(dat, race_vote_split, form, ntunes = 10, totaldraws = 1e+05, seed = 12345, sample = 1e+05, thin = 100, burnin = 1e+05, ret.mcmc = TRUE) { left_dat <- apply(dat[, 1:race_vote_split[1]], 1, sum) right_dat <- apply( dat[, race_vote_split[2]:ncol(dat)], 1, sum ) stopifnot(all.equal(left_dat, right_dat)) formula1 <- form set.seed(seed) tune.nocov <- eiPack::tuneMD(formula1, data = dat, ntunes = ntunes, totaldraws = totaldraws ) md.out <- eiPack::ei.MD.bayes(formula1, data = dat, sample = sample, thin = thin, burnin = burnin, ret.mcmc = ret.mcmc, tune.list = tune.nocov ) cat(paste("Taking first ", race_vote_split[1], " names from dat object\n", sep = "")) lmd <- eiPack::lambda.MD(md.out, columns = names(dat[, 1:race_vote_split[1]])) return(lmd) }
getRNA <- function(db = "refseq", organism, reference = FALSE, release = NULL, path = file.path("_ncbi_downloads", "RNA")) { if (!is.element(db, c("refseq", "genbank", "ensembl"))) stop( "Please select one of the available data bases: 'refseq', 'genbank', or 'ensembl'.", call. = FALSE ) if (db == "ensemblgenomes") { organism_name <- is.genome.available(db = db, organism = organism, details = TRUE)$display_name[1] if (!is.na(organism_name)) message("Starting RNA retrieval of '", organism_name, "' from ", db, " ...") if (is.na(organism_name)) message("Starting RNA retrieval of '", organism, "' from ", db, " ...") } else { message("Starting RNA retrieval of '", organism, "' from ", db, " ...") message("\n") } if (is.element(db, c("refseq", "genbank"))) { AssemblyFilesAllKingdoms <- getKingdomAssemblySummary(db = db) suppressMessages(is.genome.available(organism = organism, db = db)) if (!file.exists(path)) { dir.create(path, recursive = TRUE) } organism_name <- assembly_accession <- taxid <- refseq_category <- version_status <- NULL organism <- stringr::str_replace_all(organism, "\\(", "") organism <- stringr::str_replace_all(organism, "\\)", "") if (reference) { if (!is.taxid(organism)) { FoundOrganism <- dplyr::filter( AssemblyFilesAllKingdoms, stringr::str_detect(organism_name, organism) | stringr::str_detect(assembly_accession, organism), ((refseq_category == "representative genome") | (refseq_category == "reference genome") ), (version_status == "latest") ) } else { FoundOrganism <- dplyr::filter( AssemblyFilesAllKingdoms, taxid == as.integer(organism), ((refseq_category == "representative genome") | (refseq_category == "reference genome") ), (version_status == "latest")) } } else { if (!is.taxid(organism)) { FoundOrganism <- dplyr::filter( AssemblyFilesAllKingdoms, stringr::str_detect(organism_name, organism) | stringr::str_detect(assembly_accession, organism), (version_status == "latest") ) } else { FoundOrganism <- dplyr::filter( AssemblyFilesAllKingdoms, taxid == as.integer(organism), (version_status == "latest") ) } } if (nrow(FoundOrganism) == 0) { message( paste0( "----------> No reference RNA or representative RNA was found for '", organism, "'. Thus, download for this organism has been omitted.", " Have you tried to specify getRNA(db = '",db,"', organism = '",organism,"' , reference = FALSE) ?", " Alternatively, you can retrieve RNA using the NCBI accession ID or NCBI Taxonomy ID.", " See '?'is.genome.available' for examples." ) ) return("Not available") } else { if (nrow(FoundOrganism) > 1) { warnings( "More than one entry has been found for '", organism, "'. Only the first entry '", FoundOrganism[1, 1], "' has been used for subsequent RNA retrieval.", " If you wish to download a different version, please use the NCBI accession ID when specifying the 'organism' argument.", " See ?is.genome.available for examples." ) FoundOrganism <- FoundOrganism[1, ] } organism <- stringr::str_replace_all(organism, " ", "_") download_url <- paste0( FoundOrganism$ftp_path, "/", paste0( basename(FoundOrganism$ftp_path), "_rna_from_genomic.fna.gz" ) ) local.org <- stringr::str_replace_all(organism, "-", "_") local.org <- stringr::str_replace_all(organism, "\\/", "_") if (nrow(FoundOrganism) == 1) { if (file.exists(file.path( path, paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ) ))) { message( "File ", file.path( path, paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ) ), " exists already. Thus, download has been skipped." ) } else { tryCatch({ utils::capture.output( custom_download( download_url, destfile = file.path( path, paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ) ), mode = "wb" ) ) message("RNA download of ", organism, " is completed!") custom_download( paste0(FoundOrganism$ftp_path,"/md5checksums.txt"), file.path(path, paste0(local.org, "_md5checksums.txt")), mode = "wb" ) md5_file_path <- file.path(path, paste0(local.org, "_md5checksums.txt")) md5_file <- read_md5file(md5_file_path) file_name <- NULL md5_sum <- dplyr::filter(md5_file, file_name == paste0(" ./", paste0( basename(FoundOrganism$ftp_path), "_rna_from_genomic.fna.gz" )))$md5 message("Checking md5 hash of file: ", md5_file_path , " ...") if (!(tools::md5sum(file.path( path, paste0(local.org, "_rna_from_genomic_", db, ".fna.gz") )) == md5_sum)) stop( paste0( "Please download the file '", md5_file_path, "' again. The md5 hash between the downloaded file and the file ", "stored at NCBI do not match.", collapse = "" ) ) unlink(md5_file_path) message("The md5 hash of file '", md5_file_path, "' matches!") }, error = function(e) { message( "The download session seems to have timed out at the FTP site '", download_url, "'. This could be due to an overload of queries to the databases.", " Please restart this function to continue the data retrieval process or wait ", "for a while before restarting this function in case your IP address was logged due to an query overload on the server side." ) return(FALSE) }) } docFile( file.name = paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ), organism = organism, url = download_url, database = db, path = path, refseq_category = FoundOrganism$refseq_category, assembly_accession = FoundOrganism$assembly_accession, bioproject = FoundOrganism$bioproject, biosample = FoundOrganism$biosample, taxid = FoundOrganism$taxid, infraspecific_name = FoundOrganism$infraspecific_name, version_status = FoundOrganism$version_status, release_type = FoundOrganism$release_type, genome_rep = FoundOrganism$genome_rep, seq_rel_date = FoundOrganism$seq_rel_date, submitter = FoundOrganism$submitter ) doc <- tibble::tibble( file_name = paste0(ifelse(is.taxid(organism), paste0("taxid_", local.org), local.org), "_genomic_", db, ".fna.gz"), organism = organism, url = download_url, database = db, path = path, refseq_category = FoundOrganism$refseq_category, assembly_accession = FoundOrganism$assembly_accession, bioproject = FoundOrganism$bioproject, biosample = FoundOrganism$biosample, taxid = FoundOrganism$taxid, infraspecific_name = FoundOrganism$infraspecific_name, version_status = FoundOrganism$version_status, release_type = FoundOrganism$release_type, genome_rep = FoundOrganism$genome_rep, seq_rel_date = FoundOrganism$seq_rel_date, submitter = FoundOrganism$submitter ) readr::write_tsv(doc, path = file.path(path,paste0("doc_",local.org,"_db_",db,".tsv"))) message( paste0( "The genomic RNA of '", organism, "' has been downloaded to '", path, "' and has been named '", paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ), "' ." ) ) return(file.path( path, paste0( local.org, "_rna_from_genomic_", db, ".fna.gz" ) )) } else { message( "Something went wrong when trying to download file: ", download_url, " ... Sometimes the internet connection isn't stable and re-running the function might help. Otherwise, could there be an issue with the firewall?" ) } } } if (db == "ensembl") { if (!file.exists(path)) { dir.create(path, recursive = TRUE) } rna.path <- getENSEMBL.Seq( organism, type = "ncrna", id.type = "none", release = release, path = path ) if (is.logical(rna.path[1])) { if (!rna.path[1]) return(FALSE) } else { taxon_id <- assembly <- name <- accession <- NULL ensembl_summary <- suppressMessages(is.genome.available( organism = organism, db = "ensembl", details = TRUE )) if (nrow(ensembl_summary) > 1) { if (is.taxid(organism)) { ensembl_summary <- dplyr::filter(ensembl_summary, taxon_id == as.integer(organism), !is.na(assembly)) } else { ensembl_summary <- dplyr::filter( ensembl_summary, (name == stringr::str_to_lower(stringr::str_replace_all(organism, " ", "_"))) | (accession == organism), !is.na(assembly) ) } } new.organism <- ensembl_summary$name[1] new.organism <- paste0( stringr::str_to_upper(stringr::str_sub(new.organism, 1, 1)), stringr::str_sub(new.organism, 2, nchar(new.organism)) ) url_api <- paste0( "http://rest.ensembl.org/info/assembly/", new.organism, "?content-type=application/json" ) if (length(url_api) > 1) url_api <- url_api[1] if (curl::curl_fetch_memory(url_api)$status_code != 200) { message("The API call '",url_api,"' did not work. This might be due to a non-existing organism that you specified or a corrupted internet or firewall connection.") return("Not available") } json.qry.info <- jsonlite::fromJSON(url_api) sink(file.path( path, paste0("doc_", new.organism, "_db_", db, ".txt") )) cat(paste0("File Name: ", rna.path[1])) cat("\n") cat(paste0("Download Path: ", rna.path[2])) cat("\n") cat(paste0("Organism Name: ", new.organism)) cat("\n") cat(paste0("Database: ", db)) cat("\n") cat(paste0("Download_Date: ", date())) cat("\n") cat(paste0("assembly_name: ", json.qry.info$assembly_name)) cat("\n") cat(paste0("assembly_date: ", json.qry.info$assembly_date)) cat("\n") cat( paste0( "genebuild_last_geneset_update: ", json.qry.info$genebuild_last_geneset_update ) ) cat("\n") cat(paste0( "assembly_accession: ", json.qry.info$assembly_accession )) cat("\n") cat( paste0( "genebuild_initial_release_date: ", json.qry.info$genebuild_initial_release_date ) ) sink() doc <- tibble::tibble( file_name = rna.path[1], download_path = rna.path[2], organism = new.organism, database = db, download_data = date(), assembly_name = ifelse(!is.null(json.qry.info$assembly_name), json.qry.info$assembly_name, "none"), assembly_date = ifelse(!is.null(json.qry.info$assembly_date), json.qry.info$assembly_date, "none"), genebuild_last_geneset_update = ifelse(!is.null(json.qry.info$genebuild_last_geneset_update), json.qry.info$genebuild_last_geneset_update, "none"), assembly_accession = ifelse(!is.null(json.qry.info$assembly_accession), json.qry.info$assembly_accession, "none"), genebuild_initial_release_date = ifelse(!is.null(json.qry.info$genebuild_initial_release_date), json.qry.info$genebuild_initial_release_date, "none") ) readr::write_tsv(doc, file.path( path, paste0("doc_", new.organism, "_db_", db, ".tsv")) ) message( paste0( "The RNA of '", organism, "' has been downloaded to '", path, "' and has been named '", basename(rna.path[1]), "'." ) ) return(rna.path[1]) } } if (db == "ensemblgenomes") { if (!file.exists(path)) { dir.create(path, recursive = TRUE) } rna.path <- getENSEMBLGENOMES.Seq( organism, type = "ncrna", id.type = "none", release = release, path = path ) if (is.logical(rna.path[1])) { if (!rna.path[1]) return(FALSE) } else { taxon_id <- assembly <- name <- accession <- NULL ensembl_summary <- suppressMessages(is.genome.available( organism = organism, db = "ensemblgenomes", details = TRUE )) if (nrow(ensembl_summary) > 1) { if (is.taxid(organism)) { ensembl_summary <- dplyr::filter(ensembl_summary, taxon_id == as.integer(organism), !is.na(assembly)) } else { ensembl_summary <- dplyr::filter( ensembl_summary, (name == stringr::str_to_lower(stringr::str_replace_all(organism, " ", "_"))) | (accession == organism), !is.na(assembly) ) } } new.organism <- ensembl_summary$name[1] new.organism <- paste0( stringr::str_to_upper(stringr::str_sub(new.organism, 1, 1)), stringr::str_sub(new.organism, 2, nchar(new.organism)) ) rest_url <- paste0( "http://rest.ensembl.org/info/assembly/", new.organism, "?content-type=application/json" ) if (curl::curl_fetch_memory(rest_url)$status_code != 200) { message( "The url: '",rest_url,"' cannot be reached. This might be due to a connection issue or incorrect url path (e.g. not valid organism name).") return(FALSE) } json.qry.info <- jsonlite::fromJSON(rest_url) sink(file.path( path, paste0("doc_", new.organism, "_db_", db, ".txt") )) cat(paste0("File Name: ", rna.path[1])) cat("\n") cat(paste0("Download Path: ", rna.path[2])) cat("\n") cat(paste0("Organism Name: ", new.organism)) cat("\n") cat(paste0("Database: ", db)) cat("\n") cat(paste0("Download_Date: ", date())) cat("\n") cat(paste0("assembly_name: ", json.qry.info$assembly_name)) cat("\n") cat(paste0("assembly_date: ", json.qry.info$assembly_date)) cat("\n") cat( paste0( "genebuild_last_geneset_update: ", json.qry.info$genebuild_last_geneset_update ) ) cat("\n") cat(paste0( "assembly_accession: ", json.qry.info$assembly_accession )) cat("\n") cat( paste0( "genebuild_initial_release_date: ", json.qry.info$genebuild_initial_release_date ) ) sink() doc <- tibble::tibble( file_name = rna.path[1], download_path = rna.path[2], organism = new.organism, database = db, download_data = date(), assembly_name = ifelse(!is.null(json.qry.info$assembly_name), json.qry.info$assembly_name, "none"), assembly_date = ifelse(!is.null(json.qry.info$assembly_date), json.qry.info$assembly_date, "none"), genebuild_last_geneset_update = ifelse(!is.null(json.qry.info$genebuild_last_geneset_update), json.qry.info$genebuild_last_geneset_update, "none"), assembly_accession = ifelse(!is.null(json.qry.info$assembly_accession), json.qry.info$assembly_accession, "none"), genebuild_initial_release_date = ifelse(!is.null(json.qry.info$genebuild_initial_release_date), json.qry.info$genebuild_initial_release_date, "none") ) readr::write_tsv(doc, file.path( path, paste0("doc_", new.organism, "_db_", db, ".tsv")) ) message( paste0( "The RNA of '", organism, "' has been downloaded to '", path, "' and has been named '", basename(rna.path[1]), "'." ) ) return(rna.path[1]) } } }
gcite_graph <- function(citations, ...){ UseMethod("gcite_graph") } gcite_graph.xml_node = function(citations, ...) { citations = xml2::as_list(citations) gcite_graph(citations) } gcite_graph.xml_document = function(citations, ...) { citations = rvest::html_node(citations, css = " gcite_graph(citations) } gcite_graph.character = function(citations, ...) { res = httr::GET(url = citations, ...) stop_for_status(res) citations = httr::content(res) gcite_graph(citations) } gcite_graph.default = function(citations, ...) { cn = names(citations) a_s = cn %in% "a" info = lapply(citations[a_s], function(x) { cc = x$span[[1]] if (is.null(cc)) { cc = 0 } cc = as.numeric(cc) href = attributes(x)$href y = parse_url(href)$query[c("as_ylo", "as_yhi")] y = unlist(unique(y)) if (length(y) == 0) { y = NA } y = as.numeric(y) data.frame(year = y, n_citations = cc,stringsAsFactors = FALSE) }) info = as.data.frame(data.table::rbindlist(info, fill = TRUE)) info }
context("Hsu's Backward Construction") test_that("Default example", { data.graph <- data.frame(from = c("s", "s", "s", "u", "u", "w", "w", "x", "x", "v", "v", "y", "y"), to = c("u", "w", "x", "w", "v", "v", "y", "w", "y", "y", "t", "t", "u"), cost = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), stringsAsFactors = FALSE) data.fpaths <- data.frame(V1 = c("u", "u", "w", "x"), V2 = c("v", "w", "v","w"), V3 = c("y", "y", "y", "v"), V4 = c("u", "u", NA, "y"), V5 = c(NA, NA, NA, "t"), stringsAsFactors = FALSE) expected.gStar <- data.frame(from = c("s", "s", "s", "w", "x", "v", "v", "y", "y", "u", "u|v", "u", "u|w", "w", "x", "x|w", "w|v", "x|w", "x|w|v", "u|v", "u|v|y", "u|w"), to = c("u", "w", "x", "y", "y", "y", "t", "t", "u", "u|v", "u|v|y", "u|w", "u|v|y", "w|v", "x|w", "x|w|v", "t", "y", "t", "t", "t", "w|v"), cost = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), stringsAsFactors = FALSE) row.names(expected.gStar) <- c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L) expect_equal(modify_graph_hsu(data.graph, data.fpaths), expected.gStar) }) test_that("Additional example", { data.graph <- data.frame(from = c("c", "c", "u", "u", "t", "a", "a", "r", "e", "e", "e", "p", "i", "i", "n", "o"), to = c("u", "p", "e", "t", "a", "r", "i", "u", "r", "i", "p", "n", "n", "o", "o", "m"), stringsAsFactors = FALSE) data.fpaths <- data.frame(V1 = c("u", "p", "a"), V2 = c("t", "n", "i"), V3 = c("a", "o", "n"), V4 = c("r", "m", "o"), V5 = c("u", NA, NA), stringsAsFactors = FALSE) expected.gStar <- data.frame(from = c("c", "c", "u", "t", "a", "r", "e", "e", "e", "i", "i", "n", "o", "u", "u|t", "u|t|a", "p", "p|n", "a", "a|i", "u|t|a", "a|i"), to = c("u", "p", "e", "a", "r", "u", "r", "i", "p", "n", "o", "o", "m", "u|t", "u|t|a", "u|t|a|r", "p|n", "p|n|o", "a|i", "a|i|n", "a|i", "o"), stringsAsFactors = FALSE) row.names(expected.gStar) <- c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L) expect_equal(modify_graph_hsu(data.graph, data.fpaths), expected.gStar) }) test_that("Wrong input", { data.graph <- data.frame(from = c("s", "s", "s", "u", "u", "w", "w", "x", "x", "v", "v", "y", "y"), to = c("u", "w", "x", "w", "v", "v", "y", "w", "y", "y", "t", "t", "u"), cost = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), stringsAsFactors = FALSE) data.fpaths <- data.frame(V1 = c("u", "u", "w", "x"), V2 = c("v", "w", "v","w"), V3 = c("y", "y", "y", "v"), V4 = c("u", "u", NA, "y"), V5 = c(NA, NA, NA, "t"), stringsAsFactors = FALSE) expect_error(modify_graph_hsu(NULL, data.fpaths, 1L)) expect_error(modify_graph_hsu(NA, NA)) expect_error(modify_graph_hsu(data.graph, NULL)) expect_error(modify_graph_hsu("123", data.fpaths)) expect_error(modify_graph_hsu(data.graph, 1234)) expect_error(modify_graph_hsu(c(123,46), c(789,456))) })
test_that("totp at", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret) t <- .POSIXct(1587872481) expect_true(p$at_time(t) == "825314") expect_true(p$at_time(1587872481) == "825314") expect_true(p$now() != "825314") }) test_that("totp verify", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret) t <- .POSIXct(1587872481) trunc_t <- .POSIXct((as.double(t) %/% 30) * 30) expect_equal(p$verify("825314", t + 30), NULL) expect_equal(p$verify("825314", t), trunc_t) expect_equal(p$verify("825314", t - 30), NULL) expect_equal(p$verify("825314", t + 30, behind = 1), trunc_t) }) test_that("totp more digits", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret, digits = 8) t <- .POSIXct(1587872481) trunc_t <- .POSIXct((as.double(t) %/% 30) * 30) expect_equal(p$verify("14825314", t + 30), NULL) expect_equal(p$verify("14825314", t), trunc_t) expect_equal(p$verify("14825314", t - 30), NULL) expect_equal(p$verify("14825314", t + 30, behind = 1), trunc_t) }) test_that("totp different period", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret, period = 10) t <- .POSIXct(1587872481) trunc_t <- .POSIXct((as.double(t) %/% 10) * 10) expect_equal(p$verify("845792", t + 10), NULL) expect_equal(p$verify("845792", t), trunc_t) expect_equal(p$verify("845792", t - 10), NULL) expect_equal(p$verify("845792", t + 10, behind = 1), trunc_t) expect_equal(p$verify("845792", t + 20, behind = 1), NULL) expect_equal(p$verify("845792", t + 20, behind = 2), trunc_t) }) test_that("totp different algorithm", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret, algorithm = "sha256") t <- .POSIXct(1587872481) expect_equal(p$at_time(t), "213585") expect_equal(p$at_time(t + 30), "759908") p <- TOTP$new(secret, algorithm = "sha512") t <- .POSIXct(1587872481) expect_equal(p$at_time(t), "448289") expect_equal(p$at_time(t + 30), "761638") }) test_that("totp provision", { secret <- "JBSWY3DPEHPK3PXP" p <- TOTP$new(secret) expect_equal( p$provisioning_uri("Alice"), "otpauth://totp/Alice?secret=JBSWY3DPEHPK3PXP" ) expect_equal( p$provisioning_uri("Alice", issuer = "example.com"), "otpauth://totp/example.com:Alice?secret=JBSWY3DPEHPK3PXP&issuer=example.com" ) p <- TOTP$new(secret, digits = 7, algorithm = "sha256", period = 40) expect_equal( p$provisioning_uri("Alice"), "otpauth://totp/Alice?secret=JBSWY3DPEHPK3PXP&period=40&digits=7&algorithm=sha256" ) })
shares.total <- function (mcidataset, submarkets, suppliers, shares, localmarket, plotChart = FALSE, plotChart.title = "Total sales", plotChart.unit = "sales", check_df = TRUE) { if (check_df == TRUE) { if (exists(as.character(substitute(mcidataset)))) { checkdf(mcidataset, submarkets, suppliers, shares, localmarket) } else { stop(paste("Dataset", as.character(substitute(mcidataset))), " not found", call. = FALSE) } } mciworkfile <- mcidataset mciworkfile[[shares]][is.na(mciworkfile[[shares]])] <- 0 mciworkfile[[localmarket]][is.na(mciworkfile[[localmarket]])] <- 0 mciworkfile$E_ij <- mciworkfile[[shares]] * mcidataset[[localmarket]] suppliers_single <- levels(as.factor(as.character(mciworkfile[[suppliers]]))) suppliers_count <- nlevels(as.factor(as.character(mciworkfile[[suppliers]]))) sum_E_j <- numeric() for (j in 1:suppliers_count) { location_j <- subset (mciworkfile, mciworkfile[[suppliers]] == suppliers_single[j]) sum_E_j[j] <- sum(location_j$E_ij, na.rm = TRUE) } E_j_output <- data.frame(suppliers_single, sum_E_j) E_j_output$share_j <- E_j_output$sum_E_j/sum(E_j_output$sum_E_j, na.rm = TRUE) if (plotChart == TRUE) { E_j_output_sorted <- E_j_output[order(E_j_output$share_j),] max_x <- max(E_j_output_sorted$sum_E_j*1.2) barplot(E_j_output_sorted$sum_E_j, names.arg = E_j_output_sorted$suppliers_single, horiz = TRUE, main = plotChart.title, sub = plotChart.unit, xlim = c(0, max_x)) } return(E_j_output) }
coll <- c(" " lwd1 <- fontt <- 2 cexx=1.3 plott = function(x,y=c(1:length(x)),add=FALSE,pch=19,xlab="",col=1, main=NULL,ty="b",return.to.default=TRUE,...){ lwd1 <- fontt <- 2 if(add){ lines(x~y,xlab="",ylab = "",ty=ty,lwd=lwd1,col=col,pch=pch) } if(!add){ pardefault <- par(no.readonly = TRUE) parr = par(bg="white", bty ="n", fg = 'black' , font.lab = fontt, font.axis = fontt, font.main = fontt, col.axis = 'black',col.lab = 'black', cex.axis = 1.4, pch = 21, tck = -0.02, cex.lab = 1.6 ,cex.main = 2,las=1, mar = c(5, 4, 4, 2) + 0.4) plot(x~y,xlab=xlab, ylab = "",ty=ty,lwd=2,main=main,pch=pch,col=col,...) grid(col = "grey") if(return.to.default) { par(pardefault)} } } tsideplot <- function(series1,series2,main="", return.to.default=T, xaxis=NULL, col='red',...){ if (NROW(series1) != NROW(series2) ) { stop("Problem is that NROW(series1) != NROW(series2)") } lwd1 <- fontt <- 2 pardefault <- par(no.readonly = TRUE) par(mfrow = c(1,1),bg="white", bty ="n", fg = 'black' , font.lab = fontt, font.axis = fontt, font.main = fontt, col.axis = 'black',col.lab = 'black', cex.axis = 1.4, pch = 21, tck = -0.02, cex.lab = 1.6 ,cex.main = 2,las=1, mar = c(5, 4, 4, 4) + 0.1) if(is.null(xaxis)) {xaxis= c(1:length(series1))} plot(series1~xaxis,ty="b",pch=19,xlab="",ylab="",col = 1,lwd=lwd1,...) par(new=TRUE) plot(series2~xaxis,main=main,bty="o",ty="b",pch=19,xlab="",ylab="", axes=F,col = col,lwd=lwd1,...) axis(4,at=pretty(series2),col=col,col.ticks=col,col.axis=col) grid(col = "grey") if(return.to.default){par(pardefault)} } mplott <- function(x,wherelegend='bottomleft',textlegend=colnames(x),main="", return.to.default=T,...){ lwd1 <- fontt <- 2 pardefault <- par(no.readonly = TRUE) l = NCOL(x) pchh <- c(19,1:4) if (l>5) { l=5 textlegend=colnames(x)[1:5] print("Only columns 1:5 are plotted") } par(bg="white", bty ="n", fg = 'black' , font.lab = fontt, font.axis = fontt, font.main = fontt, col.axis = 'black',col.lab = 'black', cex.axis = 1.4, pch = 21, tck = -0.02, cex.lab = 1.6 ,cex.main = 2,las=1, mar = c(5, 4, 4, 4) + 0.1) x <- as.matrix(x) plot(x[,1],ty = "b",ylim = c(min(na.omit(x)),max(na.omit(x))),xlab = "", ylab = "",lwd=2,pch=pchh[1],main=main,...) for (i in 2:l){ if(l==1) {next} lines(x[,i],col=i,ty = "b",lty=i,lwd=2,pch=pchh[i],...) } if(is.null(textlegend)) { textlegend = paste("Series", 1:l) } legend(wherelegend,textlegend,col=1:l,lty=1:l,cex=1.3,text.font=2, ncol=2,bty="n",text.col=1:l,lwd = rep(2,l),pch=pchh[1:l]) grid(col='grey') if(return.to.default){par(pardefault)} } lagmat <- function(x,lags){ TT <- NROW(x) ; colnam <- NULL lagmatt <- matrix(nrow = TT, ncol = lags) for (i in 1:lags){ lagmatt[(i+1):(TT),i] <- x[1:(TT-i)] colnam[i] <- paste('Lag',i,sep="") } lagmatt[1:lags,] <- NA colnames(lagmatt) <- colnam lagmatt } linpred <- function(y,x,h=1,wind=NULL,rr=c("Rec")){ if (rr != "Rol" & rr !="Rec") { stop("rr is not properly defined") } if (NROW(y) != NROW(x) ) { stop("Problem is that NROW(y) != NROW(x)") } if(is.null(wind)){wind=0.25*length(y)} predd <- NULL TT <- length(y) x=as.matrix(x) if(rr=='Rec'){ for (j in (1+wind):TT){ lm0 <- lm(y[1:(j-h)]~x[1:(j-h),]) predd[j] <- lm0$coef%*%c(1,x[(j-h),]) }} if(rr=='Rol'){ for (j in 1:(TT-wind)){ lm0 <- lm(y[j:(wind+j-h)]~x[j:(wind+j-h),]) predd[(j+wind)] <- lm0$coef%*%c(1,x[(j+wind-h),]) } } predd } FCIplot <- function(series,plott=TRUE,wind1=24,wind2=60,k=60,rrr1="Rec",rrr2="Rec",main="series"){ if (wind2< wind1) { stop("wind2 has to be > than wind1") } TT <- length(series) temp <- linpred(series[2:TT],series[1:(TT-1)],h=1, wind=wind1,rr=rrr1) ertemp <- (series[2:TT]-temp)^2 TT2 <- length(ertemp) sdestimate <- linpred(ertemp[2:TT2], ertemp[1:(TT2-1)], wind = wind2, rr = rrr2) up1 = series[(wind2+2):(TT-1)] + 1*sqrt(abs(na.omit(sdestimate))) down1 = series[(wind2+2):(TT-1)] - 1*sqrt(abs(na.omit(sdestimate))) up2 = series[(wind2+2):(TT-1)] + 2*sqrt(abs(na.omit(sdestimate))) down2 = series[(wind2+2):(TT-1)] - 2*sqrt(abs(na.omit(sdestimate))) if(k>length(down2)){k=length(down2) ; warning( "k was set to a lower value" )} if(plott){ plot(tail(series,k),ylim=c(min(tail(down2,k)),max(tail(up2,k))),ty="b",pch=19,xlab="", main=main,ylab="") grid() polygon(x = c(rev(1:k),(1:k)), y = c(rev(tail(down2,k)),tail(up2,k)), col = rgb(0,0,0,0.2),border ='red') polygon(x = c(rev(1:k),(1:k)), y = c(rev(tail(down1,k)),tail(up1,k)), col = rgb(0,0,0,0.2),border ='blue') } return(sdestimate^.5) }
linesHyperb.lm <- function(object, c.prob = .95, confidence = FALSE, k = if(confidence) Inf else 1, col = 2, lty = 2, do.abline = TRUE) { n <- length(Res <- residuals(object)) df <- object $ df.resid s2 <- sum(Res^2)/df s <- sqrt(s2) if(is.null(R <- object $ R)) R <- qr.R(object $ qr) Xm <- R[1,2]/R[1,1] S.xx <- R[2,2]^2 ux <- par("usr")[1:2] d.xs <- data.frame(x = xs <- seq(ux[1],ux[2], length = 100)) names(d.xs) <- attr(object$terms,"term.labels") ys <- predict(object, new = d.xs) pred.err <- qt(1-(1-c.prob)/2, df) * s * sqrt(1/k + 1/n + (xs-Xm)^2/S.xx) o.p <- par(err=-1) on.exit(par(o.p)) if(do.abline) abline(object) lines(xs, ys - pred.err, col=col, lty=lty) lines(xs, ys + pred.err, col=col, lty=lty) }
internal.print.seqtest.mean <- function(x, print.step = 1, print.max = 1, ...) { if (print.step == 1) { cat("\nSequential triangular test for the arithmetic mean in", ifelse(x$spec$sample == "one.sample", "one sample", "two samples"), "\n\n") if (x$spec$sample == "one.sample") { if (x$spec$alternative == "two.sided") { cat(" H0: mu =", x$spec$mu, " versus H1: mu !=", x$spec$mu, "\n") } else { if (x$spec$alternative == "less") { cat(" H0: mu >=", x$spec$mu, " versus H1: mu <", x$spec$mu, "\n") } else { cat(" H0: mu <=", x$spec$mu, " versus H1: mu >", x$spec$mu, "\n") } } } else { if (x$spec$alternative == "two.sided") { cat(" H0: mu.1 = mu.2 versus H1: mu.1 != mu.2\n") } else { if (x$spec$alternative == "less") { cat(" H0: mu.1 >= mu.2 versus H1: mu.1 < mu.2\n") } else { cat(" H0: mu.1 <= mu.2 versus H1: mu.1 > mu.2\n") } } } if (x$spec$variance == "known") { cat(" alpha:", x$spec$alpha, " beta:", x$spec$beta, " delta:", x$spec$delta, " sigma:", x$spec$sigma, "\n\n") } else { cat(" alpha:", x$spec$alpha, " beta:", x$spec$beta, " theta:", x$spec$theta, "\n\n") } } V.m.print <- ifelse(!is.na(x$res$V.m[x$res$step]), formatC(x$res$V.m[x$res$step], digits = 3, format = "f"), NA) Z.m.print <- ifelse(!is.na(x$res$Z.m[x$res$step]), formatC(x$res$Z.m[x$res$step], digits = 3, format = "f"), NA) if (!is.na(V.m.print) & !is.na(V.m.print)) { if (x$spec$alternative == "two.sided") { if (x$res$V.m[x$res$step] < x$tri$intersec) { x.r <- range(c(-x$tri$a1 + 3 * x$tri$b1 * x$res$V.m[x$res$step], -x$tri$a2 + 3 * x$tri$b2 * x$res$V.m[x$res$step], x$tri$a1 + x$tri$b1 * x$res$V.m[x$res$step], x$tri$a2 + x$tri$b2 * x$res$V.m[x$res$step])) cat(" Step", x$res$step, "\n", " V.m: ", V.m.print, paste(rep(" ", times = 10 - nchar(V.m.print)), collapse = ""), "Z.m:", paste(rep(" ", times = 9 - nchar(Z.m.print)), collapse = ""), Z.m.print, "\n", paste0(" Continuation range | V.m: [", formatC(x.r[which.min(x.r)], digits = 3, format = "f"), ", ", formatC(x.r[which.max(x.r)], digits = 3, format = "f"), "]\n\n")) } else { x1.1 <- formatC(-x$tri$a1 + 3 * x$tri$b1 * x$res$V.m[x$res$step], digits = 3, format = "f") x1.2 <- formatC(-x$tri$a2 + 3 * x$tri$b2 * x$res$V.m[x$res$step], digits = 3, format = "f") x2.1 <- formatC(x$tri$a1 + x$tri$b1 * x$res$V.m[x$res$step], digits = 3, format = "f") x2.2 <- formatC(x$tri$a2 + x$tri$b2 * x$res$V.m[x$res$step], digits = 3, format = "f") width.1 <- max(c(nchar(c(x1.1, x2.1)[which.min(c(x1.1, x2.1))]), nchar(formatC(c(x1.2, x2.2)[which.min(c(x1.2, x2.2))])))) width.2 <- max(c(nchar(c(x1.1, x2.1)[which.max(c(x1.1, x2.1))]), nchar(formatC(c(x1.2, x2.2)[which.max(c(x1.2, x2.2))])))) cat(" Step", x$res$step, "\n", " V.m: ", V.m.print, paste(rep(" ", times = 10 - nchar(V.m.print)), collapse = ""), "Z.m:", paste(rep(" ", times = 10 - nchar(Z.m.print)), collapse = ""), Z.m.print, "\n", paste0(" Continuation range | V.m: [", formatC(c(x1.1, x2.1)[which.min(c(x1.1, x2.1))], width = width.1, format = "f"), ", ", formatC(c(x1.1, x2.1)[which.max(c(x1.1, x2.1))], width = width.2, format = "f"), "]\n", " [", formatC(c(x1.2, x2.2)[which.min(c(x1.2, x2.2))], width = width.1, format = "f"), ", ", formatC(c(x1.2, x2.2)[which.max(c(x1.2, x2.2))], width = width.2, format = "f"), "]\n\n")) } } else { x1 <- -x$tri$a + 3 * x$tri$b * x$res$V.m[x$res$step] x2 <- x$tri$a + x$tri$b * x$res$V.m[x$res$step] cat(" Step", x$res$step, "\n", " V.m: ", V.m.print, paste(rep(" ", times = 10 - nchar(V.m.print)), collapse = ""), "Z.m:", paste(rep(" ", times = 9 - nchar(Z.m.print)), collapse = ""), Z.m.print, "\n", paste0(" Continuation range | V.m: [", formatC(c(x1, x2)[which.min(c(x1, x2))], digits = 3, format = "f"), ", ", formatC(c(x1, x2)[which.max(c(x1, x2))], digits = 3, format = "f"), "]\n\n")) } } else { cat(" Step", x$res$step, "\n", " V.m: NA Z.m: NA\n", " Continuation range | V.m: [NA, NA]\n\n") } if (x$res$decision != "continue" | print.step == print.max) { if (x$res$decision == "continue") { cat(" Test not finished, continue by adding data via update() function\n") if (x$spec$sample == "one.sample") { cat(" Current sample size:", x$dat$n, "\n\n") } else { cat(paste0(" Current sample size for x:", x$dat$n.1, "\n", " y:", x$dat$n.2, "\n\n")) } } else { cat(" Test finished:", ifelse(x$res$decision == "H0", "Keep null hypothesis (H0)", "Accept alternative hypothesis (H1)"), "\n") if (x$spec$sample == "one.sample") { cat(" Final sample size:", x$dat$n, "\n\n") } else { cat(paste0(" Final sample size for x:", x$dat$n.1, "\n", " y:", x$dat$n.2, "\n\n")) } } } }