calculate_interaction_zscores.R 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. suppressMessages({
  2. library("ggplot2")
  3. library("plotly")
  4. library("htmlwidgets")
  5. library("dplyr")
  6. library("rlang")
  7. library("ggthemes")
  8. library("data.table")
  9. library("unix")
  10. })
  11. options(warn = 2)
  12. # Set the memory limit to 30GB (30 * 1024 * 1024 * 1024 bytes)
  13. soft_limit <- 30 * 1024 * 1024 * 1024
  14. hard_limit <- 30 * 1024 * 1024 * 1024
  15. rlimit_as(soft_limit, hard_limit)
  16. # Constants for configuration
  17. plot_width <- 14
  18. plot_height <- 9
  19. base_size <- 14
  20. parse_arguments <- function() {
  21. args <- if (interactive()) {
  22. c(
  23. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240116_jhartman2_DoxoHLD",
  24. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/apps/r/SGD_features.tab",
  25. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/easy/20240116_jhartman2_DoxoHLD/results_std.txt",
  26. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240822_jhartman2_DoxoHLD/exp1",
  27. "Experiment 1: Doxo versus HLD",
  28. 3,
  29. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240822_jhartman2_DoxoHLD/exp2",
  30. "Experiment 2: HLD versus Doxo",
  31. 3
  32. )
  33. } else {
  34. commandArgs(trailingOnly = TRUE)
  35. }
  36. # Extract paths, names, and standard deviations
  37. paths <- args[seq(4, length(args), by = 3)]
  38. names <- args[seq(5, length(args), by = 3)]
  39. sds <- as.numeric(args[seq(6, length(args), by = 3)])
  40. # Normalize paths
  41. normalized_paths <- normalizePath(paths, mustWork = FALSE)
  42. # Create named list of experiments
  43. experiments <- list()
  44. for (i in seq_along(paths)) {
  45. experiments[[names[i]]] <- list(
  46. path = normalized_paths[i],
  47. sd = sds[i]
  48. )
  49. }
  50. list(
  51. out_dir = normalizePath(args[1], mustWork = FALSE),
  52. sgd_gene_list = normalizePath(args[2], mustWork = FALSE),
  53. easy_results_file = normalizePath(args[3], mustWork = FALSE),
  54. experiments = experiments
  55. )
  56. }
  57. args <- parse_arguments()
  58. # Should we keep output in exp dirs or combine in the study output dir?
  59. # dir.create(file.path(args$out_dir, "zscores"), showWarnings = FALSE)
  60. # dir.create(file.path(args$out_dir, "zscores", "qc"), showWarnings = FALSE)
  61. # Define themes and scales
  62. theme_publication <- function(base_size = 14, base_family = "sans", legend_position = "bottom") {
  63. theme_foundation <- ggplot2::theme_grey(base_size = base_size, base_family = base_family)
  64. theme_foundation %+replace%
  65. theme(
  66. plot.title = element_text(face = "bold", size = rel(1.2), hjust = 0.5),
  67. text = element_text(),
  68. panel.background = element_rect(colour = NA),
  69. plot.background = element_rect(colour = NA),
  70. panel.border = element_rect(colour = NA),
  71. axis.title = element_text(face = "bold", size = rel(1)),
  72. axis.title.y = element_text(angle = 90, vjust = 2),
  73. axis.title.x = element_text(vjust = -0.2),
  74. axis.line = element_line(colour = "black"),
  75. panel.grid.major = element_line(colour = "#f0f0f0"),
  76. panel.grid.minor = element_blank(),
  77. legend.key = element_rect(colour = NA),
  78. legend.position = legend_position,
  79. legend.direction = ifelse(legend_position == "right", "vertical", "horizontal"),
  80. plot.margin = unit(c(10, 5, 5, 5), "mm"),
  81. strip.background = element_rect(colour = "#f0f0f0", fill = "#f0f0f0"),
  82. strip.text = element_text(face = "bold")
  83. )
  84. }
  85. scale_fill_publication <- function(...) {
  86. discrete_scale("fill", "Publication", manual_pal(values = c(
  87. "#386cb0", "#fdb462", "#7fc97f", "#ef3b2c", "#662506",
  88. "#a6cee3", "#fb9a99", "#984ea3", "#ffff33"
  89. )), ...)
  90. }
  91. scale_colour_publication <- function(...) {
  92. discrete_scale("colour", "Publication", manual_pal(values = c(
  93. "#386cb0", "#fdb462", "#7fc97f", "#ef3b2c", "#662506",
  94. "#a6cee3", "#fb9a99", "#984ea3", "#ffff33"
  95. )), ...)
  96. }
  97. # Load the initial dataframe from the easy_results_file
  98. load_and_process_data <- function(easy_results_file, sd = 3) {
  99. df <- read.delim(easy_results_file, skip = 2, as.is = TRUE, row.names = 1, strip.white = TRUE)
  100. df <- df %>%
  101. filter(!(.[[1]] %in% c("", "Scan"))) %>%
  102. filter(!is.na(ORF) & ORF != "" & !Gene %in% c("BLANK", "Blank", "blank") & Drug != "BMH21") %>%
  103. # Rename columns
  104. rename(L = l, num = Num., AUC = AUC96, scan = Scan, last_bg = LstBackgrd, first_bg = X1stBackgrd) %>%
  105. mutate(
  106. across(c(Col, Row, num, L, K, r, scan, AUC, last_bg, first_bg), as.numeric),
  107. delta_bg = last_bg - first_bg,
  108. delta_bg_tolerance = mean(delta_bg, na.rm = TRUE) + (sd * sd(delta_bg, na.rm = TRUE)),
  109. NG = if_else(L == 0 & !is.na(L), 1, 0),
  110. DB = if_else(delta_bg >= delta_bg_tolerance, 1, 0),
  111. SM = 0,
  112. OrfRep = if_else(ORF == "YDL227C", "YDL227C", OrfRep), # should these be hardcoded?
  113. conc_num = as.numeric(gsub("[^0-9\\.]", "", Conc)),
  114. conc_num_factor = as.factor(conc_num)
  115. # conc_num_factor = factor(conc_num, levels = sort(unique(conc_num)))
  116. # conc_num_numeric = as.numeric(conc_num_factor) - 1
  117. )
  118. return(df)
  119. }
  120. # Update Gene names using the SGD gene list
  121. update_gene_names <- function(df, sgd_gene_list) {
  122. # Load SGD gene list
  123. genes <- read.delim(file = sgd_gene_list,
  124. quote = "", header = FALSE,
  125. colClasses = c(rep("NULL", 3), rep("character", 2), rep("NULL", 11)))
  126. # Create a named vector for mapping ORF to GeneName
  127. gene_map <- setNames(genes$V5, genes$V4)
  128. # Vectorized match to find the GeneName from gene_map
  129. mapped_genes <- gene_map[df$ORF]
  130. # Replace NAs in mapped_genes with original Gene names (preserves existing Gene names if ORF is not found)
  131. updated_genes <- ifelse(is.na(mapped_genes) | df$OrfRep == "YDL227C", df$Gene, mapped_genes)
  132. # Ensure Gene is not left blank or incorrectly updated to "OCT1"
  133. df <- df %>%
  134. mutate(Gene = ifelse(updated_genes == "" | updated_genes == "OCT1", OrfRep, updated_genes))
  135. return(df)
  136. }
  137. calculate_summary_stats <- function(df, variables, group_vars = c("OrfRep", "conc_num", "conc_num_factor")) {
  138. # Summarize the variables within the grouped data
  139. summary_stats <- df %>%
  140. group_by(across(all_of(group_vars))) %>%
  141. summarise(
  142. N = sum(!is.na(L)),
  143. across(all_of(variables), list(
  144. mean = ~mean(., na.rm = TRUE),
  145. median = ~median(., na.rm = TRUE),
  146. max = ~ifelse(all(is.na(.)), NA, max(., na.rm = TRUE)),
  147. min = ~ifelse(all(is.na(.)), NA, min(., na.rm = TRUE)),
  148. sd = ~sd(., na.rm = TRUE),
  149. se = ~ifelse(all(is.na(.)), NA, sd(., na.rm = TRUE) / sqrt(sum(!is.na(.)) - 1))
  150. ), .names = "{.fn}_{.col}")
  151. )
  152. # Create a cleaned version of df that doesn't overlap with summary_stats
  153. cols_to_exclude <- unique(c(variables, group_vars))
  154. df_cleaned <- df %>%
  155. select(-any_of(cols_to_exclude))
  156. # Join the stats back to the original dataframe
  157. df_with_stats <- left_join(df_cleaned, summary_stats, by = group_vars)
  158. return(list(summary_stats = summary_stats, df_with_stats = df_with_stats))
  159. }
  160. calculate_interaction_scores <- function(df, max_conc, variables, group_vars = c("OrfRep", "Gene", "num")) {
  161. # Calculate total concentration variables
  162. total_conc_num <- length(unique(df$conc_num))
  163. # Pull the background means and standard deviations from zero concentration
  164. bg_means <- list(
  165. L = df %>% filter(conc_num_factor == 0) %>% pull(mean_L) %>% first(),
  166. K = df %>% filter(conc_num_factor == 0) %>% pull(mean_K) %>% first(),
  167. r = df %>% filter(conc_num_factor == 0) %>% pull(mean_r) %>% first(),
  168. AUC = df %>% filter(conc_num_factor == 0) %>% pull(mean_AUC) %>% first()
  169. )
  170. bg_sd <- list(
  171. L = df %>% filter(conc_num_factor == 0) %>% pull(sd_L) %>% first(),
  172. K = df %>% filter(conc_num_factor == 0) %>% pull(sd_K) %>% first(),
  173. r = df %>% filter(conc_num_factor == 0) %>% pull(sd_r) %>% first(),
  174. AUC = df %>% filter(conc_num_factor == 0) %>% pull(sd_AUC) %>% first()
  175. )
  176. stats <- calculate_summary_stats(df, variables,
  177. group_vars = c("OrfRep", "Gene", "num", "conc_num", "conc_num_factor"))$summary_stats
  178. stats <- df %>%
  179. group_by(OrfRep, Gene, num) %>%
  180. mutate(
  181. WT_L = mean_L,
  182. WT_K = mean_K,
  183. WT_r = mean_r,
  184. WT_AUC = mean_AUC,
  185. WT_sd_L = sd_L,
  186. WT_sd_K = sd_K,
  187. WT_sd_r = sd_r,
  188. WT_sd_AUC = sd_AUC
  189. )
  190. stats <- stats %>%
  191. mutate(
  192. Raw_Shift_L = first(mean_L) - bg_means$L,
  193. Raw_Shift_K = first(mean_K) - bg_means$K,
  194. Raw_Shift_r = first(mean_r) - bg_means$r,
  195. Raw_Shift_AUC = first(mean_AUC) - bg_means$AUC,
  196. Z_Shift_L = first(Raw_Shift_L) / bg_sd$L,
  197. Z_Shift_K = first(Raw_Shift_K) / bg_sd$K,
  198. Z_Shift_r = first(Raw_Shift_r) / bg_sd$r,
  199. Z_Shift_AUC = first(Raw_Shift_AUC) / bg_sd$AUC
  200. )
  201. stats <- stats %>%
  202. mutate(
  203. Exp_L = WT_L + Raw_Shift_L,
  204. Exp_K = WT_K + Raw_Shift_K,
  205. Exp_r = WT_r + Raw_Shift_r,
  206. Exp_AUC = WT_AUC + Raw_Shift_AUC,
  207. Delta_L = mean_L - Exp_L,
  208. Delta_K = mean_K - Exp_K,
  209. Delta_r = mean_r - Exp_r,
  210. Delta_AUC = mean_AUC - Exp_AUC
  211. )
  212. stats <- stats %>%
  213. mutate(
  214. Delta_L = if_else(NG == 1, mean_L - WT_L, Delta_L),
  215. Delta_K = if_else(NG == 1, mean_K - WT_K, Delta_K),
  216. Delta_r = if_else(NG == 1, mean_r - WT_r, Delta_r),
  217. Delta_AUC = if_else(NG == 1, mean_AUC - WT_AUC, Delta_AUC),
  218. Delta_L = if_else(SM == 1, mean_L - WT_L, Delta_L)
  219. )
  220. stats <- stats %>%
  221. mutate(
  222. Zscore_L = Delta_L / WT_sd_L,
  223. Zscore_K = Delta_K / WT_sd_K,
  224. Zscore_r = Delta_r / WT_sd_r,
  225. Zscore_AUC = Delta_AUC / WT_sd_AUC
  226. )
  227. # Calculate linear models
  228. lm_L <- lm(Delta_L ~ conc_num_factor, data = stats)
  229. lm_K <- lm(Delta_K ~ conc_num_factor, data = stats)
  230. lm_r <- lm(Delta_r ~ conc_num_factor, data = stats)
  231. lm_AUC <- lm(Delta_AUC ~ conc_num_factor, data = stats)
  232. interactions <- stats %>%
  233. group_by(OrfRep, Gene, num) %>%
  234. summarise(
  235. OrfRep = first(OrfRep),
  236. Gene = first(Gene),
  237. num = first(num),
  238. conc_num = first(conc_num),
  239. conc_num_factor = first(conc_num_factor),
  240. Raw_Shift_L = first(Raw_Shift_L),
  241. Raw_Shift_K = first(Raw_Shift_K),
  242. Raw_Shift_r = first(Raw_Shift_r),
  243. Raw_Shift_AUC = first(Raw_Shift_AUC),
  244. Z_Shift_L = first(Z_Shift_L),
  245. Z_Shift_K = first(Z_Shift_K),
  246. Z_Shift_r = first(Z_Shift_r),
  247. Z_Shift_AUC = first(Z_Shift_AUC),
  248. Sum_Zscore_L = sum(Zscore_L, na.rm = TRUE),
  249. Sum_Zscore_K = sum(Zscore_K, na.rm = TRUE),
  250. Sum_Zscore_r = sum(Zscore_r, na.rm = TRUE),
  251. Sum_Zscore_AUC = sum(Zscore_AUC, na.rm = TRUE),
  252. lm_Score_L = max_conc * coef(lm_L)[2] + coef(lm_L)[1],
  253. lm_Score_K = max_conc * coef(lm_K)[2] + coef(lm_K)[1],
  254. lm_Score_r = max_conc * coef(lm_r)[2] + coef(lm_r)[1],
  255. lm_Score_AUC = max_conc * coef(lm_AUC)[2] + coef(lm_AUC)[1],
  256. R_Squared_L = summary(lm_L)$r.squared,
  257. R_Squared_K = summary(lm_K)$r.squared,
  258. R_Squared_r = summary(lm_r)$r.squared,
  259. R_Squared_AUC = summary(lm_AUC)$r.squared,
  260. lm_intercept_L = coef(lm_L)[1],
  261. lm_slope_L = coef(lm_L)[2],
  262. lm_intercept_K = coef(lm_K)[1],
  263. lm_slope_K = coef(lm_K)[2],
  264. lm_intercept_r = coef(lm_r)[1],
  265. lm_slope_r = coef(lm_r)[2],
  266. lm_intercept_AUC = coef(lm_AUC)[1],
  267. lm_slope_AUC = coef(lm_AUC)[2],
  268. NG = sum(NG, na.rm = TRUE),
  269. DB = sum(DB, na.rm = TRUE),
  270. SM = sum(SM, na.rm = TRUE)
  271. )
  272. num_non_removed_concs <- total_conc_num - sum(stats$DB, na.rm = TRUE) - 1
  273. interactions <- interactions %>%
  274. mutate(
  275. Avg_Zscore_L = Sum_Zscore_L / num_non_removed_concs,
  276. Avg_Zscore_K = Sum_Zscore_K / num_non_removed_concs,
  277. Avg_Zscore_r = Sum_Zscore_r / (total_conc_num - 1),
  278. Avg_Zscore_AUC = Sum_Zscore_AUC / (total_conc_num - 1),
  279. Z_lm_L = (lm_Score_L - mean(lm_Score_L, na.rm = TRUE)) / sd(lm_Score_L, na.rm = TRUE),
  280. Z_lm_K = (lm_Score_K - mean(lm_Score_K, na.rm = TRUE)) / sd(lm_Score_K, na.rm = TRUE),
  281. Z_lm_r = (lm_Score_r - mean(lm_Score_r, na.rm = TRUE)) / sd(lm_Score_r, na.rm = TRUE),
  282. Z_lm_AUC = (lm_Score_AUC - mean(lm_Score_AUC, na.rm = TRUE)) / sd(lm_Score_AUC, na.rm = TRUE)
  283. ) %>%
  284. arrange(desc(Z_lm_L), desc(NG))
  285. # Declare column order for output
  286. calculations <- stats %>%
  287. select(
  288. "OrfRep", "Gene", "conc_num", "conc_num_factor", "N",
  289. "mean_L", "mean_K", "mean_r", "mean_AUC",
  290. "median_L", "median_K", "median_r", "median_AUC",
  291. "sd_L", "sd_K", "sd_r", "sd_AUC",
  292. "se_L", "se_K", "se_r", "se_AUC",
  293. "Raw_Shift_L", "Raw_Shift_K", "Raw_Shift_r", "Raw_Shift_AUC",
  294. "Z_Shift_L", "Z_Shift_K", "Z_Shift_r", "Z_Shift_AUC",
  295. "WT_L", "WT_K", "WT_r", "WT_AUC",
  296. "WT_sd_L", "WT_sd_K", "WT_sd_r", "WT_sd_AUC",
  297. "Exp_L", "Exp_K", "Exp_r", "Exp_AUC",
  298. "Delta_L", "Delta_K", "Delta_r", "Delta_AUC",
  299. "Zscore_L", "Zscore_K", "Zscore_r", "Zscore_AUC",
  300. "NG", "SM", "DB")
  301. calculations_joined <- df %>% select(-any_of(setdiff(names(calculations), c("OrfRep", "Gene", "num", "conc_num", "conc_num_factor"))))
  302. calculations_joined <- left_join(calculations_joined, calculations, by = c("OrfRep", "Gene", "num", "conc_num", "conc_num_factor"))
  303. interactions_joined <- df %>% select(-any_of(setdiff(names(interactions), c("OrfRep", "Gene", "num", "conc_num", "conc_num_factor"))))
  304. interactions_joined <- left_join(interactions_joined, interactions, by = c("OrfRep", "Gene", "num", "conc_num", "conc_num_factor"))
  305. return(list(calculations = calculations, interactions = interactions, interactions_joined = interactions_joined,
  306. calculations_joined = calculations_joined))
  307. }
  308. generate_and_save_plots <- function(output_dir, file_name, plot_configs, grid_layout = NULL) {
  309. message("Generating ", file_name, ".pdf and ", file_name, ".html")
  310. # Prepare lists to collect plots
  311. static_plots <- list()
  312. plotly_plots <- list()
  313. for (i in seq_along(plot_configs)) {
  314. config <- plot_configs[[i]]
  315. df <- config$df
  316. # Build the aes_mapping based on config
  317. aes_mapping <- if (is.null(config$color_var)) {
  318. if (is.null(config$y_var)) {
  319. aes(x = .data[[config$x_var]])
  320. } else {
  321. aes(x = .data[[config$x_var]], y = .data[[config$y_var]])
  322. }
  323. } else {
  324. if (is.null(config$y_var)) {
  325. aes(x = .data[[config$x_var]], color = as.factor(.data[[config$color_var]]))
  326. } else {
  327. aes(x = .data[[config$x_var]], y = .data[[config$y_var]], color = as.factor(.data[[config$color_var]]))
  328. }
  329. }
  330. # Start building the plot with aes_mapping
  331. plot_base <- ggplot(df, aes_mapping)
  332. # Use appropriate helper function based on plot type
  333. plot <- switch(config$plot_type,
  334. "scatter" = generate_scatter_plot(plot_base, config),
  335. "box" = generate_box_plot(plot_base, config),
  336. "density" = plot_base + geom_density(),
  337. "bar" = plot_base + geom_bar(),
  338. plot_base # default case if no type matches
  339. )
  340. # Apply additional settings if provided
  341. if (!is.null(config$legend_position)) {
  342. plot <- plot + theme(legend.position = config$legend_position)
  343. }
  344. # Add title and labels if provided
  345. if (!is.null(config$title)) {
  346. plot <- plot + ggtitle(config$title)
  347. }
  348. if (!is.null(config$x_label)) {
  349. plot <- plot + xlab(config$x_label)
  350. }
  351. if (!is.null(config$y_label)) {
  352. plot <- plot + ylab(config$y_label)
  353. }
  354. # Add interactive tooltips for plotly plots
  355. tooltip_vars <- c("x", "y") # default tooltip variables
  356. if (!is.null(config$tooltip_vars)) {
  357. tooltip_vars <- config$tooltip_vars
  358. } else {
  359. # Include default variables based on config
  360. if (!is.null(config$delta_bg_point) && config$delta_bg_point) {
  361. tooltip_vars <- c(tooltip_vars, "OrfRep", "Gene", "delta_bg")
  362. } else if (!is.null(config$gene_point) && config$gene_point) {
  363. tooltip_vars <- c(tooltip_vars, "OrfRep", "Gene")
  364. } else {
  365. # Include x and y variables by default
  366. tooltip_vars <- c("x", "y")
  367. }
  368. }
  369. # Convert to plotly object
  370. plotly_plot <- ggplotly(plot, tooltip = tooltip_vars)
  371. if (!is.null(config$legend_position) && config$legend_position == "bottom") {
  372. plotly_plot <- plotly_plot %>% layout(legend = list(orientation = "h"))
  373. }
  374. # Add plots to lists
  375. static_plots[[i]] <- plot
  376. plotly_plots[[i]] <- plotly_plot
  377. }
  378. # Save static PDF plots
  379. pdf(file.path(output_dir, paste0(file_name, ".pdf")), width = 14, height = 9)
  380. lapply(static_plots, print)
  381. dev.off()
  382. # Combine and save interactive HTML plots
  383. combined_plot <- subplot(plotly_plots, nrows = grid_layout$nrow %||% length(plotly_plots), margin = 0.05)
  384. saveWidget(combined_plot, file = file.path(output_dir, paste0(file_name, ".html")), selfcontained = TRUE)
  385. }
  386. generate_scatter_plot <- function(plot, config) {
  387. # 1. Determine Shape, Size, and Position for geom_point
  388. shape <- if (!is.null(config$shape)) config$shape else 3
  389. size <- if (!is.null(config$size)) {
  390. config$size
  391. } else {
  392. if (!is.null(config$delta_bg_point) && config$delta_bg_point) 0.2
  393. else if (!is.null(config$gene_point) && config$gene_point) 0.2
  394. else 0.1
  395. }
  396. position <- if (!is.null(config$delta_bg_point) && config$delta_bg_point) {
  397. "identity"
  398. } else if (!is.null(config$gene_point) && config$gene_point) {
  399. "jitter"
  400. } else {
  401. if (!is.null(config$position) && config$position == "jitter") "jitter" else "identity"
  402. }
  403. # 2. Add geom_point with determined parameters
  404. plot <- plot + geom_point(shape = shape, size = size, position = position)
  405. # 3. Add Smooth Line if specified
  406. if (!is.null(config$add_smooth) && config$add_smooth) {
  407. if (!is.null(config$lm_line)) {
  408. plot <- plot +
  409. geom_abline(
  410. intercept = config$lm_line$intercept,
  411. slope = config$lm_line$slope,
  412. color = "blue"
  413. )
  414. } else {
  415. plot <- plot +
  416. geom_smooth(
  417. method = "lm",
  418. se = FALSE,
  419. color = "blue"
  420. )
  421. }
  422. }
  423. # 4. Add SD Bands if specified
  424. if (!is.null(config$sd_band_values)) {
  425. for (sd_band in config$sd_band_values) {
  426. plot <- plot +
  427. annotate(
  428. "rect",
  429. xmin = -Inf, xmax = Inf,
  430. ymin = sd_band, ymax = Inf,
  431. fill = "#542788",
  432. alpha = 0.3
  433. ) +
  434. annotate(
  435. "rect",
  436. xmin = -Inf, xmax = Inf,
  437. ymin = -sd_band, ymax = -Inf,
  438. fill = "orange",
  439. alpha = 0.3
  440. ) +
  441. geom_hline(
  442. yintercept = c(-sd_band, sd_band),
  443. color = "gray"
  444. )
  445. }
  446. }
  447. # 5. Add Error Bars if specified
  448. if (!is.null(config$error_bar) && config$error_bar && !is.null(config$y_var)) {
  449. y_mean_col <- paste0("mean_", config$y_var)
  450. y_sd_col <- paste0("sd_", config$y_var)
  451. plot <- plot +
  452. geom_errorbar(
  453. aes(
  454. ymin = !!sym(y_mean_col) - !!sym(y_sd_col),
  455. ymax = !!sym(y_mean_col) + !!sym(y_sd_col)
  456. ),
  457. alpha = 0.3
  458. )
  459. }
  460. # 6. Customize X-axis if specified
  461. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  462. plot <- plot +
  463. scale_x_discrete(
  464. name = config$x_label,
  465. breaks = config$x_breaks,
  466. labels = config$x_labels
  467. )
  468. }
  469. # 7. Apply coord_cartesian if specified
  470. if (!is.null(config$coord_cartesian)) {
  471. plot <- plot + coord_cartesian(ylim = config$coord_cartesian)
  472. }
  473. # 8. Set Y-axis limits if specified
  474. if (!is.null(config$ylim_vals)) {
  475. plot <- plot + scale_y_continuous(limits = config$ylim_vals)
  476. }
  477. # 9. Add Annotations if specified
  478. if (!is.null(config$annotations)) {
  479. for (annotation in config$annotations) {
  480. plot <- plot +
  481. annotate(
  482. "text",
  483. x = annotation$x,
  484. y = annotation$y,
  485. label = annotation$label,
  486. na.rm = TRUE
  487. )
  488. }
  489. }
  490. # 10. Add Title if specified
  491. if (!is.null(config$title)) {
  492. plot <- plot + ggtitle(config$title)
  493. }
  494. # 11. Adjust Legend Position if specified
  495. if (!is.null(config$legend_position)) {
  496. plot <- plot + theme(legend.position = config$legend_position)
  497. }
  498. return(plot)
  499. }
  500. generate_box_plot <- function(plot, config) {
  501. plot <- plot + geom_boxplot()
  502. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  503. plot <- plot + scale_x_discrete(
  504. name = config$x_label,
  505. breaks = config$x_breaks,
  506. labels = config$x_labels
  507. )
  508. }
  509. if (!is.null(config$coord_cartesian)) {
  510. plot <- plot + coord_cartesian(ylim = config$coord_cartesian)
  511. }
  512. return(plot)
  513. }
  514. generate_interaction_plot_configs <- function(df, variables) {
  515. configs <- list()
  516. limits_map <- list(
  517. L = c(-65, 65),
  518. K = c(-65, 65),
  519. r = c(-0.65, 0.65),
  520. AUC = c(-6500, 6500)
  521. )
  522. df_filtered <- filter_data(df, variables, missing = TRUE, limits_map = limits_map)
  523. # Define annotation label functions
  524. generate_annotation_labels <- function(df, var, annotation_name) {
  525. switch(annotation_name,
  526. ZShift = paste("ZShift =", round(df[[paste0("Z_Shift_", var)]], 2)),
  527. lm_ZScore = paste("lm ZScore =", round(df[[paste0("Z_lm_", var)]], 2)),
  528. NG = paste("NG =", df$NG),
  529. DB = paste("DB =", df$DB),
  530. SM = paste("SM =", df$SM),
  531. NULL # Default case for unrecognized annotation names
  532. )
  533. }
  534. # Define annotation positions relative to the y-axis range
  535. calculate_annotation_positions <- function(y_range) {
  536. y_min <- min(y_range)
  537. y_max <- max(y_range)
  538. y_span <- y_max - y_min
  539. list(
  540. ZShift = y_max - 0.1 * y_span,
  541. lm_ZScore = y_max - 0.2 * y_span,
  542. NG = y_min + 0.2 * y_span,
  543. DB = y_min + 0.1 * y_span,
  544. SM = y_min + 0.05 * y_span
  545. )
  546. }
  547. # Create configurations for each variable
  548. for (variable in variables) {
  549. y_range <- limits_map[[variable]]
  550. annotation_positions <- calculate_annotation_positions(y_range)
  551. lm_line <- list(
  552. intercept = df_filtered[[paste0("lm_intercept_", variable)]],
  553. slope = df_filtered[[paste0("lm_slope_", variable)]]
  554. )
  555. # Determine x-axis midpoint
  556. num_levels <- length(levels(df_filtered$conc_num_factor))
  557. x_pos <- (1 + num_levels) / 2 # Midpoint of x-axis
  558. # Generate annotations
  559. annotations <- lapply(names(annotation_positions), function(annotation_name) {
  560. label <- generate_annotation_labels(df_filtered, variable, annotation_name)
  561. y_pos <- annotation_positions[[annotation_name]]
  562. if (!is.null(label)) {
  563. list(x = x_pos, y = y_pos, label = label)
  564. } else {
  565. message(paste("Warning: No annotation found for", annotation_name))
  566. NULL
  567. }
  568. })
  569. # Remove NULL annotations
  570. annotations <- Filter(Negate(is.null), annotations)
  571. # Shared plot settings
  572. plot_settings <- list(
  573. df = df_filtered,
  574. x_var = "conc_num_factor",
  575. y_var = variable,
  576. ylim_vals = y_range,
  577. annotations = annotations,
  578. lm_line = lm_line,
  579. x_breaks = levels(df_filtered$conc_num_factor),
  580. x_labels = levels(df_filtered$conc_num_factor),
  581. x_label = unique(df_filtered$Drug[1]),
  582. coord_cartesian = y_range # Use the actual y-limits
  583. )
  584. # Scatter plot config
  585. configs[[length(configs) + 1]] <- modifyList(plot_settings, list(
  586. plot_type = "scatter",
  587. title = sprintf("%s %s", df_filtered$OrfRep[1], df_filtered$Gene[1]),
  588. error_bar = TRUE,
  589. position = "jitter"
  590. ))
  591. # Box plot config
  592. configs[[length(configs) + 1]] <- modifyList(plot_settings, list(
  593. plot_type = "box",
  594. title = sprintf("%s %s (Boxplot)", df_filtered$OrfRep[1], df_filtered$Gene[1]),
  595. error_bar = FALSE
  596. ))
  597. }
  598. return(configs)
  599. }
  600. generate_rank_plot_configs <- function(df_filtered, is_lm = FALSE, adjust = FALSE) {
  601. # Define SD bands
  602. sd_bands <- c(1, 2, 3)
  603. # Define variables for Avg ZScore and Rank Avg ZScore plots
  604. variables <- c("r", "L", "K", "AUC")
  605. # Initialize list to store plot configurations
  606. configs <- list()
  607. # SD-based plots for L and K
  608. for (variable in c("L", "K")) {
  609. for (sd_band in sd_bands) {
  610. # Determine columns based on whether it's lm or not
  611. if (is_lm) {
  612. rank_var <- paste0(variable, "_Rank_lm")
  613. zscore_var <- paste0("Z_lm_", variable)
  614. y_label <- paste("Int Z score", variable)
  615. } else {
  616. rank_var <- paste0(variable, "_Rank")
  617. zscore_var <- paste0("Avg_Zscore_", variable)
  618. y_label <- paste("Avg Z score", variable)
  619. }
  620. # Annotated Plot Configuration
  621. configs[[length(configs) + 1]] <- list(
  622. df = df_filtered,
  623. x_var = rank_var,
  624. y_var = zscore_var,
  625. plot_type = "scatter",
  626. title = paste(y_label, "vs. Rank for", variable, "above", sd_band, "SD"),
  627. sd_band = sd_band,
  628. annotations = list(
  629. list(
  630. x = median(df_filtered[[rank_var]], na.rm = TRUE),
  631. y = 10,
  632. label = paste("Deletion Enhancers =", sum(df_filtered[[zscore_var]] >= sd_band, na.rm = TRUE))
  633. ),
  634. list(
  635. x = median(df_filtered[[rank_var]], na.rm = TRUE),
  636. y = -10,
  637. label = paste("Deletion Suppressors =", sum(df_filtered[[zscore_var]] <= -sd_band, na.rm = TRUE))
  638. )
  639. ),
  640. sd_band_values = sd_band,
  641. shape = 3,
  642. size = 0.1
  643. )
  644. # Non-Annotated Plot Configuration
  645. configs[[length(configs) + 1]] <- list(
  646. df = df_filtered,
  647. x_var = rank_var,
  648. y_var = zscore_var,
  649. plot_type = "scatter",
  650. title = paste(y_label, "vs. Rank for", variable, "above", sd_band, "SD No Annotations"),
  651. sd_band = sd_band,
  652. annotations = NULL,
  653. sd_band_values = sd_band,
  654. shape = 3,
  655. size = 0.1
  656. )
  657. }
  658. }
  659. # Avg ZScore and Rank Avg ZScore Plots for r, L, K, and AUC
  660. for (variable in variables) {
  661. for (plot_type in c("Avg_Zscore_vs_lm", "Rank_Avg_Zscore_vs_lm")) {
  662. # Define x and y variables based on plot type
  663. if (plot_type == "Avg_Zscore_vs_lm") {
  664. x_var <- paste0("Avg_Zscore_", variable)
  665. y_var <- paste0("Z_lm_", variable)
  666. title_suffix <- paste("Avg Zscore vs lm", variable)
  667. } else if (plot_type == "Rank_Avg_Zscore_vs_lm") {
  668. x_var <- paste0(variable, "_Rank")
  669. y_var <- paste0(variable, "_Rank_lm")
  670. title_suffix <- paste("Rank Avg Zscore vs lm", variable)
  671. }
  672. # Determine y-axis label
  673. if (plot_type == "Avg_Zscore_vs_lm") {
  674. y_label <- paste("Z lm", variable)
  675. } else {
  676. y_label <- paste("Rank lm", variable)
  677. }
  678. # Determine correlation text (R-squared)
  679. lm_fit <- lm(df_filtered[[y_var]] ~ df_filtered[[x_var]], data = df_filtered)
  680. r_squared <- summary(lm_fit)$r.squared
  681. # Plot Configuration
  682. configs[[length(configs) + 1]] <- list(
  683. df = df_filtered,
  684. x_var = x_var,
  685. y_var = y_var,
  686. plot_type = "scatter",
  687. title = title_suffix,
  688. annotations = list(
  689. list(
  690. x = 0,
  691. y = 0,
  692. label = paste("R-squared =", round(r_squared, 2))
  693. )
  694. ),
  695. sd_band_values = NULL, # Not applicable
  696. shape = 3,
  697. size = 0.1,
  698. add_smooth = TRUE,
  699. lm_line = list(intercept = coef(lm_fit)[1], slope = coef(lm_fit)[2]),
  700. legend_position = "right"
  701. )
  702. }
  703. }
  704. return(configs)
  705. }
  706. generate_correlation_plot_configs <- function(df) {
  707. # Define relationships for plotting
  708. relationships <- list(
  709. list(x = "Z_lm_L", y = "Z_lm_K", label = "Interaction L vs. Interaction K"),
  710. list(x = "Z_lm_L", y = "Z_lm_r", label = "Interaction L vs. Interaction r"),
  711. list(x = "Z_lm_L", y = "Z_lm_AUC", label = "Interaction L vs. Interaction AUC"),
  712. list(x = "Z_lm_K", y = "Z_lm_r", label = "Interaction K vs. Interaction r"),
  713. list(x = "Z_lm_K", y = "Z_lm_AUC", label = "Interaction K vs. Interaction AUC"),
  714. list(x = "Z_lm_r", y = "Z_lm_AUC", label = "Interaction r vs. Interaction AUC")
  715. )
  716. configs <- list()
  717. for (rel in relationships) {
  718. # Fit linear model
  719. lm_model <- lm(as.formula(paste(rel$y, "~", rel$x)), data = df)
  720. lm_summary <- summary(lm_model)
  721. # Construct plot configuration
  722. config <- list(
  723. df = df,
  724. x_var = rel$x,
  725. y_var = rel$y,
  726. plot_type = "scatter",
  727. title = rel$label,
  728. x_label = paste("z-score", gsub("Z_lm_", "", rel$x)),
  729. y_label = paste("z-score", gsub("Z_lm_", "", rel$y)),
  730. annotations = list(
  731. list(x = 0, y = 0, label = paste("R-squared =", round(lm_summary$r.squared, 3)))
  732. ),
  733. add_smooth = TRUE, # This flags that a geom_smooth layer should be added
  734. lm_line = list(intercept = coef(lm_model)[1], slope = coef(lm_model)[2]), # For direct geom_abline if needed
  735. legend_position = "right"
  736. )
  737. configs[[length(configs) + 1]] <- config
  738. }
  739. return(configs)
  740. }
  741. filter_data <- function(df, variables, nf = FALSE, missing = FALSE, adjust = FALSE,
  742. rank = FALSE, limits_map = NULL, verbose = TRUE) {
  743. # Precompute Column Names for Efficiency
  744. avg_zscore_cols <- paste0("Avg_Zscore_", variables)
  745. z_lm_cols <- paste0("Z_lm_", variables)
  746. # Adjust NAs if 'adjust' is TRUE
  747. if (adjust) {
  748. if (verbose) message("Replacing NA with 0.001 for Avg_Zscore_ and Z_lm_ columns.")
  749. df <- df %>%
  750. mutate(
  751. across(all_of(avg_zscore_cols), ~ replace_na(., 0.001)),
  752. across(all_of(z_lm_cols), ~ replace_na(., 0.001))
  753. )
  754. }
  755. # Filter Non-Finite Values if 'nf' is TRUE
  756. if (nf) {
  757. if (verbose) message("Filtering non-finite values for variables: ", paste(variables, collapse = ", "))
  758. # Identify non-finite rows for logging
  759. non_finite_df <- df %>%
  760. filter(if_any(all_of(variables), ~ !is.finite(.)))
  761. if (verbose && nrow(non_finite_df) > 0) {
  762. message("Non-finite rows for variables ", paste(variables, collapse = ", "), ":")
  763. print(non_finite_df)
  764. }
  765. # Keep only rows where all specified variables are finite
  766. df <- df %>%
  767. filter(if_all(all_of(variables), ~ is.finite(.)))
  768. }
  769. # Filter Missing Values if 'missing' is TRUE
  770. if (missing) {
  771. if (verbose) message("Filtering missing values for variables: ", paste(variables, collapse = ", "))
  772. # Identify missing rows for logging
  773. missing_df <- df %>%
  774. filter(if_any(all_of(variables), ~ is.na(.)))
  775. if (verbose && nrow(missing_df) > 0) {
  776. message("Missing data for variables ", paste(variables, collapse = ", "), ":")
  777. print(missing_df)
  778. }
  779. # Keep only rows where all specified variables are not missing
  780. df <- df %>%
  781. filter(if_all(all_of(variables), ~ !is.na(.)))
  782. }
  783. # Apply Limits from 'limits_map' if Provided
  784. if (!is.null(limits_map)) {
  785. for (variable in names(limits_map)) {
  786. if (variable %in% variables) {
  787. ylim_vals <- limits_map[[variable]]
  788. if (verbose) message("Applying limits for variable ", variable, ": [", ylim_vals[1], ", ", ylim_vals[2], "].")
  789. # Identify out-of-range data for logging
  790. out_of_range_df <- df %>%
  791. filter(.data[[variable]] < ylim_vals[1] | .data[[variable]] > ylim_vals[2])
  792. if (verbose && nrow(out_of_range_df) > 0) {
  793. message("Out-of-range data for variable ", variable, ":")
  794. print(out_of_range_df)
  795. }
  796. # Keep only rows within the specified limits
  797. df <- df %>%
  798. filter(.data[[variable]] >= ylim_vals[1] & .data[[variable]] <= ylim_vals[2])
  799. }
  800. }
  801. }
  802. # Calculate Rank Columns if 'rank' is TRUE
  803. if (rank) {
  804. if (verbose) message("Calculating rank columns for variables: ", paste(variables, collapse = ", "))
  805. # Create Rank and Rank_lm columns using mutate and across
  806. df <- df %>%
  807. mutate(
  808. # Rank based on Avg_Zscore_
  809. across(all_of(avg_zscore_cols), ~ rank(., na.last = "keep"), .names = "Rank_Avg_Zscore_{.col}"),
  810. # Rank_lm based on Z_lm_
  811. across(all_of(z_lm_cols), ~ rank(., na.last = "keep"), .names = "Rank_lm_Z_lm_{.col}")
  812. )
  813. # Prepare a named vector for renaming columns: new_name = old_name
  814. rename_vector <- c(
  815. setNames(paste0("Rank_", variables), paste0("Rank_Avg_Zscore_", avg_zscore_cols)),
  816. setNames(paste0("Rank_lm_", variables), paste0("Rank_lm_Z_lm_", z_lm_cols))
  817. )
  818. # Rename the rank columns in a single step
  819. df <- df %>%
  820. rename(!!!rename_vector)
  821. }
  822. return(df)
  823. }
  824. main <- function() {
  825. lapply(names(args$experiments), function(exp_name) {
  826. exp <- args$experiments[[exp_name]]
  827. exp_path <- exp$path
  828. exp_sd <- exp$sd
  829. out_dir <- file.path(exp_path, "zscores")
  830. out_dir_qc <- file.path(exp_path, "zscores", "qc")
  831. dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
  832. dir.create(out_dir_qc, recursive = TRUE, showWarnings = FALSE)
  833. summary_vars <- c("L", "K", "r", "AUC", "delta_bg") # fields to filter and calculate summary stats across
  834. group_vars <- c("OrfRep", "conc_num", "conc_num_factor") # default fields to group by
  835. orf_group_vars <- c("OrfRep", "Gene", "num")
  836. print_vars <- c("OrfRep", "Plate", "scan", "Col", "Row", "num", "OrfRep", "conc_num", "conc_num_factor",
  837. "delta_bg_tolerance", "delta_bg", "Gene", "L", "K", "r", "AUC", "NG", "DB")
  838. message("Loading and filtering data for experiment: ", exp_name)
  839. df <- load_and_process_data(args$easy_results_file, sd = exp_sd) %>%
  840. update_gene_names(args$sgd_gene_list) %>%
  841. as_tibble()
  842. # Filter rows above delta background tolerance
  843. df_above_tolerance <- df %>% filter(DB == 1)
  844. df_na <- df %>% mutate(across(all_of(summary_vars), ~ ifelse(DB == 1, NA, .)))
  845. df_no_zeros <- df_na %>% filter(L > 0)
  846. # Save some constants
  847. max_conc <- max(df$conc_num)
  848. l_half_median <- (median(df_above_tolerance$L, na.rm = TRUE)) / 2
  849. k_half_median <- (median(df_above_tolerance$K, na.rm = TRUE)) / 2
  850. message("Calculating summary statistics before quality control")
  851. ss <- calculate_summary_stats(df, summary_vars, group_vars = group_vars)
  852. df_stats <- ss$df_with_stats
  853. message("Filtering non-finite data")
  854. df_filtered_stats <- filter_data(df_stats, c("L"), nf = TRUE)
  855. message("Calculating summary statistics after quality control")
  856. ss <- calculate_summary_stats(df_na, summary_vars, group_vars = group_vars)
  857. df_na_ss <- ss$summary_stats
  858. df_na_stats <- ss$df_with_stats
  859. write.csv(df_na_ss, file = file.path(out_dir, "summary_stats_all_strains.csv"), row.names = FALSE)
  860. df_na_filtered_stats <- filter_data(df_na_stats, c("L"), nf = TRUE)
  861. message("Calculating summary statistics after quality control excluding zero values")
  862. ss <- calculate_summary_stats(df_no_zeros, summary_vars, group_vars = group_vars)
  863. df_no_zeros_stats <- ss$df_with_stats
  864. df_no_zeros_filtered_stats <- filter_data(df_no_zeros_stats, c("L"), nf = TRUE)
  865. message("Filtering by 2SD of K")
  866. df_na_within_2sd_k <- df_na_stats %>%
  867. filter(K >= (mean_K - 2 * sd_K) & K <= (mean_K + 2 * sd_K))
  868. df_na_outside_2sd_k <- df_na_stats %>%
  869. filter(K < (mean_K - 2 * sd_K) | K > (mean_K + 2 * sd_K))
  870. message("Calculating summary statistics for L within 2SD of K")
  871. # TODO We're omitting the original z_max calculation, not sure if needed?
  872. ss <- calculate_summary_stats(df_na_within_2sd_k, "L", group_vars = c("conc_num", "conc_num_factor"))
  873. # df_na_l_within_2sd_k_stats <- ss$df_with_stats
  874. write.csv(ss$summary_stats, file = file.path(out_dir_qc, "max_observed_L_vals_for_spots_within_2sd_K.csv"), row.names = FALSE)
  875. message("Calculating summary statistics for L outside 2SD of K")
  876. ss <- calculate_summary_stats(df_na_outside_2sd_k, "L", group_vars = c("conc_num", "conc_num_factor"))
  877. df_na_l_outside_2sd_k_stats <- ss$df_with_stats
  878. write.csv(ss$summary_stats, file = file.path(out_dir, "max_observed_L_vals_for_spots_outside_2sd_K.csv"), row.names = FALSE)
  879. # Each plots list corresponds to a file
  880. l_vs_k_plots <- list(
  881. list(
  882. df = df,
  883. x_var = "L",
  884. y_var = "K",
  885. plot_type = "scatter",
  886. delta_bg_point = TRUE,
  887. title = "Raw L vs K before quality control",
  888. color_var = "conc_num_factor",
  889. error_bar = FALSE,
  890. legend_position = "right"
  891. )
  892. )
  893. frequency_delta_bg_plots <- list(
  894. list(
  895. df = df_filtered_stats,
  896. x_var = "delta_bg",
  897. y_var = NULL,
  898. plot_type = "density",
  899. title = "Plate analysis by Drug Conc for Delta Background before quality control",
  900. color_var = "conc_num_factor",
  901. x_label = "Delta Background",
  902. y_label = "Density",
  903. error_bar = FALSE,
  904. legend_position = "right"),
  905. list(
  906. df = df_filtered_stats,
  907. x_var = "delta_bg",
  908. y_var = NULL,
  909. plot_type = "bar",
  910. title = "Plate analysis by Drug Conc for Delta Background before quality control",
  911. color_var = "conc_num_factor",
  912. x_label = "Delta Background",
  913. y_label = "Count",
  914. error_bar = FALSE,
  915. legend_position = "right")
  916. )
  917. above_threshold_plots <- list(
  918. list(
  919. df = df_above_tolerance,
  920. x_var = "L",
  921. y_var = "K",
  922. plot_type = "scatter",
  923. delta_bg_point = TRUE,
  924. title = paste("Raw L vs K for strains above Delta Background threshold of",
  925. df_above_tolerance$delta_bg_tolerance[[1]], "or above"),
  926. color_var = "conc_num_factor",
  927. position = "jitter",
  928. annotations = list(
  929. list(
  930. x = l_half_median,
  931. y = k_half_median,
  932. label = paste("# strains above Delta Background tolerance =", nrow(df_above_tolerance))
  933. )
  934. ),
  935. error_bar = FALSE,
  936. legend_position = "right"
  937. )
  938. )
  939. plate_analysis_plots <- list()
  940. for (var in summary_vars) {
  941. for (stage in c("before", "after")) {
  942. if (stage == "before") {
  943. df_plot <- df_filtered_stats
  944. } else {
  945. df_plot <- df_na_filtered_stats
  946. }
  947. config <- list(
  948. df = df_plot,
  949. x_var = "scan",
  950. y_var = var,
  951. plot_type = "scatter",
  952. title = paste("Plate analysis by Drug Conc for", var, stage, "quality control"),
  953. error_bar = TRUE,
  954. color_var = "conc_num_factor",
  955. position = "jitter")
  956. plate_analysis_plots <- append(plate_analysis_plots, list(config))
  957. }
  958. }
  959. plate_analysis_boxplots <- list()
  960. for (var in summary_vars) {
  961. for (stage in c("before", "after")) {
  962. if (stage == "before") {
  963. df_plot <- df_filtered_stats
  964. } else {
  965. df_plot <- df_na_filtered_stats
  966. }
  967. config <- list(
  968. df = df_plot,
  969. x_var = "scan",
  970. y_var = var,
  971. plot_type = "box",
  972. title = paste("Plate analysis by Drug Conc for", var, stage, "quality control"),
  973. error_bar = FALSE,
  974. color_var = "conc_num_factor")
  975. plate_analysis_boxplots <- append(plate_analysis_boxplots, list(config))
  976. }
  977. }
  978. plate_analysis_no_zeros_plots <- list()
  979. for (var in summary_vars) {
  980. config <- list(
  981. df = df_no_zeros_filtered_stats,
  982. x_var = "scan",
  983. y_var = var,
  984. plot_type = "scatter",
  985. title = paste("Plate analysis by Drug Conc for", var, "after quality control"),
  986. error_bar = TRUE,
  987. color_var = "conc_num_factor",
  988. position = "jitter")
  989. plate_analysis_no_zeros_plots <- append(plate_analysis_no_zeros_plots, list(config))
  990. }
  991. plate_analysis_no_zeros_boxplots <- list()
  992. for (var in summary_vars) {
  993. config <- list(
  994. df = df_no_zeros_filtered_stats,
  995. x_var = "scan",
  996. y_var = var,
  997. plot_type = "box",
  998. title = paste("Plate analysis by Drug Conc for", var, "after quality control"),
  999. error_bar = FALSE,
  1000. color_var = "conc_num_factor"
  1001. )
  1002. plate_analysis_no_zeros_boxplots <- append(plate_analysis_no_zeros_boxplots, list(config))
  1003. }
  1004. l_outside_2sd_k_plots <- list(
  1005. list(
  1006. df = df_na_l_outside_2sd_k_stats,
  1007. x_var = "L",
  1008. y_var = "K",
  1009. plot_type = "scatter",
  1010. delta_bg_point = TRUE,
  1011. title = "Raw L vs K for strains falling outside 2SD of the K mean at each Conc",
  1012. color_var = "conc_num_factor",
  1013. position = "jitter",
  1014. legend_position = "right"
  1015. )
  1016. )
  1017. delta_bg_outside_2sd_k_plots <- list(
  1018. list(
  1019. df = df_na_l_outside_2sd_k_stats,
  1020. x_var = "delta_bg",
  1021. y_var = "K",
  1022. plot_type = "scatter",
  1023. gene_point = TRUE,
  1024. title = "Delta Background vs K for strains falling outside 2SD of the K mean at each Conc",
  1025. color_var = "conc_num_factor",
  1026. position = "jitter",
  1027. legend_position = "right"
  1028. )
  1029. )
  1030. message("Generating quality control plots")
  1031. generate_and_save_plots(out_dir_qc, "L_vs_K_before_quality_control", l_vs_k_plots)
  1032. generate_and_save_plots(out_dir_qc, "frequency_delta_background", frequency_delta_bg_plots)
  1033. generate_and_save_plots(out_dir_qc, "L_vs_K_above_threshold", above_threshold_plots)
  1034. generate_and_save_plots(out_dir_qc, "plate_analysis", plate_analysis_plots)
  1035. generate_and_save_plots(out_dir_qc, "plate_analysis_boxplots", plate_analysis_boxplots)
  1036. generate_and_save_plots(out_dir_qc, "plate_analysis_no_zeros", plate_analysis_no_zeros_plots)
  1037. generate_and_save_plots(out_dir_qc, "plate_analysis_no_zeros_boxplots", plate_analysis_no_zeros_boxplots)
  1038. generate_and_save_plots(out_dir_qc, "L_vs_K_for_strains_2SD_outside_mean_K", l_outside_2sd_k_plots)
  1039. generate_and_save_plots(out_dir_qc, "delta_background_vs_K_for_strains_2sd_outside_mean_K", delta_bg_outside_2sd_k_plots)
  1040. # TODO: Originally this filtered L NA's
  1041. # Let's try to avoid for now since stats have already been calculated
  1042. # Process background strains
  1043. bg_strains <- c("YDL227C")
  1044. lapply(bg_strains, function(strain) {
  1045. message("Processing background strain: ", strain)
  1046. # Handle missing data by setting zero values to NA
  1047. # and then removing any rows with NA in L col
  1048. df_bg <- df_na %>%
  1049. filter(OrfRep == strain) %>%
  1050. mutate(
  1051. L = if_else(L == 0, NA, L),
  1052. K = if_else(K == 0, NA, K),
  1053. r = if_else(r == 0, NA, r),
  1054. AUC = if_else(AUC == 0, NA, AUC)
  1055. ) %>%
  1056. filter(!is.na(L))
  1057. # Recalculate summary statistics for the background strain
  1058. message("Calculating summary statistics for background strain")
  1059. ss_bg <- calculate_summary_stats(df_bg, summary_vars, group_vars = group_vars)
  1060. summary_stats_bg <- ss_bg$summary_stats
  1061. # df_bg_stats <- ss_bg$df_with_stats
  1062. write.csv(summary_stats_bg,
  1063. file = file.path(out_dir, paste0("SummaryStats_BackgroundStrains_", strain, ".csv")),
  1064. row.names = FALSE)
  1065. # Filter reference and deletion strains
  1066. # Formerly X2_RF (reference strains)
  1067. df_reference <- df_na_stats %>%
  1068. filter(OrfRep == strain) %>%
  1069. mutate(SM = 0)
  1070. # Formerly X2 (deletion strains)
  1071. df_deletion <- df_na_stats %>%
  1072. filter(OrfRep != strain) %>%
  1073. mutate(SM = 0)
  1074. # Set the missing values to the highest theoretical value at each drug conc for L
  1075. # Leave other values as 0 for the max/min
  1076. reference_strain <- df_reference %>%
  1077. group_by(conc_num) %>%
  1078. mutate(
  1079. max_l_theoretical = max(max_L, na.rm = TRUE),
  1080. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1081. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, SM),
  1082. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1083. ungroup()
  1084. # Ditto for deletion strains
  1085. deletion_strains <- df_deletion %>%
  1086. group_by(conc_num) %>%
  1087. mutate(
  1088. max_l_theoretical = max(max_L, na.rm = TRUE),
  1089. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1090. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, SM),
  1091. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1092. ungroup()
  1093. message("Calculating interaction scores")
  1094. interaction_vars <- c("L", "K", "r", "AUC")
  1095. message("Calculating reference strain(s)")
  1096. reference_results <- calculate_interaction_scores(reference_strain, max_conc, interaction_vars, group_vars = orf_group_vars)
  1097. zscores_calculations_reference <- reference_results$calculations
  1098. zscores_interactions_reference <- reference_results$interactions
  1099. zscores_calculations_reference_joined <- reference_results$calculations_joined
  1100. zscores_interactions_reference_joined <- reference_results$interactions_joined
  1101. message("Calculating deletion strain(s)")
  1102. deletion_results <- calculate_interaction_scores(deletion_strains, max_conc, interaction_vars, group_vars = orf_group_vars)
  1103. zscores_calculations <- deletion_results$calculations
  1104. zscores_interactions <- deletion_results$interactions
  1105. zscores_calculations_joined <- deletion_results$calculations_joined
  1106. zscores_interactions_joined <- deletion_results$interactions_joined
  1107. # Writing Z-Scores to file
  1108. write.csv(zscores_calculations_reference, file = file.path(out_dir, "RF_ZScores_Calculations.csv"), row.names = FALSE)
  1109. write.csv(zscores_calculations, file = file.path(out_dir, "ZScores_Calculations.csv"), row.names = FALSE)
  1110. write.csv(zscores_interactions_reference, file = file.path(out_dir, "RF_ZScores_Interaction.csv"), row.names = FALSE)
  1111. write.csv(zscores_interactions, file = file.path(out_dir, "ZScores_Interaction.csv"), row.names = FALSE)
  1112. # Create interaction plots
  1113. message("Generating reference interaction plots")
  1114. reference_plot_configs <- generate_interaction_plot_configs(zscores_interactions_reference_joined, interaction_vars)
  1115. generate_and_save_plots(out_dir, "RF_interactionPlots", reference_plot_configs, grid_layout = list(ncol = 4, nrow = 3))
  1116. message("Generating deletion interaction plots")
  1117. deletion_plot_configs <- generate_interaction_plot_configs(zscores_interactions_joined, interaction_vars)
  1118. generate_and_save_plots(out_dir, "InteractionPlots", deletion_plot_configs, grid_layout = list(ncol = 4, nrow = 3))
  1119. # Define conditions for enhancers and suppressors
  1120. # TODO Add to study config file?
  1121. threshold <- 2
  1122. enhancer_condition_L <- zscores_interactions$Avg_Zscore_L >= threshold
  1123. suppressor_condition_L <- zscores_interactions$Avg_Zscore_L <= -threshold
  1124. enhancer_condition_K <- zscores_interactions$Avg_Zscore_K >= threshold
  1125. suppressor_condition_K <- zscores_interactions$Avg_Zscore_K <= -threshold
  1126. # Subset data
  1127. enhancers_L <- zscores_interactions[enhancer_condition_L, ]
  1128. suppressors_L <- zscores_interactions[suppressor_condition_L, ]
  1129. enhancers_K <- zscores_interactions[enhancer_condition_K, ]
  1130. suppressors_K <- zscores_interactions[suppressor_condition_K, ]
  1131. # Save enhancers and suppressors
  1132. message("Writing enhancer/suppressor csv files")
  1133. write.csv(enhancers_L, file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_L.csv"), row.names = FALSE)
  1134. write.csv(suppressors_L, file = file.path(out_dir, "ZScores_Interaction_Deletion_Suppressors_L.csv"), row.names = FALSE)
  1135. write.csv(enhancers_K, file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_K.csv"), row.names = FALSE)
  1136. write.csv(suppressors_K, file = file.path(out_dir, "ZScores_Interaction_Deletion_Suppressors_K.csv"), row.names = FALSE)
  1137. # Combine conditions for enhancers and suppressors
  1138. enhancers_and_suppressors_L <- zscores_interactions[enhancer_condition_L | suppressor_condition_L, ]
  1139. enhancers_and_suppressors_K <- zscores_interactions[enhancer_condition_K | suppressor_condition_K, ]
  1140. # Save combined enhancers and suppressors
  1141. write.csv(enhancers_and_suppressors_L,
  1142. file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_and_Suppressors_L.csv"), row.names = FALSE)
  1143. write.csv(enhancers_and_suppressors_K,
  1144. file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_and_Suppressors_K.csv"), row.names = FALSE)
  1145. # Handle linear model based enhancers and suppressors
  1146. lm_threshold <- 2
  1147. enhancers_lm_L <- zscores_interactions[zscores_interactions$Z_lm_L >= lm_threshold, ]
  1148. suppressors_lm_L <- zscores_interactions[zscores_interactions$Z_lm_L <= -lm_threshold, ]
  1149. enhancers_lm_K <- zscores_interactions[zscores_interactions$Z_lm_K >= lm_threshold, ]
  1150. suppressors_lm_K <- zscores_interactions[zscores_interactions$Z_lm_K <= -lm_threshold, ]
  1151. # Save linear model based enhancers and suppressors
  1152. message("Writing linear model enhancer/suppressor csv files")
  1153. write.csv(enhancers_lm_L,
  1154. file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_L_lm.csv"), row.names = FALSE)
  1155. write.csv(suppressors_lm_L,
  1156. file = file.path(out_dir, "ZScores_Interaction_Deletion_Suppressors_L_lm.csv"), row.names = FALSE)
  1157. write.csv(enhancers_lm_K,
  1158. file = file.path(out_dir, "ZScores_Interaction_Deletion_Enhancers_K_lm.csv"), row.names = FALSE)
  1159. write.csv(suppressors_lm_K,
  1160. file = file.path(out_dir, "ZScores_Interaction_Deletion_Suppressors_K_lm.csv"), row.names = FALSE)
  1161. message("Generating rank plots")
  1162. zscores_interactions_joined_filtered <- filter_data(
  1163. zscores_interactions_joined,
  1164. variables,
  1165. missing = TRUE,
  1166. adjust = TRUE,
  1167. rank = TRUE)
  1168. rank_plot_configs <- generate_rank_plot_configs(
  1169. df = zscores_interactions_joined_filtered,
  1170. is_lm = FALSE,
  1171. adjust = TRUE
  1172. )
  1173. generate_and_save_plots(output_dir = out_dir, file_name = "RankPlots",
  1174. plot_configs = rank_plot_configs, grid_layout = list(ncol = 3, nrow = 2))
  1175. message("Generating ranked linear model plots")
  1176. rank_lm_plot_configs <- generate_rank_plot_configs(
  1177. df = zscores_interactions_joined_filtered,
  1178. is_lm = TRUE,
  1179. adjust = TRUE
  1180. )
  1181. generate_and_save_plots(output_dir = out_dir, file_name = "RankPlots_lm",
  1182. plot_configs = rank_lm_plot_configs, grid_layout = list(ncol = 3, nrow = 2))
  1183. message("Filtering and reranking plots")
  1184. # Formerly X_NArm
  1185. zscores_interactions_filtered <- zscores_interactions_joined %>%
  1186. group_by(across(all_of(orf_group_vars))) %>%
  1187. filter(!is.na(Z_lm_L) | !is.na(Avg_Zscore_L)) %>%
  1188. ungroup() %>%
  1189. rowwise() %>%
  1190. mutate(
  1191. lm_R_squared_L = if (n() > 1) summary(lm(Z_lm_L ~ Avg_Zscore_L))$r.squared else NA,
  1192. lm_R_squared_K = if (n() > 1) summary(lm(Z_lm_K ~ Avg_Zscore_K))$r.squared else NA,
  1193. lm_R_squared_r = if (n() > 1) summary(lm(Z_lm_r ~ Avg_Zscore_r))$r.squared else NA,
  1194. lm_R_squared_AUC = if (n() > 1) summary(lm(Z_lm_AUC ~ Avg_Zscore_AUC))$r.squared else NA,
  1195. Overlap = case_when(
  1196. Z_lm_L >= 2 & Avg_Zscore_L >= 2 ~ "Deletion Enhancer Both",
  1197. Z_lm_L <= -2 & Avg_Zscore_L <= -2 ~ "Deletion Suppressor Both",
  1198. Z_lm_L >= 2 & Avg_Zscore_L <= 2 ~ "Deletion Enhancer lm only",
  1199. Z_lm_L <= -2 & Avg_Zscore_L >= -2 ~ "Deletion Suppressor lm only",
  1200. Z_lm_L >= 2 & Avg_Zscore_L <= -2 ~ "Deletion Enhancer lm, Deletion Suppressor Avg Z score",
  1201. Z_lm_L <= -2 & Avg_Zscore_L >= 2 ~ "Deletion Suppressor lm, Deletion Enhancer Avg Z score",
  1202. TRUE ~ "No Effect"
  1203. )
  1204. ) %>%
  1205. ungroup()
  1206. # Re-rank
  1207. zscores_interactions_filtered <- filter_data(
  1208. df = zscores_interactions_filtered,
  1209. variables = interaction_vars,
  1210. missing = TRUE, # TODO what I'm currently having issues with
  1211. rank = TRUE
  1212. )
  1213. rank_plot_filtered_configs <- generate_rank_plot_configs(
  1214. df = zscores_interactions_filtered,
  1215. is_lm = FALSE,
  1216. adjust = FALSE
  1217. )
  1218. message("Generating filtered ranked plots")
  1219. generate_and_save_plots(
  1220. output_dir = out_dir,
  1221. file_name = "RankPlots_na_rm",
  1222. plot_configs = rank_plot_filtered_configs,
  1223. grid_layout = list(ncol = 3, nrow = 2))
  1224. message("Generating filtered ranked linear model plots")
  1225. rank_plot_lm_filtered_configs <- generate_rank_plot_configs(
  1226. df = zscores_interactions_filtered,
  1227. is_lm = TRUE,
  1228. adjust = FALSE
  1229. )
  1230. generate_and_save_plots(
  1231. output_dir = out_dir,
  1232. file_name = "RankPlots_lm_na_rm",
  1233. plot_configs = rank_plot_lm_filtered_configs,
  1234. grid_layout = list(ncol = 3, nrow = 2))
  1235. message("Generating correlation plots")
  1236. correlation_plot_configs <- generate_correlation_plot_configs(zscores_interactions_filtered)
  1237. generate_and_save_plots(
  1238. output_dir = out_dir,
  1239. file_name = "Avg_Zscore_vs_lm_NA_rm",
  1240. plot_configs = correlation_plot_configs,
  1241. grid_layout = list(ncol = 2, nrow = 2))
  1242. })
  1243. })
  1244. }
  1245. main()