calculate_interaction_zscores.R 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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. return(df)
  144. }
  145. update_gene_names <- function(df, sgd_gene_list) {
  146. genes <- read.delim(file = sgd_gene_list, quote = "", header = FALSE,
  147. colClasses = c(rep("NULL", 3), rep("character", 2), rep("NULL", 11)))
  148. gene_map <- setNames(genes$V5, genes$V4) # ORF to GeneName mapping
  149. df <- df %>%
  150. mutate(
  151. mapped_genes = gene_map[ORF],
  152. Gene = if_else(is.na(mapped_genes) | OrfRep == "YDL227C", Gene, mapped_genes),
  153. Gene = if_else(Gene == "" | Gene == "OCT1", OrfRep, Gene) # Handle invalid names
  154. )
  155. return(df)
  156. }
  157. calculate_summary_stats <- function(df, variables, group_vars) {
  158. summary_stats <- df %>%
  159. group_by(across(all_of(group_vars))) %>%
  160. summarise(
  161. N = n(),
  162. across(all_of(variables),
  163. list(
  164. mean = ~ mean(.x, na.rm = TRUE),
  165. median = ~ median(.x, na.rm = TRUE),
  166. max = ~ ifelse(all(is.na(.x)), NA, max(.x, na.rm = TRUE)),
  167. min = ~ ifelse(all(is.na(.x)), NA, min(.x, na.rm = TRUE)),
  168. sd = ~ sd(.x, na.rm = TRUE),
  169. se = ~ sd(.x, na.rm = TRUE) / sqrt(n() - 1)
  170. ),
  171. .names = "{.fn}_{.col}"
  172. ),
  173. .groups = "drop"
  174. )
  175. # Create a cleaned version of df that doesn't overlap with summary_stats
  176. df_cleaned <- df %>%
  177. select(-any_of(setdiff(intersect(names(df), names(summary_stats)), group_vars)))
  178. df_joined <- left_join(df_cleaned, summary_stats, by = group_vars)
  179. return(list(summary_stats = summary_stats, df_with_stats = df_joined))
  180. }
  181. calculate_interaction_scores <- function(df, df_bg, group_vars, overlap_threshold = 2) {
  182. max_conc <- max(as.numeric(df$conc_num_factor), na.rm = TRUE)
  183. total_conc_num <- length(unique(df$conc_num))
  184. # Calculate WT statistics from df_bg
  185. wt_stats <- df_bg %>%
  186. filter(conc_num == 0) %>%
  187. summarise(
  188. WT_L = mean(mean_L, na.rm = TRUE),
  189. WT_sd_L = mean(sd_L, na.rm = TRUE),
  190. WT_K = mean(mean_K, na.rm = TRUE),
  191. WT_sd_K = mean(sd_K, na.rm = TRUE),
  192. WT_r = mean(mean_r, na.rm = TRUE),
  193. WT_sd_r = mean(sd_r, na.rm = TRUE),
  194. WT_AUC = mean(mean_AUC, na.rm = TRUE),
  195. WT_sd_AUC = mean(sd_AUC, na.rm = TRUE)
  196. )
  197. # Add WT statistics to df
  198. df <- df %>%
  199. mutate(
  200. WT_L = wt_stats$WT_L,
  201. WT_sd_L = wt_stats$WT_sd_L,
  202. WT_K = wt_stats$WT_K,
  203. WT_sd_K = wt_stats$WT_sd_K,
  204. WT_r = wt_stats$WT_r,
  205. WT_sd_r = wt_stats$WT_sd_r,
  206. WT_AUC = wt_stats$WT_AUC,
  207. WT_sd_AUC = wt_stats$WT_sd_AUC
  208. )
  209. # Compute mean values at zero concentration
  210. mean_L_zero_df <- df %>%
  211. filter(conc_num == 0) %>%
  212. group_by(across(all_of(group_vars))) %>%
  213. summarise(
  214. mean_L_zero = mean(mean_L, na.rm = TRUE),
  215. mean_K_zero = mean(mean_K, na.rm = TRUE),
  216. mean_r_zero = mean(mean_r, na.rm = TRUE),
  217. mean_AUC_zero = mean(mean_AUC, na.rm = TRUE),
  218. .groups = "drop"
  219. )
  220. # Join mean_L_zero_df to df
  221. df <- df %>%
  222. left_join(mean_L_zero_df, by = group_vars)
  223. # Calculate Raw Shifts and Z Shifts
  224. df <- df %>%
  225. mutate(
  226. Raw_Shift_L = mean_L_zero - WT_L,
  227. Raw_Shift_K = mean_K_zero - WT_K,
  228. Raw_Shift_r = mean_r_zero - WT_r,
  229. Raw_Shift_AUC = mean_AUC_zero - WT_AUC,
  230. Z_Shift_L = Raw_Shift_L / WT_sd_L,
  231. Z_Shift_K = Raw_Shift_K / WT_sd_K,
  232. Z_Shift_r = Raw_Shift_r / WT_sd_r,
  233. Z_Shift_AUC = Raw_Shift_AUC / WT_sd_AUC
  234. )
  235. calculations <- df %>%
  236. group_by(across(all_of(group_vars))) %>%
  237. mutate(
  238. NG_sum = sum(NG, na.rm = TRUE),
  239. DB_sum = sum(DB, na.rm = TRUE),
  240. SM_sum = sum(SM, na.rm = TRUE),
  241. num_non_removed_concs = total_conc_num - sum(DB, na.rm = TRUE) - 1,
  242. # Expected values
  243. Exp_L = WT_L + Raw_Shift_L,
  244. Exp_K = WT_K + Raw_Shift_K,
  245. Exp_r = WT_r + Raw_Shift_r,
  246. Exp_AUC = WT_AUC + Raw_Shift_AUC,
  247. # Deltas
  248. Delta_L = mean_L - Exp_L,
  249. Delta_K = mean_K - Exp_K,
  250. Delta_r = mean_r - Exp_r,
  251. Delta_AUC = mean_AUC - Exp_AUC,
  252. # Adjust deltas for NG and SM
  253. Delta_L = if_else(NG == 1, mean_L - WT_L, Delta_L),
  254. Delta_K = if_else(NG == 1, mean_K - WT_K, Delta_K),
  255. Delta_r = if_else(NG == 1, mean_r - WT_r, Delta_r),
  256. Delta_AUC = if_else(NG == 1, mean_AUC - WT_AUC, Delta_AUC),
  257. Delta_L = if_else(SM == 1, mean_L - WT_L, Delta_L),
  258. # Calculate Z-scores
  259. Zscore_L = Delta_L / WT_sd_L,
  260. Zscore_K = Delta_K / WT_sd_K,
  261. Zscore_r = Delta_r / WT_sd_r,
  262. Zscore_AUC = Delta_AUC / WT_sd_AUC
  263. ) %>%
  264. group_modify(~ {
  265. # Perform linear models only if there are enough unique conc_num_factor levels
  266. if (length(unique(.x$conc_num_factor)) > 1) {
  267. # Filter and calculate each lm() separately with individual checks for NAs
  268. lm_L <- if (!all(is.na(.x$Delta_L))) tryCatch(lm(Delta_L ~ conc_num_factor, data = .x), error = function(e) NULL) else NULL
  269. lm_K <- if (!all(is.na(.x$Delta_K))) tryCatch(lm(Delta_K ~ conc_num_factor, data = .x), error = function(e) NULL) else NULL
  270. lm_r <- if (!all(is.na(.x$Delta_r))) tryCatch(lm(Delta_r ~ conc_num_factor, data = .x), error = function(e) NULL) else NULL
  271. lm_AUC <- if (!all(is.na(.x$Delta_AUC))) tryCatch(lm(Delta_AUC ~ conc_num_factor, data = .x), error = function(e) NULL) else NULL
  272. # Mutate results for each lm if it was successfully calculated, suppress warnings for perfect fits
  273. .x %>%
  274. mutate(
  275. lm_intercept_L = if (!is.null(lm_L)) coef(lm_L)[1] else NA,
  276. lm_slope_L = if (!is.null(lm_L)) coef(lm_L)[2] else NA,
  277. R_Squared_L = if (!is.null(lm_L)) suppressWarnings(summary(lm_L)$r.squared) else NA,
  278. lm_Score_L = if (!is.null(lm_L)) max_conc * coef(lm_L)[2] + coef(lm_L)[1] else NA,
  279. lm_intercept_K = if (!is.null(lm_K)) coef(lm_K)[1] else NA,
  280. lm_slope_K = if (!is.null(lm_K)) coef(lm_K)[2] else NA,
  281. R_Squared_K = if (!is.null(lm_K)) suppressWarnings(summary(lm_K)$r.squared) else NA,
  282. lm_Score_K = if (!is.null(lm_K)) max_conc * coef(lm_K)[2] + coef(lm_K)[1] else NA,
  283. lm_intercept_r = if (!is.null(lm_r)) coef(lm_r)[1] else NA,
  284. lm_slope_r = if (!is.null(lm_r)) coef(lm_r)[2] else NA,
  285. R_Squared_r = if (!is.null(lm_r)) suppressWarnings(summary(lm_r)$r.squared) else NA,
  286. lm_Score_r = if (!is.null(lm_r)) max_conc * coef(lm_r)[2] + coef(lm_r)[1] else NA,
  287. lm_intercept_AUC = if (!is.null(lm_AUC)) coef(lm_AUC)[1] else NA,
  288. lm_slope_AUC = if (!is.null(lm_AUC)) coef(lm_AUC)[2] else NA,
  289. R_Squared_AUC = if (!is.null(lm_AUC)) suppressWarnings(summary(lm_AUC)$r.squared) else NA,
  290. lm_Score_AUC = if (!is.null(lm_AUC)) max_conc * coef(lm_AUC)[2] + coef(lm_AUC)[1] else NA
  291. )
  292. } else {
  293. # If not enough conc_num_factor levels, set lm-related values to NA
  294. .x %>%
  295. mutate(
  296. lm_intercept_L = NA, lm_slope_L = NA, R_Squared_L = NA, lm_Score_L = NA,
  297. lm_intercept_K = NA, lm_slope_K = NA, R_Squared_K = NA, lm_Score_K = NA,
  298. lm_intercept_r = NA, lm_slope_r = NA, R_Squared_r = NA, lm_Score_r = NA,
  299. lm_intercept_AUC = NA, lm_slope_AUC = NA, R_Squared_AUC = NA, lm_Score_AUC = NA
  300. )
  301. }
  302. }) %>%
  303. ungroup()
  304. # Summary statistics for lm scores
  305. lm_means_sds <- calculations %>%
  306. summarise(
  307. lm_mean_L = mean(lm_Score_L, na.rm = TRUE),
  308. lm_sd_L = sd(lm_Score_L, na.rm = TRUE),
  309. lm_mean_K = mean(lm_Score_K, na.rm = TRUE),
  310. lm_sd_K = sd(lm_Score_K, na.rm = TRUE),
  311. lm_mean_r = mean(lm_Score_r, na.rm = TRUE),
  312. lm_sd_r = sd(lm_Score_r, na.rm = TRUE),
  313. lm_mean_AUC = mean(lm_Score_AUC, na.rm = TRUE),
  314. lm_sd_AUC = sd(lm_Score_AUC, na.rm = TRUE),
  315. .groups = "drop"
  316. )
  317. # Add lm score means and standard deviations to calculations
  318. calculations <- calculations %>%
  319. mutate(
  320. lm_mean_L = lm_means_sds$lm_mean_L,
  321. lm_sd_L = lm_means_sds$lm_sd_L,
  322. lm_mean_K = lm_means_sds$lm_mean_K,
  323. lm_sd_K = lm_means_sds$lm_sd_K,
  324. lm_mean_r = lm_means_sds$lm_mean_r,
  325. lm_sd_r = lm_means_sds$lm_sd_r,
  326. lm_mean_AUC = lm_means_sds$lm_mean_AUC,
  327. lm_sd_AUC = lm_means_sds$lm_sd_AUC
  328. )
  329. # Calculate Z-lm scores
  330. calculations <- calculations %>%
  331. mutate(
  332. Z_lm_L = (lm_Score_L - lm_mean_L) / lm_sd_L,
  333. Z_lm_K = (lm_Score_K - lm_mean_K) / lm_sd_K,
  334. Z_lm_r = (lm_Score_r - lm_mean_r) / lm_sd_r,
  335. Z_lm_AUC = (lm_Score_AUC - lm_mean_AUC) / lm_sd_AUC
  336. )
  337. # Build summary stats (interactions)
  338. interactions <- calculations %>%
  339. group_by(across(all_of(group_vars))) %>%
  340. summarise(
  341. Avg_Zscore_L = sum(Zscore_L, na.rm = TRUE) / first(num_non_removed_concs),
  342. Avg_Zscore_K = sum(Zscore_K, na.rm = TRUE) / first(num_non_removed_concs),
  343. Avg_Zscore_r = sum(Zscore_r, na.rm = TRUE) / (total_conc_num - 1),
  344. Avg_Zscore_AUC = sum(Zscore_AUC, na.rm = TRUE) / (total_conc_num - 1),
  345. # Interaction Z-scores
  346. Z_lm_L = first(Z_lm_L),
  347. Z_lm_K = first(Z_lm_K),
  348. Z_lm_r = first(Z_lm_r),
  349. Z_lm_AUC = first(Z_lm_AUC),
  350. # Raw Shifts
  351. Raw_Shift_L = first(Raw_Shift_L),
  352. Raw_Shift_K = first(Raw_Shift_K),
  353. Raw_Shift_r = first(Raw_Shift_r),
  354. Raw_Shift_AUC = first(Raw_Shift_AUC),
  355. # Z Shifts
  356. Z_Shift_L = first(Z_Shift_L),
  357. Z_Shift_K = first(Z_Shift_K),
  358. Z_Shift_r = first(Z_Shift_r),
  359. Z_Shift_AUC = first(Z_Shift_AUC),
  360. # R Squared values
  361. R_Squared_L = first(R_Squared_L),
  362. R_Squared_K = first(R_Squared_K),
  363. R_Squared_r = first(R_Squared_r),
  364. R_Squared_AUC = first(R_Squared_AUC),
  365. # NG, DB, SM values
  366. NG = first(NG),
  367. DB = first(DB),
  368. SM = first(SM),
  369. .groups = "drop"
  370. )
  371. # Add overlap threshold categories based on Z-lm and Avg-Z scores
  372. interactions <- interactions %>%
  373. filter(!is.na(Z_lm_L)) %>%
  374. mutate(
  375. Overlap = case_when(
  376. Z_lm_L >= overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Enhancer Both",
  377. Z_lm_L <= -overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Suppressor Both",
  378. Z_lm_L >= overlap_threshold & Avg_Zscore_L <= overlap_threshold ~ "Deletion Enhancer lm only",
  379. Z_lm_L <= overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Enhancer Avg Zscore only",
  380. Z_lm_L <= -overlap_threshold & Avg_Zscore_L >= -overlap_threshold ~ "Deletion Suppressor lm only",
  381. Z_lm_L >= -overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Suppressor Avg Zscore only",
  382. Z_lm_L >= overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Enhancer lm, Deletion Suppressor Avg Zscore",
  383. Z_lm_L <= -overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Suppressor lm, Deletion Enhancer Avg Zscore",
  384. TRUE ~ "No Effect"
  385. ),
  386. # For correlations
  387. lm_R_squared_L = if (!all(is.na(Z_lm_L)) && !all(is.na(Avg_Zscore_L))) summary(lm(Z_lm_L ~ Avg_Zscore_L))$r.squared else NA,
  388. lm_R_squared_K = if (!all(is.na(Z_lm_K)) && !all(is.na(Avg_Zscore_K))) summary(lm(Z_lm_K ~ Avg_Zscore_K))$r.squared else NA,
  389. lm_R_squared_r = if (!all(is.na(Z_lm_r)) && !all(is.na(Avg_Zscore_r))) summary(lm(Z_lm_r ~ Avg_Zscore_r))$r.squared else NA,
  390. lm_R_squared_AUC = if (!all(is.na(Z_lm_AUC)) && !all(is.na(Avg_Zscore_AUC))) summary(lm(Z_lm_AUC ~ Avg_Zscore_AUC))$r.squared else NA
  391. )
  392. # Creating the final calculations and interactions dataframes with only required columns for csv output
  393. calculations_df <- calculations %>%
  394. select(
  395. all_of(group_vars),
  396. conc_num, conc_num_factor, conc_num_factor_factor, N,
  397. mean_L, median_L, sd_L, se_L,
  398. mean_K, median_K, sd_K, se_K,
  399. mean_r, median_r, sd_r, se_r,
  400. mean_AUC, median_AUC, sd_AUC, se_AUC,
  401. Raw_Shift_L, Raw_Shift_K, Raw_Shift_r, Raw_Shift_AUC,
  402. Z_Shift_L, Z_Shift_K, Z_Shift_r, Z_Shift_AUC,
  403. WT_L, WT_K, WT_r, WT_AUC,
  404. WT_sd_L, WT_sd_K, WT_sd_r, WT_sd_AUC,
  405. Exp_L, Exp_K, Exp_r, Exp_AUC,
  406. Delta_L, Delta_K, Delta_r, Delta_AUC,
  407. Zscore_L, Zscore_K, Zscore_r, Zscore_AUC
  408. )
  409. interactions_df <- interactions %>%
  410. select(
  411. all_of(group_vars),
  412. NG, DB, SM,
  413. Avg_Zscore_L, Avg_Zscore_K, Avg_Zscore_r, Avg_Zscore_AUC,
  414. Z_lm_L, Z_lm_K, Z_lm_r, Z_lm_AUC,
  415. Raw_Shift_L, Raw_Shift_K, Raw_Shift_r, Raw_Shift_AUC,
  416. Z_Shift_L, Z_Shift_K, Z_Shift_r, Z_Shift_AUC,
  417. lm_R_squared_L, lm_R_squared_K, lm_R_squared_r, lm_R_squared_AUC,
  418. Overlap
  419. )
  420. # Join calculations and interactions to avoid dimension mismatch
  421. calculations_no_overlap <- calculations %>%
  422. select(-any_of(c("DB", "NG", "SM",
  423. "Raw_Shift_L", "Raw_Shift_K", "Raw_Shift_r", "Raw_Shift_AUC",
  424. "Z_Shift_L", "Z_Shift_K", "Z_Shift_r", "Z_Shift_AUC",
  425. "Z_lm_L", "Z_lm_K", "Z_lm_r", "Z_lm_AUC")))
  426. full_data <- calculations_no_overlap %>%
  427. left_join(interactions_df, by = group_vars)
  428. # Return final dataframes
  429. return(list(
  430. calculations = calculations_df,
  431. interactions = interactions_df,
  432. full_data = full_data
  433. ))
  434. }
  435. generate_and_save_plots <- function(out_dir, filename, plot_configs) {
  436. message("Generating ", filename, ".pdf and ", filename, ".html")
  437. # Check if we're dealing with multiple plot groups
  438. plot_groups <- if ("plots" %in% names(plot_configs)) {
  439. list(plot_configs) # Single group
  440. } else {
  441. plot_configs # Multiple groups
  442. }
  443. # Open the PDF device once for all plots
  444. pdf(file.path(out_dir, paste0(filename, ".pdf")), width = 16, height = 9)
  445. # Loop through each plot group
  446. for (group in plot_groups) {
  447. static_plots <- list()
  448. plotly_plots <- list()
  449. # Retrieve grid layout if it exists, otherwise skip
  450. grid_layout <- group$grid_layout
  451. plots <- group$plots
  452. # Only handle grid layout if it exists
  453. if (!is.null(grid_layout)) {
  454. # Set grid_ncol to 1 if not specified
  455. if (is.null(grid_layout$ncol)) {
  456. grid_layout$ncol <- 1
  457. }
  458. # If ncol is set but nrow is not, calculate nrow dynamically based on num_plots
  459. if (!is.null(grid_layout$ncol) && is.null(grid_layout$nrow)) {
  460. num_plots <- length(plots)
  461. nrow <- ceiling(num_plots / grid_layout$ncol)
  462. message("No nrow provided, automatically using nrow = ", nrow)
  463. grid_layout$nrow <- nrow
  464. }
  465. }
  466. for (i in seq_along(plots)) {
  467. config <- plots[[i]]
  468. df <- config$df
  469. # Filter points outside of y-limits if specified
  470. if (!is.null(config$ylim_vals)) {
  471. out_of_bounds_df <- df %>%
  472. filter(
  473. is.na(.data[[config$y_var]]) |
  474. .data[[config$y_var]] < config$ylim_vals[1] |
  475. .data[[config$y_var]] > config$ylim_vals[2]
  476. )
  477. # Print rows being filtered out
  478. if (nrow(out_of_bounds_df) > 0) {
  479. message("Filtered out rows outside y-limits:")
  480. print(out_of_bounds_df)
  481. }
  482. # Filter the valid data for plotting
  483. df <- df %>%
  484. filter(
  485. !is.na(.data[[config$y_var]]) &
  486. .data[[config$y_var]] >= config$ylim_vals[1] &
  487. .data[[config$y_var]] <= config$ylim_vals[2]
  488. )
  489. }
  490. # Set up aes mapping based on plot type
  491. aes_mapping <- if (config$plot_type == "bar") {
  492. if (!is.null(config$color_var)) {
  493. aes(x = .data[[config$x_var]], fill = .data[[config$color_var]], color = .data[[config$color_var]])
  494. } else {
  495. aes(x = .data[[config$x_var]])
  496. }
  497. } else if (config$plot_type == "density") {
  498. if (!is.null(config$color_var)) {
  499. aes(x = .data[[config$x_var]], color = .data[[config$color_var]])
  500. } else {
  501. aes(x = .data[[config$x_var]])
  502. }
  503. } else {
  504. if (!is.null(config$y_var) && !is.null(config$color_var)) {
  505. aes(x = .data[[config$x_var]], y = .data[[config$y_var]], color = .data[[config$color_var]])
  506. } else if (!is.null(config$y_var)) {
  507. aes(x = .data[[config$x_var]], y = .data[[config$y_var]])
  508. } else {
  509. aes(x = .data[[config$x_var]])
  510. }
  511. }
  512. plot <- ggplot(df, aes_mapping) + theme_publication(legend_position = config$legend_position)
  513. # Add appropriate plot layer based on plot type
  514. plot <- switch(config$plot_type,
  515. "scatter" = generate_scatter_plot(plot, config),
  516. "box" = generate_boxplot(plot, config),
  517. "density" = plot + geom_density(),
  518. "bar" = plot + geom_bar(),
  519. plot # default (unused)
  520. )
  521. # Add labels and title
  522. if (!is.null(config$title)) plot <- plot + ggtitle(config$title)
  523. if (!is.null(config$x_label)) plot <- plot + xlab(config$x_label)
  524. if (!is.null(config$y_label)) plot <- plot + ylab(config$y_label)
  525. if (!is.null(config$coord_cartesian)) plot <- plot + coord_cartesian(ylim = config$coord_cartesian)
  526. # Add annotations if specified
  527. if (!is.null(config$annotations)) {
  528. for (annotation in config$annotations) {
  529. plot <- plot +
  530. annotate(
  531. "text",
  532. x = ifelse(is.null(annotation$x), 0, annotation$x),
  533. y = ifelse(is.null(annotation$y), Inf, annotation$y),
  534. label = annotation$label,
  535. hjust = ifelse(is.null(annotation$hjust), 0.5, annotation$hjust),
  536. vjust = ifelse(is.null(annotation$vjust), 1, annotation$vjust),
  537. size = ifelse(is.null(annotation$size), 3, annotation$size),
  538. color = ifelse(is.null(annotation$color), "black", annotation$color)
  539. )
  540. }
  541. }
  542. # Add error bars if specified
  543. if (!is.null(config$error_bar) && config$error_bar) {
  544. y_mean_col <- paste0("mean_", config$y_var)
  545. y_sd_col <- paste0("sd_", config$y_var)
  546. # If color_var is provided and no fixed error bar color is set, use aes() to map color dynamically
  547. if (!is.null(config$color_var) && is.null(config$error_bar_params$color)) {
  548. plot <- plot + geom_errorbar(
  549. aes(
  550. x = .data[[config$x_var]],
  551. ymin = .data[[y_mean_col]] - .data[[y_sd_col]],
  552. ymax = .data[[y_mean_col]] + .data[[y_sd_col]],
  553. color = .data[[config$color_var]] # Dynamic color from the data
  554. )
  555. )
  556. } else {
  557. # If a fixed error bar color is set, use it outside aes
  558. plot <- plot + geom_errorbar(
  559. aes(
  560. x = .data[[config$x_var]],
  561. ymin = .data[[y_mean_col]] - .data[[y_sd_col]],
  562. ymax = .data[[y_mean_col]] + .data[[y_sd_col]]
  563. ),
  564. color = config$error_bar_params$color # Fixed color
  565. )
  566. }
  567. }
  568. # Convert ggplot to plotly for interactive version
  569. plotly_plot <- suppressWarnings(plotly::ggplotly(plot))
  570. # Store both static and interactive versions
  571. static_plots[[i]] <- plot
  572. plotly_plots[[i]] <- plotly_plot
  573. }
  574. # Print the plots in the current group to the PDF
  575. if (is.null(grid_layout)) {
  576. # Print each plot individually on separate pages if no grid layout is specified
  577. for (plot in static_plots) {
  578. print(plot)
  579. }
  580. } else {
  581. # Arrange plots in grid layout on a single page
  582. grid.arrange(
  583. grobs = static_plots,
  584. ncol = grid_layout$ncol,
  585. nrow = grid_layout$nrow
  586. )
  587. }
  588. }
  589. # Close the PDF device after all plots are done
  590. dev.off()
  591. # Save HTML file with interactive plots if needed
  592. out_html_file <- file.path(out_dir, paste0(filename, ".html"))
  593. message("Saving combined HTML file: ", out_html_file)
  594. htmltools::save_html(
  595. htmltools::tagList(plotly_plots),
  596. file = out_html_file
  597. )
  598. }
  599. generate_scatter_plot <- function(plot, config) {
  600. # Define the points
  601. shape <- if (!is.null(config$shape)) config$shape else 3
  602. size <- if (!is.null(config$size)) config$size else 1.5
  603. position <-
  604. if (!is.null(config$position) && config$position == "jitter") {
  605. position_jitter(width = 0.4, height = 0.1)
  606. } else {
  607. "identity"
  608. }
  609. plot <- plot + geom_point(
  610. shape = shape,
  611. size = size,
  612. position = position
  613. )
  614. if (!is.null(config$cyan_points) && config$cyan_points) {
  615. plot <- plot + geom_point(
  616. aes(x = .data[[config$x_var]], y = .data[[config$y_var]]),
  617. color = "cyan",
  618. shape = 3,
  619. size = 0.5
  620. )
  621. }
  622. # Add Smooth Line if specified
  623. if (!is.null(config$smooth) && config$smooth) {
  624. smooth_color <- if (!is.null(config$smooth_color)) config$smooth_color else "blue"
  625. if (!is.null(config$lm_line)) {
  626. plot <- plot +
  627. geom_abline(
  628. intercept = config$lm_line$intercept,
  629. slope = config$lm_line$slope,
  630. color = smooth_color
  631. )
  632. } else {
  633. plot <- plot +
  634. geom_smooth(
  635. method = "lm",
  636. se = FALSE,
  637. color = smooth_color
  638. )
  639. }
  640. }
  641. # Add SD Bands if specified
  642. if (!is.null(config$sd_band)) {
  643. plot <- plot +
  644. annotate(
  645. "rect",
  646. xmin = -Inf, xmax = Inf,
  647. ymin = config$sd_band, ymax = Inf,
  648. fill = ifelse(!is.null(config$fill_positive), config$fill_positive, "#542788"),
  649. alpha = ifelse(!is.null(config$alpha_positive), config$alpha_positive, 0.3)
  650. ) +
  651. annotate(
  652. "rect",
  653. xmin = -Inf, xmax = Inf,
  654. ymin = -config$sd_band, ymax = -Inf,
  655. fill = ifelse(!is.null(config$fill_negative), config$fill_negative, "orange"),
  656. alpha = ifelse(!is.null(config$alpha_negative), config$alpha_negative, 0.3)
  657. ) +
  658. geom_hline(
  659. yintercept = c(-config$sd_band, config$sd_band),
  660. color = ifelse(!is.null(config$hl_color), config$hl_color, "gray")
  661. )
  662. }
  663. # Add Rectangles if specified
  664. if (!is.null(config$rectangles)) {
  665. for (rect in config$rectangles) {
  666. plot <- plot + annotate(
  667. "rect",
  668. xmin = rect$xmin,
  669. xmax = rect$xmax,
  670. ymin = rect$ymin,
  671. ymax = rect$ymax,
  672. fill = ifelse(is.null(rect$fill), NA, rect$fill),
  673. color = ifelse(is.null(rect$color), "black", rect$color),
  674. alpha = ifelse(is.null(rect$alpha), 0.1, rect$alpha)
  675. )
  676. }
  677. }
  678. # Customize X-axis if specified
  679. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  680. # Check if x_var is factor or character (for discrete x-axis)
  681. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  682. plot <- plot +
  683. scale_x_discrete(
  684. name = config$x_label,
  685. breaks = config$x_breaks,
  686. labels = config$x_labels
  687. )
  688. } else {
  689. plot <- plot +
  690. scale_x_continuous(
  691. name = config$x_label,
  692. breaks = config$x_breaks,
  693. labels = config$x_labels
  694. )
  695. }
  696. }
  697. # Set Y-axis limits if specified
  698. if (!is.null(config$ylim_vals)) {
  699. plot <- plot + scale_y_continuous(limits = config$ylim_vals)
  700. }
  701. return(plot)
  702. }
  703. generate_boxplot <- function(plot, config) {
  704. # Convert x_var to a factor within aes mapping
  705. plot <- plot + geom_boxplot(aes(x = factor(.data[[config$x_var]])))
  706. # Customize X-axis if specified
  707. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  708. # Check if x_var is factor or character (for discrete x-axis)
  709. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  710. plot <- plot +
  711. scale_x_discrete(
  712. name = config$x_label,
  713. breaks = config$x_breaks,
  714. labels = config$x_labels
  715. )
  716. } else {
  717. plot <- plot +
  718. scale_x_continuous(
  719. name = config$x_label,
  720. breaks = config$x_breaks,
  721. labels = config$x_labels
  722. )
  723. }
  724. }
  725. return(plot)
  726. }
  727. generate_plate_analysis_plot_configs <- function(variables, df_before = NULL, df_after = NULL,
  728. plot_type = "scatter", stages = c("before", "after")) {
  729. plot_configs <- list()
  730. for (var in variables) {
  731. for (stage in stages) {
  732. df_plot <- if (stage == "before") df_before else df_after
  733. # Check for non-finite values in the y-variable
  734. df_plot_filtered <- df_plot %>% filter(is.finite(!!sym(var)))
  735. # Adjust settings based on plot_type
  736. plot_config <- list(
  737. df = df_plot_filtered,
  738. x_var = "scan",
  739. y_var = var,
  740. plot_type = plot_type,
  741. title = paste("Plate analysis by Drug Conc for", var, stage, "quality control"),
  742. color_var = "conc_num_factor_factor",
  743. size = 0.2,
  744. error_bar = (plot_type == "scatter"),
  745. legend_position = "bottom"
  746. )
  747. # Add config to plots list
  748. plot_configs <- append(plot_configs, list(plot_config))
  749. }
  750. }
  751. return(list(plots = plot_configs))
  752. }
  753. generate_interaction_plot_configs <- function(df, type) {
  754. # Define the y-limits for the plots
  755. limits_map <- list(
  756. L = c(0, 130),
  757. K = c(-20, 160),
  758. r = c(0, 1),
  759. AUC = c(0, 12500)
  760. )
  761. stats_plot_configs <- list()
  762. stats_boxplot_configs <- list()
  763. delta_plot_configs <- list()
  764. # Overall statistics plots
  765. OrfRep <- first(df$OrfRep) # this should correspond to the reference strain
  766. for (plot_type in c("scatter", "box")) {
  767. for (var in names(limits_map)) {
  768. y_limits <- limits_map[[var]]
  769. y_span <- y_limits[2] - y_limits[1]
  770. # Common plot configuration
  771. plot_config <- list(
  772. df = df,
  773. plot_type = plot_type,
  774. x_var = "conc_num_factor_factor",
  775. y_var = var,
  776. shape = 16,
  777. x_label = unique(df$Drug)[1],
  778. coord_cartesian = y_limits,
  779. x_breaks = unique(df$conc_num_factor_factor),
  780. x_labels = as.character(unique(df$conc_num))
  781. )
  782. # Add specific configurations for scatter and box plots
  783. if (plot_type == "scatter") {
  784. plot_config$title <- sprintf("%s Scatter RF for %s with SD", OrfRep, var)
  785. plot_config$error_bar <- TRUE
  786. plot_config$error_bar_params <- list(
  787. color = "red",
  788. center_point = TRUE
  789. )
  790. plot_config$position <- "jitter"
  791. annotations <- list(
  792. list(x = 0.25, y = y_limits[1] + 0.1 * y_span, label = " NG:"),
  793. list(x = 0.25, y = y_limits[1] + 0.05 * y_span, label = " DB:"),
  794. list(x = 0.25, y = y_limits[1], label = " SM:")
  795. )
  796. # Loop over unique x values and add NG, DB, SM values at calculated y positions
  797. for (x_val in unique(df$conc_num_factor_factor)) {
  798. current_df <- df %>% filter(.data[[plot_config$x_var]] == x_val)
  799. annotations <- append(annotations, list(
  800. list(x = x_val, y = y_limits[1] + 0.1 * y_span, label = first(current_df$NG, default = 0)),
  801. list(x = x_val, y = y_limits[1] + 0.05 * y_span, label = first(current_df$DB, default = 0)),
  802. list(x = x_val, y = y_limits[1], label = first(current_df$SM, default = 0))
  803. ))
  804. }
  805. plot_config$annotations <- annotations
  806. stats_plot_configs <- append(stats_plot_configs, list(plot_config))
  807. } else if (plot_type == "box") {
  808. plot_config$title <- sprintf("%s Boxplot RF for %s with SD", OrfRep, var)
  809. plot_config$position <- "dodge" # Boxplots don't need jitter, use dodge instead
  810. # Append to boxplot configurations
  811. stats_boxplot_configs <- append(stats_boxplot_configs, list(plot_config))
  812. }
  813. }
  814. }
  815. # Delta interaction plots
  816. if (type == "reference") {
  817. group_vars <- c("OrfRep", "Gene", "num")
  818. } else if (type == "deletion") {
  819. group_vars <- c("OrfRep", "Gene")
  820. }
  821. delta_limits_map <- list(
  822. L = c(-60, 60),
  823. K = c(-60, 60),
  824. r = c(-0.6, 0.6),
  825. AUC = c(-6000, 6000)
  826. )
  827. grouped_data <- df %>%
  828. group_by(across(all_of(group_vars))) %>%
  829. group_split()
  830. for (group_data in grouped_data) {
  831. OrfRep <- first(group_data$OrfRep)
  832. Gene <- first(group_data$Gene)
  833. num <- if ("num" %in% names(group_data)) first(group_data$num) else ""
  834. if (type == "reference") {
  835. OrfRepTitle <- paste(OrfRep, Gene, num, sep = "_")
  836. } else if (type == "deletion") {
  837. OrfRepTitle <- OrfRep
  838. }
  839. for (var in names(delta_limits_map)) {
  840. y_limits <- delta_limits_map[[var]]
  841. y_span <- y_limits[2] - y_limits[1]
  842. # Error bars
  843. WT_sd_value <- first(group_data[[paste0("WT_sd_", var)]], default = 0)
  844. # Z_Shift and lm values
  845. Z_Shift_value <- round(first(group_data[[paste0("Z_Shift_", var)]], default = 0), 2)
  846. Z_lm_value <- round(first(group_data[[paste0("Z_lm_", var)]], default = 0), 2)
  847. R_squared_value <- round(first(group_data[[paste0("R_Squared_", var)]], default = 0), 2)
  848. # NG, DB, SM values
  849. NG_value <- first(group_data$NG, default = 0)
  850. DB_value <- first(group_data$DB, default = 0)
  851. SM_value <- first(group_data$SM, default = 0)
  852. # Use the pre-calculated lm intercept and slope from the dataframe
  853. lm_intercept_col <- paste0("lm_intercept_", var)
  854. lm_slope_col <- paste0("lm_slope_", var)
  855. lm_intercept_value <- first(group_data[[lm_intercept_col]], default = 0)
  856. lm_slope_value <- first(group_data[[lm_slope_col]], default = 0)
  857. plot_config <- list(
  858. df = group_data,
  859. plot_type = "scatter",
  860. x_var = "conc_num_factor_factor",
  861. y_var = var,
  862. x_label = unique(group_data$Drug)[1],
  863. title = paste(OrfRepTitle, Gene, num, sep = " "),
  864. coord_cartesian = y_limits,
  865. annotations = list(
  866. list(x = 1, y = y_limits[2] - 0.2 * y_span, label = paste("ZShift =", Z_Shift_value)),
  867. list(x = 1, y = y_limits[2] - 0.3 * y_span, label = paste("lm ZScore =", Z_lm_value)),
  868. list(x = 1, y = y_limits[2] - 0.4 * y_span, label = paste("R-squared =", R_squared_value)),
  869. list(x = 1, y = y_limits[1] + 0.2 * y_span, label = paste("NG =", NG_value)),
  870. list(x = 1, y = y_limits[1] + 0.1 * y_span, label = paste("DB =", DB_value)),
  871. list(x = 1, y = y_limits[1], label = paste("SM =", SM_value))
  872. ),
  873. error_bar = TRUE,
  874. error_bar_params = list(
  875. ymin = 0 - (2 * WT_sd_value),
  876. ymax = 0 + (2 * WT_sd_value),
  877. color = "black"
  878. ),
  879. smooth = TRUE,
  880. x_breaks = unique(group_data$conc_num_factor_factor),
  881. x_labels = as.character(unique(group_data$conc_num)),
  882. ylim_vals = y_limits,
  883. y_filter = FALSE,
  884. lm_line = list(
  885. intercept = lm_intercept_value,
  886. slope = lm_slope_value
  887. )
  888. )
  889. delta_plot_configs <- append(delta_plot_configs, list(plot_config))
  890. }
  891. }
  892. return(list(
  893. list(grid_layout = list(ncol = 2), plots = stats_plot_configs), # nrow will be calculated dynamically
  894. list(grid_layout = list(ncol = 2), plots = stats_boxplot_configs), # nrow will be calculated dynamically
  895. list(grid_layout = list(ncol = 4), plots = delta_plot_configs) # nrow will be calculated dynamically
  896. ))
  897. }
  898. generate_rank_plot_configs <- function(df, is_lm = FALSE, adjust = FALSE, overlap_color = FALSE) {
  899. sd_bands <- c(1, 2, 3)
  900. plot_configs <- list()
  901. variables <- c("L", "K")
  902. # Adjust (if necessary) and rank columns
  903. for (variable in variables) {
  904. if (adjust) {
  905. df[[paste0("Avg_Zscore_", variable)]] <- ifelse(is.na(df[[paste0("Avg_Zscore_", variable)]]), 0.001, df[[paste0("Avg_Zscore_", variable)]])
  906. df[[paste0("Z_lm_", variable)]] <- ifelse(is.na(df[[paste0("Z_lm_", variable)]]), 0.001, df[[paste0("Z_lm_", variable)]])
  907. }
  908. df[[paste0("Rank_", variable)]] <- rank(df[[paste0("Avg_Zscore_", variable)]], na.last = "keep")
  909. df[[paste0("Rank_lm_", variable)]] <- rank(df[[paste0("Z_lm_", variable)]], na.last = "keep")
  910. }
  911. # Helper function to create a plot configuration
  912. create_plot_config <- function(variable, rank_var, zscore_var, y_label, sd_band, with_annotations = TRUE) {
  913. num_enhancers <- sum(df[[zscore_var]] >= sd_band, na.rm = TRUE)
  914. num_suppressors <- sum(df[[zscore_var]] <= -sd_band, na.rm = TRUE)
  915. # Default plot config
  916. plot_config <- list(
  917. df = df,
  918. x_var = rank_var,
  919. y_var = zscore_var,
  920. plot_type = "scatter",
  921. title = paste(y_label, "vs. Rank for", variable, "above", sd_band),
  922. sd_band = sd_band,
  923. fill_positive = "#542788",
  924. fill_negative = "orange",
  925. alpha_positive = 0.3,
  926. alpha_negative = 0.3,
  927. annotations = NULL,
  928. shape = 3,
  929. size = 0.1,
  930. y_label = y_label,
  931. x_label = "Rank",
  932. legend_position = "none"
  933. )
  934. if (with_annotations) {
  935. # Add specific annotations for plots with annotations
  936. plot_config$annotations <- list(
  937. list(
  938. x = median(df[[rank_var]], na.rm = TRUE),
  939. y = max(df[[zscore_var]], na.rm = TRUE) * 0.9,
  940. label = paste("Deletion Enhancers =", num_enhancers)
  941. ),
  942. list(
  943. x = median(df[[rank_var]], na.rm = TRUE),
  944. y = min(df[[zscore_var]], na.rm = TRUE) * 0.9,
  945. label = paste("Deletion Suppressors =", num_suppressors)
  946. )
  947. )
  948. }
  949. return(plot_config)
  950. }
  951. # Generate plots for each variable
  952. for (variable in variables) {
  953. rank_var <- if (is_lm) paste0("Rank_lm_", variable) else paste0("Rank_", variable)
  954. zscore_var <- if (is_lm) paste0("Z_lm_", variable) else paste0("Avg_Zscore_", variable)
  955. y_label <- if (is_lm) paste("Int Z score", variable) else paste("Avg Z score", variable)
  956. # Loop through SD bands
  957. for (sd_band in sd_bands) {
  958. # Create plot with annotations
  959. plot_configs[[length(plot_configs) + 1]] <- create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, with_annotations = TRUE)
  960. # Create plot without annotations
  961. plot_configs[[length(plot_configs) + 1]] <- create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, with_annotations = FALSE)
  962. }
  963. }
  964. # Calculate dynamic grid layout based on the number of plots
  965. grid_ncol <- 3
  966. num_plots <- length(plot_configs)
  967. grid_nrow <- ceiling(num_plots / grid_ncol) # Automatically calculate the number of rows
  968. return(list(grid_layout = list(ncol = grid_ncol, nrow = grid_nrow), plots = plot_configs))
  969. }
  970. generate_correlation_plot_configs <- function(df, correlation_stats) {
  971. # Define relationships for different-variable correlations
  972. relationships <- list(
  973. list(x = "L", y = "K"),
  974. list(x = "L", y = "r"),
  975. list(x = "L", y = "AUC"),
  976. list(x = "K", y = "r"),
  977. list(x = "K", y = "AUC"),
  978. list(x = "r", y = "AUC")
  979. )
  980. plot_configs <- list()
  981. # Iterate over the option to highlight cyan points (TRUE/FALSE)
  982. highlight_cyan_options <- c(FALSE, TRUE)
  983. for (highlight_cyan in highlight_cyan_options) {
  984. for (rel in relationships) {
  985. # Extract relevant variable names for Z_lm values
  986. x_var <- paste0("Z_lm_", rel$x)
  987. y_var <- paste0("Z_lm_", rel$y)
  988. # Access the correlation statistics from the correlation_stats list
  989. relationship_name <- paste0(rel$x, "_vs_", rel$y) # Example: L_vs_K
  990. stats <- correlation_stats[[relationship_name]]
  991. intercept <- stats$intercept
  992. slope <- stats$slope
  993. r_squared <- stats$r_squared
  994. # Generate the label for the plot
  995. plot_label <- paste("Interaction", rel$x, "vs.", rel$y)
  996. # Construct plot config
  997. plot_config <- list(
  998. df = df,
  999. x_var = x_var,
  1000. y_var = y_var,
  1001. plot_type = "scatter",
  1002. title = plot_label,
  1003. annotations = list(
  1004. list(
  1005. x = mean(df[[x_var]], na.rm = TRUE),
  1006. y = mean(df[[y_var]], na.rm = TRUE),
  1007. label = paste("R-squared =", round(r_squared, 3))
  1008. )
  1009. ),
  1010. smooth = TRUE,
  1011. smooth_color = "tomato3",
  1012. lm_line = list(
  1013. intercept = intercept,
  1014. slope = slope
  1015. ),
  1016. shape = 3,
  1017. size = 0.5,
  1018. color_var = "Overlap",
  1019. cyan_points = highlight_cyan # Include cyan points or not based on the loop
  1020. )
  1021. plot_configs <- append(plot_configs, list(plot_config))
  1022. }
  1023. }
  1024. return(list(plots = plot_configs))
  1025. }
  1026. main <- function() {
  1027. lapply(names(args$experiments), function(exp_name) {
  1028. exp <- args$experiments[[exp_name]]
  1029. exp_path <- exp$path
  1030. exp_sd <- exp$sd
  1031. out_dir <- file.path(exp_path, "zscores")
  1032. out_dir_qc <- file.path(exp_path, "zscores", "qc")
  1033. dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
  1034. dir.create(out_dir_qc, recursive = TRUE, showWarnings = FALSE)
  1035. # Each list of plots corresponds to a separate file
  1036. message("Loading and filtering data for experiment: ", exp_name)
  1037. df <- load_and_filter_data(args$easy_results_file, sd = exp_sd) %>%
  1038. update_gene_names(args$sgd_gene_list) %>%
  1039. as_tibble()
  1040. l_vs_k_plot_configs <- list(
  1041. plots = list(
  1042. list(
  1043. df = df,
  1044. x_var = "L",
  1045. y_var = "K",
  1046. plot_type = "scatter",
  1047. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1048. title = "Raw L vs K before quality control",
  1049. color_var = "conc_num_factor_factor",
  1050. error_bar = FALSE,
  1051. legend_position = "right"
  1052. )
  1053. )
  1054. )
  1055. message("Calculating summary statistics before quality control")
  1056. df_stats <- calculate_summary_stats(
  1057. df = df,
  1058. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1059. group_vars = c("conc_num"))$df_with_stats
  1060. frequency_delta_bg_plot_configs <- list(
  1061. plots = list(
  1062. list(
  1063. df = df_stats,
  1064. x_var = "delta_bg",
  1065. y_var = NULL,
  1066. plot_type = "density",
  1067. title = "Density plot for Delta Background by [Drug] (All Data)",
  1068. color_var = "conc_num_factor_factor",
  1069. x_label = "Delta Background",
  1070. y_label = "Density",
  1071. error_bar = FALSE,
  1072. legend_position = "right"
  1073. ),
  1074. list(
  1075. df = df_stats,
  1076. x_var = "delta_bg",
  1077. y_var = NULL,
  1078. plot_type = "bar",
  1079. title = "Bar plot for Delta Background by [Drug] (All Data)",
  1080. color_var = "conc_num_factor_factor",
  1081. x_label = "Delta Background",
  1082. y_label = "Count",
  1083. error_bar = FALSE,
  1084. legend_position = "right"
  1085. )
  1086. )
  1087. )
  1088. message("Filtering rows above delta background tolerance for plotting")
  1089. df_above_tolerance <- df %>% filter(DB == 1)
  1090. above_threshold_plot_configs <- list(
  1091. plots = list(
  1092. list(
  1093. df = df_above_tolerance,
  1094. x_var = "L",
  1095. y_var = "K",
  1096. plot_type = "scatter",
  1097. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1098. title = paste("Raw L vs K for strains above Delta Background threshold of",
  1099. round(df_above_tolerance$delta_bg_tolerance[[1]], 3), "or above"),
  1100. color_var = "conc_num_factor_factor",
  1101. position = "jitter",
  1102. annotations = list(
  1103. list(
  1104. x = median(df_above_tolerance$L, na.rm = TRUE) / 2,
  1105. y = median(df_above_tolerance$K, na.rm = TRUE) / 2,
  1106. label = paste("# strains above Delta Background tolerance =", nrow(df_above_tolerance))
  1107. )
  1108. ),
  1109. error_bar = FALSE,
  1110. legend_position = "right"
  1111. )
  1112. )
  1113. )
  1114. message("Setting rows above delta background tolerance to NA")
  1115. df_na <- df %>% mutate(across(all_of(c("L", "K", "r", "AUC", "delta_bg")), ~ ifelse(DB == 1, NA, .))) # formerly X
  1116. message("Calculating summary statistics across all strains")
  1117. ss <- calculate_summary_stats(
  1118. df = df_na,
  1119. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1120. group_vars = c("conc_num"))
  1121. df_na_ss <- ss$summary_stats
  1122. df_na_stats <- ss$df_with_stats # formerly X_stats_ALL
  1123. write.csv(df_na_ss, file = file.path(out_dir, "summary_stats_all_strains.csv"), row.names = FALSE)
  1124. # This can help bypass missing values ggplot warnings during testing
  1125. df_na_stats_filtered <- df_na_stats %>% filter(if_all(all_of(c("L", "K", "r", "AUC", "delta_bg")), is.finite))
  1126. message("Calculating summary statistics excluding zero values")
  1127. df_no_zeros <- df_na %>% filter(L > 0) # formerly X_noZero
  1128. df_no_zeros_stats <- calculate_summary_stats(
  1129. df = df_no_zeros,
  1130. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1131. group_vars = c("conc_num")
  1132. )$df_with_stats
  1133. message("Filtering by 2SD of K")
  1134. df_na_within_2sd_k <- df_na_stats %>%
  1135. filter(K >= (mean_K - 2 * sd_K) & K <= (mean_K + 2 * sd_K))
  1136. df_na_outside_2sd_k <- df_na_stats %>%
  1137. filter(K < (mean_K - 2 * sd_K) | K > (mean_K + 2 * sd_K))
  1138. message("Calculating summary statistics for L within 2SD of K")
  1139. # TODO We're omitting the original z_max calculation, not sure if needed?
  1140. ss <- calculate_summary_stats(df_na_within_2sd_k, "L",
  1141. group_vars = c("conc_num"))$summary_stats
  1142. write.csv(ss,
  1143. file = file.path(out_dir_qc, "max_observed_L_vals_for_spots_within_2SD_K.csv"),
  1144. row.names = FALSE)
  1145. message("Calculating summary statistics for L outside 2SD of K")
  1146. ss <- calculate_summary_stats(df_na_outside_2sd_k, "L", group_vars = c("conc_num"))
  1147. df_na_l_outside_2sd_k_stats <- ss$df_with_stats
  1148. write.csv(ss$summary_stats,
  1149. file = file.path(out_dir, "max_observed_L_vals_for_spots_outside_2SD_K.csv"),
  1150. row.names = FALSE)
  1151. plate_analysis_plot_configs <- generate_plate_analysis_plot_configs(
  1152. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1153. df_before = df_stats,
  1154. df_after = df_na_stats_filtered
  1155. )
  1156. plate_analysis_boxplot_configs <- generate_plate_analysis_plot_configs(
  1157. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1158. df_before = df_stats,
  1159. df_after = df_na_stats_filtered,
  1160. plot_type = "box"
  1161. )
  1162. plate_analysis_no_zeros_plot_configs <- generate_plate_analysis_plot_configs(
  1163. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1164. stages = c("after"), # Only after QC
  1165. df_after = df_no_zeros_stats
  1166. )
  1167. plate_analysis_no_zeros_boxplot_configs <- generate_plate_analysis_plot_configs(
  1168. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1169. stages = c("after"), # Only after QC
  1170. df_after = df_no_zeros_stats,
  1171. plot_type = "box"
  1172. )
  1173. l_outside_2sd_k_plot_configs <- list(
  1174. plots = list(
  1175. list(
  1176. df = df_na_l_outside_2sd_k_stats,
  1177. x_var = "L",
  1178. y_var = "K",
  1179. plot_type = "scatter",
  1180. title = "Raw L vs K for strains falling outside 2SD of the K mean at each Conc",
  1181. color_var = "conc_num_factor_factor",
  1182. position = "jitter",
  1183. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1184. annotations = list(
  1185. list(
  1186. x = median(df_na_l_outside_2sd_k_stats$L, na.rm = TRUE) / 2,
  1187. y = median(df_na_l_outside_2sd_k_stats$K, na.rm = TRUE) / 2,
  1188. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats))
  1189. )
  1190. ),
  1191. error_bar = FALSE,
  1192. legend_position = "right"
  1193. )
  1194. )
  1195. )
  1196. delta_bg_outside_2sd_k_plot_configs <- list(
  1197. plots = list(
  1198. list(
  1199. df = df_na_l_outside_2sd_k_stats,
  1200. x_var = "delta_bg",
  1201. x_label = "Delta Background",
  1202. y_var = "K",
  1203. plot_type = "scatter",
  1204. title = "Delta Background vs K for strains falling outside 2SD of the K mean at each Conc",
  1205. color_var = "conc_num_factor_factor",
  1206. position = "jitter",
  1207. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1208. annotations = list(
  1209. list(
  1210. x = 0.05,
  1211. y = 0.95,
  1212. hjust = 0,
  1213. vjust = 1,
  1214. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats)),
  1215. size = 5
  1216. )
  1217. ),
  1218. error_bar = FALSE,
  1219. legend_position = "right"
  1220. )
  1221. )
  1222. )
  1223. message("Generating quality control plots in parallel")
  1224. # future::plan(future::multicore, workers = parallel::detectCores())
  1225. future::plan(future::multisession, workers = 3) # generate 3 plots in parallel
  1226. plot_configs <- list(
  1227. list(out_dir = out_dir_qc, filename = "L_vs_K_before_quality_control",
  1228. plot_configs = l_vs_k_plot_configs),
  1229. list(out_dir = out_dir_qc, filename = "frequency_delta_background",
  1230. plot_configs = frequency_delta_bg_plot_configs),
  1231. list(out_dir = out_dir_qc, filename = "L_vs_K_above_threshold",
  1232. plot_configs = above_threshold_plot_configs),
  1233. list(out_dir = out_dir_qc, filename = "plate_analysis",
  1234. plot_configs = plate_analysis_plot_configs),
  1235. list(out_dir = out_dir_qc, filename = "plate_analysis_boxplots",
  1236. plot_configs = plate_analysis_boxplot_configs),
  1237. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros",
  1238. plot_configs = plate_analysis_no_zeros_plot_configs),
  1239. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros_boxplots",
  1240. plot_configs = plate_analysis_no_zeros_boxplot_configs),
  1241. list(out_dir = out_dir_qc, filename = "L_vs_K_for_strains_2SD_outside_mean_K",
  1242. plot_configs = l_outside_2sd_k_plot_configs),
  1243. list(out_dir = out_dir_qc, filename = "delta_background_vs_K_for_strains_2SD_outside_mean_K",
  1244. plot_configs = delta_bg_outside_2sd_k_plot_configs)
  1245. )
  1246. # furrr::future_map(plot_configs, function(config) {
  1247. # generate_and_save_plots(config$out_dir, config$filename, config$plot_configs)
  1248. # }, .options = furrr_options(seed = TRUE))
  1249. bg_strains <- c("YDL227C")
  1250. lapply(bg_strains, function(strain) {
  1251. message("Processing background strain: ", strain)
  1252. # Handle missing data by setting zero values to NA
  1253. # and then removing any rows with NA in L col
  1254. df_bg <- df_na %>%
  1255. filter(OrfRep == strain) %>%
  1256. mutate(
  1257. L = if_else(L == 0, NA, L),
  1258. K = if_else(K == 0, NA, K),
  1259. r = if_else(r == 0, NA, r),
  1260. AUC = if_else(AUC == 0, NA, AUC)
  1261. ) %>%
  1262. filter(!is.na(L))
  1263. message("Calculating background strain summary statistics")
  1264. ss_bg <- calculate_summary_stats(df_bg, c("L", "K", "r", "AUC", "delta_bg"),
  1265. group_vars = c("OrfRep", "Drug", "conc_num", "conc_num_factor_factor"))
  1266. summary_stats_bg <- ss_bg$summary_stats
  1267. df_bg_stats <- ss_bg$df_with_stats
  1268. write.csv(
  1269. summary_stats_bg,
  1270. file = file.path(out_dir, paste0("summary_stats_background_strain_", strain, ".csv")),
  1271. row.names = FALSE)
  1272. message("Setting missing reference values to the highest theoretical value at each drug conc for L")
  1273. df_reference <- df_na_stats %>% # formerly X2_RF
  1274. filter(OrfRep == strain) %>%
  1275. filter(!is.na(L)) %>%
  1276. group_by(OrfRep, Drug, conc_num) %>%
  1277. mutate(
  1278. max_l_theoretical = max(max_L, na.rm = TRUE),
  1279. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1280. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, 0),
  1281. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1282. ungroup()
  1283. message("Calculating reference strain summary statistics")
  1284. df_reference_stats <- calculate_summary_stats(
  1285. df = df_reference,
  1286. variables = c("L", "K", "r", "AUC"),
  1287. group_vars = c("OrfRep", "Gene", "Drug", "num", "conc_num", "conc_num_factor_factor")
  1288. )$df_with_stats
  1289. message("Calculating reference strain interaction scores")
  1290. results <- calculate_interaction_scores(df_reference_stats, df_bg_stats, group_vars = c("OrfRep", "Gene", "Drug", "num"))
  1291. df_calculations_reference <- results$calculations
  1292. df_interactions_reference <- results$interactions
  1293. df_interactions_reference_joined <- results$full_data
  1294. write.csv(df_calculations_reference, file = file.path(out_dir, "zscore_calculations_reference.csv"), row.names = FALSE)
  1295. write.csv(df_interactions_reference, file = file.path(out_dir, "zscore_interactions_reference.csv"), row.names = FALSE)
  1296. # message("Setting missing deletion values to the highest theoretical value at each drug conc for L")
  1297. # df_deletion <- df_na_stats %>% # formerly X2
  1298. # filter(OrfRep != strain) %>%
  1299. # filter(!is.na(L)) %>%
  1300. # group_by(OrfRep, Gene, conc_num) %>%
  1301. # mutate(
  1302. # max_l_theoretical = max(max_L, na.rm = TRUE),
  1303. # L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1304. # SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, SM),
  1305. # L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1306. # ungroup()
  1307. # message("Calculating deletion strain(s) summary statistics")
  1308. # df_deletion_stats <- calculate_summary_stats(
  1309. # df = df_deletion,
  1310. # variables = c("L", "K", "r", "AUC"),
  1311. # group_vars = c("OrfRep", "Gene", "Drug", "conc_num", "conc_num_factor_factor")
  1312. # )$df_with_stats
  1313. # message("Calculating deletion strain(s) interactions scores")
  1314. # results <- calculate_interaction_scores(df_deletion_stats, df_bg_stats, group_vars = c("OrfRep", "Gene", "Drug"))
  1315. # df_calculations <- results$calculations
  1316. # df_interactions <- results$interactions
  1317. # df_interactions_joined <- results$full_data
  1318. # write.csv(df_calculations, file = file.path(out_dir, "zscore_calculations.csv"), row.names = FALSE)
  1319. # write.csv(df_interactions, file = file.path(out_dir, "zscore_interactions.csv"), row.names = FALSE)
  1320. message("Generating reference interaction plots")
  1321. reference_plot_configs <- generate_interaction_plot_configs(df_interactions_reference_joined, "reference")
  1322. generate_and_save_plots(out_dir, "interaction_plots_reference", reference_plot_configs)
  1323. message("Generating deletion interaction plots")
  1324. deletion_plot_configs <- generate_interaction_plot_configs(df_interactions_joined, "deletion")
  1325. generate_and_save_plots(out_dir, "interaction_plots", deletion_plot_configs)
  1326. message("Writing enhancer/suppressor csv files")
  1327. interaction_threshold <- 2 # TODO add to study config?
  1328. enhancer_condition_L <- df_interactions$Avg_Zscore_L >= interaction_threshold
  1329. suppressor_condition_L <- df_interactions$Avg_Zscore_L <= -interaction_threshold
  1330. enhancer_condition_K <- df_interactions$Avg_Zscore_K >= interaction_threshold
  1331. suppressor_condition_K <- df_interactions$Avg_Zscore_K <= -interaction_threshold
  1332. enhancers_L <- df_interactions[enhancer_condition_L, ]
  1333. suppressors_L <- df_interactions[suppressor_condition_L, ]
  1334. enhancers_K <- df_interactions[enhancer_condition_K, ]
  1335. suppressors_K <- df_interactions[suppressor_condition_K, ]
  1336. enhancers_and_suppressors_L <- df_interactions[enhancer_condition_L | suppressor_condition_L, ]
  1337. enhancers_and_suppressors_K <- df_interactions[enhancer_condition_K | suppressor_condition_K, ]
  1338. write.csv(enhancers_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_L.csv"), row.names = FALSE)
  1339. write.csv(suppressors_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_L.csv"), row.names = FALSE)
  1340. write.csv(enhancers_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_K.csv"), row.names = FALSE)
  1341. write.csv(suppressors_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_K.csv"), row.names = FALSE)
  1342. write.csv(enhancers_and_suppressors_L,
  1343. file = file.path(out_dir, "zscore_interactions_deletion_enhancers_and_suppressors_L.csv"), row.names = FALSE)
  1344. write.csv(enhancers_and_suppressors_K,
  1345. file = file.path(out_dir, "zscore_interaction_deletion_enhancers_and_suppressors_K.csv"), row.names = FALSE)
  1346. message("Writing linear model enhancer/suppressor csv files")
  1347. lm_interaction_threshold <- 2 # TODO add to study config?
  1348. enhancers_lm_L <- df_interactions[df_interactions$Z_lm_L >= lm_interaction_threshold, ]
  1349. suppressors_lm_L <- df_interactions[df_interactions$Z_lm_L <= -lm_interaction_threshold, ]
  1350. enhancers_lm_K <- df_interactions[df_interactions$Z_lm_K >= lm_interaction_threshold, ]
  1351. suppressors_lm_K <- df_interactions[df_interactions$Z_lm_K <= -lm_interaction_threshold, ]
  1352. write.csv(enhancers_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_L.csv"), row.names = FALSE)
  1353. write.csv(suppressors_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_L.csv"), row.names = FALSE)
  1354. write.csv(enhancers_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_K.csv"), row.names = FALSE)
  1355. write.csv(suppressors_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_K.csv"), row.names = FALSE)
  1356. message("Generating rank plots")
  1357. rank_plot_configs <- generate_rank_plot_configs(
  1358. df_interactions_joined,
  1359. is_lm = FALSE,
  1360. adjust = TRUE
  1361. )
  1362. generate_and_save_plots(out_dir = out_dir, filename = "rank_plots",
  1363. plot_configs = rank_plot_configs)
  1364. message("Generating ranked linear model plots")
  1365. rank_lm_plot_configs <- generate_rank_plot_configs(
  1366. df_interactions_joined,
  1367. is_lm = TRUE,
  1368. adjust = TRUE
  1369. )
  1370. generate_and_save_plots(out_dir = out_dir, filename = "rank_plots_lm",
  1371. plot_configs = rank_lm_plot_configs)
  1372. message("Generating filtered ranked plots")
  1373. rank_plot_filtered_configs <- generate_rank_plot_configs(
  1374. df_interactions_joined,
  1375. is_lm = FALSE,
  1376. adjust = FALSE,
  1377. overlap_color = TRUE
  1378. )
  1379. generate_and_save_plots(
  1380. out_dir = out_dir,
  1381. filename = "RankPlots_na_rm",
  1382. plot_configs = rank_plot_filtered_configs)
  1383. message("Generating filtered ranked linear model plots")
  1384. rank_plot_lm_filtered_configs <- generate_rank_plot_configs(
  1385. df_interactions_joined,
  1386. is_lm = TRUE,
  1387. adjust = FALSE,
  1388. overlap_color = TRUE
  1389. )
  1390. generate_and_save_plots(
  1391. out_dir = out_dir,
  1392. filename = "rank_plots_lm_na_rm",
  1393. plot_configs = rank_plot_lm_filtered_configs)
  1394. message("Generating correlation curve parameter pair plots")
  1395. correlation_plot_configs <- generate_correlation_plot_configs(
  1396. df_interactions_joined
  1397. )
  1398. generate_and_save_plots(
  1399. out_dir = out_dir,
  1400. filename = "correlation_cpps",
  1401. plot_configs = correlation_plot_configs,
  1402. )
  1403. })
  1404. })
  1405. }
  1406. main()
  1407. # For future simplification of joined dataframes
  1408. # df_joined <- left_join(cleaned_df, summary_stats, by = group_vars, suffix = c("_original", "_stats"))