calculate_interaction_zscores.R 52 KB

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