calculate_interaction_zscores.R 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  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("grid")
  11. library("gridExtra")
  12. library("future")
  13. library("furrr")
  14. library("purrr")
  15. })
  16. # These parallelization libraries are very noisy
  17. suppressPackageStartupMessages({
  18. library("future")
  19. library("furrr")
  20. library("purrr")
  21. })
  22. # Turn all warnings into errors for development
  23. options(warn = 2)
  24. parse_arguments <- function() {
  25. args <- if (interactive()) {
  26. c(
  27. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240116_jhartman2_DoxoHLD",
  28. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/apps/r/SGD_features.tab",
  29. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/easy/20240116_jhartman2_DoxoHLD/results_std.txt",
  30. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240822_jhartman2_DoxoHLD/exp1",
  31. "Experiment 1: Doxo versus HLD",
  32. 3,
  33. "/home/bryan/documents/develop/hartmanlab/qhtcp-workflow/out/20240116_jhartman2_DoxoHLD/20240822_jhartman2_DoxoHLD/exp2",
  34. "Experiment 2: HLD versus Doxo",
  35. 3
  36. )
  37. } else {
  38. commandArgs(trailingOnly = TRUE)
  39. }
  40. out_dir <- normalizePath(args[1], mustWork = FALSE)
  41. sgd_gene_list <- normalizePath(args[2], mustWork = FALSE)
  42. easy_results_file <- normalizePath(args[3], mustWork = FALSE)
  43. # The remaining arguments should be in groups of 3
  44. exp_args <- args[-(1:3)]
  45. if (length(exp_args) %% 3 != 0) {
  46. stop("Experiment arguments should be in groups of 3: path, name, sd.")
  47. }
  48. # Extract the experiments into a list
  49. experiments <- list()
  50. for (i in seq(1, length(exp_args), by = 3)) {
  51. exp_name <- exp_args[i + 1]
  52. experiments[[exp_name]] <- list(
  53. path = normalizePath(exp_args[i], mustWork = FALSE),
  54. sd = as.numeric(exp_args[i + 2])
  55. )
  56. }
  57. # Extract the trailing number from each path
  58. trailing_numbers <- sapply(experiments, function(x) {
  59. path <- x$path
  60. nums <- gsub("[^0-9]", "", basename(path))
  61. as.integer(nums)
  62. })
  63. # Sort the experiments based on the trailing numbers
  64. sorted_experiments <- experiments[order(trailing_numbers)]
  65. list(
  66. out_dir = out_dir,
  67. sgd_gene_list = sgd_gene_list,
  68. easy_results_file = easy_results_file,
  69. experiments = sorted_experiments
  70. )
  71. }
  72. args <- parse_arguments()
  73. # Should we keep output in exp dirs or combine in the study output dir?
  74. # dir.create(file.path(args$out_dir, "zscores"), showWarnings = FALSE)
  75. # dir.create(file.path(args$out_dir, "zscores", "qc"), showWarnings = FALSE)
  76. theme_publication <- function(base_size = 14, base_family = "sans", legend_position = NULL) {
  77. # Ensure that legend_position has a valid value or default to "none"
  78. legend_position <- if (is.null(legend_position) || length(legend_position) == 0) "none" else legend_position
  79. theme_foundation <- ggthemes::theme_foundation(base_size = base_size, base_family = base_family)
  80. theme_foundation %+replace%
  81. theme(
  82. plot.title = element_text(face = "bold", size = rel(1.6), hjust = 0.5),
  83. text = element_text(),
  84. panel.background = element_blank(),
  85. plot.background = element_blank(),
  86. panel.border = element_blank(),
  87. axis.title = element_text(face = "bold", size = rel(1.4)),
  88. axis.title.y = element_text(angle = 90, vjust = 2),
  89. axis.text = element_text(size = rel(1.2)),
  90. axis.line = element_line(colour = "black"),
  91. panel.grid.major = element_line(colour = "#f0f0f0"),
  92. panel.grid.minor = element_blank(),
  93. legend.key = element_rect(colour = NA),
  94. legend.position = legend_position,
  95. legend.direction =
  96. if (legend_position == "right") {
  97. "vertical"
  98. } else if (legend_position == "bottom") {
  99. "horizontal"
  100. } else {
  101. NULL # No legend direction if position is "none" or other values
  102. },
  103. legend.spacing = unit(0, "cm"),
  104. legend.title = element_text(face = "italic", size = rel(1.3)),
  105. legend.text = element_text(size = rel(1.2)),
  106. plot.margin = unit(c(10, 5, 5, 5), "mm")
  107. )
  108. }
  109. scale_fill_publication <- function(...) {
  110. discrete_scale("fill", "Publication", manual_pal(values = c(
  111. "#386cb0", "#fdb462", "#7fc97f", "#ef3b2c", "#662506",
  112. "#a6cee3", "#fb9a99", "#984ea3", "#ffff33"
  113. )), ...)
  114. }
  115. scale_colour_publication <- function(...) {
  116. discrete_scale("colour", "Publication", manual_pal(values = c(
  117. "#386cb0", "#fdb462", "#7fc97f", "#ef3b2c", "#662506",
  118. "#a6cee3", "#fb9a99", "#984ea3", "#ffff33"
  119. )), ...)
  120. }
  121. # Load the initial dataframe from the easy_results_file
  122. load_and_filter_data <- function(easy_results_file, sd = 3) {
  123. df <- read.delim(easy_results_file, skip = 2, as.is = TRUE, row.names = 1, strip.white = TRUE)
  124. df <- df %>%
  125. filter(!(.[[1]] %in% c("", "Scan"))) %>%
  126. filter(!is.na(ORF) & ORF != "" & !Gene %in% c("BLANK", "Blank", "blank") & Drug != "BMH21") %>%
  127. # Rename columns
  128. rename(L = l, num = Num., AUC = AUC96, scan = Scan, last_bg = LstBackgrd, first_bg = X1stBackgrd) %>%
  129. mutate(
  130. across(c(Col, Row, num, L, K, r, scan, AUC, last_bg, first_bg), as.numeric),
  131. delta_bg = last_bg - first_bg,
  132. delta_bg_tolerance = mean(delta_bg, na.rm = TRUE) + (sd * sd(delta_bg, na.rm = TRUE)),
  133. NG = if_else(L == 0 & !is.na(L), 1, 0),
  134. DB = if_else(delta_bg >= delta_bg_tolerance, 1, 0),
  135. SM = 0,
  136. OrfRep = if_else(ORF == "YDL227C", "YDL227C", OrfRep), # should these be hardcoded?
  137. conc_num = as.numeric(gsub("[^0-9\\.]", "", Conc)),
  138. conc_num_factor = as.numeric(as.factor(conc_num)) - 1, # for legacy purposes
  139. conc_num_factor_factor = as.factor(conc_num)
  140. )
  141. return(df)
  142. }
  143. update_gene_names <- function(df, sgd_gene_list) {
  144. genes <- read.delim(file = sgd_gene_list, quote = "", header = FALSE,
  145. colClasses = c(rep("NULL", 3), rep("character", 2), rep("NULL", 11)))
  146. gene_map <- setNames(genes$V5, genes$V4) # ORF to GeneName mapping
  147. df <- df %>%
  148. mutate(
  149. mapped_genes = gene_map[ORF],
  150. Gene = if_else(is.na(mapped_genes) | OrfRep == "YDL227C", Gene, mapped_genes),
  151. Gene = if_else(Gene == "" | Gene == "OCT1", OrfRep, Gene) # Handle invalid names
  152. )
  153. return(df)
  154. }
  155. calculate_summary_stats <- function(df, variables, group_vars) {
  156. summary_stats <- df %>%
  157. group_by(across(all_of(group_vars))) %>%
  158. summarise(
  159. N = n(),
  160. across(all_of(variables),
  161. list(
  162. mean = ~ mean(.x, na.rm = TRUE),
  163. median = ~ median(.x, na.rm = TRUE),
  164. max = ~ ifelse(all(is.na(.x)), NA, max(.x, na.rm = TRUE)),
  165. min = ~ ifelse(all(is.na(.x)), NA, min(.x, na.rm = TRUE)),
  166. sd = ~ sd(.x, na.rm = TRUE),
  167. se = ~ sd(.x, na.rm = TRUE) / sqrt(n() - 1)
  168. ),
  169. .names = "{.fn}_{.col}"
  170. ),
  171. .groups = "drop"
  172. )
  173. # Create a cleaned version of df that doesn't overlap with summary_stats
  174. df_cleaned <- df %>%
  175. select(-any_of(setdiff(intersect(names(df), names(summary_stats)), group_vars)))
  176. df_joined <- left_join(df_cleaned, summary_stats, by = group_vars)
  177. return(list(summary_stats = summary_stats, df_with_stats = df_joined))
  178. }
  179. calculate_interaction_scores <- function(df, df_bg, type, overlap_threshold = 2) {
  180. max_conc <- max(as.numeric(df$conc_num_factor), na.rm = TRUE)
  181. total_conc_num <- length(unique(df$conc_num))
  182. if (type == "reference") {
  183. bg_group_vars <- c("OrfRep", "Gene", "num", "Drug", "conc_num", "conc_num_factor", "conc_num_factor_factor")
  184. group_vars <- c("OrfRep", "Gene", "num", "Drug")
  185. } else if (type == "deletion") {
  186. bg_group_vars <- c("Drug", "conc_num", "conc_num_factor", "conc_num_factor_factor")
  187. group_vars <- c("OrfRep", "Gene", "Drug")
  188. }
  189. # Calculate WT statistics from df_bg
  190. wt_stats <- df_bg %>%
  191. group_by(across(all_of(bg_group_vars))) %>%
  192. summarise(
  193. WT_L = mean(mean_L, na.rm = TRUE),
  194. WT_sd_L = mean(sd_L, na.rm = TRUE),
  195. WT_K = mean(mean_K, na.rm = TRUE),
  196. WT_sd_K = mean(sd_K, na.rm = TRUE),
  197. WT_r = mean(mean_r, na.rm = TRUE),
  198. WT_sd_r = mean(sd_r, na.rm = TRUE),
  199. WT_AUC = mean(mean_AUC, na.rm = TRUE),
  200. WT_sd_AUC = mean(sd_AUC, na.rm = TRUE),
  201. .groups = "drop"
  202. )
  203. # Join WT statistics to df
  204. df <- df %>%
  205. left_join(wt_stats, by = c(bg_group_vars))
  206. # Compute mean values at zero concentration
  207. mean_zeroes <- df %>%
  208. filter(conc_num == 0) %>%
  209. group_by(across(all_of(group_vars))) %>%
  210. summarise(
  211. mean_L_zero = mean(mean_L, na.rm = TRUE),
  212. mean_K_zero = mean(mean_K, na.rm = TRUE),
  213. mean_r_zero = mean(mean_r, na.rm = TRUE),
  214. mean_AUC_zero = mean(mean_AUC, na.rm = TRUE),
  215. .groups = "drop"
  216. )
  217. df <- df %>%
  218. left_join(mean_zeroes, by = c(group_vars))
  219. # Calculate Raw Shifts and Z Shifts
  220. df <- df %>%
  221. mutate(
  222. Raw_Shift_L = mean_L_zero - WT_L,
  223. Raw_Shift_K = mean_K_zero - WT_K,
  224. Raw_Shift_r = mean_r_zero - WT_r,
  225. Raw_Shift_AUC = mean_AUC_zero - WT_AUC,
  226. Z_Shift_L = Raw_Shift_L / WT_sd_L,
  227. Z_Shift_K = Raw_Shift_K / WT_sd_K,
  228. Z_Shift_r = Raw_Shift_r / WT_sd_r,
  229. Z_Shift_AUC = Raw_Shift_AUC / WT_sd_AUC
  230. )
  231. calculations <- df %>%
  232. group_by(across(all_of(c(group_vars, "conc_num", "conc_num_factor", "conc_num_factor_factor")))) %>%
  233. mutate(
  234. NG_sum = sum(NG, na.rm = TRUE),
  235. DB_sum = sum(DB, na.rm = TRUE),
  236. SM_sum = sum(SM, na.rm = TRUE),
  237. # Expected values
  238. Exp_L = WT_L + Raw_Shift_L,
  239. Exp_K = WT_K + Raw_Shift_K,
  240. Exp_r = WT_r + Raw_Shift_r,
  241. Exp_AUC = WT_AUC + Raw_Shift_AUC,
  242. # Deltas
  243. Delta_L = mean_L - Exp_L,
  244. Delta_K = mean_K - Exp_K,
  245. Delta_r = mean_r - Exp_r,
  246. Delta_AUC = mean_AUC - Exp_AUC,
  247. # Adjust deltas for NG and SM
  248. Delta_L = if_else(NG == 1, mean_L - WT_L, Delta_L),
  249. Delta_K = if_else(NG == 1, mean_K - WT_K, Delta_K),
  250. Delta_r = if_else(NG == 1, mean_r - WT_r, Delta_r),
  251. Delta_AUC = if_else(NG == 1, mean_AUC - WT_AUC, Delta_AUC),
  252. Delta_L = if_else(SM == 1, mean_L - WT_L, Delta_L),
  253. # Calculate Z-scores
  254. Zscore_L = Delta_L / WT_sd_L,
  255. Zscore_K = Delta_K / WT_sd_K,
  256. Zscore_r = Delta_r / WT_sd_r,
  257. Zscore_AUC = Delta_AUC / WT_sd_AUC
  258. ) %>%
  259. ungroup()
  260. calculations <- calculations %>%
  261. group_by(across(all_of(group_vars))) %>%
  262. mutate(
  263. lm_L = map2(.x = Delta_L, .y = conc_num_factor, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  264. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  265. } else {
  266. lm(.x ~ .y) %>% {
  267. list(
  268. intercept = coef(.)[1],
  269. slope = coef(.)[2],
  270. r_squared = summary(.)$r.squared,
  271. score = max_conc * coef(.)[2] + coef(.)[1]
  272. )
  273. }
  274. }),
  275. lm_K = map2(.x = Delta_K, .y = conc_num_factor, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  276. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  277. } else {
  278. lm(.x ~ .y) %>% {
  279. list(
  280. intercept = coef(.)[1],
  281. slope = coef(.)[2],
  282. r_squared = summary(.)$r.squared,
  283. score = max_conc * coef(.)[2] + coef(.)[1]
  284. )
  285. }
  286. }),
  287. lm_r = map2(.x = Delta_r, .y = conc_num_factor, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  288. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  289. } else {
  290. lm(.x ~ .y) %>% {
  291. list(
  292. intercept = coef(.)[1],
  293. slope = coef(.)[2],
  294. r_squared = summary(.)$r.squared,
  295. score = max_conc * coef(.)[2] + coef(.)[1]
  296. )
  297. }
  298. }),
  299. lm_AUC = map2(.x = Delta_AUC, .y = conc_num_factor, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  300. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  301. } else {
  302. lm(.x ~ .y) %>% {
  303. list(
  304. intercept = coef(.)[1],
  305. slope = coef(.)[2],
  306. r_squared = summary(.)$r.squared,
  307. score = max_conc * coef(.)[2] + coef(.)[1]
  308. )
  309. }
  310. }),
  311. # Extract coefficients and statistics for each model
  312. lm_intercept_L = map_dbl(lm_L, "intercept"),
  313. lm_slope_L = map_dbl(lm_L, "slope"),
  314. R_Squared_L = map_dbl(lm_L, "r_squared"),
  315. lm_Score_L = map_dbl(lm_L, "score"),
  316. lm_intercept_K = map_dbl(lm_K, "intercept"),
  317. lm_slope_K = map_dbl(lm_K, "slope"),
  318. R_Squared_K = map_dbl(lm_K, "r_squared"),
  319. lm_Score_K = map_dbl(lm_K, "score"),
  320. lm_intercept_r = map_dbl(lm_r, "intercept"),
  321. lm_slope_r = map_dbl(lm_r, "slope"),
  322. R_Squared_r = map_dbl(lm_r, "r_squared"),
  323. lm_Score_r = map_dbl(lm_r, "score"),
  324. lm_intercept_AUC = map_dbl(lm_AUC, "intercept"),
  325. lm_slope_AUC = map_dbl(lm_AUC, "slope"),
  326. R_Squared_AUC = map_dbl(lm_AUC, "r_squared"),
  327. lm_Score_AUC = map_dbl(lm_AUC, "score")
  328. ) %>%
  329. select(-lm_L, -lm_K, -lm_r, -lm_AUC) %>%
  330. ungroup()
  331. # For interaction plot error bars
  332. delta_means_sds <- calculations %>%
  333. group_by(across(all_of(group_vars))) %>%
  334. summarise(
  335. mean_Delta_L = mean(Delta_L, na.rm = TRUE),
  336. mean_Delta_K = mean(Delta_K, na.rm = TRUE),
  337. mean_Delta_r = mean(Delta_r, na.rm = TRUE),
  338. mean_Delta_AUC = mean(Delta_AUC, na.rm = TRUE),
  339. sd_Delta_L = sd(Delta_L, na.rm = TRUE),
  340. sd_Delta_K = sd(Delta_K, na.rm = TRUE),
  341. sd_Delta_r = sd(Delta_r, na.rm = TRUE),
  342. sd_Delta_AUC = sd(Delta_AUC, na.rm = TRUE),
  343. .groups = "drop"
  344. )
  345. calculations <- calculations %>%
  346. left_join(delta_means_sds, by = group_vars)
  347. # Summary statistics for lm scores
  348. calculations <- calculations %>%
  349. mutate(
  350. lm_mean_L = mean(lm_Score_L, na.rm = TRUE),
  351. lm_sd_L = sd(lm_Score_L, na.rm = TRUE),
  352. lm_mean_K = mean(lm_Score_K, na.rm = TRUE),
  353. lm_sd_K = sd(lm_Score_K, na.rm = TRUE),
  354. lm_mean_r = mean(lm_Score_r, na.rm = TRUE),
  355. lm_sd_r = sd(lm_Score_r, na.rm = TRUE),
  356. lm_mean_AUC = mean(lm_Score_AUC, na.rm = TRUE),
  357. lm_sd_AUC = sd(lm_Score_AUC, na.rm = TRUE),
  358. Z_lm_L = (lm_Score_L - lm_mean_L) / lm_sd_L,
  359. Z_lm_K = (lm_Score_K - lm_mean_K) / lm_sd_K,
  360. Z_lm_r = (lm_Score_r - lm_mean_r) / lm_sd_r,
  361. Z_lm_AUC = (lm_Score_AUC - lm_mean_AUC) / lm_sd_AUC
  362. )
  363. # Build summary stats (interactions)
  364. interactions <- calculations %>%
  365. group_by(across(all_of(group_vars))) %>%
  366. summarise(
  367. num_non_removed_concs = total_conc_num - sum(DB, na.rm = TRUE) - 1,
  368. Sum_Z_Score_L = sum(Zscore_L, na.rm = TRUE),
  369. Sum_Z_Score_K = sum(Zscore_K, na.rm = TRUE),
  370. Sum_Z_Score_r = sum(Zscore_r, na.rm = TRUE),
  371. Sum_Z_Score_AUC = sum(Zscore_AUC, na.rm = TRUE),
  372. Avg_Zscore_L = Sum_Z_Score_L / first(num_non_removed_concs),
  373. Avg_Zscore_K = Sum_Z_Score_K / first(num_non_removed_concs),
  374. Avg_Zscore_r = Sum_Z_Score_r / first(num_non_removed_concs),
  375. Avg_Zscore_AUC = Sum_Z_Score_AUC / first(num_non_removed_concs),
  376. # R_Squared
  377. R_Squared_L = first(R_Squared_L),
  378. R_Squared_K = first(R_Squared_K),
  379. R_Squared_r = first(R_Squared_r),
  380. R_Squared_AUC = first(R_Squared_AUC),
  381. # Interaction Z-scores
  382. Z_lm_L = first(Z_lm_L),
  383. Z_lm_K = first(Z_lm_K),
  384. Z_lm_r = first(Z_lm_r),
  385. Z_lm_AUC = first(Z_lm_AUC),
  386. # Raw Shifts
  387. Raw_Shift_L = first(Raw_Shift_L),
  388. Raw_Shift_K = first(Raw_Shift_K),
  389. Raw_Shift_r = first(Raw_Shift_r),
  390. Raw_Shift_AUC = first(Raw_Shift_AUC),
  391. # Z Shifts
  392. Z_Shift_L = first(Z_Shift_L),
  393. Z_Shift_K = first(Z_Shift_K),
  394. Z_Shift_r = first(Z_Shift_r),
  395. Z_Shift_AUC = first(Z_Shift_AUC),
  396. # Gene-Gene Interaction
  397. lm_Score_L = first(lm_Score_L),
  398. lm_Score_K = first(lm_Score_K),
  399. lm_Score_r = first(lm_Score_r),
  400. lm_Score_AUC = first(lm_Score_AUC),
  401. # NG, DB, SM values
  402. NG_sum_int = sum(NG),
  403. DB_sum_int = sum(DB),
  404. SM_sum_int = sum(SM),
  405. .groups = "drop"
  406. ) %>%
  407. arrange(desc(Z_lm_L), desc(NG_sum_int))
  408. # Deletion data ranking and linear modeling
  409. if (type == "deletion") {
  410. interactions <- interactions %>%
  411. mutate(
  412. Avg_Zscore_L_adjusted = ifelse(is.na(Avg_Zscore_L), 0.001, Avg_Zscore_L),
  413. Avg_Zscore_K_adjusted = ifelse(is.na(Avg_Zscore_K), 0.001, Avg_Zscore_K),
  414. Avg_Zscore_r_adjusted = ifelse(is.na(Avg_Zscore_r), 0.001, Avg_Zscore_r),
  415. Avg_Zscore_AUC_adjusted = ifelse(is.na(Avg_Zscore_AUC), 0.001, Avg_Zscore_AUC),
  416. Z_lm_L_adjusted = ifelse(is.na(Z_lm_L), 0.001, Z_lm_L),
  417. Z_lm_K_adjusted = ifelse(is.na(Z_lm_K), 0.001, Z_lm_K),
  418. Z_lm_r_adjusted = ifelse(is.na(Z_lm_r), 0.001, Z_lm_r),
  419. Z_lm_AUC_adjusted = ifelse(is.na(Z_lm_AUC), 0.001, Z_lm_AUC)
  420. ) %>%
  421. mutate(
  422. Rank_L = rank(Avg_Zscore_L_adjusted),
  423. Rank_K = rank(Avg_Zscore_K_adjusted),
  424. Rank_r = rank(Avg_Zscore_r_adjusted),
  425. Rank_AUC = rank(Avg_Zscore_AUC_adjusted),
  426. Rank_lm_L = rank(Z_lm_L_adjusted),
  427. Rank_lm_K = rank(Z_lm_K_adjusted),
  428. Rank_lm_r = rank(Z_lm_r_adjusted),
  429. Rank_lm_AUC = rank(Z_lm_AUC_adjusted)
  430. ) %>%
  431. mutate(
  432. lm_R_squared_rank_L = summary(lm(Rank_lm_L ~ Rank_L, data = .))$r.squared,
  433. lm_R_squared_rank_K = summary(lm(Rank_lm_K ~ Rank_K, data = .))$r.squared,
  434. lm_R_squared_rank_r = summary(lm(Rank_lm_r ~ Rank_r, data = .))$r.squared,
  435. lm_R_squared_rank_AUC = summary(lm(Rank_lm_AUC ~ Rank_AUC, data = .))$r.squared
  436. )
  437. # Add overlap threshold categories based on Z-lm and Avg-Z scores
  438. interactions <- interactions %>%
  439. filter(!is.na(Z_lm_L) | !is.na(Avg_Zscore_L)) %>%
  440. mutate(
  441. Overlap = case_when(
  442. Z_lm_L >= overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Enhancer Both",
  443. Z_lm_L <= -overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Suppressor Both",
  444. Z_lm_L >= overlap_threshold & Avg_Zscore_L <= overlap_threshold ~ "Deletion Enhancer lm only",
  445. Z_lm_L <= overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Enhancer Avg Zscore only",
  446. Z_lm_L <= -overlap_threshold & Avg_Zscore_L >= -overlap_threshold ~ "Deletion Suppressor lm only",
  447. Z_lm_L >= -overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Suppressor Avg Zscore only",
  448. Z_lm_L >= overlap_threshold & Avg_Zscore_L <= -overlap_threshold ~ "Deletion Enhancer lm, Deletion Suppressor Avg Zscore",
  449. Z_lm_L <= -overlap_threshold & Avg_Zscore_L >= overlap_threshold ~ "Deletion Suppressor lm, Deletion Enhancer Avg Zscore",
  450. TRUE ~ "No Effect"
  451. ),
  452. lm_L = map2(.x = Z_lm_L, .y = Avg_Zscore_L, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  453. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  454. } else {
  455. lm(.y ~ .x) %>% {
  456. list(
  457. intercept = coef(.)[1],
  458. slope = coef(.)[2],
  459. r_squared = summary(.)$r.squared,
  460. score = max_conc * coef(.)[2] + coef(.)[1]
  461. )
  462. }
  463. }),
  464. lm_K = map2(.x = Z_lm_K, .y = Avg_Zscore_K, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  465. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  466. } else {
  467. lm(.y ~ .x) %>% {
  468. list(
  469. intercept = coef(.)[1],
  470. slope = coef(.)[2],
  471. r_squared = summary(.)$r.squared,
  472. score = max_conc * coef(.)[2] + coef(.)[1]
  473. )
  474. }
  475. }),
  476. lm_r = map2(.x = Z_lm_r, .y = Avg_Zscore_r, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  477. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  478. } else {
  479. lm(.y ~ .x) %>% {
  480. list(
  481. intercept = coef(.)[1],
  482. slope = coef(.)[2],
  483. r_squared = summary(.)$r.squared,
  484. score = max_conc * coef(.)[2] + coef(.)[1]
  485. )
  486. }
  487. }),
  488. lm_AUC = map2(.x = Z_lm_AUC, .y = Avg_Zscore_AUC, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  489. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  490. } else {
  491. lm(.y ~ .x) %>% {
  492. list(
  493. intercept = coef(.)[1],
  494. slope = coef(.)[2],
  495. r_squared = summary(.)$r.squared,
  496. score = max_conc * coef(.)[2] + coef(.)[1]
  497. )
  498. }
  499. }),
  500. # For correlation plots
  501. Z_lm_K_L = map2(.x = Z_lm_K, .y = Z_lm_L, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  502. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  503. } else {
  504. lm(.y ~ .x) %>% {
  505. list(
  506. intercept = coef(.)[1],
  507. slope = coef(.)[2],
  508. r_squared = summary(.)$r.squared,
  509. score = max_conc * coef(.)[2] + coef(.)[1]
  510. )
  511. }
  512. }),
  513. Z_lm_r_L = map2(.x = Z_lm_r, .y = Z_lm_L, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  514. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  515. } else {
  516. lm(.y ~ .x) %>% {
  517. list(
  518. intercept = coef(.)[1],
  519. slope = coef(.)[2],
  520. r_squared = summary(.)$r.squared,
  521. score = max_conc * coef(.)[2] + coef(.)[1]
  522. )
  523. }
  524. }),
  525. Z_lm_R_AUC_L = map2(.x = Z_lm_AUC, .y = Z_lm_L, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  526. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  527. } else {
  528. lm(.y ~ .x) %>% {
  529. list(
  530. intercept = coef(.)[1],
  531. slope = coef(.)[2],
  532. r_squared = summary(.)$r.squared,
  533. score = max_conc * coef(.)[2] + coef(.)[1]
  534. )
  535. }
  536. }),
  537. Z_lm_R_r_K = map2(.x = Z_lm_r, .y = Z_lm_K, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  538. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  539. } else {
  540. lm(.y ~ .x) %>% {
  541. list(
  542. intercept = coef(.)[1],
  543. slope = coef(.)[2],
  544. r_squared = summary(.)$r.squared,
  545. score = max_conc * coef(.)[2] + coef(.)[1]
  546. )
  547. }
  548. }),
  549. Z_lm_R_AUC_K = map2(.x = Z_lm_AUC, .y = Z_lm_K, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  550. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  551. } else {
  552. lm(.y ~ .x) %>% {
  553. list(
  554. intercept = coef(.)[1],
  555. slope = coef(.)[2],
  556. r_squared = summary(.)$r.squared,
  557. score = max_conc * coef(.)[2] + coef(.)[1]
  558. )
  559. }
  560. }),
  561. Z_lm_R_AUC_r = map2(.x = Z_lm_AUC, .y = Z_lm_r, ~ if (all(is.na(.x)) || all(is.na(.y)) || length(.x[!is.na(.x)]) == 0) {
  562. list(intercept = NA, slope = NA, r_squared = NA, score = NA)
  563. } else {
  564. lm(.y ~ .x) %>% {
  565. list(
  566. intercept = coef(.)[1],
  567. slope = coef(.)[2],
  568. r_squared = summary(.)$r.squared,
  569. score = max_conc * coef(.)[2] + coef(.)[1]
  570. )
  571. }
  572. }),
  573. # Extract coefficients and statistics for each model
  574. lm_rank_intercept_L = map_dbl(lm_L, "intercept"),
  575. lm_rank_slope_L = map_dbl(lm_L, "slope"),
  576. R_Squared_L = map_dbl(lm_L, "r_squared"),
  577. lm_Score_L = map_dbl(lm_L, "score"),
  578. lm_intercept_K = map_dbl(lm_K, "intercept"),
  579. lm_slope_K = map_dbl(lm_K, "slope"),
  580. R_Squared_K = map_dbl(lm_K, "r_squared"),
  581. lm_Score_K = map_dbl(lm_K, "score"),
  582. lm_intercept_r = map_dbl(lm_r, "intercept"),
  583. lm_slope_r = map_dbl(lm_r, "slope"),
  584. R_Squared_r = map_dbl(lm_r, "r_squared"),
  585. lm_Score_r = map_dbl(lm_r, "score"),
  586. lm_intercept_AUC = map_dbl(lm_AUC, "intercept"),
  587. lm_slope_AUC = map_dbl(lm_AUC, "slope"),
  588. R_Squared_AUC = map_dbl(lm_AUC, "r_squared"),
  589. lm_Score_AUC = map_dbl(lm_AUC, "score"),
  590. Z_lm_intercept_K_L = map_dbl(Z_lm_K_L, "intercept"),
  591. Z_lm_slope_K_L = map_dbl(Z_lm_K_L, "slope"),
  592. Z_lm_R_squared_K_L = map_dbl(Z_lm_K_L, "r_squared"),
  593. Z_lm_Score_K_L = map_dbl(Z_lm_K_L, "score"),
  594. Z_lm_intercept_r_L = map_dbl(Z_lm_r_L, "intercept"),
  595. Z_lm_slope_r_L = map_dbl(Z_lm_r_L, "slope"),
  596. Z_lm_R_squared_r_L = map_dbl(Z_lm_r_L, "r_squared"),
  597. Z_lm_Score_r_L = map_dbl(Z_lm_r_L, "score"),
  598. Z_lm_intercept_R_AUC_L = map_dbl(Z_lm_R_AUC_L, "intercept"),
  599. Z_lm_slope_R_AUC_L = map_dbl(Z_lm_R_AUC_L, "slope"),
  600. Z_lm_R_squared_R_AUC_L = map_dbl(Z_lm_R_AUC_L, "r_squared"),
  601. Z_lm_Score_R_AUC_L = map_dbl(Z_lm_R_AUC_L, "score"),
  602. Z_lm_intercept_R_r_K = map_dbl(Z_lm_R_r_K, "intercept"),
  603. Z_lm_slope_R_r_K = map_dbl(Z_lm_R_r_K, "slope"),
  604. Z_lm_R_squared_R_r_K = map_dbl(Z_lm_R_r_K, "r_squared"),
  605. Z_lm_Score_R_r_K = map_dbl(Z_lm_R_r_K, "score"),
  606. Z_lm_intercept_R_AUC_K = map_dbl(Z_lm_R_AUC_K, "intercept"),
  607. Z_lm_slope_R_AUC_K = map_dbl(Z_lm_R_AUC_K, "slope"),
  608. Z_lm_R_squared_R_AUC_K = map_dbl(Z_lm_R_AUC_K, "r_squared"),
  609. Z_lm_Score_R_AUC_K = map_dbl(Z_lm_R_AUC_K, "score"),
  610. Z_lm_intercept_R_AUC_r = map_dbl(Z_lm_R_AUC_r, "intercept"),
  611. Z_lm_slope_R_AUC_r = map_dbl(Z_lm_R_AUC_r, "slope"),
  612. Z_lm_R_squared_R_AUC_r = map_dbl(Z_lm_R_AUC_r, "r_squared"),
  613. Z_lm_Score_R_AUC_r = map_dbl(Z_lm_R_AUC_r, "score")
  614. ) %>%
  615. select(
  616. -lm_L, -lm_K, -lm_r, -lm_AUC, -Z_lm_K_L, -Z_lm_r_L, -Z_lm_R_AUC_L,
  617. -Z_lm_R_r_K, -Z_lm_R_AUC_K, -Z_lm_R_AUC_r)
  618. } # end deletion-specific block
  619. # Create the final calculations and interactions dataframes with only required columns for csv output
  620. df_calculations <- calculations %>%
  621. select(
  622. all_of(group_vars),
  623. conc_num, conc_num_factor, conc_num_factor_factor, N,
  624. mean_L, median_L, sd_L, se_L,
  625. mean_K, median_K, sd_K, se_K,
  626. mean_r, median_r, sd_r, se_r,
  627. mean_AUC, median_AUC, sd_AUC, se_AUC,
  628. Raw_Shift_L, Raw_Shift_K, Raw_Shift_r, Raw_Shift_AUC,
  629. Z_Shift_L, Z_Shift_K, Z_Shift_r, Z_Shift_AUC,
  630. WT_L, WT_K, WT_r, WT_AUC,
  631. WT_sd_L, WT_sd_K, WT_sd_r, WT_sd_AUC,
  632. Exp_L, Exp_K, Exp_r, Exp_AUC,
  633. Delta_L, Delta_K, Delta_r, Delta_AUC,
  634. mean_Delta_L, mean_Delta_K, mean_Delta_r, mean_Delta_AUC,
  635. Zscore_L, Zscore_K, Zscore_r, Zscore_AUC,
  636. NG_sum, DB_sum, SM_sum
  637. ) %>%
  638. rename(NG = NG_sum, DB = DB_sum, SM = SM_sum)
  639. df_interactions <- interactions %>%
  640. select(
  641. all_of(group_vars),
  642. Avg_Zscore_L, Avg_Zscore_K, Avg_Zscore_r, Avg_Zscore_AUC,
  643. Sum_Z_Score_L, Sum_Z_Score_K, Sum_Z_Score_r, Sum_Z_Score_AUC,
  644. Z_lm_L, Z_lm_K, Z_lm_r, Z_lm_AUC,
  645. Raw_Shift_L, Raw_Shift_K, Raw_Shift_r, Raw_Shift_AUC,
  646. Z_Shift_L, Z_Shift_K, Z_Shift_r, Z_Shift_AUC,
  647. lm_Score_L, lm_Score_K, lm_Score_r, lm_Score_AUC,
  648. R_Squared_L, R_Squared_K, R_Squared_r, R_Squared_AUC,
  649. NG_sum_int, DB_sum_int, SM_sum_int
  650. ) %>%
  651. rename(NG = NG_sum_int, DB = DB_sum_int, SM = SM_sum_int)
  652. # Avoid column collision on left join for overlapping variables
  653. calculations_no_overlap <- calculations %>%
  654. select(-any_of(c("DB", "NG", "SM",
  655. # Don't need these anywhere so easier to remove
  656. "Raw_Shift_L", "Raw_Shift_K", "Raw_Shift_r", "Raw_Shift_AUC",
  657. "R_Squared_L", "R_Squared_K", "R_Squared_r", "R_Squared_AUC",
  658. # we need these for the interactions but the original code has the same names in both datasets
  659. "Z_Shift_L", "Z_Shift_K", "Z_Shift_r", "Z_Shift_AUC"
  660. )))
  661. full_data <- calculations_no_overlap %>%
  662. left_join(interactions, by = group_vars)
  663. # Return final dataframes
  664. return(list(
  665. calculations = df_calculations,
  666. interactions = df_interactions,
  667. full_data = full_data
  668. ))
  669. }
  670. generate_and_save_plots <- function(out_dir, filename, plot_configs, page_width = 12, page_height = 8) {
  671. message("Generating ", filename, ".pdf and ", filename, ".html")
  672. plot_groups <- if ("plots" %in% names(plot_configs)) {
  673. list(plot_configs) # Single group
  674. } else {
  675. plot_configs # Multiple groups
  676. }
  677. pdf(file.path(out_dir, paste0(filename, ".pdf")), width = page_width, height = page_height)
  678. for (group in plot_groups) {
  679. static_plots <- list()
  680. plotly_plots <- list()
  681. for (i in seq_along(group$plots)) {
  682. config <- group$plots[[i]]
  683. df <- config$df
  684. # Filter NAs
  685. if (!is.null(config$filter_na) && config$filter_na) {
  686. df <- df %>%
  687. filter(!is.na(!!sym(config$y_var)))
  688. }
  689. # TODO for now skip all NA plots NA data
  690. # Eventually add to own or filter_na block so we can handle selectively
  691. if (nrow(df) == 0) {
  692. message("Insufficient data for plot:", config$title)
  693. next # skip plot if insufficient data is available
  694. }
  695. # Create initial aes mappings for all plot types
  696. aes_mapping <- aes(x = !!sym(config$x_var)) # required
  697. if (!is.null(config$y_var)) {
  698. aes_mapping <- modifyList(aes_mapping, aes(y = !!sym(config$y_var))) # optional for density/bar plots
  699. }
  700. if (!is.null(config$color_var)) {
  701. aes_mapping <- modifyList(aes_mapping, aes(color = !!sym(config$color_var))) # dynamic color_var
  702. } else if (!is.null(config$color)) {
  703. aes_mapping <- modifyList(aes_mapping, aes(color = config$color)) # static color
  704. }
  705. if (config$plot_type == "bar" && !is.null(config$color_var)) {
  706. aes_mapping <- modifyList(aes_mapping, aes(fill = !!sym(config$color_var))) # only fill bar plots
  707. }
  708. # Begin plot generation
  709. plot <- ggplot(df, aes_mapping) + theme_publication(legend_position = config$legend_position)
  710. plot <- switch(config$plot_type,
  711. "scatter" = generate_scatter_plot(plot, config),
  712. "box" = generate_boxplot(plot, config),
  713. "density" = plot + geom_density(),
  714. "bar" = plot + geom_bar(),
  715. plot # default
  716. )
  717. if (!is.null(config$title)) {
  718. plot <- plot + ggtitle(config$title)
  719. if (!is.null(config$title_size)) {
  720. plot <- plot + theme(plot.title = element_text(size = config$title_size))
  721. }
  722. }
  723. if (!is.null(config$x_label)) plot <- plot + xlab(config$x_label)
  724. if (!is.null(config$y_label)) plot <- plot + ylab(config$y_label)
  725. if (!is.null(config$coord_cartesian)) plot <- plot + coord_cartesian(ylim = config$coord_cartesian)
  726. #plotly_plot <- suppressWarnings(plotly::ggplotly(plot))
  727. static_plots[[i]] <- plot
  728. #plotly_plots[[i]] <- plotly_plot
  729. }
  730. grid_layout <- group$grid_layout
  731. if (!is.null(grid_layout)) {
  732. if (is.null(grid_layout$ncol)) {
  733. grid_layout$ncol <- 1
  734. }
  735. if (!is.null(grid_layout$ncol) && is.null(grid_layout$nrow)) {
  736. num_plots <- length(static_plots)
  737. grid_layout$nrow <- ceiling(num_plots / grid_layout$ncol)
  738. }
  739. # total_spots <- grid_layout$nrow * grid_layout$ncol
  740. # num_plots <- length(static_plots)
  741. # if (num_plots < total_spots) {
  742. # message("Filling ", total_spots - num_plots, " empty spots with nullGrob()")
  743. # static_plots <- c(static_plots, replicate(total_spots - num_plots, nullGrob(), simplify = FALSE))
  744. # }
  745. grid.arrange(
  746. grobs = static_plots,
  747. ncol = grid_layout$ncol,
  748. nrow = grid_layout$nrow
  749. )
  750. } else {
  751. for (plot in static_plots) {
  752. print(plot)
  753. }
  754. }
  755. }
  756. dev.off()
  757. # out_html_file <- file.path(out_dir, paste0(filename, ".html"))
  758. # message("Saving combined HTML file: ", out_html_file)
  759. # htmltools::save_html(
  760. # htmltools::tagList(plotly_plots),
  761. # file = out_html_file
  762. # )
  763. }
  764. generate_scatter_plot <- function(plot, config) {
  765. # Define the points
  766. shape <- if (!is.null(config$shape)) config$shape else 3
  767. size <- if (!is.null(config$size)) config$size else 1.5
  768. position <-
  769. if (!is.null(config$position) && config$position == "jitter") {
  770. position_jitter(width = 0.4, height = 0.1)
  771. } else {
  772. "identity"
  773. }
  774. plot <- plot + geom_point(
  775. shape = shape,
  776. size = size,
  777. position = position
  778. )
  779. # Add a cyan point for the reference data for correlation plots
  780. if (!is.null(config$cyan_points) && config$cyan_points) {
  781. plot <- plot + geom_point(
  782. aes(x = !!sym(config$x_var), y = !!sym(config$y_var)),
  783. data = config$df_reference,
  784. color = "cyan",
  785. shape = 3,
  786. size = 0.5
  787. )
  788. }
  789. # Add error bars if specified
  790. if (!is.null(config$error_bar) && config$error_bar) {
  791. # Check if custom columns are provided for y_mean and y_sd, or use the defaults
  792. y_mean_col <- if (!is.null(config$error_bar_params$y_mean_col)) {
  793. config$error_bar_params$y_mean_col
  794. } else {
  795. paste0("mean_", config$y_var)
  796. }
  797. y_sd_col <- if (!is.null(config$error_bar_params$y_sd_col)) {
  798. config$error_bar_params$y_sd_col
  799. } else {
  800. paste0("sd_", config$y_var)
  801. }
  802. # Use rlang to handle custom error bar calculations
  803. if (!is.null(config$error_bar_params$custom_error_bar)) {
  804. custom_ymin_expr <- rlang::parse_expr(config$error_bar_params$custom_error_bar$ymin)
  805. custom_ymax_expr <- rlang::parse_expr(config$error_bar_params$custom_error_bar$ymax)
  806. plot <- plot + geom_errorbar(
  807. aes(
  808. ymin = !!custom_ymin_expr,
  809. ymax = !!custom_ymax_expr
  810. ),
  811. color = config$error_bar_params$color,
  812. linewidth = ifelse(is.null(config$error_bar_params$linewidth), 0.1, config$error_bar_params$linewidth)
  813. )
  814. } else {
  815. # If no custom error bar formula, use the default or dynamic ones
  816. if (!is.null(config$color_var) && config$color_var %in% colnames(config$df)) {
  817. # Only use color_var if it's present in the dataframe
  818. plot <- plot + geom_errorbar(
  819. aes(
  820. ymin = !!sym(y_mean_col) - !!sym(y_sd_col),
  821. ymax = !!sym(y_mean_col) + !!sym(y_sd_col),
  822. color = !!sym(config$color_var)
  823. ),
  824. linewidth = 0.1
  825. )
  826. } else {
  827. # If color_var is missing, fall back to a default color or none
  828. plot <- plot + geom_errorbar(
  829. aes(
  830. ymin = !!sym(y_mean_col) - !!sym(y_sd_col),
  831. ymax = !!sym(y_mean_col) + !!sym(y_sd_col)
  832. ),
  833. color = config$error_bar_params$color, # use the provided color or default
  834. linewidth = ifelse(is.null(config$error_bar_params$linewidth), 0.1, config$error_bar_params$linewidth)
  835. )
  836. }
  837. }
  838. # Add the center point if the option is provided
  839. if (!is.null(config$error_bar_params$mean_point) && config$error_bar_params$mean_point) {
  840. if (!is.null(config$error_bar_params$color)) {
  841. plot <- plot + geom_point(
  842. aes(x = !!sym(config$x_var), y = !!sym(y_mean_col)),
  843. color = config$error_bar_params$color,
  844. shape = 16
  845. )
  846. } else {
  847. plot <- plot + geom_point(
  848. aes(x = !!sym(config$x_var), y = !!sym(y_mean_col)),
  849. shape = 16
  850. )
  851. }
  852. }
  853. }
  854. # Add linear regression line if specified
  855. if (!is.null(config$lm_line)) {
  856. # Extract necessary values
  857. intercept <- config$lm_line$intercept # required
  858. slope <- config$lm_line$slope # required
  859. xmin <- ifelse(!is.null(config$lm_line$xmin), config$lm_line$xmin, min(as.numeric(config$df[[config$x_var]])))
  860. xmax <- ifelse(!is.null(config$lm_line$xmax), config$lm_line$xmax, max(as.numeric(config$df[[config$x_var]])))
  861. color <- ifelse(!is.null(config$lm_line$color), config$lm_line$color, "blue")
  862. linewidth <- ifelse(!is.null(config$lm_line$linewidth), config$lm_line$linewidth, 1)
  863. ymin <- intercept + slope * xmin
  864. ymax <- intercept + slope * xmax
  865. # Ensure y-values are within y-limits (if any)
  866. if (!is.null(config$ylim_vals)) {
  867. ymin_within_limits <- ymin >= config$ylim_vals[1] && ymin <= config$ylim_vals[2]
  868. ymax_within_limits <- ymax >= config$ylim_vals[1] && ymax <= config$ylim_vals[2]
  869. # Adjust or skip based on whether the values fall within limits
  870. if (ymin_within_limits && ymax_within_limits) {
  871. plot <- plot + annotate(
  872. "segment",
  873. x = xmin,
  874. xend = xmax,
  875. y = ymin,
  876. yend = ymax,
  877. color = color,
  878. linewidth = linewidth,
  879. )
  880. } else {
  881. message("Skipping linear regression line due to y-values outside of limits")
  882. }
  883. } else {
  884. # If no y-limits are provided, proceed with the annotation
  885. plot <- plot + annotate(
  886. "segment",
  887. x = xmin,
  888. xend = xmax,
  889. y = ymin,
  890. yend = ymax,
  891. color = color,
  892. linewidth = linewidth
  893. )
  894. }
  895. }
  896. # Add SD Bands if specified
  897. if (!is.null(config$sd_band)) {
  898. plot <- plot +
  899. annotate(
  900. "rect",
  901. xmin = -Inf, xmax = Inf,
  902. ymin = config$sd_band, ymax = Inf,
  903. fill = ifelse(!is.null(config$fill_positive), config$fill_positive, "#542788"),
  904. alpha = ifelse(!is.null(config$alpha_positive), config$alpha_positive, 0.3)
  905. ) +
  906. annotate(
  907. "rect",
  908. xmin = -Inf, xmax = Inf,
  909. ymin = -config$sd_band, ymax = -Inf,
  910. fill = ifelse(!is.null(config$fill_negative), config$fill_negative, "orange"),
  911. alpha = ifelse(!is.null(config$alpha_negative), config$alpha_negative, 0.3)
  912. ) +
  913. geom_hline(
  914. yintercept = c(-config$sd_band, config$sd_band),
  915. color = ifelse(!is.null(config$hl_color), config$hl_color, "black")
  916. )
  917. }
  918. # # Add rectangles if specified
  919. # if (!is.null(config$rectangles)) {
  920. # for (rect in config$rectangles) {
  921. # plot <- plot + annotate(
  922. # "rect",
  923. # xmin = rect$xmin,
  924. # xmax = rect$xmax,
  925. # ymin = rect$ymin,
  926. # ymax = rect$ymax,
  927. # fill = ifelse(is.null(rect$fill), NA, rect$fill),
  928. # color = ifelse(is.null(rect$color), "black", rect$color),
  929. # alpha = ifelse(is.null(rect$alpha), 0.1, rect$alpha)
  930. # )
  931. # }
  932. # }
  933. # Customize X-axis if specified
  934. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  935. # Check if x_var is factor or character (for discrete x-axis)
  936. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  937. plot <- plot +
  938. scale_x_discrete(
  939. name = config$x_label,
  940. breaks = config$x_breaks,
  941. labels = config$x_labels
  942. )
  943. } else {
  944. plot <- plot +
  945. scale_x_continuous(
  946. name = config$x_label,
  947. breaks = config$x_breaks,
  948. labels = config$x_labels
  949. )
  950. }
  951. }
  952. # Set Y-axis limits if specified
  953. if (!is.null(config$ylim_vals)) {
  954. plot <- plot + scale_y_continuous(limits = config$ylim_vals)
  955. }
  956. return(plot)
  957. }
  958. generate_boxplot <- function(plot, config) {
  959. # Convert x_var to a factor within aes mapping
  960. plot <- plot + geom_boxplot(aes(x = factor(!!sym(config$x_var))))
  961. # Customize X-axis if specified
  962. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  963. # Check if x_var is factor or character (for discrete x-axis)
  964. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  965. plot <- plot +
  966. scale_x_discrete(
  967. name = config$x_label,
  968. breaks = config$x_breaks,
  969. labels = config$x_labels
  970. )
  971. } else {
  972. plot <- plot +
  973. scale_x_continuous(
  974. name = config$x_label,
  975. breaks = config$x_breaks,
  976. labels = config$x_labels
  977. )
  978. }
  979. }
  980. return(plot)
  981. }
  982. generate_plate_analysis_plot_configs <- function(variables, df_before = NULL, df_after = NULL,
  983. plot_type = "scatter", stages = c("before", "after")) {
  984. plot_configs <- list()
  985. for (var in variables) {
  986. for (stage in stages) {
  987. df_plot <- if (stage == "before") df_before else df_after
  988. # Check for non-finite values in the y-variable
  989. # df_plot_filtered <- df_plot %>% filter(is.finite(!!sym(var)))
  990. # Adjust settings based on plot_type
  991. plot_config <- list(
  992. df = df_plot,
  993. x_var = "scan",
  994. y_var = var,
  995. plot_type = plot_type,
  996. title = paste("Plate analysis by Drug Conc for", var, stage, "quality control"),
  997. color_var = "conc_num_factor_factor",
  998. size = 0.2,
  999. error_bar = (plot_type == "scatter"),
  1000. legend_position = "bottom",
  1001. filter_na = TRUE
  1002. )
  1003. # Add config to plots list
  1004. plot_configs <- append(plot_configs, list(plot_config))
  1005. }
  1006. }
  1007. return(list(plots = plot_configs))
  1008. }
  1009. generate_interaction_plot_configs <- function(df_summary, df_interactions, type) {
  1010. # Define the y-limits for the plots
  1011. limits_map <- list(
  1012. L = c(0, 130),
  1013. K = c(-20, 160),
  1014. r = c(0, 1),
  1015. AUC = c(0, 12500)
  1016. )
  1017. stats_plot_configs <- list()
  1018. stats_boxplot_configs <- list()
  1019. delta_plot_configs <- list()
  1020. # Overall statistics plots
  1021. OrfRep <- first(df_summary$OrfRep) # this should correspond to the reference strain
  1022. for (plot_type in c("scatter", "box")) {
  1023. for (var in names(limits_map)) {
  1024. y_limits <- limits_map[[var]]
  1025. y_span <- y_limits[2] - y_limits[1]
  1026. # Common plot configuration
  1027. plot_config <- list(
  1028. df = df_summary,
  1029. plot_type = plot_type,
  1030. x_var = "conc_num_factor_factor",
  1031. y_var = var,
  1032. shape = 16,
  1033. x_label = paste0("[", unique(df_summary$Drug)[1], "]"),
  1034. coord_cartesian = y_limits,
  1035. x_breaks = unique(df_summary$conc_num_factor_factor),
  1036. x_labels = as.character(unique(df_summary$conc_num))
  1037. )
  1038. # Add specific configurations for scatter and box plots
  1039. if (plot_type == "scatter") {
  1040. plot_config$title <- sprintf("%s Scatter RF for %s with SD", OrfRep, var)
  1041. plot_config$error_bar <- TRUE
  1042. plot_config$error_bar_params <- list(
  1043. color = "red",
  1044. mean_point = TRUE,
  1045. y_mean_col = paste0("mean_mean_", var),
  1046. y_sd_col = paste0("mean_sd_", var)
  1047. )
  1048. plot_config$position <- "jitter"
  1049. annotations <- list(
  1050. list(x = 0.25, y = y_limits[1] + 0.08 * y_span, label = " NG =", size = 4),
  1051. list(x = 0.25, y = y_limits[1] + 0.04 * y_span, label = " DB =", size = 4),
  1052. list(x = 0.25, y = y_limits[1], label = " SM =", size = 4)
  1053. )
  1054. for (x_val in unique(df_summary$conc_num_factor_factor)) {
  1055. current_df <- df_summary %>% filter(!!sym(plot_config$x_var) == x_val)
  1056. annotations <- append(annotations, list(
  1057. list(x = x_val, y = y_limits[1] + 0.08 * y_span, label = first(current_df$NG, default = 0), size = 4),
  1058. list(x = x_val, y = y_limits[1] + 0.04 * y_span, label = first(current_df$DB, default = 0), size = 4),
  1059. list(x = x_val, y = y_limits[1], label = first(current_df$SM, default = 0), size = 4)
  1060. ))
  1061. }
  1062. plot_config$annotations <- annotations
  1063. stats_plot_configs <- append(stats_plot_configs, list(plot_config))
  1064. } else if (plot_type == "box") {
  1065. plot_config$title <- sprintf("%s Box RF for %s with SD", OrfRep, var)
  1066. plot_config$position <- "dodge"
  1067. stats_boxplot_configs <- append(stats_boxplot_configs, list(plot_config))
  1068. }
  1069. }
  1070. }
  1071. # Delta interaction plots
  1072. delta_limits_map <- list(
  1073. L = c(-60, 60),
  1074. K = c(-60, 60),
  1075. r = c(-0.6, 0.6),
  1076. AUC = c(-6000, 6000)
  1077. )
  1078. # Select the data grouping by data type
  1079. if (type == "reference") {
  1080. group_vars <- c("OrfRep", "Gene", "num")
  1081. } else if (type == "deletion") {
  1082. group_vars <- c("OrfRep", "Gene")
  1083. }
  1084. grouped_data <- df_interactions %>%
  1085. group_by(across(all_of(group_vars))) %>%
  1086. group_split()
  1087. for (group_data in grouped_data) {
  1088. # Build the plot title
  1089. OrfRep <- first(group_data$OrfRep)
  1090. Gene <- first(group_data$Gene)
  1091. if (type == "reference") {
  1092. num <- if ("num" %in% names(group_data)) first(group_data$num) else ""
  1093. OrfRepTitle <- paste(OrfRep, Gene, num, sep = "_")
  1094. } else if (type == "deletion") {
  1095. OrfRepTitle <- OrfRep
  1096. }
  1097. for (var in names(delta_limits_map)) {
  1098. y_limits <- delta_limits_map[[var]]
  1099. y_span <- y_limits[2] - y_limits[1]
  1100. y_var_name <- paste0("Delta_", var)
  1101. # Anti-filter to select out-of-bounds rows
  1102. out_of_bounds <- group_data %>%
  1103. filter(is.na(!!sym(y_var_name)) |
  1104. !!sym(y_var_name) < y_limits[1] |
  1105. !!sym(y_var_name) > y_limits[2])
  1106. if (nrow(out_of_bounds) > 0) {
  1107. message(sprintf("Filtered %d row(s) from '%s' because %s is outside of y-limits: [%f, %f]",
  1108. nrow(out_of_bounds), OrfRepTitle, y_var_name, y_limits[1], y_limits[2]
  1109. ))
  1110. }
  1111. # Do the actual filtering
  1112. group_data_filtered <- group_data %>%
  1113. filter(!is.na(!!sym(y_var_name)) &
  1114. !!sym(y_var_name) >= y_limits[1] &
  1115. !!sym(y_var_name) <= y_limits[2])
  1116. if (nrow(group_data_filtered) == 0) {
  1117. message("Insufficient data for plot: ", OrfRepTitle, " ", var)
  1118. next # skip plot if insufficient data is available
  1119. }
  1120. WT_sd_value <- first(group_data_filtered[[paste0("WT_sd_", var)]], default = 0)
  1121. Z_Shift_value <- round(first(group_data_filtered[[paste0("Z_Shift_", var)]], default = 0), 2)
  1122. Z_lm_value <- round(first(group_data_filtered[[paste0("Z_lm_", var)]], default = 0), 2)
  1123. R_squared_value <- round(first(group_data_filtered[[paste0("R_Squared_", var)]], default = 0), 2)
  1124. NG_value <- first(group_data_filtered$NG, default = 0)
  1125. DB_value <- first(group_data_filtered$DB, default = 0)
  1126. SM_value <- first(group_data_filtered$SM, default = 0)
  1127. lm_intercept_col <- paste0("lm_intercept_", var)
  1128. lm_slope_col <- paste0("lm_slope_", var)
  1129. lm_intercept <- first(group_data_filtered[[lm_intercept_col]], default = 0)
  1130. lm_slope <- first(group_data_filtered[[lm_slope_col]], default = 0)
  1131. plot_config <- list(
  1132. df = group_data_filtered,
  1133. plot_type = "scatter",
  1134. x_var = "conc_num_factor_factor",
  1135. y_var = y_var_name,
  1136. x_label = paste0("[", unique(df_summary$Drug)[1], "]"),
  1137. shape = 16,
  1138. title = paste(OrfRepTitle, Gene, sep = " "),
  1139. title_size = rel(1.4),
  1140. coord_cartesian = y_limits,
  1141. annotations = list(
  1142. list(x = 1, y = y_limits[2] - 0.1 * y_span, label = paste(" ZShift =", round(Z_Shift_value, 2))),
  1143. list(x = 1, y = y_limits[2] - 0.2 * y_span, label = paste(" lm ZScore =", round(Z_lm_value, 2))),
  1144. # list(x = 1, y = y_limits[2] - 0.3 * y_span, label = paste(" R-squared =", round(R_squared_value, 2))),
  1145. list(x = 1, y = y_limits[1] + 0.1 * y_span, label = paste("NG =", NG_value)),
  1146. list(x = 1, y = y_limits[1] + 0.05 * y_span, label = paste("DB =", DB_value)),
  1147. list(x = 1, y = y_limits[1], label = paste("SM =", SM_value))
  1148. ),
  1149. error_bar = TRUE,
  1150. error_bar_params = list(
  1151. custom_error_bar = list(
  1152. ymin = paste0("0 - 2 * WT_sd_", var),
  1153. ymax = paste0("0 + 2 * WT_sd_", var)
  1154. ),
  1155. color = "gray70",
  1156. linewidth = 0.5
  1157. ),
  1158. x_breaks = unique(group_data_filtered$conc_num_factor_factor),
  1159. x_labels = as.character(unique(group_data_filtered$conc_num)),
  1160. ylim_vals = y_limits,
  1161. lm_line = list(
  1162. intercept = lm_intercept,
  1163. slope = lm_slope,
  1164. color = "blue",
  1165. linewidth = 0.8
  1166. )
  1167. )
  1168. delta_plot_configs <- append(delta_plot_configs, list(plot_config))
  1169. }
  1170. }
  1171. # Group delta plots in chunks of 12 per page
  1172. chunk_size <- 12
  1173. delta_plot_chunks <- split(delta_plot_configs, ceiling(seq_along(delta_plot_configs) / chunk_size))
  1174. return(c(
  1175. list(list(grid_layout = list(ncol = 2), plots = stats_plot_configs)),
  1176. list(list(grid_layout = list(ncol = 2), plots = stats_boxplot_configs)),
  1177. lapply(delta_plot_chunks, function(chunk) list(grid_layout = list(ncol = 4), plots = chunk))
  1178. ))
  1179. }
  1180. generate_rank_plot_configs <- function(df, is_lm = FALSE, filter_na = FALSE, overlap_color = FALSE) {
  1181. sd_bands <- c(1, 2, 3)
  1182. plot_configs <- list()
  1183. variables <- c("L", "K")
  1184. # Helper function to create a rank plot configuration
  1185. create_plot_config <- function(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = TRUE) {
  1186. num_enhancers <- sum(df[[zscore_var]] >= sd_band, na.rm = TRUE)
  1187. num_suppressors <- sum(df[[zscore_var]] <= -sd_band, na.rm = TRUE)
  1188. # Default plot config
  1189. plot_config <- list(
  1190. df = df,
  1191. x_var = rank_var,
  1192. y_var = zscore_var,
  1193. x_label = "Rank",
  1194. y_label = y_label,
  1195. plot_type = "scatter",
  1196. title = paste(y_label, "vs. Rank for", variable, "above", sd_band, "SD"),
  1197. sd_band = sd_band,
  1198. fill_positive = "#542788",
  1199. fill_negative = "orange",
  1200. alpha_positive = 0.3,
  1201. alpha_negative = 0.3,
  1202. shape = 3,
  1203. size = 0.1,
  1204. filter_na = filter_na,
  1205. legend_position = "none"
  1206. )
  1207. # Selectively add annotations
  1208. if (with_annotations) {
  1209. plot_config$annotations <- list(
  1210. list(
  1211. x = nrow(df) / 2,
  1212. y = 10,
  1213. label = paste("Deletion Enhancers =", num_enhancers)
  1214. ),
  1215. list(
  1216. x = nrow(df) / 2,
  1217. y = -10,
  1218. label = paste("Deletion Suppressors =", num_suppressors)
  1219. )
  1220. )
  1221. }
  1222. return(plot_config)
  1223. }
  1224. # Generate plots for each variable
  1225. for (variable in variables) {
  1226. rank_var <- if (is_lm) paste0("Rank_lm_", variable) else paste0("Rank_", variable)
  1227. zscore_var <- if (is_lm) paste0("Z_lm_", variable) else paste0("Avg_Zscore_", variable)
  1228. y_label <- if (is_lm) paste("Int Z score", variable) else paste("Avg Z score", variable)
  1229. # Loop through SD bands
  1230. for (sd_band in sd_bands) {
  1231. # Create plot with annotations
  1232. plot_configs[[length(plot_configs) + 1]] <-
  1233. create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = TRUE)
  1234. # Create plot without annotations
  1235. plot_configs[[length(plot_configs) + 1]] <-
  1236. create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = FALSE)
  1237. }
  1238. }
  1239. # Group delta plots in chunks of 6 per page
  1240. chunk_size <- 6
  1241. plot_chunks <- split(plot_configs, ceiling(seq_along(plot_configs) / chunk_size))
  1242. return(c(
  1243. lapply(plot_chunks, function(chunk) list(grid_layout = list(ncol = 3), plots = chunk))
  1244. ))
  1245. }
  1246. generate_correlation_plot_configs <- function(df, df_reference) {
  1247. # Define relationships for different-variable correlations
  1248. relationships <- list(
  1249. list(x = "L", y = "K"), # x-var is predictor, y-var is reponse
  1250. list(x = "L", y = "r"),
  1251. list(x = "L", y = "AUC"),
  1252. list(x = "K", y = "r"),
  1253. list(x = "K", y = "AUC"),
  1254. list(x = "r", y = "AUC")
  1255. )
  1256. # Filter both dataframes for missing linear model zscores for plotting
  1257. df <- df %>%
  1258. filter(!is.na(Z_lm_L))
  1259. df_reference <- df_reference %>%
  1260. filter(!is.na(Z_lm_L))
  1261. plot_configs <- list()
  1262. # Iterate over the option to highlight cyan points (TRUE/FALSE)
  1263. highlight_cyan_options <- c(FALSE, TRUE)
  1264. for (highlight_cyan in highlight_cyan_options) {
  1265. for (rel in relationships) {
  1266. # Extract relevant variable names for Z_lm values
  1267. x_var <- paste0("Z_lm_", rel$x) # predictor
  1268. y_var <- paste0("Z_lm_", rel$y) # response
  1269. # Skip this plot if there's no valid data
  1270. # if (all(is.na(df[[x_var]])) || all(is.na(df_reference[[x_var]])) ||
  1271. # all(is.na(df[[y_var]])) || all(is.na(df_reference[[y_var]]))) {
  1272. # next
  1273. # }
  1274. # Find the max and min of both dataframes for printing linear regression line
  1275. xmin <- min(c(min(df[[x_var]], na.rm = TRUE), min(df_reference[[x_var]], na.rm = TRUE)), na.rm = TRUE)
  1276. xmax <- max(c(max(df[[x_var]], na.rm = TRUE), max(df_reference[[x_var]], na.rm = TRUE)), na.rm = TRUE)
  1277. # Extract the R-squared, intercept, and slope from the df (first value)
  1278. intercept <- df[[paste0("Z_lm_intercept_", rel$y, "_", rel$x)]][1]
  1279. slope <- df[[paste0("Z_lm_slope_", rel$y, "_", rel$x)]][1]
  1280. r_squared <- df[[paste0("Z_lm_R_squared_", rel$y, "_", rel$x)]][1]
  1281. # Generate the label for the plot
  1282. plot_label <- paste("Interaction", rel$x, "vs.", rel$y)
  1283. # Construct plot config
  1284. plot_config <- list(
  1285. df = df,
  1286. df_reference = df_reference,
  1287. x_var = x_var,
  1288. y_var = y_var,
  1289. plot_type = "scatter",
  1290. title = plot_label,
  1291. annotations = list(
  1292. list(
  1293. x = mean(df[[x_var]], na.rm = TRUE),
  1294. y = mean(df[[y_var]], na.rm = TRUE),
  1295. label = paste("R-squared =", round(r_squared, 3))
  1296. )
  1297. ),
  1298. lm_line = list(
  1299. intercept = intercept,
  1300. slope = slope,
  1301. color = "tomato3",
  1302. linewidth = 0.8,
  1303. xmin = xmin,
  1304. xmax = xmax
  1305. ),
  1306. color = "gray70",
  1307. filter_na = TRUE,
  1308. cyan_points = highlight_cyan # include cyan points or not based on the loop
  1309. )
  1310. plot_configs <- append(plot_configs, list(plot_config))
  1311. }
  1312. }
  1313. return(list(plots = plot_configs))
  1314. }
  1315. main <- function() {
  1316. lapply(names(args$experiments), function(exp_name) {
  1317. exp <- args$experiments[[exp_name]]
  1318. exp_path <- exp$path
  1319. exp_sd <- exp$sd
  1320. out_dir <- file.path(exp_path, "zscores")
  1321. out_dir_qc <- file.path(exp_path, "zscores", "qc")
  1322. dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
  1323. dir.create(out_dir_qc, recursive = TRUE, showWarnings = FALSE)
  1324. # Each list of plots corresponds to a separate file
  1325. message("Loading and filtering data for experiment: ", exp_name)
  1326. df <- load_and_filter_data(args$easy_results_file, sd = exp_sd) %>%
  1327. update_gene_names(args$sgd_gene_list) %>%
  1328. as_tibble()
  1329. l_vs_k_plot_configs <- list(
  1330. plots = list(
  1331. list(
  1332. df = df,
  1333. x_var = "L",
  1334. y_var = "K",
  1335. plot_type = "scatter",
  1336. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1337. title = "Raw L vs K before quality control",
  1338. color_var = "conc_num_factor_factor",
  1339. error_bar = FALSE,
  1340. legend_position = "right"
  1341. )
  1342. )
  1343. )
  1344. message("Calculating summary statistics before quality control")
  1345. df_stats <- calculate_summary_stats( # formerly X_stats_ALL
  1346. df = df,
  1347. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1348. group_vars = c("conc_num", "conc_num_factor_factor"))$df_with_stats
  1349. frequency_delta_bg_plot_configs <- list(
  1350. plots = list(
  1351. list(
  1352. df = df_stats,
  1353. x_var = "delta_bg",
  1354. y_var = NULL,
  1355. plot_type = "density",
  1356. title = "Density plot for Delta Background by [Drug] (All Data)",
  1357. color_var = "conc_num_factor_factor",
  1358. x_label = "Delta Background",
  1359. y_label = "Density",
  1360. error_bar = FALSE,
  1361. legend_position = "right"
  1362. ),
  1363. list(
  1364. df = df_stats,
  1365. x_var = "delta_bg",
  1366. y_var = NULL,
  1367. plot_type = "bar",
  1368. title = "Bar plot for Delta Background by [Drug] (All Data)",
  1369. color_var = "conc_num_factor_factor",
  1370. x_label = "Delta Background",
  1371. y_label = "Count",
  1372. error_bar = FALSE,
  1373. legend_position = "right"
  1374. )
  1375. )
  1376. )
  1377. message("Filtering rows above delta background tolerance for plotting")
  1378. df_above_tolerance <- df %>% filter(DB == 1)
  1379. above_threshold_plot_configs <- list(
  1380. plots = list(
  1381. list(
  1382. df = df_above_tolerance,
  1383. x_var = "L",
  1384. y_var = "K",
  1385. plot_type = "scatter",
  1386. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1387. title = paste("Raw L vs K for strains above Delta Background threshold of",
  1388. round(df_above_tolerance$delta_bg_tolerance[[1]], 3), "or above"),
  1389. color_var = "conc_num_factor_factor",
  1390. position = "jitter",
  1391. annotations = list(
  1392. list(
  1393. x = median(df_above_tolerance$L, na.rm = TRUE) / 2,
  1394. y = median(df_above_tolerance$K, na.rm = TRUE) / 2,
  1395. label = paste("# strains above Delta Background tolerance =", nrow(df_above_tolerance))
  1396. )
  1397. ),
  1398. error_bar = FALSE,
  1399. legend_position = "right"
  1400. )
  1401. )
  1402. )
  1403. message("Setting rows above delta background tolerance to NA")
  1404. df_na <- df %>% mutate(across(all_of(c("L", "K", "r", "AUC", "delta_bg")), ~ ifelse(DB == 1, NA, .))) # formerly X
  1405. message("Calculating summary statistics across all strains")
  1406. ss <- calculate_summary_stats(
  1407. df = df_na,
  1408. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1409. group_vars = c("conc_num", "conc_num_factor_factor"))
  1410. df_na_ss <- ss$summary_stats
  1411. df_na_stats <- ss$df_with_stats # formerly X_stats_ALL
  1412. write.csv(df_na_ss, file = file.path(out_dir, "summary_stats_all_strains.csv"), row.names = FALSE)
  1413. # This can help bypass missing values ggplot warnings during testing
  1414. df_na_stats_filtered <- df_na_stats %>% filter(if_all(all_of(c("L", "K", "r", "AUC", "delta_bg")), is.finite))
  1415. message("Calculating summary statistics excluding zero values")
  1416. df_no_zeros <- df_na %>% filter(L > 0) # formerly X_noZero
  1417. df_no_zeros_stats <- calculate_summary_stats(
  1418. df = df_no_zeros,
  1419. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1420. group_vars = c("conc_num", "conc_num_factor_factor")
  1421. )$df_with_stats
  1422. message("Filtering by 2SD of K")
  1423. df_na_within_2sd_k <- df_na_stats %>%
  1424. filter(K >= (mean_K - 2 * sd_K) & K <= (mean_K + 2 * sd_K))
  1425. df_na_outside_2sd_k <- df_na_stats %>%
  1426. filter(K < (mean_K - 2 * sd_K) | K > (mean_K + 2 * sd_K))
  1427. message("Calculating summary statistics for L within 2SD of K")
  1428. # TODO We're omitting the original z_max calculation, not sure if needed?
  1429. ss <- calculate_summary_stats(df_na_within_2sd_k, "L", # formerly X_stats_BY_L_within_2SD_K
  1430. group_vars = c("conc_num", "conc_num_factor_factor"))$summary_stats
  1431. write.csv(ss,
  1432. file = file.path(out_dir_qc, "max_observed_L_vals_for_spots_within_2SD_K.csv"),
  1433. row.names = FALSE)
  1434. message("Calculating summary statistics for L outside 2SD of K")
  1435. ss <- calculate_summary_stats(df_na_outside_2sd_k, "L", # formerly X_stats_BY_L_outside_2SD_K
  1436. group_vars = c("conc_num", "conc_num_factor_factor"))
  1437. df_na_l_outside_2sd_k_stats <- ss$df_with_stats
  1438. write.csv(ss$summary_stats,
  1439. file = file.path(out_dir, "max_observed_L_vals_for_spots_outside_2SD_K.csv"),
  1440. row.names = FALSE)
  1441. plate_analysis_plot_configs <- generate_plate_analysis_plot_configs(
  1442. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1443. df_before = df_stats,
  1444. df_after = df_na_stats_filtered
  1445. )
  1446. plate_analysis_boxplot_configs <- generate_plate_analysis_plot_configs(
  1447. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1448. df_before = df_stats,
  1449. df_after = df_na_stats_filtered,
  1450. plot_type = "box"
  1451. )
  1452. plate_analysis_no_zeros_plot_configs <- generate_plate_analysis_plot_configs(
  1453. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1454. stages = c("after"), # Only after QC
  1455. df_after = df_no_zeros_stats
  1456. )
  1457. plate_analysis_no_zeros_boxplot_configs <- generate_plate_analysis_plot_configs(
  1458. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1459. stages = c("after"), # Only after QC
  1460. df_after = df_no_zeros_stats,
  1461. plot_type = "box"
  1462. )
  1463. l_outside_2sd_k_plot_configs <- list(
  1464. plots = list(
  1465. list(
  1466. df = df_na_l_outside_2sd_k_stats,
  1467. x_var = "L",
  1468. y_var = "K",
  1469. plot_type = "scatter",
  1470. title = "Raw L vs K for strains falling outside 2 SD of the K mean at each Conc",
  1471. color_var = "conc_num_factor_factor",
  1472. position = "jitter",
  1473. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1474. annotations = list(
  1475. list(
  1476. x = median(df_na_l_outside_2sd_k_stats$L, na.rm = TRUE) / 2,
  1477. y = median(df_na_l_outside_2sd_k_stats$K, na.rm = TRUE) / 2,
  1478. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats))
  1479. )
  1480. ),
  1481. error_bar = FALSE,
  1482. legend_position = "right"
  1483. )
  1484. )
  1485. )
  1486. delta_bg_outside_2sd_k_plot_configs <- list(
  1487. plots = list(
  1488. list(
  1489. df = df_na_l_outside_2sd_k_stats,
  1490. x_var = "delta_bg",
  1491. x_label = "Delta Background",
  1492. y_var = "K",
  1493. plot_type = "scatter",
  1494. title = "Delta Background vs K for strains falling outside 2 SD of K",
  1495. color_var = "conc_num_factor_factor",
  1496. position = "jitter",
  1497. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1498. annotations = list(
  1499. list(
  1500. x = 0.05,
  1501. y = 0.95,
  1502. hjust = 0,
  1503. vjust = 1,
  1504. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats)),
  1505. size = 5
  1506. )
  1507. ),
  1508. error_bar = FALSE,
  1509. legend_position = "right"
  1510. )
  1511. )
  1512. )
  1513. message("Generating quality control plots in parallel")
  1514. # future::plan(future::multicore, workers = parallel::detectCores())
  1515. future::plan(future::multisession, workers = 3) # generate 3 plot files in parallel
  1516. plot_configs <- list(
  1517. list(out_dir = out_dir_qc, filename = "L_vs_K_before_quality_control",
  1518. plot_configs = l_vs_k_plot_configs, page_width = 12, page_height = 8),
  1519. list(out_dir = out_dir_qc, filename = "frequency_delta_background",
  1520. plot_configs = frequency_delta_bg_plot_configs, page_width = 12, page_height = 8),
  1521. list(out_dir = out_dir_qc, filename = "L_vs_K_above_threshold",
  1522. plot_configs = above_threshold_plot_configs, page_width = 12, page_height = 8),
  1523. list(out_dir = out_dir_qc, filename = "plate_analysis",
  1524. plot_configs = plate_analysis_plot_configs, page_width = 14, page_height = 9),
  1525. list(out_dir = out_dir_qc, filename = "plate_analysis_boxplots",
  1526. plot_configs = plate_analysis_boxplot_configs, page_width = 18, page_height = 9),
  1527. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros",
  1528. plot_configs = plate_analysis_no_zeros_plot_configs, page_width = 14, page_height = 9),
  1529. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros_boxplots",
  1530. plot_configs = plate_analysis_no_zeros_boxplot_configs, page_width = 18, page_height = 9),
  1531. list(out_dir = out_dir_qc, filename = "L_vs_K_for_strains_2SD_outside_mean_K",
  1532. plot_configs = l_outside_2sd_k_plot_configs, page_width = 10, page_height = 8),
  1533. list(out_dir = out_dir_qc, filename = "delta_background_vs_K_for_strains_2SD_outside_mean_K",
  1534. plot_configs = delta_bg_outside_2sd_k_plot_configs, page_width = 10, page_height = 8)
  1535. )
  1536. # Parallelize background and quality control plot generation
  1537. # furrr::future_map(plot_configs, function(config) {
  1538. # generate_and_save_plots(config$out_dir, config$filename, config$plot_configs,
  1539. # page_width = config$page_width, page_height = config$page_height)
  1540. # }, .options = furrr_options(seed = TRUE))
  1541. # Loop over background strains
  1542. # TODO currently only tested against one strain, if we want to do multiple strains we'll
  1543. # have to rename or group the output files by dir or something so they don't get clobbered
  1544. bg_strains <- c("YDL227C")
  1545. lapply(bg_strains, function(strain) {
  1546. message("Processing background strain: ", strain)
  1547. # Handle missing data by setting zero values to NA
  1548. # and then removing any rows with NA in L col
  1549. df_bg <- df_na %>%
  1550. filter(OrfRep == strain) %>%
  1551. mutate(
  1552. L = if_else(L == 0, NA, L),
  1553. K = if_else(K == 0, NA, K),
  1554. r = if_else(r == 0, NA, r),
  1555. AUC = if_else(AUC == 0, NA, AUC)
  1556. ) %>%
  1557. filter(!is.na(L))
  1558. message("Calculating background summary statistics")
  1559. ss_bg <- calculate_summary_stats(df_bg, c("L", "K", "r", "AUC", "delta_bg"), # formerly X_stats_BY
  1560. group_vars = c("OrfRep", "Drug", "conc_num", "conc_num_factor_factor"))
  1561. summary_stats_bg <- ss_bg$summary_stats
  1562. df_bg_stats <- ss_bg$df_with_stats
  1563. write.csv(
  1564. summary_stats_bg,
  1565. file = file.path(out_dir, paste0("summary_stats_background_strain_", strain, ".csv")),
  1566. row.names = FALSE)
  1567. message("Setting missing reference values to the highest theoretical value at each drug conc for L")
  1568. df_reference <- df_na_stats %>% # formerly X2_RF
  1569. filter(OrfRep == strain) %>%
  1570. filter(!is.na(L)) %>%
  1571. group_by(OrfRep, Drug, conc_num, conc_num_factor_factor) %>%
  1572. mutate(
  1573. max_l_theoretical = max(max_L, na.rm = TRUE),
  1574. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1575. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, 0),
  1576. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1577. ungroup()
  1578. message("Calculating reference strain summary statistics")
  1579. df_reference_summary_stats <- calculate_summary_stats( # formerly X_stats_X2_RF
  1580. df = df_reference,
  1581. variables = c("L", "K", "r", "AUC"),
  1582. group_vars = c("OrfRep", "Drug", "conc_num", "conc_num_factor_factor")
  1583. )$df_with_stats
  1584. # Summarise statistics for error bars
  1585. df_reference_summary_stats <- df_reference_summary_stats %>%
  1586. group_by(OrfRep, Drug, conc_num, conc_num_factor_factor) %>%
  1587. mutate(
  1588. mean_mean_L = first(mean_L),
  1589. mean_sd_L = first(sd_L),
  1590. mean_mean_K = first(mean_K),
  1591. mean_sd_K = first(sd_K),
  1592. mean_mean_r = first(mean_r),
  1593. mean_sd_r = first(sd_r),
  1594. mean_mean_AUC = first(mean_AUC),
  1595. mean_sd_AUC = first(sd_AUC),
  1596. .groups = "drop"
  1597. )
  1598. message("Calculating reference strain interaction summary statistics") # formerly X_stats_interaction
  1599. df_reference_interaction_stats <- calculate_summary_stats(
  1600. df = df_reference,
  1601. variables = c("L", "K", "r", "AUC"),
  1602. group_vars = c("OrfRep", "Gene", "num", "Drug", "conc_num", "conc_num_factor_factor")
  1603. )$df_with_stats
  1604. message("Calculating reference strain interaction scores")
  1605. reference_results <- calculate_interaction_scores(df_reference_interaction_stats, df_bg_stats, "reference")
  1606. df_reference_calculations <- reference_results$calculations
  1607. df_reference_interactions_joined <- reference_results$full_data
  1608. df_reference_interactions <- reference_results$interactions
  1609. write.csv(df_reference_calculations, file = file.path(out_dir, "zscore_calculations_reference.csv"), row.names = FALSE)
  1610. write.csv(df_reference_interactions, file = file.path(out_dir, "zscore_interactions_reference.csv"), row.names = FALSE)
  1611. # message("Generating reference interaction plots")
  1612. # reference_plot_configs <- generate_interaction_plot_configs(df_reference_summary_stats, df_reference_interactions_joined, "reference")
  1613. # generate_and_save_plots(out_dir, "interaction_plots_reference", reference_plot_configs, page_width = 16, page_height = 16)
  1614. message("Setting missing deletion values to the highest theoretical value at each drug conc for L")
  1615. df_deletion <- df_na_stats %>% # formerly X2
  1616. filter(OrfRep != strain) %>%
  1617. filter(!is.na(L)) %>%
  1618. group_by(OrfRep, Gene, conc_num, conc_num_factor_factor) %>%
  1619. mutate(
  1620. max_l_theoretical = max(max_L, na.rm = TRUE),
  1621. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1622. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, SM),
  1623. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1624. ungroup()
  1625. message("Calculating deletion strain(s) interaction summary statistics")
  1626. df_deletion_stats <- calculate_summary_stats(
  1627. df = df_deletion,
  1628. variables = c("L", "K", "r", "AUC"),
  1629. group_vars = c("OrfRep", "Gene", "Drug", "conc_num", "conc_num_factor_factor")
  1630. )$df_with_stats
  1631. message("Calculating deletion strain(s) interactions scores")
  1632. deletion_results <- calculate_interaction_scores(df_deletion_stats, df_bg_stats, "deletion")
  1633. df_calculations <- deletion_results$calculations
  1634. df_interactions <- deletion_results$interactions
  1635. df_interactions_joined <- deletion_results$full_data
  1636. write.csv(df_calculations, file = file.path(out_dir, "zscore_calculations.csv"), row.names = FALSE)
  1637. write.csv(df_interactions, file = file.path(out_dir, "zscore_interactions.csv"), row.names = FALSE)
  1638. # message("Generating deletion interaction plots")
  1639. # deletion_plot_configs <- generate_interaction_plot_configs(df_reference_summary_stats, df_interactions_joined, "deletion")
  1640. # generate_and_save_plots(out_dir, "interaction_plots", deletion_plot_configs, page_width = 16, page_height = 16)
  1641. # message("Writing enhancer/suppressor csv files")
  1642. # interaction_threshold <- 2 # TODO add to study config?
  1643. # enhancer_condition_L <- df_interactions$Avg_Zscore_L >= interaction_threshold
  1644. # suppressor_condition_L <- df_interactions$Avg_Zscore_L <= -interaction_threshold
  1645. # enhancer_condition_K <- df_interactions$Avg_Zscore_K >= interaction_threshold
  1646. # suppressor_condition_K <- df_interactions$Avg_Zscore_K <= -interaction_threshold
  1647. # enhancers_L <- df_interactions[enhancer_condition_L, ]
  1648. # suppressors_L <- df_interactions[suppressor_condition_L, ]
  1649. # enhancers_K <- df_interactions[enhancer_condition_K, ]
  1650. # suppressors_K <- df_interactions[suppressor_condition_K, ]
  1651. # enhancers_and_suppressors_L <- df_interactions[enhancer_condition_L | suppressor_condition_L, ]
  1652. # enhancers_and_suppressors_K <- df_interactions[enhancer_condition_K | suppressor_condition_K, ]
  1653. # write.csv(enhancers_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_L.csv"), row.names = FALSE)
  1654. # write.csv(suppressors_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_L.csv"), row.names = FALSE)
  1655. # write.csv(enhancers_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_K.csv"), row.names = FALSE)
  1656. # write.csv(suppressors_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_K.csv"), row.names = FALSE)
  1657. # write.csv(enhancers_and_suppressors_L,
  1658. # file = file.path(out_dir, "zscore_interactions_deletion_enhancers_and_suppressors_L.csv"), row.names = FALSE)
  1659. # write.csv(enhancers_and_suppressors_K,
  1660. # file = file.path(out_dir, "zscore_interaction_deletion_enhancers_and_suppressors_K.csv"), row.names = FALSE)
  1661. # message("Writing linear model enhancer/suppressor csv files")
  1662. # lm_interaction_threshold <- 2 # TODO add to study config?
  1663. # enhancers_lm_L <- df_interactions[df_interactions$Z_lm_L >= lm_interaction_threshold, ]
  1664. # suppressors_lm_L <- df_interactions[df_interactions$Z_lm_L <= -lm_interaction_threshold, ]
  1665. # enhancers_lm_K <- df_interactions[df_interactions$Z_lm_K >= lm_interaction_threshold, ]
  1666. # suppressors_lm_K <- df_interactions[df_interactions$Z_lm_K <= -lm_interaction_threshold, ]
  1667. # write.csv(enhancers_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_L.csv"), row.names = FALSE)
  1668. # write.csv(suppressors_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_L.csv"), row.names = FALSE)
  1669. # write.csv(enhancers_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_K.csv"), row.names = FALSE)
  1670. # write.csv(suppressors_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_K.csv"), row.names = FALSE)
  1671. # message("Generating rank plots")
  1672. # rank_plot_configs <- generate_rank_plot_configs(
  1673. # df_interactions,
  1674. # is_lm = FALSE,
  1675. # )
  1676. # generate_and_save_plots(out_dir, "rank_plots", rank_plot_configs,
  1677. # page_width = 18, page_height = 12)
  1678. # message("Generating ranked linear model plots")
  1679. # rank_lm_plot_configs <- generate_rank_plot_configs(
  1680. # df_interactions,
  1681. # is_lm = TRUE,
  1682. # )
  1683. # generate_and_save_plots(out_dir, "rank_plots_lm", rank_lm_plot_configs,
  1684. # page_width = 18, page_height = 12)
  1685. # message("Generating overlapped ranked plots")
  1686. # rank_plot_filtered_configs <- generate_rank_plot_configs(
  1687. # df_interactions,
  1688. # is_lm = FALSE,
  1689. # filter_na = TRUE,
  1690. # overlap_color = TRUE
  1691. # )
  1692. # generate_and_save_plots(out_dir, "rank_plots_na_rm", rank_plot_filtered_configs,
  1693. # page_width = 18, page_height = 12)
  1694. # message("Generating overlapped ranked linear model plots")
  1695. # rank_plot_lm_filtered_configs <- generate_rank_plot_configs(
  1696. # df_interactions,
  1697. # is_lm = TRUE,
  1698. # filter_na = TRUE,
  1699. # overlap_color = TRUE
  1700. # )
  1701. # generate_and_save_plots(out_dir, "rank_plots_lm_na_rm", rank_plot_lm_filtered_configs,
  1702. # page_width = 18, page_height = 12)
  1703. message("Generating correlation curve parameter pair plots")
  1704. correlation_plot_configs <- generate_correlation_plot_configs(
  1705. df_interactions,
  1706. df_reference_interactions
  1707. )
  1708. generate_and_save_plots(out_dir, "correlation_cpps", correlation_plot_configs,
  1709. page_width = 10, page_height = 7)
  1710. })
  1711. })
  1712. }
  1713. main()