calculate_interaction_zscores.R 54 KB

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