calculate_interaction_zscores.R 53 KB

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