calculate_interaction_zscores.R 60 KB

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