calculate_interaction_zscores.R 52 KB

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