cmatkhan commited on
Commit
3683866
·
1 Parent(s): cca1a99

updating scripts

Browse files
Files changed (1) hide show
  1. scripts/barkai_annotated_features.R +484 -0
scripts/barkai_annotated_features.R ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quantifies enrichment of insertions/hops in genomic regions
2
+ #
3
+ # This script:
4
+ # 1. Counts insertions overlapping each genomic region (experiment and background)
5
+ # 2. Calculates enrichment scores
6
+ # 3. Computes z-score, Poisson and hypergeometric p-values
7
+ #
8
+ # Works with any data in BED3+ format (chr, start, end, ...)
9
+ # For calling cards: each insertion is counted once regardless of depth
10
+ #
11
+ # COORDINATE SYSTEMS:
12
+ # - Input BED files are assumed to be 0-indexed, half-open [start, end)
13
+ # - GenomicRanges uses 1-indexed, closed [start, end]
14
+ # - Conversion: GR_start = BED_start + 1, GR_end = BED_end
15
+
16
+ library(tidyverse)
17
+ library(GenomicRanges)
18
+
19
+ # Statistical Functions ---------------------------------------------------
20
+
21
+ #' Calculate enrichment (calling cards effect)
22
+ #'
23
+ #' @param total_background_hops Total number of hops in background (scalar or vector)
24
+ #' @param total_experiment_hops Total number of hops in experiment (scalar or vector)
25
+ #' @param background_hops Number of hops in background per region (vector)
26
+ #' @param experiment_hops Number of hops in experiment per region (vector)
27
+ #' @param pseudocount Pseudocount to avoid division by zero (default: 0.1)
28
+ #' @return Enrichment values
29
+ calculate_enrichment <- function(total_background_hops,
30
+ total_experiment_hops,
31
+ background_hops,
32
+ experiment_hops,
33
+ pseudocount = 0.1) {
34
+
35
+ # Input validation
36
+ if (!all(is.numeric(c(total_background_hops, total_experiment_hops,
37
+ background_hops, experiment_hops)))) {
38
+ stop("All inputs must be numeric")
39
+ }
40
+
41
+ # Get the length of the region vectors
42
+ n_regions <- length(background_hops)
43
+
44
+ # Ensure experiment_hops is same length as background_hops
45
+ if (length(experiment_hops) != n_regions) {
46
+ stop("background_hops and experiment_hops must be the same length")
47
+ }
48
+
49
+ # Recycle scalar totals to match region length if needed
50
+ if (length(total_background_hops) == 1) {
51
+ total_background_hops <- rep(total_background_hops, n_regions)
52
+ }
53
+ if (length(total_experiment_hops) == 1) {
54
+ total_experiment_hops <- rep(total_experiment_hops, n_regions)
55
+ }
56
+
57
+ # Now check all are same length
58
+ if (length(total_background_hops) != n_regions ||
59
+ length(total_experiment_hops) != n_regions) {
60
+ stop("All input vectors must be the same length or scalars")
61
+ }
62
+
63
+ # Calculate enrichment
64
+ numerator <- experiment_hops / total_experiment_hops
65
+ denominator <- (background_hops + pseudocount) / total_background_hops
66
+ enrichment <- numerator / denominator
67
+
68
+ # Check for invalid values
69
+ if (any(enrichment < 0, na.rm = TRUE)) {
70
+ stop("Enrichment values must be non-negative")
71
+ }
72
+ if (any(is.na(enrichment))) {
73
+ stop("Enrichment values must not be NA")
74
+ }
75
+ if (any(is.infinite(enrichment))) {
76
+ stop("Enrichment values must not be infinite")
77
+ }
78
+
79
+ return(enrichment)
80
+ }
81
+
82
+
83
+ #' Calculate Poisson p-values
84
+ #'
85
+ #' @param total_background_hops Total number of hops in background (scalar or vector)
86
+ #' @param total_experiment_hops Total number of hops in experiment (scalar or vector)
87
+ #' @param background_hops Number of hops in background per region (vector)
88
+ #' @param experiment_hops Number of hops in experiment per region (vector)
89
+ #' @param pseudocount Pseudocount for lambda calculation (default: 0.1)
90
+ #' @param ... additional arguments to `ppois`. note that lower tail is set to FALSE
91
+ #' already
92
+ #' @return Poisson p-values
93
+ calculate_poisson_pval <- function(total_background_hops,
94
+ total_experiment_hops,
95
+ background_hops,
96
+ experiment_hops,
97
+ pseudocount = 0.1,
98
+ ...) {
99
+
100
+ # Input validation
101
+ if (!all(is.numeric(c(total_background_hops, total_experiment_hops,
102
+ background_hops, experiment_hops)))) {
103
+ stop("All inputs must be numeric")
104
+ }
105
+
106
+ # Get the length of the region vectors
107
+ n_regions <- length(background_hops)
108
+
109
+ # Ensure experiment_hops is same length as background_hops
110
+ if (length(experiment_hops) != n_regions) {
111
+ stop("background_hops and experiment_hops must be the same length")
112
+ }
113
+
114
+ # Recycle scalar totals to match region length if needed
115
+ if (length(total_background_hops) == 1) {
116
+ total_background_hops <- rep(total_background_hops, n_regions)
117
+ }
118
+ if (length(total_experiment_hops) == 1) {
119
+ total_experiment_hops <- rep(total_experiment_hops, n_regions)
120
+ }
121
+
122
+ # Now check all are same length
123
+ if (length(total_background_hops) != n_regions ||
124
+ length(total_experiment_hops) != n_regions) {
125
+ stop("All input vectors must be the same length or scalars")
126
+ }
127
+
128
+ # Calculate hop ratio
129
+ hop_ratio <- total_experiment_hops / total_background_hops
130
+
131
+ # Calculate expected number of hops (mu/lambda parameter)
132
+ # Add pseudocount to avoid mu = 0
133
+ mu <- (background_hops + pseudocount) * hop_ratio
134
+
135
+ # Observed hops in experiment
136
+ x <- experiment_hops
137
+
138
+ # Calculate p-value: P(X >= x) = 1 - P(X < x) = 1 - P(X <= x-1)
139
+ # This is equivalent to: 1 - CDF(x) + PMF(x)
140
+ # Using the upper tail directly with lower.tail = FALSE
141
+ pval <- ppois(x - 1, lambda = mu, lower.tail = FALSE, ...)
142
+
143
+ return(pval)
144
+ }
145
+
146
+
147
+ #' Calculate hypergeometric p-values
148
+ #'
149
+ #' @param total_background_hops Total number of hops in background (scalar or vector)
150
+ #' @param total_experiment_hops Total number of hops in experiment (scalar or vector)
151
+ #' @param background_hops Number of hops in background per region (vector)
152
+ #' @param experiment_hops Number of hops in experiment per region (vector)
153
+ #' @param ... additional arguments to phyper. Note that lower tail is set to
154
+ #' false already
155
+ #' @return Hypergeometric p-values
156
+ calculate_hypergeom_pval <- function(total_background_hops,
157
+ total_experiment_hops,
158
+ background_hops,
159
+ experiment_hops,
160
+ ...) {
161
+
162
+ # Input validation
163
+ if (!all(is.numeric(c(total_background_hops, total_experiment_hops,
164
+ background_hops, experiment_hops)))) {
165
+ stop("All inputs must be numeric")
166
+ }
167
+
168
+ # Get the length of the region vectors
169
+ n_regions <- length(background_hops)
170
+
171
+ # Ensure experiment_hops is same length as background_hops
172
+ if (length(experiment_hops) != n_regions) {
173
+ stop("background_hops and experiment_hops must be the same length")
174
+ }
175
+
176
+ # Recycle scalar totals to match region length if needed
177
+ if (length(total_background_hops) == 1) {
178
+ total_background_hops <- rep(total_background_hops, n_regions)
179
+ }
180
+ if (length(total_experiment_hops) == 1) {
181
+ total_experiment_hops <- rep(total_experiment_hops, n_regions)
182
+ }
183
+
184
+ # Now check all are same length
185
+ if (length(total_background_hops) != n_regions ||
186
+ length(total_experiment_hops) != n_regions) {
187
+ stop("All input vectors must be the same length or scalars")
188
+ }
189
+
190
+ # Hypergeometric parameters
191
+ # M: total number of balls (total hops)
192
+ M <- total_background_hops + total_experiment_hops
193
+ # n: number of white balls (experiment hops)
194
+ n <- total_experiment_hops
195
+ # N: number of draws (hops in region)
196
+ N <- background_hops + experiment_hops
197
+ # x: number of white balls drawn (experiment hops in region) - 1 for upper tail
198
+ x <- experiment_hops - 1
199
+
200
+ # Handle edge cases
201
+ valid <- (M >= 1) & (N >= 1)
202
+ pval <- rep(1, length(M))
203
+
204
+ # Calculate p-value for valid cases: P(X >= x) = 1 - P(X <= x-1)
205
+ if (any(valid)) {
206
+ pval[valid] <- phyper(x[valid], n[valid], M[valid] - n[valid], N[valid],
207
+ lower.tail = FALSE, ...)
208
+ }
209
+
210
+ return(pval)
211
+ }
212
+
213
+ # GRanges Conversion Functions --------------------------------------------
214
+
215
+ #' Convert BED format data frame to GRanges
216
+ #'
217
+ #' Handles coordinate system conversion from 0-indexed half-open BED format
218
+ #' to 1-indexed closed GenomicRanges format
219
+ #'
220
+ #' @param bed_df Data frame with chr, start, end columns in BED format (0-indexed, half-open)
221
+ #' @param zero_indexed Logical, whether input is 0-indexed (default: TRUE)
222
+ #' @return GRanges object
223
+ bed_to_granges <- function(bed_df, zero_indexed = TRUE) {
224
+
225
+ if (!all(c("chr", "start", "end") %in% names(bed_df))) {
226
+ stop("bed_df must have columns: chr, start, end")
227
+ }
228
+
229
+ # Convert from 0-indexed half-open [start, end) to 1-indexed closed [start, end]
230
+ if (zero_indexed) {
231
+ gr_start <- bed_df$start + 1
232
+ gr_end <- bed_df$end
233
+ } else {
234
+ gr_start <- bed_df$start
235
+ gr_end <- bed_df$end
236
+ }
237
+
238
+ # Create GRanges object (strand-agnostic for calling cards)
239
+ gr <- GRanges(
240
+ seqnames = bed_df$chr,
241
+ ranges = IRanges(start = gr_start, end = gr_end),
242
+ strand = "*"
243
+ )
244
+
245
+ # Add any additional metadata columns
246
+ extra_cols <- setdiff(names(bed_df), c("chr", "start", "end", "strand"))
247
+ if (length(extra_cols) > 0) {
248
+ mcols(gr) <- bed_df[, extra_cols, drop = FALSE]
249
+ }
250
+
251
+ return(gr)
252
+ }
253
+
254
+
255
+ #' Deduplicate insertions in GRanges object
256
+ #'
257
+ #' For calling cards, if an insertion is found at the same coordinate,
258
+ #' only one record is retained
259
+ #'
260
+ #' @param gr GRanges object
261
+ #' @return Deduplicated GRanges object
262
+ deduplicate_granges <- function(gr) {
263
+ # Find unique ranges (ignores strand and metadata)
264
+ unique_ranges <- !duplicated(granges(gr))
265
+ gr[unique_ranges]
266
+ }
267
+
268
+
269
+ #' Count overlaps between insertions and regions
270
+ #'
271
+ #' @param insertions_gr GRanges object with insertions
272
+ #' @param regions_gr GRanges object with regions
273
+ #' @param deduplicate Whether to deduplicate insertions (default: TRUE)
274
+ #' @return Integer vector of overlap counts per region
275
+ count_overlaps <- function(insertions_gr, regions_gr, deduplicate = TRUE) {
276
+
277
+ # Deduplicate if requested
278
+ if (deduplicate) {
279
+ n_before <- length(insertions_gr)
280
+ insertions_gr <- deduplicate_granges(insertions_gr)
281
+ n_after <- length(insertions_gr)
282
+ if (n_before != n_after) {
283
+ message(" Deduplicated: ", n_before, " -> ", n_after,
284
+ " (removed ", n_before - n_after, " duplicates)")
285
+ }
286
+ }
287
+
288
+ # Count overlaps per region
289
+ # countOverlaps returns an integer vector with one element per region
290
+ counts <- countOverlaps(regions_gr, insertions_gr)
291
+
292
+ return(counts)
293
+ }
294
+
295
+
296
+ # Main Analysis Function --------------------------------------------------
297
+
298
+ #' Call peaks/quantify regions using calling cards approach
299
+ #'
300
+ #' @param experiment_gr GRanges object with experiment insertions
301
+ #' @param background_gr GRanges object with background insertions
302
+ #' @param regions_gr GRanges object with regions to quantify
303
+ #' @param deduplicate_experiment Whether to deduplicate experiment insertions (default: TRUE)
304
+ #' @param pseudocount Pseudocount for calculations (default: 0.1)
305
+ #' @return GRanges object with regions and statistics as metadata columns
306
+ enrichment_analysis <- function(experiment_gr,
307
+ background_gr,
308
+ regions_gr,
309
+ deduplicate_experiment = TRUE,
310
+ pseudocount = 0.1) {
311
+
312
+ message("Starting enrichment analysis...")
313
+
314
+ # Validate inputs
315
+ if (!inherits(experiment_gr, "GRanges")) {
316
+ stop("experiment_gr must be a GRanges object")
317
+ }
318
+ if (!inherits(background_gr, "GRanges")) {
319
+ stop("background_gr must be a GRanges object")
320
+ }
321
+ if (!inherits(regions_gr, "GRanges")) {
322
+ stop("regions_gr must be a GRanges object")
323
+ }
324
+
325
+ # Count overlaps for experiment (with deduplication if requested)
326
+ message("Counting experiment overlaps...")
327
+ if (deduplicate_experiment) {
328
+ message(" Deduplication: ON")
329
+ } else {
330
+ message(" Deduplication: OFF")
331
+ }
332
+
333
+ experiment_counts <- count_overlaps(
334
+ experiment_gr, regions_gr,
335
+ deduplicate = deduplicate_experiment
336
+ )
337
+
338
+ # Count overlaps for background (never deduplicated)
339
+ message("Counting background overlaps...")
340
+ message(" Deduplication: OFF (background should not be deduplicated)")
341
+
342
+ background_counts <- count_overlaps(
343
+ background_gr, regions_gr,
344
+ deduplicate = FALSE
345
+ )
346
+
347
+ # Calculate total hops AFTER any deduplication
348
+ if (deduplicate_experiment) {
349
+ experiment_gr_dedup <- deduplicate_granges(experiment_gr)
350
+ total_experiment_hops <- length(experiment_gr_dedup)
351
+ } else {
352
+ total_experiment_hops <- length(experiment_gr)
353
+ }
354
+
355
+ total_background_hops <- length(background_gr)
356
+
357
+ message("Total experiment hops: ", total_experiment_hops)
358
+ message("Total background hops: ", total_background_hops)
359
+
360
+ if (total_experiment_hops == 0) {
361
+ stop("Experiment data is empty")
362
+ }
363
+ if (total_background_hops == 0) {
364
+ stop("Background data is empty")
365
+ }
366
+
367
+ # Add counts and totals as metadata columns
368
+ mcols(regions_gr)$experiment_hops <- as.integer(experiment_counts)
369
+ mcols(regions_gr)$background_hops <- as.integer(background_counts)
370
+ mcols(regions_gr)$total_experiment_hops <- as.integer(total_experiment_hops)
371
+ mcols(regions_gr)$total_background_hops <- as.integer(total_background_hops)
372
+
373
+ # Calculate statistics
374
+ message("Calculating enrichment scores...")
375
+ mcols(regions_gr)$callingcards_enrichment <- calculate_enrichment(
376
+ total_background_hops = total_background_hops,
377
+ total_experiment_hops = total_experiment_hops,
378
+ background_hops = background_counts,
379
+ experiment_hops = experiment_counts,
380
+ pseudocount = pseudocount
381
+ )
382
+
383
+ message("Calculating Poisson p-values...")
384
+ mcols(regions_gr)$poisson_pval <- calculate_poisson_pval(
385
+ total_background_hops = total_background_hops,
386
+ total_experiment_hops = total_experiment_hops,
387
+ background_hops = background_counts,
388
+ experiment_hops = experiment_counts,
389
+ pseudocount = pseudocount
390
+ )
391
+
392
+ message("Calculating log Poisson p-values...")
393
+ mcols(regions_gr)$log_poisson_pval <- calculate_poisson_pval(
394
+ total_background_hops = total_background_hops,
395
+ total_experiment_hops = total_experiment_hops,
396
+ background_hops = background_counts,
397
+ experiment_hops = experiment_counts,
398
+ pseudocount = pseudocount,
399
+ log.p = TRUE
400
+ )
401
+
402
+ message("Calculating hypergeometric p-values...")
403
+ mcols(regions_gr)$hypergeometric_pval <- calculate_hypergeom_pval(
404
+ total_background_hops = total_background_hops,
405
+ total_experiment_hops = total_experiment_hops,
406
+ background_hops = background_counts,
407
+ experiment_hops = experiment_counts
408
+ )
409
+
410
+ # Calculate adjusted p-values
411
+ message("Calculating adjusted p-values...")
412
+ mcols(regions_gr)$poisson_qval <- p.adjust(mcols(regions_gr)$poisson_pval, method = "fdr")
413
+ mcols(regions_gr)$hypergeometric_qval <- p.adjust(mcols(regions_gr)$hypergeometric_pval, method = "fdr")
414
+
415
+ message("Analysis complete!")
416
+
417
+ return(regions_gr)
418
+ }
419
+
420
+
421
+ # Example Usage -----------------------------------------------------------
422
+
423
+ # This is a template for how to use these functions
424
+ # Uncomment and modify for your actual data
425
+
426
+ # # Load your data (BED3+ format: chr, start, end, ...)
427
+ experiment_gr = arrow::open_dataset("~/code/hf/barkai_compendium/genome_map")
428
+
429
+ accessions <- experiment_gr |>
430
+ dplyr::select(accession) |>
431
+ dplyr::distinct() |>
432
+ dplyr::collect() |>
433
+ dplyr::pull(accession)
434
+
435
+ tmp_acc = experiment_gr %>%
436
+ filter(accession==accessions[1]) %>%
437
+ collect()
438
+
439
+ mahendrawada_control_data_root = "~/projects/parsing_yeast_database_data/data/mahendrawada_chec"
440
+ background_gr_h_m_paths = list.files(mahendrawada_control_data_root)
441
+ background_gr_h_m = map(file.path(mahendrawada_control_data_root,
442
+ background_gr_h_m_paths),
443
+ rtracklayer::import)
444
+ names(background_gr_h_m) = str_remove(background_gr_h_m_paths, "_REP1.mLb.mkD.sorted_5p.bed")
445
+
446
+ regions_gr <- read_tsv("~/code/hf/yeast_genome_resources/yiming_promoters.bed",
447
+ col_names = c('chr', 'start', 'end', 'locus_tag', 'score', 'strand')) %>%
448
+ bed_to_granges()
449
+
450
+ # # Run analysis with deduplication (default for calling cards)
451
+ results <- enrichment_analysis(
452
+ experiment_gr = experiment_gr,
453
+ background_gr = background_gr,
454
+ regions_gr = regions_gr,
455
+ deduplicate_experiment = TRUE,
456
+ pseudocount = 0.1
457
+ )
458
+
459
+
460
+ # id 9 corresponds to the binding sample -- can get from genome_map and
461
+ # annotated_feature metadata
462
+ #
463
+ # NOTE: there are some expected differences due to a change in how I am handling
464
+ # the promoter boundaries. The implementation here is correct -- please use
465
+ # this from now on. If you need to compare or doubt something, please let
466
+ # me konw
467
+ #
468
+ # curr_db_annotated_feature = arrow::read_parquet("~/code/hf/callingcards/annotated_features/batch=run_5801/part-0.parquet") %>%
469
+ # filter(id == 9)
470
+ #
471
+ # comp_df = curr_db_annotated_feature %>%
472
+ # select(target_locus_tag, experiment_hops,
473
+ # background_hops, background_total_hops,
474
+ # experiment_total_hops) %>%
475
+ # left_join(results %>%
476
+ # as_tibble() %>%
477
+ # select(locus_tag, total_background_hops,
478
+ # total_experiment_hops,
479
+ # experiment_hops, background_hops) %>%
480
+ # dplyr::rename(target_locus_tag = locus_tag,
481
+ # new_exp_hops = experiment_hops,
482
+ # new_bg_hops = background_hops,
483
+ # new_bg_total = total_background_hops,
484
+ # new_expr_total = total_experiment_hops))