calculate_interaction_zscores.R 52 KB

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