diff --git "a/data/dataset_Homeostasis.csv" "b/data/dataset_Homeostasis.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Homeostasis.csv" @@ -0,0 +1,3584 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Homeostasis","MathOnco/EvoFreq","img/readme.img.code.R",".R","3345","75","library(gridExtra) + +# Note: this can be copy and pasted after installed + +data(""example.easy.wide"") # Load a simple Data Frame example +str(example.easy.wide) # Inspect the data structure + +# 'data.frame': 8 obs. of 10 variables: +# $ parents: num 0 1 1 3 1 5 5 5 +# $ clones : num 1 2 3 4 5 6 7 8 +# $ 1 : num 1 0 0 0 0 0 0 0 +# $ 2 : num 100 5 0 0 0 0 0 0 +# $ 3 : num 200 100 5 0 0 0 0 0 +# $ 4 : num 400 5 100 1 1 0 0 0 +# $ 5 : num 0 0 200 100 100 1 0 1 +# $ 6 : num 0 0 200 125 200 10 1 15 +# $ 7 : num 0 0 300 200 300 20 10 25 +# $ 8 : num 0 0 300 300 300 25 25 100 + +# You have A column of parents and a column of clones then you have a column for each of the timepoints with sizes for that clone. + +# Then get the frequency data. (Use ?get_freq_dynamics for options) +clone_dynamics_df <- get_freq_dynamics(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"") + +# Create the plot (shown on the left below) +evo_freq_p <- plot_freq_dynamics(clone_dynamics_df) +print(evo_freq_p) + +# We can also choose to update the colors or do this during the first creation. (shown on the right below) +clone_dynamics_df_jet <- update_colors(clone_dynamics_df, clone_cmap = ""jet"") +evo_freq_p_jet <- plot_freq_dynamics(clone_dynamics_df_jet) +print(evo_freq_p_jet) + +p <- arrangeGrob(evo_freq_p, evo_freq_p_jet, ncol=2, nrow=1) +ggsave(plot=p, filename=""img/easy.wide.image.png"", units=c(""mm""),width=317.5, height=79.375, dpi=300, device=""png"") + +# Note: this can be copy and pasted after installed + +# In this example you have two files. One is the edge list of clones and their parents +# The other file is the sizes over time for those clones +# examine the structures to see how to format +# example.easy.long.edges now has an attribute column as well +data(""example.easy.long.edges"") +data(""example.easy.long.sizes"") + +# Use the long_to_wide_size_df function to get the right data structure. +wide_df <- long_to_wide_size_df(long_pop_sizes_df = example.easy.long.sizes, time_col_name = ""Time"", clone_col_name = ""clone"", parent_col_name = ""parent"", size_col_name = ""Size"", edges_df = example.easy.long.edges) +clones <- wide_df$clones +parents <- wide_df$parents +size_df <- wide_df$wide_size_df + +clone_dynamics_df <- get_freq_dynamics(size_df, clones, parents, clone_cmap = ""inferno"") +evo_freq_p <- plot_freq_dynamics(clone_dynamics_df) + +# Add custom ggplot features +evo_freq_labeled_p <- evofreq_clone_labels(clone_dynamics_df, clone_list=c(3,5,6), extant_only=F, evo_freq_p=evo_freq_p, apply_labels=T) + +p <- arrangeGrob(evo_freq_p, evo_freq_labeled_p, ncol=2, nrow=1) +ggsave(plot=p, filename=""img/easy.long.image.png"", units=c(""mm""),width=317.5, height=79.375, dpi=300, device=""png"") + +# Network plots +data(""example.wide"") +time_col_idx <- which(substr(colnames(example.wide), start=1, stop = 1)==""X"") +attribute_col_idx <- which(substr(colnames(example.wide), start=1, stop = 1) != ""X"") +colnames(example.wide)[time_col_idx] <- substring(colnames(example.wide), first=2)[time_col_idx] +attribute_df <- example.wide[, attribute_col_idx] +size_df <- example.wide[, time_col_idx] +parents <- example.wide$parent +clones <- example.wide$clone + +clone_network <- get_clone_network(size_df, clones, parents) +evofreq_plot <- plot_clone_network(clone_network, layout=""circlepack"") + + +","R" +"Homeostasis","MathOnco/EvoFreq","R/example.easy.long.edges.R",".R","418","16","#' Clone edges in Easy Long Format +#' +#' A dataset for easy understanding of EvoFreq data structures. +#' +#' @format A data frame with 6 rows and 3 variables: +#' \describe{ +#' \item{parent}{Parent of clone} +#' \item{clone}{Clone} +#' \item{fitness}{Clone attribute that to color by} +#' } +#' @source Custom Made. +#' @examples +#' ?example.easy.long.edges +#' data(""example.easy.long.edges"") +""example.easy.long.edges"" +","R" +"Homeostasis","MathOnco/EvoFreq","R/Example.Wide.R",".R","2073","56","#' Clone information dataset in Wide Format +#' +#' A dataset from a simulation taken from ""Niche engineering drives early passage through an immune bottleneck in progression to colorectal cancer"" +#' +#' @format A data frame with 6591 rows and 43 variables: +#' \describe{ +#' \item{master_random_seed}{Simulation metadata} +#' \item{macrophage_suppression}{Simulation metadata} +#' \item{macrophage_growth_benefit}{Simulation metadata} +#' \item{pdl1_protection}{Simulation metadata} +#' \item{tumor_random_seed}{Simulation metadata} +#' \item{tumor_lineage}{Simulation metadata} +#' \item{tumor_status}{Simulation metadata} +#' \item{onset}{Simulation metadata} +#' \item{parent}{Simulation metadata} +#' \item{og_parent}{Simulation metadata} +#' \item{clone}{Simulation metadata} +#' \item{type}{Simulation metadata} +#' \item{division_rate}{Simulation metadata} +#' \item{n_driver_mutations}{Simulation metadata} +#' \item{new_antigenicity}{Simulation metadata} +#' \item{og_antigenicity}{Simulation metadata} +#' \item{final_antigenicity}{Simulation metadata} +#' \item{macrophage}{Simulation metadata} +#' \item{pdl1}{Simulation metadata} +#' \item{immune_susceptibility}{Simulation metadata} +#' \item{detected}{Simulation metadata} +#' \item{size_at_time_of_detection}{Simulation metadata} +#' \item{X2227}{Timepoint} +#' \item{X2257}{Timepoint} +#' \item{X2287}{Timepoint} +#' \item{X2317}{Timepoint} +#' \item{X2347}{Timepoint} +#' \item{X2377}{Timepoint} +#' \item{X2407}{Timepoint} +#' \item{X2437}{Timepoint} +#' \item{X2467}{Timepoint} +#' \item{X2497}{Timepoint} +#' \item{X2527}{Timepoint} +#' \item{X2557}{Timepoint} +#' \item{X2587}{Timepoint} +#' \item{X2617}{Timepoint} +#' \item{X2647}{Timepoint} +#' \item{X2677}{Timepoint} +#' \item{X2707}{Timepoint} +#' \item{X2737}{Timepoint} +#' \item{X2767}{Timepoint} +#' \item{X2797}{Timepoint} +#' \item{X2808}{Timepoint} +#' } +#' @source \url{https://www.biorxiv.org/content/10.1101/623959v2} +#' @examples +#' if (require(""EvoFreq"")) { +#' example.wide +#' } +""example.wide""","R" +"Homeostasis","MathOnco/EvoFreq","R/EvoFreq_funcs.R",".R","65726","1471","#'@import ggplot2 dplyr bezier + +#'@title get_evofreq +#' +#' Collect information to plot frequency dynamics +#' +#'@param size_df Dataframe in a wide format, where each row corrsponds to a single clone, and the columns are the sizes of that clone at each timepoint +#'@param clones Array containing the clone ids. The index of each clone must correspond to the same index of the row in \code{size_df} that contains the sizes of that clone over time +#'@param parents Array containing the ids of the parent of each clone in the \code{clones} array. +#'@param fill_value Array containing information that can be used to color each clone. If NULL (the default), each clone is assigned a color. If values are a clone attribute, e.g. fitness, then the colors are assigned according to those values. The user can also provide custom colors in 3 ways: 1) hexcode; 2) rgb values as a string, with each value being a the intensity of the color channel, each separated by commas, e.g. ""255, 10, 128""; 3) Any of the named in colors in R, which can be found with \code{\link[grDevices]{colors}} +#'@param fill_range Array containing the minimum and maximum values to set the range of colors. If NULL (the default), the range is determined directly from \code{fill_value}. +#'@param time_pts Array containing the name of the timepoints. If NULL, then the name of timepoints will be a sequence from 1 to the number of columns in \code{size_df}. +#'@param clone_cmap Colormap to use for the clones. For a list of available colormaps, see https://github.com/bhaskarvk/colormap. +#'@param threshold The minimum frequency of clones to be plotted. Clones with with a frequency below this value will not be plotted +#'@param scale_by_sizes_at_time Boolean defining whether or not the plot should represent the size or frequency of each clone at each timepoint. If TRUE, the sizes are scaled by the maximum size at each timepoint, and the plot thus represents the clonal frequencies at each timepoint. If FALSE, the sizes are scaled using the maximum size in \code{size_df}, thus reflecting relative population sizes +#'@param data_type String defining what kind of information is in size_df. If ""size"", then the values in \code{size_df} are the population sizes. If ""mutation"", the values are the frequencies, between 0 and 1, of each mutation in the population over time +#'@param interpolation_steps Integer defining the number of knots to use in the spline interpolation used to fill in the gaps between observed population sizes. For sparse data, this smooths out the curves in the plot. Not recommended if the data is dense, as this is slow and may not have noticable effects +#'@param interp_method String identifying the interpolation method to use. Either ""bezier"", or a method used by \code{\link[stats]{splinefun}} +#'@param fill_gaps_in_size Boolean defining whether or not missing sizes should be filled in +#'@param test_links Make sure clone does not have the same id as it's parent. If true, it can cause infinite recursion. +#'@param add_origin Boolean defining whether or not to add origin positions to founder clones, even if not present in the data. Best for sparse observed data +#'@param tm_frac Value between 0 and 1 that determines where the maximum growth rate is in the inferred origin sizes. Lower values result in earlier maximum growth +#'@param rescale_after_thresholding Boolean determining if frequencies should be rescaled after thresholding, so that frequencies are based on what was above the threshold. +#'@param shuffle_colors Boolean determining if colors should be shuffled before being assigned to each clone. Only applies when fill_value = NULL +#'@return Formatted dataframe called a ""freq_frame"" containing the information needed to plot the frequency dynamics over time. +#' +#'@examples +#'\donttest{ +#' data(""example.easy.wide"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) +#' size_df <- example.easy.wide[, time_col_idx] +#' parents <- example.easy.wide$parents +#' clones <- example.easy.wide$clones +#' +#' ### Default is to plot size +#' freq_frame <- get_evofreq(size_df, clones, parents) +#' evo_p_by_size <- plot_evofreq(freq_frame) +#' +#' ### Can also plot frequency by setting scale_by_sizes_at_time = TRUE. +#' freq_frame <- get_evofreq(size_df, clones, parents, scale_by_sizes_at_time = TRUE) +#' evo_p_by_freq <- plot_evofreq(freq_frame) +#' +#' ### Default is to mildly smooth corners, but this can be turned by setting interpolation_steps = 0 +#' freq_frame <- get_evofreq(size_df, clones, parents, interpolation_steps = 0) +#' raw_evo_p <- plot_evofreq(freq_frame) +#' +#' ### Several other methods to smooth corners, including using Bezier curves. However, Bezier curves dont represent the data as accurately as the methods that use splinefun, i.e. c(""fmm"", ""periodic"", ""natural"", ""monoH.FC"", ""hyman"") +#' freq_frame <- get_evofreq(size_df, clones, parents, interp_method = ""bezier"") +#' bez_evo_p <- plot_evofreq(freq_frame) +#' +#' ### Data can also be provided as mutaiton frequencies by setting data_type = ""mutation"" +#' mutation_count_df <- get_mutation_df(size_df, clones, parents) +#' freq_frame <- get_evofreq(mutation_count_df, clones, parents, data_type = ""mutation"") +#' evo_p_from_mutation <- plot_evofreq(freq_frame) +#' +#' ### Input needs to be in wide format, but can be converted to long format data to wide format using \code{\link{long_to_wide_freqframe}} +#' wide_df_info <- long_to_wide_freqframe(long_pop_sizes_df = example.easy.long.sizes, time_col_name = ""Time"", clone_col_name = ""clone"", parent_col_name = ""parent"", size_col_name = ""Size"", edges_df = example.easy.long.edges) +#' clones_from_long <- wide_df_info$clones +#' parents_from_long <- wide_df_info$parents +#' size_df_from_long <- wide_df_info$wide_size_df +#' freq_frame <- get_evofreq(size_df_from_long, clones_from_long, parents_from_long) +#' evo_p_from_long <- plot_evofreq(freq_frame) +#' +#' ### Setting of colors can be done when getting the freq_frame, or by updating the color later using \code{\link{update_colors}}. For a list of available colormaps, see https://github.com/bhaskarvk/colormap. +#' ### Default colormap is rainbow_soft, but this can be changed using the \code{clone_cmap} argument. +#' jet_freq_frame <- get_evofreq(size_df, clones, parents, clone_cmap = ""jet"") +#' jet_evo_p <- plot_evofreq(jet_freq_frame) +#' +#' ### Can color each clone by an attribute by providing a \code{fill_value}. Default colormap is viridis, but this can be changed using the \code{clone_cmap} argument +#' fitness <- runif(length(clones)) +#' fitness_freq_frame <- get_evofreq(size_df, clones, parents, fill_value = fitness) +#' fitness_evo_p <- plot_evofreq(fitness_freq_frame) +#' +#' ### The user can also provide custom colors for each clone, which will need to be passed into the \code{fill_value} argument +#' ### Custom colors can be defined using RGB values. Each color should be a string specifying the color channel values, separated by commas. +#' rgb_clone_colors <- sapply(seq(1, length(clones)), function(x){paste(sample(0:255,size=3,replace=TRUE),collapse="","")}) +#' rgb_freq_frame <- get_evofreq(size_df, clones, parents, rgb_clone_colors) +#' rgb_evo_p <- plot_evofreq(rgb_freq_frame) +#' +#' ### Custom colors can also be any of the named colors in R. A list of the colors can be found with \code{colors()} +#' named_clone_colors <- sample(colors(), length(clones), replace = FALSE) +#' named_freq_frame <- update_colors(rgb_freq_frame, clones = clones, fill_value = named_clone_colors) +#' named_evo_p <- plot_evofreq(named_freq_frame) +#' +#' ### Custom colors can also be specified using hexcode +#' hex_clone_colors <- c(""#614099ff"", ""#1d347eff"", ""#94558aff"", ""#c96872ff"", ""#f1884dff"", ""#e8fa5bff"", ""#042333ff"",""#f9bb41ff"") +#' hex_freq_frame <- update_colors(rgb_freq_frame, clones = clones, fill_value = hex_clone_colors) +#' hex_evo_p <- plot_evofreq(hex_freq_frame) +#' +#' ### Can revert back to original colors +#'freq_frame_default_color <- update_colors(fitness_freq_frame, clones=clones) +#'default_cmap_evo_p <- plot_evofreq(freq_frame_default_color) +#'} +#'@export +get_evofreq <- function(size_df, clones, parents, fill_value=NULL, fill_range = NULL, time_pts=NULL, clone_cmap=NULL, threshold=0.01, scale_by_sizes_at_time = FALSE, data_type=""size"", interpolation_steps = 20, interp_method = ""monoH.FC"", fill_gaps_in_size = FALSE, test_links=TRUE, add_origin=FALSE, tm_frac=0.6, rescale_after_thresholding=FALSE, shuffle_colors=FALSE){ + # # ## FOR TESTING ### + # data(""example.easy.wide.with.attributes"") + # ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values + # time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) + # size_df <- example.easy.wide[, time_col_idx] + # parents <- example.easy.wide$parents + # clones <- example.easy.wide$clones + # fill_value <- clone_attribute_colors + + # parents <- clone_df$Parent + # clones <- row.names(clone_df) + # time_pts <- as.numeric(colnames(clone_df)) + # time_pts <- which(!is.na(time_pts)) + # size_df <- clone_df[time_pts] + # fill_value <- clone_df$Drivers + + ### HAL + # size_df <- hal_info$size_df + # clones <- hal_info$clones + # parents <- hal_info$parents + # fill_value <- NULL + + # threshold <- 0.01 + # clone_cmap <- NULL + # time_pts <- NULL + # fill_range <- NULL + # scale_by_sizes_at_time <- FALSE + # interpolation_steps <- 10 + # fill_gaps_in_size <- FALSE + # test_links <- TRUE + # data_type <- ""size"" + # interp_method <- ""monoH.FC""# ""bezier"" + # add_origin <- FALSE + # tm_frac <- 0.6 + # rescale_after_thresholding <- FALSE + # shuffle_colors <- FALSE + # # # ### + if(!is.null(fill_value)){ + fill_name <- colnames(fill_value) ### Value was passed in as a single column dataframe + if(is.null(fill_name)){ + paresed_fill_name <- deparse(substitute(fill_value)) + print(paresed_fill_name) + fill_name <- get_argname(paresed_fill_name) + print(fill_name) + } + + attribute_df <- data.frame(""clone_id""=clones) + attribute_df[fill_name] <- fill_value + }else{ + attribute_df <- NULL + fill_name <- NULL + } + + og_time_pts <- colnames(size_df) + to_plot_df <- filter_data(size_df = size_df, clones = clones, parents = parents, time_pts = time_pts, attribute_df = attribute_df, threshold = threshold, scale_by_sizes_at_time = scale_by_sizes_at_time, data_type = data_type, fill_gaps_in_size = fill_gaps_in_size, test_links=test_links, add_origin=add_origin, tm_frac=tm_frac, rescale_after_thresholding=rescale_after_thresholding) + clones <- to_plot_df$clones + parents <- to_plot_df$parents + freq_mat <- to_plot_df$freq_mat + max_mutation_size <- to_plot_df$max_size + time_pt_names <- to_plot_df$og_colnames + time_pt_df <- data.frame(""x""=as.numeric(colnames(freq_mat)), ""Time_label""=time_pt_names) ### Have to make x numeric. Otherwise, float column names are converted to strings + + if(!is.null(attribute_df)){ + attribute_df <- to_plot_df$attributes + } + + if(!is.null(fill_name)){ + fill_value <- attribute_df[,fill_name] + if(is.null(fill_range)){ + fill_range <- range(fill_value, na.rm = TRUE) + } + } + + cat(""\n"") + print(""Getting Plot Positions"") + time_pts <- colnames(freq_mat) + plot_pos_df <- get_pos(clones, parents, freq_mat, as.numeric(time_pts)) + + + if(interpolation_steps > 0){ + cat(""\n"") + print(""Smoothing Polygons"") + plot_pos_df <- smooth_pos(plot_pos_df, n_intermediate_steps = interpolation_steps, interp_method=interp_method) + } + plot_pos_df$extinction_time <- max(plot_pos_df$x) + + true_time_pt_idx <- which(colnames(freq_mat) %in% og_time_pts) + for(cidx in seq(1, length(clones))){ + clone_freq <- freq_mat[cidx, true_time_pt_idx] + zero_idx <- which(clone_freq==0) + origin_time <- which(clone_freq!=0)[1] + time_dif <- origin_time - zero_idx + if(any(time_dif < 0)){ + extinction_time_idx <- zero_idx[which(time_dif < 0)[1]] + # extinction_time <- as.numeric(names(time_dif)[extinction_time_idx]) + extinction_time <- og_time_pts[extinction_time_idx] + cidx_in_pos_df <- which(plot_pos_df$clone_id == clones[cidx]) + plot_pos_df$extinction_time[cidx_in_pos_df] <- extinction_time + } + } + + ### Supply attribute name since using deparse inside get_evofreq will return fill_value for the name of the attribute + plot_pos_df <- update_colors(evo_freq_df = plot_pos_df, clones = clones, fill_value = fill_value, clone_cmap = clone_cmap, fill_range = fill_range, fill_name=fill_name, shuffle_colors = shuffle_colors) + + if(!scale_by_sizes_at_time){ + plot_pos_df$y <- plot_pos_df$y*max_mutation_size + plot_pos_df$y_label <- ""Population Size"" + + }else{ + plot_pos_df$y_label <- ""Frequency"" + } + + + plot_pos_df$row_id <- seq(1, nrow(plot_pos_df)) + updated_time_pts <- unique(plot_pos_df$x) + ###Replace closest x value with original timepoint value before merge + for(tpt in time_pt_df$x){ + closest_x_idx <- which.min(abs(as.numeric(tpt) - updated_time_pts)) + closest_x <- updated_time_pts[closest_x_idx] + plot_pos_df$x[which(plot_pos_df$x==closest_x)] <- as.numeric(tpt) + } + + plot_pos_df <- merge(plot_pos_df, time_pt_df, by=""x"", all=TRUE) + plot_pos_df <- plot_pos_df[order(plot_pos_df$row_id), ] + + return(plot_pos_df) +} + +scale_values <- function(x, out_range=c(0, 1)){ + a <- min(out_range) + b <- max(out_range) + in_min <- min(x, na.rm = TRUE) + in_max <- max(x, na.rm = TRUE) + + scaled_x <- (b-a)*(x-in_min)/(in_max - in_min) + a + + return(scaled_x) +} + +get_genomes <- function(c_list, p_list, out=""binary""){ + ###out=binary or bases + n_clones <- length(c_list) + if(out==""binary""){ + gene_mat <- matrix(0, nrow=n_clones, ncol=n_clones) + }else{ + bases <- c(""A"", ""C"", ""T"", ""G"") + gene_mat <- matrix(sample(bases, n_clones**2, replace = TRUE), nrow=n_clones, ncol=n_clones) + } + + row.names(gene_mat) <- c_list + for(i in seq(c_list)){ + cid <- c_list[i] + children_idx <- get_all_idx(cid, c_list, p_list) + if(out==""binary""){ + gene_mat[children_idx, i] <- 1 + }else{ + gene_mat[children_idx, i] <- sample(bases, 1) + } + } + + return(as.matrix(gene_mat)) +} + +traverse <- function(c, clones, parents, fnx){ + f <- match.fun(fnx) + f(c, clones) + for(n in get_children(c, clones, parents)){ + traverse(n, clones, parents, fnx) + } +} + +fill_in_gaps <- function(size_array){ + #' + #' + ### FOR TESTING ### + # og_size_array <- c(0,0,0,1,2,3,4,0,0,0, 1, 2, 3, 0, 0, 1, 2, 0, 0) + # size_array <- og_size_array + ####### + + + above_zero_size_idx <- which(size_array > 0) ### indices for size array + time_between_non_zero_idx <- diff(above_zero_size_idx) ## If there are no gaps in sizes, all these should be 1. Dif is difference between idx and idx + 1 + left_side_of_above_0_gap_idx <- above_zero_size_idx[which(time_between_non_zero_idx > 1)] ### which indices in the original array are to the left side of a gap + + for(lidx in left_side_of_above_0_gap_idx){ + left_size <- size_array[lidx] + + temp_above_zero_idx <- which(size_array>0) + right_non_zero_idx <- temp_above_zero_idx[which(temp_above_zero_idx>lidx)][1] + right_size <- size_array[right_non_zero_idx] + + m <- (left_size-right_size)/(lidx-right_non_zero_idx) + b <- left_size - m*lidx + time_btwn <- seq(lidx+1, right_non_zero_idx - 1) + sizes_btwn <- m*time_btwn + b + size_array[time_btwn] <- sizes_btwn + } + return(size_array) +} + +check_for_missing_links_fnx <- function(clones, parents){ + for(cid in clones){ + get_ancestor_idx_evo_freq(cid, clone_list = clones, parent_list = parents) + } + return(""No missing links"") +} + +check_and_update_edges <- function(clones, parents, check_for_missing_links=TRUE){ + ##### FOR TESTING ### + # clones <- clone_list + # parents <- parent_list + ###### + + ### Make sure each clone only appears once in edge list + if(all(as.numeric(table(clones)) != 1)){ + warning(""Clone occurs more than once in edgelist"") + } + + ### Update so that parent of root has an id not in the clone_list. + clone_as_parent_idx <- which(clones==parents) + if(length(clone_as_parent_idx)>0){ + if(length(clone_as_parent_idx)>1){ + warning(""More than 1 clone is its own parent. Cannot determine root"") + } + rand_parent_id <- stats::runif(1, min = -1, max=0) + parents[clone_as_parent_idx] <- rand_parent_id + } + + ### Determine if root can be found ### + root_id <- get_root_id(clones, parents) + + return(list(""updated_clones""=clones, ""updated_parents""=parents)) +} + +check_freq_mat <- function(freq_mat, clones, parents){ + ### FOR TESTING ### + # freq_mat <- mutation_df + # clones <- clone_list + # parents <- parent_list + ######### + + ### Make sure total number children carrying the mutation ### + for(i in seq(1, length(clones))){ + cln <- clones[i] + cln_freq <- freq_mat[i, ] + all_children_idx <- get_all_idx(cln, clones, parents) + children <- clones[all_children_idx] + children_idx <- all_children_idx[clones[all_children_idx] != cln] + if(length(children == 0)){ + next + } + children_df <- freq_mat[children_idx, ] + parent_greater_than_children <- apply(children_df, 1, function(x){all(cln_freq>=x)}) + if(all(parent_greater_than_children)==FALSE){ + too_big_idx <- which(parent_greater_than_children==FALSE) + clones_too_big <- clones[too_big_idx] + stop(paste(cln, ""has descendent mutations greater than that are greater than it's size. Descendents are:"", clones_too_big)) + } + } +} + +#'\code{get_mutation_df} Converts sizes to the frequency of the mutations in the population +#'@inheritParams get_evofreq +#'@param clone_size_df Dataframe in a wide format, where each row corrsponds to a single clone, and the columns are the sizes of that clone at each timepoint +#'@examples +#'data(""example.easy.wide"") +#'### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#'time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) +#'attribute_col_idx <-suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide))))) +#'attribute_df <- example.easy.wide[, attribute_col_idx] +#'size_df <- example.easy.wide[, time_col_idx] +#'parents <- example.easy.wide$parents +#'clones <- example.easy.wide$clones +#'### Size data can be converted to mutation counts for additional analyses, like calculating mutation frequencies +#'mutation_count_df <- get_mutation_df(size_df, clones, parents) +#'total_chromosomes <- 2*colSums(size_df) ### Calculation assumes that mutations are on a single chromosome +#'allele_frequency_df <- sweep(mutation_count_df,2,total_chromosomes,""/"") +#'@export +get_mutation_df <- function(clone_size_df, clones, parents){ + ### FOR TESTING #### + # clone_size_df <- as.data.frame(size_df) + # clones <- clone_list + # parents <- parent_list + #### + cat(""\n"") + print(""Getting Mutation Counts"") + greater_than_one_time_pt <- ncol(clone_size_df)>1 + mutation_df <- matrix(NA, nrow = nrow(clone_size_df), ncol = ncol(clone_size_df)) + + pb <- utils::txtProgressBar(min = 1, max = nrow(clone_size_df), style = 3) + for(i in seq(1, length(clones))){ + utils::setTxtProgressBar(pb, i) + cln <- clones[i] + all_children_idx <- get_all_idx(cln, clones, parents) + + child_sizes_df <- clone_size_df[all_children_idx, ] + if(greater_than_one_time_pt){ + total_cells_carrying_mutation <- colSums(child_sizes_df) ### recursion already includes adding the current clone + }else{ + total_cells_carrying_mutation <- sum(child_sizes_df) + } + + mutation_df[i, ] <- total_cells_carrying_mutation + + } + + # check_freq_mat(mutation_df, clones, parents) + colnames(mutation_df) <- colnames(clone_size_df) + rownames(mutation_df) <- rownames(clone_size_df) + return(mutation_df) +} + +predict_sizes <- function(x1, y1, x2, y2, new_x){ + ### FOR Testing ### + # y1 <- 1.00 + # y2 <- 0.02 + # x1 <- 0 + # x2 <- 30 + # new_x <- 15 + #### + + + fit <- stats::lm(c(y1, y2) ~ c(x1, x2)) + new_y <- fit$coefficients[[1]] + fit$coefficients[[2]]*new_x + return(new_y) +} + +make_pointy <- function(dull_mat){ + ### FOR TESTING ### + # dull_mat <- new_mat + #### + ### Make that polygons do not have abrupt starts and stops + ### Set size to 1 for intermediate timestep before origin + ### If clone went extinct, set intemediate time step after extinction to 1 + + + time_pts <- colnames(dull_mat) + max_time <- max(time_pts) + min_time <- min(time_pts) + for(cidx in seq(nrow(dull_mat))){ + # cidx <- 2 + clone_origin_time_idx <- which(dull_mat[cidx, ] > 0)[1] + clone_origin_time <- time_pts[clone_origin_time_idx] + if(clone_origin_time > min_time){ + dull_mat[cidx, clone_origin_time_idx-1] <- 0.0001 + } + time_zero_idx <- which(dull_mat[cidx, ] == 0) + if(length(time_zero_idx) > 0){ + + if(any(time_zero_idx > clone_origin_time_idx)){ + extinction_time <- names(which(time_zero_idx > clone_origin_time_idx)[1]) + extinction_time_idx <- which(time_pts == extinction_time) + dull_mat[cidx, extinction_time_idx] <- 0.0001 + + } + } + } + return(dull_mat) +} + +interp_mut_mat <- function(mut_mat, time_pts= NULL){ + #For each clone, estimate intermediate sizes + ### FOR TESTING ### + # mut_mat <- og_mut_mat + # time_pts <- og_time_pts + #### + + if(is.null(time_pts)){ + time_pts <- seq(1, ncol(mut_mat)) + } + + intermediate_vals <- mapply(i=seq(2, length(time_pts)), FUN=function(i){(time_pts[i]-time_pts[i-1])/2 + time_pts[i-1]}) + new_times <- rep(NA, length(time_pts)+length(intermediate_vals)) + og_time_idx <- seq(1, length(new_times),2) + new_time_idx <- seq(2, length(new_times)-1,2) + + new_times[og_time_idx] <- time_pts + new_times[new_time_idx] <- intermediate_vals + n_new_times <- length(new_times) + ## Increase width of matrix + + new_mat <- matrix(NA, nrow=nrow(mut_mat), ncol=n_new_times) + colnames(new_mat) <- new_times + row.names(new_mat) <- row.names(mut_mat) + + # max_time <- max(time_pts) + # min_time <- min(time_pts) + + for(cidx in seq(nrow(new_mat))){ + # cidx <- 2 + clone_sizes <-as.numeric( mut_mat[cidx, ]) + intermediate_sizes <- mapply(i=seq(2, length(time_pts)), function(i){ + # i <- 2 + if(clone_sizes[i]== 0 | clone_sizes[i-1]== 0){ + return(0) + } + + # + fit <- stats::lm(c(clone_sizes[i], clone_sizes[i-1]) ~ c(time_pts[i], time_pts[i-1])) + new_y <- fit$coefficients[[1]] + fit$coefficients[[2]]* intermediate_vals[i-1] + # new_y <- fit$coefficients[[1]] + fit$coefficients[[2]]* intermediate_vals[i] + return(new_y) + }) + # intermediate_sizes <- clone_sizes[1:length(clone_sizes)-1] + diff(clone_sizes)/2 + new_mat[cidx, og_time_idx] <- clone_sizes + new_mat[cidx, new_time_idx] <- intermediate_sizes + + } + + new_mat <- make_pointy(new_mat) + return(new_mat) + +} + +order_clones_at_time <- function(clones_at_time, parents, clones){ + ### possible that parent and child arose within the same period. Need to ensure that parents are drawn first + + #### For testing ### + # clones_at_time <- parents_at_time + # parents <- parents + # clones <- clones + #### + root_id <- get_root_id(clones, parents) + n_clones <- length(clones_at_time) + n_ancestors_in_t <- rep(NA, n_clones) + + for(ct_i in seq(n_clones)){ + cid <- clones_at_time[ct_i] + if(cid==root_id){ + ### makes sure root is always drawn first + n_ancestors_in_t[ct_i] <- -1 + next() + } + ancestor_idx <- get_ancestor_idx_evo_freq(cid, clones, parents) + if(is.null(ancestor_idx)){ + n_ancestors_in_t[ct_i] <- 0 + }else{ + n_ancestors_in_t[ct_i] <- length(ancestor_idx) + } + } + new_order <- order(n_ancestors_in_t, decreasing = FALSE) + clones_at_time_ordered <- clones_at_time[new_order] + + return(clones_at_time_ordered) +} + +distribute_x <- function(x){ + #### For testing #### + # x <- seq(1, 6) + # x <- c(1) + # x <- c(1800, 2008, 2166, 2202, 3564, 3694) + ##################### + + ### Put even numbers on one side of first point, odd numbers on the other + x_idx <- seq(2, length(x)) + even_idx <- x_idx[x_idx %% 2 == 0] + odd_idx <- x_idx[x_idx %% 2 != 0] + new_order_idx <- c(rev(even_idx), 1, odd_idx) + new_order <- x[new_order_idx] + return(new_order) +} + +filter_freq_mat <- function(clones, parents, freq_mat, threshold, attr_vals=NULL){ + ### FOR TESTING ### + # attr_vals <- attribute_vals + ## + max_freqs <- apply(freq_mat, 1, max) + above_thresh_idx <- which(max_freqs >= threshold) + + filtered_freq_mat <- freq_mat[above_thresh_idx, ] + filtered_clones <- clones[above_thresh_idx] + filtered_parents <- parents[above_thresh_idx] + if(!is.null(attr_vals)){ + filtered_attr_vals <- attr_vals[above_thresh_idx] + }else{ + filtered_attr_vals <- NULL + } + + return_vals <- list('freq_mat'=filtered_freq_mat, 'clones'= filtered_clones, 'parents'=filtered_parents, 'attr_vals'=filtered_attr_vals, 'thresh_idx'=above_thresh_idx) +} + +linear_interp_point <- function(x1, x2, y1, y2){ + #### FOR TESTING #### + # x1 <- new_x[fp_idx-1] + # x2 <- new_x[fp_idx+1] + # y1 <- new_forward[fp_idx-1] + # y2 <- new_forward[fp_idx+1] + ##### + m <- (y1-y2)/(x1-x2) + b <- y1 - m*x1 + middle_x <- 0.5*(x1 + x2) + new_y <- m*middle_x + b + return(new_y) +} + +get_linear_m_and_b <- function(x1, x2, y1, y2){ + #### FOR TESTING #### + # x1 <- new_x[fp_idx-1] + # x2 <- new_x[fp_idx+1] + # y1 <- new_forward[fp_idx-1] + # y2 <- new_forward[fp_idx+1] + ##### + m <- (y1-y2)/(x1-x2) + b <- y1 - m*x1 + return(list(""m""=m, ""b""=b)) +} + +smooth_pos <- function(sparse_pos_df, n_intermediate_steps=20, interp_method = ""monoH.FC""){ + ###FOR TESTING ## + # sparse_pos_df <- evo_pos + # n_intermediate_steps <- 3 + # interp_method <- ""bezier"" + ### + + interp_df_list <- list() + unique_clones <- unique(sparse_pos_df$clone_id) + n_clones <- length(unique_clones) + + all_x <- unique(sparse_pos_df$x) + x_range <- range(all_x, na.rm = TRUE) + all_new_x <- seq(x_range[1], x_range[2], length.out = length(all_x)*n_intermediate_steps) + + pb <- utils::txtProgressBar(min = 0, max = n_clones, style = 3) + for(i in seq(n_clones)){ + # print(i) + # i <- 4 + cid <- unique_clones[i] + utils::setTxtProgressBar(pb, i) + clone_pos_df <- subset(sparse_pos_df, clone_id==cid) + nx <- length(unique(clone_pos_df$x)) + + if(nx >= 4){ + + forward_idx <- which(duplicated(clone_pos_df$x)==FALSE) + forward_df <- clone_pos_df[forward_idx,] + ###GO BACK TO THIS?? + # new_x <- seq(min(forward_df$x), max(forward_df$x), length.out = length(forward_df$x)*n_intermediate_steps) + ### + + clone_x_range <- range(forward_df$x) + new_x <- all_new_x[all_new_x >= clone_x_range[1] & all_new_x <= clone_x_range[2]] + + ### need at least 4 points for spline interpolation + # print(interp_method) + # print(interp_method %in% c(""fmm"", ""periodic"", ""natural"", ""monoH.FC"", ""hyman"")) + if(interp_method %in% c(""fmm"", ""periodic"", ""natural"", ""monoH.FC"", ""hyman"")){ + # print(""FW"") + # interp_method <- ""monoH.FC"" + func = stats::splinefun(x=forward_df$x, y=forward_df$y, method=interp_method, ties = mean) + new_forward <- func(new_x) + new_forward_x <- new_x + + }else if(interp_method==""bezier""){ + bezier_forward_x <- seq(0, 1, length.out = length(new_x)) + forward_bezier_points <- bezier::bezier(t=bezier_forward_x, p=forward_df[,c(""x"",""y"")]) + new_forward <- forward_bezier_points[, 2] + new_forward_x <- forward_bezier_points[, 1] + + }else if(interp_method==""bezier_curve_fit""){ + bezier_forward_x <- seq(0, 1, length.out = length(new_x)) + bz_forward_fit <- suppressWarnings(bezier::bezierCurveFit(as.matrix(forward_df[,c(""x"",""y"")]), na.fill = TRUE, maxiter=500, max.rse.percent.change = 0.2, fix.start.end = TRUE)) + forward_bezier_points <- bezier::bezier(t=bezier_forward_x, p=bz_forward_fit$p) + new_forward <- forward_bezier_points[, 2] + new_forward_x <- forward_bezier_points[, 1] + }else if(interp_method==""loess""){ + fit <- loess(forward_df$y ~ forward_df$x) + new_forward <- predict(fit, new_x) + new_forward_x <- new_x + } + + + reverse_idx <- which(duplicated(clone_pos_df$x)==TRUE) + reverse_df <- clone_pos_df[reverse_idx,] + + if(interp_method %in% c(""fmm"", ""periodic"", ""natural"", ""monoH.FC"", ""hyman"")){ + # print(""REVERSE"") + rev_func = stats::splinefun(x=rev(reverse_df$x), y=rev(reverse_df$y), method=interp_method, ties = mean) ### x has to increase + new_reverse <- rev_func(new_x) + new_reverse_x <- rev(new_x) + + }else if(interp_method==""bezier""){ + bezier_reverse_x <- seq(0, 1, length.out = length(new_x)) + reverse_bezier_points <- bezier::bezier(t=bezier_reverse_x, p= reverse_df[seq(nrow(reverse_df), 1),c(""x"",""y"")]) + new_reverse <- reverse_bezier_points[, 2] + new_reverse_x <- rev(reverse_bezier_points[, 1]) + }else if(interp_method==""bezier_curve_fit""){ + bezier_reverse_x <- seq(0, 1, length.out = length(new_x)) + bz_reverse_fit <- suppressWarnings(bezier::bezierCurveFit(as.matrix(reverse_df[seq(nrow(reverse_df), 1),c(""x"",""y"")]), na.fill = TRUE, maxiter=500, max.rse.percent.change = 0.2, fix.start.end = TRUE)) + reverse_bezier_points <- bezier::bezier(t=bezier_reverse_x, p=bz_reverse_fit$p) + new_reverse <- reverse_bezier_points[, 2] + new_reverse_x <- rev(reverse_bezier_points[, 1]) + }else if(interp_method==""loess""){ + rev_fit <- loess(rev(reverse_df$y) ~ rev(reverse_df$x)) + new_reverse <- predict(rev_fit, new_x) + new_forward_x <- rev(new_x) + } + + + #### Make sure that there are no times where the bottom and top cross. Bottom (forward) should always be less than top (reverse) + rev_forward_dist <- new_reverse - new_forward + flip_idx <- which(rev_forward_dist < 0) + n_new_x <- length(new_x) + if(length(flip_idx) > 0){ + # fp_idx <- 2 + for(fp_idx in flip_idx){ + updated_dist <- new_reverse[fp_idx] - new_forward[fp_idx] + if(updated_dist > 0){ + #### position was already updated + next() + } + if(fp_idx > n_new_x | n_new_x <= 1 | fp_idx == 1){ + ### first and last point are the new pointy ends. This just flips them to make a triangle + replace_forward <- new_reverse[fp_idx] + replace_reverse <- new_forward[fp_idx] + new_forward[fp_idx] <- replace_forward + new_reverse[fp_idx] <- replace_reverse + + }else{ + + + ### For forward: get next positive difference (should have been negative because forward should be < reverse). Connect to that point. Will also need to update any other points along that path + next_seq <- seq(fp_idx+1, n_new_x) + # next_positive_idx <- fp_idx + which(rev_forward_dist[fp_idx+1:n_new_x] > 0)[1] + next_positive_idx <- fp_idx + which(rev_forward_dist[next_seq] > 0)[1] + if(is.na(next_positive_idx)){ + ###ALL positions after this one need to be flipped + replace_forward <- new_reverse[next_seq] + replace_reverse <- new_forward[next_seq] + new_forward[next_seq] <- replace_forward + new_reverse[next_seq] <- replace_reverse + break() + } + replace_seq <- seq(fp_idx, next_positive_idx - 1) + + forward_lm <- get_linear_m_and_b(new_x[fp_idx-1], new_x[next_positive_idx], new_forward[fp_idx-1], new_forward[next_positive_idx]) + new_forward[replace_seq] <- forward_lm$m*new_x[replace_seq] + forward_lm$b + # new_forward[replace_seq] <- func(forward_lm$m*new_x[replace_seq] + forward_lm$b) + + ### For reverse: get next negative difference. Connect to that point. Will also need to update any other points along that path + reverse_lm <- get_linear_m_and_b(new_x[fp_idx-1], new_x[next_positive_idx], new_reverse[fp_idx-1], new_reverse[next_positive_idx]) + new_reverse[replace_seq] <- reverse_lm$m*new_x[replace_seq] + reverse_lm$b + + # replace_forward <- linear_interp_point(new_x[fp_idx-1], new_x[fp_idx+1], new_forward[fp_idx-1], new_forward[fp_idx+1]) + # replace_reverse <- linear_interp_point(new_x[fp_idx-1], new_x[fp_idx+1], new_reverse[fp_idx-1], new_reverse[fp_idx+1]) + } + + # if(replace_reverse - replace_forward ){ + # new_forward[fp_idx] <- replace_reverse + # new_reverse[fp_idx] <- replace_forward + # }else{ + + } + } + + # print(c(length(new_x), length(new_forward), length(new_reverse))) + new_forward_df <- data.frame('x'=new_x, 'y'=new_forward, 'clone_id'=clone_pos_df$clone_id[1], 'parent'=clone_pos_df$parent[1], 'origin_time'=clone_pos_df$origin_time[1], 'draw_order'=clone_pos_df$draw_order[1]) + new_reverse_df <- data.frame('x'=rev(new_x), 'y'=rev(new_reverse), 'clone_id'=clone_pos_df$clone_id[1], 'parent'=clone_pos_df$parent[1], 'origin_time'=clone_pos_df$origin_time[1], 'draw_order'=clone_pos_df$draw_order[1]) + + # new_forward_df <- data.frame('x'=new_forward_x, 'y'=new_forward, 'clone_id'=clone_pos_df$clone_id[1], 'parent'=clone_pos_df$parent[1], 'origin_time'=clone_pos_df$origin_time[1], 'draw_order'=clone_pos_df$draw_order[1]) + # new_reverse_df <- data.frame('x'=new_reverse_x, 'y'=rev(new_reverse), 'clone_id'=clone_pos_df$clone_id[1], 'parent'=clone_pos_df$parent[1], 'origin_time'=clone_pos_df$origin_time[1], 'draw_order'=clone_pos_df$draw_order[1]) + + new_clone_pos_df <- rbind(new_forward_df, new_reverse_df) + + # gp <- ggplot2::ggplot(new_clone_pos_df, ggplot2::aes(x=x, y=y)) + + # ggplot2::geom_polygon() + # print(gp) + + + }else{ + new_clone_pos_df <- clone_pos_df[colnames(clone_pos_df) != ""size""] + } + interp_df_list[[as.character(cid)]] <- new_clone_pos_df + } + interp_df <- do.call(rbind, interp_df_list) + + + ### interpolation may cause points to go out of bounds + interp_df$y[interp_df$y < 0] <- 0 + interp_df$y[interp_df$y > 1] <- 1 + + + return(interp_df) + +} + +#'\code{plot_evofreq} Plots the frequency dynamics using ggplot. Can also use info to create animations +#'@param freq_frame Proper dataframe returned by \code{\link{get_evofreq}} +#'@param n_time_pts Integer defining how many time points to plot, evenly spaced between \code{start_time} and \code{end_time}. If NULL, all timepoints are plotted +#'@param start_time Integer defining the timepoint at which to start plotting frequency dynamics. If NULL, plotting will begin at the first timepoint +#'@param end_time Integer defining the timepoint at which to stop plotting frequency dynamics. If NULL, plotting will end at the last timepoint +#'@param bw width of lines surrounding polygons +#'@param bc color of lines surrounding polygons +#'@param show_axes Whether to display axes +#'@param fill_range Array containing the minimum and maximum values to set the range of colors. If NULL (the default), the range is determined directly from \code{fill_value}. +#'@return ggplot of the frequency dynamics +#'@examples +#' +#' data(""example.easy.wide.with.attributes"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' size_df <- example.easy.wide.with.attributes[, time_col_idx] +#' parents <- example.easy.wide.with.attributes$parent +#' clones <- example.easy.wide.with.attributes$clone +#' fitness <- example.easy.wide.with.attributes$fitness +#' +#' #' +#' ### Setting of colors can be done when getting the freq_frame, or by updating the color later using \code{\link{update_colors}}. For a list of available colormaps, see https://github.com/bhaskarvk/colormap. +#' ### Default colormap is rainbow_soft, but this can be changed using the \code{clone_cmap} argument. +#' freq_frame <- get_evofreq(size_df, clones, parents) +#' evo_p <- plot_evofreq(freq_frame) +#' +#' ### Can color each clone by an attribute by providing a \code{fill_value}. Default colormap is viridis, but this can be changed using the \code{clone_cmap} argument +#' fitness <- runif(length(clones)) +#' fitness_freq_frame <- get_evofreq(size_df, clones, parents, fill_value = fitness) +#' fitness_evo_p <- plot_evofreq(fitness_freq_frame) +#' #' +#' ### The user can also provide custom colors for each clone, which will need to be passed into the \code{fill_value} argument +#' ### Custom colors can be defined using RGB values. Each color should be a string specifying the color channel values, separated by commas. +#' rgb_clone_colors <- sapply(seq(1, length(clones)), function(x){paste(sample(0:255,size=3,replace=TRUE),collapse="","")}) +#' rgb_freq_frame <- get_evofreq(size_df, clones, parents, rgb_clone_colors) +#' rgb_evo_p <- plot_evofreq(rgb_freq_frame) +#' +#' ### Custom colors can also be any of the named colors in R. A list of the colors can be found with \code{colors()} +#' named_clone_colors <- sample(colors(), length(clones), replace = FALSE) +#' named_freq_frame <- update_colors(rgb_freq_frame, clones = clones, fill_value = named_clone_colors) +#' named_evo_p <- plot_evofreq(named_freq_frame) +#' +#' ### Custom colors can also be specified using hexcode +#' hex_clone_colors <- c(""#614099ff"", ""#1d347eff"", ""#94558aff"", ""#c96872ff"", ""#f1884dff"", ""#e8fa5bff"", ""#042333ff"",""#f9bb41ff"") +#' hex_freq_frame <- update_colors(rgb_freq_frame, clones = clones, fill_value = hex_clone_colors) +#' hex_evo_p <- plot_evofreq(hex_freq_frame) +#' +#' ### Can revert back to original colors +#'freq_frame_default_color <- update_colors(fitness_freq_frame, clones=clones) +#'default_cmap_evo_p <- plot_evofreq(freq_frame_default_color) +#' +#'### Can add gganimate objects to evo_p_by_size to create the animation +#' +#'\donttest{ +#' library(gganimate) +#' movie_p <- fitness_evo_p + +#' transition_reveal(x, range=range(fitness_freq_frame$x)) + +#' view_follow() +#' # print(movie_p) +#' anim_save(""evofreq_movie.gif"", movie_p) +#' } +#'@export +plot_evofreq <- function(freq_frame, n_time_pts=NULL, start_time=NULL, end_time=NULL, bw=0.05, bc=""grey75"", show_axes=TRUE, fill_range=NULL){ + + ### FOR TESTING ### + # n_time_pts <- NULL + # start_time <- NULL + # end_time <- NULL + # bw <- 0.05 + # bc <- ""grey75"" + # freq_frame <- hal_plot_df + ##### + + unique_time_pts <- unique(freq_frame$x) + if(is.null(n_time_pts)){ + n_time_pts <- length(unique_time_pts) + } + if(is.null(start_time)){ + start_time <- 0 + } + if(is.null(end_time)){ + end_time <- max(freq_frame$x) + } + + + # end_time <- 50 + view_df <- subset(freq_frame, x <= end_time) + + color_attribute_name <- unique(view_df$efp_color_attribute) + if(is.na(color_attribute_name)){ + color_attribute_name <- ""plot_color"" + }else{ + if(is.null(fill_range)){ + fill_range <- range(view_df[, color_attribute_name], na.rm = TRUE) + } + + # color_df <- view_df[duplicated(view_df$plot_color)==FALSE, ] + # color_df <- color_df[order(color_df[color_attribute_name]), ] + # colorbar_colors <- color_df$plot_color + # + } + + + # all_x_maxs_at_time <- aggregate(x ~ clone_id, data=subset(view_df, extinction_time >= end_time), FUN=max) + # max_x <- min(all_x_maxs_at_time$x) + # view_df$x <- as.numeric(view_df$x) + time_pts_df <- unique(view_df[complete.cases(view_df[""Time_label""]), ][c(""x"", ""Time_label"")]) + time_pts_df$x <- as.numeric(as.character(time_pts_df$x)) + time_pts_df <- time_pts_df[order(time_pts_df$x), ] + time_pts_df <- subset(time_pts_df, x > 0) + time_pts_df$Time_label <- as.character(time_pts_df$Time_label) + # time_pts_df$Time_label <- as.character(as.numeric(time_pts_df$Time_label)) + + # time_pts_df$Time_label[1] <- ""0"" ### TODO Why is this being set to 0? + + y_label <- unique(freq_frame$y_label) + + ggevodyn <- ggplot2::ggplot(view_df, ggplot2::aes_string(x=""x"", y=""y"", group=""draw_order"", fill=color_attribute_name)) + + ggplot2::geom_polygon(size=bw, color=bc) + + ggplot2::ylab(y_label) + + ggplot2::xlab(""Time"") + + ggplot2::theme_classic() + + ggplot2::scale_x_continuous(breaks=as.numeric(as.character(time_pts_df$x)), labels=as.character(time_pts_df$Time_label)) + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1)) + + if(color_attribute_name==""plot_color""){ + ggevodyn <- ggevodyn + ggplot2::scale_fill_identity() + }else{ + colormap_name <- unique(view_df$cmap) + colorbar_colors <- get_colors(100, colormap_name) + ggevodyn <- ggevodyn + ggplot2::scale_fill_gradientn(colours = colorbar_colors, limits=fill_range) #colormap::scale_fill_colormap(color_attribute_name, colormap=colormap_name) + # ggevodyn <- ggevodyn + colormap::scale_fill_colormap(color_attribute_name, colormap=colormap_name, limits=fill_range) + } + + if(! show_axes){ + ggevodyn <- ggevodyn + ggplot2::theme_void() + } + return(ggevodyn) +} + +#'Convert data in long format to wide format +#'\code{long_to_wide_freq_ready} Converts long data frame to wide format used by evofreq. +#'@param edges_df Dataframe with 2 columns, where each row defines relation between each clone and their parent. One column contains the clone ids, and the other contains the id of that clone's parent. +#'@param long_pop_sizes_df Dataframe with 3 columns, one containing the clone id, one containing the time points, and one containing the size of the clone at that time point. There must be a size for each clone at every time point, so it did not exist, it's size is 0. +#'@param time_col_name String that specifies which column in long_pop_sizes_df contains the timepoint information +#'@param clone_col_name String that specifies which column in in edges_df contains the names of the clones. I.e. the ""to"" node in a graph +#'@param parent_col_name String that specifies which column in in edges_df contains the names of the parents of the descendent clone in the edges_df with colname clone_col_name. #I.e. the ""from"" node in a graph +#'@param size_col_name String that specifies which column in long_pop_sizes_df contains the size of each clone for the corresponding timepoint and clone in long_pop_sizes_df +#'@param fill_gaps_in_size Boolean specificing if gaps in sizes over time should be filled in, assuming linear changes. +#'@return List containing: wide_size_df, a dataframe of the sizes in wide format, where each row contains the sizes over time for a single clone; parents, a vector containing the parent id for each clone in clones; clones, a vector of clones ids correspond to each row in wide_size_df +#'@examples +# ### Input needs to be in wide format, but can convert long format data to wide format using \code{long_to_wide_freq_ready} +# wide_df_info <- long_to_wide_freq_ready(long_pop_sizes_df = example.easy.long.sizes, time_col_name = ""Time"", clone_col_name = ""clone"", parent_col_name = ""parent"", size_col_name = ""Size"", edges_df = example.easy.long.edges) +# clones_from_long <- wide_df_info$clones +# parents_from_long <- wide_df_info$parents +# size_df_from_long <- wide_df_info$wide_size_df +# pos_from_long_df <- get_evofreq(size_df_from_long, clones_from_long, parents_from_long) +# evo_p_from_long <- plot_evofreq(pos_from_long_df) +#'@export +long_to_wide_freq_ready <- function(edges_df, long_pop_sizes_df, time_col_name, clone_col_name, parent_col_name, size_col_name, fill_gaps_in_size=FALSE){ + long_pop_sizes_df <- as.data.frame(long_pop_sizes_df) + unique_times <- unique(long_pop_sizes_df[,time_col_name]) + unique_times <- unique_times[order(unique_times)] + n_time_pts <- length(unique_times) + + clones_in_edge_df <- edges_df[, clone_col_name] + parents_in_edge_df <- edges_df[, parent_col_name] + clones_in_size_df <- unique(long_pop_sizes_df[,clone_col_name]) + clones_not_in_clone_list <- clones_in_size_df[!clones_in_size_df %in% clones_in_edge_df] + + if(length(clones_not_in_clone_list)>0){ + if(length(clones_not_in_clone_list)>1){ + stop(""More thant 1 clone in size data frame but not in clone list"") + } + warning(""Clone in size data frame but not in clone list. Assuming this is the root"") + rand_parent_id <- stats::runif(1) + clones_in_edge_df <- c(clones_in_edge_df, clones_not_in_clone_list) + parents_in_edge_df <- c(parents_in_edge_df, rand_parent_id) + }else{ + # root_id <- get_root_id(clones_in_edge_df, parents_in_edge_df) + clone_as_parent_idx <- which(parents_in_edge_df==clones_in_edge_df) + if(length(clone_as_parent_idx)>0){ + rand_parent_id <- stats::runif(1) + parents_in_edge_df[clone_as_parent_idx] <- rand_parent_id + # clones_in_edge_df <- c(clones_in_edge_df, clones_not_in_clone_list) + # parents_in_edge_df <- c(parents_in_edge_df, rand_parent_id) + if(length(clone_as_parent_idx)>1){ + warning(""More than 1 clone is its own parent. Cannot determine root"") + } + } + } + + edges_df <- data.frame(parents_in_edge_df, clones_in_edge_df) + names(edges_df) <- c(parent_col_name, clone_col_name) + + n_clones <- length(clones_in_edge_df) + size_mat <- matrix(0, nrow=n_clones, ncol=length(unique_times)) + colnames(size_mat) <- unique_times + + size_mat_rownames <- rep(NA, n_clones) + cat(""\n"") + print(""Converting From Long to Wide Format"") + pb <- utils::txtProgressBar(min = 1, max = n_clones, style = 3) + for(i in seq(n_clones)){ + utils::setTxtProgressBar(pb, i) + cid <- clones_in_edge_df[i] + cidx <- which(long_pop_sizes_df[clone_col_name]==cid) + if(length(cidx)== 0){ + size_mat[i, ] <- 0 + }else{ + cid_sizes <- long_pop_sizes_df[cidx, size_col_name] + cid_times <- long_pop_sizes_df[cidx, time_col_name] + c_time_idx <- sapply(cid_times, function(x){which(unique_times==x)}) + + size_mat[i, c_time_idx] <- cid_sizes + } + size_mat_rownames[i] <- cid + } + rownames(size_mat) <- size_mat_rownames + + if(fill_gaps_in_size){ + wide_size_df <- as.data.frame(t(apply(size_mat, 1, fill_in_gaps))) + }else{ + wide_size_df <- as.data.frame(size_mat) + } + + return(list(""wide_size_df""=wide_size_df, ""parents""=edges_df[, parent_col_name], ""clones""=edges_df[, clone_col_name])) + + + + ###Reorder edges so that they are the same as + # long_pop_sizes_df <- long_pop_sizes_df[order(long_pop_sizes_df[,time_col_name]),] + # wide_size_df <- reshape(as.data.frame(long_pop_sizes_df), timevar = time_col_name, idvar = clone_col_name, direction = ""wide"") + + # parents <- edges_df[, parent_col_name] + # clones <- edges_df[, clone_col_name] + # clones_in_size_df <- unique(long_pop_sizes_df[,clone_col_name]) + # clones_not_in_clone_list <- clones_in_size_df[!clones_in_size_df %in% clones] + # if(length(clones_not_in_clone_list)>0){ + # if(length(clones_not_in_clone_list)>1){ + # stop(""More thant 1 clone in size data frame but not in clone list"") + # } + # warning(""Clone in size data frame but not in clone list. Assuming this is the root"") + # rand_parent_id <- runif(1) + # clones <- c(clones, clones_not_in_clone_list) + # parents <- c(parents, rand_parent_id) + # edges_df <- data.frame(clones, parents) + # names(edges_df) <- c(clone_col_name, parent_col_name) + # }else{ + # + # } + + # wide_size_df <- merge(wide_size_df, edges_df) + + # ordered_clones <- wide_size_df[,clone_col_name] + # ordered_parents <- wide_size_df[,parent_col_name] + # ordered_size_df <- wide_size_df[,!colnames(wide_size_df) %in% c(clone_col_name, parent_col_name)] + # return(list(""wide_size_df""=ordered_size_df, ""parents""=ordered_parents, ""clones""=ordered_clones)) +} + +#' @title get_evofreq_labels +#' @param freq_frame Properly formatted dataframe from \code{\link{get_evofreq}}. +#' @param evofreq_plot Plot returned from \code{\link{plot_evofreq}}. +#' @param apply_labels Whether to plot the labels. Must include evofreq_plot if TRUE. Default FALSE. +#' @param custom_label_text Custom labels to use (e.g. c(""Mutant X"",""Mutant Y"")) +#' @param extant_only Get labels for only the extant clones. +#' @param clone_list Only label clones with this id. Passed as a vector. +#' @param line_color Single color value. Default ""black"". +#' @param adj.factor Value to scale the label and lines by so that they are far enough from the plot. Default value is 10 (a 10th of the distance between max/min at x from max/min across x). +#' @return Dataframe containing the necessary coordinates to add labels in the proper locations. +#' +#' @examples +#' data(""example.easy.wide"") # Load Data +#' ### Get frequency dataframe +#' freq_frame <- get_evofreq(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"") +#' evofreq_plot <- plot_evofreq(freq_frame) +#' clone_labels <- get_evofreq_labels(freq_frame, extant_only=FALSE) +#' +#' ### Set evofreq_plot and apply_labels = TRUE to get a labeled plot back +#' get_evofreq_labels(freq_frame, extant_only=FALSE, evofreq_plot = evofreq_plot, apply_labels = TRUE) +#' @export +get_evofreq_labels <- function(freq_frame, apply_labels=FALSE, custom_label_text=NULL, evofreq_plot=NULL, clone_list=NULL, extant_only=FALSE, line_color=""darkgrey"", adj.factor=10){ + ### FOR TESTING ### + # freq_frame <- freq_frame + # apply_labels=TRUE + # evofreq_plot=evo_freq_p + # extant_only=FALSE + # line_color=""darkgrey"" + # adj.factor=10 + # clone_list = NULL + #### + + # Get midpoint of clone + max_ever = max(freq_frame$y)[1] + min_ever = min(freq_frame$y)[1] + mid <- freq_frame[freq_frame$x==min(freq_frame$x),]$y[[1]] + spreader <- sd(freq_frame$x)/4. + # Split by clone + freq_frame_split <- split( freq_frame , f = freq_frame$clone_id ) + + # Main values + # position_list <- lapply(freq_frame_split, FUN=function(z){return( z[z$x==min(z$x),][1,c(1,2,3,4,7)] ) }) + info_cols <- c(""clone_id"", ""x"", ""y"", ""parent"", ""extinction_time"", ""plot_color"") + position_list <- lapply(freq_frame_split, FUN=function(z){return( z[z$x==min(z$x),][1,info_cols]) }) + position_df <- do.call(rbind, position_list) + # Get the max and min value at each x regardless of clone + position_df$max <- unlist(lapply(position_list, FUN=function(z){ return( max(freq_frame[ (freq_frame$xz$x-spreader),]$y) ) })) + position_df$min <- unlist(lapply(position_list, FUN=function(z){ return( min(freq_frame[ (freq_frame$xz$x-spreader),]$y) ) })) + + # Assign information based on midline + position_df$y_plotValue <- unlist(lapply(split( position_df , f = position_df$clone_id ), FUN=function(z){ if(z$y>mid){return(z$max+(abs(max_ever-z$max))/adj.factor)}else{return(z$min-(abs(z$min-min_ever))/adj.factor)} })) + + # Adjust if multiple have the same x: + + dup_x <- position_df$x[which(duplicated(position_df$x))] + keeper_df <- subset(position_df, ! x %in% dup_x) + for(dx in dup_x){ + x_df <- subset(position_df, x==dx) + new_mid <- mean(x_df$y) + x_df$y_plotValue <- unlist(lapply(split(x_df, f=x_df$clone_id), FUN=function(z){ if(z$y>new_mid){return(z$max+(abs(max_ever-z$max))/adj.factor)}else{return(z$min-(abs(z$min-min_ever))/adj.factor)} })) + keeper_df <- rbind(keeper_df, x_df) + } + position_df <- keeper_df + + + ### Get origin time, final time, and extinct/extant status + max_time <- max(freq_frame$x) + final_time_df <- aggregate(list(""final_time""=freq_frame$x), by = list(""clone_id"" = freq_frame$clone_id), FUN=max) + origin_time_df <- aggregate(list(""origin_time""=freq_frame$x), by = list(""clone_id"" = freq_frame$clone_id), FUN=min) + position_df <- Reduce(function(x, y) merge(x, y, all=TRUE, by=""clone_id""), list(position_df, origin_time_df, final_time_df)) + position_df$extant <- TRUE + position_df$extant[position_df$final_time < max_time] <- FALSE + if(extant_only){ + position_df <- subset(position_df, position_df$extant==TRUE) + } + + if(!is.null(clone_list)){ + position_df <- subset(position_df, position_df$clone_id %in% clone_list) + } else { + position_df <- position_df + } + + if(apply_labels & !is.null(evofreq_plot) & is.null(custom_label_text)){ + evo_freq_p_labeled <- evofreq_plot + geom_segment(data = position_df, aes(x=position_df$x,xend=position_df$x,y=position_df$y,yend=position_df$y_plotValue), color=line_color, size=1, inherit.aes = FALSE) + + geom_label(data=position_df, aes(x=position_df$x, y=position_df$y_plotValue, fill=position_df$plot_color, label=paste(""Clone"",position_df$clone_id)), color=""white"", inherit.aes = FALSE) + return(evo_freq_p_labeled) + } else if(apply_labels & !is.null(evofreq_plot) & !is.null(custom_label_text)) { + evo_freq_p_labeled <- evofreq_plot + geom_segment(data = position_df, aes(x=position_df$x,xend=position_df$x,y=position_df$y,yend=position_df$y_plotValue), color=line_color, size=1, inherit.aes = FALSE) + + geom_label(data=position_df, aes(x=position_df$x, y=position_df$y_plotValue, fill=position_df$plot_color, label=custom_label_text), color=""white"", inherit.aes = FALSE) + return(evo_freq_p_labeled) + } else if(apply_labels){ + # No evofreq_plot + stop(""Please provide an evofreq_plot created by plot_evofreq() or ensure that custom_label_text is provided"") + } else { + return(position_df) # just return dataframe + } +} + +filter_data <- function(size_df, clones, parents, time_pts=NULL, attribute_df=NULL, threshold=0.01, scale_by_sizes_at_time = FALSE, data_type=""size"", fill_gaps_in_size = FALSE, test_links=TRUE, add_origin=FALSE, tm_frac=0.6, rescale_after_thresholding=FALSE){ + # data(""example.easy.wide.with.attributes"") + # ## Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values + # time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) + # attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) + # attribute_df <- example.easy.wide.with.attributes[, attribute_col_idx] + # size_df <- example.easy.wide.with.attributes[, time_col_idx] + # parents <- example.easy.wide.with.attributes$parent + # clones <- example.easy.wide.with.attributes$clone + # + # clone_cmap <- ""rainbow_soft"" + # # size_df <- mut_freq + # threshold <- 0.0 + # # clones <- mut_df$clone + # # parents <- mut_df$parent + # time_pts <- NULL + # fill_name <- ""fitness"" #""new_antigenicity"" + # attribute_df <- attribute_df + # data_type <- ""size"" + # data_type <- ""size"" + # scale_by_sizes_at_time <- FALSE + # interpolation_steps <- 10 + # fill_gaps_in_size <- FALSE + # test_links <- TRUE + # threshold <- 0.01 + # fill_range <- NULL + # add_origin <- TRUE + # tm_frac <- 0.6 + ##### + + + ### Possible that column names are numbers, but timepoints are unequally spaced. Only change if cannot be converted to numeric + og_colnames <- colnames(size_df) + if(suppressWarnings(all(is.na(as.numeric(colnames(size_df)))))){ + colnames(size_df) <- seq(1, ncol(size_df)) + } + + if(any(duplicated(clones))){ + warning(""Some clones have the same ID. Each clone should have a unique ID"") + } + if(is.null(time_pts)){ + time_pts <- colnames(size_df) + }else{ + time_pts <- as.character(sort(as.numeric(unique(time_pts)))) + } + + if(fill_gaps_in_size){ + size_df <- as.data.frame(t(apply(size_df, 1, fill_in_gaps))) + } + + ### Make sure clone does not have the same id as it's parent. If true, it can cause infinite recursion + if(test_links){ + updated_edges <- check_and_update_edges(clones, parents) + clones <- updated_edges$updated_clones + parents <- updated_edges$updated_parents + } + + if(data_type==""size""){ + ### data are sizes of each clone. Here, the frequency of each mutation will be determined + freq_df <- get_mutation_df(size_df, clones = clones, parents = parents) + freq_mat <- as.matrix(freq_df) + if(add_origin){ + og_time_pts <- colnames(freq_mat) + freq_mat <- add_origin_mat(freq_mat, tm_frac = tm_frac) + # neg_time_pts <- colnames(freq_mat)[! colnames(freq_mat) %in% og_time_pts] + added_time_pts <- colnames(freq_mat)[! colnames(freq_mat) %in% og_time_pts] + time_pts <- c(added_time_pts, time_pts) + og_colnames <- c(rep("""", length(added_time_pts)), og_colnames) + } + + }else{ + check_freq_mat(size_df, clones, parents) + freq_mat <- size_df + freq_mat <- as.data.frame(freq_mat) + if(add_origin){ + og_time_pts <- colnames(freq_mat) + freq_mat <- add_origin_mat(freq_mat, tm_frac = tm_frac) + added_time_pts <- colnames(freq_mat)[! colnames(freq_mat) %in% og_time_pts] + time_pts <- c(added_time_pts, time_pts) + og_colnames <- c(rep("""", length(added_time_pts)), og_colnames) + + } + + # parents[which(! parents %in% clones)] + # updated_edges <- check_and_update_edges(clones, parents) + # clones <- updated_edges$updated_clones + # parents <- updated_edges$updated_parents + } + + ### Possible that parent has frequency of 0. Shouldn't, but possible output of bioinformatics tools + # size_zero_idx <- which(apply(freq_mat, 1, function(x){all(x==0)})) + # clones_with_all_size_zero <- clones[clones %in% clones[size_zero_idx]] + # p_with_all_size_zero <- clones_with_all_size_zero[which(clones_with_all_size_zero %in% parents)] + # for(p in p_with_all_size_zero){ + # children_idx <- get_all_idx(p, clones, parents) + # children_ids <- clones[children_idx] + # actual_children_idx <- which(children_ids != p) + # children_origins <- apply(freq_mat[children_idx[actual_children_idx], ], 1, function(x){which(x>0)[1]}) + # first_child <- names(which.min(children_origins)) + # first_child_idx <- which(clones==first_child) + # + # pidx <- which(clones==p) + # freq_mat[pidx, ] <- freq_mat[first_child_idx, ] + # } + + + + + max_mutation_size <- max(freq_mat) + if(scale_by_sizes_at_time){ + max_sizes_at_each_time <- apply(freq_mat, 2, max) + freq_mat <- sweep(freq_mat, MARGIN = 2, max_sizes_at_each_time, FUN = ""/"") + + }else{ + freq_mat <- freq_mat/max_mutation_size + } + + + ### Subset time points to be plotted + + # freq_mat <- freq_mat[,which(colnames(size_df) %in% time_pts)] + freq_mat <- freq_mat[, time_pts] + if(is.null(nrow(freq_mat))){ + ###Only 1 clone + freq_mat <- t(as.matrix(freq_mat)) + } + colnames(freq_mat) <- time_pts + row.names(freq_mat) <- clones + + ### Possible that a clone was recorded, but never had any sizes greater than 0 + existed_idx <- which(rowSums(freq_mat) > 0) + freq_mat <- freq_mat[existed_idx, ] + clones <- clones[existed_idx] + parents <- parents[existed_idx] + + ### Get idx of clones that are extant after subsetting timepoints ### + origin_times <- apply(freq_mat, 1, function(x){which(x>0)[1]}) + idx_after_time_thresh <- which(is.na(origin_times)==FALSE) + freq_mat <- freq_mat[idx_after_time_thresh, ] + + if(is.null(nrow(freq_mat))){ + ###Only 1 clone + freq_mat <- t(as.matrix(freq_mat)) + } + + clones <- clones[idx_after_time_thresh] + parents <- parents[idx_after_time_thresh] + origin_times <-origin_times[idx_after_time_thresh] ### Order by origin times at the end + time_pts <- as.numeric(time_pts) + + if(!is.null(attribute_df)){ + attribute_df <- attribute_df[idx_after_time_thresh, ] + } + + ### Filter values based on threshold + if(threshold > 0){ + filtered_info <- filter_freq_mat(clones, parents, freq_mat, threshold) + freq_mat <- filtered_info$freq_mat + parents <- filtered_info$parents + + clones <- filtered_info$clones + filtered_idx <- filtered_info$thresh_idx + origin_times <- origin_times[filtered_idx] + + if(rescale_after_thresholding){ + freq_mat <- rescale_frequencies(size_df, clones, parents, filtered_idx, data_type, scale_by_sizes_at_time) + # if(data_type==""size""){ + # sink(""/dev/null"") ### Suppress output + # freq_df <- get_mutation_df(size_df[filtered_idx, ], clones = clones, parents = parents) + # sink() + # freq_mat <- as.matrix(freq_df) + # }else{ + # freq_mat <- as.matrix(freq_mat[filtered_idx,]) + # } + # + # + # max_mutation_size <- max(freq_mat) + # if(scale_by_sizes_at_time){ + # max_sizes_at_each_time <- apply(freq_mat, 2, max) + # freq_mat <- sweep(freq_mat, MARGIN = 2, max_sizes_at_each_time, FUN = ""/"") + # + # }else{ + # freq_mat <- freq_mat/max_mutation_size + # } + } + + if(is.null(nrow(freq_mat))){ + ### Only 1 clone after thresholding + freq_mat <- t(as.matrix(freq_mat)) + row.names(freq_mat) <- clones + filtered_idx <- as.numeric(filtered_idx) + } + + if(!is.null(attribute_df)){ + attribute_df <- attribute_df[filtered_idx, ] + } + } + if(is.null(attribute_df)){ + attribute_df <- data.frame(""clone_id""=clones, ""parents""=parents) + } + + attribute_df$origin <- origin_times + + ordered_idx <- order(origin_times) + clones <- clones[ordered_idx] + parents <- parents[ordered_idx] + attribute_df <- attribute_df[ordered_idx, ] + freq_mat <- freq_mat[ordered_idx, ] + # + # clone_col_idx <- as.numeric(which(sapply(colnames(attribute_df), FUN = function(x){all(clones %in% as.character(unique(attribute_df[,x])))})==TRUE)) + # + # if(length(clone_col_idx) > 1){ + # #### If all clones in pos df are also parents, and there are both parent and clone ids in attribute_df, then more than 1 column will considered the clone_id column in attribute_df + # ### Not possible for all clones in attribute df to also all be parents + # ### So clone_id column is the one that has more unique elements + # n_unique_clones <- apply(attribute_df[clone_col_idx], 2, function(x){length(unique(x))}) + # clone_col_name <- names(n_unique_clones)[which(n_unique_clones==max(n_unique_clones))] + # clone_col_idx <- which(colnames(attribute_df)==clone_col_name) + # } + # + # colnames(attribute_df)[clone_col_idx] <- ""clone_id"" + + return(list(""clones""=clones, ""parents""=parents, ""attributes""=attribute_df, ""freq_mat""=freq_mat, ""max_size""=max_mutation_size, ""og_colnames""=og_colnames)) + + +} + +beta_growth_fxn <- function(x, te, tm, y_max){ + ###https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4244967/ + y <- y_max*(1+ (te-x)/(te-tm))*((x/te)**(te/(te-tm))) + return(y) +} + +add_origin_mat <- function(mut_freq, tm_frac=0.6){ + ### FOR TESTING + # mut_freq = freq_mat + ##### + # colnames(mut_freq) <- seq(1, ncol(mut_freq)) + time_step_size <- mean(diff(as.numeric(colnames(mut_freq)))) + ntime_steps <- ncol(mut_freq) + te <- ntime_steps*time_step_size + nx <- 10 + new_x <- seq(0.000001, te, length.out = nx) + + + + origin_times <- apply(mut_freq, 1, FUN = function(x){which(x>0)[1]}) + origin_at_t1_idx <- which(origin_times==1) + size_order <- order(mut_freq[origin_at_t1_idx, 1], decreasing = TRUE) + origin_at_t1_idx <- origin_at_t1_idx[size_order] + + nudge_val <- floor(nx/(length(origin_at_t1_idx)+1)) + nudge <- 0 + origin_size_mat <- matrix(0, nrow=nrow(mut_freq), ncol = nx) + colnames(origin_size_mat) <- as.character(new_x) + for(idx in origin_at_t1_idx){ + initial_size <- mut_freq[idx, 1] + + ### temp_te gets small and smaller: 0 to nx - nudge + temp_te <- nx - nudge + temp_tm <- tm_frac*temp_te + ### Also adjust tm, but do same as with above + + ### shift position in origin matrix by same amount temp_te is decreasing by: nude to ncol + + clone_new_x <- seq(0, temp_te, length.out = nx-nudge) + origin_size_mat[idx, seq(nudge+1, nx)] <- beta_growth_fxn(clone_new_x, temp_te, temp_tm, initial_size) + nudge <- nudge + nudge_val + } + + + colnames(origin_size_mat) <- rev(-as.numeric(colnames(origin_size_mat))) + new_origin_mat <- origin_size_mat[, seq(1, ncol(origin_size_mat)-1)] + colnames(new_origin_mat) <- colnames(origin_size_mat)[seq(2, ncol(origin_size_mat))] + new_mat <- cbind(new_origin_mat, mut_freq) #### Last column of origin_size_mat is same as first column of mut_freq + + return(new_mat) + +} + +get_argname <- function(paresed_name, default_name = ""fill_value""){ + ### argname isn't from a dataframe + + dollar_in <- grepl(""\\$"", paresed_name) + bracket_in <- grepl('\\[', paresed_name) + if(dollar_in == FALSE & bracket_in == FALSE){ + if( grepl(',', paresed_name)){ + ## Value passed in as an array. I.e. c(1,2,3...) + return(default_name) + }else{ + return(paresed_name) + } + } + + ## value passed in from dataframe + no_dollar <- tail(strsplit(paresed_name, split = ""$"", fixed = TRUE)[[1]], n = 1) + xname <- strsplit(no_dollar, split = '\""', fixed = TRUE)[[1]] + keep_idx <- which(grepl(""\\[|\\]"", xname) == FALSE) + xname <- xname[keep_idx] + + return(xname) +} + +rescale_frequencies <- function(freq_mat, clones, parents, filtered_idx=NULL, data_type=""size"", scale_by_sizes_at_time=FALSE){ + ### Can rescale the frequencies to only show what was detected + if(is.null(filtered_idx)){ + filtered_idx <- seq(1, nrow(freq_mat)) + } + + if(data_type==""size""){ + sink(""/dev/null"") ### Suppress output + freq_df <- get_mutation_df(freq_mat[filtered_idx, ], clones = clones, parents = parents) + sink() + freq_mat <- as.matrix(freq_df) + }else{ + freq_mat <- as.matrix(freq_mat[filtered_idx,]) + } + + + max_mutation_size <- max(freq_mat) + if(scale_by_sizes_at_time){ + max_sizes_at_each_time <- apply(freq_mat, 2, max) + freq_mat <- sweep(freq_mat, MARGIN = 2, max_sizes_at_each_time, FUN = ""/"") + + }else{ + freq_mat <- freq_mat/max_mutation_size + } + + return(freq_mat) +} +","R" +"Homeostasis","MathOnco/EvoFreq","R/cmap_hex_list.R",".R","225","15","#' Hex codes +#' +#' Hex codes +#' +#' @format List of 43 different palettes containing 1000 hex codes +#' \describe{ +#' +#' } +#' @source custom made +#' @examples +#' if (require(""EvoFreq"")) { +#' cmap_hex_list +#' } +""cmap_hex_list"" +","R" +"Homeostasis","MathOnco/EvoFreq","R/example.easy.wide.with.attributes.R",".R","846","25","#' Clone information dataset in Easy Wide Format +#' +#' A dataset for easy understanding of EvoFreq data structures. +#' +#' @format A data frame with 8 rows and 12 variables: +#' \describe{ +#' \item{parent}{Parent clone} +#' \item{clone}{Clone metadata} +#' \item{fitness}{Clone attribute to color by} +#' \item{color}{Clone attribute that is custom color} +#' \item{0}{Timepoint 0 clone sizes} +#' \item{10}{Timepoint 10 clone sizes} +#' \item{20}{Timepoint 20 clone sizes} +#' \item{30}{Timepoint 30 clone sizes} +#' \item{40}{Timepoint 40 clone sizes} +#' \item{50}{Timepoint 50 clone sizes} +#' \item{60}{Timepoint 60 clone sizes} +#' \item{70}{Timepoint 70 clone sizes} +#' } +#' @source Custom Made. +#' @examples +#' ?example.easy.wide.with.attributes +#' data(""example.easy.wide.with.attributes"") +""example.easy.wide.with.attributes"" +","R" +"Homeostasis","MathOnco/EvoFreq","R/example.easy.long.sizes.R",".R","456","16","#' Clone information dataset in Easy Long Format +#' +#' A dataset for easy understanding of EvoFreq data structures. +#' +#' @format A data frame with 47 rows and 3 variables: +#' \describe{ +#' \item{clone}{Clone} +#' \item{Time}{Timepoint at which clone size is measured} +#' \item{Size}{Size of clone at timepoint in Time} +#' } +#' @source Custom Made. +#' @examples +#' ?example.easy.long.sizes +#' data(""example.easy.long.sizes"") +""example.easy.long.sizes"" +","R" +"Homeostasis","MathOnco/EvoFreq","R/EvoFreq_Parsers.R",".R","10242","267"," +#'@title parse_phylowgs +#' +#' Parse phylowgs outputs to visualize using EvoFreq. +#' +#'@param json_file json file output from PhyloWGS containing tree structure and cellular prevalance information. +#'@param return_all if false, return the best result based on the linearity index provided by PhyloWGS. +#'@return A list of dataframes of resolved phylogenies from PhyloWGS. +#' +#'@examples +#'\donttest{ +#'phylowgs_output=""run_name.summ.json"" +#' +#'tree_data <- parse_phylowgs(json_file=phylowgs_output) +#' +#'#EvoFreqPlots +#'pdf('./evofreqs.pdf', width=8, height=4, onefile = T) +#'for (i in 1:length(f$all)){ +#' clone_dynamics_df <- get_evofreq(tree_data[[i]][,c(5,length(colnames(tree_data)))], clones=tree_data[[i]]$clone, parents=tree_data[[i]]$parent, clone_cmap = ""jet"") +#' p <- plot_evofreq(evofreq_df) +#' print(p) +#'} +#'dev.off() +#'} +#' +#'@export +parse_phylowgs <- function(json_file, return_all=TRUE){ + if(substr(json_file, nchar(json_file)-2+1, nchar(json_file))==""gz""){ + theFile <- gzfile(json_file, open=""rb"") + result <- rjson::fromJSON(file = theFile) + close(theFile, type=""rb"") + } else { + result <- rjson::fromJSON(file = json_file) + } + + i=1 + trees=list() + for(item in result$trees){ + #clones + clones <- unlist(item$structure) + + #clone parents + parents <- names(item$structure) + parentNames <- list() + count = 1 + for(children in item$structure){ + parentNames[[count]] = rep(parents[count], length(children)) + count=count+1 + } + parents <- as.numeric(unlist(parentNames)) + + # Edge dataframe + edges <- data.frame(parent=parents, clone=clones) + root <- data.frame(parent=0, clone=0) + edges <- rbind(root,edges) + + # Pull information + node <- names(item$structure) + count=1 + cellPrev <- list() + snvs <- list() + cnvs <- list() + for(details in item$populations){ + cellPrev[[count]] = details$cellular_prevalence + snvs[[count]] = details$num_ssms + cnvs[[count]] = details$num_cnvs + count=count+1 + } + cellPrev <- do.call(rbind,cellPrev) %>% as.data.frame + names(cellPrev) <- seq(1,length(names(cellPrev))) + snvs <- do.call(rbind,snvs) %>% as.data.frame + cnvs <- do.call(rbind,cnvs) %>% as.data.frame + + + df <- cbind(data.frame(snv=snvs, cnv=cnvs), edges, cellPrev) + colnames(df) <- c(""snv"",""cnv"", ""parent"",""clone"", seq(1,length(names(cellPrev)))) + + trees[[i]] <- list(evofreq=df, llh=item$llh, linearity_index=item$linearity_index, clustering_index=item$clustering_index) + i=i+1 + } + + minVal <- Inf + minIdx <- 0 + treeOut <- list() + if(return_all==FALSE){ + for(i in 1:length(trees)){ + if(trees[[i]]$linearity_index"", lines, fixed = TRUE)] + nodePairs <- sub(""^[[:space:]]+\"""", ""\"""", sub(""\""[;[:space:]]+$"",""\"""", unlist(strsplit(body, ""->"")))) + nodeLists <- split(nodePairs, 1:length(nodePairs)%%2) + nodes <- unique(nodePairs) + edges <- as.matrix(data.frame(parent = sub("" "","""",nodeLists[[2]]), + clone = sub("" "","""",sub("";"","""",nodeLists[[1]])), stringsAsFactors = F)) + + lines <- readLines(soln) + fileInfo <- lines[seq(grep(""U"",lines, fixed=T)+1,length(lines))] + headerInfo = unlist(strsplit(fileInfo[1],"","")) + proportion <- list() + timepoints <- list() + for(i in 2:length(fileInfo)){ + d <-unlist(strsplit(fileInfo[i], ',')) + timepoints[[i]] <- d[1] + proportion[[i]] <- as.numeric(d[2:length(d)]) + } + prop.mat <- as.data.frame((do.call(rbind, proportion[2:length(proportion)])), stringsAsFactors = F) + colnames(prop.mat) <- clones + dataMat <- cbind(unlist(timepoints), prop.mat) + names(dataMat) <- c(""time"", names(prop.mat)) + df <- melt(dataMat, id.vars = c(""time"")) + colnames(df) <- c(""time"",""clone"",""size"") + df <- data.frame(time = as.character(df$time), clone = as.character(df$clone), size = df$size, stringsAsFactors = F) + + out <- list(clones = clones, edges = as.data.frame(edges, stringsAsFactors = F), cloneLabels=cloneLabels, sizeDf = df) + print(out) + print(str(out)) + wide_df <- long_to_wide_size_df(long_pop_sizes_df = out$sizeDf, + edges_df = out$edges, + time_col_name = ""time"", + clone_col_name = ""clone"", + parent_col_name = ""parent"", + size_col_name = ""size"", + fill_gaps_in_size = T + ) + + return(wide_df) +} + +#' @title read.HAL +#' @param path_to_file String defining the location of the data output from HAL +#' @param fill_name Optional string defining which attribute to color by. See \code{\link{update_colors}} for more details. +#' @param get_evofreq_df Boolean defining if a freq_frame and evofreq should be returned. +#' @param get_evofreq_arg_list List containing additional arguments passed to \code{\link{get_evofreq}} +#' @param get_dendogram_df Boolean defining if the dataframes to plot evograms and the evogram itself should be returned. +#' @param get_evogram_arg_list List containing additional arguments passed to \code{\link{get_evogram}} +#' @return List containing information get and plot Muller plots and dendrograms +#' +#' @examples +#' \donttest{ +#' ## Default is to return the plot and all info needed to create new ones +#' hal_info <- read.HAL(path_to_hal_results) +#' print(hal_info$evofreq_plot) +#' +#' ### Can define column to use for coloring +#' hal_info <- read.HAL(path_to_hal_results, fill_name = ""Passengers"") +#' print(hal_info$evofreq_plot) +#' +#' ### The information needed to create new plots is also returned. This can be useful if you want to change colors +#' updated_plot <- update_colors(hal_info$freq_frame, hal_info$clones, hal_info$attributes$Drivers) +#' plot_evofreq(updated_plot) +#' +#' ### Can use a list to pass additional arguments to get_evofreq +#' evofreq_args <- list(""threshold""=0.0, ""clone_cmap""=""plasma"") +#' hal_info <- read.HAL(path_to_hal_results, fill_name = ""Passengers"", get_evofreq_arg_list = evofreq_args) +#' print(hal_info$evofreq_plot) +#' +#' ### Use the same approach to get dendrograms by setting get_dendogram_df = T. Set return_dendrogram_plot = T to get the dendrogram plot too +#' evogram_args <- list(""threshold""=0.0, ""clone_cmap""=""plasma"") +#' hal_info <- read.HAL(path_to_hal_results, fill_name = ""Drivers"", get_evogram_arg_list = evofreq_args, get_dendogram_df=T) +#' print(hal_info$evogram_plot) +#' } +#' @export +read.HAL <- function(path_to_file, fill_name=NULL, get_evofreq_df=TRUE, get_evofreq_arg_list=list(), get_dendogram_df=FALSE, get_evogram_arg_list=list()){ + ## FOR TESTING ### + # path_to_file <- f + # fill_name <- ""Drivers"" + # get_evofreq_arg_list <- list(""threshold""=0.1, ""clone_cmap""=""jet"") + # return_evofreq_plot <- TRUE + # get_dendogram_df <- TRUE + # get_evofreq_arg_list = evofreq_args + # get_evogram_arg_list <- evofreq_args + # return_dendrogram_plot = TRUE + ### + + clone_df <- read.csv(path_to_file, check.names = FALSE, stringsAsFactors = FALSE) + df_cols <- colnames(clone_df) + time_col_idx <- suppressWarnings(which(!is.na(as.numeric(df_cols)))) + time_cols <- df_cols[time_col_idx] + size_df <- clone_df[, time_cols] + + return_list <- list(""clones""=clone_df$CloneID, ""parents""=clone_df$ParentID, ""size_df""=size_df) + + hal_args <- list(""size_df"" = size_df, ""clones""=clone_df$CloneID, ""parents""=clone_df$ParentID) + + attribute_col_idx <- which(!df_cols %in% c(time_cols, ""CloneID"", ""ParentID"")) + if(length(attribute_col_idx) > 0){ + attribute_df <- cbind(data.frame(""CloneID""=clone_df$CloneID),clone_df[, attribute_col_idx]) + return_list[[""attributes""]] <- attribute_df + if(!is.null(fill_name)){ + hal_args[[""fill_value""]] <- clone_df[fill_name] + } + + } + + ### Get info to plot evofreq + if(get_evofreq_df){ + freq_df <- do.call(get_evofreq, c(hal_args, get_evofreq_arg_list)) + return_list[[""freq_frame""]] <- freq_df + return_list[[""evofreq_plot""]] <- plot_evofreq(freq_df) + } + + + ### Get info to plot evogram + if(get_dendogram_df){ + dendro_df <- do.call(get_evogram, c(hal_args, get_evogram_arg_list)) + return_list[[""dendro_links""]] <- dendro_df$links + return_list[[""dendro_pos""]] <- dendro_df$dendro_pos + return_list[[""evogram_plot""]] <- plot_evogram(dendro_df$dendro_pos, dendro_df$links) + } + + return(return_list) +} + + +","R" +"Homeostasis","MathOnco/EvoFreq","R/Example.Long.Edges.R",".R","637","19","#' Clone information dataset in Long Format +#' +#' A dataset from a simulation taken from ""Niche engineering drives early passage through an immune bottleneck in progression to colorectal cancer"" +#' +#' @format A data frame with 1181 rows and 5 variables: +#' \describe{ +#' \item{parents}{Parent clone} +#' \item{fitness}{Clone metadata} +#' \item{drivers}{Driver mutations of clone} +#' \item{passengers}{Passenger mutations of clone} +#' \item{clone_id}{ID of the clone} + +#' } +#' @source \url{https://www.biorxiv.org/content/10.1101/623959v2} +#' @examples +#' if (require(""EvoFreq"")) { +#' example.long.edges +#' } +""example.long.edges""","R" +"Homeostasis","MathOnco/EvoFreq","R/idx_funcs.R",".R","8543","264","get_all_idx <- function(c, c_list, p_list){ + all_children_idx <- c() + add_child_idx <- function(i, c_list){ + child_idx <- which(c_list==i) + all_children_idx <<- append(all_children_idx, child_idx) + } + traverse(c, c_list, p_list, add_child_idx) + + return(all_children_idx) +} + +get_root_id <- function(clones, parents){ + ### FOR TESTING ### + # clones <- clone_list + # parents <- parent_list + ################### + ### Root is either a clone that is also its own parent, or is not in the clone list (i.e. root's root) + parents_not_in_clone <- unique(parents[which(! parents %in%clones)]) + if(length(parents_not_in_clone)==1){ + root_id <- parents_not_in_clone + return(root_id) + }else if(length(parents_not_in_clone) > 1){ + warning(""More that 1 parent is not in clone list. Cannot determine root id"") + } + clone_as_parent <- unique(parents[which(parents==clones)]) + if(length(clone_as_parent) == 1){ + root_id <- clone_as_parent + return(root_id) + }else if(clone_as_parent > 1){ + warning(""More that 1 clone is also its own parent. Cannot determine root id"") + } + warning(""Expect ID of root to be either a parent not in the clone list, or a clone with the same ID as its parent. Neither seems to be true, and so cannot determine root id"") +} + +get_ancestor_idx_evo_freq <- function(clone_id, clone_list, parent_list){ + ###FOR TESTING ### + # clone_id <- cid + # clone_list <- clones + # parent_list <- parents + #### + root_id <- get_root_id(clone_list, parent_list) + if(root_id==clone_id){ + return(NULL) + } + clone_idx <- which(clone_list == clone_id) + clone_parent <- parent_list[clone_idx] + ancestral_idx <- c() + while(clone_parent != root_id){ + parent_idx <- which(clone_list == clone_parent) + ancestral_idx <- append(ancestral_idx, parent_idx) + clone_parent <- parent_list[parent_idx] + } + + return(ancestral_idx) +} + +get_pos <- function(clones, parents, mut_mat, og_time_pts=NULL){ + ### FOR TESTING ### + # parents <- parents + # clones <- clones + # mut_mat <- freq_mat + # og_time_pts <- NULL #as.numeric(time_pts) + # get_pos(clones, parents, freq_mat) + ############### + # roots_root_idx <- which(!parents %in% clones) + # roots_root <- parents[roots_root_idx] + # root_id <- clones[roots_root_idx] + + roots_root <- get_root_id(clones, parents) + # root_idx <- which(parents==roots_root) + # root_id <- clones[root_idx] + + # g <- graph_from_data_frame(data.frame(""from""=parents, ""to""=clones)) + # plot(g) + + if(is.null(og_time_pts)){ + og_time_pts <- seq(1, ncol(mut_mat)) + } + + og_mut_mat <- mut_mat + mut_mat <- interp_mut_mat(og_mut_mat, og_time_pts) + time_pts <- as.numeric(colnames(mut_mat)) + + origin_times <- apply(mut_mat, 1, function(x){which(x>0)[1]}) + unique_ordered_origin_times <- sort(unique(origin_times)) ### ensure earlier clones are drawn first + y_btm_list <- list() + y_top_list <- list() + + clone_id <- roots_root + clone_str_id <- as.character(clone_id) + n_time_pts <- ncol(mut_mat) + + max_size <- max(mut_mat) + y_btm <- rep(0, n_time_pts) + y_top <- rep(1, n_time_pts) + y_btm_list[[clone_str_id]] <- y_btm + y_top_list[[clone_str_id]] <- y_top + + x_vals <- time_pts + + clone_x <- c(x_vals, rev(x_vals)) + + clone_str_id <- as.character(clone_id) + clone_pos_list <- list() + draw_order <- 0 + + # print(unique_ordered_origin_times) + for(ot in unique_ordered_origin_times){ + # ot <- unique_ordered_origin_times[1] + parents_at_time <- unique(parents[origin_times==ot]) + n_parents <- length(parents_at_time) + if(n_parents > 1){ + parents_at_time <- order_clones_at_time(parents_at_time, parents = parents, clones=clones) + } + + for(parent in parents_at_time){ + + parent_str_id <- as.character(parent) + children_idx <- which(parents==parent) + if(length(children_idx)==1){ + total_child_area <- mut_mat[children_idx,] + }else{ + total_child_area <- as.numeric(colSums(mut_mat[children_idx,])) + } + + + if(parent==roots_root){ + parent_area <- rep(1, n_time_pts) + n_children <- 1 + }else{ + parent_idx <- which(clones==parent) + parent_area <- as.numeric(mut_mat[parent_idx,]) + n_children <- length(children_idx)### TODO PUT HERE??? + # children_sizes <- mut_mat[children_idx,] + # if(length(children_idx) > 1){ + # # print(children_sizes) + # n_children <- apply(children_sizes, MARGIN = 2, function(x){length(x[x>0])}) + # }else{ + # n_children <- rep(0, length(children_sizes)) + # n_children[children_sizes > 0] <- 1 + # print(n_children) + # } + # # print(n_children) + + } + # n_children <- length(children_idx)### NOTE WAS HERE + # n_children <- length(children_idx) + spacing <- (parent_area - total_child_area)/(n_children+1) + # spacing[spacing < 0] <- min(spacing[spacing >= 0]) ###TODO DOES THIS WORK? + + ### Get bottom of parent's polygon + current_btm <- y_btm_list[[parent_str_id]] + loc <- spacing + current_btm + # print(paste(""parent"", parent_str_id)) + # print(spacing) + # print(current_btm) + # print(loc) + ### Draw points around center + if(n_children > 3){ + children_origin_times <- as.numeric(origin_times[children_idx]) + children_idx <- distribute_x(children_idx[order(children_origin_times)]) + + ### First sort children_idx by time or origin? + } + # print(parent_str_id) + # print(parent_str_id %in% names(y_btm_list)) + # print(clones[children_idx]) + # print(current_btm) + + for(cidx in children_idx){ + clone_id <-clones[cidx] + + clone_id_str <- as.character(clone_id) + + if(clone_id_str %in% names(clone_pos_list)){ + next + } + + child_size <- mut_mat[cidx,] + non_zero_idx <- which(child_size > 0) + # print(clone_id_str) + # print(non_zero_idx) + # print(child_size) + + bottom <- loc + loc <- loc + child_size + top <- loc + loc <- loc + spacing + + # if(any(is.na(bottom))){ + # print(paste(""bottom positions are NA for clone"", clone_id)) + # print(paste(""bottom positions are NA for clone"", clone_id, "". Previous clone"", clones[children_idx[z-1]], ""had top y values of:"")) + # print(temp_loc) + # } + # if(any(is.na(top))){ + # print(paste(""top positions are NA for clone"", clone_id)) + # print(paste(""top positions are NA for clone"", clone_id, "". Previous clone"", clones[children_idx[z-1]], ""had top y values of:"")) + # print(temp_loc) + # } + + y_btm_list[[clone_id_str]] <- bottom + y_top_list[[clone_id_str]] <- top + + clone_x <- c(x_vals[non_zero_idx], rev(x_vals[non_zero_idx])) + clone_y <- c(bottom[non_zero_idx], rev(top[non_zero_idx])) + clone_sizes <- c(child_size[non_zero_idx], rev(child_size[non_zero_idx])) + clone_shape_df <- data.frame(x=clone_x, y=clone_y, clone_id = clone_id, parent= parent, origin_time=ot, draw_order = draw_order, size=clone_sizes) + draw_order <- draw_order + 1 + clone_pos_list[[clone_id_str]] <- clone_shape_df + + } + } + } + + clone_pos_df <- do.call(rbind, clone_pos_list) + + # print(any(is.na(clone_pos_df$y))) + clone_pos_df$draw_order <- factor(clone_pos_df$draw_order, ordered=TRUE, levels = sort(unique(clone_pos_df$draw_order), decreasing = FALSE)) + # clone_pos_df$color <- as.character(clone_pos_df$color) + clone_pos_df <- clone_pos_df[order(clone_pos_df$draw_order),] + clone_pos_df$x <- as.numeric(clone_pos_df$x) + clone_pos_df$y <- as.numeric(clone_pos_df$y) + return(clone_pos_df) + +} + +get_children <- function(c, clone_list, parent_list){ + children_idx <- which(parent_list==c) + children <- clone_list[children_idx] + return(children) +} + +get_node_idx <- function(c, c_list, p_list){ + node_idx <- c() + c_ids <- c() + i <- 0 + add_idx <- function(c, c_list){ + node_idx <<- append(node_idx, i) + c_ids <<- append(c_ids, c) + i <<- i + 1 + } + traverse(c, c_list, p_list, add_idx) + + return(list(""idx""=node_idx, ""vertex""=c_ids)) +} + +get_last_idx_above_0 <- function(x){ + + idx <- utils::tail(which(x > 0), 1) + if(length(idx)==0){ + ###clone was never above 0 + idx <- 0 + } + return(idx) +} + +get_last_idx_at_0 <- function(x){ + idx <- utils::tail(which(x == 0), 1) + if(length(idx)==0){ + ### clone was never 0 + idx <- 0 + } + return(idx) +}","R" +"Homeostasis","MathOnco/EvoFreq","R/Animate_funcs.R",".R","18713","463","#'@title animate_evogram +#' +#'View changes in the dendrogram over time. Has most of the same options as \code{\link{plot_evogram}}, but does not have option to set link type +#'@inheritParams get_evofreq +#'@inheritParams plot_evogram +#'@return List infromation need to craete the animation: ""dendro_pos_df"" contains all of the positions of the nodes and edges at each timestep, while ""animation_plot"" that can be used with gganimate to create the animation. For details on how to customize and save the animation, see \code{\link[gganimate]{gganimate}} +#'@examples +#' data(""example.easy.wide.with.attributes"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' size_df <- example.easy.wide.with.attributes[, time_col_idx] +#' parents <- example.easy.wide.with.attributes$parent +#' clones <- example.easy.wide.with.attributes$clone +#' fitness <- example.easy.wide.with.attributes$fitness +#' dendro_movie_info <- animate_evogram(size_df, clones = clones, parents = parents, fill_value = fitness) +#' dendro_movie_plot <- dendro_movie_info$animation_plot +#' +#'### Add gganimate object to dendro_movie_plot to finish animation +#' \donttest{ +#' library(gganimate) +#' movie_p <- dendro_movie_plot + +#' transition_time(time) + +#' ease_aes() + +#' exit_shrink() + +#' ggtitle('Time {frame_time}') +#' +#' print(movie_p) +#'} +#'@export +animate_evogram <- function(size_df, clones, parents, fill_value=NULL, fill_range = NULL, time_pts=NULL, clone_cmap=NULL, threshold=0.01, data_type=""size"", fill_gaps_in_size = FALSE, test_links=TRUE, node_size=5, scale_by_node_size=TRUE, orientation=""td"", depth=""origin"", rescale_after_thresholding=FALSE){ + # ## FOR TESTING ### + # data(""example.easy.wide.with.attributes"") + # # Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values + # time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) + # attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) + # attribute_df <- example.easy.wide.with.attributes[, attribute_col_idx] + # size_df <- example.easy.wide.with.attributes[, time_col_idx] + # parents <- example.easy.wide.with.attributes$parent + # clones <- example.easy.wide.with.attributes$clone + # fill_value <- example.easy.wide.with.attributes$fitness + # + # clone_cmap <- NULL + # size_df <- size_df + # threshold <- 0.01 + # clones <- clones + # parents <- parents + # time_pts <- NULL + # data_type <- ""size"" + # scale_by_sizes_at_time <- FALSE + # fill_gaps_in_size <- FALSE + # test_links <- TRUE + # threshold <- 0.01 + # attribute_val_range <- NULL + # fill_range <- NULL + # + # node_size <- 5 + # scale_by_node_size <- TRUE + # orientation <- ""td"" + ##### + + if(!is.null(fill_value)){ + fill_name <- colnames(fill_value) ### Value was passed in using a string to get the column, e.g. df[fill_name] + if(is.null(fill_name)){ + paresed_fill_name <- deparse(substitute(fill_value)) + fill_name <- get_argname(paresed_fill_name) + } + attribute_df <- data.frame(""clone_id""=clones) + attribute_df[fill_name] <- fill_value + }else{ + attribute_df <- NULL + fill_name <- NULL + } + + if(!is.null(fill_name)){ + attribute_vals <- attribute_df[,fill_name] + if(is.null(fill_range)){ + fill_range <- range(attribute_vals, na.rm = TRUE) + } + } + + + if(is.null(time_pts)){ + time_pts <- colnames(size_df) + } + + all_time_df_list <- list() + + cat(""\n"") + print(""Making Movie Frames"") + pb <- utils::txtProgressBar(min = 1, max = length(time_pts), style = 3) + for(time_idx in seq(length(time_pts))){ + utils::setTxtProgressBar(pb, time_idx) + tp <- time_pts[time_idx] + sink(""/dev/null"") ### Suppress output + # to_plot_df <- filter_edges_at_time(size_df = size_df, clones = clones, parents = parents, time_pt = tp, attribute_df = attribute_df, clone_id_col_in_att_df=clone_id_col_in_att_df, threshold = threshold, data_type = data_type, fill_gaps_in_size = fill_gaps_in_size, test_links=test_links) + to_plot_df <- filter_edges_at_time(size_df = size_df, clones = clones, parents = parents, time_pt = tp, attribute_df = attribute_df, threshold = threshold, data_type = data_type, fill_gaps_in_size = fill_gaps_in_size, test_links=test_links, rescale_after_thresholding=rescale_after_thresholding) + sink() + time_dendro_pos <- get_dendrogram_pos(to_plot_df$attributes, clones_for_d = to_plot_df$clones, parents_for_d = to_plot_df$parents) + + ###TODO Use level to get x position, but if depth is not level, move y to desired level + + + time_dendro_pos <- get_straight_links(time_dendro_pos) + time_dendro_pos$time <- time_idx + + + all_time_df_list[[as.character(tp)]] <- time_dendro_pos + + if(time_idx==1){next()} + + prev_pos_df <- all_time_df_list[[as.character(time_pts[time_idx-1])]] + + new_clone_idx <- which(!time_dendro_pos$clone_id %in% prev_pos_df$clone_id) + + if(length(new_clone_idx)>0){ + for(cidx in new_clone_idx){ + new_clones_parent <- time_dendro_pos$parent[cidx] + parent_idx <- which(prev_pos_df$clone_id == new_clones_parent) + new_clone_df <- time_dendro_pos[cidx, ] + new_clone_df$time <- prev_pos_df$time[parent_idx] + new_clone_df$freq <- 0 + new_clone_df[c(""y"", ""tree_y"", ""dendro_y"", ""x"", ""time"", ""origin"")] <- prev_pos_df[parent_idx, c(""y"", ""tree_y"", ""dendro_y"", ""x"", ""time"", ""origin"")] + new_clone_df$end_x <- new_clone_df$x + new_clone_df$end_y <- new_clone_df$y + new_clone_df$end_tree_y <- new_clone_df$tree_y + new_clone_df$end_origin <- new_clone_df$origin + new_clone_df$end_dendro_y <- new_clone_df$dendro_y + prev_pos_df[parent_idx,] + # new_clone_df[c(""end_x"", ""end_y"", ""end_tree_y"", ""end_origin"", ""end_dendro_y"")] <- NA + prev_pos_df <- rbind(prev_pos_df, new_clone_df) + } + all_time_df_list[[as.character(time_pts[time_idx-1])]] <- prev_pos_df + } + } + + + d_pos_df <- do.call(rbind, all_time_df_list) + d_pos_df <- d_pos_df[order(d_pos_df$time), ] + + # if(is.null(fill_name)){ + # attribute_df <- NULL + # } + # + # d_pos_df <- update_colors(evo_freq_df = d_pos_df, attribute_df = attribute_df, fill_name = fill_name, clone_id_col_in_att_df=clone_id_col_in_att_df, clone_cmap = clone_cmap, attribute_range = attribute_val_range) + length(fill_value) + d_pos_df <- update_colors(evo_freq_df = d_pos_df, clones = clones, fill_value = fill_value, clone_cmap = clone_cmap, fill_range = fill_range, fill_name=fill_name) + + + + if(depth == ""origin""){ + y_name <- ""origin_y"" + end_y_name <- ""end_origin"" + d_pos_df$origin_y <- d_pos_df$origin + }else if(depth==""level""){ + y_name <- ""tree_y"" + end_y_name <- ""end_tree_y"" + }else if(depth==""bottom""){ + y_name <- ""dendro_y"" + end_y_name <- ""end_dendro_y"" + } + + color_attribute_name <- unique(d_pos_df$efp_color_attribute) + if(is.na(color_attribute_name)){ + color_attribute_name <- ""plot_color"" + }else{ + if(is.null(fill_range)){ + fill_range <- range(d_pos_df[, color_attribute_name], na.rm = TRUE) + } + } + + + p <- ggplot2::ggplot(d_pos_df, ggplot2::aes_string(x=""x"", y=y_name, color=color_attribute_name, group=""clone_id"", xend=""end_x"", yend=end_y_name, size=""freq"")) + + ggplot2::geom_segment(color=""black"", size=1, na.rm=TRUE) + + if(scale_by_node_size){ + p <- p + ggplot2::geom_point() + }else{ + p <- p + ggplot2::geom_point(size=node_size) + } + if(orientation==""lr""){ + p <- p + ggplot2::coord_flip() + }else{ + p <- p + ggplot2::scale_y_reverse() + } + + if(color_attribute_name==""plot_color""){ + p <- p + ggplot2::scale_color_identity() + }else{ + # p <- p + ggplot2::scale_color_gradientn(colours = colorbar_colors) #colormap::scale_fill_colormap(color_attribute_name, colormap=colormap_name) + colormap_name <- unique(d_pos_df$cmap) + colorbar_colors <- get_colors(100, colormap_name) + p <- p + ggplot2::scale_fill_gradientn(colours = colorbar_colors, limits=fill_range) #colorma + # p <- p + colormap::scale_color_colormap(color_attribute_name, colormap=colormap_name, limits=fill_range) + } + + p <- p + ggplot2::theme_void() + + return(list(""dendro_pos_df""=d_pos_df, ""animation_plot""=p)) +} + +add_links <- function(d_pos_list){ + ###FOR TESTING ### + # d_pos_list <- d_pos_df + #### + + for(tidx in names(d_pos_list)){ + t_df <- d_pos_list[[tidx]] + t_df$end_x <- NA + t_df$end_y <- NA + t_df$end_origin <- NA + t_df$end_dendro_y <- NA + t_df$end_tree_y <- NA + n_clones <- length(t_df$clone_id) + for(cidx in seq(1, n_clones)){ + + pid <- t_df$parents[cidx] + p_idx <- which(t_df$clone_id == pid) + if(length(p_idx)==0){ + ## root ## + next() + } + t_df$end_x[cidx] <- t_df$x[p_idx] + t_df$end_y[cidx] <- t_df$tree_y[p_idx] + t_df$end_origin[cidx] <- t_df$origin[p_idx] + t_df$end_dendro_y[cidx] <- t_df$dendro_y[p_idx] + t_df$end_tree_y[cidx] <- t_df$tree_y[p_idx] + } + d_pos_list[[tidx]] <- t_df + } + + return(d_pos_list) +} + +set_clone_origin_d_pos <- function(d_pos_list){ + ### FOR TESTING ### + # d_pos_list <- recentered_d_pos_list + ### + ### Give children parent's position in frame before origin + time_pts <- names(d_pos_list) + n_time_pts <- length(time_pts) + + for(t_idx in seq(2, n_time_pts)){ + # t_idx <- 5 + current_time <- time_pts[t_idx] + current_d <- d_pos_list[[current_time]] + current_d <- current_d[order(current_d$x, decreasing = TRUE), ] + current_d <- current_d[order(current_d$node_id), ] + ### prev time df needs to be based on updated prev, so that positions are consistent + prev_time <- time_pts[t_idx - 1] + prev_pos_df <- d_pos_list[[prev_time]] + prev_pos_df <- prev_pos_df[order(prev_pos_df$node_id), ] + # og_prev_d <- d_pos_list[[prev_time]] + prev_clones <- prev_pos_df$clone_id[prev_pos_df$present_at_time == TRUE] + + # available_pos_df <- current_d + n_pos <- nrow(current_d) + n_levels <- max(current_d$tree_y) + for(l in seq(1, n_levels)){ + ### Clone is new: Add to updated previous position list, using parent's original position. Give it a left over postion in current time point + new_clone_idx <- which(!current_d$clone_id %in% prev_clones & current_d$tree_y == l) + for(ncidx in new_clone_idx){ + ### For previous timestep, give clone its parent's position + pid <- current_d$parents[ncidx] + prev_pidx <- which(prev_pos_df$clone_id==pid) + new_row <- current_d[ncidx, ] + new_row$x <- prev_pos_df$x[prev_pidx] + new_row$tree_y <- prev_pos_df$tree_y[prev_pidx] + new_row$y <- prev_pos_df$y[prev_pidx] + new_row$origin <- prev_pos_df$origin[prev_pidx] + new_row$dendro_y <- prev_pos_df$dendro_y[prev_pidx] + new_row$time <- prev_pos_df$time[prev_pidx] + new_row$present_at_time <- FALSE + prev_pos_df <- rbind(prev_pos_df, new_row) + + } + } + d_pos_list[[prev_time]] <- prev_pos_df + } + return(d_pos_list) +} + +recenter_parents <- function(d_pos_list){ + ##FOR TESTING ### + # d_pos_list <- matched_d_pos_list + #### + + for(tidx in names(d_pos_list)){ + t_df <- d_pos_list[[tidx]] + n_levels <- max(t_df$tree_y) + rev_levels <- seq(n_levels-1, 1) + for(l in rev_levels){ + p_in_level_idx <- which(t_df$y== l) + for(pidx in p_in_level_idx){ + p <- t_df$clone_id[pidx] + children_idx <- which(t_df$parents==p) + if(length(children_idx)>0){ + children_pos <- t_df$x[children_idx] + t_df$x[pidx] <- mean(children_pos) + } + } + } + d_pos_list[[tidx]] <- t_df + # tp2 <- ggplot(t_df, aes(x=x, y=-tree_y, color=as.factor(clone), group=clone, size=size)) + + # # geom_segment(color=""black"", size=1) + + # geom_point() + + # theme_void() + # + # f <- paste0(t_idx, ""_final.png"") + # ggsave(f, tp2) + + } + return(d_pos_list) +} + +match_d_pos <- function(d_pos_list){ + ### FOR TESTING ### + # d_pos_list <- intital_d_pos_list + ### + + ### Keep each node near its previous position + + ### 3 Scenarios: + ### 1) Clone existed in previous time step. Update it's position based on updated previous positions + ### 2) Clone is new: Add to updated previous position list, using parent's original position. Give it a left over postion in current time point + updated_df_h_list <- list() + time_pts <- names(d_pos_list) + n_time_pts <- length(time_pts) + updated_df_h_list[[time_pts[1]]] <- d_pos_list[[time_pts[1]]] + # for(t_idx in seq(2, 4)){ + for(t_idx in seq(2, n_time_pts)){ + # t_idx <- 5 + current_time <- time_pts[t_idx] + current_d <- d_pos_list[[current_time]] + current_d <- current_d[order(current_d$x, decreasing = TRUE), ] + current_d <- current_d[order(current_d$node_id), ] + ### prev time df needs to be based on updated prev, so that positions are consistent + prev_time <- time_pts[t_idx - 1] + updated_prev_pos_df <- updated_df_h_list[[prev_time]] + updated_prev_pos_df <- updated_prev_pos_df[order(updated_prev_pos_df$node_id), ] + prev_clones <- updated_prev_pos_df$clone_id[updated_prev_pos_df$present_at_time == TRUE] + + available_pos_df <- current_d + n_pos <- nrow(available_pos_df) + n_levels <- max(current_d$tree_y) + for(l in seq(1, n_levels)){ + # l <- 1 + #### update from top down. Will allow to adjust children based on parent's new position + extant_clone_idx <- which(current_d$clone_id %in% prev_clones & current_d$tree_y == l) + idx_in_prev_df <- which(updated_prev_pos_df$clone_id %in% current_d$clone_id[extant_clone_idx]) + + ### Avoid big jumps by taking care of worst case scenarios first (largest jumps possible) + pos_dmat <- abs(outer(updated_prev_pos_df$x[idx_in_prev_df], available_pos_df$x[available_pos_df$tree_y == l], ""-"")) + max_d <- apply(pos_dmat, 1, max) + extant_clone_idx <- extant_clone_idx[order(max_d, decreasing = TRUE)] + ### Clone existed in previous time step. Change its position based on its updated previous positions + for(ecidx in extant_clone_idx){ + ecid <- current_d$clone_id[ecidx] + + + idx_in_updated_prev_pos <- which(updated_prev_pos_df$clone_id==ecid) + prev_x <- updated_prev_pos_df$x[idx_in_updated_prev_pos] + prev_y <- updated_prev_pos_df$tree_y[idx_in_updated_prev_pos] + dx <- rep(NA, n_pos) + for(i in seq(1, n_pos)){ + if(available_pos_df$pos_available[i] & available_pos_df$tree_y[i]==l){ + ###Only consider available spaces in the same heirarchy level + dx[i] <- abs(available_pos_df$x[i] - prev_x) + } + } + closest_idx <- which.min(dx)[1] + current_d$x[ecidx] <- available_pos_df$x[closest_idx] + current_d$pos_available[closest_idx] <- FALSE + available_pos_df$pos_available[closest_idx] <- FALSE + } + + ### Clone is new: Add to updated previous position list, using parent's original position. Give it a left over postion in current time point + # new_clone_idx <- which(!current_d$clone %in% og_prev_d$clone) + new_clone_idx <- which(!current_d$clone_id %in% prev_clones & current_d$tree_y == l) + for(ncidx in new_clone_idx){ + ### Give clone one of the left over positions ### + available_pos <- which(available_pos_df$pos_available & available_pos_df$tree_y == l)[1] + current_d$x[ncidx] <- available_pos_df$x[available_pos] + current_d$y[ncidx] <- available_pos_df$y[available_pos] + current_d$tree_y[ncidx] <- available_pos_df$tree_y[available_pos] + current_d$pos_available[available_pos] <- FALSE + available_pos_df$pos_available[available_pos] <- FALSE + } + } + + # any(duplicated(current_d[c(""x"",""y"")])) + updated_df_h_list[[prev_time]] <- updated_prev_pos_df + updated_df_h_list[[current_time]] <- current_d + # + # tp2 <- ggplot(current_d, aes(x=x, y=-tree_y, color=as.factor(clone), group=clone, size=size)) + + # # geom_segment(color=""black"", size=1) + + # geom_point() + + # theme_void() + # + # f <- paste0(t_idx, ""_updated.png"") + # ggsave(f, tp2) + } + return(updated_df_h_list) +} + +get_initial_d_pos <- function(mut_freq, clones, parents, attribute_df, fill_name=NULL){ + ### Get positions of nodes for each dendrogram + ### FOR TESTING ### + # clones <- to_plot_df$clones + # parents <- to_plot_df$parents + # mut_freq <- to_plot_df$freq_mat + # attribute_df <- to_plot_df$attributes + # fill_name <- ""fitness"" + ### + + attribute_df$clone_id <- clones + attribute_df$parents <- parents + time_pts <- colnames(mut_freq) + n_time_pts <- length(time_pts) + + first_time_dendro <- attribute_df[1, ] ### Ordered by origin time, so root is a top + first_time_dendro$x <- 0.5 + first_time_dendro$y <- 0 + first_time_dendro$tree_y <- 0 + first_time_dendro$dendro_y <- 0 + first_time_dendro$time <- as.numeric(time_pts[1]) + first_time_dendro$present_at_time <- TRUE + first_time_dendro$pos_available <- TRUE + first_time_dendro$freq <- mut_freq[1, 1] + + # first_time_dendro <- update_colors(first_time_dendro, attribute_df = first_time_dendro, fill_name = fill_name) + + attribute_df <- attribute_df[order(attribute_df$origin), ] + + pos_df_list <- list() + pos_df_list[[as.character(first_time_dendro$time)]] <- first_time_dendro + for(time_idx in seq(2, n_time_pts)){ + # time_idx <- 2 + freq_at_time <- as.numeric(mut_freq[, time_idx]) + present_idx <- which(freq_at_time > 0) + at_time_df <- attribute_df[present_idx, ] + at_time_df$freq <- freq_at_time[present_idx] + at_time_dendro <- get_dendrogram_pos(at_time_df, at_time_df$clone_id, at_time_df$parents) + at_time_dendro[1,]$x <- 0.5 ### Keep root in middle + at_time_dendro$time <- as.numeric(time_pts[time_idx]) + at_time_dendro$present_at_time <- TRUE + at_time_dendro$pos_available <- TRUE + # at_time_dendro <- update_colors(at_time_dendro, attribute_df = at_time_dendro, fill_name = fill_name) + pos_df_list[[as.character(unique(at_time_dendro$time))]] <- at_time_dendro + + # tp <- ggplot(at_time_dendro, aes(x=x, y=-tree_y, color=as.factor(clone), group=clone, size=size)) + + # # geom_segment(color=""black"", size=1) + + # geom_point() + + # theme_void() + # + # f <- paste0(time_idx, "".png"") + # ggsave(f, tp) + } + + return(pos_df_list) + +} +","R" +"Homeostasis","MathOnco/EvoFreq","R/color_funcs.R",".R","10451","240"," +data(cmap_hex_list) + +get_colors <- function(n_clones, cmap_name){ + ### FOR TESTING ### + # n_clones <- 10 + # cmap_name = ""rainbow_soft"" + ##### + cmap_hex_vals <- cmap_hex_list[[cmap_name]] + color_ramp_fxn <- colorRampPalette(cmap_hex_vals) + cmap_vals <- color_ramp_fxn(n_clones) + return(cmap_vals) +} + +#'@title update_colors +#' +#'Update the colors of clones in the frequency dynamics dataframe or dendrogram plot dataframe +#' +#'@inheritParams get_evofreq +#'@param evo_freq_df Dataframe returned by \code{\link{get_evofreq}} or \code{\link{get_evogram}} , which contains the information to plot the frequency dynamics +#'@param clone_cmap String defining which colormap should be used to color the clones (nodes) if no attributes to color by. For a list of available colormaps, see https://github.com/bhaskarvk/colormap +#'@param fill_name String defining the name of the attribute used for coloring. If NULL, the default, the name will be inferred from the \code{fill_value} argument. +#'@examples +#' data(""example.easy.wide"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) +#' size_df <- example.easy.wide[, time_col_idx] +#' parents <- example.easy.wide$parents +#' clones <- example.easy.wide$clones +#' ### Setting of colors can be done when getting the freq_frame, or by updating the color later using \code{\link{update_colors}}. For a list of available colormaps, see https://github.com/bhaskarvk/colormap. +#' ### Default colormap is rainbow_soft, but this can be changed using the \code{clone_cmap} argument. +#' freq_frame <- get_evofreq(size_df, clones, parents) +#' evo_p <- plot_evofreq(freq_frame) +#' +#' ### Can color each clone by an attribute by providing a \code{fill_value}. Default colormap is viridis, but this can be changed using the \code{clone_cmap} argument. There is also the option to set the color range using the \code{fill_range} argument +#' fitness <- runif(length(clones),0, 100) +#' fitness_freq_frame <- update_colors(freq_frame, clones = clones, fill_value = fitness, fill_range= c(0, 100)) +#' fitness_evo_p <- plot_evofreq(fitness_freq_frame, fill_range = c(0, 100)) +#' +#' ### The user can also provide custom colors for each clone, which will need to be passed into the \code{fill_value} argument +#' ### Custom colors can be defined using RGB values. Each color should be a string specifying the color channel values, separated by commas. +#' rgb_clone_colors <- sapply(seq(1, length(clones)), function(x){paste(sample(0:255,size=3,replace=TRUE),collapse="","")}) +#' rgb_freq_frame <- update_colors(freq_frame, clones = clones, fill_value = rgb_clone_colors) +#' rgb_evo_p <- plot_evofreq(rgb_freq_frame) +#' +#' ### Custom colors can also be any of the named colors in R. A list of the colors can be found with \code{colors()} +#' named_clone_colors <- sample(colors(), length(clones), replace = FALSE) +#' named_freq_frame <- update_colors(freq_frame, clones = clones, fill_value = named_clone_colors) +#' named_evo_p <- plot_evofreq(named_freq_frame) +#' +#' ### Custom colors can also be specified using hexcode +#' hex_clone_colors <- c(""#614099ff"", ""#1d347eff"", ""#94558aff"", ""#c96872ff"", ""#f1884dff"", ""#e8fa5bff"", ""#042333ff"",""#f9bb41ff"") +#' hex_freq_frame <- update_colors(freq_frame, clones = clones, fill_value = hex_clone_colors) +#' hex_evo_p <- plot_evofreq(hex_freq_frame) +#' +#' ### Method can also be used to update node colors of the dendrograms +#' dendro_df <- get_evogram(size_df, clones, parents) +#' tree_pos <- dendro_df$dendro_pos +#' tree_links <- dendro_df$links +#' tree_p <- plot_evogram(tree_pos, tree_links) +#' +#' ### Color node by fitness +#' tree_pos_fitness_color <- update_colors(evo_freq_df = tree_pos, clones = clones, fill_value = fitness) +#' tree_p_fitness <- plot_evogram(tree_pos_fitness_color, tree_links) +#' ### Color node using custom colors in hexcode format +#' tree_info_custom_color <- update_colors(evo_freq_df = tree_pos, clones = clones, fill_value = hex_clone_colors) +#' tree_p_custom_color <- plot_evogram(tree_info_custom_color, tree_links) +#'@export +update_colors <- function(evo_freq_df, clones, fill_value=NULL, clone_cmap=NULL, fill_range=NULL, fill_name=NULL, shuffle_colors=FALSE){ + ### FOR TESTING ### + # evo_freq_df <- d_pos_df + # attribute_range <- NULL + # clone_cmap <- NULL #""viridis"" + # fill_value <- fill_value + # attribute_range <- fill_range + # fill_name <- fill_name + #### + if(!is.null(fill_value)){ + ### Value is an attribute to be colored by + if(is.null(fill_name)){ + fill_name <- colnames(fill_value) ### Value was passed in using a string to get the column, e.g. df[fill_name] + if(is.null(fill_name)){ + paresed_fill_name <- deparse(substitute(fill_value)) + fill_name <- get_argname(paresed_fill_name) + } + } + attribute_df <- data.frame(""clone_id""=clones) + attribute_df[fill_name] <- fill_value + + r_colors <- colors() + str_fill_value <- as.character(fill_value) + all_hex <- all(sapply(str_fill_value, function(x){startsWith(x, ""#"") & nchar(x)> 6 & nchar(x) <=9})) + all_rgb <- all(sapply(str_fill_value, function(x){length(strsplit(x, "","")[[1]])==3})) + all_named <- all(sapply(str_fill_value, function(x){x %in% r_colors})) + + user_defined_colors <- any(all_hex, all_rgb, all_named) + if(user_defined_colors){ + fill_name <- NULL + clone_cmap <- ""custom"" + if(all_hex){ + clone_color <- fill_value + }else if(all_rgb){ + clone_color <- rgb2hex(fill_value) + }else if(all_named){ + clone_color <- named2hex(fill_value) + } + + }else{ + ### If values are not hex or cannot be converted to hex, then assume user wants colors generated using a colormap + + if(is.null(clone_cmap)){ + clone_cmap <- 'viridis' + } + if(is.null(fill_range)){ + fill_range <- range(fill_value, na.rm = TRUE) + } + clone_color <- get_attribute_colors(fill_value, min_x = fill_range[1], max_x = fill_range[2], cmap=clone_cmap) + } + # attribute_df <- data.frame(""clone_id""=clones, ""parents""=parents, ""plot_color""=clone_color) + attribute_df <- data.frame(""clone_id""=clones, ""plot_color""=clone_color) + if(!user_defined_colors){ + attribute_df[fill_name] <- fill_value + } + + }else{ + ### Assign unique color for each clone + fill_name <- NULL + if(is.null(clone_cmap)){ + clone_cmap <- 'rainbow_soft' + } + clone_color <- get_clone_color(length(clones), clone_cmap) + if(shuffle_colors){ + clone_color <- sample(clone_color) + } + # attribute_df <- data.frame(""clone_id""=clones, ""parents""=parents, ""plot_color""=clone_color) + attribute_df <- data.frame(""clone_id""=clones, ""plot_color""=clone_color) + } + + attribute_df$cmap <- clone_cmap + + evo_freq_df <- evo_freq_df[! colnames(evo_freq_df) %in% c(""efp_color_attribute"", ""plot_color"", ""cmap"")] ### remove previous color and attribute names + updated_attribute_df <- merge(evo_freq_df, attribute_df, all.x = TRUE, all.y = FALSE, by=""clone_id"") + + ### If any duplicated columns, keep those that were originally in X + dup_x_col_idx <- grep(""\\.x"", colnames(updated_attribute_df)) + if(length(dup_x_col_idx)>0){ + dup_y_col_idx <- grep(""\\.y"", colnames(updated_attribute_df)) + new_x_colnames <- colnames(updated_attribute_df)[dup_x_col_idx] + new_x_colnames <- gsub( ""\\.x"", """", new_x_colnames) + colnames(updated_attribute_df)[dup_x_col_idx] <- new_x_colnames + updated_attribute_df <- updated_attribute_df[-dup_y_col_idx] + } + + if(is.null(fill_name)){ + fill_name <- NA + } + updated_attribute_df$efp_color_attribute <- fill_name + updated_attribute_df$plot_color <- as.character(updated_attribute_df$plot_color) + updated_attribute_df$cmap <- clone_cmap + return(updated_attribute_df) +} + +get_clone_color <- function(n_clones, cmap=""rainbow_soft""){ + ### FOR TESTING ### + # n_clones <- length(clones) + #### + # pop_colors <- colormap::colormap(colormap=colormap::colormaps[cmap][[1]], nshades=n_clones+1)[1:n_clones] + # n_clones, cmap_name + # pop_colors <- get_colors(n_clones+1, cmap)[1:n_clones] + pop_colors <- get_colors(n_clones+1, cmap)[1:n_clones] + return(pop_colors) +} + +get_attribute_colors <- function(x, min_x =NULL, max_x = NULL, n_color_bins = 100, cmap=""viridis""){ + ### FOR TESTING ### + # x <- clone_antigenicity + # x <- fill_value + # min_x <- fill_range[1] + # max_x <- fill_range[2] + # cmap <- clone_cmap + # n_color_bins <- 100 + #### + if(is.null(min_x)){ + min_x <- min(x) + } + if(is.null(max_x)){ + max_x <- max(x) + } + + bin_breaks <- seq(min_x, max_x , length.out = n_color_bins) + bin_number <- findInterval(x, bin_breaks, rightmost.closed = FALSE, all.inside=TRUE) + + # cmap_colors <- colormap::colormap(colormaps[cmap][[1]], nshades=n_color_bins) + cmap_colors <- get_colors(n_color_bins, cmap) + colors <- cmap_colors[bin_number] + return(colors) +} + +scale_value <- function(x, in_min, in_max, out_min, out_max){ + new_x <- ((out_max - out_min)*(x-in_min))/(in_max - in_min) + out_min + return(new_x) +} + +rgb2hex <- function(cvals){ + ### FOR TESTING ### + # cvals <- sapply(seq(1, 10), function(x){paste(sample(0:255,size=3,replace=TRUE),collapse="","")}) + # cvals <- sapply(seq(1, 10), function(x){paste(sample(0:255,size=3,replace=TRUE),collapse="" "")}) + ### FOR TESTING ### + delimiters <- c("" "", "","") + delimiter <- delimiters[which(sapply(delimiters, function(x){grepl(x, cvals[1])}))] + fill_mat <- t(sapply(cvals, function(x){as.numeric(strsplit(x, delimiter)[[1]])})) + max_fill_val <- max(fill_mat) + if(max_fill_val <= 1){ + max_fill_val <- 1 + }else{ + max_fill_val <- 255 + } + + hex_colors <- sapply(seq(nrow(fill_mat)), function(x){rgb(fill_mat[x, 1], fill_mat[x, 2], fill_mat[x, 3], maxColorValue=max_fill_val, alpha=max_fill_val)}) + return(hex_colors) +} + +named2hex <- function(cvals){ + ### FOR TESTING ### + # cvals <- sample(colors(), 10) + #### + + fill_mat <- t(sapply(cvals, function(x){as.numeric(col2rgb(x))})) ### Each column is a color + max_fill_val <- max(fill_mat) + if(max_fill_val <= 1){ + max_fill_val <- 1 + }else{ + max_fill_val <- 255 + } + + hex_colors <- sapply(seq(nrow(fill_mat)), function(x){rgb(fill_mat[x, 1], fill_mat[x, 3], fill_mat[x, 3], maxColorValue=max_fill_val, alpha=max_fill_val)}) + + return(hex_colors) + +}","R" +"Homeostasis","MathOnco/EvoFreq","R/Dendro_funcs.R",".R","24538","577","get_heirarchy_level <- function(clone_id, clone_list, parent_list){ + ###FOR TESTING ### + # clone_list <- clones_for_d + # parent_list <- parents_for_d + # clone_id <- 48 + #### + ### Assigns y-position, based on number of parents. Represents number of steps back to common ancestor + + ### clone 48 is at level 11. It's parent, 32 should be at level 10 but it is at level 5. OR, clone 48 should be at level 6 + + root_id <- get_root_id(clone_list, parent_list) + if(root_id==clone_id){ + return(NULL) + } + clone_idx <- which(clone_list == clone_id) + clone_parent <- parent_list[clone_idx] + h_level <- 0 + while(clone_parent != root_id){ + h_level <- h_level + 1 + parent_idx <- which(clone_list == clone_parent) + clone_parent <- parent_list[parent_idx] + } + return(h_level) +} + +get_dendrogram_pos <- function(attr_df, clones_for_d, parents_for_d){ + ### FOR TESTING + ### NOTE attr_df needs to at least have clone ids, parent_ids, and node_ids + # clones_for_d <- to_plot_df$clones + # parents_for_d <- to_plot_df$parents + # attr_df <- to_plot_df$attributes + ### + ### All have been sorted by origin + h_level_df <- attr_df + h_level_df$clone_id <- clones_for_d + h_level_df$parents <- parents_for_d + + h_level_df$y <- sapply(clones_for_d, function(x){get_heirarchy_level(x, clones_for_d, parents_for_d)}) + h_level_df$tree_y <- h_level_df$y + max_level <- max(h_level_df$y) + leaves_idx <- which(!clones_for_d %in% parents_for_d) + h_level_df$y[leaves_idx] <- max_level ###can put all leaves at the bottom + h_level_df$dendro_y <- h_level_df$y ### Their position if drawn so all leaves on bottom + + h_level_df$x <- NA + + ### Get position of all leaves + n_leaves <- length(leaves_idx) + if(n_leaves == 1){ + leaf_x <- 0.5 + }else{ + leaf_x <- seq(0, 1, length.out = n_leaves) + } + + ### Start at top, move down. + ### For each node, get leaves of subtree. Center node around leaves of this subtree + ### TODO Order leaves so that they go + ### Keep track of where in leaf positions + root_id <- get_root_id(clones_for_d, parents_for_d) + parent_pos_range_list <- list() + parent_pos_range_list[[as.character(root_id)]] <- leaf_x + traversal_idx <- get_node_idx(root_id, c_list = h_level_df$clone_id, p_list = h_level_df$parents) + traversal_order <- order(traversal_idx$vertex) + for(i in traversal_order){ + ### Can go through tree using traversal order. Gurantees parent's positions will have been determined already + if(i == 1){ + ### This is the root + next() + } + + cid <- traversal_idx$vertex[i] #h_level_df$clone_id[traversal_idx$idx[i]] + if(as.character(cid) %in% names(parent_pos_range_list)){next()} + clone_parent <- h_level_df$parents[h_level_df$clone_id == cid] #h_level_df$parents[traversal_idx$idx[i]] + parents_pos_range <- parent_pos_range_list[[as.character(clone_parent)]] + all_nodes <- h_level_df$clone_id[which(h_level_df$parents == clone_parent)] ### Get all nodes with this parent + + pos_idx <- 0 + for(cidx in seq(1, length(all_nodes))){ + subtree_idx <- get_all_idx(all_nodes[cidx], c_list = h_level_df$clone_id, p_list = h_level_df$parents) ### includes clone, so should always have at least length 1 + n_leaves <- length(which(!h_level_df$clone_id[subtree_idx] %in% h_level_df$parents[subtree_idx])) + next_pos_idx <- n_leaves + pos_idx + leaf_range <- parents_pos_range[seq(pos_idx + 1, next_pos_idx)] + + h_level_df$x[h_level_df$clone_id == all_nodes[cidx]] <- mean(leaf_range) + + # print(all_nodes[cidx]) + # print(c(n_leaves, length(subtree_idx))) + + # print(leaf_range) + # print(mean(leaf_range)) + # print("""") + + pos_idx <- next_pos_idx + parent_pos_range_list[[as.character(all_nodes[cidx])]] <- leaf_range + + } + + } + + return(h_level_df) + +} + +filter_edges_at_time <- function(size_df, clones, parents, time_pt=NULL, attribute_df=NULL, threshold=0.01, data_type=""size"", fill_gaps_in_size = FALSE, test_links=TRUE, rescale_after_thresholding=FALSE){ + ### FOR TESTING ### + # clones <- clone_df$CloneID + # parents <- clone_df$ParentID + # size_df + + #### + if(any(duplicated(clones))){ + warning(""Some clones have the same ID. Each clone should have a unique ID"") + } + if(is.null(time_pt)){ + time_pt <- tail(colnames(size_df), n=1) + }else{ + time_pt <- as.character(time_pt) + } + + if(fill_gaps_in_size){ + size_df <- as.data.frame(t(apply(size_df, 1, fill_in_gaps))) + } + + ### Make sure clone does not have the same id as it's parent. If true, it can cause infinite recursion + if(test_links){ + updated_edges <- check_and_update_edges(clones, parents) + clones <- updated_edges$updated_clones + parents <- updated_edges$updated_parents + } + + if(data_type==""size""){ + ### data are sizes of each clone. Here, the frequency of each mutation will be determined + freq_df <- get_mutation_df(size_df, clones = clones, parents = parents) + freq_mat <- as.matrix(freq_df) + freq_mat <- sweep(freq_mat, 2, colSums(size_df), ""/"") + + }else{ + check_freq_mat(size_df, clones, parents) + freq_mat <- size_df + updated_edges <- check_and_update_edges(clones, parents) + clones <- updated_edges$updated_clones + parents <- updated_edges$updated_parents + } + + + ### Subset time points to be plotted + if(is.null(nrow(freq_mat))){ + ###Only 1 clone + freq_mat <- t(as.matrix(freq_mat)) + } + + colnames(freq_mat) <- colnames(size_df) + row.names(freq_mat) <- clones + freq_array <- freq_mat[,time_pt] + origin_times <- as.numeric(apply(freq_mat, 1, function(x){which(x>0)[1]})) + + + ### Possible that a clone was recorded, but didn't exist at this time point + existed_idx <- which(freq_array > 0) + freq_array <- freq_array[existed_idx] + clones <- clones[existed_idx] + parents <- parents[existed_idx] + origin_times <- origin_times[existed_idx] + if(! is.null(attribute_df)){ + attribute_df <- attribute_df[existed_idx, ] + } + + ### Filter values based on threshold + if(threshold > 0){ + filtered_idx <- which(freq_array >= threshold) + freq_array <- freq_array[filtered_idx] + parents <- parents[filtered_idx] + clones <- clones[filtered_idx] + origin_times <- origin_times[filtered_idx] + + if(rescale_after_thresholding){ + freq_mat <- rescale_frequencies(size_df, clones, parents, filtered_idx, data_type) + } + + if(!is.null(attribute_df)){ + attribute_df <- attribute_df[filtered_idx, ] + } + } + if(is.null(attribute_df)){ + attribute_df <- data.frame(""clone_id""=clones, ""parents""=parents) + } + + attribute_df$freq <- freq_array + attribute_df$origin <- origin_times + + ordered_idx <- order(origin_times) + clones <- clones[ordered_idx] + parents <- parents[ordered_idx] + attribute_df <- attribute_df[ordered_idx, ] + attribute_df$node_id <- seq(1, length(clones)) + + # clone_col_idx <- as.numeric(which(sapply(colnames(attribute_df), FUN = function(x){all(clones %in% as.character(unique(attribute_df[,x])))})==TRUE)) + # + # if(length(clone_col_idx) > 1){ + # #### If all clones in pos df are also parents, and there are both parent and clone ids in attribute_df, then more than 1 column will considered the clone_id column in attribute_df + # ### Not possible for all clones in attribute df to also all be parents + # ### So clone_id column is the one that has more unique elements + # n_unique_clones <- apply(attribute_df[clone_col_idx], 2, function(x){length(unique(x))}) + # clone_col_name <- names(n_unique_clones)[which(n_unique_clones==max(n_unique_clones))] + # } + # + # colnames(attribute_df)[clone_col_idx] <- ""clone_id"" + + # to_plot_df$attributes + # clone_col_idx <- which(colnames(to_plot_df$attributes)==clone_id_col_in_att_df) + # if(length(clone_col_idx) == 0 | clone_id_col_in_att_df != ""clone_id"" | ! ""clone_id"" %in% colnames(to_plot_df$attributes){ + # print(""do not know column in attribute_df that contains clone IDs. Please check the clone_id_col_in_att_df argument or set the clone ID column in attribute_df to be 'clone_id'"") + # } + + # clone_col_idx <- which(colnames(attribute_df)==clone_id_col_in_att_df) + # if(length(clone_col_idx) == 0 & clone_id_col_in_att_df != ""clone_id"" & ! ""clone_id"" %in% colnames(attribute_df)){ + # print(""do not know column in attribute_df that contains clone IDs. Please check the clone_id_col_in_att_df argument or set the clone ID column in attribute_df to be 'clone_id'"") + # } + # colnames(attribute_df)[clone_col_idx] <- ""clone_id"" + + + return(list(""clones""=clones, ""parents""=parents, ""attributes""=attribute_df)) +} + +get_straight_links <- function(dendro_df){ + ### FOR TESTING ### + # dendro_df <- dendro_pos + #### + link_df <- dendro_df + link_df$link_type <- ""straight"" + link_df$end_x <- NA + link_df$end_y <- NA + link_df$end_tree_y <- NA + link_df$end_origin <- NA + link_df$end_dendro_y <- NA + n_clones <- length(link_df$clone_id) + for(cidx in seq(1, n_clones)){ + + pid <- link_df$parents[cidx] + p_idx <- which(link_df$clone_id == pid) + if(length(p_idx)==0){ + ## root ## + next() + } + link_df$end_x[cidx] <- link_df$x[p_idx] + link_df$end_y[cidx] <- link_df$y[p_idx] + link_df$end_origin[cidx] <- link_df$origin[p_idx] + link_df$end_dendro_y[cidx] <- link_df$dendro_y[p_idx] + link_df$end_tree_y[cidx] <- link_df$tree_y[p_idx] + } + return(link_df) +} + +get_elbow_links <- function(dendro_df){ + ### FOR TESTING ### + # dendro_df <- dendro_pos + #### + info_cols <- colnames(dendro_df)[! colnames(dendro_df) %in% c(""x"", ""dendro_y"", ""tree_y"", ""y"")] + link_df_list <- list() + parents <- unique(dendro_df$parents) + for(p in parents){ + # p <- parents[2] + pidx <- which(dendro_df$clone_id == p) + if(length(pidx)== 0){ + ### root + next() + } + + children_idx <- which(dendro_df$parents == p) + + mid_y <- mean(c(dendro_df$y[pidx], min(dendro_df$y[children_idx]))) + mid_tree_y <- mean(c(dendro_df$tree_y[pidx], min(dendro_df$tree_y[children_idx]))) + mid_origin <- mean(c(dendro_df$origin[pidx], min(dendro_df$origin[children_idx]))) + mid_dendro_y <- mean(c(dendro_df$dendro_y[pidx], min(dendro_df$dendro_y[children_idx]))) + + for(cidx in children_idx){ + ### each parent has a path: + ### 2) its xy + ### 2) its same x, down to y between it and child + ### 3) child's x, and the y between it and child + ### 4) child's xy + link_info <- dendro_df[cidx, info_cols] + # mid_y <- mean(c(dendro_df$y[pidx], dendro_df$y[cidx])) + # mid_origin <- mean(c(dendro_df$origin[pidx], dendro_df$origin[cidx])) + # mid_dendro_y <- mean(c(dendro_df$dendro_y[pidx], dendro_df$dendro_y[cidx])) + # mid_tree_y <- mean(c(dendro_df$tree_y[pidx], dendro_df$tree_y[cidx])) + single_link_df <- link_info[rep(1, 4), ] + single_link_df$x <- c(dendro_df$x[pidx], dendro_df$x[pidx], dendro_df$x[cidx], dendro_df$x[cidx]) + single_link_df$y <- c(dendro_df$y[pidx], mid_y, mid_y, dendro_df$y[cidx]) + single_link_df$origin_y <- c(dendro_df$origin[pidx], mid_origin, mid_origin, dendro_df$origin[cidx]) + single_link_df$dendro_y <- c(dendro_df$dendro_y[pidx], mid_dendro_y, mid_dendro_y, dendro_df$dendro_y[cidx]) + single_link_df$tree_y <- c(dendro_df$tree_y[pidx], mid_tree_y, mid_tree_y, dendro_df$tree_y[cidx]) + link_df_list[[as.character(cidx)]] <- single_link_df + } + } + + link_df <- do.call(rbind, link_df_list) + link_df$link_type <- ""elbow"" + # link_df$tree_y <- link_df$y + return(link_df) + + +} + +#'@title get_evogram +#' +#'Collect information to plot dendrogram +#'@inheritParams get_evofreq +#'@param time_pt Timepoint with which the dendrgram should be drawn +#'@param link_type Defines the shape of the edges berween nodes: ""straight"" draws straight lines between parents and childrend, while ""elbow"" draws a step from parent to child +#'@return List containing two dataframes: ""dendro_pos"" contains the positions of the nodes, ""links"" contains the positions of the edges between nodes +#' @examples +#' data(""example.easy.wide"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide))))) +#' size_df <- example.easy.wide[, time_col_idx] +#' parents <- example.easy.wide$parent +#' clones <- example.easy.wide$clone +#' +#' tree_info <- get_evogram(size_df, parents = parents, clones = clones) +#' tree_pos <- tree_info$dendro_pos +#' elbow_links <- tree_info$links +#' tree_p <- plot_evogram(tree_pos, elbow_links) +#' +#' ### Can also plot with straight links +#' tree_info <- get_evogram(size_df, parents = parents, clones = clones, link_type = ""straight"") +#' tree_pos <- tree_info$dendro_pos +#' straight_links <- tree_info$links +#' tree_straight_p <- plot_evogram(tree_pos, straight_links) +#' +#' ### Can also set nodes to be colored by attribute +#' data(""example.easy.wide.with.attributes"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attr_size_df <- example.easy.wide.with.attributes[, time_col_idx] +#' attr_parents <- example.easy.wide.with.attributes$parent +#' attr_clones <- example.easy.wide.with.attributes$clone +#' fitness <- example.easy.wide.with.attributes$fitness +#' +#' attribute_dendro_df <- get_evogram(attr_size_df, attr_clones, attr_parents, fill_value = fitness) +#' attribute_tree_pos <- attribute_dendro_df$dendro_pos +#' attribute_elbow_links <- attribute_dendro_df$links +#' attribute_tree_elbow_p <- plot_evogram(attribute_tree_pos, attribute_elbow_links, scale_by_node_size = TRUE) +#' @export +get_evogram <- function(size_df, clones, parents, fill_value=NULL, fill_range = NULL, time_pt=NULL, clone_cmap=NULL, threshold=0.01, data_type=""size"", fill_gaps_in_size = FALSE, test_links=TRUE, link_type=""elbow"", rescale_after_thresholding=FALSE, shuffle_colors=FALSE){ + # ## FOR TESTING ### + # Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values# + # data(""example.easy.wide"") + # ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values + # time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) + # attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide))))) + # size_df <-size_df #example.easy.wide[, time_col_idx] + # parents <- clone_df$ParentID #example.easy.wide$parent + # clones <- clone_df$CloneID #example.easy.wide$clone + # fill_value <- clone_df$Passengers + # threshold <- 0.02 + # clone_cmap <- ""rainbow_soft"" + + # size_df <- hal_info$size_df + # clones <- hal_info$clones + # parents <- hal_info$parents + # time_pt <- NULL + # data_type <- ""size"" + # scale_by_sizes_at_time <- FALSE + # fill_gaps_in_size <- FALSE + # test_links <- TRUE + # threshold <- 0.01 + # link_type <- ""elbow"" + # rescale_after_thresholding <- F + # fill_value <- NULL + # # ### + + + if(!is.null(fill_value)){ + fill_name <- colnames(fill_value) ### Value was passed in using a string to get the column, e.g. df[fill_name] + if(is.null(fill_name)){ + paresed_fill_name <- deparse(substitute(fill_value)) + fill_name <- get_argname(paresed_fill_name) + } + attribute_df <- data.frame(""clone_id""=clones) + attribute_df[fill_name] <- fill_value + }else{ + attribute_df <- NULL + fill_name <- NULL + } + if(!is.null(fill_name)){ + fill_value <- attribute_df[, fill_name] + if(is.null(fill_range)){ + fill_range <- range(fill_value, na.rm = TRUE) + } + } + + ### Filter info ### + to_plot_df <- filter_edges_at_time(size_df = size_df, clones = clones, parents = parents, time_pt = time_pt, attribute_df = attribute_df, threshold = threshold, data_type = data_type, fill_gaps_in_size = fill_gaps_in_size, test_links=test_links, rescale_after_thresholding=rescale_after_thresholding) + ### Get dendrogram positions and attributes ### + + dendro_pos <- get_dendrogram_pos(to_plot_df$attributes, clones_for_d = to_plot_df$clones, parents_for_d = to_plot_df$parents) + if(!is.null(attribute_df)){ + attribute_df <- to_plot_df$attributes + } + + ### At this point, origin times are based on the column idx. Needs to also include actual timepoints + actual_time_pts <- colnames(size_df) + dendro_pos$origin_time <- actual_time_pts[dendro_pos$origin] + any_non_numeric_time_pts <- suppressWarnings(any(is.na(as.numeric(dendro_pos$origin_time)))) + if(! any_non_numeric_time_pts){ + dendro_pos$origin <- as.numeric(dendro_pos$origin_time) + } + + dendro_pos <- update_colors(evo_freq_df = dendro_pos, clones = clones, fill_value = fill_value, clone_cmap = clone_cmap, fill_range = fill_range, fill_name=fill_name, shuffle_colors=shuffle_colors) + + ### Add line segments: Elbow or diagonal ### + if(link_type == ""straight""){ + link_df <- get_straight_links(dendro_pos) + }else{ + link_df <- get_elbow_links(dendro_pos) + } + + return(list(""dendro_pos""=dendro_pos, ""links""=link_df)) +} + + +#'@title plot_evogram +#'Plot dendrogram +#'@inheritParams plot_evofreq +#'@param dendro_pos_df Position of nodes returned by \code{\link{get_evogram}} +#'@param link_df Position of edges returned by \code{\link{get_evogram}} +#'@param node_size Determines the size of nodes if \code{scale_by_node_size} is FALSE +#'@param scale_by_node_size Boolean defining if the size of each node should be proportional to its frequency. If FALSE, then all nodes have the same size, determined by \code{node_size} +#'@param orientation Defines orientation of the tree: ""td"" draws it top-down, ""lr"" draws it left-right +#'@param depth Determines the y-position of the nodes: ""level"" places the nodes based on how deeply they are nested in the tree, ""origin"" makes the y-position the same as the clone's origin time, ""bottom"" positions nodes so that all leaves have the same position, furthest from the root +#'@return a ggplot object to plot the tree +#'@examples +#' data(""example.easy.wide"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide))))) +#' +#' size_df <- example.easy.wide[, time_col_idx] +#' parents <- example.easy.wide$parent +#' clones <- example.easy.wide$clone +#' +#' tree_info <- get_evogram(size_df, parents = parents, clones = clones) +#' tree_pos <- tree_info$dendro_pos +#' elbow_links <- tree_info$links +#' tree_p <- plot_evogram(tree_pos, elbow_links) +#' +#' ### Can also plot with elbow links +#' tree_info <- get_evogram(size_df, parents = parents, clones = clones, link_type = ""straight"") +#' tree_pos <- tree_info$dendro_pos +#' straight_links <- tree_info$links +#' tree_straight_p <- plot_evogram(tree_pos, straight_links) +#' +#' ### Default is for y to show time of clonal origin , all leaves can be at the highest level +#' elbow_bottom_p <- plot_evogram(tree_pos, elbow_links, depth = ""bottom"") +#' ### Can view left to right by changing orientation argument +#' lr_tree_elbow_p <- plot_evogram(tree_pos, elbow_links, orientation = ""lr"") +#' #' ### Can color using attributes +#' data(""example.easy.wide.with.attributes"") +#' ### Split dataframe into clone info and size info using fact timepoint column names can be converted to numeric values +#' time_col_idx <- suppressWarnings(which(! is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attribute_col_idx <- suppressWarnings(which(is.na(as.numeric(colnames(example.easy.wide.with.attributes))))) +#' attr_size_df <- example.easy.wide.with.attributes[, time_col_idx] +#' attr_parents <- example.easy.wide.with.attributes$parent +#' attr_clones <- example.easy.wide.with.attributes$clone +#' fitness <- example.easy.wide.with.attributes$fitness +#' #' ### Can set color using attributes. Default colormap is viridis, but can be changed to any colormap available in the colormaps package. For a list of available colormaps, see https://github.com/bhaskarvk/colormap +#' attribute_dendro_df <- get_evogram(attr_size_df, attr_clones, attr_parents, fill_value = fitness) +#' attribute_tree_pos <- attribute_dendro_df$dendro_pos +#' attribute_elbow_links <- attribute_dendro_df$links +#' attribute_tree_elbow_p <- plot_evogram(attribute_tree_pos, attribute_elbow_links) +#' @export +plot_evogram <- function(dendro_pos_df, link_df, fill_range=NULL, node_size=5, scale_by_node_size=TRUE, orientation=""td"", depth=""origin""){ + ### FOR TESTING ### + # dendro_pos_df <- hal_dendro_df$dendro_pos + # link_df <- hal_dendro_df$links + # scale_by_node_size = TRUE + # orientation=""td"" #= top_down, ""lr"" left right + # depth <- ""origin"" + # fill_range <- NULL + ### + + link_df <- link_df[complete.cases(link_df$x),] + link_type <- unique(link_df$link_type) + + if(depth == ""origin""){ + y_name <- ""origin_y"" + end_y_name <- ""end_origin"" + dendro_pos_df$origin_y <- dendro_pos_df$origin + time_levels <- as.numeric(as.character(unique(dendro_pos_df$origin))) + time_labels <- as.character(unique(dendro_pos_df$origin_time)) + if(link_type==""straight""){ + link_df$origin_y <- link_df$origin + } + }else if(depth==""level""){ + y_name <- ""tree_y"" + end_y_name <- ""end_tree_y"" + }else if(depth==""bottom""){ + y_name <- ""dendro_y"" + end_y_name <- ""end_dendro_y"" + } + + color_attribute_name <- unique(dendro_pos_df$efp_color_attribute) + if(is.na(color_attribute_name)){ + color_attribute_name <- ""plot_color"" + }else{ + if(is.null(fill_range)){ + fill_range <- range(dendro_pos_df[, color_attribute_name], na.rm = TRUE) + } + } + # unique(link_df$clone_id) + # unique(dendro_pos_df$clone_id) + if(link_type == ""straight""){ + p <- ggplot2::ggplot(dendro_pos_df, ggplot2::aes_string(x=""x"", y=y_name, color=color_attribute_name, size=""freq"")) + + ggplot2::geom_segment(data=link_df, ggplot2::aes_string(x=""x"", y=y_name, xend=""end_x"", yend=end_y_name), inherit.aes = FALSE) #+ + # ggplot2::scale_color_identity() + + }else{ + p <- ggplot2::ggplot(dendro_pos_df, ggplot2::aes_string(x=""x"", y=y_name, color=color_attribute_name, size=""freq"")) + + ggplot2::geom_path(data=link_df, ggplot2::aes_string(x=""x"", y=y_name, group=""clone_id""), inherit.aes = FALSE) #+ + # ggplot2::scale_color_identity() + } + + if(color_attribute_name==""plot_color""){ + p <- p + ggplot2::scale_color_identity() + }else{ + colormap_name <- unique(dendro_pos_df$cmap) + colorbar_colors <- get_colors(100, colormap_name) + p <- p + ggplot2::scale_fill_gradientn(colours = colorbar_colors, limits=fill_range) #colormap::scale_fill_colormap(color_attribute_name, colormap=colormap_name) + # p <- p + colormap::scale_color_colormap(color_attribute_name, colormap=colormap_name, limits=fill_range) + # p <- p + ggplot2::scale_color_gradientn(colours = colorbar_colors) #colormap::scale_fill_colormap(color_attribute_name, colormap=colormap_name) + } + + + if(depth==""origin""){ + y_title <- ""Time"" + }else{ + y_title <- ""Level"" + } + + + if(scale_by_node_size){ + p <- p + ggplot2::geom_point() + }else{ + p <- p + ggplot2::geom_point(size=node_size) + } + + p <- p + + ggplot2::theme_classic() + + ggplot2::ylab(y_title) + + if(orientation==""lr""){ + if(depth==""origin""){ + p <- p + ggplot2::scale_y_continuous(breaks=time_levels, labels=time_labels) + } + p <- p + ggplot2::coord_flip() + + ggplot2::theme(axis.text.y = ggplot2::element_blank(), + axis.ticks.y = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(angle = 45, hjust = 1)) + + + }else{ + p <- p + ggplot2::theme(axis.text.x = ggplot2::element_blank(), + axis.ticks.x = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank()) + if(depth==""origin""){ + p <- p + ggplot2::scale_y_reverse(breaks=time_levels, labels=time_labels) + }else{ + p <- p + ggplot2::scale_y_reverse() + } + } + + return(p) +}","R" +"Homeostasis","MathOnco/EvoFreq","R/Example.Easy.Wide.R",".R","681","23","#' Clone information dataset in Easy Wide Format +#' +#' A dataset for easy understanding of EvoFreq data structures. +#' +#' @format A data frame with 8 rows and 10 variables: +#' \describe{ +#' \item{parents}{Parent clone} +#' \item{clones}{Clone metadata} +#' \item{1}{Timepoint 1 clone sizes} +#' \item{2}{Timepoint 2 clone sizes} +#' \item{3}{Timepoint 3 clone sizes} +#' \item{4}{Timepoint 4 clone sizes} +#' \item{5}{Timepoint 5 clone sizes} +#' \item{6}{Timepoint 6 clone sizes} +#' \item{7}{Timepoint 7 clone sizes} +#' \item{8}{Timepoint 8 clone sizes} +#' } +#' @source Custom Made. +#' @examples +#' ?example.easy.wide +#' data(""example.easy.wide"") +""example.easy.wide"" +","R" +"Homeostasis","MathOnco/EvoFreq","R/Example.Long.Clone.History.R",".R","534","16","#' Clone information dataset in Long Format +#' +#' A dataset from a simulation taken from ""Niche engineering drives early passage through an immune bottleneck in progression to colorectal cancer"" +#' +#' @format A data frame with 2677 rows and 5 variables: +#' \describe{ +#' \item{clone_id}{ID of clone} +#' \item{time}{Time of measurement} +#' \item{size}{Size of clone} +#' } +#' @source \url{https://www.biorxiv.org/content/10.1101/623959v2} +#' @examples +#' if (require(""EvoFreq"")) { +#' example.long.clones +#' } +""example.long.clones""","R" +"Homeostasis","MathOnco/EvoFreq","tests/testthat/test.example.labels.R",".R","1130","19","context(""evofreq_clone_labels testing"") + +test_that(""evofreq_clone_labels evaluation on easy examples."",{ + data(""example.easy.wide"") # Load Data + clone_dyn_df <- get_freq_dynamics(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"") + evo_freq_p <- plot_freq_dynamics(clone_dyn_df) + clone_labels <- evofreq_clone_labels(clone_dyn_df, extant_only=T, evo_freq_p=evo_freq_p, apply_labels=T) + expect_equal(class(clone_labels), c(""gg"",""ggplot"")) + clone_labels <- evofreq_clone_labels(clone_dyn_df, extant_only=T, evo_freq_p=evo_freq_p, apply_labels=F) + expect_equal(clone_labels$clone_id, c(1,3,4,5,6,7,8)) + expect_equal(round(clone_labels$y_plotValue[4],4), 802.9992) + clone_labels <- evofreq_clone_labels(clone_dyn_df, extant_only=F, evo_freq_p=evo_freq_p, apply_labels=F) + expect_equal(clone_labels$clone_id, c(1,2,3,4,5,6,7,8)) + expect_equal(round(clone_labels$y_plotValue[2],4), 433.7922) + clone_labels <- evofreq_clone_labels(clone_dyn_df, extant_only=F, evo_freq_p=evo_freq_p, apply_labels=F, clone_list = c(2)) + expect_equal(length(clone_labels$clone_id), 1) +}) + +","R" +"Homeostasis","MathOnco/EvoFreq","tests/testthat/test.example.plotting.R",".R","106","5","context(""plot_freq_dynamics testing"") + +test_that(""plot_freq_dynamics evaluation on easy examples."",{ + +})","R" +"Homeostasis","MathOnco/EvoFreq","tests/testthat/test.example.get_freq_dynamics.R",".R","1242","16","context(""get_freq_dynamics testing"") + +test_that(""get_freq_dynamics evaluation on easy examples."",{ + data(""example.easy.wide"") + clone_dyn_df.wide <- get_freq_dynamics(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"",scale_by_sizes_at_time = F) + clone_dyn_df.wide.scale <- get_freq_dynamics(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"", scale_by_sizes_at_time = T) + val <- clone_dyn_df.wide.scale[66,3] + val2 <- clone_dyn_df.wide[26,3] + expect_equal(colnames(example.easy.wide), c(""parents"",""clones"",""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"")) + expect_equal(unique(unique(as.numeric(clone_dyn_df.wide$draw_order))==c(1,2,3,5,4,6,7,8)), TRUE) + expect_equal(unique(as.numeric(clone_dyn_df.wide$origin_time)), c(1,2,6,8)) + expect_equal(7.727264e-18*1e18, expected = val*1e18, tolerance = 0.001, scale = val) + expect_equal(335.661975, expected = val2, tolerance = 0.001, scale = val2) + clone_dyn_df.wide <- get_freq_dynamics(example.easy.wide[,seq(3,10)], example.easy.wide$clones, example.easy.wide$parents, clone_cmap = ""magma"",scale_by_sizes_at_time = T, threshold=0.1) + expect_equal(0.0, expected = clone_dyn_df.wide[75,3]) +})","R"