calculate_interaction_zscores.R 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  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 = 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. "Z_lm_L", "Z_lm_K", "Z_lm_r", "Z_lm_AUC"
  661. )))
  662. full_data <- calculations_no_overlap %>%
  663. left_join(interactions, by = group_vars)
  664. # Return final dataframes
  665. return(list(
  666. calculations = df_calculations,
  667. interactions = df_interactions,
  668. full_data = full_data
  669. ))
  670. }
  671. generate_and_save_plots <- function(out_dir, filename, plot_configs, page_width = 12, page_height = 8) {
  672. message("Generating ", filename, ".pdf and ", filename, ".html")
  673. plot_groups <- if ("plots" %in% names(plot_configs)) {
  674. list(plot_configs) # Single group
  675. } else {
  676. plot_configs # Multiple groups
  677. }
  678. pdf(file.path(out_dir, paste0(filename, ".pdf")), width = page_width, height = page_height)
  679. for (group in plot_groups) {
  680. static_plots <- list()
  681. plotly_plots <- list()
  682. for (i in seq_along(group$plots)) {
  683. config <- group$plots[[i]]
  684. df <- config$df
  685. # Filter NAs
  686. if (!is.null(config$filter_na) && config$filter_na) {
  687. df <- df %>%
  688. filter(!is.na(!!sym(config$y_var)))
  689. }
  690. # TODO for now skip all NA plots NA data
  691. # Eventually add to own or filter_na block so we can handle selectively
  692. if (nrow(df) == 0) {
  693. message("Insufficient data for plot:", config$title)
  694. next # skip plot if insufficient data is available
  695. }
  696. # Create initial aes mappings for all plot types
  697. aes_mapping <- aes(x = !!sym(config$x_var)) # required
  698. if (!is.null(config$y_var)) {
  699. aes_mapping <- modifyList(aes_mapping, aes(y = !!sym(config$y_var))) # optional for density/bar plots
  700. }
  701. if (!is.null(config$color_var)) {
  702. aes_mapping <- modifyList(aes_mapping, aes(color = !!sym(config$color_var))) # dynamic color_var
  703. } else if (!is.null(config$color)) {
  704. aes_mapping <- modifyList(aes_mapping, aes(color = config$color)) # static color
  705. }
  706. if (config$plot_type == "bar" && !is.null(config$color_var)) {
  707. aes_mapping <- modifyList(aes_mapping, aes(fill = !!sym(config$color_var))) # only fill bar plots
  708. }
  709. # Begin plot generation
  710. plot <- ggplot(df, aes_mapping) + theme_publication(legend_position = config$legend_position)
  711. plot <- switch(config$plot_type,
  712. "scatter" = generate_scatter_plot(plot, config),
  713. "box" = generate_boxplot(plot, config),
  714. "density" = plot + geom_density(),
  715. "bar" = plot + geom_bar(),
  716. plot # default
  717. )
  718. if (!is.null(config$title)) {
  719. plot <- plot + ggtitle(config$title)
  720. if (!is.null(config$title_size)) {
  721. plot <- plot + theme(plot.title = element_text(size = config$title_size))
  722. }
  723. }
  724. if (!is.null(config$x_label)) plot <- plot + xlab(config$x_label)
  725. if (!is.null(config$y_label)) plot <- plot + ylab(config$y_label)
  726. if (!is.null(config$coord_cartesian)) plot <- plot + coord_cartesian(ylim = config$coord_cartesian)
  727. #plotly_plot <- suppressWarnings(plotly::ggplotly(plot))
  728. static_plots[[i]] <- plot
  729. #plotly_plots[[i]] <- plotly_plot
  730. }
  731. grid_layout <- group$grid_layout
  732. if (!is.null(grid_layout)) {
  733. if (is.null(grid_layout$ncol)) {
  734. grid_layout$ncol <- 1
  735. }
  736. if (!is.null(grid_layout$ncol) && is.null(grid_layout$nrow)) {
  737. num_plots <- length(static_plots)
  738. grid_layout$nrow <- ceiling(num_plots / grid_layout$ncol)
  739. }
  740. # total_spots <- grid_layout$nrow * grid_layout$ncol
  741. # num_plots <- length(static_plots)
  742. # if (num_plots < total_spots) {
  743. # message("Filling ", total_spots - num_plots, " empty spots with nullGrob()")
  744. # static_plots <- c(static_plots, replicate(total_spots - num_plots, nullGrob(), simplify = FALSE))
  745. # }
  746. grid.arrange(
  747. grobs = static_plots,
  748. ncol = grid_layout$ncol,
  749. nrow = grid_layout$nrow
  750. )
  751. } else {
  752. for (plot in static_plots) {
  753. print(plot)
  754. }
  755. }
  756. }
  757. dev.off()
  758. # out_html_file <- file.path(out_dir, paste0(filename, ".html"))
  759. # message("Saving combined HTML file: ", out_html_file)
  760. # htmltools::save_html(
  761. # htmltools::tagList(plotly_plots),
  762. # file = out_html_file
  763. # )
  764. }
  765. generate_scatter_plot <- function(plot, config) {
  766. # Define the points
  767. shape <- if (!is.null(config$shape)) config$shape else 3
  768. size <- if (!is.null(config$size)) config$size else 1.5
  769. position <-
  770. if (!is.null(config$position) && config$position == "jitter") {
  771. position_jitter(width = 0.4, height = 0.1)
  772. } else {
  773. "identity"
  774. }
  775. plot <- plot + geom_point(
  776. shape = shape,
  777. size = size,
  778. position = position
  779. )
  780. # Add a cyan point for the reference data for correlation plots
  781. if (!is.null(config$cyan_points) && config$cyan_points) {
  782. plot <- plot + geom_point(
  783. aes(x = !!sym(config$x_var), y = !!sym(config$y_var)),
  784. data = config$df_reference,
  785. color = "cyan",
  786. shape = 3,
  787. size = 0.5
  788. )
  789. }
  790. # Add error bars if specified
  791. if (!is.null(config$error_bar) && config$error_bar) {
  792. # Check if custom columns are provided for y_mean and y_sd, or use the defaults
  793. y_mean_col <- if (!is.null(config$error_bar_params$y_mean_col)) {
  794. config$error_bar_params$y_mean_col
  795. } else {
  796. paste0("mean_", config$y_var)
  797. }
  798. y_sd_col <- if (!is.null(config$error_bar_params$y_sd_col)) {
  799. config$error_bar_params$y_sd_col
  800. } else {
  801. paste0("sd_", config$y_var)
  802. }
  803. # Use rlang to handle custom error bar calculations
  804. if (!is.null(config$error_bar_params$custom_error_bar)) {
  805. custom_ymin_expr <- rlang::parse_expr(config$error_bar_params$custom_error_bar$ymin)
  806. custom_ymax_expr <- rlang::parse_expr(config$error_bar_params$custom_error_bar$ymax)
  807. plot <- plot + geom_errorbar(
  808. aes(
  809. ymin = !!custom_ymin_expr,
  810. ymax = !!custom_ymax_expr
  811. ),
  812. color = config$error_bar_params$color,
  813. linewidth = ifelse(is.null(config$error_bar_params$linewidth), 0.1, config$error_bar_params$linewidth)
  814. )
  815. } else {
  816. # If no custom error bar formula, use the default or dynamic ones
  817. if (!is.null(config$color_var) && config$color_var %in% colnames(config$df)) {
  818. # Only use color_var if it's present in the dataframe
  819. plot <- plot + geom_errorbar(
  820. aes(
  821. ymin = !!sym(y_mean_col) - !!sym(y_sd_col),
  822. ymax = !!sym(y_mean_col) + !!sym(y_sd_col),
  823. color = !!sym(config$color_var)
  824. ),
  825. linewidth = 0.1
  826. )
  827. } else {
  828. # If color_var is missing, fall back to a default color or none
  829. plot <- plot + geom_errorbar(
  830. aes(
  831. ymin = !!sym(y_mean_col) - !!sym(y_sd_col),
  832. ymax = !!sym(y_mean_col) + !!sym(y_sd_col)
  833. ),
  834. color = config$error_bar_params$color, # use the provided color or default
  835. linewidth = ifelse(is.null(config$error_bar_params$linewidth), 0.1, config$error_bar_params$linewidth)
  836. )
  837. }
  838. }
  839. # Add the center point if the option is provided
  840. if (!is.null(config$error_bar_params$mean_point) && config$error_bar_params$mean_point) {
  841. if (!is.null(config$error_bar_params$color)) {
  842. plot <- plot + geom_point(
  843. aes(x = !!sym(config$x_var), y = !!sym(y_mean_col)),
  844. color = config$error_bar_params$color,
  845. shape = 16
  846. )
  847. } else {
  848. plot <- plot + geom_point(
  849. aes(x = !!sym(config$x_var), y = !!sym(y_mean_col)),
  850. shape = 16
  851. )
  852. }
  853. }
  854. }
  855. # Add linear regression line if specified
  856. if (!is.null(config$lm_line)) {
  857. # Extract necessary values
  858. intercept <- config$lm_line$intercept # required
  859. slope <- config$lm_line$slope # required
  860. xmin <- ifelse(!is.null(config$lm_line$xmin), config$lm_line$xmin, min(as.numeric(config$df[[config$x_var]])))
  861. xmax <- ifelse(!is.null(config$lm_line$xmax), config$lm_line$xmax, max(as.numeric(config$df[[config$x_var]])))
  862. color <- ifelse(!is.null(config$lm_line$color), config$lm_line$color, "blue")
  863. linewidth <- ifelse(!is.null(config$lm_line$linewidth), config$lm_line$linewidth, 1)
  864. ymin <- intercept + slope * xmin
  865. ymax <- intercept + slope * xmax
  866. # Ensure y-values are within y-limits (if any)
  867. if (!is.null(config$ylim_vals)) {
  868. ymin_within_limits <- ymin >= config$ylim_vals[1] && ymin <= config$ylim_vals[2]
  869. ymax_within_limits <- ymax >= config$ylim_vals[1] && ymax <= config$ylim_vals[2]
  870. # Adjust or skip based on whether the values fall within limits
  871. if (ymin_within_limits && ymax_within_limits) {
  872. plot <- plot + annotate(
  873. "segment",
  874. x = xmin,
  875. xend = xmax,
  876. y = ymin,
  877. yend = ymax,
  878. color = color,
  879. linewidth = linewidth,
  880. )
  881. } else {
  882. message("Skipping linear regression line due to y-values outside of limits")
  883. }
  884. } else {
  885. # If no y-limits are provided, proceed with the annotation
  886. plot <- plot + annotate(
  887. "segment",
  888. x = xmin,
  889. xend = xmax,
  890. y = ymin,
  891. yend = ymax,
  892. color = color,
  893. linewidth = linewidth
  894. )
  895. }
  896. }
  897. # Add SD Bands if specified
  898. if (!is.null(config$sd_band)) {
  899. plot <- plot +
  900. annotate(
  901. "rect",
  902. xmin = -Inf, xmax = Inf,
  903. ymin = config$sd_band, ymax = Inf,
  904. fill = ifelse(!is.null(config$fill_positive), config$fill_positive, "#542788"),
  905. alpha = ifelse(!is.null(config$alpha_positive), config$alpha_positive, 0.3)
  906. ) +
  907. annotate(
  908. "rect",
  909. xmin = -Inf, xmax = Inf,
  910. ymin = -config$sd_band, ymax = -Inf,
  911. fill = ifelse(!is.null(config$fill_negative), config$fill_negative, "orange"),
  912. alpha = ifelse(!is.null(config$alpha_negative), config$alpha_negative, 0.3)
  913. ) +
  914. geom_hline(
  915. yintercept = c(-config$sd_band, config$sd_band),
  916. color = ifelse(!is.null(config$hl_color), config$hl_color, "black")
  917. )
  918. }
  919. # # Add rectangles if specified
  920. # if (!is.null(config$rectangles)) {
  921. # for (rect in config$rectangles) {
  922. # plot <- plot + annotate(
  923. # "rect",
  924. # xmin = rect$xmin,
  925. # xmax = rect$xmax,
  926. # ymin = rect$ymin,
  927. # ymax = rect$ymax,
  928. # fill = ifelse(is.null(rect$fill), NA, rect$fill),
  929. # color = ifelse(is.null(rect$color), "black", rect$color),
  930. # alpha = ifelse(is.null(rect$alpha), 0.1, rect$alpha)
  931. # )
  932. # }
  933. # }
  934. # Customize X-axis if specified
  935. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  936. # Check if x_var is factor or character (for discrete x-axis)
  937. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  938. plot <- plot +
  939. scale_x_discrete(
  940. name = config$x_label,
  941. breaks = config$x_breaks,
  942. labels = config$x_labels
  943. )
  944. } else {
  945. plot <- plot +
  946. scale_x_continuous(
  947. name = config$x_label,
  948. breaks = config$x_breaks,
  949. labels = config$x_labels
  950. )
  951. }
  952. }
  953. # Set Y-axis limits if specified
  954. if (!is.null(config$ylim_vals)) {
  955. plot <- plot + scale_y_continuous(limits = config$ylim_vals)
  956. }
  957. return(plot)
  958. }
  959. generate_boxplot <- function(plot, config) {
  960. # Convert x_var to a factor within aes mapping
  961. plot <- plot + geom_boxplot(aes(x = factor(!!sym(config$x_var))))
  962. # Customize X-axis if specified
  963. if (!is.null(config$x_breaks) && !is.null(config$x_labels) && !is.null(config$x_label)) {
  964. # Check if x_var is factor or character (for discrete x-axis)
  965. if (is.factor(plot$data[[config$x_var]]) || is.character(plot$data[[config$x_var]])) {
  966. plot <- plot +
  967. scale_x_discrete(
  968. name = config$x_label,
  969. breaks = config$x_breaks,
  970. labels = config$x_labels
  971. )
  972. } else {
  973. plot <- plot +
  974. scale_x_continuous(
  975. name = config$x_label,
  976. breaks = config$x_breaks,
  977. labels = config$x_labels
  978. )
  979. }
  980. }
  981. return(plot)
  982. }
  983. generate_plate_analysis_plot_configs <- function(variables, df_before = NULL, df_after = NULL,
  984. plot_type = "scatter", stages = c("before", "after")) {
  985. plot_configs <- list()
  986. for (var in variables) {
  987. for (stage in stages) {
  988. df_plot <- if (stage == "before") df_before else df_after
  989. # Check for non-finite values in the y-variable
  990. # df_plot_filtered <- df_plot %>% filter(is.finite(!!sym(var)))
  991. # Adjust settings based on plot_type
  992. plot_config <- list(
  993. df = df_plot,
  994. x_var = "scan",
  995. y_var = var,
  996. plot_type = plot_type,
  997. title = paste("Plate analysis by Drug Conc for", var, stage, "quality control"),
  998. color_var = "conc_num_factor_factor",
  999. size = 0.2,
  1000. error_bar = (plot_type == "scatter"),
  1001. legend_position = "bottom",
  1002. filter_na = TRUE
  1003. )
  1004. # Add config to plots list
  1005. plot_configs <- append(plot_configs, list(plot_config))
  1006. }
  1007. }
  1008. return(list(plots = plot_configs))
  1009. }
  1010. generate_interaction_plot_configs <- function(df_summary, df_interactions, type) {
  1011. # Define the y-limits for the plots
  1012. limits_map <- list(
  1013. L = c(0, 130),
  1014. K = c(-20, 160),
  1015. r = c(0, 1),
  1016. AUC = c(0, 12500)
  1017. )
  1018. stats_plot_configs <- list()
  1019. stats_boxplot_configs <- list()
  1020. delta_plot_configs <- list()
  1021. # Overall statistics plots
  1022. OrfRep <- first(df_summary$OrfRep) # this should correspond to the reference strain
  1023. for (plot_type in c("scatter", "box")) {
  1024. for (var in names(limits_map)) {
  1025. y_limits <- limits_map[[var]]
  1026. y_span <- y_limits[2] - y_limits[1]
  1027. # Common plot configuration
  1028. plot_config <- list(
  1029. df = df_summary,
  1030. plot_type = plot_type,
  1031. x_var = "conc_num_factor_factor",
  1032. y_var = var,
  1033. shape = 16,
  1034. x_label = paste0("[", unique(df_summary$Drug)[1], "]"),
  1035. coord_cartesian = y_limits,
  1036. x_breaks = unique(df_summary$conc_num_factor_factor),
  1037. x_labels = as.character(unique(df_summary$conc_num))
  1038. )
  1039. # Add specific configurations for scatter and box plots
  1040. if (plot_type == "scatter") {
  1041. plot_config$title <- sprintf("%s Scatter RF for %s with SD", OrfRep, var)
  1042. plot_config$error_bar <- TRUE
  1043. plot_config$error_bar_params <- list(
  1044. color = "red",
  1045. mean_point = TRUE,
  1046. y_mean_col = paste0("mean_mean_", var),
  1047. y_sd_col = paste0("mean_sd_", var)
  1048. )
  1049. plot_config$position <- "jitter"
  1050. annotations <- list(
  1051. list(x = 0.25, y = y_limits[1] + 0.08 * y_span, label = " NG =", size = 4),
  1052. list(x = 0.25, y = y_limits[1] + 0.04 * y_span, label = " DB =", size = 4),
  1053. list(x = 0.25, y = y_limits[1], label = " SM =", size = 4)
  1054. )
  1055. for (x_val in unique(df_summary$conc_num_factor_factor)) {
  1056. current_df <- df_summary %>% filter(!!sym(plot_config$x_var) == x_val)
  1057. annotations <- append(annotations, list(
  1058. list(x = x_val, y = y_limits[1] + 0.08 * y_span, label = first(current_df$NG, default = 0), size = 4),
  1059. list(x = x_val, y = y_limits[1] + 0.04 * y_span, label = first(current_df$DB, default = 0), size = 4),
  1060. list(x = x_val, y = y_limits[1], label = first(current_df$SM, default = 0), size = 4)
  1061. ))
  1062. }
  1063. plot_config$annotations <- annotations
  1064. stats_plot_configs <- append(stats_plot_configs, list(plot_config))
  1065. } else if (plot_type == "box") {
  1066. plot_config$title <- sprintf("%s Box RF for %s with SD", OrfRep, var)
  1067. plot_config$position <- "dodge"
  1068. stats_boxplot_configs <- append(stats_boxplot_configs, list(plot_config))
  1069. }
  1070. }
  1071. }
  1072. # Delta interaction plots
  1073. delta_limits_map <- list(
  1074. L = c(-60, 60),
  1075. K = c(-60, 60),
  1076. r = c(-0.6, 0.6),
  1077. AUC = c(-6000, 6000)
  1078. )
  1079. # Select the data grouping by data type
  1080. if (type == "reference") {
  1081. group_vars <- c("OrfRep", "Gene", "num")
  1082. } else if (type == "deletion") {
  1083. group_vars <- c("OrfRep", "Gene")
  1084. }
  1085. grouped_data <- df_interactions %>%
  1086. group_by(across(all_of(group_vars))) %>%
  1087. group_split()
  1088. for (group_data in grouped_data) {
  1089. # Build the plot title
  1090. OrfRep <- first(group_data$OrfRep)
  1091. Gene <- first(group_data$Gene)
  1092. if (type == "reference") {
  1093. num <- if ("num" %in% names(group_data)) first(group_data$num) else ""
  1094. OrfRepTitle <- paste(OrfRep, Gene, num, sep = "_")
  1095. } else if (type == "deletion") {
  1096. OrfRepTitle <- OrfRep
  1097. }
  1098. for (var in names(delta_limits_map)) {
  1099. y_limits <- delta_limits_map[[var]]
  1100. y_span <- y_limits[2] - y_limits[1]
  1101. y_var_name <- paste0("Delta_", var)
  1102. # Anti-filter to select out-of-bounds rows
  1103. out_of_bounds <- group_data %>%
  1104. filter(is.na(!!sym(y_var_name)) |
  1105. !!sym(y_var_name) < y_limits[1] |
  1106. !!sym(y_var_name) > y_limits[2])
  1107. if (nrow(out_of_bounds) > 0) {
  1108. message(sprintf("Filtered %d row(s) from '%s' because %s is outside of y-limits: [%f, %f]",
  1109. nrow(out_of_bounds), OrfRepTitle, y_var_name, y_limits[1], y_limits[2]
  1110. ))
  1111. }
  1112. # Do the actual filtering
  1113. group_data_filtered <- group_data %>%
  1114. filter(!is.na(!!sym(y_var_name)) &
  1115. !!sym(y_var_name) >= y_limits[1] &
  1116. !!sym(y_var_name) <= y_limits[2])
  1117. if (nrow(group_data_filtered) == 0) {
  1118. message("Insufficient data for plot: ", OrfRepTitle, " ", var)
  1119. next # skip plot if insufficient data is available
  1120. }
  1121. WT_sd_value <- first(group_data_filtered[[paste0("WT_sd_", var)]], default = 0)
  1122. Z_Shift_value <- round(first(group_data_filtered[[paste0("Z_Shift_", var)]], default = 0), 2)
  1123. Z_lm_value <- round(first(group_data_filtered[[paste0("Z_lm_", var)]], default = 0), 2)
  1124. R_squared_value <- round(first(group_data_filtered[[paste0("R_Squared_", var)]], default = 0), 2)
  1125. NG_value <- first(group_data_filtered$NG, default = 0)
  1126. DB_value <- first(group_data_filtered$DB, default = 0)
  1127. SM_value <- first(group_data_filtered$SM, default = 0)
  1128. lm_intercept_col <- paste0("lm_intercept_", var)
  1129. lm_slope_col <- paste0("lm_slope_", var)
  1130. lm_intercept <- first(group_data_filtered[[lm_intercept_col]], default = 0)
  1131. lm_slope <- first(group_data_filtered[[lm_slope_col]], default = 0)
  1132. plot_config <- list(
  1133. df = group_data_filtered,
  1134. plot_type = "scatter",
  1135. x_var = "conc_num_factor_factor",
  1136. y_var = y_var_name,
  1137. x_label = paste0("[", unique(df_summary$Drug)[1], "]"),
  1138. shape = 16,
  1139. title = paste(OrfRepTitle, Gene, sep = " "),
  1140. title_size = rel(1.4),
  1141. coord_cartesian = y_limits,
  1142. annotations = list(
  1143. list(x = 1, y = y_limits[2] - 0.1 * y_span, label = paste(" ZShift =", round(Z_Shift_value, 2))),
  1144. list(x = 1, y = y_limits[2] - 0.2 * y_span, label = paste(" lm ZScore =", round(Z_lm_value, 2))),
  1145. # list(x = 1, y = y_limits[2] - 0.3 * y_span, label = paste(" R-squared =", round(R_squared_value, 2))),
  1146. list(x = 1, y = y_limits[1] + 0.1 * y_span, label = paste("NG =", NG_value)),
  1147. list(x = 1, y = y_limits[1] + 0.05 * y_span, label = paste("DB =", DB_value)),
  1148. list(x = 1, y = y_limits[1], label = paste("SM =", SM_value))
  1149. ),
  1150. error_bar = TRUE,
  1151. error_bar_params = list(
  1152. custom_error_bar = list(
  1153. ymin = paste0("0 - 2 * WT_sd_", var),
  1154. ymax = paste0("0 + 2 * WT_sd_", var)
  1155. ),
  1156. color = "gray70",
  1157. linewidth = 0.5
  1158. ),
  1159. x_breaks = unique(group_data_filtered$conc_num_factor_factor),
  1160. x_labels = as.character(unique(group_data_filtered$conc_num)),
  1161. ylim_vals = y_limits,
  1162. lm_line = list(
  1163. intercept = lm_intercept,
  1164. slope = lm_slope,
  1165. color = "blue",
  1166. linewidth = 0.8
  1167. )
  1168. )
  1169. delta_plot_configs <- append(delta_plot_configs, list(plot_config))
  1170. }
  1171. }
  1172. # Group delta plots in chunks of 12 per page
  1173. chunk_size <- 12
  1174. delta_plot_chunks <- split(delta_plot_configs, ceiling(seq_along(delta_plot_configs) / chunk_size))
  1175. return(c(
  1176. list(list(grid_layout = list(ncol = 2), plots = stats_plot_configs)),
  1177. list(list(grid_layout = list(ncol = 2), plots = stats_boxplot_configs)),
  1178. lapply(delta_plot_chunks, function(chunk) list(grid_layout = list(ncol = 4), plots = chunk))
  1179. ))
  1180. }
  1181. generate_rank_plot_configs <- function(df, is_lm = FALSE, filter_na = FALSE, overlap_color = FALSE) {
  1182. sd_bands <- c(1, 2, 3)
  1183. plot_configs <- list()
  1184. variables <- c("L", "K")
  1185. # Helper function to create a rank plot configuration
  1186. create_plot_config <- function(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = TRUE) {
  1187. num_enhancers <- sum(df[[zscore_var]] >= sd_band, na.rm = TRUE)
  1188. num_suppressors <- sum(df[[zscore_var]] <= -sd_band, na.rm = TRUE)
  1189. # Default plot config
  1190. plot_config <- list(
  1191. df = df,
  1192. x_var = rank_var,
  1193. y_var = zscore_var,
  1194. x_label = "Rank",
  1195. y_label = y_label,
  1196. plot_type = "scatter",
  1197. title = paste(y_label, "vs. Rank for", variable, "above", sd_band, "SD"),
  1198. sd_band = sd_band,
  1199. fill_positive = "#542788",
  1200. fill_negative = "orange",
  1201. alpha_positive = 0.3,
  1202. alpha_negative = 0.3,
  1203. shape = 3,
  1204. size = 0.1,
  1205. filter_na = filter_na,
  1206. legend_position = "none"
  1207. )
  1208. # Selectively add annotations
  1209. if (with_annotations) {
  1210. plot_config$annotations <- list(
  1211. list(
  1212. x = nrow(df) / 2,
  1213. y = 10,
  1214. label = paste("Deletion Enhancers =", num_enhancers)
  1215. ),
  1216. list(
  1217. x = nrow(df) / 2,
  1218. y = -10,
  1219. label = paste("Deletion Suppressors =", num_suppressors)
  1220. )
  1221. )
  1222. }
  1223. return(plot_config)
  1224. }
  1225. # Generate plots for each variable
  1226. for (variable in variables) {
  1227. rank_var <- if (is_lm) paste0("Rank_lm_", variable) else paste0("Rank_", variable)
  1228. zscore_var <- if (is_lm) paste0("Z_lm_", variable) else paste0("Avg_Zscore_", variable)
  1229. y_label <- if (is_lm) paste("Int Z score", variable) else paste("Avg Z score", variable)
  1230. # Loop through SD bands
  1231. for (sd_band in sd_bands) {
  1232. # Create plot with annotations
  1233. plot_configs[[length(plot_configs) + 1]] <-
  1234. create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = TRUE)
  1235. # Create plot without annotations
  1236. plot_configs[[length(plot_configs) + 1]] <-
  1237. create_plot_config(variable, rank_var, zscore_var, y_label, sd_band, filter_na, with_annotations = FALSE)
  1238. }
  1239. }
  1240. # Group delta plots in chunks of 6 per page
  1241. chunk_size <- 6
  1242. plot_chunks <- split(plot_configs, ceiling(seq_along(plot_configs) / chunk_size))
  1243. return(c(
  1244. lapply(plot_chunks, function(chunk) list(grid_layout = list(ncol = 3), plots = chunk))
  1245. ))
  1246. }
  1247. generate_correlation_plot_configs <- function(df, df_reference) {
  1248. # Define relationships for different-variable correlations
  1249. relationships <- list(
  1250. list(x = "L", y = "K"), # x-var is predictor, y-var is reponse
  1251. list(x = "L", y = "r"),
  1252. list(x = "L", y = "AUC"),
  1253. list(x = "K", y = "r"),
  1254. list(x = "K", y = "AUC"),
  1255. list(x = "r", y = "AUC")
  1256. )
  1257. # Filter both dataframes for missing linear model zscores for plotting
  1258. df <- df %>%
  1259. filter(!is.na(Z_lm_L))
  1260. df_reference <- df_reference %>%
  1261. filter(!is.na(Z_lm_L))
  1262. plot_configs <- list()
  1263. # Iterate over the option to highlight cyan points (TRUE/FALSE)
  1264. highlight_cyan_options <- c(FALSE, TRUE)
  1265. for (highlight_cyan in highlight_cyan_options) {
  1266. for (rel in relationships) {
  1267. # Extract relevant variable names for Z_lm values
  1268. x_var <- paste0("Z_lm_", rel$x) # predictor
  1269. y_var <- paste0("Z_lm_", rel$y) # response
  1270. # Find the max and min of both dataframes for printing linear regression line
  1271. xmin <- min(c(min(df[[x_var]], na.rm = TRUE), min(df_reference[[x_var]], na.rm = TRUE)), na.rm = TRUE)
  1272. xmax <- max(c(max(df[[x_var]], na.rm = TRUE), max(df_reference[[x_var]], na.rm = TRUE)), na.rm = TRUE)
  1273. # Extract the R-squared, intercept, and slope from the df (first value)
  1274. intercept <- df[[paste0("Z_lm_intercept_", rel$y, "_", rel$x)]][1]
  1275. slope <- df[[paste0("Z_lm_slope_", rel$y, "_", rel$x)]][1]
  1276. r_squared <- df[[paste0("Z_lm_R_squared_", rel$y, "_", rel$x)]][1]
  1277. # Generate the label for the plot
  1278. plot_label <- paste("Interaction", rel$x, "vs.", rel$y)
  1279. # Construct plot config
  1280. plot_config <- list(
  1281. df = df,
  1282. df_reference = df_reference,
  1283. x_var = x_var,
  1284. y_var = y_var,
  1285. plot_type = "scatter",
  1286. title = plot_label,
  1287. annotations = list(
  1288. list(
  1289. x = mean(df[[x_var]], na.rm = TRUE),
  1290. y = mean(df[[y_var]], na.rm = TRUE),
  1291. label = paste("R-squared =", round(r_squared, 3))
  1292. )
  1293. ),
  1294. lm_line = list(
  1295. intercept = intercept,
  1296. slope = slope,
  1297. color = "tomato3",
  1298. linewidth = 0.8,
  1299. xmin = xmin,
  1300. xmax = xmax
  1301. ),
  1302. color = "gray70",
  1303. filter_na = TRUE,
  1304. cyan_points = highlight_cyan # include cyan points or not based on the loop
  1305. )
  1306. plot_configs <- append(plot_configs, list(plot_config))
  1307. }
  1308. }
  1309. return(list(plots = plot_configs))
  1310. }
  1311. main <- function() {
  1312. lapply(names(args$experiments), function(exp_name) {
  1313. exp <- args$experiments[[exp_name]]
  1314. exp_path <- exp$path
  1315. exp_sd <- exp$sd
  1316. out_dir <- file.path(exp_path, "zscores")
  1317. out_dir_qc <- file.path(exp_path, "zscores", "qc")
  1318. dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
  1319. dir.create(out_dir_qc, recursive = TRUE, showWarnings = FALSE)
  1320. # Each list of plots corresponds to a separate file
  1321. message("Loading and filtering data for experiment: ", exp_name)
  1322. df <- load_and_filter_data(args$easy_results_file, sd = exp_sd) %>%
  1323. update_gene_names(args$sgd_gene_list) %>%
  1324. as_tibble()
  1325. l_vs_k_plot_configs <- list(
  1326. plots = list(
  1327. list(
  1328. df = df,
  1329. x_var = "L",
  1330. y_var = "K",
  1331. plot_type = "scatter",
  1332. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1333. title = "Raw L vs K before quality control",
  1334. color_var = "conc_num_factor_factor",
  1335. error_bar = FALSE,
  1336. legend_position = "right"
  1337. )
  1338. )
  1339. )
  1340. message("Calculating summary statistics before quality control")
  1341. df_stats <- calculate_summary_stats( # formerly X_stats_ALL
  1342. df = df,
  1343. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1344. group_vars = c("conc_num", "conc_num_factor_factor"))$df_with_stats
  1345. frequency_delta_bg_plot_configs <- list(
  1346. plots = list(
  1347. list(
  1348. df = df_stats,
  1349. x_var = "delta_bg",
  1350. y_var = NULL,
  1351. plot_type = "density",
  1352. title = "Density plot for Delta Background by [Drug] (All Data)",
  1353. color_var = "conc_num_factor_factor",
  1354. x_label = "Delta Background",
  1355. y_label = "Density",
  1356. error_bar = FALSE,
  1357. legend_position = "right"
  1358. ),
  1359. list(
  1360. df = df_stats,
  1361. x_var = "delta_bg",
  1362. y_var = NULL,
  1363. plot_type = "bar",
  1364. title = "Bar plot for Delta Background by [Drug] (All Data)",
  1365. color_var = "conc_num_factor_factor",
  1366. x_label = "Delta Background",
  1367. y_label = "Count",
  1368. error_bar = FALSE,
  1369. legend_position = "right"
  1370. )
  1371. )
  1372. )
  1373. message("Filtering rows above delta background tolerance for plotting")
  1374. df_above_tolerance <- df %>% filter(DB == 1)
  1375. above_threshold_plot_configs <- list(
  1376. plots = list(
  1377. list(
  1378. df = df_above_tolerance,
  1379. x_var = "L",
  1380. y_var = "K",
  1381. plot_type = "scatter",
  1382. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1383. title = paste("Raw L vs K for strains above Delta Background threshold of",
  1384. round(df_above_tolerance$delta_bg_tolerance[[1]], 3), "or above"),
  1385. color_var = "conc_num_factor_factor",
  1386. position = "jitter",
  1387. annotations = list(
  1388. list(
  1389. x = median(df_above_tolerance$L, na.rm = TRUE) / 2,
  1390. y = median(df_above_tolerance$K, na.rm = TRUE) / 2,
  1391. label = paste("# strains above Delta Background tolerance =", nrow(df_above_tolerance))
  1392. )
  1393. ),
  1394. error_bar = FALSE,
  1395. legend_position = "right"
  1396. )
  1397. )
  1398. )
  1399. message("Setting rows above delta background tolerance to NA")
  1400. df_na <- df %>% mutate(across(all_of(c("L", "K", "r", "AUC", "delta_bg")), ~ ifelse(DB == 1, NA, .))) # formerly X
  1401. message("Calculating summary statistics across all strains")
  1402. ss <- calculate_summary_stats(
  1403. df = df_na,
  1404. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1405. group_vars = c("conc_num", "conc_num_factor_factor"))
  1406. df_na_ss <- ss$summary_stats
  1407. df_na_stats <- ss$df_with_stats # formerly X_stats_ALL
  1408. write.csv(df_na_ss, file = file.path(out_dir, "summary_stats_all_strains.csv"), row.names = FALSE)
  1409. # This can help bypass missing values ggplot warnings during testing
  1410. df_na_stats_filtered <- df_na_stats %>% filter(if_all(all_of(c("L", "K", "r", "AUC", "delta_bg")), is.finite))
  1411. message("Calculating summary statistics excluding zero values")
  1412. df_no_zeros <- df_na %>% filter(L > 0) # formerly X_noZero
  1413. df_no_zeros_stats <- calculate_summary_stats(
  1414. df = df_no_zeros,
  1415. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1416. group_vars = c("conc_num", "conc_num_factor_factor")
  1417. )$df_with_stats
  1418. message("Filtering by 2SD of K")
  1419. df_na_within_2sd_k <- df_na_stats %>%
  1420. filter(K >= (mean_K - 2 * sd_K) & K <= (mean_K + 2 * sd_K))
  1421. df_na_outside_2sd_k <- df_na_stats %>%
  1422. filter(K < (mean_K - 2 * sd_K) | K > (mean_K + 2 * sd_K))
  1423. message("Calculating summary statistics for L within 2SD of K")
  1424. # TODO We're omitting the original z_max calculation, not sure if needed?
  1425. ss <- calculate_summary_stats(df_na_within_2sd_k, "L", # formerly X_stats_BY_L_within_2SD_K
  1426. group_vars = c("conc_num", "conc_num_factor_factor"))$summary_stats
  1427. write.csv(ss,
  1428. file = file.path(out_dir_qc, "max_observed_L_vals_for_spots_within_2SD_K.csv"),
  1429. row.names = FALSE)
  1430. message("Calculating summary statistics for L outside 2SD of K")
  1431. ss <- calculate_summary_stats(df_na_outside_2sd_k, "L", # formerly X_stats_BY_L_outside_2SD_K
  1432. group_vars = c("conc_num", "conc_num_factor_factor"))
  1433. df_na_l_outside_2sd_k_stats <- ss$df_with_stats
  1434. write.csv(ss$summary_stats,
  1435. file = file.path(out_dir, "max_observed_L_vals_for_spots_outside_2SD_K.csv"),
  1436. row.names = FALSE)
  1437. plate_analysis_plot_configs <- generate_plate_analysis_plot_configs(
  1438. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1439. df_before = df_stats,
  1440. df_after = df_na_stats_filtered
  1441. )
  1442. plate_analysis_boxplot_configs <- generate_plate_analysis_plot_configs(
  1443. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1444. df_before = df_stats,
  1445. df_after = df_na_stats_filtered,
  1446. plot_type = "box"
  1447. )
  1448. plate_analysis_no_zeros_plot_configs <- generate_plate_analysis_plot_configs(
  1449. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1450. stages = c("after"), # Only after QC
  1451. df_after = df_no_zeros_stats
  1452. )
  1453. plate_analysis_no_zeros_boxplot_configs <- generate_plate_analysis_plot_configs(
  1454. variables = c("L", "K", "r", "AUC", "delta_bg"),
  1455. stages = c("after"), # Only after QC
  1456. df_after = df_no_zeros_stats,
  1457. plot_type = "box"
  1458. )
  1459. l_outside_2sd_k_plot_configs <- list(
  1460. plots = list(
  1461. list(
  1462. df = df_na_l_outside_2sd_k_stats,
  1463. x_var = "L",
  1464. y_var = "K",
  1465. plot_type = "scatter",
  1466. title = "Raw L vs K for strains falling outside 2 SD of the K mean at each Conc",
  1467. color_var = "conc_num_factor_factor",
  1468. position = "jitter",
  1469. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1470. annotations = list(
  1471. list(
  1472. x = median(df_na_l_outside_2sd_k_stats$L, na.rm = TRUE) / 2,
  1473. y = median(df_na_l_outside_2sd_k_stats$K, na.rm = TRUE) / 2,
  1474. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats))
  1475. )
  1476. ),
  1477. error_bar = FALSE,
  1478. legend_position = "right"
  1479. )
  1480. )
  1481. )
  1482. delta_bg_outside_2sd_k_plot_configs <- list(
  1483. plots = list(
  1484. list(
  1485. df = df_na_l_outside_2sd_k_stats,
  1486. x_var = "delta_bg",
  1487. x_label = "Delta Background",
  1488. y_var = "K",
  1489. plot_type = "scatter",
  1490. title = "Delta Background vs K for strains falling outside 2 SD of K",
  1491. color_var = "conc_num_factor_factor",
  1492. position = "jitter",
  1493. tooltip_vars = c("OrfRep", "Gene", "delta_bg"),
  1494. annotations = list(
  1495. list(
  1496. x = 0.05,
  1497. y = 0.95,
  1498. hjust = 0,
  1499. vjust = 1,
  1500. label = paste("Total strains:", nrow(df_na_l_outside_2sd_k_stats)),
  1501. size = 5
  1502. )
  1503. ),
  1504. error_bar = FALSE,
  1505. legend_position = "right"
  1506. )
  1507. )
  1508. )
  1509. message("Generating quality control plots in parallel")
  1510. # future::plan(future::multicore, workers = parallel::detectCores())
  1511. future::plan(future::multisession, workers = 3) # generate 3 plot files in parallel
  1512. plot_configs <- list(
  1513. list(out_dir = out_dir_qc, filename = "L_vs_K_before_quality_control",
  1514. plot_configs = l_vs_k_plot_configs, page_width = 12, page_height = 8),
  1515. list(out_dir = out_dir_qc, filename = "frequency_delta_background",
  1516. plot_configs = frequency_delta_bg_plot_configs, page_width = 12, page_height = 8),
  1517. list(out_dir = out_dir_qc, filename = "L_vs_K_above_threshold",
  1518. plot_configs = above_threshold_plot_configs, page_width = 12, page_height = 8),
  1519. list(out_dir = out_dir_qc, filename = "plate_analysis",
  1520. plot_configs = plate_analysis_plot_configs, page_width = 14, page_height = 9),
  1521. list(out_dir = out_dir_qc, filename = "plate_analysis_boxplots",
  1522. plot_configs = plate_analysis_boxplot_configs, page_width = 18, page_height = 9),
  1523. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros",
  1524. plot_configs = plate_analysis_no_zeros_plot_configs, page_width = 14, page_height = 9),
  1525. list(out_dir = out_dir_qc, filename = "plate_analysis_no_zeros_boxplots",
  1526. plot_configs = plate_analysis_no_zeros_boxplot_configs, page_width = 18, page_height = 9),
  1527. list(out_dir = out_dir_qc, filename = "L_vs_K_for_strains_2SD_outside_mean_K",
  1528. plot_configs = l_outside_2sd_k_plot_configs, page_width = 10, page_height = 8),
  1529. list(out_dir = out_dir_qc, filename = "delta_background_vs_K_for_strains_2SD_outside_mean_K",
  1530. plot_configs = delta_bg_outside_2sd_k_plot_configs, page_width = 10, page_height = 8)
  1531. )
  1532. # Parallelize background and quality control plot generation
  1533. # furrr::future_map(plot_configs, function(config) {
  1534. # generate_and_save_plots(config$out_dir, config$filename, config$plot_configs,
  1535. # page_width = config$page_width, page_height = config$page_height)
  1536. # }, .options = furrr_options(seed = TRUE))
  1537. # Loop over background strains
  1538. # TODO currently only tested against one strain, if we want to do multiple strains we'll
  1539. # have to rename or group the output files by dir or something so they don't get clobbered
  1540. bg_strains <- c("YDL227C")
  1541. lapply(bg_strains, function(strain) {
  1542. message("Processing background strain: ", strain)
  1543. # Handle missing data by setting zero values to NA
  1544. # and then removing any rows with NA in L col
  1545. df_bg <- df_na %>%
  1546. filter(OrfRep == strain) %>%
  1547. mutate(
  1548. L = if_else(L == 0, NA, L),
  1549. K = if_else(K == 0, NA, K),
  1550. r = if_else(r == 0, NA, r),
  1551. AUC = if_else(AUC == 0, NA, AUC)
  1552. ) %>%
  1553. filter(!is.na(L))
  1554. message("Calculating background summary statistics")
  1555. ss_bg <- calculate_summary_stats(df_bg, c("L", "K", "r", "AUC", "delta_bg"), # formerly X_stats_BY
  1556. group_vars = c("OrfRep", "Drug", "conc_num", "conc_num_factor_factor"))
  1557. summary_stats_bg <- ss_bg$summary_stats
  1558. df_bg_stats <- ss_bg$df_with_stats
  1559. write.csv(
  1560. summary_stats_bg,
  1561. file = file.path(out_dir, paste0("summary_stats_background_strain_", strain, ".csv")),
  1562. row.names = FALSE)
  1563. message("Setting missing reference values to the highest theoretical value at each drug conc for L")
  1564. df_reference <- df_na_stats %>% # formerly X2_RF
  1565. filter(OrfRep == strain) %>%
  1566. filter(!is.na(L)) %>%
  1567. group_by(OrfRep, Drug, conc_num, conc_num_factor_factor) %>%
  1568. mutate(
  1569. max_l_theoretical = max(max_L, na.rm = TRUE),
  1570. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1571. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, 0),
  1572. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1573. ungroup()
  1574. message("Calculating reference strain summary statistics")
  1575. df_reference_summary_stats <- calculate_summary_stats( # formerly X_stats_X2_RF
  1576. df = df_reference,
  1577. variables = c("L", "K", "r", "AUC"),
  1578. group_vars = c("OrfRep", "Drug", "conc_num", "conc_num_factor_factor")
  1579. )$df_with_stats
  1580. # Summarise statistics for error bars
  1581. df_reference_summary_stats <- df_reference_summary_stats %>%
  1582. group_by(OrfRep, Drug, conc_num, conc_num_factor_factor) %>%
  1583. mutate(
  1584. mean_mean_L = first(mean_L),
  1585. mean_sd_L = first(sd_L),
  1586. mean_mean_K = first(mean_K),
  1587. mean_sd_K = first(sd_K),
  1588. mean_mean_r = first(mean_r),
  1589. mean_sd_r = first(sd_r),
  1590. mean_mean_AUC = first(mean_AUC),
  1591. mean_sd_AUC = first(sd_AUC),
  1592. .groups = "drop"
  1593. )
  1594. message("Calculating reference strain interaction summary statistics") # formerly X_stats_interaction
  1595. df_reference_interaction_stats <- calculate_summary_stats(
  1596. df = df_reference,
  1597. variables = c("L", "K", "r", "AUC"),
  1598. group_vars = c("OrfRep", "Gene", "num", "Drug", "conc_num", "conc_num_factor_factor")
  1599. )$df_with_stats
  1600. message("Calculating reference strain interaction scores")
  1601. reference_results <- calculate_interaction_scores(df_reference_interaction_stats, df_bg_stats, "reference")
  1602. df_reference_interactions_joined <- reference_results$full_data
  1603. df_reference_interactions <- reference_results$interactions
  1604. write.csv(reference_results$calculations, file = file.path(out_dir, "zscore_calculations_reference.csv"), row.names = FALSE)
  1605. write.csv(df_reference_interactions, file = file.path(out_dir, "zscore_interactions_reference.csv"), row.names = FALSE)
  1606. # message("Generating reference interaction plots")
  1607. # reference_plot_configs <- generate_interaction_plot_configs(df_reference_summary_stats, df_reference_interactions_joined, "reference")
  1608. # generate_and_save_plots(out_dir, "interaction_plots_reference", reference_plot_configs, page_width = 16, page_height = 16)
  1609. message("Setting missing deletion values to the highest theoretical value at each drug conc for L")
  1610. df_deletion <- df_na_stats %>% # formerly X2
  1611. filter(OrfRep != strain) %>%
  1612. filter(!is.na(L)) %>%
  1613. group_by(OrfRep, Gene, conc_num, conc_num_factor_factor) %>%
  1614. mutate(
  1615. max_l_theoretical = max(max_L, na.rm = TRUE),
  1616. L = ifelse(L == 0 & !is.na(L) & conc_num > 0, max_l_theoretical, L),
  1617. SM = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, 1, SM),
  1618. L = ifelse(L >= max_l_theoretical & !is.na(L) & conc_num > 0, max_l_theoretical, L)) %>%
  1619. ungroup()
  1620. message("Calculating deletion strain(s) interaction summary statistics")
  1621. df_deletion_stats <- calculate_summary_stats(
  1622. df = df_deletion,
  1623. variables = c("L", "K", "r", "AUC"),
  1624. group_vars = c("OrfRep", "Gene", "Drug", "conc_num", "conc_num_factor_factor")
  1625. )$df_with_stats
  1626. message("Calculating deletion strain(s) interactions scores")
  1627. deletion_results <- calculate_interaction_scores(df_deletion_stats, df_bg_stats, "deletion")
  1628. df_interactions <- deletion_results$interactions
  1629. df_interactions_joined <- deletion_results$full_data
  1630. write.csv(deletion_results$calculations, file = file.path(out_dir, "zscore_calculations.csv"), row.names = FALSE)
  1631. write.csv(df_interactions, file = file.path(out_dir, "zscore_interactions.csv"), row.names = FALSE)
  1632. # message("Generating deletion interaction plots")
  1633. # deletion_plot_configs <- generate_interaction_plot_configs(df_reference_summary_stats, df_interactions_joined, "deletion")
  1634. # generate_and_save_plots(out_dir, "interaction_plots", deletion_plot_configs, page_width = 16, page_height = 16)
  1635. # message("Writing enhancer/suppressor csv files")
  1636. # interaction_threshold <- 2 # TODO add to study config?
  1637. # enhancer_condition_L <- df_interactions$Avg_Zscore_L >= interaction_threshold
  1638. # suppressor_condition_L <- df_interactions$Avg_Zscore_L <= -interaction_threshold
  1639. # enhancer_condition_K <- df_interactions$Avg_Zscore_K >= interaction_threshold
  1640. # suppressor_condition_K <- df_interactions$Avg_Zscore_K <= -interaction_threshold
  1641. # enhancers_L <- df_interactions[enhancer_condition_L, ]
  1642. # suppressors_L <- df_interactions[suppressor_condition_L, ]
  1643. # enhancers_K <- df_interactions[enhancer_condition_K, ]
  1644. # suppressors_K <- df_interactions[suppressor_condition_K, ]
  1645. # enhancers_and_suppressors_L <- df_interactions[enhancer_condition_L | suppressor_condition_L, ]
  1646. # enhancers_and_suppressors_K <- df_interactions[enhancer_condition_K | suppressor_condition_K, ]
  1647. # write.csv(enhancers_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_L.csv"), row.names = FALSE)
  1648. # write.csv(suppressors_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_L.csv"), row.names = FALSE)
  1649. # write.csv(enhancers_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_K.csv"), row.names = FALSE)
  1650. # write.csv(suppressors_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_K.csv"), row.names = FALSE)
  1651. # write.csv(enhancers_and_suppressors_L,
  1652. # file = file.path(out_dir, "zscore_interactions_deletion_enhancers_and_suppressors_L.csv"), row.names = FALSE)
  1653. # write.csv(enhancers_and_suppressors_K,
  1654. # file = file.path(out_dir, "zscore_interaction_deletion_enhancers_and_suppressors_K.csv"), row.names = FALSE)
  1655. # message("Writing linear model enhancer/suppressor csv files")
  1656. # lm_interaction_threshold <- 2 # TODO add to study config?
  1657. # enhancers_lm_L <- df_interactions[df_interactions$Z_lm_L >= lm_interaction_threshold, ]
  1658. # suppressors_lm_L <- df_interactions[df_interactions$Z_lm_L <= -lm_interaction_threshold, ]
  1659. # enhancers_lm_K <- df_interactions[df_interactions$Z_lm_K >= lm_interaction_threshold, ]
  1660. # suppressors_lm_K <- df_interactions[df_interactions$Z_lm_K <= -lm_interaction_threshold, ]
  1661. # write.csv(enhancers_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_L.csv"), row.names = FALSE)
  1662. # write.csv(suppressors_lm_L, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_L.csv"), row.names = FALSE)
  1663. # write.csv(enhancers_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_enhancers_lm_K.csv"), row.names = FALSE)
  1664. # write.csv(suppressors_lm_K, file = file.path(out_dir, "zscore_interactions_deletion_suppressors_lm_K.csv"), row.names = FALSE)
  1665. # message("Generating rank plots")
  1666. # rank_plot_configs <- generate_rank_plot_configs(
  1667. # df_interactions,
  1668. # is_lm = FALSE,
  1669. # )
  1670. # generate_and_save_plots(out_dir, "rank_plots", rank_plot_configs,
  1671. # page_width = 18, page_height = 12)
  1672. # message("Generating ranked linear model plots")
  1673. # rank_lm_plot_configs <- generate_rank_plot_configs(
  1674. # df_interactions,
  1675. # is_lm = TRUE,
  1676. # )
  1677. # generate_and_save_plots(out_dir, "rank_plots_lm", rank_lm_plot_configs,
  1678. # page_width = 18, page_height = 12)
  1679. # message("Generating overlapped ranked plots")
  1680. # rank_plot_filtered_configs <- generate_rank_plot_configs(
  1681. # df_interactions,
  1682. # is_lm = FALSE,
  1683. # filter_na = TRUE,
  1684. # overlap_color = TRUE
  1685. # )
  1686. # generate_and_save_plots(out_dir, "rank_plots_na_rm", rank_plot_filtered_configs,
  1687. # page_width = 18, page_height = 12)
  1688. # message("Generating overlapped ranked linear model plots")
  1689. # rank_plot_lm_filtered_configs <- generate_rank_plot_configs(
  1690. # df_interactions,
  1691. # is_lm = TRUE,
  1692. # filter_na = TRUE,
  1693. # overlap_color = TRUE
  1694. # )
  1695. # generate_and_save_plots(out_dir, "rank_plots_lm_na_rm", rank_plot_lm_filtered_configs,
  1696. # page_width = 18, page_height = 12)
  1697. message("Generating correlation curve parameter pair plots")
  1698. correlation_plot_configs <- generate_correlation_plot_configs(
  1699. df_interactions,
  1700. df_reference_interactions
  1701. )
  1702. generate_and_save_plots(out_dir, "correlation_cpps", correlation_plot_configs,
  1703. page_width = 10, page_height = 7)
  1704. })
  1705. })
  1706. }
  1707. main()