calculate_interaction_zscores.R 52 KB

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