calculate_interaction_zscores.R 51 KB

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