calculate_interaction_zscores.R 55 KB

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