code
stringlengths
1
13.8M
more_colors <- function(n = 24){ c( RColorBrewer::brewer.pal(12,'Paired'), RColorBrewer::brewer.pal(12,'Set3') ) %>% head(n) }
NULL count_self_fn <- function(th) { node_types <- get_node_types(th) fn_defs <- dplyr::filter(node_types, .data$name == "function", .data$call_status == TRUE) if(nrow(fn_defs) == 0) return(0L) fn_def_ids <- fn_defs$id parent_ids <- sapply(fn_def_ids, get_parent_id, x=th) sum(node_types$name[parent_ids] %in% c("=", "<-")) } count_lam_fn <- function(th) { node_types <- get_node_types(th) fn_defs <- dplyr::filter(node_types, .data$name == "function", .data$call_status == TRUE) if(nrow(fn_defs) == 0) return(0L) fn_def_ids <- fn_defs$id parent_ids <- sapply(fn_def_ids, get_parent_id, x = th) sum(!node_types$name[parent_ids] %in% c("=", "<-")) } count_fn_call <- function(th, pattern, pkg_name) { node_types <- get_node_types(th) if(!missing(pattern) && !missing(pkg_name)){ stop("Only one of pattern or pkg_name should be supplied.") } if(!missing(pattern)) { fn_calls <- dplyr::filter(node_types, stringr::str_detect(.data$name, pattern), .data$call_status == TRUE) return(nrow(fn_calls)) } if(!missing(pkg_name)){ fn_list <- ls(getNamespace(pkg_name)) fn_calls <- dplyr::filter(node_types, .data$call_status == TRUE) return(sum(fn_calls$name %in% fn_list)) } } extract_fn_call <- function(th, pattern, pkg_name) { node_types <- get_node_types(th) if(!missing(pattern) && !missing(pkg_name)){ stop("Only one of pattern or pkg_name should be supplied.") } if(!missing(pattern)) { fn_calls <- dplyr::filter(node_types, stringr::str_detect(.data$name, pattern), .data$call_status == TRUE) return(fn_calls$name) } if(!missing(pkg_name)){ fn_list <- ls(getNamespace(pkg_name)) fn_calls <- dplyr::filter(node_types, .data$call_status == TRUE) return(fn_calls$name[fn_calls$name %in% fn_list]) } } extract_formal_args <- function(th, fn_name) { node_types <- get_node_types(th) fn_calls <- dplyr::filter(node_types, .data$name == fn_name, .data$call_status == TRUE) fn_call_ids <- fn_calls$id child_ids <- lapply(fn_call_ids, get_child_ids, x=th) if(length(child_ids) == 0L) { return(NULL) } else { child_ids <- unlist(child_ids) } fn_args <- dplyr::filter(node_types, .data$id %in% child_ids, .data$formal_arg == TRUE) if(nrow(fn_args) == 0) return(NULL) return(fn_args$name) } extract_assigned_objects <- function(th) { node_types <- get_node_types(th) all_assign_rows <- dplyr::filter(node_types, .data$name %in% c("<-", "=")) if(nrow(all_assign_rows) == 0) return(character(0)) child_id_list <- lapply(all_assign_rows$id, get_child_ids, x=th) first_child_id <- sapply(child_id_list, function(x) x[1]) sub_tree_list <- lapply(first_child_id, function(x) { if(node_types$call_status[x]){ subtree_at(th, x, TRUE) } else { subtree_at(th, x, FALSE) } }) sapply(sub_tree_list, function(x) x@repr, USE.NAMES = FALSE) } extract_actual_args <- function(th) { node_types <- get_node_types(th) actual_arg_rows <- dplyr::filter(node_types, !.data$call_status, !.data$formal_arg) if(nrow(actual_arg_rows) == 0) return(0L) actual_arg_rows$name } detect_growing <- function(th, count=FALSE, within_for=FALSE) { nt <- get_node_types(th) c_rows <- dplyr::filter(nt, .data$name %in% c("c", "append")) if(nrow(c_rows) == 0) { if(count) return(0) else return(FALSE) } if(within_for) { paths_to_root <- lapply(c_rows$id, function(x) path_to_root(th, x)) keep_ids <- sapply(paths_to_root, function(x) { "for" %in% nt$name[x==1] }) c_rows <- c_rows[keep_ids,] if(nrow(c_rows) == 0) { if(count) return(0) else return(FALSE) } } c_parents <- sapply(c_rows$id, get_parent_id, x=th) c_parents <- Filter(function(x) nt$name[x] %in% c("=", "<-"), c_parents) if(length(c_parents) == 0) return(FALSE) c_assigned_name <- sapply(c_parents, function(y){ child_ids <- get_child_ids(th, y) nt$name[child_ids[1]] }) c_children_names <- lapply(c_rows$id, function(y) { child_ids <- get_child_ids(th, y) nt$name[child_ids] }) detect_out <- mapply(function(x, y) x %in% y, x=c_assigned_name, y=c_children_names) if(count){ return(sum(unname(detect_out))) } any(detect_out) } detect_for_in_fn_def <- function(th, fn_name) { nt <- get_node_types(th) nt_names <- nt$name if((nt_names[1] != "<-") || (nt_names[2] != fn_name) || (nt_names[3] != "function")) return(FALSE) for_id <- which(nt_names == "for") if(length(for_id) > 0 && nt$depth[for_id] > 2) return(TRUE) else return(FALSE) } count_fn_in_fn <- function(th, fn_name, sub_fn) { nt <- get_node_types(th) nt_names <- nt$name if((nt_names[1] != "<-") || (nt_names[2] != fn_name) || (nt_names[3] != "function")) return(0) sub_fn_count <- count_fn_call(th, pattern=sub_fn) sub_fn_count } detect_fn_call_in_for <- function(th, fn_name) { for_loop_indicator <- count_fn_call(th, pattern="for") send_ltr_indicator <- count_fn_call(th, pattern=fn_name) if((for_loop_indicator == 0) || (send_ltr_indicator == 0)){ return(FALSE) } nt <- get_node_types(th) send_ids <- which(nt$name == fn_name) paths_to_parent <- lapply(send_ids, path_to_root, th=th) parent_names <- lapply(paths_to_parent, function(x) nt$name[which(x == 1)]) for_in_parent <- lapply(parent_names, function(x) "for" %in% x) return(any(unlist(for_in_parent))) } extract_self_fn <- function(th) { fn_def <- count_self_fn(th) if(fn_def==0){ return(NULL) } node_types <- get_node_types(th) out_tree <- subtree_at(th, 2, node_types$call_status[2]) out_tree@repr } detect_fn_arg <- function(th, fn_name, arg) { nt <- get_node_types(th) nt_names <- nt$name fn_ids <- which(nt_names == fn_name) if(length(fn_ids) == 0){ return(FALSE) } arg_ids <- lapply(fn_ids, get_child_ids, x=th) check_args <- sapply(arg_ids, function(x) arg %in% nt_names[x]) any(check_args) } detect_nested_for <- function(th) { node_types <- get_node_types(th) for_ids <- which(node_types$name == "for") if(length(for_ids) == 0){ return(FALSE) } else { for_count_along_branch <- vapply(for_ids, function(x) sum(node_types$name[which(path_to_root(th, x) == 1)] == "for"), FUN.VALUE=1L) } any(for_count_along_branch > 1) }
qpvt <- function(dataFrame, rows=NULL, columns=NULL, calculations=NULL, theme=NULL, replaceExistingStyles=FALSE, tableStyle=NULL, headingStyle=NULL, cellStyle=NULL, totalStyle=NULL, ...) { arguments <- list(...) checkArgument(3, TRUE, "", "qpvt", dataFrame, missing(dataFrame), allowMissing=FALSE, allowNull=FALSE, allowedClasses="data.frame") checkArgument(3, TRUE, "", "qpvt", rows, missing(rows), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qpvt", columns, missing(columns), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qpvt", calculations, missing(calculations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qpvt", theme, missing(theme), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyles"), allowedListElementClasses="character") checkArgument(3, TRUE, "", "qpvt", replaceExistingStyles, missing(replaceExistingStyles), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical") checkArgument(3, TRUE, "", "qpvt", tableStyle, missing(tableStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qpvt", headingStyle, missing(headingStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qpvt", cellStyle, missing(cellStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qpvt", totalStyle, missing(totalStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) argumentCheckMode <- arguments$argumentCheckMode if(is.null(argumentCheckMode)) argumentCheckMode <- "auto" compatibility <- arguments$compatibility dataName <- deparse(substitute(dataFrame)) pt <- buildPivot(functionName="qpvt", argumentCheckMode=argumentCheckMode, dataFrame=dataFrame, dataName=dataName, rows=rows, columns=columns, calculations=calculations, format=arguments[["format"]], formats=arguments[["formats"]], totalsSpecified=("totals" %in% names(arguments)), totals=arguments[["totals"]], theme=theme, replaceExistingStyles=replaceExistingStyles, tableStyle=tableStyle, headingStyle=headingStyle, cellStyle=cellStyle, totalStyle=totalStyle, compatibility=compatibility) pt$evaluatePivot() return(pt) } qhpvt <- function(dataFrame, rows=NULL, columns=NULL, calculations=NULL, theme=NULL, replaceExistingStyles=FALSE, tableStyle=NULL, headingStyle=NULL, cellStyle=NULL, totalStyle=NULL, ...) { arguments <- list(...) checkArgument(3, TRUE, "", "qhpvt", dataFrame, missing(dataFrame), allowMissing=FALSE, allowNull=FALSE, allowedClasses="data.frame") checkArgument(3, TRUE, "", "qhpvt", rows, missing(rows), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qhpvt", columns, missing(columns), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qhpvt", calculations, missing(calculations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qhpvt", theme, missing(theme), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyles"), allowedListElementClasses="character") checkArgument(3, TRUE, "", "qhpvt", replaceExistingStyles, missing(replaceExistingStyles), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical") checkArgument(3, TRUE, "", "qhpvt", tableStyle, missing(tableStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qhpvt", headingStyle, missing(headingStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qhpvt", cellStyle, missing(cellStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) checkArgument(3, TRUE, "", "qhpvt", totalStyle, missing(totalStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle")) argumentCheckMode <- arguments$argumentCheckMode if(is.null(argumentCheckMode)) argumentCheckMode <- "auto" compatibility <- arguments$compatibility styleNamePrefix <- arguments$styleNamePrefix dataName <- deparse(substitute(dataFrame)) pt <- buildPivot(functionName="qhpvt", argumentCheckMode=argumentCheckMode, dataFrame=dataFrame, dataName=dataName, rows=rows, columns=columns, calculations=calculations, format=arguments[["format"]], formats=arguments[["formats"]], totalsSpecified=("totals" %in% names(arguments)), totals=arguments[["totals"]], theme=theme, replaceExistingStyles=replaceExistingStyles, tableStyle=tableStyle, headingStyle=headingStyle, cellStyle=cellStyle, totalStyle=totalStyle, compatibility=compatibility) w <- pt$renderPivot(styleNamePrefix=styleNamePrefix) return(w) } qlpvt <- function(dataFrame, rows=NULL, columns=NULL, calculations=NULL, ...) { arguments <- list(...) checkArgument(3, TRUE, "", "qlpvt", dataFrame, missing(dataFrame), allowMissing=FALSE, allowNull=FALSE, allowedClasses="data.frame") checkArgument(3, TRUE, "", "qlpvt", rows, missing(rows), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qlpvt", columns, missing(columns), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(3, TRUE, "", "qlpvt", calculations, missing(calculations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") argumentCheckMode <- arguments$argumentCheckMode if(is.null(argumentCheckMode)) argumentCheckMode <- "auto" compatibility <- arguments$compatibility dataName <- deparse(substitute(dataFrame)) pt <- buildPivot(functionName="qlpvt", argumentCheckMode=argumentCheckMode, dataFrame=dataFrame, dataName=dataName, rows=rows, columns=columns, calculations=calculations, format=arguments[["format"]], formats=arguments[["formats"]], totalsSpecified=("totals" %in% names(arguments)), totals=arguments[["totals"]], compatibility=compatibility) return(pt$getLatex(caption=arguments$caption, label=arguments$label)) } addCalculations <- function(pt, calculations, format=NULL, formats=NULL) { nms <- names(calculations) for(i in 1:length(calculations)) { calc <- calculations[i] nme <- nms[i] if(is.null(nme)) nme <- paste0("calc", sprintf("%06d", i)) cf <- NULL if(is.null(format)==FALSE) cf <- format else { if(is.null(formats)==FALSE) { if(length(formats)>=i) cf <-formats[[i]] } } pt$defineCalculation(calculationName=make.names(nme), caption=nme, summariseExpression=calc, format=cf) } } buildPivot <- function(functionName=NULL, argumentCheckMode=NULL, dataFrame=NULL, dataName=NULL, rows=NULL, columns=NULL, calculations=NULL, format=NULL, formats=NULL, totalsSpecified=FALSE, totals=NULL, theme=NULL, replaceExistingStyles=FALSE, tableStyle=NULL, headingStyle=NULL, cellStyle=NULL, totalStyle=NULL, compatibility=compatibility) { if(is.null(dataFrame)) stop(paste0(functionName, "(): dataFrame argument must not be NULL."), call. = FALSE) if(!is.data.frame(dataFrame)) stop(paste0(functionName, "(): dataFrame argument must be a data frame."), call. = FALSE) if((!is.null(rows))&&(!anyNA(rows))) { if(!is.character(rows)) stop(paste0(functionName, "(): rows must be a character vector."), call. = FALSE) } if((!is.null(columns))&&(!anyNA(columns))) { if(!is.character(columns)) stop(paste0(functionName, "(): columns must be a character vector."), call. = FALSE) } if((length(rows[rows=="="])+length(columns[columns=="="]))>1) { stop(paste0(functionName, "(): Calculations cannot be added more than once."), call. = FALSE) } totalNames <- NULL totalCaptions <- NULL if((totalsSpecified==TRUE)&&(!is.null(totals))&&(length(totals)>0)) { if(is.character(totals)) { totalNames <- totals } else if(is.list(totals)) { for(i in 1:length(totals)) { if(!is.character(totals[[i]])) { stop(paste0(functionName, "(): elements of the totals list must be character values."), call. = FALSE) } } totalNames <- names(totals) totalCaptions <- totals } else { stop(paste0(functionName, "(): totals must be a character vector."), call. = FALSE) } } pt <- PivotTable$new(argumentCheckMode=argumentCheckMode, theme=theme, replaceExistingStyles=replaceExistingStyles, tableStyle=tableStyle, headingStyle=headingStyle, cellStyle=cellStyle, totalStyle=totalStyle, compatibility=compatibility) pt$addData(dataFrame, dataName=dataName) bCalculationsAdded <- FALSE if((!is.null(rows))&&(!anyNA(rows))) { for(i in 1:length(rows)) { if(rows[i]=="=") { if(bCalculationsAdded==TRUE) stop(paste0(functionName, "(): Calculations cannot be added more than once."), call. = FALSE) addCalculations(pt, calculations, format=format, formats=formats) pt$addRowCalculationGroups() bCalculationsAdded <- TRUE } else { includeTotal <- FALSE totalCaption <- NULL if(totalsSpecified==FALSE) includeTotal <- TRUE else if(rows[i] %in% totalNames) { includeTotal <- TRUE totalCaption <- totalCaptions[[rows[i]]] } if(is.null(totalCaption)) totalCaption <- "Total" pt$addRowDataGroups(rows[i], addTotal=includeTotal, totalCaption=totalCaption) } } } if((!is.null(columns))&&(!anyNA(columns))) { for(i in 1:length(columns)) { if(columns[i]=="=") { if(bCalculationsAdded==TRUE) stop(paste0(functionName, "(): Calculations cannot be added more than once."), call. = FALSE) addCalculations(pt, calculations, format=format, formats=formats) pt$addColumnCalculationGroups() bCalculationsAdded <- TRUE } else { includeTotal <- FALSE totalCaption <- NULL if(totalsSpecified==FALSE) includeTotal <- TRUE else if(columns[i] %in% totalNames) { includeTotal <- TRUE totalCaption <- totalCaptions[[columns[i]]] } if(is.null(totalCaption)) totalCaption <- "Total" pt$addColumnDataGroups(columns[i], addTotal=includeTotal, totalCaption=totalCaption) } } } if(bCalculationsAdded==FALSE) { addCalculations(pt, calculations, format=format, formats=formats) pt$addColumnCalculationGroups() } return(pt) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(leanpubr) slug = "biostatmethods" res = lp_summary(slug, error = FALSE, verbose = TRUE) res$content
context("prop_miss") test_that("prop_miss handles 0 cases as I expect",{ expect_equal(prop_miss(0), 0) expect_equal(prop_miss(TRUE), 0) expect_equal(prop_miss(numeric(0)),NaN) expect_equal(prop_miss(iris[0]),NaN) }) test_that("prop_miss correctly counts the proportion of missings",{ expect_equal(prop_miss(c(0,NA,120,NA)),0.5) expect_equal(prop_miss(c(NA,NA,120,NA)),0.75) expect_equal(prop_miss(c(NA,NA,NA,NA)),1) expect_equal(prop_miss(c(1,2,3,4,5)),0) }) test_that("prop_miss works for dataframes",{ expect_true(dplyr::near(round(prop_miss(airquality),5), 0.047930)) })
FrF2 <- function(nruns=NULL, nfactors=NULL, factor.names = if(!is.null(nfactors)) {if(nfactors<=50) Letters[1:nfactors] else paste("F",1:nfactors,sep="")} else NULL, default.levels = c(-1,1), ncenter=0, center.distribute=NULL, generators=NULL, design=NULL, resolution=NULL, select.catlg=catlg, estimable=NULL, clear=TRUE, method="VF2", sort="natural", ignore.dom=!isTRUE(all.equal(blocks,1)), useV = TRUE, firsthit = FALSE, res3=FALSE, max.time=60, perm.start=NULL, perms=NULL, MaxC2=FALSE, replications=1, repeat.only=FALSE, randomize=TRUE, seed=NULL, alias.info=2, blocks=1, block.name="Blocks", block.old=FALSE, force.godolphin=FALSE, bbreps=replications, wbreps=1, alias.block.2fis = FALSE, hard=NULL, check.hard=10, WPs=1, nfac.WP=0, WPfacs=NULL, check.WPs=10, ...){ creator <- sys.call() if (!is.logical(block.old)) stop("block.old must be logical") if (block.old && ! identical(blocks, 1)){ cc <- as.list(creator) cc$block.old <- NULL cc[[1]] <- FrF2old cc <- as.call(cc) erg <- eval(cc) di <- design.info(erg) di$creator <- creator di$block.old <- block.old design.info(erg) <- di return(erg) } catlg.name <- deparse(substitute(select.catlg)) nichtda <- "try-error" %in% class(try(eval(parse(text=paste(catlg.name,"[1]",sep=""))),silent=TRUE)) if (nichtda){ catlgs128 <- c("catlg128.8to15","catlg128.26to33",paste("catlg128",16:25,sep=".")) if (catlg.name %in% catlgs128){ if (!requireNamespace("FrF2.catlg128", quietly=TRUE, character.only=TRUE)) stop("Package FrF2.catlg128 is not available") if (packageVersion("FrF2.catlg128") < numeric_version(1.2)){ if (catlg.name %in% catlgs128[c(1,3:11)]) stop("For this version of package FrF2.catlg128,\n", "load ", catlg.name, " with the command data(", catlg.name,")\n", "and then rerun the FrF2 command.\n", "Alternatively, install the latest version of package FrF2.catlg128.") else stop("You need to get the latest version of package FrF2.catlg128 for using ", catlg.name) } } else stop(catlg.name, " not available") } if (!"catlg" %in% class(select.catlg)) stop("invalid choice for select.catlg") if (!is.numeric(ncenter)) stop("ncenter must be a number") if (!length(ncenter)==1) stop("ncenter must be a number") if (!ncenter==floor(ncenter)) stop("ncenter must be an integer number") if (is.null(center.distribute)){ if (!randomize) center.distribute <- min(ncenter, 1) else center.distribute <- min(ncenter, 3)} if (!is.numeric(center.distribute)) stop("center.distribute must be a number") if (!center.distribute==floor(center.distribute)) stop("center.distribute must be an integer number") if (center.distribute > ncenter) stop("center.distribute can be at most ncenter") if (randomize & center.distribute==1) warning("running all center point runs together is usually not a good idea.") block.name <- make.names(block.name) if (ncenter>0 && !identical(WPs,1)) stop("center points for split plot designs are not supported") if (!(is.null(generators) || (identical(WPs,1) || !is.null(WPfacs)))) stop("generators can only be used with split-plot designs, if WPfacs are specified.") if (!is.null(nruns)) if (ncenter>0) if (center.distribute > nruns + 1) stop("center.distribute must not be larger than nruns+1") if (!(is.null(generators) || is.null(design))) stop("generators and design must not be specified together.") if (is.null(nruns) & !(is.null(generators))) stop("If generators is specified, nruns must be given.") if (!(is.null(generators) || is.null(estimable))) stop("generators and estimable must not be specified together.") if (!(identical(blocks,1) || is.null(estimable))){ if (!(is.numeric(blocks) && length(blocks)==1)) stop("estimable can only be combined with automatic blocking.") if (!clear) message("clear=FALSE will be ignored, ", "as estimability for blocked designs is only implemented for clear 2fis.") } igdom <- ignore.dom if (!(is.null(design) || is.null(estimable))){ message("estimability is only attempted for the specified design") igdom <- TRUE } if (!is.null(useV)) { if (!is.logical(useV)) stop("useV must be logical") } if (!is.logical(firsthit)) stop("firsthit must be logical") if (!(identical(WPs,1) || is.null(estimable))) stop("WPs and estimable must not be specified together.") if (!(is.null(hard) | is.null(estimable))) stop("hard and estimable must not be specified together.") if (!(identical(blocks,1) || identical(WPs,1))) stop("blocks and WPs must not be specified together.") if (!(identical(blocks,1) || is.null(hard))) stop("blocks and hard must not be specified together.") if (!(identical(WPs,1) || is.null(hard))) stop("WPs and hard must not be specified together.") if (identical(blocks,1) & !identical(wbreps,1)) stop("wbreps must not differ from 1, if blocks = 1.") if (!(is.null(WPfacs) || identical(WPs,1)) && is.null(design) && is.null(generators)) stop("WPfacs requires explicit definition of a design via design or generators.") if (identical(nfac.WP,0) && is.null(WPfacs) && !identical(WPs,1)) stop("WPs whole plots require specification of whole plot factors", "through nfac.WP or WPfacs!") if ((nfac.WP > 0 || !is.null(WPfacs)) && identical(WPs, 1)) stop("WPs must be specified for creating a split-plot design") if (!(is.null(resolution) || is.null(estimable))) stop("You can only specify resolution OR estimable.") if (!(is.null(resolution) || is.null(nruns))) warning("resolution is ignored, if nruns is given.") if (default.levels[1]==default.levels[2]) stop("Both default levels are identical.") if (!(is.logical(clear) & is.logical(res3) & is.logical(MaxC2) & is.logical(repeat.only) & is.logical(randomize) & is.logical(alias.block.2fis) & is.logical(force.godolphin))) stop("clear, res3, MaxC2, repeat.only, randomize, alias.block.2fis and force.godolphin must be logicals (TRUE or FALSE).") if (!is.numeric(max.time)) stop("max.time must be a positive maximum run time for searching a design with estimable given and clear=FALSE.") if (!is.numeric(check.hard)) stop("check.hard must be an integer number.") if (!is.numeric(check.WPs)) stop("check.WPs must be an integer number.") check.hard <- floor(check.hard) check.WPs <- floor(check.WPs) if (!is.numeric(bbreps)) stop("bbreps must be an integer number.") if (!is.numeric(wbreps)) stop("wbreps must be an integer number.") if (!is.numeric(replications)) stop("replications must be an integer number.") if (bbreps > 1 & identical(blocks,1) & !replications > 1) stop("Use replications, not bbreps, for specifying replications for unblocked designs.") if (!alias.info %in% c(2,3)) stop("alias.info can be 2 or 3 only.") if (!(is.numeric(default.levels) | is.character(default.levels))) stop("default.levels must be a numeric or character vector of length 2") if (!length(default.levels) ==2) stop("default.levels must be a numeric or character vector of length 2") if (!(is.null(hard) | is.numeric(hard))) stop("hard must be numeric.") if (!(is.null(resolution) | is.numeric(resolution))) stop("resolution must be numeric.") if (is.numeric(resolution)) if(!(resolution == floor(resolution) & resolution>=3)) stop("resolution must be an integer number (at least 3), if specified.") res.WP <- NULL if (!is.null(design)){ if (!is.character(design)) stop("design must be a character string.") if (!length(design)==1) stop("design must be one character string.") if (design %in% names(select.catlg)){ cand <- select.catlg[design] if (!is.null(nruns)) {if (!nruns==cand[[1]]$nruns) stop("selected design does not have the desired number of runs.")} else nruns <- cand[[1]]$nruns if (!is.null(factor.names)) {if (!length(factor.names)==cand[[1]]$nfac) stop("selected design does not have the number of factors specified in factor.names.")} if (!is.null(nfactors)) {if (!nfactors==cand[[1]]$nfac) stop("selected design does not have the number of factors specified in nfactors.")} else nfactors <- cand[[1]]$nfac } else stop("invalid entry for design") } if (!is.null(nruns)){ k <- round(log2(nruns)) if (!2^k==nruns) stop("nruns must be a power of 2.") if (nruns < 4 | nruns > 4096) stop("less than 4 or more than 4096 runs are not covered by function FrF2.") } if (is.null(factor.names) && is.null(nfactors) && (is.null(nruns) || is.null(generators)) && is.null(estimable)) stop("The number of factors must be specified via nfactors, via factor.names, via estimable, through selecting one specific catalogued design or via nruns together with generators.") if (!is.null(factor.names) && !(is.character(factor.names) || is.list(factor.names)) ) stop("factor.names must be a character vector or a list.") if (is.null(nfactors)) {if (!is.null(factor.names)) nfactors <- length(factor.names) else if (!is.null(generators)) nfactors <- length(generators)+k } if (!is.null(estimable)) { if (!is.character(sort)) stop("option sort must be a character string") if (!is.character(method)) stop("option method must be a character string") if (!sort %in% c("natural","high","low")) stop("invalid choice for option sort") if (clear && !method %in% c("LAD","VF2")) stop("invalid choice for option method") estimable <- estimable.check(estimable, nfactors, factor.names) if (is.null(nfactors)) nfactors <- estimable$nfac estimable <- estimable$estimable if (is.null(nruns)) { nruns <- nfactors+ncol(estimable)+1 + (nfactors+ncol(estimable)+1)%%2 if (!isTRUE(all.equal(log2(nruns) %% 1,0))) nruns <- 2^(floor(log2(nruns))+1) k <- round(log2(nruns)) if (k<3) stop("Please specify nruns and/or nfactors. Calculated values are unreasonable.") } if (is.null(perm.start)) perm.start <- 1:nfactors else if (!is.numeric(perm.start)) stop ("perm.start must be NULL or a numeric permutation vector of length nfactors.") if (!all(sort(perm.start)==1:nfactors)) stop ("perm.start must be NULL or a numeric permutation vector of length nfactors.") if (!is.null(perms)) { if (!is.matrix(perms) | !is.numeric(perms)) stop("perms must be a numeric matrix.") if (!ncol(perms)==nfactors) stop ("matrix perms must have nfactors columns.") if (any(apply(perms,1,function(obj) any(!sort(obj)==1:nfactors)))) stop("Each row of perms must be a permutation of 1:nfactors.") } if (is.null(design)) cand <- select.catlg } if (!nfactors==floor(nfactors)) stop("nfactors must be an integer number.") if (!is.null(factor.names) && !length(factor.names)==nfactors) stop("There must be nfactors factor names, if any.") if (is.null(factor.names)) if(nfactors<=50) factor.names <- Letters[1:nfactors] else factor.names <- paste("F",1:nfactors,sep="") if (!((is.character(default.levels) | is.numeric(default.levels)) & length(default.levels)==2) ) stop("default.levels must be a vector of 2 levels.") if (is.list(factor.names)){ if (is.null(names(factor.names))){ if (nfactors<=50) names(factor.names) <- Letters[1:nfactors] else names(factor.names) <- paste("F", 1:nfactors, sep="") } if (any(factor.names=="")) factor.names[which(factor.names=="")] <- list(default.levels)} else {hilf <- vector("list",nfactors) names(hilf) <- factor.names hilf[1:nfactors]<-list(default.levels) factor.names <- hilf} names(factor.names) <- make.names(names(factor.names), unique=TRUE) if (ncenter > 0) if(any(is.na(sapply(factor.names,"is.numeric")))) stop("Center points are implemented for experiments with all factors quantitative only.") genspec <- FALSE if (!is.null(generators)){ genspec <- TRUE generators <- gen.check(k, generators) g <- nfactors - k if (!length(generators)== g) stop("This design in ", nruns, " runs with ", nfactors," factors requires ", g, " generators.") res <- NA; nclear.2fis<-NA; clear.2fis<-NULL;all.2fis.clear<-NA if (g<10) wl <- words.all(k, generators,max.length=6) else if (g<15) wl <- words.all(k, generators,max.length=5) else if (g<20) wl <- words.all(k, generators,max.length=4) else if (g>=20) wl <- alias3fi(k, generators, order=2) WLP <- NULL clear.2fis <- combn(nfactors, 2) hilf <- rep(TRUE, choose(nfactors, 2)) wl4 <- wl[[2]] wl4 <- wl4[lengths(wl4)==4] if (length(wl4) > 0) for (i in 1:choose(nfactors, 2)) if (any(sapply(wl4, function(obj) all(clear.2fis[,i] %in% obj)))) hilf[i] <- FALSE clear.2fis <- clear.2fis[,hilf] nclear.2fis <- ncol(clear.2fis) all.2fis.clear <- (nclear.2fis==choose(nfactors, 2)) if (g < 20){ WLP <- wl$WLP if (all(WLP==0)) res <- Inf else res <- min(as.numeric(names(WLP)[which(WLP>0)])) if (res==Inf) {if (g<10) res="7+" else if (g<15) res="6+" else if (g<20) res="5+" } } else{ if (!is.list(wl)) res="5+" else{ if (length(wl$"main")>0) res="3" else if (length(wl$"fi2")>0) res="4" else res="5+"} } gen <- sapply(generators,function(obj) which(sapply(Yates[1:(nruns-1)], function(obj2) isTRUE(all.equal(sort(abs(obj)),obj2))))) gen <- gen*sapply(generators, function(obj) sign(obj[1])) cand <- list(custom=list(res=res, nfac=nfactors, nruns=nruns, gen=unlist(gen), WLP=WLP, nclear.2fis=nclear.2fis, clear.2fis=clear.2fis, all.2fis.clear=all.2fis.clear)) class(cand) <- c("catlg","list") } if (!identical(blocks,1)) { blocks <- block.check(k, blocks, nfactors, factor.names) if (is.list(blocks)) k.block <- length(blocks) block.auto=FALSE map <- NULL } if (!is.list(blocks)){ if (blocks>1){ block.auto=TRUE if (is.null(nruns)) stop("blocks>1 only works if nruns is specified.") k.block <- round(log2(blocks)) if (blocks > nruns/2) stop("There cannot be more blocks than half the run size.") if (nfactors+blocks-1>=nruns) stop(paste(nfactors, "factors cannot be accomodated in", nruns, "runs with", blocks, "blocks.")) ntreat <- nfactors } } if (!is.null(hard)){ if (is.null(generators)){ if (is.null(nruns)){ cand <- select.catlg[which(res.catlg(select.catlg)>=resolution & nfac.catlg(select.catlg)==nfactors)] if (length(cand)==0) { message("full factorial design needed for achieving requested resolution") k <- nfactors nruns <- 2^k cand <- list(list(gen=numeric(0))) } else { nruns <- min(nruns.catlg(cand)) k <- round(log2(nruns)) cand <- cand[which(nruns.catlg(cand)==nruns)] } } else { if (nfactors > k) cand <- select.catlg[which(nfac.catlg(select.catlg)==nfactors & nruns.catlg(select.catlg)==nruns)] else cand <- list(list(gen=numeric(0))) } } if (hard == nfactors) stop("It does not make sense to choose hard equal to nfactors.") if (hard >= nruns/2) warning ("Do you really need to declare so many factors as hard-to-change ?") nfac.WP <- hard if (hard < nruns/2){ WPs <- NA if (length(cand[[1]]$gen) > 0) for (i in 1:min(length(cand),check.hard)){ leftadjust.out <- leftadjust(k,cand[[i]]$gen, early=hard, show=1) if (is.na(WPs) | WPs > 2^leftadjust.out$k.early) WPs <- 2^leftadjust.out$k.early } else WPs <- 2^hard } if (hard>=nruns/2 | WPs==nruns) { warning("There are so many hard-to-change factors that no good special design could be found. Randomization has been switched off.") randomize <- FALSE WPs <- 1 leftadjust.out <- leftadjust(k,cand[[1]]$gen,early=hard,show=1) generators <- leftadjust.out$gen } } if (!identical(WPs,1)) { if (is.null(nruns)) stop("WPs>1 only works if nruns is specified.") if (WPs > nruns/2) stop("There cannot be more whole plots (WPs) than half the run size.") k.WP <- round(log2(WPs)) if (!WPs == 2^k.WP) stop("WPs must be a power of 2.") if (!is.null(WPfacs) & nfac.WP==0){ nfac.WP <- length(WPfacs) if (nfac.WP < k.WP) stop("WPfacs must specify at least log2(WPs) whole plot factors.") } if (nfac.WP==0) stop("If WPs > 1, a positive nfac.WP or WPfacs must also be given.") if (nfac.WP < k.WP) { add <- k.WP - nfac.WP names.add <- rep(list(default.levels),add) names(names.add) <- paste("WP",(nfac.WP+1):(nfac.WP+add),sep="") nfactors <- nfactors + add factor.names <- c(factor.names[1:nfac.WP],names.add,factor.names[-(1:nfac.WP)]) nfac.WP <- k.WP warning("There are fewer factors than needed for a full factorial whole plot design. ", add, " dummy splitting factor(s) have been introduced.") } if (!is.null(WPfacs)) { WPfacs <- WP.check(k, WPfacs, nfac.WP, nfactors, factor.names) WPsnum <- as.numeric(chartr("F", " ", WPfacs)) WPsorig <- WPsnum } else {WPsorig <- WPsnum <- 1:nfac.WP } } if (!is.null(nruns)){ if (nfactors<=k && identical(blocks,1) && identical(WPs,1)) { if (nfactors==k) aus <- fac.design(2, k, factor.names=factor.names, replications=replications, repeat.only=repeat.only, randomize=randomize, seed=seed) else aus <- fac.design(2, nfactors, factor.names=factor.names, replications=replications*2^(k-nfactors), repeat.only=repeat.only, randomize=randomize, seed=seed) aus <- qua.design(aus, quantitative="none", contrasts=rep("contr.FrF2",nfactors)) if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute) di <- design.info(aus) di$creator <- creator di <- c(di, list(FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)) design.info(aus) <- di return(aus) } else { if (nfactors < k) stop("A full factorial for nfactors factors requires fewer than nruns runs. Please reduce the number of runs and introduce replications instead.") full <- FALSE if (nfactors == k) { full <- TRUE genspec <- TRUE generators <- as.list(numeric(0)) cand <- list(custom=list(res=Inf, nfac=nfactors, nruns=nruns, gen=numeric(0), WLP=c(0,0,0,0), nclear.2fis=choose(k,2), clear.2fis=combn(k,2), all.2fis.clear="all")) class(cand) <- c("catlg","list") } if (nfactors > nruns - 1) stop("You can accomodate at most ", nruns-1, " factors in a FrF2 design with ", nruns, " runs." ) g <- nfactors - k if (!is.null(estimable)) { desmat <- estimable(estimable, nfactors, nruns, clear=clear, res3=res3, max.time=max.time, select.catlg=cand, method=method,sort=sort, perm.start=perm.start, perms=perms, order=alias.info, ignore.dom=igdom) map <- desmat$map cand <- cand[names(map)] design.info <- list(type="FrF2.estimable", nruns=nruns, nfactors=nfactors, factor.names=factor.names, catlg.name = catlg.name, map=desmat$map, aliased=desmat$aliased, clear=clear, res3=res3, FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version) desmat <- desmat$design desmat <- as.matrix(sapply(desmat,function(obj) as.numeric(as.character(obj)))) rownames(desmat) <- 1:nrow(desmat) } else if (is.null(generators) && is.null(design)) cand <- select.catlg[nruns.catlg(select.catlg)==nruns & nfac.catlg(select.catlg)==nfactors] block.gen <- NULL if (!is.list(blocks)){ if (blocks > 1) { if ((g==0 || choose(nruns - 1 - nfactors, k.block) < 100000) && is.null(estimable) && !force.godolphin ){ for (i in 1:length(cand)){ if (g==0) {blockpick.out <- try(blockpick(k, gen=0, k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE) } else { if (is.null(generators)) blockpick.out <- try(blockpick(k, design=names(cand[i]), k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE) else blockpick.out <- try(blockpick(k, gen=cand[[i]]$gen, k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE) } if (!"try-error" %in% class(blockpick.out)) { blocks <- blockpick.out$blockcols block.gen <- unlist(c(blocks)) cand <- cand[i] cand[[1]]$gen <- c(cand[[1]]$gen, block.gen) blocks <- nfactors + (1:k.block) nfactors <- nfactors + k.block g <- g + k.block hilf <- factor.names factor.names <- vector("list", nfactors) factor.names[-blocks] <- hilf factor.names[blocks] <- list(default.levels) names(factor.names) <- c(names(hilf),paste("b",1:k.block,sep="")) blocks <- as.list(blocks) break } } } else{ for (i in 1:length(cand)){ if (is.null(useV)) useV <- cand[[1]]$res > 4 && !is.null(estimable) if (useV) X <- colpick(cand[i], k - k.block, estimable=estimable, quiet=TRUE, method=method, sort=sort, select.catlg = cand[i], res3=res3, firsthit=firsthit) else X <- colpickIV(cand[i], k - k.block, estimable=estimable, quiet=TRUE, method=method, sort=sort, select.catlg = cand[i], res3=res3, firsthit=firsthit) if (!is.null(X)) { cand <- cand[i] block.gen <- blockgencreate(X$X, p=g) block.gen <- sapply(block.gen, function(obj) which(names(Yates) %in% obj)) if (any(block.gen %in% cand[[1]]$gen)) warning("block generator coincides with main effect") cand[[1]]$gen <- c(cand[[1]]$gen, block.gen) blocks <- nfactors + 1:k.block nfactors <- nfactors + k.block cand[[1]]$nfactors <- nfactors g <- g + k.block if (!is.null(estimable)) map <- X$map hilf <- factor.names factor.names <- vector("list", nfactors) factor.names[-blocks] <- hilf factor.names[blocks] <- list(default.levels) names(factor.names) <- c(names(hilf), paste("b",1:k.block, sep="")) blocks <- as.list(blocks) break } } } if (!is.list(blocks)) { stopmsg <- "no adequate blocked design found" if (nruns >= 128 && !full) stopmsg <- c(stopmsg, " in catalogue ", deparse(substitute(select.catlg))) if (!alias.block.2fis) stopmsg <- c(stopmsg, " with 2fis unconfounded with blocks") if (!is.null(design)) stopmsg <- c(stopmsg, paste(" in design", design)) else { if (!is.null(estimable) && !full){ stopmsg <- c(stopmsg, paste(" in design", names(cand))) } if (!is.null(estimable) && !full){ if (ignore.dom) stopmsg <- c(stopmsg, " which is the first suitable element of select.catlg") else stopmsg <- c(stopmsg, " which is the first suitable dominating element of select.catlg") if (!useV && !nfactors==log2(nruns)) stopmsg <- c(stopmsg, " without trying to reshuffle map from unblocked fraction", " (useV=TRUE might be worth a try)") } } stop(stopmsg) } } } if (is.list(blocks)) { hilf.gen <- c(2^(0:(k-1)), cand[[1]]$gen) hilf.block.gen <- sapply(blocks, function(obj) as.intBase(paste(rowSums(do.call(cbind, lapply(obj, function(obj2) digitsBase(hilf.gen[obj2],2,k))))%%2, collapse="")) ) k.block.add <- length(intersect(hilf.block.gen, hilf.gen)) if (is.null(block.gen)) { ntreat <- nfactors - k.block.add block.gen <- hilf.block.gen } bf <- blockfull(blocks, k, hilf.gen) if (k.block > 1) {if (length(unique(bf)) < 2^k.block - 1) stop("specified blocks is invalid (dependencies)")} if (length(intersect(bf, hilf.gen)) > k.block.add){ if (alias.block.2fis && length(bf) > 4) warning(paste("Main effects of factors", paste(names(factor.names)[hilf.gen %in% bf], collapse=", "), "are confounded with blocks.", "The design is a split-plot design", "and has to be analyzed as such", "(only recommended in case of many blocks).", "Preferrably, construct it with arguments WPs and WPfacs.", "You may also want to try using function FF_from_X", "for obtaining a better block structure.")) else stop("main effects confounded with blocks") } hilf.gen <- setdiff(hilf.gen, block.gen) sel <- combn(ntreat, 2) nam2fis <- sapply(1:ncol(sel), function(obj) ifelse(ntreat<=50, paste0(Letters[sel[,obj]], collapse=":"), paste0("F",sel[,obj], collapse=":"))) twoficols <- sapply(1:ncol(sel), function(obj) as.intBase(paste(rowSums(do.call(cbind, lapply(sel[,obj], function(obj2) digitsBase(hilf.gen[obj2],2,k))))%%2, collapse="")) ) names(twoficols) <- nam2fis if (!alias.block.2fis) if (length(intersect(bf, twoficols)) > 0){ if (force.godolphin) stop("blocks aliased with 2-factor interactions, ", "although alias.block.2fis=FALSE; ", "force.godolphin=TRUE does not attempt ", "to avoid confounding of non-clear 2fis") else stop("blocks aliased with 2-factor interactions, ", "although alias.block.2fis=FALSE") } if (alias.info == 3){ sel <- combn(ntreat, 3) nam3fis <- sapply(1:ncol(sel), function(obj) ifelse(ntreat<=50, paste0(Letters[sel[,obj]], collapse=":"), paste0("F",sel[,obj], collapse=":"))) threeficols <- sapply(1:ncol(sel), function(obj) as.intBase(paste(rowSums(do.call(cbind, lapply(sel[,obj], function(obj2) digitsBase(hilf.gen[obj2],2,k))))%%2, collapse="")) ) names(threeficols) <- nam3fis } if (is.null(generators)) generators <- gen.check(k, hilf.gen[-(1:k)]) } if (WPs > 1){ WP.auto <- FALSE map <- 1:k orignew <- WPsorig if (is.null(WPfacs)){ WP.auto <- TRUE max.res.5 <- c(1,2,3, 5, 6, 8, 11, 17) for (i in 1:length(cand)){ if (is.null(generators)){ if (cand[[i]]$res>=5 & nfac.WP > max.res.5[k.WP]) next if (cand[[i]]$res>=4 & nfac.WP > WPs/2) next } if (nfac.WP > WPs/2 || nfac.WP <= k.WP) splitpick.out <- try(splitpick(k, cand[[i]]$gen, k.WP=k.WP, nfac.WP=nfac.WP, show=1),TRUE) else splitpick.out <- try(splitpick(k, cand[[i]]$gen, k.WP=k.WP, nfac.WP=nfac.WP, show=check.WPs),TRUE) if (!"try-error" %in% class(splitpick.out)) { WPfacs <- 1:k.WP if (nfac.WP > k.WP) WPfacs <- c(WPfacs, (k + 1):(k+nfac.WP-k.WP)) cand <- cand[i] cand[[1]]$gen <- splitpick.out$gen[1,] res.WP <- splitpick.out$res.WP[1] map <- splitpick.out$perms[1,] break } } if (is.null(res.WP)){ if (nruns >= 2^nfactors) { res.WP <- Inf WP.auto <- TRUE WPfacs <- 1:k.WP if (!k.WP == nfac.WP) stop(nfac.WP, " whole plot factors cannot be accomodated in ", (2^k.WP), " whole plots for a full factorial. Please request smaller design with replication instead.") cand <- list(list(gen=numeric(0))) } else stop("no adequate splitplot design found") } orignew <- WPsnum <- WPfacs WPfacs <- paste("F",WPfacs,sep="") } } } } else { if (is.null(resolution) && is.null(estimable)) stop("At least one of nruns or resolution or estimable must be given.") if (!is.null(resolution)){ cand <- select.catlg[which(res.catlg(select.catlg)>=resolution & nfac.catlg(select.catlg)==nfactors)] if (length(cand)==0) { message("full factorial design needed") aus <- fac.design(2, nfactors, factor.names=factor.names, replications=replications, repeat.only=repeat.only, randomize=randomize, seed=seed) for (i in 1:nfactors) if (is.factor(aus[[i]])) contrasts(aus[[i]]) <- contr.FrF2(2) if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute) return(aus) } } else{ cand <- select.catlg[which(nfac.catlg(select.catlg)==nfactors)] if (length(cand)==0) stop("No design listed in catalogue ", deparse(substitute(select.catlg)), " fulfills all requirements.") } } if (MaxC2 && is.null(estimable) && is.null(generators) ) { if (!res3) cand <- cand[which.max(sapply(cand[which(sapply(cand, function(obj) obj$res)==max(sapply(cand, function(obj) obj$res)))], function(obj) obj$nclear.2fis))] else cand <- cand[which.max(sapply(cand, function(obj) obj$nclear.2fis))] } if (is.null(nruns)) {nruns <- cand[[1]]$nruns k <- round(log2(nruns)) g <- nfactors - k} if (is.null(estimable) || is.list(blocks)){ destxt <- "expand.grid(c(-1,1)" for (i in 2:k) destxt <- paste(destxt,",c(-1,1)",sep="") destxt <- paste("as.matrix(",destxt,"))",sep="") desmat <- eval(parse(text=destxt)) if (is.character(WPfacs) | is.list(blocks)) { desmat <- desmat[,k:1] } if (!is.null(hard)) { desmat <- rep(c(-1,1),each=nruns/2) for (i in 2:k) desmat <- cbind(desmat,rep(c(1,-1,-1,1),times=(2^i)/4,each=nruns/(2^i))) } if (g>0) for (i in 1:g) desmat <- cbind(desmat, sign(cand[[1]]$gen[i][1])*apply(desmat[,unlist(Yates[abs(cand[[1]]$gen[i])])],1,prod)) if (WPs > 1) { if (!WP.auto) { hilf <- apply(desmat[,WPsorig,drop=FALSE],1,paste,collapse="") if (!length(table(hilf))==WPs) stop("The specified design creates ", length(table(hilf)), " and not ", WPs, " whole plots.") for (j in setdiff(1:nfactors,WPsorig)) if (!length(table(paste(hilf,desmat[,j],sep="")))>WPs) stop("Factor ", names(factor.names)[j], " is also a whole plot factor.") if (nfac.WP<3) res.WP <- Inf else res.WP <- GR((3-desmat[,WPsorig,drop=FALSE])%/%2)$GR%/%1 } } if (is.null(rownames(desmat))) rownames(desmat) <- 1:nruns if (is.list(blocks)) { if (is.null(block.gen)) block.gen <- blocks hilf <- blocks for (i in 1:k.block) hilf[[i]] <- apply(desmat[,hilf[[i]],drop=FALSE],1,prod) Blocks <- factor(as.numeric(factor(apply(matrix(as.character(unlist(hilf)), ncol=k.block), 1, paste, collapse="")))) hilf <- order(Blocks, as.numeric(rownames(desmat))) desmat <- desmat[hilf,] Blocks <- Blocks[hilf] contrasts(Blocks) <- contr.FrF2(levels(Blocks)) nblocks <- 2^length(blocks) blocksize <- nruns / nblocks block.no <- paste(Blocks,rep(1:blocksize,nblocks),sep=".") } if (is.character(WPfacs)) { desmat <- desmat[,c(WPsnum,setdiff(1:nfactors,WPsnum))] factor.names <- factor.names[c(WPsorig,setdiff(1:nfactors,WPsorig))] plotsize <- round(nruns/WPs) if (is.null(hard)){ hilf <- ord(cbind(desmat[,1:nfac.WP],as.numeric(rownames(desmat)))) desmat <- desmat[hilf,] } wp.no <- paste(rep(1:WPs,each=plotsize),rep(1:plotsize,WPs),sep=".") } } if (randomize & !is.null(seed)) set.seed(seed) if (!(is.list(blocks) || WPs > 1)){ rand.ord <- rep(1:nruns,replications) if (replications > 1 & repeat.only) rand.ord <- rep(1:nruns,each=replications) if (randomize & !repeat.only) for (i in 1:replications) rand.ord[((i-1)*nruns+1):(i*nruns)] <- sample(nruns) if (randomize & repeat.only) rand.ord <- rep(sample(1:nruns), each=replications) } else { if (is.list(blocks)){ rand.ord <- rep(1:nruns, bbreps * wbreps) if ((!repeat.only) & !randomize) for (i in 0:(nblocks-1)) for (j in 1:wbreps) rand.ord[(i*blocksize*wbreps+(j-1)*blocksize+1):((i+1)*blocksize*wbreps+j*blocksize)] <- (i*blocksize+1):((i+1)*blocksize) rand.ord <- rep(rand.ord[1:(nruns*wbreps)],bbreps) if (repeat.only & !randomize) for (j in 1:wbreps) rand.ord[(i*blocksize*wbreps + (j-1)*blocksize + 1) : (i*blocksize*wbreps + j*blocksize)] <- sample((i%%nblocks*blocksize+1):(i%%nblocks*blocksize+blocksize)) if (wbreps > 1 & repeat.only) rand.ord <- rep(1:nruns,bbreps, each=wbreps) if ((!repeat.only) & randomize) for (i in 0:(nblocks*bbreps-1)) for (j in 1:wbreps) rand.ord[(i*blocksize*wbreps + (j-1)*blocksize + 1) : (i*blocksize*wbreps + j*blocksize)] <- sample((i%%nblocks*blocksize+1):(i%%nblocks*blocksize+blocksize)) if (repeat.only & randomize) for (i in 0:(nblocks*bbreps-1)) rand.ord[(i*blocksize*wbreps + 1) : ((i+1)*blocksize*wbreps)] <- rep(sample((((i%%nblocks)*blocksize)+1): ((i%%nblocks+1)*blocksize)),each=wbreps) } else { rand.ord <- rep(1:nruns,replications) if (replications > 1 & repeat.only) rand.ord <- rep(1:nruns,each=replications) if ((!repeat.only) & randomize){ for (i in 1:(WPs*replications)) rand.ord[((i-1)*plotsize+1):(i*plotsize)] <- sample(rand.ord[((i-1)*plotsize+1):(i*plotsize)]) for (i in 1:replications){ if (is.null(hard)){ WPsamp <- sample(WPs) WPsamp <- (rep(WPsamp,each=plotsize)-1)*plotsize + rep(1:plotsize,WPs) rand.ord[((i-1)*plotsize*WPs+1):(i*plotsize*WPs)] <- rand.ord[(i-1)*plotsize*WPs + WPsamp] } } } if (repeat.only & randomize){ for (i in 1:WPs) rand.ord[((i-1)*plotsize*replications+1):(i*plotsize*replications)] <- rand.ord[(i-1)*plotsize*replications + rep(replications*(sample(plotsize)-1),each=replications) + rep(1:2,each=plotsize)] if (is.null(hard)){ WPsamp <- sample(WPs) WPsamp <- (rep(WPsamp,each=plotsize*replications)-1)*plotsize*replications + rep(1:(plotsize*replications),WPs) rand.ord <- rand.ord[WPsamp] } } } } orig.no <- rownames(desmat) orig.no <- orig.no[rand.ord] orig.no.levord <- sort(as.numeric(orig.no),index=TRUE)$ix rownames(desmat) <- NULL desmat <- desmat[rand.ord,] if (is.list(blocks)) { Blocks <- Blocks[rand.ord] block.no <- block.no[rand.ord] } if (WPs > 1) wp.no <- wp.no[rand.ord] colnames(desmat) <- names(factor.names) if (is.list(blocks)) orig.no <- paste(orig.no,block.no,sep=".") if (WPs > 1) orig.no <- paste(orig.no,wp.no,sep=".") orig.no.rp <- orig.no if (bbreps * wbreps > 1){ if (bbreps > 1) { if (repeat.only & !is.list(blocks)) orig.no.rp <- paste(orig.no.rp, rep(1:bbreps,nruns),sep=".") else orig.no.rp <- paste(orig.no.rp, rep(1:bbreps,each=nruns*wbreps),sep=".") } if (wbreps > 1){ if (repeat.only) orig.no.rp <- paste(orig.no.rp, rep(1:wbreps,nruns*bbreps),sep=".") else orig.no.rp <- paste(orig.no.rp, rep(1:wbreps,each=blocksize,nblocks*bbreps),sep=".") } } desdf <- data.frame(desmat) quant <- rep(FALSE,nfactors) for (i in 1:nfactors) { desdf[,i] <- des.recode(desdf[,i],"-1=factor.names[[i]][1];1=factor.names[[i]][2]") quant[i] <- is.numeric(desdf[,i]) desdf[,i] <- factor(desdf[,i],levels=factor.names[[i]]) contrasts(desdf[,i]) <- contr.FrF2(2) } if (is.list(blocks)) { desdf <- cbind(Blocks, desdf, stringsAsFactors=TRUE) hilf <- blocks if (all(sapply(hilf,length)==1) && !block.auto) { hilf <- as.numeric(hilf) + 1 levels(desdf$Blocks) <- unique(apply(desdf[,hilf,drop=FALSE],1,paste,collapse="")) } colnames(desdf)[1] <- block.name hilf <- blocks hilf <- as.numeric(hilf[which(sapply(hilf,length)==1)]) if (length(hilf)>0) { desdf <- desdf[,-(hilf+1)] desmat <- desmat[,-hilf] factor.names <- factor.names[-hilf] } if (!is.null(estimable)) { factor.names <- factor.names[invperm(map)] names(desdf) <- c(block.name, names(factor.names)) } desmat <- cbind(model.matrix(~desdf[,1])[,-1],desmat) colnames(desmat)[1:(2^k.block-1)] <- paste(block.name,1:(2^k.block-1),sep="") MEcols <- hilf.gen if (ntreat<=50) names(MEcols) <- Letters[1:ntreat] else names(MEcols) <- paste0("F",1:ntreat) effs <- c(MEcols, twoficols) if (alias.info==3) effs <- c(effs, threeficols) aliased.with.blocks <- names(effs[effs %in% bf]) effs <- effs[!effs %in% bf] aliased <- split(names(effs), effs) aliased <- aliased[lengths(aliased) > 1] if (nfactors<=50) leg <- paste(Letters[1:ntreat],names(factor.names),sep="=") else leg <- paste(paste("F",1:ntreat,sep=""),names(factor.names),sep="=") if (length(aliased.with.blocks)==0) aliased.with.blocks <- "none" else { aliased.with.blocks <- recalc.alias.block.new(aliased.with.blocks, leg) aliased.with.blocks <- aliased.with.blocks[ord(data.frame(nchar(aliased.with.blocks),aliased.with.blocks))] if (nfactors <= 50) aliased.with.blocks <- gsub(":","",aliased.with.blocks) } if (length(aliased) > 0) aliased <- struc.aliased.new(struc=recalc.alias.block.new(aliased, leg), nk=nfactors, order=alias.info) ntreat <- ncol(desdf) - 1 if (block.auto) factor.names <- factor.names[1:ntreat] design.info <- list(type="FrF2.blocked", block.name=block.name, nruns=nruns, nfactors=ntreat, nblocks=nblocks, block.gen=block.gen, blocksize=blocksize, ntreat=ntreat,factor.names=factor.names, aliased.with.blocks=aliased.with.blocks, aliased=aliased, bbreps=bbreps, wbreps=wbreps, FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version) if (!is.null(generators) && genspec) { if (g>0) design.info <- c(design.info, list(base.design=paste("generator columns:", paste(setdiff(cand[[1]]$gen, block.gen), collapse=", ")))) else design.info <- c(design.info, list(base.design="full factorial")) } else design.info <- c(design.info, list(catlg.name = catlg.name, base.design=names(cand[1]))) if (!is.null(estimable)) design.info <- c(design.info, list(map=map)) if (bbreps>1) { hilflev <- paste(rep(levels(desdf[,1]), each=bbreps), rep(1:bbreps, nblocks), sep=".") desdf[,1] <- factor(paste(desdf[,1], rep(1:bbreps, each=nruns*wbreps),sep="."), levels=hilflev) } } if (WPs > 1){ if (alias.info==3) aliased <- aliases(lm((1:nrow(desmat))~(.)^3,data=data.frame(desmat)))$aliases else aliased <- aliases(lm((1:nrow(desmat))~(.)^2,data=data.frame(desmat)))$aliases aliased <- aliased[which(sapply(aliased,length)>1)] if (length(aliased) > 0){ if (nfactors<=50) leg <- paste(Letters[1:nfactors],names(factor.names),sep="=") else leg <- paste(paste("F",1:nfactors,sep=""),names(factor.names),sep="=") aliased <- struc.aliased(recalc.alias.block(aliased, leg), nfactors, alias.info) } design.info <- list(type="FrF2.splitplot", nruns=nruns, nfactors=nfactors, nfac.WP=nfac.WP, nfac.SP=nfactors-nfac.WP, factor.names=factor.names, nWPs=WPs, plotsize=nruns/WPs, res.WP=res.WP, aliased=aliased, FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version) if (!is.null(generators) && genspec){ gennam <- names(generators) if (is.null(gennam)) if (is.list(generators)) gennam <- sapply(generators, function(obj) paste0(Letters[sort(obj)], collapse="")) else if(is.character(generators)) gennam <- generators gencols <- sapply(gennam, function(obj) which(names(Yates)[1:(nruns-1)] == obj)) design.info <- c(design.info, list(base.design=paste("generator columns:", paste(gencols, collapse=", ")), map=map, orig.fac.order = c(orignew, setdiff(1:nfactors,orignew)))) } else design.info <- c(design.info, list(catlg.name = catlg.name, base.design=names(cand[1]), map=map, orig.fac.order = c(orignew, setdiff(1:nfactors,orignew)))) } if (is.null(estimable) && is.null(generators) && !(is.list(blocks) || WPs > 1)) design.info <- list(type="FrF2", nruns=nruns, nfactors=nfactors, factor.names=factor.names, catlg.name = catlg.name, catlg.entry=cand[1], aliased = alias3fi(k,cand[1][[1]]$gen,order=alias.info), FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version) if ((!is.null(generators)) && !is.list(blocks) && !WPs > 1) { if (nfactors <= 50) names(generators) <- Letters[(k+1):nfactors] else names(generators) <- paste("F",(k+1):nfactors, sep="") gen.display <- paste(names(generators),sapply(generators,function(obj){ if (nfactors <= 50) paste(if (obj[1]<0) "-" else "", paste(Letters[abs(obj)],collapse=""),sep="") else paste(if (obj[1]<0) "-" else "", paste(paste("F",abs(obj),sep=""),collapse=":"),sep="")}), sep="=") design.info <- list(type="FrF2.generators", nruns=nruns, nfactors=nfactors, factor.names=factor.names, generators=gen.display, aliased = alias3fi(k,generators,order=alias.info), FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version) } aus <- desdf rownames(aus) <- rownames(desmat) <- 1:nrow(aus) class(aus) <- c("design","data.frame") attr(aus,"desnum") <- desmat orig.no <- factor(orig.no, levels=unique(orig.no[orig.no.levord])) orig.no.rp <- factor(orig.no.rp, levels=unique(orig.no.rp[orig.no.levord])) if (!(is.list(blocks) || WPs > 1)) attr(aus,"run.order") <- data.frame("run.no.in.std.order"=orig.no,"run.no"=1:nrow(desmat), "run.no.std.rp"=orig.no.rp, stringsAsFactors=TRUE) else attr(aus,"run.order") <- data.frame("run.no.in.std.order"=orig.no,"run.no"=1:nrow(desmat), "run.no.std.rp"=orig.no.rp, stringsAsFactors=TRUE) if (design.info$type=="FrF2.blocked") { if (design.info$wbreps==1) repeat.only <- FALSE design.info$block.old <- block.old nfactors <- ntreat } if (nfactors<=50) design.info$aliased <- c(list(legend=paste(Letters[1:nfactors],names(factor.names),sep="=")), design.info$aliased) else design.info$aliased <- c(list(legend=paste(paste("F",1:nfactors,sep=""),names(factor.names),sep="=")), design.info$aliased) attr(aus,"design.info") <- c(design.info, list(replications=replications, repeat.only=repeat.only, randomize=randomize, seed=seed, creator=creator)) if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute) aus }
dtdz = function(z, lambda0, q0) { term1 = (1.0 + z) term2 = 2.0 * (q0 + lambda0) * z + 1.0 - lambda0 term3 = (1.0 + z) * (1.0 +z) return(1.0 / (term1 * sqrt(term2 * term3 + lambda0))) }
mesh.hunif <- function (p, ...) { if (!is.matrix(p)) stop("Input `p' should be matrix.") return(rep(1, nrow(p))) }
NULL lookoutforvision_create_dataset <- function(ProjectName, DatasetType, DatasetSource = NULL, ClientToken = NULL) { op <- new_operation( name = "CreateDataset", http_method = "POST", http_path = "/2020-11-20/projects/{projectName}/datasets", paginator = list() ) input <- .lookoutforvision$create_dataset_input(ProjectName = ProjectName, DatasetType = DatasetType, DatasetSource = DatasetSource, ClientToken = ClientToken) output <- .lookoutforvision$create_dataset_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$create_dataset <- lookoutforvision_create_dataset lookoutforvision_create_model <- function(ProjectName, Description = NULL, ClientToken = NULL, OutputConfig, KmsKeyId = NULL) { op <- new_operation( name = "CreateModel", http_method = "POST", http_path = "/2020-11-20/projects/{projectName}/models", paginator = list() ) input <- .lookoutforvision$create_model_input(ProjectName = ProjectName, Description = Description, ClientToken = ClientToken, OutputConfig = OutputConfig, KmsKeyId = KmsKeyId) output <- .lookoutforvision$create_model_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$create_model <- lookoutforvision_create_model lookoutforvision_create_project <- function(ProjectName, ClientToken = NULL) { op <- new_operation( name = "CreateProject", http_method = "POST", http_path = "/2020-11-20/projects", paginator = list() ) input <- .lookoutforvision$create_project_input(ProjectName = ProjectName, ClientToken = ClientToken) output <- .lookoutforvision$create_project_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$create_project <- lookoutforvision_create_project lookoutforvision_delete_dataset <- function(ProjectName, DatasetType, ClientToken = NULL) { op <- new_operation( name = "DeleteDataset", http_method = "DELETE", http_path = "/2020-11-20/projects/{projectName}/datasets/{datasetType}", paginator = list() ) input <- .lookoutforvision$delete_dataset_input(ProjectName = ProjectName, DatasetType = DatasetType, ClientToken = ClientToken) output <- .lookoutforvision$delete_dataset_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$delete_dataset <- lookoutforvision_delete_dataset lookoutforvision_delete_model <- function(ProjectName, ModelVersion, ClientToken = NULL) { op <- new_operation( name = "DeleteModel", http_method = "DELETE", http_path = "/2020-11-20/projects/{projectName}/models/{modelVersion}", paginator = list() ) input <- .lookoutforvision$delete_model_input(ProjectName = ProjectName, ModelVersion = ModelVersion, ClientToken = ClientToken) output <- .lookoutforvision$delete_model_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$delete_model <- lookoutforvision_delete_model lookoutforvision_delete_project <- function(ProjectName, ClientToken = NULL) { op <- new_operation( name = "DeleteProject", http_method = "DELETE", http_path = "/2020-11-20/projects/{projectName}", paginator = list() ) input <- .lookoutforvision$delete_project_input(ProjectName = ProjectName, ClientToken = ClientToken) output <- .lookoutforvision$delete_project_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$delete_project <- lookoutforvision_delete_project lookoutforvision_describe_dataset <- function(ProjectName, DatasetType) { op <- new_operation( name = "DescribeDataset", http_method = "GET", http_path = "/2020-11-20/projects/{projectName}/datasets/{datasetType}", paginator = list() ) input <- .lookoutforvision$describe_dataset_input(ProjectName = ProjectName, DatasetType = DatasetType) output <- .lookoutforvision$describe_dataset_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$describe_dataset <- lookoutforvision_describe_dataset lookoutforvision_describe_model <- function(ProjectName, ModelVersion) { op <- new_operation( name = "DescribeModel", http_method = "GET", http_path = "/2020-11-20/projects/{projectName}/models/{modelVersion}", paginator = list() ) input <- .lookoutforvision$describe_model_input(ProjectName = ProjectName, ModelVersion = ModelVersion) output <- .lookoutforvision$describe_model_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$describe_model <- lookoutforvision_describe_model lookoutforvision_describe_project <- function(ProjectName) { op <- new_operation( name = "DescribeProject", http_method = "GET", http_path = "/2020-11-20/projects/{projectName}", paginator = list() ) input <- .lookoutforvision$describe_project_input(ProjectName = ProjectName) output <- .lookoutforvision$describe_project_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$describe_project <- lookoutforvision_describe_project lookoutforvision_detect_anomalies <- function(ProjectName, ModelVersion, Body, ContentType) { op <- new_operation( name = "DetectAnomalies", http_method = "POST", http_path = "/2020-11-20/projects/{projectName}/models/{modelVersion}/detect", paginator = list() ) input <- .lookoutforvision$detect_anomalies_input(ProjectName = ProjectName, ModelVersion = ModelVersion, Body = Body, ContentType = ContentType) output <- .lookoutforvision$detect_anomalies_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$detect_anomalies <- lookoutforvision_detect_anomalies lookoutforvision_list_dataset_entries <- function(ProjectName, DatasetType, Labeled = NULL, AnomalyClass = NULL, BeforeCreationDate = NULL, AfterCreationDate = NULL, NextToken = NULL, MaxResults = NULL, SourceRefContains = NULL) { op <- new_operation( name = "ListDatasetEntries", http_method = "GET", http_path = "/2020-11-20/projects/{projectName}/datasets/{datasetType}/entries", paginator = list() ) input <- .lookoutforvision$list_dataset_entries_input(ProjectName = ProjectName, DatasetType = DatasetType, Labeled = Labeled, AnomalyClass = AnomalyClass, BeforeCreationDate = BeforeCreationDate, AfterCreationDate = AfterCreationDate, NextToken = NextToken, MaxResults = MaxResults, SourceRefContains = SourceRefContains) output <- .lookoutforvision$list_dataset_entries_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$list_dataset_entries <- lookoutforvision_list_dataset_entries lookoutforvision_list_models <- function(ProjectName, NextToken = NULL, MaxResults = NULL) { op <- new_operation( name = "ListModels", http_method = "GET", http_path = "/2020-11-20/projects/{projectName}/models", paginator = list() ) input <- .lookoutforvision$list_models_input(ProjectName = ProjectName, NextToken = NextToken, MaxResults = MaxResults) output <- .lookoutforvision$list_models_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$list_models <- lookoutforvision_list_models lookoutforvision_list_projects <- function(NextToken = NULL, MaxResults = NULL) { op <- new_operation( name = "ListProjects", http_method = "GET", http_path = "/2020-11-20/projects", paginator = list() ) input <- .lookoutforvision$list_projects_input(NextToken = NextToken, MaxResults = MaxResults) output <- .lookoutforvision$list_projects_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$list_projects <- lookoutforvision_list_projects lookoutforvision_start_model <- function(ProjectName, ModelVersion, MinInferenceUnits, ClientToken = NULL) { op <- new_operation( name = "StartModel", http_method = "POST", http_path = "/2020-11-20/projects/{projectName}/models/{modelVersion}/start", paginator = list() ) input <- .lookoutforvision$start_model_input(ProjectName = ProjectName, ModelVersion = ModelVersion, MinInferenceUnits = MinInferenceUnits, ClientToken = ClientToken) output <- .lookoutforvision$start_model_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$start_model <- lookoutforvision_start_model lookoutforvision_stop_model <- function(ProjectName, ModelVersion, ClientToken = NULL) { op <- new_operation( name = "StopModel", http_method = "POST", http_path = "/2020-11-20/projects/{projectName}/models/{modelVersion}/stop", paginator = list() ) input <- .lookoutforvision$stop_model_input(ProjectName = ProjectName, ModelVersion = ModelVersion, ClientToken = ClientToken) output <- .lookoutforvision$stop_model_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$stop_model <- lookoutforvision_stop_model lookoutforvision_update_dataset_entries <- function(ProjectName, DatasetType, Changes, ClientToken = NULL) { op <- new_operation( name = "UpdateDatasetEntries", http_method = "PATCH", http_path = "/2020-11-20/projects/{projectName}/datasets/{datasetType}/entries", paginator = list() ) input <- .lookoutforvision$update_dataset_entries_input(ProjectName = ProjectName, DatasetType = DatasetType, Changes = Changes, ClientToken = ClientToken) output <- .lookoutforvision$update_dataset_entries_output() config <- get_config() svc <- .lookoutforvision$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .lookoutforvision$operations$update_dataset_entries <- lookoutforvision_update_dataset_entries
transformFitness = function(fitness, task, selector) { task.dir = task$minimize sup.dir = rep(attr(selector, "supported.opt.direction"), task$n.objectives) sup.dir = (sup.dir == "minimize") fn.scale = ifelse(xor(task.dir, sup.dir), -1, 1) fn.scale = if (task$n.objectives == 1L) { as.matrix(fn.scale) } else { diag(fn.scale) } return(fn.scale %*% fitness) }
utils::globalVariables(c("id", "year", "cites")) compare_scholars <- function(ids, pagesize=100) { data <- lapply(ids, function(x) cbind(id=x, get_publications(x, pagesize=pagesize))) data <- do.call("rbind", data) data <- data %>% group_by(id, year) %>% summarize(cites=sum(cites, na.rm=TRUE)) %>% mutate(total=cumsum(cites)) names <- lapply(ids, function(i) { p <- get_profile(i) data.frame(id=p$id, name=p$name) }) names <- do.call("rbind", names) final <- merge(data, names) return(final) } compare_scholar_careers <- function(ids, career=TRUE) { data <- lapply(ids, function(x) return(cbind(id=x, get_citation_history(x)))) data <- do.call("rbind", data) if (career) { data <- data %>% group_by(id) %>% mutate(career_year=year-min(year)) } names <- lapply(ids, function(i) { p <- get_profile(i) data.frame(id=p$id, name=p$name) }) names <- do.call("rbind", names) data <- merge(data, names) return(data) }
compute_uniCondProb_based_on_bivProb <- function(bivProb, nvar, idx.pairs, idx.Y1, idx.Gy2, idx.cat.y1.split, idx.cat.y2.split) { bivProb.split <- split(bivProb, idx.pairs) lngth <- 2*length(bivProb) idx.vec.el <- 1:lngth ProbY1Gy2 <- rep(NA, lngth) no.pairs <- nvar*(nvar-1)/2 idx2.pairs <- combn(nvar,2) for(k in 1:no.pairs){ y2Sums <- tapply(bivProb.split[[k]], idx.cat.y2.split[[k]], sum) y2Sums.mult <- y2Sums[idx.cat.y2.split[[k]] ] Y1Gy2 <- bivProb.split[[k]]/ y2Sums.mult tmp.idx.vec.el <- idx.vec.el[(idx.Y1 == idx2.pairs[1,k]) & (idx.Gy2 == idx2.pairs[2,k])] ProbY1Gy2[tmp.idx.vec.el] <- Y1Gy2 } for(k in 1:no.pairs){ y1Sums <- tapply(bivProb.split[[k]], idx.cat.y1.split[[k]], sum) y1Sums.mult <- y1Sums[idx.cat.y1.split[[k]] ] Y2Gy1 <- bivProb.split[[k]]/ y1Sums.mult reordered_Y2Gy1 <- Y2Gy1[order(idx.cat.y1.split[[k]])] tmp.idx.vec.el <- idx.vec.el[(idx.Y1 == idx2.pairs[2,k]) & (idx.Gy2 == idx2.pairs[1,k])] ProbY1Gy2[tmp.idx.vec.el] <- reordered_Y2Gy1 } ProbY1Gy2 } pairwiseExpProbVec_GivenObs <- function(lavobject) { yhat <- lavPredict(object=lavobject, type = "yhat" ) ngroups <- lavobject@Data@ngroups univariateProb <- vector("list", length=ngroups) pairwiseProb <- vector("list", length=ngroups) idx.ThetaMat <- which(names(lavobject@Model@GLIST)=="theta") for(g in seq_len(ngroups)) { if(ngroups>1L){ yhat_group <- yhat[[g]] } else { yhat_group <- yhat } nsize <- lavobject@Data@nobs[[g]] nvar <- lavobject@Model@nvar[[g]] Data <- lavobject@Data@X[[g]] TH <- lavobject@Fit@TH[[g]] th.idx <- lavobject@[email protected][[g]] Theta <- lavobject@Model@GLIST[ idx.ThetaMat[g] ]$theta error.stddev <- diag(Theta)^0.5 nlev <- lavobject@Data@ov$nlev idx.uniy <- rep(1:nvar, times=nlev) idx.pairs.yiyj <- combn(1:nvar,2) no_biv_resp_cat_yiyj <- sapply(1:ncol(idx.pairs.yiyj), function(x){ prod( nlev[idx.pairs.yiyj[,x]] ) }) idx.y1 <- unlist( mapply(rep, idx.pairs.yiyj[1,], each= no_biv_resp_cat_yiyj) ) idx.y2 <- unlist( mapply(rep, idx.pairs.yiyj[2,], each= no_biv_resp_cat_yiyj) ) univariateProb[[g]] <- matrix(0, nrow = nsize, ncol = sum(nlev) ) pairwiseProb[[g]] <- matrix(0, nrow = nsize, ncol = length(lavobject@Cache[[g]]$bifreq)) idx.MissVar.casewise <- apply(Data, 1, function(x) { which(is.na(x)) } ) for(i in 1:nsize){ idx.MissVar <- idx.MissVar.casewise[[i]] noMissVar <- length(idx.MissVar) if( noMissVar>0L ) { TH.list <- split(TH,th.idx) tmp.TH <- TH.list[idx.MissVar] tmp.lowerTH <- unlist(lapply(tmp.TH, function(x){c(-Inf,x)})) tmp.upperTH <- unlist(lapply(tmp.TH, function(x){c(x,Inf) })) idx.items <- rep(c(1:noMissVar), times=nlev[idx.MissVar]) tmp.mean <- yhat_group[i,idx.MissVar] tmp.mean.extended <- tmp.mean[idx.items] tmp.stddev <- error.stddev[idx.MissVar] tmp.stddev.extended <- tmp.stddev[idx.items] tmp.uniProb <- pnorm( (tmp.upperTH - tmp.mean.extended )/ tmp.stddev.extended ) - pnorm( (tmp.lowerTH - tmp.mean.extended )/ tmp.stddev.extended ) idx.columnsUni <- which(idx.uniy %in% idx.MissVar) univariateProb[[g]][i, idx.columnsUni] <- tmp.uniProb if( noMissVar>1L ) { idx.pairsMiss <- combn(idx.MissVar ,2) no.pairs <- ncol(idx.pairsMiss) idx.pairsV2 <- combn(noMissVar, 2) idx.columns <- unlist(lapply(1:no.pairs, function(x){ which( (idx.y1 == idx.pairsMiss[1,x]) & (idx.y2 == idx.pairsMiss[2,x]) ) } ) ) if( all( Theta[t(idx.pairsMiss)]==0 ) ){ tmp.uniProb.list <- split(tmp.uniProb, idx.items) pairwiseProb[[g]][i, idx.columns] <- unlist( lapply(1:no.pairs, function(x){ c( outer(tmp.uniProb.list[[ idx.pairsV2[1,x] ]] , tmp.uniProb.list[[ idx.pairsV2[2,x] ]] ) ) }) ) } else { tmp.th.idx <- th.idx[th.idx %in% idx.MissVar] tmp.th.idx.recoded <- rep(c(1:noMissVar), times=table(tmp.th.idx)) tmp.TH <- TH[th.idx %in% idx.MissVar] tmp.ind.vec <- LongVecInd(no.x = noMissVar, all.thres = tmp.TH, index.var.of.thres = tmp.th.idx.recoded) tmp.th.rho.vec <- LongVecTH.Rho.Generalised( no.x = noMissVar, TH = tmp.TH, th.idx = tmp.th.idx.recoded, cov.xixj = Theta[t(idx.pairsMiss)] , mean.x = yhat_group[i,idx.MissVar], stddev.x = error.stddev[idx.MissVar] ) tmp.bivProb <- pairwiseExpProbVec(ind.vec = tmp.ind.vec , th.rho.vec = tmp.th.rho.vec) pairwiseProb[[g]][i, idx.columns] <- tmp.bivProb } } } } } list(univariateProbGivObs = univariateProb, pairwiseProbGivObs = pairwiseProb) } LongVecTH.Rho.Generalised <- function(no.x, TH, th.idx, cov.xixj, mean.x, stddev.x ) { all.std.thres <- (TH - mean.x[th.idx]) / stddev.x[th.idx] id.pairs <- utils::combn(no.x,2) cor.xixj <- cov.xixj /( stddev.x[id.pairs[1,]] * stddev.x[id.pairs[2,]]) LongVecTH.Rho(no.x = no.x, all.thres = all.std.thres, index.var.of.thres = th.idx, rho.xixj = cor.xixj) } pairwiseExpProbVec_GivenObs_UncMod <- function(lavobject) { ngroups <- lavobject@Data@ngroups TH <- lavobject@implied$th TH.IDX <- lavobject@[email protected] Sigma.hat <- lavobject@implied$cov univariateProb <- vector("list", length=ngroups) pairwiseProb <- vector("list", length=ngroups) for(g in 1:ngroups) { Sigma.hat.g <- Sigma.hat[[g]] Cor.hat.g <- cov2cor(Sigma.hat.g) cors <- Cor.hat.g[lower.tri(Cor.hat.g)] if(any(abs(cors) > 1)) { warning("lavaan WARNING: some model-implied correlations are larger than 1.0") } nvar <- nrow(Sigma.hat.g) MEAN <- rep(0, nvar) TH.g <- TH[[g]] th.idx.g <- TH.IDX[[g]] nlev <- lavobject@Data@ov$nlev idx.uniy <- rep(1:nvar, times=nlev) idx.pairs.yiyj <- combn(1:nvar,2) no_biv_resp_cat_yiyj <- sapply(1:ncol(idx.pairs.yiyj), function(x){ prod( nlev[idx.pairs.yiyj[,x]] ) }) idx.y1 <- unlist( mapply(rep, idx.pairs.yiyj[1,], each= no_biv_resp_cat_yiyj) ) idx.y2 <- unlist( mapply(rep, idx.pairs.yiyj[2,], each= no_biv_resp_cat_yiyj) ) Data <- lavobject@Data@X[[g]] nsize <- nrow(Data) univariateProb[[g]] <- matrix(0, nrow = nsize, ncol = sum(nlev) ) pairwiseProb[[g]] <- matrix(0, nrow = nsize, ncol = length(lavobject@Cache[[g]]$bifreq)) idx.MissVar.casewise <- apply(Data, 1, function(x) { which(is.na(x)) } ) for(i in 1:nsize){ idx.MissVar <- idx.MissVar.casewise[[i]] noMissVar <- length(idx.MissVar) if( noMissVar>0L ) { TH.VAR <- lapply(1:nvar, function(x) c(-Inf, TH.g[th.idx.g==x], +Inf)) lower <- sapply(1:nvar, function(x) TH.VAR[[x]][ Data[i,x] ]) upper <- sapply(1:nvar, function(x) TH.VAR[[x]][ Data[i,x] + 1L ]) lower.denom <- lower[-idx.MissVar] upper.denom <- upper[-idx.MissVar] MEAN.i <- MEAN[-idx.MissVar] Corhat.i <- Cor.hat.g[-idx.MissVar, -idx.MissVar, drop=FALSE] denom <- sadmvn(lower.denom, upper.denom, mean=MEAN.i, varcov=Corhat.i)[1] } if( noMissVar==1L ) { TH.MissVar <- c(-Inf, TH.g[th.idx.g==idx.MissVar], +Inf) no.cat <- nlev[idx.MissVar] numer <- sapply(1:no.cat, function(x){ lower[idx.MissVar] <- TH.MissVar[x] upper[idx.MissVar] <- TH.MissVar[x+ 1L] sadmvn(lower, upper, mean=MEAN, varcov=Cor.hat.g)[1] }) idx.columnsUni <- which(idx.uniy %in% idx.MissVar) univariateProb[[g]][i, idx.columnsUni] <- numer / denom } if( noMissVar>1L ) { idx.pairsMiss <- combn(idx.MissVar ,2) no.pairs <- ncol(idx.pairsMiss) for(j in 1:no.pairs ) { idx.Missy1y2 <- idx.pairsMiss[,j] idx.Missy1 <- idx.Missy1y2[1] idx.Missy2 <- idx.Missy1y2[2] idx.MissRestItems <- idx.MissVar[ !(idx.MissVar %in% idx.Missy1y2)] TH.Missy1 <- c(-Inf, TH.g[th.idx.g==idx.Missy1], +Inf) TH.Missy2 <- c(-Inf, TH.g[th.idx.g==idx.Missy2], +Inf) no.cat.Missy1 <- nlev[ idx.Missy1 ] no.cat.Missy2 <- nlev[ idx.Missy2 ] no.bivRespCat <- no.cat.Missy1 * no.cat.Missy2 mat_bivRespCat <- matrix(1:no.bivRespCat, nrow= no.cat.Missy1, ncol=no.cat.Missy2) numer <- sapply(1:no.bivRespCat, function(x){ idx_y1_cat <- which(mat_bivRespCat==x, arr.ind=TRUE)[1] idx_y2_cat <- which(mat_bivRespCat==x, arr.ind=TRUE)[2] lower[idx.Missy1y2] <- c( TH.Missy1[idx_y1_cat], TH.Missy2[idx_y2_cat] ) upper[idx.Missy1y2] <- c( TH.Missy1[idx_y1_cat+1L], TH.Missy2[idx_y2_cat+1L] ) lower.tmp <- lower upper.tmp <- upper MEAN.tmp <- MEAN Cor.hat.g.tmp <- Cor.hat.g if( length(idx.MissRestItems)>0 ){ lower.tmp <- lower[-idx.MissRestItems] upper.tmp <- upper[-idx.MissRestItems] MEAN.tmp <- MEAN[-idx.MissRestItems] Cor.hat.g.tmp <- Cor.hat.g[-idx.MissRestItems, -idx.MissRestItems] } sadmvn(lower.tmp, upper.tmp, mean=MEAN.tmp, varcov=Cor.hat.g.tmp)[1] }) idx.columns <- which( (idx.y1 == idx.Missy1) & (idx.y2 == idx.Missy2) ) tmp_biv <- numer/denom pairwiseProb[[g]][i, idx.columns] <- tmp_biv if(j==1L){ univariateProb[[g]][i, which(idx.uniy %in% idx.Missy1) ] <- apply(mat_bivRespCat, 1, function(x){ sum( tmp_biv[x])} ) univariateProb[[g]][i, which(idx.uniy %in% idx.Missy2) ] <- apply(mat_bivRespCat, 2, function(x){ sum( tmp_biv[x])} ) } if(j>1L & j<noMissVar){ univariateProb[[g]][i, which(idx.uniy %in% idx.Missy2) ] <- apply(mat_bivRespCat, 2, function(x){ sum( tmp_biv[x])} ) } } } } } list(univariateProbGivObs = univariateProb, pairwiseProbGivObs = pairwiseProb) }
test_that("Check capacity algorithm - testing procedures",{ n_sample <- c(100) dist_sd <- 1 input_num <- 4 xx <- signif(c(0, exp( seq( from = log(0.01), to = log(100), length.out = input_num-1))), digits = 2) example_means <- 10*(xx/(1+xx)) example_sds <- rep(dist_sd, input_num) tempdata <- data.frame(signal = c(t(replicate(n_sample, xx))), output = c(matrix(rnorm(n = input_num*n_sample, mean = example_means,sd = example_sds), ncol = input_num,byrow = TRUE))) tempdata$signal <- factor(x = tempdata$signal,levels = sort(unique(tempdata$signal))) signal_name <- "signal" response_name <- "output" seed_to_use <- 12345 bootstrap_num <- 10 bootstrap_frac <- 0.8 overfitting_num <- 10 training_frac <- 0.6 cores_num=1 tempoutput <- SLEMI::capacity_logreg_main( dataRaw = tempdata, signal = signal_name, response = response_name, output_path = NULL, testing = TRUE, plot_width = 10 , plot_height = 8, TestingSeed = seed_to_use, testing_cores = cores_num, boot_num = bootstrap_num, boot_prob = bootstrap_frac, traintest_num = overfitting_num, partition_trainfrac = training_frac ) expect_equal(names(tempoutput), c("regression","model","p_opt","cc","testing","testing_pv","time","params" )) expect_true(tempoutput$cc>=0) expect_equal(round(sum(tempoutput$p_opt),digits=8),1) expect_true(all(sapply(tempoutput$testing$bootstrap,function(x) x$cc)>0)) expect_true(all(sapply(tempoutput$testing$traintest,function(x) x$cc)>0)) })
nodeHeight <- function(tree) { if (is.null(attr(tree, "order")) || attr(tree, "order") == "cladewise") { tree <- reorder(tree, "postorder") } node_height_cpp(as.integer(tree$edge[, 1]), as.integer(tree$edge[, 2]), as.double(tree$edge.length)) } ancstat <- function(phy, x) { contrast <- attr(x, "contrast") storage.mode(contrast) <- "integer" phy <- reorder(phy, "postorder") res <- matrix(0L, max(phy$edge), ncol(contrast)) colnames(res) <- attr(x, "levels") nTips <- length(phy$tip.label) pa <- phy$edge[, 1] ch <- phy$edge[, 2] res[1:nTips, ] <- contrast[as.numeric(x)[match(phy$tip.label, names(x))], , drop = FALSE ] for (i in seq_along(pa)) { res[pa[i], ] <- res[pa[i], ] | res[ch[i], ] } res } comp <- function(x, y) { tmp1 <- matrix(rowSums(x), nrow(x), nrow(y)) res <- matrix(rowSums(y), nrow(x), nrow(y), byrow = TRUE) tmp3 <- tcrossprod(x, 1 - y) tmp0 <- tcrossprod(x, y) tmp0[tmp3 > 0] <- 0L res[!(tmp0 > (tmp1 - 1e-8))] <- 10000000L apply(res, 1, which.min) } comp2 <- function(x, y) { res <- matrix(rowSums(x), nrow(x), nrow(y)) tmp1 <- matrix(rowSums(y), nrow(x), nrow(y), byrow = TRUE) tmp3 <- tcrossprod(1 - x, y) tmp0 <- tcrossprod(x, y) tmp0[tmp3 > 0] <- 0L res[tmp0 < 2] <- Inf apply(res, 2, which.min) } coalSpeciesTree <- function(tree, X = NULL, sTree = NULL) { if (is.null(X)) return(speciesTree(tree)) trees <- unclass(tree) States <- lapply(tree, ancstat, X) NH <- lapply(tree, nodeHeight) if (is.null(sTree)) { l <- attr(X, "nc") m <- choose(l, 2) SST <- matrix(0L, m, l) k <- 1 for (i in 1:(l - 1)) { for (j in (i + 1):l) { SST[k, i] <- SST[k, j] <- 1L k <- k + 1 } } Y <- matrix(Inf, length(NH), nrow(SST)) dm <- rep(Inf, m) for (i in seq_along(NH)) { ind <- comp2(States[[i]], SST) dm <- pmin(dm, NH[[i]][ind]) } dm <- structure(2 * dm, Labels = attr(X, "levels"), Size = l, class = "dist", Diag = FALSE, Upper = FALSE ) sTree <- upgma(dm, "single") } else { SST <- ancstat(sTree, X) Y <- matrix(Inf, length(NH), nrow(SST)) for (i in seq_along(NH)) { ind <- comp(States[[i]], SST) for (j in seq_along(ind)) Y[i, ind[j]] <- min(Y[i, ind[j]], NH[[i]][j]) } STH <- apply(Y, 2, min) sTree$edge.length <- STH[sTree$edge[, 1]] - STH[sTree$edge[, 2]] } sTree }
mjoint <- function(formLongFixed, formLongRandom, formSurv, data, survData = NULL, timeVar, inits = NULL, verbose = FALSE, pfs = TRUE, control = list(), ...) { time.start <- Sys.time() Call <- match.call() balanced <- FALSE if (!is.list(formLongFixed)) { balanced <- TRUE formLongFixed <- list(formLongFixed) formLongRandom <- list(formLongRandom) K <- 1 } else { K <- length(formLongFixed) } if (!("list" %in% class(data))) { balanced <- TRUE data <- list(data) if (K > 1) { for (k in 2:K) { data[[k]] <- data[[1]] } } } else { balanced <- (length(unique(data)) == 1) } if (length(data) != K) { stop(paste("The number of datasets expected is K =", K)) } data <- lapply(data, function(d) { if (any(c("tbl_df", "tbl") %in% class(d))) { return(as.data.frame(d)) } else { return(d) } }) id <- as.character(nlme::splitFormula(formLongRandom[[1]], "|")[[2]])[2] n <- length(unique(data[[1]][, id])) if (length(timeVar) == 1 & (K > 1)) { timeVar <- rep(timeVar, K) } if (length(timeVar) != K) { stop(paste("The length of timeVar must equal", K)) } for (k in 1:K) { data[[k]] <- data[[k]][order(xtfrm(data[[k]][, id]), data[[k]][, timeVar[k]]), ] data[[k]][, id] <- as.factor(data[[k]][, id]) data[[k]] <- droplevels(data[[k]]) } if (K > 1) { uniq.ids <- list(sort(unique(data[[1]][, id]))) for (k in 2:K) { uniq.ids[[k]] <- sort(unique(data[[k]][, id])) if (!identical(uniq.ids[[k - 1]], uniq.ids[[k]])) { stop("Every subject must have at least one measurement per each outcome") } } } con <- list(nMC = 100*K, nMCscale = 5, nMCmax = 20000, burnin = 100*K, mcmaxIter = 100*K + 200, convCrit = "sas", gammaOpt = "NR", tol0 = 1e-03, tol1 = 1e-03, tol2 = 5e-03, tol.em = 1e-04, rav = 0.1, type = "antithetic") nc <- names(con) control <- c(control, list(...)) con[(conArgs <- names(control))] <- control if (("tol.em" %in% names(control)) || ("tol2" %in% names(control))) { con$tol.em <- min(con$tol.em, con$tol2) } if (("burnin" %in% names(control)) && !("mcmaxIter" %in% names(control))) { con$mcmaxIter <- con$burnin + 200 } if (con$type %in% c("sobol", "halton")) { if (!("burnin" %in% names(control))) { con$burnin <- 5 } if (!("tol2" %in% names(control))) { con$tol2 <- 1e-03 } } if (length(unmatched <- conArgs[!(conArgs %in% nc)]) > 0) { warning("Unknown arguments passed to 'control': ", paste(unmatched, collapse = ", ")) } lfit <- list() mf.fixed <- list() yik <- list() Xik <- list() nk <- vector(length = K) Xik.list <- list() nik.list <- list() Zik <- list() Zik.list <- list() for (k in 1:K) { lfit[[k]] <- nlme::lme(fixed = formLongFixed[[k]], random = formLongRandom[[k]], data = data[[k]], method = "ML", control = nlme::lmeControl(opt = "optim")) lfit[[k]]$call$fixed <- eval(lfit[[k]]$call$fixed) mf.fixed[[k]] <- model.frame(lfit[[k]]$terms, data[[k]][, all.vars(formLongFixed[[k]])]) yik[[k]] <- by(model.response(mf.fixed[[k]], "numeric"), data[[k]][, id], as.vector) Xik[[k]] <- data.frame("id" = data[[k]][, id], model.matrix(formLongFixed[[k]], data[[k]])) nk[k] <- nrow(Xik[[k]]) Xik.list[[k]] <- by(Xik[[k]], Xik[[k]]$id, function(u) { as.matrix(u[, -1]) }) nik.list[[k]] <- by(Xik[[k]], Xik[[k]]$id, nrow) ffk <- nlme::splitFormula(formLongRandom[[k]], "|")[[1]] Zik[[k]] <- data.frame("id" = data[[k]][, id], model.matrix(ffk, data[[k]])) Zik.list[[k]] <- by(Zik[[k]], Zik[[k]]$id, function(u) { as.matrix(u[, -1]) }) } yi <- sapply(names(yik[[1]]), function(i) { unlist(lapply(yik, "[[", i)) }, USE.NAMES = TRUE, simplify = FALSE) Xi <- sapply(names(Xik.list[[1]]), function(i) { as.matrix(Matrix::bdiag(lapply(Xik.list, "[[", i))) }, USE.NAMES = TRUE, simplify = FALSE) Zi <- sapply(names(Zik.list[[1]]), function(i) { as.matrix(Matrix::bdiag(lapply(Zik.list, "[[", i))) }, USE.NAMES = TRUE, simplify = FALSE) Zit <- lapply(Zi, t) XtXi <- lapply(Xi, crossprod) XtX.inv <- solve(Reduce("+", XtXi)) Xtyi <- mapply(function(x, y) { crossprod(x, y) }, x = Xi, y = yi, SIMPLIFY = FALSE) XtZi <- mapply(function(x, z) { crossprod(x, z) }, x = Xi, z = Zi, SIMPLIFY = FALSE) nik <- sapply(names(nik.list[[1]]), function(i) { unlist(lapply(nik.list, "[[", i)) }, USE.NAMES = TRUE, simplify = FALSE) p <- sapply(1:K, function(i) { ncol(Xik[[i]]) - 1 }) r <- sapply(1:K, function(i) { ncol(Zik[[i]]) - 1 }) l <- list(yi = yi, Xi = Xi, Zi = Zi, Zit = Zit, nik = nik, yik = yik, Xik.list = Xik.list, Zik.list = Zik.list, XtX.inv = XtX.inv, Xtyi = Xtyi, XtZi = XtZi, p = p, r = r, K = K, n = n, nk = nk) if (is.null(survData)) { survData <- data[[1]][!duplicated(data[[1]][, id]), ] } survdat <- survData sfit <- survival::coxph(formSurv, data = survdat, x = TRUE) q <- ncol(sfit$x) sfit.start <- survival::survfit(sfit) tj <- sfit.start$time[sfit.start$n.event > 0] nev <- sfit.start$n.event[sfit.start$n.event > 0] nev.uniq <- length(tj) survdat2 <- data.frame(survdat[, id], sfit$x, sfit$y[, 1], sfit$y[, 2]) xcenter <- NULL if (q > 0) { xcenter <- apply(survdat2[2:(q + 1)], 2, mean) survdat2[2:(q + 1)] <- scale(survdat2[2:(q + 1)], center = xcenter, scale = FALSE) } colnames(survdat2)[c(1, (q + 2):(q + 3))] <- c("id", "T", "delta") survdat2$tj.ind <- sapply(1:n, function(i) { sum(tj <= survdat2$T[i]) }) survdat2.list <- by(survdat2, survdat2$id, list) if (q > 0) { V <- by(survdat2, survdat2$id, function(u) { unlist(u[, 2:(q + 1)]) }) } else { V <- by(survdat2, survdat2$id, function(u) { 0 }) } t <- list(V = V, survdat2 = survdat2, survdat2.list = survdat2.list, q = q, nev = nev, nev.uniq = nev.uniq, xcenter = xcenter, tj = tj) for (k in 1:K) { for (i in survdat2$id) { if (max(data[[k]][data[[k]][, id] == i, timeVar[k]]) > survdat2[survdat2$id == i, "T"]) { stop("Longitudinal measurements should not be recorded after the event time") } } } log.lik0 <- sum(sapply(lfit, logLik)) + sfit$loglik[ifelse(q > 0, 2, 1)] - sfit$nevent log.lik <- log.lik0 Zdat.fail <- data.frame( "id" = rep(unique(survdat2$id), pmax(survdat2$tj.ind, 1)), "time" = unlist(sapply(1:n, function(i) { tj[1:max(survdat2$tj.ind[i], 1)] }, simplify = FALSE)) ) names(Zdat.fail)[1] <- id Zik.fail <- list() Zik.fail.list <- list() for(k in 1:K) { if (ncol(Zdat.fail) == 2) { names(Zdat.fail)[2] <- timeVar[k] } ffk <- nlme::splitFormula(formLongRandom[[k]], "|")[[1]] Zik.fail[[k]] <- data.frame("id" = Zdat.fail[, id], model.matrix(ffk, Zdat.fail)) Zik.fail.list[[k]] <- by(Zik.fail[[k]], Zik.fail[[k]]$id, function(u) { as.matrix(u[, -1]) }) } Zi.fail <- sapply(names(Zik.fail.list[[1]]), function(i) { as.matrix(Matrix::bdiag(lapply(Zik.fail.list, "[[", i))) }, USE.NAMES = TRUE, simplify = FALSE) Zit.fail <- lapply(Zi.fail, t) IW.fail <- by(survdat2, survdat2$id, function(u) { do.call("cbind", lapply(1:K, function(i) diag(max(u$tj.ind, 1)))) }) z <- list(Zi.fail = Zi.fail, Zit.fail = Zit.fail, IW.fail = IW.fail) if (!is.null(inits)) { if (!is.list(inits)) { stop("inits must be a list.\n") } theta.names <- c("D", "beta", "sigma2", "gamma", "haz") if (length(unmatched <- names(inits)[!(names(inits) %in% theta.names)]) > 0) { warning("Unknown initial parameters passed to 'inits': ", paste(unmatched, collapse = ", ")) } } inits.long <- initsLong(lfit = lfit, inits = inits, l = l, z = z, K = K, p = p, r = r, tol.em = con$tol.em, verbose = verbose) inits.surv <- initsSurv(data = data, lfit = lfit, sfit = sfit, survdat2 = survdat2, formSurv = formSurv, id = id, timeVar = timeVar, K = K, q = q, balanced = balanced, inits = inits) D <- inits.long$D beta <- inits.long$beta sigma2 <- inits.long$sigma2 gamma <- inits.surv$gamma haz <- inits.surv$haz theta <- list("D" = D, "beta" = beta, "sigma2" = sigma2, "gamma" = gamma, "haz" = haz) rm(yi, Xi, Zi, Zit, yik, Xik.list, Zik.list, XtX.inv, Xtyi, XtZi, V, survdat2, survdat2.list, nev, nev.uniq, xcenter, tj, Zdat.fail, Zi.fail, Zit.fail, IW.fail) all.iters <- list() conv.track <- rep(FALSE, con$mcmaxIter) Delta.vec <- rep(NA, con$mcmaxIter) ll.hx <- rep(NA, con$mcmaxIter) cv.old <- 0 time.em.start <- Sys.time() nMC <- con$nMC nmc.iters <- c() for (it in 1:(con$mcmaxIter)) { if (verbose) { cat("-------------------------------------------------------------\n\n") cat(paste0("Iteration: ", it, "\n\n")) } nmc.iters <- c(nmc.iters, nMC) stepUpdate <- stepEM(theta = theta, l = l, t = t, z = z, nMC = nMC, verbose = verbose, gammaOpt = con$gammaOpt, pfs = FALSE, type = con$type) theta.new <- stepUpdate$theta.new log.lik.new <- stepUpdate$ll ll.hx[it] <- log.lik.new all.iters[[it]] <- theta.new if (verbose) { print(theta.new[-which(names(theta.new) == "haz")]) } conv.status <- convMonitor(theta = theta, theta.new = theta.new, log.lik = log.lik, log.lik.new = log.lik.new, con = con, verbose = verbose) conv.track[it] <- conv.status$conv Delta.vec[it] <- conv.status$max.reldelta.pars log.lik <- log.lik.new if (it >= con$burnin + 3) { conv <- all(conv.track[(it - 2):it]) } else { conv <- FALSE } if (!conv && (it >= con$burnin)) { cv <- ifelse(it >= 3, sd(Delta.vec[(it - 2):it]) / mean(Delta.vec[(it - 2):it]), 0) if (verbose) { cat(paste("CV statistic (old) =", round(cv.old, 6), "\n")) cat(paste("CV statistic (new) =", round(cv, 6), "\n\n")) } ripatti <- (cv > cv.old) cv.old <- cv lldrift <- (con$type %in% c("sobol", "halton")) && (conv.status$rel.ll < 0) if (ripatti || lldrift) { nMC.old <- nMC nMC <- min(nMC + floor(nMC / con$nMCscale), con$nMCmax) } if (verbose) { cat(paste("Using number of MC nodes:", nMC, "\n\n")) } } if (conv) { message("EM algorithm has converged!\n") theta <- theta.new if (pfs) { message("Calculating post model fit statistics...\n") postFitCalcs <- stepEM(theta = theta, l = l, t = t, z = z, nMC = nMC, verbose = FALSE, gammaOpt = "NR", pfs = TRUE, type = con$type) } break } else { theta <- theta.new } if ((it == con$mcmaxIter) & !conv) { message("Failed to converge!") } utils::flush.console() } hx.beta <- sapply(all.iters, function(x) x$beta) rownames(hx.beta) <- paste0("long_", rownames(hx.beta)) hx.gamma <- sapply(all.iters, function(x) x$gamma) if ((q + K) == 1) { hx.gamma <- matrix(hx.gamma, nrow = 1) } rownames(hx.gamma) <- paste0("surv_", rownames(hx.gamma)) hx.D <- sapply(all.iters, function(x) x$D[lower.tri(x$D, diag = TRUE)]) if (sum(r) == 1) { hx.D <- matrix(hx.D, nrow = 1) } ltri <- lower.tri(theta$D, diag = TRUE) rownames(hx.D) <- paste0("D_", row = row(theta$D)[ltri], ",", col = col(theta$D)[ltri]) hx.haz <- sapply(all.iters, function(x) x$haz) rownames(hx.haz) <- paste0("haz_", 1:nrow(hx.haz)) hx.sigma2 <- sapply(all.iters, function(x) x$sigma2) if (K == 1) { hx.sigma2 <- matrix(hx.sigma2, nrow = 1) } if (K > 1) { rownames(hx.sigma2) <- paste0("sigma2_", 1:K) } else { rownames(hx.sigma2) <- "sigma2" } out <- list("coefficients" = theta.new) out$history <- rbind(hx.beta, hx.gamma, hx.sigma2, hx.D, hx.haz) out$nMC.hx <- nmc.iters out$formLongFixed <- formLongFixed out$formLongRandom <- formLongRandom out$formSurv <- formSurv out$data <- data out$survData <- survData out$timeVar <- timeVar out$id <- id out$dims <- list("p" = p, "r" = r, "K" = K, "q" = q, "n" = n, "nk" = nk) out$sfit <- sfit out$lfit <- lfit out$log.lik0 <- log.lik0 out$log.lik <- log.lik out$ll.hx <- ll.hx out$control <- con out$finalnMC <- nMC if (conv && pfs) { out$Hessian <- postFitCalcs$H out$Eb <- postFitCalcs$Eb out$Vb <- postFitCalcs$Vb out$dmats <- list(l = l, t = t, z = z) } out$call <- Call out$conv <- conv time.end <- Sys.time() time.diff <- c("Total" = time.end - time.start, "EM" = time.end - time.em.start) out$comp.time <- time.diff if (verbose) { cat(paste("Total time taken:", round(as.numeric(time.diff[1]), 1), attr(time.diff[1], "units"), "\n")) cat(paste("EM algorithm took", round(as.numeric(time.diff[2]), 1), attr(time.diff[2], "units"), "\n\n")) } class(out) <- "mjoint" invisible(out) }
getAccess <- function (ClassDef) .Defunct() getClassName <- function (ClassDef) .Defunct() getClassPackage <- function (ClassDef) .Defunct() getExtends <- function (ClassDef) .Defunct() getProperties <- function (ClassDef) .Defunct() getPrototype <- function (ClassDef) .Defunct() getSubclasses <- function (ClassDef) .Defunct() getVirtual <- function (ClassDef) .Defunct() getAllMethods <- function(f, fdef, where = topenv(parent.frame())) .Defunct() mlistMetaName <- function(name = "", package = "") .Defunct() removeMethodsObject <- function(f, where = topenv(parent.frame())) .Defunct() seemsS4Object <- function(object) .Defunct("isS4") allGenerics <- function(...) .Defunct("getGenerics") bind_activation <- function(on = TRUE) { stop("methods:::bind_activation() is defunct;\n rather provide methods for cbind2() / rbind2()") }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) knitr::opts_knit$set(global.par = TRUE) oldpar = par(no.readonly = TRUE) par(mar = c(1, 1, 1, 1)) oldoptions = options() options(crayon.enabled = TRUE) old_hooks = fansi::set_knit_hooks( knitr::knit_hooks, which = c("output", "message", "error") ) library(sfnetworks) library(sf) library(tidygraph) library(tidyverse) library(TSP) net = as_sfnetwork(roxel, directed = FALSE) %>% st_transform(3035) %>% activate("edges") %>% mutate(weight = edge_length()) net paths = st_network_paths(net, from = 495, to = c(458, 121)) paths paths %>% slice(1) %>% pull(node_paths) %>% unlist() paths %>% slice(1) %>% pull(edge_paths) %>% unlist() plot_path = function(node_path) { net %>% activate("nodes") %>% slice(node_path) %>% plot(cex = 1.5, lwd = 1.5, add = TRUE) } colors = sf.colors(3, categorical = TRUE) plot(net, col = "grey") paths %>% pull(node_paths) %>% walk(plot_path) net %>% activate("nodes") %>% st_as_sf() %>% slice(c(495, 121, 458)) %>% plot(col = colors, pch = 8, cex = 2, lwd = 2, add = TRUE) p1 = st_geometry(net, "nodes")[495] + st_sfc(st_point(c(50, -50))) st_crs(p1) = st_crs(net) p2 = st_geometry(net, "nodes")[458] p3 = st_geometry(net, "nodes")[121] + st_sfc(st_point(c(-10, 100))) st_crs(p3) = st_crs(net) paths = st_network_paths(net, from = p1, to = c(p2, p3)) plot(net, col = "grey") paths %>% pull(node_paths) %>% walk(plot_path) plot(c(p1, p2, p3), col = colors, pch = 8, cex = 2, lwd = 2, add = TRUE) with_graph(net, graph_component_count()) connected_net = net %>% activate("nodes") %>% filter(group_components() == 1) plot(net, col = colors[2]) plot(connected_net, cex = 1.1, lwd = 1.1, add = TRUE) st_network_cost(net, from = c(p1, p2, p3), to = c(p1, p2, p3)) with_graph(net, graph_order()) cost_matrix = st_network_cost(net) dim(cost_matrix) set.seed(128) hull = net %>% activate("nodes") %>% st_geometry() %>% st_combine() %>% st_convex_hull() sites = st_sample(hull, 50, type = "random") facilities = st_sample(hull, 5, type = "random") new_net = net %>% activate("nodes") %>% filter(group_components() == 1) %>% st_network_blend(c(sites, facilities)) cost_matrix = st_network_cost(new_net, from = sites, to = facilities) closest = facilities[apply(cost_matrix, 1, function(x) which(x == min(x))[1])] draw_lines = function(sources, targets) { lines = mapply( function(a, b) st_sfc(st_cast(c(a, b), "LINESTRING"), crs = st_crs(net)), sources, targets, SIMPLIFY = FALSE ) do.call("c", lines) } connections = draw_lines(sites, closest) plot(new_net, col = "grey") plot(connections, col = colors[2], lwd = 2, add = TRUE) plot(facilities, pch = 8, cex = 2, lwd = 2, col = colors[3], add = TRUE) plot(sites, pch = 20, cex = 2, col = colors[2], add = TRUE) set.seed(403) rdm = net %>% st_bbox() %>% st_as_sfc() %>% st_sample(10, type = "random") net = activate(net, "nodes") cost_matrix = st_network_cost(net, from = rdm, to = rdm) rdm_idxs = st_nearest_feature(rdm, net) row.names(cost_matrix) = rdm_idxs colnames(cost_matrix) = rdm_idxs round(cost_matrix, 0) tour = solve_TSP(TSP(cost_matrix)) tour_idxs = as.numeric(names(tour)) tour_idxs round(tour_length(tour), 0) from_idxs = tour_idxs to_idxs = c(tour_idxs[2:length(tour_idxs)], tour_idxs[1]) tsp_paths = mapply(st_network_paths, from = from_idxs, to = to_idxs, MoreArgs = list(x = net) )["node_paths", ] %>% unlist(recursive = FALSE) plot(net, col = "grey") plot(rdm, pch = 20, col = colors[2], add = TRUE) walk(tsp_paths, plot_path) plot( st_as_sf(slice(net, rdm_idxs)), pch = 20, col = colors[3], add = TRUE ) plot( st_as_sf(slice(net, tour_idxs[1])), pch = 8, cex = 2, lwd = 2, col = colors[3], add = TRUE ) text( st_coordinates(st_as_sf(slice(net, tour_idxs[1]))) - c(200, 90), labels = "start/end\npoint" ) types = net %>% activate("edges") %>% pull(type) %>% unique() types set.seed(1) speeds = runif(length(types), 3 * 1000 / 60 / 60, 7 * 1000 / 60 / 60) net = net %>% activate("edges") %>% group_by(type) %>% mutate(speed = units::set_units(speeds[cur_group_id()], "m/s")) %>% mutate(time = weight / speed) %>% ungroup() net net = activate(net, "nodes") p = net %>% st_geometry() %>% st_combine() %>% st_centroid() iso = net %>% filter(node_distance_from(st_nearest_feature(p, net), weights = time) <= 600) iso_poly = iso %>% st_geometry() %>% st_combine() %>% st_convex_hull() plot(net, col = "grey") plot(iso_poly, col = NA, border = "black", lwd = 3, add = TRUE) plot(iso, col = colors[2], add = TRUE) plot(p, col = colors[1], pch = 8, cex = 2, lwd = 2, add = TRUE) table(roxel$type) paths_sf = net %>% activate("edges") %>% slice(unlist(paths$edge_paths)) %>% st_as_sf() table(paths_sf$type) plot(paths_sf["type"], lwd = 4, key.pos = 4, key.width = lcm(4)) weighting_profile = c( cycleway = Inf, footway = Inf, path = Inf, pedestrian = Inf, residential = 3, secondary = 1, service = 1, track = 10, unclassified = 1 ) weighted_net = net %>% activate("edges") %>% mutate(multiplier = weighting_profile[type]) %>% mutate(weight = edge_length() * multiplier) weighted_paths = st_network_paths(weighted_net, from = 495, to = c(458, 121)) weighted_paths_sf = weighted_net %>% activate("edges") %>% slice(unlist(weighted_paths$edge_paths)) %>% st_as_sf() table(weighted_paths_sf$type) plot(st_as_sf(net, "edges")["type"], lwd = 4, key.pos = NULL, reset = FALSE, main = "Distance weights") plot(st_geometry(paths_sf), add = TRUE) plot(st_as_sf(net, "edges")["type"], lwd = 4, key.pos = NULL, reset = FALSE, main = "Custom weights") plot(st_geometry(weighted_paths_sf), add = TRUE) par(oldpar) options(oldoptions)
parse_api_results <- function(res, type, include_stats, meta, format) { api_content <- content(res) if (length(api_content$errors) > 0) { return(list( error_code = api_content$errors[[1]]$code, error_message = api_content$errors[[1]]$message )) } results <- api_content$results[[1]] results <- modify_depth( results, vec_depth(results) - 1, function(x){ if (is.null(x)){ NA } else { x } }, .ragged = TRUE ) if (!is.null(results$stats)) { stats <- tibble( type = names(results$stats), value = as.numeric(results$stats) ) } else { stats <- NULL } if (length(results$data) == 0) { message("No data returned.") if (include_stats) { return(stats) } } res_names <- results$columns res_data <- results$data if (meta) { res_meta <- map(res_data, "meta") %>% map(flatten_dfr) %>% setNames(paste(res_names, "meta", sep = "_")) } res_data <- map(res_data, function(x) { x$meta <- NULL x }) if (type == "row") { res <- attempt::attempt({ purrr::map_depth(res_data, 3, tibble::as_tibble) %>% purrr::map(purrr::flatten) %>% purrr::transpose() %>% purrr::map(rbindlist_to_tibble) }, silent = TRUE) if (class(res)[1] == "try-error") { res <- flatten(res_data) %>% purrr::map_dfr(purrr::flatten_dfc) %>% list() } if (length(res_data) != 0){ res <- res %>% setNames(res_names) } if (include_stats) { res <- c(res, list(stats = stats)) } else { class(res) <- c("neo", class(res)) } if (meta) { res <- c(res, res_meta) } class(res) <- c("neo", class(res)) return(res) } else if (type == "graph") { graph <- map(res_data, "graph") nodes <- compact(map(graph, "nodes")) relations <- compact(map(graph, "relationships")) nodes_tbl <- NULL relations_tbl <- NULL if (length(nodes) == 0 & length(relations) == 0) { message("No graph data found.") message("Either your call can't be converted to a graph \nor there is no data at all matching your call.") message("Verify your call or try type = \"row\".") } if (length(nodes) != 0) { nodes <- purrr::flatten(nodes) nodes_tbl <- unique(tibble( id = map_chr(nodes, ~.x$id), label = map(nodes, ~as.character(.x$labels)), properties = map(nodes, ~.x$properties) )) } if (length(relations) != 0) { relations <- flatten(relations) relations_tbl <- unique(tibble( id = as.character(map(relations, ~.x$id)), type = as.character(map(relations, ~.x$type)), startNode = as.character(map(relations, ~.x$startNode)), endNode = as.character(map(relations, ~.x$endNode)), properties = map(relations, ~.x$properties) )) } if (include_stats) { res <- compact(list(nodes = nodes_tbl, relationships = relations_tbl, stats = stats)) class(res) <- c("neo", class(res)) } else { res <- compact(list(nodes = nodes_tbl, relationships = relations_tbl)) if (length(res) != 0) { class(res) <- c("neo", class(res)) } } res } } rbindlist_to_tibble <- function(l){ tibble::as_tibble(data.table::rbindlist(l)) }
context("YahooFinanceSource") test_that("YahooFinanceSource",{ lengthcorp <- 20 testcorp <- WebCorpus(YahooFinanceSource("MSFT")) expect_that(length(testcorp), equals(lengthcorp)) expect_that(class(testcorp), equals(c("WebCorpus","VCorpus","Corpus"))) contentlength <- sapply(testcorp, function(x) if( length(content(x)) < 1) 0 else nchar(content(x))) contentratio <- length(which(contentlength > 0)) / length(testcorp) expect_that(contentratio > 0.5, is_true()) datetimestamp <- lapply(testcorp, function(x) meta(x, "datetimestamp")) expect_that(all(sapply(datetimestamp, function(x) class(x)[1] == "POSIXlt")), is_true()) description <- lapply(testcorp, function(x) meta(x, "description")) expect_that(all(sapply(description, function(x) class(x)[1] == "character")), is_true()) heading <- lapply(testcorp, function(x) meta(x, "heading")) expect_that(all(sapply(heading, function(x) class(x)[1] == "character")), is_true()) expect_that(all(sapply(heading, nchar) > 0), is_true()) id <- lapply(testcorp, function(x) meta(x, "id")) expect_that(all(sapply(id, function(x) class(x)[1] == "character")), is_true()) expect_that(all(sapply(id, nchar) > 0), is_true()) origin <- lapply(testcorp, function(x) meta(x, "origin")) expect_that(all(sapply(origin, function(x) class(x)[1] == "character")), is_true()) expect_that(all(sapply(origin, nchar) > 0), is_true()) testcorp <- testcorp[1:10] testcorp <- corpus.update(testcorp) expect_that(length(testcorp) >= lengthcorp, is_true()) cat(" | Contentratio: ", sprintf("%.0f%%", contentratio * 100)) })
device.data <- data.frame( DeviceName = c("Cypher Sirolimus DES", "Taxus Express 2", "Cypher Select Sirolimus DES", "Cypher Select Plus Sirolimus DES", "Taxus Liberte", "Endeavor ABT578", "Endeavor Sprint Zotarolimus DES", "Xience V", "Taxus Element Monrail ION", "Xience Nano", "Promus Element Plus", "Xience Prime", "Endeavor Resolute DES","Endeavor Resolute Integrity DES", "Promus Premier", "Xience Xpedition LL and SV"), DeviceManufacturer = c("Cordis Cashel","Boston Scientific","Cordis Cashel", "Cordis Cashel","Boston Scientific","Medtronic Inc", "Medtronic Inc", "Abbott Vascular", "Boston Scientific", "Abbott Vascular","Boston Scientific", "Abbott Vascular", "Medtronic Inc", "Medtronic Inc","Boston Scientific", "Abbott Vascular"), start_date = as.Date(c("2002-11-15", "2003-09-09", "2005-10-21", "2006-10-25","2008-02-05", "2008-02-27", "2009-06-10", "2009-08-21", "2011-08-19", "2011-10-24", "2012-01-30", "2012-04-10", "2012-04-14", "2013-03-07", "2013-09-30", "2014-02-19")), end_date = as.Date(c("2007-07-18", "2010-11-10", "2007-07-18", "2013-04-05", "2013-11-01", "2016-03-31", "2016-03-31", "2016-03-31", "2011-09-16", "2016-03-31", "2016-03-31", "2016-03-31", "2016-03-31", "2016-03-31", "2016-03-31", "2016-03-31")), stringsAsFactors = FALSE ) vistime(device.data, col.event="DeviceName", col.group ="DeviceManufacturer", col.start="start_date", col.end ="end_date", linewidth = 20) hc_vistime(device.data, col.event="DeviceName", col.group ="DeviceManufacturer", col.start="start_date", col.end ="end_date")
slpm_gen <- function(M, N, K, hyper_pars = NULL) { delta <- a <- b <- rep(1,K) if (!is.null(hyper_pars)) { delta = hyper_pars$delta a = hyper_pars$a_gamma b = hyper_pars$b_gamma } gamma <- rep(NA,K) for (k in 1:K) gamma[k] = rgamma(n = 1, shape = a[k], rate = b[k]) U <- matrix(NA, M, K) V <- matrix(NA, N, K) for (k in 1:K) { U[,k] = rnorm(n = M, mean = 0, sd = sqrt(1/gamma[k])) V[,k] = rnorm(n = N, mean = 0, sd = sqrt(1/gamma[k])) } lambda <- as.numeric(rdirichlet(n = 1, alpha = delta)) adj <- matrix(0,M,N) for (i in 1:M) for (j in 1:N) for (k in 1:K) { d <- (U[i,k] - V[j,k])^2 adj[i,j] = adj[i,j] + lambda[k] / d } list(adj = adj, U = U, V = V, lambda = lambda, gamma = gamma) }
summaryRMD <- function(fit, fit2, pathout, numTrials=1, thisTrial){ dir.create(paste(pathout, "/", thisTrial, sep="")); cmPat <- fit$data$n.subj parms <- mcmc(cbind(fit$beta.dose, fit$beta.other, fit$s2.gamma, fit$s2.epsilon)) if (ncol(fit$beta.other) == 2) { varnames(parms) <- c("beta.dose", "beta.intercept", "beta.cycle", "s2.gamma", "s2.epsilon") }else{ varnames(parms) <- c("beta.dose", "beta.intercept", "s2.gamma", "s2.epsilon") } parms2 <- mcmc(cbind(fit2$beta.dose, fit2$beta.other, fit2$s2.gamma, fit2$s2.epsilon)) if (ncol(fit2$beta.other) == 2) { varnames(parms2) <- c("beta.dose", "beta.intercept", "beta.cycle", "s2.gamma", "s2.epsilon") }else{ varnames(parms2) <- c("beta.dose", "beta.intercept", "s2.gamma", "s2.epsilon") } combined=mcmc.list(mcmc(parms),mcmc(parms2)); res = summary(parms) write.table(res$statistics, file=paste(pathout, "/", thisTrial, "/statsParms", cmPat, ".txt", sep="")) write.table(res$quantile, file=paste(pathout, "/", thisTrial, "/quanParms", cmPat, ".txt", sep="")) write.table(effectiveSize(parms), file=paste(pathout, "/", thisTrial, "/sizeParms", cmPat, ".txt", sep="")) gamma.mc <- mcmc(fit$gamma) colnames.gamma <- NULL for (i in 1:cmPat) colnames.gamma <- c(colnames.gamma, paste("gamma", i, sep='')) varnames(gamma.mc) <- colnames.gamma res = summary(gamma.mc) write.table(res$statistics, file=paste(pathout, "/", thisTrial, "/statsGamma", cmPat, ".txt", sep="")) write.table(res$quantile, file=paste(pathout, "/", thisTrial, "/quanGamma", cmPat, ".txt", sep="")) write.table(effectiveSize(gamma.mc), file=paste(pathout, "/", thisTrial, "/sizeGamma", cmPat, ".txt", sep="")) if (thisTrial ==1 ){ } }
library(BART) k = 50 C = 8 thin = 10 ndpost = 1000 nskip = 100 par(mfrow=c(2, 2)) for(n in c(100, 1000, 10000)) { set.seed(12) x.train=matrix(runif(n*k, min=-1, max=1), n, k) Ey.train = pnorm(x.train[ , 1]^3) y.train=rbinom(n, 1, Ey.train) table(y.train) mc.train = mc.pbart(x.train, y.train, mc.cores=C, keepevery=thin, seed=99, ndpost=ndpost, nskip=nskip) x <- seq(-1, 1, length.out=200) plot(x, x^3, ylab='f(x)', type='l', sub=paste0('N:', n, ', k:', k, ', thin:', thin)) points(x.train[ , 1], mc.train$yhat.train.mean, pch='.', cex=2) i <- floor(seq(1, n, length.out=10)) auto.corr <- acf(mc.train$yhat.train[ , i], plot=FALSE) max.lag <- max(auto.corr$lag[ , 1, 1]) j <- seq(-0.5, 0.4, length.out=10) for(h in 1:10) { if(h==1) plot(1:max.lag+j[h], auto.corr$acf[1+(1:max.lag), h, h], type='h', xlim=c(0, max.lag+1), ylim=c(-1, 1), ylab='acf', xlab='lag') else lines(1:max.lag+j[h], auto.corr$acf[1+(1:max.lag), h, h], type='h', col=h) } for(j in 1:10) { if(j==1) plot(pnorm(mc.train$yhat.train[ , i[j]]), type='l', ylim=c(0, 1), sub=paste0('N:', n, ', k:', k, ', thin:', thin), ylab=expression(Phi(f(x))), xlab='m') else lines(pnorm(mc.train$yhat.train[ , i[j]]), type='l', col=j) } geweke <- gewekediag(mc.train$yhat.train) j <- -10^(log10(n)-1) plot(geweke$z, pch='.', cex=2, ylab='z', xlab='i', sub=paste0('N:', n, ', k:', k, ', thin:', thin), xlim=c(j, n), ylim=c(-5, 5)) lines(1:n, rep(-1.96, n), type='l', col=6) lines(1:n, rep(+1.96, n), type='l', col=6) lines(1:n, rep(-2.576, n), type='l', col=5) lines(1:n, rep(+2.576, n), type='l', col=5) lines(1:n, rep(-3.291, n), type='l', col=4) lines(1:n, rep(+3.291, n), type='l', col=4) lines(1:n, rep(-3.891, n), type='l', col=3) lines(1:n, rep(+3.891, n), type='l', col=3) lines(1:n, rep(-4.417, n), type='l', col=2) lines(1:n, rep(+4.417, n), type='l', col=2) text(c(1, 1), c(-1.96, 1.96), pos=2, cex=0.6, labels='0.95') text(c(1, 1), c(-2.576, 2.576), pos=2, cex=0.6, labels='0.99') text(c(1, 1), c(-3.291, 3.291), pos=2, cex=0.6, labels='0.999') text(c(1, 1), c(-3.891, 3.891), pos=2, cex=0.6, labels='0.9999') text(c(1, 1), c(-4.417, 4.417), pos=2, cex=0.6, labels='0.99999') } par(mfrow=c(1, 1))
confus <- function (clustering, model, diss=NULL) { clustering <- clustify(clustering) if (inherits(model,'tree')) { fitted <- predict(model) } else if (inherits(model,'randomForestest')) { fitted <- predict(model,type='prob') } else if (inherits(model,'matrix')) { fitted <- model } numplt <- length(clustering) numclu <- length(levels(clustering)) pred <- apply(fitted,1,which.max) res <- matrix(0,nrow=numclu,ncol=numclu) for (i in 1:numplt) { res[clustering[i],pred[i]] <- res[clustering[i],pred[i]] + 1 } if(!is.null(diss)) { part <- partana(clustering,diss) shunt <- diag(part$ctc) shunt[shunt==0] <- 1 tmp <- part$ctc/shunt fuzerr <- 1- matrix(pmin(1,tmp),ncol=ncol(tmp)) diag(fuzerr) <- 1 fuzres <- res for (i in 1:ncol(res)) { for (j in 1:ncol(res)) { if (i != j) { fuzres[i,j] <- res[i,j] * fuzerr[i,j] fuzres[i,i] <- fuzres[i,i] + res[i,j] * (1-fuzerr[i,j]) } } } res <- fuzres } correct <- sum(diag(res)) percent <- correct/numplt rowsum <- apply(res,1,sum) colsum <- apply(res,2,sum) summar <- sum(rowsum*colsum) kappa <- ((numplt*correct) - summar) / (numplt^2 - summar) out <- list(confus=res,correct=correct,percent=percent,kappa=kappa) out }
getAttXY <- function(attPerturb, attX, attY) { if (length(attPerturb) < 2) stop(paste0("sim should contain two or more perturbed attributes to plot a performance space.")) if (is.null(attX) & is.null(attY)) { attX <- attPerturb[1] attY <- attPerturb[2] message(paste0("Using attX = ", attX, ", and attY = ", attY, ". Specify attX and attY in the function call to choose alternate attributes.")) } else { attInd <- which(attPerturb %in% c(attX, attY)) if (!identical(attInd, integer(0))) { attPerturb <- attPerturb[-attInd] } if (is.null(attX)) { attX <- attPerturb[1] message(paste0("Using attX = ", attX, ". Specify attX in the function call to choose an alternate attribute.")) } else { attY <- attPerturb[1] message(paste0("Using attY = ", attY, ". Specify attY in the function call to choose an alternate attribute.")) } } return(list(attX = attX, attY = attY)) } getSimFitness <- function(sim) { repNames <- names(sim[grep("Rep", names(sim))]) if (is.null(repNames)) stop("There are no replicates in sim.") tarNames <- names(sim[[repNames[1]]]) nRep <- length(repNames) nTar <- length(tarNames) fitName <- "score" simFitness <- matrix(NA, nrow = length(tarNames), ncol = length(repNames)) for (r in 1:nRep) { simFitness[ ,r] <- sapply(sim[[repNames[r]]], function(x){sum(x[["score"]])}) } return(simFitness) } getPerfStat <- function(performance, simFitness, topReps, nRep, statFUN = mean ) { nTar <- nrow(performance) if (!is.null(topReps)) { if (topReps < nRep) { sortedPerf <- matrix(0, nrow = dim(performance)[1], ncol = dim(performance)[2]) for(i in 1:nTar){ ind <- order(simFitness[i, ], decreasing = TRUE) sortedPerf[i, ] <- performance[i, ind] } performanceStat <- as.data.frame(apply(sortedPerf[ , 1:topReps], 1, FUN = statFUN)) } else { performanceStat <- as.data.frame(apply(performance, 1, FUN = statFUN)) } } else { performanceStat <- as.data.frame(apply(performance, 1, FUN = statFUN)) } return(performanceStat) } checkAttPert <- function(targetMat, attX, attY) { if (attX == attY) { stop("attY should be different from attX.") } attNames <- colnames(targetMat) colAttX <- which(attNames == attX) colAttY <- which(attNames == attY) if (length(colAttX) == 0 | colAttY == 0) { stop("attX or attY is not available in sim.") } return(invisible()) } getSliceIndices <- function(expSpace, attSlices) { if (!(is.list(attSlices))) stop("attSlices should be a list.") attIn <- names(attSlices) if (is.null(attIn)) stop("attSlices should be named using the attribute tags to be sliced.") if (sum(attIn %in% c(expSpace[["attPerturb"]], expSpace[["attHold"]])) != length(attIn)) stop("attSlices should contain only attributes present in the expSpace of sim.") attPInd <- which(attIn %in% expSpace[["attPerturb"]]) attHInd <- which(attIn %in% expSpace[["attHold"]]) if (!identical(attHInd, integer(0))) { for (i in 1:length(attHInd)) { iAtt <- attIn[attHInd[i]] iAttVar <- strsplit(iAtt, "_")[[1]][1] if (iAttVar == "Temp") { if (attSlices[[iAtt]] != 0) stop(paste0(iAtt, " is a held attribute. attSlices[[\"", iAtt, "\"]] should be 0 or NULL.")) } else { if (attSlices[[iAtt]] != 1) stop(paste0(iAtt, " is a held attribute. attSlices[[\"", iAtt, "\"]] should be 1 or NULL.")) } } } targetMat <- expSpace[["targetMat"]] if (!identical(attPInd, integer(0))) { sliceIndicesList <- list() for (i in 1:length(attPInd)) { iAtt <- attIn[attPInd[i]] iSlice <- attSlices[[iAtt]] if (length(iSlice) == 1) { iSliceInd <- which(targetMat[[iAtt]] == iSlice) } else if (length(iSlice == 2)) { sMin <- min(iSlice) sMax <- max(iSlice) iSliceInd <- which(targetMat[[iAtt]]>=sMin & targetMat[[iAtt]]<=sMax) } if (identical(iSliceInd, integer(0))) stop(paste0("attSlices[[\"", iAtt, "\"]] is not valid for this expSpace.")) sliceIndicesList[[i]] <- iSliceInd } sliceIndices <- Reduce(intersect, sliceIndicesList) } else { sliceIndices <- c(1:nrow(targetMat)) } return(sliceIndices) } plotPerformanceSpace <- function(performance, sim, metric = NULL, attX = NULL, attY = NULL, topReps = NULL, perfThresh = NULL, perfThreshLabel = "Threshold", attSlices = NULL, climData = NULL, colMap = NULL, colLim = NULL ) { if (is.list(performance)) { if (!is.null(metric)) { if (!is.character(metric)) stop("`metric` should be specified as a string.") if (length(metric) > 1) stop("A single `metric` should be specified.") performance <- performance[metric] if (is.null(performance[[1]])) stop(paste0("Cannot find metric `", metric, "` in performance.")) perfName <- metric } else { if (is.null(names(performance))) { perfName <- rep("Performance", length(performance)) } else { perfName <- names(performance) } } } else if (is.matrix(performance)) { perfName <- "Performance" perfMat <- performance performance <- list() performance[[1]] <- perfMat rm(perfMat) } repNames <- names(sim[grep("Rep", names(sim))]) if (is.null(repNames)) stop("There are no replicates in sim.") tarNames <- names(sim[[repNames[1]]]) nRep <- length(repNames) nTar <- length(tarNames) targetMat <- sim[["expSpace"]][["targetMat"]] if (is.list(sim[["controlFile"]])) { simFitness <- getSimFitness(sim) if (!identical(dim(simFitness), dim(performance[[1]]))) { stop("The number of targets and replicates in sim and performance should match. Is the performance calculated using sim?") } if (!is.null(topReps)) { if (topReps > nRep) { message(paste0("sim does not contain ", topReps, " replicates. Using all replicates available in sim.\n")) } } } else { if (!(sim[["controlFile"]] == "scaling")) stop("sim$controlFile is unrecognized.") simFitness <- NULL topReps <- NULL } if (!is.null(attSlices)) { tarInd <- getSliceIndices(sim[["expSpace"]], attSlices) targetMat <- targetMat[tarInd, ] } else { tarInd <- NULL } if (is.null(attX) | is.null(attY)) { attPerturb <- sim[["expSpace"]][["attPerturb"]] attList <- getAttXY(attPerturb, attX, attY) attX <- attList[["attX"]] attY <- attList[["attY"]] } checkAttPert(targetMat, attX, attY) attNames <- colnames(targetMat) colAttX <- which(attNames == attX) colAttY <- which(attNames == attY) nPerf <- length(performance) perfPlots <- list() if (nPerf > 1) message("performance contains more than one performance metric, the first metric is plotted.") if (!is.null(tarInd)) { perfMatrix <- performance[[1]][tarInd, ] } else { perfMatrix <- performance[[1]] } performanceAv <- getPerfStat(perfMatrix, simFitness, topReps, nRep) names(performanceAv) <- perfName[1] perfPlotData <- cbind(targetMat[colAttX], targetMat[colAttY], performanceAv) perfPlots <- heatPlot(perfPlotData, colLim = colLim, colMap = colMap, perfThresh = perfThresh, perfThreshLabel = perfThreshLabel, climData = climData) print(perfPlots) return(invisible(perfPlots)) } plotPerfQuiltPlot <- function(plotData, nx, ny, colLim = NULL, colBar = TRUE, perfThresh = NULL, climData = NULL){ xyAtts <- colnames(plotData)[1:2] xyAttDefs <- mapply(tagBlender_noUnits, xyAtts, USE.NAMES = FALSE) if (is.null(colLim)) { tempMat <- plotData names(tempMat) <- c("x", "y", "z") tempMatAvg <- aggregate(.~x+y, tempMat, mean) colLim = c(min(tempMatAvg[ ,3]), max(tempMatAvg[ ,3])) rm(tempMat, tempMatAvg) } varNames <- sapply(strsplit(xyAtts, "_"), `[[`, 1) varUnits <- getVarUnits(varNames) xyLabels <- paste0(xyAttDefs, " (", varUnits, ")") par(mar=c(3.8,3.8,1,1),oma=c(5,0.3,0.3,0.3), mgp = c(0,0.5,0)) fields::quilt.plot(x = plotData[ ,1], y = plotData[ ,2], z = plotData[ ,3], nx = nx ,ny = ny, add.legend = FALSE, nlevel = perfSpace_nlevel, col = foreSIGHT.colmap(perfSpace_nlevel), xlim = c(min(plotData[ ,1]), max(plotData[ ,1])), ylim = c(min(plotData[ ,2]), max(plotData[ ,2])), zlim = colLim, xlab = "", ylab =) box(col = "black") mtext(side=1,text=xyLabels[1],line=1.8) mtext(side=2,text=xyLabels[2],line=1.8) if (perfSpace_contours) { look <- fields::as.image(plotData[ ,3], ind = cbind(plotData[ ,1], plotData[ ,2]), nx = nx, ny = ny) contour(add = TRUE, x = look$x, y = look$y, z = look$z, method="edge", labcex = 1, nlevels = perfSpace_nContour) } if (!is.null(perfThresh)) { contour(add = TRUE, x = look$x, y = look$y, z = look$z, lty=threshLty, lwd = threshLwd, col = perfSpace_threshCol, drawlabels = FALSE, levels = perfThresh) legend("topright", inset = c(0.005, 0.005), legend=paste0("Performance\nThreshold (", perfThresh, ")"), col=perfSpace_threshCol, lwd=threshLwd, lty=threshLty, cex=1, bty="n") } if (!is.null(climData)) { if (sum(colnames(climData) %in% xyAtts) == 2) { points(x = climData[[xyAtts[1]]], y = climData[[xyAtts[2]]], pch = perfSpace_climDataPch, col = perfSpace_climDataCol, bg = perfSpace_climDataBg) } else { warning(paste0("climData is not plotted since it does not contain ", paste(xyAtts[(colnames(climData) %in% xyAtts)], sep = ","), ".")) } } if(colBar){ fields::image.plot(legend.only = TRUE, zlim = colLim, col = foreSIGHT.colmap(perfSpace_nlevel), horizontal = TRUE, smallplot=c(0.2,0.9,0.0001,0.02)) } mtext(tag_text, side=1, line=1.5, adj=1.0, cex=0.8, col=tag_textCol, outer=TRUE) } heatPlot <- function(plotData, colLim = NULL, colMap = NULL, perfThresh = NULL, perfThreshLabel = "Threshold", climData = NULL) { level <- NULL xyAtts <- colnames(plotData)[1:2] perfName <- colnames(plotData)[3] xyAttDefs <- mapply(tagBlender_noUnits, xyAtts, USE.NAMES = FALSE) tempMat <- plotData names(tempMat) <- c("x", "y", "z") plotDataMean <- aggregate(.~x+y, tempMat, mean) names(plotDataMean) <- names(plotData) if (is.null(colLim)) { colLimIn = c(min(plotDataMean[ ,3]), max(plotDataMean[ ,3])) } else { colLimIn <- colLim } if (!is.null(perfThresh)) { tempData <- plotDataMean[ ,3] threshName <- paste0("Thresh", names(plotDataMean)[3]) names(tempData) <- threshName plotDataMean <- cbind(plotDataMean, tempData) names(plotDataMean) <- c(names(plotData), threshName) } varNames <- sapply(strsplit(xyAtts, "_"), `[[`, 1) varUnits <- getVarUnits(varNames) xyLabels <- paste0(xyAttDefs, " (", varUnits, ")") xlimits <- c(min(plotDataMean[ ,1]), max(plotDataMean[ ,1])) ylimits <- c(min(plotDataMean[ ,2]), max(plotDataMean[ ,2])) p1 <- ggplot() + geom_tile(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], fill = .data[[perfName]])) + labs(x = xyLabels[1], y = xyLabels[2]) + scale_x_continuous(expand=c(0, 0)) + scale_y_continuous(expand=c(0, 0)) + coord_cartesian(xlim=xlimits, ylim=ylimits) + theme_heatPlot() if(perfSpace_contours) { contourBreaks <- pretty(colLimIn, perfSpace_nContour) p1 <- p1 + geom_contour(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], z = .data[[perfName]]), colour = "black", breaks = contourBreaks) + directlabels::geom_dl(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], z = .data[[perfName]], label = stat(level)), method = list("first.points", "calc.boxes", "enlarge.box", box.color = NA, fill = "transparent", vjust=-0.5,hjust=-0.5, "draw.rects"),stat="contour", breaks = contourBreaks) } if (!is.null(perfThresh)) { p1 <- addContourThreshold(p1, plotDataMean, perfThresh, perfThreshLabel, xyAtts, perfName) } p2List <- addClimData(p1, climData, perfName, xyAtts, xlimits, ylimits, colLim, colLimIn) p2 <- p2List[[1]] colLimIn <- p2List[[2]] if (is.null(colMap)) { coloursIn <- foreSIGHT.colmap(perfSpace_nlevel) } else { coloursIn <- colMap } p2 <- p2 + scale_fill_gradientn(colours = coloursIn, limits = colLimIn, guide = guide_colorbar(title = perfName, title.position = "right", order = 1, barwidth = 12, barheight = 0.6)) + labs(tag = tag_text) return(p2) } addContourThreshold <- function(p1, plotDataMean, perfThresh, perfThreshLabel, xyAtts, perfName){ p1 <- p1 + geom_contour(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], z = .data[[perfName]]), breaks = perfThresh, colour = perfSpace_threshCol, size = threshLineSize) nx <- length(unique(plotDataMean[, 1])) ny <- length(unique(plotDataMean[, 2])) look <- fields::as.image(plotDataMean[ ,3], ind = cbind(plotDataMean[ ,1], plotDataMean[ ,2]), nx = nx, ny = ny) lineThresh <- contourLines(x = look$x, y = look$y, z = look$z, levels = perfThresh) if (!(length(lineThresh) == 0)) { lineNo <- 1 perfThreshData <- data.frame(x = lineThresh[[lineNo]]$x, y = lineThresh[[lineNo]]$y) perfThreshData$Tname <- perfThreshLabel nLines <- nrow(perfThreshData) p1 <- p1 + geom_label(data = perfThreshData[nLines, ], mapping = aes(x = .data$x, y = .data$y, label = .data$Tname), size = threshLabelSize, vjust = "inward", hjust = "inward") } else { message("perfThresh is not plotted becasue it is outside the performance space.") } return(p1) } addThresholdLines <- function(p1, plotDataMean, perfThresh, perfThreshLabel, xyAtts, perfName, lineCol, lineSize, lineAlpha, label = "beginning"){ p1 <- p1 + geom_contour(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], z = .data[[perfName]]), breaks = perfThresh, colour = lineCol, size = lineSize, alpha = lineAlpha) p2 <- ggplot()+geom_contour(data = plotDataMean, aes(x = .data[[xyAtts[1]]], y = .data[[xyAtts[2]]], z = .data[[perfName]]), breaks = perfThresh, colour = lineCol, size = lineSize, alpha = lineAlpha) p2Build <- ggplot_build(p2) threshContour <- data.frame(x = p2Build[["data"]][[1]]$x, y = p2Build[["data"]][[1]]$y) if (nrow(threshContour) > 0) { if (label == "beginning") { nLine <- 1 } else { nLine <- nrow(threshContour)-1 if (nLine == 0) nLine = 1 } threshContour$Tname <- perfThreshLabel p1 <- p1 + geom_label(data = threshContour[nLine, ], mapping = aes(x = .data$x, y = .data$y, label = .data$Tname), size = threshLabelSize, vjust = "inward", hjust = "inward") } else { message("perfThresh is not plotted becasue it is outside the performance space.") } return(p1) }
rainfarm <- function(r, slope, nf, weights = 1., fglob = FALSE, fsmooth = TRUE, verbose = FALSE) { drop <- FALSE nax <- dim(r)[1] nay <- dim(r)[2] nt <- dim(r)[3] if ( is.na(nt) ) { drop <- TRUE nt <- 1 } dim(r) <- c(nax, nay, nt) if ( nax == nay ) { nas <- nax } else { stop("The spatial dimensions of input array must be square") } ns <- nas * nf f <- initmetagauss(slope, ns) rd <- array(0., c(ns, ns, nt)) for (k in 1:nt) { if (verbose) { print(paste0("Frame ", k)) } r1 <- r[ , , k] if (mean(r1) == 0.) { rd[ , , k] <- matrix(0., ns, ns) } else { fm <- downscale(r1, f, weights, fglob = fglob, fsmooth = fsmooth) rd[ , , k] <- fm } } if (drop) { rd <- drop(rd) } return(rd) }
beta_cor=function(K=K,nk=nk,alpha=alpha,X=X,y=y){ n=nrow(X);p=ncol(X) M=N=W=c(rep(1,K)) R=matrix(rep(0,n*nk), ncol=n); Io=matrix(rep(0,nk*K), ncol=nk); mr=matrix(rep(0,K*nk),ncol=nk) for (i in 1:K){ mr[i,]=sample(1:n,nk,replace=T); r=matrix(c(1:nk,mr[i,]),ncol=nk,byrow=T); R[t(r)]=1 Io[i,]=r[2,] X1=R%*%X;y1=R%*%y; ux=solve(crossprod(X1)) W[i]= sum(diag(t(ux)%*% ux)) M[i]= det(X1%*%t(X1)) N[i]=t(y1)%*% y1 } int=intersect(intersect(Io[which.min(W),],Io[which.min(M),]),Io[which.min(N),]) lWMN=length(intersect(intersect(Io[which.min(W),],Io[which.max(M),]),Io[which.min(N),])) Xcor= X[intersect(intersect(Io[which.min(W),],Io[which.max(M),]),Io[which.min(N),]),]; ycor= y[intersect(intersect(Io[which.min(W),],Io[which.max(M),]),Io[which.min(N),])] betaC=solve(crossprod(Xcor))%*%t(Xcor)%*% ycor return(list(betaC=betaC)) }
AFglm <- function(object, data, exposure, clusterid, case.control = FALSE){ call <- match.call() if(!(as.character(object$call[1]) == "glm")) stop("The object is not a glm object", call. = FALSE) if(!(object$family[1] == "binomial" & object$family[2] == "logit")) stop("The object is not a logistic regression", call. = FALSE) formula <- object$formula npar <- length(object$coef) rownames(data) <- 1:nrow(data) m <- model.matrix(object = formula, data = data) complete <- as.numeric(rownames(m)) data <- data[complete, ] outcome <- as.character(terms(formula)[[2]]) n <- nrow(data) n.cases <- sum(data[, outcome]) clusters <- data[, clusterid] if(missing(clusterid)) n.cluster <- 0 else { n.cluster <- length(unique(data[, clusterid])) } if(!class(exposure) == "character") stop("Exposure must be a string.", call. = FALSE) if(!is.binary(data[, exposure])) stop("Only binary exposure (0/1) is accepted.", call. = FALSE) if(max(all.vars(formula[[3]]) == exposure) == 0) stop("The exposure variable is not included in the formula.", call. = FALSE) data0 <- data data0[, exposure] <- 0 design <- model.matrix(object = delete.response(terms(object)), data = data) design0 <- model.matrix(object = delete.response(terms(object)), data = data0) if (case.control == TRUE){ diff.design <- design0 - design linearpredictor <- design %*% coef(object) linearpredictor0 <- design0 %*% coef(object) log.or <- linearpredictor - linearpredictor0 AF.est <- 1 - sum(data[, outcome] * exp( - log.or)) / sum(data[, outcome]) score.AF <- data[, outcome] * (exp( - log.or) - AF.est) pred.diff <- data[, outcome] - predict(object, newdata = data, type = "response") score.beta <- design * pred.diff score.equations <- cbind(score.AF, score.beta) if (!missing(clusterid)){ score.equations <- score.equations score.equations <- aggr(score.equations, clusters = clusters) } meat <- var(score.equations, na.rm=TRUE) hessian.AF1 <- - data[, outcome] hessian.AF2 <- (design0 - design) * as.vector(data[, outcome] * exp( - log.or)) hessian.AF <- cbind(mean(hessian.AF1), t(colMeans(hessian.AF2, na.rm = TRUE))) hessian.beta <- cbind(matrix(rep(0, npar), nrow = npar, ncol = 1), - solve(vcov(object = object)) / n) bread <- rbind(hessian.AF, hessian.beta) if (!missing(clusterid)) sandwich <- (solve (bread) %*% meat %*% t(solve (bread)) * n.cluster / n^2 ) [1:2, 1:2] else sandwich <- (solve (bread) %*% meat %*% t(solve (bread)) / n) [1:2, 1:2] AF.var <- sandwich[1, 1] out <- c(list(AF.est = AF.est, AF.var = AF.var, log.or = log.or, objectcall = object$call, call = call, exposure = exposure, outcome = outcome, object = object, sandwich = sandwich, formula = formula, n = n, n.cases = n.cases, n.cluster = n.cluster)) } else { score.P <- data[, outcome] pred.Y <- predict(object, newdata = data, type = "response") score.P0 <- predict(object, newdata = data0, type = "response") score.beta <- design * (score.P - pred.Y) score.equations <- cbind(score.P, score.P0, score.beta) if (!missing(clusterid)){ score.equations <- score.equations score.equations <- aggr(score.equations, clusters = clusters) } meat <- var(score.equations, na.rm = TRUE) hessian.P <- matrix(c(- 1, 0, rep(0,npar)), nrow = 1, ncol = 2 + npar) g <- family(object)$mu.eta dmu.deta <- g(predict(object = object, newdata = data0)) deta.dbeta <- design0 dmu.dbeta <- dmu.deta * deta.dbeta hessian.P0 <- matrix(c(0, - 1, colMeans(dmu.dbeta)), nrow = 1, ncol = 2 + npar) hessian.beta <- cbind(matrix(rep(0, npar * 2), nrow = npar, ncol = 2) , - solve(vcov(object = object)) / n) bread <- rbind(hessian.P, hessian.P0, hessian.beta) if (!missing(clusterid)) sandwich <- (solve (bread) %*% meat %*% t(solve (bread)) * n.cluster / n^2 ) [1:2, 1:2] else sandwich <- (solve (bread) %*% meat %*% t(solve (bread)) / n) [1:2, 1:2] P.est <- mean(score.P, na.rm = TRUE) P0.est <- mean(score.P0, na.rm = TRUE) AF.est <- 1 - P0.est / P.est gradient <- as.matrix(c(P0.est / P.est ^ 2, - 1 / P.est), nrow = 2, ncol = 1) AF.var <- t(gradient) %*% sandwich %*% gradient P.var <- sandwich[1, 1] P0.var <- sandwich[2, 2] objectcall <- object$call out <- c(list(AF.est = AF.est, AF.var = AF.var, P.est = P.est, P0.est = P0.est, P.var = P.var, P0.var = P0.var, objectcall = objectcall, call = call, exposure = exposure, outcome = outcome, object = object, sandwich = sandwich, gradient = gradient, formula = formula, n = n, n.cases = n.cases, n.cluster = n.cluster)) } class(out) <- "AF" return(out) }
zero_range <- function(x, tol = .Machine$double.eps ^ 0.5) { if (length(x) == 1) return(TRUE) x <- range(x) / mean(x) isTRUE(all.equal(x[1], x[2], tolerance = tol)) } s2Data <- function(xL, yL, xU = NULL, preprocess = T){ n_l = nrow(xL) p = ncol(xL) if(any(is.na(xL)) | any(is.na(xU)) | any(is.na(yL))){ stop("NA's not supported :( yet :)") } if(!is.null(xU)){ if(ncol(xU)!=p){ stop("xL and xU have different number of columns") } } if(is.data.frame(xL)){ if (!isFALSE(preprocess)) { X = rbind(xL, xU) X = stats::model.matrix(~., X)[,-1] xL = X[1:n_l, ] if(!is.null(xU)) xU = X[-(1:n_l), ] } } type = "regression" base = 0 if(is.factor(yL)){ if(length(levels(yL))!=2){ stop("If yL is a factor, it should have exactly two levels") } y = as.numeric(yL) - 1 type = "classification" base = levels(yL)[1] yL = y } if(!is.numeric(yL)) stop("yL is not numeric or factor") xL = as.matrix(xL) yL = as.matrix(yL) if(!is.null(xU)) xU = as.matrix(xU) if(ncol(yL)!=1){ stop("yL has more than one column. Multivariate response not supported :( yet :)") } if(nrow(yL)!=n_l){ stop("xL and yL have different number of rows") } if(isTRUE(preprocess)){ rm_cols = apply(xL, 2, zero_range) xL = xL[, !rm_cols] if(!is.null(xU)) xU = xU[, !rm_cols] xL = scale(xL) s_scale = attr(xL, "scaled:scale") s_center = attr(xL, "scaled:center") if(!is.null(xU)) xU = scale(xU, center = s_center, scale = s_scale) if(type == "regression"){ yL = scale(yL, center = T, scale = F) y_center = attr(yL, "scaled:center") }else{ y_center = 0 } }else{ if(class(preprocess) == "s2Data"){ rm_cols = attr(preprocess, "pr:rm_cols") xL = xL[, !rm_cols] if(!is.null(xU)) xU = xU[, !rm_cols] s_scale = attr(preprocess, "pr:scale") s_center = attr(preprocess, "pr:center") xL = scale(xL, center = s_center, scale = s_scale) if(!is.null(xU)) xU = scale(xU, center = s_center, scale = s_scale) y_center = attr(preprocess, "pr:ycenter") if(type == "regression"){yL = scale(yL, center = y_center, scale = F)} }else{ rm_cols = rep(FALSE, ncol(xL)) s_scale = rep(1, ncol(xL)) s_center = rep(0, ncol(xL)) y_center = 0 } } s2D = list( xL = xL, yL = yL, xU = xU, type = type, base = base ) class(s2D) = "s2Data" attr(s2D, "pr:rm_cols") = unname(rm_cols) attr(s2D, "pr:center") = unname(s_center) attr(s2D, "pr:scale") = unname(s_scale) attr(s2D, "pr:ycenter") = unname(y_center) return(s2D) } print.s2Data <- function(x, ...){ plog("s2Data frame:") plog("Labeled data: ", nrow(x$xL), " ", ncol(x$xL)) plog("Unlabeled data: ", nrow(x$xU), " ", ncol(x$xU)) plog("Task ", x$type) } plog <- function(text,...){ cat(paste0(text,..., "\n")) }
context("inspect_na single dataframe") data("starwars", package = "dplyr") starwars$mass_lg <- starwars$mass > 70 test_that("Proportion test is correct", { d1 <- starwars %>% select(birth_year) d2 <- starwars[1:20, ] %>% select(birth_year) p1 <- inspect_na(d1, d2) %>% select(6) %>% as.numeric p2 <- prop.test(c(sum(is.na(d1)), sum(is.na(d2))), c(nrow(d1), nrow(d2)))$p.value expect_equal(p1, p2) })
context("bigquery") test_that("bigquery exists", { exists('TokenBigQueryKernel') exists('query_exec') })
context("select_n_to_m") test_that("n_to_m large = TRUE", { data("linkexample1", "linkexample2") by <- c("lastname", "firstname", "address", "sex", "postcode") p <- pair_blocking(linkexample1, linkexample2) %>% compare_pairs(by = by, default_comparator = jaro_winkler()) %>% score_simsum() %>% select_n_to_m(threshold = 2) expect_equal(names(p), c("x", "y", by, "simsum", "select")) expect_gt(min(p$simsum[p$select]), 2) expect_true(all(!duplicated(p$x[p$select]))) expect_true(all(!duplicated(p$y[p$select]))) expect_equal(attr(p, "x"), linkexample1) expect_equal(attr(p, "y"), linkexample2) expect_null(attr(p, "blocking_var")) expect_equal(attr(p, "by"), c("lastname", "firstname", "address", "sex", "postcode")) expect_equal(attr(p, "score"), "simsum") expect_equal(attr(p, "select"), "select") expect_s3_class(p, "compare") expect_s3_class(p, "pairs") expect_s3_class(p, "pairs_blocking") expect_s3_class(p, "ldat") }) gc() test_that("n_to_m large = FALSE", { data("linkexample1", "linkexample2") by <- c("lastname", "firstname", "address", "sex", "postcode") p <- pair_blocking(linkexample1, linkexample2, large = FALSE) %>% compare_pairs(by = by, default_comparator = jaro_winkler()) %>% score_simsum() %>% select_n_to_m(threshold = 2) expect_equal(names(p), c("x", "y", by, "simsum", "select")) expect_gt(min(p$simsum[p$select]), 2) expect_true(all(!duplicated(p$x[p$select]))) expect_true(all(!duplicated(p$y[p$select]))) expect_equal(attr(p, "x"), linkexample1) expect_equal(attr(p, "y"), linkexample2) expect_null(attr(p, "blocking_var")) expect_equal(attr(p, "by"), c("lastname", "firstname", "address", "sex", "postcode")) expect_equal(attr(p, "score"), "simsum") expect_equal(attr(p, "select"), "select") expect_s3_class(p, "compare") expect_s3_class(p, "pairs") expect_s3_class(p, "pairs_blocking") expect_s3_class(p, "data.frame") }) gc()
generate_compass_overlay = function(x=0.85, y=0.15, size=0.075, text_size=1, bearing=0, heightmap = NULL, width=NA, height=NA, color1 = "white", color2 = "black", text_color = "black", border_color = "black", border_width = 1, halo_color = NA, halo_expand = 1, halo_alpha = 1, halo_offset = c(0,0), halo_blur = 1) { loc = rep(0,2) loc[1] = x loc[2] = y if(is.na(height)) { height = ncol(heightmap) } if(is.na(width)) { width = nrow(heightmap) } cols <- rep(c(color1,color2),8) bearing = bearing*pi/180 radii <- rep(size/c(1,4,2,4),4) x <- radii[(0:15)+1]*cos((0:15)*pi/8+bearing)+loc[1] y <- radii[(0:15)+1]*sin((0:15)*pi/8+bearing)+loc[2] tempoverlay = tempfile(fileext = ".png") grDevices::png(filename = tempoverlay, width = width, height = height, units="px",bg = "transparent") graphics::par(mar = c(0,0,0,0)) graphics::plot(x=c(0,1),y=c(0,1), xlim = c(0,1), ylim = c(0,1), asp=1, pch = 0,bty="n",axes=FALSE, xaxs = "i", yaxs = "i", cex = 0, col = NA) for (i in 1:15) { x1 <- c(x[i],x[i+1],loc[1]) y1 <- c(y[i],y[i+1],loc[2]) graphics::polygon(x1,y1,col=cols[i], border = border_color, lwd = border_width) } graphics::polygon(c(x[16],x[1],loc[1]),c(y[16],y[1],loc[2]),col=cols[16], border = border_color, lwd = border_width) b <- c("E","N","W","S") for (i in 0:3) { graphics::text((size+graphics::par("cxy")[1])*cos(bearing+i*pi/2)+loc[1], (size+graphics::par("cxy")[2])*sin(bearing+i*pi/2)+loc[2],b[i+1], cex=text_size,col=text_color) } grDevices::dev.off() overlay_temp = png::readPNG(tempoverlay) if(!is.na(halo_color)) { if(!("rayimage" %in% rownames(utils::installed.packages()))) { stop("{rayimage} package required for `halo_color`") } tempoverlay = tempfile(fileext = ".png") grDevices::png(filename = tempoverlay, width = width, height = height, units="px",bg = "transparent") graphics::par(mar = c(0,0,0,0)) graphics::plot(x=c(0,1),y=c(0,1), xlim = c(0,1), ylim = c(0,1), asp=1, pch = 0,bty="n",axes=FALSE, xaxs = "i", yaxs = "i", cex = 0, col = NA) for (i in 1:15) { x1 <- c(x[i],x[i+1],loc[1]) y1 <- c(y[i],y[i+1],loc[2]) graphics::polygon(x1+halo_offset[1],y1+halo_offset[2],col=cols[i], border = border_color, lwd = border_width) } graphics::polygon(c(x[16],x[1],loc[1])+halo_offset[1], c(y[16],y[1],loc[2])+halo_offset[2],col=cols[16], border = border_color, lwd = border_width) b <- c("E","N","W","S") for (i in 0:3) { graphics::text((size+graphics::par("cxy")[1])*cos(bearing+i*pi/2)+loc[1]+halo_offset[1], (size+graphics::par("cxy")[2])*sin(bearing+i*pi/2)+loc[2]+halo_offset[2],b[i+1], cex=text_size,col=text_color) } grDevices::dev.off() overlay_temp_under = png::readPNG(tempoverlay) if(halo_expand != 0 || any(halo_offset != 0)) { temp_alpha = overlay_temp_under[,,4] temp_alpha[temp_alpha > 0] = 1 booldistance = rayimage::render_boolean_distance(temp_alpha) booldistance = booldistance - halo_expand temp_alpha[booldistance <= 0] = 1 temp_alpha[booldistance < 1 & booldistance > 0] = 1 - booldistance[booldistance < 1 & booldistance > 0] temp_alpha[booldistance > 1] = 0 col_below = convert_color(halo_color) temp_array = array(0, dim = dim(overlay_temp_under)) temp_array[,,1] = col_below[1] temp_array[,,2] = col_below[2] temp_array[,,3] = col_below[3] temp_array[,,4] = temp_alpha * halo_alpha overlay_temp_under = temp_array } if(halo_blur > 0) { overlay_temp_under = rayimage::render_convolution(overlay_temp_under, kernel = rayimage::generate_2d_gaussian(sd = halo_blur, dim = 31, width = 30), progress = FALSE) } return(add_overlay(overlay_temp_under, overlay_temp)) } return(overlay_temp) }
1++1 - 3 / 23 * 3 ^4
myffitYP412 <- function(x2, myY, myd, myZ, beta1) { tempT <- fitYP41(Y=myY, d=myd, Z=myZ, beta1=beta1, beta2=x2) return( - tempT$EmpLik) }
library("shiny") library("shinyWidgets") ui <- fluidPage( tags$h2("Dropdown Button"), br(), dropdown( tags$h3("List of Input"), pickerInput(inputId = 'xcol2', label = 'X Variable', choices = names(iris), options = list(`style` = "btn-info")), pickerInput(inputId = 'ycol2', label = 'Y Variable', choices = names(iris), selected = names(iris)[[2]], options = list(`style` = "btn-warning")), sliderInput(inputId = 'clusters2', label = 'Cluster count', value = 3, min = 1, max = 9), style = "unite", icon = icon("cog"), status = "danger", width = "300px", animate = animateOptions( enter = animations$fading_entrances$fadeInLeftBig, exit = animations$fading_exits$fadeOutRightBig ) ), plotOutput(outputId = 'plot2') ) server <- function(input, output, session) { selectedData2 <- reactive({ iris[, c(input$xcol2, input$ycol2)] }) clusters2 <- reactive({ kmeans(selectedData2(), input$clusters2) }) output$plot2 <- renderPlot({ palette(c(" " " par(mar = c(5.1, 4.1, 0, 1)) plot(selectedData2(), col = clusters2()$cluster, pch = 20, cex = 3) points(clusters2()$centers, pch = 4, cex = 4, lwd = 4) }) } shinyApp(ui = ui, server = server)
library(gbutils) pdf1 <- function(x) dnorm(x, mean = 100, sd = 5) qdf1 <- function(x) qnorm(x, mean = 100, sd = 5) cdf1 <- function(x) pnorm(x, mean = 100, sd = 5) plotpdf(pdf1, qdf1) plotpdf(pdf1, cdf = cdf1) plotpdf(pdf1, cdf = cdf1, lq = 0.001, uq = 0.999) plotpdf(cdf1, cdf = cdf1, lq = 0.001, uq = 0.999) pf1 <- function(x){ 0.25 * pnorm(x, mean = 3, sd = 0.2) + 0.75 * pnorm(x, mean = -1, sd = 0.5) } df1 <- function(x){ 0.25 * dnorm(x, mean = 3, sd = 0.2) + 0.75 * dnorm(x, mean = -1, sd = 0.5) } plotpdf(df1, cdf = pf1) plotpdf(pf1, cdf = pf1) plotpdf(pf1, cdf = pf1) plotpdf(df1, cdf = pf1, add = TRUE, col = "blue") c(q5pc = cdf2quantile(0.05, pf1), q95pc = cdf2quantile(0.95, pf1))
setClassUnion("nullOrDatatable", c("NULL", "data.table"))
from_integer_flux_lists_with_defaults=function( internal_flux_rates=list() ,out_flux_rates=list() ,numberOfPools ){ np=PoolIndex(numberOfPools) N=matrix(nrow=np,ncol=np,0) for (ofr in out_flux_rates){ src=ofr@sourceIndex if (src> np){stop("The index of the source pool must be smaller than the number of pools")} N[src,src]=ofr@rate_constant } for (ifr in internal_flux_rates){ dest<-ifr@destinationIndex if (dest> np){stop("The index of the destination pool of all internal fluxes must be smaller than the number of pools")} src<-ifr@sourceIndex if (src> np){stop("The index of the source pool of all internal fluxes must be smaller than the number of pools")} N[src,src]=N[src,src]+ifr@rate_constant } To=diag(nrow=np,-1) for (ifr in internal_flux_rates){ To[dest,src]=ifr@rate_constant/N[src,src] } B<-To%*%N return(new('ConstLinDecompOp',mat=B)) } setMethod( f="initialize", signature="ConstLinDecompOp", definition=function (.Object,mat=matrix()) { .Object@mat=mat return(.Object) } ) setMethod( "ConstLinDecompOp" ,signature=signature( mat='matrix' ,internal_flux_rates='missing' ,out_flux_rates='missing' ,numberOfPools='missing' ,poolNames='missing' ) ,definition=function( mat){ r <- nrow(mat) c <- ncol(mat) assertthat::are_equal( r ,c ,msg=sprintf('The matrix has to be quadratic!. Your matrix has %s rows and %s columns',r,c) ) return(new("ConstLinDecompOp",mat=mat)) } ) setMethod( "ConstLinDecompOp" ,signature=signature( mat='missing' ,internal_flux_rates='ConstantInternalFluxRateList_by_PoolIndex' ,out_flux_rates='ConstantOutFluxRateList_by_PoolIndex' ,numberOfPools='numeric' ,poolNames='missing' ) ,definition=function( internal_flux_rates ,out_flux_rates ,numberOfPools ){ from_integer_flux_lists_with_defaults( internal_flux_rates=internal_flux_rates ,out_flux_rates = out_flux_rates ,numberOfPools = numberOfPools ) } ) setMethod( "ConstLinDecompOp" ,signature=signature( mat='missing' ,internal_flux_rates='missing' ,out_flux_rates='ConstantOutFluxRateList_by_PoolIndex' ,numberOfPools='numeric' ,poolNames='missing' ) ,definition=function( out_flux_rates ,numberOfPools ){ from_integer_flux_lists_with_defaults( out_flux_rates = out_flux_rates ,numberOfPools = numberOfPools ) } ) setMethod( "ConstLinDecompOp" ,signature=signature( mat='missing' ,internal_flux_rates='ConstantInternalFluxRateList_by_PoolIndex' ,out_flux_rates='missing' ,numberOfPools='numeric' ,poolNames='missing' ) ,definition=function( internal_flux_rates ,numberOfPools ){ from_integer_flux_lists_with_defaults( internal_flux_rates=internal_flux_rates ,numberOfPools = numberOfPools ) } ) setMethod( 'ConstLinDecompOp' ,signature=signature( mat='missing' ,internal_flux_rates='ConstantInternalFluxRateList_by_PoolName' ,out_flux_rates='ConstantOutFluxRateList_by_PoolName' ,poolNames='character' ,numberOfPools='missing' ) ,definition=function( internal_flux_rates ,out_flux_rates ,poolNames ){ ConstLinDecompOp( internal_flux_rates=by_PoolIndex(internal_flux_rates,poolNames) , out_flux_rates=by_PoolIndex(out_flux_rates,poolNames) ,numberOfPools=length(poolNames) ) } ) no_outflux_warning=function(){ warning('Compartmental system without out fluxes. For non zero inputs the material will accumulate in the system.') } setMethod( f="getFunctionDefinition", signature="ConstLinDecompOp", definition=function (object){ return(function(t){object@mat}) } ) setMethod( f="getTimeRange", signature="ConstLinDecompOp", definition=function (object) { return( c("t_min"=-Inf,"t_max"=Inf)) } ) setMethod( f= "getMeanTransitTime", signature= "ConstLinDecompOp", definition=function (object, inputDistribution ){ f=getFunctionDefinition(object) g=function(t){spectralNorm(f(t))} t_max=function(t_end){ t_step=t_end/10 t=seq(0,t_end,t_step) norms=sapply(t,g) tm=100*max(norms) return(tm) } t_end=20 t_end_new=t_max(t_end) while(t_end_new>t_end){ t_end=t_end_new t_end_new=t_max(t_end) } longTailEstimate=t_end subd=10000 t_step=t_end/subd t=seq(0,t_end,t_step) shortTailEstimate=min(sapply(t,g)) ttdd=getTransitTimeDistributionDensity(object,inputDistribution,t) int2=splinefun(t,ttdd*t) meanTimeIntegrate=integrate(int2,0,t_end,subdivisions=subd)[["value"]] return(meanTimeIntegrate) } ) setMethod( f= "getTransitTimeDistributionDensity", signature= "ConstLinDecompOp", definition=function (object, inputDistribution, times ){ sVmat=inputDistribution n=length(inputDistribution) inputFluxes=BoundInFluxes( map=function(t0){matrix(nrow=n,ncol=1,0)}, starttime= -Inf, endtime=+Inf ) mod=GeneralModel(times,object,sVmat,inputFluxes) R=getReleaseFlux(mod) TTD=rowSums(R) return(TTD) } ) setMethod( f= "getCompartmentalMatrixFunc", signature(object="ConstLinDecompOp"), definition=function(object){ getFunctionDefinition(object) } ) setMethod( f= "getConstantCompartmentalMatrix", signature(object="ConstLinDecompOp"), definition=function(object){ object@mat } ) non_zero_rates=function(all_rates){ all_rates[ as.logical( lapply( all_rates ,function(cofr){cofr@rate_constant!=0} ) ) ] } setMethod( f= "getConstantOutFluxRateList_by_PoolIndex", signature(object="ConstLinDecompOp"), definition=function(object){ B=object@mat np=nrow(B) all_rates=lapply( 1:np ,function(pool){ ConstantOutFluxRate_by_PoolIndex( sourceIndex=pool ,rate_constant= -sum(B[, pool]) ) } ) ConstantOutFluxRateList_by_PoolIndex( non_zero_rates( all_rates ) ) } ) setMethod( f= "getConstantInternalFluxRateList_by_PoolIndex", signature(object="ConstLinDecompOp"), definition=function(object){ B=object@mat np=nrow(B) pipes=sets::cset_cartesian(1:np,1:np) - as.set(lapply((1:np),function(i){tuple(i,i)})) all_rates=lapply( pipes ,function(tup){ pool_to <-tup[[1]] pool_from<-tup[[2]] flux_rate = ConstantInternalFluxRate_by_PoolIndex( sourceIndex =pool_from ,destinationIndex =pool_to ,rate_constant= B[pool_to, pool_from] ) } ) ConstantInternalFluxRateList_by_PoolIndex( non_zero_rates( all_rates ) ) } )
"[<-.XMLNode" <- function(x, i, value) { x$children[i] <- value if(!is.character(i)) { names(x$children)[i] = if(inherits(value, "XMLNode")) xmlName(value) else sapply(value, xmlName) } x } "[[<-.XMLNode" <- function(x, i, value) { x$children[[i]] <- value if(!is.character(i)) { names(x$children)[i] = if(inherits(value, "XMLNode")) xmlName(value) else sapply(value, xmlName) } x } append <- append.xmlNode <- function(to, ...) { UseMethod("append") } append.XMLNode <- function(to, ...) { args <- list(...) if(!inherits(args[[1]], "XMLNode") && is.list(args[[1]])) args <- args[[1]] idx <- seq(length(to$children) + 1, length=length(args)) args = addNames(args) if(is.null(to$children)) to$children <- args else { to$children[idx] <- args names(to$children)[idx] <- names(args) } to } append.default <- function(to, ...) base::append(to, ...) if(FALSE) { xmlAddChild <- function(node, child) { node$children <- append(node$children, list(child)) names(node$children) <- sapply(node$children,xmlName) node } }
ch_job <- function(n = 1, locale = NULL) { assert(n, c('integer', 'numeric')) if (n == 1) { JobProvider$new(locale = locale)$render() } else { x <- JobProvider$new(locale = locale) replicate(n, x$render()) } }
context("EAT") simulated <- eat:::X2Y2.sim(N = 50, border = 0.1) model <- EAT(data = simulated, x = c(1,2), y = c(3, 4)) test_that("Return an object EAT of length 5", { expect_s3_class(model, "EAT") expect_equal(length(model), 5) }) test_that("Tree is a list", { expect_type(model[["tree"]], "list") }) test_that("Acceptable data: dataframe matrix or list", { data1 <- data.frame(simulated) data2 <- as.matrix(simulated) data3 <- list(x1 = data1$x1, x2 = data1$x2, y1 = data1$y1, y2 = data1$y2) set.seed(10) EAT1 <- EAT(data = data1, x = c(1, 2), y = c(3, 4)) set.seed(10) EAT2 <- EAT(data = data2, x = c(1, 2), y = c(3, 4)) set.seed(10) EAT3 <- EAT(data = data3, x = c(1, 2), y = c(3, 4)) expect_identical(EAT1, EAT2) expect_identical(EAT1, EAT3) }) test_that("Indexes bad defined", { expect_error(EAT(data = simulated, x = c(1, 8), y = c(3, 4))) }) test_that("Pareto-dominance property", { expect_true(checkEAT(model[["tree"]])) })
setMethodS3("findAnnotationDataByChipType", "default", function(chipType, pattern=chipType, ...) { findAnnotationData(name=chipType, pattern=pattern, set="chipTypes", ...) }, protected=TRUE)
knitr::opts_chunk$set(eval = TRUE, message = FALSE, warning = FALSE) library(economiccomplexity) head(world_trade_avg_1998_to_2000) head(world_gdp_avg_1998_to_2000) bi <- balassa_index(world_trade_avg_1998_to_2000) head(bi) bi_dec <- balassa_index(world_trade_avg_1998_to_2000, discrete = F) head(bi_dec) com_fit <- complexity_measures(bi) com_fit$complexity_index_country[1:5] com_fit$complexity_index_product[1:5] com_ref <- complexity_measures(bi, method = "reflections") com_ref$complexity_index_country[1:5] com_ref$complexity_index_product[1:5] com_eig <- complexity_measures(bi, method = "eigenvalues") com_eig$complexity_index_country[1:5] com_eig$complexity_index_product[1:5] pro <- proximity(bi) pro$proximity_country[1:5,1:5] pro$proximity_product[1:5,1:5] library(igraph) net <- projections(pro$proximity_country, pro$proximity_product) E(net$network_country)[1:5] E(net$network_product)[1:5] set.seed(200100) library(Matrix) library(ggraph) aggregated_countries <- aggregate( world_trade_avg_1998_to_2000$value, by = list(country = world_trade_avg_1998_to_2000$country), FUN = sum ) aggregated_countries <- setNames(aggregated_countries$x, aggregated_countries$country) V(net$network_country)$size <- aggregated_countries[match(V(net$network_country)$name, names(aggregated_countries))] ggraph(net$network_country, layout = "kk") + geom_edge_link(edge_colour = " geom_node_point(aes(size = size), color = " geom_node_text(aes(label = name), size = 2, vjust = 2.2) + ggtitle("Proximity Based Network Projection for Countries") + theme_void() set.seed(200100) aggregated_products <- aggregate( world_trade_avg_1998_to_2000$value, by = list(country = world_trade_avg_1998_to_2000$product), FUN = sum ) aggregated_products <- setNames(aggregated_products$x, aggregated_products$country) V(net$network_product)$size <- aggregated_products[match(V(net$network_product)$name, names(aggregated_products))] ggraph(net$network_product, layout = "kk") + geom_edge_link(edge_colour = " geom_node_point(aes(size = size), color = " geom_node_text(aes(label = name), size = 2, vjust = 2.2) + ggtitle("Proximity Based Network Projection for Products") + theme_void() co <- complexity_outlook( economiccomplexity_output$balassa_index, economiccomplexity_output$proximity$proximity_product, economiccomplexity_output$complexity_measures$complexity_index_product ) co$complexity_outlook_index[1:5] co$complexity_outlook_gain[1:5,1:5] pl <- productivity_levels(world_trade_avg_1998_to_2000, world_gdp_avg_1998_to_2000) pl$productivity_level_country[1:5] pl$productivity_level_product[1:5]
.intervalSystem <- function(intervalSystem, lengths = NULL, data) { if (is.null(intervalSystem)) { intervalSystem <- data$defaultIntervalSystem } intervalSystem <- match.arg(intervalSystem, c("all", "dyaLen", "dyaPar")) ret <- list(intervalSystem = intervalSystem) possibleLengthsIntervalSystem <- switch(intervalSystem, all = 1:data$n, dyaLen = 2^(0:as.integer(floor(log2(data$n)) + 1e-6)), dyaPar = 2^(0:as.integer(floor(log2(data$n)) + 1e-6)) ) ret$possibleLengths <- data$possibleLengths[.inOrdered(data$possibleLengths, possibleLengthsIntervalSystem)] if (is.null(lengths)) { lengths <- data$defaultLengths[.inOrdered(data$defaultLengths, ret$possibleLengths)] } else { if (!is.numeric(lengths) || any(!is.finite(lengths))) { stop("lengths must be an integer vector containing finite values") } if (any(!is.integer(lengths))) { lengths <- as.integer(lengths + 1e-6) } if (is.unsorted(lengths, strictly = TRUE)) { lengths <- sort(lengths) if (is.unsorted(lengths, strictly = TRUE)) { warning("lengths contains duplicated values, they will be removed") lengths <- unique(lengths) } } if (any(!(.inOrdered(lengths, ret$possibleLengths)))) { wrongIntervalSystem <- !(.inOrdered(lengths, possibleLengthsIntervalSystem)) wrongData <- !(.inOrdered(lengths, data$possibleLengths)) if (any(wrongIntervalSystem) && any(wrongData)) { stop("argument 'lengths' contains inappropriate values.", " The following lengths are not possible for ", data$n, " observations and ", "interval system '", intervalSystem, "': ", paste(lengths[wrongIntervalSystem], collapse = ', '), ". ", "And the following lengths are not possible for parametric family '", data$family, "': ", paste(lengths[wrongData], collapse = ', '), ". ", "Please see also the documentation for possible choices.") } else if (any(wrongIntervalSystem)) { stop("argument 'lengths' contains inappropriate values.", " The following lengths are not possible for ", data$n, " observations and ", "interval system '", intervalSystem, "': ", paste(lengths[wrongIntervalSystem], collapse = ', '), ". ", "Please see also the documentation for possible choices.") } else if (any(wrongData)) { stop("argument 'lengths' contains inappropriate values.", " The following lengths are not possible for ", data$n, " observations and ", "parametric family '", data$family, "': ", paste(lengths[wrongData], collapse = ', '), ". ", "Please see also the documentation for possible choices.") } } } ret$lengths <- lengths if (intervalSystem == "all") { lengths <- logical(data$n) lengths[ret$lengths] <- TRUE if (all(lengths)) { ret$type = 0L } else { ret$type = 1L ret$argumentsList = list(lengths = lengths) } } else if (intervalSystem == "dyaLen") { if (length(lengths) == as.integer(floor(log2(data$n)) + 1e-6) + 1) { ret$type = 10L } else { ret$type = 11L ret$argumentsList = list(lengths = as.integer(ret$lengths)) } } else if (intervalSystem == "dyaPar") { if (length(lengths) == as.integer(floor(log2(data$n)) + 1e-6) + 1) { ret$type = 20L } else { ret$type = 21L ret$argumentsList = list(lengths = as.integer(ret$lengths)) } } ret }
output$parametric_changepoint_table_select <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) parametric_seriesToChangePoint <- reactiveValues(table=data.frame()) observeEvent(input$parametric_changepoint_button_select, priority = 1, { parametric_seriesToChangePoint$table <<- rbind(parametric_seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$parametric_changepoint_table_select_rows_selected]) & !(rownames(yuimaGUItable$series) %in% rownames(parametric_seriesToChangePoint$table)),]) }) observeEvent(input$parametric_changepoint_button_selectAll, priority = 1, { parametric_seriesToChangePoint$table <<- rbind(parametric_seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$parametric_changepoint_table_select_rows_all]) & !(rownames(yuimaGUItable$series) %in% rownames(parametric_seriesToChangePoint$table)),]) }) output$parametric_changepoint_table_selected <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (length(rownames(parametric_seriesToChangePoint$table))==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (parametric_seriesToChangePoint$table) }) observe({ if(length(parametric_seriesToChangePoint$table)!=0){ if (length(yuimaGUItable$series)==0) parametric_seriesToChangePoint$table <<- data.frame() else parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[which(as.character(parametric_seriesToChangePoint$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) observeEvent(input$parametric_changepoint_button_delete, priority = 1,{ if (!is.null(input$parametric_changepoint_table_selected_rows_selected)) parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[-input$parametric_changepoint_table_selected_rows_selected,] }) observeEvent(input$parametric_changepoint_button_deleteAll, priority = 1,{ if (!is.null(input$parametric_changepoint_table_selected_rows_all)) parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[-input$parametric_changepoint_table_selected_rows_all,] }) output$parametric_changepoint_model <- renderUI({ choices <- as.vector(defaultModels[names(defaultModels)=="Diffusion process"]) sel <- choices[1] for(i in names(yuimaGUIdata$usr_model)) if (yuimaGUIdata$usr_model[[i]]$class=="Diffusion process") choices <- c(i, choices) selectInput("parametric_changepoint_model", label = "Model", choices = choices, multiple = FALSE, selected = sel) }) parametric_range_selectRange <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$parametric_selectRange_brush) & !is.null(input$parametric_plotsRangeSeries)){ data <- getData(input$parametric_plotsRangeSeries) test <- (length(index(window(data, start = input$parametric_selectRange_brush$xmin, end = input$parametric_selectRange_brush$xmax))) > 3) if (test==TRUE){ parametric_range_selectRange$x <- c(as.Date(input$parametric_selectRange_brush$xmin), as.Date(input$parametric_selectRange_brush$xmax)) parametric_range_selectRange$y <- c(input$parametric_selectRange_brush$ymin, input$parametric_selectRange_brush$ymax) } } }) observe({ shinyjs::toggle(id="parametric_plotsRangeErrorMessage", condition = nrow(parametric_seriesToChangePoint$table)==0) shinyjs::toggle(id="parametric_plotsRangeAll", condition = nrow(parametric_seriesToChangePoint$table)!=0) }) observe({ symb <- input$parametric_plotsRangeSeries if(!is.null(symb)) if (symb %in% rownames(yuimaGUItable$series)){ data <- getData(symb) incr <- na.omit(Delt(data, type = "arithmetic")) condition <- all(is.finite(incr)) shinyjs::toggle("parametric_selectRangeReturns", condition = condition) parametric_range_selectRange$x <- NULL parametric_range_selectRange$y <- NULL start <- as.character(parametric_seriesToChangePoint$table[input$parametric_plotsRangeSeries,"From"]) end <- as.character(parametric_seriesToChangePoint$table[input$parametric_plotsRangeSeries,"To"]) if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } output$parametric_selectRange <- renderPlot({ if ((symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(parametric_seriesToChangePoint$table)))){ par(bg="black") plot.zoo(window(data, start = parametric_range_selectRange$x[1], end = parametric_range_selectRange$x[2]), main=symb, xlab="Index", ylab=NA, log=switch(input$parametric_scale_selectRange,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(data, start = start, end = end), col = "green") grid(col="grey") } }) output$parametric_selectRangeReturns <- renderPlot({ if (symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(parametric_seriesToChangePoint$table)) & condition){ par(bg="black") plot.zoo( window(incr, start = parametric_range_selectRange$x[1], end = parametric_range_selectRange$x[2]), main=paste(symb, " - Percentage Increments"), xlab="Index", ylab=NA, log=switch(input$parametric_scale_selectRange,"Linear"="","Logarithmic (Y)"="", "Logarithmic (X)"="x", "Logarithmic (XY)"="x"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(incr, start = start, end = end), col = "green") grid(col="grey") } }) } }) output$parametric_plotsRangeSeries <- renderUI({ selectInput("parametric_plotsRangeSeries", label = "Series", choices = rownames(parametric_seriesToChangePoint$table), selected = input$parametric_plotsRangeSeries) }) output$parametric_chooseRange <- renderUI({ sel <- "full" if (!is.null(parametric_range_selectRange$x)) sel <- "selected" selectInput("parametric_chooseRange", label = "Range", choices = c("Full Range" = "full", "Select Range from Charts" = "selected", "Specify Range" = "specify"), selected = sel) }) output$parametric_chooseRange_specify <- renderUI({ if(!is.null(input$parametric_plotsRangeSeries)) { data <- getData(input$parametric_plotsRangeSeries) if(class(index(data))=="numeric") return(div( column(6,numericInput("parametric_chooseRange_specify_t0", label = "From", min = start(data), max = end(data), value = start(data))), column(6,numericInput("parametric_chooseRange_specify_t1", label = "To", min = start(data), max = end(data), value = end(data))) )) if(class(index(data))=="Date") return(dateRangeInput("parametric_chooseRange_specify_date", start = start(data), end = end(data), label = "Specify Range")) } }) observe({ shinyjs::toggle(id = "parametric_chooseRange_specify", condition = (input$parametric_chooseRange)=="specify") }) updateRange_parametric_seriesToChangePoint <- function(symb, range = c("full","selected","specify"), type = c("Date", "numeric")){ for (i in symb){ data <- getData(i) if (range == "full"){ levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start(data))) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end(data))) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start(data)) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end(data)) } if (range == "selected"){ if(!is.null(parametric_range_selectRange$x) & class(index(data))==type){ start <- parametric_range_selectRange$x[1] end <- parametric_range_selectRange$x[2] if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } start <- max(start(data),start) end <- min(end(data), end) levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start)) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end)) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end) } } if (range == "specify"){ if(class(index(data))==type){ if(class(index(data))=="Date"){ start <- input$parametric_chooseRange_specify_date[1] end <- input$parametric_chooseRange_specify_date[2] } if(class(index(data))=="numeric"){ start <- input$parametric_chooseRange_specify_t0 end <- input$parametric_chooseRange_specify_t1 } start <- max(start(data),start) end <- min(end(data), end) levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start)) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end)) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end) } } } } observeEvent(input$parametric_selectRange_dbclick, priority = 1, { updateRange_parametric_seriesToChangePoint(input$parametric_plotsRangeSeries, range = "selected", type = class(index(getData(input$parametric_plotsRangeSeries)))) }) observeEvent(input$parametric_buttonApplyRange, priority = 1, { updateRange_parametric_seriesToChangePoint(input$parametric_plotsRangeSeries, range = input$parametric_chooseRange, type = class(index(getData(input$parametric_plotsRangeSeries)))) }) observeEvent(input$parametric_buttonApplyAllRange, priority = 1, { updateRange_parametric_seriesToChangePoint(rownames(parametric_seriesToChangePoint$table), range = input$parametric_chooseRange, type = class(index(getData(input$parametric_plotsRangeSeries)))) }) parametric_modal_prev_buttonDelta <- 0 parametric_modal_prev_buttonAllDelta <- 0 observe({ for (symb in rownames(parametric_seriesToChangePoint$table)){ if (is.null(yuimaGUIsettings$delta[[symb]])) yuimaGUIsettings$delta[[symb]] <<- 0.01 if (is.null(yuimaGUIsettings$toLog[[symb]])) yuimaGUIsettings$toLog[[symb]] <<- FALSE data <- getData(symb) if (yuimaGUIsettings$toLog[[symb]]==TRUE) data <- log(data) for (modName in input$parametric_changepoint_model){ if (class(try(setModelByName(modName, jumps = NA, AR_C = NA, MA_C = NA)))!="try-error"){ if (is.null(yuimaGUIsettings$estimation[[modName]])) yuimaGUIsettings$estimation[[modName]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]])) yuimaGUIsettings$estimation[[modName]][[symb]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["start"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["start"]] <<- list() startMinMax <- defaultBounds(name = modName, jumps = NA, AR_C = NA, MA_C = NA, strict = FALSE, data = data, delta = yuimaGUIsettings$delta[[symb]]) upperLower <- defaultBounds(name = modName, jumps = NA, AR_C = NA, MA_C = NA, strict = TRUE, data = data, delta = yuimaGUIsettings$delta[[symb]]) if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]] <<- startMinMax$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]] <<- startMinMax$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]] <<- upperLower$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]] <<- upperLower$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["method"]])){ yuimaGUIsettings$estimation[[modName]][[symb]][["method"]] <<- "L-BFGS-B" } if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]] <<- 1 if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]] <<- NA if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]] <<- FALSE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]] <<- TRUE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]] <<- NA } } } parametric_modal_prev_buttonDelta <<- input$advancedSettingsButtonApplyDelta parametric_modal_prev_buttonAllDelta <<- input$advancedSettingsButtonApplyAllDelta }) observe({ shinyjs::toggle(id="parametric_modal_body", condition = nrow(parametric_seriesToChangePoint$table)!=0) shinyjs::toggle(id="parametric_modal_errorMessage", condition = nrow(parametric_seriesToChangePoint$table)==0) }) output$parametric_modal_series <- renderUI({ if (nrow(parametric_seriesToChangePoint$table)!=0) selectInput(inputId = "parametric_modal_series", label = "Series", choices = rownames(parametric_seriesToChangePoint$table)) }) output$parametric_modal_delta <- renderUI({ if (!is.null(input$parametric_modal_series)) return (numericInput("parametric_modal_delta", label = paste("delta", input$parametric_modal_series), value = yuimaGUIsettings$delta[[input$parametric_modal_series]])) }) output$parametric_modal_toLog <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)){ choices <- FALSE if (all(getData(input$parametric_modal_series)>0)) choices <- c(FALSE, TRUE) return (selectInput("parametric_modal_toLog", label = "Convert to log", choices = choices, selected = yuimaGUIsettings$toLog[[input$parametric_modal_series]])) } }) output$parametric_modal_model <- renderUI({ if(!is.null(input$parametric_changepoint_model)) selectInput(inputId = "parametric_modal_model", label = "Model", choices = input$parametric_changepoint_model) }) output$parametric_modal_parameter <- renderUI({ if (!is.null(input$parametric_modal_model)){ mod <- setModelByName(input$parametric_modal_model, jumps = NA, AR_C = NA, MA_C = NA) par <- getAllParams(mod, 'Diffusion process') selectInput(inputId = "parametric_modal_parameter", label = "Parameter", choices = par) } }) output$parametric_modal_start <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) numericInput(inputId = "parametric_modal_start", label = "start", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["start"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_startMin <- renderUI({ input$parametric_modal_button_applyDelta input$parametric_modal_button_applyAllDelta if (!is.null(input$parametric_modal_start) & !is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (is.na(input$parametric_modal_start)) numericInput(inputId = "parametric_modal_startMin", label = "start: Min", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMin"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_startMax <- renderUI({ input$parametric_modal_button_applyDelta input$parametric_modal_button_applyAllDelta if (!is.null(input$parametric_modal_start) & !is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (is.na(input$parametric_modal_start)) numericInput(inputId = "parametric_modal_startMax", label = "start: Max", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMax"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_lower <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (input$parametric_modal_method=="L-BFGS-B" | input$parametric_modal_method=="Brent") numericInput("parametric_modal_lower", label = "lower", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["lower"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_upper <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (input$parametric_modal_method=="L-BFGS-B" | input$parametric_modal_method=="Brent") numericInput("parametric_modal_upper", label = "upper", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["upper"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_method <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)) selectInput("parametric_modal_method", label = "method", choices = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", "Brent"), selected = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]]) }) output$parametric_modal_trials <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_method)) numericInput("parametric_modal_trials", label = "trials", min = 1, value = ifelse(input$parametric_modal_method=="SANN" & yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]]!="SANN",1,yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["trials"]])) }) output$parametric_modal_seed <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)) numericInput("parametric_modal_seed", label = "seed", min = 1, value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["seed"]]) }) observeEvent(input$parametric_modal_button_applyDelta, { yuimaGUIsettings$delta[[input$parametric_modal_series]] <<- input$parametric_modal_delta yuimaGUIsettings$toLog[[input$parametric_modal_series]] <<- input$parametric_modal_toLog }) observeEvent(input$parametric_modal_button_applyAllDelta, { for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$delta[[symb]] <<- input$parametric_modal_delta if (input$parametric_modal_toLog==FALSE) yuimaGUIsettings$toLog[[symb]] <<- input$parametric_modal_toLog else if (all(getData(symb)>0)) yuimaGUIsettings$toLog[[symb]] <<- input$parametric_modal_toLog } }) observeEvent(input$parametric_modal_button_applyModel,{ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["start"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_start yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMin"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMin yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMax"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMax yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["lower"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_lower yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["upper"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_upper }) observeEvent(input$parametric_modal_button_applyAllModel,{ for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["start"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_start yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["startMin"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMin yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["startMax"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMax yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["lower"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_lower yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["upper"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_upper } }) observeEvent(input$parametric_modal_button_applyGeneral,{ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]] <<- input$parametric_modal_method yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["trials"]] <<- input$parametric_modal_trials yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["seed"]] <<- input$parametric_modal_seed }) observeEvent(input$parametric_modal_button_applyAllModelGeneral,{ for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["method"]] <<- input$parametric_modal_method yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["trials"]] <<- input$parametric_modal_trials yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["seed"]] <<- input$parametric_modal_seed } }) output$parametric_changepoint_symb <- renderUI({ n <- names(yuimaGUIdata$cpYuima) if(length(n)!=0) selectInput("parametric_changepoint_symb", "Symbol", choices = sort(n), selected = last(n)) }) observeEvent(input$parametric_changepoint_button_startEstimation, { if (length(rownames(parametric_seriesToChangePoint$table))!=0) closeAlert(session = session, alertId = "parametric_changepoint_alert_err") withProgress(message = 'Analyzing: ', value = 0, { errors <- c() for (symb in rownames(parametric_seriesToChangePoint$table)){ incProgress(1/length(rownames(parametric_seriesToChangePoint$table)), detail = symb) test <- try(addCPoint(modelName = input$parametric_changepoint_model, symb = symb, fracL = input$parametric_modal_rangeFraction[1]/100, fracR = input$parametric_modal_rangeFraction[2]/100, from = as.character(parametric_seriesToChangePoint$table[symb, "From"]), to = as.character(parametric_seriesToChangePoint$table[symb, "To"]), delta = yuimaGUIsettings$delta[[symb]], toLog = yuimaGUIsettings$toLog[[symb]], start = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["start"]], startMin = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["startMin"]], startMax = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["startMax"]], method = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["method"]], trials = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["trials"]], seed = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["seed"]], lower = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["lower"]], upper = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["upper"]])) if(class(test)=="try-error") errors <- c(errors, symb) } if (!is.null(errors)) createAlert(session = session, anchorId = "parametric_changepoint_alert", alertId = "parametric_changepoint_alert_err", style = "error", dismiss = TRUE, content = paste("Unable to estimate Change Point of:", paste(errors, collapse = " "))) }) }) parametric_range_changePoint <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$parametric_changePoint_brush) & !is.null(input$parametric_changepoint_symb)){ data <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$series test <- (length(index(window(data, start = input$parametric_changePoint_brush$xmin, end = input$parametric_changePoint_brush$xmax))) > 3) if (test==TRUE){ parametric_range_changePoint$x <- c(as.Date(input$parametric_changePoint_brush$xmin), as.Date(input$parametric_changePoint_brush$xmax)) parametric_range_changePoint$y <- c(input$parametric_changePoint_brush$ymin, input$parametric_changePoint_brush$ymax) } } }) observeEvent(input$parametric_changePoint_dbclick,{ parametric_range_changePoint$x <- c(NULL, NULL) }) observeEvent(input$parametric_changepoint_symb, { parametric_range_changePoint$x <- c(NULL, NULL) output$parametric_changepoint_plot_series <- renderPlot({ if(!is.null(input$parametric_changepoint_symb)) { cp <- isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]}) data <- cp$series toLog <- cp$info$toLog symb <- cp$info$symb par(bg="black") plot(window(data, start = parametric_range_changePoint$x[1], end = parametric_range_changePoint$x[2]), main=ifelse(toLog==TRUE, paste("log(",symb,")", sep = ""), symb), xlab="Index", ylab=NA, log=switch(input$parametric_changepoint_scale,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") abline(v=cp$tau, col = "red") grid(col="grey") } }) }) output$parametric_changepoint_info <- renderUI({ if(!is.null(input$parametric_changepoint_symb)){ info <- isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$info}) div( h3(info$model), withMathJax(printModelLatex(names = info$model, process = "Diffusion process")), br(), h4( em(paste("Change Point:", as.character(isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$tau})))) ), align="center" ) } }) output$parametric_changepoint_modal_info_text <- renderUI({ info <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$info div( h3(input$parametric_changepoint_symb, " - " , info$model, class = "hModal"), h4( em("series to log:"), info$toLog, br(), em("method:"), info$method, br(), em("trials:"), info$trials, br(), em("seed:"), info$seed, br(), class = "hModal" ), align="center") }) output$parametric_changepoint_modal_info_tableL <- renderTable(rownames = T, { cp <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] tL <- summary(cp$qmleL)@coef for (i in 1:nrow(tL)){ tL[i,"Estimate"] <- signifDigits(value = tL[i,"Estimate"], sd = tL[i,"Std. Error"]) tL[i,"Std. Error"] <- signifDigits(value = tL[i,"Std. Error"], sd = tL[i,"Std. Error"]) } return(tL) }) output$parametric_changepoint_modal_info_tableR <- renderTable(rownames = T, { cp <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] tR <- summary(cp$qmleR)@coef for (i in 1:nrow(tR)){ tR[i,"Estimate"] <- signifDigits(value = tR[i,"Estimate"], sd = tR[i,"Std. Error"]) tR[i,"Std. Error"] <- signifDigits(value = tR[i,"Std. Error"], sd = tR[i,"Std. Error"]) } return(tR) }) observeEvent(input$parametric_changepoint_button_delete_estimated, { yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] <<- NULL }) observeEvent(input$parametric_changepoint_button_deleteAll_estimated, { yuimaGUIdata$cpYuima <<- list() })
library(tinytest) library(ggiraph) library(ggplot2) library(xml2) source("setup.R") { eval(test_scale, envir = list(name = "scale_size_interactive")) eval(test_scale, envir = list(name = "scale_size_area_interactive")) eval(test_scale, envir = list(name = "scale_size_continuous_interactive")) eval(test_scale, envir = list(name = "scale_size_discrete_interactive")) eval(test_scale, envir = list(name = "scale_size_binned_interactive")) eval(test_scale, envir = list(name = "scale_size_binned_area_interactive")) eval(test_scale, envir = list(name = "scale_size_date_interactive")) eval(test_scale, envir = list(name = "scale_size_datetime_interactive")) eval(test_scale, envir = list(name = "scale_size_ordinal_interactive")) eval(test_scale, envir = list(name = "scale_radius_interactive")) }
.nomValues<-function(indivN,i,k){ indivN_t1<-indivN[indivN[,"indiv"]==i ,] indivN1<-indivN_t1[indivN_t1[,"variable"]==k ,] as.matrix(indivN1) } .p<-function(list,l){ resul<-0 if(sum(list[,"value"]==l)!=0){ if(any(dimnames(list)[[2]]=="frequency")){ resul<-list[list[,"value"]==l,]["frequency"] } else{ resul<-1/nrow(list) } } resul } .pp<-function(list,indivN,k,l){ resul<-0 if(sum(list[,"value"]==l)!=0){ indivN1<-indivN[indivN[,"variable"]==k ,] resul<-1/sum(indivN1[,"value"]==l) } resul } .gsum<-function(table.Symbolic,i,j,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables gsum=0 if(is.null(k))stop("wrong k null") if(length(k)!=1)stop(paste("wrong k",k)) if(variables[k,"type"]=="IC"){ gsum<-max(indivIC[i,k,2],indivIC[j,k,2])-min(indivIC[i,k,1],indivIC[j,k,1]) } if (variables[k,"type"]=="N" || variables[k,"type"]=="MN"){ indivN_t1<-indivN[indivN[,"indiv"]==i ,] indivN_t2<-indivN[indivN[,"indiv"]==j ,] indivN1<-indivN_t1[indivN_t1[,"variable"]==k ,] indivN2<-indivN_t2[indivN_t2[,"variable"]==k ,] gsum<-nrow(indivN1)+nrow(indivN2)-.gprod(table.Symbolic,i,j,k) } gsum } .gprod<-function(table.Symbolic,i,j,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables gprod=0 if(is.null(k))stop("wrong k null") if(length(k)!=1)stop(paste("wrong k",k)) if(variables[k,"type"]=="IC"){ if(indivIC[i,k,1]>=indivIC[j,k,2] || indivIC[i,k,2]<=indivIC[j,k,1]){ gprod<-0 } else{ if (indivIC[i, k, 1] <= indivIC[j, k, 1]) { if (indivIC[i, k, 2] <= indivIC[j, k, 2]) gprod <- abs(indivIC[i, k, 2] - indivIC[j, k, 1]) else gprod <- abs(indivIC[j, k, 2] - indivIC[j, k, 1]) } else { if (indivIC[j, k, 2] <= indivIC[i, k, 2]) gprod <- abs(indivIC[j, k, 2] - indivIC[i, k, 1]) else gprod <- abs(indivIC[i, k, 2] - indivIC[i, k, 1]) } } } if (variables[k,"type"]=="N" || variables[k,"type"]=="MN"){ gprod<-0 indivN_t1<-indivN[indivN[,"indiv"]==i ,] indivN_t2<-indivN[indivN[,"indiv"]==j ,] indivN1<-indivN_t1[indivN_t1[,"variable"]==k ,] indivN2<-indivN_t2[indivN_t2[,"variable"]==k ,] if (!is.null(indivN1[,"value"]) && !is.null(indivN1[,"value"])) { for (z in 1:(nrow(indivN1))) { if ( sum(indivN2[,"value"]==indivN1[z,"value"])!=0) { gprod<-gprod+1 } } } } gprod } .gabs<-function(table.Symbolic,i,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables gabs<-0 if(is.null(k))stop("wrong k null") if(length(k)!=1)stop(paste("wrong k",k)) if(variables[k,"type"]=="IC"){ gabs<-abs(indivIC[i,k,2]-indivIC[i,k,1]) } if (variables[k,"type"]=="N" || variables[k,"type"]=="MN"){ indivN_t1<-indivN[indivN[,"indiv"]==i ,] indivN1<-indivN_t1[indivN_t1[,"variable"]==k ,] gabs<-nrow(indivN1) } gabs } .gdomainLength<-function(table.Symbolic,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables if(is.null(k))stop("wrong k null") if(length(k)!=1)stop(paste("wrong k",k)) if(variables[k,"type"]=="IC"){ gdomainLength<-abs(max(indivIC[,k,1])-min(indivIC[,k,1])) } if (variables[k,"type"]=="N"){ gdomainLength<-length(unique(indivN[indivN[,"variable"]==k,])) } if (variables[k,"type"]=="MN"){ gdomainLength<-length(unique(indivN[indivN[,"variable"]==k,])) } gdomainLength } .dpobject<-function(table.Symbolic,i,variableSelection){ dp<-1 for(k in variableSelection){ dp<-dp*.gabs(table.Symbolic,i,k) } dp } .dpsum<-function(table.Symbolic,i,j,variableSelection){ dp<-1 for(k in variableSelection){ dp<-dp*.gsum(table.Symbolic,i,j,k) } dp } .dpprod<-function(table.Symbolic,i,j,variableSelection){ dp<-1 for(k in variableSelection){ dp<-dp*.gprod(table.Symbolic,i,j,k) } dp } .dpmax<-function(table.Symbolic,variableSelection){ dpobjects<-NULL for(i in 1:length(table.Symbolic$individuals)){ dpobjects<-c(dpobjects,.dpobject(table.Symbolic,i,variableSelection)) } max(dpobjects) } .C1alpha<-function(table.Symbolic,i,j,k){ .gprod(table.Symbolic,i,j,k) } .C1beta<-function(table.Symbolic,i,j,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables if(table.Symbolic$variables[k,"type"]=="N" || table.Symbolic$variables[k,"type"]=="MN"){ beta<-.gsum(table.Symbolic,i,j,k)-.gabs(table.Symbolic,j,k) } if(table.Symbolic$variables[k,"type"]=="IC"){ if (indivIC[i,k,1]<=indivIC[j,k,1]) { if (indivIC[i,k,2]<=indivIC[j,k,2]) beta<-abs(indivIC[i,k,1]-indivIC[j,k,1]) else beta<-abs(indivIC[j,k,2]-indivIC[j,k,2])+abs(indivIC[i,k,2]-indivIC[i,k,2]) } else { if (indivIC[j,k,2]<=indivIC[i,k,2]) beta<-abs(indivIC[i,k,2]-indivIC[j,k,2]) else beta<-0 } } beta } .C1gamma<-function(table.Symbolic,i,j,k){ indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN variables<-table.Symbolic$variables if(table.Symbolic$variables[k,"type"]=="N" || table.Symbolic$variables[k,"type"]=="MN"){ gamma<-.gsum(table.Symbolic,i,j,k)-.gabs(table.Symbolic,j,k) } if(table.Symbolic$variables[k,"type"]=="IC"){ if (indivIC[j,k,1]<=indivIC[j,k,1]) { if (indivIC[j,k,2]<=indivIC[i,k,2]) gamma<-abs(indivIC[i,k,1]-indivIC[j,k,1]) else gamma<-abs(indivIC[j,k,2]-indivIC[j,k,2])+abs(indivIC[i,k,2]-indivIC[i,k,2]) } else { if (indivIC[i,k,2]<=indivIC[j,k,2]) gamma<-abs(indivIC[i,k,2]-indivIC[j,k,2]) else gamma<-0 } } gamma } .probDist<-function(indivNM,i,j,k,probType,s,p){ resul<-0 list1<-.nomValues(indivNM,i,k) list2<-.nomValues(indivNM,j,k) if(probType=="J"){ for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ if(.p(list1,l)!=0 && .p(list2,l)!=0){ resul<-resul+(.p(list2,l)*log(.p(list2,l)/.p(list1,l))+.p(list1,l)*log(.p(list1,l)/.p(list2,l)))/2 } } } if(probType=="CHI"){ for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ if(.p(list1,l)!=0){ resul<-resul+(.p(list1,l)-.p(list2,l))^2/.p(list1,l) } } } if(probType=="CHER"){ for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ resul<-resul+(.p(list1,l)^(1-s)*.p(list2,l)^s) } resul<--log(resul) } if(probType=="REN"){ for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ resul<-resul+(.p(list1,l)^(1-s)*.p(list2,l)^s) } resul<--log(resul)/(s-1) } if(probType=="LP"){ for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ resul<-resul+abs(.p(list1,l)-.p(list2,l))^p } resul<-resul^(1/p) } resul } dist_SDA<-function(table.Symbolic,type="U_2",subType=NULL,gamma=0.5,power=2,probType="J",probAggregation="P_1",s=0.5,p=2,variableSelection=NULL,weights=NULL){ if(type=="H"){ return (dist.Symbolic(SO2Simple(table.Symbolic),type="H",power=power)); } types<-c(paste("U",2:4,sep="_"),"C_1",paste("SO",1:5,sep="_"),"H","L_1","L_2") subTypes<-c(paste("D",1:5,sep="_")) probTypes=c("J","CHI2","REN","CHER","LP") if(sum(types==type)==0){ stop(paste("Dissimilarity type should be one of the following:",paste(types,collapse=","))) } if(!is.null(subType) && sum(subTypes==subType)==0){ stop(paste("Dissimilarity subType for(C_1) and (SO_1) distance should be one of the following:",paste(subTypes,collapse=","))) } if(is.null(subType) && (type=="C_1" || type=="SO_1")){ stop(paste("Dissimilarity subType for(C_1) and (SO_1) distance should be one of the following:",paste(subTypes,collapse=",")," but not null")) } if(sum(types==type)==0){ stop(paste("Dissimilarity type should be one of the following:",paste(types,collapse=","))) } if (!.is.symbolic(table.Symbolic)) stop ("Cannot count dissimilarity measures on non-symbolic data") indivIC<-table.Symbolic$indivIC indivN<-table.Symbolic$indivN indivNM<-table.Symbolic$indivNM variables<-table.Symbolic$variables individuals<-table.Symbolic$individuals individualsNo<-nrow(individuals) variablesNo<-nrow(variables) if(is.null(weights)) weights<-rep(1,nrow(variables)) if(length(weights)==1) weights<-rep(weights,nrow(variables)) if(length(weights)!=nrow(variables)){ stop ("Weights vector should have the same length as the number of variables") } if (is.null(variableSelection)) variableSelection=(1:variablesNo) distS<-array(0,c(individualsNo,individualsNo)) for (i in 1:(individualsNo-1)) for (j in (i+1):individualsNo){ if(type=="U_2"){ D<-0 for(k in variableSelection){ d<-.gsum(table.Symbolic,i,j,k)-.gprod(table.Symbolic,i,j,k)+gamma*(2*.gprod(table.Symbolic,i,j,k)-.gabs(table.Symbolic,i,k)-.gabs(table.Symbolic,j,k)) D<-D+d^power if(variables[k,"type"]=="NM"){ D<-D+.probDist(indivNM,i,j,k,probType,s,p)^power } } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="U_3"){ D<-0 for(k in variableSelection){ d<-.gsum(table.Symbolic,i,j,k)-.gprod(table.Symbolic,i,j,k)+gamma*(2*.gprod(table.Symbolic,i,j,k)-.gabs(table.Symbolic,i,k)-.gabs(table.Symbolic,j,k)) d<-d/.gdomainLength(table.Symbolic,k) D<-D+d^power if(variables[k,"type"]=="NM"){ D<-D+.probDist(indivNM,i,j,k,probType,s,p)^power } } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="U_4"){ D<-0 for(k in variableSelection){ print(paste("k=",k)) d<-.gsum(table.Symbolic,i,j,k)-.gprod(table.Symbolic,i,j,k)+gamma*(2*.gprod(table.Symbolic,i,j,k)-.gabs(table.Symbolic,i,k)-.gabs(table.Symbolic,j,k)) d<-d/.gdomainLength(table.Symbolic,i) D<-D+weights[k]*d^power if(variables[k,"type"]=="NM"){ D<-D+weights[k]*.probDist(indivNM,i,j,k,probType,s,p)^power } } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="C_1"){ D<-0 for(k in variableSelection){ alpha=.C1alpha(table.Symbolic,i,j,k) beta=.C1gamma(table.Symbolic,i,j,k) gamma=.C1gamma(table.Symbolic,i,j,k) if(subType=="D_1"){ d<-alpha/(alpha+beta+gamma) } if(subType=="D_2"){ d<-2*alpha/(2*alpha+beta+gamma) } if(subType=="D_3"){ d<-alpha/(alpha+2*beta+2*gamma) } if(subType=="D_4"){ d<-alpha/(2*alpha+2*beta)+alpha(2*alpha+2*gamma) } if(subType=="D_5"){ d<-alpha/(sqrt(alpha+beta)*sqrt(alpha+gamma)) } if(!is.nan(d)) D<-D+(d^power)/length(variables) } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="SO_1"){ D<-0 for(k in variableSelection){ alpha=as.numeric(.C1alpha(table.Symbolic,i,j,k)) bbeta=as.numeric(.C1beta(table.Symbolic,i,j,k)) gamma=as.numeric(.C1gamma(table.Symbolic,i,j,k)) if(subType=="D_1"){ d<-alpha/(alpha+bbeta+gamma) } if(subType=="D_2"){ d<-2*alpha/(2*alpha+bbeta+gamma) } if(subType=="D_3"){ d<-alpha/(alpha+2*bbeta+2*gamma) } if(subType=="D_4"){ d<-alpha/(2*alpha+2*bbeta)+alpha(2*alpha+2*gamma) } if(subType=="D_5"){ d<-alpha/(sqrt(alpha+bbeta)*sqrt(alpha+gamma)) } if(!is.nan(d)) D<-D+weights[k]*(d^power) } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="SO_2"){ D<-0 for(k in variableSelection){ d<-.gsum(table.Symbolic,i,j,k)-.gprod(table.Symbolic,i,j,k)+gamma*(2*.gprod(table.Symbolic,i,j,k)-.gabs(table.Symbolic,i,k)-.gabs(table.Symbolic,j,k)) d<-d/.gsum(table.Symbolic,i,j,k) D<-D+(d^power)/length(variables) } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } if(type=="SO_3"){ D<-0 for(k in variableSelection){ d<-.dpsum(table.Symbolic,i,j,variableSelection)-.dpprod(table.Symbolic,i,j,variableSelection)+gamma*(2*.dpprod(table.Symbolic,i,j,variableSelection)-.dpobject(table.Symbolic,i,variableSelection)-.dpobject(table.Symbolic,j,variableSelection)) D<-d } distS[i,j]<-D distS[j,i]<-distS[i,j] } if(type=="SO_4"){ D<-0 for(k in variableSelection){ d<-.dpsum(table.Symbolic,i,j,variableSelection)-.dpprod(table.Symbolic,i,j,variableSelection)+gamma*(2*.dpprod(table.Symbolic,i,j,variableSelection)-.dpobject(table.Symbolic,i,variableSelection)-.dpobject(table.Symbolic,j,variableSelection)) D<-d/.dpmax(table.Symbolic,k) } distS[i,j]<-D/.dpmax(table.Symbolic,variableSelection) distS[j,i]<-distS[i,j] } if(type=="SO_5"){ D<-0 for(k in variableSelection){ d<-.dpsum(table.Symbolic,i,j,variableSelection)-.dpprod(table.Symbolic,i,j,variableSelection)+gamma*(2*.dpprod(table.Symbolic,i,j,variableSelection)-.dpobject(table.Symbolic,i,variableSelection)-.dpobject(table.Symbolic,j,variableSelection)) D<-d/.dpsum(table.Symbolic,i,j,variableSelection) } distS[i,j]<-D distS[j,i]<-distS[i,j] } if(type=="L_1" || type=="L_2"){ if(type=="L_1"){ L_i<-1 } else{ L_i<-2 } D<-0 for(k in variableSelection){ if(variables[k,"type"]=="IC"){ D<-D+abs(indivIC[i,k,1]-indivIC[j,k,1])^2++(indivIC[i,k,2]-indivIC[j,k,2])^L_i } if(variables[k,"type"]=="MN" || variables[k,"type"]=="N" || variables[k,"type"]=="NM"){ if(variables[k,"type"]=="NM"){ list1<-.nomValues(indivNM,i,k) list2<-.nomValues(indivNM,j,k) } else{ list1<-.nomValues(indivN,i,k) list2<-.nomValues(indivN,j,k) } for(l in 1:max(c(list1[,"value"],list2[,"value"]))){ if(variables[k,"type"]=="NM"){ D<-D+abs(.p(list1,l)-.p(list2,l))^L_i } else{ D<-D+abs(.pp(list1,indivN,k,l)-.pp(list2,indivN,k,l))^L_i } } } } distS[i,j]<-D^(1/power) distS[j,i]<-distS[i,j] } } as.dist(distS) }
dapimask<-function(img, size=NULL, voxelsize=NULL, thresh="auto", silent=TRUE, cores=1) { if (is.null(size)&is.null(voxelsize)){stop("Either size or voxelsize is required")} if (length(dim(img))==3) { mb<-apply(img,3,mean) mbr<-0.8*quantile(mb,0.01)+0.2*quantile(mb,0.99) mbr<-which(mbr<mb) small<-min(mbr):max(mbr) dims0<-dim(img) blau<-img[,,small] dims<-dim(blau) } else { blau=img dims<-dim(blau) } blau<-blau-median(blau) blau[blau<0]<-0 blau<-array(blau,dims) blau<-blau/max(blau) blau<-bioimagetools::filterImage3d(blau,"var",4,1/3,silent=silent) if(is.null(voxelsize))voxelsize<-size/dim(img) xymic<-mean(voxelsize[1:2]) brush<-EBImage::makeBrush(25,shape="gaussian",sigma=.1/xymic) blau2<-EBImage::filter2(blau,brush) xx<-apply(blau2,1,mean) yy<-apply(blau2,2,mean) temp<-list("a"=xx,"b"=rev(xx),"c"=yy,"d"=rev(yy)) if(thresh=="auto"){ if(cores>1){thresh<-unlist(parallel::mclapply(temp,find.first.mode,mc.cores=4))}else{thresh<-unlist(lapply(temp,find.first.mode))} thresh=median(thresh, na.rm=TRUE) } b<-blau>median(thresh/2) if (length(dim(img))==3) { b2<-array(0,dims0) b2[,,small]<-array(as.integer(b),dim(b)) } else { b2=b } n<-5 mask<-1-bioimagetools::outside(b2,0,n) brush<-makeBrush(2*n-1,shape='box') mask<-erode(mask,brush) if (length(dim(img))==3) { mask0<-bioimagetools::bwlabel3d(mask) mask1<-bioimagetools::cmoments3d(mask0,mask) which<-rev(order(mask1[,5]))[1] } else { mask0<-EBImage::bwlabel(mask) mask1<-EBImage::computeFeatures(mask0[,,1,1],mask[,,1,1],methods.ref="computeFeatures.basic") which<-rev(order(mask1[,6]))[1] } mask<-ifelse(mask0==which,1,0) mask<-EBImage::fillHull(mask) return(mask) } find.first.mode<-function(x) { s<-stats::sd(diff(x)) i<-1 go<-TRUE try({ while(go) { i<-i+1 if(x[i]-x[i-1]<(-1.96*s))go<-FALSE } },silent=TRUE) return(x[i-1]) }
densityHeatmap = function(data, density_param = list(na.rm = TRUE), col = rev(brewer.pal(11, "Spectral")), color_space = "LAB", ylab = deparse(substitute(data)), column_title = paste0("Density heatmap of ", deparse(substitute(data))), title = column_title, ylim = NULL, range = ylim, title_gp = gpar(fontsize = 14), ylab_gp = gpar(fontsize = 12), tick_label_gp = gpar(fontsize = 10), quantile_gp = gpar(fontsize = 10), show_quantiles = TRUE, column_order = NULL, column_names_side = "bottom", show_column_names = TRUE, column_names_max_height = unit(6, "cm"), column_names_gp = gpar(fontsize = 12), column_names_rot = 90, cluster_columns = FALSE, clustering_distance_columns = "ks", clustering_method_columns = "complete", mc.cores = 1, cores = mc.cores, ...) { arg_list = list(...) if(length(arg_list)) { if(any(c("row_km", "row_split", "split", "km") %in% names(arg_list))) { stop_wrap("density heatmaps do not allow row splitting.") } if(any(grepl("row", names(arg_list)))) { stop_wrap("density heatmaps do not allow to set rows.") } if("anno" %in% names(arg_list)) { stop_wrap("`anno` is removed from the argument. Please directly construct a `HeatmapAnnotation` object and set to `top_annotation` or `bottom_annotation`.") } } ylab = ylab column_title = column_title density_param$na.rm = TRUE if(!is.matrix(data) && !is.data.frame(data) && !is.list(data)) { stop_wrap("only matrix and list are allowed.") } if(is.matrix(data)) { data2 = as.list(as.data.frame(data)) names(data2) = colnames(data) data = data2 } density_list = lapply(data, function(x) do.call(density, c(list(x = x), density_param))) quantile_list = sapply(data, quantile, na.rm = TRUE) mean_value = sapply(data, mean, na.rm = TRUE) n = length(density_list) nm = names(density_list) max_x = quantile(unlist(lapply(density_list, function(x) x$x)), 0.99) min_x = quantile(unlist(lapply(density_list, function(x) x$x)), 0.01) if(!is.null(range)) { max_x = range[2] min_x = range[1] } x = seq(min_x, max_x, length.out = 500) mat = lapply(density_list, function(r) { f = approxfun(r$x, r$y) res = f(x) res[is.na(res)] = 0 rev(res) }) mat = as.matrix(as.data.frame(mat)) colnames(mat) = nm if(cluster_columns) { if(clustering_distance_columns == "ks") { d = ks_dist(mat, cores = cores) dend = as.dendrogram(hclust(d, clustering_method_columns)) dend = reorder(dend, colMeans(mat)) cluster_columns = dend } } if(inherits(col, "function")) { col = col(mat) } else { col = colorRamp2(seq(0, quantile(mat, 0.99, na.rm = TRUE), length.out = length(col)), col, space = color_space) } bb = grid.pretty(c(min_x, max_x)) ht = Heatmap(mat, col = col, name = "density", column_title = title, column_title_gp = title_gp, cluster_rows = FALSE, cluster_columns = cluster_columns, clustering_distance_columns = clustering_distance_columns, clustering_method_columns = clustering_method_columns, column_dend_reorder = mean_value, column_names_side = column_names_side, show_column_names = show_column_names, column_names_max_height = column_names_max_height, column_names_gp = column_names_gp, column_names_rot = column_names_rot, column_order = column_order, left_annotation = rowAnnotation(axis = anno_empty(border = FALSE, width = grobHeight(textGrob(ylab, gp = ylab_gp))*2 + max_text_width(bb, gp = tick_label_gp) + unit(4, "mm")), show_annotation_name = FALSE), right_annotation = {if(show_quantiles) {rowAnnotation(quantile = anno_empty(border = FALSE, width = grobWidth(textGrob("100%", gp = quantile_gp)) + unit(6, "mm")), show_annotation_name = FALSE)} else NULL}, ... ) random_str = paste(sample(c(letters, LETTERS, 0:9), 8), collapse = "") ht@name = paste0(ht@name, "_", random_str) names(ht@left_annotation) = paste0(names(ht@left_annotation), "_", random_str) if(show_quantiles) { names(ht@right_annotation) = paste0(names(ht@right_annotation), "_", random_str) } post_fun = function(ht) { column_order = column_order(ht) if(!is.list(column_order)) { column_order = list(column_order) } n_slice = length(column_order) decorate_annotation(paste0("axis_", random_str), { grid.text(ylab, x = grobHeight(textGrob(ylab, gp = ylab_gp)), rot = 90) }, slice = 1) if(!is.null(ht@right_annotation)) { for(i_slice in 1:n_slice) { decorate_heatmap_body(paste0("density_", random_str), { n = length(column_order[[i_slice]]) pushViewport(viewport(xscale = c(0.5, n + 0.5), yscale = c(min_x, max_x), clip = TRUE)) for(i in seq_len(5)) { grid.lines(1:n, quantile_list[i, column_order[[i_slice]] ], default.units = "native", gp = gpar(lty = 2)) } grid.lines(1:n, mean_value[ column_order[[i_slice]] ], default.units = "native", gp = gpar(lty = 2, col = "darkred")) upViewport() }, column_slice = i_slice) } } decorate_heatmap_body(paste0("density_", random_str), { pushViewport(viewport(yscale = c(min_x, max_x), clip = FALSE)) grid.rect(gp = gpar(fill = NA)) grid.yaxis(gp = tick_label_gp) upViewport() }, column_slice = 1) if(!is.null(ht@right_annotation)) { decorate_heatmap_body(paste0("density_", random_str), { n = length(column_order[[n_slice]]) lq = !apply(quantile_list, 1, function(x) all(x > max_x) || all(x < min_x)) lq = c(lq, !(all(mean_value > max_x) || all(mean_value < min_x))) if(sum(lq) == 0) { return(NULL) } labels = c(rownames(quantile_list), "mean") y = c(quantile_list[, column_order[[n_slice]][n] ], mean_value[ column_order[[n_slice]][n] ]) labels = labels[lq] y = y[lq] od = order(y) y = y[od] labels = labels[od] pushViewport(viewport(xscale = c(0.5, n + 0.5), yscale = c(min_x, max_x), clip = FALSE)) text_height = convertHeight(grobHeight(textGrob(labels[1])) * 2, "native", valueOnly = TRUE) h1 = y - text_height*0.5 h2 = y + text_height*0.5 pos = rev(smartAlign(h1, h2, c(min_x, max_x))) h = (pos[, 1] + pos[, 2])/2 link_width = unit(6, "mm") n2 = length(labels) grid.text(labels, unit(1, "npc") + rep(link_width, n2), h, default.units = "native", just = "left", gp = quantile_gp) link_width = link_width - unit(1, "mm") ly = y <= max_x & y >= min_x if(sum(ly)) { grid.segments(unit(rep(1, n2), "npc")[ly], y[ly], unit(1, "npc") + rep(link_width * (1/3), n2)[ly], y[ly], default.units = "native") grid.segments(unit(1, "npc") + rep(link_width * (1/3), n2)[ly], y[ly], unit(1, "npc") + rep(link_width * (2/3), n2)[ly], h[ly], default.units = "native") grid.segments(unit(1, "npc") + rep(link_width * (2/3), n2)[ly], h[ly], unit(1, "npc") + rep(link_width, n2)[ly], h[ly], default.units = "native") } upViewport() }, column_slice = n_slice) } } ht@heatmap_param$post_fun = post_fun ht_list = ht return(ht_list) } ks_dist_pair = function(x, y) { n <- length(x) n.x <- as.double(n) n.y <- length(y) n <- n.x * n.y/(n.x + n.y) w <- c(x, y) z <- cumsum(ifelse(order(w) <= n.x, 1/n.x, -1/n.y)) max(abs(z)) } ks_dist = function(data, cores = 1) { has_names = TRUE if(is.matrix(data)) { has_names = !is.null(colnames(data)) data = as.data.frame(data) } nc = length(data) ind_mat = expand.grid(seq_len(nc), seq_len(nc)) ind_mat = ind_mat[ ind_mat[, 1] > ind_mat[, 2], , drop = FALSE] registerDoParallel(cores) v <- foreach (ind = seq_len(nrow(ind_mat))) %dopar% { i = ind_mat[ind, 1] j = ind_mat[ind, 2] suppressWarnings(d <- ks_dist_pair(data[[i]], data[[j]])) return(d) } stopImplicitCluster() v = unlist(v) i = ind_mat[, 1] j = ind_mat[, 2] ind = (j - 1) * nc + i d = matrix(0, nrow = nc, ncol = nc) if(has_names) rownames(d) = colnames(d) = names(data) d[ind] = v as.dist(d) } ks_dist_1 = function(data) { has_names = TRUE if(is.matrix(data)) { has_names = !is.null(colnames(data)) data = as.data.frame(data) } nc = length(data) d = matrix(NA, nrow = nc, ncol = nc) if(has_names) rownames(d) = colnames(d) = names(data) for(i in 2:nc) { for(j in 1:(nc-1)) { suppressWarnings(d[i, j] <- ks_dist_pair(data[[i]], data[[j]])) } } as.dist(d) } frequencyHeatmap = function(data, breaks = "Sturges", stat = c("count", "density", "proportion"), col = brewer.pal(9, "Blues"), color_space = "LAB", ylab = deparse(substitute(data)), column_title = paste0("Frequency heatmap of ", deparse(substitute(data))), title = column_title, ylim = NULL, range = ylim, title_gp = gpar(fontsize = 14), ylab_gp = gpar(fontsize = 12), tick_label_gp = gpar(fontsize = 10), column_order = NULL, column_names_side = "bottom", show_column_names = TRUE, column_names_max_height = unit(6, "cm"), column_names_gp = gpar(fontsize = 12), column_names_rot = 90, cluster_columns = FALSE, use_3d = FALSE, ...) { arg_list = list(...) if(length(arg_list)) { if(any(c("row_km", "row_split", "split", "km") %in% names(arg_list))) { stop_wrap("frequency heatmaps do not allow row splitting.") } if(any(grepl("row", names(arg_list)))) { stop_wrap("frequency heatmaps do not allow to set rows.") } if("anno" %in% names(arg_list)) { stop_wrap("`anno` is removed from the argument. Please directly construct a `HeatmapAnnotation` object and set to `top_annotation` or `bottom_annotation`.") } } ylab = ylab column_title = column_title if(!is.matrix(data) && !is.data.frame(data) && !is.list(data)) { stop_wrap("only matrix and list are allowed.") } if(is.matrix(data)) { data2 = as.list(as.data.frame(data)) names(data2) = colnames(data) data = data2 } h = hist(unlist(data), breaks = breaks, plot = FALSE) breaks = h$breaks min_x = min(breaks) max_x = max(breaks) freq_list = lapply(data, function(x) hist(x, plot = FALSE, breaks = breaks)) n = length(freq_list) nm = names(freq_list) stat = match.arg(stat)[1] if(stat == "count") { mat = lapply(freq_list, function(x) { rev(x$count) }) } else if(stat == "proportion") { mat = lapply(freq_list, function(x) { rev(x$count)/sum(x$count) }) } else if(stat == "density") { mat = lapply(freq_list, function(x) { rev(x$density) }) } mat = as.matrix(as.data.frame(mat)) colnames(mat) = nm if(inherits(col, "function")) { col = col(mat) } else { col = colorRamp2(seq(0, quantile(mat, 0.99, na.rm = TRUE), length.out = length(col)), col, space = color_space) } bb = grid.pretty(c(min_x, max_x)) if(use_3d) { ht = Heatmap3D(mat, col = col, name = stat, column_title = title, column_title_gp = title_gp, cluster_rows = FALSE, cluster_columns = cluster_columns, column_names_side = column_names_side, show_column_names = show_column_names, column_names_max_height = column_names_max_height, column_names_gp = column_names_gp, column_names_rot = column_names_rot, column_order = column_order, left_annotation = rowAnnotation(axis = anno_empty(border = FALSE, width = grobHeight(textGrob(ylab, gp = ylab_gp))*2 + max_text_width(bb, gp = tick_label_gp) + unit(4, "mm")), show_annotation_name = FALSE), ... ) } else { ht = Heatmap(mat, col = col, name = stat, column_title = title, column_title_gp = title_gp, cluster_rows = FALSE, cluster_columns = cluster_columns, column_names_side = column_names_side, show_column_names = show_column_names, column_names_max_height = column_names_max_height, column_names_gp = column_names_gp, column_names_rot = column_names_rot, column_order = column_order, left_annotation = rowAnnotation(axis = anno_empty(border = FALSE, width = grobHeight(textGrob(ylab, gp = ylab_gp))*2 + max_text_width(bb, gp = tick_label_gp) + unit(4, "mm")), show_annotation_name = FALSE), ... ) } random_str = paste(sample(c(letters, LETTERS, 0:9), 8), collapse = "") ht@name = paste0(ht@name, "_", random_str) names(ht@left_annotation) = paste0(names(ht@left_annotation), "_", random_str) post_fun = function(ht) { column_order = column_order(ht) if(!is.list(column_order)) { column_order = list(column_order) } n_slice = length(column_order) decorate_annotation(paste0("axis_", random_str), { grid.text(ylab, x = grobHeight(textGrob(ylab, gp = ylab_gp)), rot = 90) }, slice = 1) decorate_heatmap_body(paste0(stat, "_", random_str), { pushViewport(viewport(yscale = c(min_x, max_x), clip = FALSE)) grid.segments(0, 0, 0, 1) grid.yaxis(gp = tick_label_gp) upViewport() }, column_slice = 1) } ht@heatmap_param$post_fun = post_fun ht_list = ht return(ht_list) }
library(tidyverse) library(ggthemr) ggthemr("earth", type = "outer") theme_update(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) big_epa_cars <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-10-15/big_epa_cars.csv") big_epa_cars %>% select(co2, co2TailpipeGpm) %>% ggplot(aes(co2, co2TailpipeGpm)) + geom_point() + coord_fixed(ratio = 1) + labs(title = "co2TailpipeGpm vs co2", subtitle = "Can we use co2TailpipeGpm instead of co2?", x = "co2 in grams / mile", y = "co2TailpipeGpm in grams / mile") summary(big_epa_cars$co2) summary(big_epa_cars$co2TailpipeGpm) big_epa_cars %>% select(make, model, co2, co2TailpipeGpm) %>% filter(co2 != floor(co2TailpipeGpm)) %>% distinct(co2) big_co2 <- big_epa_cars %>% filter(co2TailpipeGpm == max(co2TailpipeGpm)) %>% select(make, model, co2TailpipeGpm, year) %>% filter(year == max(year)) %>% distinct() %>% mutate(car = paste(make, model)) first_0_co2 <- big_epa_cars %>% filter(co2TailpipeGpm == 0) %>% select(make, model, year) %>% distinct() %>% arrange(year) %>% filter(year == min(year)) %>% mutate(car = paste(make, model)) big_epa_cars %>% mutate(co2ana = co2TailpipeGpm) %>% select(make, model, year, co2ana) %>% mutate(year = as.factor(year)) %>% ggplot(aes(year, co2ana, color = co2ana)) + geom_point(alpha = 0.5, position = "jitter")+ stat_summary(fun.y=max, colour="red", geom="line", aes(group = 1), size = 2, alpha = 0.5) + stat_summary(fun.y=min, colour="green", geom="line", aes(group = 1), size = 2, alpha = 0.5) + stat_summary(fun.y=mean, colour="orange", geom="line", aes(group = 1), size = 2, alpha = 0.8) + scale_x_discrete(breaks = c(1985,1990,1995,2000,2005,2010,2015,2020)) + scale_color_gradient2(name = "CO2 Emission", low="green", mid = "grey", high = "red", midpoint = 500) + annotate("label", x =2, y = 540, size = 3, color = "orange", label = "Mean", fill = " annotate("text", x =2, y = 1320, size = 3, color = "red", label = "Max", alpha = 0.7, fontface = "bold") + annotate("text", x =2, y = 160, size = 3, color = "green", label = "Min", alpha = 0.7, fontface = "bold") + annotate("text", x = (big_co2$year - min(big_epa_cars$year)+6), y = big_co2$co2TailpipeGpm, size = 3, color = "white", label = big_co2$car) + annotate("text", x = (first_0_co2$year - min(big_epa_cars$year)-5), y = 0, size = 3, color = "white", label = first_0_co2$car[1]) + annotate("text", x = (first_0_co2$year - min(big_epa_cars$year)-5), y = 40, size = 3, color = "white", label = first_0_co2$car[2]) + annotate("text", x = (2011 - min(big_epa_cars$year)+5), y = 40, size = 3, color = "white", label = "1st Tesla") + geom_curve(aes(x = (big_co2$year - min(big_epa_cars$year)+3), y = big_co2$co2TailpipeGpm+10, xend = (big_co2$year - min(big_epa_cars$year)+1), yend = big_co2$co2TailpipeGpm + 10), arrow = arrow(length = unit(0.1, "inch")), size = 0.3, color = "grey85", curvature = 0.5) + geom_curve(aes(x = (unique(first_0_co2$year) - min(big_epa_cars$year) - 3), y = 0, xend = (unique(first_0_co2$year) - min(big_epa_cars$year)+1), yend = 0), arrow = arrow(length = unit(0.1, "inch")), size = 0.3, color = "grey85", curvature = 0.3) + geom_curve(aes(x = (2011 - min(big_epa_cars$year) + 3), y = 40, xend = (2011 - min(big_epa_cars$year)+1), yend = 0), arrow = arrow(length = unit(0.1, "inch")), size = 0.3, color = "grey85", curvature = 0.3) + labs(title = "Evolution in co2 emission over year", x = "Years", y = "Co2 in grams / mile", caption = "Visualisation: Christophe Nicault | Data: www.fueleconomy.gov")
addCIM <- function(R,carm=2) { K <- R$K alphas <- R$alphas im1r <- R$Main1RL im1se <- R$Main1SE is1r <- R$Samp1RL is1se <- R$Sub1SE nmvec <- c(paste0("Main",carm,"RL"),paste0("Main",carm,"SE"),paste0("Samp",carm,"RL"),paste0("Sub",carm,"SE")) im2r <- R[[ nmvec[1] ]] im2se <- R[[ nmvec[2] ]] is2r <- R[[ nmvec[3] ]] is2se <- R[[ nmvec[4] ]] times <- 1:K alpha1 <- alphas alpha2 <- alphas WantM <- expand.grid(alpha1,alpha2,times) colnames(WantM) <- c("alpha1","alpha2","t") WantList <- apply(WantM,1,as.list) ECI <- lapply( WantList, CI, type=1, im1r = im1r, im1se = im1se, is1r = is1r, is1se = is1se, im2r = im2r, im2se = im2se, is2r = is2r, is2se = is2se ) ECI <- do.call(rbind,ECI) SCI <- lapply( WantList, CI, type=2, im1r = im1r, im1se = im1se, is1r = is1r, is1se = is1se, im2r = im2r, im2se = im2se, is2r = is2r, is2se = is2se ) SCI <- do.call(rbind,SCI) R$ECI <- ECI R$SCI <- SCI return(R) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(bpbounds) library(dplyr) library(tidyr) tab1dat <- data.frame( z = c(0, 0, 1, 1, 1, 1, 0, 0), x = c(0, 0, 0, 0, 1, 1, 1, 1), y = c(0, 1, 0, 1, 0, 1, 0, 1), freq = c(74, 11514, 34, 2385, 12, 9663, 0, 0) ) tab1inddat <- uncount(tab1dat, freq) xt <- xtabs(~ x + y + z, data = tab1inddat) xt p <- prop.table(xt, margin = 3) p bpres <- bpbounds(p) sbp = summary(bpres) print(sbp) covyz = cov(tab1inddat$y, tab1inddat$z) covxz = cov(tab1inddat$x, tab1inddat$z) ace = covyz / covxz ace condprob = c(.0064, 0, .9936, 0, .0028, .001, .1972, .799) tabp = array(condprob, dim = c(2, 2, 2), dimnames = list( x = c(0, 1), y = c(0, 1), z = c(0, 1) )) %>% as.table() bpbounds(tabp) gtab = xtabs( ~ y + z, data = tab1inddat) gp = prop.table(gtab, margin = 2) gp ttab = xtabs( ~ x + z, data = tab1inddat) tp = prop.table(ttab, margin = 2) tp bpres2 = bpbounds(p = gp, t = tp, fmt = "bivariate") sbp2 = summary(bpres2) print(sbp2) mt3 <- c(.83, .05, .11, .01, .88, .06, .05, .01, .72, .05, .20, .03) p3 = array(mt3, dim = c(2, 2, 3), dimnames = list( x = c(0, 1), y = c(0, 1), z = c(0, 1, 2) )) p3 = as.table(p3) bpres3 = bpbounds(p3) sbp3 = summary(bpres3) print(sbp3) set.seed(2232011) n = 10000 z = rbinom(n, 1, .5) u = rbinom(n, 1, .5) px = .05 + .1 * z + .1 * u x = rbinom(n, 1, px) p1 = .1 + .2 * z + .05 * x + .1 * u y1 = rbinom(n, 1, p1) p2 = .1 + .05 * z + .05 * x + .1 * u y2 = rbinom(n, 1, p2) tab1 = xtabs(~ x + y1 + z) p1 <- prop.table(tab1, margin = 3) bpres1 = bpbounds(p1) sbp1 = summary(bpres1) print(sbp1) tab2 = xtabs(~ x + y2 + z) p2 <- prop.table(tab2, margin = 3) bpres2 = bpbounds(p2) sbp2 = summary(bpres2) print(sbp2)
"pCMin" <- function(theta,delta,s,t) {if(missing(theta) | missing(delta)){theta<-1;delta<-1}; pc<-pmax(0,(s+t-1)); resu<-pc }
mat2df <- function(cormat, pmat) { ut <- upper.tri(cormat) data.frame( Pos1 = rownames(cormat)[row(cormat)[ut]], Pos2 = rownames(cormat)[col(cormat)[ut]], cor =(cormat)[ut], p = pmat[ut] ) }
source("JTK_CYCLEv3.1.R") project <- "Example2" options(stringsAsFactors=FALSE) annot <- read.delim("Example2_annot.txt") data <- read.delim("Example2_data.txt") rownames(data) <- data[,1] data <- data[,-1] jtkdist(13, 2) periods <- 5:7 jtk.init(periods,4) cat("JTK analysis started on",date(),"\n") flush.console() st <- system.time({ res <- apply(data,1,function(z) { jtkx(z) c(JTK.ADJP,JTK.PERIOD,JTK.LAG,JTK.AMP) }) res <- as.data.frame(t(res)) bhq <- p.adjust(unlist(res[,1]),"BH") res <- cbind(bhq,res) colnames(res) <- c("BH.Q","ADJ.P","PER","LAG","AMP") results <- cbind(annot,res,data) results <- results[order(res$ADJ.P,-res$AMP),] }) print(st) save(results,file=paste("JTK",project,"rda",sep=".")) write.table(results,file=paste("JTK",project,"txt",sep="."),row.names=F,col.names=T,quote=F,sep="\t")
myft=function(x,vanilla=TRUE,fontsize=10,digits,showid=FALSE,...){ if("imputedReg" %in% class(x)){ if(missing(digits)) digits=c(1,4,4,4,2,4,4,4,4,4,4,1) } else if("autoReg" %in% class(x)) { if(showid==FALSE) x$id=NULL if(names(x)[1]=="name"){ names(x)[1]=paste0("Dependent: \n",attr(x,"yvars")) } names(x)[2]=" " if(attr(x,"model")=="coxph") names(x)[3]="all" if(missing(digits)) digits=2 } else if(("gaze" %in% class(x))&(showid==FALSE)) { x$id=NULL names(x)[2]="levels" if(missing(digits)) digits=2 } yvars=attr(x,"yvars") yvars if(length(yvars)>0){ if(!is.null(attr(x,"missing"))) { yname=str_remove(attr(x,"yvars"),"Missing") names(x)[1]=paste0("Dependent:",yname) } } vanilla=TRUE ft<-x %>% df2flextable(vanilla=vanilla,fontsize=fontsize,digits=digits,...) if(length(yvars)>1){ small_border = fp_border(color="gray", width = 1) df=attr(x,"groups") if(length(yvars)==2) { collapse=" " } else { collapse="\n" } groupvar=paste0(c(yvars[-length(yvars)],"(N)"),collapse=collapse) header=c(groupvar,map_chr(1:nrow(df),function(i){paste0(df[i,],collapse=collapse)})) length=nrow(df) no=(ncol(x)-2)%/%length widths=c(2,rep(no,length)) ft<-ft %>% flextable::add_header_row(values=header,colwidths=widths) %>% hline(i=1,border=fp_border(color="gray", width = 0),part="header") %>% hline(i=1,border=fp_border(color="gray", width = 1),part="header") %>% hline_top(border=fp_border(color="black", width = 2),part="header") } if(("autoReg" %in% class(x))&(!is.null(attr(x,"add")))) { ft=footnote(ft,i=1,j=1,value=as_paragraph(paste0(attr(x,"add"),collapse=",")),ref_symbols="",part="body") } ft %>% flextable::align(align="center",part="header") %>% flextable::align(j=1:2,align="left",part="body") %>% flextable::autofit() }
ClusterRenameDescendingSize <- function(Cls) { if(!is.vector(Cls)){ warning('ClusterRenameDescendingSize: Cls is not a vector. Calling as.numeric(as.character(Cls))') Cls=as.numeric(as.character(Cls)) } ListeV <- ClusterCount(Cls) countPerClass <- ListeV[[2]] UniqueClasses=ListeV[[1]] sortedClasses <- sort(na.last=TRUE,countPerClass, decreasing = TRUE, index.return=TRUE) numberOfClasses <- length(countPerClass) renamedCls <- Cls for (i in 1: numberOfClasses) { renamedCls[which(Cls == UniqueClasses[sortedClasses$ix[i]],arr.ind = T)] <- i } return(renamedCls) }
source("incl/start.R") if (requireNamespace("furrr", quietly = TRUE)) { for (strategy in c("sequential", "multisession", "multicore")) { future::plan(strategy) print(future::plan()) message("* with_progress()") with_progress({ p <- progressor(4) y <- furrr::future_map(3:6, function(n) { p() slow_sum(1:n, stdout=TRUE, message=TRUE) }) }) message("* global progression handler") handlers(global = TRUE) local({ p <- progressor(4) y <- furrr::future_map(3:6, function(n) { p() slow_sum(1:n, stdout=TRUE, message=TRUE) }) }) handlers(global = FALSE) } } source("incl/end.R")
pastestar <- function(...) paste(..., sep = "*") expand_cond <- function(cond, obsnames) { chk1 <- sapply(cond, function(x) substr(x, nchar(x), nchar(x))) %in% obsnames if(!any(chk1)) { return(paste(cond, collapse = "; ")) } retcond <- cond[!chk1] for(j in (1:length(cond))[chk1]) { newcond <- paste0(substr(cond[j], 1, nchar(cond[j]) - 1), c("0", "1")) retcond <- paste(retcond, newcond, sep = "; ") } retcond } const.to.sets <- function(constr, objterms) { sets <- lapply(strsplit(constr, " = "), function(x) { tmp1 <- grep("q", x, value = TRUE) trimws(unlist(strsplit(tmp1, "( \\+ | - )"))) }) pnames <- lapply(strsplit(constr, " = "), function(x) { tmp1 <- grep("(q)", x, value = TRUE, invert = TRUE) trimws(tmp1) }) K <- length(sets) sets[(K+1):(K + length(objterms))]<- objterms reduced.sets <- reduce.sets(sets) constr.new <- reduced.sets[1:K] obj.new <- reduced.sets[(K+1):(K+length(objterms))] var.new <- reduced.sets[[1]] list(constr = paste(unlist(lapply(constr.new, paste, collapse = " + ")), " = ", pnames), objective.terms = obj.new, variables = var.new, raw.sets = constr.new, pnames = pnames) } reduce.sets <- function(sets){ K <- length(sets) fullset <- sets[[1]] common <- list() left <- fullset r <- 1 while(length(left)>1){ tmp <- left[1] for(i in 2:length(left)){ together <- vector(length=K) for(k in 1:K){ if((left[1]%in%sets[[k]] & left[i]%in%sets[[k]]) | (!left[1]%in%sets[[k]] & !left[i]%in%sets[[k]])) together[k] <- TRUE } if(sum(together)==K) tmp <- c(tmp, left[i]) } left <- setdiff(left, tmp) if(length(tmp)>1){ common[[r]] <- tmp r <- r+1 } } if(length(common) == 0) return(sets) R <- length(common) for(r in 1:R){ tmp <- common[[r]][-1] for(k in 1:K){ ind <- match(tmp, sets[[k]]) if(sum(is.na(ind))==0) sets[[k]] <- sets[[k]][-ind] } } fullset <- sets[[1]] for(i in 1:length(sets)){ tmp <- sets[[i]] for(j in 1:length(tmp)){ tmp[j] <- paste0("q", match(tmp[j], fullset)) } sets[[i]] <- tmp } return(sets) } symb.subtract <- function(x1, x2) { res1 <- x1 res2 <- NULL for(j in x2) { if(!j %in% res1){ res2 <- c(res2, j) } else { res1 <- res1[-which(res1 == j)[1]] } } list(res1, res2) } parse_effect <- function(text) { text <- gsub("(\\n|\\t| )", "", text) terms0 <- strsplit(text, split = "-|\\+")[[1]] opers <- as.list(grep("-|\\+", strsplit(text, "")[[1]], value = TRUE)) terms0 <- gsub("(p\\{)|(\\})", "", terms0) termssplit <- lapply(terms0, function(x) { strsplit(x, ";")[[1]] }) res.effs <- res.vals <- res.pcheck <- vector(mode = "list", length= length(termssplit)) for(j in 1:length(termssplit)) { terms0 <- termssplit[[j]] parse1 <- lapply(terms0, function(x) { rmain <- unlist(strsplit(x, "=\\d+$")) val0 <- substr(x = x, start = nchar(rmain) + 2, stop = nchar(x)) list(as.numeric(val0), rmain) }) terms <- lapply(parse1, "[[", 2) vals <- lapply(parse1, "[[", 1) pcheck <- grepl("(", terms, fixed = TRUE) pterms <- gsub("(", " = list(", terms, fixed = TRUE) parsedEffect <- vector(mode = "list", length = length(pterms)) for(k in 1:length(parsedEffect)) { if(pcheck[k] == TRUE) { parsedEffect[[k]] <- eval(parse(text = pterms[k], keep.source = FALSE)) names(parsedEffect)[[k]] <- strsplit(pterms[k], " = ")[[1]][1] } else { parsedEffect[[k]] <- pterms[k] names(parsedEffect)[[k]] <- pterms[k] } } names(vals) <- names(parsedEffect) res.effs[[j]] <- parsedEffect res.vals[[j]] <- vals res.pcheck[[j]] <- pcheck } list(vars = res.effs, oper = opers, values = res.vals, pcheck = res.pcheck) } parse_constraints <- function(constraints, obsnames) { parsed.constraints <- NULL for(j in 1:length(constraints)) { constin <- gsub("\\s", "", constraints[[j]]) p0 <- strsplit(constin, "\\)")[[1]] pl1 <- strsplit(p0[1], "\\(")[[1]] leftout <- pl1[1] leftcond <- strsplit(pl1[-1], ",")[[1]] opdex <- ifelse(substr(p0[-1], 2, 2) == "=", 2, 1) operator <- substr(p0[-1], 1, opdex) if(operator == "=") operator <- "==" pr1 <- strsplit(substr(p0[-1], opdex + 1, nchar(p0[-1])), "\\(")[[1]] rightout <- pr1[1] if(!is.na(suppressWarnings(as.numeric(rightout)))) { rightcond2 <- rightout } else { rightcond <- strsplit(gsub("\\)", "", pr1[-1]), ",")[[1]] rightcond2 <- expand_cond(rightcond, obsnames) } leftcond2 <- expand_cond(leftcond, obsnames) conds <- expand.grid(leftcond = leftcond2, rightcond = rightcond2, stringsAsFactors = FALSE) parsed.constraints <- rbind(parsed.constraints, data.frame(leftout = leftout, rightout = rightout, operator, conds, stringsAsFactors = FALSE)) } parsed.constraints } latex_bounds <- function(bounds, parameters, prob.sym = "P", brackets = c("(", ")")) { lkeyup <- do.call(expand.grid, c(lapply(1:length(attr(parameters, "rightvars")), function(x) c("0", "1")), stringsAsFactors = FALSE)) if(length(attr(parameters, "condvars")) == 0) { probstate <- lapply(1:nrow(lkeyup), function(i) { lkey <- lkeyup[i, ] paste0(prob.sym, brackets[1], paste(paste0(attr(parameters, "rightvars"), " = ", lkey), collapse = ", "), brackets[2]) }) namelook <- sapply(1:nrow(lkeyup), function(i) { paste0("p", paste(lkeyup[i, ], collapse = ""), "_") }) names(probstate) <- namelook } else { nr <- length(attr(parameters, "rightvars")) nc <- length(attr(parameters, "condvars")) lrkeyup <- do.call(expand.grid, c(lapply(1:(nr + nc), function(x) c("0", "1")), stringsAsFactors = FALSE)) probstate <- lapply(1:nrow(lrkeyup), function(i) { lkey <- lrkeyup[i, 1:nr] rkey <- lrkeyup[i, (nr + 1):(nr + nc)] paste0(prob.sym, brackets[1], paste(paste0(attr(parameters, "rightvars"), " = ", lkey), collapse = ", "), " | ", paste0(attr(parameters, "condvars"), " = ", rkey, collapse = ", "), brackets[2]) }) namelook <- sapply(1:nrow(lrkeyup), function(i) { paste0("p", paste(lrkeyup[i, 1:nr], collapse = ""), "_", paste(lrkeyup[i, (nr+1):(nr+nc)], collapse = "")) }) names(probstate) <- namelook } bnd2 <- gsub("\\n}\\n", "", substr(bounds, 8, nchar(bounds))) bnd3 <- strsplit(bnd2, "\\n") for(i in 1:length(probstate)) { bnd3$lower <- gsub(names(probstate)[i], probstate[[i]], bnd3$lower, fixed = TRUE) bnd3$upper <- gsub(names(probstate)[i], probstate[[i]], bnd3$upper, fixed = TRUE) } if(length(bnd3$lower) == 1) { lwr <- bnd3$lower } else { l0 <- paste(bnd3$lower, collapse = "\\\\ \n ") lwr <- sprintf("\\mbox{max} \\left. \\begin{cases} %s \\end{cases} \\right\\}", l0) } if(length(bnd3$upper) == 1) { upr <- bnd3$upper } else { r0 <- paste(bnd3$upper, collapse = "\\\\ \n ") upr <- sprintf("\\mbox{min} \\left. \\begin{cases} %s \\end{cases} \\right\\}", r0) } return(sprintf("\\[ \n \\mbox{Lower bound} = %s \n \\] \n \\[ \n \\mbox{Upper bound} = %s \n \\] \n", lwr, upr)) }
fast_anticlustering <- function(x, K, k_neighbours = Inf, categories = NULL) { input_validation_anticlustering(x, K, "variance", "exchange", FALSE, categories, NULL) categories <- merge_into_one_variable(categories) if (!isTRUE(k_neighbours == Inf)) { validate_input(k_neighbours, "k_neighbours", objmode = "numeric", len = 1, must_be_integer = TRUE, greater_than = 0, not_na = TRUE) } x <- as.matrix(x) exchange_partners <- all_exchange_partners(x, k_neighbours, categories) init <- initialize_clusters(nrow(x), K, categories) fast_exchange_(x, init, exchange_partners) } fast_exchange_ <- function(data, clusters, all_exchange_partners) { N <- nrow(data) best_total <- variance_objective_(clusters, data) centers <- cluster_centers(data, clusters) distances <- dist_from_centers(data, centers, squared = TRUE) tab <- c(table(clusters)) for (i in 1:N) { cluster_i <- clusters[i] exchange_partners <- all_exchange_partners[[i]] exchange_partners <- exchange_partners[clusters[exchange_partners] != clusters[i]] if (length(exchange_partners) == 0) { next } comparison_objectives <- rep(NA, length(exchange_partners)) for (j in seq_along(exchange_partners)) { tmp_clusters <- clusters tmp_swap <- exchange_partners[j] cluster_j <- tmp_clusters[tmp_swap] tmp_clusters[i] <- cluster_j tmp_clusters[tmp_swap] <- cluster_i tmp_centers <- update_centers(centers, data, i, tmp_swap, cluster_i, cluster_j, tab) tmp_distances <- update_distances(data, tmp_centers, distances, cluster_i, cluster_j) comparison_objectives[j] <- sum(tmp_distances[cbind(1:nrow(tmp_distances), tmp_clusters)]) } best_this_round <- max(comparison_objectives) if (best_this_round > best_total) { swap <- exchange_partners[comparison_objectives == best_this_round][1] centers <- update_centers(centers, data, i, swap, clusters[i], clusters[swap], tab) distances <- update_distances(data, centers, distances, cluster_i, clusters[swap]) clusters[i] <- clusters[swap] clusters[swap] <- cluster_i best_total <- best_this_round } } clusters } update_distances <- function(features, centers, distances, cluster_i, cluster_j) { for (k in c(cluster_i, cluster_j)) { distances[, k] <- colSums((t(features) - centers[k,])^2) } distances } update_centers <- function(centers, features, i, j, cluster_i, cluster_j, tab) { centers[cluster_i, ] <- centers[cluster_i, ] - (features[i, ] / tab[cluster_i]) + (features[j, ] / tab[cluster_i]) centers[cluster_j, ] <- centers[cluster_j, ] + (features[i, ] / tab[cluster_j]) - (features[j, ] / tab[cluster_j]) centers } all_exchange_partners <- function(features, k_neighbours, categories) { if (is.infinite(k_neighbours)) { return(all_exchange_partners_(nrow(features), categories)) } return(nearest_neighbours(features, k_neighbours, categories)) } all_exchange_partners_ <- function(N, categories) { if (argument_exists(categories)) { category_ids <- lapply(1:max(categories), function(i) which(categories == i)) return(category_ids[categories]) } rep(list(1:N), N) } nearest_neighbours <- function(features, k_neighbours, categories) { if (!argument_exists(categories)) { idx <- matrix_to_list(RANN::nn2(features, k = min(k_neighbours + 1, nrow(features)))$nn.idx) } else { nns <- list() new_order <- list() for (i in 1:max(categories)) { tmp_indices <- which(categories == i) new_order[[i]] <- tmp_indices tmp_features <- features[tmp_indices, , drop = FALSE] tmp_nn <- RANN::nn2(tmp_features, k = min(k_neighbours + 1, nrow(tmp_features)))$nn.idx nns[[i]] <- which(categories == i)[tmp_nn] dim(nns[[i]]) <- dim(tmp_nn) } idx_list <- lapply(nns, matrix_to_list) idx <- merge_lists(idx_list) original_order <- order(unlist(new_order)) idx <- idx[original_order] } idx } matrix_to_list <- function(x) { as.list(as.data.frame(t(x))) } merge_lists <- function(list_of_lists) { do.call(c, list_of_lists) }
FileListFromDates <- function(start_date, end_date=start_date){ start_date <- as.Date(start_date) end_date <- as.Date(end_date) if(end_date < start_date) stop("end_date cannot be before start_date") if(start_date < as.Date("1979-01-01")) stop("start_date cannot be before 1979") if(end_date > Sys.Date()) stop("end_date cannot be in the future") out <- character(0) if(start_date < "2006-01-01"){ start_year <- as.numeric(format(start_date, "%Y")) end_year <- min(c(2005,as.numeric(format(end_date, "%Y")))) out <- c(out, paste(start_year:end_year, ".zip", sep="")) } if(start_date < as.Date("2013-04-01") & end_date >= as.Date("2006-01-01")) { if( start_date < as.Date("2006-01-01") ) { b_start_date <- as.Date("2006-01-01") } else { b_start_date <- as.Date(paste(format(start_date, "%Y-%m-"), "01", sep="")) } if( end_date < as.Date("2013-04-01") ) { b_end_date <- end_date } else { b_end_date <- as.Date("2013-03-31") } out <- c(out, paste(format(seq(from=b_start_date, to=b_end_date, by="month"), "%Y%m"), ".zip", sep="")) } if( end_date >= as.Date("2013-04-01") ){ if( start_date < as.Date("2013-04-01") ) { c_start_date <- as.Date("2013-04-01") } else { c_start_date <- start_date } out <- c(out, paste(format(seq(from=c_start_date, to=end_date, by="day"), "%Y%m%d"), ".export.CSV.zip", sep="")) } out <- setdiff(out, c("20140123.export.CSV.zip","20140124.export.CSV.zip","20140125.export.CSV.zip")) return( out ) }
context("create") test_that("create_env()", { env <- create_env(lapply(letters, as.name), toupper) expect_equal(env$a, "A") expect_equal(env$x, "X") expect_null(env$X) expect_equal(length(ls(env)), length(letters)) expect_error(env$a <- "a", "read-only") }) test_that("create_env() with character", { env <- create_env(letters, toupper) expect_equal(env$a, "A") expect_equal(env$x, "X") expect_null(env$X) expect_equal(length(ls(env)), length(letters)) expect_error(env$a <- "a", "read-only") }) test_that("create_env() with inheritance", { env <- create_env(lapply(letters, as.name), toupper) env2 <- create_env(lapply(LETTERS, as.name), tolower, .enclos = env) expect_equal(get("a", env2), "A") expect_equal(get("x", env2), "X") expect_null(env2$a) expect_null(env2$x) expect_equal(env2$B, "b") expect_equal(env2$Y, "y") expect_equal(length(ls(env2)), length(letters)) expect_error(env2$B <- "B", "read-only") expect_error(env2$a <- "a", NA) expect_equal(get("a", env2), "a") }) test_that("create_env() with local function", { a <- function(x) b(x) b <- function(x) c(x) c <- function(x) toupper(x) env <- create_env(lapply(letters, as.name), a) expect_equal(env$a, "A") expect_equal(env$x, "X") expect_null(env$X) expect_equal(length(ls(env)), length(letters)) expect_error(env$a <- "a", "read-only") })
test_that('mtpi_selector matches published example.', { num_doses <- 5 target <- 0.3 model <- get_mtpi(num_doses = num_doses, target = target, epsilon1 = 0.05, epsilon2 = 0.05, exclusion_certainty = 0.95) fit <- model %>% fit('1NNN') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNT 1TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NTT 1TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1TTT 1TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1TTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NNT 1TTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1NTT 1TTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNN 1TTT 1TTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NNT 1TTT 1TTT 1TTT 1TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1NTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNN 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NNT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1NTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNN 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NNT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1NTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNN 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NNT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1NTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNN 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NNT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1NTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNN 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NNT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1NTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT 1TTT') expect_true(is.na(recommended_dose(fit))) expect_false(continue(fit)) expect_equal(dose_admissible(fit), rep(FALSE, num_doses(fit))) fit <- model %>% fit('2NNN') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2TTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNT 2TTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NTT 2TTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2TTT 2TTT') expect_equal(recommended_dose(fit), 3) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NNT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2NTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNN 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NNT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 2) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2NTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNN 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NNT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2NTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNN 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NNT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2NTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNN 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NNT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2NTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNN 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NNT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2NTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNN 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NNT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2NTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT 2TTT') expect_equal(recommended_dose(fit), 1) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, FALSE, FALSE, FALSE, FALSE)) fit <- model %>% fit('5NNN') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NNT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5NTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNN 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NNT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 5) expect_true(continue(fit)) expect_equal(dose_admissible(fit), rep(TRUE, num_doses(fit))) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5NTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNN 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NNT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5NTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNN 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NNT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5NTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNN 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NNT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5NTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNN 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NNT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5NTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNN 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NNT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5NTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) fit <- model %>% fit('5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT 5TTT') expect_equal(recommended_dose(fit), 4) expect_true(continue(fit)) expect_equal(dose_admissible(fit), c(TRUE, TRUE, TRUE, TRUE, FALSE)) }) test_that('mtpi_selector supports correct interface.', { num_doses <- 5 target <- 0.3 model_fitter <- get_mtpi(num_doses = num_doses, target = target, epsilon1 = 0.05, epsilon2 = 0.05, exclusion_certainty = 0.9) x <- fit(model_fitter, '1NNN 2NTT') expect_equal(tox_target(x), 0.3) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_error(prob_tox_samples(x)) expect_error(prob_tox_samples(x, tall = TRUE)) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) x <- fit(model_fitter, '') expect_equal(tox_target(x), 0.3) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 0) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), integer(0)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), integer(0)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), integer(0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) mf <- model_frame(x) expect_equal(nrow(mf), 0) expect_equal(ncol(mf), 4) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 0) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_error(prob_tox_samples(x)) expect_error(prob_tox_samples(x, tall = TRUE)) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) outcomes <- tibble( cohort = c(1,1,1, 2,2,2), dose = c(1,1,1, 2,2,2), tox = c(0,0, 0,0, 1,1) ) x <- fit(model_fitter, outcomes) expect_equal(tox_target(x), 0.3) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_error(prob_tox_samples(x)) expect_error(prob_tox_samples(x, tall = TRUE)) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) }) test_that('mtpi_selector respects suspended doses', { model <- get_mtpi(num_doses = 5, target = 0.3, epsilon1 = 0.05, epsilon2 = 0.05, exclusion_certainty = 0.7) fit <- model %>% fit('2N') expect_equal(fit %>% recommended_dose(), 3) expect_true(fit %>% continue()) expect_equal(fit %>% dose_admissible(), rep(TRUE, num_doses(fit))) fit <- model %>% fit('3TTT') expect_equal(fit %>% recommended_dose(), 2) expect_true(fit %>% continue()) expect_equal(fit %>% dose_admissible(), c(TRUE, TRUE, FALSE, FALSE, FALSE)) fit <- model %>% fit('3TTT 2N') expect_equal(fit %>% recommended_dose(), 2) expect_true(fit %>% continue()) expect_equal(fit %>% dose_admissible(), c(TRUE, TRUE, FALSE, FALSE, FALSE)) fit <- model %>% fit('3TTT 2N 1N') expect_equal(fit %>% recommended_dose(), 2) expect_true(fit %>% continue()) expect_equal(fit %>% dose_admissible(), c(TRUE, TRUE, FALSE, FALSE, FALSE)) fit <- model %>% fit('3TTT 2N 1N 2NNNNNNNNNNNNNNNNNNN') expect_equal(fit %>% recommended_dose(), 2) expect_true(fit %>% continue()) expect_equal(fit %>% dose_admissible(), c(TRUE, TRUE, FALSE, FALSE, FALSE)) })
Errmax<-function(x,i){ sampleData2<-x i=i sampleData3<-sampleData2[,c(1,i)] sampleData3$FZZH<- NA sampleData4<-sampleData3[,c(1,3)] transDatacol<-sampleData4 names(transDatacol)[1] <- names(sampleData2[1]) names(transDatacol)[2] <- names(sampleData2[i]) return(transDatacol) }
.lmacfPlot <- function(x, lag.max = max(2, floor(10*log10(length(x)))), ci = 0.95, type = c("both", "acf", "hurst"), labels = TRUE, trace = TRUE, ...) { if (!is.timeSeries(x)) x = as.timeSeries(x) Units = colnames(x) X = x type = match.arg(type) if (labels) { main1 = "" xlab1 = "lag" ylab1 = "ACF" main2 = "" xlab2 = "log lag" ylab2 = "log ACF" } else { main1 = xlab1 = ylab1 = "" main2 = xlab2 = ylab2 = "" } Fitted = list() Hurst = NULL DIM = dim(X)[2] for (i in 1:DIM) { x.ret = as.matrix(X)[, i] x = abs(x.ret) if (labels) main1 = main2 = Units[i] z = acf(x, lag.max = lag.max, type = "correlation", plot = FALSE) z$acf[1] = 0 cl = qnorm(0.5 + ci/2)/sqrt(z$n.used) z.min = min(z$acf, -cl) x = seq(0, lag.max, by = 1) y = z$acf if (type == "both" | type == "acf") { plot(x = x[-1], y = y[-1], type = "l", main = main1, col = "steelblue", xlab = xlab1, ylab = ylab1, xlim = c(0, lag.max), ylim = c(-2*cl, max(y[-1])), ...) if (trace) { cat ("\nLong Memory Autocorrelation Function:") paste (cat ("\n Maximum Lag "), cat(lag.max)) paste (cat ("\n Cut-Off ConfLevel "), cat(cl)) } ACF = acf(x.ret, lag.max = lag.max, plot = FALSE)$acf[,,1] lines(x = 1:lag.max, y = ACF[-1], type = "l", col = "steelblue") lines(x = c(-0.1, 1.1)*lag.max, y = c(+cl, +cl), lty = 3, col = "darkgrey") lines(x = c(-0.1, 1.1)*lag.max, y = c(-cl, -cl), lty = 3, col = "darkgrey") } x = x[y > cl] y = y[y > cl] if (length(x) < 10) { Fit = c(NA, NA) hurst = NA cat("\n The time series exhibits no long memory! \n") } else { Fit = lsfit(log(x), log(y)) fit = unlist(Fit)[1:2] hurst = 1 + fit[2]/2 if (type == "both" | type == "hurst") { plot(x = log(x), y = log(y), type = "l", xlab = xlab2, ylab = ylab2, main = main2, col = "steelblue", ...) Text = paste("Hurst Exponent:", signif(hurst, 3)) mtext(Text, side = 4, adj = 0, col = "darkgrey", cex = 0.7) if (labels) grid() } abline(fit[1], fit[2], col = 1) if (trace) { paste (cat ('\n Plot-Intercept '), cat(fit[1])) paste (cat ('\n Plot-Slope '), cat(fit[2])) paste (cat ('\n Hurst Exponent '), cat(hurst), cat("\n")) } } if (DIM == 1) Fitted = Fit else Fitted[[i]] = Fit Hurst = c(Hurst, hurst) } invisible(list(fit = Fitted, hurst = Hurst)) } .logpdfPlot = function(x, breaks = "FD", type = c("lin-log", "log-log"), doplot = TRUE, labels = TRUE, ...) { if (!is.timeSeries(x)) x = as.timeSeries(x) Units = colnames(x) type = match.arg(type) if (labels) { if (type == "lin-log") { main = "log PDF" xlab = "x" ylab = "log PDF" } else if (type == "log-log") { main = "log PDF" xlab = "log x" ylab = "log PDF" } } else { main = xlab = ylab = "" } X = x DIM = ncol(X) for (i in 1:DIM) { x = as.vector(X[, i]) if (labels) main = Units[i] if (type == "lin-log") { result = hist(x, breaks = breaks, plot = FALSE) prob.counts = result$counts/sum(result$counts) / diff(result$breaks)[1] histogram = list(breaks = result$breaks, counts = prob.counts) yh = histogram$counts xh = histogram$breaks xh = xh[1:(length(xh)-1)] + diff(xh)/2 xh = xh[yh > 0] yh = log(yh[yh > 0]) if (doplot) { par(err = -1) plot(xh, yh, type = "p", pch = 19, col = "steelblue", main = main, xlab = xlab, ylab = ylab, ...) Text = "Scales: log-log" mtext(Text, side = 4, adj =0, col = "darkgrey", cex = 0.7) } xg = seq(from = xh[1], to = xh[length(xh)], length = 301) yg = log(dnorm(xg, mean(x), sqrt(var(x)))) if (doplot) { par(err = -1) lines(xg, yg, col = "brown") } result = list(breaks = xh, counts = yh, fbreaks = xg, fcounts = yg) } if (type == "log-log") { result = hist(x, breaks = breaks, plot = FALSE) prob.counts = result$counts/sum(result$counts) / diff(result$breaks)[1] histogram = list(breaks = result$breaks, counts = prob.counts) yh = histogram$counts xh = histogram$breaks xh = xh[1:(length(xh)-1)] + diff(xh)/2 xh = xh[yh > 0] yh = yh[yh > 0] yh1 = yh[xh < 0] xh1 = abs(xh[xh < 0]) yh2 = yh[xh > 0] xh2 = xh[xh > 0] if (doplot) { plot(log(xh1), log(yh1), type = "p", pch = 19, col = "darkgreen", main = main, xlab = xlab, ylab = ylab, ...) Text = "Scales: log-log" mtext(Text, side = 4, adj =0, col = "darkgrey", cex = 0.7) par(err = -1) points(log(xh2), log(yh2), col = 2, ...) } xg = seq(from = min(xh1[1], xh[2]), to = max(xh1[length(xh1)], xh2[length(xh2)]), length = 301) xg = xg[xg > 0] yg = log(dnorm(xg, mean(x), sqrt(var(x)))) if (doplot) { par(err = -1) lines(log(xg), yg, col = "brown") } result = list(breaks = c(xh1, xh2), counts = c(yh1, yh2), fbreaks = c(-rev(xg), xg), fcounts = c(-rev(yg), yg)) } if (labels) grid() } invisible(result) } .qqgaussPlot <- function(x, span = 5, col = "steelblue", labels = TRUE, ...) { if (!is.timeSeries(x)) x = as.timeSeries(x) Units = colnames(x) if (labels) { main = "Normal QQ Plot" xlab = "Theoretical Quantiles" ylab = "Sample Quantiles" } else { main = xlab = ylab = "" } X = x DIM = dim(X)[2] for (i in 1:DIM) { x = as.vector(as.matrix(X)[, i]) if (labels) main = Units[i] y = (x-mean(x)) / sqrt(var(x)) y[abs(y) < span] lim = c(-span, span) qqnorm(y, main = main, xlab = xlab, ylab = ylab, xlim = lim, ylim = lim, col = col, ...) qqline(y, ...) if (labels) grid() } invisible(x) } .ccfPlot <- function(x, y, lag.max = max(2, floor(10*log10(length(x)))), type = c("correlation", "covariance", "partial"), labels = TRUE, ...) { if (class(x) == "timeSeries") stopifnot(isUnivariate(x)) if (class(y) == "timeSeries") stopifnot(isUnivariate(y)) x = as.vector(x) y = as.vector(y) if (labels) { main = "Crosscorrelation Function" xlab = "lag" ylab = "CCF" } else { main = xlab = ylab = "" } X = cbind(x = x, y = y) acf.out = acf(X, lag.max = lag.max, plot = FALSE, type = type[1]) lag = c(rev(acf.out$lag[-1, 2, 1]), acf.out$lag[, 1, 2]) y = c(rev(acf.out$acf[-1, 2, 1]), acf.out$acf[, 1, 2]) acf.out$acf = array(y, dim = c(length(y), 1, 1)) acf.out$lag = array(lag, dim = c(length(y), 1, 1)) acf.out$snames = paste(acf.out$snames, collapse = " & ") plot(acf.out, main = main, xlab = xlab, ylab = ylab, ...) invisible(acf.out) } .stylizedFactsGUI <- function(x, mfrow = c(3, 3)) { stylizedFactsRefreshCode <- function(...) { selectedAsset = .tdSliderMenu(no = 1) type = as.integer(.tdSliderMenu(obj.name = "stylizedFactsType")) Unit = colnames(x) if (type == 1) { if (selectedAsset == 0) { par(mfrow = mfrow) acfPlot(x) } else { par(mfrow = c(1, 1)) acfPlot(x[, selectedAsset]) } } if (type == 2) { if (selectedAsset == 0) { par(mfrow = mfrow) pacfPlot(x) } else { par(mfrow = c(1, 1)) pacfPlot(x[, selectedAsset]) } } if (type == 3) { if (selectedAsset == 0) { par(mfrow = mfrow) acfPlot(abs(x)) } else { par(mfrow = c(1, 1)) acfPlot(abs(x[, selectedAsset])) } } if (type == 4) { if (selectedAsset == 0) { par(mfrow = mfrow) teffectPlot(x) } else { par(mfrow = c(1, 1)) teffectPlot(x[, selectedAsset]) } } if (type == 5) { if (selectedAsset == 0) { par(mfrow = mfrow) .lmacfPlot(abs(x)) } else { par(mfrow = c(1, 1)) .lmacfPlot(abs(x[, selectedAsset])) } } if (type == 6) { if (selectedAsset == 0) { par(mfrow = mfrow) lacfPlot(x) } else { par(mfrow = c(1, 1)) lacfPlot(x[, selectedAsset]) } } if (type == 7) { if (selectedAsset == 0) { par(mfrow = mfrow) .logpdfPlot(x) } else { par(mfrow = c(1, 1)) .logpdfPlot(x[, selectedAsset]) } } if (type == 8) { if (selectedAsset == 0) { par(mfrow = mfrow) .logpdfPlot(x, type = "log-log") } else { par(mfrow = c(1, 1)) .logpdfPlot(x[, selectedAsset], type = "log-log") } } if (type == 9) { if (selectedAsset == 0) { par(mfrow = mfrow) .qqgaussPlot(x, pch = 19) } else { par(mfrow = c(1, 1)) .qqgaussPlot(x[, selectedAsset], pch = 19) } } if (type == 10) { if (selectedAsset == 0) { par(mfrow = mfrow) scalinglawPlot(x, pch = 19) } else { par(mfrow = c(1, 1)) scalinglawPlot(x[, selectedAsset], pch = 19) } } } nAssets = dim(x)[2] .tdSliderMenu( stylizedFactsRefreshCode, names = c("Selected Asset"), minima = c( 0), maxima = c( nAssets), resolutions = c( 1), starts = c( 0), but.functions = list( function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "1") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "2") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "3") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "4") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "5") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "6") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "7") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "8") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "9") stylizedFactsRefreshCode()}, function(...){ .tdSliderMenu(obj.name = "stylizedFactsType", obj.value = "10") stylizedFactsRefreshCode()} ), but.names = c( "1 ACF Function of Returns", "2 Partial ACF of Returns", "3 ACF of absolute Returns", "4 Taylor Effect", "5 Long Memory ACF of abs Returns", "6 Lagged Autocorrelations", "7 Lin-Log Tail Density Plot", "8 Log-Log Lower Tail Density", "9 Simple Normal QQ Plot", "10 Scaling Law Plot"), title = "Stylized Facts GUI" ) .tdSliderMenu(obj.name = "type", obj.value = "1", no = 1) invisible() }
library(potts) library(pooh) set.seed(42) ncolor <- as.integer(4) alpha <- rnorm(ncolor) * 0.01 beta <- log(1 + sqrt(ncolor)) theta <- c(alpha, beta) nrow <- 25 ncol <- 20 x <- matrix(1, nrow = nrow, ncol = ncol) foo <- packPotts(x, ncolor) out <- potts(foo, theta, nbatch = 5, blen = 3, nspac = 2, debug = TRUE, boundary = "condition") names(out) identical(out$initial, foo) before <- out$pstate dim(before) niter <- dim(before)[1] niter == out$nbatch * out$blen * out$nspac after <- before after[- niter, , ] <- before[- 1, ,] after[niter, , ] <- unpackPotts(out$final) sort(unique(as.vector(before))) sort(unique(as.vector(after))) all.equal(x, before[1, , ]) before.foo <- before before.foo[ , seq(2, nrow - 1), seq(2, ncol - 1)] <- 0 after.foo <- after after.foo[ , seq(2, nrow - 1), seq(2, ncol - 1)] <- 0 identical(apply(before.foo, c(2, 3), max), before.foo[1, , ]) identical(apply(before.foo, c(2, 3), min), before.foo[1, , ]) identical(apply(after.foo, c(2, 3), max), before.foo[1, , ]) identical(apply(after.foo, c(2, 3), min), before.foo[1, , ]) ttt <- matrix(NA, niter, ncolor + 1) for (icolor in 1:ncolor) ttt[ , icolor] <- apply(after - after.foo == icolor, 1, sum) colin <- seq(2, ncol - 1) rowin <- seq(2, nrow - 1) tstar <- rep(0, niter) for (i in 2:nrow) tstar <- tstar + apply(after[ , i, colin] == after[ , i - 1, colin], 1, sum) for (i in 2:ncol) tstar <- tstar + apply(after[ , rowin, i] == after[ , rowin, i - 1], 1, sum) ttt[ , ncolor + 1] <- tstar foo <- ttt[seq(1, niter) %% out$nspac == 0, ] foo <- array(as.vector(foo), c(out$blen, out$nbatch, ncolor + 1)) foo <- apply(foo, c(2, 3), mean) identical(foo, out$batch) bprob <- (- expm1(- beta)) all.equal(bprob, 1 - exp(- beta)) my.hstate.possible <- array(FALSE, c(niter, nrow, ncol)) for (i in seq(1, nrow - 1)) my.hstate.possible[ , i, colin] <- before[ , i, colin] == before[ , i + 1, colin] storage.mode(my.hstate.possible) <- "integer" identical(my.hstate.possible == 1, out$hunif != -1) my.hstate <- out$hunif < bprob storage.mode(my.hstate) <- "integer" my.hstate <- my.hstate * my.hstate.possible identical(my.hstate, out$hstate) my.vstate.possible <- array(FALSE, c(niter, nrow, ncol)) for (i in seq(1, ncol - 1)) my.vstate.possible[ , rowin, i] <- before[ , rowin, i] == before[ , rowin, i + 1] storage.mode(my.vstate.possible) <- "integer" identical(my.vstate.possible == 1, out$vunif != -1) my.vstate <- out$vunif < bprob storage.mode(my.vstate) <- "integer" my.vstate <- my.vstate * my.vstate.possible identical(my.vstate, out$vstate) my.row <- row(my.hstate[1, , ]) my.col <- col(my.hstate[1, , ]) my.other.row <- my.row + 1 my.other.row[my.other.row > nrow] <- 1 my.other.col <- my.col + 1 my.other.col[my.other.col > ncol] <- 1 vertices <- paste(my.row, my.col, sep = ":") patch.equals <- NULL for (iiter in 1:niter) { isbond <- my.hstate[iiter, , ] == 1 my.row.bond <- as.vector(my.row[isbond]) my.col.bond <- as.vector(my.col[isbond]) my.other.row.bond <- as.vector(my.other.row[isbond]) my.from.h <- paste(my.row.bond, my.col.bond, sep = ":") my.to.h <- paste(my.other.row.bond, my.col.bond, sep = ":") isbond <- my.vstate[iiter, , ] == 1 my.row.bond <- as.vector(my.row[isbond]) my.col.bond <- as.vector(my.col[isbond]) my.other.col.bond <- as.vector(my.other.col[isbond]) my.from.v <- paste(my.row.bond, my.col.bond, sep = ":") my.to.v <- paste(my.row.bond, my.other.col.bond, sep = ":") wout <- weak(from = c(my.from.h, my.from.v), to = c(my.to.h, my.to.v), domain = vertices, markers = TRUE) blab <- as.vector(out$patch[iiter, , ]) widx <- sort(unique(wout)) bidx <- blab[match(widx, wout)] patch.equals <- c(patch.equals, identical(bidx[wout], blab)) } all(patch.equals) unif.equals <- NULL my.after <- after for (iiter in 1:niter) { fred <- out$patch[iiter, , ] blab <- as.vector(fred) blab.count <- tabulate(blab, nbins = nrow * ncol) blab.fixed <- c(fred[c(1, nrow), ], fred[ , c(1, ncol)]) blab.fixed <- sort(unique(blab.fixed)) punif <- out$punif[iiter, ] unif.equals <- c(unif.equals, identical(punif != -1, blab.count != 0)) alpha.prod <- outer(blab.count, alpha) p.prod <- exp(alpha.prod) p.sum <- apply(p.prod, 1, sum) p <- sweep(p.prod, 1, p.sum, "/") p.cum <- apply(p, 1, cumsum) p.cum <- t(p.cum) p.foo <- sweep(p.cum, 1, out$punif[iiter, ]) newcolor <- apply(p.foo < 0, 1, sum) + 1 newcolor[blab.count == 0] <- NA is.fixed <- blab %in% blab.fixed color.old <- as.vector(before[iiter, , ]) color.new <- newcolor[blab] color.new[is.fixed] <- color.old[is.fixed] my.after[iiter, , ] <- matrix(color.new, nrow, ncol) } all(unif.equals) all.equal(after, my.after) u <- c(as.vector(out$hunif), as.vector(out$vunif), as.vector(out$punif)) u <- u[u != -1] ks.test(x = u, y = "punif") alpha <- rep(0, ncolor) theta <- c(alpha, beta) out.too <- potts(out, param = theta, debug = FALSE) alpha <- rep(0.1, ncolor) theta <- c(alpha, beta) out.too.too <- potts(out, param = theta, debug = FALSE) all.equal(out.too$batch, out.too.too$batch)
expected <- TRUE test(id=939, code={ argv <- list(function (e1, e2) { ok <- switch(.Generic, "<" = , ">" = , "<=" = , ">=" = , "==" = , "!=" = TRUE, FALSE) if (!ok) { warning(sprintf("'%s' is not meaningful for ordered factors", .Generic)) return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2)))) } if (.Generic %in% c("==", "!=")) return(NextMethod(.Generic)) nas <- is.na(e1) | is.na(e2) ord1 <- FALSE ord2 <- FALSE if (nzchar(.Method[1L])) { l1 <- levels(e1) ord1 <- TRUE } if (nzchar(.Method[2L])) { l2 <- levels(e2) ord2 <- TRUE } if (all(nzchar(.Method)) && (length(l1) != length(l2) || !all(l2 == l1))) stop("level sets of factors are different") if (ord1 && ord2) { e1 <- as.integer(e1) e2 <- as.integer(e2) } else if (!ord1) { e1 <- match(e1, l2) e2 <- as.integer(e2) } else if (!ord2) { e2 <- match(e2, l1) e1 <- as.integer(e1) } value <- get(.Generic, mode = "function")(e1, e2) value[nas] <- NA value }) do.call('is.function', argv); }, o = expected);
generate_report_data_signatures_mp <- function(vcf_fname, pcgr_data, sample_name, pcgr_config, type_specific = T) { pcgrr:::log4r_info("------") pcgrr:::log4r_info(paste0("Identifying weighted contributions of reference ", "mutational signatures (COSMIC v3.2) using ", "MutationalPatterns")) assay <- tolower(pcgr_config$assay_props$type) pcg_report_signatures <- pcgrr::init_report(config = pcgr_config, class = "m_signature_mp") prevalent_site_signatures <- NULL if(type_specific == T){ prevalent_site_signatures <- pcgrr::get_prevalent_site_signatures( site = pcgr_config[["t_props"]][["tumor_type"]], pcgr_data = pcgr_data, incl_poss_artifacts = pcgr_config[["msigs"]][["include_artefact_signatures"]]) } if(type_specific == F){ prevalent_site_signatures <- pcgrr::get_prevalent_site_signatures( site = "Any", pcgr_data = pcgr_data, incl_poss_artifacts = pcgr_config[["msigs"]][["include_artefact_signatures"]]) } if(file.exists(vcf_fname)){ vcfs <- suppressWarnings( MutationalPatterns::read_vcfs_as_granges( vcf_files = vcf_fname, sample_names = sample_name, genome = pcgr_data[["assembly"]][["ref_genome"]], predefined_dbs_mbs = T), ) pcgrr:::log4r_info(paste0("Number of SNVs for signature analysis: ", length(vcfs[[1]]))) pcg_report_signatures[["eval"]] <- TRUE if (length(vcfs[[1]]) >= pcgr_config[["msigs"]][["mutation_limit"]]) { pcg_report_signatures[["variant_set"]][["all"]] <- data.frame('VAR_ID' = rownames(mcols(vcfs[[1]])), stringsAsFactors = F) %>% tidyr::separate(VAR_ID, c('CHROM', 'pos_ref_alt'), sep=":", remove = T) %>% tidyr::separate(pos_ref_alt, c("POS","ref_alt"), sep="_", remove = T) %>% tidyr::separate(ref_alt, c("REF","ALT"), sep = "/", remove = T) %>% dplyr::mutate(POS = as.integer(POS)) mut_mat <- MutationalPatterns::mut_matrix( vcf_list = vcfs, ref_genome = pcgr_data[["assembly"]][["ref_genome"]], extension = 1) mut_mat <- mut_mat + 0.0001 all_reference_signatures <- MutationalPatterns::get_known_signatures( muttype = "snv", genome = stringr::str_replace( pcgr_data[["assembly"]][["grch_name"]], "grc", "GRC" ), incl_poss_artifacts = pcgr_config[["msigs"]][["include_artefact_signatures"]] ) selected_sigs <- intersect( colnames(all_reference_signatures), unique(prevalent_site_signatures$aetiology$signature_id) ) selected_reference_signatures <- all_reference_signatures[, selected_sigs] fit_ref <- MutationalPatterns::fit_to_signatures(mut_mat, selected_reference_signatures) sim_original_reconstructed <- as.data.frame( MutationalPatterns::cos_sim_matrix( mut_mat, fit_ref[["reconstructed"]])) %>% magrittr::set_colnames("cosine_sim") %>% magrittr::set_rownames(NULL) tot <- as.data.frame( setNames(reshape2::melt(colSums(fit_ref[["contribution"]])), c("tot"))) %>% dplyr::mutate(sample_id = as.character(rownames(.))) %>% magrittr::set_rownames(NULL) contributions_per_signature <- as.data.frame(setNames(reshape2::melt(fit_ref[["contribution"]]), c("signature_id", "sample_id", "contribution_raw"))) %>% dplyr::mutate(signature_id = as.character(signature_id)) %>% dplyr::mutate(sample_id = as.character(sample_id)) %>% dplyr::left_join(tot, by = "sample_id") %>% dplyr::mutate(prop_signature = round(as.numeric(contribution_raw) / tot, digits = 3)) %>% dplyr::select(signature_id, sample_id, prop_signature) %>% dplyr::filter(prop_signature > 0) %>% dplyr::arrange(desc(prop_signature)) %>% dplyr::left_join( dplyr::select(pcgr_data[["mutational_signatures"]][["aetiologies"]], signature_id, aetiology, comments, aetiology_keyword), by = c("signature_id")) %>% dplyr::rename(group = aetiology_keyword) %>% dplyr::mutate( contribution = paste0(round(prop_signature * 100, digits = 2), "%")) %>% dplyr::distinct() contributions_per_group <- as.data.frame( contributions_per_signature %>% dplyr::group_by(group) %>% dplyr::summarise(prop_group = sum(prop_signature), signature_id_group = paste(signature_id, collapse=", "), .groups = "drop") ) cols <- contributions_per_group %>% dplyr::arrange(desc(prop_group)) %>% dplyr::select(group) %>% dplyr::distinct() color_vec <- head(pcgrr::color_palette[["tier"]][["values"]], nrow(cols)) names(color_vec) <- cols$group color_vec2 <- color_vec names(color_vec2) <- NULL cols <- cols %>% dplyr::mutate(col = color_vec2) contributions_per_signature <- contributions_per_signature %>% dplyr::left_join(cols, by = "group") contributions <- list() contributions[["per_group"]] <- contributions_per_group contributions[["per_signature"]] <- contributions_per_signature if(!is.null(prevalent_site_signatures$aetiology) & NROW(contributions[["per_signature"]]) > 0){ if("signature_id" %in% colnames(prevalent_site_signatures$aetiology)){ reference_sigs <- paste(sort(prevalent_site_signatures$aetiology$signature_id), collapse=",") tsv_data <- contributions[["per_signature"]] %>% pcgrr::remove_cols_from_df( cnames = c("contribution","col","aetiology","comments")) %>% dplyr::mutate( all_reference_signatures = !type_specific, tumor_type = pcgr_config[["t_props"]][["tumor_type"]], reference_collection = "COSMIC_v32", reference_signatures = reference_sigs, fitting_accuracy = round(sim_original_reconstructed$cosine_sim * 100, digits = 1)) } } vr <- vcfs[[sample_name]] GenomeInfoDb::seqlengths(vr) <- GenomeInfoDb::seqlengths(pcgr_data[["assembly"]][["bsg"]])[GenomeInfoDb::seqlevels(pcgr_data[["assembly"]][["bsg"]]) %in% unique(GenomeInfoDb::seqlevels(vr))] chromosomes <- head(GenomeInfoDb::seqnames(pcgr_data[["assembly"]][["bsg"]]), 24) pcg_report_signatures[["result"]][["vr"]] <- vr pcg_report_signatures[["result"]][["mut_mat"]] <- mut_mat pcg_report_signatures[["result"]][["chromosomes"]] <- chromosomes pcg_report_signatures[["result"]][["contributions"]] <- contributions pcg_report_signatures[["result"]][["tsv"]] <- tsv_data pcg_report_signatures[["result"]][["reference_data"]] <- prevalent_site_signatures$aetiology pcg_report_signatures[["result"]][["scale_fill_values"]] <- color_vec pcg_report_signatures[["result"]][["scale_fill_names"]] <- names(color_vec) pcg_report_signatures[["result"]][["goodness_of_fit"]] <- round(sim_original_reconstructed$cosine_sim * 100, digits = 1) }else{ pcg_report_signatures[["missing_data"]] <- TRUE if (length(vcfs[[1]]) > 0) { pcg_report_signatures[["variant_set"]][["all"]] <- as.data.frame(vcfs[[1]]) %>% dplyr::rename(POS = start, CHROM = seqnames) %>% dplyr::select(CHROM, POS, REF, ALT) %>% magrittr::set_rownames(NULL) pcgrr:::log4r_info( paste0("Too few SNVs (n = ", nrow(pcg_report_signatures[["variant_set"]][["all"]]), ") for reconstruction of mutational signatures by ", "MutationalPatterns, limit set to ", pcgr_config[["msigs"]][["mutation_limit"]])) } } } return(pcg_report_signatures) } get_prevalent_site_signatures <- function(site = "Any", custom_collection = NULL, pcgr_data = NULL, prevalence_pct = 5, incl_poss_artifacts = T) { if(is.null(custom_collection)){ pcgrr:::log4r_info(paste0( "Retrieving prevalent (prevalence >= ", prevalence_pct, " percent) reference signatures for ", site, ", using COSMIC v3.2 collection")) } pcgrr:::log4r_info(paste0( "Inclusion of mutational signature artefacts (e.g. sequencing artefacts): ", incl_poss_artifacts)) invisible( assertthat::assert_that( !is.null(pcgr_data[["mutational_signatures"]][["aetiologies"]]), msg = "Cannot load ref. aetiologies (COSMIC v3.2) of mutational signatures")) invisible( assertthat::assert_that( is.data.frame(pcgr_data[["mutational_signatures"]][["aetiologies"]]), msg = "Reference aetiologies must be of type data.frame()")) invisible( assertthat::assert_that( prevalence_pct == 0 | prevalence_pct == 2 | prevalence_pct == 5 | prevalence_pct == 10 | prevalence_pct == 15 | prevalence_pct == 20, msg = "Argument 'prevalence_pct' must be any of '0, 2, 5, 10, 15 or 20'")) valid_signature_ids <- unique(pcgr_data[["mutational_signatures"]][["aetiologies"]]$signature_id) signatures_prevalence <- data.frame() if(!is.null(custom_collection)){ invisible( assertthat::assert_that( is.character(custom_collection), msg = "Argument 'custom_collection' must be a character vector")) pcgrr:::log4r_info(paste0( "Retrieving reference signatures from COSMIC v3.2 collection based on user-defined collection (", paste(unique(custom_collection), collapse=", "), ")") ) i <- 1 while(i <= length(custom_collection)){ if(!(custom_collection[i] %in% valid_signature_ids)){ pcgrr:::log4r_warn(paste0("Could not find specified custom signature id '", custom_collection[i], "' in COSMIC v3.2 reference collection", " - ignoring")) } i <- i + 1 } signatures_prevalence <- pcgr_data[["mutational_signatures"]][["aetiologies"]] %>% dplyr::select(signature_id, aetiology_keyword, aetiology, associated_signatures, comments) %>% dplyr::filter(signature_id %in% custom_collection) %>% dplyr::distinct() }else{ unique_sites_with_signature_prevalence <- unique(pcgr_data[["mutational_signatures"]][["aetiologies"]][["primary_site"]]) if (!(site %in% unique_sites_with_signature_prevalence)) { pcgrr:::log4r_info( paste0("Primary tumor site '", site, "' ", "does not have any signatures with significant ", "prevalence - considering all")) signatures_prevalence <- pcgr_data[["mutational_signatures"]][["aetiologies"]] %>% dplyr::select(signature_id, aetiology_keyword, aetiology, associated_signatures, comments) %>% dplyr::distinct() }else{ signatures_prevalence <- pcgr_data[["mutational_signatures"]][["aetiologies"]] %>% dplyr::filter(primary_site == site) %>% dplyr::select(signature_id, primary_site, prevalence_pct, prevalence_above_5pct, prevalence_above_10pct, prevalence_above_15pct, prevalence_above_20pct, aetiology_keyword, aetiology, associated_signatures, comments) %>% dplyr::distinct() if (prevalence_pct > 0) { if (prevalence_pct == 5) { signatures_prevalence <- signatures_prevalence %>% dplyr::filter(prevalence_above_5pct == T | is.na(prevalence_above_5pct)) }else if (prevalence_pct == 10) { signatures_prevalence <- signatures_prevalence %>% dplyr::filter(prevalence_above_10pct == T | is.na(prevalence_above_10pct)) } else if (prevalence_pct == 15) { signatures_prevalence <- signatures_prevalence %>% dplyr::filter(prevalence_above_15pct == T | is.na(prevalence_above_15pct)) }else if (prevalence_pct == 20) { signatures_prevalence <- signatures_prevalence %>% dplyr::filter(prevalence_above_20pct == T | is.na(prevalence_above_20pct)) } } signatures_prevalence <- signatures_prevalence %>% dplyr::select(-c(primary_site, prevalence_above_5pct, prevalence_above_10pct, prevalence_above_15pct, prevalence_above_20pct)) %>% dplyr::distinct() %>% dplyr::arrange(desc(prevalence_pct)) %>% dplyr::select(-prevalence_pct) } } if(incl_poss_artifacts == F){ signatures_prevalence <- signatures_prevalence %>% dplyr::filter(!stringr::str_detect(aetiology_keyword,"artefact")) } signatures_prevalence <- signatures_prevalence %>% dplyr::distinct() sigs <- unique(signatures_prevalence$signature_id) pcgrr:::log4r_info(paste0("Limiting reference collection to signatures: ", paste(sigs, collapse = ", "))) result <- list("aetiology" = signatures_prevalence) return(result) } generate_report_data_rainfall <- function(variant_set, colors = NULL, autosomes = F, build = "grch37") { pcg_report_rainfall <- pcgrr::init_report(class = "rainfall") if(NROW(variant_set) == 0){ return(pcg_report_rainfall) } invisible(assertthat::assert_that (assertthat::is.flag(autosomes), msg = "Argument 'autosomes' should be TRUE/FALSE")) invisible(assertthat::assert_that( is.data.frame(variant_set), msg = paste0("Argument variant_set needs be of type data.frame"))) assertable::assert_colnames( variant_set, c("CHROM", "REF", "ALT", "POS", "VARIANT_CLASS"), only_colnames = F, quiet = T) invisible( assertthat::assert_that( build == "grch37" | build == "grch38", msg = paste0("Value for argument build ('", build, "') not allowed, available reference build values are:", "'grch37' or 'grch38'"))) pcgrr:::log4r_info("------") pcgrr:::log4r_info(paste0("Calculating data for rainfall plot")) sbs_types <- c("C>A", "C>G", "C>T", "T>A", "T>C", "T>G") if (is.null(colors)) { colors <- RColorBrewer::brewer.pal(6, "Dark2") }else{ invisible( assertthat::assert_that( length(colors) == 6, msg = "'colors' should be a character vector of six color codes")) } chr_prefix <- FALSE chromosome_names <- unique(variant_set[, "CHROM"]) for (m in chromosome_names) { if (startsWith(m, "chr")) { chr_prefix <- TRUE } } if (chr_prefix == F) { variant_set <- variant_set %>% dplyr::mutate(CHROM = paste0("chr", CHROM)) } dat <- dplyr::select(variant_set, CHROM, POS, REF, ALT, VARIANT_CLASS) %>% dplyr::filter(VARIANT_CLASS == "SNV") if (nrow(dat) < 10 | length(chromosome_names) < 2) { pcgrr:::log4r_info( paste0("Too few variants (< 10) and chromosomes ", " represented (< 2) - skipping rainfall plot")) pcg_report_rainfall[["eval"]] <- F }else{ dat <- dat %>% pcgrr::assign_mutation_type() %>% dplyr::mutate( MUTATION_TYPE = dplyr::if_else(stringr::str_detect(MUTATION_TYPE, "^C>"), stringr::str_replace(MUTATION_TYPE, ":[A-Z]>[A-Z]$", ""), as.character(MUTATION_TYPE))) %>% dplyr::mutate( MUTATION_TYPE = dplyr::if_else(stringr::str_detect(MUTATION_TYPE, "^A>"), stringr::str_replace(MUTATION_TYPE, "^[A-Z]>[A-Z]:", ""), as.character(MUTATION_TYPE))) %>% pcgrr::sort_chromosomal_segments() bsg <- BSgenome.Hsapiens.UCSC.hg19 chr_length <- head(GenomeInfoDb::seqlengths(bsg), 24) chromosomes <- head(GenomeInfoDb::seqnames(bsg), 24) if (build == "grch38") { bsg <- BSgenome.Hsapiens.UCSC.hg38 chr_length <- head(GenomeInfoDb::seqlengths(bsg), 24) } if (autosomes == T) { chr_length <- head(chr_length, 22) } chr_cum <- c(0, cumsum(as.numeric(chr_length))) names(chr_cum) <- names(chr_length) labels <- gsub("chr", "", names(chr_length)) m <- c() for (i in 2:length(chr_cum)) m <- c(m, (chr_cum[i - 1] + chr_cum[i]) / 2) type <- c() loc <- c() dist <- c() chrom <- c() for (i in 1:length(chromosomes)) { chr_subset <- dplyr::filter(dat, CHROM == chromosomes[i]) n <- nrow(chr_subset) if (n <= 1) { next } type <- c(type, chr_subset$MUTATION_TYPE[-1]) loc <- c(loc, (chr_subset$POS + chr_cum[i])[-1]) dist <- c(dist, diff(chr_subset$POS)) chrom <- c(chrom, rep(chromosomes[i], n - 1)) } invisible(assertthat::assert_that(length(type) == length(loc) & length(loc) == length(dist) & length(chrom) == length(dist), msg = "Length of type/loc/dist not identical")) data <- data.frame(type = type, location = loc, distance = dist, chromosome = chrom, stringsAsFactors = F) typesin <- sbs_types %in% sort(unique(data$type)) colors_selected <- colors[typesin] ylim <- 1e+09 pcg_report_rainfall[["eval"]] <- T pcg_report_rainfall[["rfdata"]] <- list("data" = data, "intercept" = m, "ylim" = ylim, "chr_cum" = chr_cum, "colors" = colors_selected, "labels" = labels, "cex" = 0.8, "cex_text" = 3) } return(pcg_report_rainfall) }
test_that("GraphqlClient client initialization works", { expect_is(GraphqlClient, "R6ClassGenerator") aa <- GraphqlClient$new() expect_is(aa, "GraphqlClient") expect_is(aa, "R6") expect_is(aa$.__enclos_env__, "environment") expect_is(aa$print, "function") expect_is(aa$ping, "function") expect_is(aa$load_schema, "function") expect_is(aa$dump_schema, "function") expect_is(aa$schema2json, "function") expect_is(aa$fragment, "function") expect_is(aa$exec, "function") expect_is(aa$prep_query, "function") expect_null(aa$url) expect_null(aa$headers) expect_null(aa$schema) expect_null(aa$result) expect_is(aa$fragments, "list") expect_equal(length(aa$fragments), 0) }) test_that("GraphqlClient construction works", { skip_on_cran() token <- Sys.getenv("GITHUB_TOKEN") aa <- GraphqlClient$new( url = "https://api.github.com/graphql", headers = list(Authorization = paste0("Bearer ", token)) ) expect_true(aa$ping()) qry <- Query$new() qry$query('repos', '{ viewer { repositories(last: 10, isFork: false, privacy: PUBLIC) { edges { node { isPrivate id name } } } } }') out <- aa$exec(qry$queries$repos) expect_is(out, "character") expect_match(out, "repositories") expect_match(out, "isPrivate") parsed <- jsonlite::fromJSON(out) expect_is(parsed, "list") expect_named(parsed, "data") expect_is(parsed$data$viewer$repositories$edges, "data.frame") }) test_that("GraphqlClient construction works with comments inside the query and inside fragment", { skip_on_cran() token <- Sys.getenv("GITHUB_TOKEN") aa <- GraphqlClient$new( url = "https://api.github.com/graphql", headers = list(Authorization = paste0("Bearer ", token)) ) expect_true(aa$ping()) frag <- Fragment$new() frag$fragment('ownerInfo', ' fragment on RepositoryOwner { id avatarUrl resourcePath url }') qry <- Query$new() qry$query('repos', '{ ghql: repository(owner: "ropensci", name: "ghql") { name owner { ...ownerInfo } } jsonlite: repository(owner: "jeroen", name: "jsonlite") { name owner { ...ownerInfo } } }') qry$add_fragment('repos', frag$fragments$ownerInfo) out <- aa$exec(qry$queries$repos) expect_is(out, "character") expect_match(out, "ghql") expect_match(out, "jsonlite") expect_match(out, "avatarUrl") parsed <- jsonlite::fromJSON(out) expect_is(parsed, "list") expect_named(parsed, "data") expect_is(parsed$data$ghql, "list") expect_is(parsed$data$jsonlite, "list") }) test_that("GraphqlClient class fails well", { expect_error(GraphqlClient$new(a = 5), "unused argument") rr <- GraphqlClient$new() expect_error(rr$fragment(), "argument \"name\" is missing") expect_error(rr$exec(), "argument \"query\" is missing") })
GCBellPol <- function(nv=c(),m=1,b=FALSE) { v<-MFB(nv,m); v<-MFB2Set( v ); for (j in 1:length(v)) { c <- as.character(v[[j]][2]); x <- v[[j]][3] ; i <- v[[j]][4] ; k <- strtoi(v[[j]][5]); if (x=="f") { vi<-unlist(strsplit(i,",",fixed=TRUE)); if (length(vi)==1) {x<-paste0("(y",ifelse(i==1,")", paste0("^",i,")")) );} else {x<-""; for (lvi in 1:length(vi)) if (vi[lvi]!="0") x<-paste0(x,"(y",lvi,ifelse(vi[lvi]=="1","",paste0("^",vi[lvi])),")"); } i<-""; } else if ( (m>1) && (b) ) {x<-"g"; } v[[j]][2] <- c; v[[j]][3] <- x; v[[j]][4] <- i; v[[j]][5] <- k; } Set2expr(v); }
textNormal = function(...) {textProperties( ... )} textBold = function(...) {textProperties( font.weight = "bold", ... )} textItalic = function( ... ) {textProperties( font.style = "italic", ... )} textBoldItalic = function( ... ) {textProperties( font.weight = "bold", font.style = "italic", ... )} parRight = function( ... ) {parProperties( text.align = "right", ... )} parLeft = function( ... ) {parProperties( text.align = "left", ... )} parCenter = function( ... ) {parProperties( text.align = "center", ... )} parJustify = function( ... ) {parProperties( text.align = "justify", ... )} borderDotted = function( ... ) {borderProperties( style="dotted", ... )} borderDashed = function( ... ) {borderProperties( style="dashed", ... )} borderNone = function( ... ) {borderProperties( style="none", ... )} borderSolid = function( ... ) {borderProperties( style = "solid", ... )} cellBorderNone = function( ... ) { cellProperties( border.left = borderNone(), border.top = borderNone(), border.bottom = borderNone(), border.right = borderNone(), ... ) } cellBorderBottom = function( ... ) { cellProperties( border.left = borderNone(), border.top = borderNone(), border.bottom = borderSolid(), border.right = borderNone(), ... ) } cellBorderTop = function( ... ) { cellProperties( border.left = borderNone(), border.top = borderSolid(), border.bottom = borderNone(), border.right = borderNone(), ... ) } cellBorderTB = function( ... ) { cellProperties( border.left = borderNone(), border.top = borderSolid(), border.bottom = borderSolid(), border.right = borderNone(), ... ) }
knitr::opts_chunk$set(echo = TRUE, fig.align = "center") load("../data/cjs.rda") load("../data/cjs_no_rho.rda") postpack::post_dim(cjs) postpack::get_params(cjs, type = "base_index")
prior_terminal_node_coef <- function(range = c(0, 1), trans = NULL) { new_quant_param( type = "double", range = range, inclusive = c(FALSE, TRUE), trans = trans, default = 0.95, label = c(prior_terminal_node_coef = "Terminal Node Prior Coefficient"), finalize = NULL ) } prior_terminal_node_expo <- function(range = c(0, 3), trans = NULL) { new_quant_param( type = "double", range = range, inclusive = c(TRUE, TRUE), trans = trans, default = 2.0, label = c(prior_terminal_node_expo = "Terminal Node Prior Exponent"), finalize = NULL ) } prior_outcome_range <- function(range = c(0, 5), trans = NULL) { new_quant_param( type = "double", range = range, inclusive = c(FALSE, TRUE), trans = trans, default = 2.0, label = c(prior_outcome_range = "Prior for Outcome Range"), finalize = NULL ) }
set.varitas.options <- function(...) { updated.options <- get.varitas.options(); options.to.add <- list(...); if( any( grepl('^filters.default', names(options.to.add) )) ) { error.message <- paste( 'Currently cannot set default filters with set.varitas.options.', 'Please use overwrite.varitas.options instead' ); stop( error.message ); } if( 'mode' %in% names(options.to.add) ) { option.value <- tolower( options.to.add[[ 'mode' ]] ); if( !( option.value %in% c('ctdna', 'tumour') ) ) { stop('mode must be either ctDNA or tumour'); } warning.message <- paste( 'Setting mode to', option.value, '- overwriting any previous filters' ); warning( warning.message ); mode.default.file <- system.file( paste0(option.value, '_defaults.yaml'), package = get.varitas.options('pkgname') ); mode.defaults <- yaml::yaml.load_file( mode.default.file ); for(setting.name in names(mode.defaults) ) { updated.options <- add.option( name = setting.name, value = mode.defaults[[ setting.name ]], old.options = updated.options ); } options.to.add <- options.to.add[ 'mode' != names(options.to.add) ]; } for( i in seq_along(options.to.add) ) { option.name <- names(options.to.add)[i]; option.value <- options.to.add[[i]]; updated.options <- add.option( name = option.name, value = option.value, old.options = updated.options ); } options(varitas = updated.options); }
influence.sglg <- function(model, ...) { epsil <- model$rord if (model$censored == FALSE) { if (model$Knot == 0) Xbar <- model$X if (model$Knot > 0) Xbar <- model$N n <- dim(Xbar)[1] q <- dim(Xbar)[2] plot1 <- ggplot() plot2 <- ggplot() plot3 <- ggplot() plot4 <- ggplot() cweight <- function(model) { Delt_gammas <- matrix(0, q, n) for (i in 1:q) { Delt_gammas[i, ] <- Xbar[, i] * (-(1/(model$sigma * model$lambda)) * (1 - exp(model$lambda * epsil))) } Delt_sw <- -(1/model$sigma) - (1/model$sigma * model$lambda) * epsil + (1/model$sigma * model$lambda) * epsil * exp(model$lambda * epsil) Delt_lw <- (1/model$lambda) + (2/model$lambda^3) * digamma(1/model$lambda^2) - (2/model$lambda^3) + 2 * log(model$lambda^2)/model$lambda^3 - (1/model$lambda^2) * epsil + (2/model$lambda^3) * exp(model$lambda * epsil) - (1/model$lambda^2) * epsil * exp(model$lambda * epsil) Delta <- Delt_gammas Delta <- rbind(Delta, t(Delt_sw)) Delta <- rbind(Delta, t(Delt_lw)) NC = t(Delta) %*% model$Itheta %*% Delta norm = sqrt(sum(diag(t(NC) %*% NC))) CNC = NC/norm Eigen = eigen(CNC) Cmax <- Eigen$vectors[, 1] dCNC = diag(CNC) vls1 <- abs(Cmax) df1 <- as.data.frame(vls1) plot1 <- ggplot(data=df1,aes(1:n,vls1)) + geom_point(colour="orange",alpha=0.5) + ggtitle("Case-weight perturbation") + xlab("Index") + ylab("Local Influence") vls2 <- dCNC df2 <- as.data.frame(vls2) plot2 <- ggplot(data=df2,aes(1:n,vls2)) + geom_point(colour="orange",alpha=0.5) + ggtitle("Case-weight perturbation") + xlab("Index") + ylab("Total Local Influence") return(list(plot1=plot1,plot2=plot2)) } respert <- function(model) { D = function(epsilon, lambd) { w <- as.vector(exp(lambd * epsilon)) D_eps <- diag(w, n, n) return(D_eps) } Ds <- D(epsil, model$lambda) Delt_gammas <- (1/model$sigma^2) * t(Xbar) %*% Ds Delt_sw <- (1/model$sigma * model$lambda^2) * (Ds %*% (model$lambda * epsil + 1) - 1) Delt_lw <- (1/model$sigma * (model$lambda^2)) * (-1 + Ds %*% (1 - model$lambda * epsil)) Delta <- Delt_gammas Delta <- rbind(Delta, t(Delt_sw)) Delta <- rbind(Delta, t(Delt_lw)) NC = t(Delta) %*% model$Itheta %*% Delta norm = sqrt(sum(diag(t(NC) %*% NC))) CNC = NC/norm Eigen = eigen(CNC) Cmax = Eigen$vectors[, 1] dCNC = diag(CNC) vls3 <- abs(Cmax) df3 <- as.data.frame(vls3) plot3 <- ggplot(data=df3,aes(1:n,vls3)) + geom_point(colour="orange",alpha=0.5) + ggtitle("Response Perturbation") + xlab("Index") + ylab("Local Influence") vls4 <- dCNC df4 <- as.data.frame(vls4) plot4 <- ggplot(data=df4,aes(1:n,vls4)) + geom_point(colour="orange",alpha=0.5) + ggtitle("Response Perturbation") + xlab("Index") + ylab("Total Local Influence") return(list(plot3=plot3,plot4=plot4)) } plots_cw <- cweight(model) plots_r <- respert(model) grid.arrange(plots_cw$plot1, plots_cw$plot2, plots_r$plot3, plots_r$plot4, ncol=2) } if (model$censored == TRUE) { delta <- model$delta cweight <- function(model) { X_bar <- model$X_bar n <- model$size qs <- dim(X_bar)[2] aaa <- (1/model$lambda^2) * exp(model$lambda * epsil) S <- pgamma((1/model$lambda^2) * exp(model$lambda * epsil), 1/model$lambda^2, lower.tail = FALSE) bb <- (aaa^(1/model$lambda^2) * exp(-aaa))/(gamma(1/model$lambda^2) * S) Delt_gsw <- matrix(0, qs, n) for (j in 1:qs) { Delt_gsw[j, ] = X_bar[, j] * ((1 - delta) * (1/(model$lambda * model$sigma)) * (exp(model$lambda * epsil) - 1) + delta * (model$lambda/model$sigma) * bb) } part1 <- (1/model$sigma) * (-1 - (1/model$lambda) * (epsil - epsil * exp(model$lambda * epsil))) part2 <- (model$lambda/model$sigma) * epsil * bb Delt_sw <- (1 - delta) * part1 + delta * part2 Delt_sw <- t(as.matrix(Delt_sw)) Delta <- Delt_gsw Delta <- rbind(Delta, Delt_sw) NC = t(Delta) %*% model$Itheta %*% Delta norm = sqrt(sum(diag(t(NC) %*% NC))) CNC = NC/norm Eigen = eigen(CNC) Cmax <- Eigen$vectors[, 1] lci <- abs(Cmax) plot(1:n, lci, xlab = "Index", ylab = "e_max_i", main = "Case-weight perturbation", pch = 20) pinfp <- order(lci)[(n - 1):n] text(pinfp, lci[pinfp], label = as.character(pinfp), cex = 0.7, pos = 4) dCNC = diag(CNC) plot(1:n, dCNC, xlab = "Index", ylab = "B_i", main = "Case-weight perturbation", pch = 20) pinfp <- order(dCNC)[(n - 1):n] text(pinfp, dCNC[pinfp], label = as.character(pinfp), cex = 0.7, pos = 4) } respert <- function(model) { X <- model$X n <- dim(X)[1] p <- dim(X)[2] sigma <- model$sigma lambda <- model$lambda w <- as.vector(exp(lambda * epsil)) Ds <- diag(w, n) aaa = (1/lambda^2) * exp(lambda * epsil) S = pgamma((1/lambda^2) * exp(lambda * epsil), 1/lambda^2, lower.tail = FALSE) bb = (aaa^(1/lambda^2) * exp(-aaa))/(gamma(1/lambda^2) * S) Delt_bw <- matrix(0, p, n) for (j in 1:p) { Delt_bw[j, ] = X[, j] * ((1 - delta) * (1/sigma^2) * exp(lambda * epsil) + delta * (-(lambda/sigma)^2) * bb * (aaa - 1/lambda^2 - bb)) } Delt_sw <- (1/sigma * lambda^2) * (Ds %*% (lambda * epsil + 1) - 1) expep <- exp(lambda * epsil) Delt_sw <- (1 - delta) * (1/(lambda * (sigma^2))) * (-1 + expep + lambda * epsil * expep) + delta * ((((lambda/sigma)^2) * bb) * (-1/lambda + epsil * (aaa - 1/lambda^2 - bb))) Delt_sw <- t(as.matrix(Delt_sw)) Delta <- Delt_bw Delta <- rbind(Delta, Delt_sw) NC = t(Delta) %*% model$Itheta %*% Delta norm = sqrt(sum(diag(t(NC) %*% NC))) CNC = NC/norm Eigen = eigen(CNC) Cmax = Eigen$vectors[, 1] plot(1:n, abs(Cmax), xlab = "Index", ylab = "Local influence", main = "Response perturbation", pch = 20) dCNC = diag(CNC) plot(1:n, dCNC, xlab = "Index", ylab = "Total local influence", main = "Response perturbation", pch = 20) } } }
util_set_sQuoteString <- function(string) { old <- options(useFancyQuotes = FALSE) on.exit(options(old)) sQuote(string) }
if(1==99 && .Machine$sizeof.pointer != 4){ library(ctsem) library(testthat) set.seed(1) context("nonlinearcheck") test_that("simplenonlinearcheck", { sunspots<-sunspot.year sunspots<-sunspots[50: (length(sunspots) - (1988-1924))] id <- 1 time <- 1749:1924 datalong <- cbind(id, time, sunspots) ssmodel <- ctModel(type='stanct', n.latent=2, n.manifest=1, manifestNames='sunspots', latentNames=c('ss_level', 'ss_velocity'), LAMBDA=matrix(c( 1, 'ma1|log1p(exp(param))'), nrow=1, ncol=2), DRIFT=matrix(c(0, 'a21|-log1p(exp(param))', 1, 'a22'), nrow=2, ncol=2), TDPREDEFFECT=matrix(c('tdeffect',0),2), MANIFESTMEANS=matrix(c('mm|param*10+44'), nrow=1, ncol=1), MANIFESTVAR=diag(0,1), T0VAR=matrix(c(1,0,0,1), nrow=2, ncol=2), DIFFUSION=matrix(c(0, 0, 0, 'diff'), ncol=2, nrow=2)) TD1 <- 0 datalong <- cbind(datalong,TD1) datalong[seq(10,150,10),'TD1'] = 1 ssfitnl <- ctStanFit(datalong, ssmodel, iter=300, cores=1,optimize=T,verbose=0,maxtimestep = .3, nopriors=F,deoptim=FALSE) ssfitl <- ctStanFit(datalong, ssmodel, iter=300, chains=1,optimize=T,verbose=0,nopriors=F) ssfitnlm <- ctStanFit(datalong, ssmodel, iter=300, chains=1,optimize=T,verbose=0,maxtimestep = 2,fit=T,nopriors=F) expect_equal(ssfitnl$stanfit$rawest,ssfitl$stanfit$rawest,tol=1e-2) expect_equal(ssfitnl$stanfit$rawest,ssfitnlm$stanfit$rawest,tol=1e-2) expect_equal(ssfitnl$stanfit$optimfit$value,ssfitnlm$stanfit$optimfit$value,tol=1e-2) expect_equal(ssfitnl$stanfit$optimfit$value,ssfitl$stanfit$optimfit$value,tol=1e-2) cbind(ssfitnl$stanfit$rawest,ssfitl$stanfit$rawest,ssfitnlm$stanfit$rawest) c(ssfitnl$stanfit$optimfit$value,ssfitl$stanfit$optimfit$value,ssfitnlm$stanfit$optimfit$value) }) }
spatialIC <- function( L, R, y, xcov, IC, scale.designX, scaled, area, binary, I, C, nn, order, knots, grids, a_eta, b_eta, a_ga, b_ga, a_lamb, b_lamb, beta_iter, phi_iter, beta_cand, beta_sig0, x_user, total, burnin, thin, conf.int, seed){ Ispline<-function(x,order,knots){ k=order+1 m=length(knots) n=m-2+k t=c(rep(1,k)*knots[1], knots[2:(m-1)], rep(1,k)*knots[m]) yy1=array(rep(0,(n+k-1)*length(x)),dim=c(n+k-1, length(x))) for (l in k:n){ yy1[l,]=(x>=t[l] & x<t[l+1])/(t[l+1]-t[l]) } yytem1=yy1 for (ii in 1:order){ yytem2=array(rep(0,(n+k-1-ii)*length(x)),dim=c(n+k-1-ii, length(x))) for (i in (k-ii):n){ yytem2[i,]=(ii+1)*((x-t[i])*yytem1[i,]+(t[i+ii+1]-x)*yytem1[i+1,])/(t[i+ii+1]-t[i])/ii } yytem1=yytem2 } index=rep(0,length(x)) for (i in 1:length(x)){ index[i]=sum(t<=x[i]) } yy=array(rep(0,(n-1)*length(x)),dim=c(n-1,length(x))) if (order==1){ for (i in 2:n){ yy[i-1,]=(i<index-order+1)+(i==index)*(t[i+order+1]-t[i])*yytem2[i,]/(order+1) } }else{ for (j in 1:length(x)){ for (i in 2:n){ if (i<(index[j]-order+1)){ yy[i-1,j]=1 }else if ((i<=index[j]) && (i>=(index[j]-order+1))){ yy[i-1,j]=(t[(i+order+1):(index[j]+order+1)]-t[i:index[j]])%*%yytem2[i:index[j],j]/(order+1) }else{ yy[i-1,j]=0 } } } } return(yy) } Mspline<-function(x,order,knots){ k1=order m=length(knots) n1=m-2+k1 t1=c(rep(1,k1)*knots[1], knots[2:(m-1)], rep(1,k1)*knots[m]) tem1=array(rep(0,(n1+k1-1)*length(x)),dim=c(n1+k1-1, length(x))) for (l in k1:n1){ tem1[l,]=(x>=t1[l] & x<t1[l+1])/(t1[l+1]-t1[l]) } if (order==1){ mbases=tem1 }else{ mbases=tem1 for (ii in 1:(order-1)){ tem=array(rep(0,(n1+k1-1-ii)*length(x)),dim=c(n1+k1-1-ii, length(x))) for (i in (k1-ii):n1){ tem[i,]=(ii+1)*((x-t1[i])*mbases[i,]+(t1[i+ii+1]-x)*mbases[i+1,])/(t1[i+ii+1]-t1[i])/ii } mbases=tem } } return(mbases) } poissrndpositive<-function(lambda){ q=200 t=seq(0,q,1) p=dpois(t,lambda) pp=cumsum(p[2:(q+1)])/(1-p[1]) u=runif(1) while(u>pp[q]){ q=q+1 pp[q]=pp[q-1]+dpois(q,lambda)/(1-p[1]) } ll=sum(u>pp)+1 } set.seed(seed) L=matrix(L,ncol=1) R=matrix(R,ncol=1) y=matrix(y,ncol=1) xcov=as.matrix(xcov) IC=matrix(IC,ncol=1) p=ncol(xcov) N=nrow(L) if (scale.designX==TRUE){ mean_X<-apply(xcov,2,mean) sd_X<-apply(xcov,2,sd) for (r in 1:p){ if (scaled[r]==1) xcov[,r]<-(xcov[,r]-mean_X[r])/sd_X[r] } } K=length(knots)-2+order kgrids=length(grids) bisL=Ispline(L,order,knots) bisR=Ispline(R,order,knots) bisg=Ispline(grids,order,knots) eta=rgamma(1,a_eta,rate=b_eta) lamb=rgamma(1,a_lamb,rate=b_lamb) gamcoef=matrix(rgamma(K, 1, rate=1),ncol=K) phicoef<-matrix(rep(0,I),ncol=1) phicoef2<-matrix(rep(0,N),ncol=1) for (j in 1:N){ phicoef2[j]<-phicoef[area[j]] } beta=matrix(rep(0,p),p,1) beta_original=matrix(rep(0,p),ncol=1) LambdatL=t(gamcoef%*%bisL) LambdatR=t(gamcoef%*%bisR) Lambdatg=t(gamcoef%*%bisg) parbeta=array(rep(0,total*p),dim=c(total,p)) parbeta_original=array(rep(0,total*p),dim=c(total,p)) pareta=array(rep(0,total),dim=c(total,1)) parlamb=array(rep(0,total),dim=c(total,1)) parphi=array(rep(0,total*I),dim=c(total,I)) pargam=array(rep(0,total*K),dim=c(total,K)) parsurv0=array(rep(0,total*kgrids),dim=c(total,kgrids)) parLambdatL=array(rep(0,total*N),dim=c(total,N)) parLambdatR=array(rep(0,total*N),dim=c(total,N)) pardev=array(rep(0,total),dim=c(total,1)) parfinv=array(rep(0,total*N),dim=c(total,N)) if (is.null(x_user)){parsurv=parsurv0} else { G<-length(x_user)/p parsurv=array(rep(0,total*kgrids*G),dim=c(total,kgrids*G))} iter=1 while (iter<total+1) { z=array(rep(0,N),dim=c(N,1)); w=z zz=array(rep(0,N*K),dim=c(N,K)); ww=zz for (j in 1:N){ if (y[j]==0){ templam1=LambdatR[j]*exp(xcov[j,]%*%beta+phicoef[area[j]]) z[j]=poissrndpositive(templam1) zz[j,]=rmultinom(1,z[j],gamcoef*t(bisR[,j])) } else if (y[j]==1){ templam1=(LambdatR[j]-LambdatL[j])*exp(xcov[j,]%*%beta+phicoef[area[j]]) w[j]=poissrndpositive(templam1) ww[j,]=rmultinom(1,w[j],gamcoef*t(bisR[,j]-bisL[,j])) } } te1=z*(y==0)+w*(y==1) te2=(LambdatR*(y==0)+LambdatR*(y==1)+LambdatL*(y==2)) for (r in 1:p){ if (binary[r]==0){ beta1<-beta2<-beta if (iter<beta_iter) sd_cand<-beta_cand[r] else sd_cand<-sd(parbeta[1:(iter-1),r]) xt<-beta[r] yt<-rnorm(1,xt,sd_cand) beta1[r]<-yt beta2[r]<-xt log_f1<-sum(yt*xcov[,r]*te1)-sum(exp(xcov%*%beta1+phicoef2)*te2)-0.5*(yt^2)/(beta_sig0^2) log_f2<-sum(xt*xcov[,r]*te1)-sum(exp(xcov%*%beta2+phicoef2)*te2)-0.5*(xt^2)/(beta_sig0^2) num<-log_f1 den<-log_f2 if (log(runif(1))<(num-den)) beta[r]<-yt else beta[r]<-xt } if (binary[r]==1 & p>1){ te4=sum(xcov[,r]*te1) te5=sum(te2*exp(as.matrix(xcov[,-r])%*%as.matrix(beta[-r])+phicoef2)*xcov[,r]) beta[r]<-log(rgamma(1,a_ga+te4,rate=b_ga+te5)) } if (binary[r]==1 & p==1){ te4=sum(xcov[,r]*te1) te5=sum(te2*exp(phicoef2)*xcov[,r]) beta[r]<-log(rgamma(1,a_ga+te4,rate=b_ga+te5)) } } if (scale.designX==TRUE){ for (r in 1:p) beta_original[r]<-ifelse(scaled[r]==1,beta[r]/sd_X[r],beta[r]) } if (scale.designX==FALSE) beta_original<-beta for (l in 1:K){ tempa=1+sum(zz[,l]*(y==0)+ww[,l]*(y==1)) tempb=eta+sum(((bisR[l,])*(y==0)+(bisR[l,])*(y==1) +(bisL[l,])*(y==2))*exp(xcov%*%beta+phicoef2)) gamcoef[l]=rgamma(1,tempa,rate=tempb) } LambdatL=t(gamcoef%*%bisL) LambdatR=t(gamcoef%*%bisR) eta=rgamma(1,a_eta+K, rate=b_eta+sum(gamcoef)) phi1<-array(rep(0,N),dim=c(N,1)) phi2<-array(rep(0,N),dim=c(N,1)) for (i in 1:I){ phi1<-phi2<-phicoef2 if (iter<phi_iter) sd_cand<-sqrt(1/nn[i]) else sd_cand<-sd(parphi[1:(iter-1),i]) xt<-phicoef[i] yt<-rnorm(1,xt,sd_cand) phi1[area==i]<-yt phi2[area==i]<-xt log_f1<-sum(phi1*te1)-sum((exp(xcov%*%beta+phi1))*te2)-0.5*nn[i]*lamb*(yt-C[i,]%*%phicoef/nn[i])^2 log_f2<-sum(phi2*te1)-sum((exp(xcov%*%beta+phi2))*te2)-0.5*nn[i]*lamb*(xt-C[i,]%*%phicoef/nn[i])^2 num<-log_f1 den<-log_f2 if (log(runif(1))<(num-den)) phicoef[i]<-yt else phicoef[i]<-xt phicoef<-phicoef-mean(phicoef) phicoef2[area==i]<-phicoef[i] } A<-matrix(rep(0,I*I),nrow=I,byrow=TRUE) for (i in 1:I){ for (j in 1:I){ A[i,j]<-(phicoef[i]-phicoef[j])^2*C[i,j]*as.numeric(i < j) } } lamb<-rgamma(1,0.5*(I-1)+a_lamb,rate=0.5*sum(A)+b_lamb) FL<-1-exp(-LambdatL*exp(xcov%*%beta+phicoef2)) FR<-1-exp(-LambdatR*exp(xcov%*%beta+phicoef2)) f_iter<-(FR^(y==0))*((FR-FL)^(y==1))*((1-FL)^(y==2)) finv_iter<-1/f_iter loglike<-sum(log(FR^(y==0))+log((FR-FL)^(y==1))+log((1-FL)^(y==2))) dev<--2*loglike parbeta[iter,]=beta parbeta_original[iter,]=beta_original pareta[iter]=eta parlamb[iter]=lamb parphi[iter,]=phicoef pargam[iter,]=gamcoef ttt=gamcoef%*%bisg parsurv0[iter,]=exp(-ttt) if (scale.designX==FALSE) {parsurv0[iter,]<-exp(-ttt)} if (scale.designX==TRUE) {parsurv0[iter,]<-exp(-ttt*exp(-sum((beta*mean_X/sd_X)[scaled==1])))} parLambdatL[iter,]=LambdatL parLambdatR[iter,]=LambdatR pardev[iter]=dev parfinv[iter,]=finv_iter if (is.null(x_user)){parsurv[iter,]=parsurv0[iter,]} else { A<-matrix(x_user,byrow=TRUE,ncol=p) if (scale.designX==TRUE){ for (r in 1:p){ if (scaled[r]==1) A[,r]<-(A[,r]-mean_X[r])/sd_X[r]} } B<-exp(A%*%beta) for (g in 1:G){ parsurv[iter,((g-1)*kgrids+1):(g*kgrids)]=exp(-ttt*B[g,1])} } iter=iter+1 if (iter%%100==0) print(iter) } wbeta=as.matrix(parbeta_original[seq((burnin+thin),total,by=thin),],ncol=p) wparsurv0=as.matrix(parsurv0[seq((burnin+thin),total,by=thin),],ncol=kgrids) wparsurv=as.matrix(parsurv[seq((burnin+thin),total,by=thin),],ncol=kgrids*G) coef<-apply(wbeta,2,mean) coef_ssd<-apply(wbeta,2,sd) coef_ci<-array(rep(0,p*2),dim=c(p,2)) S0_m<-apply(wparsurv0,2,mean) S_m<- apply(wparsurv,2,mean) colnames(coef_ci)<-c(paste(100*(1-conf.int)/2,"%CI"),paste(100*(0.5+conf.int/2),"%CI")) for (r in 1:p) coef_ci[r,]<-quantile(wbeta[,r],c((1-conf.int)/2,0.5+conf.int/2)) CPO=1/apply(parfinv[seq((burnin+thin),total,by=thin),],2,mean) NLLK=-sum(log(CPO)) LambdatL_m<-apply(parLambdatL[seq((burnin+thin),total,by=thin),],2,mean) LambdatR_m<-apply(parLambdatR[seq((burnin+thin),total,by=thin),],2,mean) beta_m<-apply(as.matrix(parbeta[seq((burnin+thin),total,by=thin),]),2,mean) phicoef_m<-apply(parphi[seq((burnin+thin),total,by=thin),],2,mean) phicoef2_m<-array(rep(0,N),dim=c(N,1)) for (j in 1:N){ phicoef2_m[j]<-phicoef_m[area[j]] } FL_m<-1-exp(-LambdatL_m*exp(as.matrix(xcov)%*%as.matrix(beta_m)+phicoef2_m)) FR_m<-1-exp(-LambdatR_m*exp(as.matrix(xcov)%*%as.matrix(beta_m)+phicoef2_m)) loglike_m<-sum(log(FR_m^(y==0))+log((FR_m-FL_m)^(y==1))+log((1-FL_m)^(y==2))) D_thetabar<--2*loglike_m D_bar=mean(pardev[seq((burnin+thin),total,by=thin)]) DIC=2*D_bar-D_thetabar est<-list( N=nrow(xcov), nameX=colnames(xcov), parbeta=parbeta_original, parsurv0=parsurv0, parsurv=parsurv, parphi=parphi, parlamb=parlamb, coef = coef, coef_ssd = coef_ssd, coef_ci = coef_ci, S0_m = S0_m, S_m = S_m, grids=grids, DIC = DIC, NLLK = NLLK ) est }
test_that("mpm_standardize works correctly", { repro_stages <- apply(mat_f_inter, 2, function(x) any(x > 0)) matrix_stages <- c('prop', 'active', 'active', 'active', 'active') x1 <- mpm_standardize(mat_u_inter, mat_f_inter, repro_stages = repro_stages, matrix_stages = matrix_stages) expect_type(x1, "list") expect_length(x1, 4) expect_equal(ncol(x1$matA), 4) x2 <- mpm_standardise(mat_u_inter, mat_f_inter, repro_stages = repro_stages, matrix_stages = matrix_stages) expect_identical(x1, x2) })
solveMinBoundsCalib <- function(Xs, d, total, q=NULL, maxIter=500, calibTolerance=1e-06, description=TRUE) { if (!requireNamespace("Rglpk", quietly = TRUE) || !requireNamespace("slam", quietly = TRUE)) { stop("Package Rglpk needed for this function to work. Please install it.", call. = FALSE) } n <- length(d) oneN <- rep(1,n) zeroN <- rep(0,n) IdentityN <- diag(1,n) B <- t(diag(d) %*% Xs) a <- c(0,1,rep(0,n)) A1 <- rbind( cbind(-oneN,-oneN,IdentityN) , cbind(-oneN,oneN,IdentityN) ) b1 <- rep(0,2*n) A3 <- matrix(cbind(rep(0,nrow(B)+1),rep(0,nrow(B)+1),rbind(B,zeroN)), ncol= n+2, nrow= nrow(B)+1) b3 <- c(total,0) Amat <- rbind(A1,A3) bvec <- c(b1,b3) const <- c(rep("<=",n), rep(">=",n), rep("==", length(b3))) Amat_sparse <- slam::as.simple_triplet_matrix(Amat) simplexSolution <- Rglpk::Rglpk_solve_LP(obj=a, mat=Amat_sparse, dir=const, rhs=bvec) xSol <- simplexSolution$solution center <- xSol[1] minBounds <- xSol[2] gSol <- xSol[3:(n+2)] wSol <- gSol * d if(description) { writeLines("Solution found for calibration on minimal bounds:") writeLines(paste("L =",min(gSol))) writeLines(paste("U =",max(gSol))) } return(gSol) } minBoundsCalib <- function(Xs, d, total, q=NULL, maxIter=500, calibTolerance=1e-06, description=TRUE, precisionBounds=1e-4, forceSimplex=FALSE, forceBisection=FALSE) { usedSimplex <- FALSE if( ( forceSimplex || (nrow(Xs)*ncol(Xs)) <= 1e8 ) && !forceBisection) { gSol <- solveMinBoundsCalib(Xs, d, total, q, maxIter, calibTolerance, description) usedSimplex <- TRUE Lmax <- min(gSol) Umin <- max(gSol) maxIter <- 5000 } else { Lmax <- 1.0 Umin <- 1.0 } digitsPrec <- abs(log(precisionBounds,10)) Ltest1 <- round(Lmax - 5*10**(-digitsPrec-1),digitsPrec) Utest1 <- round(Umin + 5*10**(-digitsPrec-1),digitsPrec) Ltest <- Ltest1 Utest <- Utest1 gFinal <- calib(Xs=Xs, d=d, total=total, method="logit", bounds = c(Ltest,Utest), maxIter=maxIter, calibTolerance=calibTolerance) if(is.null(gFinal)) { gTestMin <- calib(Xs=Xs, d=d, total=total, method="linear", maxIter=maxIter, calibTolerance=calibTolerance) Llinear <- min(gTestMin) Ulinear <- max(gTestMin) if(!usedSimplex) { distTo1 <- pmax((1-Llinear), (Ulinear-1)) LtestMin <- 1-distTo1 LtestMax <- 1+distTo1 } else { LtestMin <- Llinear LtestMax <- Ulinear } method <- "logit" return(bisectMinBounds(c(LtestMin,LtestMax),c(Ltest1,Utest1),gTestMin, Xs,d,total, method,maxIter, calibTolerance, precisionBounds, description)) Ltest <- Ltest1 Utest <- Utest1 } return(gFinal) } bisectMinBounds <- function(convergentBounds,minBounds,gFinalSauv, Xs,d,total, method,maxIter, calibTolerance, precisionBounds, description=TRUE) { newBounds <- (minBounds + convergentBounds) / 2 Ltest <- newBounds[1] Utest <- newBounds[2] if(description) { writeLines(paste("------ Bisection search : ",newBounds[1],";",newBounds[2])) } gFinal <- calib(Xs=Xs, d=d, total=total, method="logit", bounds = c(Ltest,Utest), maxIter=maxIter, calibTolerance=calibTolerance) if(is.null(gFinal)) { return( bisectMinBounds(convergentBounds,c(Ltest,Utest),gFinalSauv, Xs,d,total, method,maxIter, calibTolerance, precisionBounds, description) ) } else { if( all(abs(c( (max(gFinal) - max(gFinalSauv)) , (min(gFinal) - min(gFinalSauv)))) <= c(precisionBounds,precisionBounds)) ) { return(gFinal) } else { return( bisectMinBounds(c(Ltest,Utest),minBounds,gFinal, Xs,d,total, method,maxIter, calibTolerance, precisionBounds, description) ) } } }
contributionByLevel<-function(da.object, fit.functions=NULL) { checkDominanceAnalysis(da.object) if(is.null(fit.functions)) { fit.functions=da.object$fit.functions } out<-da.object$contribution.by.level[fit.functions] out<-lapply(out,function(xx) { names(xx)<-replaceTermsInString(names(xx),da.object$terms) xx }) class(out)<-c("daContributionByLevel","list") out } print.daContributionByLevel<-function(x,...) { cat("\nContribution by level\n") for(fit in names(x)) { cat("* Fit index: ", fit,"\n") print(round(x[[fit]],3),na.print = "",row.names=F) } invisible(x) }
if(interactive()){ data(mstData) data(crtData) outputSRTBoot <- srtFREQ(Posttest~ Intervention + Prettest, intervention = "Intervention",nBoot=1000, data = mstData) plot(outputSRTBoot,group=1) outputSRTPerm <- srtFREQ(Posttest~ Intervention + Prettest, intervention = "Intervention",nPerm=1000, data = mstData) plot(outputSRTPerm,group=1) outputMST <- mstFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", data = mstData) plot(outputMST) outputMSTBoot <- mstFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", nBoot = 1000, data = mstData) plot(outputMSTBoot) plot(outputMSTBoot,group=1) outputMSTPerm <- mstFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", nPerm = 1000, data = mstData) plot(outputMSTPerm) plot(outputMSTPerm,group=1) outputCRT <- crtFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", data = crtData) plot(outputCRT) outputCRTBoot <- crtFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", nBoot = 1000, data = crtData) plot(outputCRTBoot,group=1) outputCRTPerm <- crtFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", nPerm = 1000, data = crtData) plot(outputCRTPerm,group=1) }
"possum"
ComposPare_X <- function(AS,Ex,trans=TRUE) { Obs_AS<-data.frame(rowSums(AS)) colnames(Obs_AS)<-c("X_io") Exp_AS <- data.frame(sample(Ex$X,nrow(Obs_AS),replace = T,prob = Ex$Density)) colnames(Exp_AS)<-c("X_ie") df<-as.data.frame(c(Obs_AS,Exp_AS)) df_t <- data.frame(OvE=factor(rep(c("Obs", "Exp"), each=nrow(Obs_AS))),freq=(c(df$X_io,df$X_ie))) if(trans){ return(df) }else{ return(df_t) } }
"ivphiBB1" <- function(theta,delta,t) { ivphiBB1<-(exp(theta*(-log(t))^(1/delta))-1)^delta resultivphiBB1<-matrix(c(theta,delta,t,ivphiBB1),nrow=1) }
ds.box <- function(x, c = 1.5, c.width = 0.15 , out = TRUE, tojson = FALSE) { b <- grDevices::boxplot.stats(x, coef = c, do.out = out) lo.whisker <- unname(unlist(b)[1]) lo.hinge <- unname(unlist(b)[2]) median <- unname(unlist(b)[3]) up.hinge <- unname(unlist(b)[4]) up.whisker <- unname(unlist(b)[5]) n <- unname(unlist(b)[6]) box.width <- round(c.width * sqrt(n), 2) if (out == TRUE & c != 0) { lo.out <- x[x < lo.hinge - c * diff(c(lo.hinge,up.hinge))] up.out <- x[x > up.hinge + c * diff(c(lo.hinge,up.hinge))] } else { lo.out <- NULL up.out <- NULL } box <- list( lo.whisker = lo.whisker, lo.hinge = lo.hinge, median = median, up.hinge = up.hinge, up.whisker = up.whisker, box.width = box.width, lo.out = lo.out, up.out = up.out, n = n) if (tojson == TRUE) { box <- jsonlite::toJSON(box) } return(box) }
TOSTmeta<-function(ES,var,se,low_eqbound_d, high_eqbound_d, alpha, plot = TRUE, verbose = TRUE){ if(missing(alpha)) { alpha<-0.05 } if(missing(se)) { if(missing(var)) { stop("Need to specify variance (var) or standard error (se).") } se<-sqrt(var) } if(missing(var)) { if(missing(se)) { stop("Need to specify variance (var) or standard error (se).") } } if(low_eqbound_d >= high_eqbound_d) warning("The lower bound is equal to or larger than the upper bound. Check the plot and output to see if the bounds are specified as you intended.") if(1 <= alpha | alpha <= 0) stop("The alpha level should be a positive value between 0 and 1.") Z1<-(ES-low_eqbound_d)/se p1<-pnorm(Z1, lower.tail=FALSE) Z2<-(ES-high_eqbound_d)/se p2<-pnorm(Z2, lower.tail=TRUE) Z<-(ES/se) pttest<-2*pnorm(-abs(Z)) LL90<-ES-qnorm(1-alpha)*(se) UL90<-ES+qnorm(1-alpha)*(se) LL95<-ES-qnorm(1-alpha/2)*(se) UL95<-ES+qnorm(1-alpha/2)*(se) ptost<-max(p1,p2) Ztost<-ifelse(abs(Z1) < abs(Z2), Z1, Z2) results<-data.frame(Z1,p1,Z2,p2,LL90,UL90) colnames(results) <- c("Z-value 1","p-value 1","Z-value 2","p-value 2", paste("Lower Limit ",100*(1-alpha*2),"% CI",sep=""),paste("Upper Limit ",100*(1-alpha*2),"% CI",sep="")) testoutcome<-ifelse(pttest<alpha,"significant","non-significant") TOSToutcome<-ifelse(ptost<alpha,"significant","non-significant") if (plot == TRUE) { plot(NA, ylim=c(0,1), xlim=c(min(LL95,low_eqbound_d,ES)-max(UL95-LL95, high_eqbound_d-low_eqbound_d,ES)/10, max(UL95,high_eqbound_d,ES)+max(UL95-LL95, high_eqbound_d-low_eqbound_d, ES)/10), bty="l", yaxt="n", ylab="",xlab="Effect size") points(x=ES, y=0.5, pch=15, cex=2) abline(v=high_eqbound_d, lty=2) abline(v=low_eqbound_d, lty=2) abline(v=0, lty=2, col="grey") segments(LL90,0.5,UL90,0.5, lwd=3) segments(LL95,0.5,UL95,0.5, lwd=1) title(main=paste("Equivalence bounds ",round(low_eqbound_d,digits=3)," and ",round(high_eqbound_d,digits=3),"\nEffect size = ",round(ES,digits=3)," \n TOST: ", 100*(1-alpha*2),"% CI [",round(LL90,digits=3),";",round(UL90,digits=3),"] ", TOSToutcome," \n NHST: ", 100*(1-alpha),"% CI [",round(LL95,digits=3),";",round(UL95,digits=3),"] ", testoutcome,sep=""), cex.main=1) } if(missing(verbose)) { verbose <- TRUE } if(verbose == TRUE){ cat("TOST results:\n") cat("Z-value lower bound:",format(Z1, digits = 3, nsmall = 2, scientific = FALSE),"\tp-value lower bound:",format(p1, digits = 1, nsmall = 3, scientific = FALSE)) cat("\n") cat("Z-value upper bound:",format(Z2, digits = 3, nsmall = 2, scientific = FALSE),"\tp-value upper bound:",format(p2, digits = 1, nsmall = 3, scientific = FALSE)) cat("\n\n") cat("Equivalence bounds (Cohen's d):") cat("\n") cat("low eqbound:", paste0(round(low_eqbound_d, digits = 4)),"\nhigh eqbound:",paste0(round(high_eqbound_d, digits = 4))) cat("\n\n") cat("TOST confidence interval:") cat("\n") cat("lower bound ",100*(1-alpha*2),"% CI: ", paste0(round(LL90, digits = 3)),"\nupper bound ",100*(1-alpha*2),"% CI: ",paste0(round(UL90,digits = 3)), sep = "") cat("\n\n") cat("NHST confidence interval:") cat("\n") cat("lower bound ",100*(1-alpha),"% CI: ", paste0(round(LL95, digits = 3)),"\nupper bound ",100*(1-alpha),"% CI: ",paste0(round(UL95,digits = 3)), sep = "") cat("\n\n") cat("Equivalence Test Result:\n") message(cat("The equivalence test was ",TOSToutcome,", Z = ",format(Ztost, digits = 3, nsmall = 3, scientific = FALSE),", p = ",format(ptost, digits = 3, nsmall = 3, scientific = FALSE),", given equivalence bounds of ",format(low_eqbound_d, digits = 3, nsmall = 3, scientific = FALSE)," and ",format(high_eqbound_d, digits = 3, nsmall = 3, scientific = FALSE)," and an alpha of ",alpha,".",sep="")) cat("\n") cat("Null Hypothesis Test Result:\n") message(cat("The null hypothesis test was ",testoutcome,", Z = ",format(Z, digits = 3, nsmall = 3, scientific = FALSE),", p = ",format(pttest, digits = 3, nsmall = 3, scientific = FALSE),", given an alpha of ",alpha,".",sep="")) if(pttest <= alpha && ptost <= alpha){ combined_outcome <- "statistically different from zero and statistically equivalent to zero" } if(pttest < alpha && ptost > alpha){ combined_outcome <- "statistically different from zero and statistically not equivalent to zero" } if(pttest > alpha && ptost <= alpha){ combined_outcome <- "statistically not different from zero and statistically equivalent to zero" } if(pttest > alpha && ptost > alpha){ combined_outcome <- "statistically not different from zero and statistically not equivalent to zero" } cat("\n") message(cat("Based on the equivalence test and the null-hypothesis test combined, we can conclude that the observed effect is ",combined_outcome,".",sep="")) } invisible(list(ES=ES,TOST_Z1=Z1,TOST_p1=p1,TOST_Z2=Z2,TOST_p2=p2,alpha=alpha,low_eqbound_d=low_eqbound_d,high_eqbound_d=high_eqbound_d, LL_CI_TOST=LL90,UL_CI_TOST=UL90,LL_CI_ZTEST=LL95,UL_CI_ZTEST=UL95)) }
kntoms=function(wvkn){(0.5144444*wvkn)}
squareBinning <- function(x, y = NULL, bins = 30) { if (is.null(y)) { x = as.matrix(x) y = x[, 2] x = x[, 1] } else { x = as.vector(x) y = as.vector(y) } data = cbind(x, y) n = bins if (length(n) == 1) { nbins = c(n, n) } else { nbins = n } xo = seq(min(x), max(x), length = nbins[1]) yo = seq(min(y), max(y), length = nbins[2]) xvals = xo[-1] - diff(xo)/2 yvals = yo[-1] - diff(yo)/2 ix = findInterval(x, xo) iy = findInterval(y, yo) xcm = ycm = zvals = matrix(0, nrow = nbins[1], ncol = nbins[2]) for (i in 1:length(x)) { zvals[ix[i], iy[i]] = zvals[ix[i], iy[i]] + 1 xcm[ix[i], iy[i]] = xcm[ix[i], iy[i]] + x[i] ycm[ix[i], iy[i]] = ycm[ix[i], iy[i]] + y[i] } u = v = w = ucm = vcm = rep(0, times = nbins[1]*nbins[2]) L = 0 for (i in 1:(nbins[1]-1)) { for (j in 1:(nbins[2]-1)) { if (zvals[i, j] > 0) { L = L + 1 u[L] = xvals[i] v[L] = yvals[j] w[L] = zvals[i, j] ucm[L] = xcm[i, j]/w[L] vcm[L] = ycm[i, j]/w[L] } } } length(u) = length(v) = length(w) = L length(ucm) = length(vcm) = L ans = list(x = u, y = v, z = w, xcm = ucm, ycm = vcm, bins = bins, data = data) class(ans) = "squareBinning" ans } plot.squareBinning <- function(x, col = heat.colors(12), addPoints = TRUE, addRug = TRUE, ...) { X = x$x Y = x$y plot(X, Y, type = "n", ...) rx = min(diff(unique(sort(X))))/2 ry = min(diff(unique(sort(Y))))/2 u = c(-rx, rx, rx, -rx) v = c( ry, ry, -ry, -ry) N = length(col) Z = x$z zMin = min(Z) zMax = max(Z) Z = (Z - zMin)/(zMax - zMin) Z = trunc(Z*(N-1)+1) for (i in 1:length(X)) { polygon(u+X[i], v+Y[i], col = col[Z[i]], border = "white") } if (addPoints) { points(x$xcm, x$ycm, pch = 19, cex = 1/3, col = "black") } if (addRug) { rug(x$data[, 1], ticksize = 0.01, side = 3) rug(x$data[, 2], ticksize = 0.01, side = 4) } invisible(NULL) } hexBinning <- function(x, y = NULL, bins = 30) { if (is.null(y)) { x = as.matrix(x) y = x[, 2] x = x[, 1] } else { x = as.vector(x) y = as.vector(y) } data = cbind(x, y) shape = 1 n = length(x) xbnds = range(x) ybnds = range(y) jmax = floor(bins + 1.5001) c1 = 2 * floor((bins *shape)/sqrt(3) + 1.5001) imax = trunc((jmax*c1 -1)/jmax + 1) lmax = jmax * imax cell = cnt = xcm = ycm = rep(0, times = max(n, lmax)) xmin = xbnds[1] ymin = ybnds[1] xr = xbnds[2] - xmin yr = ybnds[2] - ymin c1 = bins/xr c2 = bins*shape/(yr*sqrt(3.0)) jinc = jmax lat = jinc + 1 iinc = 2*jinc con1 = 0.25 con2 = 1.0/3.0 for ( i in 1:n ) { sx = c1 * (x[i] - xmin) sy = c2 * (y[i] - ymin) j1 = floor(sx + 0.5) i1 = floor(sy + 0.5) dist1 = (sx-j1)^2 + 3.0*(sy-i1)^2 if( dist1 < con1) { L = i1*iinc + j1 + 1 } else if (dist1 > con2) { L = floor(sy)*iinc + floor(sx) + lat } else { j2 = floor(sx) i2 = floor(sy) test = (sx-j2 -0.5)^2 + 3.0*(sy-i2-0.5)^2 if ( dist1 <= test ) { L = i1*iinc + j1 + 1 } else { L = i2*iinc + j2 + lat } } cnt[L] = cnt[L]+1 xcm[L] = xcm[L] + (x[i] - xcm[L])/cnt[L] ycm[L] = ycm[L] + (y[i] - ycm[L])/cnt[L] } nc = 0 for ( L in 1:lmax ) { if(cnt[L] > 0) { nc = nc + 1 cell[nc] = L cnt[nc] = cnt[L] xcm[nc] = xcm[L] ycm[nc] = ycm[L] } } bnd = c(imax, jmax) bnd[1] = (cell[nc]-1)/bnd[2] + 1 length(cell) = nc length(cnt) = nc length(xcm) = nc length(ycm) = nc if(sum(cnt) != n) warning("Lost counts in binning") c3 = diff(xbnds)/bins ybnds = ybnds c4 = (diff(ybnds) * sqrt(3))/(2 * shape * bins) cell = cell - 1 i = cell %/% jmax j = cell %% jmax y = c4 * i + ybnds[1] x = c3 * ifelse(i %% 2 == 0, j, j + 0.5) + xbnds[1] ans = list(x = x, y = y, z = cnt, xcm = xcm, ycm = ycm, bins = bins, data = data) class(ans) = "hexBinning" ans } plot.hexBinning <- function(x, col = heat.colors(12), addPoints = TRUE, addRug = TRUE, ...) { X = x$x Y = x$y plot(X, Y, type = "n", ...) rx = min(diff(unique(sort(X)))) ry = min(diff(unique(sort(Y)))) rt = 2*ry u = c(rx, 0, -rx, -rx, 0, rx) v = c(ry, rt, ry, -ry, -rt, -ry) / 3 N = length(col) z = x$z zMin = min(z) zMax = max(z) Z = (z - zMin)/(zMax - zMin) Z = trunc(Z*(N-1)+1) for (i in 1:length(X)) { polygon(u+X[i], v+Y[i], col = col[Z[i]], border = "white") } if (addPoints) { points(x$xcm, x$ycm, pch = 19, cex = 1/3, col = "black") } if (addRug) { rug(x$data[, 1], ticksize = 0.01, side = 3) rug(x$data[, 2], ticksize = 0.01, side = 4) } invisible(NULL) }
skip_on_cran() m <- SDMtune:::bm_maxent m1 <- SDMtune:::bm_maxnet train <- SDMtune:::t train@data <- train@data[train@pa == 1, ] train@coords <- train@coords[train@pa == 1, ] train@pa <- train@pa[train@pa == 1] files <- list.files(path = file.path(system.file(package = "dismo"), "ex"), pattern = "grd", full.names = TRUE) predictors <- raster::stack(files) test_that("The method works with data frames", { p <- predict(m, train@data, "raw", clamp = FALSE) expect_length(p, nrow(train@data)) expect_vector(p) }) test_that("The method works with SWD objects", { p <- predict(m1, train, "logistic") expect_length(p, nrow(train@data)) expect_vector(p) }) test_that("The method works with raster stack objects", { p <- predict(m, predictors, "raw") expect_length(p, predictors$bio1@ncols * predictors$bio1@nrows) expect_s4_class(p, "RasterLayer") })
setGeneric("raster2contour", function(x, ...) {standardGeneric("raster2contour")}) setMethod(f = "raster2contour", signature = c(x = ".UD"), definition = function(x, ...) { vol<-getVolumeUD(x) rasterToContour(vol, ...) }) setMethod(f = "raster2contour", signature = c(x = ".UDStack"), definition = function(x, ...) { xx<-split(x) tmp<-lapply(xx, raster2contour, ...=...) x<-mapply(spChFIDs, tmp, mapply(paste,lapply(tmp,row.names), names(tmp), SIMPLIFY=F)) tmp<-do.call('rbind',mapply('[[<-',MoreArgs=list(i='individual.local.identifier'),x=x, value=names(tmp))) return(tmp) })
VAFmethod <- function(initialSample, b = n, increases = FALSE) { if(is.vector(initialSample)) { initialSample <- matrix(initialSample,nrow=1) } n <- nrow(initialSample) parameterCheckForResampling(initialSample,b) if(increases) { initialSample <- transformFromIncreases(initialSample) } if(!all(apply(initialSample, 1, is.Fuzzy))) { stop("Some values in initial sample are not correct fuzzy numbers") } initialValues <- calculateValue(initialSample) initialAmbiguites <- calculateAmbiguity(initialSample) initialFuzziness <- calculateFuzziness(initialSample) numbers <- sample(n,b, replace = TRUE) outputSample <- matrix(0, nrow = b, ncol = 4) for (i in 1:b) { if (is.Triangular(initialSample[numbers[i],])) { outputSample[i,] <- initialSample[numbers[i],] } else { selectedValue <- initialValues[numbers[i]] selectedAmbiguity <- initialAmbiguites[numbers[i]] selectedFuzziness <- initialFuzziness[numbers[i]] s <- selectedAmbiguity - 2/3 * selectedFuzziness c <- runif(1,selectedValue-2/3 * selectedFuzziness,selectedValue+2/3 * selectedFuzziness) l <- 3*(selectedAmbiguity-selectedValue+c-s) r <- 3*(selectedAmbiguity+selectedValue-c-s) outputSample[i,] <- c(c-l-s,c-s,c+s,c+r+s) } } if(increases) { outputSample <- transformToIncreases(outputSample) } return(outputSample) }
library(rstan) d <- read.csv('input/data-mvn.txt') data <- list(N=nrow(d), D=2, Y=d) fit <- stan(file='model/model9-2.stan', data=data, seed=1234) fit_b <- stan(file='model/model9-2b.stan', data=data, seed=1234)
context("single_example") test_that("single example", { set.seed(4321) is_personal <- !is.na(file.info(file.path("..", "..", ".lintr"))$size) cores_vals <- 1 n <- 5000 if (is_personal) { cores_vals <- c(cores_vals, 2, 4) n <- 10000 } m <- 4 N <- n * m p <- 20 q <- 2 beta <- rbind(1, matrix(mnormt::rmnorm(p, 10, 1), p, 1)) R <- diag(m) D <- matrix(c(16, 0, 0, 0.025), nrow = q) sigma <- 1 beta_start <- beta R_start <- R D_start <- D sigma_start <- sigma subject <- rep(1:n, each = m) repeats <- rep(1:m, n) myresult_x <- lapply(1:n, function(i) cbind(1, matrix(rnorm(m * p), nrow = m))) X <- do.call(rbind, myresult_x) Z <- X[, 1:q] myresult_b <- lapply(1:n, function(i) mnormt::rmnorm(1, rep(0, q), D)) myresult_e <- lapply(1:n, function(i) mnormt::rmnorm(1, rep(0, m), sigma * R)) myresulty <- lapply( seq_len(n), function(i) { (myresult_x[[i]] %*% beta) + (myresult_x[[i]][, 1:q] %*% myresult_b[[i]]) + myresult_e[[i]] } ) y <- do.call(rbind, myresulty) if (is_personal) cat("\nstarting timings...\n\n") timings <- list() pars <- list() for (i in seq_along(cores_vals)) { timing <- system.time({ ans.gauss <- lmmpar( y, X, Z, subject, beta = beta, R = R, D = D, cores = cores_vals[i], sigma = sigma, verbose = is_personal ) }) if (is_personal) print(ans.gauss) expect_true(abs(ans.gauss$beta[1, 1] - 1) < 2) expect_true(all(ans.gauss$beta[-1, 1] > 5)) if (is_personal) print(timing) timing <- as.list(timing) timing$cores <- cores_vals[i] timing$n <- n timing$repeats <- m timing$p <- p timings[[i]] <- timing pars$Beta_start <- beta_start pars$R_start <- R_start pars$D_start <- D_start pars$sigma_start <- sigma_start expect_true(TRUE) } if (is_personal) { cat("\n") print(as.data.frame(do.call(rbind, timings))) print(pars) } }) if (FALSE) { }
data(sesamesim) sesameCFA <- sesamesim names(sesameCFA)[6] <- "pea" model2 <- ' A =~ Ab + Al + Af + An + Ar + Ac B =~ Bb + Bl + Bf + Bn + Br + Bc A ~ B + age + pea ' fit2 <- lavaan::sem(model2, data = sesameCFA, std.lv = TRUE) hypotheses2 <- "A~B > A~pea = A~age = 0; A~B > A~pea > A~age = 0; A~B > A~pea > A~age > 0" set.seed(100) y1 <- bain(fit2, hypotheses2, fraction = 1, standardize = TRUE) sy1 <- summary(y1, ci = 0.99) set.seed(100) y2 <- bain(fit2, hypotheses2, fraction = 2, standardize = TRUE) set.seed(100) y3 <- bain(fit2, hypotheses2, fraction = 3, standardize = TRUE) ngroup2 <- lavaan::nobs(fit2) PE2 <- lavaan::parameterEstimates(fit2, standardize = TRUE) estimate2 <- PE2[ PE2$op == "~", "std.all"] names(estimate2) <- c("before", "age", "pea") PT2 <- parTable(fit2) par.idx2 <- PT2$free[ PT2$op == "~" ] covariance2 <- list(lavInspect(fit2, "vcov.std.all")[par.idx2, par.idx2]) hypotheses2 <- "before > pea = age = 0; before > pea > age = 0; before > pea > age > 0" set.seed(100) z1 <- bain(estimate2, hypotheses2, n = ngroup2, Sigma = covariance2, group_parameters = 3,joint_parameters = 0) sz1<-summary(z1, ci = 0.99) set.seed(100) z2 <- bain(estimate2, hypotheses2, n = ngroup2/2, Sigma = covariance2, group_parameters = 3,joint_parameters = 0) set.seed(100) z3 <- bain(estimate2, hypotheses2, n = ngroup2/3, Sigma = covariance2, group_parameters = 3, joint_parameters = 0) test_that("Bain mutual", {expect_equal(y1$fit$Fit , z1$fit$Fit)}) test_that("Bain mutual", {expect_equal(y1$fit$Com , z1$fit$Com)}) test_that("Bain mutual", {expect_equal(y1$independent_restrictions, z1$independent_restrictions)}) test_that("Bain mutual", {expect_equal(y1$b, z1$b)}) test_that("Bain mutual", {expect_equal(as.vector(y1$posterior[13:15, 13:15]), as.vector(z1$posterior))}) test_that("Bain mutual", {expect_equal(as.vector(y1$prior[13:15, 13:15]), as.vector(z1$prior))}) test_that("Bain mutual", {expect_equal(y1$fit$BF,z1$fit$BF)}) test_that("Bain mutual", {expect_equal(y1$fit$PMPb , z1$fit$PMPb)}) test_that("Bain mutual", {expect_equal(as.vector(t(y1$BFmatrix)), as.vector(t(z1$BFmatrix)))}) test_that("summary", {expect_equal(sy1$Estimate[13:15] , sz1$Estimate)}) test_that("summary", {expect_equal(sy1$n[1] , sz1$n[1])}) test_that("summary", {expect_equal(sy1$lb[13:15] , sz1$lb)}) test_that("summary", {expect_equal(sy1$ub[13:15] , sz1$ub)}) test_that("Bain mutual", {expect_equal(y2$fit$Fit , z2$fit$Fit)}) test_that("Bain mutual", {expect_equal(y2$fit$Com , z2$fit$Com)}) test_that("Bain mutual", {expect_equal(y2$independent_restrictions, z2$independent_restrictions)}) test_that("Bain mutual", {expect_equal(y2$b, z2$b)}) test_that("Bain mutual", {expect_equal(as.vector(y2$posterior[13:15, 13:15]), as.vector(z2$posterior))}) test_that("Bain mutual", {expect_equal(as.vector(y2$prior[13:15, 13:15]), as.vector(z2$prior))}) test_that("Bain mutual", {expect_equal(y2$fit$BF,z2$fit$BF)}) test_that("Bain mutual", {expect_equal(y2$fit$PMPb , z2$fit$PMPb)}) test_that("Bain mutual", {expect_equal(as.vector(t(y2$BFmatrix)), as.vector(t(z2$BFmatrix)))}) test_that("Bain mutual", {expect_equal(y3$fit$Fit , z3$fit$Fit)}) test_that("Bain mutual", {expect_equal(y3$fit$Com , z3$fit$Com)}) test_that("Bain mutual", {expect_equal(y3$independent_restrictions, z3$independent_restrictions)}) test_that("Bain mutual", {expect_equal(y3$b, z3$b)}) test_that("Bain mutual", {expect_equal(as.vector(y3$posterior[13:15, 13:15]), as.vector(z3$posterior))}) test_that("Bain mutual", {expect_equal(as.vector(y3$prior[13:15, 13:15]), as.vector(z3$prior))}) test_that("Bain mutual", {expect_equal(y3$fit$BF,z3$fit$BF)}) test_that("Bain mutual", {expect_equal(y3$fit$PMPb , z3$fit$PMPb)}) test_that("Bain mutual", {expect_equal(as.vector(t(y3$BFmatrix)), as.vector(t(z3$BFmatrix)))})
asymmetrise <- function(df, .x, .y) { .x <- enquo(.x) .y <- enquo(.y) .x_data <- eval_tidy(.x, df) .y_data <- eval_tidy(.y, df) if (inherits(.x_data, "factor") | inherits(.y_data, "factor")) { data_levels <- organize_levels(.x_data, .y_data) df <- df %>% dplyr::mutate( !!.x := as.character(!!.x), !!.y := as.character(!!.y) ) } else { data_levels <- NULL } new_df <- dplyr::bind_rows(df, swap_cols(df, !!.x, !!.y)) %>% add_missing_combinations(!!.x, !!.y) if (!is.null(data_levels)) { new_df <- new_df %>% dplyr::mutate( !!.x := factor(!!.x, levels = data_levels), !!.y := factor(!!.y, levels = data_levels) ) } return(new_df) } asymmetrize <- asymmetrise swap_cols <- function(df, .x, .y) { groups <- dplyr::groups(df) df <- dplyr::ungroup(df) .x <- enquo(.x) .y <- enquo(.y) .x_data <- eval_tidy(.x, df) .y_data <- eval_tidy(.y, df) new_df <- df %>% dplyr::mutate( !!.x := .y_data, !!.y := .x_data ) return(dplyr::group_by(new_df, !!!groups)) } add_missing_combinations <- function(df, .x, .y) { .x <- enquo(.x) .y <- enquo(.y) .x_data <- eval_tidy(.x, df) .y_data <- eval_tidy(.y, df) if (inherits(.x_data, "factor") | inherits(.y_data, "factor")) { data_levels <- organize_levels(.x_data, .y_data) df <- df %>% dplyr::mutate( !!.x := as.character(!!.x), !!.y := as.character(!!.y) ) .x_data <- as.character(.x_data) .y_data <- as.character(.y_data) } else { data_levels <- NULL } if (is_grouped(df)) { original_groups <- dplyr::groups(df) new_df <- df %>% tidyr::nest() %>% dplyr::mutate(data = purrr::map( data, function(a) { b <- bind_missing_combs(a, !!.x, !!.y) } )) %>% tidyr::unnest(data) %>% dplyr::group_by(!!!original_groups) } else { new_df <- bind_missing_combs(df, !!.x, !!.y) } if (!is.null(data_levels)) { new_df <- new_df %>% dplyr::mutate( !!.x := factor(!!.x, levels = data_levels), !!.y := factor(!!.y, levels = data_levels) ) } return(new_df) } bind_missing_combs <- function(df, .x, .y) { .x <- enquo(.x) .y <- enquo(.y) others_combs <- get_other_combs( eval_tidy(.x, df), eval_tidy(.y, df) ) if (nrow(others_combs) > 0) { df_cp <- make_fill_df(df, n_rows = nrow(others_combs)) %>% dplyr::mutate( !!.x := others_combs$Var1, !!.y := others_combs$Var2 ) new_df <- dplyr::bind_rows(df, df_cp) } else { new_df <- df } return(new_df) } get_other_combs <- function(x, y) { current_combs <- paste(x, y, sep = "_") all_vals <- unique(c(x, y)) all_combs <- expand.grid(all_vals, all_vals, stringsAsFactors = FALSE, KEEP.OUT.ATTRS = FALSE) %>% unique() %>% dplyr::mutate(comb = paste(Var1, Var2, sep = "_")) %>% dplyr::filter(!(comb %in% current_combs)) %>% dplyr::select(-comb) return(all_combs) } make_fill_df <- function(df, n_rows = 1, fill_val = NA) { if (ncol(df) < 1) stop("df must have at least 1 column") if (n_rows < 1) stop("must request at least one row") na_df <- df %>% dplyr::slice(1) %>% dplyr::mutate_all(function(i) fill_val) na_df <- dplyr::bind_rows(purrr::map(seq_len(n_rows), ~na_df)) return(na_df) } organize_levels <- function(x, y, ...) { x_levels <- levels(x) y_levels <- levels(y) if (is.null(x_levels) | is.null(y_levels)) { message("x and/or y have no levels, both coerced to char") return(NULL) } else if (identical(x_levels, y_levels)) { return(x_levels) } else if (identical(intersect(x_levels, y_levels), character(0))) { message("completely different levels for x and y, coerced to char") return(NULL) } else if (length(intersect(x_levels, y_levels)) >= 1) { message("partial overlap of levels, merging levels of x and y") return(sort(unique(c(x_levels, y_levels)), ...)) } else { stop("Unforeseen condition in organizing levels --> open an Issue") } } is_grouped <- function(data) { dplyr::n_groups(data) > 1 } utils::globalVariables(c("Var1", "Var2", "comb", ".grp_nest", "data"), add = TRUE )
if_else_block <- function(testexpr, ..., thenexprs = NULL, elseexprs = NULL) { wrapr::stop_if_dot_args(substitute(list(...)), "rquery::if_else_block") if((length(thenexprs) + length(elseexprs))<=0) { return(NULL) } knownsyms <- c(names(thenexprs), names(elseexprs)) testsym <- setdiff( paste0('ifebtest_', seq_len(length(knownsyms)+1)), knownsyms)[[1]] program <- c(testsym %:=% testexpr) prepStmts <- function(stmts, condition) { ret <- NULL n <- length(stmts) if(n<=0) { return(ret) } isSpecial <- startsWith(names(stmts), 'ifebtest_') if(any(isSpecial)) { spc <- stmts[isSpecial] stmts <- stmts[!isSpecial] ret <- c(ret, spc) } n <- length(stmts) if(n<=0) { return(ret) } nexprs <- vapply(1:n, function(i) { paste0('ifelse( ', condition, ', ', stmts[[i]], ', ', names(stmts)[[i]], ')') }, character(1)) names(nexprs) <- names(stmts) ret <- c(ret,nexprs) ret } program <- c(program, prepStmts(thenexprs, testsym)) program <- c(program, prepStmts(elseexprs, paste('! ', testsym))) program } if_else_op <- function(source, testexpr, ..., thenexprs = NULL, elseexprs = NULL, env = parent.frame()) { force(env) wrapr::stop_if_dot_args(substitute(list(...)), "rquery::if_else_op") steps <- if_else_block(testexpr = testexpr, thenexprs = thenexprs, elseexprs = elseexprs) source %.>% extend_se(., steps, env = env) %.>% drop_columns(., "ifebtest_1", env = env) }
`circtics` <- function(r=1, dr=.02, dang=10,... ) { if(missing(r)) { r=1 } if(missing(dr)) { dr=0.02 } if(missing(dang)) { dang=10 } points(0,0, pch=3) DR = r+dr ang =pi*seq(0, 360, by=dang)/180 segments(r*cos(ang), r*sin(ang), DR*cos(ang), DR*sin(ang), ...) }
isVector = function(par) { UseMethod("isVector") } isVector.Param = function(par) { isVectorTypeString(par$type) } isVector.ParamSet = function(par) { all(vlapply(par$pars, isVector)) }