calculate_interaction_zscores.R 54 KB

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