cmatkhan commited on
Commit
5a5b92c
·
verified ·
1 Parent(s): a017f60

Upload folder using huggingface_hub

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