calculate_interaction_zscores.R 53 KB

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