Debian Codegraph @

samtools/bedidx.c

raw symbols SCIP
1 /* bedidx.c -- BED file indexing.
2
3 Copyright (C) 2011 Broad Institute.
4 Copyright (C) 2014, 2017-2019, 2024 Genome Research Ltd.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <config.h>
27
28 #include <stdlib.h>
29 #include <stdint.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <errno.h>
33 #include <zlib.h>
34 #include "bedidx.h"
35
36 #include "htslib/ksort.h"
37
38 #include "htslib/kseq.h"
39 KSTREAM_INIT(gzFile, gzread, 8192)
40
41 static inline int lt_pair_pos(hts_pair_pos_t a, hts_pair_pos_t b) {
42 if (a.beg == b.beg) return a.end < b.end;
43 return a.beg < b.beg;
44 }
45 KSORT_INIT_STATIC(hts_pair_pos_t, hts_pair_pos_t, lt_pair_pos)
46
47 /*! @typedef
48 * @abstract bed_reglist_t - value type of the BED hash table
49 * This structure encodes the list of intervals (ranges) for the regions provided via BED file or
50 * command line arguments.
51 * @field *a pointer to the array of intervals.
52 * @field n actual number of elements contained by a
53 * @field m number of allocated elements to a (n <= m)
54 * @field *idx index array for computing the minimum offset
55 */
56 typedef struct {
57 int n, m;
58 hts_pair_pos_t *a;
59 int *idx;
60 int filter;
61 hts_pos_t max_idx;
62 } bed_reglist_t;
63
64 #include "htslib/khash.h"
65 KHASH_MAP_INIT_STR(reg, bed_reglist_t)
66
67 typedef kh_reg_t reghash_t;
68
69 #if 0
70 // Debug function
71 static void bed_print(void *reg_hash) {
72 reghash_t *h = (reghash_t *)reg_hash;
73 bed_reglist_t *p;
74 khint_t k;
75 int i;
76 const char *reg;
77
78 if (!h) {
79 printf("Hash table is empty!\n");
80 return;
81 }
82 for (k = kh_begin(h); k < kh_end(h); k++) {
83 if (kh_exist(h,k)) {
84 reg = kh_key(h,k);
85 printf("Region: '%s'\n", reg);
86 if ((p = &kh_val(h,k)) != NULL && p->n > 0) {
87 printf("Filter: %d\n", p->filter);
88 for (i=0; i<p->n; i++) {
89 printf("\tinterval[%d]: %"PRIhts_pos"-%"PRIhts_pos"\n",
90 i,p->a[i].beg,p->a[i].end);
91 }
92 } else {
93 printf("Region '%s' has no intervals!\n", reg);
94 }
95 }
96 }
97 }
98 #endif
99
100 static int bed_index_core(bed_reglist_t *regions)
101 {
102 int i, *idx = NULL;
103 size_t idx_size = 0;
104 hts_pos_t last_end = 0;
105 hts_pair_pos_t *a = regions->a;
106
107 // Construct a linear index on regions, to allow rapid lookup of
108 // where to start searching for matches
109 for (i = 0; i < regions->n; ++i) {
110 hts_pos_t beg = a[i].beg >= 0 ? a[i].beg >> LIDX_SHIFT : 0;
111 hts_pos_t end = a[i].end >= 0 ? a[i].end >> LIDX_SHIFT : 0;
112 hts_pos_t j;
113 if (end < last_end)
114 continue; // Can happen for a containment
115 if (end + 1 >= SIZE_MAX / sizeof(*idx)) { // Ensure no overflow
116 errno = ENOMEM;
117 free(idx);
118 return -1;
119 }
120 if (hts_resize(int, (size_t) end + 1, &idx_size, &idx, 0) < 0) {
121 free(idx);
122 return -1;
123 }
124 // Fill any gap prior to this region by pointing to the previous one
125 for (j = last_end; j < beg; j++)
126 idx[j] = i > 0 ? i - 1 : 0;
127 // Fill from max(last_end, beg) to `end` (inclusive) with current region
128 for (; j <= end; j++)
129 idx[j] = i;
130 // Remember where finished for the next gap
131 last_end = end + 1;
132 }
133 regions->idx = idx;
134 regions->max_idx = last_end;
135 return 0;
136 }
137
138 static int bed_index(reghash_t *h)
139 {
140 khint_t k;
141 for (k = 0; k < kh_end(h); ++k) {
142 if (kh_exist(h, k)) {
143 bed_reglist_t *p = &kh_val(h, k);
144 if (p->idx) {
145 free(p->idx);
146 p->idx = NULL;
147 }
148 ks_introsort(hts_pair_pos_t, p->n, p->a);
149 if (bed_index_core(p) != 0) {
150 return -1;
151 }
152 }
153 }
154 return 0;
155 }
156
157 static int bed_minoff(const bed_reglist_t *p, hts_pos_t beg) {
158 int min_off=0;
159
160 if (p && p->idx && p->max_idx > 0 && beg >= 0) {
161 min_off = (beg>>LIDX_SHIFT >= p->max_idx)? p->idx[p->max_idx-1] : p->idx[beg>>LIDX_SHIFT];
162 }
163
164 return min_off;
165 }
166
167 static int bed_overlap_core(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end)
168 {
169 int i, min_off;
170 if (p->n == 0) return 0;
171 min_off = bed_minoff(p, beg);
172
173 for (i = min_off; i < p->n; ++i) {
174 if (p->a[i].beg >= end) break; // out of range; no need to proceed
175 if (p->a[i].end > beg && p->a[i].beg < end)
176 return 1; // find the overlap; return
177 }
178 return 0;
179 }
180
181 int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end)
182 {
183 const reghash_t *h = (const reghash_t*)_h;
184 khint_t k;
185 if (!h) return 0;
186 k = kh_get(reg, h, chr);
187 if (k == kh_end(h)) return 0;
188 return bed_overlap_core(&kh_val(h, k), beg, end);
189 }
190
191 /** @brief Trim a sorted interval list, inside a region hash table,
192 * by removing completely contained intervals and merging adjacent or
193 * overlapping intervals.
194 * @param reg_hash the region hash table with interval lists as values
195 */
196
197 void bed_unify(void *reg_hash) {
198
199 int i, j, new_n;
200 reghash_t *h;
201 bed_reglist_t *p;
202
203 if (!reg_hash)
204 return;
205
206 h = (reghash_t *)reg_hash;
207
208 for (i = kh_begin(h); i < kh_end(h); i++) {
209 if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || !(p->n))
210 continue;
211
212 for (new_n = 0, j = 1; j < p->n; j++) {
213 if (p->a[new_n].end < p->a[j].beg) {
214 p->a[++new_n] = p->a[j];
215 } else {
216 if (p->a[new_n].end < p->a[j].end)
217 p->a[new_n].end = p->a[j].end;
218 }
219 }
220
221 p->n = ++new_n;
222 }
223 }
224
225 /* "BED" file reader, which actually reads two different formats.
226
227 BED files contain between three and nine fields per line, of which
228 only the first three (reference, start, end) are of interest to us.
229 BED counts positions from base 0, and the end is the base after the
230 region of interest. While not properly documented in the specification,
231 it is also possible to have 'browser' and 'track' lines in BED files that
232 do not follow the standard format and should be ignored. Examination
233 of the BED file reading code in
234 http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git shows that BED
235 files can also have comment lines starting with '#', leading whitespace
236 is stripped, and that fields are separated by one or more consecutive
237 whitespace characters.
238
239 The alternative format was originally for reading positions in VCF
240 format. This expects two columns, which indicate the reference and
241 a position. The position corresponds to a single base, and unlike
242 BED counts from 1.
243
244 Which format is in use is determined based on whether one or two
245 numbers can be decoded on the line. As this choice is made line-by-line
246 in this implementation, it is possible (but probably a bad idea) to mix
247 both formats in the same file. If trying to read a VCF file by this
248 method, it would be important to ensure that the third column (ID) does
249 not contain any entries that start with a digit, to avoid the line
250 erroneously being parsed as a BED file entry.
251
252 The BED specification is at http://www.genome.ucsc.edu/FAQ/FAQformat.html
253 The VCF specification is at https://github.com/samtools/hts-specs
254 */
255
256 void *bed_read(const char *fn)
257 {
258 reghash_t *h = kh_init(reg);
259 gzFile fp;
260 kstream_t *ks = NULL;
261 int dret;
262 unsigned int line = 0, save_errno;
263 kstring_t str = { 0, 0, NULL };
264
265 if (NULL == h) return NULL;
266 // read the list
267 fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
268 if (fp == 0) goto fail;
269 ks = ks_init(fp);
270 if (NULL == ks) goto fail; // In case ks_init ever gets error checking...
271 int ks_len;
272 while ((ks_len = ks_getuntil(ks, KS_SEP_LINE, &str, &dret)) >= 0) { // read a line
273 char *ref = str.s, *ref_end;
274 uint64_t beg = 0, end = 0;
275 int num = 0;
276 khint_t k;
277 bed_reglist_t *p;
278
279 if (ks_len == 0)
280 continue; // skip blank lines
281
282 line++;
283 while (*ref && isspace(*ref)) ref++;
284 if ('\0' == *ref) continue; // Skip blank lines
285 if ('#' == *ref) continue; // Skip BED file comments
286 ref_end = ref; // look for the end of the reference name
287 while (*ref_end && !isspace(*ref_end)) ref_end++;
288 if ('\0' != *ref_end) {
289 *ref_end = '\0'; // terminate ref and look for start, end
290 num = sscanf(ref_end + 1, "%"SCNu64" %"SCNu64, &beg, &end);
291 }
292 if (1 == num) { // VCF-style format
293 end = beg--; // Counts from 1 instead of 0 for BED files
294 }
295 if (num < 1 || end < beg) {
296 // These two are special lines that can occur in BED files.
297 // Check for them here instead of earlier in case someone really
298 // has called their reference "browser" or "track".
299 if (0 == strcmp(ref, "browser")) continue;
300 if (0 == strcmp(ref, "track")) continue;
301 if (num < 1) {
302 fprintf(stderr,
303 "[bed_read] Parse error reading \"%s\" at line %u\n",
304 fn, line);
305 } else {
306 fprintf(stderr,
307 "[bed_read] Parse error reading \"%s\" at line %u : "
308 "end (%"PRIu64") must not be less "
309 "than start (%"PRIu64")\n",
310 fn, line, end, beg);
311 }
312 errno = 0; // Prevent caller from printing misleading error messages
313 goto fail;
314 }
315
316 // Put reg in the hash table if not already there
317 k = kh_get(reg, h, ref);
318 if (k == kh_end(h)) { // absent from the hash table
319 int ret;
320 char *s = strdup(ref);
321 if (NULL == s) goto fail;
322 k = kh_put(reg, h, s, &ret);
323 if (-1 == ret) {
324 free(s);
325 goto fail;
326 }
327 memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
328 }
329 p = &kh_val(h, k);
330
331 // Add begin,end to the list
332 if (p->n == p->m) {
333 p->m = p->m ? p->m<<1 : 4;
334 hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
335 if (NULL == new_a) goto fail;
336 p->a = new_a;
337 }
338 p->a[p->n].beg = beg;
339 p->a[p->n++].end = end;
340 }
341 // FIXME: Need to check for errors in ks_getuntil. At the moment it
342 // doesn't look like it can return one. Possibly use gzgets instead?
343
344 if (gzclose(fp) != Z_OK) {
345 fp = NULL;
346 goto fail;
347 }
348 if (bed_index(h) != 0)
349 goto fail;
350 ks_destroy(ks);
351 free(str.s);
352 //bed_unify(h);
353 return h;
354 fail:
355 save_errno = errno;
356 if (ks) ks_destroy(ks);
357 if (fp) gzclose(fp);
358 free(str.s);
359 bed_destroy(h);
360 errno = save_errno;
361 return NULL;
362 }
363
364 void bed_destroy(void *_h)
365 {
366 reghash_t *h;
367 khint_t k;
368
369 if (!_h)
370 return;
371
372 h = (reghash_t*)_h;
373 for (k = 0; k < kh_end(h); ++k) {
374 if (kh_exist(h, k)) {
375 free(kh_val(h, k).a);
376 free(kh_val(h, k).idx);
377 free((char*)kh_key(h, k));
378 }
379 }
380 kh_destroy(reg, h);
381 }
382
383 static void *bed_insert(void *reg_hash, char *reg, hts_pos_t beg, hts_pos_t end) {
384
385 reghash_t *h;
386 khint_t k;
387 bed_reglist_t *p;
388
389 if (!reg_hash)
390 return NULL;
391
392 h = (reghash_t *)reg_hash;
393
394 // Put reg in the hash table if not already there
395 k = kh_get(reg, h, reg); //looks strange, but only the second reg is the actual region name.
396 if (k == kh_end(h)) { // absent from the hash table
397 int ret;
398 char *s = strdup(reg);
399 if (NULL == s) goto fail;
400 k = kh_put(reg, h, s, &ret);
401 if (-1 == ret) {
402 free(s);
403 goto fail;
404 }
405 memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
406 }
407 p = &kh_val(h, k);
408
409 // Add beg and end to the list
410 if (p->n == p->m) {
411 p->m = p->m ? p->m<<1 : 4;
412 hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
413 if (NULL == new_a) goto fail;
414 p->a = new_a;
415 }
416 p->a[p->n].beg = beg;
417 p->a[p->n++].end = end;
418
419 fail:
420 return h;
421 }
422
423 /* @brief Filter a region hash table (coming from the BED file) by another
424 * region hash table (coming from CLI), so that only intervals contained in
425 * both hash tables are kept.
426 * @param reg_hash the target region hash table
427 * @param tmp_hash the filter region hash table
428 * @return pointer to the filtered hash table
429 */
430
431 static void *bed_filter(void *reg_hash, void *tmp_hash) {
432
433 reghash_t *h;
434 reghash_t *t;
435 bed_reglist_t *p, *q;
436 khint_t l, k;
437 hts_pair_pos_t *new_a;
438 int i, j, new_n, min_off;
439 const char *reg;
440 hts_pos_t beg, end;
441
442 h = (reghash_t *)reg_hash;
443 t = (reghash_t *)tmp_hash;
444 if (!h)
445 return NULL;
446 if (!t)
447 return h;
448
449 for (l = kh_begin(t); l < kh_end(t); l++) {
450 if (!kh_exist(t,l) || !(q = &kh_val(t,l)) || !(q->n))
451 continue;
452
453 reg = kh_key(t,l);
454 k = kh_get(reg, h, reg); //looks strange, but only the second reg is a proper argument.
455 if (k == kh_end(h) || !(p = &kh_val(h, k)) || !(p->n))
456 continue;
457
458 new_a = calloc(q->n + p->n, sizeof(new_a[0]));
459 if (!new_a)
460 return NULL;
461 new_n = 0;
462
463 for (i = 0; i < q->n; i++) {
464 beg = q->a[i].beg;
465 end = q->a[i].end;
466
467 min_off = bed_minoff(p, beg);
468 for (j = min_off; j < p->n; ++j) {
469 if (p->a[j].beg >= end) break; // out of range; no need to proceed
470 if (p->a[j].end > beg && p->a[j].beg < end) {
471 new_a[new_n].beg = MAX(p->a[j].beg, beg);
472 new_a[new_n++].end = MIN(p->a[j].end, end);
473 }
474 }
475 }
476
477 if (new_n > 0) {
478 free(p->a);
479 p->a = new_a;
480 p->n = new_n;
481 p->m = new_n;
482 p->filter = FILTERED;
483 } else {
484 free(new_a);
485 p->filter = ALL;
486 }
487 }
488
489 return h;
490 }
491
492 void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op) {
493
494 reghash_t *h = (reghash_t *)reg_hash;
495 reghash_t *t = NULL;
496
497 int i;
498 char reg[1024];
499 const char *q;
500 int beg, end;
501
502 if (h) {
503 t = kh_init(reg);
504 if (!t) {
505 fprintf(stderr, "Error when creating the temporary region hash table!\n");
506 return NULL;
507 }
508 } else {
509 h = kh_init(reg);
510 if (!h) {
511 fprintf(stderr, "Error when creating the region hash table!\n");
512 return NULL;
513 }
514 *op = 1;
515 }
516
517 for (i=first; i<last; i++) {
518
519 // Note, ideally we would call sam_parse_region here, but it's complicated by not
520 // having the sam header known and the likelihood of the bed file containing data for other
521 // references too which we currently just ignore.
522 //
523 // TO DO...
524 q = hts_parse_reg(regs[i], &beg, &end);
525 if (q) {
526 if ((int)(q - regs[i] + 1) > 1024) {
527 fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
528 continue;
529 }
530 strncpy(reg, regs[i], q - regs[i]);
531 reg[q - regs[i]] = 0;
532 } else {
533 // not parsable as a region, but possibly a sequence named "foo:a"
534 if (strlen(regs[i]) + 1 > 1024) {
535 fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
536 continue;
537 }
538 strcpy(reg, regs[i]);
539 beg = 0; end = INT_MAX;
540 }
541
542 //if op==1 insert reg to the bed hash table
543 if (*op && !(bed_insert(h, reg, beg, end))) {
544 fprintf(stderr, "Error when inserting region='%s' in the bed hash table at address=%p!\n", regs[i], (void *)h);
545 }
546 //if op==0, first insert the regions in the temporary hash table,
547 //then filter the bed hash table using it
548 if (!(*op) && !(bed_insert(t, reg, beg, end))) {
549 fprintf(stderr, "Error when inserting region='%s' in the temporary hash table at address=%p!\n", regs[i], (void *)t);
550 }
551 }
552
553 if (!(*op)) {
554 if (bed_index(t) != 0)
555 goto fail;
556 bed_unify(t);
557 if (bed_filter(h, t) == NULL)
558 goto fail;
559 bed_destroy(t);
560 t = NULL;
561 }
562
563 if (h) {
564 if (bed_index(h) != 0)
565 goto fail;
566 bed_unify(h);
567 }
568
569 return h;
570
571 fail:
572 // Clean up whichever hash we made
573 if (reg_hash) {
574 if (t)
575 bed_destroy(t);
576 } else {
577 if (h)
578 bed_destroy(h);
579 }
580 return NULL;
581 }
582
583 const char* bed_get(void *reg_hash, int i, int filter) {
584
585 reghash_t *h;
586 bed_reglist_t *p;
587
588 if (!reg_hash)
589 return NULL;
590
591 h = (reghash_t *)reg_hash;
592 if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
593 return NULL;
594
595 return kh_key(h, i);
596 }
597
598 /**
599 * Create a region list from a the region hash table
600 * @param reg_hash The region hash table
601 * @param filter 0 - allow all regions, 1 - allow only selected regions
602 * @param n_reg Pointer to the returned region number
603 * @return The regions list as a hts_reglist_t
604 */
605
606 hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *n_reg) {
607
608 reghash_t *h;
609 bed_reglist_t *p;
610 khint_t i;
611 hts_reglist_t *reglist = NULL;
612 int count = 0;
613 int j;
614
615 if (!reg_hash)
616 return NULL;
617
618 h = (reghash_t *)reg_hash;
619
620 for (i = kh_begin(h); i < kh_end(h); i++) {
621 if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
622 continue;
623 count++;
624 }
625 if (!count)
626 return NULL;
627
628 reglist = (hts_reglist_t *)calloc(count, sizeof(hts_reglist_t));
629 if (!reglist)
630 return NULL;
631
632 *n_reg = count;
633 count = 0;
634
635 for (i = kh_begin(h); i < kh_end(h) && count < *n_reg; i++) {
636 if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
637 continue;
638
639 reglist[count].reg = kh_key(h,i);
640 reglist[count].intervals = (hts_pair32_t *)calloc(p->n, sizeof(hts_pair32_t));
641 if(!(reglist[count].intervals)) {
642 hts_reglist_free(reglist, count);
643 return NULL;
644 }
645 reglist[count].count = p->n;
646 reglist[count].max_end = 0;
647
648 for (j = 0; j < p->n; j++) {
649 reglist[count].intervals[j].beg = p->a[j].beg;
650 reglist[count].intervals[j].end = p->a[j].end;
651
652 if (reglist[count].intervals[j].end > reglist[count].max_end)
653 reglist[count].max_end = reglist[count].intervals[j].end;
654 }
655 count++;
656 }
657
658 return reglist;
659 }