-
Notifications
You must be signed in to change notification settings - Fork 9
/
megadepth.cpp
3507 lines (3329 loc) · 151 KB
/
megadepth.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The MIT License
Copyright (c) 2018- by Christopher Wilks <[email protected]>
and Ben Langmead <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
.___ ___. _______ _______ ___ _______ _______ .______ .___________. __ __
| \/ | | ____| / _____| / \ | \ | ____|| _ \ | || | | |
| \ / | | |__ | | __ / ^ \ | .--. || |__ | |_) | `---| |----`| |__| |
| |\/| | | __| | | |_ | / /_\ \ | | | || __| | ___/ | | | __ |
| | | | | |____ | |__| | / _____ \ | '--' || |____ | | | | | | | |
|__| |__| |_______| \______| /__/ \__\ |_______/ |_______|| _| |__| |__| |__|
*/
#define __STDC_FORMAT_MACROS
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstring>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <thread>
#include <iterator>
#include <numeric>
#include <zlib.h>
#include <htslib/sam.h>
#include <htslib/hts.h>
#include <htslib/bgzf.h>
#include <htslib/tbx.h>
#include <sys/stat.h>
#include "bigWig.h"
#include "countlut.hpp"
#ifdef WINDOWS_MINGW
#include <unordered_map>
#include <unordered_set>
#include "getline.h"
#include "mingw-std-threads/mingw.thread.h"
template<class K, class V>
using hashmap = std::unordered_map<K, V>;
template<class V2>
using hashset = std::unordered_set<V2>;
#else
#include "robin_hood.h"
template<class K, class V>
using hashmap = robin_hood::unordered_map<K, V>;
template<class V2>
using hashset = robin_hood::unordered_set<V2>;
#endif
#if defined(__AVX2__) || defined(__SSE2__)
#include <x86intrin.h>
#endif
#if defined(__GNUC__) || defined(__clang__)
# ifndef unlikely
# define unlikely(x) __builtin_expect(!!(x), 0)
# endif
# ifndef likely
# define likely(x) __builtin_expect(!!(x), 1)
# endif
#endif
int UNKNOWN_FORMAT=-1;
int BAM_FORMAT = 1;
int BW_FORMAT = 2;
int CRAM_FORMAT = 3;
//taken from HTSlib bgzip
int BGZF_WRITE_WINDOW_SZ = 64 * 1024;
//critical to use a high value here for remote BigWigs
//accesses, has much less (maybe no) effect on local processing
const uint32_t default_BW_READ_BUFFER = 1<<30;
uint32_t BW_READ_BUFFER = default_BW_READ_BUFFER;
bool SUMS_ONLY = false;
bool SORTED_ANNOTATIONS = true;
int COLLAPSED_ANNOTATION_MAX_DISTANCE = 2200;
typedef std::vector<std::string> strvec;
typedef hashmap<std::string, uint64_t> mate2len;
typedef hashmap<std::string, double*> str2dblist;
uint64_t MAX_INT = (2^63);
//how many intervals to start with for a chromosome in a BigWig file
//uint64_t STARTING_NUM_INTERVALS = 1000;
uint64_t STARTING_NUM_INTERVALS = 1000000;
//used for --annotation where we read a 3+ column BED file
static const int CHRM_COL=0;
static const int START_COL=1;
static const int END_COL=2;
//1MB per line should be more than enough for CIO
static const int LINE_BUFFER_LENGTH=1048576;
static const int BIGWIG_INIT_VAL = 17;
static double SOFTCLIP_POLYA_TOTAL_COUNT_MIN=3;
static double SOFTCLIP_POLYA_RATIO_MIN=0.8;
//used for buffering up text/gz output
static const int OUT_BUFF_SZ=4000000;
static const int COORD_STR_LEN=34;
enum Op { csum, cmean, cmin, cmax };
static const void print_version() {
std::cout << "megadepth " << std::string(MEGADEPTH_VERSION) << std::endl;
}
struct Coordinate {
char* chrm;
int32_t start;
int32_t end;
};
static char emptystr[] = "\0";
static const char USAGE[] = "BAM and BigWig utility.\n"
"\n"
"Usage:\n"
" megadepth <bam|bw|-> [options]\n"
"\n"
"Options:\n"
" -h --help Show this screen.\n"
" --version Show version.\n"
" --threads # of threads to do: BAM decompression OR compute sums over multiple BigWigs in parallel\n"
" if the 2nd is intended then a TXT file listing the paths to the BigWigs to process in parallel\n"
" should be passed in as the main input file instead of a single BigWig file (EXPERIMENTAL).\n"
" --prefix String to use to prefix all output files.\n"
" --no-auc-stdout Force all AUC(s) to be written to <prefix>.auc.tsv rather than STDOUT\n"
" --no-annotation-stdout Force summarized annotation regions to be written to <prefix>.annotation.tsv rather than STDOUT\n"
" --no-coverage-stdout Force covered regions to be written to <prefix>.coverage.tsv rather than STDOUT\n"
" --keep-order Output annotation coverage in the order chromosomes appear in the BAM/BigWig file\n"
" The default is to output annotation coverage in the order chromosomes appear in the annotation BED file.\n"
" This is only applicable if --annotation is used for either BAM or BigWig input.\n"
"\n"
"BigWig Input:\n"
"Extract regions and their counts from a BigWig outputting BED format if a BigWig file is detected as input (exclusive of the other BAM modes):\n"
" Extracts all reads from the passed in BigWig and output as BED format.\n"
" This will also report the AUC over the annotated regions to STDOUT.\n"
" If only the name of the BigWig file is passed in with no other args, it will *only* report total AUC to STDOUT.\n"
" --annotation <bed> Only output the regions in this BED applying the argument to --op to them.\n"
" --op <sum[default], mean, min, max> Statistic to run on the intervals provided by --annotation\n"
" --sums-only Discard coordinates from output of summarized regions\n"
" --distance (2200[default]) Number of base pairs between end of last annotation and start of new to consider in the same BigWig query window (a form of binning) for performance. This determines the number of times the BigWig index is queried.\n"
" --unsorted (off[default]) There's a performance improvement *if* BED file passed to --annotation is 1) sorted by sort -k1,1 -k2,2n (default is to assume sorted and check for unsorted positions, if unsorted positions are found, will fall back to slower version)\n"
" --bwbuffer <1GB[default]> Size of buffer for reading BigWig files, critical to use a large value (~1GB) for remote BigWigs.\n"
" Default setting should be fine for most uses, but raise if very slow on a remote BigWig.\n"
"\n"
"\n"
"BAM Input:\n"
"Extract basic junction information from the BAM, including co-occurrence\n"
"If only the name of the BAM file is passed in with no other args, it will *only* report total AUC to STDOUT.\n"
" --fasta Path to the reference FASTA file if a CRAM file is passed as the input file (ignored otherwise)\n"
" If not passed, references will be downloaded using the CRAM header.\n"
" --junctions Extract co-occurring jx coordinates, strand, and anchor length, per read\n"
" writes to a TSV file <prefix>.jxs.tsv\n"
" --all-junctions Extract all jx coordinates, strand, and anchor length, per read for any jx\n"
" writes to a TSV file <prefix>.all_jxs.tsv\n"
" --longreads Modifies certain buffer sizes to accommodate longer reads such as PB/Oxford.\n"
" --filter-in Integer bitmask, any bits of which alignments need to have to be kept (similar to samtools view -f).\n"
" --filter-out Integer bitmask, any bits of which alignments need to have to be skipped (similar to samtools view -F).\n"
" --add-chr-prefix Adds \"chr\" prefix to relevant chromosomes for BAMs w/o it, pass \"human\" or \"mouse\".\n"
" Only works for human/mouse references (default: off).\n"
"\n"
"Non-reference summaries:\n"
" --alts Print differing from ref per-base coverages\n"
" Writes to a CSV file <prefix>.alts.tsv\n"
" --include-softclip Print a record to the alts CSV for soft-clipped bases\n"
" Writes total counts to a separate TSV file <prefix>.softclip.tsv\n"
" --only-polya If --include-softclip, only print softclips which are mostly A's or T's\n"
" --include-n Print mismatch records when mismatched read base is N\n"
" --print-qual Print quality values for mismatched bases\n"
" --delta Print POS field as +/- delta from previous\n"
" --require-mdz Quit with error unless MD:Z field exists everywhere it's\n"
" expected\n"
" --head Print sequence names and lengths in SAM/BAM header\n"
"\n"
"Coverage and quantification:\n"
" --coverage Print per-base coverage (slow but totally worth it)\n"
" --auc Print per-base area-under-coverage, will generate it for the genome\n"
" and for the annotation if --annotation is also passed in\n"
" Defaults to STDOUT, unless other params are passed in as well, then\n"
" if writes to a TSV file <prefix>.auc.tsv\n"
" --bigwig Output coverage as BigWig file(s). Writes to <prefix>.bw\n"
" (also <prefix>.unique.bw when --min-unique-qual is specified).\n"
" Requires libBigWig.\n"
" --annotation <BED|window_size> Path to BED file containing list of regions to sum coverage over\n"
" (tab-delimited: chrm,start,end). Or this can specify a contiguous region size in bp.\n"
" --op <sum[default], mean> Statistic to run on the intervals provided by --annotation\n"
" --no-index If using --annotation, skip the use of the BAM index (BAI) for pulling out regions.\n"
" Setting this can be faster if doing windows across the whole genome.\n"
" This will be turned on automatically if a window size is passed to --annotation.\n"
" --min-unique-qual <int>\n"
" Output second bigWig consisting built only from alignments\n"
" with at least this mapping quality. --bigwig must be specified.\n"
" Also produces second set of annotation sums based on this coverage\n"
" if --annotation is enabled\n"
" --double-count Allow overlapping ends of PE read to count twice toward\n"
" coverage\n"
" --num-bases Report total sum of bases in alignments processed (that pass filters)\n"
" --gzip Turns on gzipping of coverage output (no effect if --bigwig is passsed),\n"
" this will also enable --no-coverage-stdout.\n"
"\n"
"Other outputs:\n"
" --read-ends Print counts of read starts/ends, if --min-unique-qual is set\n"
" then only the alignments that pass that filter will be counted here\n"
" Writes to 2 TSV files: <prefix>.starts.tsv, <prefix>.ends.tsv\n"
" --frag-dist Print fragment length distribution across the genome\n"
" Writes to a TSV file <prefix>.frags.tsv\n"
" --echo-sam Print a SAM record for each aligned read\n"
" --ends Report end coordinate for each read (useful for debugging)\n"
" --test-polya Lower Poly-A filter minimums for testing (only useful for debugging/testing)\n"
"\n";
int my_write(void* fh, char* buf, uint32_t buf_len) {
#if USE_POSIX
return ::write(::fileno(fh), buf, bu_len);
#else
return std::fwrite(buf, 1, buf_len, (FILE *)fh);
#endif
}
int my_gzwrite(void* fh, char* buf, uint32_t buf_len) {
return bgzf_write((BGZF*)fh, buf, buf_len);
//return gzwrite(*((gzFile*) fh), buf, buf_len);
}
template <typename T>
int print_local(char* buf,const char* c, long start, long end, T val, double* local_vals, long z);
template <typename T>
int print_local_sums_only(char* buf,const char* c, long start, long end, T val, double* local_vals, long z);
template <typename T>
int print_shared(char* buf,const char* c, long start, long end, T val, double* local_vals, long z);
template <typename T>
int print_shared_sums_only(char* buf,const char* c, long start, long end, T val, double* local_vals, long z);
template <>
int print_local<long>(char* buf,const char* c, long start, long end, long val, double* local_vals, long z) {
return sprintf(buf, "%s\t%lu\t%lu\t%lu\n", c, start, end, (long) local_vals[z]);
}
template <>
int print_local_sums_only<long>(char* buf,const char* c, long start, long end, long val, double* local_vals, long z) {
return sprintf(buf, "%lu\n", (long) local_vals[z]);
}
template <>
int print_shared<long>(char* buf,const char* c, long start, long end, long val, double* local_vals, long z) {
return sprintf(buf, "%s\t%lu\t%lu\t%lu\n", c, start, end, val);
}
template <>
int print_shared_sums_only<long>(char* buf,const char* c, long start, long end, long val, double* local_vals, long z) {
return sprintf(buf, "%lu\n", val);
}
template <>
int print_shared<double>(char* buf, const char* c, long start, long end, double val, double* local_vals, long z) {
//from https://stackoverflow.com/questions/994764/rounding-doubles-5-sprintf
return sprintf(buf, "%s\t%lu\t%lu\t%.2f\n", c, (long) start, (long) end, (round(val*100.)/100.));
//return sprintf(buf, "%s\t%lu\t%lu\t%.2f\t%.11f\t%lu\n", c, (long) start, (long) end, (round(val*100.)/100.), val, (end-start));
}
template <>
int print_shared_sums_only<double>(char* buf, const char* c, long start, long end, double val, double* local_vals, long z) {
return sprintf(buf, "%.2f\n", (round(val*100.)/100.));
}
template <>
int print_local<double>(char* buf, const char* c, long start, long end, double val, double* local_vals, long z) {
return sprintf(buf, "%s\t%lu\t%lu\t%.2f\n", c, (long) start, (long) end, (round(local_vals[z]*100.)/100.));
}
template <>
int print_local_sums_only<double>(char* buf, const char* c, long start, long end, double val, double* local_vals, long z) {
return sprintf(buf, "%.2f\n", (round(local_vals[z]*100.)/100.));
}
static const char* get_positional_n(const char ** begin, const char ** end, size_t n) {
size_t i = 0;
for(const char **itr = begin; itr != end; itr++) {
if((*itr)[0] != '-' || strlen(*itr) == 1) {
if(i++ == n) {
return *itr;
}
}
}
return nullptr;
}
static bool has_option(const char** begin, const char** end, const std::string& option) {
return std::find(begin, end, option) != end;
}
/**
* Return the argument after the given one, (or further downstream when shift > 0).
*/
static const char** get_option(
const char** begin,
const char** end,
const std::string& option,
unsigned shift = 0)
{
const char** itr = std::find(begin, end, option);
return itr + shift + 1;
}
/**
* Holds an MDZ "operation"
* op can be
*/
struct MdzOp {
char op;
int run;
char str[1024];
};
//from https://github.com/samtools/htslib/blob/7c04ea5c328547e9e8a9af4b932b87a3cb1939e6/hts.c#L82
int A_idx = 1;
int T_idx = 8;
static inline int polya_check(const uint8_t *str, size_t off, size_t run, char *c) {
char seq_nt16_str_counts[16] = {0};
for(size_t i = off; i < off + run; i++)
seq_nt16_str_counts[bam_seqi(str, i)]++;
int count = -1;
if((seq_nt16_str_counts[A_idx] / (double) run) >= SOFTCLIP_POLYA_RATIO_MIN) {
*c = 'A';
count = seq_nt16_str_counts[A_idx];
}
else if((seq_nt16_str_counts[T_idx] / (double) run) >= SOFTCLIP_POLYA_RATIO_MIN) {
*c = 'T';
count = seq_nt16_str_counts[T_idx];
}
return count;
}
static const char seq_rev_nt16_str[] = "=TGMCRSVAWYHKDBN";
static inline std::ostream& seq_substring(std::ostream& os, const uint8_t *str, size_t off, size_t run, bool reverse=false) {
if(reverse) {
int i=(off+run)-1;
while(((int) off) <= i) {
int io = bam_seqi(str, i);
os << seq_rev_nt16_str[io];
i--;
}
return os;
}
for(size_t i = off; i < off + run; i++) {
os << seq_nt16_str[bam_seqi(str, i)];
}
return os;
}
static inline char* seq_substring(const uint8_t *str, size_t off, size_t run, bool reverse=false) {
char* seq = new char[off + run + 1];
int k = 0;
if(reverse) {
int i=(off+run)-1;
while(((int) off) <= i) {
int io = bam_seqi(str, i);
seq[k++] = seq_rev_nt16_str[io];
i--;
}
seq[k]='\0';
return seq;
}
for(size_t i = off; i < off + run; i++) {
seq[k++] = seq_nt16_str[bam_seqi(str, i)];
}
seq[k]='\0';
return seq;
}
static inline std::ostream& kstring_out(std::ostream& os, const kstring_t *str) {
for(size_t i = 0; i < str->l; i++) {
os << str->s[i];
}
return os;
}
static inline std::ostream& cstr_substring(std::ostream& os, const uint8_t *str, size_t off, size_t run) {
for(size_t i = off; i < off + run; i++) {
os << (char)str[i];
}
return os;
}
static inline char* cstr_substring(const uint8_t *str, size_t off, size_t run) {
char* quals = new char[off + run];
int k = 0;
for(size_t i = off; i < off + run; i++)
quals[k++] = (char)str[i];
quals[k]='\0';
return quals;
}
static inline std::ostream& qstr_substring(std::ostream& os, const uint8_t *str, size_t off, size_t run, bool reverse=false) {
if(reverse) {
int i=(off+run)-1;
while(((int) off) <= i) {
os << (char)(str[i]+33);
i--;
}
return os;
}
for(size_t i = off; i < off + run; i++) {
os << (char)(str[i]+33);
}
return os;
}
/**
* Parse given MD:Z extra field into a vector of MD:Z operations.
*/
static void parse_mdz(
const uint8_t *mdz,
std::vector<MdzOp>& ops)
{
int i = 0;
size_t mdz_len = strlen((char *)mdz);
while(i < mdz_len) {
if(isdigit(mdz[i])) {
int run = 0;
while(i < mdz_len && isdigit(mdz[i])) {
run *= 10;
run += (int)(mdz[i] - '0');
i++;
}
if(run > 0) {
ops.emplace_back(MdzOp{'=', run, ""});
ops.back().str[0] = '\0';
}
} else if(isalpha(mdz[i])) {
int st = i;
while(i < mdz_len && isalpha(mdz[i])) i++;
assert(i > st);
ops.emplace_back(MdzOp{'X', i - st, ""});
for(int j = 0; j < i ; j++) {
ops.back().str[j] = mdz[st + j];
}
std::memcpy(ops.back().str, mdz + st, (size_t)(i - st));
ops.back().str[i - st] = '\0';
} else if(mdz[i] == '^') {
i++;
int st = i;
while (i < mdz_len && isalpha(mdz[i])) i++;
assert(i > st);
ops.emplace_back(MdzOp{'^', i - st, ""});
std::memcpy(ops.back().str, mdz + st, (size_t)(i - st));
ops.back().str[i - st] = '\0';
} else {
std::stringstream ss;
ss << "Unknown MD:Z operation: \"" << mdz[i] << "\"";
throw std::runtime_error(ss.str());
}
}
}
static bool check_for_overlap(std::vector<Coordinate>* overlapping_coords, int starting_idx, int32_t refpos) {
for(auto it : *overlapping_coords)
if(it.start <= refpos && it.end >= refpos)
return true;
return false;
}
struct CigarOp {
char op;
int32_t refidx;
int32_t refpos;
char* seq;
char* quals;
//std::ostream seq;
//std::ostream quals;
int32_t del_len;
};
typedef hashmap<std::string, std::vector<CigarOp>> read2cigarops;
//only applies to X,D, and I ops (not S [softclipping])
static void emit_alt_record(std::fstream& fout, CigarOp& cig, const char* qname) {
fout << cig.refidx << ',' << cig.refpos << ',' << cig.op << ',';
if(cig.op == 'D')
fout << cig.del_len;
else
fout << cig.seq;
//cleanup, assumes there's only 2 mates in a read
delete cig.seq;
fout << ',' << qname << ',';
if(cig.quals) {
fout << cig.quals;
delete cig.quals;
}
fout << '\n';
}
static void check_saved_ops(std::fstream& fout, std::vector<CigarOp>* saved_ops, std::vector<Coordinate>* overlapping_coords, char* real_qname, bool check_for_overlaps_flag = true) {
int coord_idx = 0;
for(auto it : *saved_ops) {
char* qname = emptystr;
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, it.refpos))
qname = real_qname;
emit_alt_record(fout, it, qname);
}
}
static bool output_from_cigar_mdz(
const bam1_t *rec,
std::vector<MdzOp>& mdz,
std::fstream& fout,
uint64_t* total_softclip_count,
char* real_qname,
std::vector<Coordinate>* overlapping_coords,
std::vector<CigarOp>* saved_ops = nullptr,
bool save_ops = false,
bool print_qual = false,
bool include_sc = false,
bool only_polya_sc = false,
bool include_n_mms = false,
bool delta = false)
{
//bool check_for_saved_ops = saved_ops->size() > 0;
if(saved_ops->size() > 0)
check_saved_ops(fout, saved_ops, overlapping_coords, real_qname);
uint8_t *seq = bam_get_seq(rec);
uint8_t *qual = bam_get_qual(rec);
// If QUAL field is *. this array is just a bunch of 255s
uint32_t *cigar = bam_get_cigar(rec);
size_t mdzi = 0, seq_off = 0;
int32_t ref_off = rec->core.pos;
bool found = false;
bool check_for_overlaps_flag = overlapping_coords->size() > 0;
for(unsigned int k = 0; k < rec->core.n_cigar; k++) {
int op = bam_cigar_op(cigar[k]);
int run = bam_cigar_oplen(cigar[k]);
if((strchr("DNMX=", BAM_CIGAR_STR[op]) != nullptr) && mdzi >= mdz.size()) {
std::stringstream ss;
ss << "Found read-consuming CIGAR op after MD:Z had been exhausted" << std::endl;
throw std::runtime_error(ss.str());
}
int coord_idx = 0;
//TODO: track each I,D,X for a read if 1) first in a pair 2) possible overlap, otherwise just print
if(op == BAM_CMATCH || op == BAM_CDIFF || op == BAM_CEQUAL) {
// Look for block matches and mismatches in MD:Z string
int runleft = run;
while(runleft > 0 && mdzi < mdz.size()) {
int run_comb = std::min(runleft, mdz[mdzi].run);
runleft -= run_comb;
assert(mdz[mdzi].op == 'X' || mdz[mdzi].op == '=');
if(mdz[mdzi].op == '=') {
// nop
} else {
assert(mdz[mdzi].op == 'X');
assert(strlen(mdz[mdzi].str) == run_comb);
int cread = bam_seqi(seq, seq_off);
if(!include_n_mms && run_comb == 1 && seq_nt16_str[cread] == 'N') {
// skip
} else {
char* qname = emptystr;
if(save_ops) {
CigarOp cig;
cig.refidx = rec->core.tid;
cig.refpos = ref_off;
cig.op = 'X';
cig.seq = seq_substring(seq, seq_off, (size_t)run_comb);
cig.quals = nullptr;
if(print_qual)
cig.quals = cstr_substring(qual, seq_off, (size_t)run_comb);
cig.del_len = 0;
saved_ops->push_back(cig);
}
else {
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, ref_off))
qname = real_qname;
fout << rec->core.tid << ',' << ref_off << ",X,";
seq_substring(fout, seq, seq_off, (size_t)run_comb) << ',' << qname << ',';
if(print_qual)
cstr_substring(fout, qual, seq_off, (size_t)run_comb);
fout << '\n';
found = true;
}
}
}
seq_off += run_comb;
ref_off += run_comb;
if(run_comb < mdz[mdzi].run) {
assert(mdz[mdzi].op == '=');
mdz[mdzi].run -= run_comb;
} else {
mdzi++;
}
}
} else if(op == BAM_CINS) {
char* qname = emptystr;
if(save_ops) {
CigarOp cig;
cig.refidx = rec->core.tid;
cig.refpos = ref_off;
cig.op = 'I';
cig.seq = seq_substring(seq, seq_off, (size_t)run);
cig.quals = nullptr;
cig.del_len = 0;
saved_ops->push_back(cig);
}
else {
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, ref_off))
qname = real_qname;
fout << rec->core.tid << ',' << ref_off << ",I,";
seq_substring(fout, seq, seq_off, (size_t)run) << ',' << qname << ",\n";
found = true;
}
seq_off += run;
} else if(op == BAM_CSOFT_CLIP) {
if(include_sc) {
char direction = '+';
if(seq_off == 0)
direction = '-';
(*total_softclip_count)+=run;
if(only_polya_sc) {
char c;
int count_polya = polya_check(seq, seq_off, (size_t)run, &c);
if(count_polya != -1 && run >= SOFTCLIP_POLYA_TOTAL_COUNT_MIN) {
char* qname = emptystr;
/*if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, ref_off))
qname = real_qname;*/
fout << rec->core.tid << ',' << ref_off << ",S,";
fout << run << ',' << qname << ',' << direction << ',' << c << ',' << count_polya << '\n';
found = true;
}
}
else {
char* qname = emptystr;
/*if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, ref_off))
qname = real_qname;*/
fout << rec->core.tid << ',' << ref_off << ",S,";
seq_substring(fout, seq, seq_off, (size_t)run) << ',' << qname << ",\n";
found = true;
}
}
seq_off += run;
} else if (op == BAM_CDEL) {
assert(mdz[mdzi].op == '^');
assert(run == mdz[mdzi].run);
assert(strlen(mdz[mdzi].str) == run);
mdzi++;
char* qname = emptystr;
if(save_ops) {
CigarOp cig;
cig.refidx = rec->core.tid;
cig.refpos = ref_off;
cig.op = 'D';
cig.seq = nullptr;
cig.quals = nullptr;
cig.del_len = run;
saved_ops->push_back(cig);
}
else {
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, ref_off))
qname = real_qname;
fout << rec->core.tid << ',' << ref_off << ",D," << run << ',' << qname << ",\n";
found = true;
}
ref_off += run;
} else if (op == BAM_CREF_SKIP) {
ref_off += run;
} else if (op == BAM_CHARD_CLIP) {
} else if (op == BAM_CPAD) {
} else {
std::stringstream ss;
ss << "No such CIGAR operation as \"" << op << "\"";
throw std::runtime_error(ss.str());
}
}
assert(mdzi == mdz.size());
return found;
}
static bool output_from_cigar(const bam1_t *rec, std::fstream& fout, uint64_t* total_softclip_count, const bool include_sc, const bool only_polya_sc, char* real_qname, std::vector<Coordinate>* overlapping_coords, std::vector<CigarOp>* saved_ops = nullptr, bool save_ops = false) {
if(saved_ops->size() > 0)
check_saved_ops(fout, saved_ops, overlapping_coords, real_qname);
uint8_t *seq = bam_get_seq(rec);
uint32_t *cigar = bam_get_cigar(rec);
uint32_t n_cigar = rec->core.n_cigar;
bool found = false;
if(n_cigar == 1)
return found;
int32_t refpos = rec->core.pos;
int32_t seqpos = 0;
int coord_idx = 0;
bool check_for_overlaps_flag = overlapping_coords->size() > 0;
for(uint32_t k = 0; k < n_cigar; k++) {
int op = bam_cigar_op(cigar[k]);
int run = bam_cigar_oplen(cigar[k]);
switch(op) {
case BAM_CDEL: {
char* qname = emptystr;
if(save_ops) {
CigarOp cig;
cig.refidx = rec->core.tid;
cig.refpos = refpos;
cig.op = 'D';
cig.seq = nullptr;
cig.quals = nullptr;
cig.del_len = run;
saved_ops->push_back(cig);
}
else {
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, refpos))
qname = real_qname;
fout << rec->core.tid << ',' << refpos << ",D," << run << "," << qname << ",\n";
}
refpos += run;
break;
}
case BAM_CSOFT_CLIP: {
if(include_sc) {
char direction = '+';
if(seqpos == 0)
direction = '-';
(*total_softclip_count) += run;
if(only_polya_sc) {
char c;
int count_polya = polya_check(seq, (size_t)seqpos, (size_t)run, &c);
if(count_polya != -1 && run >= SOFTCLIP_POLYA_TOTAL_COUNT_MIN) {
char* qname = emptystr;
fout << rec->core.tid << ',' << refpos << ',' << BAM_CIGAR_STR[op] << ',';
fout << run << ',' << qname << ',' << direction << ',' << c << ',' << count_polya << '\n';
found = true;
}
}
else {
char* qname = emptystr;
fout << rec->core.tid << ',' << refpos << ',' << BAM_CIGAR_STR[op] << ',';
seq_substring(fout, seq, (size_t)seqpos, (size_t)run) << ',' << qname << ",\n";
found = true;
}
}
seqpos += run;
break;
}
case BAM_CINS: {
char* qname = emptystr;
if(save_ops) {
CigarOp cig;
cig.refidx = rec->core.tid;
cig.refpos = refpos;
cig.op = 'I';
cig.seq = seq_substring(seq, (size_t)seqpos, (size_t)run);
cig.quals = nullptr;
cig.del_len = 0;
saved_ops->push_back(cig);
}
else {
if(check_for_overlaps_flag && check_for_overlap(overlapping_coords, coord_idx, refpos))
qname = real_qname;
fout << rec->core.tid << ',' << refpos << ',' << BAM_CIGAR_STR[op] << ',';
seq_substring(fout, seq, (size_t)seqpos, (size_t)run) << ',' << qname << ",\n";
found = true;
}
seqpos += run;
break;
}
case BAM_CREF_SKIP: {
refpos += run;
break;
}
case BAM_CMATCH:
case BAM_CDIFF:
case BAM_CEQUAL: {
seqpos += run;
refpos += run;
break;
}
case BAM_CHARD_CLIP:
case BAM_CPAD: { break; }
default: {
std::stringstream ss;
//ss << "No such CIGAR operation as \"" << op << "\"" << n_cigar << " " << run << " " << k;
ss << "No such CIGAR operation as \"" << op << "\"";
throw std::runtime_error(ss.str());
}
}
}
return found;
}
static void print_header(const bam_hdr_t * hdr) {
for(int32_t i = 0; i < hdr->n_targets; i++) {
std::cout << '@' << i << ','
<< hdr->target_name[i] << ','
<< hdr->target_len[i] << std::endl;
}
}
static const long get_longest_target_size(const bam_hdr_t * hdr) {
long max = 0;
for(int32_t i = 0; i < hdr->n_targets; i++) {
if(hdr->target_len[i] > max)
max = hdr->target_len[i];
}
return max;
}
static void reset_array(uint32_t* arr, const long arr_sz) {
#if USE_SIMD_ZERO
#if __AVX2__
__m256i zero = _mm256_setzero_si256();
static constexpr size_t nper = sizeof(__m256i) / sizeof(uint32_t);
const size_t nsimd = arr_sz / nper;
const size_t nsimd4 = (nsimd / 4) * 4;
size_t i = 0;
for(; i < nsimd4; i += 4) {
_mm256_storeu_si256((__m256i *)(arr + nper * i), zero);
_mm256_storeu_si256((__m256i *)(arr + nper * (i + 1)), zero);
_mm256_storeu_si256((__m256i *)(arr + nper * (i + 2)), zero);
_mm256_storeu_si256((__m256i *)(arr + nper * (i + 3)), zero);
}
for(;i < nsimd; ++i) {
_mm256_storeu_si256((__m256i *)(arr + nper * i), zero);
}
for(i *= sizeof(__m256i) / sizeof(uint32_t); i < arr_sz; ++i) {
arr[i] = 0;
}
#elif __SSE2__
__m128i zero = _mm_setzero_si128();
const size_t nsimd = arr_sz / 4;
const size_t nsimd4 = (nsimd / 4) * 4;
size_t i = 0;
for(; i < nsimd4; i += 4) {
_mm_storeu_si128((__m128i *)(arr + 4 * i), zero);
_mm_storeu_si128((__m128i *)(arr + 4 * (i + 1)), zero);
_mm_storeu_si128((__m128i *)(arr + 4 * (i + 2)), zero);
_mm_storeu_si128((__m128i *)(arr + 4 * (i + 3)), zero);
}
for(;i < nsimd; ++i) {
_mm_storeu_si128((__m128i *)(arr + 4 * i), zero);
}
for(i *= 4; i < arr_sz; ++i) {
arr[i] = 0;
}
#endif
#else
std::memset(arr, 0, sizeof(uint32_t) * arr_sz);
#endif
}
template <typename T2>
static uint64_t print_array(const char* prefix,
char* chrm,
int32_t tid,
const T2* arr,
const long arr_sz,
const bool skip_zeros,
bigWigFile_t* bwfp,
FILE* cov_fh,
const bool dont_output_coverage = false,
bool no_region=true,
BGZF* gcov_fh = nullptr,
hts_idx_t* cidx = nullptr,
int* chrms_in_cidx = nullptr,
FILE* wcov_fh=nullptr,
BGZF* gwcov_fh=nullptr,
int window_size=0,
Op op = csum) {
bool first = true;
bool first_print = true;
uint32_t running_value = 0;
uint32_t last_pos = 0;
uint64_t auc = 0;
//from https://stackoverflow.com/questions/27401388/efficient-gzip-writing-with-gzprintf
int chrnamelen = strlen(chrm);
int total_line_len = chrnamelen + COORD_STR_LEN;
int num_lines_per_buf = round(OUT_BUFF_SZ / total_line_len) - 3;
int buf_written = 0;
char* buf = nullptr;
char* bufptr = nullptr;
int (*printPtr) (void* fh, char* buf, uint32_t buf_len) = &my_write;
void* cfh = nullptr;
if(!bwfp) {
buf = new char[OUT_BUFF_SZ];
bufptr = buf;
cfh = cov_fh;
//writing gzip
if(!cov_fh) {
printPtr = &my_gzwrite;
cfh = gcov_fh;
}
}
//might only want to print windowed coverage
bool print_windowed_coverage = window_size > 0 && (gwcov_fh || wcov_fh);
void* wcfh = nullptr;
if(print_windowed_coverage) {
wcfh = wcov_fh;
//this assumes we're never going to have coverage and windowed coverage be different in terms of --gzip
if(!wcov_fh) {
printPtr = &my_gzwrite;
wcfh = gwcov_fh;
}
}
uint32_t buf_len = 0;
int bytes_written = 0;
char* startp = new char[32];
char* endp = new char[32];
char* valuep = new char[32];
float running_value_ = 0.0;
uint32_t wcounter = 0;
int64_t wsum = 0;
char* wbuf = new char[1024];
int window_bytes_written = -1;
uint32_t window_start = 0;
//make sure we track this chromosome in whatever index we're building
//if we may it this far, means the chromosome had some alignments
if(chrms_in_cidx && chrms_in_cidx[tid+1] == 0)
chrms_in_cidx[tid+1] = ++chrms_in_cidx[0];
for(uint32_t i = 0; i < arr_sz; i++) {
if(first || (!no_region && running_value != arr[i]) || (no_region && arr[i] != 0)) {
if(!first) {
if(running_value > 0 || !skip_zeros) {
//based on wiggletools' AUC calculation
auc += (i - last_pos) * ((long) running_value);
if(not dont_output_coverage) {
if(bwfp && first_print) {
running_value_ = static_cast<float>(running_value);
bwAddIntervals(bwfp, &chrm, &last_pos, &i, &running_value_, 1);
}
else if(bwfp) {
running_value_ = static_cast<float>(running_value);
bwAppendIntervals(bwfp, &last_pos, &i, &running_value_, 1);
}
else {
memcpy(bufptr, chrm, chrnamelen);
char *oldbufptr = bufptr;
bufptr += chrnamelen;
*bufptr++='\t';
//idea from https://github.com/brentp/mosdepth/releases/tag/v0.2.9
uint32_t digits = u32toa_countlut(last_pos, bufptr, '\t');
bufptr+=digits+1;
digits = u32toa_countlut(i, bufptr, '\t');
bufptr+=digits+1;
digits = u32toa_countlut(running_value, bufptr, '\n');
bufptr+=digits+1;
buf_len += (bufptr - oldbufptr); // Track bytes written using the distance bufptr has traveled
bufptr[0]='\0';
(*printPtr)(cfh, buf, buf_len);
if(cidx) {
if(hts_idx_push(cidx, chrms_in_cidx[tid+1]-1, last_pos, i, bgzf_tell((BGZF*) cfh), 1) < 0) {
fprintf(stderr,"error writing line in index at coordinates: %s:%u-%u, tid: %d idx tid: %d exiting\n",chrm,last_pos,i, tid, chrms_in_cidx[tid+1]-1);
//TODO: change this to a return
exit(-1);
}
}
buf_written++;
bufptr = buf;
buf_written = 0;
buf_len = 0;
}
first_print = false;
}
}
}
first = false;
if(no_region)