calculate_interaction_zscores.R 69 KB

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