calculate_interaction_zscores.R 54 KB

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