Debian Codegraph @

samtools/bedidx.c.pysam.c

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