calculate_interaction_zscores.R 54 KB

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