calculate_interaction_zscores.R 53 KB

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