calculate_interaction_zscores.R 53 KB

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