calculate_interaction_zscores.R 53 KB

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