calculate_interaction_zscores.R 61 KB

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