ZTWHHH commited on
Commit
c5fecc5
·
verified ·
1 Parent(s): c54fac3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. falcon/lib/python3.10/site-packages/pysam/include/bcftools/call.h +149 -0
  2. falcon/lib/python3.10/site-packages/pysam/include/bcftools/ccall.c.pysam.c +340 -0
  3. falcon/lib/python3.10/site-packages/pysam/include/bcftools/hclust.h +77 -0
  4. falcon/lib/python3.10/site-packages/pysam/include/bcftools/ploidy.c +268 -0
  5. falcon/lib/python3.10/site-packages/pysam/include/bcftools/rbuf.h +261 -0
  6. falcon/lib/python3.10/site-packages/pysam/include/bcftools/tsv2vcf.c.pysam.c +137 -0
  7. falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfconvert.c +1791 -0
  8. falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfgtcheck.c.pysam.c +1286 -0
  9. falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfmerge.c.pysam.c +0 -0
  10. falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfsort.c +460 -0
  11. falcon/lib/python3.10/site-packages/pysam/include/samtools/amplicon_stats.c.pysam.c +1758 -0
  12. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.c +267 -0
  13. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.h +39 -0
  14. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam2depth.c +999 -0
  15. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_addrprg.c +499 -0
  16. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c +1117 -0
  17. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c.pysam.c +1119 -0
  18. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.h +54 -0
  19. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_aux.c +61 -0
  20. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_color.c.pysam.c +175 -0
  21. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c +86 -0
  22. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c.pysam.c +88 -0
  23. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_import.c.pysam.c +525 -0
  24. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c +289 -0
  25. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c.pysam.c +291 -0
  26. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.c +225 -0
  27. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.h +57 -0
  28. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_markdup.c +2510 -0
  29. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c +728 -0
  30. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c.pysam.c +730 -0
  31. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_md.c.pysam.c +534 -0
  32. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_quickcheck.c +190 -0
  33. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_reheader.c +634 -0
  34. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdup.c.pysam.c +327 -0
  35. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c +230 -0
  36. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c.pysam.c +232 -0
  37. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_samples.c +433 -0
  38. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_sort.c.pysam.c +0 -0
  39. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c +618 -0
  40. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c.pysam.c +620 -0
  41. falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_stat.c +346 -0
  42. falcon/lib/python3.10/site-packages/pysam/include/samtools/bamtk.c +307 -0
  43. falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c +637 -0
  44. falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c.pysam.c +639 -0
  45. falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.h +45 -0
  46. falcon/lib/python3.10/site-packages/pysam/include/samtools/consensus_pileup.h +102 -0
  47. falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c +665 -0
  48. falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c.pysam.c +667 -0
  49. falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c +257 -0
  50. falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c.pysam.c +259 -0
falcon/lib/python3.10/site-packages/pysam/include/bcftools/call.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* call.h -- variant calling declarations.
2
+
3
+ Copyright (C) 2013-2015, 2019-2020 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE. */
24
+
25
+ #ifndef __CALL_H__
26
+ #define __CALL_H__
27
+
28
+ #include <htslib/vcf.h>
29
+ #include <htslib/synced_bcf_reader.h>
30
+ #include "vcmp.h"
31
+
32
+ #define CALL_KEEPALT 1
33
+ #define CALL_VARONLY (1<<1)
34
+ #define CALL_CONSTR_TRIO (1<<2)
35
+ #define CALL_CONSTR_ALLELES (1<<3)
36
+ //
37
+ #define CALL_FMT_PV4 (1<<5)
38
+ #define CALL_FMT_GQ (1<<6)
39
+ #define CALL_FMT_GP (1<<7)
40
+
41
+ #define FATHER 0
42
+ #define MOTHER 1
43
+ #define CHILD 2
44
+ typedef struct
45
+ {
46
+ char *name;
47
+ int sample[3]; // father, mother, child
48
+ int type; // see FTYPE_* definitions in mcall.c
49
+ }
50
+ family_t;
51
+
52
+ // For the single-sample and grouped -G calling
53
+ typedef struct
54
+ {
55
+ double ref_lk, max_lk, lk_sum;
56
+ float *qsum; // QS(quality sum) values
57
+ int nqsum;
58
+ uint32_t *smpl, nsmpl;
59
+ uint32_t nals, als;
60
+ }
61
+ smpl_grp_t;
62
+
63
+ // For the `-C alleles -i` constrained calling
64
+ typedef struct
65
+ {
66
+ uint32_t n:31, used:1;
67
+ char **allele;
68
+ }
69
+ tgt_als_t;
70
+
71
+ typedef struct _ccall_t ccall_t;
72
+ typedef struct
73
+ {
74
+ // mcall only
75
+ int npdg;
76
+ int *als_map, nals_map; // mapping from full set of alleles to trimmed set of alleles (old -> new)
77
+ int *pl_map, npl_map; // same as above for PLs, but reverse (new -> old)
78
+ char **als; // array to hold the trimmed set of alleles to appear on output
79
+ int nals; // size of the als array
80
+ int als_new, nals_new; // bitmask with final alleles and their number
81
+ family_t *fams; // list of families and samples for trio calling
82
+ int nfams, mfams;
83
+ int ntrio[5][5]; // possible trio genotype combinations and their counts; first idx:
84
+ uint16_t *trio[5][5]; // family type, second index: allele count (2-4, first two are unused)
85
+ double *GLs;
86
+ float *GPs; // FORMAT/GP: posterior probabilities
87
+ int32_t *GQs, *ADs; // FORMAT/GQ: genotype qualities; AD: allelic depth for -G
88
+ int32_t *itmp; // temporary int array, used for new PLs with CALL_CONSTR_ALLELES
89
+ int n_itmp, nGPs, nADs;
90
+ vcmp_t *vcmp;
91
+ double trio_Pm_SNPs, trio_Pm_del, trio_Pm_ins; // P(mendelian) for trio calling, see mcall_call_trio_genotypes()
92
+ int32_t *ugts, *cgts; // unconstraind and constrained GTs
93
+ uint32_t output_tags;
94
+ char *prior_AN, *prior_AC; // reference panel AF tags (AF=AC/AN)
95
+ tgt_als_t *tgt_als; // for CALL_CONSTR_ALLELES
96
+ char *sample_groups; // for single-sample or grouped calling with -G
97
+ char *sample_groups_tag; // for -G [AD|QS:]
98
+ smpl_grp_t *smpl_grp;
99
+ int nsmpl_grp;
100
+
101
+ // ccall only
102
+ double indel_frac, min_perm_p, min_lrt;
103
+ double prior_type, pref;
104
+ int ngrp1_samples, n_perm;
105
+ char *prior_file;
106
+ ccall_t *cdat;
107
+
108
+ // shared
109
+ bcf_srs_t *srs; // BCF synced readers holding target alleles for CALL_CONSTR_ALLELES
110
+ bcf1_t *rec;
111
+ bcf_hdr_t *hdr;
112
+ uint32_t flag; // One or more of the CALL_* flags defined above
113
+ uint8_t *ploidy, all_diploid, unseen;
114
+
115
+ double pl2p[256]; // PL to 10^(-PL/10) table
116
+ int32_t *PLs; // VCF PL likelihoods (rw)
117
+ int nPLs, mPLs, nac;
118
+ int32_t *gts, *ac; // GTs and AC (w)
119
+ double *pdg; // PLs converted to P(D|G)
120
+ float *anno16; int n16; // see anno[16] in bam2bcf.h
121
+ double theta; // prior
122
+ }
123
+ call_t;
124
+
125
+ void error(const char *format, ...);
126
+
127
+ /*
128
+ * call() - return -1 value on critical error; -2 to skip the site; or the number of non-reference
129
+ * alleles on success.
130
+ */
131
+ int mcall(call_t *call, bcf1_t *rec); // multiallic and rare-variant calling model
132
+ int ccall(call_t *call, bcf1_t *rec); // the default consensus calling model
133
+ int qcall(call_t *call, bcf1_t *rec); // QCall output
134
+
135
+ void mcall_init(call_t *call);
136
+ void ccall_init(call_t *call);
137
+ void qcall_init(call_t *call);
138
+
139
+ void mcall_destroy(call_t *call);
140
+ void ccall_destroy(call_t *call);
141
+ void qcall_destroy(call_t *call);
142
+
143
+ void call_init_pl2p(call_t *call);
144
+ uint32_t *call_trio_prep(int is_x, int is_son);
145
+
146
+ void init_allele_trimming_maps(call_t *call, int nals_ori, int als_out);
147
+ void mcall_trim_and_update_numberR(call_t *call, bcf1_t *rec, int nals_ori, int nals_new);
148
+
149
+ #endif
falcon/lib/python3.10/site-packages/pysam/include/bcftools/ccall.c.pysam.c ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bcftools.pysam.h"
2
+
3
+ /* ccall.c -- consensus variant calling.
4
+
5
+ Copyright (C) 2013-2014 Genome Research Ltd.
6
+ Portions copyright (C) 2010 Broad Institute.
7
+
8
+ Author: Petr Danecek <pd3@sanger.ac.uk>
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 THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ THE SOFTWARE. */
27
+
28
+ #include <math.h>
29
+ #include <assert.h>
30
+ #include <htslib/kfunc.h>
31
+ #include "call.h"
32
+ #include "kmin.h"
33
+ #include "prob1.h"
34
+
35
+ // Most of the original -c calling was moved to bcftools as it was
36
+ // and its data structures were wrapped into the ccal_t to make it
37
+ // functional quickly. This is not the desired state.
38
+ struct _ccall_t
39
+ {
40
+ bcf_p1aux_t *p1;
41
+ };
42
+
43
+ void ccall_init(call_t *call)
44
+ {
45
+ call->cdat = (ccall_t*) calloc(1,sizeof(ccall_t));
46
+ call_init_pl2p(call);
47
+ call->cdat->p1 = bcf_p1_init(bcf_hdr_nsamples(call->hdr), call->ploidy);
48
+ call->gts = (int*) calloc(bcf_hdr_nsamples(call->hdr)*2,sizeof(int)); // assuming at most diploid everywhere
49
+ call->nals_map = 5;
50
+ call->als_map = (int*) malloc(sizeof(int)*call->nals_map);
51
+
52
+ bcf_hdr_append(call->hdr,"##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
53
+ if ( call->output_tags & CALL_FMT_GQ )
54
+ {
55
+ bcf_hdr_append(call->hdr,"##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">");
56
+ call->GQs = (int32_t*) malloc(sizeof(int32_t)*bcf_hdr_nsamples(call->hdr));
57
+ }
58
+ if ( call->output_tags & CALL_FMT_GP )
59
+ error("Sorry, -f GP is not supported with -c\n");
60
+ bcf_hdr_append(call->hdr,"##INFO=<ID=AF1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\">");
61
+ // Todo: groups not migrated to 'bcftools call' yet
62
+ bcf_hdr_append(call->hdr,"##INFO=<ID=AF2,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first and second group ALT allele frequency (assuming HWE)\">");
63
+ bcf_hdr_append(call->hdr,"##INFO=<ID=AC1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\">");
64
+ bcf_hdr_append(call->hdr,"##INFO=<ID=MQ,Number=1,Type=Integer,Description=\"Root-mean-square mapping quality of covering reads\">\n");
65
+ bcf_hdr_append(call->hdr,"##INFO=<ID=FQ,Number=1,Type=Float,Description=\"Phred probability of all samples being the same\">\n");
66
+ bcf_hdr_append(call->hdr,"##INFO=<ID=PV4,Number=4,Type=Float,Description=\"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\">\n");
67
+ bcf_hdr_append(call->hdr,"##INFO=<ID=G3,Number=3,Type=Float,Description=\"ML estimate of genotype frequencies\">\n");
68
+ bcf_hdr_append(call->hdr,"##INFO=<ID=HWE,Number=1,Type=Float,Description=\"Chi^2 based HWE test P-value based on G3\">\n");
69
+ // bcf_hdr_append(call->hdr,);
70
+ // bcf_hdr_append(call->hdr,);
71
+ bcf_hdr_append(call->hdr,"##INFO=<ID=DP4,Number=4,Type=Integer,Description=\"Number of high-quality ref-forward , ref-reverse, alt-forward and alt-reverse bases\">");
72
+
73
+ return;
74
+ }
75
+ void ccall_destroy(call_t *call)
76
+ {
77
+ free(call->itmp);
78
+ free(call->als_map);
79
+ free(call->gts);
80
+ free(call->anno16);
81
+ free(call->PLs);
82
+ free(call->GQs);
83
+ free(call->pdg);
84
+ bcf_p1_destroy(call->cdat->p1);
85
+ free(call->cdat);
86
+ return;
87
+ }
88
+
89
+ // Inits P(D|G): convert PLs from log space, only two alleles (three PLs) are used.
90
+ // NB: The original samtools calling code uses pdgs in reverse order (AA comes
91
+ // first, RR last), while the -m calling model uses the canonical order.
92
+ static void set_pdg3(double *pl2p, int *PLs, double *pdg, int n_smpl, int n_gt)
93
+ {
94
+ int i;
95
+ for (i=0; i<n_smpl; i++)
96
+ {
97
+ pdg[2] = pl2p[ PLs[0] ];
98
+ pdg[1] = pl2p[ PLs[1] ];
99
+ pdg[0] = pl2p[ PLs[2] ];
100
+ PLs += n_gt;
101
+ pdg += 3;
102
+ }
103
+ }
104
+
105
+ static double ttest(int n1, int n2, float a[4])
106
+ {
107
+ extern double kf_betai(double a, double b, double x);
108
+ double t, v, u1, u2;
109
+ if (n1 == 0 || n2 == 0 || n1 + n2 < 3) return 1.0;
110
+ u1 = (double)a[0] / n1; u2 = (double)a[2] / n2;
111
+ if (u1 <= u2) return 1.;
112
+ t = (u1 - u2) / sqrt(((a[1] - n1 * u1 * u1) + (a[3] - n2 * u2 * u2)) / (n1 + n2 - 2) * (1./n1 + 1./n2));
113
+ v = n1 + n2 - 2;
114
+ return t < 0.? 1. : .5 * kf_betai(.5*v, .5, v/(v+t*t));
115
+ }
116
+
117
+ static int test16_core(float anno[16], anno16_t *a)
118
+ {
119
+ extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two);
120
+ double left, right;
121
+ int i;
122
+ a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.;
123
+ for (i=0; i<4; i++) a->d[i] = anno[i];
124
+ a->depth = anno[0] + anno[1] + anno[2] + anno[3];
125
+ a->is_tested = (anno[0] + anno[1] > 0 && anno[2] + anno[3] > 0);
126
+ if (a->depth == 0) return -1;
127
+ a->mq = (int)(sqrt((anno[9] + anno[11]) / a->depth) + .499);
128
+ kt_fisher_exact(anno[0], anno[1], anno[2], anno[3], &left, &right, &a->p[0]);
129
+ for (i = 1; i < 4; ++i)
130
+ a->p[i] = ttest(anno[0] + anno[1], anno[2] + anno[3], anno+4*i);
131
+ return 0;
132
+ }
133
+
134
+ int test16(float *anno16, anno16_t *a)
135
+ {
136
+ a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.;
137
+ a->d[0] = a->d[1] = a->d[2] = a->d[3] = 0.;
138
+ a->mq = a->depth = a->is_tested = 0;
139
+ return test16_core(anno16, a);
140
+ }
141
+ static int update_bcf1(call_t *call, bcf1_t *rec, const bcf_p1rst_t *pr, double em[10])
142
+ {
143
+ int has_I16, is_var;
144
+ float fq, r;
145
+ anno16_t a;
146
+ float tmpf[4], tmpi;
147
+
148
+ bcf_get_info_float(call->hdr, rec, "I16", &call->anno16, &call->n16);
149
+
150
+ has_I16 = test16(call->anno16, &a) >= 0? 1 : 0;
151
+
152
+ // print EM
153
+ if (em[0] >= 0)
154
+ {
155
+ tmpf[0] = 1 - em[0];
156
+ bcf_update_info_float(call->hdr, rec, "AF1", tmpf, 1);
157
+ }
158
+ if (em[4] >= 0 && em[4] <= 0.05)
159
+ {
160
+ tmpf[0] = em[3]; tmpf[1] = em[2]; tmpf[2] = em[1]; tmpf[3] = em[4];
161
+ bcf_update_info_float(call->hdr, rec, "G3", tmpf, 3);
162
+ bcf_update_info_float(call->hdr, rec, "HWE", &tmpf[3], 1);
163
+ }
164
+ if (em[5] >= 0 && em[6] >= 0)
165
+ {
166
+ tmpf[0] = 1 - em[5]; tmpf[1] = 1 - em[6];
167
+ bcf_update_info_float(call->hdr, rec, "AF2", tmpf, 2);
168
+ }
169
+ if (em[7] >= 0)
170
+ {
171
+ tmpf[0] = em[7];
172
+ bcf_update_info_float(call->hdr, rec, "LRT", tmpf, 1);
173
+ }
174
+ if (em[8] >= 0)
175
+ {
176
+ tmpf[0] = em[8];
177
+ bcf_update_info_float(call->hdr, rec, "LRT2", tmpf, 1);
178
+ }
179
+
180
+ bcf_p1aux_t *p1 = call->cdat->p1;
181
+ if (p1->cons_llr > 0)
182
+ {
183
+ tmpi = p1->cons_llr;
184
+ bcf_update_info_int32(call->hdr, rec, "CLR", &tmpi, 1);
185
+ // todo: trio calling with -c
186
+ if (p1->cons_gt > 0)
187
+ {
188
+ char tmp[4];
189
+ tmp[0] = p1->cons_gt&0xff; tmp[1] = p1->cons_gt>>8&0xff; tmp[2] = p1->cons_gt>>16&0xff; tmp[3] = 0;
190
+ bcf_update_info_string(call->hdr, rec, "UGT", tmp);
191
+ tmp[0] = p1->cons_gt>>32&0xff; tmp[1] = p1->cons_gt>>40&0xff; tmp[2] = p1->cons_gt>>48&0xff;
192
+ bcf_update_info_string(call->hdr, rec, "CGT", tmp);
193
+ }
194
+ }
195
+ is_var = (pr->p_ref < call->pref);
196
+ r = is_var? pr->p_ref : pr->p_var;
197
+
198
+ bcf_update_info_int32(call->hdr, rec, "AC1", &pr->ac, 1);
199
+ int32_t dp[4]; dp[0] = call->anno16[0]; dp[1] = call->anno16[1]; dp[2] = call->anno16[2]; dp[3] = call->anno16[3];
200
+ bcf_update_info_int32(call->hdr, rec, "DP4", dp, 4);
201
+ bcf_update_info_int32(call->hdr, rec, "MQ", &a.mq, 1);
202
+
203
+ fq = pr->p_ref_folded < 0.5? -4.343 * log(pr->p_ref_folded) : 4.343 * log(pr->p_var_folded);
204
+ if (fq < -999) fq = -999;
205
+ if (fq > 999) fq = 999;
206
+ bcf_update_info_float(call->hdr, rec, "FQ", &fq, 1);
207
+
208
+ assert( pr->cmp[0]<0 );
209
+ // todo
210
+ // if (pr->cmp[0] >= 0.) { // two sample groups
211
+ // int i, q[3];
212
+ // for (i = 1; i < 3; ++i) {
213
+ // double x = pr->cmp[i] + pr->cmp[0]/2.;
214
+ // q[i] = x == 0? 255 : (int)(-4.343 * log(x) + .499);
215
+ // if (q[i] > 255) q[i] = 255;
216
+ // }
217
+ // if (pr->perm_rank >= 0) ksprintf(&s, "PR=%d;", pr->perm_rank);
218
+ //
219
+ // ksprintf(&s, "PCHI2=%.3g;PC2=%d,%d;", q[1], q[2], pr->p_chi2);
220
+ // }
221
+
222
+ if (has_I16 && a.is_tested)
223
+ {
224
+ int i;
225
+ for (i=0; i<4; i++) tmpf[i] = a.p[i];
226
+ bcf_update_info_float(call->hdr, rec, "PV4", tmpf, 4);
227
+ }
228
+ bcf_update_info_int32(call->hdr, rec, "I16", NULL, 0); // remove I16 tag
229
+ bcf_update_info_int32(call->hdr, rec, "QS", NULL, 0); // remove QS tag
230
+
231
+ rec->qual = r < 1e-100? 999 : -4.343 * log(r);
232
+ if (rec->qual > 999) rec->qual = 999;
233
+
234
+ // Remove unused alleles
235
+ int nals_ori = rec->n_allele, nals = !is_var && !(call->flag & CALL_KEEPALT) ? 1 : pr->rank0 < 2? 2 : pr->rank0+1;
236
+ if ( call->flag & CALL_KEEPALT && call->unseen==nals-1 ) nals--;
237
+
238
+ if ( nals<rec->n_allele )
239
+ {
240
+ bcf_update_alleles(call->hdr, rec, (const char**)rec->d.allele, nals);
241
+
242
+ // Update PLs
243
+ int npls_src = call->nPLs / rec->n_sample, npls_dst = nals*(nals+1)/2;
244
+ int *pls_src = call->PLs - npls_src, *pls_dst = call->PLs - npls_dst;
245
+ int isample, i;
246
+ for (isample = 0; isample < rec->n_sample; isample++)
247
+ {
248
+ pls_src += npls_src;
249
+ pls_dst += npls_dst;
250
+ if ( !call->ploidy || call->ploidy[isample]==2 )
251
+ {
252
+ for (i=0; i<npls_dst; i++)
253
+ pls_dst[i] = pls_src[i];
254
+ }
255
+ else
256
+ {
257
+ for (i=0; i<nals; i++)
258
+ {
259
+ int isrc = (i+1)*(i+2)/2-1;
260
+ pls_dst[i] = pls_src[isrc];
261
+ }
262
+ if (i<npls_dst) pls_dst[i] = bcf_int32_vector_end;
263
+ }
264
+ }
265
+ bcf_update_format_int32(call->hdr, rec, "PL", call->PLs, npls_dst*rec->n_sample);
266
+ }
267
+
268
+ // Call genotypes
269
+ int i;
270
+ for (i=0; i<rec->n_sample; i++)
271
+ {
272
+ int x = ( is_var || call->output_tags & CALL_FMT_GQ ) ? bcf_p1_call_gt(p1, pr->f_exp, i, is_var) : 2;
273
+ int gt = x&3;
274
+ if ( !call->ploidy || call->ploidy[i]==2 )
275
+ {
276
+ if ( gt==1 )
277
+ {
278
+ call->gts[2*i] = bcf_gt_unphased(0);
279
+ call->gts[2*i+1] = bcf_gt_unphased(1);
280
+ }
281
+ else if ( gt==0 )
282
+ {
283
+ call->gts[2*i] = bcf_gt_unphased(1);
284
+ call->gts[2*i+1] = bcf_gt_unphased(1);
285
+ }
286
+ else
287
+ {
288
+ call->gts[2*i] = bcf_gt_unphased(0);
289
+ call->gts[2*i+1] = bcf_gt_unphased(0);
290
+ }
291
+ if ( call->output_tags & CALL_FMT_GQ ) call->GQs[i] = x>>2;
292
+ }
293
+ else
294
+ {
295
+ if ( gt==0 ) call->gts[2*i] = bcf_gt_unphased(1);
296
+ else call->gts[2*i] = bcf_gt_unphased(0);
297
+ call->gts[2*i+1] = bcf_int32_vector_end;
298
+ if ( call->output_tags & CALL_FMT_GQ ) call->GQs[i] = bcf_int32_missing;
299
+ }
300
+ }
301
+ bcf_update_genotypes(call->hdr, rec, call->gts, rec->n_sample*2);
302
+ if ( call->output_tags & CALL_FMT_GQ )
303
+ bcf_update_format_int32(call->hdr, rec, "GQ", call->GQs, rec->n_sample);
304
+
305
+ // trim Number=R tags
306
+ int out_als = 0;
307
+ for (i=0; i<nals; i++) out_als |= 1<<i;
308
+ init_allele_trimming_maps(call, nals_ori, out_als);
309
+ mcall_trim_and_update_numberR(call, rec, nals_ori, nals);
310
+
311
+ return is_var;
312
+ }
313
+
314
+
315
+ int ccall(call_t *call, bcf1_t *rec)
316
+ {
317
+ int nsmpl = bcf_hdr_nsamples(call->hdr);
318
+
319
+ // Get the genotype likelihoods
320
+ int nals = rec->n_allele;
321
+ call->nPLs = bcf_get_format_int32(call->hdr, rec, "PL", &call->PLs, &call->mPLs);
322
+ if ( call->nPLs!=nsmpl*nals*(nals+1)/2 && call->nPLs!=nsmpl*nals ) // diploid+haploid or haploid only
323
+ error("Wrong number of PL fields? nals=%d npl=%d\n", nals,call->nPLs);
324
+
325
+ // Convert PLs to probabilities, only first two alleles are considered
326
+ int ngts = nals*(nals+1)/2;
327
+ hts_expand(double, 3*nsmpl, call->npdg, call->pdg);
328
+ set_pdg3(call->pl2p, call->PLs, call->pdg, nsmpl, ngts);
329
+
330
+ double em[10] = {-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.};
331
+ int ret = bcf_em1(call, rec, call->ngrp1_samples, 0x1ff, em);
332
+
333
+ bcf_p1rst_t pr;
334
+ int do_contrast = (em[7] >= 0 && em[7] < call->min_lrt) ? 1 : 0;
335
+ ret = bcf_p1_cal(call, rec, do_contrast, call->cdat->p1, &pr);
336
+ if (pr.p_ref >= call->pref && (call->flag & CALL_VARONLY)) return 0;
337
+ if (ret >= 0) ret = update_bcf1(call, rec, &pr, em);
338
+ return ret;
339
+ }
340
+
falcon/lib/python3.10/site-packages/pysam/include/bcftools/hclust.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The MIT License
2
+
3
+ Copyright (c) 2016 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.
24
+
25
+ */
26
+
27
+ /*
28
+ Simple hierarchical clustering
29
+ */
30
+
31
+ #ifndef __HCLUST_H__
32
+ #define __HCLUST_H__
33
+
34
+ #include <stdio.h>
35
+
36
+ typedef struct _hclust_t hclust_t;
37
+
38
+ typedef struct
39
+ {
40
+ float dist;
41
+ int nmemb, *memb;
42
+ }
43
+ cluster_t;
44
+
45
+ #define PDIST(mat,a,b) (mat)[((a)>(b)?((a)*((a)-1)/2+(b)):((b)*((b)-1)/2+(a)))]
46
+
47
+ /*
48
+ * hclust_init() - init and run clustering
49
+ * @n: number of elements
50
+ * @pdist: pairwise distances. The array will be modified by hclust and
51
+ * must exist until hclust_destroy() is called
52
+ */
53
+ hclust_t *hclust_init(int n, float *pdist);
54
+ void hclust_destroy(hclust_t *clust);
55
+
56
+ /*
57
+ * hclust_create_list() - returns a list of clusters
58
+ * @min_inter_dist: minimum inter-cluster distance. If smaller, elements are considered
59
+ * homogenous, belonging to the same cluster.
60
+ * @max_intra_dist: maximum intra-cluster distance allowed. If smaller than 0,
61
+ * the threshold can be heuristically lowered, otherwise considered
62
+ * a fixed cutoff. The pointer will be filled to the cutoff actually used.
63
+ */
64
+ cluster_t *hclust_create_list(hclust_t *clust, float min_inter_dist, float *max_intra_dist, int *nclust);
65
+ void hclust_destroy_list(cluster_t *clust, int nclust);
66
+
67
+ /*
68
+ * Access debugging data used in the decision making process. Note that this
69
+ * must be called immediately after hclust_create_list because other calls,
70
+ * such as hclust_create_dot(), invalidate the temporary data structures.
71
+ */
72
+ char **hclust_explain(hclust_t *clust, int *nlines);
73
+
74
+ char *hclust_create_dot(hclust_t *clust, char **labels, float th);
75
+
76
+ #endif
77
+
falcon/lib/python3.10/site-packages/pysam/include/bcftools/ploidy.c ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (C) 2014-2016 Genome Research Ltd.
3
+
4
+ Author: Petr Danecek <pd3@sanger.ac.uk>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
23
+ */
24
+
25
+ #include <htslib/khash_str2int.h>
26
+ #include <htslib/kseq.h>
27
+ #include <htslib/hts.h>
28
+ #include "bcftools.h"
29
+ #include "ploidy.h"
30
+
31
+ struct _ploidy_t
32
+ {
33
+ int nsex, msex; // number of genders, m:number of allocated elements in id2sex array
34
+ int dflt, min, max; // ploidy: default, min and max (only explicitly listed)
35
+ int *sex2dflt;
36
+ regidx_t *idx;
37
+ regitr_t *itr;
38
+ void *sex2id;
39
+ char **id2sex;
40
+ kstring_t tmp_str;
41
+ };
42
+
43
+ typedef struct
44
+ {
45
+ int sex, ploidy;
46
+ }
47
+ sex_ploidy_t;
48
+
49
+
50
+ regidx_t *ploidy_regions(ploidy_t *ploidy)
51
+ {
52
+ return ploidy->idx;
53
+ }
54
+
55
+ int ploidy_parse(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr)
56
+ {
57
+ int i, ret;
58
+ ploidy_t *ploidy = (ploidy_t*) usr;
59
+ void *sex2id = ploidy->sex2id;
60
+
61
+ // Check for special case of default ploidy "* * * <sex> <ploidy>"
62
+ int default_ploidy_def = 0;
63
+
64
+ char *ss = (char*) line;
65
+ while ( *ss && isspace(*ss) ) ss++;
66
+ if ( ss[0]=='*' && (!ss[1] || isspace(ss[1])) )
67
+ default_ploidy_def = 1; // definition of default ploidy, chr="*"
68
+ else
69
+ {
70
+ // Fill CHR,FROM,TO
71
+ ret = regidx_parse_tab(line,chr_beg,chr_end,beg,end,NULL,NULL);
72
+ if ( ret!=0 ) return ret;
73
+ }
74
+
75
+ // Skip the fields already parsed by regidx_parse_tab
76
+ ss = (char*) line;
77
+ while ( *ss && isspace(*ss) ) ss++;
78
+ for (i=0; i<3; i++)
79
+ {
80
+ while ( *ss && !isspace(*ss) ) ss++;
81
+ if ( !*ss ) return -2; // wrong number of fields
82
+ while ( *ss && isspace(*ss) ) ss++;
83
+ }
84
+ if ( !*ss ) return -2;
85
+
86
+ // Parse the payload
87
+ char *se = ss;
88
+ while ( *se && !isspace(*se) ) se++;
89
+ if ( !*se || se==ss ) error("Could not parse: %s\n", line);
90
+ ploidy->tmp_str.l = 0;
91
+ kputsn(ss,se-ss,&ploidy->tmp_str);
92
+
93
+ sex_ploidy_t *sp = (sex_ploidy_t*) payload;
94
+ if ( khash_str2int_get(sex2id, ploidy->tmp_str.s, &sp->sex) != 0 )
95
+ {
96
+ ploidy->nsex++;
97
+ hts_expand0(char*,ploidy->nsex,ploidy->msex,ploidy->id2sex);
98
+ ploidy->id2sex[ploidy->nsex-1] = strdup(ploidy->tmp_str.s);
99
+ sp->sex = khash_str2int_inc(ploidy->sex2id, ploidy->id2sex[ploidy->nsex-1]);
100
+ ploidy->sex2dflt = (int*) realloc(ploidy->sex2dflt,sizeof(int)*ploidy->nsex);
101
+ ploidy->sex2dflt[ploidy->nsex-1] = -1;
102
+ }
103
+
104
+ ss = se;
105
+ while ( *se && isspace(*se) ) se++;
106
+ if ( !*se ) error("Could not parse: %s\n", line);
107
+ sp->ploidy = strtol(ss,&se,10);
108
+ if ( ss==se ) error("Could not parse: %s\n", line);
109
+ if ( ploidy->min<0 || sp->ploidy < ploidy->min ) ploidy->min = sp->ploidy;
110
+ if ( ploidy->max<0 || sp->ploidy > ploidy->max ) ploidy->max = sp->ploidy;
111
+
112
+ // Special case, chr="*" stands for a default value
113
+ if ( default_ploidy_def )
114
+ {
115
+ ploidy->sex2dflt[ploidy->nsex-1] = sp->ploidy;
116
+ return -1;
117
+ }
118
+
119
+ return 0;
120
+ }
121
+
122
+ static void _set_defaults(ploidy_t *ploidy, int dflt)
123
+ {
124
+ int i;
125
+ if ( khash_str2int_get(ploidy->sex2id, "*", &i) == 0 ) dflt = ploidy->sex2dflt[i];
126
+ for (i=0; i<ploidy->nsex; i++)
127
+ if ( ploidy->sex2dflt[i]==-1 ) ploidy->sex2dflt[i] = dflt;
128
+
129
+ ploidy->dflt = dflt;
130
+ if ( ploidy->min<0 || dflt < ploidy->min ) ploidy->min = dflt;
131
+ if ( ploidy->max<0 || dflt > ploidy->max ) ploidy->max = dflt;
132
+ }
133
+
134
+ ploidy_t *ploidy_init(const char *fname, int dflt)
135
+ {
136
+ ploidy_t *pld = (ploidy_t*) calloc(1,sizeof(ploidy_t));
137
+ if ( !pld ) return NULL;
138
+
139
+ pld->min = pld->max = -1;
140
+ pld->sex2id = khash_str2int_init();
141
+ pld->idx = regidx_init(fname,ploidy_parse,NULL,sizeof(sex_ploidy_t),pld);
142
+ if ( !pld->idx )
143
+ {
144
+ ploidy_destroy(pld);
145
+ return NULL;
146
+ }
147
+ pld->itr = regitr_init(pld->idx);
148
+ _set_defaults(pld,dflt);
149
+ return pld;
150
+ }
151
+
152
+ ploidy_t *ploidy_init_string(const char *str, int dflt)
153
+ {
154
+ ploidy_t *pld = (ploidy_t*) calloc(1,sizeof(ploidy_t));
155
+ if ( !pld ) return NULL;
156
+
157
+ pld->min = pld->max = -1;
158
+ pld->sex2id = khash_str2int_init();
159
+ pld->idx = regidx_init(NULL,ploidy_parse,NULL,sizeof(sex_ploidy_t),pld);
160
+ pld->itr = regitr_init(pld->idx);
161
+
162
+ kstring_t tmp = {0,0,0};
163
+ const char *ss = str;
164
+ while ( *ss )
165
+ {
166
+ while ( *ss && isspace(*ss) ) ss++;
167
+ const char *se = ss;
168
+ while ( *se && *se!='\r' && *se!='\n' ) se++;
169
+ tmp.l = 0;
170
+ kputsn(ss, se-ss, &tmp);
171
+ regidx_insert(pld->idx,tmp.s);
172
+ while ( *se && isspace(*se) ) se++;
173
+ ss = se;
174
+ }
175
+ free(tmp.s);
176
+
177
+ _set_defaults(pld,dflt);
178
+ return pld;
179
+ }
180
+
181
+ void ploidy_destroy(ploidy_t *ploidy)
182
+ {
183
+ if ( ploidy->sex2id ) khash_str2int_destroy_free(ploidy->sex2id);
184
+ if ( ploidy->itr ) regitr_destroy(ploidy->itr);
185
+ if ( ploidy->idx ) regidx_destroy(ploidy->idx);
186
+ free(ploidy->id2sex);
187
+ free(ploidy->tmp_str.s);
188
+ free(ploidy->sex2dflt);
189
+ free(ploidy);
190
+ }
191
+
192
+ int ploidy_query(ploidy_t *ploidy, char *seq, int pos, int *sex2ploidy, int *min, int *max)
193
+ {
194
+ int i, ret = regidx_overlap(ploidy->idx, seq,pos,pos, ploidy->itr);
195
+
196
+ if ( !sex2ploidy && !min && !max ) return ret;
197
+
198
+ if ( !ret )
199
+ {
200
+ // no overlap
201
+ if ( min ) *min = ploidy->dflt;
202
+ if ( max ) *max = ploidy->dflt;
203
+ if ( sex2ploidy )
204
+ for (i=0; i<ploidy->nsex; i++) sex2ploidy[i] = ploidy->sex2dflt[i];
205
+ return 0;
206
+ }
207
+
208
+ int _min = INT_MAX, _max = -1;
209
+ if ( sex2ploidy ) for (i=0; i<ploidy->nsex; i++) sex2ploidy[i] = ploidy->dflt;
210
+
211
+ while ( regitr_overlap(ploidy->itr) )
212
+ {
213
+ int sex = regitr_payload(ploidy->itr,sex_ploidy_t).sex;
214
+ int pld = regitr_payload(ploidy->itr,sex_ploidy_t).ploidy;
215
+ if ( pld!=ploidy->dflt )
216
+ {
217
+ if ( sex2ploidy ) sex2ploidy[ sex ] = pld;
218
+ if ( _min > pld ) _min = pld;
219
+ if ( _max < pld ) _max = pld;
220
+ }
221
+ }
222
+ if ( _max==-1 ) _max = _min = ploidy->dflt;
223
+ if ( max ) *max = _max;
224
+ if ( min ) *min = _min;
225
+
226
+ return 1;
227
+ }
228
+
229
+ int ploidy_nsex(ploidy_t *ploidy)
230
+ {
231
+ return ploidy->nsex;
232
+ }
233
+
234
+ char *ploidy_id2sex(ploidy_t *ploidy, int id)
235
+ {
236
+ if ( id<0 || id>=ploidy->nsex ) return NULL;
237
+ return ploidy->id2sex[id];
238
+ }
239
+
240
+ int ploidy_sex2id(ploidy_t *ploidy, char *sex)
241
+ {
242
+ int id;
243
+ if ( khash_str2int_get(ploidy->sex2id,sex,&id)!=0 ) return -1;
244
+ return id;
245
+ }
246
+
247
+ int ploidy_add_sex(ploidy_t *ploidy, const char *sex)
248
+ {
249
+ int id;
250
+ if ( khash_str2int_get(ploidy->sex2id, sex, &id)==0 ) return id;
251
+ ploidy->nsex++;
252
+ hts_expand0(char*,ploidy->nsex,ploidy->msex,ploidy->id2sex);
253
+ ploidy->id2sex[ploidy->nsex-1] = strdup(sex);
254
+ ploidy->sex2dflt = (int*) realloc(ploidy->sex2dflt,sizeof(int)*ploidy->nsex);
255
+ ploidy->sex2dflt[ploidy->nsex-1] = ploidy->dflt;
256
+ return khash_str2int_inc(ploidy->sex2id, ploidy->id2sex[ploidy->nsex-1]);
257
+ }
258
+
259
+ int ploidy_max(ploidy_t *ploidy)
260
+ {
261
+ return ploidy->dflt > ploidy->max ? ploidy->dflt : ploidy->max;
262
+ }
263
+
264
+ int ploidy_min(ploidy_t *ploidy)
265
+ {
266
+ return ploidy->dflt < ploidy->min ? ploidy->dflt : ploidy->min;
267
+ }
268
+
falcon/lib/python3.10/site-packages/pysam/include/bcftools/rbuf.h ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* rbuf.h -- round buffers.
2
+
3
+ Copyright (C) 2013-2014, 2017 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE. */
24
+
25
+ #ifndef __RBUF_H__
26
+ #define __RBUF_H__
27
+
28
+ #include <string.h>
29
+
30
+ typedef struct
31
+ {
32
+ int m,n,f; // m: allocated size, n: number of elements in the buffer, f: first element
33
+ }
34
+ rbuf_t;
35
+
36
+ /**
37
+ * rbuf_init() - initialize round buffer
38
+ * @rbuf: the rbuf_t holder
39
+ * @size: the maximum number of elements
40
+ *
41
+ */
42
+ static inline void rbuf_init(rbuf_t *rbuf, int size)
43
+ {
44
+ rbuf->m = size; rbuf->n = rbuf->f = 0;
45
+ }
46
+ /**
47
+ * rbuf_kth() - get index of the k-th element of the round buffer
48
+ * @rbuf: the rbuf_t holder
49
+ * @k: 0-based index. If negative, return k-th element from the end, 1-based
50
+ */
51
+ static inline int rbuf_kth(rbuf_t *rbuf, int k)
52
+ {
53
+ if ( k >= rbuf->n ) return -1;
54
+ if ( k < 0 )
55
+ {
56
+ k = rbuf->n + k;
57
+ if ( k < 0 ) return -1;
58
+ }
59
+ int i = k + rbuf->f;
60
+ if ( i >= rbuf->m ) i -= rbuf->m;
61
+ return i;
62
+ }
63
+ /**
64
+ * rbuf_last() - get index of the last element of the round buffer
65
+ * @rbuf: the rbuf_t holder
66
+ */
67
+ #define rbuf_last(rbuf) rbuf_kth(rbuf, -1)
68
+
69
+ /**
70
+ * rbuf_l2ridx() - get 0-based rbuf index which corresponds to i-th linear index
71
+ * @rbuf: the rbuf_t holder
72
+ * @idx: 0-based linear index
73
+ *
74
+ * Returns 0-based circular index or -1 if out of bounds
75
+ */
76
+ static inline int rbuf_l2ridx(rbuf_t *rbuf, int idx)
77
+ {
78
+ if ( idx < 0 || idx >= rbuf->n ) return -1;
79
+ if ( idx >= rbuf->f )
80
+ {
81
+ int i = idx - rbuf->f;
82
+ if ( i >= rbuf->n ) return -1;
83
+ return i;
84
+ }
85
+ int i = rbuf->m - rbuf->f + idx;
86
+ if ( i >= rbuf->n ) return -1;
87
+ return i;
88
+ }
89
+
90
+ /**
91
+ * rbuf_next() - get index of the next element in the round buffer
92
+ * @rbuf: the rbuf_t holder
93
+ * @i: pointer to the last rbuf index. Set to -1 before the first call.
94
+ *
95
+ * Sets i to the next position in the buffer. The return value indicates if
96
+ * the position points to a valid element (1) or if there are no more elements
97
+ * after *i (0). When the end is reached, *i is set to the first element in the
98
+ * buffer.
99
+ */
100
+ static inline int rbuf_next(rbuf_t *rbuf, int *i)
101
+ {
102
+ if ( !rbuf->n ) return 0;
103
+ if ( *i==-1 ) { *i = rbuf->f; return 1; }
104
+ int n = (rbuf->f <= *i) ? *i - rbuf->f + 1 : *i + rbuf->m - rbuf->f + 1;
105
+ if ( ++(*i) >= rbuf->m ) *i = 0;
106
+ if ( n < rbuf->n ) return 1;
107
+ *i = rbuf->f;
108
+ return 0;
109
+ }
110
+ /**
111
+ * rbuf_prev() - get index of the previous element in the round buffer
112
+ * @rbuf: the rbuf_t holder
113
+ * @i: pointer to the last rbuf index. Set to -1 before the first call.
114
+ *
115
+ * Sets i to the previous position in the buffer. The return value indicates if
116
+ * the position points to a valid element (1) or if there are no more elements
117
+ * before *i (0).
118
+ */
119
+ static inline int rbuf_prev(rbuf_t *rbuf, int *i)
120
+ {
121
+ if ( !rbuf->n || *i==rbuf->f ) return 0;
122
+ if ( *i==-1 )
123
+ {
124
+ *i = rbuf_last(rbuf);
125
+ return 1;
126
+ }
127
+ if ( --(*i) < 0 ) *i = rbuf->m - 1;
128
+ return 1;
129
+ }
130
+ /**
131
+ * rbuf_prepend() - register new element at the start of the round buffer
132
+ * @rbuf: the rbuf_t holder
133
+ *
134
+ * Returns index of the newly inserted element.
135
+ */
136
+ static inline int rbuf_prepend(rbuf_t *rbuf)
137
+ {
138
+ if ( rbuf->n < rbuf->m ) rbuf->n++;
139
+
140
+ rbuf->f = rbuf->f > 0 ? rbuf->f - 1 : rbuf->m - 1;
141
+ return rbuf->f;
142
+ }
143
+ /**
144
+ * rbuf_append() - register new element at the end of the round buffer
145
+ * @rbuf: the rbuf_t holder
146
+ *
147
+ * Returns index of the newly inserted element.
148
+ */
149
+ static inline int rbuf_append(rbuf_t *rbuf)
150
+ {
151
+ if ( rbuf->n < rbuf->m )
152
+ {
153
+ rbuf->n++;
154
+ int i = rbuf->f + rbuf->n;
155
+ return i <= rbuf->m ? i - 1 : i - rbuf->m - 1;
156
+ }
157
+
158
+ rbuf->f++;
159
+ if ( rbuf->f >= rbuf->m )
160
+ {
161
+ rbuf->f = 0;
162
+ return rbuf->m - 1;
163
+ }
164
+ return rbuf->f - 1;
165
+ }
166
+ /**
167
+ * rbuf_shift() - removes first element from the buffer
168
+ * @rbuf: the rbuf_t holder
169
+ *
170
+ * Returns index of the removed element.
171
+ */
172
+ static inline int rbuf_shift(rbuf_t *rbuf)
173
+ {
174
+ if ( !rbuf->n ) return -1;
175
+ int ret = rbuf->f;
176
+ rbuf->f++;
177
+ if ( rbuf->f >= rbuf->m ) rbuf->f = 0;
178
+ rbuf->n--;
179
+ return ret;
180
+ }
181
+ /**
182
+ * rbuf_shift_n() - removes first n elements from the buffer
183
+ * @rbuf: the rbuf_t holder
184
+ * @n: number of elements to remove
185
+ */
186
+ static inline void rbuf_shift_n(rbuf_t *rbuf, int n)
187
+ {
188
+ if ( n >= rbuf->n )
189
+ {
190
+ rbuf->n = rbuf->f = 0;
191
+ return;
192
+ }
193
+ rbuf->n -= n;
194
+ rbuf->f += n;
195
+ if ( rbuf->f >= rbuf->m ) rbuf->f -= rbuf->m;
196
+ }
197
+
198
+ /**
199
+ * rbuf_expand0() - expand round buffer and set the newly allocated elements to 0
200
+ * @rbuf: the rbuf holder
201
+ * @type_t: data type
202
+ * @n: requested number of elements
203
+ * @data: data array to be realloced
204
+ *
205
+ * Note: The new array is linearized and leaves the rbuf.f offset untouched,
206
+ * thus the size of the new buffer is determined by the current position.
207
+ */
208
+ #define rbuf_expand0(rbuf,type_t,n,data) \
209
+ { \
210
+ if ( n > (rbuf)->m ) \
211
+ { \
212
+ int m = n + (rbuf)->f; \
213
+ m--, m|=m>>1, m|=m>>2, m|=m>>4, m|=m>>8, m|=m>>16, m++; /* kroundup32 */ \
214
+ data = (type_t*) realloc(data, sizeof(type_t)*m); \
215
+ type_t *ptr = data; \
216
+ memset(ptr+(rbuf)->m,0,sizeof(type_t)*(m-(rbuf)->m)); \
217
+ if ( (rbuf)->f ) \
218
+ { \
219
+ memcpy(ptr+(rbuf)->m,ptr,sizeof(type_t)*(rbuf)->f); \
220
+ memset(ptr,0,sizeof(type_t)*(rbuf)->f); \
221
+ } \
222
+ (rbuf)->m = m; \
223
+ } \
224
+ }
225
+
226
+ /**
227
+ * rbuf_remove_kth() - remove k-th rbuf element (0-based) and memmove the data block
228
+ * @rbuf: the rbuf holder
229
+ * @type_t: data type
230
+ * @k: k-th element to remove
231
+ * @data: data array to be modified
232
+ */
233
+ #define rbuf_remove_kth(rbuf, type_t, kth, data) \
234
+ { \
235
+ int k = rbuf_kth(rbuf, kth); \
236
+ if ( k < (rbuf)->f ) /* shrink from back */ \
237
+ { \
238
+ int l = rbuf_kth(rbuf, -1); \
239
+ if ( k < l ) \
240
+ { \
241
+ type_t tmp = (data)[k]; \
242
+ memmove(data+k, data+k+1, (l - k)*sizeof(type_t)); \
243
+ (data)[l] = tmp; \
244
+ } \
245
+ (rbuf)->n--; \
246
+ } \
247
+ else /* shrink from front */ \
248
+ { \
249
+ if ( k > (rbuf)->f ) \
250
+ { \
251
+ type_t tmp = (data)[k]; \
252
+ memmove(&data[(rbuf)->f+1], &data[(rbuf)->f], (k - (rbuf)->f)*sizeof(type_t)); \
253
+ (data)[(rbuf)->f] = tmp; \
254
+ } \
255
+ (rbuf)->f++; \
256
+ (rbuf)->n--; \
257
+ if ( (rbuf)->f == (rbuf)->m ) (rbuf)->f = 0; \
258
+ } \
259
+ }
260
+
261
+ #endif
falcon/lib/python3.10/site-packages/pysam/include/bcftools/tsv2vcf.c.pysam.c ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bcftools.pysam.h"
2
+
3
+ /* tsv2vcf.c -- convert from whitespace-separated fields to VCF
4
+
5
+ Copyright (C) 2014-2021 Genome Research Ltd.
6
+
7
+ Author: Petr Danecek <pd3@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
+ THE SOFTWARE.
26
+ */
27
+
28
+ #include <ctype.h>
29
+ #include <strings.h>
30
+ #include "tsv2vcf.h"
31
+
32
+ tsv_t *tsv_init(const char *str)
33
+ {
34
+ tsv_t *tsv = (tsv_t *) calloc(1,sizeof(tsv_t));
35
+ kstring_t tmp = {0,0,0};
36
+ const char *ss = str, *se = ss;
37
+ tsv->ncols = 0;
38
+ while ( *ss )
39
+ {
40
+ if ( *se && *se!=',' ) { se++; continue; }
41
+ tsv->ncols++;
42
+ tsv->cols = (tsv_col_t*) realloc(tsv->cols,sizeof(tsv_col_t)*tsv->ncols);
43
+ tsv->cols[tsv->ncols-1].name = NULL;
44
+ tsv->cols[tsv->ncols-1].setter = NULL;
45
+ tmp.l = 0;
46
+ kputsn(ss, se-ss, &tmp);
47
+ if ( strcasecmp("-",tmp.s) )
48
+ tsv->cols[tsv->ncols-1].name = strdup(tmp.s);
49
+ if ( !*se ) break;
50
+ ss = ++se;
51
+ }
52
+ free(tmp.s);
53
+ return tsv;
54
+ }
55
+
56
+ void tsv_destroy(tsv_t *tsv)
57
+ {
58
+ int i;
59
+ for (i=0; i<tsv->ncols; i++) free(tsv->cols[i].name);
60
+ free(tsv->cols);
61
+ free(tsv);
62
+ }
63
+
64
+ int tsv_register(tsv_t *tsv, const char *id, tsv_setter_t setter, void *usr)
65
+ {
66
+ int i;
67
+ for (i=0; i<tsv->ncols; i++)
68
+ {
69
+ if ( !tsv->cols[i].name || strcasecmp(tsv->cols[i].name,id) ) continue;
70
+ tsv->cols[i].setter = setter;
71
+ tsv->cols[i].usr = usr;
72
+ return 0;
73
+ }
74
+ return -1;
75
+ }
76
+
77
+ int tsv_parse(tsv_t *tsv, bcf1_t *rec, char *str)
78
+ {
79
+ int status = 0;
80
+ tsv->icol = 0;
81
+ tsv->ss = tsv->se = str;
82
+ while ( *tsv->ss && tsv->icol < tsv->ncols )
83
+ {
84
+ while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++;
85
+ if ( tsv->cols[tsv->icol].setter )
86
+ {
87
+ int ret = tsv->cols[tsv->icol].setter(tsv,rec,tsv->cols[tsv->icol].usr);
88
+ if ( ret<0 ) return -1;
89
+ status++;
90
+ }
91
+ while ( *tsv->se && isspace(*tsv->se) ) tsv->se++;
92
+ tsv->ss = tsv->se;
93
+ tsv->icol++;
94
+ }
95
+ return status ? 0 : -1;
96
+ }
97
+
98
+ int tsv_setter_chrom(tsv_t *tsv, bcf1_t *rec, void *usr)
99
+ {
100
+ char tmp = *tsv->se;
101
+ *tsv->se = 0;
102
+ rec->rid = bcf_hdr_name2id((bcf_hdr_t*)usr, tsv->ss);
103
+ *tsv->se = tmp;
104
+ return rec->rid==-1 ? -1 : 0;
105
+ }
106
+
107
+ int tsv_setter_pos(tsv_t *tsv, bcf1_t *rec, void *usr)
108
+ {
109
+ char *endptr;
110
+ rec->pos = strtol(tsv->ss, &endptr, 10) - 1;
111
+ if ( tsv->ss==endptr ) return -1;
112
+ return 0;
113
+ }
114
+
115
+ int tsv_setter_id(tsv_t *tsv, bcf1_t *rec, void *usr)
116
+ {
117
+ char tmp = *tsv->se;
118
+ *tsv->se = 0;
119
+ bcf_update_id((bcf_hdr_t*)usr, rec, tsv->ss);
120
+ *tsv->se = tmp;
121
+ return 0;
122
+ }
123
+
124
+ int tsv_setter_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
125
+ {
126
+ bcf_hdr_t *hdr = (bcf_hdr_t*)usr;
127
+ char *sb = tsv->ss;
128
+ while ( *sb && !isspace(*sb) ) sb++;
129
+ if ( !*sb ) return -1;
130
+ char tmp = *sb;
131
+ *sb = ',';
132
+ bcf_update_alleles_str(hdr, rec, tsv->ss);
133
+ *sb = tmp;
134
+ return 0;
135
+ }
136
+
137
+
falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfconvert.c ADDED
@@ -0,0 +1,1791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* vcfconvert.c -- convert between VCF/BCF and related formats.
2
+
3
+ Copyright (C) 2013-2023 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE. */
24
+
25
+ #include <stdio.h>
26
+ #include <strings.h>
27
+ #include <unistd.h>
28
+ #include <getopt.h>
29
+ #include <ctype.h>
30
+ #include <string.h>
31
+ #include <errno.h>
32
+ #include <sys/stat.h>
33
+ #include <sys/types.h>
34
+ #include <inttypes.h>
35
+ #include <htslib/faidx.h>
36
+ #include <htslib/vcf.h>
37
+ #include <htslib/bgzf.h>
38
+ #include <htslib/synced_bcf_reader.h>
39
+ #include <htslib/vcfutils.h>
40
+ #include <htslib/kseq.h>
41
+ #include "bcftools.h"
42
+ #include "filter.h"
43
+ #include "convert.h"
44
+ #include "tsv2vcf.h"
45
+
46
+ // Logic of the filters: include or exclude sites which match the filters?
47
+ #define FLT_INCLUDE 1
48
+ #define FLT_EXCLUDE 2
49
+
50
+ typedef struct _args_t args_t;
51
+ struct _args_t
52
+ {
53
+ faidx_t *ref;
54
+ filter_t *filter;
55
+ char *filter_str;
56
+ int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
57
+ convert_t *convert;
58
+ bcf_srs_t *files;
59
+ bcf_hdr_t *header;
60
+ void (*convert_func)(struct _args_t *);
61
+ struct {
62
+ int total, skipped, hom_rr, het_ra, hom_aa, het_aa, missing, written;
63
+ } n;
64
+ kstring_t str;
65
+ int32_t *gts;
66
+ float *flt;
67
+ int rev_als, output_vcf_ids, hap2dip, gen_3N6;
68
+ int nsamples, *samples, sample_is_file, targets_is_file, regions_is_file, output_type;
69
+ int regions_overlap, targets_overlap;
70
+ char **argv, *sample_list, *targets_list, *regions_list, *tag, *columns;
71
+ char *outfname, *infname, *ref_fname, *sex_fname;
72
+ int argc, n_threads, record_cmd_line, keep_duplicates, clevel;
73
+ char *index_fn;
74
+ int write_index;
75
+ struct {
76
+ kstring_t ref,alt,refalt;
77
+ } tsv;
78
+ };
79
+
80
+ static void destroy_data(args_t *args)
81
+ {
82
+ if ( args->ref ) fai_destroy(args->ref);
83
+ if ( args->convert) convert_destroy(args->convert);
84
+ if ( args->filter ) filter_destroy(args->filter);
85
+ free(args->samples);
86
+ if ( args->files ) bcf_sr_destroy(args->files);
87
+ }
88
+
89
+ static void open_vcf(args_t *args, const char *format_str)
90
+ {
91
+ args->files = bcf_sr_init();
92
+ if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)!=0 )
93
+ error("Could not initialize --threads %d\n", args->n_threads);
94
+
95
+ if ( args->regions_list )
96
+ {
97
+ bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
98
+ if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 )
99
+ error("Failed to read the regions: %s\n", args->regions_list);
100
+ }
101
+ if ( args->targets_list )
102
+ {
103
+ bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
104
+ if ( bcf_sr_set_targets(args->files, args->targets_list, args->targets_is_file, 0)<0 )
105
+ error("Failed to read the targets: %s\n", args->targets_list);
106
+ }
107
+ if ( !bcf_sr_add_reader(args->files, args->infname) )
108
+ error("Failed to open %s: %s\n", args->infname,bcf_sr_strerror(args->files->errnum));
109
+
110
+ args->header = args->files->readers[0].header;
111
+
112
+ if ( args->filter_str )
113
+ args->filter = filter_init(args->header, args->filter_str);
114
+
115
+ int i, nsamples = 0, *samples = NULL;
116
+ if ( args->sample_list && strcmp("-",args->sample_list) )
117
+ {
118
+ for (i=0; i<args->files->nreaders; i++)
119
+ {
120
+ int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file);
121
+ if ( ret<0 ) error("Error parsing the sample list\n");
122
+ else if ( ret>0 ) error("Sample name mismatch: sample #%d not found in the header\n", ret);
123
+ }
124
+
125
+ if ( args->sample_list[0]!='^' )
126
+ {
127
+ // the sample ordering may be different if not negated
128
+ int n;
129
+ char **smpls = hts_readlist(args->sample_list, args->sample_is_file, &n);
130
+ if ( !smpls ) error("Could not parse %s\n", args->sample_list);
131
+ if ( n!=bcf_hdr_nsamples(args->files->readers[0].header) )
132
+ error("The number of samples does not match, perhaps some are present multiple times?\n");
133
+ nsamples = bcf_hdr_nsamples(args->files->readers[0].header);
134
+ samples = (int*) malloc(sizeof(int)*nsamples);
135
+ for (i=0; i<n; i++)
136
+ {
137
+ samples[i] = bcf_hdr_id2int(args->files->readers[0].header, BCF_DT_SAMPLE,smpls[i]);
138
+ free(smpls[i]);
139
+ }
140
+ free(smpls);
141
+ }
142
+ }
143
+ if ( format_str ) args->convert = convert_init(args->header, samples, nsamples, format_str);
144
+ free(samples);
145
+ }
146
+
147
+ static int _set_ref_alt(args_t *args, bcf1_t *rec)
148
+ {
149
+ args->tsv.refalt.l = 0;
150
+ kputs(args->tsv.ref.s, &args->tsv.refalt);
151
+ if ( strcmp(".",args->tsv.alt.s) && strcmp(args->tsv.ref.s,args->tsv.alt.s) )
152
+ {
153
+ kputc(',', &args->tsv.refalt);
154
+ kputs(args->tsv.alt.s, &args->tsv.refalt);
155
+ }
156
+ bcf_update_alleles_str(args->header, rec, args->tsv.refalt.s);
157
+ args->tsv.ref.l = 0;
158
+ args->tsv.alt.l = 0;
159
+ args->tsv.refalt.l = 0;
160
+ return 0;
161
+ }
162
+ static int tsv_setter_ref(tsv_t *tsv, bcf1_t *rec, void *usr)
163
+ {
164
+ args_t *args = (args_t*) usr;
165
+ kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.ref);
166
+ if ( args->tsv.alt.l ) return _set_ref_alt(args,rec);
167
+ return 0;
168
+ }
169
+ static int tsv_setter_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
170
+ {
171
+ args_t *args = (args_t*) usr;
172
+ kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.alt);
173
+ if ( args->tsv.ref.l ) return _set_ref_alt(args,rec);
174
+ return 0;
175
+ }
176
+
177
+ // Try to set CHROM:POS_REF_ALT[_END]. Return 0 on success, -1 on error
178
+ static int _set_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
179
+ {
180
+ args_t *args = (args_t*) usr;
181
+
182
+ char tmp, *se = tsv->ss, *ss = tsv->ss;
183
+ while ( se < tsv->se && *se!=':' ) se++;
184
+ if ( *se!=':' ) return -1;
185
+ tmp = *se; *se = 0;
186
+ int rid = bcf_hdr_name2id(args->header,ss);
187
+ *se = tmp;
188
+ if ( rid<0 ) return -1;
189
+
190
+ // POS
191
+ hts_pos_t pos = strtol(se+1,&ss,10);
192
+ if ( ss==se+1 ) return -1;
193
+ pos--;
194
+
195
+ // REF,ALT
196
+ args->str.l = 0;
197
+ se = ++ss;
198
+ while ( se < tsv->se && *se!='_' ) se++;
199
+ if ( *se!='_' ) return -1;
200
+ kputsn(ss,se-ss,&args->str);
201
+ ss = ++se;
202
+ while ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) se++;
203
+ if ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) return -1;
204
+ kputc(',',&args->str);
205
+ kputsn(ss,se-ss,&args->str);
206
+
207
+ // END - optional
208
+ if (*se && *se=='_')
209
+ {
210
+ long end = strtol(se+1,&ss,10);
211
+ if ( ss==se+1 ) return -1;
212
+ bcf_update_info_int32(args->header, rec, "END", &end, 1);
213
+ }
214
+
215
+ rec->rid = rid;
216
+ rec->pos = pos;
217
+ bcf_update_alleles_str(args->header, rec, args->str.s);
218
+
219
+ return 0;
220
+ }
221
+ static int tsv_setter_chrom_pos_ref_alt_or_chrom(tsv_t *tsv, bcf1_t *rec, void *usr)
222
+ {
223
+ args_t *args = (args_t*)usr;
224
+ int ret = _set_chrom_pos_ref_alt(tsv,rec,usr);
225
+ if ( !ret ) return ret;
226
+ return tsv_setter_chrom(tsv,rec,args->header);
227
+ }
228
+ static int tsv_setter_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
229
+ {
230
+ int ret = _set_chrom_pos_ref_alt(tsv,rec,usr);
231
+ if ( ret!=0 ) error("Could not parse the CHROM:POS_REF_ALT[_END] string: %s\n", tsv->ss);
232
+ return ret;
233
+ }
234
+ // This function must be called first, then tsv_setter_chrom_pos_ref_alt_id_or_die.
235
+ // One of them is expected to find the CHROM:POS_REF_ALT[_END] string, if not, die.
236
+ static int tsv_setter_chrom_pos_ref_alt_or_id(tsv_t *tsv, bcf1_t *rec, void *usr)
237
+ {
238
+ args_t *args = (args_t*)usr;
239
+ if ( _set_chrom_pos_ref_alt(tsv,rec,usr)==0 ) return 0;
240
+ rec->pos = -1; // mark the record as unset
241
+ if ( !args->output_vcf_ids) return 0;
242
+ return tsv_setter_id(tsv,rec,usr);
243
+ }
244
+ static int tsv_setter_chrom_pos_ref_alt_id_or_die(tsv_t *tsv, bcf1_t *rec, void *usr)
245
+ {
246
+ args_t *args = (args_t*)usr;
247
+ if ( rec->pos!=-1 )
248
+ {
249
+ if ( !args->output_vcf_ids ) return 0;
250
+ return tsv_setter_id(tsv,rec,usr);
251
+ }
252
+ return tsv_setter_chrom_pos_ref_alt(tsv,rec,usr);
253
+ }
254
+ static int tsv_setter_verify_pos(tsv_t *tsv, bcf1_t *rec, void *usr)
255
+ {
256
+ char *se;
257
+ int pos = strtol(tsv->ss,&se,10);
258
+ if ( tsv->ss==se ) error("Could not parse POS: %s\n", tsv->ss);
259
+ if ( rec->pos != pos-1 ) error("POS mismatch: %s\n", tsv->ss);
260
+ return 0;
261
+ }
262
+ static int tsv_setter_verify_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
263
+ {
264
+ args_t *args = (args_t*) usr;
265
+ args->rev_als = 0;
266
+ char tmp = *tsv->se; *tsv->se = 0;
267
+ if ( strcmp(tsv->ss,rec->d.allele[0]) )
268
+ {
269
+ if ( strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); }
270
+ args->rev_als = 1;
271
+ }
272
+ *tsv->se = tmp;
273
+ while ( *tsv->se && isspace(*tsv->se) ) tsv->se++;
274
+ tsv->ss = tsv->se;
275
+ while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++;
276
+ tmp = *tsv->se; *tsv->se = 0;
277
+ if ( !args->rev_als && strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); }
278
+ else if ( args->rev_als && strcmp(tsv->ss,rec->d.allele[0]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[0]); }
279
+ *tsv->se = tmp;
280
+ return 0;
281
+ }
282
+ static int tsv_setter_gt_gp(tsv_t *tsv, bcf1_t *rec, void *usr)
283
+ {
284
+ args_t *args = (args_t*) usr;
285
+ int i, nsamples = bcf_hdr_nsamples(args->header);
286
+ for (i=0; i<nsamples; i++)
287
+ {
288
+ float aa,ab,bb;
289
+ aa = strtod(tsv->ss, &tsv->se);
290
+ if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse first value of %d-th sample\n", i+1); return -1; }
291
+ tsv->ss = tsv->se+1;
292
+ ab = strtod(tsv->ss, &tsv->se);
293
+ if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse second value of %d-th sample\n", i+1); return -1; }
294
+ tsv->ss = tsv->se+1;
295
+ bb = strtod(tsv->ss, &tsv->se);
296
+ if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse third value of %d-th sample\n", i+1); return -1; }
297
+ tsv->ss = tsv->se+1;
298
+
299
+ if ( args->rev_als ) { float tmp = bb; bb = aa; aa = tmp; }
300
+ args->flt[3*i+0] = aa;
301
+ args->flt[3*i+1] = ab;
302
+ args->flt[3*i+2] = bb;
303
+
304
+ if ( aa >= ab )
305
+ {
306
+ if ( aa >= bb ) args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(0);
307
+ else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1);
308
+ }
309
+ else if ( ab >= bb )
310
+ {
311
+ args->gts[2*i+0] = bcf_gt_unphased(0);
312
+ args->gts[2*i+1] = bcf_gt_unphased(1);
313
+ }
314
+ else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1);
315
+ }
316
+ if ( *tsv->se ) error("Could not parse: %s\n", tsv->ss);
317
+ if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n");
318
+ if ( bcf_update_format_float(args->header,rec,"GP",args->flt,nsamples*3) ) error("Could not update GP field\n");
319
+ return 0;
320
+ }
321
+ static int tsv_setter_haps(tsv_t *tsv, bcf1_t *rec, void *usr)
322
+ {
323
+ args_t *args = (args_t*) usr;
324
+ int i, nsamples = bcf_hdr_nsamples(args->header);
325
+
326
+ int32_t a0, a1;
327
+ if ( args->rev_als ) { a0 = bcf_gt_phased(1); a1 = bcf_gt_phased(0); }
328
+ else { a0 = bcf_gt_phased(0); a1 = bcf_gt_phased(1); }
329
+
330
+ // up is short for "unphased"
331
+ int nup = 0;
332
+ for (i=0; i<nsamples; i++)
333
+ {
334
+ char *ss = tsv->ss + 4*i + nup;
335
+ int up = 0, all;
336
+
337
+ for (all=0; all < 2; all++){
338
+ // checking for premature ending
339
+ if ( !ss[0] || !ss[1] || !ss[2] ||
340
+ (up && (!ss[3] || !ss[4]) ) )
341
+ {
342
+ fprintf(stderr,"Wrong number of fields at %d-th sample ([%c][%c][%c]). ",i+1,ss[0],ss[1],ss[2]);
343
+ return -1;
344
+ }
345
+
346
+ switch(ss[all*2+up]){
347
+ case '0':
348
+ args->gts[2*i+all] = a0;
349
+ break;
350
+ case '1' :
351
+ args->gts[2*i+all] = a1;
352
+ break;
353
+ case '?' :
354
+ // there is no macro to express phased missing allele
355
+ args->gts[2*i+all] = bcf_gt_phased(-1);
356
+ break;
357
+ case '-' :
358
+ args->gts[2*i+all] = bcf_int32_vector_end;
359
+ break;
360
+ default :
361
+ fprintf(stderr,"Could not parse: [%c][%s]\n", ss[all*2+up],tsv->ss);
362
+ return -1;
363
+ }
364
+ if( ss[all*2+up+1]=='*' ) up = up + 1;
365
+ }
366
+
367
+ if(up && up != 2)
368
+ {
369
+ fprintf(stderr,"Missing unphased marker '*': [%c][%s]", ss[2+up], tsv->ss);
370
+ return -1;
371
+ }
372
+
373
+ // change alleles to unphased if the alleles are unphased
374
+ if ( up )
375
+ {
376
+ args->gts[2*i] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i]));
377
+ args->gts[2*i+1] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i+1]));
378
+ }
379
+ nup = nup + up;
380
+ }
381
+ if ( tsv->ss[(nsamples-1)*4+3+nup] )
382
+ {
383
+ fprintf(stderr,"nup: %d", nup);
384
+ fprintf(stderr,"Wrong number of fields (%d-th column = [%c]). ", nsamples*2,tsv->ss[(nsamples-1)*4+nup]);
385
+ return -1;
386
+ }
387
+
388
+ if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n");
389
+ return 0;
390
+ }
391
+ static void gensample_to_vcf(args_t *args)
392
+ {
393
+ /*
394
+ * Inpute: IMPUTE2 output (indentation changed here for clarity):
395
+ *
396
+ * 20:62116619_C_T 20:62116619 62116619 C T 0.969 0.031 0 ...
397
+ * --- 20:62116698_C_A 62116698 C A 1 0 0 ...
398
+ *
399
+ * Second column is expected in the form of CHROM:POS_REF_ALT. We use second
400
+ * column because the first can be empty ("--") when filling sites from reference
401
+ * panel. When the option --vcf-ids is given, the first column is used to set the
402
+ * VCF ID.
403
+ *
404
+ * Output: VCF with filled GT,GP
405
+ *
406
+ */
407
+ kstring_t line = {0,0,0};
408
+
409
+ char *gen_fname = NULL, *sample_fname = NULL;
410
+ sample_fname = strchr(args->infname,',');
411
+ if ( !sample_fname )
412
+ {
413
+ args->str.l = 0;
414
+ ksprintf(&args->str,"%s.gen.gz", args->infname);
415
+ gen_fname = strdup(args->str.s);
416
+ args->str.l = 0;
417
+ ksprintf(&args->str,"%s.samples", args->infname);
418
+ sample_fname = strdup(args->str.s);
419
+ }
420
+ else
421
+ {
422
+ *sample_fname = 0;
423
+ gen_fname = strdup(args->infname);
424
+ sample_fname = strdup(sample_fname+1);
425
+ }
426
+ htsFile *gen_fh = hts_open(gen_fname, "r");
427
+ if ( !gen_fh ) error("Could not read: %s\n", gen_fname);
428
+ if ( hts_getline(gen_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", gen_fname);
429
+
430
+ // Find out the chromosome name, depending on the format variant (--3N6 or plain) and the ordering
431
+ // of the columns (CHROM:POS_REF_ALT comes first or second)
432
+ args->str.l = 0;
433
+ char *sb = line.s, *se = line.s;
434
+ while ( *se && !isspace(*se) ) se++;
435
+ if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
436
+ if ( args->gen_3N6 ) // first column, just CHROM
437
+ kputsn(sb, se-sb, &args->str);
438
+ else // first or second column, part of CHROM:POS_REF_ALT
439
+ {
440
+ char *sc = strchr(sb,':');
441
+ if ( !sc || sc > se )
442
+ {
443
+ while ( *se && !isspace(*se) ) se++;
444
+ if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
445
+ sb = ++se;
446
+ sc = strchr(sb,':');
447
+ if ( !sc ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
448
+ }
449
+ kputsn(sb, sc-sb, &args->str);
450
+ }
451
+
452
+ // Initialize and print the VCF header, args->str.s contains the chr name
453
+ args->header = bcf_hdr_init("w");
454
+ bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
455
+ bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
456
+ bcf_hdr_append(args->header, "##FORMAT=<ID=GP,Number=G,Type=Float,Description=\"Genotype Probabilities\">");
457
+ bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
458
+ if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
459
+
460
+ tsv_t *tsv;
461
+ if ( args->gen_3N6 )
462
+ {
463
+ tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP");
464
+ tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header);
465
+ }
466
+ else
467
+ tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP");
468
+ tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt_or_id, args);
469
+ tsv_register(tsv, "ID", tsv_setter_chrom_pos_ref_alt_id_or_die, args);
470
+ tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL);
471
+ tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
472
+ tsv_register(tsv, "GT_GP", tsv_setter_gt_gp, args);
473
+
474
+ // Find out sample names
475
+ int i, nsamples;
476
+ char **samples = hts_readlist(sample_fname, 1, &nsamples);
477
+ if ( !samples ) error("Could not read %s\n", sample_fname);
478
+ for (i=2; i<nsamples; i++)
479
+ {
480
+ se = samples[i]; while ( *se && !isspace(*se) ) se++;
481
+ *se = 0;
482
+ bcf_hdr_add_sample(args->header,samples[i]);
483
+ }
484
+ for (i=0; i<nsamples; i++) free(samples[i]);
485
+ free(samples);
486
+
487
+ char wmode[8];
488
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
489
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
490
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
491
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
492
+ if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname);
493
+ if ( args->write_index && init_index(out_fh,args->header,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
494
+ bcf1_t *rec = bcf_init();
495
+
496
+ nsamples -= 2;
497
+ args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
498
+ args->flt = (float *) malloc(sizeof(float)*nsamples*3);
499
+
500
+ do
501
+ {
502
+ bcf_clear(rec);
503
+ args->n.total++;
504
+ if ( !tsv_parse(tsv, rec, line.s) )
505
+ {
506
+ if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
507
+ }
508
+ else
509
+ error("Error occurred while parsing: %s\n", line.s);
510
+ }
511
+ while ( hts_getline(gen_fh, KS_SEP_LINE, &line)>0 );
512
+
513
+ if ( args->write_index )
514
+ {
515
+ if ( bcf_idx_save(out_fh)<0 )
516
+ {
517
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
518
+ error("Error: cannot write to index %s\n", args->index_fn);
519
+ }
520
+ free(args->index_fn);
521
+ }
522
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
523
+ if ( hts_close(gen_fh) ) error("Close failed: %s\n", gen_fname);
524
+ bcf_hdr_destroy(args->header);
525
+ bcf_destroy(rec);
526
+ free(sample_fname);
527
+ free(gen_fname);
528
+ free(args->str.s);
529
+ free(line.s);
530
+ free(args->gts);
531
+ free(args->flt);
532
+ tsv_destroy(tsv);
533
+
534
+ fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
535
+ }
536
+
537
+ static void haplegendsample_to_vcf(args_t *args)
538
+ {
539
+ /*
540
+ * Convert from IMPUTE2 hap/legend/sample output files to VCF
541
+ *
542
+ * hap:
543
+ * 0 1 0 1
544
+ * legend:
545
+ * id position a0 a1
546
+ * 1:186946386_G_T 186946386 G T
547
+ * sample:
548
+ * sample population group sex
549
+ * sample1 sample1 sample1 2
550
+ * sample2 sample2 sample2 2
551
+ *
552
+ * Output: VCF with filled GT
553
+ */
554
+ kstring_t line = {0,0,0};
555
+
556
+ if ( args->output_vcf_ids )
557
+ error(
558
+ "The option --haplegendsample2vcf cannot be combined with --vcf-ids. This is because the\n"
559
+ "ID column must be formatted as \"CHROM:POS_REF_ALT\" to check sanity of the operation\n");
560
+
561
+ char *hap_fname = NULL, *leg_fname = NULL, *sample_fname = NULL;
562
+ sample_fname = strchr(args->infname,',');
563
+ if ( !sample_fname )
564
+ {
565
+ args->str.l = 0;
566
+ ksprintf(&args->str,"%s.hap.gz", args->infname);
567
+ hap_fname = strdup(args->str.s);
568
+ args->str.l = 0;
569
+ ksprintf(&args->str,"%s.samples", args->infname);
570
+ sample_fname = strdup(args->str.s);
571
+ args->str.l = 0;
572
+ ksprintf(&args->str,"%s.legend.gz", args->infname);
573
+ leg_fname = strdup(args->str.s);
574
+ }
575
+ else
576
+ {
577
+ char *ss = sample_fname, *se = strchr(ss+1,',');
578
+ if ( !se ) error("Could not parse hap/legend/sample file names: %s\n", args->infname);
579
+ *ss = 0;
580
+ *se = 0;
581
+ hap_fname = strdup(args->infname);
582
+ leg_fname = strdup(ss+1);
583
+ sample_fname = strdup(se+1);
584
+ }
585
+ htsFile *hap_fh = hts_open(hap_fname, "r");
586
+ if ( !hap_fh ) error("Could not read: %s\n", hap_fname);
587
+
588
+ htsFile *leg_fh = hts_open(leg_fname,"r");
589
+ if ( !leg_fh ) error("Could not read: %s\n", leg_fname);
590
+
591
+ // Eat up first legend line, then determine chromosome name
592
+ if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname);
593
+ if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname);
594
+
595
+ // Find out the chromosome name, sample names, init and print the VCF header
596
+ args->str.l = 0;
597
+ char *se = strchr(line.s,':');
598
+ if ( !se ) error("Expected CHROM:POS_REF_ALT in first column of %s\n", leg_fname);
599
+ kputsn(line.s, se-line.s, &args->str);
600
+
601
+ tsv_t *leg_tsv = tsv_init("CHROM_POS_REF_ALT,POS,REF_ALT");
602
+ tsv_register(leg_tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args);
603
+ tsv_register(leg_tsv, "POS", tsv_setter_verify_pos, NULL);
604
+ tsv_register(leg_tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
605
+ tsv_t *hap_tsv = tsv_init("HAPS");
606
+ tsv_register(hap_tsv, "HAPS", tsv_setter_haps, args);
607
+
608
+ args->header = bcf_hdr_init("w");
609
+ bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
610
+ bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
611
+ bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
612
+ if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
613
+
614
+ int i, nrows, nsamples;
615
+ char **samples = hts_readlist(sample_fname, 1, &nrows);
616
+ if ( !samples ) error("Could not read %s\n", sample_fname);
617
+ nsamples = nrows - 1;
618
+
619
+ // sample_fname should contain a header line, so need to ignore first row
620
+ // returned from hts_readlist (i=1, and not i=0)
621
+ for (i=1; i<nrows; i++)
622
+ {
623
+ se = samples[i]; while ( *se && !isspace(*se) ) se++;
624
+ *se = 0;
625
+ bcf_hdr_add_sample(args->header,samples[i]);
626
+ }
627
+ bcf_hdr_add_sample(args->header,NULL);
628
+ for (i=0; i<nrows; i++) free(samples[i]);
629
+ free(samples);
630
+
631
+ char wmode[8];
632
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
633
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
634
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
635
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
636
+ if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname);
637
+ if ( args->write_index && init_index(out_fh,args->header,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
638
+ bcf1_t *rec = bcf_init();
639
+
640
+ args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
641
+
642
+ while (1)
643
+ {
644
+ bcf_clear(rec);
645
+ args->n.total++;
646
+ if ( tsv_parse(leg_tsv, rec, line.s) )
647
+ error("Error occurred while parsing %s: %s\n", leg_fname,line.s);
648
+
649
+ if ( hts_getline(hap_fh, KS_SEP_LINE, &line)<=0 )
650
+ error("Different number of records in %s and %s?\n", leg_fname,hap_fname);
651
+
652
+ if ( tsv_parse(hap_tsv, rec, line.s) )
653
+ error("Error occurred while parsing %s: %s\n", hap_fname,line.s);
654
+
655
+ if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
656
+
657
+ if ( hts_getline(leg_fh, KS_SEP_LINE, &line)<=0 )
658
+ {
659
+ if ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 )
660
+ error("Different number of records in %s and %s?\n", leg_fname,hap_fname);
661
+ break;
662
+ }
663
+ }
664
+
665
+ if ( args->write_index )
666
+ {
667
+ if ( bcf_idx_save(out_fh)<0 )
668
+ {
669
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
670
+ error("Error: cannot write to index %s\n", args->index_fn);
671
+ }
672
+ free(args->index_fn);
673
+ }
674
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
675
+ if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname);
676
+ if ( hts_close(leg_fh) ) error("Close failed: %s\n", leg_fname);
677
+ bcf_hdr_destroy(args->header);
678
+ bcf_destroy(rec);
679
+ free(sample_fname);
680
+ free(hap_fname);
681
+ free(leg_fname);
682
+ free(args->str.s);
683
+ free(line.s);
684
+ free(args->gts);
685
+ tsv_destroy(hap_tsv);
686
+ tsv_destroy(leg_tsv);
687
+
688
+ fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
689
+ }
690
+
691
+ static void hapsample_to_vcf(args_t *args)
692
+ {
693
+ /*
694
+ * Input: SHAPEIT output
695
+ *
696
+ * 20:19995888_A_G rsid1 19995888 A G 0 0 0 0 ...
697
+ * 20 20:19995888_A_G 19995888 A G 0 0 0 0 ...
698
+ *
699
+ * First column is expected in the form of CHROM:POS_REF_ALT
700
+ *
701
+ * Output: VCF with filled GT
702
+ *
703
+ */
704
+ kstring_t line = {0,0,0};
705
+
706
+ char *hap_fname = NULL, *sample_fname = NULL;
707
+ sample_fname = strchr(args->infname,',');
708
+ if ( !sample_fname )
709
+ {
710
+ args->str.l = 0;
711
+ ksprintf(&args->str,"%s.hap.gz", args->infname);
712
+ hap_fname = strdup(args->str.s);
713
+ args->str.l = 0;
714
+ ksprintf(&args->str,"%s.samples", args->infname);
715
+ sample_fname = strdup(args->str.s);
716
+ }
717
+ else
718
+ {
719
+ *sample_fname = 0;
720
+ hap_fname = strdup(args->infname);
721
+ sample_fname = strdup(sample_fname+1);
722
+ }
723
+ htsFile *hap_fh = hts_open(hap_fname, "r");
724
+ if ( !hap_fh ) error("Could not read: %s\n", hap_fname);
725
+ if ( hts_getline(hap_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", hap_fname);
726
+
727
+ // Find out the chromosome name, it can be either in the first or second column
728
+ args->str.l = 0;
729
+ char *sb = line.s, *se = line.s;
730
+ while ( *se && !isspace(*se) ) se++;
731
+ if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
732
+ if ( !args->output_vcf_ids )
733
+ {
734
+ // first column should be just CHROM, but the second must be CHROM:POS_REF_ALT, use that
735
+ sb = ++se;
736
+ while ( *se && !isspace(*se) ) se++;
737
+ if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
738
+ if ( !strchr(sb,':') )
739
+ error("Could not determine CHROM in the second column of %s: %s\n", hap_fname,line.s);
740
+ }
741
+ // Parse CHROM:POS_REF_ALT
742
+ char *sc = strchr(sb,':');
743
+ if ( !sc || sc > se )
744
+ error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
745
+ kputsn(sb, sc-sb, &args->str);
746
+
747
+ // Initialize and print the VCF header, args->str.s contains the chr name
748
+ args->header = bcf_hdr_init("w");
749
+ bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
750
+ bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
751
+ bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
752
+ if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
753
+
754
+ tsv_t *tsv;
755
+ if ( args->output_vcf_ids )
756
+ {
757
+ tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,HAPS");
758
+ tsv_register(tsv, "ID", tsv_setter_id, args);
759
+ }
760
+ else
761
+ {
762
+ tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,POS,REF_ALT,HAPS");
763
+ tsv_register(tsv, "CHROM", tsv_setter_chrom_pos_ref_alt_or_chrom, args);
764
+ }
765
+ tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args);
766
+ tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL);
767
+ tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
768
+ tsv_register(tsv, "HAPS", tsv_setter_haps, args);
769
+
770
+ int i, nsamples;
771
+ char **samples = hts_readlist(sample_fname, 1, &nsamples);
772
+ if ( !samples ) error("Could not read %s\n", sample_fname);
773
+ for (i=2; i<nsamples; i++)
774
+ {
775
+ se = samples[i]; while ( *se && !isspace(*se) ) se++;
776
+ *se = 0;
777
+ bcf_hdr_add_sample(args->header,samples[i]);
778
+ }
779
+ bcf_hdr_add_sample(args->header,NULL);
780
+ for (i=0; i<nsamples; i++) free(samples[i]);
781
+ free(samples);
782
+
783
+ char wmode[8];
784
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
785
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
786
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
787
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
788
+ if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
789
+ if ( args->write_index && init_index(out_fh,args->header,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
790
+ bcf1_t *rec = bcf_init();
791
+
792
+ nsamples -= 2;
793
+ args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
794
+
795
+ do
796
+ {
797
+ bcf_clear(rec);
798
+ args->n.total++;
799
+ if ( !tsv_parse(tsv, rec, line.s) )
800
+ {
801
+ if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
802
+ }
803
+ else
804
+ error("Error occurred while parsing: %s\n", line.s);
805
+ }
806
+ while ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 );
807
+
808
+ if ( args->write_index )
809
+ {
810
+ if ( bcf_idx_save(out_fh)<0 )
811
+ {
812
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
813
+ error("Error: cannot write to index %s\n", args->index_fn);
814
+ }
815
+ free(args->index_fn);
816
+ }
817
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
818
+ if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname);
819
+ bcf_hdr_destroy(args->header);
820
+ bcf_destroy(rec);
821
+ free(sample_fname);
822
+ free(hap_fname);
823
+ free(args->str.s);
824
+ free(line.s);
825
+ free(args->gts);
826
+ tsv_destroy(tsv);
827
+
828
+ fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
829
+ }
830
+
831
+ char *init_sample2sex(bcf_hdr_t *hdr, char *sex_fname)
832
+ {
833
+ int i, nlines;
834
+ char *sample2sex = (char*) calloc(bcf_hdr_nsamples(hdr),1);
835
+ char **lines = hts_readlist(sex_fname, 1, &nlines);
836
+ if ( !lines ) error("Could not read %s\n", sex_fname);
837
+ for (i=0; i<nlines; i++)
838
+ {
839
+ char *se = lines[i]; while ( *se && !isspace(*se) ) se++;
840
+ char tmp = *se;
841
+ *se = 0;
842
+ int id = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, lines[i]);
843
+ *se = tmp;
844
+ if ( id<0 ) continue;
845
+ while ( *se && isspace(*se) ) se++;
846
+ if ( *se=='M' ) sample2sex[id] = '1';
847
+ else if ( *se=='F' ) sample2sex[id] = '2';
848
+ else error("Could not parse %s: %s\n", sex_fname,lines[i]);
849
+ }
850
+ for (i=0; i<nlines; i++) free(lines[i]);
851
+ free(lines);
852
+ for (i=0; i<bcf_hdr_nsamples(hdr); i++)
853
+ if ( !sample2sex[i] ) error("Missing sex for sample %s in %s\n", bcf_hdr_int2id(hdr, BCF_DT_SAMPLE, i),sex_fname);
854
+ return sample2sex;
855
+ }
856
+
857
+ static void vcf_to_gensample(args_t *args)
858
+ {
859
+ kstring_t str = {0,0,0};
860
+
861
+ // insert chrom as first column if needed
862
+ if ( args->gen_3N6 )
863
+ kputs("%CHROM ", &str);
864
+
865
+ kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str);
866
+
867
+ // insert rsid as second column if needed
868
+ if ( args->output_vcf_ids )
869
+ kputs("%ID ", &str);
870
+ else
871
+ kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str);
872
+
873
+ kputs("%POS %REF %FIRST_ALT", &str);
874
+ if ( !args->tag || !strcmp(args->tag,"GT") ) kputs("%_GT_TO_PROB3",&str);
875
+ else if ( !strcmp(args->tag,"PL") ) kputs("%_PL_TO_PROB3",&str);
876
+ else if ( !strcmp(args->tag,"GP") ) kputs("%_GP_TO_PROB3",&str);
877
+ else error("todo: --tag %s\n", args->tag);
878
+ kputs("\n", &str);
879
+ open_vcf(args,str.s);
880
+
881
+ int ret, gen_compressed = 1, sample_compressed = 0;
882
+ char *gen_fname = NULL, *sample_fname = NULL;
883
+ str.l = 0;
884
+ kputs(args->outfname,&str);
885
+ int n_files = 0, i;
886
+ char **files = hts_readlist(str.s, 0, &n_files);
887
+ if ( n_files==1 )
888
+ {
889
+ int l = str.l;
890
+ kputs(".samples",&str);
891
+ sample_fname = strdup(str.s);
892
+ str.l = l;
893
+ kputs(".gen.gz",&str);
894
+ gen_fname = strdup(str.s);
895
+ }
896
+ else if ( n_files==2 )
897
+ {
898
+ if (strlen(files[0]) && strcmp(files[0],".")!=0) gen_fname = strdup(files[0]);
899
+ if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]);
900
+ }
901
+ else
902
+ {
903
+ error("Error parsing --gensample filenames: %s\n", args->outfname);
904
+ }
905
+ for (i=0; i<n_files; i++) free(files[i]);
906
+ free(files);
907
+
908
+ if ( gen_fname && (strlen(gen_fname)<3 || strcasecmp(".gz",gen_fname+strlen(gen_fname)-3)) ) gen_compressed = 0;
909
+ if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
910
+
911
+ if (gen_fname) fprintf(stderr, "Gen file: %s\n", gen_fname);
912
+ if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
913
+
914
+ // write samples file
915
+ if (sample_fname)
916
+ {
917
+ char *sample2sex = NULL;
918
+ if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
919
+
920
+ int i;
921
+ BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
922
+ str.l = 0;
923
+ kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str);
924
+ ret = bgzf_write(sout, str.s, str.l);
925
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
926
+ for (i=0; i<bcf_hdr_nsamples(args->header); i++)
927
+ {
928
+ str.l = 0;
929
+ if ( sample2sex )
930
+ ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]);
931
+ else
932
+ ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]);
933
+ ret = bgzf_write(sout, str.s, str.l);
934
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
935
+ }
936
+ if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
937
+ free(sample_fname);
938
+ free(sample2sex);
939
+ }
940
+ if (!gen_fname) {
941
+ if ( str.m ) free(str.s);
942
+ return;
943
+ }
944
+
945
+ int prev_rid = -1, prev_pos = -1;
946
+ int no_alt = 0, non_biallelic = 0, filtered = 0, ndup = 0, nok = 0;
947
+ BGZF *gout = bgzf_open(gen_fname, gen_compressed ? "wg" : "wu");
948
+ while ( bcf_sr_next_line(args->files) )
949
+ {
950
+ bcf1_t *line = bcf_sr_get_line(args->files,0);
951
+ if ( args->filter )
952
+ {
953
+ int pass = filter_test(args->filter, line, NULL);
954
+ if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
955
+ if ( !pass ) { filtered++; continue; }
956
+ }
957
+
958
+ // ALT allele is required
959
+ if ( line->n_allele<2 ) { no_alt++; continue; }
960
+
961
+ // biallelic required
962
+ if ( line->n_allele>2 ) {
963
+ if (!non_biallelic)
964
+ fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
965
+ non_biallelic++;
966
+ continue;
967
+ }
968
+
969
+ // skip duplicate lines, or otherwise shapeit complains
970
+ if ( !args->keep_duplicates && prev_rid==line->rid && prev_pos==line->pos ) { ndup++; continue; }
971
+ prev_rid = line->rid;
972
+ prev_pos = line->pos;
973
+
974
+ str.l = 0;
975
+ convert_line(args->convert, line, &str);
976
+ if ( str.l )
977
+ {
978
+ int ret = bgzf_write(gout, str.s, str.l);
979
+ if ( ret!= str.l ) error("Error writing %s: %s\n", gen_fname,strerror(errno));
980
+ nok++;
981
+ }
982
+ }
983
+ fprintf(stderr, "%d records written, %d skipped: %d/%d/%d/%d no-ALT/non-biallelic/filtered/duplicated\n",
984
+ nok, no_alt+non_biallelic+filtered+ndup, no_alt, non_biallelic, filtered, ndup);
985
+
986
+ if ( str.m ) free(str.s);
987
+ if ( bgzf_close(gout)!=0 ) error("Error closing %s: %s\n", gen_fname,strerror(errno));
988
+ free(gen_fname);
989
+ }
990
+
991
+ static void vcf_to_haplegendsample(args_t *args)
992
+ {
993
+ kstring_t str = {0,0,0};
994
+ if ( args->hap2dip )
995
+ kputs("%_GT_TO_HAP2\n", &str);
996
+ else
997
+ kputs("%_GT_TO_HAP\n", &str);
998
+ open_vcf(args,str.s);
999
+
1000
+ int ret, hap_compressed = 1, legend_compressed = 1, sample_compressed = 0;
1001
+ char *hap_fname = NULL, *legend_fname = NULL, *sample_fname = NULL;
1002
+ str.l = 0;
1003
+ kputs(args->outfname,&str);
1004
+ int n_files = 0, i;
1005
+ char **files = hts_readlist(str.s, 0, &n_files);
1006
+ if ( n_files==1 )
1007
+ {
1008
+ int l = str.l;
1009
+ kputs(".samples",&str);
1010
+ sample_fname = strdup(str.s);
1011
+ str.l = l;
1012
+ kputs(".legend.gz",&str);
1013
+ legend_fname = strdup(str.s);
1014
+ str.l = l;
1015
+ kputs(".hap.gz",&str);
1016
+ hap_fname = strdup(str.s);
1017
+ }
1018
+ else if ( n_files==3 )
1019
+ {
1020
+ if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]);
1021
+ if (strlen(files[1]) && strcmp(files[1],".")!=0) legend_fname = strdup(files[1]);
1022
+ if (strlen(files[2]) && strcmp(files[2],".")!=0) sample_fname = strdup(files[2]);
1023
+ }
1024
+ else
1025
+ {
1026
+ error("Error parsing --hapslegendsample filenames: %s\n", args->outfname);
1027
+ }
1028
+ for (i=0; i<n_files; i++) free(files[i]);
1029
+ free(files);
1030
+
1031
+ if ( hap_fname && (strlen(hap_fname)<3 || strcasecmp(".gz",hap_fname+strlen(hap_fname)-3)) ) hap_compressed = 0;
1032
+ if ( legend_fname && (strlen(legend_fname)<3 || strcasecmp(".gz",legend_fname+strlen(legend_fname)-3)) ) legend_compressed = 0;
1033
+ if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
1034
+
1035
+ if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname);
1036
+ if (legend_fname) fprintf(stderr, "Legend file: %s\n", legend_fname);
1037
+ if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
1038
+
1039
+ // write samples file
1040
+ if (sample_fname)
1041
+ {
1042
+ char *sample2sex = NULL;
1043
+ if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
1044
+
1045
+ int i;
1046
+ BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
1047
+ str.l = 0;
1048
+ kputs("sample population group sex\n", &str);
1049
+ ret = bgzf_write(sout, str.s, str.l);
1050
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1051
+ for (i=0; i<bcf_hdr_nsamples(args->header); i++)
1052
+ {
1053
+ str.l = 0;
1054
+ ksprintf(&str, "%s %s %s %c\n", args->header->samples[i], args->header->samples[i], args->header->samples[i], sample2sex ? sample2sex[i] : '2');
1055
+ ret = bgzf_write(sout, str.s, str.l);
1056
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1057
+ }
1058
+ if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
1059
+ free(sample_fname);
1060
+ free(sample2sex);
1061
+ }
1062
+ if (!hap_fname && !legend_fname) {
1063
+ if ( str.m ) free(str.s);
1064
+ return;
1065
+ }
1066
+
1067
+ // open haps and legend outputs
1068
+ BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL;
1069
+ if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize);
1070
+ BGZF *lout = legend_fname ? bgzf_open(legend_fname, legend_compressed ? "wg" : "wu") : NULL;
1071
+ if (legend_fname) {
1072
+ str.l = 0;
1073
+ kputs("id position a0 a1\n", &str);
1074
+ ret = bgzf_write(lout, str.s, str.l);
1075
+ if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno));
1076
+ }
1077
+
1078
+ int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0;
1079
+ while ( bcf_sr_next_line(args->files) )
1080
+ {
1081
+ bcf1_t *line = bcf_sr_get_line(args->files,0);
1082
+ if ( args->filter )
1083
+ {
1084
+ int pass = filter_test(args->filter, line, NULL);
1085
+ if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1086
+ if ( !pass ) { filtered++; continue; }
1087
+ }
1088
+
1089
+ // ALT allele is required
1090
+ if ( line->n_allele<2 ) { no_alt++; continue; }
1091
+ // biallelic required
1092
+ if ( line->n_allele>2 ) {
1093
+ if (!non_biallelic)
1094
+ fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
1095
+ non_biallelic++;
1096
+ continue;
1097
+ }
1098
+
1099
+ str.l = 0;
1100
+ convert_line(args->convert, line, &str);
1101
+ if ( !str.l ) continue;
1102
+
1103
+ // write haps file
1104
+ if (hap_fname) {
1105
+ ret = bgzf_write(hout, str.s, str.l); // write hap file
1106
+ if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno));
1107
+ }
1108
+ if (legend_fname) {
1109
+ str.l = 0;
1110
+ if ( args->output_vcf_ids && (line->d.id[0]!='.' || line->d.id[1]!=0) )
1111
+ ksprintf(&str, "%s %"PRId64" %s %s\n", line->d.id, (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]);
1112
+ else
1113
+ ksprintf(&str, "%s:%"PRId64"_%s_%s %"PRId64" %s %s\n", bcf_seqname(args->header, line), (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1], (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]);
1114
+
1115
+ // write legend file
1116
+ ret = bgzf_write(lout, str.s, str.l);
1117
+ if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno));
1118
+ }
1119
+ nok++;
1120
+ }
1121
+ fprintf(stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok,no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered);
1122
+ if ( str.m ) free(str.s);
1123
+ if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno));
1124
+ if ( lout && bgzf_close(lout)!=0 ) error("Error closing %s: %s\n", legend_fname, strerror(errno));
1125
+ if (hap_fname) free(hap_fname);
1126
+ if (legend_fname) free(legend_fname);
1127
+ }
1128
+
1129
+ static void vcf_to_hapsample(args_t *args)
1130
+ {
1131
+ /*
1132
+ * WTCCC style haplotypes file
1133
+ * see https://mathgen.stats.ox.ac.uk/genetics_software/shapeit/shapeit.html#hapsample
1134
+ *
1135
+ * These are essentially the haplotypes from the impute2 format with some
1136
+ * legend info tacked on to the first 5 columns
1137
+ *
1138
+ */
1139
+ kstring_t str = {0,0,0};
1140
+
1141
+ // print ID instead of CHROM:POS_REF_ALT1
1142
+ if ( args->output_vcf_ids )
1143
+ kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT %ID %POS %REF %FIRST_ALT ", &str);
1144
+ else
1145
+ kputs("%CHROM %CHROM:%POS\\_%REF\\_%FIRST_ALT %POS %REF %FIRST_ALT ", &str);
1146
+
1147
+ if ( args->hap2dip )
1148
+ kputs("%_GT_TO_HAP2\n", &str);
1149
+ else
1150
+ kputs("%_GT_TO_HAP\n", &str);
1151
+ open_vcf(args,str.s);
1152
+
1153
+ int ret, hap_compressed = 1, sample_compressed = 0;
1154
+ char *hap_fname = NULL, *sample_fname = NULL;
1155
+ str.l = 0;
1156
+ kputs(args->outfname,&str);
1157
+ int n_files = 0, i;
1158
+ char **files = hts_readlist(str.s, 0, &n_files);
1159
+ if ( n_files==1 )
1160
+ {
1161
+ int l = str.l;
1162
+ kputs(".samples",&str);
1163
+ sample_fname = strdup(str.s);
1164
+ str.l = l;
1165
+ kputs(".hap.gz",&str);
1166
+ hap_fname = strdup(str.s);
1167
+ }
1168
+ else if ( n_files==2 )
1169
+ {
1170
+ if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]);
1171
+ if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]);
1172
+ }
1173
+ else
1174
+ {
1175
+ error("Error parsing --hapsample filenames: %s\n", args->outfname);
1176
+ }
1177
+ for (i=0; i<n_files; i++) free(files[i]);
1178
+ free(files);
1179
+
1180
+ if ( hap_fname && (strlen(hap_fname)<3 || strcasecmp(".gz",hap_fname+strlen(hap_fname)-3)) ) hap_compressed = 0;
1181
+ if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
1182
+
1183
+ if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname);
1184
+ if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
1185
+
1186
+ // write samples file
1187
+ if (sample_fname)
1188
+ {
1189
+ char *sample2sex = NULL;
1190
+ if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
1191
+
1192
+ int i;
1193
+ BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
1194
+ str.l = 0;
1195
+ kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str);
1196
+ ret = bgzf_write(sout, str.s, str.l);
1197
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1198
+ for (i=0; i<bcf_hdr_nsamples(args->header); i++)
1199
+ {
1200
+ str.l = 0;
1201
+ if ( sample2sex )
1202
+ ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]);
1203
+ else
1204
+ ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]);
1205
+ ret = bgzf_write(sout, str.s, str.l);
1206
+ if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1207
+ }
1208
+ if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
1209
+ free(sample_fname);
1210
+ free(sample2sex);
1211
+ }
1212
+ if (!hap_fname) {
1213
+ if ( str.m ) free(str.s);
1214
+ return;
1215
+ }
1216
+
1217
+ // open haps output
1218
+ BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL;
1219
+ if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize);
1220
+
1221
+ int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0;
1222
+ while ( bcf_sr_next_line(args->files) )
1223
+ {
1224
+ bcf1_t *line = bcf_sr_get_line(args->files,0);
1225
+ if ( args->filter )
1226
+ {
1227
+ int pass = filter_test(args->filter, line, NULL);
1228
+ if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1229
+ if ( !pass ) { filtered++; continue; }
1230
+ }
1231
+
1232
+ // ALT allele is required
1233
+ if ( line->n_allele<2 ) { no_alt++; continue; }
1234
+ // biallelic required
1235
+ if ( line->n_allele>2 ) {
1236
+ if (!non_biallelic)
1237
+ fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
1238
+ non_biallelic++;
1239
+ continue;
1240
+ }
1241
+
1242
+ str.l = 0;
1243
+ convert_line(args->convert, line, &str);
1244
+ if ( !str.l ) continue;
1245
+
1246
+ // write haps file
1247
+ if (hap_fname) {
1248
+ ret = bgzf_write(hout, str.s, str.l); // write hap file
1249
+ if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno));
1250
+ }
1251
+ nok++;
1252
+ }
1253
+ fprintf(stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok, no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered);
1254
+ if ( str.m ) free(str.s);
1255
+ if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno));
1256
+ if (hap_fname) free(hap_fname);
1257
+ }
1258
+
1259
+ static void bcf_hdr_set_chrs(bcf_hdr_t *hdr, faidx_t *fai)
1260
+ {
1261
+ int i, n = faidx_nseq(fai);
1262
+ for (i=0; i<n; i++)
1263
+ {
1264
+ const char *seq = faidx_iseq(fai,i);
1265
+ int len = faidx_seq_len(fai, seq);
1266
+ bcf_hdr_printf(hdr, "##contig=<ID=%s,length=%d>", seq,len);
1267
+ }
1268
+ }
1269
+ static inline int acgt_to_5(char base)
1270
+ {
1271
+ if ( base=='A' ) return 0;
1272
+ if ( base=='C' ) return 1;
1273
+ if ( base=='G' ) return 2;
1274
+ if ( base=='T' ) return 3;
1275
+ return 4;
1276
+ }
1277
+ static inline int tsv_setter_aa1(args_t *args, char *ss, char *se, int alleles[], int *nals, int ref, int32_t *gts)
1278
+ {
1279
+ if ( se - ss > 2 ) return -1; // currently only SNPs
1280
+
1281
+ if ( ss[0]=='-' || ss[0]=='.' )
1282
+ {
1283
+ // missing GT
1284
+ gts[0] = bcf_gt_missing;
1285
+ gts[1] = bcf_gt_missing;
1286
+ args->n.missing++;
1287
+ return 0;
1288
+ }
1289
+ if ( ss[0]=='I' ) return -2; // skip insertions/deletions for now
1290
+ if ( ss[0]=='D' ) return -2;
1291
+
1292
+ int a0 = acgt_to_5(toupper(ss[0]));
1293
+ int a1 = ss[1] ? acgt_to_5(toupper(ss[1])) : a0;
1294
+ if ( alleles[a0]<0 ) alleles[a0] = (*nals)++;
1295
+ if ( alleles[a1]<0 ) alleles[a1] = (*nals)++;
1296
+
1297
+ gts[0] = bcf_gt_unphased(alleles[a0]);
1298
+ gts[1] = ss[1] ? bcf_gt_unphased(alleles[a1]) : bcf_int32_vector_end;
1299
+
1300
+ if ( ref==a0 && ref==a1 ) args->n.hom_rr++; // hom ref: RR
1301
+ else if ( ref==a0 ) args->n.het_ra++; // het: RA
1302
+ else if ( ref==a1 ) args->n.het_ra++; // het: AR
1303
+ else if ( a0==a1 ) args->n.hom_aa++; // hom-alt: AA
1304
+ else args->n.het_aa++; // non-ref het: AA
1305
+
1306
+ return 0;
1307
+ }
1308
+ static int tsv_setter_aa(tsv_t *tsv, bcf1_t *rec, void *usr)
1309
+ {
1310
+ args_t *args = (args_t*) usr;
1311
+
1312
+ int len;
1313
+ char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(args->header,rec->rid), rec->pos, rec->pos, &len);
1314
+ if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1315
+
1316
+ int nals = 1, alleles[5] = { -1, -1, -1, -1, -1 }; // a,c,g,t,n
1317
+ ref[0] = toupper(ref[0]);
1318
+ int iref = acgt_to_5(ref[0]);
1319
+ alleles[iref] = 0;
1320
+
1321
+ rec->n_sample = bcf_hdr_nsamples(args->header);
1322
+
1323
+ int i, ret;
1324
+ for (i=0; i<rec->n_sample; i++)
1325
+ {
1326
+ if ( i>0 )
1327
+ {
1328
+ ret = tsv_next(tsv);
1329
+ if ( ret==-1 ) error("Too few columns for %d samples at %s:%"PRId64"\n", rec->n_sample,bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1330
+ }
1331
+ ret = tsv_setter_aa1(args, tsv->ss, tsv->se, alleles, &nals, iref, args->gts+i*2);
1332
+ if ( ret==-1 ) error("Error parsing the site %s:%"PRId64", expected two characters\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1333
+ if ( ret==-2 )
1334
+ {
1335
+ // something else than a SNP
1336
+ free(ref);
1337
+ return -1;
1338
+ }
1339
+ }
1340
+
1341
+ args->str.l = 0;
1342
+ kputc(ref[0], &args->str);
1343
+ for (i=0; i<5; i++)
1344
+ {
1345
+ if ( alleles[i]>0 )
1346
+ {
1347
+ kputc(',', &args->str);
1348
+ kputc("ACGTN"[i], &args->str);
1349
+ }
1350
+ }
1351
+ bcf_update_alleles_str(args->header, rec, args->str.s);
1352
+ if ( bcf_update_genotypes(args->header,rec,args->gts,rec->n_sample*2) ) error("Could not update the GT field\n");
1353
+
1354
+ free(ref);
1355
+ return 0;
1356
+ }
1357
+
1358
+ static void tsv_to_vcf(args_t *args)
1359
+ {
1360
+ if ( !args->ref_fname ) error("--tsv2vcf requires the --fasta-ref option\n");
1361
+
1362
+ args->ref = fai_load(args->ref_fname);
1363
+ if ( !args->ref ) error("Could not load the reference %s\n", args->ref_fname);
1364
+
1365
+ args->header = bcf_hdr_init("w");
1366
+ bcf_hdr_set_chrs(args->header, args->ref);
1367
+ bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
1368
+ if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
1369
+
1370
+ int i, nsmpl;
1371
+ char **smpl;
1372
+ if ( args->sample_list )
1373
+ {
1374
+ smpl = hts_readlist(args->sample_list, args->sample_is_file, &nsmpl);
1375
+ if ( !smpl ) error("Could not parse %s\n", args->sample_list);
1376
+ for (i=0; i<nsmpl; i++)
1377
+ {
1378
+ bcf_hdr_add_sample(args->header, smpl[i]);
1379
+ free(smpl[i]);
1380
+ }
1381
+ free(smpl);
1382
+ bcf_hdr_add_sample(args->header, NULL);
1383
+ args->gts = (int32_t *) malloc(sizeof(int32_t)*nsmpl*2);
1384
+ }
1385
+
1386
+ char wmode[8];
1387
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1388
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1389
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1390
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1391
+ if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1392
+ if ( args->write_index && init_index(out_fh,args->header,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
1393
+
1394
+ tsv_t *tsv = tsv_init(args->columns ? args->columns : "ID,CHROM,POS,AA");
1395
+ if ( tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header) < 0 ) error("Expected CHROM column\n");
1396
+ if ( tsv_register(tsv, "POS", tsv_setter_pos, NULL) < 0 ) error("Expected POS column\n");
1397
+ if ( tsv_register(tsv, "ID", tsv_setter_id, args->header) < 0 && !args->columns ) error("Expected ID column\n");
1398
+ if ( tsv_register(tsv, "AA", tsv_setter_aa, args) < 0 )
1399
+ {
1400
+ if ( args->sample_list ) error("Expected AA column with -s/-S\n");
1401
+ if ( tsv_register(tsv, "REF", tsv_setter_ref, args) < 0 || tsv_register(tsv, "ALT", tsv_setter_alt, args) < 0 )
1402
+ error("Expected REF and ALT columns when AA was not given\n");
1403
+ }
1404
+
1405
+ bcf1_t *rec = bcf_init();
1406
+ bcf_float_set_missing(rec->qual);
1407
+
1408
+ kstring_t line = {0,0,0};
1409
+ htsFile *in_fh = hts_open(args->infname, "r");
1410
+ if ( !in_fh ) error("Could not read: %s\n", args->infname);
1411
+ while ( hts_getline(in_fh, KS_SEP_LINE, &line) > 0 )
1412
+ {
1413
+ if ( line.s[0]=='#' ) continue; // skip comments
1414
+ bcf_clear(rec);
1415
+
1416
+ args->n.total++;
1417
+ if ( !tsv_parse(tsv, rec, line.s) )
1418
+ {
1419
+ if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1420
+ args->n.written++;
1421
+ }
1422
+ else
1423
+ args->n.skipped++;
1424
+ }
1425
+ if ( hts_close(in_fh) ) error("Close failed: %s\n", args->infname);
1426
+ free(line.s);
1427
+
1428
+ if ( args->write_index )
1429
+ {
1430
+ if ( bcf_idx_save(out_fh)<0 )
1431
+ {
1432
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1433
+ error("Error: cannot write to index %s\n", args->index_fn);
1434
+ }
1435
+ free(args->index_fn);
1436
+ }
1437
+ bcf_hdr_destroy(args->header);
1438
+ if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1439
+ tsv_destroy(tsv);
1440
+ bcf_destroy(rec);
1441
+ free(args->str.s);
1442
+ free(args->gts);
1443
+ free(args->tsv.ref.s);
1444
+ free(args->tsv.alt.s);
1445
+ free(args->tsv.refalt.s);
1446
+
1447
+ fprintf(stderr,"Rows total: \t%d\n", args->n.total);
1448
+ fprintf(stderr,"Rows skipped: \t%d\n", args->n.skipped);
1449
+ fprintf(stderr,"Sites written: \t%d\n", args->n.written);
1450
+ if ( args->sample_list )
1451
+ {
1452
+ fprintf(stderr,"Missing GTs: \t%d\n", args->n.missing);
1453
+ fprintf(stderr,"Hom RR: \t%d\n", args->n.hom_rr);
1454
+ fprintf(stderr,"Het RA: \t%d\n", args->n.het_ra);
1455
+ fprintf(stderr,"Hom AA: \t%d\n", args->n.hom_aa);
1456
+ fprintf(stderr,"Het AA: \t%d\n", args->n.het_aa);
1457
+ }
1458
+ }
1459
+
1460
+ static void vcf_to_vcf(args_t *args)
1461
+ {
1462
+ open_vcf(args,NULL);
1463
+ char wmode[8];
1464
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1465
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1466
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1467
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1468
+
1469
+ bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
1470
+ if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1471
+ if ( args->write_index && init_index(out_fh,args->header,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
1472
+
1473
+ while ( bcf_sr_next_line(args->files) )
1474
+ {
1475
+ bcf1_t *line = bcf_sr_get_line(args->files,0);
1476
+ if ( args->filter )
1477
+ {
1478
+ int pass = filter_test(args->filter, line, NULL);
1479
+ if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1480
+ if ( !pass ) continue;
1481
+ }
1482
+ if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1483
+ }
1484
+ if ( args->write_index )
1485
+ {
1486
+ if ( bcf_idx_save(out_fh)<0 )
1487
+ {
1488
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1489
+ error("Error: cannot write to index %s\n", args->index_fn);
1490
+ }
1491
+ free(args->index_fn);
1492
+ }
1493
+ if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1494
+ }
1495
+
1496
+ static void gvcf_to_vcf(args_t *args)
1497
+ {
1498
+ if ( !args->ref_fname ) error("--gvcf2vcf requires the --fasta-ref option\n");
1499
+
1500
+ args->ref = fai_load(args->ref_fname);
1501
+ if ( !args->ref ) error("Could not load the fai index for reference %s\n", args->ref_fname);
1502
+
1503
+ open_vcf(args,NULL);
1504
+ char wmode[8];
1505
+ set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1506
+ htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1507
+ if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1508
+ if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1509
+
1510
+ bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
1511
+ if (args->record_cmd_line) bcf_hdr_append_version(hdr, args->argc, args->argv, "bcftools_convert");
1512
+ if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1513
+ if ( args->write_index && init_index(out_fh,hdr,args->outfname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->outfname);
1514
+
1515
+ int32_t *itmp = NULL, nitmp = 0;
1516
+
1517
+ while ( bcf_sr_next_line(args->files) )
1518
+ {
1519
+ bcf1_t *line = bcf_sr_get_line(args->files,0);
1520
+ if ( args->filter )
1521
+ {
1522
+ int pass = filter_test(args->filter, line, NULL);
1523
+ if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1524
+ if ( !pass )
1525
+ {
1526
+ if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1527
+ continue;
1528
+ }
1529
+ }
1530
+
1531
+ // check if alleles compatible with being a gVCF record
1532
+ // ALT must be one of ., <*>, <X>, <NON_REF>
1533
+ // check for INFO/END is below
1534
+ int i, gallele = -1;
1535
+ if (line->n_allele==1)
1536
+ gallele = 0; // illumina/bcftools-call gvcf (if INFO/END present)
1537
+ else if ( line->d.allele[1][0]=='<' )
1538
+ {
1539
+ for (i=1; i<line->n_allele; i++)
1540
+ {
1541
+ if ( line->d.allele[i][1]=='*' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // mpileup/spec compliant gVCF
1542
+ if ( line->d.allele[i][1]=='X' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // old mpileup gVCF
1543
+ if ( strcmp(line->d.allele[i],"<NON_REF>")==0 ) { gallele = i; break; } // GATK gVCF
1544
+ }
1545
+ }
1546
+
1547
+ // no gVCF compatible alleles
1548
+ if (gallele<0)
1549
+ {
1550
+ if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1551
+ continue;
1552
+ }
1553
+
1554
+ int nend = bcf_get_info_int32(hdr,line,"END",&itmp,&nitmp);
1555
+ if ( nend!=1 )
1556
+ {
1557
+ // No INFO/END => not gVCF record
1558
+ if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1559
+ continue;
1560
+ }
1561
+ bcf_update_info_int32(hdr,line,"END",NULL,0);
1562
+ int pos, len;
1563
+ for (pos=line->pos; pos<itmp[0]; pos++)
1564
+ {
1565
+ line->pos = pos;
1566
+ char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(hdr,line->rid), line->pos, line->pos, &len);
1567
+ if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(hdr,line->rid),(int64_t) line->pos+1);
1568
+ strncpy(line->d.allele[0],ref,len);
1569
+ if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1570
+ free(ref);
1571
+ }
1572
+ }
1573
+ free(itmp);
1574
+ if ( args->write_index )
1575
+ {
1576
+ if ( bcf_idx_save(out_fh)<0 )
1577
+ {
1578
+ if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1579
+ error("Error: cannot write to index %s\n", args->index_fn);
1580
+ }
1581
+ free(args->index_fn);
1582
+ }
1583
+ if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1584
+ }
1585
+
1586
+ static void usage(void)
1587
+ {
1588
+ fprintf(stderr, "\n");
1589
+ fprintf(stderr, "About: Converts VCF/BCF to other formats and back. See man page for file\n");
1590
+ fprintf(stderr, " formats details. When specifying output files explicitly instead\n");
1591
+ fprintf(stderr, " of with PREFIX, one can use '-' for stdout and '.' to suppress.\n");
1592
+ fprintf(stderr, "Usage: bcftools convert [OPTIONS] INPUT_FILE\n");
1593
+ fprintf(stderr, "\n");
1594
+ fprintf(stderr, "VCF input options:\n");
1595
+ fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n");
1596
+ fprintf(stderr, " -i, --include EXPR Select sites for which the expression is true\n");
1597
+ fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1598
+ fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1599
+ fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1600
+ fprintf(stderr, " -s, --samples LIST List of samples to include\n");
1601
+ fprintf(stderr, " -S, --samples-file FILE File of samples to include\n");
1602
+ fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1603
+ fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1604
+ fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1605
+ fprintf(stderr, "\n");
1606
+ fprintf(stderr, "VCF output options:\n");
1607
+ fprintf(stderr, " --no-version Do not append version and command line to the header\n");
1608
+ fprintf(stderr, " -o, --output FILE Output file name [stdout]\n");
1609
+ fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
1610
+ fprintf(stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
1611
+ fprintf(stderr, " --write-index Automatically index the output files [off]\n");
1612
+ fprintf(stderr, "\n");
1613
+ fprintf(stderr, "GEN/SAMPLE conversion (input/output from IMPUTE2):\n");
1614
+ fprintf(stderr, " -G, --gensample2vcf ... <PREFIX>|<GEN-FILE>,<SAMPLE-FILE>\n");
1615
+ fprintf(stderr, " -g, --gensample ... <PREFIX>|<GEN-FILE>,<SAMPLE-FILE>\n");
1616
+ fprintf(stderr, " --3N6 Use 3*N+6 column format instead of the old 3*N+5 column format\n");
1617
+ fprintf(stderr, " --tag STRING Tag to take values for .gen file: GT,PL,GL,GP [GT]\n");
1618
+ fprintf(stderr, " --chrom Output chromosome in first column instead of CHROM:POS_REF_ALT\n");
1619
+ fprintf(stderr, " --keep-duplicates Keep duplicate positions\n");
1620
+ fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1621
+ fprintf(stderr, " --vcf-ids Output VCF IDs in second column instead of CHROM:POS_REF_ALT\n");
1622
+ fprintf(stderr, "\n");
1623
+ fprintf(stderr, "gVCF conversion:\n");
1624
+ fprintf(stderr, " --gvcf2vcf Expand gVCF reference blocks\n");
1625
+ fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n");
1626
+ fprintf(stderr, "\n");
1627
+ fprintf(stderr, "HAP/SAMPLE conversion (output from SHAPEIT):\n");
1628
+ fprintf(stderr, " --hapsample2vcf ... <PREFIX>|<HAP-FILE>,<SAMPLE-FILE>\n");
1629
+ fprintf(stderr, " --hapsample ... <PREFIX>|<HAP-FILE>,<SAMPLE-FILE>\n");
1630
+ fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n");
1631
+ fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1632
+ fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n");
1633
+ fprintf(stderr, "\n");
1634
+ fprintf(stderr, "HAP/LEGEND/SAMPLE conversion:\n");
1635
+ fprintf(stderr, " -H, --haplegendsample2vcf ... <PREFIX>|<HAP-FILE>,<LEGEND-FILE>,<SAMPLE-FILE>\n");
1636
+ fprintf(stderr, " -h, --haplegendsample ... <PREFIX>|<HAP-FILE>,<LEGEND-FILE>,<SAMPLE-FILE>\n");
1637
+ fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n");
1638
+ fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1639
+ fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n");
1640
+ fprintf(stderr, "\n");
1641
+ fprintf(stderr, "TSV conversion:\n");
1642
+ fprintf(stderr, " --tsv2vcf FILE\n");
1643
+ fprintf(stderr, " -c, --columns STRING Columns of the input tsv file, see man page for details [ID,CHROM,POS,AA]\n");
1644
+ fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n");
1645
+ fprintf(stderr, " -s, --samples LIST List of sample names\n");
1646
+ fprintf(stderr, " -S, --samples-file FILE File of sample names\n");
1647
+ fprintf(stderr, "\n");
1648
+ // fprintf(stderr, "PLINK options:\n");
1649
+ // fprintf(stderr, " -p, --plink <prefix>|<ped>,<map>,<fam>|<bed>,<bim>,<fam>|<tped>,<tfam>\n");
1650
+ // fprintf(stderr, " --tped make tped file instead\n");
1651
+ // fprintf(stderr, " --bin make binary bed/fam/bim files\n");
1652
+ // fprintf(stderr, "\n");
1653
+ // fprintf(stderr, "PBWT options:\n");
1654
+ // fprintf(stderr, " -b, --pbwt <prefix> or <pbwt>,<sites>,<sample>,<missing>\n");
1655
+ // fprintf(stderr, "\n");
1656
+ exit(1);
1657
+ }
1658
+
1659
+ int main_vcfconvert(int argc, char *argv[])
1660
+ {
1661
+ int c;
1662
+ args_t *args = (args_t*) calloc(1,sizeof(args_t));
1663
+ args->argc = argc; args->argv = argv;
1664
+ args->outfname = "-";
1665
+ args->output_type = FT_VCF;
1666
+ args->n_threads = 0;
1667
+ args->record_cmd_line = 1;
1668
+ args->regions_overlap = 1;
1669
+ args->targets_overlap = 0;
1670
+ args->clevel = -1;
1671
+
1672
+ static struct option loptions[] =
1673
+ {
1674
+ {"include",required_argument,NULL,'i'},
1675
+ {"exclude",required_argument,NULL,'e'},
1676
+ {"output",required_argument,NULL,'o'},
1677
+ {"output-type",required_argument,NULL,'O'},
1678
+ {"threads",required_argument,NULL,9},
1679
+ {"regions",required_argument,NULL,'r'},
1680
+ {"regions-file",required_argument,NULL,'R'},
1681
+ {"regions-overlap",required_argument,NULL,13},
1682
+ {"targets",required_argument,NULL,'t'},
1683
+ {"targets-file",required_argument,NULL,'T'},
1684
+ {"targets-overlap",required_argument,NULL,14},
1685
+ {"samples",required_argument,NULL,'s'},
1686
+ {"samples-file",required_argument,NULL,'S'},
1687
+ {"sex",required_argument,NULL,11},
1688
+ {"gensample",required_argument,NULL,'g'},
1689
+ {"gensample2vcf",required_argument,NULL,'G'},
1690
+ {"tag",required_argument,NULL,1},
1691
+ {"chrom",no_argument,NULL,8},
1692
+ {"3N6",no_argument,NULL,15},
1693
+ {"tsv2vcf",required_argument,NULL,2},
1694
+ {"hapsample",required_argument,NULL,7},
1695
+ {"hapsample2vcf",required_argument,NULL,3},
1696
+ {"vcf-ids",no_argument,NULL,4},
1697
+ {"haploid2diploid",no_argument,NULL,5},
1698
+ {"gvcf2vcf",no_argument,NULL,6},
1699
+ {"haplegendsample",required_argument,NULL,'h'},
1700
+ {"haplegendsample2vcf",required_argument,NULL,'H'},
1701
+ {"columns",required_argument,NULL,'c'},
1702
+ {"fasta-ref",required_argument,NULL,'f'},
1703
+ {"no-version",no_argument,NULL,10},
1704
+ {"keep-duplicates",no_argument,NULL,12},
1705
+ {"write-index",no_argument,NULL,16},
1706
+ {NULL,0,NULL,0}
1707
+ };
1708
+ char *tmp;
1709
+ while ((c = getopt_long(argc, argv, "?h:r:R:s:S:t:T:i:e:g:G:o:O:c:f:H:",loptions,NULL)) >= 0) {
1710
+ switch (c) {
1711
+ case 'e':
1712
+ if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1713
+ args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
1714
+ case 'i':
1715
+ if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1716
+ args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
1717
+ case 'r': args->regions_list = optarg; break;
1718
+ case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;
1719
+ case 't': args->targets_list = optarg; break;
1720
+ case 'T': args->targets_list = optarg; args->targets_is_file = 1; break;
1721
+ case 's': args->sample_list = optarg; break;
1722
+ case 'S': args->sample_list = optarg; args->sample_is_file = 1; break;
1723
+ case 'g': args->convert_func = vcf_to_gensample; args->outfname = optarg; break;
1724
+ case 'G': args->convert_func = gensample_to_vcf; args->infname = optarg; break;
1725
+ case 1 : args->tag = optarg; break;
1726
+ case 2 : args->convert_func = tsv_to_vcf; args->infname = optarg; break;
1727
+ case 3 : args->convert_func = hapsample_to_vcf; args->infname = optarg; break;
1728
+ case 4 : args->output_vcf_ids = 1; break;
1729
+ case 5 : args->hap2dip = 1; break;
1730
+ case 6 : args->convert_func = gvcf_to_vcf; break;
1731
+ case 7 : args->convert_func = vcf_to_hapsample; args->outfname = optarg; break;
1732
+ case 8 : error("The --chrom option has been deprecated, please use --3N6 instead\n"); break;
1733
+ case 15 : args->gen_3N6 = 1; break;
1734
+ case 16 : args->write_index = 1; break;
1735
+ case 'H': args->convert_func = haplegendsample_to_vcf; args->infname = optarg; break;
1736
+ case 'f': args->ref_fname = optarg; break;
1737
+ case 'c': args->columns = optarg; break;
1738
+ case 'o': args->outfname = optarg; break;
1739
+ case 'O':
1740
+ switch (optarg[0]) {
1741
+ case 'b': args->output_type = FT_BCF_GZ; break;
1742
+ case 'u': args->output_type = FT_BCF; break;
1743
+ case 'z': args->output_type = FT_VCF_GZ; break;
1744
+ case 'v': args->output_type = FT_VCF; break;
1745
+ default:
1746
+ {
1747
+ args->clevel = strtol(optarg,&tmp,10);
1748
+ if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1749
+ }
1750
+ }
1751
+ if ( optarg[1] )
1752
+ {
1753
+ args->clevel = strtol(optarg+1,&tmp,10);
1754
+ if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
1755
+ }
1756
+ break;
1757
+ case 'h': args->convert_func = vcf_to_haplegendsample; args->outfname = optarg; break;
1758
+ case 9 : args->n_threads = strtol(optarg, 0, 0); break;
1759
+ case 10 : args->record_cmd_line = 0; break;
1760
+ case 11 : args->sex_fname = optarg; break;
1761
+ case 12 : args->keep_duplicates = 1; break;
1762
+ case 13 :
1763
+ args->regions_overlap = parse_overlap_option(optarg);
1764
+ if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1765
+ break;
1766
+ case 14 :
1767
+ args->targets_overlap = parse_overlap_option(optarg);
1768
+ if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1769
+ break;
1770
+ case '?': usage(); break;
1771
+ default: error("Unknown argument: %s\n", optarg);
1772
+ }
1773
+ }
1774
+
1775
+ if ( !args->infname )
1776
+ {
1777
+ if ( optind>=argc )
1778
+ {
1779
+ if ( !isatty(fileno((FILE *)stdin)) ) args->infname = "-";
1780
+ }
1781
+ else args->infname = argv[optind];
1782
+ }
1783
+ if ( !args->infname ) usage();
1784
+
1785
+ if ( args->convert_func ) args->convert_func(args);
1786
+ else vcf_to_vcf(args);
1787
+
1788
+ destroy_data(args);
1789
+ free(args);
1790
+ return 0;
1791
+ }
falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfgtcheck.c.pysam.c ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bcftools.pysam.h"
2
+
3
+ /* vcfgtcheck.c -- Check sample identity.
4
+
5
+ Copyright (C) 2013-2023 Genome Research Ltd.
6
+
7
+ Author: Petr Danecek <pd3@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
+ THE SOFTWARE. */
26
+
27
+ #include <stdio.h>
28
+ #include <stdarg.h>
29
+ #include <unistd.h>
30
+ #include <getopt.h>
31
+ #include <assert.h>
32
+ #include <ctype.h>
33
+ #include <string.h>
34
+ #include <strings.h>
35
+ #include <errno.h>
36
+ #include <sys/stat.h>
37
+ #include <sys/types.h>
38
+ #include <math.h>
39
+ #include <htslib/vcf.h>
40
+ #include <htslib/synced_bcf_reader.h>
41
+ #include <htslib/vcfutils.h>
42
+ #include <htslib/kbitset.h>
43
+ #include <htslib/hts_os.h>
44
+ #include <inttypes.h>
45
+ #include <sys/time.h>
46
+ #include "bcftools.h"
47
+ #include "extsort.h"
48
+ //#include "hclust.h"
49
+
50
+ typedef struct
51
+ {
52
+ int iqry, igt;
53
+ }
54
+ pair_t;
55
+
56
+ typedef struct
57
+ {
58
+ bcf_srs_t *files; // first reader is the query VCF - single sample normally or multi-sample for cross-check
59
+ bcf_hdr_t *gt_hdr, *qry_hdr; // VCF with genotypes to compare against and the query VCF
60
+ char *cwd, **argv, *gt_samples, *qry_samples, *regions, *targets, *qry_fname, *gt_fname, *pair_samples;
61
+ int argc, gt_samples_is_file, qry_samples_is_file, regions_is_file, targets_is_file, pair_samples_is_file;
62
+ int regions_overlap, targets_overlap;
63
+ int qry_use_GT,gt_use_GT, nqry_smpl,ngt_smpl, *qry_smpl,*gt_smpl;
64
+ int nused[2][2];
65
+ double *pdiff, *qry_prob, *gt_prob;
66
+ uint32_t *ndiff,*ncnt,ncmp, npairs;
67
+ int32_t *qry_arr,*gt_arr, nqry_arr,ngt_arr;
68
+ uint8_t *qry_dsg, *gt_dsg;
69
+ pair_t *pairs;
70
+ double *hwe_prob, dsg2prob[8][3], pl2prob[256];
71
+ double min_inter_err, max_intra_err;
72
+ int all_sites, hom_only, ntop, cross_check, calc_hwe_prob, sort_by_hwe, dry_run, use_PLs;
73
+ FILE *fp;
74
+ unsigned int nskip_no_match, nskip_not_ba, nskip_mono, nskip_no_data, nskip_dip_GT, nskip_dip_PL;
75
+
76
+ // for --distinctive-sites
77
+ double distinctive_sites;
78
+ kbitset_t *kbs_diff;
79
+ size_t diff_sites_size;
80
+ extsort_t *es;
81
+ char *es_tmp_prefix, *es_max_mem;
82
+ }
83
+ args_t;
84
+
85
+ static void set_cwd(args_t *args)
86
+ {
87
+ int i;
88
+ char *buf;
89
+ size_t nbuf = 500;
90
+ args->cwd = (char*) malloc(sizeof(char)*nbuf);
91
+ for (i=0; i<5; i++)
92
+ {
93
+ if ( (buf = getcwd(args->cwd, nbuf)) ) break;
94
+ nbuf *= 2;
95
+ args->cwd = (char*) realloc(args->cwd, sizeof(char)*nbuf);
96
+ }
97
+ assert(buf);
98
+ }
99
+ static void print_header(args_t *args, FILE *fp)
100
+ {
101
+ fprintf(fp, "# This file was produced by bcftools (%s+htslib-%s), the command line was:\n", bcftools_version(), hts_version());
102
+ fprintf(fp, "# \t bcftools %s ", args->argv[0]);
103
+ int i;
104
+ for (i=1; i<args->argc; i++)
105
+ fprintf(fp, " %s",args->argv[i]);
106
+ fprintf(fp, "\n# and the working directory was:\n");
107
+ fprintf(fp, "# \t %s\n#\n", args->cwd);
108
+ }
109
+
110
+ static int cmp_int(const void *_a, const void *_b)
111
+ {
112
+ int a = *((int*)_a);
113
+ int b = *((int*)_b);
114
+ if ( a < b ) return -1;
115
+ if ( a > b ) return 1;
116
+ return 0;
117
+ }
118
+ static int cmp_pair(const void *_a, const void *_b)
119
+ {
120
+ pair_t *a = (pair_t*)_a;
121
+ pair_t *b = (pair_t*)_b;
122
+ if ( a->iqry < b->iqry ) return -1;
123
+ if ( a->iqry > b->iqry ) return 1;
124
+ if ( a->igt < b->igt ) return -1;
125
+ if ( a->igt > b->igt ) return 1;
126
+ return 0;
127
+ }
128
+
129
+ typedef struct
130
+ {
131
+ uint32_t ndiff,rid,pos,rand; // rand is to shuffle sites with the same ndiff from across all chromosoms
132
+ unsigned long kbs_dat[1];
133
+ }
134
+ diff_sites_t;
135
+ #if DBG
136
+ static void diff_sites_debug_print(args_t *args, diff_sites_t *ds)
137
+ {
138
+ int i;
139
+ memcpy(args->kbs_diff->b,ds->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
140
+ fprintf(bcftools_stderr,"%s:%d\t%d\t",bcf_hdr_id2name(args->qry_hdr,ds->rid),ds->pos+1,ds->ndiff);
141
+ for (i=0; i<args->npairs; i++) fprintf(bcftools_stderr,"%d",kbs_exists(args->kbs_diff,i)?1:0);
142
+ fprintf(bcftools_stderr,"\n");
143
+ }
144
+ #endif
145
+ static int diff_sites_cmp(const void *aptr, const void *bptr)
146
+ {
147
+ diff_sites_t *a = *((diff_sites_t**)aptr);
148
+ diff_sites_t *b = *((diff_sites_t**)bptr);
149
+ if ( a->ndiff < b->ndiff ) return 1; // descending order
150
+ if ( a->ndiff > b->ndiff ) return -1;
151
+ if ( a->rand < b->rand ) return -1;
152
+ if ( a->rand > b->rand ) return 1;
153
+ return 0;
154
+ }
155
+ static void diff_sites_init(args_t *args)
156
+ {
157
+ int nsites = args->distinctive_sites<=1 ? args->npairs*args->distinctive_sites : args->distinctive_sites;
158
+ if ( nsites<=0 ) error("The value for --distinctive-sites was set too low: %d\n",nsites);
159
+ if ( nsites > args->npairs )
160
+ {
161
+ fprintf(bcftools_stderr,"Warning: The value for --distinctive-sites is bigger than is the number of pairs, all discordant sites be printed.\n");
162
+ nsites = args->npairs;
163
+ args->distinctive_sites = args->npairs + 1;
164
+ }
165
+ else
166
+ args->distinctive_sites = nsites;
167
+ args->kbs_diff = kbs_init(args->npairs);
168
+ size_t n = (args->npairs + KBS_ELTBITS-1) / KBS_ELTBITS;
169
+ assert( n==args->kbs_diff->n );
170
+ args->diff_sites_size = sizeof(diff_sites_t) + (n-1)*sizeof(unsigned long);
171
+ args->es = extsort_alloc();
172
+ extsort_set_opt(args->es,size_t,DAT_SIZE,args->diff_sites_size);
173
+ extsort_set_opt(args->es,const char*,TMP_PREFIX,args->es_tmp_prefix);
174
+ extsort_set_opt(args->es,const char*,MAX_MEM,args->es_max_mem);
175
+ extsort_set_opt(args->es,extsort_cmp_f,FUNC_CMP,diff_sites_cmp);
176
+ extsort_init(args->es);
177
+ }
178
+ static void diff_sites_destroy(args_t *args)
179
+ {
180
+ kbs_destroy(args->kbs_diff);
181
+ extsort_destroy(args->es);
182
+ }
183
+ static inline void diff_sites_reset(args_t *args)
184
+ {
185
+ kbs_clear(args->kbs_diff);
186
+ }
187
+ static inline void diff_sites_push(args_t *args, int ndiff, int rid, int pos)
188
+ {
189
+ diff_sites_t *dat = (diff_sites_t*) malloc(args->diff_sites_size);
190
+ memset(dat,0,sizeof(*dat)); // for debugging: prevent warnings about uninitialized memory coming from struct padding (not needed after rand added)
191
+ dat->ndiff = ndiff;
192
+ dat->rid = rid;
193
+ dat->pos = pos;
194
+ dat->rand = hts_lrand48();
195
+ memcpy(dat->kbs_dat,args->kbs_diff->b,args->kbs_diff->n*sizeof(unsigned long));
196
+ extsort_push(args->es,dat);
197
+ }
198
+ static inline int diff_sites_shift(args_t *args, int *ndiff, int *rid, int *pos)
199
+ {
200
+ diff_sites_t *dat = (diff_sites_t*) extsort_shift(args->es);
201
+ if ( !dat ) return 0;
202
+ *ndiff = dat->ndiff;
203
+ *rid = dat->rid;
204
+ *pos = dat->pos;
205
+ memcpy(args->kbs_diff->b,dat->kbs_dat,args->kbs_diff->n*sizeof(unsigned long));
206
+ return 1;
207
+ }
208
+
209
+ static void init_samples(char *list, int list_is_file, int **smpl, int *nsmpl, bcf_hdr_t *hdr, char *vcf_fname)
210
+ {
211
+ int i;
212
+ if ( !strcmp(list,"-") )
213
+ {
214
+ *nsmpl = bcf_hdr_nsamples(hdr);
215
+ *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
216
+ for (i=0; i<*nsmpl; i++) (*smpl)[i] = i;
217
+ return;
218
+ }
219
+
220
+ char **tmp = hts_readlist(list, list_is_file, nsmpl);
221
+ if ( !tmp || !*nsmpl ) error("Failed to parse %s\n", list);
222
+ *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl));
223
+ for (i=0; i<*nsmpl; i++)
224
+ {
225
+ int idx = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, tmp[i]);
226
+ if ( idx<0 ) error("No such sample in %s: [%s]\n",vcf_fname,tmp[i]);
227
+ (*smpl)[i] = idx;
228
+ free(tmp[i]);
229
+ }
230
+ free(tmp);
231
+ qsort(*smpl,*nsmpl,sizeof(**smpl),cmp_int);
232
+ // check for duplicates
233
+ for (i=1; i<*nsmpl; i++)
234
+ if ( (*smpl)[i-1]==(*smpl)[i] )
235
+ error("Error: the sample \"%s\" is listed twice in %s\n", hdr->samples[(*smpl)[i]],list);
236
+ }
237
+
238
+ static void init_data(args_t *args)
239
+ {
240
+ hts_srand48(0);
241
+
242
+ args->files = bcf_sr_init();
243
+ if ( args->regions )
244
+ {
245
+ bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
246
+ if ( bcf_sr_set_regions(args->files, args->regions, args->regions_is_file)<0 ) error("Failed to read the regions: %s\n", args->regions);
247
+ }
248
+ if ( args->targets )
249
+ {
250
+ bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
251
+ if ( bcf_sr_set_targets(args->files, args->targets, args->targets_is_file, 0)<0 ) error("Failed to read the targets: %s\n", args->targets);
252
+ }
253
+
254
+ if ( args->gt_fname ) bcf_sr_set_opt(args->files, BCF_SR_REQUIRE_IDX);
255
+ if ( !bcf_sr_add_reader(args->files,args->qry_fname) ) error("Failed to open %s: %s\n", args->qry_fname,bcf_sr_strerror(args->files->errnum));
256
+ if ( args->gt_fname && !bcf_sr_add_reader(args->files, args->gt_fname) )
257
+ error("Failed to read from %s: %s\n", !strcmp("-",args->gt_fname)?"standard input":args->gt_fname,bcf_sr_strerror(args->files->errnum));
258
+
259
+ args->qry_hdr = bcf_sr_get_header(args->files,0);
260
+ if ( !bcf_hdr_nsamples(args->qry_hdr) ) error("No samples in %s?\n", args->qry_fname);
261
+ if ( args->gt_fname )
262
+ {
263
+ args->gt_hdr = bcf_sr_get_header(args->files,1);
264
+ if ( !bcf_hdr_nsamples(args->gt_hdr) ) error("No samples in %s?\n", args->gt_fname);
265
+ }
266
+
267
+ // Determine whether GT or PL will be used
268
+ if ( args->qry_use_GT==-1 ) // not set by -u, qry uses PL by default
269
+ {
270
+ if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")>=0 )
271
+ args->qry_use_GT = 0;
272
+ else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")>=0 )
273
+ args->qry_use_GT = 1;
274
+ else
275
+ error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->qry_fname);
276
+ }
277
+ else if ( args->qry_use_GT==1 )
278
+ {
279
+ if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")<0 )
280
+ error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->qry_fname);
281
+ }
282
+ else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")<0 )
283
+ error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->qry_fname);
284
+
285
+ if ( args->gt_hdr )
286
+ {
287
+ if ( args->gt_use_GT==-1 ) // not set by -u, gt uses GT by default
288
+ {
289
+ if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")>=0 )
290
+ args->gt_use_GT = 1;
291
+ else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")>=0 )
292
+ args->gt_use_GT = 0;
293
+ else
294
+ error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->gt_fname);
295
+ }
296
+ else if ( args->gt_use_GT==1 )
297
+ {
298
+ if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")<0 )
299
+ error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->gt_fname);
300
+ }
301
+ else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")<0 )
302
+ error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->gt_fname);
303
+ }
304
+ else
305
+ args->gt_use_GT = args->qry_use_GT;
306
+
307
+ // Prepare samples
308
+ int i,j;
309
+ args->nqry_smpl = bcf_hdr_nsamples(args->qry_hdr);
310
+ if ( args->qry_samples )
311
+ {
312
+ init_samples(args->qry_samples, args->qry_samples_is_file, &args->qry_smpl, &args->nqry_smpl, args->qry_hdr, args->qry_fname);
313
+ }
314
+ if ( args->gt_samples )
315
+ {
316
+ init_samples(args->gt_samples, args->gt_samples_is_file, &args->gt_smpl, &args->ngt_smpl,
317
+ args->gt_hdr ? args->gt_hdr : args->qry_hdr,
318
+ args->gt_fname ? args->gt_fname : args->qry_fname);
319
+ }
320
+ else if ( args->pair_samples )
321
+ {
322
+ int npairs;
323
+ char **tmp = hts_readlist(args->pair_samples, args->pair_samples_is_file, &npairs);
324
+ if ( !tmp || !npairs ) error("Failed to parse %s\n", args->pair_samples);
325
+ if ( !args->pair_samples_is_file && npairs%2 ) error("Expected even number of comma-delimited samples with -p\n");
326
+ args->npairs = args->pair_samples_is_file ? npairs : npairs/2;
327
+ args->pairs = (pair_t*) calloc(args->npairs,sizeof(*args->pairs));
328
+ if ( !args->pair_samples_is_file )
329
+ {
330
+ for (i=0; i<args->npairs; i++)
331
+ {
332
+ args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i]);
333
+ args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i+1]);
334
+ if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[2*i]);
335
+ if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,tmp[2*i+1]);
336
+ free(tmp[2*i]);
337
+ free(tmp[2*i+1]);
338
+ }
339
+ }
340
+ else
341
+ {
342
+ for (i=0; i<args->npairs; i++)
343
+ {
344
+ char *ptr = tmp[i];
345
+ while ( *ptr && !isspace(*ptr) ) ptr++;
346
+ if ( !*ptr ) error("Could not parse %s: %s\n",args->pair_samples,tmp[i]);
347
+ *ptr = 0;
348
+ args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[i]);
349
+ if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[i]);
350
+ ptr++;
351
+ while ( *ptr && isspace(*ptr) ) ptr++;
352
+ args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, ptr);
353
+ if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,ptr);
354
+ free(tmp[i]);
355
+ }
356
+ }
357
+ free(tmp);
358
+ qsort(args->pairs,args->npairs,sizeof(*args->pairs),cmp_pair);
359
+ }
360
+ else if ( args->gt_hdr )
361
+ args->ngt_smpl = bcf_hdr_nsamples(args->gt_hdr);
362
+ if ( !args->ngt_smpl )
363
+ {
364
+ args->ngt_smpl = args->nqry_smpl;
365
+ args->gt_smpl = args->qry_smpl;
366
+ args->cross_check = 1;
367
+ }
368
+
369
+ // The data arrays
370
+ if ( !args->npairs ) args->npairs = args->cross_check ? args->nqry_smpl*(args->nqry_smpl+1)/2 : args->ngt_smpl*args->nqry_smpl;
371
+ if ( !args->pair_samples )
372
+ {
373
+ args->qry_dsg = (uint8_t*) malloc(args->nqry_smpl);
374
+ args->gt_dsg = args->cross_check ? args->qry_dsg : (uint8_t*) malloc(args->ngt_smpl);
375
+ }
376
+ if ( args->use_PLs )
377
+ {
378
+ args->pdiff = (double*) calloc(args->npairs,sizeof(*args->pdiff)); // log probability of pair samples being the same
379
+ args->qry_prob = (double*) malloc(3*args->nqry_smpl*sizeof(*args->qry_prob));
380
+ args->gt_prob = args->cross_check ? args->qry_prob : (double*) malloc(3*args->ngt_smpl*sizeof(*args->gt_prob));
381
+
382
+ // dsg2prob: the first index is bitmask of 8 possible dsg combinations (only 1<<0,1<<2,1<<3 are set, accessing
383
+ // anything else indicated an error, this is just to reuse gt_to_dsg()); the second index are the corresponding
384
+ // probabilities of 0/0, 0/1, and 1/1 genotypes
385
+ for (i=0; i<8; i++)
386
+ for (j=0; j<3; j++)
387
+ args->dsg2prob[i][j] = HUGE_VAL;
388
+ args->dsg2prob[1][0] = -log(1-pow(10,-0.1*args->use_PLs));
389
+ args->dsg2prob[1][1] = -log(0.5*pow(10,-0.1*args->use_PLs));
390
+ args->dsg2prob[1][2] = -log(0.5*pow(10,-0.1*args->use_PLs));
391
+ args->dsg2prob[2][0] = -log(0.5*pow(10,-0.1*args->use_PLs));
392
+ args->dsg2prob[2][1] = -log(1-pow(10,-0.1*args->use_PLs));
393
+ args->dsg2prob[2][2] = -log(0.5*pow(10,-0.1*args->use_PLs));
394
+ args->dsg2prob[4][0] = -log(0.5*pow(10,-0.1*args->use_PLs));
395
+ args->dsg2prob[4][1] = -log(0.5*pow(10,-0.1*args->use_PLs));
396
+ args->dsg2prob[4][2] = -log(1-pow(10,-0.1*args->use_PLs));
397
+
398
+ // lookup table to avoid exponentiation
399
+ for (i=0; i<256; i++) args->pl2prob[i] = pow(10,-0.1*i);
400
+ }
401
+ else
402
+ args->ndiff = (uint32_t*) calloc(args->npairs,sizeof(*args->ndiff)); // number of differing genotypes for each pair of samples
403
+ args->ncnt = (uint32_t*) calloc(args->npairs,sizeof(*args->ncnt)); // number of comparisons performed (non-missing data)
404
+ if ( !args->ncnt ) error("Error: failed to allocate %.1f Mb\n", args->npairs*sizeof(*args->ncnt)/1e6);
405
+ if ( args->calc_hwe_prob )
406
+ {
407
+ // prob of the observed sequence of matches given site AFs and HWE
408
+ args->hwe_prob = (double*) calloc(args->npairs,sizeof(*args->hwe_prob));
409
+ if ( !args->hwe_prob ) error("Error: failed to allocate %.1f Mb. Run with --no-HWE-prob to save some memory.\n", args->npairs*sizeof(*args->hwe_prob)/1e6);
410
+ }
411
+
412
+ if ( args->distinctive_sites ) diff_sites_init(args);
413
+
414
+ args->fp = bcftools_stdout;
415
+ print_header(args, args->fp);
416
+ }
417
+
418
+ static void destroy_data(args_t *args)
419
+ {
420
+ if ( args->gt_dsg!=args->qry_dsg ) free(args->gt_dsg);
421
+ free(args->qry_dsg);
422
+ if ( args->gt_prob!=args->qry_prob ) free(args->gt_prob);
423
+ free(args->qry_prob);
424
+ free(args->es_max_mem);
425
+ fclose(args->fp);
426
+ if ( args->distinctive_sites ) diff_sites_destroy(args);
427
+ free(args->hwe_prob);
428
+ free(args->cwd);
429
+ free(args->qry_arr);
430
+ if ( args->gt_hdr ) free(args->gt_arr);
431
+ free(args->pdiff);
432
+ free(args->ndiff);
433
+ free(args->ncnt);
434
+ free(args->qry_smpl);
435
+ if ( args->gt_smpl!=args->qry_smpl ) free(args->gt_smpl);
436
+ free(args->pairs);
437
+ bcf_sr_destroy(args->files);
438
+ }
439
+
440
+ static inline uint8_t gt_to_dsg(int32_t *ptr)
441
+ {
442
+ if ( bcf_gt_is_missing(ptr[0]) || bcf_gt_is_missing(ptr[1]) || ptr[1]==bcf_int32_vector_end ) return 0;
443
+ uint8_t dsg = (bcf_gt_allele(ptr[0])?1:0) + (bcf_gt_allele(ptr[1])?1:0);
444
+ return 1<<dsg;
445
+ }
446
+ static inline uint8_t pl_to_dsg(int32_t *ptr)
447
+ {
448
+ if ( ptr[0]==bcf_int32_missing || ptr[1]==bcf_int32_missing || ptr[2]==bcf_int32_missing ) return 0;
449
+ if ( ptr[1]==bcf_int32_vector_end || ptr[2]==bcf_int32_vector_end ) return 0;
450
+ int min_pl = ptr[0]<ptr[1] ? (ptr[0]<ptr[2]?ptr[0]:ptr[2]) : (ptr[1]<ptr[2]?ptr[1]:ptr[2]);
451
+ uint8_t dsg = 0;
452
+ if ( ptr[0]==min_pl ) dsg |= 1;
453
+ if ( ptr[1]==min_pl ) dsg |= 2;
454
+ if ( ptr[2]==min_pl ) dsg |= 4;
455
+ return dsg;
456
+ }
457
+ static inline uint8_t gt_to_prob(args_t *args, int32_t *ptr, double *prob)
458
+ {
459
+ uint8_t dsg = gt_to_dsg(ptr);
460
+ if ( dsg )
461
+ {
462
+ prob[0] = args->dsg2prob[dsg][0];
463
+ prob[1] = args->dsg2prob[dsg][1];
464
+ prob[2] = args->dsg2prob[dsg][2];
465
+ }
466
+ return dsg;
467
+ }
468
+ static inline uint8_t pl_to_prob(args_t *args, int32_t *ptr, double *prob)
469
+ {
470
+ uint8_t dsg = pl_to_dsg(ptr);
471
+ if ( dsg )
472
+ {
473
+ prob[0] = (ptr[0]>=0 && ptr[0]<255) ? args->pl2prob[ptr[0]] : args->pl2prob[255];
474
+ prob[1] = (ptr[1]>=0 && ptr[1]<255) ? args->pl2prob[ptr[1]] : args->pl2prob[255];
475
+ prob[2] = (ptr[2]>=0 && ptr[2]<255) ? args->pl2prob[ptr[2]] : args->pl2prob[255];
476
+ double sum = prob[0] + prob[1] + prob[2];
477
+ prob[0] /= sum;
478
+ prob[1] /= sum;
479
+ prob[2] /= sum;
480
+ prob[0] = -log(prob[0]);
481
+ prob[1] = -log(prob[1]);
482
+ prob[2] = -log(prob[2]);
483
+ }
484
+ return dsg;
485
+ }
486
+ static int set_data(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec, int32_t **arr, int32_t *narr, int *narr1, int *use_GT)
487
+ {
488
+ static int warn_dip_GT = 1;
489
+ static int warn_dip_PL = 1;
490
+ int i;
491
+ for (i=0; i<2; i++)
492
+ {
493
+ if ( *use_GT )
494
+ {
495
+ int ret = bcf_get_genotypes(hdr,rec,arr,narr);
496
+ if ( ret < 0 )
497
+ {
498
+ if ( !i ) { *use_GT = 0; continue; }
499
+ args->nskip_no_data++;
500
+ return -1;
501
+ }
502
+ if ( ret != 2*bcf_hdr_nsamples(hdr) )
503
+ {
504
+ if ( warn_dip_GT )
505
+ {
506
+ fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/GT fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
507
+ warn_dip_GT = 0;
508
+ }
509
+ args->nskip_dip_GT++;
510
+ return -1;
511
+ }
512
+ *narr1 = 2;
513
+ return 0;
514
+ }
515
+
516
+ int ret = bcf_get_format_int32(hdr,rec,"PL",arr,narr);
517
+ if ( ret < 0 )
518
+ {
519
+ if ( !i ) { *use_GT = 1; continue; }
520
+ args->nskip_no_data++;
521
+ return -1;
522
+ }
523
+ if ( ret != 3*bcf_hdr_nsamples(hdr) )
524
+ {
525
+ if ( warn_dip_PL )
526
+ {
527
+ fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", only diploid FORMAT/PL fields supported. (This is printed only once.)\n", bcf_seqname(hdr,rec),rec->pos+1);
528
+ warn_dip_PL = 0;
529
+ }
530
+ args->nskip_dip_PL++;
531
+ return -1;
532
+ }
533
+ *narr1 = 3;
534
+ return 0;
535
+ }
536
+ return -1; // should never reach
537
+ }
538
+ static void process_line(args_t *args)
539
+ {
540
+ int i,j,k, nqry1, ngt1, ret;
541
+
542
+ bcf1_t *gt_rec = NULL, *qry_rec = bcf_sr_get_line(args->files,0); // the query file
543
+ int qry_use_GT = args->qry_use_GT;
544
+ int gt_use_GT = args->gt_use_GT;
545
+
546
+ ret = set_data(args, args->qry_hdr, qry_rec, &args->qry_arr, &args->nqry_arr, &nqry1, &qry_use_GT);
547
+ if ( ret<0 ) return;
548
+
549
+ if ( args->gt_hdr )
550
+ {
551
+ gt_rec = bcf_sr_get_line(args->files,1);
552
+ ret = set_data(args, args->gt_hdr, gt_rec, &args->gt_arr, &args->ngt_arr, &ngt1, &gt_use_GT);
553
+ if ( ret<0 ) return;
554
+ }
555
+ else
556
+ {
557
+ ngt1 = nqry1;
558
+ args->gt_arr = args->qry_arr;
559
+ }
560
+
561
+ // stats: number of compared sites, and used tags
562
+ args->ncmp++;
563
+ args->nused[qry_use_GT][gt_use_GT]++;
564
+
565
+ double af,hwe_dsg[8];
566
+ if ( args->calc_hwe_prob )
567
+ {
568
+ int ac[2];
569
+ if ( args->gt_hdr )
570
+ {
571
+ if ( bcf_calc_ac(args->gt_hdr, gt_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
572
+ }
573
+ else if ( bcf_calc_ac(args->qry_hdr, qry_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n");
574
+
575
+ // hwe indexes correspond to the bitmask of eight dsg combinations to account for PL uncertainty
576
+ // for in the extreme case we can have uninformative PL=0,0,0. So the values are the minima of e.g.
577
+ // hwe[1,2,4] .. dsg=0,1,2
578
+ // hwe[3] .. dsg=0 or 1
579
+ // hwe[6] .. dsg=1 or 2
580
+
581
+ double hwe[3];
582
+ const double min_af = 1e-5; // cap the AF in case we get unrealistic values
583
+ af = (double)ac[1]/(ac[0]+ac[1]);
584
+ hwe[0] = af>min_af ? -log(af*af) : -log(min_af*min_af);
585
+ hwe[1] = af>min_af && af<1-min_af ? -log(2*af*(1-af)) : -log(2*min_af*(1-min_af));
586
+ hwe[2] = af<(1-min_af) ? -log((1-af)*(1-af)) : -log(min_af*min_af);
587
+ hwe_dsg[0] = 0;
588
+ for (i=1; i<8; i++)
589
+ {
590
+ hwe_dsg[i] = HUGE_VAL;
591
+ for (k=0; k<3; k++)
592
+ {
593
+ if ( ((1<<k)&i) && hwe_dsg[i] > hwe[k] ) hwe_dsg[i] = hwe[k];
594
+ }
595
+ }
596
+ }
597
+
598
+ // The sample pairs were given explicitly via -p/-P options
599
+ if ( args->pairs )
600
+ {
601
+ if ( !args->use_PLs )
602
+ {
603
+ int ndiff = 0;
604
+ if ( args->kbs_diff ) diff_sites_reset(args);
605
+
606
+ for (i=0; i<args->npairs; i++)
607
+ {
608
+ int32_t *ptr;
609
+ uint8_t qry_dsg, gt_dsg;
610
+
611
+ ptr = args->gt_arr + args->pairs[i].igt*ngt1;
612
+ gt_dsg = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
613
+ if ( !gt_dsg ) continue; // missing value
614
+ if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
615
+
616
+ ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
617
+ qry_dsg = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
618
+ if ( !qry_dsg ) continue; // missing value
619
+
620
+ int match = qry_dsg & gt_dsg;
621
+ if ( !match )
622
+ {
623
+ args->ndiff[i]++;
624
+ if ( args->kbs_diff ) { ndiff++; kbs_insert(args->kbs_diff, i); }
625
+ }
626
+ else if ( args->calc_hwe_prob ) args->hwe_prob[i] += hwe_dsg[match];
627
+ args->ncnt[i]++;
628
+ }
629
+
630
+ if ( ndiff ) diff_sites_push(args, ndiff, qry_rec->rid, qry_rec->pos);
631
+ }
632
+ else // use_PLs set
633
+ {
634
+ for (i=0; i<args->npairs; i++)
635
+ {
636
+ int32_t *ptr;
637
+ double qry_prob[3], gt_prob[3];
638
+ uint8_t qry_dsg, gt_dsg;
639
+
640
+ ptr = args->gt_arr + args->pairs[i].igt*ngt1;
641
+ gt_dsg = gt_use_GT ? gt_to_prob(args,ptr,gt_prob) : pl_to_prob(args,ptr,gt_prob);
642
+ if ( !gt_dsg ) continue; // missing value
643
+ if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom
644
+
645
+ ptr = args->qry_arr + args->pairs[i].iqry*nqry1;
646
+ qry_dsg = qry_use_GT ? gt_to_prob(args,ptr,qry_prob) : pl_to_prob(args,ptr,qry_prob);
647
+ if ( !qry_dsg ) continue; // missing value
648
+
649
+ double min = qry_prob[0] + gt_prob[0];
650
+ qry_prob[1] += gt_prob[1];
651
+ if ( min > qry_prob[1] ) min = qry_prob[1];
652
+ qry_prob[2] += gt_prob[2];
653
+ if ( min > qry_prob[2] ) min = qry_prob[2];
654
+ args->pdiff[i] += min;
655
+
656
+ if ( args->calc_hwe_prob )
657
+ {
658
+ int match = qry_dsg & gt_dsg;
659
+ args->hwe_prob[i] += hwe_dsg[match];
660
+ }
661
+ args->ncnt[i]++;
662
+ }
663
+ }
664
+ return;
665
+ }
666
+
667
+ int idx=0;
668
+ if ( !args->use_PLs )
669
+ {
670
+ for (i=0; i<args->nqry_smpl; i++)
671
+ {
672
+ int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
673
+ int32_t *ptr = args->qry_arr + nqry1*iqry;
674
+ args->qry_dsg[i] = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
675
+ }
676
+ if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
677
+ {
678
+ for (i=0; i<args->ngt_smpl; i++)
679
+ {
680
+ int igt = args->gt_smpl ? args->gt_smpl[i] : i;
681
+ int32_t *ptr = args->gt_arr + ngt1*igt;
682
+ args->gt_dsg[i] = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr);
683
+ if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
684
+ }
685
+ }
686
+ for (i=0; i<args->nqry_smpl; i++)
687
+ {
688
+ int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
689
+ if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
690
+ for (j=0; j<ngt; j++)
691
+ {
692
+ if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
693
+ int match = args->qry_dsg[i] & args->gt_dsg[j];
694
+ if ( !match ) args->ndiff[idx]++;
695
+ else if ( args->calc_hwe_prob ) args->hwe_prob[idx] += hwe_dsg[match];
696
+ args->ncnt[idx]++;
697
+ idx++;
698
+ }
699
+ }
700
+ }
701
+ else // use_PLs set
702
+ {
703
+ for (i=0; i<args->nqry_smpl; i++)
704
+ {
705
+ int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
706
+ int32_t *ptr = args->qry_arr + nqry1*iqry;
707
+ args->qry_dsg[i] = qry_use_GT ? gt_to_prob(args,ptr,args->qry_prob+i*3) : pl_to_prob(args,ptr,args->qry_prob+i*3);
708
+ }
709
+ if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg
710
+ {
711
+ for (i=0; i<args->ngt_smpl; i++)
712
+ {
713
+ int igt = args->gt_smpl ? args->gt_smpl[i] : i;
714
+ int32_t *ptr = args->gt_arr + ngt1*igt;
715
+ args->gt_dsg[i] = gt_use_GT ? gt_to_prob(args,ptr,args->gt_prob+i*3) : pl_to_prob(args,ptr,args->gt_prob+i*3);
716
+ if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value
717
+ }
718
+ }
719
+ for (i=0; i<args->nqry_smpl; i++)
720
+ {
721
+ int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode?
722
+ if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value
723
+ for (j=0; j<ngt; j++)
724
+ {
725
+ if ( !args->gt_dsg[j] ) { idx++; continue; } // missing value
726
+
727
+ double min = args->qry_prob[i*3] + args->gt_prob[j*3];
728
+ if ( min > args->qry_prob[i*3+1] + args->gt_prob[j*3+1] ) min = args->qry_prob[i*3+1] + args->gt_prob[j*3+1];
729
+ if ( min > args->qry_prob[i*3+2] + args->gt_prob[j*3+2] ) min = args->qry_prob[i*3+2] + args->gt_prob[j*3+2];
730
+ args->pdiff[idx] += min;
731
+
732
+ if ( args->calc_hwe_prob )
733
+ {
734
+ int match = args->qry_dsg[i] & args->gt_dsg[j];
735
+ args->hwe_prob[idx] += hwe_dsg[match];
736
+ }
737
+ args->ncnt[idx]++;
738
+ idx++;
739
+ }
740
+ }
741
+ }
742
+ }
743
+
744
+
745
+ typedef struct
746
+ {
747
+ int ism, idx;
748
+ double val;
749
+ }
750
+ idbl_t;
751
+ static int cmp_idbl(const void *_a, const void *_b)
752
+ {
753
+ idbl_t *a = (idbl_t*)_a;
754
+ idbl_t *b = (idbl_t*)_b;
755
+ if ( a->val < b->val ) return -1;
756
+ if ( a->val > b->val ) return 1;
757
+ return 0;
758
+ }
759
+ static void report_distinctive_sites(args_t *args)
760
+ {
761
+ extsort_sort(args->es);
762
+
763
+ fprintf(args->fp,"# DS, distinctive sites:\n");
764
+ fprintf(args->fp,"# - chromosome\n");
765
+ fprintf(args->fp,"# - position\n");
766
+ fprintf(args->fp,"# - cumulative number of pairs distinguished by this block\n");
767
+ fprintf(args->fp,"# - block id\n");
768
+ fprintf(args->fp,"#DS\t[2]Chromosome\t[3]Position\t[4]Cumulative number of distinct pairs\t[5]Block id\n");
769
+
770
+ kbitset_t *kbs_blk = kbs_init(args->npairs);
771
+ kbitset_iter_t itr;
772
+ int i,ndiff,rid,pos,ndiff_tot = 0, iblock = 0;
773
+ int ndiff_min = args->distinctive_sites <= args->npairs ? args->distinctive_sites : args->npairs;
774
+ while ( diff_sites_shift(args,&ndiff,&rid,&pos) )
775
+ {
776
+ int ndiff_new = 0, ndiff_dbg = 0;
777
+ kbs_start(&itr);
778
+ while ( (i=kbs_next(args->kbs_diff, &itr))>=0 )
779
+ {
780
+ ndiff_dbg++;
781
+ if ( kbs_exists(kbs_blk,i) ) continue; // already set
782
+ kbs_insert(kbs_blk,i);
783
+ ndiff_new++;
784
+ }
785
+ if ( ndiff_dbg!=ndiff ) error("Corrupted data, fixme: %d vs %d\n",ndiff_dbg,ndiff);
786
+ if ( !ndiff_new ) continue; // no new pair distinguished by this site
787
+ ndiff_tot += ndiff_new;
788
+ fprintf(args->fp,"DS\t%s\t%d\t%d\t%d\n",bcf_hdr_id2name(args->qry_hdr,rid),pos+1,ndiff_tot,iblock);
789
+ if ( ndiff_tot < ndiff_min ) continue; // fewer than the requested number of pairs can be distinguished at this point
790
+ iblock++;
791
+ ndiff_tot = 0;
792
+ kbs_clear(kbs_blk);
793
+ }
794
+ kbs_destroy(kbs_blk);
795
+ }
796
+ static void report(args_t *args)
797
+ {
798
+ fprintf(args->fp,"INFO\tsites-compared\t%u\n",args->ncmp);
799
+ fprintf(args->fp,"INFO\tsites-skipped-no-match\t%u\n",args->nskip_no_match);
800
+ fprintf(args->fp,"INFO\tsites-skipped-multiallelic\t%u\n",args->nskip_not_ba);
801
+ fprintf(args->fp,"INFO\tsites-skipped-monoallelic\t%u\n",args->nskip_mono);
802
+ fprintf(args->fp,"INFO\tsites-skipped-no-data\t%u\n",args->nskip_no_data);
803
+ fprintf(args->fp,"INFO\tsites-skipped-GT-not-diploid\t%u\n",args->nskip_dip_GT);
804
+ fprintf(args->fp,"INFO\tsites-skipped-PL-not-diploid\t%u\n",args->nskip_dip_PL);
805
+ fprintf(args->fp,"INFO\tsites-used-PL-vs-PL\t%u\n",args->nused[0][0]);
806
+ fprintf(args->fp,"INFO\tsites-used-PL-vs-GT\t%u\n",args->nused[0][1]);
807
+ fprintf(args->fp,"INFO\tsites-used-GT-vs-PL\t%u\n",args->nused[1][0]);
808
+ fprintf(args->fp,"INFO\tsites-used-GT-vs-GT\t%u\n",args->nused[1][1]);
809
+ fprintf(args->fp,"# DC, discordance:\n");
810
+ fprintf(args->fp,"# - query sample\n");
811
+ fprintf(args->fp,"# - genotyped sample\n");
812
+ fprintf(args->fp,"# - discordance (either an abstract score or number of mismatches, see -e/-u in the man page for details; smaller is better)\n");
813
+ fprintf(args->fp,"# - negative log of HWE probability at matching sites (rare genotypes matches are more informative, bigger is better)\n");
814
+ fprintf(args->fp,"# - number of sites compared (bigger is better)\n");
815
+ fprintf(args->fp,"#DC\t[2]Query Sample\t[3]Genotyped Sample\t[4]Discordance\t[5]-log P(HWE)\t[6]Number of sites compared\n");
816
+
817
+ int trim = args->ntop;
818
+ if ( !args->pairs )
819
+ {
820
+ if ( !args->ngt_smpl && args->nqry_smpl <= args->ntop ) trim = 0;
821
+ if ( args->ngt_smpl && args->ngt_smpl <= args->ntop ) trim = 0;
822
+ }
823
+
824
+ if ( args->pairs )
825
+ {
826
+ int i;
827
+ for (i=0; i<args->npairs; i++)
828
+ {
829
+ int iqry = args->pairs[i].iqry;
830
+ int igt = args->pairs[i].igt;
831
+ if ( args->ndiff )
832
+ {
833
+ fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
834
+ args->qry_hdr->samples[iqry],
835
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
836
+ args->ndiff[i],
837
+ args->calc_hwe_prob ? args->hwe_prob[i] : 0,
838
+ args->ncnt[i]);
839
+ }
840
+ else
841
+ {
842
+ fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
843
+ args->qry_hdr->samples[iqry],
844
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
845
+ args->pdiff[i],
846
+ args->calc_hwe_prob ? args->hwe_prob[i] : 0,
847
+ args->ncnt[i]);
848
+ }
849
+ }
850
+ }
851
+ else if ( !trim )
852
+ {
853
+ int i,j,idx=0;
854
+ for (i=0; i<args->nqry_smpl; i++)
855
+ {
856
+ int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
857
+ int ngt = args->cross_check ? i : args->ngt_smpl;
858
+ for (j=0; j<ngt; j++)
859
+ {
860
+ int igt = args->gt_smpl ? args->gt_smpl[j] : j;
861
+ if ( args->ndiff )
862
+ {
863
+ fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
864
+ args->qry_hdr->samples[iqry],
865
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
866
+ args->ndiff[idx],
867
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
868
+ args->ncnt[idx]);
869
+ }
870
+ else
871
+ {
872
+ fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
873
+ args->qry_hdr->samples[iqry],
874
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
875
+ args->pdiff[idx],
876
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
877
+ args->ncnt[idx]);
878
+ }
879
+ idx++;
880
+ }
881
+ }
882
+ }
883
+ else if ( !args->cross_check )
884
+ {
885
+ idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*args->ngt_smpl);
886
+ int i,j;
887
+ for (i=0; i<args->nqry_smpl; i++)
888
+ {
889
+ int idx = i*args->ngt_smpl;
890
+ for (j=0; j<args->ngt_smpl; j++)
891
+ {
892
+ if ( args->sort_by_hwe )
893
+ arr[j].val = -args->hwe_prob[idx];
894
+ else if ( args->ndiff )
895
+ arr[j].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
896
+ else
897
+ arr[j].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
898
+ arr[j].ism = j;
899
+ arr[j].idx = idx;
900
+ idx++;
901
+ }
902
+ qsort(arr, args->ngt_smpl, sizeof(*arr), cmp_idbl);
903
+ int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
904
+ for (j=0; j<args->ntop; j++)
905
+ {
906
+ int idx = arr[j].idx;
907
+ int igt = args->gt_smpl ? args->gt_smpl[arr[j].ism] : arr[j].ism;
908
+ if ( args->ndiff )
909
+ {
910
+ fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
911
+ args->qry_hdr->samples[iqry],
912
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
913
+ args->ndiff[idx],
914
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
915
+ args->ncnt[idx]);
916
+ }
917
+ else
918
+ {
919
+ fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
920
+ args->qry_hdr->samples[iqry],
921
+ args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt],
922
+ args->pdiff[idx],
923
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
924
+ args->ncnt[idx]);
925
+ }
926
+ }
927
+ }
928
+ free(arr);
929
+ }
930
+ else
931
+ {
932
+ int narr = args->nqry_smpl-1;
933
+ idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*narr);
934
+ int i,j,k,idx;
935
+ for (i=0; i<args->nqry_smpl; i++)
936
+ {
937
+ k = 0, idx = i*(i-1)/2;
938
+ for (j=0; j<i; j++)
939
+ {
940
+ if ( args->sort_by_hwe )
941
+ arr[k].val = -args->hwe_prob[idx];
942
+ else if ( args->ndiff )
943
+ arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
944
+ else
945
+ arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
946
+ arr[k].ism = j;
947
+ arr[k].idx = idx;
948
+ idx++;
949
+ k++;
950
+ }
951
+ for (; j<narr; j++)
952
+ {
953
+ idx = j*(j+1)/2 + i;
954
+ if ( args->sort_by_hwe )
955
+ arr[k].val = -args->hwe_prob[idx];
956
+ else if ( args->ndiff )
957
+ arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0;
958
+ else
959
+ arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0;
960
+ arr[k].ism = j + 1;
961
+ arr[k].idx = idx;
962
+ k++;
963
+ }
964
+ qsort(arr, narr, sizeof(*arr), cmp_idbl);
965
+ int iqry = args->qry_smpl ? args->qry_smpl[i] : i;
966
+ for (j=0; j<args->ntop; j++)
967
+ {
968
+ if ( i <= arr[j].ism ) continue;
969
+ int idx = arr[j].idx;
970
+ int igt = args->qry_smpl ? args->qry_smpl[arr[j].ism] : arr[j].ism;
971
+ if ( args->ndiff )
972
+ {
973
+ fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n",
974
+ args->qry_hdr->samples[iqry],
975
+ args->qry_hdr->samples[igt],
976
+ args->ndiff[idx],
977
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
978
+ args->ncnt[idx]);
979
+ }
980
+ else
981
+ {
982
+ fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n",
983
+ args->qry_hdr->samples[iqry],
984
+ args->qry_hdr->samples[igt],
985
+ args->pdiff[idx],
986
+ args->calc_hwe_prob ? args->hwe_prob[idx] : 0,
987
+ args->ncnt[idx]);
988
+ }
989
+ }
990
+ }
991
+ free(arr);
992
+ }
993
+ }
994
+
995
+ static int is_input_okay(args_t *args, int nmatch)
996
+ {
997
+ int i;
998
+ const char *msg;
999
+ bcf_hdr_t *hdr;
1000
+ bcf1_t *rec;
1001
+ if ( args->gt_hdr && nmatch!=2 )
1002
+ {
1003
+ if ( args->nskip_no_match++ ) return 0;
1004
+ for (i=0; i<2; i++)
1005
+ {
1006
+ rec = bcf_sr_get_line(args->files,i);
1007
+ if ( rec ) break;
1008
+ }
1009
+ hdr = bcf_sr_get_header(args->files,i);
1010
+ fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", no record with matching POS+ALT. (This is printed only once.)\n",
1011
+ bcf_seqname(hdr,rec),rec->pos+1);
1012
+ return 0;
1013
+ }
1014
+ for (i=0; i<2; i++)
1015
+ {
1016
+ hdr = bcf_sr_get_header(args->files,i);
1017
+ rec = bcf_sr_get_line(args->files,i);
1018
+ if ( rec->n_allele>2 )
1019
+ {
1020
+ if ( args->nskip_not_ba++ ) return 0;
1021
+ msg = "not a biallelic site, run `bcftools norm -m -` first";
1022
+ goto not_okay;
1023
+ }
1024
+ if ( bcf_get_variant_types(rec)==VCF_REF )
1025
+ {
1026
+ if ( args->nskip_mono++ ) return 0;
1027
+ msg = "monoallelic site";
1028
+ goto not_okay;
1029
+ }
1030
+ if ( !args->gt_hdr ) break;
1031
+ }
1032
+ return 1;
1033
+
1034
+ not_okay:
1035
+ fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", %s. (This is printed only once.)\n",
1036
+ bcf_seqname(hdr,rec),rec->pos+1,msg);
1037
+ return 0;
1038
+ }
1039
+
1040
+ static void usage(void)
1041
+ {
1042
+ fprintf(bcftools_stderr, "\n");
1043
+ fprintf(bcftools_stderr, "About: Check sample identity. With no -g BCF given, multi-sample cross-check is performed.\n");
1044
+ fprintf(bcftools_stderr, "Usage: bcftools gtcheck [options] [-g <genotypes.vcf.gz>] <query.vcf.gz>\n");
1045
+ fprintf(bcftools_stderr, "\n");
1046
+ fprintf(bcftools_stderr, "Options:\n");
1047
+ //fprintf(bcftools_stderr, " -a, --all-sites Output comparison for all sites\n");
1048
+ //fprintf(bcftools_stderr, " -c, --cluster MIN,MAX Min inter- and max intra-sample error [0.23,-0.3]\n");
1049
+ fprintf(bcftools_stderr, " --distinctive-sites Find sites that can distinguish between at least NUM sample pairs.\n");
1050
+ fprintf(bcftools_stderr, " NUM[,MEM[,TMP]] If the number is smaller or equal to 1, it is interpreted as the fraction of pairs.\n");
1051
+ fprintf(bcftools_stderr, " The optional MEM string sets the maximum memory used for in-memory sorting [500M]\n");
1052
+ #ifdef _WIN32
1053
+ fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/bcftools.XXXXXX]\n");
1054
+ #else
1055
+ fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/tmp/bcftools.XXXXXX]\n");
1056
+ #endif
1057
+ fprintf(bcftools_stderr, " --dry-run Stop after first record to estimate required time\n");
1058
+ fprintf(bcftools_stderr, " -e, --error-probability INT Phred-scaled probability of genotyping error, 0 for faster but less accurate results [40]\n");
1059
+ fprintf(bcftools_stderr, " -g, --genotypes FILE Genotypes to compare against\n");
1060
+ fprintf(bcftools_stderr, " -H, --homs-only Homozygous genotypes only, useful with low coverage data (requires -g)\n");
1061
+ fprintf(bcftools_stderr, " --n-matches INT Print only top INT matches for each sample (sorted by average score), 0 for unlimited.\n");
1062
+ fprintf(bcftools_stderr, " Use negative value to sort by HWE probability rather than by discordance [0]\n");
1063
+ fprintf(bcftools_stderr, " --no-HWE-prob Disable calculation of HWE probability\n");
1064
+ fprintf(bcftools_stderr, " -p, --pairs LIST Comma-separated sample pairs to compare (qry,gt[,qry,gt..] with -g or qry,qry[,qry,qry..] w/o)\n");
1065
+ fprintf(bcftools_stderr, " -P, --pairs-file FILE File with tab-delimited sample pairs to compare (qry,gt with -g or qry,qry w/o)\n");
1066
+ fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1067
+ fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1068
+ fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1069
+ fprintf(bcftools_stderr, " -s, --samples [qry|gt]:LIST List of query or -g samples, \"-\" to select all samples (by default all samples are compared)\n");
1070
+ fprintf(bcftools_stderr, " -S, --samples-file [qry|gt]:FILE File with the query or -g samples to compare\n");
1071
+ fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1072
+ fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1073
+ fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1074
+ fprintf(bcftools_stderr, " -u, --use TAG1[,TAG2] Which tag to use in the query file (TAG1) and the -g file (TAG2) [PL,GT]\n");
1075
+ fprintf(bcftools_stderr, "Examples:\n");
1076
+ fprintf(bcftools_stderr, " # Check discordance of all samples from B against all sample in A\n");
1077
+ fprintf(bcftools_stderr, " bcftools gtcheck -g A.bcf B.bcf\n");
1078
+ fprintf(bcftools_stderr, "\n");
1079
+ fprintf(bcftools_stderr, " # Limit comparisons to the fiven list of samples\n");
1080
+ fprintf(bcftools_stderr, " bcftools gtcheck -s gt:a1,a2,a3 -s qry:b1,b2 -g A.bcf B.bcf\n");
1081
+ fprintf(bcftools_stderr, "\n");
1082
+ fprintf(bcftools_stderr, " # Compare only two pairs a1,b1 and a1,b2\n");
1083
+ fprintf(bcftools_stderr, " bcftools gtcheck -p a1,b1,a1,b2 -g A.bcf B.bcf\n");
1084
+ fprintf(bcftools_stderr, "\n");
1085
+ bcftools_exit(1);
1086
+ }
1087
+
1088
+ int main_vcfgtcheck(int argc, char *argv[])
1089
+ {
1090
+ int c;
1091
+ args_t *args = (args_t*) calloc(1,sizeof(args_t));
1092
+ args->argc = argc; args->argv = argv; set_cwd(args);
1093
+ args->qry_use_GT = -1;
1094
+ args->gt_use_GT = -1;
1095
+ args->calc_hwe_prob = 1;
1096
+ args->use_PLs = 40;
1097
+ args->regions_overlap = 1;
1098
+ args->targets_overlap = 0;
1099
+
1100
+ // external sort for --distinctive-sites
1101
+ #ifdef _WIN32
1102
+ args->es_tmp_prefix = NULL;
1103
+ #else
1104
+ args->es_tmp_prefix = "/tmp/bcftools-gtcheck";
1105
+ #endif
1106
+ args->es_max_mem = strdup("500M");
1107
+
1108
+ // In simulated sample swaps the minimum error was 0.3 and maximum intra-sample error was 0.23
1109
+ // - min_inter: pairs with smaller err value will be considered identical
1110
+ // - max_intra: pairs with err value bigger than abs(max_intra_err) will be considered
1111
+ // different. If negative, the cutoff may be heuristically lowered
1112
+ args->min_inter_err = 0.23;
1113
+ args->max_intra_err = -0.3;
1114
+
1115
+ static struct option loptions[] =
1116
+ {
1117
+ {"error-probability",1,0,'e'},
1118
+ {"use",1,0,'u'},
1119
+ {"cluster",1,0,'c'},
1120
+ {"GTs-only",1,0,'G'},
1121
+ {"all-sites",0,0,'a'},
1122
+ {"homs-only",0,0,'H'},
1123
+ {"help",0,0,'h'},
1124
+ {"genotypes",1,0,'g'},
1125
+ {"plot",1,0,'p'},
1126
+ {"samples",1,0,'s'},
1127
+ {"samples-file",1,0,'S'},
1128
+ {"n-matches",1,0,2},
1129
+ {"no-HWE-prob",0,0,3},
1130
+ {"target-sample",1,0,4},
1131
+ {"dry-run",0,0,5},
1132
+ {"distinctive-sites",1,0,6},
1133
+ {"regions",1,0,'r'},
1134
+ {"regions-file",1,0,'R'},
1135
+ {"regions-overlap",required_argument,NULL,7},
1136
+ {"targets",1,0,'t'},
1137
+ {"targets-file",1,0,'T'},
1138
+ {"targets-overlap",required_argument,NULL,8},
1139
+ {"pairs",1,0,'p'},
1140
+ {"pairs-file",1,0,'P'},
1141
+ {0,0,0,0}
1142
+ };
1143
+ char *tmp;
1144
+ while ((c = getopt_long(argc, argv, "hg:p:s:S:p:P:Hr:R:at:T:G:c:u:e:",loptions,NULL)) >= 0) {
1145
+ switch (c) {
1146
+ case 'e':
1147
+ args->use_PLs = strtol(optarg,&tmp,10);
1148
+ if ( !tmp || *tmp ) error("Could not parse: --error-probability %s\n", optarg);
1149
+ break;
1150
+ case 'u':
1151
+ {
1152
+ int i,nlist;
1153
+ char **list = hts_readlist(optarg, 0, &nlist);
1154
+ if ( !list || nlist<=0 || nlist>2 ) error("Failed to parse --use %s\n", optarg);
1155
+ if ( !strcasecmp("GT",list[0]) ) args->qry_use_GT = 1;
1156
+ else if ( !strcasecmp("PL",list[0]) ) args->qry_use_GT = 0;
1157
+ else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
1158
+ if ( nlist==2 )
1159
+ {
1160
+ if ( !strcasecmp("GT",list[1]) ) args->gt_use_GT = 1;
1161
+ else if ( !strcasecmp("PL",list[1]) ) args->gt_use_GT = 0;
1162
+ else error("Failed to parse --use %s; only GT and PL are supported\n", optarg);
1163
+ }
1164
+ else args->gt_use_GT = args->qry_use_GT;
1165
+ for (i=0; i<nlist; i++) free(list[i]);
1166
+ free(list);
1167
+ }
1168
+ break;
1169
+ case 2 :
1170
+ args->ntop = strtol(optarg,&tmp,10);
1171
+ if ( !tmp || *tmp ) error("Could not parse: --n-matches %s\n", optarg);
1172
+ if ( args->ntop < 0 )
1173
+ {
1174
+ args->sort_by_hwe = 1;
1175
+ args->ntop *= -1;
1176
+ }
1177
+ break;
1178
+ case 3 : args->calc_hwe_prob = 0; break;
1179
+ case 4 : error("The option -S, --target-sample has been deprecated\n"); break;
1180
+ case 5 : args->dry_run = 1; break;
1181
+ case 6 :
1182
+ args->distinctive_sites = strtod(optarg,&tmp);
1183
+ if ( *tmp )
1184
+ {
1185
+ if ( *tmp!=',' ) error("Could not parse: --distinctive-sites %s\n", optarg);
1186
+ tmp++;
1187
+ free(args->es_max_mem);
1188
+ args->es_max_mem = strdup(tmp);
1189
+ while ( *tmp && *tmp!=',' ) tmp++;
1190
+ if ( *tmp ) { *tmp = 0; args->es_tmp_prefix = tmp+1; }
1191
+ }
1192
+ args->use_PLs = 0;
1193
+ break;
1194
+ case 'c':
1195
+ error("The -c option is to be implemented, please open an issue on github\n");
1196
+ args->min_inter_err = strtod(optarg,&tmp);
1197
+ if ( *tmp )
1198
+ {
1199
+ if ( *tmp!=',') error("Could not parse: -c %s\n", optarg);
1200
+ args->max_intra_err = strtod(tmp+1,&tmp);
1201
+ if ( *tmp ) error("Could not parse: -c %s\n", optarg);
1202
+ }
1203
+ break;
1204
+ case 'G': error("The option -G, --GTs-only has been deprecated\n"); break;
1205
+ case 'a': args->all_sites = 1; error("The -a option is to be implemented, please open an issue on github\n"); break;
1206
+ case 'H': args->hom_only = 1; break;
1207
+ case 'g': args->gt_fname = optarg; break;
1208
+ // case 'p': args->plot = optarg; break;
1209
+ case 's':
1210
+ if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3;
1211
+ else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4;
1212
+ else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
1213
+ break;
1214
+ case 'S':
1215
+ if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3, args->gt_samples_is_file = 1;
1216
+ else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4, args->qry_samples_is_file = 1;
1217
+ else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg);
1218
+ break;
1219
+ case 'p': args->pair_samples = optarg; break;
1220
+ case 'P': args->pair_samples = optarg; args->pair_samples_is_file = 1; break;
1221
+ case 'r': args->regions = optarg; break;
1222
+ case 'R': args->regions = optarg; args->regions_is_file = 1; break;
1223
+ case 't': args->targets = optarg; break;
1224
+ case 'T': args->targets = optarg; args->targets_is_file = 1; break;
1225
+ case 7 :
1226
+ args->regions_overlap = parse_overlap_option(optarg);
1227
+ if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1228
+ break;
1229
+ case 8 :
1230
+ args->targets_overlap = parse_overlap_option(optarg);
1231
+ if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1232
+ break;
1233
+ case 'h':
1234
+ case '?': usage(); break;
1235
+ default: error("Unknown argument: %s\n", optarg);
1236
+ }
1237
+ }
1238
+ if ( optind==argc )
1239
+ {
1240
+ if ( !isatty(fileno((FILE *)stdin)) ) args->qry_fname = "-"; // reading from stdin
1241
+ else usage(); // no files given
1242
+ }
1243
+ else args->qry_fname = argv[optind];
1244
+ if ( argc>optind+1 ) error("Error: too many files given, run with -h for help\n"); // too many files given
1245
+ if ( args->pair_samples )
1246
+ {
1247
+ if ( args->gt_samples || args->qry_samples ) error("The -p/-P option cannot be combined with -s/-S\n");
1248
+ if ( args->ntop ) error("The --n-matches option cannot be combined with -p/-P\n");
1249
+ }
1250
+ if ( args->distinctive_sites && !args->pair_samples ) error("The experimental option --distinctive-sites requires -p/-P\n");
1251
+ if ( args->hom_only && !args->gt_fname ) error("The option --homs-only requires --genotypes\n");
1252
+ if ( args->distinctive_sites && args->use_PLs ) error("The option --distinctive-sites cannot be combined with --error-probability\n");
1253
+
1254
+ init_data(args);
1255
+
1256
+ int ret;
1257
+ while ( (ret=bcf_sr_next_line(args->files)) )
1258
+ {
1259
+ if ( !is_input_okay(args,ret) ) continue;
1260
+
1261
+ // time one record to give the user an estimate with very big files
1262
+ struct timeval t0, t1;
1263
+ if ( !args->ncmp ) gettimeofday(&t0, NULL);
1264
+
1265
+ process_line(args);
1266
+
1267
+ if ( args->ncmp==1 )
1268
+ {
1269
+ gettimeofday(&t1, NULL);
1270
+ double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
1271
+ fprintf(bcftools_stderr,"INFO:\tTime required to process one record .. %f seconds\n",delta/1e6);
1272
+ fprintf(args->fp,"INFO\tTime required to process one record .. %f seconds\n",delta/1e6);
1273
+ if ( args->dry_run ) break;
1274
+ }
1275
+ }
1276
+ if ( !args->dry_run )
1277
+ {
1278
+ report(args);
1279
+ if ( args->distinctive_sites ) report_distinctive_sites(args);
1280
+ }
1281
+
1282
+ destroy_data(args);
1283
+ free(args);
1284
+ return 0;
1285
+ }
1286
+
falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfmerge.c.pysam.c ADDED
The diff for this file is too large to render. See raw diff
 
falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfsort.c ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* vcfsort.c -- sort subcommand
2
+
3
+ Copyright (C) 2017-2023 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.
24
+
25
+ */
26
+
27
+ #include <stdio.h>
28
+ #include <unistd.h>
29
+ #include <getopt.h>
30
+ #include <ctype.h>
31
+ #include <string.h>
32
+ #include <strings.h>
33
+ #include <errno.h>
34
+ #include <sys/stat.h>
35
+ #include <sys/types.h>
36
+ #include <fcntl.h>
37
+ #include <math.h>
38
+ #ifdef _WIN32
39
+ #include <windows.h>
40
+ #endif
41
+ #include <htslib/vcf.h>
42
+ #include <htslib/kstring.h>
43
+ #include <htslib/hts_os.h>
44
+ #include "kheap.h"
45
+ #include "bcftools.h"
46
+
47
+ typedef struct
48
+ {
49
+ char *fname;
50
+ htsFile *fh;
51
+ bcf1_t *rec;
52
+ }
53
+ blk_t;
54
+
55
+ typedef struct _args_t
56
+ {
57
+ bcf_hdr_t *hdr;
58
+ char **argv, *fname, *output_fname, *tmp_dir;
59
+ int argc, output_type, clevel;
60
+ size_t max_mem, mem;
61
+ bcf1_t **buf;
62
+ uint8_t *mem_block;
63
+ size_t nbuf, mbuf, nblk;
64
+ blk_t *blk;
65
+ char *index_fn;
66
+ int write_index;
67
+ }
68
+ args_t;
69
+
70
+ void clean_files(args_t *args)
71
+ {
72
+ int i;
73
+ fprintf(stderr,"Cleaning\n");
74
+ for (i=0; i<args->nblk; i++)
75
+ {
76
+ blk_t *blk = args->blk + i;
77
+ if ( blk->fname )
78
+ {
79
+ unlink(blk->fname);
80
+ free(blk->fname);
81
+ }
82
+ if ( blk->rec )
83
+ bcf_destroy(blk->rec);
84
+ }
85
+ rmdir(args->tmp_dir);
86
+ }
87
+ void clean_files_and_throw(args_t *args, const char *format, ...)
88
+ {
89
+ va_list ap;
90
+ va_start(ap, format);
91
+ vfprintf(stderr, format, ap);
92
+ va_end(ap);
93
+ clean_files(args);
94
+ exit(-1);
95
+ }
96
+
97
+ int cmp_bcf_pos(const void *aptr, const void *bptr)
98
+ {
99
+ bcf1_t *a = *((bcf1_t**)aptr);
100
+ bcf1_t *b = *((bcf1_t**)bptr);
101
+ if ( a->rid < b->rid ) return -1;
102
+ if ( a->rid > b->rid ) return 1;
103
+ if ( a->pos < b->pos ) return -1;
104
+ if ( a->pos > b->pos ) return 1;
105
+
106
+ // Sort the same chr:pos records lexicographically by ref,alt.
107
+ // This will be called rarely so should not slow the sorting down
108
+ // noticeably.
109
+
110
+ int i;
111
+ for (i=0; i<a->n_allele; i++)
112
+ {
113
+ if ( i >= b->n_allele ) return 1;
114
+ int ret = strcasecmp(a->d.allele[i],b->d.allele[i]);
115
+ if ( ret ) return ret;
116
+ }
117
+ if ( a->n_allele < b->n_allele ) return -1;
118
+ return 0;
119
+ }
120
+
121
+ void buf_flush(args_t *args)
122
+ {
123
+ if ( !args->nbuf ) return;
124
+
125
+ qsort(args->buf, args->nbuf, sizeof(*args->buf), cmp_bcf_pos);
126
+
127
+ args->nblk++;
128
+ args->blk = (blk_t*) realloc(args->blk, sizeof(blk_t)*args->nblk);
129
+ if ( !args->blk ) error("Error: could not allocate %zu bytes of memory, try reducing --max-mem\n",sizeof(blk_t)*args->nblk);
130
+ blk_t *blk = args->blk + args->nblk - 1;
131
+
132
+ kstring_t str = {0,0,0};
133
+ ksprintf(&str, "%s/%05d.bcf", args->tmp_dir, (int)args->nblk);
134
+ blk->fname = str.s;
135
+ blk->rec = NULL;
136
+ blk->fh = NULL;
137
+
138
+ htsFile *fh = hts_open(blk->fname, "wbu");
139
+ if ( fh == NULL ) clean_files_and_throw(args, "Cannot write %s: %s\n", blk->fname, strerror(errno));
140
+ if ( bcf_hdr_write(fh, args->hdr)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,blk->fname);
141
+
142
+ int i;
143
+ for (i=0; i<args->nbuf; i++)
144
+ {
145
+ if ( bcf_write(fh, args->hdr, args->buf[i])!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,blk->fname);
146
+ }
147
+ if ( hts_close(fh)!=0 ) clean_files_and_throw(args, "[%s] Error: close failed .. %s\n", __func__,blk->fname);
148
+
149
+ args->nbuf = 0;
150
+ args->mem = 0;
151
+ }
152
+
153
+
154
+ static inline uint8_t *_align_up(uint8_t *ptr)
155
+ {
156
+ return (uint8_t*)(((size_t)ptr + 8 - 1) & ~((size_t)(8 - 1)));
157
+ }
158
+
159
+ void buf_push(args_t *args, bcf1_t *rec)
160
+ {
161
+ size_t delta = sizeof(bcf1_t) + rec->shared.l + rec->indiv.l + rec->unpack_size[0] + rec->unpack_size[1]
162
+ + sizeof(*rec->d.allele)*rec->d.m_allele
163
+ + sizeof(bcf1_t*) // args->buf
164
+ + 8; // the number of _align_up() calls
165
+
166
+ if ( delta > args->max_mem - args->mem )
167
+ {
168
+ args->nbuf++;
169
+ hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf);
170
+ args->buf[args->nbuf-1] = rec;
171
+ buf_flush(args);
172
+ bcf_destroy(rec);
173
+ return;
174
+ }
175
+
176
+ // make sure nothing has changed in htslib
177
+ assert( rec->unpacked==BCF_UN_STR && !rec->d.flt && !rec->d.info && !rec->d.fmt && !rec->d.var );
178
+
179
+ uint8_t *ptr_beg = args->mem_block + args->mem;
180
+ uint8_t *ptr = _align_up(ptr_beg);
181
+ bcf1_t *new_rec = (bcf1_t*)ptr;
182
+ memcpy(new_rec,rec,sizeof(*rec));
183
+ ptr += sizeof(*rec);
184
+
185
+ // The array of allele pointers does not need alignment as bcf1_t is already padded to the biggest
186
+ // data type in the structure
187
+ char **allele = (char**)ptr;
188
+ ptr += rec->n_allele*sizeof(*allele);
189
+
190
+ // This is just to prevent valgrind from complaining about memcpy, unpack_size is a high-water mark
191
+ // and the end may be uninitialized
192
+ delta = rec->d.allele[rec->n_allele-1] - rec->d.allele[0];
193
+ while ( delta < rec->unpack_size[1] ) if ( !rec->d.als[delta++] ) break;
194
+ memcpy(ptr,rec->d.als,delta);
195
+ new_rec->d.als = (char*)ptr;
196
+ ptr = ptr + delta;
197
+
198
+ int i;
199
+ for (i=0; i<rec->n_allele; i++) allele[i] = new_rec->d.als + (ptrdiff_t)(rec->d.allele[i] - rec->d.allele[0]);
200
+ new_rec->d.allele = allele;
201
+
202
+ memcpy(ptr,rec->shared.s,rec->shared.l);
203
+ new_rec->shared.s = (char*)ptr;
204
+ new_rec->shared.m = rec->shared.l;
205
+ ptr += rec->shared.l;
206
+
207
+ memcpy(ptr,rec->indiv.s,rec->indiv.l);
208
+ new_rec->indiv.s = (char*)ptr;
209
+ new_rec->indiv.m = rec->indiv.l;
210
+ ptr += rec->indiv.l;
211
+
212
+ // This is just to prevent valgrind from complaining about memcpy, unpack_size is a high-water mark
213
+ // and the end may be uninitialized
214
+ i = 0;
215
+ while ( i < rec->unpack_size[0] ) if ( !rec->d.id[i++] ) break;
216
+ memcpy(ptr,rec->d.id,i);
217
+ new_rec->d.id = (char*)ptr;
218
+ ptr += i;
219
+
220
+ args->nbuf++;
221
+ hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf);
222
+ args->buf[args->nbuf-1] = new_rec;
223
+
224
+ delta = ptr - ptr_beg;
225
+ args->mem += delta;
226
+
227
+ assert( args->mem <= args->max_mem );
228
+
229
+ bcf_destroy(rec);
230
+ }
231
+
232
+ void sort_blocks(args_t *args)
233
+ {
234
+ htsFile *in = hts_open(args->fname, "r");
235
+ if ( !in ) clean_files_and_throw(args, "Could not read %s\n", args->fname);
236
+ args->hdr = bcf_hdr_read(in);
237
+ if ( !args->hdr) clean_files_and_throw(args, "Could not read VCF/BCF headers from %s\n", args->fname);
238
+
239
+ while ( 1 )
240
+ {
241
+ bcf1_t *rec = bcf_init();
242
+ int ret = bcf_read1(in, args->hdr, rec);
243
+ if ( ret < -1 ) clean_files_and_throw(args,"Error encountered while parsing the input\n");
244
+ if ( ret == -1 )
245
+ {
246
+ bcf_destroy(rec);
247
+ break;
248
+ }
249
+ if ( rec->errcode ) clean_files_and_throw(args,"Error encountered while parsing the input at %s:%d\n",bcf_seqname(args->hdr,rec),rec->pos+1);
250
+ bcf_unpack(rec, BCF_UN_STR);
251
+ buf_push(args, rec);
252
+ }
253
+ buf_flush(args);
254
+ free(args->buf);
255
+
256
+ if ( hts_close(in)!=0 ) clean_files_and_throw(args,"Close failed: %s\n", args->fname);
257
+ }
258
+
259
+ static inline int blk_is_smaller(blk_t **aptr, blk_t **bptr)
260
+ {
261
+ blk_t *a = *aptr;
262
+ blk_t *b = *bptr;
263
+ int ret = cmp_bcf_pos(&a->rec, &b->rec);
264
+ if ( ret < 0 ) return 1;
265
+ return 0;
266
+ }
267
+ KHEAP_INIT(blk, blk_t*, blk_is_smaller)
268
+
269
+ void blk_read(args_t *args, khp_blk_t *bhp, bcf_hdr_t *hdr, blk_t *blk)
270
+ {
271
+ if ( !blk->fh ) return;
272
+ int ret = bcf_read(blk->fh, hdr, blk->rec);
273
+ if ( ret < -1 ) clean_files_and_throw(args, "Error reading %s\n", blk->fname);
274
+ if ( ret == -1 )
275
+ {
276
+ if ( hts_close(blk->fh)!=0 ) clean_files_and_throw(args, "Close failed: %s\n", blk->fname);
277
+ blk->fh = 0;
278
+ return;
279
+ }
280
+ bcf_unpack(blk->rec, BCF_UN_STR);
281
+ khp_insert(blk, bhp, &blk);
282
+ }
283
+
284
+ void merge_blocks(args_t *args)
285
+ {
286
+ fprintf(stderr,"Merging %d temporary files\n", (int)args->nblk);
287
+ khp_blk_t *bhp = khp_init(blk);
288
+
289
+ int i;
290
+ for (i=0; i<args->nblk; i++)
291
+ {
292
+ blk_t *blk = args->blk + i;
293
+ blk->fh = hts_open(blk->fname, "r");
294
+ if ( !blk->fh ) clean_files_and_throw(args, "Could not read %s: %s\n", blk->fname, strerror(errno));
295
+ bcf_hdr_t *hdr = bcf_hdr_read(blk->fh);
296
+ bcf_hdr_destroy(hdr);
297
+ blk->rec = bcf_init();
298
+ blk_read(args, bhp, args->hdr, blk);
299
+ }
300
+
301
+ char wmode[8];
302
+ set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
303
+ htsFile *out = hts_open(args->output_fname ? args->output_fname : "-", wmode);
304
+ if ( bcf_hdr_write(out, args->hdr)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,args->output_fname);
305
+ if ( args->write_index && init_index(out,args->hdr,args->output_fname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->output_fname);
306
+ while ( bhp->ndat )
307
+ {
308
+ blk_t *blk = bhp->dat[0];
309
+ if ( bcf_write(out, args->hdr, blk->rec)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,args->output_fname);
310
+ khp_delete(blk, bhp);
311
+ blk_read(args, bhp, args->hdr, blk);
312
+ }
313
+ if ( args->write_index )
314
+ {
315
+ if ( bcf_idx_save(out)<0 )
316
+ {
317
+ if ( hts_close(out)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout");
318
+ error("Error: cannot write to index %s\n", args->index_fn);
319
+ }
320
+ free(args->index_fn);
321
+ }
322
+ if ( hts_close(out)!=0 ) clean_files_and_throw(args, "Close failed: %s\n", args->output_fname);
323
+
324
+ clean_files(args);
325
+
326
+ free(args->blk);
327
+ khp_destroy(blk, bhp);
328
+ fprintf(stderr,"Done\n");
329
+ }
330
+
331
+ static void usage(args_t *args)
332
+ {
333
+ fprintf(stderr, "\n");
334
+ fprintf(stderr, "About: Sort VCF/BCF file.\n");
335
+ fprintf(stderr, "Usage: bcftools sort [OPTIONS] <FILE.vcf>\n");
336
+ fprintf(stderr, "\n");
337
+ fprintf(stderr, "Options:\n");
338
+ fprintf(stderr, " -m, --max-mem FLOAT[kMG] maximum memory to use [768M]\n"); // using metric units, 1M=1e6
339
+ fprintf(stderr, " -o, --output FILE output file name [stdout]\n");
340
+ fprintf(stderr, " -O, --output-type b|u|z|v b: compressed BCF, u: uncompressed BCF, z: compressed VCF, v: uncompressed VCF [v]\n");
341
+ fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
342
+
343
+ #ifdef _WIN32
344
+ fprintf(stderr, " -T, --temp-dir DIR temporary files [/bcftools.XXXXXX]\n");
345
+ #else
346
+ fprintf(stderr, " -T, --temp-dir DIR temporary files [/tmp/bcftools.XXXXXX]\n");
347
+ #endif
348
+ fprintf(stderr, " --write-index Automatically index the output files [off]\n");
349
+ fprintf(stderr, "\n");
350
+ exit(1);
351
+ }
352
+
353
+ size_t parse_mem_string(const char *str)
354
+ {
355
+ char *tmp;
356
+ double mem = strtod(str, &tmp);
357
+ if ( tmp==str ) error("Could not parse the memory string: \"%s\"\n", str);
358
+ if ( !strcasecmp("k",tmp) ) mem *= 1000;
359
+ else if ( !strcasecmp("m",tmp) ) mem *= 1000*1000;
360
+ else if ( !strcasecmp("g",tmp) ) mem *= 1000*1000*1000;
361
+ return mem;
362
+ }
363
+
364
+ void mkdir_p(const char *fmt, ...);
365
+ static void init(args_t *args)
366
+ {
367
+ args->max_mem *= 0.9;
368
+ args->mem_block = malloc(args->max_mem);
369
+ if ( !args->mem_block ) error("Error: could not allocate %zu bytes of memory, try reducing --max-mem\n",args->max_mem);
370
+ args->mem = 0;
371
+
372
+ args->tmp_dir = init_tmp_prefix(args->tmp_dir);
373
+
374
+ #ifdef _WIN32
375
+ int ret = mkdir(mktemp(args->tmp_dir), 0700);
376
+ if ( ret ) error("mkdir(%s) failed: %s\n", args->tmp_dir,strerror(errno));
377
+ #else
378
+ char *tmp = mkdtemp(args->tmp_dir);
379
+ if ( !tmp ) error("mkdtemp(%s) failed: %s\n", args->tmp_dir,strerror(errno));
380
+ int ret = chmod(tmp, S_IRUSR|S_IWUSR|S_IXUSR);
381
+ if ( ret ) error("chmod(%s,S_IRUSR|S_IWUSR|S_IXUSR) failed: %s\n", args->tmp_dir,strerror(errno));
382
+ #endif
383
+
384
+ fprintf(stderr,"Writing to %s\n", args->tmp_dir);
385
+ }
386
+ static void destroy(args_t *args)
387
+ {
388
+ bcf_hdr_destroy(args->hdr);
389
+ free(args->mem_block);
390
+ free(args->tmp_dir);
391
+ free(args);
392
+ }
393
+
394
+ int main_sort(int argc, char *argv[])
395
+ {
396
+ int c;
397
+ args_t *args = (args_t*) calloc(1,sizeof(args_t));
398
+ args->argc = argc; args->argv = argv;
399
+ args->max_mem = 768*1000*1000;
400
+ args->output_fname = "-";
401
+ args->clevel = -1;
402
+
403
+ static struct option loptions[] =
404
+ {
405
+ {"max-mem",required_argument,NULL,'m'},
406
+ {"temp-dir",required_argument,NULL,'T'},
407
+ {"output-type",required_argument,NULL,'O'},
408
+ {"output-file",required_argument,NULL,'o'},
409
+ {"output",required_argument,NULL,'o'},
410
+ {"help",no_argument,NULL,'h'},
411
+ {"write-index",no_argument,NULL,1},
412
+ {0,0,0,0}
413
+ };
414
+ char *tmp;
415
+ while ((c = getopt_long(argc, argv, "m:T:O:o:h?",loptions,NULL)) >= 0)
416
+ {
417
+ switch (c)
418
+ {
419
+ case 'm': args->max_mem = parse_mem_string(optarg); break;
420
+ case 'T': args->tmp_dir = optarg; break;
421
+ case 'o': args->output_fname = optarg; break;
422
+ case 'O':
423
+ switch (optarg[0]) {
424
+ case 'b': args->output_type = FT_BCF_GZ; break;
425
+ case 'u': args->output_type = FT_BCF; break;
426
+ case 'z': args->output_type = FT_VCF_GZ; break;
427
+ case 'v': args->output_type = FT_VCF; break;
428
+ default:
429
+ {
430
+ args->clevel = strtol(optarg,&tmp,10);
431
+ if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
432
+ }
433
+ };
434
+ if ( optarg[1] )
435
+ {
436
+ args->clevel = strtol(optarg+1,&tmp,10);
437
+ if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
438
+ }
439
+ break;
440
+ case 1 : args->write_index = 1; break;
441
+ case 'h':
442
+ case '?': usage(args); break;
443
+ default: error("Unknown argument: %s\n", optarg);
444
+ }
445
+ }
446
+
447
+ if ( optind>=argc )
448
+ {
449
+ if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-"; // reading from stdin
450
+ else usage(args);
451
+ }
452
+ else args->fname = argv[optind];
453
+
454
+ init(args);
455
+ sort_blocks(args);
456
+ merge_blocks(args);
457
+ destroy(args);
458
+
459
+ return 0;
460
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/amplicon_stats.c.pysam.c ADDED
@@ -0,0 +1,1758 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* stats.c -- This is the former bamcheck integrated into samtools/htslib.
4
+
5
+ Copyright (C) 2020-2021 Genome Research Ltd.
6
+
7
+ Author: James Bonfield <jkb@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ /*
28
+ * This tool is designed to give "samtools stats" style output, but dedicated
29
+ * to small amplicon sequencing projects. It gathers stats on the
30
+ * distribution of reads across amplicons.
31
+ */
32
+
33
+ /*
34
+ * TODO:
35
+ * - Cope with multiple references. What do we do here? Just request one?
36
+ * - Permit regions rather than consuming whole file (maybe solves above).
37
+ */
38
+
39
+ #include <config.h>
40
+ #include <stdio.h>
41
+ #include <stdlib.h>
42
+ #include <string.h>
43
+ #include <inttypes.h>
44
+ #include <getopt.h>
45
+ #include <unistd.h>
46
+ #include <math.h>
47
+
48
+ #include <htslib/sam.h>
49
+ #include <htslib/khash.h>
50
+
51
+ #include "samtools.h"
52
+ #include "sam_opts.h"
53
+ #include "bam_ampliconclip.h"
54
+
55
+ KHASH_MAP_INIT_INT64(tcoord, int64_t)
56
+ KHASH_MAP_INIT_STR(qname, int64_t)
57
+
58
+ #ifndef MIN
59
+ #define MIN(a,b) ((a)<(b)?(a):(b))
60
+ #endif
61
+
62
+ #ifndef MAX
63
+ #define MAX(a,b) ((a)>(b)?(a):(b))
64
+ #endif
65
+
66
+ #ifndef ABS
67
+ #define ABS(a) ((a)>=0?(a):-(a))
68
+ #endif
69
+
70
+ #define TCOORD_MIN_COUNT 10
71
+ #define MAX_AMP 1000 // Default maximum number of amplicons
72
+ #define MAX_AMP_LEN 1000 // Default maximum length of any single amplicon
73
+ #define MAX_PRIMER_PER_AMPLICON 4 // Max primers per LEFT/RIGHT
74
+ #define MAX_DEPTH 5 // Number of different depths permitted
75
+
76
+ typedef struct {
77
+ sam_global_args ga;
78
+ uint32_t flag_require;
79
+ uint32_t flag_filter;
80
+ int max_delta; // Used for matching read to amplicon primer loc
81
+ int min_depth[MAX_DEPTH]; // Used for coverage; must be >= min_depth deep
82
+ int use_sample_name;
83
+ int max_amp; // Total number of amplicons
84
+ int max_amp_len; // Maximum length of an individual amplicon
85
+ double depth_bin;// aggregate depth within this fraction
86
+ int tlen_adj; // Adjust tlen by this amount, due to clip but no fixmate
87
+ FILE *out_fp;
88
+ char *argv;
89
+ int tcoord_min_count;
90
+ int tcoord_bin;
91
+ int multi_ref;
92
+ } astats_args_t;
93
+
94
+ typedef struct {
95
+ int nseq; // total sequence count
96
+ int nfiltered; // sequence filtered
97
+ int nfailprimer;// count of sequences not matching the primer locations
98
+
99
+ // Sizes of memory allocated below, to permit reset
100
+ int max_amp, max_amp_len, max_len;
101
+
102
+ // Summary across all samples, sum(x) plus sum(x^2) for s.d. calc
103
+ int64_t *nreads, *nreads2; // [max_amp]
104
+ double *nfull_reads; // [max_amp]; 0.5/read if paired.
105
+ double *nrperc, *nrperc2; // [max_amp]
106
+ int64_t *nbases, *nbases2; // [max_amp]
107
+ int64_t *coverage; // [max_amp][max_amp_len]
108
+ double (*covered_perc)[MAX_DEPTH]; // [max_amp][MAX_DEPTH]
109
+ double (*covered_perc2)[MAX_DEPTH];// [max_amp][MAX_DEPTH];
110
+ khash_t(tcoord) **tcoord; // [max_amp+1]
111
+
112
+ // 0 is correct pair, 1 is incorrect pair, 2 is unidentified
113
+ int (*amp_dist)[3]; // [MAX_AMP][3];
114
+
115
+ int *depth_valid; // [max_len]
116
+ int *depth_all; // [max_len]
117
+ khash_t(qname) *qend; // queryname end, for overlap removal
118
+ } astats_t;
119
+
120
+ // We can have multiple primers for LEFT / RIGHT, so this
121
+ // permits detection by any compatible combination.
122
+ // One reference:
123
+ typedef struct {
124
+ int64_t left[MAX_PRIMER_PER_AMPLICON];
125
+ int nleft;
126
+ int64_t right[MAX_PRIMER_PER_AMPLICON];
127
+ int nright;
128
+ int64_t max_left, min_right; // inner dimensions
129
+ int64_t min_left, max_right; // outer dimensions
130
+ } amplicon_t;
131
+
132
+ // Multiple references, we have an array of amplicons_t - one per used ref.
133
+ // We have per reference local and global stats here, as some of the stats
134
+ // are coordinate based. However we report them combined together as a single
135
+ // list across all references.
136
+ // "namp" is the number of amplicons in this reference, but they're
137
+ // numbered first_amp to first_amp+namp-1 inclusively.
138
+ typedef struct {
139
+ int tid, namp;
140
+ int64_t len;
141
+ bed_entry_list_t *sites;
142
+ amplicon_t *amp;
143
+ astats_t *lstats, *gstats; // local (1 file) and global (all file) stats
144
+ const char *ref; // ref name (pointer to the bed hash table key)
145
+ int first_amp; // first amplicon number for this ref
146
+ } amplicons_t;
147
+
148
+ // Reinitialised for each new reference/chromosome.
149
+ // Counts from 1 to namp, -1 for no match and 0 for ?.
150
+ static int *pos2start = NULL;
151
+ static int *pos2end = NULL;
152
+ static int pos2size = 0; // allocated size of pos2start/end
153
+
154
+ // Lookup table to go from position to amplicon based on
155
+ // read start / end.
156
+ static int initialise_amp_pos_lookup(astats_args_t *args,
157
+ amplicons_t *amps,
158
+ int ref) {
159
+ int64_t i, j;
160
+ amplicon_t *amp = amps[ref].amp;
161
+ int64_t max_len = amps[ref].len;
162
+ int namp = amps[ref].namp;
163
+
164
+ if (max_len+1 > pos2size) {
165
+ if (!(pos2start = realloc(pos2start, (max_len+1)*sizeof(*pos2start))))
166
+ return -1;
167
+ if (!(pos2end = realloc(pos2end, (max_len+1)*sizeof(*pos2end))))
168
+ return -1;
169
+ pos2size = max_len;
170
+ }
171
+ for (i = 0; i < max_len; i++)
172
+ pos2start[i] = pos2end[i] = -1;
173
+
174
+ for (i = 0; i < namp; i++) {
175
+ for (j = 0; j < amp[i].nleft; j++) {
176
+ int64_t p;
177
+ for (p = amp[i].left[j] - args->max_delta;
178
+ p <= amp[i].left[j] + args->max_delta; p++) {
179
+ if (p < 1 || p > max_len)
180
+ continue;
181
+ pos2start[p-1] = i;
182
+ }
183
+ }
184
+ for (j = 0; j < amp[i].nright; j++) {
185
+ int64_t p;
186
+ for (p = amp[i].right[j] - args->max_delta;
187
+ p <= amp[i].right[j] + args->max_delta; p++) {
188
+ if (p < 1 || p > max_len)
189
+ continue;
190
+ pos2end[p-1] = i;
191
+ }
192
+ }
193
+ }
194
+
195
+ return 0;
196
+ }
197
+
198
+ // Counts amplicons.
199
+ // Assumption: input BED file alternates between LEFT and RIGHT primers
200
+ // per amplicon, thus we can count the number based on the switching
201
+ // orientation.
202
+ static int count_amplicon(bed_entry_list_t *sites) {
203
+ int i, namp, last_rev = 0;
204
+ for (i = namp = 0; i < sites->length; i++) {
205
+ if (sites->bp[i].rev == 0 && last_rev)
206
+ namp++;
207
+ last_rev = sites->bp[i].rev;
208
+ }
209
+
210
+ return ++namp;
211
+ }
212
+
213
+ // We're only interest in the internal part of the amplicon.
214
+ // Our bed file has LEFT start/end followed by RIGHT start/end,
215
+ // so collapse these to LEFT end / RIGHT start.
216
+ //
217
+ // Returns right most amplicon position on success,
218
+ // < 0 on error
219
+ static int64_t bed2amplicon(astats_args_t *args, bed_entry_list_t *sites,
220
+ amplicon_t *amp, int *namp, int do_title,
221
+ const char *ref, int first_amp) {
222
+ int i, j;
223
+ int64_t max_right = 0;
224
+ FILE *ofp = args->out_fp;
225
+
226
+ *namp = 0;
227
+
228
+ // Assume all primers for the same amplicon are adjacent in BED
229
+ // with all + followed by all -. Thus - to + signifies next primer set.
230
+ int last_rev = 0;
231
+ amp[0].max_left = 0;
232
+ amp[0].min_right = INT64_MAX;
233
+ amp[0].min_left = INT64_MAX;
234
+ amp[0].max_right = 0;
235
+ if (do_title) {
236
+ fprintf(ofp, "# Amplicon locations from BED file.\n");
237
+ fprintf(ofp, "# LEFT/RIGHT are <start>-<end> format and "
238
+ "comma-separated for alt-primers.\n");
239
+ if (args->multi_ref)
240
+ fprintf(ofp, "#\n# AMPLICON\tREF\tNUMBER\tLEFT\tRIGHT\n");
241
+ else
242
+ fprintf(ofp, "#\n# AMPLICON\tNUMBER\tLEFT\tRIGHT\n");
243
+ }
244
+ for (i = j = 0; i < sites->length; i++) {
245
+ if (i == 0 && sites->bp[i].rev != 0) {
246
+ fprintf(samtools_stderr, "[ampliconstats] error: BED file should start"
247
+ " with the + strand primer\n");
248
+ return -1;
249
+ }
250
+ if (sites->bp[i].rev == 0 && last_rev) {
251
+ j++;
252
+ if (j >= args->max_amp) {
253
+ fprintf(samtools_stderr, "[ampliconstats] error: too many amplicons"
254
+ " (%d). Use -a option to raise this.\n", j);
255
+ return -1;
256
+ }
257
+ amp[j].max_left = 0;
258
+ amp[j].min_right = INT64_MAX;
259
+ amp[j].min_left = INT64_MAX;
260
+ amp[j].max_right = 0;
261
+ }
262
+ if (sites->bp[i].rev == 0) {
263
+ if (i == 0 || last_rev) {
264
+ if (j>0) fprintf(ofp, "\n");
265
+ if (args->multi_ref)
266
+ fprintf(ofp, "AMPLICON\t%s\t%d", ref, j+1 + first_amp);
267
+ else
268
+ fprintf(ofp, "AMPLICON\t%d", j+1);
269
+ }
270
+ if (amp[j].nleft >= MAX_PRIMER_PER_AMPLICON) {
271
+ print_error_errno("ampliconstats",
272
+ "too many primers per amplicon (%d).\n",
273
+ MAX_PRIMER_PER_AMPLICON);
274
+ return -1;
275
+ }
276
+ amp[j].left[amp[j].nleft++] = sites->bp[i].right;
277
+ if (amp[j].max_left < sites->bp[i].right+1)
278
+ amp[j].max_left = sites->bp[i].right+1;
279
+ if (amp[j].min_left > sites->bp[i].right+1)
280
+ amp[j].min_left = sites->bp[i].right+1;
281
+ // BED file, so left+1 as zero based. right(+1-1) as
282
+ // BED goes one beyond end (and we want inclusive range).
283
+ fprintf(ofp, "%c%"PRId64"-%"PRId64, "\t,"[amp[j].nleft > 1],
284
+ sites->bp[i].left+1, sites->bp[i].right);
285
+ } else {
286
+ if (amp[j].nright >= MAX_PRIMER_PER_AMPLICON) {
287
+ print_error_errno("ampliconstats",
288
+ "too many primers per amplicon (%d)",
289
+ MAX_PRIMER_PER_AMPLICON);
290
+ return -1;
291
+ }
292
+ amp[j].right[amp[j].nright++] = sites->bp[i].left;
293
+ if (amp[j].min_right > sites->bp[i].left-1)
294
+ amp[j].min_right = sites->bp[i].left-1;
295
+ if (amp[j].max_right < sites->bp[i].left-1) {
296
+ amp[j].max_right = sites->bp[i].left-1;
297
+ if (amp[j].max_right - amp[j].min_left + 1 >=
298
+ args->max_amp_len) {
299
+ fprintf(samtools_stderr, "[ampliconstats] error: amplicon "
300
+ "longer (%d) than max_amp_len option (%d)\n",
301
+ (int)(amp[j].max_right - amp[j].min_left + 2),
302
+ args->max_amp_len);
303
+ return -1;
304
+ }
305
+ if (max_right < amp[j].max_right)
306
+ max_right = amp[j].max_right;
307
+ }
308
+ fprintf(ofp, "%c%"PRId64"-%"PRId64, "\t,"[amp[j].nright > 1],
309
+ sites->bp[i].left+1, sites->bp[i].right);
310
+ }
311
+ last_rev = sites->bp[i].rev;
312
+ }
313
+ if (last_rev != 1) {
314
+ fprintf(ofp, "\n"); // useful if going to samtools_stdout
315
+ fprintf(samtools_stderr, "[ampliconstats] error: bed file does not end on"
316
+ " a reverse strand primer.\n");
317
+ return -1;
318
+ }
319
+ *namp = ++j;
320
+ if (j) fprintf(ofp, "\n");
321
+
322
+ if (j >= args->max_amp) {
323
+ fprintf(samtools_stderr, "[ampliconstats] error: "
324
+ "too many amplicons (%d). Use -a option to raise this.", j);
325
+ return -1;
326
+ }
327
+
328
+ // for (i = 0; i < *namp; i++) {
329
+ // fprintf(samtools_stdout, "%d\t%ld", i, amp[i].length);
330
+ // for (j = 0; j < amp[i].nleft; j++)
331
+ // fprintf(samtools_stdout, "%c%ld", "\t,"[j>0], amp[i].left[j]);
332
+ // for (j = 0; j < amp[i].nright; j++)
333
+ // fprintf(samtools_stdout, "%c%ld", "\t,"[j>0], amp[i].right[j]);
334
+ // fprintf(samtools_stdout, "\n");
335
+ // }
336
+
337
+ return max_right;
338
+ }
339
+
340
+ void stats_free(astats_t *st) {
341
+ if (!st)
342
+ return;
343
+
344
+ free(st->nreads);
345
+ free(st->nreads2);
346
+ free(st->nfull_reads);
347
+ free(st->nrperc);
348
+ free(st->nrperc2);
349
+ free(st->nbases);
350
+ free(st->nbases2);
351
+ free(st->coverage);
352
+ free(st->covered_perc);
353
+ free(st->covered_perc2);
354
+ free(st->amp_dist);
355
+
356
+ free(st->depth_valid);
357
+ free(st->depth_all);
358
+
359
+ if (st->tcoord) {
360
+ int i;
361
+ for (i = 0; i <= st->max_amp; i++) {
362
+ if (st->tcoord[i])
363
+ kh_destroy(tcoord, st->tcoord[i]);
364
+ }
365
+ free(st->tcoord);
366
+ }
367
+
368
+ khiter_t k;
369
+ for (k = kh_begin(st->qend); k != kh_end(st->qend); k++)
370
+ if (kh_exist(st->qend, k))
371
+ free((void *)kh_key(st->qend, k));
372
+ kh_destroy(qname, st->qend);
373
+
374
+ free(st);
375
+ }
376
+
377
+ astats_t *stats_alloc(int64_t max_len, int max_amp, int max_amp_len) {
378
+ astats_t *st = calloc(1, sizeof(*st));
379
+ if (!st)
380
+ return NULL;
381
+
382
+ st->max_amp = max_amp;
383
+ st->max_amp_len = max_amp_len;
384
+ st->max_len = max_len;
385
+
386
+ if (!(st->nreads = calloc(max_amp, sizeof(*st->nreads)))) goto err;
387
+ if (!(st->nreads2 = calloc(max_amp, sizeof(*st->nreads2)))) goto err;
388
+ if (!(st->nrperc = calloc(max_amp, sizeof(*st->nrperc)))) goto err;
389
+ if (!(st->nrperc2 = calloc(max_amp, sizeof(*st->nrperc2)))) goto err;
390
+ if (!(st->nbases = calloc(max_amp, sizeof(*st->nbases)))) goto err;
391
+ if (!(st->nbases2 = calloc(max_amp, sizeof(*st->nbases2)))) goto err;
392
+
393
+ if (!(st->nfull_reads = calloc(max_amp, sizeof(*st->nfull_reads))))
394
+ goto err;
395
+
396
+ if (!(st->coverage = calloc(max_amp*max_amp_len, sizeof(*st->coverage))))
397
+ goto err;
398
+
399
+ if (!(st->covered_perc = calloc(max_amp, sizeof(*st->covered_perc))))
400
+ goto err;
401
+ if (!(st->covered_perc2 = calloc(max_amp, sizeof(*st->covered_perc2))))
402
+ goto err;
403
+
404
+ if (!(st->tcoord = calloc(max_amp+1, sizeof(*st->tcoord)))) goto err;
405
+ int i;
406
+ for (i = 0; i <= st->max_amp; i++)
407
+ if (!(st->tcoord[i] = kh_init(tcoord)))
408
+ goto err;
409
+
410
+ if (!(st->qend = kh_init(qname)))
411
+ goto err;
412
+
413
+ if (!(st->depth_valid = calloc(max_len, sizeof(*st->depth_valid))))
414
+ goto err;
415
+ if (!(st->depth_all = calloc(max_len, sizeof(*st->depth_all))))
416
+ goto err;
417
+
418
+ if (!(st->amp_dist = calloc(max_amp, sizeof(*st->amp_dist)))) goto err;
419
+
420
+ return st;
421
+
422
+ err:
423
+ stats_free(st);
424
+ return NULL;
425
+ }
426
+
427
+ static void stats_reset(astats_t *st) {
428
+ st->nseq = 0;
429
+ st->nfiltered = 0;
430
+ st->nfailprimer = 0;
431
+
432
+ memset(st->nreads, 0, st->max_amp * sizeof(*st->nreads));
433
+ memset(st->nreads2, 0, st->max_amp * sizeof(*st->nreads2));
434
+ memset(st->nfull_reads, 0, st->max_amp * sizeof(*st->nfull_reads));
435
+
436
+ memset(st->nrperc, 0, st->max_amp * sizeof(*st->nrperc));
437
+ memset(st->nrperc2, 0, st->max_amp * sizeof(*st->nrperc2));
438
+
439
+ memset(st->nbases, 0, st->max_amp * sizeof(*st->nbases));
440
+ memset(st->nbases2, 0, st->max_amp * sizeof(*st->nbases2));
441
+
442
+ memset(st->coverage, 0, st->max_amp * st->max_amp_len
443
+ * sizeof(*st->coverage));
444
+ memset(st->covered_perc, 0, st->max_amp * sizeof(*st->covered_perc));
445
+ memset(st->covered_perc2, 0, st->max_amp * sizeof(*st->covered_perc2));
446
+
447
+ // Keep the allocated entries as it's likely all files will share
448
+ // the same keys. Instead we reset counters to zero for common ones
449
+ // and delete rare ones.
450
+ int i;
451
+ for (i = 0; i <= st->max_amp; i++) {
452
+ khiter_t k;
453
+ for (k = kh_begin(st->tcoord[i]);
454
+ k != kh_end(st->tcoord[i]); k++)
455
+ if (kh_exist(st->tcoord[i], k)) {
456
+ if (kh_value(st->tcoord[i], k) < 5)
457
+ kh_del(tcoord, st->tcoord[i], k);
458
+ else
459
+ kh_value(st->tcoord[i], k) = 0;
460
+ }
461
+ }
462
+
463
+ khiter_t k;
464
+ for (k = kh_begin(st->qend); k != kh_end(st->qend); k++)
465
+ if (kh_exist(st->qend, k))
466
+ free((void *)kh_key(st->qend, k));
467
+ kh_clear(qname, st->qend);
468
+
469
+ memset(st->depth_valid, 0, st->max_len * sizeof(*st->depth_valid));
470
+ memset(st->depth_all, 0, st->max_len * sizeof(*st->depth_all));
471
+ memset(st->amp_dist, 0, st->max_amp * sizeof(*st->amp_dist));
472
+ }
473
+
474
+ static void amp_stats_reset(amplicons_t *amps, int nref) {
475
+ int i;
476
+ for (i = 0; i < nref; i++) {
477
+ if (!amps[i].sites)
478
+ continue;
479
+ stats_reset(amps[i].lstats);
480
+ }
481
+ }
482
+
483
+ static int accumulate_stats(astats_args_t *args, amplicons_t *amps,
484
+ bam1_t *b) {
485
+ int ref = b->core.tid;
486
+ amplicon_t *amp = amps[ref].amp;
487
+ astats_t *stats = amps[ref].lstats;
488
+ int len = amps[ref].len;
489
+
490
+ if (!stats)
491
+ return 0;
492
+
493
+ stats->nseq++;
494
+ if ((b->core.flag & args->flag_require) != args->flag_require ||
495
+ (b->core.flag & args->flag_filter) != 0) {
496
+ stats->nfiltered++;
497
+ return 0;
498
+ }
499
+
500
+ int64_t start = b->core.pos, mstart = start; // modified start
501
+ int64_t end = bam_endpos(b), i;
502
+
503
+ // Compute all-template-depth and valid-template-depth.
504
+ // We track current end location per read name so we can remove overlaps.
505
+ // Potentially we could use this data for a better amplicon-depth
506
+ // count too, but for now it's purely for the per-base plots.
507
+ int ret;
508
+ khiter_t k;
509
+ int prev_start = 0, prev_end = 0;
510
+ if ((b->core.flag & BAM_FPAIRED)
511
+ && !(b->core.flag & (BAM_FSUPPLEMENTARY | BAM_FSECONDARY))) {
512
+ k = kh_put(qname, stats->qend, bam_get_qname(b), &ret);
513
+ if (ret == 0) {
514
+ prev_start = kh_value(stats->qend, k) & 0xffffffff;
515
+ prev_end = kh_value(stats->qend, k)>>32;
516
+ mstart = MAX(mstart, prev_end);
517
+ // Ideally we'd reuse strings so we don't thrash free/malloc.
518
+ // However let's see if the official way of doing that (malloc
519
+ // itself) is fast enough first.
520
+ free((void *)kh_key(stats->qend, k));
521
+ kh_del(qname, stats->qend, k);
522
+ //fprintf(samtools_stderr, "remove overlap %d to %d\n", (int)start, (int)mstart);
523
+ } else {
524
+ if (!(kh_key(stats->qend, k) = strdup(bam_get_qname(b))))
525
+ return -1;
526
+
527
+ kh_value(stats->qend, k) = start | (end << 32);
528
+ }
529
+ }
530
+ for (i = mstart; i < end && i < len; i++)
531
+ stats->depth_all[i]++;
532
+ if (i < end) {
533
+ print_error("ampliconstats", "record %s overhangs end of reference",
534
+ bam_get_qname(b));
535
+ // But keep going, as it's harmless.
536
+ }
537
+
538
+ // On single ended runs, eg ONT or PacBio, we just use the start/end
539
+ // of the template to assign.
540
+ int anum = (b->core.flag & BAM_FREVERSE) || !(b->core.flag & BAM_FPAIRED)
541
+ ? (end-1 >= 0 && end-1 < len ? pos2end[end-1] : -1)
542
+ : (start >= 0 && start < len ? pos2start[start] : -1);
543
+
544
+ // ivar sometimes soft-clips 100% of the bases.
545
+ // This is essentially unmapped
546
+ if (end == start && (args->flag_filter & BAM_FUNMAP)) {
547
+ stats->nfiltered++;
548
+ return 0;
549
+ }
550
+
551
+ if (anum == -1)
552
+ stats->nfailprimer++;
553
+
554
+ if (anum >= 0) {
555
+ int64_t c = MIN(end,amp[anum].min_right+1) - MAX(start,amp[anum].max_left);
556
+ if (c > 0) {
557
+ stats->nreads[anum]++;
558
+ // NB: ref bases rather than read bases
559
+ stats->nbases[anum] += c;
560
+
561
+ int64_t i;
562
+ if (start < 0) start = 0;
563
+ if (end > len) end = len;
564
+
565
+ int64_t ostart = MAX(start, amp[anum].min_left-1);
566
+ int64_t oend = MIN(end, amp[anum].max_right);
567
+ int64_t offset = amp[anum].min_left-1;
568
+ for (i = ostart; i < oend; i++)
569
+ stats->coverage[anum*stats->max_amp_len + i-offset]++;
570
+ } else {
571
+ stats->nfailprimer++;
572
+ }
573
+ }
574
+
575
+ // Template length in terms of amplicon number to amplicon number.
576
+ // We expect left to right of same amplicon (len 0), but it may go
577
+ // to next amplicon (len 1) or prev (len -1), etc.
578
+ int64_t t_end;
579
+ int oth_anum = -1;
580
+
581
+ if (b->core.flag & BAM_FPAIRED) {
582
+ t_end = (b->core.flag & BAM_FREVERSE ? end : start)
583
+ + b->core.isize;
584
+
585
+ // If we've clipped the primers but not followed up with a fixmates
586
+ // then our start+TLEN will take us to a location which is
587
+ // length(LEFT_PRIMER) + length(RIGHT_PRIMER) too far away.
588
+ //
589
+ // The correct solution is to run samtools fixmate so TLEN is correct.
590
+ // The hacky solution is to fudge the expected tlen by double the
591
+ // average primer length (e.g. 50).
592
+ t_end += b->core.isize > 0 ? -args->tlen_adj : +args->tlen_adj;
593
+
594
+ if (t_end > 0 && t_end < len && b->core.isize != 0)
595
+ oth_anum = (b->core.flag & BAM_FREVERSE)
596
+ ? pos2start[t_end]
597
+ : pos2end[t_end];
598
+ } else {
599
+ // Not paired (see int anum = (REV || !PAIR) ?en :st expr above)
600
+ oth_anum = pos2start[start];
601
+ t_end = end;
602
+ }
603
+
604
+ // We don't want to count our pairs twice.
605
+ // If both left/right are known, count it on left only.
606
+ // If only one is known, we'll only get to this code once
607
+ // so we can also count it.
608
+ int astatus = 2;
609
+ if (anum != -1 && oth_anum != -1) {
610
+ astatus = oth_anum == anum ? 0 : 1;
611
+ if (start <= t_end)
612
+ stats->amp_dist[anum][astatus]++;
613
+ } else if (anum >= 0) {
614
+ stats->amp_dist[anum][astatus = 2]++;
615
+ }
616
+
617
+ if (astatus == 0 && !(b->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))) {
618
+ if (prev_end && mstart > prev_end) {
619
+ // 2nd read with gap to 1st; undo previous increment.
620
+ for (i = prev_start; i < prev_end; i++)
621
+ stats->depth_valid[i]--;
622
+ stats->nfull_reads[anum] -= (b->core.flag & BAM_FPAIRED) ? 0.5 : 1;
623
+ } else {
624
+ // 1st read, or 2nd read that overlaps 1st
625
+ for (i = mstart; i < end; i++)
626
+ stats->depth_valid[i]++;
627
+ stats->nfull_reads[anum] += (b->core.flag & BAM_FPAIRED) ? 0.5 : 1;
628
+ }
629
+ }
630
+
631
+ // Track template start,end frequencies, so we can give stats on
632
+ // amplicon primer usage.
633
+ if ((b->core.flag & BAM_FPAIRED) && b->core.isize <= 0)
634
+ // left to right only, so we don't double count template positions.
635
+ return 0;
636
+
637
+ start = b->core.pos;
638
+ t_end = b->core.flag & BAM_FPAIRED
639
+ ? start + b->core.isize-1
640
+ : end;
641
+ uint64_t tcoord = MIN(start+1, UINT32_MAX) | (MIN(t_end+1, UINT32_MAX)<<32);
642
+ k = kh_put(tcoord, stats->tcoord[anum+1], tcoord, &ret);
643
+ if (ret < 0)
644
+ return -1;
645
+ if (ret == 0)
646
+ kh_value(stats->tcoord[anum+1], k)++;
647
+ else
648
+ kh_value(stats->tcoord[anum+1], k)=1;
649
+ kh_value(stats->tcoord[anum+1], k) |= ((int64_t)astatus<<32);
650
+
651
+ return 0;
652
+ }
653
+
654
+ // Append file local stats to global stats
655
+ int append_lstats(astats_t *lstats, astats_t *gstats, int namp, int all_nseq) {
656
+ gstats->nseq += lstats->nseq;
657
+ gstats->nfiltered += lstats->nfiltered;
658
+ gstats->nfailprimer += lstats->nfailprimer;
659
+
660
+ int a;
661
+ for (a = -1; a < namp; a++) {
662
+ // Add khash local (kl) to khash global (kg)
663
+ khiter_t kl, kg;
664
+ for (kl = kh_begin(lstats->tcoord[a+1]);
665
+ kl != kh_end(lstats->tcoord[a+1]); kl++) {
666
+ if (!kh_exist(lstats->tcoord[a+1], kl) ||
667
+ kh_value(lstats->tcoord[a+1], kl) == 0)
668
+ continue;
669
+
670
+ int ret;
671
+ kg = kh_put(tcoord, gstats->tcoord[a+1],
672
+ kh_key(lstats->tcoord[a+1], kl),
673
+ &ret);
674
+ if (ret < 0)
675
+ return -1;
676
+
677
+ kh_value(gstats->tcoord[a+1], kg) =
678
+ (ret == 0
679
+ ? (kh_value(gstats->tcoord[a+1], kg) & 0xFFFFFFFF)
680
+ : 0)
681
+ + kh_value(lstats->tcoord[a+1], kl);
682
+ }
683
+ if (a == -1) continue;
684
+
685
+ gstats->nreads[a] += lstats->nreads[a];
686
+ gstats->nreads2[a] += lstats->nreads[a] * lstats->nreads[a];
687
+ gstats->nfull_reads[a] += lstats->nfull_reads[a];
688
+
689
+ // To get mean & sd for amplicon read percentage, we need
690
+ // to do the divisions here as nseq differs for each sample.
691
+ double nrperc = all_nseq ? 100.0 * lstats->nreads[a] / all_nseq : 0;
692
+ gstats->nrperc[a] += nrperc;
693
+ gstats->nrperc2[a] += nrperc*nrperc;
694
+
695
+ gstats->nbases[a] += lstats->nbases[a];
696
+ gstats->nbases2[a] += lstats->nbases[a] * lstats->nbases[a];
697
+
698
+ int d;
699
+ for (d = 0; d < MAX_DEPTH; d++) {
700
+ gstats->covered_perc[a][d] += lstats->covered_perc[a][d];
701
+ gstats->covered_perc2[a][d] += lstats->covered_perc[a][d]
702
+ * lstats->covered_perc[a][d];
703
+ }
704
+
705
+ for (d = 0; d < 3; d++)
706
+ gstats->amp_dist[a][d] += lstats->amp_dist[a][d];
707
+ }
708
+
709
+ for (a = 0; a < lstats->max_len; a++) {
710
+ gstats->depth_valid[a] += lstats->depth_valid[a];
711
+ gstats->depth_all[a] += lstats->depth_all[a];
712
+ }
713
+
714
+ return 0;
715
+ }
716
+
717
+ int append_stats(amplicons_t *amps, int nref) {
718
+ int i, r, all_nseq = 0;
719
+ for (r = 0; r < nref; r++) {
720
+ if (!amps[r].sites)
721
+ continue;
722
+ astats_t *stats = amps[r].lstats;
723
+ all_nseq += stats->nseq - stats->nfiltered - stats->nfailprimer;
724
+ }
725
+
726
+ for (i = 0; i < nref; i++) {
727
+ if (!amps[i].sites)
728
+ continue;
729
+ if (append_lstats(amps[i].lstats, amps[i].gstats, amps[i].namp,
730
+ all_nseq) < 0)
731
+ return -1;
732
+ }
733
+
734
+ return 0;
735
+ }
736
+
737
+ typedef struct {
738
+ int32_t start, end;
739
+ uint32_t freq;
740
+ uint32_t status;
741
+ } tcoord_t;
742
+
743
+ // Sort tcoord by descending frequency and then ascending start and end.
744
+ static int tcoord_freq_sort(const void *vp1, const void *vp2) {
745
+ const tcoord_t *t1 = (const tcoord_t *)vp1;
746
+ const tcoord_t *t2 = (const tcoord_t *)vp2;
747
+
748
+ if (t1->freq != t2->freq)
749
+ return t2->freq - t1->freq;
750
+
751
+ if (t1->start != t2->start)
752
+ return t1->start - t2->start;
753
+
754
+ return t1->end - t2->end;
755
+ }
756
+
757
+
758
+ /*
759
+ * Merges tcoord start,end,freq,status tuples if their coordinates are
760
+ * close together. We aim to keep the start,end for the most frequent
761
+ * value and assume that is the correct coordinate and all others are
762
+ * minor fluctuations due to errors or variants.
763
+ *
764
+ * We sort by frequency first and then merge later items in the list into
765
+ * the earlier more frequent ones. It's O(N^2), but sufficient for now
766
+ * given current scale of projects.
767
+ *
768
+ * If we ever need to resolve that then consider sorting by start
769
+ * coordinate and scanning the list to find all items within X, find
770
+ * the most frequent of those, and then cluster that way. (I'd have
771
+ * done that had I thought of it at the time!)
772
+ */
773
+ static void aggregate_tcoord(astats_args_t *args, tcoord_t *tpos, size_t *np){
774
+ size_t n = *np, j, j2, j3, k;
775
+
776
+ // Sort by frequency and cluster infrequent coords into frequent
777
+ // ones provided they're close by.
778
+ // This is O(N^2), but we've already binned by tcoord_bin/2 so
779
+ // the list isn't intended to be vast at this point.
780
+ qsort(tpos, n, sizeof(*tpos), tcoord_freq_sort);
781
+
782
+ // For frequency ties, find mid start coord, and then find mid end
783
+ // coord of those matching start.
784
+ // We make that the first item so we merge into that mid point.
785
+ for (j = 0; j < n; j++) {
786
+ for (j2 = j+1; j2 < n; j2++) {
787
+ if (tpos[j].freq != tpos[j2].freq)
788
+ break;
789
+ if (tpos[j2].start - tpos[j].start >= args->tcoord_bin)
790
+ break;
791
+ }
792
+
793
+ // j to j2 all within bin of a common start,
794
+ // m is the mid start.
795
+ if (j2-1 > j) {
796
+ size_t m = (j2-1 + j)/2;
797
+
798
+ // Find mid end for this same start
799
+ while (m > 1 && tpos[m].start == tpos[m-1].start)
800
+ m--;
801
+ for (j3 = m+1; j3 < j2; j3++) {
802
+ if (tpos[m].start != tpos[j3].start)
803
+ break;
804
+ if (tpos[m].end - tpos[j3].end >= args->tcoord_bin)
805
+ break;
806
+ }
807
+ if (j3-1 > m)
808
+ m = (j3-1 + m)/2;
809
+
810
+ // Swap with first item.
811
+ tcoord_t tmp = tpos[j];
812
+ tpos[j] = tpos[m];
813
+ tpos[m] = tmp;
814
+ j = j2-1;
815
+ }
816
+ }
817
+
818
+ // Now merge in coordinates.
819
+ // This bit is O(N^2), so consider binning first to reduce the
820
+ // size of the list if we have excessive positional variation.
821
+ for (k = j = 0; j < n; j++) {
822
+ if (!tpos[j].freq)
823
+ continue;
824
+
825
+ if (k < j)
826
+ tpos[k] = tpos[j];
827
+
828
+ for (j2 = j+1; j2 < n; j2++) {
829
+ if (ABS(tpos[j].start-tpos[j2].start) < args->tcoord_bin/2 &&
830
+ ABS(tpos[j].end -tpos[j2].end) < args->tcoord_bin/2 &&
831
+ tpos[j].status == tpos[j2].status) {
832
+ tpos[k].freq += tpos[j2].freq;
833
+ tpos[j2].freq = 0;
834
+ }
835
+ }
836
+ k++;
837
+ }
838
+
839
+ *np = k;
840
+ }
841
+
842
+ int dump_stats(astats_args_t *args, char type, char *name, int nfile,
843
+ amplicons_t *amps, int nref, int local) {
844
+ int i, r;
845
+ FILE *ofp = args->out_fp;
846
+ tcoord_t *tpos = NULL;
847
+ size_t ntcoord = 0;
848
+
849
+ // summary stats for this sample (or for all samples)
850
+ fprintf(ofp, "# Summary stats.\n");
851
+ fprintf(ofp, "# Use 'grep ^%cSS | cut -f 2-' to extract this part.\n", type);
852
+
853
+ for (r = 0; r < nref; r++) {
854
+ if (!amps[r].sites)
855
+ continue;
856
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
857
+ int nmatch = stats->nseq - stats->nfiltered - stats->nfailprimer;
858
+ char *name_ref = malloc(strlen(name) + strlen(amps[r].ref) + 2);
859
+ if (!name_ref)
860
+ return -1;
861
+ if (args->multi_ref)
862
+ sprintf(name_ref, "%s\t%s", name, amps[r].ref);
863
+ else
864
+ sprintf(name_ref, "%s", name);
865
+ fprintf(ofp, "%cSS\t%s\traw total sequences:\t%d\n",
866
+ type, name_ref, stats->nseq);
867
+ fprintf(ofp, "%cSS\t%s\tfiltered sequences:\t%d\n",
868
+ type, name_ref, stats->nfiltered);
869
+ fprintf(ofp, "%cSS\t%s\tfailed primer match:\t%d\n",
870
+ type, name_ref, stats->nfailprimer);
871
+ fprintf(ofp, "%cSS\t%s\tmatching sequences:\t%d\n",
872
+ type, name_ref, nmatch);
873
+
874
+ int d = 0;
875
+ do {
876
+ // From first to last amplicon only, so not entire consensus.
877
+ // If contig length is known, maybe we want to add the missing
878
+ // count to < DEPTH figures?
879
+ int64_t start = 0, covered = 0, total = 0;
880
+ amplicon_t *amp = amps[r].amp;
881
+ for (i = 0; i < amps[r].namp; i++) {
882
+ int64_t j, offset = amp[i].min_left-1;
883
+ if (amp[i].min_right - amp[i].min_left > stats->max_amp_len) {
884
+ fprintf(samtools_stderr, "[ampliconstats] error: "
885
+ "Maximum amplicon length (%d) exceeded for '%s'\n",
886
+ stats->max_amp, name);
887
+ return -1;
888
+ }
889
+ for (j = MAX(start, amp[i].max_left-1);
890
+ j < MAX(start, amp[i].min_right); j++) {
891
+ if (stats->coverage[i*stats->max_amp_len + j-offset]
892
+ >= args->min_depth[d])
893
+ covered++;
894
+ total++;
895
+ }
896
+ start = MAX(start, amp[i].min_right);
897
+ }
898
+ fprintf(ofp, "%cSS\t%s\tconsensus depth count < %d and >= %d:\t%"
899
+ PRId64"\t%"PRId64"\n", type, name_ref,
900
+ args->min_depth[d], args->min_depth[d],
901
+ total-covered, covered);
902
+ } while (++d < MAX_DEPTH && args->min_depth[d]);
903
+
904
+ free(name_ref);
905
+ }
906
+
907
+ // Read count
908
+ fprintf(ofp, "# Absolute matching read counts per amplicon.\n");
909
+ fprintf(ofp, "# Use 'grep ^%cREADS | cut -f 2-' to extract this part.\n", type);
910
+ fprintf(ofp, "%cREADS\t%s", type, name);
911
+ for (r = 0; r < nref; r++) {
912
+ if (!amps[r].sites)
913
+ continue;
914
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
915
+ for (i = 0; i < amps[r].namp; i++) {
916
+ fprintf(ofp, "\t%"PRId64, stats->nreads[i]);
917
+ }
918
+ }
919
+ fprintf(ofp, "\n");
920
+
921
+ // Valid depth is the number of full length reads (already divided
922
+ // by the number we expect to cover), so +0.5 per read in pair.
923
+ // A.k.a "usable depth" in the plots.
924
+ fprintf(ofp, "%cVDEPTH\t%s", type, name);
925
+ for (r = 0; r < nref; r++) {
926
+ if (!amps[r].sites)
927
+ continue;
928
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
929
+ for (i = 0; i < amps[r].namp; i++)
930
+ fprintf(ofp, "\t%d", (int)stats->nfull_reads[i]);
931
+ }
932
+ fprintf(ofp, "\n");
933
+
934
+ if (type == 'C') {
935
+ // For combined we can compute mean & standard deviation too
936
+ fprintf(ofp, "CREADS\tMEAN");
937
+ for (r = 0; r < nref; r++) {
938
+ if (!amps[r].sites)
939
+ continue;
940
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
941
+ for (i = 0; i < amps[r].namp; i++) {
942
+ fprintf(ofp, "\t%.1f", stats->nreads[i] / (double)nfile);
943
+ }
944
+ }
945
+ fprintf(ofp, "\n");
946
+
947
+ fprintf(ofp, "CREADS\tSTDDEV");
948
+ for (r = 0; r < nref; r++) {
949
+ if (!amps[r].sites)
950
+ continue;
951
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
952
+ for (i = 0; i < amps[r].namp; i++) {
953
+ double n1 = stats->nreads[i];
954
+ fprintf(ofp, "\t%.1f", nfile > 1 && stats->nreads2[i] > 0
955
+ ? sqrt(stats->nreads2[i]/(double)nfile
956
+ - (n1/nfile)*(n1/nfile))
957
+ : 0);
958
+ }
959
+ }
960
+ fprintf(ofp, "\n");
961
+ }
962
+
963
+ fprintf(ofp, "# Read percentage of distribution between amplicons.\n");
964
+ fprintf(ofp, "# Use 'grep ^%cRPERC | cut -f 2-' to extract this part.\n", type);
965
+ fprintf(ofp, "%cRPERC\t%s", type, name);
966
+ int all_nseq = 0;
967
+ for (r = 0; r < nref; r++) {
968
+ if (!amps[r].sites)
969
+ continue;
970
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
971
+ all_nseq += stats->nseq - stats->nfiltered - stats->nfailprimer;
972
+ }
973
+ for (r = 0; r < nref; r++) {
974
+ if (!amps[r].sites)
975
+ continue;
976
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
977
+ for (i = 0; i < amps[r].namp; i++) {
978
+ if (type == 'C') {
979
+ fprintf(ofp, "\t%.3f", (double)stats->nrperc[i] / nfile);
980
+ } else {
981
+ fprintf(ofp, "\t%.3f",
982
+ all_nseq ? 100.0 * stats->nreads[i] / all_nseq : 0);
983
+ }
984
+ }
985
+ }
986
+ fprintf(ofp, "\n");
987
+
988
+ if (type == 'C') {
989
+ // For combined we compute mean and standard deviation too
990
+ fprintf(ofp, "CRPERC\tMEAN");
991
+ for (r = 0; r < nref; r++) {
992
+ if (!amps[r].sites)
993
+ continue;
994
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
995
+ for (i = 0; i < amps[r].namp; i++) {
996
+ fprintf(ofp, "\t%.3f", stats->nrperc[i] / nfile);
997
+ }
998
+ }
999
+ fprintf(ofp, "\n");
1000
+
1001
+ fprintf(ofp, "CRPERC\tSTDDEV");
1002
+ for (r = 0; r < nref; r++) {
1003
+ if (!amps[r].sites)
1004
+ continue;
1005
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1006
+ for (i = 0; i < amps[r].namp; i++) {
1007
+ // variance = SUM(X^2) - ((SUM(X)^2) / N)
1008
+ double n1 = stats->nrperc[i];
1009
+ double v = stats->nrperc2[i]/nfile - (n1/nfile)*(n1/nfile);
1010
+ fprintf(ofp, "\t%.3f", v>0?sqrt(v):0);
1011
+ }
1012
+ }
1013
+ fprintf(ofp, "\n");
1014
+ }
1015
+
1016
+ // Base depth
1017
+ fprintf(ofp, "# Read depth per amplicon.\n");
1018
+ fprintf(ofp, "# Use 'grep ^%cDEPTH | cut -f 2-' to extract this part.\n", type);
1019
+ fprintf(ofp, "%cDEPTH\t%s", type, name);
1020
+ for (r = 0; r < nref; r++) {
1021
+ if (!amps[r].sites)
1022
+ continue;
1023
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1024
+ amplicon_t *amp = amps[r].amp;
1025
+ for (i = 0; i < amps[r].namp; i++) {
1026
+ int nseq = stats->nseq - stats->nfiltered - stats->nfailprimer;
1027
+ int64_t alen = amp[i].min_right - amp[i].max_left+1;
1028
+ fprintf(ofp, "\t%.1f", nseq ? stats->nbases[i] / (double)alen : 0);
1029
+ }
1030
+ }
1031
+ fprintf(ofp, "\n");
1032
+
1033
+ if (type == 'C') {
1034
+ // For combined we can compute mean & standard deviation too
1035
+ fprintf(ofp, "CDEPTH\tMEAN");
1036
+ for (r = 0; r < nref; r++) {
1037
+ if (!amps[r].sites)
1038
+ continue;
1039
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1040
+ amplicon_t *amp = amps[r].amp;
1041
+ int nseq = stats->nseq - stats->nfiltered - stats->nfailprimer;
1042
+ for (i = 0; i < amps[r].namp; i++) {
1043
+ int64_t alen = amp[i].min_right - amp[i].max_left+1;
1044
+ fprintf(ofp, "\t%.1f", nseq ? stats->nbases[i] / (double)alen / nfile : 0);
1045
+ }
1046
+ }
1047
+ fprintf(ofp, "\n");
1048
+
1049
+ fprintf(ofp, "CDEPTH\tSTDDEV");
1050
+ for (r = 0; r < nref; r++) {
1051
+ if (!amps[r].sites)
1052
+ continue;
1053
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1054
+ amplicon_t *amp = amps[r].amp;
1055
+ for (i = 0; i < amps[r].namp; i++) {
1056
+ double alen = amp[i].min_right - amp[i].max_left+1;
1057
+ double n1 = stats->nbases[i] / alen;
1058
+ double v = stats->nbases2[i] / (alen*alen) /nfile
1059
+ - (n1/nfile)*(n1/nfile);
1060
+ fprintf(ofp, "\t%.1f", v>0?sqrt(v):0);
1061
+ }
1062
+ }
1063
+ fprintf(ofp, "\n");
1064
+ }
1065
+
1066
+ // Percent Coverage
1067
+ if (type == 'F') {
1068
+ fprintf(ofp, "# Percentage coverage per amplicon\n");
1069
+ fprintf(ofp, "# Use 'grep ^%cPCOV | cut -f 2-' to extract this part.\n", type);
1070
+ int d = 0;
1071
+ do {
1072
+ fprintf(ofp, "%cPCOV-%d\t%s", type, args->min_depth[d], name);
1073
+
1074
+ for (r = 0; r < nref; r++) {
1075
+ if (!amps[r].sites)
1076
+ continue;
1077
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1078
+ amplicon_t *amp = amps[r].amp;
1079
+ for (i = 0; i < amps[r].namp; i++) {
1080
+ int covered = 0;
1081
+ if (amp[i].min_right - amp[i].min_left > stats->max_amp_len) {
1082
+ fprintf(samtools_stderr, "[ampliconstats] error: "
1083
+ "Maximum amplicon length (%d) exceeded for '%s'\n",
1084
+ stats->max_amp, name);
1085
+ return -1;
1086
+ }
1087
+ int64_t j, offset = amp[i].min_left-1;
1088
+ for (j = amp[i].max_left-1; j < amp[i].min_right; j++) {
1089
+ int apos = i*stats->max_amp_len + j-offset;
1090
+ if (stats->coverage[apos] >= args->min_depth[d])
1091
+ covered++;
1092
+ }
1093
+ int64_t alen = amp[i].min_right - amp[i].max_left+1;
1094
+ stats->covered_perc[i][d] = 100.0 * covered / alen;
1095
+ fprintf(ofp, "\t%.2f", 100.0 * covered / alen);
1096
+ }
1097
+ }
1098
+ fprintf(ofp, "\n");
1099
+ } while (++d < MAX_DEPTH && args->min_depth[d]);
1100
+
1101
+ } else if (type == 'C') {
1102
+ // For combined we can compute mean & standard deviation too
1103
+ int d = 0;
1104
+ do {
1105
+ fprintf(ofp, "CPCOV-%d\tMEAN", args->min_depth[d]);
1106
+ for (r = 0; r < nref; r++) {
1107
+ if (!amps[r].sites)
1108
+ continue;
1109
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1110
+ for (i = 0; i < amps[r].namp; i++) {
1111
+ fprintf(ofp, "\t%.1f", stats->covered_perc[i][d] / nfile);
1112
+ }
1113
+ }
1114
+ fprintf(ofp, "\n");
1115
+
1116
+ fprintf(ofp, "CPCOV-%d\tSTDDEV", args->min_depth[d]);
1117
+ for (r = 0; r < nref; r++) {
1118
+ if (!amps[r].sites)
1119
+ continue;
1120
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1121
+ for (i = 0; i < amps[r].namp; i++) {
1122
+ double n1 = stats->covered_perc[i][d] / nfile;
1123
+ double v = stats->covered_perc2[i][d] / nfile - n1*n1;
1124
+ fprintf(ofp, "\t%.1f", v>0?sqrt(v):0);
1125
+ }
1126
+ }
1127
+ fprintf(ofp, "\n");
1128
+ } while (++d < MAX_DEPTH && args->min_depth[d]);
1129
+ }
1130
+
1131
+ // Plus base depth for all reads, irrespective of amplicon.
1132
+ // This is post overlap removal, if reads in the read-pair overlap.
1133
+ fprintf(ofp, "# Depth per reference base for ALL data.\n");
1134
+ fprintf(ofp, "# Use 'grep ^%cDP_ALL | cut -f 2-' to extract this part.\n",
1135
+ type);
1136
+ for (r = 0; r < nref; r++) {
1137
+ if (!amps[r].sites)
1138
+ continue;
1139
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1140
+ if (args->multi_ref)
1141
+ fprintf(ofp, "%cDP_ALL\t%s\t%s", type, name, amps[r].ref);
1142
+ else
1143
+ fprintf(ofp, "%cDP_ALL\t%s", type, name);
1144
+
1145
+ for (i = 0; i < amps[r].len; i++) {
1146
+ // Basic run-length encoding provided all values are within
1147
+ // +- depth_bin fraction of the mid-point.
1148
+ int dmin = stats->depth_all[i], dmax = stats->depth_all[i], j;
1149
+ double dmid = (dmin + dmax)/2.0;
1150
+ double low = dmid*(1-args->depth_bin);
1151
+ double high = dmid*(1+args->depth_bin);
1152
+ for (j = i+1; j < amps[r].len; j++) {
1153
+ int d = stats->depth_all[j];
1154
+ if (d < low || d > high)
1155
+ break;
1156
+ if (dmin > d) {
1157
+ dmin = d;
1158
+ dmid = (dmin + dmax)/2.0;
1159
+ low = dmid*(1-args->depth_bin);
1160
+ high = dmid*(1+args->depth_bin);
1161
+ } else if (dmax < d) {
1162
+ dmax = d;
1163
+ dmid = (dmin + dmax)/2.0;
1164
+ low = dmid*(1-args->depth_bin);
1165
+ high = dmid*(1+args->depth_bin);
1166
+ }
1167
+ }
1168
+ fprintf(ofp, "\t%d,%d", (int)dmid, j-i);
1169
+ i = j-1;
1170
+ }
1171
+ fprintf(ofp, "\n");
1172
+ }
1173
+
1174
+ // And depth for only reads matching to a single amplicon for full
1175
+ // length. This is post read overlap removal.
1176
+ fprintf(ofp, "# Depth per reference base for full-length valid amplicon data.\n");
1177
+ fprintf(ofp, "# Use 'grep ^%cDP_VALID | cut -f 2-' to extract this "
1178
+ "part.\n", type);
1179
+ for (r = 0; r < nref; r++) {
1180
+ if (!amps[r].sites)
1181
+ continue;
1182
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1183
+ if (args->multi_ref)
1184
+ fprintf(ofp, "%cDP_VALID\t%s\t%s", type, name, amps[r].ref);
1185
+ else
1186
+ fprintf(ofp, "%cDP_VALID\t%s", type, name);
1187
+
1188
+ for (i = 0; i < amps[r].len; i++) {
1189
+ int dmin = stats->depth_valid[i], dmax = stats->depth_valid[i], j;
1190
+ double dmid = (dmin + dmax)/2.0;
1191
+ double low = dmid*(1-args->depth_bin);
1192
+ double high = dmid*(1+args->depth_bin);
1193
+ for (j = i+1; j < amps[r].len; j++) {
1194
+ int d = stats->depth_valid[j];
1195
+ if (d < low || d > high)
1196
+ break;
1197
+ if (dmin > d) {
1198
+ dmin = d;
1199
+ dmid = (dmin + dmax)/2.0;
1200
+ low = dmid*(1-args->depth_bin);
1201
+ high = dmid*(1+args->depth_bin);
1202
+ } else if (dmax < d) {
1203
+ dmax = d;
1204
+ dmid = (dmin + dmax)/2.0;
1205
+ low = dmid*(1-args->depth_bin);
1206
+ high = dmid*(1+args->depth_bin);
1207
+ }
1208
+ }
1209
+ fprintf(ofp, "\t%d,%d", (int)dmid, j-i);
1210
+ i = j-1;
1211
+ }
1212
+ fprintf(ofp, "\n");
1213
+ }
1214
+
1215
+ // TCOORD (start to end) distribution
1216
+ fprintf(ofp, "# Distribution of aligned template coordinates.\n");
1217
+ fprintf(ofp, "# Use 'grep ^%cTCOORD | cut -f 2-' to extract this part.\n", type);
1218
+ for (r = 0; r < nref; r++) {
1219
+ if (!amps[r].sites)
1220
+ continue;
1221
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1222
+ for (i = 0 - (nref==1); i < amps[r].namp; i++) {
1223
+ if (ntcoord < kh_size(stats->tcoord[i+1])) {
1224
+ ntcoord = kh_size(stats->tcoord[i+1]);
1225
+ tcoord_t *tmp = realloc(tpos, ntcoord * sizeof(*tmp));
1226
+ if (!tmp) {
1227
+ free(tpos);
1228
+ return -1;
1229
+ }
1230
+ tpos = tmp;
1231
+ }
1232
+
1233
+ khiter_t k;
1234
+ size_t n = 0, j;
1235
+ for (k = kh_begin(stats->tcoord[i+1]);
1236
+ k != kh_end(stats->tcoord[i+1]); k++) {
1237
+ if (!kh_exist(stats->tcoord[i+1], k) ||
1238
+ (kh_value(stats->tcoord[i+1], k) & 0xFFFFFFFF) == 0)
1239
+ continue;
1240
+ // Key is start,end in 32-bit quantities.
1241
+ // Yes this limits us to 4Gb references, but just how
1242
+ // many primers are we planning on making? Not that many
1243
+ // I hope.
1244
+ tpos[n].start = kh_key(stats->tcoord[i+1], k)&0xffffffff;
1245
+ tpos[n].end = kh_key(stats->tcoord[i+1], k)>>32;
1246
+
1247
+ // Value is frequency (top 32-bits) and status (bottom 32).
1248
+ tpos[n].freq = kh_value(stats->tcoord[i+1], k)&0xffffffff;
1249
+ tpos[n].status = kh_value(stats->tcoord[i+1], k)>>32;
1250
+ n++;
1251
+ }
1252
+
1253
+ if (args->tcoord_bin > 1)
1254
+ aggregate_tcoord(args, tpos, &n);
1255
+
1256
+ fprintf(ofp, "%cTCOORD\t%s\t%d", type, name,
1257
+ i+1+amps[r].first_amp); // per amplicon
1258
+ for (j = 0; j < n; j++) {
1259
+ if (tpos[j].freq < args->tcoord_min_count)
1260
+ continue;
1261
+ fprintf(ofp, "\t%d,%d,%u,%u",
1262
+ tpos[j].start,
1263
+ tpos[j].end,
1264
+ tpos[j].freq,
1265
+ tpos[j].status);
1266
+ }
1267
+ fprintf(ofp, "\n");
1268
+ }
1269
+ }
1270
+
1271
+
1272
+ // AMP length distribution.
1273
+ // 0 = both ends in this amplicon
1274
+ // 1 = ends in different amplicons
1275
+ // 2 = other end matching an unknown amplicon site
1276
+ // (see tcoord for further analysis of where)
1277
+ fprintf(ofp, "# Classification of amplicon status. Columns are\n");
1278
+ fprintf(ofp, "# number with both primers from this amplicon, number with\n");
1279
+ fprintf(ofp, "# primers from different amplicon, and number with a position\n");
1280
+ fprintf(ofp, "# not matching any valid amplicon primer site\n");
1281
+ fprintf(ofp, "# Use 'grep ^%cAMP | cut -f 2-' to extract this part.\n", type);
1282
+
1283
+ fprintf(ofp, "%cAMP\t%s\t0", type, name); // all merged
1284
+ int amp_dist[3] = {0};
1285
+ for (r = 0; r < nref; r++) {
1286
+ if (!amps[r].sites)
1287
+ continue;
1288
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1289
+ for (i = 0; i < amps[r].namp; i++) { // accumulate for all amps
1290
+ amp_dist[0] += stats->amp_dist[i][0];
1291
+ amp_dist[1] += stats->amp_dist[i][1];
1292
+ amp_dist[2] += stats->amp_dist[i][2];
1293
+ }
1294
+ }
1295
+ fprintf(ofp, "\t%d\t%d\t%d\n", amp_dist[0], amp_dist[1], amp_dist[2]);
1296
+
1297
+ for (r = 0; r < nref; r++) {
1298
+ if (!amps[r].sites)
1299
+ continue;
1300
+ astats_t *stats = local ? amps[r].lstats : amps[r].gstats;
1301
+ for (i = 0; i < amps[r].namp; i++) {
1302
+ // per amplicon
1303
+ fprintf(ofp, "%cAMP\t%s\t%d", type, name, i+1+amps[r].first_amp);
1304
+ fprintf(ofp, "\t%d\t%d\t%d\n", stats->amp_dist[i][0],
1305
+ stats->amp_dist[i][1], stats->amp_dist[i][2]);
1306
+ }
1307
+ }
1308
+
1309
+ free(tpos);
1310
+ return 0;
1311
+ }
1312
+
1313
+ int dump_lstats(astats_args_t *args, char type, char *name, int nfile,
1314
+ amplicons_t *amps, int nref) {
1315
+ return dump_stats(args, type, name, nfile, amps, nref, 1);
1316
+ }
1317
+
1318
+ int dump_gstats(astats_args_t *args, char type, char *name, int nfile,
1319
+ amplicons_t *amps, int nref) {
1320
+ return dump_stats(args, type, name, nfile, amps, nref, 0);
1321
+ }
1322
+
1323
+ char const *get_sample_name(sam_hdr_t *header, char *RG) {
1324
+ kstring_t ks = {0};
1325
+ sam_hdr_find_tag_id(header, "RG", RG?"ID":NULL, RG, "SM", &ks);
1326
+ return ks.s;
1327
+ }
1328
+
1329
+ // Return maximum reference length (SQ is NULL) or the length
1330
+ // of the specified reference in SQ.
1331
+ int64_t get_ref_len(sam_hdr_t *header, const char *SQ) {
1332
+ if (SQ) {
1333
+ int tid = SQ ? sam_hdr_name2tid(header, SQ) : 0;
1334
+ return tid >= 0 ? sam_hdr_tid2len(header, tid) : -1;
1335
+ } else {
1336
+ int nref = sam_hdr_nref(header), tid;;
1337
+ int64_t len = 0;
1338
+ for (tid = 0; tid < nref; tid++) {
1339
+ int64_t rl = sam_hdr_tid2len(header, tid);
1340
+ if (len < rl)
1341
+ len = rl;
1342
+ }
1343
+ return len;
1344
+ }
1345
+ }
1346
+
1347
+ static int amplicon_stats(astats_args_t *args,
1348
+ khash_t(bed_list_hash) *bed_hash,
1349
+ char **filev, int filec) {
1350
+ int i, ref = -1, ref_tid = -1, ret = -1, nref = 0;
1351
+ samFile *fp = NULL;
1352
+ sam_hdr_t *header = NULL;
1353
+ bam1_t *b = bam_init1();
1354
+ FILE *ofp = args->out_fp;
1355
+ char sname_[8192], *sname = NULL;
1356
+ amplicons_t *amps = NULL;
1357
+
1358
+ // Report initial SS header. We gather data from the bed_hash entries
1359
+ // as well as from the first SAM header (with the requirement that all
1360
+ // headers should be compatible).
1361
+ if (filec) {
1362
+ if (!(fp = sam_open_format(filev[0], "r", &args->ga.in))) {
1363
+ print_error_errno("ampliconstats",
1364
+ "Cannot open input file \"%s\"",
1365
+ filev[0]);
1366
+ goto err;
1367
+ }
1368
+ if (!(header = sam_hdr_read(fp)))
1369
+ goto err;
1370
+
1371
+ if (!amps) {
1372
+ amps = calloc(nref=sam_hdr_nref(header), sizeof(*amps));
1373
+ if (!amps)
1374
+ goto err;
1375
+ fprintf(ofp, "# Summary statistics, used for scaling the plots.\n");
1376
+ fprintf(ofp, "SS\tSamtools version: %s\n", samtools_version());
1377
+ fprintf(ofp, "SS\tCommand line: %s\n", args->argv);
1378
+ fprintf(ofp, "SS\tNumber of files:\t%d\n", filec);
1379
+
1380
+ // Note: order of hash entries will be different to order of
1381
+ // BED file which may also differ to order of SQ headers.
1382
+ // SQ header is canonical ordering (pos sorted file).
1383
+ khiter_t k;
1384
+ int bam_nref = sam_hdr_nref(header);
1385
+ for (i = 0; i < bam_nref; i++) {
1386
+ k = kh_get(bed_list_hash, bed_hash,
1387
+ sam_hdr_tid2name(header, i));
1388
+ if (!kh_exist(bed_hash, k))
1389
+ continue;
1390
+
1391
+ bed_entry_list_t *sites = &kh_value(bed_hash, k);
1392
+
1393
+ ref = i;
1394
+ amps[ref].ref = kh_key(bed_hash, k);
1395
+ amps[ref].sites = sites;
1396
+ amps[ref].namp = count_amplicon(sites);
1397
+ amps[ref].amp = calloc(sites->length,
1398
+ sizeof(*amps[ref].amp));
1399
+ if (!amps[ref].amp)
1400
+ goto err;
1401
+ if (args->multi_ref)
1402
+ fprintf(ofp, "SS\tNumber of amplicons:\t%s\t%d\n",
1403
+ kh_key(bed_hash, k), amps[ref].namp);
1404
+ else
1405
+ fprintf(ofp, "SS\tNumber of amplicons:\t%d\n",
1406
+ amps[ref].namp);
1407
+
1408
+ amps[ref].tid = ref;
1409
+ if (ref_tid == -1)
1410
+ ref_tid = ref;
1411
+
1412
+ int64_t len = get_ref_len(header, kh_key(bed_hash, k));
1413
+ amps[ref].len = len;
1414
+ if (args->multi_ref)
1415
+ fprintf(ofp, "SS\tReference length:\t%s\t%"PRId64"\n",
1416
+ kh_key(bed_hash, k), len);
1417
+ else
1418
+ fprintf(ofp, "SS\tReference length:\t%"PRId64"\n",
1419
+ len);
1420
+
1421
+ amps[ref].lstats = stats_alloc(len, args->max_amp,
1422
+ args->max_amp_len);
1423
+ amps[ref].gstats = stats_alloc(len, args->max_amp,
1424
+ args->max_amp_len);
1425
+ if (!amps[ref].lstats || !amps[ref].gstats)
1426
+ goto err;
1427
+ }
1428
+ }
1429
+
1430
+ sam_hdr_destroy(header);
1431
+ header = NULL;
1432
+ if (sam_close(fp) < 0) {
1433
+ fp = NULL;
1434
+ goto err;
1435
+ }
1436
+ fp = NULL;
1437
+ }
1438
+ fprintf(ofp, "SS\tEnd of summary\n");
1439
+
1440
+ // Extract the bits of amplicon data we need from bed hash and turn
1441
+ // it into a position-to-amplicon lookup table.
1442
+ int offset = 0;
1443
+ for (i = 0; i < nref; i++) {
1444
+ if (!amps[i].sites)
1445
+ continue;
1446
+
1447
+ amps[i].first_amp = offset;
1448
+ if (bed2amplicon(args, amps[i].sites, amps[i].amp,
1449
+ &amps[i].namp, i==0, amps[i].ref, offset) < 0)
1450
+ goto err;
1451
+
1452
+ offset += amps[i].namp; // cumulative amplicon number across refs
1453
+ }
1454
+
1455
+ // Now iterate over file contents, one at a time.
1456
+ for (i = 0; i < filec; i++) {
1457
+ char *nstart = filev[i];
1458
+
1459
+ fp = sam_open_format(filev[i], "r", &args->ga.in);
1460
+ if (!fp) {
1461
+ print_error_errno("ampliconstats",
1462
+ "Cannot open input file \"%s\"",
1463
+ filev[i]);
1464
+ goto err;
1465
+ }
1466
+
1467
+ if (args->ga.nthreads > 0)
1468
+ hts_set_threads(fp, args->ga.nthreads);
1469
+
1470
+ if (!(header = sam_hdr_read(fp)))
1471
+ goto err;
1472
+
1473
+ if (nref != sam_hdr_nref(header)) {
1474
+ print_error_errno("ampliconstats",
1475
+ "SAM headers are not consistent across input files");
1476
+ goto err;
1477
+ }
1478
+ int r;
1479
+ for (r = 0; r < nref; r++) {
1480
+ if (!amps[r].sites)
1481
+ continue;
1482
+ if (!amps[r].ref ||
1483
+ strcmp(amps[r].ref, sam_hdr_tid2name(header, r)) != 0 ||
1484
+ amps[r].len != sam_hdr_tid2len(header, r)) {
1485
+ print_error_errno("ampliconstats",
1486
+ "SAM headers are not consistent across "
1487
+ "input files");
1488
+ goto err;
1489
+ }
1490
+ }
1491
+
1492
+ if (args->use_sample_name)
1493
+ sname = (char *)get_sample_name(header, NULL);
1494
+
1495
+ if (!sname) {
1496
+ sname = sname_;
1497
+ char *nend = filev[i] + strlen(filev[i]), *cp;
1498
+ if ((cp = strrchr(filev[i], '/')))
1499
+ nstart = cp+1;
1500
+ if ((cp = strrchr(nstart, '.')) &&
1501
+ (strcmp(cp, ".bam") == 0 ||
1502
+ strcmp(cp, ".sam") == 0 ||
1503
+ strcmp(cp, ".cram") == 0))
1504
+ nend = cp;
1505
+ if (nend - nstart >= 8192) nend = nstart+8191;
1506
+ memcpy(sname, nstart, nend-nstart);
1507
+ sname[nend-nstart] = 0;
1508
+ }
1509
+
1510
+ // Stats local to this sample only
1511
+ amp_stats_reset(amps, nref);
1512
+
1513
+ int last_ref = -9;
1514
+ while ((r = sam_read1(fp, header, b)) >= 0) {
1515
+ // Other filter options useful here?
1516
+ if (b->core.tid < 0)
1517
+ continue;
1518
+
1519
+ if (last_ref != b->core.tid) {
1520
+ last_ref = b->core.tid;
1521
+ if (initialise_amp_pos_lookup(args, amps, last_ref) < 0)
1522
+ goto err;
1523
+ }
1524
+
1525
+ if (accumulate_stats(args, amps, b) < 0)
1526
+ goto err;
1527
+ }
1528
+
1529
+ if (r < -1) {
1530
+ print_error_errno("ampliconstats", "Fail reading record");
1531
+ goto err;
1532
+ }
1533
+
1534
+ sam_hdr_destroy(header);
1535
+ if (sam_close(fp) < 0) {
1536
+ fp = NULL;
1537
+ goto err;
1538
+ }
1539
+
1540
+ fp = NULL;
1541
+ header = NULL;
1542
+
1543
+ if (dump_lstats(args, 'F', sname, filec, amps, nref) < 0)
1544
+ goto err;
1545
+
1546
+ if (append_stats(amps, nref) < 0)
1547
+ goto err;
1548
+
1549
+ if (sname && sname != sname_)
1550
+ free(sname);
1551
+ sname = NULL;
1552
+ }
1553
+
1554
+ if (dump_gstats(args, 'C', "COMBINED", filec, amps, nref) < 0)
1555
+ goto err;
1556
+
1557
+ ret = 0;
1558
+ err:
1559
+ bam_destroy1(b);
1560
+ if (ret) {
1561
+ if (header)
1562
+ sam_hdr_destroy(header);
1563
+ if (fp)
1564
+ sam_close(fp);
1565
+ }
1566
+ for (i = 0; i < nref; i++) {
1567
+ stats_free(amps[i].lstats);
1568
+ stats_free(amps[i].gstats);
1569
+ free(amps[i].amp);
1570
+ }
1571
+ free(amps);
1572
+ free(pos2start);
1573
+ free(pos2end);
1574
+ if (ret) {
1575
+ if (sname && sname != sname_)
1576
+ free(sname);
1577
+ }
1578
+
1579
+ return ret;
1580
+ }
1581
+
1582
+ static int usage(astats_args_t *args, FILE *fp, int exit_status) {
1583
+ fprintf(fp,
1584
+ "\n"
1585
+ "Usage: samtools ampliconstats [options] primers.bed *.bam > astats.txt\n"
1586
+ "\n"
1587
+ "Options:\n");
1588
+ fprintf(fp, " -f, --required-flag STR|INT\n"
1589
+ " Only include reads with all of the FLAGs present [0x%X]\n",args->flag_require);
1590
+ fprintf(fp, " -F, --filter-flag STR|INT\n"
1591
+ " Only include reads with none of the FLAGs present [0x%X]\n",args->flag_filter & 0xffff);
1592
+ fprintf(fp, " -a, --max-amplicons INT\n"
1593
+ " Change the maximum number of amplicons permitted [%d]\n", MAX_AMP);
1594
+ fprintf(fp, " -l, --max-amplicon-length INT\n"
1595
+ " Change the maximum length of an individual amplicon [%d]\n", MAX_AMP_LEN);
1596
+ fprintf(fp, " -d, --min-depth INT[,INT]...\n"
1597
+ " Minimum base depth(s) to consider position covered [%d]\n", args->min_depth[0]);
1598
+ fprintf(fp, " -m, --pos-margin INT\n"
1599
+ " Margin of error for matching primer positions [%d]\n", args->max_delta);
1600
+ fprintf(fp, " -o, --output FILE\n"
1601
+ " Specify output file [samtools_stdout if unset]\n");
1602
+ fprintf(fp, " -s, --use-sample-name\n"
1603
+ " Use the sample name from the first @RG header line\n");
1604
+ fprintf(fp, " -t, --tlen-adjust INT\n"
1605
+ " Add/subtract from TLEN; use when clipping but no fixmate step\n");
1606
+ fprintf(fp, " -b, --tcoord-bin INT\n"
1607
+ " Bin template start,end positions into multiples of INT[1]\n");
1608
+ fprintf(fp, " -c, --tcoord-min-count INT\n"
1609
+ " Minimum template start,end frequency for recording [%d]\n", TCOORD_MIN_COUNT);
1610
+ fprintf(fp, " -D, --depth-bin FRACTION\n"
1611
+ " Merge FDP values within +/- FRACTION together\n");
1612
+ fprintf(fp, " -S, --single-ref\n"
1613
+ " Force single-ref (<=1.12) output format\n");
1614
+ sam_global_opt_help(fp, "I.--.@");
1615
+
1616
+ return exit_status;
1617
+ }
1618
+
1619
+ int main_ampliconstats(int argc, char **argv) {
1620
+ astats_args_t args = {
1621
+ .ga = SAM_GLOBAL_ARGS_INIT,
1622
+ .flag_require = 0,
1623
+ .flag_filter = 0x10B04,
1624
+ //.sites = BED_LIST_INIT,
1625
+ .max_delta = 30, // large enough to cope with alt primers
1626
+ .min_depth = {1},
1627
+ .use_sample_name = 0,
1628
+ .max_amp = MAX_AMP,
1629
+ .max_amp_len = MAX_AMP_LEN,
1630
+ .tlen_adj = 0,
1631
+ .out_fp = samtools_stdout,
1632
+ .tcoord_min_count = TCOORD_MIN_COUNT,
1633
+ .tcoord_bin = 1,
1634
+ .depth_bin = 0.01,
1635
+ .multi_ref = 1
1636
+ }, oargs = args;
1637
+
1638
+ static const struct option loptions[] =
1639
+ {
1640
+ SAM_OPT_GLOBAL_OPTIONS('I', 0, '-', '-', 0, '@'),
1641
+ {"help", no_argument, NULL, 'h'},
1642
+ {"flag-require", required_argument, NULL, 'f'},
1643
+ {"flag-filter", required_argument, NULL, 'F'},
1644
+ {"min-depth", required_argument, NULL, 'd'},
1645
+ {"output", required_argument, NULL, 'o'},
1646
+ {"pos-margin", required_argument, NULL, 'm'},
1647
+ {"use-sample-name", no_argument, NULL, 's'},
1648
+ {"max-amplicons", required_argument, NULL, 'a'},
1649
+ {"max-amplicon-length", required_argument, NULL, 'l'},
1650
+ {"tlen-adjust", required_argument, NULL, 't'},
1651
+ {"tcoord-min-count", required_argument, NULL, 'c'},
1652
+ {"tcoord-bin", required_argument, NULL, 'b'},
1653
+ {"depth-bin", required_argument, NULL, 'D'},
1654
+ {"single-ref", no_argument, NULL, 'S'},
1655
+ {NULL, 0, NULL, 0}
1656
+ };
1657
+ int opt;
1658
+
1659
+ while ( (opt=getopt_long(argc,argv,"?hf:F:@:p:m:d:sa:l:t:o:c:b:D:S",loptions,NULL))>0 ) {
1660
+ switch (opt) {
1661
+ case 'f': args.flag_require = bam_str2flag(optarg); break;
1662
+ case 'F':
1663
+ if (args.flag_filter & 0x10000)
1664
+ args.flag_filter = 0; // strip default on first -F usage
1665
+ args.flag_filter |= bam_str2flag(optarg); break;
1666
+
1667
+ case 'm': args.max_delta = atoi(optarg); break; // margin
1668
+ case 'D': args.depth_bin = atof(optarg); break; // depth bin fraction
1669
+ case 'd': {
1670
+ int d = 0;
1671
+ char *cp = optarg, *ep;
1672
+ do {
1673
+ long n = strtol(cp, &ep, 10);
1674
+ args.min_depth[d++] = n;
1675
+ if (*ep != ',')
1676
+ break;
1677
+ cp = ep+1;
1678
+ } while (d < MAX_DEPTH);
1679
+ break;
1680
+ }
1681
+
1682
+ case 'a': args.max_amp = atoi(optarg)+1;break;
1683
+ case 'l': args.max_amp_len = atoi(optarg)+1;break;
1684
+
1685
+ case 'c': args.tcoord_min_count = atoi(optarg);break;
1686
+ case 'b':
1687
+ args.tcoord_bin = atoi(optarg);
1688
+ if (args.tcoord_bin < 1)
1689
+ args.tcoord_bin = 1;
1690
+ break;
1691
+
1692
+ case 't': args.tlen_adj = atoi(optarg);break;
1693
+
1694
+ case 's': args.use_sample_name = 1;break;
1695
+
1696
+ case 'o':
1697
+ if (!(args.out_fp = fopen(optarg, "w"))) {
1698
+ perror(optarg);
1699
+ return 1;
1700
+ }
1701
+ break;
1702
+
1703
+ case 'S':
1704
+ args.multi_ref = 0;
1705
+ break;
1706
+
1707
+ case '?': return usage(&oargs, samtools_stderr, EXIT_FAILURE);
1708
+ case 'h': return usage(&oargs, samtools_stdout, EXIT_SUCCESS);
1709
+
1710
+ default:
1711
+ if (parse_sam_global_opt(opt, optarg, loptions, &args.ga) != 0)
1712
+ usage(&oargs,samtools_stderr, EXIT_FAILURE);
1713
+ break;
1714
+ }
1715
+ }
1716
+
1717
+ if (argc <= optind)
1718
+ return usage(&oargs, samtools_stdout, EXIT_SUCCESS);
1719
+ if (argc <= optind+1 && isatty(STDIN_FILENO))
1720
+ return usage(&oargs, samtools_stderr, EXIT_FAILURE);
1721
+
1722
+ khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash);
1723
+ if (load_bed_file_multi_ref(argv[optind], 1, 0, bed_hash)) {
1724
+ print_error_errno("ampliconstats",
1725
+ "Could not read file \"%s\"", argv[optind]);
1726
+ return 1;
1727
+
1728
+ }
1729
+
1730
+ khiter_t k, ref_count = 0;
1731
+ for (k = kh_begin(bed_hash); k != kh_end(bed_hash); k++) {
1732
+ if (!kh_exist(bed_hash, k))
1733
+ continue;
1734
+ ref_count++;
1735
+ }
1736
+ if (ref_count == 0)
1737
+ return 1;
1738
+ if (ref_count > 1 && args.multi_ref == 0) {
1739
+ print_error("ampliconstats",
1740
+ "Single-ref mode is not permitted for BED files\n"
1741
+ "containing more than one reference.");
1742
+ return 1;
1743
+ }
1744
+
1745
+ args.argv = stringify_argv(argc, argv);
1746
+ int ret;
1747
+ if (argc == ++optind) {
1748
+ char *av = "-";
1749
+ ret = amplicon_stats(&args, bed_hash, &av, 1);
1750
+ } else {
1751
+ ret = amplicon_stats(&args, bed_hash, &argv[optind], argc-optind);
1752
+ }
1753
+
1754
+ free(args.argv);
1755
+ destroy_bed_hash(bed_hash);
1756
+
1757
+ return ret;
1758
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.c ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam.c -- miscellaneous BAM functions.
2
+
3
+ Copyright (C) 2008-2013, 2015, 2019-2020, 2022 Genome Research Ltd.
4
+ Portions copyright (C) 2009-2012 Broad Institute.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <stdio.h>
29
+ #include <ctype.h>
30
+ #include <errno.h>
31
+ #include "bam.h"
32
+ #include "htslib/kstring.h"
33
+
34
+ // FIXME: we should also check the LB tag associated with each alignment
35
+ const char *bam_get_library(sam_hdr_t *h, const bam1_t *b)
36
+ {
37
+ const char *rg;
38
+ kstring_t lib = { 0, 0, NULL };
39
+ rg = (char *)bam_aux_get(b, "RG");
40
+
41
+ if (!rg)
42
+ return NULL;
43
+ else
44
+ rg++;
45
+
46
+ if (sam_hdr_find_tag_id(h, "RG", "ID", rg, "LB", &lib) < 0)
47
+ return NULL;
48
+
49
+ static char LB_text[1024];
50
+ int len = lib.l < sizeof(LB_text) - 1 ? lib.l : sizeof(LB_text) - 1;
51
+
52
+ memcpy(LB_text, lib.s, len);
53
+ LB_text[len] = 0;
54
+
55
+ free(lib.s);
56
+
57
+ return LB_text;
58
+ }
59
+
60
+ /************
61
+ * Remove B *
62
+ ************/
63
+
64
+ #define bam1_seq_seti(s, i, c) ( (s)[(i)>>1] = ((s)[(i)>>1] & 0xf<<(((i)&1)<<2)) | (c)<<((~(i)&1)<<2) )
65
+
66
+ int bam_remove_B(bam1_t *b)
67
+ {
68
+ int i, j, end_j, k, l, no_qual;
69
+ uint32_t *cigar, *new_cigar;
70
+ uint8_t *seq, *qual, *p;
71
+ // test if removal is necessary
72
+ if (b->core.flag & BAM_FUNMAP) return 0; // unmapped; do nothing
73
+ cigar = bam_get_cigar(b);
74
+ for (k = 0; k < b->core.n_cigar; ++k)
75
+ if (bam_cigar_op(cigar[k]) == BAM_CBACK) break;
76
+ if (k == b->core.n_cigar) return 0; // no 'B'
77
+ if (bam_cigar_op(cigar[0]) == BAM_CBACK) goto rmB_err; // cannot be removed
78
+ // allocate memory for the new CIGAR
79
+ if (b->l_data + (b->core.n_cigar + 1) * 4 > b->m_data) { // not enough memory
80
+ b->m_data = b->l_data + b->core.n_cigar * 4;
81
+ kroundup32(b->m_data);
82
+ b->data = (uint8_t*)realloc(b->data, b->m_data);
83
+ cigar = bam_get_cigar(b); // after realloc, cigar may be changed
84
+ }
85
+ new_cigar = (uint32_t*)(b->data + (b->m_data - b->core.n_cigar * 4)); // from the end of b->data
86
+ // the core loop
87
+ seq = bam_get_seq(b); qual = bam_get_qual(b);
88
+ no_qual = (qual[0] == 0xff); // test whether base quality is available
89
+ i = j = 0; end_j = -1;
90
+ for (k = l = 0; k < b->core.n_cigar; ++k) {
91
+ int op = bam_cigar_op(cigar[k]);
92
+ int len = bam_cigar_oplen(cigar[k]);
93
+ if (op == BAM_CBACK) { // the backward operation
94
+ int t, u;
95
+ if (k == b->core.n_cigar - 1) break; // ignore 'B' at the end of CIGAR
96
+ if (len > j) goto rmB_err; // an excessively long backward
97
+ for (t = l - 1, u = 0; t >= 0; --t) { // look back
98
+ int op1 = bam_cigar_op(new_cigar[t]);
99
+ int len1 = bam_cigar_oplen(new_cigar[t]);
100
+ if (bam_cigar_type(op1)&1) { // consume the query
101
+ if (u + len1 >= len) { // stop
102
+ new_cigar[t] -= (len - u) << BAM_CIGAR_SHIFT;
103
+ break;
104
+ } else u += len1;
105
+ }
106
+ }
107
+ if (bam_cigar_oplen(new_cigar[t]) == 0) --t; // squeeze out the zero-length operation
108
+ l = t + 1;
109
+ end_j = j; j -= len;
110
+ } else { // other CIGAR operations
111
+ new_cigar[l++] = cigar[k];
112
+ if (bam_cigar_type(op)&1) { // consume the query
113
+ if (i != j) { // no need to copy if i == j
114
+ int u, c, c0;
115
+ for (u = 0; u < len; ++u) { // construct the consensus
116
+ c = bam_seqi(seq, i+u);
117
+ if (j + u < end_j) { // in an overlap
118
+ c0 = bam_seqi(seq, j+u);
119
+ if (c != c0) { // a mismatch; choose the better base
120
+ if (qual[j+u] < qual[i+u]) { // the base in the 2nd segment is better
121
+ bam1_seq_seti(seq, j+u, c);
122
+ qual[j+u] = qual[i+u] - qual[j+u];
123
+ } else qual[j+u] -= qual[i+u]; // the 1st is better; reduce base quality
124
+ } else qual[j+u] = qual[j+u] > qual[i+u]? qual[j+u] : qual[i+u];
125
+ } else { // not in an overlap; copy over
126
+ bam1_seq_seti(seq, j+u, c);
127
+ qual[j+u] = qual[i+u];
128
+ }
129
+ }
130
+ }
131
+ i += len, j += len;
132
+ }
133
+ }
134
+ }
135
+ if (no_qual) qual[0] = 0xff; // in very rare cases, this may be modified
136
+ // merge adjacent operations if possible
137
+ for (k = 1; k < l; ++k)
138
+ if (bam_cigar_op(new_cigar[k]) == bam_cigar_op(new_cigar[k-1]))
139
+ new_cigar[k] += new_cigar[k-1] >> BAM_CIGAR_SHIFT << BAM_CIGAR_SHIFT, new_cigar[k-1] &= 0xf;
140
+ // kill zero length operations
141
+ for (k = i = 0; k < l; ++k)
142
+ if (new_cigar[k] >> BAM_CIGAR_SHIFT)
143
+ new_cigar[i++] = new_cigar[k];
144
+ l = i;
145
+ // update b
146
+ memcpy(cigar, new_cigar, l * 4); // set CIGAR
147
+ p = b->data + b->core.l_qname + l * 4;
148
+ memmove(p, seq, (j+1)>>1); p += (j+1)>>1; // set SEQ
149
+ memmove(p, qual, j); p += j; // set QUAL
150
+ memmove(p, bam_get_aux(b), bam_get_l_aux(b)); p += bam_get_l_aux(b); // set optional fields
151
+ b->core.n_cigar = l, b->core.l_qseq = j; // update CIGAR length and query length
152
+ b->l_data = p - b->data; // update record length
153
+ return 0;
154
+
155
+ rmB_err:
156
+ b->core.flag |= BAM_FUNMAP;
157
+ return -1;
158
+ }
159
+
160
+ /* Calculate the current read's start based on the stored cigar string. */
161
+ hts_pos_t unclipped_start(bam1_t *b) {
162
+ uint32_t *cigar = bam_get_cigar(b);
163
+ int64_t clipped = 0;
164
+ uint32_t i;
165
+
166
+ for (i = 0; i < b->core.n_cigar; i++) {
167
+ char c = bam_cigar_opchr(cigar[i]);
168
+
169
+ if (c == 'S' || c == 'H') { // clips
170
+ clipped += bam_cigar_oplen(cigar[i]);
171
+ } else {
172
+ break;
173
+ }
174
+ }
175
+
176
+ return b->core.pos - clipped + 1;
177
+ }
178
+
179
+ /* Calculate the mate's unclipped start based on position and cigar string from MC tag. */
180
+ hts_pos_t unclipped_other_start(hts_pos_t op, char *cigar) {
181
+ char *c = cigar;
182
+ int64_t clipped = 0;
183
+
184
+ while (*c && *c != '*') {
185
+ long num = 0;
186
+
187
+ if (isdigit((int)*c)) {
188
+ num = strtol(c, &c, 10);
189
+ } else {
190
+ num = 1;
191
+ }
192
+
193
+ if (*c == 'S' || *c == 'H') { // clips
194
+ clipped += num;
195
+ } else {
196
+ break;
197
+ }
198
+
199
+ c++;
200
+ }
201
+
202
+ return op - clipped + 1;
203
+ }
204
+
205
+ /* Calculate the current read's end based on the stored cigar string. */
206
+ hts_pos_t unclipped_end(bam1_t *b) {
207
+ uint32_t *cigar = bam_get_cigar(b);
208
+ hts_pos_t end_pos, clipped = 0;
209
+ int32_t i;
210
+
211
+ end_pos = bam_endpos(b);
212
+
213
+ // now get the clipped end bases (if any)
214
+ // if we get to the beginning of the cigar string
215
+ // without hitting a non-clip then the results are meaningless
216
+ for (i = b->core.n_cigar - 1; i >= 0; i--) {
217
+ char c = bam_cigar_opchr(cigar[i]);
218
+
219
+ if (c == 'S' || c == 'H') { // clips
220
+ clipped += bam_cigar_oplen(cigar[i]);
221
+ } else {
222
+ break;
223
+ }
224
+ }
225
+
226
+ return end_pos + clipped;
227
+ }
228
+
229
+
230
+ /* Calculate the mate's unclipped end based on start position and cigar string from MC tag.*/
231
+ hts_pos_t unclipped_other_end(int64_t op, char *cigar) {
232
+ char *c = cigar;
233
+ int64_t refpos = 0;
234
+ int skip = 1;
235
+
236
+ while (*c && *c != '*') {
237
+ long num = 0;
238
+
239
+ if (isdigit((int)*c)) {
240
+ num = strtol(c, &c, 10);
241
+ } else {
242
+ num = 1;
243
+ }
244
+
245
+ switch (*c) {
246
+ case 'M':
247
+ case 'D':
248
+ case 'N':
249
+ case '=':
250
+ case 'X':
251
+ refpos += num;
252
+ skip = 0; // ignore initial clips
253
+ break;
254
+
255
+ case 'S':
256
+ case 'H':
257
+ if (!skip) {
258
+ refpos += num;
259
+ }
260
+ break;
261
+ }
262
+
263
+ c++;
264
+ }
265
+
266
+ return op + refpos;
267
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam.h -- miscellaneous BAM functions.
2
+
3
+ Copyright (C) 2008-2014, 2019 Genome Research Ltd.
4
+
5
+ Author: Heng Li <lh3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #ifndef BAM_BAM_H
26
+ #define BAM_BAM_H
27
+
28
+ #include "htslib/sam.h"
29
+
30
+ int bam_remove_B(bam1_t *b);
31
+
32
+ const char *bam_get_library(sam_hdr_t *header, const bam1_t *b);
33
+
34
+ hts_pos_t unclipped_start(bam1_t *b);
35
+ hts_pos_t unclipped_other_start(hts_pos_t op, char *cigar);
36
+ hts_pos_t unclipped_end(bam1_t *b);
37
+ hts_pos_t unclipped_other_end(int64_t op, char *cigar);
38
+
39
+ #endif
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam2depth.c ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam2depth.c -- depth subcommand.
2
+
3
+ Copyright (C) 2011, 2012 Broad Institute.
4
+ Copyright (C) 2012-2016, 2018, 2019-2022 Genome Research Ltd.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk> (to 2020)
7
+ Author: James Bonfield <jkb@sanger.ac.uk> (2021 rewrite)
8
+
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
+ /* This program demonstrates how to generate pileup from multiple BAMs
29
+ * simultaneously, to achieve random access and to use the BED interface.
30
+ * To compile this program separately, you may:
31
+ *
32
+ * gcc -g -O2 -Wall -o bam2depth -D_MAIN_BAM2DEPTH bam2depth.c -lhts -lz
33
+ */
34
+
35
+ #include <config.h>
36
+
37
+ #include <stdlib.h>
38
+ #include <string.h>
39
+ #include <stdio.h>
40
+ #include <limits.h>
41
+ #include <unistd.h>
42
+ #include "htslib/sam.h"
43
+ #include "samtools.h"
44
+ #include "bedidx.h"
45
+ #include "sam_opts.h"
46
+ #include "htslib/khash.h"
47
+
48
+ // From bam_plcmd.c
49
+ int read_file_list(const char *file_list, int *n, char **argv[]);
50
+
51
+ // We accumulate to hist[pos & (size-1)]. This is a ring-buffer.
52
+ // We track where we last got to in output and what the biggest value
53
+ // we've written to so far (in absolute unmasked coordinates) in
54
+ // "last_output" and "end_pos" respectively.
55
+ // For each new record we just flush anything we haven't written yet
56
+ // already, between "last_output" and this read's start position, and
57
+ // initialise any newly seen positions between "end_pos" and this read's
58
+ // end position.
59
+ typedef struct {
60
+ size_t size;
61
+ int **hist; // hist[nfiles][size]
62
+ hts_pos_t *end_pos; // end_pos[nfiles]
63
+ hts_pos_t last_output;
64
+ int last_ref;
65
+ int nfiles;
66
+ const char *ref;
67
+ kstring_t ks;
68
+ hts_pos_t beg, end; // limit to region
69
+ int tid;
70
+ } depth_hist;
71
+
72
+ typedef struct {
73
+ int header;
74
+ int flag;
75
+ int incl_flag;
76
+ int require_flag;
77
+ int min_qual;
78
+ int min_mqual;
79
+ int min_len;
80
+ int skip_del;
81
+ int all_pos;
82
+ int remove_overlaps;
83
+ FILE *out;
84
+ char *reg;
85
+ void *bed;
86
+ } depth_opt;
87
+
88
+ static void zero_region(depth_opt *opt, depth_hist *dh,
89
+ const char *name, hts_pos_t start, hts_pos_t end) {
90
+ hts_pos_t i;
91
+ kstring_t *ks = &dh->ks;
92
+
93
+ kputs(name, ks_clear(ks));
94
+ kputc('\t', ks);
95
+ size_t cur_l = ks->l;
96
+ if (dh->beg >= 0 && start < dh->beg)
97
+ start = dh->beg;
98
+ if (dh->end >= 0 && end > dh->end)
99
+ end = dh->end;
100
+
101
+ for (i = start; i < end; i++) {
102
+ // Could be optimised, but needs better API to skip to next
103
+ // bed region.
104
+ if (opt->bed && bed_overlap(opt->bed, name, i, i+1) == 0)
105
+ continue;
106
+
107
+ ks->l = cur_l;
108
+ kputll(i+1, ks);
109
+ int n;
110
+ for (n = 0; n < dh->nfiles; n++) {
111
+ kputc_('\t', ks);
112
+ kputc_('0', ks);
113
+ }
114
+ kputc('\n', ks);
115
+ fputs(ks->s, opt->out);
116
+ }
117
+ ks->l = cur_l;
118
+ }
119
+
120
+ // A variation of bam_cigar2qlen which doesn't count soft-clips in to the
121
+ // equation. Basically it's the number of bases in query that are aligned
122
+ // in some way to the reference (including insertions, which are considered
123
+ // to be aligned by dint of being anchored either side).
124
+ hts_pos_t qlen_used(bam1_t *b) {
125
+ int n_cigar = b->core.n_cigar;
126
+ const uint32_t *cigar = bam_get_cigar(b);
127
+
128
+ hts_pos_t l;
129
+
130
+ if (b->core.l_qseq) {
131
+ // Known SEQ permits of short cut of l_qseq minus CSOFT_CLIPs.
132
+ // Full scan not needed, which helps on excessively long CIGARs.
133
+ l = b->core.l_qseq;
134
+ int kl, kr;
135
+ for (kl = 0; kl < n_cigar; kl++)
136
+ if (bam_cigar_op(cigar[kl]) == BAM_CSOFT_CLIP)
137
+ l -= bam_cigar_oplen(cigar[kl]);
138
+ else
139
+ break;
140
+
141
+ for (kr = n_cigar-1; kr > kl; kr--)
142
+ if (bam_cigar_op(cigar[kr]) == BAM_CSOFT_CLIP)
143
+ l -= bam_cigar_oplen(cigar[kr]);
144
+ else
145
+ break;
146
+ } else {
147
+ // Unknown SEQ ("*") needs a full scan through the CIGAR string.
148
+ static int query[16] = {
149
+ //M I D N S H P = X B ? ? ? ? ? ?
150
+ 1,1,0,0, 0,0,0,1, 1,0,0,0, 0,0,0,0
151
+ };
152
+ int k;
153
+ for (k = l = 0; k < n_cigar; k++)
154
+ if (query[bam_cigar_op(cigar[k])])
155
+ l += bam_cigar_oplen(cigar[k]);
156
+ }
157
+ return l;
158
+
159
+ }
160
+
161
+ // Adds the depth for a single read to a depth_hist struct.
162
+ // For just one file, this is easy. We just have a circular buffer
163
+ // where we increment values for bits that overlap existing data
164
+ // and initialise values for coordinates which we're seeing for the first
165
+ // time. This is tracked by "end_pos" to know where we've got to.
166
+ //
167
+ // As the input is sorted, we can flush output from "last_output" to
168
+ // b->core.pos.
169
+ //
170
+ // With multiple files, we must feed data in sorted order as if all files
171
+ // are merged, but track depth per file. This also means "end_pos" is per
172
+ // file too, but "last_output" is global as it corresponds to rows printed.
173
+ static int add_depth(depth_opt *opt, depth_hist *dh, sam_hdr_t *h, bam1_t *b,
174
+ int overlap_clip, int file) {
175
+ hts_pos_t i;
176
+ size_t hmask = dh->size-1;
177
+ int n;
178
+
179
+ if (!b || b->core.tid != dh->last_ref) {
180
+ // New ref
181
+ if (dh->last_ref >= 0) {
182
+ // do end
183
+ size_t cur_l = dh->ks.l;
184
+ int nf = dh->nfiles;
185
+ i = dh->last_output;
186
+ for (i = dh->last_output; nf; i++) {
187
+ nf = 0;
188
+ for (n = 0; n < dh->nfiles; n++) {
189
+ if (i < dh->end_pos[n])
190
+ nf++;
191
+ }
192
+ if (!nf)
193
+ break;
194
+
195
+ if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0)
196
+ continue;
197
+
198
+ dh->ks.l = cur_l;
199
+ kputll(i+1, &dh->ks);
200
+ for (n = 0; n < dh->nfiles; n++) {
201
+ kputc_('\t', &dh->ks);
202
+ int d = i < dh->end_pos[n]
203
+ ? dh->hist[n][i & hmask]
204
+ : 0;
205
+ kputuw(d, &dh->ks);
206
+ }
207
+ kputc('\n', &dh->ks);
208
+ fputs(dh->ks.s, opt->out);
209
+ }
210
+ if (opt->all_pos) {
211
+ // End of last ref
212
+ zero_region(opt, dh,
213
+ sam_hdr_tid2name(h, dh->last_ref),
214
+ i, sam_hdr_tid2len(h, dh->last_ref));
215
+ }
216
+ dh->ks.l = cur_l;
217
+ }
218
+
219
+ if (opt->all_pos > 1 && !opt->reg) {
220
+ // Any previous unused refs
221
+ int lr = dh->last_ref < 0 ? 0 : dh->last_ref+1;
222
+ int rr = b ? b->core.tid : sam_hdr_nref(h), r;
223
+ for (r = lr; r < rr; r++)
224
+ zero_region(opt, dh,
225
+ sam_hdr_tid2name(h, r),
226
+ 0, sam_hdr_tid2len(h, r));
227
+ }
228
+
229
+ if (!b) {
230
+ // we're just flushing to end of file
231
+ if (opt->all_pos && opt->reg && dh->last_ref < 0)
232
+ // -a or -aa without a single read being output yet
233
+ zero_region(opt, dh, sam_hdr_tid2name(h, dh->tid), dh->beg,
234
+ MIN(dh->end, sam_hdr_tid2len(h, dh->tid)));
235
+
236
+ return 0;
237
+ }
238
+
239
+ for (n = 0; dh->end_pos && n < dh->nfiles; n++)
240
+ dh->end_pos[n] = 0;
241
+ dh->last_output = dh->beg >= 0
242
+ ? MAX(b->core.pos, dh->beg)
243
+ : b->core.pos;
244
+ dh->last_ref = b->core.tid;
245
+ dh->ref = sam_hdr_tid2name(h, b->core.tid);
246
+ kputs(dh->ref, ks_clear(&dh->ks));
247
+ kputc('\t', &dh->ks);
248
+
249
+ if (opt->all_pos)
250
+ // Start of ref
251
+ zero_region(opt, dh, dh->ref, 0, b->core.pos);
252
+ } else {
253
+ if (dh->last_output < b->core.pos) {
254
+ // Flush any depth outputs up to start of new read
255
+ size_t cur_l = dh->ks.l;
256
+ int nf = dh->nfiles;
257
+ for (i = dh->last_output; i < b->core.pos; i++) {
258
+ nf = 0;
259
+ for (n = 0; n < dh->nfiles; n++) {
260
+ if (i < dh->end_pos[n])
261
+ nf++;
262
+ }
263
+ if (!nf)
264
+ break;
265
+
266
+ if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0)
267
+ continue;
268
+
269
+ dh->ks.l = cur_l;
270
+ kputll(i+1, &dh->ks);
271
+ for (n = 0; n < dh->nfiles; n++) {
272
+ kputc_('\t', &dh->ks);
273
+ int d = i < dh->end_pos[n]
274
+ ? dh->hist[n][i & hmask]
275
+ : 0;
276
+ kputuw(d, &dh->ks);
277
+ }
278
+ kputc('\n', &dh->ks);
279
+ fputs(dh->ks.s, opt->out);
280
+ }
281
+ if (opt->all_pos && i < b->core.pos)
282
+ // Hole in middle of ref
283
+ zero_region(opt, dh, dh->ref, i, b->core.pos);
284
+
285
+ dh->ks.l = cur_l;
286
+ dh->last_output = b->core.pos;
287
+ }
288
+ }
289
+
290
+ hts_pos_t end_pos = bam_endpos(b); // 0 based, 1 past end.
291
+ //printf("%d %d\n", (int)b->core.pos+1, (int)end_pos);
292
+
293
+ if (b->core.tid < dh->last_ref ||
294
+ (dh->last_ref == b->core.tid && end_pos < dh->last_output)) {
295
+ print_error_errno("depth", "Data is not position sorted");
296
+ return -1;
297
+ }
298
+
299
+ // If needed, grow the circular buffer.
300
+ if (end_pos+1 - b->core.pos >= dh->size) {
301
+ size_t old_size = dh->size;
302
+ size_t old_hmask = hmask;
303
+ while (end_pos+1 - b->core.pos >= dh->size)
304
+ dh->size = dh->size ? 2*dh->size : 2048;
305
+ hmask = dh->size-1;
306
+ if (!dh->hist) {
307
+ dh->hist = calloc(dh->nfiles, sizeof(*dh->hist));
308
+ dh->end_pos = calloc(dh->nfiles, sizeof(*dh->end_pos));
309
+ if (!dh->hist || !dh->end_pos)
310
+ return -1;
311
+ }
312
+ for (n = 0; n < dh->nfiles; n++) {
313
+ int *hist = calloc(dh->size, sizeof(*dh->hist[n]));
314
+ if (!hist)
315
+ return -1;
316
+
317
+ // Simple approach for now; copy over old histogram verbatim.
318
+ for (i = dh->last_output; i < dh->last_output + old_size; i++)
319
+ hist[i & hmask] = dh->hist[n][i & old_hmask];
320
+ free(dh->hist[n]);
321
+ dh->hist[n] = hist;
322
+ }
323
+ }
324
+
325
+ // Accumulate depth, based on CIGAR
326
+ uint32_t *cig = bam_get_cigar(b);
327
+ int ncig = b->core.n_cigar, j, k, spos = 0;
328
+
329
+ // Zero new (previously unseen) coordinates so increment works later.
330
+ hts_pos_t end = MAX(dh->end_pos[file], b->core.pos);
331
+ if (end_pos > end && (end & hmask) < (end_pos & hmask)) {
332
+ memset(&dh->hist[file][end & hmask], 0,
333
+ sizeof(**dh->hist) * (end_pos - end));
334
+ } else {
335
+ for (i = end; i < end_pos; i++)
336
+ dh->hist[file][i & hmask] = 0;
337
+ }
338
+
339
+ i = b->core.pos;
340
+ uint8_t *qual = bam_get_qual(b);
341
+ int min_qual = opt->min_qual;
342
+ for (j = 0; j < ncig; j++) {
343
+ int op = bam_cigar_op(cig[j]);
344
+ int oplen = bam_cigar_oplen(cig[j]);
345
+
346
+ switch (op) {
347
+ case BAM_CDEL:
348
+ case BAM_CREF_SKIP:
349
+ if (op != BAM_CDEL || opt->skip_del) {
350
+ // don't increment reference location
351
+ if (i + oplen >= dh->end_pos[file]) {
352
+ for (k = 0; k < oplen; k++, i++) {
353
+ if (i >= dh->end_pos[file])
354
+ // redundant due to zero new elements above?
355
+ dh->hist[file][i & hmask] = 0;
356
+ }
357
+ } else {
358
+ i += oplen;
359
+ }
360
+ } else { // op == BAM_CDEL and we count them (-J option),
361
+ // We don't incr spos here, but we still use qual.
362
+ // This doesn't make much sense, but it's for compatibility
363
+ // with the old code. Arguably DEL shouldn't have a min
364
+ // qual and should always pass (as we've explicitly asked to
365
+ // include them).
366
+ int *hist = dh->hist[file];
367
+ k = 0;
368
+ if (overlap_clip) {
369
+ if (i+oplen < overlap_clip) {
370
+ i += oplen;
371
+ break;
372
+ } else if (i < overlap_clip) {
373
+ k = overlap_clip - i;
374
+ i = overlap_clip;
375
+ }
376
+ }
377
+
378
+ // Question: should we even check quality values for DEL?
379
+ // We've explicitly asked to include them, and the quality
380
+ // is wrong anyway (it's the neighbouring base). We do this
381
+ // for now for compatibility with the old depth command.
382
+
383
+ if (spos < b->core.l_qseq)
384
+ for (; k < oplen; k++, i++)
385
+ hist[i & hmask]+=qual[spos]>=min_qual;
386
+ else
387
+ for (; k < oplen; k++, i++)
388
+ hist[i & hmask]++;
389
+ }
390
+ break;
391
+
392
+ case BAM_CMATCH:
393
+ case BAM_CEQUAL:
394
+ case BAM_CDIFF:
395
+ if ((i & hmask) < ((i+oplen) & hmask)) {
396
+ // Optimisation when not wrapping around
397
+
398
+ // Unrolling doesn't help clang, but helps gcc,
399
+ // especially when not using -O3.
400
+ int *hist = &dh->hist[file][i & hmask];
401
+ if (min_qual || overlap_clip) {
402
+ k = 0;
403
+ if (overlap_clip) {
404
+ if (i+oplen < overlap_clip) {
405
+ i += oplen;
406
+ spos += oplen;
407
+ break;
408
+ } else if (i < overlap_clip) {
409
+ oplen -= overlap_clip - i;
410
+ spos += overlap_clip - i;
411
+ hist += overlap_clip - i;
412
+ i = overlap_clip;
413
+ }
414
+ }
415
+
416
+ // approx 50% of this func cpu time in this loop
417
+ for (; k < (oplen & ~7); k+=8) {
418
+ hist[k+0]+=qual[spos+0]>=min_qual;
419
+ hist[k+1]+=qual[spos+1]>=min_qual;
420
+ hist[k+2]+=qual[spos+2]>=min_qual;
421
+ hist[k+3]+=qual[spos+3]>=min_qual;
422
+ hist[k+4]+=qual[spos+4]>=min_qual;
423
+ hist[k+5]+=qual[spos+5]>=min_qual;
424
+ hist[k+6]+=qual[spos+6]>=min_qual;
425
+ hist[k+7]+=qual[spos+7]>=min_qual;
426
+ spos += 8;
427
+ }
428
+ } else {
429
+ // easier to vectorize when no min_qual
430
+ for (k = 0; k < (oplen & ~7); k+=8) {
431
+ hist[k+0]++;
432
+ hist[k+1]++;
433
+ hist[k+2]++;
434
+ hist[k+3]++;
435
+ hist[k+4]++;
436
+ hist[k+5]++;
437
+ hist[k+6]++;
438
+ hist[k+7]++;
439
+ }
440
+ spos += k;
441
+ }
442
+ for (; k < oplen && spos < b->core.l_qseq; k++, spos++)
443
+ hist[k]+=qual[spos]>=min_qual;
444
+ for (; k < oplen; k++, spos++)
445
+ hist[k]++;
446
+ i += oplen;
447
+ } else {
448
+ // Simple to understand case, but slower.
449
+ // We use this only for reads with wrap-around.
450
+ int *hist = dh->hist[file];
451
+ k = 0;
452
+ if (overlap_clip) {
453
+ if (i+oplen < overlap_clip) {
454
+ i += oplen;
455
+ break;
456
+ } else if (i < overlap_clip) {
457
+ oplen -= overlap_clip - i;
458
+ spos += overlap_clip - i;
459
+ i = overlap_clip;
460
+ }
461
+ }
462
+ for (; k < oplen && spos < b->core.l_qseq; k++, i++, spos++)
463
+ hist[i & hmask]+=qual[spos]>=min_qual;
464
+ for (; k < oplen; k++, i++, spos++)
465
+ hist[i & hmask]++;
466
+ }
467
+ break;
468
+
469
+ case BAM_CINS:
470
+ case BAM_CSOFT_CLIP:
471
+ spos += oplen;
472
+ break;
473
+
474
+ case BAM_CPAD:
475
+ case BAM_CHARD_CLIP:
476
+ // ignore
477
+ break;
478
+
479
+ default:
480
+ print_error("depth", "Unsupported cigar op '%d'", op);
481
+ return -1;
482
+ }
483
+ }
484
+
485
+ if (dh->end >= 0 && end_pos > dh->end)
486
+ end_pos = dh->end;
487
+ if (dh->end_pos[file] < end_pos)
488
+ dh->end_pos[file] = end_pos;
489
+
490
+ return 0;
491
+ }
492
+
493
+ // Hash on name -> alignment end pos. This permits a naive overlap removal.
494
+ // Note it cannot analyse the overlapping sequence and qualities, so the
495
+ // interaction of basecalls/qualities and the -Q parameter cannot be
496
+ // applied here (unlike the full mpileup algorithm).
497
+ KHASH_MAP_INIT_STR(olap_hash, hts_pos_t)
498
+ typedef khash_t(olap_hash) olap_hash_t;
499
+
500
+ static int fastdepth_core(depth_opt *opt, uint32_t nfiles, char **fn,
501
+ samFile **fp, hts_itr_t **itr, sam_hdr_t **h) {
502
+ int ret = -1, err = 1, i;
503
+ olap_hash_t **overlaps = NULL;
504
+ depth_hist dh = {0};
505
+
506
+ // An array of bam structs, one per input file, to hold the next entry
507
+ bam1_t **b = calloc(nfiles, sizeof(*b));
508
+ int *finished = calloc(nfiles, sizeof(*finished)), to_go = nfiles;
509
+ if (!b || !finished)
510
+ goto err;
511
+
512
+ for (i = 0; i < nfiles; i++)
513
+ if (!(b[i] = bam_init1()))
514
+ goto err;
515
+
516
+ // Do we need one overlap hash per file? Or shared?
517
+ if (opt->remove_overlaps) {
518
+ if (!(overlaps = calloc(nfiles, sizeof(*overlaps))))
519
+ return -1;
520
+ for (i = 0; i < nfiles; i++) {
521
+ if (!(overlaps[i] = kh_init(olap_hash)))
522
+ return -1;
523
+ }
524
+ }
525
+
526
+ // Create the initial histogram
527
+ dh.nfiles = nfiles;
528
+ dh.size = 0;
529
+ dh.hist = NULL;
530
+ dh.last_ref = -99;
531
+ dh.end_pos = NULL;
532
+ dh.last_output = itr && itr[0] ? itr[0]->beg : 0;
533
+ ks_initialize(&dh.ks);
534
+
535
+ // Clip results to region if specified
536
+ dh.beg = -1;
537
+ dh.end = -1;
538
+ dh.tid = 0;
539
+ if (itr && itr[0]) {
540
+ dh.tid = itr[0]->tid;
541
+ dh.beg = itr[0]->beg;
542
+ dh.end = itr[0]->end;
543
+ }
544
+
545
+ if (opt->header) {
546
+ fprintf(opt->out, "#CHROM\tPOS");
547
+ for (i = 0; i < nfiles; i++)
548
+ fprintf(opt->out, "\t%s", fn[i]);
549
+ fputc('\n', opt->out);
550
+ }
551
+
552
+ // Populate first record per file
553
+ for (i = 0; i < nfiles; i++) {
554
+ for(;;) {
555
+ ret = itr && itr[i]
556
+ ? sam_itr_next(fp[i], itr[i], b[i])
557
+ : sam_read1(fp[i], h[i], b[i]);
558
+ if (ret < -1)
559
+ goto err;
560
+ if (ret == -1) {
561
+ to_go--;
562
+ finished[i] = 1;
563
+ break;
564
+ }
565
+
566
+ if (b[i]->core.tid < 0)
567
+ continue;
568
+ if (b[i]->core.flag & opt->flag)
569
+ continue; // must have none of the flags set
570
+ if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0)
571
+ continue; // must have at least one flag set
572
+ if ((b[i]->core.flag & opt->require_flag) != opt->require_flag)
573
+ continue; // must have all lags set
574
+ if (b[i]->core.qual < opt->min_mqual)
575
+ continue;
576
+
577
+ // Original samtools depth used the total sequence (l_qseq)
578
+ // including soft-clips. This doesn't feel like a useful metric
579
+ // to be filtering on. We now only count sequence bases that
580
+ // form the used part of the alignment.
581
+ if (opt->min_len) {
582
+ if (qlen_used(b[i]) < opt->min_len)
583
+ continue;
584
+ }
585
+
586
+ break;
587
+ }
588
+ }
589
+
590
+ // Loop through input files, merging in order so we're
591
+ // always adding the next record in sequence
592
+ while (to_go) {
593
+ // Find next record in file list
594
+ int best_tid = INT_MAX, best_file = 0;
595
+ hts_pos_t best_pos = HTS_POS_MAX;
596
+
597
+ for (i = 0; i < nfiles; i++) {
598
+ if (finished[i])
599
+ continue;
600
+ if (best_tid > b[i]->core.tid) {
601
+ best_tid = b[i]->core.tid;
602
+ best_pos = b[i]->core.pos;
603
+ best_file = i;
604
+ } else if (best_tid == b[i]->core.tid &&
605
+ best_pos > b[i]->core.pos) {
606
+ best_pos = b[i]->core.pos;
607
+ best_file = i;
608
+ }
609
+ }
610
+ i = best_file;
611
+
612
+ hts_pos_t clip = 0;
613
+ if (overlaps && (b[i]->core.flag & BAM_FPAIRED) &&
614
+ !(b[i]->core.flag & BAM_FMUNMAP)) {
615
+ khiter_t k = kh_get(olap_hash, overlaps[i], bam_get_qname(b[i]));
616
+ if (k == kh_end(overlaps[i])) {
617
+ // not seen before
618
+ hts_pos_t endpos = bam_endpos(b[i]);
619
+
620
+ // Don't add if mate location is known and can't overlap.
621
+ if (b[i]->core.mpos == -1 ||
622
+ (b[i]->core.tid == b[i]->core.mtid &&
623
+ b[i]->core.mpos <= endpos)) {
624
+ k = kh_put(olap_hash, overlaps[i], bam_get_qname(b[i]),
625
+ &ret);
626
+ if (ret < 0)
627
+ return -1;
628
+ kh_key(overlaps[i], k) = strdup(bam_get_qname(b[i]));
629
+ kh_value(overlaps[i], k) = endpos;
630
+ }
631
+ } else {
632
+ // seen before
633
+ clip = kh_value(overlaps[i], k);
634
+ free((char *)kh_key(overlaps[i], k));
635
+ kh_del(olap_hash, overlaps[i], k);
636
+ }
637
+ }
638
+
639
+ // Add the next merged BAM record to the depth plot
640
+ if ((ret = add_depth(opt, &dh, h[i], b[i], clip, i)) < 0) {
641
+ ret = -1;
642
+ goto err;
643
+ }
644
+
645
+ // Populate next record from this file
646
+ for(;!finished[i];) {
647
+ ret = itr && itr[i]
648
+ ? sam_itr_next(fp[i], itr[i], b[i])
649
+ : sam_read1(fp[i], h[i], b[i]);
650
+ if (ret < -1) {
651
+ ret = -1;
652
+ goto err;
653
+ }
654
+ if (ret == -1) {
655
+ to_go--;
656
+ finished[i] = 1;
657
+ break;
658
+ }
659
+
660
+ if (b[i]->core.tid < 0)
661
+ continue;
662
+ if (b[i]->core.flag & opt->flag)
663
+ continue; // must have none of the flags set
664
+ if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0)
665
+ continue; // must have at least one flag set
666
+ if ((b[i]->core.flag & opt->require_flag) != opt->require_flag)
667
+ continue; // must have all lags set
668
+ if (b[i]->core.qual < opt->min_mqual)
669
+ continue;
670
+
671
+ if (opt->min_len) {
672
+ if (qlen_used(b[i]) < opt->min_len)
673
+ continue;
674
+ }
675
+
676
+ break;
677
+ }
678
+ }
679
+
680
+ // Tidy up end.
681
+ ret = add_depth(opt, &dh, h[0], NULL, 0, 0);
682
+ err = 0;
683
+
684
+ err:
685
+ if (ret == 0 && err)
686
+ ret = -1;
687
+
688
+ for (i = 0; i < nfiles; i++) {
689
+ if (b[i])
690
+ bam_destroy1(b[i]);
691
+ if (dh.hist && dh.hist[i])
692
+ free(dh.hist[i]);
693
+ }
694
+ free(b);
695
+ free(finished);
696
+ ks_free(&dh.ks);
697
+ free(dh.hist);
698
+ free(dh.end_pos);
699
+ if (overlaps) {
700
+ khiter_t k;
701
+ for (i = 0; i < nfiles; i++) {
702
+ if (!overlaps[i])
703
+ continue;
704
+ for (k = kh_begin(overlaps[i]); k < kh_end(overlaps[i]); k++)
705
+ if (kh_exist(overlaps[i], k))
706
+ free((char *)kh_key(overlaps[i], k));
707
+ kh_destroy(olap_hash, overlaps[i]);
708
+ }
709
+ free(overlaps);
710
+ }
711
+
712
+ return ret;
713
+ }
714
+
715
+ static void usage_exit(FILE *fp, int exit_status)
716
+ {
717
+ fprintf(fp, "Usage: samtools depth [options] in.bam [in.bam ...]\n");
718
+ fprintf(fp, "\nOptions:\n");
719
+ fprintf(fp, " -a Output all positions (including zero depth)\n");
720
+ fprintf(fp, " -a -a, -aa Output absolutely all positions, including unused ref seqs\n");
721
+ fprintf(fp, " -r REG Specify a region in chr or chr:from-to syntax\n");
722
+ fprintf(fp, " -b FILE Use bed FILE for list of regions\n");
723
+ fprintf(fp, " -f FILE Specify list of input BAM/SAM/CRAM filenames\n");
724
+ fprintf(fp, " -X Use custom index files (in -X *.bam *.bam.bai order)\n");
725
+ fprintf(fp, " -g INT Remove specified flags from default filter-out flag list\n");
726
+ fprintf(fp, " -G, --excl-flags FLAGS\n");
727
+ fprintf(fp, " Add specified flags to the default filter-out flag list\n");
728
+ fprintf(fp, " [UNMAP,SECONDARY,QCFAIL,DUP]\n");
729
+ fprintf(fp, " --incl-flags FLAGS\n");
730
+ fprintf(fp, " Only include records with at least one the FLAGs present [0]\n");
731
+ fprintf(fp, " --require-flags FLAGS\n");
732
+ fprintf(fp, " Only include records with all of the FLAGs present [0]\n");
733
+ fprintf(fp, " -H Print a file header line\n");
734
+ fprintf(fp, " -l INT Minimum read length [0]\n");
735
+ fprintf(fp, " -o FILE Write output to FILE [stdout]\n");
736
+ fprintf(fp, " -q, --min-BQ INT\n"
737
+ " Filter bases with base quality smaller than INT [0]\n");
738
+ fprintf(fp, " -Q, --min-MQ INT\n"
739
+ " Filter alignments with mapping quality smaller than INT [0]\n");
740
+ fprintf(fp, " -J Include reads with deletions in depth computation\n");
741
+ fprintf(fp, " -s Do not count overlapping reads within a template\n");
742
+ sam_global_opt_help(fp, "-.--.@-.");
743
+ exit(exit_status);
744
+ }
745
+
746
+ int main_depth(int argc, char *argv[])
747
+ {
748
+ int nfiles, i;
749
+ samFile **fp;
750
+ sam_hdr_t **header;
751
+ int c, has_index_file = 0;
752
+ char *file_list = NULL, **fn = NULL;
753
+ char *out_file = NULL;
754
+ depth_opt opt = {
755
+ .flag = BAM_FUNMAP | BAM_FSECONDARY | BAM_FDUP | BAM_FQCFAIL,
756
+ .incl_flag = 0,
757
+ .require_flag = 0,
758
+ .min_qual = 0,
759
+ .min_mqual = 0,
760
+ .skip_del = 1,
761
+ .header = 0,
762
+ .min_len = 0,
763
+ .out = stdout,
764
+ .all_pos = 0,
765
+ .remove_overlaps = 0,
766
+ .reg = NULL,
767
+ .bed = NULL,
768
+ };
769
+
770
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
771
+ static const struct option lopts[] = {
772
+ {"min-MQ", required_argument, NULL, 'Q'},
773
+ {"min-mq", required_argument, NULL, 'Q'},
774
+ {"min-BQ", required_argument, NULL, 'q'},
775
+ {"min-bq", required_argument, NULL, 'q'},
776
+ {"excl-flags", required_argument, NULL, 'G'},
777
+ {"incl-flags", required_argument, NULL, 1},
778
+ {"require-flags", required_argument, NULL, 2},
779
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'),
780
+ {NULL, 0, NULL, 0}
781
+ };
782
+
783
+ while ((c = getopt_long(argc, argv, "@:q:Q:JHd:m:l:g:G:o:ar:Xf:b:s",
784
+ lopts, NULL)) >= 0) {
785
+ switch (c) {
786
+ case 'a':
787
+ opt.all_pos++;
788
+ break;
789
+
790
+ case 'b':
791
+ opt.bed = bed_read(optarg);
792
+ if (!opt.bed) {
793
+ print_error_errno("depth", "Could not read file \"%s\"",
794
+ optarg);
795
+ return 1;
796
+ }
797
+ break;
798
+
799
+ case 'f':
800
+ file_list = optarg;
801
+ break;
802
+
803
+ case 'd':
804
+ case 'm':
805
+ // depth limit - now ignored
806
+ break;
807
+
808
+ case 'g':
809
+ opt.flag &= ~bam_str2flag(optarg);
810
+ break;
811
+ case 'G': // reject if any set
812
+ opt.flag |= bam_str2flag(optarg);
813
+ break;
814
+ case 1: // reject unless at least one set (0 means ignore option)
815
+ opt.incl_flag |= bam_str2flag(optarg);
816
+ break;
817
+ case 2: // reject unless all set
818
+ opt.require_flag |= bam_str2flag(optarg);
819
+ break;
820
+
821
+ case 'l':
822
+ opt.min_len = atoi(optarg);
823
+ break;
824
+
825
+ case 'H':
826
+ opt.header = 1;
827
+ break;
828
+
829
+ case 'q':
830
+ opt.min_qual = atoi(optarg);
831
+ break;
832
+ case 'Q':
833
+ opt.min_mqual = atoi(optarg);
834
+ break;
835
+
836
+ case 'J':
837
+ opt.skip_del = 0;
838
+ break;
839
+
840
+ case 'o':
841
+ if (opt.out != stdout)
842
+ break;
843
+ opt.out = fopen(out_file = optarg, "w");
844
+ if (!opt.out) {
845
+ print_error_errno("depth", "Cannot open \"%s\" for writing.",
846
+ optarg);
847
+ return EXIT_FAILURE;
848
+ }
849
+ break;
850
+
851
+ case 'r':
852
+ opt.reg = optarg;
853
+ break;
854
+
855
+ case 's':
856
+ opt.remove_overlaps = 1;
857
+ break;
858
+
859
+ case 'X':
860
+ has_index_file = 1;
861
+ break;
862
+
863
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
864
+ /* else fall-through */
865
+ case '?':
866
+ usage_exit(stderr, EXIT_FAILURE);
867
+ }
868
+ }
869
+
870
+ if (argc < optind+1 && !file_list) {
871
+ if (argc == optind)
872
+ usage_exit(stdout, EXIT_SUCCESS);
873
+ else
874
+ usage_exit(stderr, EXIT_FAILURE);
875
+ }
876
+
877
+ if (file_list) {
878
+ if (has_index_file) {
879
+ print_error("depth", "The -f option cannot be combined with -X");
880
+ return 1;
881
+ }
882
+ if (read_file_list(file_list, &nfiles, &fn))
883
+ return 1;
884
+ argv = fn;
885
+ argc = nfiles;
886
+ optind = 0;
887
+ } else {
888
+ nfiles = argc - optind;
889
+ }
890
+
891
+ if (has_index_file) {
892
+ if (nfiles%1) {
893
+ print_error("depth", "-X needs one index specified per bam file");
894
+ return 1;
895
+ }
896
+ nfiles /= 2;
897
+ }
898
+ fp = malloc(nfiles * sizeof(*fp));
899
+ header = malloc(nfiles * sizeof(*header));
900
+ if (!fp || !header) {
901
+ print_error_errno("depth", "Out of memory");
902
+ return 1;
903
+ }
904
+
905
+ hts_itr_t **itr = NULL;
906
+ if (opt.reg) {
907
+ itr = calloc(nfiles, sizeof(*itr));
908
+ if (!itr)
909
+ return 1;
910
+ }
911
+
912
+ for (i = 0; i < nfiles; i++, optind++) {
913
+ fp[i] = sam_open_format(argv[optind], "r", &ga.in);
914
+ if (fp[i] == NULL) {
915
+ print_error_errno("depth",
916
+ "Cannot open input file \"%s\"", argv[optind]);
917
+ return 1;
918
+ }
919
+
920
+ if (ga.nthreads > 0)
921
+ hts_set_threads(fp[i], ga.nthreads);
922
+
923
+ if (hts_set_opt(fp[i], CRAM_OPT_REQUIRED_FIELDS,
924
+ SAM_FLAG | SAM_RNAME | SAM_POS | SAM_CIGAR
925
+ | (opt.remove_overlaps ? SAM_QNAME|SAM_RNEXT|SAM_PNEXT
926
+ : 0)
927
+ | (opt.min_mqual ? SAM_MAPQ : 0)
928
+ | (opt.min_len ? SAM_SEQ : 0)
929
+ | (opt.min_qual ? SAM_QUAL : 0))) {
930
+ fprintf(stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n");
931
+ return 1;
932
+ }
933
+
934
+ if (hts_set_opt(fp[i], CRAM_OPT_DECODE_MD, 0)) {
935
+ fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
936
+ return 1;
937
+ }
938
+
939
+ // FIXME: what if headers differ?
940
+ header[i] = sam_hdr_read(fp[i]);
941
+ if (header == NULL) {
942
+ fprintf(stderr, "Failed to read header for \"%s\"\n",
943
+ argv[optind]);
944
+ return 1;
945
+ }
946
+
947
+ if (opt.reg) {
948
+ hts_idx_t *idx = has_index_file
949
+ ? sam_index_load2(fp[i], argv[optind], argv[optind+nfiles])
950
+ : sam_index_load(fp[i], argv[optind]);
951
+ if (!idx) {
952
+ print_error("depth", "cannot load index for \"%s\"",
953
+ argv[optind]);
954
+ return 1;
955
+ }
956
+ if (!(itr[i] = sam_itr_querys(idx, header[i], opt.reg))) {
957
+ print_error("depth", "cannot parse region \"%s\"", opt.reg);
958
+ return 1;
959
+ }
960
+ hts_idx_destroy(idx);
961
+ }
962
+ }
963
+
964
+ int ret = fastdepth_core(&opt, nfiles, &argv[argc-nfiles], fp, itr, header)
965
+ ? 1 : 0;
966
+
967
+ for (i = 0; i < nfiles; i++) {
968
+ sam_hdr_destroy(header[i]);
969
+ sam_close(fp[i]);
970
+ if (itr && itr[i])
971
+ hts_itr_destroy(itr[i]);
972
+ }
973
+ free(header);
974
+ free(fp);
975
+ free(itr);
976
+ if (file_list) {
977
+ for (i=0; i<nfiles; i++)
978
+ free(fn[i]);
979
+ free(fn);
980
+ }
981
+ if (opt.bed)
982
+ bed_destroy(opt.bed);
983
+ sam_global_args_free(&ga);
984
+ if (opt.out != stdout) {
985
+ if (fclose(opt.out) != 0 && ret == 0) {
986
+ print_error_errno("depth", "error on closing \"%s\"", out_file);
987
+ ret = 1;
988
+ }
989
+ }
990
+
991
+ return ret;
992
+ }
993
+
994
+ #ifdef _MAIN_BAM2DEPTH
995
+ int main(int argc, char *argv[])
996
+ {
997
+ return main_depth(argc, argv);
998
+ }
999
+ #endif
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_addrprg.c ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_addrprg.c -- samtools command to add or replace readgroups.
2
+
3
+ Copyright (c) 2013, 2015-2017, 2019-2021 Genome Research Limited.
4
+
5
+ Author: Martin O. Pollard <mp15@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <htslib/sam.h>
28
+ #include <htslib/kstring.h>
29
+ #include "samtools.h"
30
+ #include "htslib/thread_pool.h"
31
+ #include "sam_opts.h"
32
+ #include <string.h>
33
+ #include <stdio.h>
34
+ #include <stdlib.h>
35
+ #include <stdbool.h>
36
+ #include <limits.h>
37
+ #include <assert.h>
38
+ #include <unistd.h>
39
+
40
+ typedef enum {
41
+ overwrite_all,
42
+ orphan_only,
43
+ } rg_mode;
44
+
45
+ struct parsed_opts {
46
+ char* input_name;
47
+ char* output_name;
48
+ char* rg_id;
49
+ char* rg_line;
50
+ int no_pg;
51
+ rg_mode mode;
52
+ sam_global_args ga;
53
+ htsThreadPool p;
54
+ int uncompressed;
55
+ int overwrite_hdr_rg;
56
+ };
57
+
58
+ struct state;
59
+ typedef struct parsed_opts parsed_opts_t;
60
+ typedef struct state state_t;
61
+
62
+ struct state {
63
+ samFile* input_file;
64
+ sam_hdr_t* input_header;
65
+ samFile* output_file;
66
+ sam_hdr_t* output_header;
67
+ char* rg_id;
68
+ void (*mode_func)(const state_t*, bam1_t*);
69
+ };
70
+
71
+ static void cleanup_opts(parsed_opts_t* opts)
72
+ {
73
+ if (!opts) return;
74
+ free(opts->rg_id);
75
+ free(opts->output_name);
76
+ free(opts->input_name);
77
+ free(opts->rg_line);
78
+ if (opts->p.pool) hts_tpool_destroy(opts->p.pool);
79
+ sam_global_args_free(&opts->ga);
80
+ free(opts);
81
+ }
82
+
83
+ static void cleanup_state(state_t* state)
84
+ {
85
+ if (!state) return;
86
+ free(state->rg_id);
87
+ if (state->output_file) sam_close(state->output_file);
88
+ sam_hdr_destroy(state->output_header);
89
+ if (state->input_file) sam_close(state->input_file);
90
+ sam_hdr_destroy(state->input_header);
91
+ free(state);
92
+ }
93
+
94
+ // Converts \t and \n into real tabs and newlines
95
+ static char* basic_unescape(const char* in)
96
+ {
97
+ assert(in);
98
+ char *ptr, *out;
99
+ out = ptr = malloc(strlen(in)+1);
100
+ size_t size = 0;
101
+ while (*in) {
102
+ if (*in == '\\') {
103
+ ++in;
104
+ if (*in == '\0') {
105
+ fprintf(stderr, "[%s] Unterminated escape sequence.\n", __func__);
106
+ free(out);
107
+ return NULL;
108
+ }
109
+ switch (*in) {
110
+ case '\\':
111
+ *ptr = '\\';
112
+ break;
113
+ case 't':
114
+ *ptr = '\t';
115
+ break;
116
+ case 'n':
117
+ fprintf(stderr, "[%s] \\n in escape sequence is not supported.\n", __func__);
118
+ free(out);
119
+ return NULL;
120
+ default:
121
+ fprintf(stderr, "[%s] Unsupported escape sequence.\n", __func__);
122
+ free(out);
123
+ return NULL;
124
+ }
125
+ } else {
126
+ *ptr = *in;
127
+ }
128
+ ++in;
129
+ ++ptr;
130
+ ++size;
131
+ }
132
+ *ptr = '\0';
133
+ ++size;
134
+ char* tmp = (char*)realloc(out, size);
135
+ if (!tmp) {
136
+ free(out);
137
+ }
138
+ return tmp;
139
+ }
140
+
141
+ // Malloc a string containing [s,slim) or to the end of s if slim is NULL.
142
+ // If lenp is non-NULL, stores the length of the resulting string there.
143
+ static char *dup_substring(const char *s, const char *slim, size_t *lenp)
144
+ {
145
+ size_t len = slim? (slim - s) : strlen(s);
146
+ char *ns = malloc(len+1);
147
+ if (ns == NULL) return NULL;
148
+ memcpy(ns, s, len);
149
+ ns[len] = '\0';
150
+ if (lenp) *lenp = len;
151
+ return ns;
152
+ }
153
+
154
+
155
+ // Given a @RG line return the id
156
+ static char* get_rg_id(const char *line)
157
+ {
158
+ const char *id = strstr(line, "\tID:");
159
+ if (! id) return NULL;
160
+
161
+ id += 4;
162
+ return dup_substring(id, strchr(id, '\t'), NULL);
163
+ }
164
+
165
+
166
+ static void usage(FILE *fp)
167
+ {
168
+ fprintf(fp,
169
+ "Usage: samtools addreplacerg [options] [-r <@RG line> | -R <existing id>] [-m orphan_only|overwrite_all] [-o <output.bam>] <input.bam>\n"
170
+ "\n"
171
+ "Options:\n"
172
+ " -m MODE Set the mode of operation from one of overwrite_all, orphan_only [overwrite_all]\n"
173
+ " -o FILE Where to write output to [stdout]\n"
174
+ " -r STRING @RG line text\n"
175
+ " -R STRING ID of @RG line in existing header to use\n"
176
+ " -u Output uncompressed data\n"
177
+ " -w Overwrite an existing @RG line\n"
178
+ " --no-PG Do not add a PG line\n"
179
+ );
180
+ sam_global_opt_help(fp, "..O..@..");
181
+ }
182
+
183
+ static bool parse_args(int argc, char** argv, parsed_opts_t** opts)
184
+ {
185
+ *opts = NULL;
186
+ int n;
187
+
188
+ if (argc == 1) { usage(stdout); return true; }
189
+
190
+ parsed_opts_t* retval = calloc(1, sizeof(parsed_opts_t));
191
+ if (! retval ) {
192
+ fprintf(stderr, "[%s] Out of memory allocating parsed_opts_t\n", __func__);
193
+ return false;
194
+ }
195
+ // Set defaults
196
+ retval->mode = overwrite_all;
197
+ sam_global_args_init(&retval->ga);
198
+ static const struct option lopts[] = {
199
+ SAM_OPT_GLOBAL_OPTIONS(0, 0, 'O', 0, 0, '@'),
200
+ {"no-PG", no_argument, NULL, 1},
201
+ { NULL, 0, NULL, 0 }
202
+ };
203
+ kstring_t rg_line = {0,0,NULL};
204
+
205
+ while ((n = getopt_long(argc, argv, "r:R:m:o:O:h@:uw", lopts, NULL)) >= 0) {
206
+ switch (n) {
207
+ case 'r':
208
+ // Are we adding to existing rg line?
209
+ if (ks_len(&rg_line) == 0) {
210
+ if (strlen(optarg)<3 || (optarg[0] != '@' && optarg[1] != 'R' && optarg[2] != 'G')) {
211
+ kputs("@RG\t", &rg_line);
212
+ }
213
+ } else {
214
+ kputs("\t", &rg_line);
215
+ }
216
+ kputs(optarg, &rg_line);
217
+ break;
218
+ case 'R':
219
+ retval->rg_id = strdup(optarg);
220
+ break;
221
+ case 'm': {
222
+ if (strcmp(optarg, "overwrite_all") == 0) {
223
+ retval->mode = overwrite_all;
224
+ } else if (strcmp(optarg, "orphan_only") == 0) {
225
+ retval->mode = orphan_only;
226
+ } else {
227
+ usage(stderr);
228
+ return false;
229
+ }
230
+ break;
231
+ }
232
+ case 'o':
233
+ retval->output_name = strdup(optarg);
234
+ break;
235
+ case 'h':
236
+ usage(stdout);
237
+ free(retval);
238
+ return true;
239
+ case 1:
240
+ retval->no_pg = 1;
241
+ break;
242
+ case 'u':
243
+ retval->uncompressed = 1;
244
+ break;
245
+ case 'w':
246
+ retval->overwrite_hdr_rg = 1;
247
+ break;
248
+ case '?':
249
+ usage(stderr);
250
+ free(retval);
251
+ return false;
252
+ case 'O':
253
+ default:
254
+ if (parse_sam_global_opt(n, optarg, lopts, &retval->ga) == 0) break;
255
+ usage(stderr);
256
+ free(retval);
257
+ return false;
258
+ }
259
+ }
260
+ retval->rg_line = ks_release(&rg_line);
261
+
262
+ if (argc-optind < 1) {
263
+ fprintf(stderr, "You must specify an input file.\n");
264
+ usage(stderr);
265
+ cleanup_opts(retval);
266
+ return false;
267
+ }
268
+ if (retval->rg_id && retval->rg_line) {
269
+ fprintf(stderr, "The options -r and -R are mutually exclusive.\n");
270
+ cleanup_opts(retval);
271
+ return false;
272
+ }
273
+
274
+ if (retval->rg_line)
275
+ {
276
+ char* tmp = basic_unescape(retval->rg_line);
277
+
278
+ if ((retval->rg_id = get_rg_id(tmp)) == NULL) {
279
+ fprintf(stderr, "[%s] The supplied RG line lacks an ID tag.\n", __func__);
280
+ free(tmp);
281
+ cleanup_opts(retval);
282
+ return false;
283
+ }
284
+ free(retval->rg_line);
285
+ retval->rg_line = tmp;
286
+ }
287
+ retval->input_name = strdup(argv[optind+0]);
288
+
289
+ if (retval->ga.nthreads > 0) {
290
+ if (!(retval->p.pool = hts_tpool_init(retval->ga.nthreads))) {
291
+ fprintf(stderr, "Error creating thread pool\n");
292
+ return false;
293
+ }
294
+ }
295
+
296
+ *opts = retval;
297
+ return true;
298
+ }
299
+
300
+ static void overwrite_all_func(const state_t* state, bam1_t* file_read)
301
+ {
302
+ uint8_t* data = (uint8_t*)strdup(state->rg_id);
303
+ int len = strlen(state->rg_id)+1;
304
+ // If the old exists delete it
305
+ uint8_t* old = bam_aux_get(file_read, "RG");
306
+ if (old != NULL) {
307
+ bam_aux_del(file_read, old);
308
+ }
309
+
310
+ bam_aux_append(file_read, "RG", 'Z', len, data);
311
+ free(data);
312
+ }
313
+
314
+ static void orphan_only_func(const state_t* state, bam1_t* file_read)
315
+ {
316
+ uint8_t* data = (uint8_t*)strdup(state->rg_id);
317
+ int len = strlen(state->rg_id)+1;
318
+ // If the old exists don't do anything
319
+ uint8_t* old = bam_aux_get(file_read, "RG");
320
+ if (old == NULL) {
321
+ bam_aux_append(file_read, "RG",'Z',len,data);
322
+ }
323
+ free(data);
324
+ }
325
+
326
+ static bool init(const parsed_opts_t* opts, state_t** state_out) {
327
+ char output_mode[9] = "w";
328
+ state_t* retval = (state_t*) calloc(1, sizeof(state_t));
329
+
330
+ if (retval == NULL) {
331
+ fprintf(stderr, "[init] Out of memory allocating state struct.\n");
332
+ return false;
333
+ }
334
+ *state_out = retval;
335
+
336
+ // Open files
337
+ retval->input_file = sam_open_format(opts->input_name, "r", &opts->ga.in);
338
+ if (retval->input_file == NULL) {
339
+ print_error_errno("addreplacerg", "could not open \"%s\"", opts->input_name);
340
+ return false;
341
+ }
342
+ retval->input_header = sam_hdr_read(retval->input_file);
343
+
344
+ retval->output_header = sam_hdr_dup(retval->input_header);
345
+
346
+ if (opts->uncompressed)
347
+ strcat(output_mode, "0");
348
+ if (opts->output_name) // File format auto-detection
349
+ sam_open_mode(output_mode + strlen(output_mode),
350
+ opts->output_name, NULL);
351
+ retval->output_file = sam_open_format(opts->output_name == NULL?"-":opts->output_name, output_mode, &opts->ga.out);
352
+
353
+ if (retval->output_file == NULL) {
354
+ print_error_errno("addreplacerg", "could not create \"%s\"", opts->output_name);
355
+ return false;
356
+ }
357
+
358
+ if (opts->p.pool) {
359
+ hts_set_opt(retval->input_file, HTS_OPT_THREAD_POOL, &opts->p);
360
+ hts_set_opt(retval->output_file, HTS_OPT_THREAD_POOL, &opts->p);
361
+ }
362
+
363
+ if (opts->rg_line) {
364
+ // Append new RG line to header.
365
+ // Check does not already exist
366
+ kstring_t hdr_line = { 0, 0, NULL };
367
+ if (sam_hdr_find_line_id(retval->output_header, "RG", "ID", opts->rg_id, &hdr_line) == 0) {
368
+ if (opts->overwrite_hdr_rg) {
369
+ if(-1 == sam_hdr_remove_line_id(retval->output_header, "RG", "ID", opts->rg_id)) {
370
+ fprintf(stderr, "[init] Error removing the RG line with ID:%s from the output header.\n", opts->rg_id);
371
+ ks_free(&hdr_line);
372
+ return false;
373
+ }
374
+ } else {
375
+ fprintf(stderr, "[init] RG line with ID:%s already present in the header. Use -w to overwrite.\n", opts->rg_id);
376
+ ks_free(&hdr_line);
377
+ return false;
378
+ }
379
+ }
380
+ ks_free(&hdr_line);
381
+
382
+ if (-1 == sam_hdr_add_lines(retval->output_header, opts->rg_line, strlen(opts->rg_line))) {
383
+ fprintf(stderr, "[init] Error adding RG line with ID:%s to the output header.\n", opts->rg_id);
384
+ return false;
385
+ }
386
+ if (opts->mode == overwrite_all &&
387
+ -1 == sam_hdr_remove_except(retval->output_header, "RG", "ID", opts->rg_id)) {
388
+ fprintf(stderr, "[init] Error removing the old RG lines from the output header.\n");
389
+ return false;
390
+ }
391
+ retval->rg_id = strdup(opts->rg_id);
392
+ } else {
393
+ if (opts->rg_id) {
394
+ // Confirm what has been supplied exists
395
+ kstring_t hdr_line = { 0, 0, NULL };
396
+ if (sam_hdr_find_line_id(retval->output_header, "RG", "ID", opts->rg_id, &hdr_line) < 0) {
397
+ fprintf(stderr, "RG ID supplied does not exist in header. Supply full @RG line with -r instead?\n");
398
+ return false;
399
+ }
400
+ retval->rg_id = strdup(opts->rg_id);
401
+ ks_free(&hdr_line);
402
+ } else {
403
+ kstring_t rg_id = { 0, 0, NULL };
404
+ if (sam_hdr_find_tag_id(retval->output_header, "RG", NULL, NULL, "ID", &rg_id) < 0) {
405
+ fprintf(stderr, "No RG specified on command line or in existing header.\n");
406
+ return false;
407
+ }
408
+ retval->rg_id = ks_release(&rg_id);
409
+ }
410
+ }
411
+
412
+ switch (opts->mode) {
413
+ case overwrite_all:
414
+ retval->mode_func = &overwrite_all_func;
415
+ break;
416
+ case orphan_only:
417
+ retval->mode_func = &orphan_only_func;
418
+ break;
419
+ }
420
+
421
+ return true;
422
+ }
423
+
424
+ static bool readgroupise(parsed_opts_t *opts, state_t* state, char *arg_list)
425
+ {
426
+ if (!opts->no_pg && sam_hdr_add_pg(state->output_header, "samtools",
427
+ "VN", samtools_version(),
428
+ arg_list ? "CL": NULL,
429
+ arg_list ? arg_list : NULL,
430
+ NULL))
431
+ return false;
432
+
433
+ if (sam_hdr_write(state->output_file, state->output_header) != 0) {
434
+ print_error_errno("addreplacerg", "[%s] Could not write header to output file", __func__);
435
+ return false;
436
+ }
437
+ char *idx_fn = NULL;
438
+ if (opts->ga.write_index) {
439
+ if (!(idx_fn = auto_index(state->output_file, opts->output_name, state->output_header)))
440
+ return false;
441
+ }
442
+
443
+ bam1_t* file_read = bam_init1();
444
+ int ret;
445
+ while ((ret = sam_read1(state->input_file, state->input_header, file_read)) >= 0) {
446
+ state->mode_func(state, file_read);
447
+
448
+ if (sam_write1(state->output_file, state->output_header, file_read) < 0) {
449
+ print_error_errno("addreplacerg", "[%s] Could not write read to output file", __func__);
450
+ bam_destroy1(file_read);
451
+ free(idx_fn);
452
+ return false;
453
+ }
454
+ }
455
+ bam_destroy1(file_read);
456
+ if (ret != -1) {
457
+ print_error_errno("addreplacerg", "[%s] Error reading from input file", __func__);
458
+ free(idx_fn);
459
+ return false;
460
+ } else {
461
+
462
+ if (opts->ga.write_index) {
463
+ if (sam_idx_save(state->output_file) < 0) {
464
+ print_error_errno("addreplacerg", "[%s] Writing index failed", __func__);
465
+ free(idx_fn);
466
+ return false;
467
+ }
468
+ }
469
+ free(idx_fn);
470
+ return true;
471
+ }
472
+ }
473
+
474
+ int main_addreplacerg(int argc, char** argv)
475
+ {
476
+ parsed_opts_t* opts = NULL;
477
+ state_t* state = NULL;
478
+ char *arg_list = stringify_argv(argc+1, argv-1);
479
+ if (!arg_list)
480
+ return EXIT_FAILURE;
481
+
482
+ if (!parse_args(argc, argv, &opts)) goto error;
483
+ if (opts) { // Not an error but user doesn't want us to proceed
484
+ if (!init(opts, &state) || !readgroupise(opts, state, arg_list))
485
+ goto error;
486
+ }
487
+
488
+ cleanup_state(state);
489
+ cleanup_opts(opts);
490
+ free(arg_list);
491
+
492
+ return EXIT_SUCCESS;
493
+ error:
494
+ cleanup_state(state);
495
+ cleanup_opts(opts);
496
+ free(arg_list);
497
+
498
+ return EXIT_FAILURE;
499
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_ampliconclip.c -- loads amplicon primers from a BED file and cuts reads
2
+ from the 5' end.
3
+
4
+ Copyright (C) 2020-2023 Genome Research Ltd.
5
+
6
+ Authors: Andrew Whitwham <aw7@sanger.ac.uk>
7
+ Rob Davies <rmd+git@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE
26
+ */
27
+
28
+ #include <config.h>
29
+
30
+ #include <assert.h>
31
+ #include <stdbool.h>
32
+ #include <stdlib.h>
33
+ #include <string.h>
34
+ #include <unistd.h>
35
+ #include <errno.h>
36
+ #include "htslib/thread_pool.h"
37
+ #include "sam_opts.h"
38
+ #include <htslib/hts.h>
39
+ #include "htslib/hfile.h"
40
+ #include "htslib/kstring.h"
41
+ #include "htslib/sam.h"
42
+ #include "samtools.h"
43
+ #include "bam_ampliconclip.h"
44
+
45
+ typedef enum {
46
+ soft_clip,
47
+ hard_clip
48
+ } clipping_type;
49
+
50
+ typedef struct {
51
+ int add_pg;
52
+ int use_strand;
53
+ int write_clipped;
54
+ int mark_fail;
55
+ int both;
56
+ int fail_len;
57
+ int filter_len;
58
+ int unmapped;
59
+ int oa_tag;
60
+ int del_tag;
61
+ int tol;
62
+ int unmap_len;
63
+ char *arg_list;
64
+ char *stats_file;
65
+ char *rejects_file;
66
+ } cl_param_t;
67
+
68
+
69
+ static int bed_entry_sort(const void *av, const void *bv) {
70
+ bed_entry_t *a = (bed_entry_t *) av;
71
+ bed_entry_t *b = (bed_entry_t *) bv;
72
+ return a->right < b->right ? -1 : (a->right == b->right ? 0 : 1);
73
+ }
74
+
75
+
76
+ int load_bed_file_multi_ref(char *infile, int get_strand, int sort_by_pos, khash_t(bed_list_hash) *bed_lists) {
77
+ hFILE *fp;
78
+ int line_count = 0, ret;
79
+ int64_t left, right;
80
+ kstring_t line = KS_INITIALIZE;
81
+ bed_entry_list_t *list;
82
+ khiter_t bed_itr;
83
+
84
+ if ((fp = hopen(infile, "r")) == NULL) {
85
+ print_error_errno("amplicon", "unable to open file %s.", infile);
86
+ return 1;
87
+ }
88
+
89
+ char ref[1024];
90
+
91
+ while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) {
92
+ line_count++;
93
+ int hret;
94
+ char strand;
95
+
96
+ if (line.l == 0 || *line.s == '#') continue;
97
+ if (strncmp(line.s, "track ", 6) == 0) continue;
98
+ if (strncmp(line.s, "browser ", 8) == 0) continue;
99
+
100
+ if (get_strand) {
101
+ if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64" %*s %*s %c",
102
+ ref, &left, &right, &strand) != 4) {
103
+ fprintf(stderr, "[amplicon] error: bad bed file format in line %d of %s.\n"
104
+ "(N.B. ref/chrom name limited to 1023 characters.)\n",
105
+ line_count, infile);
106
+ ret = 1;
107
+ goto error;
108
+ }
109
+ } else {
110
+ if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64,
111
+ ref, &left, &right) != 3) {
112
+ fprintf(stderr, "[amplicon] error: bad bed file format in line %d of %s\n"
113
+ "(N.B. ref/chrom name limited to 1023 characters.)\n",
114
+ line_count, infile);
115
+ ret = 1;
116
+ goto error;
117
+ }
118
+ }
119
+
120
+ bed_itr = kh_get(bed_list_hash, bed_lists, ref);
121
+
122
+ if (bed_itr == kh_end(bed_lists)) { // new ref entry
123
+ char *ref_name = strdup(ref); // need a copy for the hash key
124
+
125
+ if (!ref_name) {
126
+ fprintf(stderr, "[amplicon] error: unable to allocate memory for ref name.\n");
127
+ ret = 1;
128
+ goto error;
129
+ }
130
+
131
+ bed_itr = kh_put(bed_list_hash, bed_lists, ref_name, &hret);
132
+
133
+ if (hret > 0) {
134
+ list = &kh_val(bed_lists, bed_itr);
135
+
136
+ // initialise the new hash entry
137
+ list->longest = 0;
138
+ list->size = 0;
139
+ list->length = 0;
140
+ list->bp = NULL;
141
+ } else {
142
+ fprintf(stderr, "[amplicon] error: ref hashing failure.\n");
143
+ ret = 1;
144
+ goto error;
145
+ }
146
+ } else { // existing ref
147
+ list = &kh_val(bed_lists, bed_itr);
148
+ }
149
+
150
+ if (list->length == list->size) {
151
+ bed_entry_t *tmp;
152
+
153
+ list->size += list->size / 2 + 256;
154
+
155
+ if ((tmp = realloc(list->bp, list->size * sizeof(bed_entry_t))) == NULL) {
156
+ fprintf(stderr, "[amplicon] error: unable to allocate more memory for bed data.\n");
157
+ ret = 1;
158
+ goto error;
159
+ }
160
+
161
+ list->bp = tmp;
162
+ }
163
+
164
+ list->bp[list->length].left = left;
165
+ list->bp[list->length].right = right;
166
+
167
+ if (get_strand) {
168
+ if (strand == '+') {
169
+ list->bp[list->length].rev = 0;
170
+ } else if (strand == '-') {
171
+ list->bp[list->length].rev = 1;
172
+ } else {
173
+ fprintf(stderr, "[amplicon] error: bad strand value in line %d, expecting '+' or '-', found '%c'.\n",
174
+ line_count, strand);
175
+ ret = 1;
176
+ goto error;
177
+ }
178
+ }
179
+
180
+ if (right - left > list->longest)
181
+ list->longest = right - left;
182
+
183
+ list->length++;
184
+ }
185
+
186
+ if (sort_by_pos) {
187
+ for (bed_itr = kh_begin(bed_lists); bed_itr != kh_end(bed_lists); ++bed_itr) {
188
+ if (kh_exist(bed_lists, bed_itr)) {
189
+ list = &kh_val(bed_lists, bed_itr);
190
+ qsort(list->bp, list->length, sizeof(list->bp[0]), bed_entry_sort);
191
+ }
192
+ }
193
+ }
194
+
195
+ if (kh_size(bed_lists) > 0) {// any entries
196
+ ret = 0;
197
+ } else {
198
+ ret = 1;
199
+ }
200
+
201
+ error:
202
+ ks_free(&line);
203
+
204
+ if (hclose(fp) != 0) {
205
+ fprintf(stderr, "[amplicon] warning: failed to close %s", infile);
206
+ }
207
+
208
+ return ret;
209
+ }
210
+
211
+
212
+ void destroy_bed_hash(khash_t(bed_list_hash) *hash) {
213
+ khiter_t itr;
214
+
215
+ for (itr = kh_begin(hash); itr != kh_end(hash); ++itr) {
216
+ if (kh_exist(hash, itr)) {
217
+ free(kh_val(hash, itr).bp);
218
+ free((char *)kh_key(hash, itr));
219
+ kh_key(hash, itr) = NULL;
220
+ }
221
+ }
222
+
223
+ kh_destroy(bed_list_hash, hash);
224
+ }
225
+
226
+
227
+ static int matching_clip_site(bed_entry_list_t *sites, hts_pos_t pos,
228
+ int is_rev, int use_strand, int64_t longest,
229
+ cl_param_t *param) {
230
+ int i, size; // may need this to be variable
231
+ int tol = param->tol;
232
+ int l = 0, mid = sites->length / 2, r = sites->length;
233
+ int pos_tol = is_rev ? (pos > tol ? pos - tol : 0) : pos;
234
+
235
+ while (r - l > 1) {
236
+ if (sites->bp[mid].right <= pos_tol) {
237
+ l = mid;
238
+ } else {
239
+ r = mid;
240
+ }
241
+ mid = (l + r) / 2;
242
+ }
243
+
244
+ size = 0;
245
+
246
+ for (i = l; i < sites->length; i++) {
247
+ hts_pos_t mod_left, mod_right;
248
+
249
+ if (use_strand && is_rev != sites->bp[i].rev)
250
+ continue;
251
+
252
+ if (is_rev) {
253
+ mod_left = sites->bp[i].left;
254
+ mod_right = sites->bp[i].right + tol;
255
+ } else {
256
+ if (sites->bp[i].left > tol) {
257
+ mod_left = sites->bp[i].left - tol;
258
+ } else {
259
+ mod_left = 0;
260
+ }
261
+ mod_right = sites->bp[i].right;
262
+ }
263
+
264
+ if (pos + longest + tol < mod_right)
265
+ break;
266
+
267
+ if (pos >= mod_left && pos <= mod_right) {
268
+ if (is_rev) {
269
+ if (size < pos - sites->bp[i].left) {
270
+ size = pos - sites->bp[i].left;
271
+ }
272
+ } else {
273
+ if (size < sites->bp[i].right - pos) {
274
+ size = sites->bp[i].right - pos;
275
+ }
276
+ }
277
+ }
278
+ }
279
+
280
+ return size;
281
+ }
282
+
283
+
284
+ static int bam_trim_left(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
285
+ clipping_type clipping) {
286
+ uint32_t *orig_cigar = bam_get_cigar(rec);
287
+ uint8_t *orig_seq = bam_get_seq(rec);
288
+ uint8_t *orig_qual = bam_get_qual(rec);
289
+ uint8_t *orig_aux = bam_get_aux(rec);
290
+ uint32_t *new_cigar;
291
+ uint8_t *new_qual;
292
+ size_t orig_l_aux = bam_get_l_aux(rec);
293
+ uint32_t i, j;
294
+ uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
295
+ hts_pos_t new_pos = rec->core.pos;
296
+ uint32_t cig_type, cig_op;
297
+
298
+ if (rec->l_data + 8 > rec_out->m_data) {
299
+ uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
300
+ if (!new_data) {
301
+ fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
302
+ return 1;
303
+ }
304
+ rec_out->data = new_data;
305
+ rec_out->m_data = rec->l_data + 8;
306
+ }
307
+
308
+ // Copy core data & name
309
+ memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
310
+ memcpy(rec_out->data, rec->data, rec->core.l_qname);
311
+
312
+ // Modify CIGAR
313
+ new_cigar = bam_get_cigar(rec_out);
314
+
315
+ for (i = 0; i < rec->core.n_cigar; i++) {
316
+ cig_op = bam_cigar_op(orig_cigar[i]);
317
+ cig_type = bam_cigar_type(cig_op);
318
+
319
+ if (cig_op == BAM_CHARD_CLIP) {
320
+ hardclip += bam_cigar_oplen(orig_cigar[i]);
321
+ } else {
322
+ if (cig_type & 2) {
323
+ if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
324
+ ref_remove -= bam_cigar_oplen(orig_cigar[i]);
325
+ } else {
326
+ break;
327
+ }
328
+ new_pos += bam_cigar_oplen(orig_cigar[i]);
329
+ }
330
+ if (cig_type & 1) {
331
+ qry_removed += bam_cigar_oplen(orig_cigar[i]);
332
+ }
333
+ }
334
+ }
335
+
336
+ if (i < rec->core.n_cigar) {
337
+ cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
338
+
339
+ // account for the last operation
340
+ if (cig_type & 2) {
341
+ new_pos += ref_remove;
342
+ }
343
+ if (cig_type & 1) {
344
+ qry_removed += ref_remove;
345
+ }
346
+ } else {
347
+ if (clipping == hard_clip) {
348
+
349
+ rec_out->core.l_qseq = 0;
350
+ rec_out->core.n_cigar = 0;
351
+
352
+ if (orig_l_aux)
353
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
354
+
355
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
356
+
357
+ return 0;
358
+ }
359
+
360
+ qry_removed = rec->core.l_qseq;
361
+ }
362
+
363
+ j = 0;
364
+ if (clipping == hard_clip && hardclip + qry_removed > 0) {
365
+ new_cigar[j++] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
366
+ }
367
+ if (clipping == soft_clip) {
368
+ if (hardclip > 0) {
369
+ new_cigar[j++] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
370
+ }
371
+ if (qry_removed > 0) {
372
+ new_cigar[j++] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
373
+ }
374
+ }
375
+
376
+ if (i < rec->core.n_cigar
377
+ && bam_cigar_oplen(orig_cigar[i]) > ref_remove) {
378
+ new_cigar[j++] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
379
+
380
+ // fill in the rest of the cigar
381
+ i++;
382
+
383
+ for (; i < rec->core.n_cigar; i++) {
384
+ new_cigar[j++] = orig_cigar[i];
385
+ }
386
+ }
387
+
388
+ rec_out->core.n_cigar = j;
389
+
390
+ if (clipping == soft_clip) {
391
+ qry_removed = 0; // Copy all the sequence and confidence values
392
+ }
393
+
394
+ new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
395
+ // Copy remaining SEQ
396
+ if ((qry_removed & 1) == 0) {
397
+ memcpy(bam_get_seq(rec_out), orig_seq + (qry_removed / 2),
398
+ (rec->core.l_qseq - qry_removed + 1) / 2); // +1 to account for odd numbers
399
+ } else {
400
+ uint8_t *in = orig_seq + qry_removed / 2;
401
+ uint8_t *out = bam_get_seq(rec_out);
402
+ uint32_t i;
403
+ for (i = qry_removed; i < rec->core.l_qseq - 1; i += 2) {
404
+ *out++ = ((in[0] & 0x0f) << 4) | ((in[1] & 0xf0) >> 4);
405
+ in++;
406
+ }
407
+ if (i < rec->core.l_qseq) {
408
+ *out++ = (in[0] & 0x0f) << 4;
409
+ }
410
+ assert(out == new_qual);
411
+ }
412
+
413
+ // Copy remaining QUAL
414
+ memmove(new_qual, orig_qual, rec->core.l_qseq - qry_removed);
415
+
416
+ // Set new l_qseq
417
+ rec_out->core.l_qseq -= qry_removed;
418
+
419
+ // Move AUX
420
+ if (orig_l_aux)
421
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
422
+
423
+ // Set new l_data
424
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
425
+
426
+ // put in new pos
427
+ rec_out->core.pos = new_pos;
428
+
429
+ return 0;
430
+ }
431
+
432
+
433
+ static int bam_trim_right(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
434
+ clipping_type clipping) {
435
+ uint32_t *orig_cigar = bam_get_cigar(rec);
436
+ uint8_t *orig_seq = bam_get_seq(rec);
437
+ uint8_t *orig_qual = bam_get_qual(rec);
438
+ uint8_t *orig_aux = bam_get_aux(rec);
439
+ uint32_t *new_cigar;
440
+ uint32_t new_n_cigar = 0;
441
+ uint8_t *new_qual;
442
+ size_t orig_l_aux = bam_get_l_aux(rec);
443
+ int32_t i;
444
+ int32_t j;
445
+ uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
446
+ uint32_t cig_type, cig_op;
447
+
448
+ if (rec->l_data + 8 > rec_out->m_data) {
449
+ uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
450
+ if (!new_data) {
451
+ fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
452
+ return 1;
453
+ }
454
+ rec_out->data = new_data;
455
+ rec_out->m_data = rec->l_data + 8;
456
+ }
457
+
458
+ // Copy core data & name
459
+ memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
460
+ memcpy(rec_out->data, rec->data, rec->core.l_qname);
461
+
462
+ // Modify CIGAR here
463
+ new_cigar = bam_get_cigar(rec_out);
464
+
465
+ for (i = rec->core.n_cigar - 1; i >= 0; --i) {
466
+ cig_op = bam_cigar_op(orig_cigar[i]);
467
+ cig_type = bam_cigar_type(cig_op);
468
+
469
+ if (cig_op == BAM_CHARD_CLIP) {
470
+ hardclip += bam_cigar_oplen(orig_cigar[i]);
471
+ } else {
472
+ if (cig_type & 2) {
473
+ if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
474
+ ref_remove -= bam_cigar_oplen(orig_cigar[i]);
475
+ } else {
476
+ break;
477
+ }
478
+ }
479
+ if (cig_type & 1) {
480
+ qry_removed += bam_cigar_oplen(orig_cigar[i]);
481
+ }
482
+ }
483
+ }
484
+
485
+ if (i >= 0) {
486
+ cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
487
+ if (cig_type & 1) {
488
+ qry_removed += ref_remove;
489
+ }
490
+ j = i;
491
+ if (qry_removed > 0) j++;
492
+ if (hardclip > 0 && (clipping == soft_clip || qry_removed == 0)) j++;
493
+ } else {
494
+ if (clipping == hard_clip) {
495
+
496
+ rec_out->core.l_qseq = 0;
497
+ rec_out->core.n_cigar = 0;
498
+
499
+ if (orig_l_aux)
500
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
501
+
502
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
503
+
504
+ return 0;
505
+ }
506
+
507
+ qry_removed = rec->core.l_qseq;
508
+ j = 0;
509
+ if (hardclip > 0 && clipping == soft_clip) j++;
510
+ }
511
+
512
+ if (clipping == hard_clip && hardclip + qry_removed > 0) {
513
+ new_cigar[j] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
514
+ new_n_cigar++;
515
+ }
516
+ if (clipping == soft_clip) {
517
+ if (hardclip > 0) {
518
+ new_cigar[j] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
519
+ new_n_cigar++;
520
+ if (qry_removed > 0) --j;
521
+ }
522
+ if (qry_removed > 0) {
523
+ new_cigar[j] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
524
+ new_n_cigar++;
525
+ }
526
+ }
527
+
528
+ if (j > 0) {
529
+ new_cigar[--j] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
530
+ new_n_cigar++;
531
+ }
532
+
533
+ // fill in the rest of the cigar
534
+ while (j > 0) {
535
+ new_cigar[--j] = orig_cigar[--i];
536
+ new_n_cigar++;
537
+ }
538
+
539
+ rec_out->core.n_cigar = new_n_cigar;
540
+
541
+ if (clipping == soft_clip)
542
+ qry_removed = 0; // Copy all the sequence and confidence values
543
+
544
+ new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
545
+ // Copy remaining SEQ
546
+ memcpy(bam_get_seq(rec_out), orig_seq, (rec->core.l_qseq - qry_removed + 1) / 2);
547
+
548
+ // Copy remaining QUAL
549
+ memcpy(new_qual, orig_qual, rec->core.l_qseq - qry_removed);
550
+
551
+ // Set new l_qseq
552
+ rec_out->core.l_qseq -= qry_removed;
553
+
554
+ // Copy AUX
555
+ if (orig_l_aux)
556
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
557
+
558
+ // Set new l_data
559
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
560
+
561
+ return 0;
562
+ }
563
+
564
+
565
+ static hts_pos_t active_query_len(bam1_t *b) {
566
+ uint32_t *cigar = bam_get_cigar(b);
567
+ uint32_t cig_type, cig_op;
568
+ hts_pos_t len = 0;
569
+ int i;
570
+
571
+ for (i = 0; i < b->core.n_cigar; i++) {
572
+ cig_op = bam_cigar_op(cigar[i]);
573
+ cig_type = bam_cigar_type(cig_op);
574
+
575
+ if ((cig_type & 1) && (cig_op != BAM_CSOFT_CLIP)) {
576
+ len += bam_cigar_oplen(cigar[i]);
577
+ }
578
+ }
579
+
580
+ return len;
581
+ }
582
+
583
+
584
+ static inline void swap_bams(bam1_t **a, bam1_t **b) {
585
+ bam1_t *tmp = *a;
586
+ *a = *b;
587
+ *b = tmp;
588
+ }
589
+
590
+
591
+ // Format OA:Z:(RNAME,POS,strand,CIGAR,MAPQ,NM;
592
+ static inline int tag_original_data(bam1_t *orig, kstring_t *oa_tag) {
593
+ char strand;
594
+ uint8_t *nm_tag, *old_oa_tag;
595
+ uint32_t *cigar;
596
+ int64_t nm = 0;
597
+ int i, res = 0;
598
+
599
+ ks_clear(oa_tag);
600
+
601
+ // if there is an existing OA tag the new one gets appended to it
602
+ if ((old_oa_tag = bam_aux_get(orig, "OA"))) {
603
+ res |= ksprintf(oa_tag, "%s", bam_aux2Z(old_oa_tag)) < 0;
604
+ }
605
+
606
+ if (orig->core.flag & BAM_FREVERSE)
607
+ strand = '-';
608
+ else
609
+ strand = '+';
610
+
611
+ if ((nm_tag = bam_aux_get(orig, "NM"))) {
612
+ nm = bam_aux2i(nm_tag);
613
+ }
614
+
615
+ res |= ksprintf(oa_tag, "%s,%"PRIhts_pos",%c,", bam_get_qname(orig), orig->core.pos + 1, strand) < 0;
616
+
617
+ for (i = 0, cigar = bam_get_cigar(orig); i < orig->core.n_cigar && res == 0; ++i) {
618
+ res |= kputw(bam_cigar_oplen(cigar[i]), oa_tag) < 0;
619
+ res |= kputc(bam_cigar_opchr(cigar[i]), oa_tag) < 0;
620
+ }
621
+
622
+ if (nm_tag) {
623
+ res |= ksprintf(oa_tag, ",%d,%"PRId64";", orig->core.qual, nm) < 0;
624
+ } else {
625
+ res |= ksprintf(oa_tag, "%d,;", orig->core.qual) < 0;
626
+ }
627
+
628
+ return res;
629
+ }
630
+
631
+
632
+ static int bam_clip(samFile *in, samFile *out, samFile *reject, char *bedfile,
633
+ clipping_type clipping, cl_param_t *param) {
634
+ int ret = 1, r, file_open = 0;
635
+
636
+ bam_hdr_t *header = NULL;
637
+ bam1_t *b = NULL, *b_tmp = NULL;
638
+ long f_count = 0, r_count = 0, n_count = 0, l_count = 0, l_exclude = 0, b_count = 0;
639
+ long filtered = 0, written = 0, failed = 0;
640
+ kstring_t str = KS_INITIALIZE;
641
+ kstring_t oat = KS_INITIALIZE;
642
+ kstring_t seq = KS_INITIALIZE;
643
+ bed_entry_list_t *sites;
644
+ FILE *stats_fp = stderr;
645
+ khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash);
646
+
647
+ if (load_bed_file_multi_ref(bedfile, param->use_strand, 1, bed_hash)) {
648
+ fprintf(stderr, "[ampliconclip] error: unable to load bed file.\n");
649
+ goto fail;
650
+ }
651
+
652
+ if ((header = sam_hdr_read(in)) == NULL) {
653
+ fprintf(stderr, "[ampliconclip] error: could not read header\n");
654
+ goto fail;
655
+ }
656
+
657
+ // changing pos can ruin coordinate sort order
658
+ if (sam_hdr_find_tag_hd(header, "SO", &str) == 0 && str.s && strcmp(str.s, "coordinate") == 0) {
659
+ const char *new_order = "unknown";
660
+
661
+ if (sam_hdr_update_hd(header, "SO", new_order) == -1) {
662
+ fprintf(stderr, "[ampliconclip] error: unable to change sort order to 'SO:%s'\n", new_order);
663
+ goto fail;
664
+ }
665
+ }
666
+
667
+ ks_free(&str);
668
+
669
+ if (param->add_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(),
670
+ param->arg_list ? "CL" : NULL,
671
+ param->arg_list ? param->arg_list : NULL,
672
+ NULL) != 0) {
673
+ fprintf(stderr, "[ampliconclip] warning: unable to add @PG line to header.\n");
674
+ }
675
+ if (sam_hdr_write(out, header) < 0) {
676
+ fprintf(stderr, "[ampliconclip] error: could not write header.\n");
677
+ goto fail;
678
+ }
679
+
680
+ if (reject) {
681
+ if (sam_hdr_write(reject, header) < 0) {
682
+ fprintf(stderr, "[ampliconclip] error: could not write header to rejects file.\n");
683
+ goto fail;
684
+ }
685
+ }
686
+
687
+ b = bam_init1();
688
+ b_tmp = bam_init1();
689
+ if (!b || !b_tmp) {
690
+ fprintf(stderr, "[ampliconclip] error: out of memory when trying to create record.\n");
691
+ goto fail;
692
+ }
693
+
694
+ int32_t last_tid = -1;
695
+ int ref_found = 0;
696
+
697
+ while ((r = sam_read1(in, header, b)) >= 0) {
698
+ hts_pos_t pos;
699
+ int is_rev;
700
+ int p_size;
701
+ int been_clipped = 0, filter = 0;
702
+ int exclude = (BAM_FUNMAP | BAM_FQCFAIL);
703
+ khiter_t itr;
704
+
705
+ l_count++;
706
+
707
+ if (b->core.tid != last_tid) {
708
+ const char *ref_name;
709
+
710
+ ref_found = 0;
711
+ last_tid = b->core.tid;
712
+
713
+ if ((ref_name = sam_hdr_tid2name(header, b->core.tid)) != NULL) {
714
+ itr = kh_get(bed_list_hash, bed_hash, ref_name);
715
+
716
+ if (itr != kh_end(bed_hash)) {
717
+ sites = &kh_val(bed_hash, itr);
718
+ ref_found = 1;
719
+ }
720
+ }
721
+ }
722
+
723
+ if (!(b->core.flag & exclude) && ref_found) {
724
+ if (param->oa_tag)
725
+ if (tag_original_data(b, &oat))
726
+ goto fail;
727
+
728
+ if (!param->both) {
729
+ if (bam_is_rev(b)) {
730
+ pos = bam_endpos(b);
731
+ is_rev = 1;
732
+ } else {
733
+ pos = b->core.pos;
734
+ is_rev = 0;
735
+ }
736
+
737
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
738
+ if (is_rev) {
739
+ if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
740
+ goto fail;
741
+
742
+ swap_bams(&b, &b_tmp);
743
+ r_count++;
744
+ } else {
745
+ if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
746
+ goto fail;
747
+
748
+ swap_bams(&b, &b_tmp);
749
+ f_count++;
750
+ }
751
+
752
+ if (param->oa_tag) {
753
+ if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
754
+ goto fail;
755
+ }
756
+
757
+ if (param->del_tag) {
758
+ uint8_t *tag;
759
+
760
+ if ((tag = bam_aux_get(b, "NM")))
761
+ bam_aux_del(b, tag);
762
+
763
+ if ((tag = bam_aux_get(b, "MD")))
764
+ bam_aux_del(b, tag);
765
+ }
766
+
767
+ been_clipped = 1;
768
+ } else {
769
+ if (param->mark_fail) {
770
+ b->core.flag |= BAM_FQCFAIL;
771
+ }
772
+
773
+ n_count++;
774
+ }
775
+ } else {
776
+ int left = 0, right = 0;
777
+
778
+ // left first
779
+ pos = b->core.pos;
780
+ is_rev = 0;
781
+
782
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
783
+ if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
784
+ goto fail;
785
+
786
+ swap_bams(&b, &b_tmp);
787
+ f_count++;
788
+ left = 1;
789
+ been_clipped = 1;
790
+ }
791
+
792
+ // the right
793
+ pos = bam_endpos(b);
794
+ is_rev = 1;
795
+
796
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
797
+ if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
798
+ goto fail;
799
+
800
+ swap_bams(&b, &b_tmp);
801
+ r_count++;
802
+ right = 1;
803
+ been_clipped = 1;
804
+ }
805
+
806
+ if (left || right) {
807
+ uint8_t *tag;
808
+
809
+ if (param->oa_tag) {
810
+ if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
811
+ goto fail;
812
+ }
813
+
814
+ if (param->del_tag) {
815
+ if ((tag = bam_aux_get(b, "NM")))
816
+ bam_aux_del(b, tag);
817
+
818
+ if ((tag = bam_aux_get(b, "MD")))
819
+ bam_aux_del(b, tag);
820
+ }
821
+ }
822
+
823
+ if (left && right) {
824
+ b_count++;
825
+ } else if (!left && !right) {
826
+ if (param->mark_fail) {
827
+ b->core.flag |= BAM_FQCFAIL;
828
+ }
829
+
830
+ n_count++;
831
+ }
832
+ }
833
+
834
+ if (param->fail_len >= 0 || param->filter_len >= 0 || param->unmap_len >= 0) {
835
+ hts_pos_t aql = active_query_len(b);
836
+
837
+ if (param->fail_len >= 0 && aql <= param->fail_len) {
838
+ b->core.flag |= BAM_FQCFAIL;
839
+ }
840
+
841
+ if (param->filter_len >= 0 && aql <= param->filter_len) {
842
+ filter = 1;
843
+ }
844
+
845
+ if (param->unmap_len >= 0 && aql <= param->unmap_len) {
846
+
847
+ if (ks_resize(&seq, b->core.l_qseq) < 0) {
848
+ fprintf(stderr, "[ampliconclip] error: allocate memory for sequence %s\n", bam_get_seq(b));
849
+ goto fail;
850
+ }
851
+
852
+ ks_clear(&seq);
853
+ char *sb = ks_str(&seq);
854
+ uint8_t *sequence = bam_get_seq(b);
855
+ int i;
856
+
857
+ for (i = 0; i < b->core.l_qseq ; ++i) {
858
+ *sb++ = seq_nt16_str[bam_seqi(sequence, i)];
859
+ }
860
+
861
+ if (bam_set1(b_tmp, b->core.l_qname - b->core.l_extranul - 1, bam_get_qname(b),
862
+ (b->core.flag | BAM_FUNMAP), b->core.tid, b->core.pos, 0,
863
+ 0, NULL, b->core.mtid, b->core.mpos, b->core.isize,
864
+ b->core.l_qseq, seq.s, (const char *)bam_get_qual(b),
865
+ bam_get_l_aux(b)) < 0) {
866
+ fprintf(stderr, "[ampliconclip] error: could not unmap read %s\n", bam_get_seq(b));
867
+ goto fail;
868
+ }
869
+
870
+ memcpy(bam_get_aux(b_tmp), bam_get_aux(b), bam_get_l_aux(b));
871
+ b_tmp->l_data += bam_get_l_aux(b);
872
+ swap_bams(&b, &b_tmp);
873
+ }
874
+ }
875
+
876
+ if (b->core.flag & BAM_FQCFAIL) {
877
+ failed++;
878
+ }
879
+
880
+ if (param->write_clipped && !been_clipped) {
881
+ filter = 1;
882
+ }
883
+
884
+ } else {
885
+ l_exclude++;
886
+
887
+ if (param->unmapped) {
888
+ filter = 1;
889
+ }
890
+ }
891
+
892
+ if (!filter) {
893
+ if (sam_write1(out, header, b) < 0) {
894
+ fprintf(stderr, "[ampliconclip] error: could not write line %ld.\n", l_count);
895
+ goto fail;
896
+ }
897
+
898
+ written++;
899
+ } else {
900
+ if (reject) {
901
+ if (sam_write1(reject, header, b) < 0) {
902
+ fprintf(stderr, "[ampliconclip] error: could not write to reject file %s\n",
903
+ param->rejects_file);
904
+ goto fail;
905
+ }
906
+ }
907
+
908
+ filtered++;
909
+ }
910
+ }
911
+
912
+ if (r < -1) {
913
+ fprintf(stderr, "[ampliconclip] error: failed to read input.\n");
914
+ goto fail;
915
+ }
916
+
917
+ if (param->stats_file) {
918
+ if ((stats_fp = fopen(param->stats_file, "w")) == NULL) {
919
+ fprintf(stderr, "[ampliconclip] warning: cannot write stats to %s.\n", param->stats_file);
920
+ } else {
921
+ file_open = 1;
922
+ }
923
+ }
924
+
925
+ fprintf(stats_fp, "COMMAND: %s\n"
926
+ "TOTAL READS: %ld\n"
927
+ "TOTAL CLIPPED: %ld\n"
928
+ "FORWARD CLIPPED: %ld\n"
929
+ "REVERSE CLIPPED: %ld\n"
930
+ "BOTH CLIPPED: %ld\n"
931
+ "NOT CLIPPED: %ld\n"
932
+ "EXCLUDED: %ld\n"
933
+ "FILTERED: %ld\n"
934
+ "FAILED: %ld\n"
935
+ "WRITTEN: %ld\n", param->arg_list, l_count, f_count + r_count,
936
+ f_count, r_count, b_count, n_count, l_exclude,
937
+ filtered, failed, written);
938
+
939
+ if (file_open) {
940
+ fclose(stats_fp);
941
+ }
942
+
943
+ ret = 0;
944
+
945
+ fail:
946
+ destroy_bed_hash(bed_hash);
947
+ ks_free(&oat);
948
+ ks_free(&seq);
949
+ sam_hdr_destroy(header);
950
+ bam_destroy1(b);
951
+ bam_destroy1(b_tmp);
952
+ return ret;
953
+ }
954
+
955
+
956
+ static void usage(void) {
957
+ fprintf(stderr, "Usage: samtools ampliconclip -b BED file <input.bam> -o <output.bam>\n\n");
958
+ fprintf(stderr, "Option: \n");
959
+ fprintf(stderr, " -b FILE BED file of regions (eg amplicon primers) to be removed.\n");
960
+ fprintf(stderr, " -o FILE output file name (default stdout).\n");
961
+ fprintf(stderr, " -f FILE write stats to file name (default stderr)\n");
962
+ fprintf(stderr, " -u Output uncompressed data\n");
963
+ fprintf(stderr, " --soft-clip soft clip amplicon primers from reads (default)\n");
964
+ fprintf(stderr, " --hard-clip hard clip amplicon primers from reads.\n");
965
+ fprintf(stderr, " --both-ends clip on both 5' and 3' ends.\n");
966
+ fprintf(stderr, " --strand use strand data from BED file to match read direction.\n");
967
+ fprintf(stderr, " --clipped only output clipped reads.\n");
968
+ fprintf(stderr, " --fail mark unclipped, mapped reads as QCFAIL.\n");
969
+ fprintf(stderr, " --filter-len INT do not output reads INT size or shorter.\n");
970
+ fprintf(stderr, " --fail-len INT mark as QCFAIL reads INT size or shorter.\n");
971
+ fprintf(stderr, " --unmap-len INT unmap reads INT size or shorter, default 0.\n");
972
+ fprintf(stderr, " --no-excluded do not write excluded reads (unmapped or QCFAIL).\n");
973
+ fprintf(stderr, " --rejects-file FILE file to write filtered reads.\n");
974
+ fprintf(stderr, " --original for clipped entries add an OA tag with original data.\n");
975
+ fprintf(stderr, " --keep-tag for clipped entries keep the old NM and MD tags.\n");
976
+ fprintf(stderr, " --tolerance match region within this number of bases, default 5.\n");
977
+ fprintf(stderr, " --no-PG do not add an @PG line.\n");
978
+ sam_global_opt_help(stderr, "-.O..@-.");
979
+ fprintf(stderr, "\nAbout: Soft clips read alignments where they match BED file defined regions.\n"
980
+ "Default clipping is only on the 5' end.\n\n");
981
+ }
982
+
983
+
984
+ int amplicon_clip_main(int argc, char **argv) {
985
+ int c, ret;
986
+ char wmode[4] = {'w', 'b', 0, 0};
987
+ char *bedfile = NULL, *fnout = "-";
988
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
989
+ htsThreadPool p = {NULL, 0};
990
+ samFile *in = NULL, *out = NULL, *reject = NULL;
991
+ clipping_type clipping = soft_clip;
992
+ cl_param_t param = {1, 0, 0, 0, 0, -1, -1, 0, 0, 1, 5, 0, NULL, NULL, NULL};
993
+
994
+ static const struct option lopts[] = {
995
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
996
+ {"no-PG", no_argument, NULL, 1002},
997
+ {"soft-clip", no_argument, NULL, 1003},
998
+ {"hard-clip", no_argument, NULL, 1004},
999
+ {"strand", no_argument, NULL, 1005},
1000
+ {"clipped", no_argument, NULL, 1006},
1001
+ {"fail", no_argument, NULL, 1007},
1002
+ {"both-ends", no_argument, NULL, 1008},
1003
+ {"filter-len", required_argument, NULL, 1009},
1004
+ {"fail-len", required_argument, NULL, 1010},
1005
+ {"no-excluded", no_argument, NULL, 1011},
1006
+ {"rejects-file", required_argument, NULL, 1012},
1007
+ {"original", no_argument, NULL, 1013},
1008
+ {"keep-tag", no_argument, NULL, 1014},
1009
+ {"tolerance", required_argument, NULL, 1015},
1010
+ {"unmap-len", required_argument, NULL, 1016},
1011
+ {NULL, 0, NULL, 0}
1012
+ };
1013
+
1014
+ while ((c = getopt_long(argc, argv, "b:@:o:O:f:u", lopts, NULL)) >= 0) {
1015
+ switch (c) {
1016
+ case 'b': bedfile = optarg; break;
1017
+ case 'o': fnout = optarg; break;
1018
+ case 'f': param.stats_file = optarg; break;
1019
+ case 'u': wmode[2] = '0'; break;
1020
+ case 1002: param.add_pg = 0; break;
1021
+ case 1003: clipping = soft_clip; break;
1022
+ case 1004: clipping = hard_clip; break;
1023
+ case 1005: param.use_strand = 1; break;
1024
+ case 1006: param.write_clipped = 1; break;
1025
+ case 1007: param.mark_fail = 1; break;
1026
+ case 1008: param.both = 1; break;
1027
+ case 1009: param.filter_len = atoi(optarg); break;
1028
+ case 1010: param.fail_len = atoi(optarg); break;
1029
+ case 1011: param.unmapped = 1; break;
1030
+ case 1012: param.rejects_file = optarg; break;
1031
+ case 1013: param.oa_tag = 1; break;
1032
+ case 1014: param.del_tag = 0; break;
1033
+ case 1015: param.tol = atoi(optarg); break;
1034
+ case 1016: param.unmap_len = atoi(optarg); break;
1035
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1036
+ /* else fall-through */
1037
+ case '?': usage(); exit(1);
1038
+ }
1039
+ }
1040
+
1041
+ if (!bedfile) {
1042
+ usage();
1043
+ return 1;
1044
+ }
1045
+
1046
+ if (optind + 1 > argc) {
1047
+ usage();
1048
+ return 1;
1049
+ }
1050
+
1051
+ if (param.tol < 0) {
1052
+ fprintf(stderr, "[ampliconclip] warning: invalid tolerance of %d,"
1053
+ " resetting tolerance to default of 5.\n", param.tol);
1054
+ param.tol = 5;
1055
+ }
1056
+
1057
+ if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
1058
+ print_error_errno("ampliconclip", "cannot open input file");
1059
+ return 1;
1060
+ }
1061
+
1062
+ sam_open_mode(wmode+1, fnout, NULL);
1063
+
1064
+ if ((out = sam_open_format(fnout, wmode, &ga.out)) == NULL) {
1065
+ print_error_errno("ampliconclip", "cannot open output file");
1066
+ return 1;
1067
+ }
1068
+
1069
+ if (param.rejects_file) {
1070
+ sam_open_mode(wmode+1, param.rejects_file, NULL);
1071
+
1072
+ if ((reject = sam_open_format(param.rejects_file, wmode, &ga.out)) == NULL) {
1073
+ print_error_errno("ampliconclip", "cannot open rejects file");
1074
+ return 1;
1075
+ }
1076
+ }
1077
+
1078
+ if (ga.nthreads > 0) {
1079
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
1080
+ fprintf(stderr, "[ampliconclip] error: cannot create thread pool.\n");
1081
+ return 1;
1082
+ }
1083
+ hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
1084
+ hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
1085
+
1086
+ if (reject) {
1087
+ hts_set_opt(reject, HTS_OPT_THREAD_POOL, &p);
1088
+ }
1089
+ }
1090
+
1091
+ param.arg_list = stringify_argv(argc + 1, argv - 1);
1092
+
1093
+ ret = bam_clip(in, out, reject, bedfile, clipping, &param);
1094
+
1095
+ // cleanup
1096
+ sam_close(in);
1097
+
1098
+ if (sam_close(out) < 0) {
1099
+ fprintf(stderr, "[ampliconclip] error: error while closing output file %s.\n", argv[optind+1]);
1100
+ ret = 1;
1101
+ }
1102
+
1103
+ if (reject) {
1104
+ if (sam_close(reject) < 0) {
1105
+ fprintf(stderr, "[ampliconclip] error: error while closing reject file %s.\n", param.rejects_file);
1106
+ ret = 1;
1107
+ }
1108
+ }
1109
+
1110
+ if (p.pool) hts_tpool_destroy(p.pool);
1111
+
1112
+ sam_global_args_free(&ga);
1113
+ free(param.arg_list);
1114
+
1115
+ return ret;
1116
+ }
1117
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c.pysam.c ADDED
@@ -0,0 +1,1119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_ampliconclip.c -- loads amplicon primers from a BED file and cuts reads
4
+ from the 5' end.
5
+
6
+ Copyright (C) 2020-2023 Genome Research Ltd.
7
+
8
+ Authors: Andrew Whitwham <aw7@sanger.ac.uk>
9
+ Rob Davies <rmd+git@sanger.ac.uk>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in
19
+ all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
+ DEALINGS IN THE SOFTWARE
28
+ */
29
+
30
+ #include <config.h>
31
+
32
+ #include <assert.h>
33
+ #include <stdbool.h>
34
+ #include <stdlib.h>
35
+ #include <string.h>
36
+ #include <unistd.h>
37
+ #include <errno.h>
38
+ #include "htslib/thread_pool.h"
39
+ #include "sam_opts.h"
40
+ #include <htslib/hts.h>
41
+ #include "htslib/hfile.h"
42
+ #include "htslib/kstring.h"
43
+ #include "htslib/sam.h"
44
+ #include "samtools.h"
45
+ #include "bam_ampliconclip.h"
46
+
47
+ typedef enum {
48
+ soft_clip,
49
+ hard_clip
50
+ } clipping_type;
51
+
52
+ typedef struct {
53
+ int add_pg;
54
+ int use_strand;
55
+ int write_clipped;
56
+ int mark_fail;
57
+ int both;
58
+ int fail_len;
59
+ int filter_len;
60
+ int unmapped;
61
+ int oa_tag;
62
+ int del_tag;
63
+ int tol;
64
+ int unmap_len;
65
+ char *arg_list;
66
+ char *stats_file;
67
+ char *rejects_file;
68
+ } cl_param_t;
69
+
70
+
71
+ static int bed_entry_sort(const void *av, const void *bv) {
72
+ bed_entry_t *a = (bed_entry_t *) av;
73
+ bed_entry_t *b = (bed_entry_t *) bv;
74
+ return a->right < b->right ? -1 : (a->right == b->right ? 0 : 1);
75
+ }
76
+
77
+
78
+ int load_bed_file_multi_ref(char *infile, int get_strand, int sort_by_pos, khash_t(bed_list_hash) *bed_lists) {
79
+ hFILE *fp;
80
+ int line_count = 0, ret;
81
+ int64_t left, right;
82
+ kstring_t line = KS_INITIALIZE;
83
+ bed_entry_list_t *list;
84
+ khiter_t bed_itr;
85
+
86
+ if ((fp = hopen(infile, "r")) == NULL) {
87
+ print_error_errno("amplicon", "unable to open file %s.", infile);
88
+ return 1;
89
+ }
90
+
91
+ char ref[1024];
92
+
93
+ while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) {
94
+ line_count++;
95
+ int hret;
96
+ char strand;
97
+
98
+ if (line.l == 0 || *line.s == '#') continue;
99
+ if (strncmp(line.s, "track ", 6) == 0) continue;
100
+ if (strncmp(line.s, "browser ", 8) == 0) continue;
101
+
102
+ if (get_strand) {
103
+ if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64" %*s %*s %c",
104
+ ref, &left, &right, &strand) != 4) {
105
+ fprintf(samtools_stderr, "[amplicon] error: bad bed file format in line %d of %s.\n"
106
+ "(N.B. ref/chrom name limited to 1023 characters.)\n",
107
+ line_count, infile);
108
+ ret = 1;
109
+ goto error;
110
+ }
111
+ } else {
112
+ if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64,
113
+ ref, &left, &right) != 3) {
114
+ fprintf(samtools_stderr, "[amplicon] error: bad bed file format in line %d of %s\n"
115
+ "(N.B. ref/chrom name limited to 1023 characters.)\n",
116
+ line_count, infile);
117
+ ret = 1;
118
+ goto error;
119
+ }
120
+ }
121
+
122
+ bed_itr = kh_get(bed_list_hash, bed_lists, ref);
123
+
124
+ if (bed_itr == kh_end(bed_lists)) { // new ref entry
125
+ char *ref_name = strdup(ref); // need a copy for the hash key
126
+
127
+ if (!ref_name) {
128
+ fprintf(samtools_stderr, "[amplicon] error: unable to allocate memory for ref name.\n");
129
+ ret = 1;
130
+ goto error;
131
+ }
132
+
133
+ bed_itr = kh_put(bed_list_hash, bed_lists, ref_name, &hret);
134
+
135
+ if (hret > 0) {
136
+ list = &kh_val(bed_lists, bed_itr);
137
+
138
+ // initialise the new hash entry
139
+ list->longest = 0;
140
+ list->size = 0;
141
+ list->length = 0;
142
+ list->bp = NULL;
143
+ } else {
144
+ fprintf(samtools_stderr, "[amplicon] error: ref hashing failure.\n");
145
+ ret = 1;
146
+ goto error;
147
+ }
148
+ } else { // existing ref
149
+ list = &kh_val(bed_lists, bed_itr);
150
+ }
151
+
152
+ if (list->length == list->size) {
153
+ bed_entry_t *tmp;
154
+
155
+ list->size += list->size / 2 + 256;
156
+
157
+ if ((tmp = realloc(list->bp, list->size * sizeof(bed_entry_t))) == NULL) {
158
+ fprintf(samtools_stderr, "[amplicon] error: unable to allocate more memory for bed data.\n");
159
+ ret = 1;
160
+ goto error;
161
+ }
162
+
163
+ list->bp = tmp;
164
+ }
165
+
166
+ list->bp[list->length].left = left;
167
+ list->bp[list->length].right = right;
168
+
169
+ if (get_strand) {
170
+ if (strand == '+') {
171
+ list->bp[list->length].rev = 0;
172
+ } else if (strand == '-') {
173
+ list->bp[list->length].rev = 1;
174
+ } else {
175
+ fprintf(samtools_stderr, "[amplicon] error: bad strand value in line %d, expecting '+' or '-', found '%c'.\n",
176
+ line_count, strand);
177
+ ret = 1;
178
+ goto error;
179
+ }
180
+ }
181
+
182
+ if (right - left > list->longest)
183
+ list->longest = right - left;
184
+
185
+ list->length++;
186
+ }
187
+
188
+ if (sort_by_pos) {
189
+ for (bed_itr = kh_begin(bed_lists); bed_itr != kh_end(bed_lists); ++bed_itr) {
190
+ if (kh_exist(bed_lists, bed_itr)) {
191
+ list = &kh_val(bed_lists, bed_itr);
192
+ qsort(list->bp, list->length, sizeof(list->bp[0]), bed_entry_sort);
193
+ }
194
+ }
195
+ }
196
+
197
+ if (kh_size(bed_lists) > 0) {// any entries
198
+ ret = 0;
199
+ } else {
200
+ ret = 1;
201
+ }
202
+
203
+ error:
204
+ ks_free(&line);
205
+
206
+ if (hclose(fp) != 0) {
207
+ fprintf(samtools_stderr, "[amplicon] warning: failed to close %s", infile);
208
+ }
209
+
210
+ return ret;
211
+ }
212
+
213
+
214
+ void destroy_bed_hash(khash_t(bed_list_hash) *hash) {
215
+ khiter_t itr;
216
+
217
+ for (itr = kh_begin(hash); itr != kh_end(hash); ++itr) {
218
+ if (kh_exist(hash, itr)) {
219
+ free(kh_val(hash, itr).bp);
220
+ free((char *)kh_key(hash, itr));
221
+ kh_key(hash, itr) = NULL;
222
+ }
223
+ }
224
+
225
+ kh_destroy(bed_list_hash, hash);
226
+ }
227
+
228
+
229
+ static int matching_clip_site(bed_entry_list_t *sites, hts_pos_t pos,
230
+ int is_rev, int use_strand, int64_t longest,
231
+ cl_param_t *param) {
232
+ int i, size; // may need this to be variable
233
+ int tol = param->tol;
234
+ int l = 0, mid = sites->length / 2, r = sites->length;
235
+ int pos_tol = is_rev ? (pos > tol ? pos - tol : 0) : pos;
236
+
237
+ while (r - l > 1) {
238
+ if (sites->bp[mid].right <= pos_tol) {
239
+ l = mid;
240
+ } else {
241
+ r = mid;
242
+ }
243
+ mid = (l + r) / 2;
244
+ }
245
+
246
+ size = 0;
247
+
248
+ for (i = l; i < sites->length; i++) {
249
+ hts_pos_t mod_left, mod_right;
250
+
251
+ if (use_strand && is_rev != sites->bp[i].rev)
252
+ continue;
253
+
254
+ if (is_rev) {
255
+ mod_left = sites->bp[i].left;
256
+ mod_right = sites->bp[i].right + tol;
257
+ } else {
258
+ if (sites->bp[i].left > tol) {
259
+ mod_left = sites->bp[i].left - tol;
260
+ } else {
261
+ mod_left = 0;
262
+ }
263
+ mod_right = sites->bp[i].right;
264
+ }
265
+
266
+ if (pos + longest + tol < mod_right)
267
+ break;
268
+
269
+ if (pos >= mod_left && pos <= mod_right) {
270
+ if (is_rev) {
271
+ if (size < pos - sites->bp[i].left) {
272
+ size = pos - sites->bp[i].left;
273
+ }
274
+ } else {
275
+ if (size < sites->bp[i].right - pos) {
276
+ size = sites->bp[i].right - pos;
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ return size;
283
+ }
284
+
285
+
286
+ static int bam_trim_left(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
287
+ clipping_type clipping) {
288
+ uint32_t *orig_cigar = bam_get_cigar(rec);
289
+ uint8_t *orig_seq = bam_get_seq(rec);
290
+ uint8_t *orig_qual = bam_get_qual(rec);
291
+ uint8_t *orig_aux = bam_get_aux(rec);
292
+ uint32_t *new_cigar;
293
+ uint8_t *new_qual;
294
+ size_t orig_l_aux = bam_get_l_aux(rec);
295
+ uint32_t i, j;
296
+ uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
297
+ hts_pos_t new_pos = rec->core.pos;
298
+ uint32_t cig_type, cig_op;
299
+
300
+ if (rec->l_data + 8 > rec_out->m_data) {
301
+ uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
302
+ if (!new_data) {
303
+ fprintf(samtools_stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
304
+ return 1;
305
+ }
306
+ rec_out->data = new_data;
307
+ rec_out->m_data = rec->l_data + 8;
308
+ }
309
+
310
+ // Copy core data & name
311
+ memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
312
+ memcpy(rec_out->data, rec->data, rec->core.l_qname);
313
+
314
+ // Modify CIGAR
315
+ new_cigar = bam_get_cigar(rec_out);
316
+
317
+ for (i = 0; i < rec->core.n_cigar; i++) {
318
+ cig_op = bam_cigar_op(orig_cigar[i]);
319
+ cig_type = bam_cigar_type(cig_op);
320
+
321
+ if (cig_op == BAM_CHARD_CLIP) {
322
+ hardclip += bam_cigar_oplen(orig_cigar[i]);
323
+ } else {
324
+ if (cig_type & 2) {
325
+ if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
326
+ ref_remove -= bam_cigar_oplen(orig_cigar[i]);
327
+ } else {
328
+ break;
329
+ }
330
+ new_pos += bam_cigar_oplen(orig_cigar[i]);
331
+ }
332
+ if (cig_type & 1) {
333
+ qry_removed += bam_cigar_oplen(orig_cigar[i]);
334
+ }
335
+ }
336
+ }
337
+
338
+ if (i < rec->core.n_cigar) {
339
+ cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
340
+
341
+ // account for the last operation
342
+ if (cig_type & 2) {
343
+ new_pos += ref_remove;
344
+ }
345
+ if (cig_type & 1) {
346
+ qry_removed += ref_remove;
347
+ }
348
+ } else {
349
+ if (clipping == hard_clip) {
350
+
351
+ rec_out->core.l_qseq = 0;
352
+ rec_out->core.n_cigar = 0;
353
+
354
+ if (orig_l_aux)
355
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
356
+
357
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
358
+
359
+ return 0;
360
+ }
361
+
362
+ qry_removed = rec->core.l_qseq;
363
+ }
364
+
365
+ j = 0;
366
+ if (clipping == hard_clip && hardclip + qry_removed > 0) {
367
+ new_cigar[j++] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
368
+ }
369
+ if (clipping == soft_clip) {
370
+ if (hardclip > 0) {
371
+ new_cigar[j++] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
372
+ }
373
+ if (qry_removed > 0) {
374
+ new_cigar[j++] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
375
+ }
376
+ }
377
+
378
+ if (i < rec->core.n_cigar
379
+ && bam_cigar_oplen(orig_cigar[i]) > ref_remove) {
380
+ new_cigar[j++] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
381
+
382
+ // fill in the rest of the cigar
383
+ i++;
384
+
385
+ for (; i < rec->core.n_cigar; i++) {
386
+ new_cigar[j++] = orig_cigar[i];
387
+ }
388
+ }
389
+
390
+ rec_out->core.n_cigar = j;
391
+
392
+ if (clipping == soft_clip) {
393
+ qry_removed = 0; // Copy all the sequence and confidence values
394
+ }
395
+
396
+ new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
397
+ // Copy remaining SEQ
398
+ if ((qry_removed & 1) == 0) {
399
+ memcpy(bam_get_seq(rec_out), orig_seq + (qry_removed / 2),
400
+ (rec->core.l_qseq - qry_removed + 1) / 2); // +1 to account for odd numbers
401
+ } else {
402
+ uint8_t *in = orig_seq + qry_removed / 2;
403
+ uint8_t *out = bam_get_seq(rec_out);
404
+ uint32_t i;
405
+ for (i = qry_removed; i < rec->core.l_qseq - 1; i += 2) {
406
+ *out++ = ((in[0] & 0x0f) << 4) | ((in[1] & 0xf0) >> 4);
407
+ in++;
408
+ }
409
+ if (i < rec->core.l_qseq) {
410
+ *out++ = (in[0] & 0x0f) << 4;
411
+ }
412
+ assert(out == new_qual);
413
+ }
414
+
415
+ // Copy remaining QUAL
416
+ memmove(new_qual, orig_qual, rec->core.l_qseq - qry_removed);
417
+
418
+ // Set new l_qseq
419
+ rec_out->core.l_qseq -= qry_removed;
420
+
421
+ // Move AUX
422
+ if (orig_l_aux)
423
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
424
+
425
+ // Set new l_data
426
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
427
+
428
+ // put in new pos
429
+ rec_out->core.pos = new_pos;
430
+
431
+ return 0;
432
+ }
433
+
434
+
435
+ static int bam_trim_right(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
436
+ clipping_type clipping) {
437
+ uint32_t *orig_cigar = bam_get_cigar(rec);
438
+ uint8_t *orig_seq = bam_get_seq(rec);
439
+ uint8_t *orig_qual = bam_get_qual(rec);
440
+ uint8_t *orig_aux = bam_get_aux(rec);
441
+ uint32_t *new_cigar;
442
+ uint32_t new_n_cigar = 0;
443
+ uint8_t *new_qual;
444
+ size_t orig_l_aux = bam_get_l_aux(rec);
445
+ int32_t i;
446
+ int32_t j;
447
+ uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
448
+ uint32_t cig_type, cig_op;
449
+
450
+ if (rec->l_data + 8 > rec_out->m_data) {
451
+ uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
452
+ if (!new_data) {
453
+ fprintf(samtools_stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
454
+ return 1;
455
+ }
456
+ rec_out->data = new_data;
457
+ rec_out->m_data = rec->l_data + 8;
458
+ }
459
+
460
+ // Copy core data & name
461
+ memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
462
+ memcpy(rec_out->data, rec->data, rec->core.l_qname);
463
+
464
+ // Modify CIGAR here
465
+ new_cigar = bam_get_cigar(rec_out);
466
+
467
+ for (i = rec->core.n_cigar - 1; i >= 0; --i) {
468
+ cig_op = bam_cigar_op(orig_cigar[i]);
469
+ cig_type = bam_cigar_type(cig_op);
470
+
471
+ if (cig_op == BAM_CHARD_CLIP) {
472
+ hardclip += bam_cigar_oplen(orig_cigar[i]);
473
+ } else {
474
+ if (cig_type & 2) {
475
+ if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
476
+ ref_remove -= bam_cigar_oplen(orig_cigar[i]);
477
+ } else {
478
+ break;
479
+ }
480
+ }
481
+ if (cig_type & 1) {
482
+ qry_removed += bam_cigar_oplen(orig_cigar[i]);
483
+ }
484
+ }
485
+ }
486
+
487
+ if (i >= 0) {
488
+ cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
489
+ if (cig_type & 1) {
490
+ qry_removed += ref_remove;
491
+ }
492
+ j = i;
493
+ if (qry_removed > 0) j++;
494
+ if (hardclip > 0 && (clipping == soft_clip || qry_removed == 0)) j++;
495
+ } else {
496
+ if (clipping == hard_clip) {
497
+
498
+ rec_out->core.l_qseq = 0;
499
+ rec_out->core.n_cigar = 0;
500
+
501
+ if (orig_l_aux)
502
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
503
+
504
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
505
+
506
+ return 0;
507
+ }
508
+
509
+ qry_removed = rec->core.l_qseq;
510
+ j = 0;
511
+ if (hardclip > 0 && clipping == soft_clip) j++;
512
+ }
513
+
514
+ if (clipping == hard_clip && hardclip + qry_removed > 0) {
515
+ new_cigar[j] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
516
+ new_n_cigar++;
517
+ }
518
+ if (clipping == soft_clip) {
519
+ if (hardclip > 0) {
520
+ new_cigar[j] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
521
+ new_n_cigar++;
522
+ if (qry_removed > 0) --j;
523
+ }
524
+ if (qry_removed > 0) {
525
+ new_cigar[j] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
526
+ new_n_cigar++;
527
+ }
528
+ }
529
+
530
+ if (j > 0) {
531
+ new_cigar[--j] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
532
+ new_n_cigar++;
533
+ }
534
+
535
+ // fill in the rest of the cigar
536
+ while (j > 0) {
537
+ new_cigar[--j] = orig_cigar[--i];
538
+ new_n_cigar++;
539
+ }
540
+
541
+ rec_out->core.n_cigar = new_n_cigar;
542
+
543
+ if (clipping == soft_clip)
544
+ qry_removed = 0; // Copy all the sequence and confidence values
545
+
546
+ new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
547
+ // Copy remaining SEQ
548
+ memcpy(bam_get_seq(rec_out), orig_seq, (rec->core.l_qseq - qry_removed + 1) / 2);
549
+
550
+ // Copy remaining QUAL
551
+ memcpy(new_qual, orig_qual, rec->core.l_qseq - qry_removed);
552
+
553
+ // Set new l_qseq
554
+ rec_out->core.l_qseq -= qry_removed;
555
+
556
+ // Copy AUX
557
+ if (orig_l_aux)
558
+ memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
559
+
560
+ // Set new l_data
561
+ rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
562
+
563
+ return 0;
564
+ }
565
+
566
+
567
+ static hts_pos_t active_query_len(bam1_t *b) {
568
+ uint32_t *cigar = bam_get_cigar(b);
569
+ uint32_t cig_type, cig_op;
570
+ hts_pos_t len = 0;
571
+ int i;
572
+
573
+ for (i = 0; i < b->core.n_cigar; i++) {
574
+ cig_op = bam_cigar_op(cigar[i]);
575
+ cig_type = bam_cigar_type(cig_op);
576
+
577
+ if ((cig_type & 1) && (cig_op != BAM_CSOFT_CLIP)) {
578
+ len += bam_cigar_oplen(cigar[i]);
579
+ }
580
+ }
581
+
582
+ return len;
583
+ }
584
+
585
+
586
+ static inline void swap_bams(bam1_t **a, bam1_t **b) {
587
+ bam1_t *tmp = *a;
588
+ *a = *b;
589
+ *b = tmp;
590
+ }
591
+
592
+
593
+ // Format OA:Z:(RNAME,POS,strand,CIGAR,MAPQ,NM;
594
+ static inline int tag_original_data(bam1_t *orig, kstring_t *oa_tag) {
595
+ char strand;
596
+ uint8_t *nm_tag, *old_oa_tag;
597
+ uint32_t *cigar;
598
+ int64_t nm = 0;
599
+ int i, res = 0;
600
+
601
+ ks_clear(oa_tag);
602
+
603
+ // if there is an existing OA tag the new one gets appended to it
604
+ if ((old_oa_tag = bam_aux_get(orig, "OA"))) {
605
+ res |= ksprintf(oa_tag, "%s", bam_aux2Z(old_oa_tag)) < 0;
606
+ }
607
+
608
+ if (orig->core.flag & BAM_FREVERSE)
609
+ strand = '-';
610
+ else
611
+ strand = '+';
612
+
613
+ if ((nm_tag = bam_aux_get(orig, "NM"))) {
614
+ nm = bam_aux2i(nm_tag);
615
+ }
616
+
617
+ res |= ksprintf(oa_tag, "%s,%"PRIhts_pos",%c,", bam_get_qname(orig), orig->core.pos + 1, strand) < 0;
618
+
619
+ for (i = 0, cigar = bam_get_cigar(orig); i < orig->core.n_cigar && res == 0; ++i) {
620
+ res |= kputw(bam_cigar_oplen(cigar[i]), oa_tag) < 0;
621
+ res |= kputc(bam_cigar_opchr(cigar[i]), oa_tag) < 0;
622
+ }
623
+
624
+ if (nm_tag) {
625
+ res |= ksprintf(oa_tag, ",%d,%"PRId64";", orig->core.qual, nm) < 0;
626
+ } else {
627
+ res |= ksprintf(oa_tag, "%d,;", orig->core.qual) < 0;
628
+ }
629
+
630
+ return res;
631
+ }
632
+
633
+
634
+ static int bam_clip(samFile *in, samFile *out, samFile *reject, char *bedfile,
635
+ clipping_type clipping, cl_param_t *param) {
636
+ int ret = 1, r, file_open = 0;
637
+
638
+ bam_hdr_t *header = NULL;
639
+ bam1_t *b = NULL, *b_tmp = NULL;
640
+ long f_count = 0, r_count = 0, n_count = 0, l_count = 0, l_exclude = 0, b_count = 0;
641
+ long filtered = 0, written = 0, failed = 0;
642
+ kstring_t str = KS_INITIALIZE;
643
+ kstring_t oat = KS_INITIALIZE;
644
+ kstring_t seq = KS_INITIALIZE;
645
+ bed_entry_list_t *sites;
646
+ FILE *stats_fp = samtools_stderr;
647
+ khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash);
648
+
649
+ if (load_bed_file_multi_ref(bedfile, param->use_strand, 1, bed_hash)) {
650
+ fprintf(samtools_stderr, "[ampliconclip] error: unable to load bed file.\n");
651
+ goto fail;
652
+ }
653
+
654
+ if ((header = sam_hdr_read(in)) == NULL) {
655
+ fprintf(samtools_stderr, "[ampliconclip] error: could not read header\n");
656
+ goto fail;
657
+ }
658
+
659
+ // changing pos can ruin coordinate sort order
660
+ if (sam_hdr_find_tag_hd(header, "SO", &str) == 0 && str.s && strcmp(str.s, "coordinate") == 0) {
661
+ const char *new_order = "unknown";
662
+
663
+ if (sam_hdr_update_hd(header, "SO", new_order) == -1) {
664
+ fprintf(samtools_stderr, "[ampliconclip] error: unable to change sort order to 'SO:%s'\n", new_order);
665
+ goto fail;
666
+ }
667
+ }
668
+
669
+ ks_free(&str);
670
+
671
+ if (param->add_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(),
672
+ param->arg_list ? "CL" : NULL,
673
+ param->arg_list ? param->arg_list : NULL,
674
+ NULL) != 0) {
675
+ fprintf(samtools_stderr, "[ampliconclip] warning: unable to add @PG line to header.\n");
676
+ }
677
+ if (sam_hdr_write(out, header) < 0) {
678
+ fprintf(samtools_stderr, "[ampliconclip] error: could not write header.\n");
679
+ goto fail;
680
+ }
681
+
682
+ if (reject) {
683
+ if (sam_hdr_write(reject, header) < 0) {
684
+ fprintf(samtools_stderr, "[ampliconclip] error: could not write header to rejects file.\n");
685
+ goto fail;
686
+ }
687
+ }
688
+
689
+ b = bam_init1();
690
+ b_tmp = bam_init1();
691
+ if (!b || !b_tmp) {
692
+ fprintf(samtools_stderr, "[ampliconclip] error: out of memory when trying to create record.\n");
693
+ goto fail;
694
+ }
695
+
696
+ int32_t last_tid = -1;
697
+ int ref_found = 0;
698
+
699
+ while ((r = sam_read1(in, header, b)) >= 0) {
700
+ hts_pos_t pos;
701
+ int is_rev;
702
+ int p_size;
703
+ int been_clipped = 0, filter = 0;
704
+ int exclude = (BAM_FUNMAP | BAM_FQCFAIL);
705
+ khiter_t itr;
706
+
707
+ l_count++;
708
+
709
+ if (b->core.tid != last_tid) {
710
+ const char *ref_name;
711
+
712
+ ref_found = 0;
713
+ last_tid = b->core.tid;
714
+
715
+ if ((ref_name = sam_hdr_tid2name(header, b->core.tid)) != NULL) {
716
+ itr = kh_get(bed_list_hash, bed_hash, ref_name);
717
+
718
+ if (itr != kh_end(bed_hash)) {
719
+ sites = &kh_val(bed_hash, itr);
720
+ ref_found = 1;
721
+ }
722
+ }
723
+ }
724
+
725
+ if (!(b->core.flag & exclude) && ref_found) {
726
+ if (param->oa_tag)
727
+ if (tag_original_data(b, &oat))
728
+ goto fail;
729
+
730
+ if (!param->both) {
731
+ if (bam_is_rev(b)) {
732
+ pos = bam_endpos(b);
733
+ is_rev = 1;
734
+ } else {
735
+ pos = b->core.pos;
736
+ is_rev = 0;
737
+ }
738
+
739
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
740
+ if (is_rev) {
741
+ if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
742
+ goto fail;
743
+
744
+ swap_bams(&b, &b_tmp);
745
+ r_count++;
746
+ } else {
747
+ if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
748
+ goto fail;
749
+
750
+ swap_bams(&b, &b_tmp);
751
+ f_count++;
752
+ }
753
+
754
+ if (param->oa_tag) {
755
+ if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
756
+ goto fail;
757
+ }
758
+
759
+ if (param->del_tag) {
760
+ uint8_t *tag;
761
+
762
+ if ((tag = bam_aux_get(b, "NM")))
763
+ bam_aux_del(b, tag);
764
+
765
+ if ((tag = bam_aux_get(b, "MD")))
766
+ bam_aux_del(b, tag);
767
+ }
768
+
769
+ been_clipped = 1;
770
+ } else {
771
+ if (param->mark_fail) {
772
+ b->core.flag |= BAM_FQCFAIL;
773
+ }
774
+
775
+ n_count++;
776
+ }
777
+ } else {
778
+ int left = 0, right = 0;
779
+
780
+ // left first
781
+ pos = b->core.pos;
782
+ is_rev = 0;
783
+
784
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
785
+ if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
786
+ goto fail;
787
+
788
+ swap_bams(&b, &b_tmp);
789
+ f_count++;
790
+ left = 1;
791
+ been_clipped = 1;
792
+ }
793
+
794
+ // the right
795
+ pos = bam_endpos(b);
796
+ is_rev = 1;
797
+
798
+ if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
799
+ if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
800
+ goto fail;
801
+
802
+ swap_bams(&b, &b_tmp);
803
+ r_count++;
804
+ right = 1;
805
+ been_clipped = 1;
806
+ }
807
+
808
+ if (left || right) {
809
+ uint8_t *tag;
810
+
811
+ if (param->oa_tag) {
812
+ if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
813
+ goto fail;
814
+ }
815
+
816
+ if (param->del_tag) {
817
+ if ((tag = bam_aux_get(b, "NM")))
818
+ bam_aux_del(b, tag);
819
+
820
+ if ((tag = bam_aux_get(b, "MD")))
821
+ bam_aux_del(b, tag);
822
+ }
823
+ }
824
+
825
+ if (left && right) {
826
+ b_count++;
827
+ } else if (!left && !right) {
828
+ if (param->mark_fail) {
829
+ b->core.flag |= BAM_FQCFAIL;
830
+ }
831
+
832
+ n_count++;
833
+ }
834
+ }
835
+
836
+ if (param->fail_len >= 0 || param->filter_len >= 0 || param->unmap_len >= 0) {
837
+ hts_pos_t aql = active_query_len(b);
838
+
839
+ if (param->fail_len >= 0 && aql <= param->fail_len) {
840
+ b->core.flag |= BAM_FQCFAIL;
841
+ }
842
+
843
+ if (param->filter_len >= 0 && aql <= param->filter_len) {
844
+ filter = 1;
845
+ }
846
+
847
+ if (param->unmap_len >= 0 && aql <= param->unmap_len) {
848
+
849
+ if (ks_resize(&seq, b->core.l_qseq) < 0) {
850
+ fprintf(samtools_stderr, "[ampliconclip] error: allocate memory for sequence %s\n", bam_get_seq(b));
851
+ goto fail;
852
+ }
853
+
854
+ ks_clear(&seq);
855
+ char *sb = ks_str(&seq);
856
+ uint8_t *sequence = bam_get_seq(b);
857
+ int i;
858
+
859
+ for (i = 0; i < b->core.l_qseq ; ++i) {
860
+ *sb++ = seq_nt16_str[bam_seqi(sequence, i)];
861
+ }
862
+
863
+ if (bam_set1(b_tmp, b->core.l_qname - b->core.l_extranul - 1, bam_get_qname(b),
864
+ (b->core.flag | BAM_FUNMAP), b->core.tid, b->core.pos, 0,
865
+ 0, NULL, b->core.mtid, b->core.mpos, b->core.isize,
866
+ b->core.l_qseq, seq.s, (const char *)bam_get_qual(b),
867
+ bam_get_l_aux(b)) < 0) {
868
+ fprintf(samtools_stderr, "[ampliconclip] error: could not unmap read %s\n", bam_get_seq(b));
869
+ goto fail;
870
+ }
871
+
872
+ memcpy(bam_get_aux(b_tmp), bam_get_aux(b), bam_get_l_aux(b));
873
+ b_tmp->l_data += bam_get_l_aux(b);
874
+ swap_bams(&b, &b_tmp);
875
+ }
876
+ }
877
+
878
+ if (b->core.flag & BAM_FQCFAIL) {
879
+ failed++;
880
+ }
881
+
882
+ if (param->write_clipped && !been_clipped) {
883
+ filter = 1;
884
+ }
885
+
886
+ } else {
887
+ l_exclude++;
888
+
889
+ if (param->unmapped) {
890
+ filter = 1;
891
+ }
892
+ }
893
+
894
+ if (!filter) {
895
+ if (sam_write1(out, header, b) < 0) {
896
+ fprintf(samtools_stderr, "[ampliconclip] error: could not write line %ld.\n", l_count);
897
+ goto fail;
898
+ }
899
+
900
+ written++;
901
+ } else {
902
+ if (reject) {
903
+ if (sam_write1(reject, header, b) < 0) {
904
+ fprintf(samtools_stderr, "[ampliconclip] error: could not write to reject file %s\n",
905
+ param->rejects_file);
906
+ goto fail;
907
+ }
908
+ }
909
+
910
+ filtered++;
911
+ }
912
+ }
913
+
914
+ if (r < -1) {
915
+ fprintf(samtools_stderr, "[ampliconclip] error: failed to read input.\n");
916
+ goto fail;
917
+ }
918
+
919
+ if (param->stats_file) {
920
+ if ((stats_fp = fopen(param->stats_file, "w")) == NULL) {
921
+ fprintf(samtools_stderr, "[ampliconclip] warning: cannot write stats to %s.\n", param->stats_file);
922
+ } else {
923
+ file_open = 1;
924
+ }
925
+ }
926
+
927
+ fprintf(stats_fp, "COMMAND: %s\n"
928
+ "TOTAL READS: %ld\n"
929
+ "TOTAL CLIPPED: %ld\n"
930
+ "FORWARD CLIPPED: %ld\n"
931
+ "REVERSE CLIPPED: %ld\n"
932
+ "BOTH CLIPPED: %ld\n"
933
+ "NOT CLIPPED: %ld\n"
934
+ "EXCLUDED: %ld\n"
935
+ "FILTERED: %ld\n"
936
+ "FAILED: %ld\n"
937
+ "WRITTEN: %ld\n", param->arg_list, l_count, f_count + r_count,
938
+ f_count, r_count, b_count, n_count, l_exclude,
939
+ filtered, failed, written);
940
+
941
+ if (file_open) {
942
+ fclose(stats_fp);
943
+ }
944
+
945
+ ret = 0;
946
+
947
+ fail:
948
+ destroy_bed_hash(bed_hash);
949
+ ks_free(&oat);
950
+ ks_free(&seq);
951
+ sam_hdr_destroy(header);
952
+ bam_destroy1(b);
953
+ bam_destroy1(b_tmp);
954
+ return ret;
955
+ }
956
+
957
+
958
+ static void usage(void) {
959
+ fprintf(samtools_stderr, "Usage: samtools ampliconclip -b BED file <input.bam> -o <output.bam>\n\n");
960
+ fprintf(samtools_stderr, "Option: \n");
961
+ fprintf(samtools_stderr, " -b FILE BED file of regions (eg amplicon primers) to be removed.\n");
962
+ fprintf(samtools_stderr, " -o FILE output file name (default samtools_stdout).\n");
963
+ fprintf(samtools_stderr, " -f FILE write stats to file name (default samtools_stderr)\n");
964
+ fprintf(samtools_stderr, " -u Output uncompressed data\n");
965
+ fprintf(samtools_stderr, " --soft-clip soft clip amplicon primers from reads (default)\n");
966
+ fprintf(samtools_stderr, " --hard-clip hard clip amplicon primers from reads.\n");
967
+ fprintf(samtools_stderr, " --both-ends clip on both 5' and 3' ends.\n");
968
+ fprintf(samtools_stderr, " --strand use strand data from BED file to match read direction.\n");
969
+ fprintf(samtools_stderr, " --clipped only output clipped reads.\n");
970
+ fprintf(samtools_stderr, " --fail mark unclipped, mapped reads as QCFAIL.\n");
971
+ fprintf(samtools_stderr, " --filter-len INT do not output reads INT size or shorter.\n");
972
+ fprintf(samtools_stderr, " --fail-len INT mark as QCFAIL reads INT size or shorter.\n");
973
+ fprintf(samtools_stderr, " --unmap-len INT unmap reads INT size or shorter, default 0.\n");
974
+ fprintf(samtools_stderr, " --no-excluded do not write excluded reads (unmapped or QCFAIL).\n");
975
+ fprintf(samtools_stderr, " --rejects-file FILE file to write filtered reads.\n");
976
+ fprintf(samtools_stderr, " --original for clipped entries add an OA tag with original data.\n");
977
+ fprintf(samtools_stderr, " --keep-tag for clipped entries keep the old NM and MD tags.\n");
978
+ fprintf(samtools_stderr, " --tolerance match region within this number of bases, default 5.\n");
979
+ fprintf(samtools_stderr, " --no-PG do not add an @PG line.\n");
980
+ sam_global_opt_help(samtools_stderr, "-.O..@-.");
981
+ fprintf(samtools_stderr, "\nAbout: Soft clips read alignments where they match BED file defined regions.\n"
982
+ "Default clipping is only on the 5' end.\n\n");
983
+ }
984
+
985
+
986
+ int amplicon_clip_main(int argc, char **argv) {
987
+ int c, ret;
988
+ char wmode[4] = {'w', 'b', 0, 0};
989
+ char *bedfile = NULL, *fnout = "-";
990
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
991
+ htsThreadPool p = {NULL, 0};
992
+ samFile *in = NULL, *out = NULL, *reject = NULL;
993
+ clipping_type clipping = soft_clip;
994
+ cl_param_t param = {1, 0, 0, 0, 0, -1, -1, 0, 0, 1, 5, 0, NULL, NULL, NULL};
995
+
996
+ static const struct option lopts[] = {
997
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
998
+ {"no-PG", no_argument, NULL, 1002},
999
+ {"soft-clip", no_argument, NULL, 1003},
1000
+ {"hard-clip", no_argument, NULL, 1004},
1001
+ {"strand", no_argument, NULL, 1005},
1002
+ {"clipped", no_argument, NULL, 1006},
1003
+ {"fail", no_argument, NULL, 1007},
1004
+ {"both-ends", no_argument, NULL, 1008},
1005
+ {"filter-len", required_argument, NULL, 1009},
1006
+ {"fail-len", required_argument, NULL, 1010},
1007
+ {"no-excluded", no_argument, NULL, 1011},
1008
+ {"rejects-file", required_argument, NULL, 1012},
1009
+ {"original", no_argument, NULL, 1013},
1010
+ {"keep-tag", no_argument, NULL, 1014},
1011
+ {"tolerance", required_argument, NULL, 1015},
1012
+ {"unmap-len", required_argument, NULL, 1016},
1013
+ {NULL, 0, NULL, 0}
1014
+ };
1015
+
1016
+ while ((c = getopt_long(argc, argv, "b:@:o:O:f:u", lopts, NULL)) >= 0) {
1017
+ switch (c) {
1018
+ case 'b': bedfile = optarg; break;
1019
+ case 'o': fnout = optarg; break;
1020
+ case 'f': param.stats_file = optarg; break;
1021
+ case 'u': wmode[2] = '0'; break;
1022
+ case 1002: param.add_pg = 0; break;
1023
+ case 1003: clipping = soft_clip; break;
1024
+ case 1004: clipping = hard_clip; break;
1025
+ case 1005: param.use_strand = 1; break;
1026
+ case 1006: param.write_clipped = 1; break;
1027
+ case 1007: param.mark_fail = 1; break;
1028
+ case 1008: param.both = 1; break;
1029
+ case 1009: param.filter_len = atoi(optarg); break;
1030
+ case 1010: param.fail_len = atoi(optarg); break;
1031
+ case 1011: param.unmapped = 1; break;
1032
+ case 1012: param.rejects_file = optarg; break;
1033
+ case 1013: param.oa_tag = 1; break;
1034
+ case 1014: param.del_tag = 0; break;
1035
+ case 1015: param.tol = atoi(optarg); break;
1036
+ case 1016: param.unmap_len = atoi(optarg); break;
1037
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1038
+ /* else fall-through */
1039
+ case '?': usage(); samtools_exit(1);
1040
+ }
1041
+ }
1042
+
1043
+ if (!bedfile) {
1044
+ usage();
1045
+ return 1;
1046
+ }
1047
+
1048
+ if (optind + 1 > argc) {
1049
+ usage();
1050
+ return 1;
1051
+ }
1052
+
1053
+ if (param.tol < 0) {
1054
+ fprintf(samtools_stderr, "[ampliconclip] warning: invalid tolerance of %d,"
1055
+ " resetting tolerance to default of 5.\n", param.tol);
1056
+ param.tol = 5;
1057
+ }
1058
+
1059
+ if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
1060
+ print_error_errno("ampliconclip", "cannot open input file");
1061
+ return 1;
1062
+ }
1063
+
1064
+ sam_open_mode(wmode+1, fnout, NULL);
1065
+
1066
+ if ((out = sam_open_format(fnout, wmode, &ga.out)) == NULL) {
1067
+ print_error_errno("ampliconclip", "cannot open output file");
1068
+ return 1;
1069
+ }
1070
+
1071
+ if (param.rejects_file) {
1072
+ sam_open_mode(wmode+1, param.rejects_file, NULL);
1073
+
1074
+ if ((reject = sam_open_format(param.rejects_file, wmode, &ga.out)) == NULL) {
1075
+ print_error_errno("ampliconclip", "cannot open rejects file");
1076
+ return 1;
1077
+ }
1078
+ }
1079
+
1080
+ if (ga.nthreads > 0) {
1081
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
1082
+ fprintf(samtools_stderr, "[ampliconclip] error: cannot create thread pool.\n");
1083
+ return 1;
1084
+ }
1085
+ hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
1086
+ hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
1087
+
1088
+ if (reject) {
1089
+ hts_set_opt(reject, HTS_OPT_THREAD_POOL, &p);
1090
+ }
1091
+ }
1092
+
1093
+ param.arg_list = stringify_argv(argc + 1, argv - 1);
1094
+
1095
+ ret = bam_clip(in, out, reject, bedfile, clipping, &param);
1096
+
1097
+ // cleanup
1098
+ sam_close(in);
1099
+
1100
+ if (sam_close(out) < 0) {
1101
+ fprintf(samtools_stderr, "[ampliconclip] error: error while closing output file %s.\n", argv[optind+1]);
1102
+ ret = 1;
1103
+ }
1104
+
1105
+ if (reject) {
1106
+ if (sam_close(reject) < 0) {
1107
+ fprintf(samtools_stderr, "[ampliconclip] error: error while closing reject file %s.\n", param.rejects_file);
1108
+ ret = 1;
1109
+ }
1110
+ }
1111
+
1112
+ if (p.pool) hts_tpool_destroy(p.pool);
1113
+
1114
+ sam_global_args_free(&ga);
1115
+ free(param.arg_list);
1116
+
1117
+ return ret;
1118
+ }
1119
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_ampliconclip.h -- shared functions between amplicon clip/stats
2
+
3
+ Copyright (C) 2020-2021 Genome Research Ltd.
4
+
5
+ Author: James Bonfield <jkb@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #ifndef BAM_AMPLICONCLIP_H
26
+ #define BAM_AMPLICONCLIP_H
27
+
28
+ #include "htslib/khash.h"
29
+
30
+ typedef struct {
31
+ int64_t left;
32
+ int64_t right;
33
+ int rev;
34
+ } bed_entry_t;
35
+
36
+ typedef struct {
37
+ bed_entry_t *bp;
38
+ int64_t longest;
39
+ int length;
40
+ int size;
41
+ } bed_entry_list_t;
42
+
43
+ KHASH_MAP_INIT_STR(bed_list_hash, bed_entry_list_t);
44
+
45
+ #define BED_LIST_INIT {NULL, 0, 0, 0, {0}}
46
+
47
+
48
+ int load_bed_file_multi_ref(char *infile, int get_strand,
49
+ int sort_by_pos, khash_t(bed_list_hash) *bed_lists);
50
+
51
+ void destroy_bed_hash(khash_t(bed_list_hash) *hash);
52
+
53
+
54
+ #endif /* BAM_AMPLICONCLIP_H */
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_aux.c ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_aux.c -- remaining aux field handling.
2
+
3
+ Copyright (C) 2008-2010, 2013, 2015, 2019 Genome Research Ltd.
4
+ Portions copyright (C) 2011 Broad Institute.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <ctype.h>
29
+ #include "htslib/sam.h"
30
+
31
+ static inline int bam_aux_type2size(int x)
32
+ {
33
+ if (x == 'C' || x == 'c' || x == 'A') return 1;
34
+ else if (x == 'S' || x == 's') return 2;
35
+ else if (x == 'I' || x == 'i' || x == 'f' || x == 'F') return 4;
36
+ else return 0;
37
+ }
38
+
39
+ #define __skip_tag(s) do { \
40
+ int type = toupper(*(s)); \
41
+ ++(s); \
42
+ if (type == 'Z' || type == 'H') { while (*(s)) ++(s); ++(s); } \
43
+ else if (type == 'B') (s) += 5 + bam_aux_type2size(*(s)) * (*(int32_t*)((s)+1)); \
44
+ else (s) += bam_aux_type2size(type); \
45
+ } while(0)
46
+
47
+
48
+ int bam_aux_drop_other(bam1_t *b, uint8_t *s)
49
+ {
50
+ if (s) {
51
+ uint8_t *p, *aux;
52
+ aux = bam_get_aux(b);
53
+ p = s - 2;
54
+ __skip_tag(s);
55
+ memmove(aux, p, s - p);
56
+ b->l_data -= bam_get_l_aux(b) - (s - p);
57
+ } else {
58
+ b->l_data -= bam_get_l_aux(b);
59
+ }
60
+ return 0;
61
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_color.c.pysam.c ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_color.c -- color-space support.
4
+
5
+ Copyright (C) 2009, 2012 University of California - Los Angeles.
6
+
7
+ Author: Nils Homer <nilshomer@gmail.com>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ #include <config.h>
28
+
29
+ #include <ctype.h>
30
+ #include <string.h>
31
+
32
+ #include "htslib/sam.h"
33
+
34
+ /*!
35
+ @abstract Get the color encoding the previous and current base
36
+ @param b pointer to an alignment
37
+ @param i The i-th position, 0-based
38
+ @return color
39
+
40
+ @discussion Returns 0 no color information is found.
41
+ */
42
+ char bam_aux_getCSi(bam1_t *b, int i)
43
+ {
44
+ uint8_t *c = bam_aux_get(b, "CS");
45
+ char *cs = NULL;
46
+
47
+ // return the base if the tag was not found
48
+ if(0 == c) return 0;
49
+
50
+ cs = bam_aux2Z(c);
51
+ // adjust for strandedness and leading adaptor
52
+ if(bam_is_rev(b)) {
53
+ i = strlen(cs) - 1 - i;
54
+ // adjust for leading hard clip
55
+ uint32_t cigar = bam_get_cigar(b)[0];
56
+ if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) {
57
+ i -= cigar >> BAM_CIGAR_SHIFT;
58
+ }
59
+ } else { i++; }
60
+ return cs[i];
61
+ }
62
+
63
+ /*!
64
+ @abstract Get the color quality of the color encoding the previous and current base
65
+ @param b pointer to an alignment
66
+ @param i The i-th position, 0-based
67
+ @return color quality
68
+
69
+ @discussion Returns 0 no color information is found.
70
+ */
71
+ char bam_aux_getCQi(bam1_t *b, int i)
72
+ {
73
+ uint8_t *c = bam_aux_get(b, "CQ");
74
+ char *cq = NULL;
75
+
76
+ // return the base if the tag was not found
77
+ if(0 == c) return 0;
78
+
79
+ cq = bam_aux2Z(c);
80
+ // adjust for strandedness
81
+ if(bam_is_rev(b)) {
82
+ i = strlen(cq) - 1 - i;
83
+ // adjust for leading hard clip
84
+ uint32_t cigar = bam_get_cigar(b)[0];
85
+ if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) {
86
+ i -= (cigar >> BAM_CIGAR_SHIFT);
87
+ }
88
+ }
89
+ return cq[i];
90
+ }
91
+
92
+ char bam_aux_nt2int(char a)
93
+ {
94
+ switch(toupper(a)) {
95
+ case 'A':
96
+ return 0;
97
+ break;
98
+ case 'C':
99
+ return 1;
100
+ break;
101
+ case 'G':
102
+ return 2;
103
+ break;
104
+ case 'T':
105
+ return 3;
106
+ break;
107
+ default:
108
+ return 4;
109
+ break;
110
+ }
111
+ }
112
+
113
+ char bam_aux_ntnt2cs(char a, char b)
114
+ {
115
+ a = bam_aux_nt2int(a);
116
+ b = bam_aux_nt2int(b);
117
+ if(4 == a || 4 == b) return '4';
118
+ return "0123"[(int)(a ^ b)];
119
+ }
120
+
121
+ /*!
122
+ @abstract Get the color error profile at the give position
123
+ @param b pointer to an alignment
124
+ @return the original color if the color was an error, '-' (dash) otherwise
125
+
126
+ @discussion Returns 0 no color information is found.
127
+ */
128
+ char bam_aux_getCEi(bam1_t *b, int i)
129
+ {
130
+ int cs_i;
131
+ uint8_t *c = bam_aux_get(b, "CS");
132
+ char *cs = NULL;
133
+ char prev_b, cur_b;
134
+ char cur_color, cor_color;
135
+
136
+ // return the base if the tag was not found
137
+ if(0 == c) return 0;
138
+
139
+ cs = bam_aux2Z(c);
140
+
141
+ // adjust for strandedness and leading adaptor
142
+ if(bam_is_rev(b)) { //reverse strand
143
+ cs_i = strlen(cs) - 1 - i;
144
+ // adjust for leading hard clip
145
+ uint32_t cigar = bam_get_cigar(b)[0];
146
+ if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) {
147
+ cs_i -= cigar >> BAM_CIGAR_SHIFT;
148
+ }
149
+ // get current color
150
+ cur_color = cs[cs_i];
151
+ // get previous base. Note: must rc adaptor
152
+ prev_b = (cs_i == 1) ? "TGCAN"[(int)bam_aux_nt2int(cs[0])] : seq_nt16_str[bam_seqi(bam_get_seq(b), i+1)];
153
+ // get current base
154
+ cur_b = seq_nt16_str[bam_seqi(bam_get_seq(b), i)];
155
+ }
156
+ else {
157
+ cs_i=i+1;
158
+ // get current color
159
+ cur_color = cs[cs_i];
160
+ // get previous base
161
+ prev_b = (0 == i) ? cs[0] : seq_nt16_str[bam_seqi(bam_get_seq(b), i-1)];
162
+ // get current base
163
+ cur_b = seq_nt16_str[bam_seqi(bam_get_seq(b), i)];
164
+ }
165
+
166
+ // corrected color
167
+ cor_color = bam_aux_ntnt2cs(prev_b, cur_b);
168
+
169
+ if(cur_color == cor_color) {
170
+ return '-';
171
+ }
172
+ else {
173
+ return cur_color;
174
+ }
175
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_flags.c -- flags subcommand.
2
+
3
+ Copyright (C) 2013-2014, 2021 Genome Research Ltd.
4
+
5
+ Author: Petr Danecek <pd3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <ctype.h>
28
+ #include <string.h>
29
+ #include <stdlib.h>
30
+ #include <stdio.h>
31
+ #include <stdint.h>
32
+ #include <unistd.h>
33
+ #include <stdarg.h>
34
+ #include <htslib/sam.h>
35
+ #include "samtools.h"
36
+
37
+ static void usage(FILE *fp)
38
+ {
39
+ static const struct { int bit; const char *desc; } *fl, flags[] = {
40
+ { BAM_FPAIRED, "paired-end / multiple-segment sequencing technology" },
41
+ { BAM_FPROPER_PAIR, "each segment properly aligned according to aligner" },
42
+ { BAM_FUNMAP, "segment unmapped" },
43
+ { BAM_FMUNMAP, "next segment in the template unmapped" },
44
+ { BAM_FREVERSE, "SEQ is reverse complemented" },
45
+ { BAM_FMREVERSE, "SEQ of next segment in template is rev.complemented" },
46
+ { BAM_FREAD1, "the first segment in the template" },
47
+ { BAM_FREAD2, "the last segment in the template" },
48
+ { BAM_FSECONDARY, "secondary alignment" },
49
+ { BAM_FQCFAIL, "not passing quality controls or other filters" },
50
+ { BAM_FDUP, "PCR or optical duplicate" },
51
+ { BAM_FSUPPLEMENTARY, "supplementary alignment" },
52
+ { 0, NULL }
53
+ };
54
+
55
+ fprintf(fp,
56
+ "About: Convert between textual and numeric flag representation\n"
57
+ "Usage: samtools flags FLAGS...\n"
58
+ "\n"
59
+ "Each FLAGS argument is either an INT (in decimal/hexadecimal/octal) representing\n"
60
+ "a combination of the following numeric flag values, or a comma-separated string\n"
61
+ "NAME,...,NAME representing a combination of the following flag names:\n"
62
+ "\n");
63
+ for (fl = flags; fl->desc; fl++) {
64
+ char *name = bam_flag2str(fl->bit);
65
+ fprintf(fp, "%#6x %5d %-15s%s\n", fl->bit, fl->bit, name, fl->desc);
66
+ free(name);
67
+ }
68
+ }
69
+
70
+
71
+ int main_flags(int argc, char *argv[])
72
+ {
73
+ if ( argc < 2 ) { usage(stdout); return 0; }
74
+
75
+ int i;
76
+ for (i = 1; i < argc; i++)
77
+ {
78
+ int mask = bam_str2flag(argv[i]);
79
+ if ( mask<0 ) { print_error("flags", "Could not parse \"%s\"", argv[i]); usage(stderr); return 1; }
80
+ char *str = bam_flag2str(mask);
81
+ printf("0x%x\t%d\t%s\n", mask, mask, str);
82
+ free(str);
83
+ }
84
+ return 0;
85
+ }
86
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c.pysam.c ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_flags.c -- flags subcommand.
4
+
5
+ Copyright (C) 2013-2014, 2021 Genome Research Ltd.
6
+
7
+ Author: Petr Danecek <pd3@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ #include <config.h>
28
+
29
+ #include <ctype.h>
30
+ #include <string.h>
31
+ #include <stdlib.h>
32
+ #include <stdio.h>
33
+ #include <stdint.h>
34
+ #include <unistd.h>
35
+ #include <stdarg.h>
36
+ #include <htslib/sam.h>
37
+ #include "samtools.h"
38
+
39
+ static void usage(FILE *fp)
40
+ {
41
+ static const struct { int bit; const char *desc; } *fl, flags[] = {
42
+ { BAM_FPAIRED, "paired-end / multiple-segment sequencing technology" },
43
+ { BAM_FPROPER_PAIR, "each segment properly aligned according to aligner" },
44
+ { BAM_FUNMAP, "segment unmapped" },
45
+ { BAM_FMUNMAP, "next segment in the template unmapped" },
46
+ { BAM_FREVERSE, "SEQ is reverse complemented" },
47
+ { BAM_FMREVERSE, "SEQ of next segment in template is rev.complemented" },
48
+ { BAM_FREAD1, "the first segment in the template" },
49
+ { BAM_FREAD2, "the last segment in the template" },
50
+ { BAM_FSECONDARY, "secondary alignment" },
51
+ { BAM_FQCFAIL, "not passing quality controls or other filters" },
52
+ { BAM_FDUP, "PCR or optical duplicate" },
53
+ { BAM_FSUPPLEMENTARY, "supplementary alignment" },
54
+ { 0, NULL }
55
+ };
56
+
57
+ fprintf(fp,
58
+ "About: Convert between textual and numeric flag representation\n"
59
+ "Usage: samtools flags FLAGS...\n"
60
+ "\n"
61
+ "Each FLAGS argument is either an INT (in decimal/hexadecimal/octal) representing\n"
62
+ "a combination of the following numeric flag values, or a comma-separated string\n"
63
+ "NAME,...,NAME representing a combination of the following flag names:\n"
64
+ "\n");
65
+ for (fl = flags; fl->desc; fl++) {
66
+ char *name = bam_flag2str(fl->bit);
67
+ fprintf(fp, "%#6x %5d %-15s%s\n", fl->bit, fl->bit, name, fl->desc);
68
+ free(name);
69
+ }
70
+ }
71
+
72
+
73
+ int main_flags(int argc, char *argv[])
74
+ {
75
+ if ( argc < 2 ) { usage(samtools_stdout); return 0; }
76
+
77
+ int i;
78
+ for (i = 1; i < argc; i++)
79
+ {
80
+ int mask = bam_str2flag(argv[i]);
81
+ if ( mask<0 ) { print_error("flags", "Could not parse \"%s\"", argv[i]); usage(samtools_stderr); return 1; }
82
+ char *str = bam_flag2str(mask);
83
+ fprintf(samtools_stdout, "0x%x\t%d\t%s\n", mask, mask, str);
84
+ free(str);
85
+ }
86
+ return 0;
87
+ }
88
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_import.c.pysam.c ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_import -- Import of FASTQ files.
4
+ *
5
+ * samtools import -1 a_1.fq -2 a_2.fq --i1 a_i1.fq --i2 a_i2.fq
6
+ * samtools import a_1.fq a_2.fq
7
+ * samtools import a_interleaved.fq
8
+ *
9
+ * Copyright (C) 2020-2021, 2023 Genome Research Ltd.
10
+ *
11
+ * Author: James Bonfield <jkb@sanger.ac.uk>
12
+ */
13
+
14
+ /*
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notices and this permission notice shall be included in
23
+ all copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31
+ DEALINGS IN THE SOFTWARE.
32
+ */
33
+
34
+ // TODO: Store other non-aux comments; in new sam tag?
35
+
36
+ #include <config.h>
37
+ #include <ctype.h>
38
+
39
+ #include "htslib/sam.h"
40
+ #include "htslib/thread_pool.h"
41
+
42
+ #include "samtools.h"
43
+ #include "sam_opts.h"
44
+
45
+ static int usage(FILE *fp, int exit_status) {
46
+ fprintf(fp, "Usage: samtools import [options] [file.fastq ...]\n");
47
+ fprintf(fp, "\n");
48
+ fprintf(fp, "Options:\n");
49
+ fprintf(fp, " -s FILE Read paired-ended data from single FILE\n");
50
+ fprintf(fp, " -0 FILE Read single-ended data from FILE\n");
51
+ fprintf(fp, " -1 FILE Read-1 from FILE\n");
52
+ fprintf(fp, " -2 FILE Read-2 from FILE\n");
53
+ fprintf(fp, " --i1 FILE Index-1 from FILE\n");
54
+ fprintf(fp, " --i2 FILE Index-2 from FILE\n");
55
+ fprintf(fp, " -i Parse CASAVA identifier\n");
56
+ fprintf(fp, " --barcode-tag TAG\n");
57
+ fprintf(fp, " Tag to use with barcode sequences [BC]\n");
58
+ fprintf(fp, " --quality-tag TAG\n");
59
+ fprintf(fp, " Tag to use with barcode qualities [QT]\n");
60
+ fprintf(fp, " -N, --name2 Use 2nd field as read name (SRA format)\n");
61
+ fprintf(fp, " -r STRING Build up a complete @RG line\n");
62
+ fprintf(fp, " -R STRING Add a simple RG line of \"@RG\\tID:STRING\"\n");
63
+ fprintf(fp, " -T TAGLIST Parse tags in SAM format; list of '*' for all\n");
64
+ fprintf(fp, " -o FILE Output to FILE instead of samtools_stdout\n");
65
+ fprintf(fp, " -u Uncompressed output\n");
66
+ fprintf(fp, " --order TAG Store Nth record count in TAG\n");
67
+ fprintf(fp, "\n");
68
+ sam_global_opt_help(fp, "-.O.-@--");
69
+
70
+ fprintf(fp, "\nA single fastq file will be interpreted as -s, -0 or -1 depending on\n");
71
+ fprintf(fp, "file contents, and a pair of fastq files as \"-1 FILE1 -2 FILE2\".\n");
72
+
73
+ return exit_status;
74
+ }
75
+
76
+ // Order matters here as we want to read index elements before main
77
+ // sequences so on reading the seqs we can emit a fully annotated record.
78
+ enum fileno {
79
+ FQ_I1, FQ_I2, // index seqs for R1 and R2
80
+ FQ_R0, // single file and unpaired data (singled-ended tech).
81
+ FQ_R1, FQ_R2, // separate read1 and read2 files
82
+ FQ_SINGLE, // single file, but with read1 and/or read2 present.
83
+ FQ_END
84
+ };
85
+
86
+ typedef struct {
87
+ sam_global_args ga;
88
+ int no_pg;
89
+ char *fn[FQ_END], *fn_out;
90
+ int idx_both; // add index to READ2 too, not just READ1
91
+ int casava;
92
+ char *barcode_seq;
93
+ char *barcode_qual;
94
+ char *aux;
95
+ char *rg;
96
+ char *rg_line;
97
+ char *order;
98
+ int order_str;
99
+ int compress_level;
100
+ htsThreadPool p;
101
+ int name2;
102
+ } opts_t;
103
+
104
+ // Append a sequence and quality string from a BAM record to a BC:Z and
105
+ // QT:Z style aux tag string.
106
+ static int append_index(kstring_t *s, kstring_t *q, bam1_t *b) {
107
+ char *sp, *qp;
108
+ if (ks_resize(s, s->l + b->core.l_qseq+1 +1) < 0)
109
+ return -1;
110
+ if (ks_resize(q, q->l + b->core.l_qseq+1 +1) < 0)
111
+ return -1;
112
+
113
+ sp = s->s + s->l - (s->l > 0);
114
+ qp = q->s + q->l - (q->l > 0);
115
+
116
+ if (s->l)
117
+ *sp++ = '-';
118
+
119
+ if (q->l)
120
+ *qp++ = ' ';
121
+
122
+ int i;
123
+ uint8_t *seq = bam_get_seq(b);
124
+ uint8_t *qual = bam_get_qual(b);
125
+ for (i = 0; i < b->core.l_qseq; i++) {
126
+ *sp++ = seq_nt16_str[bam_seqi(seq, i)];
127
+ *qp++ = qual[i] + '!';
128
+ }
129
+ *sp++ = 0;
130
+ *qp++ = 0;
131
+
132
+ s->l = sp - s->s;
133
+ q->l = qp - q->s;
134
+
135
+ return 0;
136
+ }
137
+
138
+ static int import_fastq(int argc, char **argv, opts_t *opts) {
139
+ int i, n, ret = 0;
140
+ samFile *fp_in[FQ_END] = {NULL};
141
+ bam1_t *b = bam_init1();
142
+ int ids[FQ_END];
143
+ samFile *fp_out = NULL;
144
+ sam_hdr_t *hdr_out = NULL;
145
+ kstring_t index_str = {0,0};
146
+ kstring_t read_str = {0,0};
147
+ char *rg = opts->rg;
148
+ kstring_t rg_line = {0,0};
149
+ uint64_t read_num = 0;
150
+ kstring_t idx_seq = {0};
151
+ kstring_t idx_qual = {0};
152
+
153
+ // Any additional arguments are assumed to be r1 r2, as a
154
+ // short cut. We support reading index tags out of those too (eg
155
+ // Illumina CASAVA format), but if we do that we lack the barcode
156
+ // quality string.
157
+ //
158
+ // We also consider a read name ending in /1 or /2 to be a single
159
+ // file containing interleaved fastq records for both ends.
160
+ // These will be labeled as fn[FQ_R1] but adjusted during reading.
161
+ if (argc == 1)
162
+ opts->fn[FQ_SINGLE] = argv[0];
163
+ else
164
+ for (i = 0; i < 4; i++)
165
+ if (argc > i)
166
+ opts->fn[FQ_R1+i] = argv[i];
167
+
168
+ // Open all files
169
+ for (i = n = 0; i < FQ_END; i++) {
170
+ if (!opts->fn[i])
171
+ continue;
172
+ fp_in[i] = sam_open_format(opts->fn[i], "r", &opts->ga.in);
173
+ if (!fp_in[i]) {
174
+ perror(opts->fn[i]);
175
+ ret = -1;
176
+ goto err;
177
+ }
178
+ if (opts->p.pool)
179
+ hts_set_thread_pool(fp_in[i], &opts->p);
180
+ ids[n++] = i;
181
+
182
+ if (opts->name2)
183
+ hts_set_opt(fp_in[i], FASTQ_OPT_NAME2, 1);
184
+ if (opts->casava)
185
+ hts_set_opt(fp_in[i], FASTQ_OPT_CASAVA, 1);
186
+ if (opts->barcode_seq) // for auto-CASAVA parsing
187
+ hts_set_opt(fp_in[i], FASTQ_OPT_BARCODE, opts->barcode_seq);
188
+ if (opts->aux)
189
+ hts_set_opt(fp_in[i], FASTQ_OPT_AUX,
190
+ *opts->aux == '*' || *opts->aux == '\0'
191
+ ? NULL : opts->aux);
192
+
193
+ switch (i) {
194
+ case FQ_I1:
195
+ kputs("--i1 I1.fastq ", &read_str);
196
+ kputs("i*", &index_str);
197
+ break;
198
+ case FQ_I2:
199
+ kputs("--i2 I2.fastq ", &read_str);
200
+ kputs("i*", &index_str);
201
+ break;
202
+
203
+ case FQ_R0:
204
+ kputs("-0 unpaired.fastq ", &read_str);
205
+ break;
206
+
207
+ case FQ_R1:
208
+ kputs("-1 R1.fastq ", &read_str);
209
+ break;
210
+
211
+ case FQ_R2:
212
+ kputs("-2 R2.fastq ", &read_str);
213
+ break;
214
+
215
+ case FQ_SINGLE:
216
+ kputs("-N -o paired.fastq ", &read_str);
217
+ break;
218
+
219
+ default:
220
+ ks_clear(&read_str); // not reversible
221
+ kputs("", &read_str);
222
+ }
223
+ }
224
+ if (n == 0) {
225
+ bam_destroy1(b);
226
+ return usage(samtools_stdout, EXIT_SUCCESS);
227
+ }
228
+
229
+ char out_mode[10] = {'w', 0, 0};
230
+ if (opts->compress_level != -1)
231
+ out_mode[1] = '0' + opts->compress_level;
232
+ sam_open_mode(out_mode+strlen(out_mode), opts->fn_out, NULL);
233
+ fp_out = sam_open_format(opts->fn_out, out_mode, &opts->ga.out);
234
+ if (!fp_out) {
235
+ perror(opts->fn_out);
236
+ goto err;
237
+ }
238
+ autoflush_if_stdout(fp_out, opts->fn_out);
239
+ if (opts->p.pool)
240
+ hts_set_thread_pool(fp_out, &opts->p);
241
+
242
+ // Create header
243
+ if (ks_len(&read_str)) {
244
+ char CO[2100];
245
+ if (ks_len(&index_str))
246
+ snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s "
247
+ "--index-format=\"%s\"\n",
248
+ ks_str(&read_str), ks_str(&index_str));
249
+ else
250
+ snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s\n",
251
+ ks_str(&read_str));
252
+
253
+ hdr_out = sam_hdr_parse(strlen(CO), CO);
254
+ } else {
255
+ hdr_out = sam_hdr_init();
256
+ }
257
+
258
+ // Add a version line with the sort order to the output header
259
+ if (sam_hdr_add_line(hdr_out, "HD", "VN", SAM_FORMAT_VERSION, "SO", "unsorted", "GO", "query", NULL) < 0) {
260
+ fprintf(samtools_stderr, "Could not set SO and GO in the header.\n");
261
+ goto err;
262
+ }
263
+
264
+ // Read group
265
+ if (opts->rg_line) {
266
+ if (*opts->rg_line != '@')
267
+ ksprintf(&rg_line, "@RG\t%s", opts->rg_line);
268
+ else
269
+ kputs(opts->rg_line, &rg_line);
270
+ } else if (opts->rg) {
271
+ ksprintf(&rg_line, "@RG\tID:%s", opts->rg);
272
+ }
273
+
274
+ if (ks_len(&rg_line)) {
275
+ if (sam_hdr_add_lines(hdr_out, ks_str(&rg_line), 0) < 0)
276
+ goto err;
277
+ rg = strstr(ks_str(&rg_line), "\tID:");
278
+ if (!rg) {
279
+ fprintf(samtools_stderr, "\"-r RG-LINE\" option contained no ID field\n");
280
+ goto err;
281
+ }
282
+ rg += 4;
283
+
284
+ i = 0;
285
+ while (rg[i] != '\t' && rg[i] != '\0')
286
+ i++;
287
+ rg[i] = 0;
288
+ }
289
+
290
+ if ((ret = sam_hdr_write(fp_out, hdr_out)) < 0)
291
+ goto err;
292
+
293
+
294
+ // Interleave / combine from n files (ids[0..n-1]).
295
+ int res;
296
+ int eof = 0;
297
+ do {
298
+ idx_seq.l = idx_qual.l = 0;
299
+ for (i = 0; i < n; i++) {
300
+ if ((res = sam_read1(fp_in[ids[i]], NULL, b)) < 0) {
301
+ if (res == -1) {
302
+ eof++;
303
+ continue;
304
+ } else
305
+ break;
306
+ }
307
+
308
+ // index
309
+ if (ids[i] == FQ_I1 || ids[i] == FQ_I2) {
310
+ if (append_index(&idx_seq, &idx_qual, b) < 0) {
311
+ res = -1;
312
+ break;
313
+ }
314
+ continue;
315
+ }
316
+
317
+ // full read
318
+ if (idx_seq.l) {
319
+ if (opts->idx_both || ids[i] == FQ_SINGLE ||
320
+ ids[i] == FQ_R0 || ids[i] == FQ_R1) {
321
+ if (bam_aux_append(b, opts->barcode_seq, 'Z', idx_seq.l,
322
+ (uint8_t *)idx_seq.s) ||
323
+ bam_aux_append(b, opts->barcode_qual, 'Z', idx_qual.l,
324
+ (uint8_t *)idx_qual.s)) {
325
+ res = -1;
326
+ break;
327
+ }
328
+ }
329
+ }
330
+
331
+ switch(ids[i]) {
332
+ case FQ_R0:
333
+ // unpaired; no flags to declare
334
+ break;
335
+ case FQ_SINGLE:
336
+ // paired (but don't know if R1 or R2) or unpaired.
337
+ // We rely on the /1 and /2 read suffix parsing in htslib
338
+ // to distinguish the two cases, or CASAVA tags if
339
+ // explicitly enabled.
340
+ break;
341
+ case FQ_R1:
342
+ if ((b->core.flag & (BAM_FREAD1 | BAM_FREAD2)) == 0)
343
+ b->core.flag |= BAM_FREAD1;
344
+ b->core.flag |= BAM_FPAIRED;
345
+ if (i+1 < n && ids[i+1] == FQ_R2)
346
+ b->core.flag |= BAM_FMUNMAP;
347
+ break;
348
+ case FQ_R2:
349
+ b->core.flag |= BAM_FPAIRED | BAM_FREAD2;
350
+ if (i > 0 && ids[i-1] == FQ_R1)
351
+ b->core.flag |= BAM_FMUNMAP;
352
+ break;
353
+ }
354
+
355
+ if (rg) {
356
+ if (bam_aux_append(b, "RG", 'Z', strlen(rg)+1,
357
+ (uint8_t *)rg) < 0) {
358
+ ret = -1;
359
+ goto err;
360
+ }
361
+ }
362
+
363
+ if (opts->order) {
364
+ if (opts->order_str) {
365
+ char buf[25];
366
+ snprintf(buf, sizeof(buf), "%0*"PRIu64,
367
+ opts->order_str, read_num++);
368
+ if (bam_aux_update_str(b, opts->order,
369
+ strlen(buf), buf) < 0) {
370
+ ret = -1;
371
+ goto err;
372
+ }
373
+ } else {
374
+ if (bam_aux_update_int(b, opts->order, read_num++) < 0) {
375
+ ret = -1;
376
+ goto err;
377
+ }
378
+ if (read_num == UINT_MAX)
379
+ fprintf(samtools_stderr, "Warning: --order tag has overflowed."
380
+ " Consider using TAG:LENGTH instead\n");
381
+ }
382
+ }
383
+
384
+ res = sam_write1(fp_out, hdr_out, b);
385
+ }
386
+ } while (res >= 0);
387
+
388
+ if (res != -1) {
389
+ print_error("import", "truncated file. Aborting");
390
+ ret = res;
391
+ goto err;
392
+ }
393
+
394
+ if (eof != n) {
395
+ print_error("import", "input files with differing number of records");
396
+ ret = -1;
397
+ goto err;
398
+ }
399
+
400
+ // Close and return
401
+ ret = 0;
402
+ err:
403
+ bam_destroy1(b);
404
+ sam_hdr_destroy(hdr_out);
405
+ ks_free(&rg_line);
406
+ ks_free(&index_str);
407
+ ks_free(&read_str);
408
+ if (fp_out) {
409
+ release_autoflush(fp_out);
410
+ if (sam_close(fp_out) < 0) {
411
+ perror(opts->fn_out);
412
+ ret |= -1;
413
+ }
414
+ }
415
+ for (i = 0; i < FQ_END; i++) {
416
+ if (fp_in[i] && sam_close(fp_in[i]) < 0) {
417
+ perror(opts->fn[i]);
418
+ ret |= -1;
419
+ }
420
+ }
421
+ ks_free(&idx_seq);
422
+ ks_free(&idx_qual);
423
+
424
+ return ret;
425
+ }
426
+
427
+ int main_import(int argc, char *argv[]) {
428
+ int c;
429
+ opts_t opts = {
430
+ .no_pg = 0,
431
+ .ga = SAM_GLOBAL_ARGS_INIT,
432
+ .fn = {NULL},
433
+ .fn_out = "-",
434
+ .casava = 0,
435
+ .barcode_seq = "BC",
436
+ .barcode_qual = "QT",
437
+ .aux = NULL,
438
+ .rg = NULL,
439
+ .rg_line = NULL,
440
+ .order = NULL,
441
+ .order_str = 0,
442
+ .compress_level = -1,
443
+ .name2 = 0,
444
+ };
445
+ kstring_t rg = {0};
446
+
447
+ static const struct option lopts[] = {
448
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, '-', '@'),
449
+ {"no-PG", no_argument, NULL, 9},
450
+ {"i1", required_argument, NULL, 1},
451
+ {"i2", required_argument, NULL, 2},
452
+ {"r1", required_argument, NULL, '1'},
453
+ {"r2", required_argument, NULL, '2'},
454
+ {"rg", required_argument, NULL, 'R'},
455
+ {"rg-line", required_argument, NULL, 'r'},
456
+ {"order", required_argument, NULL, 3},
457
+ {"barcode-tag", required_argument, NULL, 4},
458
+ {"quality-tag", required_argument, NULL, 5},
459
+ {"name2", no_argument, NULL, 'N'},
460
+ { NULL, 0, NULL, 0 }
461
+ };
462
+
463
+ while ((c = getopt_long(argc, argv, "1:2:s:0:bhiT:r:R:o:O:u@:N", lopts, NULL)) >= 0) {
464
+ switch (c) {
465
+ case 'b': opts.idx_both = 1; break;
466
+ case '0': opts.fn[FQ_R0] = optarg; break;
467
+ case '1': opts.fn[FQ_R1] = optarg; break;
468
+ case '2': opts.fn[FQ_R2] = optarg; break;
469
+ case 1: opts.fn[FQ_I1] = optarg; break;
470
+ case 2: opts.fn[FQ_I2] = optarg; break;
471
+ case 's': opts.fn[FQ_SINGLE] = optarg; break;
472
+ case 'o': opts.fn_out = optarg; break;
473
+ case 'i': opts.casava = 1; break;
474
+ case 4: opts.barcode_seq = optarg; break;
475
+ case 5: opts.barcode_qual = optarg; break;
476
+ case 'T': opts.aux = optarg; break;
477
+ case 'u': opts.compress_level = 0; break;
478
+ case 'R': opts.rg = optarg; break;
479
+ case 'r':
480
+ if (*optarg != '@' && ks_len(&rg) == 0)
481
+ kputs("@RG", &rg);
482
+ if (ks_len(&rg))
483
+ kputc_('\t', &rg);
484
+ kputs(optarg, &rg);
485
+ opts.rg_line = rg.s;
486
+ break;
487
+
488
+ case 'N': opts.name2 = 1; break;
489
+
490
+ case 9: opts.no_pg = 1; break;
491
+ case 3:
492
+ opts.order = optarg;
493
+ if (strlen(optarg) > 3 && optarg[2] == ':')
494
+ opts.order_str = atoi(optarg+3);
495
+ break;
496
+
497
+ case 'h': return usage(samtools_stdout, EXIT_SUCCESS);
498
+ case '?': return usage(samtools_stderr, EXIT_FAILURE);
499
+
500
+ default:
501
+ if (parse_sam_global_opt(c, optarg, lopts, &opts.ga) != 0)
502
+ return usage(samtools_stderr, EXIT_FAILURE);
503
+ break;
504
+ }
505
+ }
506
+
507
+ if (opts.ga.nthreads > 0) {
508
+ if (!(opts.p.pool = hts_tpool_init(opts.ga.nthreads))) {
509
+ fprintf(samtools_stderr, "Failed to create thread pool\n");
510
+ if (rg.s)
511
+ free(rg.s);
512
+ return -1;;
513
+ }
514
+ }
515
+
516
+ int ret = import_fastq(argc-optind, argv+optind, &opts) ? 1 : 0;
517
+
518
+ if (rg.s)
519
+ free(rg.s);
520
+
521
+ if (opts.p.pool)
522
+ hts_tpool_destroy(opts.p.pool);
523
+
524
+ return ret;
525
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_index.c -- index and idxstats subcommands.
2
+
3
+ Copyright (C) 2008-2011, 2013-2016, 2018, 2019, 2023 Genome Research Ltd.
4
+ Portions copyright (C) 2010 Broad Institute.
5
+ Portions copyright (C) 2013 Peter Cock, The James Hutton Institute.
6
+
7
+ Author: Heng Li <lh3@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notices and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ #include <config.h>
28
+
29
+ #include <htslib/hts.h>
30
+ #include <htslib/sam.h>
31
+ #include <htslib/hfile.h>
32
+ #include <htslib/khash.h>
33
+ #include <stdlib.h>
34
+ #include <stdio.h>
35
+ #include <inttypes.h>
36
+ #include <unistd.h>
37
+ #include <getopt.h>
38
+
39
+ #include "samtools.h"
40
+ #include "sam_opts.h"
41
+
42
+ #define BAM_LIDX_SHIFT 14
43
+
44
+ static void index_usage(FILE *fp)
45
+ {
46
+ fprintf(fp,
47
+ "Usage: samtools index -M [-bc] [-m INT] <in1.bam> <in2.bam>...\n"
48
+ " or: samtools index [-bc] [-m INT] <in.bam> [out.index]\n"
49
+ "Options:\n"
50
+ " -b, --bai Generate BAI-format index for BAM files [default]\n"
51
+ " -c, --csi Generate CSI-format index for BAM files\n"
52
+ " -m, --min-shift INT Set minimum interval size for CSI indices to 2^INT [%d]\n"
53
+ " -M Interpret all filename arguments as files to be indexed\n"
54
+ " -o, --output FILE Write index to FILE [alternative to <out.index> in args]\n"
55
+ " -@, --threads INT Sets the number of threads [none]\n", BAM_LIDX_SHIFT);
56
+ }
57
+
58
+ // Returns 1 if the file does not exist or can be positively
59
+ // identified as an index file.
60
+ static int nonexistent_or_index(const char *fn)
61
+ {
62
+ int ret1, ret2;
63
+ htsFormat fmt;
64
+ hFILE *fp = hopen(fn, "r");
65
+ if (fp == NULL) return 1;
66
+
67
+ ret1 = hts_detect_format2(fp, fn, &fmt);
68
+ ret2 = hclose(fp);
69
+ if (ret1 < 0 || ret2 < 0) return 0;
70
+
71
+ return fmt.category == index_file;
72
+ }
73
+
74
+ int bam_index(int argc, char *argv[])
75
+ {
76
+ int csi = 0;
77
+ int min_shift = BAM_LIDX_SHIFT;
78
+ int multiple = 0;
79
+ int n_threads = 0;
80
+ int n_files, c, i, ret;
81
+ const char *fn_idx = NULL;
82
+
83
+ static const struct option lopts[] = {
84
+ SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'),
85
+ {"output", required_argument, NULL, 'o'},
86
+ {"bai", no_argument, NULL, 'b'},
87
+ {"csi", no_argument, NULL, 'c'},
88
+ {"min-shift", required_argument, NULL, 'm'},
89
+ { NULL, 0, NULL, 0 }
90
+ };
91
+
92
+ while ((c = getopt_long(argc, argv, "bcm:Mo:@:", lopts, NULL)) >= 0)
93
+ switch (c) {
94
+ case 'b': csi = 0; break;
95
+ case 'c': csi = 1; break;
96
+ case 'm': csi = 1; min_shift = atoi(optarg); break;
97
+ case 'M': multiple = 1; break;
98
+ case 'o': fn_idx = optarg; break;
99
+ case '@': n_threads = atoi(optarg); break;
100
+ default:
101
+ index_usage(stderr);
102
+ return 1;
103
+ }
104
+
105
+ n_files = argc - optind;
106
+
107
+ if (n_files == 0) {
108
+ index_usage(stdout);
109
+ return 0;
110
+ }
111
+
112
+ // Handle legacy synopsis
113
+ if (n_files == 2 && !fn_idx && nonexistent_or_index(argv[optind+1])) {
114
+ n_files = 1;
115
+ fn_idx = argv[optind+1];
116
+ }
117
+
118
+ if (n_files > 1 && !multiple) {
119
+ print_error("index", "use -M to enable indexing more than one alignment file");
120
+ return EXIT_FAILURE;
121
+ }
122
+
123
+ if (fn_idx && n_files > 1) {
124
+ // TODO In future we may allow %* placeholders or similar
125
+ print_error("index", "can't use -o with multiple input alignment files");
126
+ return EXIT_FAILURE;
127
+ }
128
+
129
+ for (i = optind; i < optind + n_files; i++) {
130
+ ret = sam_index_build3(argv[i], fn_idx, csi? min_shift : 0, n_threads);
131
+ if (ret < 0) {
132
+ if (ret == -2)
133
+ print_error_errno("index", "failed to open \"%s\"", argv[i]);
134
+ else if (ret == -3)
135
+ print_error("index", "\"%s\" is in a format that cannot be usefully indexed", argv[i]);
136
+ else if (ret == -4 && fn_idx)
137
+ print_error("index", "failed to create or write index \"%s\"", fn_idx);
138
+ else if (ret == -4)
139
+ print_error("index", "failed to create or write index");
140
+ else
141
+ print_error_errno("index", "failed to create index for \"%s\"", argv[i]);
142
+ return EXIT_FAILURE;
143
+ }
144
+ }
145
+
146
+ return EXIT_SUCCESS;
147
+ }
148
+
149
+ /*
150
+ * Cram indices do not contain mapped/unmapped record counts, so we have to
151
+ * decode each record and count. However we can speed this up as much as
152
+ * possible by using the required fields parameter.
153
+ *
154
+ * This prints the stats to stdout in the same manner than the BAM function
155
+ * does.
156
+ *
157
+ * Returns 0 on success,
158
+ * -1 on failure.
159
+ */
160
+ int slow_idxstats(samFile *fp, sam_hdr_t *header) {
161
+ int ret, last_tid = -2;
162
+ bam1_t *b = bam_init1();
163
+
164
+ if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, SAM_RNAME | SAM_FLAG))
165
+ return -1;
166
+
167
+ uint64_t (*count0)[2] = calloc(sam_hdr_nref(header)+1, sizeof(*count0));
168
+ uint64_t (*counts)[2] = count0+1;
169
+ if (!count0)
170
+ return -1;
171
+
172
+ while ((ret = sam_read1(fp, header, b)) >= 0) {
173
+ if (b->core.tid >= sam_hdr_nref(header) || b->core.tid < -1) {
174
+ free(count0);
175
+ return -1;
176
+ }
177
+
178
+ if (b->core.tid != last_tid) {
179
+ if (last_tid >= -1) {
180
+ if (counts[b->core.tid][0] + counts[b->core.tid][1]) {
181
+ print_error("idxstats", "file is not position sorted");
182
+ free(count0);
183
+ return -1;
184
+ }
185
+ }
186
+ last_tid = b->core.tid;
187
+ }
188
+
189
+ counts[b->core.tid][(b->core.flag & BAM_FUNMAP) ? 1 : 0]++;
190
+ }
191
+
192
+ if (ret == -1) {
193
+ int i;
194
+ for (i = 0; i < sam_hdr_nref(header); i++) {
195
+ printf("%s\t%"PRId64"\t%"PRIu64"\t%"PRIu64"\n",
196
+ sam_hdr_tid2name(header, i),
197
+ (int64_t) sam_hdr_tid2len(header, i),
198
+ counts[i][0], counts[i][1]);
199
+ }
200
+ printf("*\t0\t%"PRIu64"\t%"PRIu64"\n", counts[-1][0], counts[-1][1]);
201
+ }
202
+
203
+ free(count0);
204
+
205
+ bam_destroy1(b);
206
+
207
+ return (ret == -1) ? 0 : -1;
208
+ }
209
+
210
+ static void usage_exit(FILE *fp, int exit_status)
211
+ {
212
+ fprintf(fp, "Usage: samtools idxstats [options] <in.bam>\n");
213
+ sam_global_opt_help(fp, "-.---@-.");
214
+ exit(exit_status);
215
+ }
216
+
217
+ int bam_idxstats(int argc, char *argv[])
218
+ {
219
+ hts_idx_t* idx;
220
+ sam_hdr_t* header;
221
+ samFile* fp;
222
+ int c;
223
+
224
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
225
+ static const struct option lopts[] = {
226
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '@'),
227
+ {NULL, 0, NULL, 0}
228
+ };
229
+
230
+ while ((c = getopt_long(argc, argv, "@:", lopts, NULL)) >= 0) {
231
+ switch (c) {
232
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
233
+ /* else fall-through */
234
+ case '?':
235
+ usage_exit(stderr, EXIT_FAILURE);
236
+ }
237
+ }
238
+
239
+ if (argc != optind+1) {
240
+ if (argc == optind) usage_exit(stdout, EXIT_SUCCESS);
241
+ else usage_exit(stderr, EXIT_FAILURE);
242
+ }
243
+
244
+ fp = sam_open_format(argv[optind], "r", &ga.in);
245
+ if (fp == NULL) {
246
+ print_error_errno("idxstats", "failed to open \"%s\"", argv[optind]);
247
+ return 1;
248
+ }
249
+ header = sam_hdr_read(fp);
250
+ if (header == NULL) {
251
+ print_error("idxstats", "failed to read header for \"%s\"", argv[optind]);
252
+ return 1;
253
+ }
254
+
255
+ if (hts_get_format(fp)->format != bam) {
256
+ slow_method:
257
+ if (ga.nthreads)
258
+ hts_set_threads(fp, ga.nthreads);
259
+
260
+ if (slow_idxstats(fp, header) < 0) {
261
+ print_error("idxstats", "failed to process \"%s\"", argv[optind]);
262
+ return 1;
263
+ }
264
+ } else {
265
+ idx = sam_index_load(fp, argv[optind]);
266
+ if (idx == NULL) {
267
+ print_error("idxstats", "fail to load index for \"%s\", "
268
+ "reverting to slow method", argv[optind]);
269
+ goto slow_method;
270
+ }
271
+
272
+ int i;
273
+ for (i = 0; i < sam_hdr_nref(header); ++i) {
274
+ // Print out contig name and length
275
+ printf("%s\t%"PRId64, sam_hdr_tid2name(header, i), (int64_t) sam_hdr_tid2len(header, i));
276
+ // Now fetch info about it from the meta bin
277
+ uint64_t u, v;
278
+ hts_idx_get_stat(idx, i, &u, &v);
279
+ printf("\t%" PRIu64 "\t%" PRIu64 "\n", u, v);
280
+ }
281
+ // Dump information about unmapped reads
282
+ printf("*\t0\t0\t%" PRIu64 "\n", hts_idx_get_n_no_coor(idx));
283
+ hts_idx_destroy(idx);
284
+ }
285
+
286
+ sam_hdr_destroy(header);
287
+ sam_close(fp);
288
+ return 0;
289
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c.pysam.c ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_index.c -- index and idxstats subcommands.
4
+
5
+ Copyright (C) 2008-2011, 2013-2016, 2018, 2019, 2023 Genome Research Ltd.
6
+ Portions copyright (C) 2010 Broad Institute.
7
+ Portions copyright (C) 2013 Peter Cock, The James Hutton Institute.
8
+
9
+ Author: Heng Li <lh3@sanger.ac.uk>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notices and this permission notice shall be included in
19
+ all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
+ DEALINGS IN THE SOFTWARE. */
28
+
29
+ #include <config.h>
30
+
31
+ #include <htslib/hts.h>
32
+ #include <htslib/sam.h>
33
+ #include <htslib/hfile.h>
34
+ #include <htslib/khash.h>
35
+ #include <stdlib.h>
36
+ #include <stdio.h>
37
+ #include <inttypes.h>
38
+ #include <unistd.h>
39
+ #include <getopt.h>
40
+
41
+ #include "samtools.h"
42
+ #include "sam_opts.h"
43
+
44
+ #define BAM_LIDX_SHIFT 14
45
+
46
+ static void index_usage(FILE *fp)
47
+ {
48
+ fprintf(fp,
49
+ "Usage: samtools index -M [-bc] [-m INT] <in1.bam> <in2.bam>...\n"
50
+ " or: samtools index [-bc] [-m INT] <in.bam> [out.index]\n"
51
+ "Options:\n"
52
+ " -b, --bai Generate BAI-format index for BAM files [default]\n"
53
+ " -c, --csi Generate CSI-format index for BAM files\n"
54
+ " -m, --min-shift INT Set minimum interval size for CSI indices to 2^INT [%d]\n"
55
+ " -M Interpret all filename arguments as files to be indexed\n"
56
+ " -o, --output FILE Write index to FILE [alternative to <out.index> in args]\n"
57
+ " -@, --threads INT Sets the number of threads [none]\n", BAM_LIDX_SHIFT);
58
+ }
59
+
60
+ // Returns 1 if the file does not exist or can be positively
61
+ // identified as an index file.
62
+ static int nonexistent_or_index(const char *fn)
63
+ {
64
+ int ret1, ret2;
65
+ htsFormat fmt;
66
+ hFILE *fp = hopen(fn, "r");
67
+ if (fp == NULL) return 1;
68
+
69
+ ret1 = hts_detect_format2(fp, fn, &fmt);
70
+ ret2 = hclose(fp);
71
+ if (ret1 < 0 || ret2 < 0) return 0;
72
+
73
+ return fmt.category == index_file;
74
+ }
75
+
76
+ int bam_index(int argc, char *argv[])
77
+ {
78
+ int csi = 0;
79
+ int min_shift = BAM_LIDX_SHIFT;
80
+ int multiple = 0;
81
+ int n_threads = 0;
82
+ int n_files, c, i, ret;
83
+ const char *fn_idx = NULL;
84
+
85
+ static const struct option lopts[] = {
86
+ SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'),
87
+ {"output", required_argument, NULL, 'o'},
88
+ {"bai", no_argument, NULL, 'b'},
89
+ {"csi", no_argument, NULL, 'c'},
90
+ {"min-shift", required_argument, NULL, 'm'},
91
+ { NULL, 0, NULL, 0 }
92
+ };
93
+
94
+ while ((c = getopt_long(argc, argv, "bcm:Mo:@:", lopts, NULL)) >= 0)
95
+ switch (c) {
96
+ case 'b': csi = 0; break;
97
+ case 'c': csi = 1; break;
98
+ case 'm': csi = 1; min_shift = atoi(optarg); break;
99
+ case 'M': multiple = 1; break;
100
+ case 'o': fn_idx = optarg; break;
101
+ case '@': n_threads = atoi(optarg); break;
102
+ default:
103
+ index_usage(samtools_stderr);
104
+ return 1;
105
+ }
106
+
107
+ n_files = argc - optind;
108
+
109
+ if (n_files == 0) {
110
+ index_usage(samtools_stdout);
111
+ return 0;
112
+ }
113
+
114
+ // Handle legacy synopsis
115
+ if (n_files == 2 && !fn_idx && nonexistent_or_index(argv[optind+1])) {
116
+ n_files = 1;
117
+ fn_idx = argv[optind+1];
118
+ }
119
+
120
+ if (n_files > 1 && !multiple) {
121
+ print_error("index", "use -M to enable indexing more than one alignment file");
122
+ return EXIT_FAILURE;
123
+ }
124
+
125
+ if (fn_idx && n_files > 1) {
126
+ // TODO In future we may allow %* placeholders or similar
127
+ print_error("index", "can't use -o with multiple input alignment files");
128
+ return EXIT_FAILURE;
129
+ }
130
+
131
+ for (i = optind; i < optind + n_files; i++) {
132
+ ret = sam_index_build3(argv[i], fn_idx, csi? min_shift : 0, n_threads);
133
+ if (ret < 0) {
134
+ if (ret == -2)
135
+ print_error_errno("index", "failed to open \"%s\"", argv[i]);
136
+ else if (ret == -3)
137
+ print_error("index", "\"%s\" is in a format that cannot be usefully indexed", argv[i]);
138
+ else if (ret == -4 && fn_idx)
139
+ print_error("index", "failed to create or write index \"%s\"", fn_idx);
140
+ else if (ret == -4)
141
+ print_error("index", "failed to create or write index");
142
+ else
143
+ print_error_errno("index", "failed to create index for \"%s\"", argv[i]);
144
+ return EXIT_FAILURE;
145
+ }
146
+ }
147
+
148
+ return EXIT_SUCCESS;
149
+ }
150
+
151
+ /*
152
+ * Cram indices do not contain mapped/unmapped record counts, so we have to
153
+ * decode each record and count. However we can speed this up as much as
154
+ * possible by using the required fields parameter.
155
+ *
156
+ * This prints the stats to samtools_stdout in the same manner than the BAM function
157
+ * does.
158
+ *
159
+ * Returns 0 on success,
160
+ * -1 on failure.
161
+ */
162
+ int slow_idxstats(samFile *fp, sam_hdr_t *header) {
163
+ int ret, last_tid = -2;
164
+ bam1_t *b = bam_init1();
165
+
166
+ if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, SAM_RNAME | SAM_FLAG))
167
+ return -1;
168
+
169
+ uint64_t (*count0)[2] = calloc(sam_hdr_nref(header)+1, sizeof(*count0));
170
+ uint64_t (*counts)[2] = count0+1;
171
+ if (!count0)
172
+ return -1;
173
+
174
+ while ((ret = sam_read1(fp, header, b)) >= 0) {
175
+ if (b->core.tid >= sam_hdr_nref(header) || b->core.tid < -1) {
176
+ free(count0);
177
+ return -1;
178
+ }
179
+
180
+ if (b->core.tid != last_tid) {
181
+ if (last_tid >= -1) {
182
+ if (counts[b->core.tid][0] + counts[b->core.tid][1]) {
183
+ print_error("idxstats", "file is not position sorted");
184
+ free(count0);
185
+ return -1;
186
+ }
187
+ }
188
+ last_tid = b->core.tid;
189
+ }
190
+
191
+ counts[b->core.tid][(b->core.flag & BAM_FUNMAP) ? 1 : 0]++;
192
+ }
193
+
194
+ if (ret == -1) {
195
+ int i;
196
+ for (i = 0; i < sam_hdr_nref(header); i++) {
197
+ fprintf(samtools_stdout, "%s\t%"PRId64"\t%"PRIu64"\t%"PRIu64"\n",
198
+ sam_hdr_tid2name(header, i),
199
+ (int64_t) sam_hdr_tid2len(header, i),
200
+ counts[i][0], counts[i][1]);
201
+ }
202
+ fprintf(samtools_stdout, "*\t0\t%"PRIu64"\t%"PRIu64"\n", counts[-1][0], counts[-1][1]);
203
+ }
204
+
205
+ free(count0);
206
+
207
+ bam_destroy1(b);
208
+
209
+ return (ret == -1) ? 0 : -1;
210
+ }
211
+
212
+ static void usage_exit(FILE *fp, int exit_status)
213
+ {
214
+ fprintf(fp, "Usage: samtools idxstats [options] <in.bam>\n");
215
+ sam_global_opt_help(fp, "-.---@-.");
216
+ samtools_exit(exit_status);
217
+ }
218
+
219
+ int bam_idxstats(int argc, char *argv[])
220
+ {
221
+ hts_idx_t* idx;
222
+ sam_hdr_t* header;
223
+ samFile* fp;
224
+ int c;
225
+
226
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
227
+ static const struct option lopts[] = {
228
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '@'),
229
+ {NULL, 0, NULL, 0}
230
+ };
231
+
232
+ while ((c = getopt_long(argc, argv, "@:", lopts, NULL)) >= 0) {
233
+ switch (c) {
234
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
235
+ /* else fall-through */
236
+ case '?':
237
+ usage_exit(samtools_stderr, EXIT_FAILURE);
238
+ }
239
+ }
240
+
241
+ if (argc != optind+1) {
242
+ if (argc == optind) usage_exit(samtools_stdout, EXIT_SUCCESS);
243
+ else usage_exit(samtools_stderr, EXIT_FAILURE);
244
+ }
245
+
246
+ fp = sam_open_format(argv[optind], "r", &ga.in);
247
+ if (fp == NULL) {
248
+ print_error_errno("idxstats", "failed to open \"%s\"", argv[optind]);
249
+ return 1;
250
+ }
251
+ header = sam_hdr_read(fp);
252
+ if (header == NULL) {
253
+ print_error("idxstats", "failed to read header for \"%s\"", argv[optind]);
254
+ return 1;
255
+ }
256
+
257
+ if (hts_get_format(fp)->format != bam) {
258
+ slow_method:
259
+ if (ga.nthreads)
260
+ hts_set_threads(fp, ga.nthreads);
261
+
262
+ if (slow_idxstats(fp, header) < 0) {
263
+ print_error("idxstats", "failed to process \"%s\"", argv[optind]);
264
+ return 1;
265
+ }
266
+ } else {
267
+ idx = sam_index_load(fp, argv[optind]);
268
+ if (idx == NULL) {
269
+ print_error("idxstats", "fail to load index for \"%s\", "
270
+ "reverting to slow method", argv[optind]);
271
+ goto slow_method;
272
+ }
273
+
274
+ int i;
275
+ for (i = 0; i < sam_hdr_nref(header); ++i) {
276
+ // Print out contig name and length
277
+ fprintf(samtools_stdout, "%s\t%"PRId64, sam_hdr_tid2name(header, i), (int64_t) sam_hdr_tid2len(header, i));
278
+ // Now fetch info about it from the meta bin
279
+ uint64_t u, v;
280
+ hts_idx_get_stat(idx, i, &u, &v);
281
+ fprintf(samtools_stdout, "\t%" PRIu64 "\t%" PRIu64 "\n", u, v);
282
+ }
283
+ // Dump information about unmapped reads
284
+ fprintf(samtools_stdout, "*\t0\t0\t%" PRIu64 "\n", hts_idx_get_n_no_coor(idx));
285
+ hts_idx_destroy(idx);
286
+ }
287
+
288
+ sam_hdr_destroy(header);
289
+ sam_close(fp);
290
+ return 0;
291
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.c ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_lpileup.c -- lplbuf routines.
2
+
3
+ Copyright (C) 2008, 2009, 2013 Genome Research Ltd.
4
+
5
+ Author: Heng Li <lh3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <stdlib.h>
28
+ #include <stdio.h>
29
+ #include <assert.h>
30
+ #include "bam_plbuf.h"
31
+ #include "bam_lpileup.h"
32
+ #include "splaysort.h"
33
+
34
+ #define TV_GAP 2
35
+
36
+ typedef struct __freenode_t {
37
+ uint32_t level:28, cnt:4;
38
+ struct __freenode_t *next;
39
+ } freenode_t, *freenode_p;
40
+
41
+ #define freenode_lt(a,b) ((a)->cnt < (b)->cnt || ((a)->cnt == (b)->cnt && (a)->level < (b)->level))
42
+ SPLAYSORT_INIT(node, freenode_p, freenode_lt)
43
+
44
+ /* Memory pool, similar to the one in bam_pileup.c */
45
+ typedef struct {
46
+ int cnt, n, max;
47
+ freenode_t **buf;
48
+ } mempool_t;
49
+
50
+ static mempool_t *mp_init(void)
51
+ {
52
+ return (mempool_t*)calloc(1, sizeof(mempool_t));
53
+ }
54
+ static void mp_destroy(mempool_t *mp)
55
+ {
56
+ int k;
57
+ for (k = 0; k < mp->n; ++k) free(mp->buf[k]);
58
+ free(mp->buf); free(mp);
59
+ }
60
+ static inline freenode_t *mp_alloc(mempool_t *mp)
61
+ {
62
+ ++mp->cnt;
63
+ if (mp->n == 0) return (freenode_t*)calloc(1, sizeof(freenode_t));
64
+ else return mp->buf[--mp->n];
65
+ }
66
+ static inline void mp_free(mempool_t *mp, freenode_t *p)
67
+ {
68
+ --mp->cnt; p->next = 0; p->cnt = TV_GAP;
69
+ if (mp->n == mp->max) {
70
+ mp->max = mp->max? mp->max<<1 : 256;
71
+ mp->buf = (freenode_t**)realloc(mp->buf, sizeof(freenode_t*) * mp->max);
72
+ }
73
+ mp->buf[mp->n++] = p;
74
+ }
75
+
76
+ /* core part */
77
+ struct __bam_lplbuf_t {
78
+ int max, n_cur, n_pre;
79
+ int max_level, *cur_level, *pre_level;
80
+ mempool_t *mp;
81
+ freenode_t **aux, *head, *tail;
82
+ int n_nodes, m_aux;
83
+ bam_pileup_f func;
84
+ void *user_data;
85
+ bam_plbuf_t *plbuf;
86
+ };
87
+
88
+ void bam_lplbuf_reset(bam_lplbuf_t *buf)
89
+ {
90
+ freenode_t *p, *q;
91
+ bam_plbuf_reset(buf->plbuf);
92
+ for (p = buf->head; p->next;) {
93
+ q = p->next;
94
+ mp_free(buf->mp, p);
95
+ p = q;
96
+ }
97
+ buf->head = buf->tail;
98
+ buf->max_level = 0;
99
+ buf->n_cur = buf->n_pre = 0;
100
+ buf->n_nodes = 0;
101
+ }
102
+
103
+ static int tview_func(uint32_t tid, hts_pos_t pos, int n, const bam_pileup1_t *pl, void *data)
104
+ {
105
+ bam_lplbuf_t *tv = (bam_lplbuf_t*)data;
106
+ freenode_t *p;
107
+ int i, l, max_level;
108
+ // allocate memory if necessary
109
+ if (tv->max < n) { // enlarge
110
+ tv->max = n;
111
+ kroundup32(tv->max);
112
+ tv->cur_level = (int*)realloc(tv->cur_level, sizeof(int) * tv->max);
113
+ tv->pre_level = (int*)realloc(tv->pre_level, sizeof(int) * tv->max);
114
+ }
115
+ tv->n_cur = n;
116
+ // update cnt
117
+ for (p = tv->head; p->next; p = p->next)
118
+ if (p->cnt > 0) --p->cnt;
119
+ // calculate cur_level[]
120
+ max_level = 0;
121
+ for (i = l = 0; i < n; ++i) {
122
+ const bam_pileup1_t *p = pl + i;
123
+ if (p->is_head) {
124
+ if (tv->head->next && tv->head->cnt == 0) { // then take a free slot
125
+ freenode_t *p = tv->head->next;
126
+ tv->cur_level[i] = tv->head->level;
127
+ mp_free(tv->mp, tv->head);
128
+ tv->head = p;
129
+ --tv->n_nodes;
130
+ } else tv->cur_level[i] = ++tv->max_level;
131
+ } else {
132
+ tv->cur_level[i] = tv->pre_level[l++];
133
+ if (p->is_tail) { // then return a free slot
134
+ tv->tail->level = tv->cur_level[i];
135
+ tv->tail->next = mp_alloc(tv->mp);
136
+ tv->tail = tv->tail->next;
137
+ ++tv->n_nodes;
138
+ }
139
+ }
140
+ if (tv->cur_level[i] > max_level) max_level = tv->cur_level[i];
141
+ ((bam_pileup1_t*)p)->level = tv->cur_level[i];
142
+ }
143
+ assert(l == tv->n_pre);
144
+ tv->func(tid, pos, n, pl, tv->user_data);
145
+ // sort the linked list
146
+ if (tv->n_nodes) {
147
+ freenode_t *q;
148
+ if (tv->n_nodes + 1 > tv->m_aux) { // enlarge
149
+ tv->m_aux = tv->n_nodes + 1;
150
+ kroundup32(tv->m_aux);
151
+ tv->aux = (freenode_t**)realloc(tv->aux, sizeof(freenode_t*) * tv->m_aux);
152
+ }
153
+ for (p = tv->head, i = l = 0; p->next;) {
154
+ if (p->level > max_level) { // then discard this entry
155
+ q = p->next;
156
+ mp_free(tv->mp, p);
157
+ p = q;
158
+ } else {
159
+ tv->aux[i++] = p;
160
+ p = p->next;
161
+ }
162
+ }
163
+ tv->aux[i] = tv->tail; // add a proper tail for the loop below
164
+ tv->n_nodes = i;
165
+ if (tv->n_nodes) {
166
+ splaysort(node, tv->n_nodes, tv->aux);
167
+ for (i = 0; i < tv->n_nodes; ++i) tv->aux[i]->next = tv->aux[i+1];
168
+ tv->head = tv->aux[0];
169
+ } else tv->head = tv->tail;
170
+ }
171
+ // clean up
172
+ tv->max_level = max_level;
173
+ memcpy(tv->pre_level, tv->cur_level, tv->n_cur * 4);
174
+ // squeeze out terminated levels
175
+ for (i = l = 0; i < n; ++i) {
176
+ const bam_pileup1_t *p = pl + i;
177
+ if (!p->is_tail)
178
+ tv->pre_level[l++] = tv->pre_level[i];
179
+ }
180
+ tv->n_pre = l;
181
+ /*
182
+ fprintf(stderr, "%d\t", pos+1);
183
+ for (i = 0; i < n; ++i) {
184
+ const bam_pileup1_t *p = pl + i;
185
+ if (p->is_head) fprintf(stderr, "^");
186
+ if (p->is_tail) fprintf(stderr, "$");
187
+ fprintf(stderr, "%d,", p->level);
188
+ }
189
+ fprintf(stderr, "\n");
190
+ */
191
+ return 0;
192
+ }
193
+
194
+ bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data)
195
+ {
196
+ bam_lplbuf_t *tv;
197
+ tv = (bam_lplbuf_t*)calloc(1, sizeof(bam_lplbuf_t));
198
+ tv->mp = mp_init();
199
+ tv->head = tv->tail = mp_alloc(tv->mp);
200
+ tv->func = func;
201
+ tv->user_data = data;
202
+ tv->plbuf = bam_plbuf_init(tview_func, tv);
203
+ return (bam_lplbuf_t*)tv;
204
+ }
205
+
206
+ void bam_lplbuf_destroy(bam_lplbuf_t *tv)
207
+ {
208
+ freenode_t *p, *q;
209
+ free(tv->cur_level); free(tv->pre_level);
210
+ bam_plbuf_destroy(tv->plbuf);
211
+ free(tv->aux);
212
+ for (p = tv->head; p->next;) {
213
+ q = p->next;
214
+ mp_free(tv->mp, p); p = q;
215
+ }
216
+ mp_free(tv->mp, p);
217
+ assert(tv->mp->cnt == 0);
218
+ mp_destroy(tv->mp);
219
+ free(tv);
220
+ }
221
+
222
+ int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *tv)
223
+ {
224
+ return bam_plbuf_push(b, tv->plbuf);
225
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_lpileup.h -- lplbuf routines (declarations copied from bam.h).
2
+
3
+ Copyright (C) 2008, 2013 Genome Research Ltd.
4
+
5
+ Author: Heng Li <lh3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #ifndef BAM_LPILEUP_H
26
+ #define BAM_LPILEUP_H
27
+
28
+
29
+ #include <htslib/sam.h>
30
+
31
+ struct __bam_lplbuf_t;
32
+ typedef struct __bam_lplbuf_t bam_lplbuf_t;
33
+
34
+ #ifndef BAM_PILEUP_F_DEFINED
35
+ #define BAM_PILEUP_F_DEFINED
36
+ typedef int (*bam_pileup_f)(uint32_t tid, hts_pos_t pos, int n, const bam_pileup1_t *pl, void *data);
37
+ #endif //BAM_PILEUP_F_DEFINED
38
+
39
+
40
+ #ifdef __cplusplus
41
+ extern "C" {
42
+ #endif
43
+ void bam_lplbuf_reset(bam_lplbuf_t *buf);
44
+
45
+ /*! @abstract bam_plbuf_init() equivalent with level calculated. */
46
+ bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data);
47
+
48
+ /*! @abstract bam_plbuf_destroy() equivalent with level calculated. */
49
+ void bam_lplbuf_destroy(bam_lplbuf_t *tv);
50
+
51
+ /*! @abstract bam_plbuf_push() equivalent with level calculated. */
52
+ int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *buf);
53
+ #ifdef __cplusplus
54
+ }
55
+ #endif
56
+
57
+ #endif // BAM_LPILEUP_H
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_markdup.c ADDED
@@ -0,0 +1,2510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_markdup.c -- Mark duplicates from a coord sorted file that has gone
2
+ through fixmates with the mate scoring option on.
3
+
4
+ Copyright (C) 2017-2023 Genome Research Ltd.
5
+
6
+ Author: Andrew Whitwham <aw7@sanger.ac.uk>
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
+ Estimate library size derived from Picard DuplicationMetrics.java
27
+ Copyright (c) 2009,2018 The Broad Institute. MIT license.
28
+ */
29
+
30
+ #include <config.h>
31
+
32
+ #include <stdlib.h>
33
+ #include <string.h>
34
+ #include <stdio.h>
35
+ #include <unistd.h>
36
+ #include <ctype.h>
37
+ #include <time.h>
38
+ #include <sys/stat.h>
39
+ #include <math.h>
40
+ #include <regex.h>
41
+ #include "htslib/thread_pool.h"
42
+ #include "htslib/sam.h"
43
+ #include "sam_opts.h"
44
+ #include "samtools.h"
45
+ #include "htslib/khash.h"
46
+ #include "htslib/klist.h"
47
+ #include "htslib/kstring.h"
48
+ #include "tmp_file.h"
49
+ #include "bam.h"
50
+
51
+
52
+ typedef struct {
53
+ samFile *in;
54
+ samFile *out;
55
+ char *prefix;
56
+ int remove_dups;
57
+ int32_t max_length;
58
+ int do_stats;
59
+ int supp;
60
+ int tag;
61
+ int opt_dist;
62
+ int no_pg;
63
+ int clear;
64
+ int mode;
65
+ int write_index;
66
+ int include_fails;
67
+ int check_chain;
68
+ char *stats_file;
69
+ char *arg_list;
70
+ char *out_fn;
71
+ regex_t *rgx;
72
+ int rgx_x;
73
+ int rgx_y;
74
+ int rgx_t;
75
+ char *barcode;
76
+ regex_t *bc_rgx;
77
+ int read_groups;
78
+ int json;
79
+ int dc;
80
+ } md_param_t;
81
+
82
+ typedef struct {
83
+ hts_pos_t this_coord;
84
+ hts_pos_t other_coord;
85
+ int32_t this_ref;
86
+ int32_t other_ref;
87
+ int32_t barcode;
88
+ int32_t read_group;
89
+ int8_t single;
90
+ int8_t leftmost;
91
+ int8_t orientation;
92
+ } key_data_t;
93
+
94
+ typedef struct read_queue_s {
95
+ key_data_t pair_key;
96
+ key_data_t single_key;
97
+ bam1_t *b;
98
+ struct read_queue_s *duplicate;
99
+ struct read_queue_s *original;
100
+ int dc;
101
+ hts_pos_t pos;
102
+ int dup_checked;
103
+ int read_group;
104
+ } read_queue_t;
105
+
106
+ typedef struct {
107
+ read_queue_t *p;
108
+ } in_hash_t;
109
+
110
+ typedef struct {
111
+ char *name;
112
+ char type;
113
+ int read_group;
114
+ } dup_map_t;
115
+
116
+ typedef struct {
117
+ bam1_t *b;
118
+ int64_t score;
119
+ int64_t mate_score;
120
+ long x;
121
+ long y;
122
+ int opt;
123
+ int beg;
124
+ int end;
125
+ } check_t;
126
+
127
+ typedef struct {
128
+ check_t *c;
129
+ size_t size;
130
+ size_t length;
131
+ } check_list_t;
132
+
133
+ typedef struct {
134
+ long reading;
135
+ long writing;
136
+ long excluded;
137
+ long duplicate;
138
+ long single;
139
+ long pair;
140
+ long single_dup;
141
+ long examined;
142
+ long optical;
143
+ long single_optical;
144
+ long np_duplicate;
145
+ long np_opt_duplicate;
146
+ } stats_block_t;
147
+
148
+ static khint32_t do_hash(unsigned char *key, khint32_t len);
149
+
150
+ static khint_t hash_key(key_data_t key) {
151
+ int i = 0;
152
+ khint_t hash;
153
+
154
+ if (key.single) {
155
+ unsigned char sig[21];
156
+
157
+ memcpy(sig + i, &key.this_ref, 4); i += 4;
158
+ memcpy(sig + i, &key.this_coord, 8); i += 8;
159
+ memcpy(sig + i, &key.orientation, 1); i += 1;
160
+ memcpy(sig + i, &key.barcode, 4); i += 4;
161
+ memcpy(sig + i, &key.read_group, 4); i += 4;
162
+
163
+ hash = do_hash(sig, i);
164
+ } else {
165
+ unsigned char sig[34];
166
+
167
+ memcpy(sig + i, &key.this_ref, 4); i += 4;
168
+ memcpy(sig + i, &key.this_coord, 8); i += 8;
169
+ memcpy(sig + i, &key.other_ref, 4); i += 4;
170
+ memcpy(sig + i, &key.other_coord, 8); i += 8;
171
+ memcpy(sig + i, &key.leftmost, 1); i += 1;
172
+ memcpy(sig + i, &key.orientation, 1); i += 1;
173
+ memcpy(sig + i, &key.barcode, 4); i += 4;
174
+ memcpy(sig + i, &key.read_group, 4); i += 4;
175
+
176
+ hash = do_hash(sig, i);
177
+ }
178
+
179
+ return hash;
180
+ }
181
+
182
+
183
+ static int key_equal(key_data_t a, key_data_t b) {
184
+ int match = 1;
185
+
186
+ if (a.this_coord != b.this_coord)
187
+ match = 0;
188
+ else if (a.orientation != b.orientation)
189
+ match = 0;
190
+ else if (a.this_ref != b.this_ref)
191
+ match = 0;
192
+ else if (a.single != b.single)
193
+ match = 0;
194
+ else if (a.barcode != b.barcode)
195
+ match = 0;
196
+ else if (a.read_group != b.read_group)
197
+ match = 0;
198
+
199
+ if (!a.single) {
200
+ if (a.other_coord != b.other_coord)
201
+ match = 0;
202
+ else if (a.leftmost != b.leftmost)
203
+ match = 0;
204
+ else if (a.other_ref != b.other_ref)
205
+ match = 0;
206
+ }
207
+
208
+ return match;
209
+ }
210
+
211
+
212
+ #define __free_queue_element(p)
213
+
214
+ // Orientations (prime numbers to feed to hashing algorithm)
215
+ #define O_FF 2
216
+ #define O_RR 3
217
+ #define O_FR 5
218
+ #define O_RF 7
219
+
220
+ // Left or rightmost
221
+ #define R_LE 11
222
+ #define R_RI 13
223
+
224
+ #define BMD_WARNING_MAX 10
225
+
226
+ #define MD_MIN_QUALITY 15
227
+
228
+ // Duplicate finding mode
229
+ #define MD_MODE_TEMPLATE 0
230
+ #define MD_MODE_SEQUENCE 1
231
+
232
+ KHASH_INIT(reads, key_data_t, in_hash_t, 1, hash_key, key_equal) // read map hash
233
+ KLIST_INIT(read_queue, read_queue_t, __free_queue_element) // the reads buffer
234
+ KHASH_MAP_INIT_STR(duplicates, dup_map_t) // map of duplicates for supplementary dup id
235
+ KHASH_MAP_INIT_STR(read_groups, int) // read group lookup
236
+
237
+ /* The Bob Jenkins one_at_a_time hash to reduce the key to a 32 bit value. */
238
+
239
+ static khint32_t do_hash(unsigned char *key, khint32_t len) {
240
+ khint32_t hash, i;
241
+
242
+ for (hash = 0, i = 0; i < len; ++i) {
243
+ hash += key[i];
244
+ hash += (hash << 10);
245
+ hash ^= (hash >> 6);
246
+ }
247
+
248
+ hash += (hash << 3);
249
+ hash ^= (hash >> 11);
250
+ hash += (hash << 15);
251
+
252
+ return hash;
253
+ }
254
+
255
+
256
+ /* Get mate score from tag. */
257
+
258
+ static int64_t get_mate_score(bam1_t *b) {
259
+ uint8_t *data;
260
+ int64_t score;
261
+
262
+ if ((data = bam_aux_get(b, "ms"))) {
263
+ score = bam_aux2i(data);
264
+ } else {
265
+ print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
266
+ return -1;
267
+ }
268
+
269
+ return score;
270
+ }
271
+
272
+
273
+ /* Calc current score from quality. */
274
+
275
+ static int64_t calc_score(bam1_t *b)
276
+ {
277
+ int64_t score = 0;
278
+ uint8_t *qual = bam_get_qual(b);
279
+ int i;
280
+
281
+ for (i = 0; i < b->core.l_qseq; i++) {
282
+ if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
283
+ }
284
+
285
+ return score;
286
+ }
287
+
288
+
289
+ /* Create a signature hash of the current read and its pair.
290
+ Uses the unclipped start (or end depending on orientation),
291
+ the reference id, orientation and whether the current
292
+ read is leftmost of the pair. */
293
+
294
+
295
+ static int make_pair_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) {
296
+ hts_pos_t this_coord, this_end, other_coord, other_end, leftmost;
297
+ int32_t this_ref, other_ref, barcode = 0;
298
+ int8_t orientation, left_read;
299
+ uint8_t *data;
300
+ char *cig, *bar;
301
+ long incoming_warnings = *warnings;
302
+
303
+ this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash
304
+ other_ref = bam->core.mtid + 1;
305
+
306
+ this_coord = unclipped_start(bam);
307
+ this_end = unclipped_end(bam);
308
+
309
+ if ((data = bam_aux_get(bam, "MC"))) {
310
+ if (!(cig = bam_aux2Z(data))) {
311
+ print_error("markdup", "error, MC tag wrong type. Please use the MC tag provided by samtools fixmate.\n");
312
+ return 1;
313
+ }
314
+
315
+ other_end = unclipped_other_end(bam->core.mpos, cig);
316
+ other_coord = unclipped_other_start(bam->core.mpos, cig);
317
+ } else {
318
+ print_error("markdup", "error, no MC tag. Please run samtools fixmate on file first.\n");
319
+ return 1;
320
+ }
321
+
322
+ // work out orientations
323
+ if (param->mode == MD_MODE_TEMPLATE) {
324
+
325
+ if (this_ref != other_ref) {
326
+ leftmost = this_ref < other_ref;
327
+ } else {
328
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
329
+ if (!bam_is_rev(bam)) {
330
+ leftmost = this_coord <= other_coord;
331
+ } else {
332
+ leftmost = this_end <= other_end;
333
+ }
334
+ } else {
335
+ if (bam_is_rev(bam)) {
336
+ leftmost = this_end <= other_coord;
337
+ } else {
338
+ leftmost = this_coord <= other_end;
339
+ }
340
+ }
341
+ }
342
+
343
+ // pair orientation
344
+ if (leftmost) {
345
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
346
+ other_coord = other_end;
347
+
348
+ if (!bam_is_rev(bam)) {
349
+ if (bam->core.flag & BAM_FREAD1) {
350
+ orientation = O_FF;
351
+ } else {
352
+ orientation = O_RR;
353
+ }
354
+ } else {
355
+ if (bam->core.flag & BAM_FREAD1) {
356
+ orientation = O_RR;
357
+ } else {
358
+ orientation = O_FF;
359
+ }
360
+ }
361
+ } else {
362
+ if (!bam_is_rev(bam)) {
363
+ orientation = O_FR;
364
+ other_coord = other_end;
365
+ } else {
366
+ orientation = O_RF;
367
+ this_coord = this_end;
368
+ }
369
+ }
370
+ } else {
371
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
372
+ this_coord = this_end;
373
+
374
+ if (!bam_is_rev(bam)) {
375
+ if (bam->core.flag & BAM_FREAD1) {
376
+ orientation = O_RR;
377
+ } else {
378
+ orientation = O_FF;
379
+ }
380
+ } else {
381
+ if (bam->core.flag & BAM_FREAD1) {
382
+ orientation = O_FF;
383
+ } else {
384
+ orientation = O_RR;
385
+ }
386
+ }
387
+ } else {
388
+ if (!bam_is_rev(bam)) {
389
+ orientation = O_RF;
390
+ other_coord = other_end;
391
+ } else {
392
+ orientation = O_FR;
393
+ this_coord = this_end;
394
+ }
395
+ }
396
+ }
397
+ } else { // MD_MODE_SEQUENCE
398
+
399
+ if (this_ref != other_ref) {
400
+ leftmost = this_ref - other_ref;
401
+ } else {
402
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
403
+ if (!bam_is_rev(bam)) {
404
+ leftmost = this_coord - other_coord;
405
+ } else {
406
+ leftmost = this_end - other_end;
407
+ }
408
+ } else {
409
+ if (bam_is_rev(bam)) {
410
+ leftmost = this_end - other_coord;
411
+ } else {
412
+ leftmost = this_coord - other_end;
413
+ }
414
+ }
415
+ }
416
+
417
+ if (leftmost < 0) {
418
+ leftmost = 1;
419
+ } else if (leftmost > 0) {
420
+ leftmost = 0;
421
+ } else {
422
+ // tie breaks
423
+
424
+ if (bam->core.pos == bam->core.mpos) {
425
+ if (bam->core.flag & BAM_FREAD1) {
426
+ leftmost = 1;
427
+ } else {
428
+ leftmost = 0;
429
+ }
430
+ } else if (bam->core.pos < bam->core.mpos) {
431
+ leftmost = 1;
432
+ } else {
433
+ leftmost = 0;
434
+ }
435
+ }
436
+
437
+ // pair orientation
438
+ if (leftmost) {
439
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
440
+
441
+ if (!bam_is_rev(bam)) {
442
+ orientation = O_FF;
443
+ } else {
444
+ orientation = O_RR;
445
+ }
446
+ } else {
447
+ if (!bam_is_rev(bam)) {
448
+ orientation = O_FR;
449
+ } else {
450
+ orientation = O_RF;
451
+ }
452
+ }
453
+ } else {
454
+ if (bam_is_rev(bam) == bam_is_mrev(bam)) {
455
+
456
+ if (!bam_is_rev(bam)) {
457
+ orientation = O_RR;
458
+ } else {
459
+ orientation = O_FF;
460
+ }
461
+ } else {
462
+ if (!bam_is_rev(bam)) {
463
+ orientation = O_RF;
464
+ } else {
465
+ orientation = O_FR;
466
+ }
467
+ }
468
+ }
469
+
470
+ if (!bam_is_rev(bam)) {
471
+ this_coord = unclipped_start(bam);
472
+ } else {
473
+ this_coord = unclipped_end(bam);
474
+ }
475
+
476
+ if (!bam_is_mrev(bam)) {
477
+ other_coord = unclipped_other_start(bam->core.mpos, cig);
478
+ } else {
479
+ other_coord = unclipped_other_end(bam->core.mpos, cig);
480
+ }
481
+ }
482
+
483
+ if (!leftmost)
484
+ left_read = R_RI;
485
+ else
486
+ left_read = R_LE;
487
+
488
+ if (param->barcode) {
489
+ if ((data = bam_aux_get(bam, param->barcode))) {
490
+ if (!(bar = bam_aux2Z(data))) {
491
+ (*warnings)++;
492
+
493
+ if (*warnings <= BMD_WARNING_MAX) {
494
+ print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode);
495
+ }
496
+ } else {
497
+ barcode = do_hash((unsigned char *)bar, strlen(bar));
498
+ }
499
+ }
500
+ } else if (param->bc_rgx) {
501
+ int result;
502
+ regmatch_t matches[3];
503
+ size_t max_matches = 2;
504
+ char *qname = bam_get_qname(bam);
505
+
506
+ if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) {
507
+ int bc_start, bc_end;
508
+
509
+ bc_start = matches[1].rm_so;
510
+ bc_end = matches[1].rm_eo;
511
+
512
+ if (bc_start != -1) {
513
+ barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start);
514
+ } else {
515
+ (*warnings)++;
516
+
517
+ if (*warnings <= BMD_WARNING_MAX) {
518
+ print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname);
519
+ }
520
+ }
521
+ } else {
522
+ (*warnings)++;
523
+
524
+ if (*warnings <= BMD_WARNING_MAX) {
525
+ char warn_msg[256];
526
+
527
+ regerror(result, param->bc_rgx, warn_msg, 256);
528
+ print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname);
529
+ }
530
+ }
531
+ }
532
+
533
+ if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) {
534
+ print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n",
535
+ *warnings);
536
+ }
537
+
538
+ key->single = 0;
539
+ key->this_ref = this_ref;
540
+ key->this_coord = this_coord;
541
+ key->other_ref = other_ref;
542
+ key->other_coord = other_coord;
543
+ key->leftmost = left_read;
544
+ key->orientation = orientation;
545
+ key->barcode = barcode;
546
+ key->read_group = rg_num;
547
+
548
+ return 0;
549
+ }
550
+
551
+
552
+ /* Create a signature hash of single read (or read with an unmatched pair).
553
+ Uses unclipped start (or end depending on orientation), reference id,
554
+ and orientation. */
555
+
556
+ static void make_single_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) {
557
+ hts_pos_t this_coord;
558
+ int32_t this_ref, barcode = 0;
559
+ int8_t orientation;
560
+ uint8_t *data;
561
+ char *bar;
562
+ long incoming_warnings = *warnings;
563
+
564
+ this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash
565
+
566
+ if (bam_is_rev(bam)) {
567
+ this_coord = unclipped_end(bam);
568
+ orientation = O_RR;
569
+ } else {
570
+ this_coord = unclipped_start(bam);
571
+ orientation = O_FF;
572
+ }
573
+
574
+ if (param->barcode) {
575
+ if ((data = bam_aux_get(bam, param->barcode))) {
576
+ if (!(bar = bam_aux2Z(data))) {
577
+ (*warnings)++;
578
+
579
+ if (*warnings <= BMD_WARNING_MAX) {
580
+ print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode);
581
+ }
582
+ } else {
583
+ barcode = do_hash((unsigned char *)bar, strlen(bar));
584
+ }
585
+ }
586
+ } else if (param->bc_rgx) {
587
+ int result;
588
+ regmatch_t matches[3];
589
+ size_t max_matches = 2;
590
+ char *qname = bam_get_qname(bam);
591
+
592
+ if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) {
593
+ int bc_start, bc_end;
594
+
595
+ bc_start = matches[1].rm_so;
596
+ bc_end = matches[1].rm_eo;
597
+
598
+ if (bc_start != -1) {
599
+ barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start);
600
+ } else {
601
+ (*warnings)++;
602
+
603
+ if (*warnings <= BMD_WARNING_MAX) {
604
+ print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname);
605
+ }
606
+ }
607
+ } else {
608
+ (*warnings)++;
609
+
610
+ if (*warnings <= BMD_WARNING_MAX) {
611
+ char warn_msg[256];
612
+
613
+ regerror(result, param->bc_rgx, warn_msg, 256);
614
+ print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname);
615
+ }
616
+ }
617
+ }
618
+
619
+ if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) {
620
+ print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n",
621
+ *warnings);
622
+ }
623
+
624
+
625
+ key->single = 1;
626
+ key->this_ref = this_ref;
627
+ key->this_coord = this_coord;
628
+ key->orientation = orientation;
629
+ key->barcode = barcode;
630
+ key->read_group = rg_num;
631
+ }
632
+
633
+
634
+ /* Add the duplicate name to a hash if it does not exist. */
635
+
636
+ static int add_duplicate(khash_t(duplicates) *d_hash, bam1_t *dupe, char *orig_name, char type, int group) {
637
+ khiter_t d;
638
+ int ret;
639
+
640
+ d = kh_get(duplicates, d_hash, bam_get_qname(dupe));
641
+
642
+ if (d == kh_end(d_hash)) {
643
+ char *name = strdup(bam_get_qname(dupe));
644
+ if (name) {
645
+ d = kh_put(duplicates, d_hash, name, &ret);
646
+ } else {
647
+ ret = -1;
648
+ }
649
+
650
+ if (ret >= 0) {
651
+ if (orig_name) {
652
+ if (ret == 0) {
653
+ // replace old name
654
+ free(kh_value(d_hash, d).name);
655
+ free(name);
656
+ }
657
+
658
+ kh_value(d_hash, d).name = strdup(orig_name);
659
+
660
+ if (kh_value(d_hash, d).name == NULL) {
661
+ print_error("markdup", "error, unable to allocate memory for duplicate original name.\n");
662
+ return 1;
663
+ }
664
+ } else {
665
+ kh_value(d_hash, d).name = NULL;
666
+ }
667
+
668
+ kh_value(d_hash, d).type = type;
669
+ kh_value(d_hash, d).read_group = group;
670
+ } else {
671
+ print_error("markdup", "error, unable to store supplementary duplicates.\n");
672
+ free(name);
673
+ return 1;
674
+ }
675
+ }
676
+
677
+ return 0;
678
+ }
679
+
680
+
681
+ /* Get coordinates from the standard Illumina style read names.
682
+ Returned values are of the x and y coordinates and a section of
683
+ the read name to test (t) for string equality e.g. lane and tile part. */
684
+
685
+ static int get_coordinates_colons(md_param_t *param, const char *qname, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
686
+ int sep = 0;
687
+ int pos = 0;
688
+ int xpos = 0, ypos = 0;
689
+ char *end;
690
+
691
+ while (qname[pos]) {
692
+ if (qname[pos] == ':') {
693
+ sep++;
694
+
695
+ if (sep == 2) {
696
+ xpos = pos + 1;
697
+ } else if (sep == 3) {
698
+ ypos = pos + 1;
699
+ } else if (sep == 4) { // HiSeq style names
700
+ xpos = ypos;
701
+ ypos = pos + 1;
702
+ } else if (sep == 5) { // Newer Illumina format
703
+ xpos = pos + 1;
704
+ } else if (sep == 6) {
705
+ ypos = pos + 1;
706
+ }
707
+ }
708
+
709
+ pos++;
710
+ }
711
+
712
+ /* The most current Illumina read format at time of writing is:
713
+ @machine:run:flowcell:lane:tile:x:y:UMI or
714
+ @machine:run:flowcell:lane:tile:x:y
715
+
716
+ Counting the separating colons gives us a quick format check.
717
+ Older name formats have fewer elements.
718
+ */
719
+
720
+ if (!(sep == 3 || sep == 4 || sep == 6 || sep == 7)) {
721
+ (*warnings)++;
722
+
723
+ if (*warnings <= BMD_WARNING_MAX) {
724
+ print_error("markdup", "warning, cannot decipher read name %s for optical duplicate marking.\n", qname);
725
+ }
726
+
727
+ return 1;
728
+ } else {
729
+ *x_coord = strtol(qname + xpos, &end, 10);
730
+
731
+ if ((qname + xpos) == end) {
732
+ (*warnings)++;
733
+
734
+ if (*warnings <= BMD_WARNING_MAX) {
735
+ print_error("markdup", "warning, cannot decipher x coordinate in %s .\n", qname);
736
+ }
737
+
738
+ return 1;
739
+ }
740
+
741
+ *y_coord = strtol(qname + ypos, &end, 10);
742
+
743
+ if ((qname + ypos) == end) {
744
+ (*warnings)++;
745
+
746
+ if (*warnings <= BMD_WARNING_MAX) {
747
+ print_error("markdup", "warning, cannot decipher y coordinate in %s .\n", qname);
748
+ }
749
+
750
+ return 1;
751
+ }
752
+
753
+ *t_beg = 0;
754
+ *t_end = xpos;
755
+ }
756
+
757
+ return 0;
758
+ }
759
+
760
+ /* Get the coordinates from the read name.
761
+ Returned values are of the x and y coordinates and an optional section of
762
+ the read name to test (t) for string equality e.g. lane and tile part. */
763
+
764
+ static inline int get_coordinates_regex(md_param_t *param, const char *qname, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
765
+ regmatch_t matches[5];
766
+ size_t max_matches = 5;
767
+ int xpos, ypos, xend, yend, xlen, ylen;
768
+ char coord[255];
769
+ char *end;
770
+
771
+ if (!param->rgx_t)
772
+ max_matches = 4;
773
+
774
+ if (regexec(param->rgx, qname, max_matches, matches, 0))
775
+ return -1;
776
+
777
+ xpos = matches[param->rgx_x].rm_so;
778
+ ypos = matches[param->rgx_y].rm_so;
779
+
780
+ if (param->rgx_t) {
781
+ *t_beg = matches[param->rgx_t].rm_so;
782
+ *t_end = matches[param->rgx_t].rm_eo;
783
+ } else {
784
+ *t_beg = *t_end = 0;
785
+ }
786
+
787
+ if (xpos == -1 || ypos == -1 || *t_beg == -1)
788
+ return -1;
789
+
790
+ xend = matches[param->rgx_x].rm_eo;
791
+ yend = matches[param->rgx_y].rm_eo;
792
+
793
+ if ((xlen = xend - xpos) > 254) {
794
+ (*warnings)++;
795
+
796
+ if (*warnings <= BMD_WARNING_MAX) {
797
+ print_error("markdup", "warning, x coordinate string longer than allowed qname length in %s (%d long).\n", qname, xlen);
798
+ }
799
+
800
+ return 1;
801
+ }
802
+
803
+ strncpy(coord, qname + xpos, xlen);
804
+ coord[xlen] = '\0';
805
+ *x_coord = strtol(coord, &end, 10);
806
+
807
+ if (coord == end) {
808
+ (*warnings)++;
809
+
810
+ if (*warnings <= BMD_WARNING_MAX) {
811
+ print_error("markdup", "warning, cannot decipher x coordinate in %s (%s).\n", qname, coord);
812
+ }
813
+
814
+ return 1;
815
+ }
816
+
817
+ if ((ylen = yend - ypos) > 254) {
818
+ (*warnings)++;
819
+
820
+ if (*warnings <= BMD_WARNING_MAX) {
821
+ print_error("markdup", "warning, y coordinate string longer than allowed qname length in %s (%d long).\n", qname, ylen);
822
+ }
823
+
824
+ return 1;
825
+ }
826
+
827
+ strncpy(coord, qname + ypos, ylen);
828
+ coord[ylen] = '\0';
829
+ *y_coord = strtol(coord, &end, 10);
830
+
831
+ if (coord == end) {
832
+ (*warnings)++;
833
+
834
+ if (*warnings <= BMD_WARNING_MAX) {
835
+ print_error("markdup", "warning, cannot decipher y coordinate in %s (%s).\n", qname, coord);
836
+ }
837
+
838
+ return 1;
839
+ }
840
+
841
+ return 0;
842
+ }
843
+
844
+
845
+ static int get_coordinates(md_param_t *param, const char *name, int *t_beg, int *t_end, long *x_coord, long *y_coord, long *warnings) {
846
+ int ret = 1;
847
+
848
+ if (param->rgx == NULL) {
849
+ ret = get_coordinates_colons(param, name, t_beg, t_end, x_coord, y_coord, warnings);
850
+ } else {
851
+ ret = get_coordinates_regex(param, name, t_beg, t_end, x_coord, y_coord, warnings);
852
+ }
853
+
854
+ return ret;
855
+ }
856
+
857
+
858
+ /* Using the coordinates from the read name, see whether the duplicated read is
859
+ close enough (set by max_dist) to the original to be counted as optical.*/
860
+
861
+ static int is_optical_duplicate(md_param_t *param, bam1_t *ori, bam1_t *dup, long max_dist, long *warnings) {
862
+ int ret = 0;
863
+ char *original, *duplicate;
864
+ long ox, oy, dx, dy;
865
+ int o_beg = 0, o_end = 0, d_beg = 0, d_end = 0;
866
+
867
+ original = bam_get_qname(ori);
868
+ duplicate = bam_get_qname(dup);
869
+
870
+ if (get_coordinates(param, original, &o_beg, &o_end, &ox, &oy, warnings)) {
871
+ return ret;
872
+ }
873
+
874
+ if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) {
875
+ return ret;
876
+ }
877
+
878
+ if (strncmp(original + o_beg, duplicate + d_beg, o_end - o_beg) == 0) {
879
+ long xdiff, ydiff;
880
+
881
+ if (ox > dx) {
882
+ xdiff = ox - dx;
883
+ } else {
884
+ xdiff = dx - ox;
885
+ }
886
+
887
+ if (xdiff <= max_dist) {
888
+ // still might be optical
889
+
890
+ if (oy > dy) {
891
+ ydiff = oy - dy;
892
+ } else {
893
+ ydiff = dy - oy;
894
+ }
895
+
896
+ if (ydiff <= max_dist) ret = 1;
897
+ }
898
+ }
899
+
900
+ return ret;
901
+ }
902
+
903
+
904
+ /* Using the coordinates from the Illumina read name, see whether the duplicated read is
905
+ close enough (set by max_dist) to the original to be counted as optical.
906
+
907
+ This function needs the values from the first read to be already calculated. */
908
+
909
+ static int optical_duplicate_partial(md_param_t *param, const char *name, const int o_beg, const int o_end, const long ox, const long oy, bam1_t *dup, check_t *c, long max_dist, long *warnings) {
910
+ int ret = 0;
911
+ char *duplicate;
912
+ int d_beg = 0, d_end = 0;
913
+ long dx, dy;
914
+
915
+ duplicate = bam_get_qname(dup);
916
+
917
+ if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) {
918
+ return ret;
919
+ }
920
+
921
+ if (strncmp(name + o_beg, duplicate + d_beg, o_end - o_beg) == 0) {
922
+ // the initial parts match, look at the numbers
923
+ long xdiff, ydiff;
924
+
925
+ if (ox > dx) {
926
+ xdiff = ox - dx;
927
+ } else {
928
+ xdiff = dx - ox;
929
+ }
930
+
931
+ if (xdiff <= max_dist) {
932
+ // still might be optical
933
+
934
+ if (oy > dy) {
935
+ ydiff = oy - dy;
936
+ } else {
937
+ ydiff = dy - oy;
938
+ }
939
+
940
+ if (ydiff <= max_dist) ret = 1;
941
+ }
942
+ }
943
+
944
+ c->x = dx;
945
+ c->y = dy;
946
+ c->beg = d_beg;
947
+ c->end = d_end;
948
+
949
+ return ret;
950
+ }
951
+
952
+
953
+ /* Mark the read as a duplicate and update the duplicate hash (if needed) */
954
+ static int mark_duplicates(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *ori, bam1_t *dup,
955
+ int read_group, long *optical, long *warn) {
956
+ char dup_type = 0;
957
+ long incoming_warnings = *warn;
958
+
959
+ dup->core.flag |= BAM_FDUP;
960
+
961
+ if (param->tag) {
962
+ if (bam_aux_update_str(dup, "do", strlen(bam_get_qname(ori)) + 1, bam_get_qname(ori))) {
963
+ print_error("markdup", "error, unable to append 'do' tag.\n");
964
+ return -1;
965
+ }
966
+ }
967
+
968
+ if (param->opt_dist) { // mark optical duplicates
969
+ if (is_optical_duplicate(param, ori, dup, param->opt_dist, warn)) {
970
+ bam_aux_update_str(dup, "dt", 3, "SQ");
971
+ dup_type = 'O';
972
+ (*optical)++;
973
+ } else {
974
+ // not an optical duplicate
975
+ bam_aux_update_str(dup, "dt", 3, "LB");
976
+ }
977
+ }
978
+
979
+ if ((*warn == BMD_WARNING_MAX) && (incoming_warnings != *warn)) {
980
+ print_error("markdup", "warning, %ld decipher read name warnings. New warnings will not be reported.\n",
981
+ *warn);
982
+ }
983
+
984
+ if (param->supp) {
985
+ if (bam_aux_get(dup, "SA") || (dup->core.flag & BAM_FMUNMAP) || bam_aux_get(dup, "XA")) {
986
+ char *original = NULL;
987
+
988
+ if (param->tag) {
989
+ original = bam_get_qname(ori);
990
+ }
991
+
992
+ if (add_duplicate(dup_hash, dup, original, dup_type, read_group))
993
+ return -1;
994
+ }
995
+ }
996
+
997
+ return 0;
998
+ }
999
+
1000
+
1001
+ /* If the duplicate type has changed to optical then retag and duplicate hash. */
1002
+ static inline int optical_retag(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *b, int paired, stats_block_t *stats) {
1003
+ int ret = 0;
1004
+
1005
+ if (bam_aux_update_str(b, "dt", 3, "SQ")) {
1006
+ print_error("markdup", "error, unable to update 'dt' tag.\n");
1007
+ ret = -1;
1008
+ }
1009
+
1010
+ if (paired) {
1011
+ stats->optical++;
1012
+ } else {
1013
+ stats->single_optical++;
1014
+ }
1015
+
1016
+ if (param->supp) {
1017
+ // Change the duplicate type
1018
+
1019
+ if (bam_aux_get(b, "SA") || (b->core.flag & BAM_FMUNMAP)
1020
+ || bam_aux_get(b, "XA")) {
1021
+ khiter_t d;
1022
+
1023
+ d = kh_get(duplicates, dup_hash, bam_get_qname(b));
1024
+
1025
+ if (d == kh_end(dup_hash)) {
1026
+ // error, name should already be in dup hash
1027
+ print_error("markdup", "error, duplicate name %s not found in hash.\n",
1028
+ bam_get_qname(b));
1029
+ ret = -1;
1030
+ } else {
1031
+ kh_value(dup_hash, d).type = 'O';
1032
+ }
1033
+ }
1034
+ }
1035
+
1036
+ return ret;
1037
+ }
1038
+
1039
+
1040
+ /* Check all duplicates of the highest quality read (the "original") for consistancy. Also
1041
+ pre-calculate any values for use in check_duplicate_chain later.
1042
+ Returns 0 on success, >0 on coordinate reading error (program can continue) or
1043
+ <0 on an error (program should not continue. */
1044
+ static int check_chain_against_original(md_param_t *param, khash_t(duplicates) *dup_hash, read_queue_t *ori,
1045
+ check_list_t *list, long *warn, stats_block_t *stats) {
1046
+
1047
+ int ret = 0, coord_fail = 0;
1048
+ char *ori_name = bam_get_qname(ori->b);
1049
+ read_queue_t *current = ori->duplicate;
1050
+ int t_beg = 0, t_end = 0;
1051
+ long x, y;
1052
+
1053
+ if (param->opt_dist) {
1054
+ coord_fail = get_coordinates(param, ori_name, &t_beg, &t_end, &x, &y, warn);
1055
+ }
1056
+
1057
+ list->length = 0;
1058
+
1059
+ while (current) {
1060
+ check_t *c;
1061
+
1062
+ if (list->length >= list->size) {
1063
+ check_t *tmp;
1064
+
1065
+ list->size *= 2;
1066
+
1067
+ if (!(tmp = realloc(list->c, list->size * sizeof(check_t)))) {
1068
+ print_error("markdup", "error, Unable to expand optical check list.\n");
1069
+ return -1;
1070
+ }
1071
+
1072
+ list->c = tmp;
1073
+ }
1074
+
1075
+ c = &list->c[list->length];
1076
+
1077
+ c->b = current->b;
1078
+ c->x = -1;
1079
+ c->y = -1;
1080
+ c->opt = 0;
1081
+ c->score = 0;
1082
+ c->mate_score = 0;
1083
+ current->dup_checked = 1;
1084
+
1085
+ if (param->tag) {
1086
+ uint8_t *data;
1087
+
1088
+ // at this stage all duplicates should have a do tag
1089
+ if ((data = bam_aux_get(current->b, "do")) != NULL) {
1090
+ // see if we need to change the tag
1091
+ char *old_name = bam_aux2Z(data);
1092
+
1093
+ if (old_name) {
1094
+ if (strcmp(old_name, ori_name) != 0) {
1095
+ if (bam_aux_update_str(current->b, "do", strlen(ori_name) + 1, (const char *)ori_name)) {
1096
+ print_error("markdup", "error, unable to update 'do' tag.\n");
1097
+ ret = -1;
1098
+ break;
1099
+ }
1100
+ }
1101
+ } else {
1102
+ print_error("markdup", "error, 'do' tag has wrong type for read %s.\n", bam_get_qname(current->b));
1103
+ ret = -1;
1104
+ break;
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ if (param->opt_dist && !coord_fail) {
1110
+ uint8_t *data;
1111
+ char *dup_type;
1112
+ int is_opt = 0;
1113
+ int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP);
1114
+
1115
+ if ((data = bam_aux_get(current->b, "dt"))) {
1116
+ if ((dup_type = bam_aux2Z(data))) {
1117
+ if (strcmp(dup_type, "SQ") == 0) {
1118
+ c->opt = 1;
1119
+ }
1120
+ }
1121
+ }
1122
+
1123
+ // need to run this to get the duplicates x and y scores
1124
+ is_opt = optical_duplicate_partial(param, ori_name, t_beg, t_end, x, y, current->b, c, param->opt_dist, warn);
1125
+
1126
+ if (!c->opt && is_opt) {
1127
+ if (optical_retag(param, dup_hash, current->b, current_paired, stats)) {
1128
+ ret = -1;
1129
+ break;
1130
+ }
1131
+
1132
+ c->opt = 1;
1133
+ }
1134
+
1135
+ c->score = calc_score(current->b);
1136
+
1137
+ if (current_paired) {
1138
+ if ((c->mate_score = get_mate_score(current->b)) == -1) {
1139
+ print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1140
+ ret = -1;
1141
+ break;
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+ current = current->duplicate;
1147
+ list->length++;
1148
+ }
1149
+
1150
+ if (!ret && coord_fail)
1151
+ ret = coord_fail;
1152
+
1153
+ ori->dup_checked = 1;
1154
+
1155
+ return ret;
1156
+ }
1157
+
1158
+
1159
+ static int xcoord_sort(const void *a, const void *b) {
1160
+ check_t *ac = (check_t *) a;
1161
+ check_t *bc = (check_t *) b;
1162
+
1163
+ return (ac->x - bc->x);
1164
+ }
1165
+
1166
+
1167
+ /* Check all the duplicates against each other to see if they are optical duplicates. */
1168
+ static int check_duplicate_chain(md_param_t *param, khash_t(duplicates) *dup_hash, check_list_t *list,
1169
+ long *warn, stats_block_t *stats) {
1170
+ int ret = 0;
1171
+ size_t curr = 0;
1172
+
1173
+ qsort(list->c, list->length, sizeof(list->c[0]), xcoord_sort);
1174
+
1175
+ while (curr < list->length - 1) {
1176
+ check_t *current = &list->c[curr];
1177
+ size_t count = curr;
1178
+ char *cur_name = bam_get_qname(current->b);
1179
+ int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP);
1180
+
1181
+ while (++count < list->length && (list->c[count].x - current->x <= param->opt_dist)) {
1182
+ // while close enough along the x coordinate
1183
+ check_t *chk = &list->c[count];
1184
+
1185
+ if (current->opt && chk->opt)
1186
+ continue;
1187
+
1188
+ // if both are already optical duplicates there is no need to check again, otherwise...
1189
+
1190
+ long ydiff;
1191
+
1192
+ if (current->y > chk->y) {
1193
+ ydiff = current->y - chk->y;
1194
+ } else {
1195
+ ydiff = chk->y - current->y;
1196
+ }
1197
+
1198
+ if (ydiff > param->opt_dist)
1199
+ continue;
1200
+
1201
+ // the number are right, check the names
1202
+ if (strncmp(cur_name + current->beg, bam_get_qname(chk->b) + chk->beg, current->end - current->beg) != 0)
1203
+ continue;
1204
+
1205
+ // optical duplicates
1206
+ int chk_dup = 0;
1207
+ int chk_paired = (chk->b->core.flag & BAM_FPAIRED) && !(chk->b->core.flag & BAM_FMUNMAP);
1208
+
1209
+ if (current_paired != chk_paired) {
1210
+ if (!chk_paired) {
1211
+ // chk is single vs pair, this is a dup.
1212
+ chk_dup = 1;
1213
+ }
1214
+ } else {
1215
+ // do it by scores
1216
+ int64_t cur_score, chk_score;
1217
+
1218
+ if ((current->b->core.flag & BAM_FQCFAIL) != (chk->b->core.flag & BAM_FQCFAIL)) {
1219
+ if (current->b->core.flag & BAM_FQCFAIL) {
1220
+ cur_score = 0;
1221
+ chk_score = 1;
1222
+ } else {
1223
+ cur_score = 1;
1224
+ chk_score = 0;
1225
+ }
1226
+ } else {
1227
+ cur_score = current->score;
1228
+ chk_score = chk->score;
1229
+
1230
+ if (current_paired) {
1231
+ // they are pairs so add mate scores.
1232
+ chk_score += chk->mate_score;
1233
+ cur_score += current->mate_score;
1234
+ }
1235
+ }
1236
+
1237
+ if (cur_score == chk_score) {
1238
+ if (strcmp(bam_get_qname(chk->b), cur_name) < 0) {
1239
+ chk_score++;
1240
+ } else {
1241
+ chk_score--;
1242
+ }
1243
+ }
1244
+
1245
+ if (cur_score > chk_score) {
1246
+ chk_dup = 1;
1247
+ }
1248
+ }
1249
+
1250
+ if (chk_dup) {
1251
+ // the duplicate is the optical duplicate
1252
+ if (!chk->opt) { // only change if not already an optical duplicate
1253
+ if (optical_retag(param, dup_hash, chk->b, chk_paired, stats)) {
1254
+ ret = -1;
1255
+ goto fail;
1256
+ }
1257
+
1258
+ chk->opt = 1;
1259
+ }
1260
+ } else {
1261
+ if (!current->opt) {
1262
+ if (optical_retag(param, dup_hash, current->b, current_paired, stats)) {
1263
+ ret = -1;
1264
+ goto fail;
1265
+ }
1266
+
1267
+ current->opt = 1;
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ curr++;
1273
+ }
1274
+
1275
+ fail:
1276
+ return ret;
1277
+ }
1278
+
1279
+
1280
+ /* Where there is more than one duplicate go down the list and check for optical duplicates and change
1281
+ do tags (where used) to point to original (non-duplicate) read. */
1282
+ static int find_duplicate_chains(md_param_t *param, read_queue_t *in_read , khash_t(duplicates) *dup_hash, check_list_t *dup_list,
1283
+ long *warn, stats_block_t *stats) {
1284
+ int ret = 0;
1285
+
1286
+ while (in_read->original) in_read = in_read->original;
1287
+
1288
+ // check against the original for tagging and optical duplication
1289
+ if ((ret = check_chain_against_original(param, dup_hash, in_read, dup_list, warn, stats + in_read->read_group))) {
1290
+ if (ret < 0) { // real error
1291
+ ret = -1;
1292
+ } else { // coordinate decoding error
1293
+ ret = 0;
1294
+ }
1295
+ } else {
1296
+ // check the rest of the duplicates against each other for optical duplication
1297
+ if (param->opt_dist && check_duplicate_chain(param, dup_hash, dup_list, warn, stats + in_read->read_group)) {
1298
+ ret = -1;
1299
+ }
1300
+ }
1301
+
1302
+ return ret;
1303
+ }
1304
+
1305
+
1306
+ /*
1307
+ Function to use when estimating library size.
1308
+
1309
+ This is based on an approximate formula for the coverage of a set
1310
+ obtained after sampling it a given number of times with replacement.
1311
+
1312
+ x = number of items in the set (the number of unique fragments in the library)
1313
+
1314
+ c = number of unique items (unique read pairs observed)
1315
+
1316
+ n = number of items samples (total number of read pairs)
1317
+
1318
+ c and n are known; x is unknown.
1319
+
1320
+ As n -> infinity, the coverage (c/x) can be given as:
1321
+
1322
+ c / x = 1 - exp(-n / x) (see https://math.stackexchange.com/questions/32800)
1323
+
1324
+ This needs to be solved for x, so it is rearranged to put both terms on the
1325
+ left side and estimate_library_size() finds a value of x which gives a
1326
+ result of zero (or as close as it can get).
1327
+ */
1328
+ static inline double coverage_equation(double x, double c, double n) {
1329
+ return c / x - 1 + exp(-n / x);
1330
+ }
1331
+
1332
+
1333
+ /* estimate the library size, based on the Picard code in DuplicationMetrics.java*/
1334
+ static unsigned long estimate_library_size(unsigned long paired_reads, unsigned long paired_duplicate_reads, unsigned long optical) {
1335
+ unsigned long estimated_size = 0;
1336
+ unsigned long non_optical_pairs = (paired_reads - optical) / 2;
1337
+ unsigned long unique_pairs = (paired_reads - paired_duplicate_reads) / 2;
1338
+ unsigned long duplicate_pairs = (paired_duplicate_reads - optical) / 2;
1339
+
1340
+ if ((non_optical_pairs && duplicate_pairs && unique_pairs) && (non_optical_pairs > duplicate_pairs)) {
1341
+ double m = 1;
1342
+ double M = 100;
1343
+ int i;
1344
+
1345
+ if (coverage_equation(m * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) < 0) {
1346
+ print_error("markdup", "warning, unable to calculate estimated library size.\n");
1347
+ return estimated_size;
1348
+ }
1349
+
1350
+ while (coverage_equation(M * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) > 0) {
1351
+ M *= 10;
1352
+ }
1353
+
1354
+ for (i = 0; i < 40; i++) {
1355
+ double r = (m + M) / 2;
1356
+ double u = coverage_equation(r * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs);
1357
+
1358
+ if (u > 0) {
1359
+ m = r;
1360
+ } else if (u < 0) {
1361
+ M = r;
1362
+ } else {
1363
+ break;
1364
+ }
1365
+ }
1366
+
1367
+ estimated_size = (unsigned long)(unique_pairs * (m + M) / 2);
1368
+ } else {
1369
+ print_error("markdup", "warning, unable to calculate estimated library size."
1370
+ " Read pairs %ld should be greater than duplicate pairs %ld,"
1371
+ " which should both be non zero.\n",
1372
+ non_optical_pairs, duplicate_pairs);
1373
+ }
1374
+
1375
+ return estimated_size;
1376
+ }
1377
+
1378
+
1379
+ static void write_stats(FILE *fp, const char *title, const char *title_con, stats_block_t *stats) {
1380
+ unsigned long els;
1381
+
1382
+ els = estimate_library_size(stats->pair, stats->duplicate, stats->optical);
1383
+
1384
+ if (title) {
1385
+ fprintf(fp, "%s%s\n", title, title_con);
1386
+ }
1387
+
1388
+ fprintf(fp,
1389
+ "READ: %ld\n"
1390
+ "WRITTEN: %ld\n"
1391
+ "EXCLUDED: %ld\n"
1392
+ "EXAMINED: %ld\n"
1393
+ "PAIRED: %ld\n"
1394
+ "SINGLE: %ld\n"
1395
+ "DUPLICATE PAIR: %ld\n"
1396
+ "DUPLICATE SINGLE: %ld\n"
1397
+ "DUPLICATE PAIR OPTICAL: %ld\n"
1398
+ "DUPLICATE SINGLE OPTICAL: %ld\n"
1399
+ "DUPLICATE NON PRIMARY: %ld\n"
1400
+ "DUPLICATE NON PRIMARY OPTICAL: %ld\n"
1401
+ "DUPLICATE PRIMARY TOTAL: %ld\n"
1402
+ "DUPLICATE TOTAL: %ld\n"
1403
+ "ESTIMATED_LIBRARY_SIZE: %ld\n", stats->reading, stats->writing, stats->excluded, stats->examined, stats->pair, stats->single,
1404
+ stats->duplicate, stats->single_dup, stats->optical, stats->single_optical, stats->np_duplicate, stats->np_opt_duplicate,
1405
+ stats->single_dup + stats->duplicate, stats->single_dup + stats->duplicate + stats->np_duplicate, els);
1406
+ }
1407
+
1408
+
1409
+ static void write_json_stats(FILE *fp, const char *offset, const char *group_name, stats_block_t *stats, const char *end) {
1410
+ unsigned long els;
1411
+
1412
+ els = estimate_library_size(stats->pair, stats->duplicate, stats->optical);
1413
+
1414
+ if (group_name) {
1415
+ fprintf(fp, "%s\"READ GROUP\": \"%s\",\n", offset, group_name);
1416
+ }
1417
+
1418
+ fprintf(fp, "%s\"READ\": %ld,\n", offset, stats->reading);
1419
+ fprintf(fp, "%s\"WRITTEN\": %ld,\n", offset, stats->writing);
1420
+ fprintf(fp, "%s\"EXCLUDED\": %ld,\n", offset, stats->excluded);
1421
+ fprintf(fp, "%s\"EXAMINED\": %ld,\n", offset, stats->examined);
1422
+ fprintf(fp, "%s\"PAIRED\": %ld,\n", offset, stats->pair);
1423
+ fprintf(fp, "%s\"SINGLE\": %ld,\n", offset, stats->single);
1424
+ fprintf(fp, "%s\"DUPLICATE PAIR\": %ld,\n", offset, stats->duplicate);
1425
+ fprintf(fp, "%s\"DUPLICATE SINGLE\": %ld,\n", offset, stats->single_dup);
1426
+ fprintf(fp, "%s\"DUPLICATE PAIR OPTICAL\": %ld,\n", offset, stats->optical);
1427
+ fprintf(fp, "%s\"DUPLICATE SINGLE OPTICAL\": %ld,\n", offset, stats->single_optical);
1428
+ fprintf(fp, "%s\"DUPLICATE NON PRIMARY\": %ld,\n", offset, stats->np_duplicate);
1429
+ fprintf(fp, "%s\"DUPLICATE NON PRIMARY OPTICAL\": %ld,\n", offset, stats->np_opt_duplicate);
1430
+ fprintf(fp, "%s\"DUPLICATE PRIMARY TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate);
1431
+ fprintf(fp, "%s\"DUPLICATE TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate + stats->np_duplicate);
1432
+ fprintf(fp, "%s\"ESTIMATED_LIBRARY_SIZE\": %ld", offset, els);
1433
+
1434
+ if (end) {
1435
+ fprintf(fp, "%s", end);
1436
+ }
1437
+ }
1438
+
1439
+
1440
+ /* Compare the reads near each other (coordinate sorted) and try to spot the duplicates.
1441
+ Generally the highest quality scoring is chosen as the original and all others the duplicates.
1442
+ The score is based on the sum of the quality values (<= 15) of the read and its mate (if any).
1443
+ While single reads are compared to only one read of a pair, the pair will chosen as the original.
1444
+ The comparison is done on position and orientation, see above for details.
1445
+
1446
+ Marking the supplementary reads of a duplicate as also duplicates takes an extra file read/write
1447
+ step. This is because the duplicate can occur before the primary read.*/
1448
+
1449
+ static int bam_mark_duplicates(md_param_t *param) {
1450
+ bam_hdr_t *header = NULL;
1451
+ khiter_t k;
1452
+ khash_t(reads) *pair_hash = kh_init(reads);
1453
+ khash_t(reads) *single_hash = kh_init(reads);
1454
+ klist_t(read_queue) *read_buffer = kl_init(read_queue);
1455
+ kliter_t(read_queue) *rq;
1456
+ khash_t(duplicates) *dup_hash = kh_init(duplicates);
1457
+ khash_t(read_groups) *rg_hash = kh_init(read_groups);
1458
+ int32_t prev_tid;
1459
+ hts_pos_t prev_coord;
1460
+ read_queue_t *in_read;
1461
+ int ret;
1462
+ stats_block_t *stats, *stat_array = NULL;
1463
+ int num_groups = 0;
1464
+ long opt_warnings = 0, bc_warnings = 0;
1465
+ tmp_file_t temp;
1466
+ char *idx_fn = NULL;
1467
+ int exclude = 0;
1468
+ check_list_t dup_list = {NULL, 0, 0};
1469
+
1470
+ if (!pair_hash || !single_hash || !read_buffer || !dup_hash || !rg_hash) {
1471
+ print_error("markdup", "error, unable to allocate memory to initialise structures.\n");
1472
+ goto fail;
1473
+ }
1474
+
1475
+ if ((header = sam_hdr_read(param->in)) == NULL) {
1476
+ print_error("markdup", "error reading header\n");
1477
+ goto fail;
1478
+ }
1479
+
1480
+ // accept unknown, unsorted or coordinate sort order, but error on queryname sorted.
1481
+ // only really works on coordinate sorted files.
1482
+ kstring_t str = KS_INITIALIZE;
1483
+ if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "queryname")) {
1484
+ print_error("markdup", "error, queryname sorted, must be sorted by coordinate.\n");
1485
+ ks_free(&str);
1486
+ goto fail;
1487
+ }
1488
+ ks_free(&str);
1489
+
1490
+ if (!param->no_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(),
1491
+ param->arg_list ? "CL" : NULL,
1492
+ param->arg_list ? param->arg_list : NULL,
1493
+ NULL) != 0) {
1494
+ print_error("markdup", "warning, unable to add @PG line to header.\n");
1495
+ }
1496
+
1497
+ if (sam_hdr_write(param->out, header) < 0) {
1498
+ print_error("markdup", "error writing header.\n");
1499
+ goto fail;
1500
+ }
1501
+ if (param->write_index) {
1502
+ if (!(idx_fn = auto_index(param->out, param->out_fn, header)))
1503
+ goto fail;
1504
+ }
1505
+
1506
+ if (param->read_groups) {
1507
+ num_groups = sam_hdr_count_lines(header, "RG");
1508
+ int g_ret = 0;
1509
+
1510
+ if (num_groups > 0) {
1511
+ int i;
1512
+
1513
+ for (i = 0; i < num_groups; i++) {
1514
+ const char *rg_key;
1515
+ khiter_t rg;
1516
+
1517
+ rg_key = sam_hdr_line_name(header, "RG", i);
1518
+
1519
+ if (rg_key) {
1520
+ rg = kh_get(read_groups, rg_hash, rg_key);
1521
+
1522
+ if (rg == kh_end(rg_hash)) { // new entry
1523
+ rg = kh_put(read_groups, rg_hash, rg_key, &g_ret);
1524
+
1525
+ if (g_ret > 0) {
1526
+ kh_value(rg_hash, rg) = i + 1;
1527
+ } else {
1528
+ print_error("markdup", "error, unable to populate read group ids. "
1529
+ "Read groups will not be used\n");
1530
+ g_ret = -1;
1531
+ break;
1532
+ }
1533
+ } else {
1534
+ print_error("markdup", "error, duplicate read group ids %s."
1535
+ "Read groups will not be used\n", rg_key);
1536
+ g_ret = -1;
1537
+ break;
1538
+ }
1539
+ } else {
1540
+ print_error("markdup", "error, Unable to retrieve read group at position %d."
1541
+ "Read groups will not be used\n", i);
1542
+ g_ret = -1;
1543
+ break;
1544
+ }
1545
+ }
1546
+ } else {
1547
+ print_error("markdup", "error, no read groups found.\n");
1548
+ g_ret = -1;
1549
+ }
1550
+
1551
+ if (g_ret < 0) {
1552
+ print_error("markdup", "error, read groups will not be used.\n");
1553
+ param->read_groups = 0;
1554
+ num_groups = 0;
1555
+ }
1556
+ }
1557
+
1558
+ // stat_array[0] will be for ungrouped reads
1559
+ stat_array = calloc(num_groups + 1, sizeof(stats_block_t));
1560
+
1561
+ if (stat_array == NULL) {
1562
+ print_error("markdup", "error, unable to allocate memory for stats.\n");
1563
+ goto fail;
1564
+ }
1565
+
1566
+ // used for coordinate order checks
1567
+ prev_tid = prev_coord = 0;
1568
+
1569
+ // get the buffer going
1570
+ in_read = kl_pushp(read_queue, read_buffer);
1571
+ if (!in_read) {
1572
+ print_error("markdup", "error, unable to allocate memory to hold reads.\n");
1573
+ goto fail;
1574
+ }
1575
+
1576
+ // handling supplementary reads needs a temporary file
1577
+ if (param->supp) {
1578
+ if (tmp_file_open_write(&temp, param->prefix, 1)) {
1579
+ print_error("markdup", "error, unable to open tmp file %s.\n", param->prefix);
1580
+ goto fail;
1581
+ }
1582
+ }
1583
+
1584
+ if ((in_read->b = bam_init1()) == NULL) {
1585
+ print_error("markdup", "error, unable to allocate memory for alignment.\n");
1586
+ goto fail;
1587
+ }
1588
+
1589
+ if (param->check_chain && !(param->tag || param->opt_dist))
1590
+ param->check_chain = 0;
1591
+
1592
+ if (param->check_chain) {
1593
+ dup_list.size = 128;
1594
+ dup_list.c = NULL;
1595
+
1596
+ if ((dup_list.c = malloc(dup_list.size * sizeof(check_t))) == NULL) {
1597
+ print_error("markdup", "error, unable to allocate memory for dup_list.\n");
1598
+ goto fail;
1599
+ }
1600
+ }
1601
+
1602
+ while ((ret = sam_read1(param->in, header, in_read->b)) >= 0) {
1603
+
1604
+ // do some basic coordinate order checks
1605
+ if (in_read->b->core.tid >= 0) { // -1 for unmapped reads
1606
+ if (in_read->b->core.tid < prev_tid ||
1607
+ ((in_read->b->core.tid == prev_tid) && (in_read->b->core.pos < prev_coord))) {
1608
+ print_error("markdup", "error, not in coordinate sorted order.\n");
1609
+ goto fail;
1610
+ }
1611
+ }
1612
+
1613
+ prev_coord = in_read->pos = in_read->b->core.pos;
1614
+ prev_tid = in_read->b->core.tid;
1615
+ in_read->pair_key.single = 1;
1616
+ in_read->single_key.single = 0;
1617
+ in_read->duplicate = NULL;
1618
+ in_read->original = NULL;
1619
+ in_read->dup_checked = 0;
1620
+ in_read->read_group = 0;
1621
+ in_read->dc = 1;
1622
+
1623
+ if (param->read_groups) {
1624
+ uint8_t *data;
1625
+ char *rg;
1626
+
1627
+ if ((data = bam_aux_get(in_read->b, "RG"))) {
1628
+ if ((rg = bam_aux2Z(data))) {
1629
+ khiter_t r;
1630
+
1631
+ r = kh_get(read_groups, rg_hash, rg);
1632
+
1633
+ if (r != kh_end(rg_hash)) {
1634
+ in_read->read_group = kh_value(rg_hash, r);
1635
+ }
1636
+ }
1637
+ }
1638
+ }
1639
+
1640
+ stats = stat_array + in_read->read_group;
1641
+
1642
+ stats->reading++;
1643
+
1644
+ if (param->clear && (in_read->b->core.flag & BAM_FDUP)) {
1645
+ uint8_t *data;
1646
+
1647
+ in_read->b->core.flag ^= BAM_FDUP;
1648
+
1649
+ if ((data = bam_aux_get(in_read->b, "dt")) != NULL) {
1650
+ bam_aux_del(in_read->b, data);
1651
+ }
1652
+
1653
+ if ((data = bam_aux_get(in_read->b, "do")) != NULL) {
1654
+ bam_aux_del(in_read->b, data);
1655
+ }
1656
+ }
1657
+
1658
+ if (param->include_fails) {
1659
+ exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP);
1660
+ } else {
1661
+ exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP | BAM_FQCFAIL);
1662
+ }
1663
+
1664
+ // read must not be secondary, supplementary, unmapped or (possibly) failed QC
1665
+ if (!(in_read->b->core.flag & exclude)) {
1666
+ stats->examined++;
1667
+
1668
+
1669
+ // look at the pairs first
1670
+ if ((in_read->b->core.flag & BAM_FPAIRED) && !(in_read->b->core.flag & BAM_FMUNMAP)) {
1671
+ int ret, mate_tmp;
1672
+ key_data_t pair_key;
1673
+ key_data_t single_key;
1674
+ in_hash_t *bp;
1675
+
1676
+ if (make_pair_key(param, &pair_key, in_read->b, in_read->read_group, &bc_warnings)) {
1677
+ print_error("markdup", "error, unable to assign pair hash key.\n");
1678
+ goto fail;
1679
+ }
1680
+
1681
+ make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings);
1682
+
1683
+ stats->pair++;
1684
+ in_read->pos = single_key.this_coord; // cigar/orientation modified pos
1685
+
1686
+ // put in singles hash for checking against non paired reads
1687
+ k = kh_put(reads, single_hash, single_key, &ret);
1688
+
1689
+ if (ret > 0) { // new
1690
+ // add to single duplicate hash
1691
+ bp = &kh_val(single_hash, k);
1692
+ bp->p = in_read;
1693
+ in_read->single_key = single_key;
1694
+ } else if (ret == 0) { // exists
1695
+ // look at singles only for duplication marking
1696
+ bp = &kh_val(single_hash, k);
1697
+
1698
+ if (!(bp->p->b->core.flag & BAM_FPAIRED) || (bp->p->b->core.flag & BAM_FMUNMAP)) {
1699
+ // singleton will always be marked duplicate even if
1700
+ // scores more than one read of the pair
1701
+ bam1_t *dup = bp->p->b;
1702
+
1703
+ if (param->check_chain) {
1704
+ in_read->duplicate = bp->p;
1705
+ bp->p->original = in_read;
1706
+ }
1707
+
1708
+ bp->p = in_read;
1709
+ bp->p->dc += 1;
1710
+
1711
+ if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings))
1712
+ goto fail;
1713
+
1714
+ stats->single_dup++;
1715
+ }
1716
+ } else {
1717
+ print_error("markdup", "error, single hashing failure for paired read.\n");
1718
+ goto fail;
1719
+ }
1720
+
1721
+ // now do the pair
1722
+ k = kh_put(reads, pair_hash, pair_key, &ret);
1723
+
1724
+ if (ret > 0) { // new
1725
+ // add to the pair hash
1726
+ bp = &kh_val(pair_hash, k);
1727
+ bp->p = in_read;
1728
+ in_read->pair_key = pair_key;
1729
+ } else if (ret == 0) {
1730
+ int64_t old_score, new_score, tie_add = 0;
1731
+ bam1_t *dup = NULL;
1732
+
1733
+ bp = &kh_val(pair_hash, k);
1734
+
1735
+ if ((bp->p->b->core.flag & BAM_FQCFAIL) != (in_read->b->core.flag & BAM_FQCFAIL)) {
1736
+ if (bp->p->b->core.flag & BAM_FQCFAIL) {
1737
+ old_score = 0;
1738
+ new_score = 1;
1739
+ } else {
1740
+ old_score = 1;
1741
+ new_score = 0;
1742
+ }
1743
+ } else {
1744
+ if ((mate_tmp = get_mate_score(bp->p->b)) == -1) {
1745
+ print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1746
+ goto fail;
1747
+ } else {
1748
+ old_score = calc_score(bp->p->b) + mate_tmp;
1749
+ }
1750
+
1751
+ if ((mate_tmp = get_mate_score(in_read->b)) == -1) {
1752
+ print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n");
1753
+ goto fail;
1754
+ } else {
1755
+ new_score = calc_score(in_read->b) + mate_tmp;
1756
+ }
1757
+ }
1758
+
1759
+ // choose the highest score as the original
1760
+ // and add it to the pair hash, mark the other as duplicate
1761
+
1762
+ if (new_score == old_score) {
1763
+ if (strcmp(bam_get_qname(in_read->b), bam_get_qname(bp->p->b)) < 0) {
1764
+ tie_add = 1;
1765
+ } else {
1766
+ tie_add = -1;
1767
+ }
1768
+ }
1769
+
1770
+ if (new_score + tie_add > old_score) { // swap reads
1771
+ dup = bp->p->b;
1772
+ in_read->dc += bp->p->dc;
1773
+
1774
+ if (param->check_chain) {
1775
+
1776
+ if (in_read->duplicate) {
1777
+ read_queue_t *current = in_read->duplicate;
1778
+
1779
+ while (current->duplicate) {
1780
+ current = current->duplicate;
1781
+ }
1782
+
1783
+ current->duplicate = bp->p;
1784
+ } else {
1785
+ in_read->duplicate = bp->p;
1786
+ }
1787
+
1788
+ bp->p->original = in_read;
1789
+ }
1790
+
1791
+ bp->p = in_read;
1792
+ } else {
1793
+ if (param->check_chain) {
1794
+ if (bp->p->duplicate) {
1795
+ if (in_read->duplicate) {
1796
+ read_queue_t *current = bp->p->duplicate;
1797
+
1798
+ while (current->duplicate) {
1799
+ current = current->duplicate;
1800
+ }
1801
+
1802
+ current->duplicate = in_read->duplicate;
1803
+ }
1804
+
1805
+ in_read->duplicate = bp->p->duplicate;
1806
+ }
1807
+
1808
+ bp->p->duplicate = in_read;
1809
+ in_read->original = bp->p;
1810
+ }
1811
+
1812
+ dup = in_read->b;
1813
+ bp->p->dc += 1;
1814
+ }
1815
+
1816
+ if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->optical, &opt_warnings))
1817
+ goto fail;
1818
+
1819
+ stats->duplicate++;
1820
+ } else {
1821
+ print_error("markdup", "error, pair hashing failure.\n");
1822
+ goto fail;
1823
+ }
1824
+ } else { // do the single (or effectively single) reads
1825
+ int ret;
1826
+ key_data_t single_key;
1827
+ in_hash_t *bp;
1828
+
1829
+ make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings);
1830
+
1831
+ stats->single++;
1832
+ in_read->pos = single_key.this_coord; // cigar/orientation modified pos
1833
+
1834
+ k = kh_put(reads, single_hash, single_key, &ret);
1835
+
1836
+ if (ret > 0) { // new
1837
+ bp = &kh_val(single_hash, k);
1838
+ bp->p = in_read;
1839
+ in_read->single_key = single_key;
1840
+ } else if (ret == 0) { // exists
1841
+ bp = &kh_val(single_hash, k);
1842
+
1843
+ if ((bp->p->b->core.flag & BAM_FPAIRED) && !(bp->p->b->core.flag & BAM_FMUNMAP)) {
1844
+ // if matched against one of a pair just mark as duplicate
1845
+
1846
+ if (param->check_chain) {
1847
+ if (bp->p->duplicate) {
1848
+ in_read->duplicate = bp->p->duplicate;
1849
+ }
1850
+
1851
+ bp->p->duplicate = in_read;
1852
+ in_read->original = bp->p;
1853
+ }
1854
+
1855
+ bp->p->dc += 1;
1856
+
1857
+ if (mark_duplicates(param, dup_hash, bp->p->b, in_read->b, in_read->read_group, &stats->single_optical, &opt_warnings))
1858
+ goto fail;
1859
+
1860
+ } else {
1861
+ int64_t old_score, new_score;
1862
+ bam1_t *dup = NULL;
1863
+
1864
+ old_score = calc_score(bp->p->b);
1865
+ new_score = calc_score(in_read->b);
1866
+
1867
+ // choose the highest score as the original, add it
1868
+ // to the single hash and mark the other as duplicate
1869
+ if (new_score > old_score) { // swap reads
1870
+ dup = bp->p->b;
1871
+ in_read->dc += bp->p->dc;
1872
+
1873
+ if (param->check_chain) {
1874
+ in_read->duplicate = bp->p;
1875
+ bp->p->original = in_read;
1876
+ }
1877
+
1878
+ bp->p = in_read;
1879
+ } else {
1880
+ if (param->check_chain) {
1881
+ if (bp->p->duplicate) {
1882
+ in_read->duplicate = bp->p->duplicate;
1883
+ }
1884
+
1885
+ bp->p->duplicate = in_read;
1886
+ in_read->original = bp->p;
1887
+ }
1888
+
1889
+ bp->p->dc += 1;
1890
+ dup = in_read->b;
1891
+ }
1892
+
1893
+ if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings))
1894
+ goto fail;
1895
+ }
1896
+
1897
+ stats->single_dup++;
1898
+ } else {
1899
+ print_error("markdup", "error, single hashing failure for single read.\n");
1900
+ goto fail;
1901
+ }
1902
+ }
1903
+ } else {
1904
+ stats->excluded++;
1905
+ }
1906
+
1907
+ // loop through the stored reads and write out those we
1908
+ // no longer need
1909
+ rq = kl_begin(read_buffer);
1910
+ while (rq != kl_end(read_buffer)) {
1911
+ in_read = &kl_val(rq);
1912
+
1913
+ /* keep a moving window of reads based on coordinates and max read length. Any unaligned reads
1914
+ should just be written as they cannot be matched as duplicates. */
1915
+ if (in_read->pos + param->max_length > prev_coord && in_read->b->core.tid == prev_tid && (prev_tid != -1 || prev_coord != -1)) {
1916
+ break;
1917
+ }
1918
+
1919
+ if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) {
1920
+ if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) {
1921
+ print_error("markdup", "error, duplicate checking failed.\n");
1922
+ goto fail;
1923
+ }
1924
+ }
1925
+
1926
+ if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) {
1927
+ if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
1928
+ bam_aux_update_int(in_read->b, "dc", in_read->dc);
1929
+ }
1930
+ if (param->supp) {
1931
+ if (tmp_file_write(&temp, in_read->b)) {
1932
+ print_error("markdup", "error, writing temp output failed.\n");
1933
+ goto fail;
1934
+ }
1935
+ } else {
1936
+ if (sam_write1(param->out, header, in_read->b) < 0) {
1937
+ print_error("markdup", "error, writing output failed.\n");
1938
+ goto fail;
1939
+ }
1940
+ }
1941
+
1942
+ stat_array[in_read->read_group].writing++;
1943
+ }
1944
+
1945
+ // remove from hash
1946
+ if (in_read->pair_key.single == 0) {
1947
+ k = kh_get(reads, pair_hash, in_read->pair_key);
1948
+ kh_del(reads, pair_hash, k);
1949
+ }
1950
+
1951
+ if (in_read->single_key.single == 1) {
1952
+ k = kh_get(reads, single_hash, in_read->single_key);
1953
+ kh_del(reads, single_hash, k);
1954
+ }
1955
+
1956
+ kl_shift(read_queue, read_buffer, NULL);
1957
+ bam_destroy1(in_read->b);
1958
+ rq = kl_begin(read_buffer);
1959
+ }
1960
+
1961
+ // set the next one up for reading
1962
+ in_read = kl_pushp(read_queue, read_buffer);
1963
+ if (!in_read) {
1964
+ print_error("markdup", "error, unable to allocate memory for read in queue.\n");
1965
+ goto fail;
1966
+ }
1967
+
1968
+ if ((in_read->b = bam_init1()) == NULL) {
1969
+ print_error("markdup", "error, unable to allocate memory for alignment.\n");
1970
+ goto fail;
1971
+ }
1972
+ }
1973
+
1974
+ if (ret < -1) {
1975
+ print_error("markdup", "error, truncated input file.\n");
1976
+ goto fail;
1977
+ }
1978
+
1979
+ // write out the end of the list
1980
+ rq = kl_begin(read_buffer);
1981
+ while (rq != kl_end(read_buffer)) {
1982
+ in_read = &kl_val(rq);
1983
+
1984
+ if (bam_get_qname(in_read->b)) { // last entry will be blank
1985
+ if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) {
1986
+ if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) {
1987
+ print_error("markdup", "error, duplicate checking failed.\n");
1988
+ goto fail;
1989
+ }
1990
+ }
1991
+
1992
+ if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) {
1993
+ if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
1994
+ bam_aux_update_int(in_read->b, "dc", in_read->dc);
1995
+ }
1996
+
1997
+ if (param->supp) {
1998
+ if (tmp_file_write(&temp, in_read->b)) {
1999
+ print_error("markdup", "error, writing temp output failed on final write.\n");
2000
+ goto fail;
2001
+ }
2002
+ } else {
2003
+ if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) {
2004
+ bam_aux_update_int(in_read->b, "dc", in_read->dc);
2005
+ }
2006
+
2007
+ if (sam_write1(param->out, header, in_read->b) < 0) {
2008
+ print_error("markdup", "error, writing output failed on final write.\n");
2009
+ goto fail;
2010
+ }
2011
+ }
2012
+
2013
+ stat_array[in_read->read_group].writing++;
2014
+ }
2015
+ }
2016
+
2017
+ kl_shift(read_queue, read_buffer, NULL);
2018
+ bam_destroy1(in_read->b);
2019
+ rq = kl_begin(read_buffer);
2020
+ }
2021
+
2022
+ if (param->supp) {
2023
+ bam1_t *b;
2024
+
2025
+ if (tmp_file_end_write(&temp)) {
2026
+ print_error("markdup", "error, unable to end tmp writing.\n");
2027
+ goto fail;
2028
+ }
2029
+
2030
+ // read data from temp file and mark duplicate supplementary alignments
2031
+
2032
+ if (tmp_file_begin_read(&temp)) {
2033
+ goto fail;
2034
+ }
2035
+
2036
+ b = bam_init1();
2037
+
2038
+ while ((ret = tmp_file_read(&temp, b)) > 0) {
2039
+
2040
+ if ((b->core.flag & BAM_FSUPPLEMENTARY) || (b->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FSECONDARY)) {
2041
+
2042
+ k = kh_get(duplicates, dup_hash, bam_get_qname(b));
2043
+
2044
+ if (k != kh_end(dup_hash)) {
2045
+
2046
+ b->core.flag |= BAM_FDUP;
2047
+ stat_array[kh_val(dup_hash, k).read_group].np_duplicate++;
2048
+
2049
+ if (param->tag && kh_val(dup_hash, k).name) {
2050
+ if (bam_aux_update_str(b, "do", strlen(kh_val(dup_hash, k).name) + 1, (char*)kh_val(dup_hash, k).name)) {
2051
+ print_error("markdup", "error, unable to append supplementary 'do' tag.\n");
2052
+ goto fail;
2053
+ }
2054
+ }
2055
+
2056
+ if (param->opt_dist) {
2057
+ if (kh_val(dup_hash, k).type) {
2058
+ bam_aux_update_str(b, "dt", 3, "SQ");
2059
+ stat_array[kh_val(dup_hash, k).read_group].np_opt_duplicate++;
2060
+ } else {
2061
+ bam_aux_update_str(b, "dt", 3, "LB");
2062
+ }
2063
+ }
2064
+ }
2065
+ }
2066
+
2067
+ if (!param->remove_dups || !(b->core.flag & BAM_FDUP)) {
2068
+ if (param->dc && (b->core.flag & BAM_FDUP)) {
2069
+ uint8_t* data = bam_aux_get(b, "dc");
2070
+ if(data) bam_aux_del(b, data);
2071
+ }
2072
+ if (sam_write1(param->out, header, b) < 0) {
2073
+ print_error("markdup", "error, writing final output failed.\n");
2074
+ goto fail;
2075
+ }
2076
+ }
2077
+ }
2078
+
2079
+ if (ret == -1) {
2080
+ print_error("markdup", "error, failed to read tmp file.\n");
2081
+ goto fail;
2082
+ }
2083
+
2084
+ for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) {
2085
+ if (kh_exist(dup_hash, k)) {
2086
+ free(kh_val(dup_hash, k).name);
2087
+ free((char *)kh_key(dup_hash, k));
2088
+ kh_key(dup_hash, k) = NULL;
2089
+ }
2090
+ }
2091
+
2092
+ tmp_file_destroy(&temp);
2093
+ bam_destroy1(b);
2094
+ }
2095
+
2096
+ if (opt_warnings) {
2097
+ print_error("markdup", "warning, number of failed attempts to get coordinates from read names = %ld\n",
2098
+ opt_warnings);
2099
+ }
2100
+
2101
+ if (bc_warnings) {
2102
+ print_error("markdup", "warning, number of failed attempts to get barcodes = %ld\n", bc_warnings);
2103
+ }
2104
+
2105
+ if (param->do_stats) {
2106
+ FILE *fp;
2107
+ int file_open = 0;
2108
+ stats_block_t total;
2109
+ int i;
2110
+
2111
+ if (param->stats_file) {
2112
+ if (NULL == (fp = fopen(param->stats_file, "w"))) {
2113
+ print_error("markdup", "warning, cannot write stats to %s.\n", param->stats_file);
2114
+ fp = stderr;
2115
+ } else {
2116
+ file_open = 1;
2117
+ }
2118
+ } else {
2119
+ fp = stderr;
2120
+ }
2121
+
2122
+ total = stat_array[0];
2123
+
2124
+ if (param->read_groups) {
2125
+ for (i = 1; i <= num_groups; i++) {
2126
+ total.reading += stat_array[i].reading;
2127
+ total.writing += stat_array[i].writing;
2128
+ total.excluded += stat_array[i].excluded;
2129
+ total.duplicate += stat_array[i].duplicate;
2130
+ total.single += stat_array[i].single;
2131
+ total.pair += stat_array[i].pair;
2132
+ total.single_dup += stat_array[i].single_dup;
2133
+ total.examined += stat_array[i].examined;
2134
+ total.optical += stat_array[i].optical;
2135
+ total.single_optical += stat_array[i].single_optical;
2136
+ total.np_duplicate += stat_array[i].np_duplicate;
2137
+ total.np_opt_duplicate += stat_array[i].np_opt_duplicate;
2138
+ }
2139
+ }
2140
+
2141
+ if (!param->json) {
2142
+ write_stats(fp, "COMMAND: ", param->arg_list, &total);
2143
+ fprintf(fp, "\n");
2144
+
2145
+ if (param->read_groups) {
2146
+ if (stat_array[0].reading) {
2147
+ write_stats(fp, "READ GROUP: ", "ungrouped", stat_array);
2148
+ fprintf(fp, "\n");
2149
+ }
2150
+
2151
+ for (i = 0; i < num_groups; i++) {
2152
+ write_stats(fp, "READ GROUP: ", sam_hdr_line_name(header, "RG", i), stat_array + i + 1);
2153
+ fprintf(fp, "\n");
2154
+ }
2155
+ }
2156
+ } else {
2157
+ char space4[] = " ";
2158
+ char space8[] = " ";
2159
+ char space12[] = " ";
2160
+
2161
+ fprintf(fp, "{\n");
2162
+ fprintf(fp, "%s\"COMMAND\": \"%s\",\n", space4, param->arg_list);
2163
+ write_json_stats(fp, space4, NULL, &total, param->read_groups ? ",\n" : "\n");
2164
+
2165
+ if (param->read_groups) {
2166
+ fprintf(fp, "%s\"READ GROUPS\": [\n", space4);
2167
+
2168
+ if (stat_array[0].reading) {
2169
+ fprintf(fp, "%s{\n", space8);
2170
+ write_json_stats(fp, space12, "ungrouped", stat_array, "\n");
2171
+ fprintf(fp, "%s},\n", space8);
2172
+ }
2173
+
2174
+ for (i = 0; i < num_groups; i++) {
2175
+ fprintf(fp, "%s{\n", space8);
2176
+
2177
+ write_json_stats(fp, space12, sam_hdr_line_name(header, "RG", i), stat_array + i + 1, "\n");
2178
+
2179
+ if (i < num_groups -1 ) {
2180
+ fprintf(fp, "%s},\n", space8);
2181
+ } else {
2182
+ fprintf(fp, "%s}\n", space8);
2183
+ }
2184
+ }
2185
+
2186
+ fprintf(fp, "%s]\n", space4);
2187
+ }
2188
+
2189
+ fprintf(fp, "}\n");
2190
+ }
2191
+
2192
+ if (file_open) {
2193
+ fclose(fp);
2194
+ }
2195
+ }
2196
+
2197
+ if (param->write_index) {
2198
+ if (sam_idx_save(param->out) < 0) {
2199
+ print_error_errno("markdup", "error, writing index failed");
2200
+ goto fail;
2201
+ }
2202
+ }
2203
+
2204
+ if (param->check_chain && (param->tag || param->opt_dist))
2205
+ free(dup_list.c);
2206
+
2207
+ free(idx_fn);
2208
+ free(stat_array);
2209
+ kh_destroy(reads, pair_hash);
2210
+ kh_destroy(reads, single_hash);
2211
+ kl_destroy(read_queue, read_buffer);
2212
+ kh_destroy(duplicates, dup_hash);
2213
+ kh_destroy(read_groups, rg_hash);
2214
+ sam_hdr_destroy(header);
2215
+
2216
+ return 0;
2217
+
2218
+ fail:
2219
+ for (rq = kl_begin(read_buffer); rq != kl_end(read_buffer); rq = kl_next(rq))
2220
+ bam_destroy1(kl_val(rq).b);
2221
+ kl_destroy(read_queue, read_buffer);
2222
+
2223
+ for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) {
2224
+ if (kh_exist(dup_hash, k)) {
2225
+ free((char *)kh_key(dup_hash, k));
2226
+ }
2227
+ }
2228
+ kh_destroy(duplicates, dup_hash);
2229
+ kh_destroy(read_groups, rg_hash);
2230
+
2231
+ if (param->check_chain && (param->tag || param->opt_dist))
2232
+ free(dup_list.c);
2233
+
2234
+ free(idx_fn);
2235
+ free(stat_array);
2236
+ kh_destroy(reads, pair_hash);
2237
+ kh_destroy(reads, single_hash);
2238
+ sam_hdr_destroy(header);
2239
+ return 1;
2240
+ }
2241
+
2242
+
2243
+ static int markdup_usage(void) {
2244
+ fprintf(stderr, "\n");
2245
+ fprintf(stderr, "Usage: samtools markdup <input.bam> <output.bam>\n\n");
2246
+ fprintf(stderr, "Option: \n");
2247
+ fprintf(stderr, " -r Remove duplicate reads\n");
2248
+ fprintf(stderr, " -l INT Max read length (default 300 bases)\n");
2249
+ fprintf(stderr, " -S Mark supplementary alignments of duplicates as duplicates (slower).\n");
2250
+ fprintf(stderr, " -s Report stats.\n");
2251
+ fprintf(stderr, " -f NAME Write stats to named file. Implies -s.\n");
2252
+ fprintf(stderr, " --json Output stats in JSON. Also implies -s\n");
2253
+ fprintf(stderr, " -T PREFIX Write temporary files to PREFIX.samtools.nnnn.nnnn.tmp.\n");
2254
+ fprintf(stderr, " -d INT Optical distance (if set, marks with dt tag)\n");
2255
+ fprintf(stderr, " -c Clear previous duplicate settings and tags.\n");
2256
+ fprintf(stderr, " -m --mode TYPE Duplicate decision method for paired reads.\n"
2257
+ " TYPE = t measure positions based on template start/end (default).\n"
2258
+ " s measure positions based on sequence start.\n");
2259
+ fprintf(stderr, " -u Output uncompressed data\n");
2260
+ fprintf(stderr, " --include-fails Include quality check failed reads.\n");
2261
+ fprintf(stderr, " --no-PG Do not add a PG line\n");
2262
+ fprintf(stderr, " --no-multi-dup Reduced duplicates of duplicates checking.\n");
2263
+ fprintf(stderr, " --read-coords STR Regex for coords from read name.\n");
2264
+ fprintf(stderr, " --coords-order STR Order of regex elements. txy (default). With t being a part of\n"
2265
+ " the read names that must be equal and x/y being coordinates.\n");
2266
+ fprintf(stderr, " --barcode-tag STR Use barcode a tag that duplicates much match.\n");
2267
+ fprintf(stderr, " --barcode-name Use the UMI/barcode in the read name (eigth colon delimited part).\n");
2268
+ fprintf(stderr, " --barcode-rgx STR Regex for barcode in the readname (alternative to --barcode-name).\n");
2269
+ fprintf(stderr, " --use-read-groups Use the read group tags in duplicate matching.\n");
2270
+ fprintf(stderr, " -t Mark primary duplicates with the name of the original in a \'do\' tag."
2271
+ " Mainly for information and debugging.\n");
2272
+ fprintf(stderr, " --duplicate-count Record the original primary read duplication count(include itself) in a \'dc\' tag.\n");
2273
+
2274
+ sam_global_opt_help(stderr, "-.O..@..");
2275
+
2276
+ fprintf(stderr, "\nThe input file must be coordinate sorted and must have gone"
2277
+ " through fixmates with the mate scoring option on.\n");
2278
+
2279
+ return 1;
2280
+ }
2281
+
2282
+
2283
+ int bam_markdup(int argc, char **argv) {
2284
+ int c, ret, bc_name = 0;
2285
+ char wmode[4] = {'w', 0, 0, 0};
2286
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
2287
+ htsThreadPool p = {NULL, 0};
2288
+ kstring_t tmpprefix = {0, 0, NULL};
2289
+ struct stat st;
2290
+ unsigned int t;
2291
+ char *regex = NULL, *bc_regex = NULL;
2292
+ char *regex_order = "txy";
2293
+ md_param_t param = {NULL, NULL, NULL, 0, 300, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2294
+ 1, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0};
2295
+
2296
+ static const struct option lopts[] = {
2297
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
2298
+ {"include-fails", no_argument, NULL, 1001},
2299
+ {"no-PG", no_argument, NULL, 1002},
2300
+ {"mode", required_argument, NULL, 'm'},
2301
+ {"no-multi-dup", no_argument, NULL, 1003},
2302
+ {"read-coords", required_argument, NULL, 1004},
2303
+ {"coords-order", required_argument, NULL, 1005},
2304
+ {"barcode-tag", required_argument, NULL, 1006},
2305
+ {"barcode-name", no_argument, NULL, 1007},
2306
+ {"barcode-rgx", required_argument, NULL, 1008},
2307
+ {"use-read-groups", no_argument, NULL, 1009},
2308
+ {"json", no_argument, NULL, 1010},
2309
+ {"duplicate-count", no_argument, NULL, 1011},
2310
+ {NULL, 0, NULL, 0}
2311
+ };
2312
+
2313
+ while ((c = getopt_long(argc, argv, "rsl:StT:O:@:f:d:cm:u", lopts, NULL)) >= 0) {
2314
+ switch (c) {
2315
+ case 'r': param.remove_dups = 1; break;
2316
+ case 'l': param.max_length = atoi(optarg); break;
2317
+ case 's': param.do_stats = 1; break;
2318
+ case 'T': kputs(optarg, &tmpprefix); break;
2319
+ case 'S': param.supp = 1; break;
2320
+ case 't': param.tag = 1; break;
2321
+ case 'f': param.stats_file = optarg; param.do_stats = 1; break;
2322
+ case 'd': param.opt_dist = atoi(optarg); break;
2323
+ case 'c': param.clear = 1; break;
2324
+ case 'm':
2325
+ if (strcmp(optarg, "t") == 0) {
2326
+ param.mode = MD_MODE_TEMPLATE;
2327
+ } else if (strcmp(optarg, "s") == 0) {
2328
+ param.mode = MD_MODE_SEQUENCE;
2329
+ } else {
2330
+ print_error("markdup", "error, unknown mode '%s'.\n", optarg);
2331
+ return markdup_usage();
2332
+ }
2333
+
2334
+ break;
2335
+ case 'u': wmode[1] = '0'; break;
2336
+ case 1001: param.include_fails = 1; break;
2337
+ case 1002: param.no_pg = 1; break;
2338
+ case 1003: param.check_chain = 0; break;
2339
+ case 1004: regex = optarg; break;
2340
+ case 1005: regex_order = optarg; break;
2341
+ case 1006: param.barcode = optarg; break;
2342
+ case 1007: bc_name = 1; break;
2343
+ case 1008: bc_name = 1, bc_regex = optarg; break;
2344
+ case 1009: param.read_groups = 1; break;
2345
+ case 1010: param.json = 1; param.do_stats = 1; break;
2346
+ case 1011: param.dc = 1; break;
2347
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
2348
+ /* else fall-through */
2349
+ case '?': return markdup_usage();
2350
+ }
2351
+ }
2352
+
2353
+ if (optind + 2 > argc)
2354
+ return markdup_usage();
2355
+
2356
+ if (param.barcode && bc_name) {
2357
+ print_error("markdup", "error, cannot specify --barcode-tag and "
2358
+ "--barcode-name (or --barcode-rgx) at same time.\n");
2359
+ return 1;
2360
+ }
2361
+
2362
+ if (param.opt_dist < 0) param.opt_dist = 0;
2363
+ if (param.max_length < 0) param.max_length = 300;
2364
+
2365
+ if (regex) {
2366
+ int result;
2367
+
2368
+ // set the order the elements of the regex are assigned to.
2369
+ // x and y being coordinates, t being any other important part of the read
2370
+ // e.g. tile and lane
2371
+ // x and y order does not matter as long as it is consistent
2372
+
2373
+ if ((strncmp(regex_order, "txy", 3) == 0) || (strncmp(regex_order, "tyx", 3) == 0)) {
2374
+ param.rgx_t = 1;
2375
+ param.rgx_x = 2;
2376
+ param.rgx_y = 3;
2377
+ } else if ((strncmp(regex_order, "xyt", 3) == 0) || (strncmp(regex_order, "yxt", 3) == 0)) {
2378
+ param.rgx_x = 1;
2379
+ param.rgx_y = 2;
2380
+ param.rgx_t = 3;
2381
+ } else if ((strncmp(regex_order, "xty", 3) == 0) || (strncmp(regex_order, "ytx", 3) == 0)) {
2382
+ param.rgx_x = 1;
2383
+ param.rgx_t = 2;
2384
+ param.rgx_y = 3;
2385
+ } else if ((strncmp(regex_order, "xy", 2) == 0) || (strncmp(regex_order, "yx", 2) == 0)) {
2386
+ param.rgx_x = 1;
2387
+ param.rgx_y = 2;
2388
+ param.rgx_t = 0;
2389
+ } else {
2390
+ print_error("markdup", "error, could not recognise regex coordinate order \"%s\".\n", regex_order);
2391
+ return 1;
2392
+ }
2393
+
2394
+ if ((param.rgx = malloc(sizeof(regex_t))) == NULL) {
2395
+ print_error("markdup", "error, could not allocate memory for regex.\n");
2396
+ return 1;
2397
+ }
2398
+
2399
+ if ((result = regcomp(param.rgx, regex, REG_EXTENDED))) {
2400
+ char err_msg[256];
2401
+
2402
+ regerror(result, param.rgx, err_msg, 256);
2403
+ print_error("markdup", "error, regex fail \"%s\"\n", err_msg);
2404
+ free(param.rgx);
2405
+ return 1;
2406
+ }
2407
+ }
2408
+
2409
+ if (bc_name) {
2410
+ int result;
2411
+
2412
+ /* From Illumina UMI documentation: "The UMI sequence is located in the
2413
+ eighth colon-delimited field of the read name (QNAME)". */
2414
+ char *rgx = "[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:[0-9A-Za-z]+:([!-?A-~]+)";
2415
+
2416
+ if ((param.bc_rgx = malloc(sizeof(regex_t))) == NULL) {
2417
+ print_error("markdup", "error, could not allocate memory for barcode regex.\n");
2418
+ return 1;
2419
+ }
2420
+
2421
+ if (bc_regex) {
2422
+ rgx = bc_regex;
2423
+ }
2424
+
2425
+ if ((result = regcomp(param.bc_rgx, rgx, REG_EXTENDED))) {
2426
+ char err_msg[256];
2427
+
2428
+ regerror(result, param.bc_rgx, err_msg, 256);
2429
+ print_error("markdup", "error, barcode regex fail \"%s\"\n", err_msg);
2430
+ free(param.bc_rgx);
2431
+ return 1;
2432
+ }
2433
+ }
2434
+
2435
+ param.in = sam_open_format(argv[optind], "r", &ga.in);
2436
+
2437
+ if (!param.in) {
2438
+ print_error_errno("markdup", "error, failed to open \"%s\" for input", argv[optind]);
2439
+ return 1;
2440
+ }
2441
+
2442
+ strcat(wmode, "b"); // default if unknown suffix
2443
+ sam_open_mode(wmode + strlen(wmode)-1, argv[optind + 1], NULL);
2444
+ param.out = sam_open_format(argv[optind + 1], wmode, &ga.out);
2445
+
2446
+ if (!param.out) {
2447
+ print_error_errno("markdup", "error, failed to open \"%s\" for output", argv[optind + 1]);
2448
+ return 1;
2449
+ }
2450
+
2451
+ if (ga.nthreads > 0) {
2452
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
2453
+ print_error("markdup", "error creating thread pool.\n");
2454
+ return 1;
2455
+ }
2456
+
2457
+ hts_set_opt(param.in, HTS_OPT_THREAD_POOL, &p);
2458
+ hts_set_opt(param.out, HTS_OPT_THREAD_POOL, &p);
2459
+ }
2460
+
2461
+ // actual stuff happens here
2462
+
2463
+ // we need temp files so fix up the name here
2464
+ if (tmpprefix.l == 0) {
2465
+
2466
+ if (strcmp(argv[optind + 1], "-") != 0)
2467
+ ksprintf(&tmpprefix, "%s.", argv[optind + 1]);
2468
+ else
2469
+ kputc('.', &tmpprefix);
2470
+ }
2471
+
2472
+ if (stat(tmpprefix.s, &st) == 0 && S_ISDIR(st.st_mode)) {
2473
+ if (tmpprefix.s[tmpprefix.l-1] != '/') kputc('/', &tmpprefix);
2474
+ }
2475
+
2476
+ t = ((unsigned) time(NULL)) ^ ((unsigned) clock());
2477
+ ksprintf(&tmpprefix, "samtools.%d.%u.tmp", (int) getpid(), t % 10000);
2478
+ param.prefix = tmpprefix.s;
2479
+
2480
+ param.arg_list = stringify_argv(argc + 1, argv - 1);
2481
+ param.write_index = ga.write_index;
2482
+ param.out_fn = argv[optind + 1];
2483
+
2484
+ ret = bam_mark_duplicates(&param);
2485
+
2486
+ sam_close(param.in);
2487
+
2488
+ if (sam_close(param.out) < 0) {
2489
+ print_error("markdup", "error closing output file.\n");
2490
+ ret = 1;
2491
+ }
2492
+
2493
+ if (p.pool) hts_tpool_destroy(p.pool);
2494
+
2495
+ if (param.rgx) {
2496
+ regfree(param.rgx);
2497
+ free(param.rgx);
2498
+ }
2499
+
2500
+ if (param.bc_rgx) {
2501
+ regfree(param.bc_rgx);
2502
+ free(param.bc_rgx);
2503
+ }
2504
+
2505
+ free(param.arg_list);
2506
+ free(tmpprefix.s);
2507
+ sam_global_args_free(&ga);
2508
+
2509
+ return ret;
2510
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_mate.c -- fix mate pairing information and clean up flags.
2
+
3
+ Copyright (C) 2009, 2011-2017, 2019, 2022 Genome Research Ltd.
4
+ Portions copyright (C) 2011 Broad Institute.
5
+ Portions copyright (C) 2012 Peter Cock, The James Hutton Institute.
6
+
7
+ Author: Heng Li <lh3@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notices and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ #include <config.h>
28
+
29
+ #include <assert.h>
30
+ #include <stdbool.h>
31
+ #include <stdlib.h>
32
+ #include <string.h>
33
+ #include <unistd.h>
34
+ #include "htslib/thread_pool.h"
35
+ #include "sam_opts.h"
36
+ #include "htslib/kstring.h"
37
+ #include "htslib/sam.h"
38
+ #include "samtools.h"
39
+
40
+
41
+ #define MD_MIN_QUALITY 15
42
+
43
+ /*
44
+ * This function calculates ct tag for two bams, it assumes they are from the same template and
45
+ * writes the tag to the first read in position terms.
46
+ */
47
+ static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str)
48
+ {
49
+ bam1_t *swap;
50
+ int i;
51
+ hts_pos_t end;
52
+ uint32_t *cigar;
53
+ str->l = 0;
54
+ if (b1->core.tid != b2->core.tid || b1->core.tid < 0 || b1->core.pos < 0 || b2->core.pos < 0 || b1->core.flag&BAM_FUNMAP || b2->core.flag&BAM_FUNMAP) return; // coordinateless or not on the same chr; skip
55
+ if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate
56
+ kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
57
+ kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
58
+ for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) {
59
+ kputw(bam_cigar_oplen(cigar[i]), str);
60
+ kputc(bam_cigar_opchr(cigar[i]), str);
61
+ }
62
+ end = bam_endpos(b1);
63
+ kputw(b2->core.pos - end, str);
64
+ kputc('T', str);
65
+ kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
66
+ kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
67
+ for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) {
68
+ kputw(bam_cigar_oplen(cigar[i]), str);
69
+ kputc(bam_cigar_opchr(cigar[i]), str);
70
+ }
71
+
72
+ uint8_t* data;
73
+ if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data);
74
+ if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data);
75
+
76
+ bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s);
77
+ }
78
+
79
+ /*
80
+ * What This Program is Supposed To Do:
81
+ * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted
82
+ * alignment.
83
+ *
84
+ * How We Handle Input
85
+ *
86
+ * Secondary and supplementary Reads:
87
+ * -write to output unchanged
88
+ * All Reads:
89
+ * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag
90
+ * single Reads:
91
+ * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0,
92
+ * tid = -1
93
+ * -clear bad flags (PAIRED, MREVERSE, PROPER_PAIR)
94
+ * -set mpos = 0 (1 based), mtid = -1 and isize = 0
95
+ * -write to output
96
+ * Paired Reads:
97
+ * -if read is unmapped and mate is not, set pos and tid to equal that of mate
98
+ * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid
99
+ * -recalculate ISIZE if possible, otherwise set it to 0
100
+ * -optionally clear PROPER_PAIR flag from reads where mapping or orientation
101
+ * indicate this is not possible (Illumina orientation only)
102
+ * -calculate ct and apply to lowest positioned read
103
+ * -write to output
104
+ * Limitations
105
+ * -Does not handle tandem reads
106
+ * -Should mark supplementary reads the same as primary.
107
+ * Notes
108
+ * -CT definition appears to be something else in spec, this was in here before
109
+ * I started tampering with it, anyone know what is going on here? To work
110
+ * around this I have demoted the CT this tool generates to ct.
111
+ */
112
+
113
+ static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) {
114
+ if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) {
115
+ // Set unmapped read's RNAME and POS to those of its mapped mate
116
+ // (recommended best practice, ensures if coord sort will be together)
117
+ dest->core.tid = src->core.tid;
118
+ dest->core.pos = src->core.pos;
119
+ }
120
+ }
121
+
122
+ static void sync_mate_inner(bam1_t* src, bam1_t* dest)
123
+ {
124
+ // sync mate pos information
125
+ dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos;
126
+ // sync flag info
127
+ if (src->core.flag&BAM_FREVERSE)
128
+ dest->core.flag |= BAM_FMREVERSE;
129
+ else
130
+ dest->core.flag &= ~BAM_FMREVERSE;
131
+ if (src->core.flag & BAM_FUNMAP) {
132
+ dest->core.flag |= BAM_FMUNMAP;
133
+ }
134
+ }
135
+
136
+ // Is it plausible that these reads are properly paired?
137
+ // Can't really give definitive answer without checking isize
138
+ static bool plausibly_properly_paired(bam1_t* a, bam1_t* b)
139
+ {
140
+ if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false;
141
+ assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly
142
+
143
+ if (a->core.tid != b->core.tid) return false;
144
+
145
+ bam1_t* first = a;
146
+ bam1_t* second = b;
147
+ hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos;
148
+ hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos;
149
+ if (a_pos > b_pos) {
150
+ first = b;
151
+ second = a;
152
+ } else {
153
+ first = a;
154
+ second = b;
155
+ }
156
+
157
+ if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE))
158
+ return true;
159
+ else
160
+ return false;
161
+ }
162
+
163
+ // Returns 0 on success, -1 on failure.
164
+ static int bam_format_cigar(const bam1_t* b, kstring_t* str)
165
+ {
166
+ // An empty cigar is a special case return "*" rather than ""
167
+ if (b->core.n_cigar == 0) {
168
+ return (kputc('*', str) == EOF) ? -1 : 0;
169
+ }
170
+
171
+ const uint32_t *cigar = bam_get_cigar(b);
172
+ uint32_t i;
173
+
174
+ for (i = 0; i < b->core.n_cigar; ++i) {
175
+ if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1;
176
+ if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1;
177
+ }
178
+
179
+ return 0;
180
+ }
181
+
182
+ // Returns 0 on success, -1 on failure.
183
+ static int sync_mq_mc(bam1_t* src, bam1_t* dest)
184
+ {
185
+ if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped
186
+ // Copy Mate Mapping Quality
187
+ uint32_t mq = src->core.qual;
188
+ uint8_t* data;
189
+ if ((data = bam_aux_get(dest,"MQ")) != NULL) {
190
+ bam_aux_del(dest, data);
191
+ }
192
+
193
+ bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq);
194
+ }
195
+ // Copy mate cigar if either read is mapped
196
+ if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) {
197
+ uint8_t* data_mc;
198
+ if ((data_mc = bam_aux_get(dest,"MC")) != NULL) {
199
+ bam_aux_del(dest, data_mc);
200
+ }
201
+
202
+ // Convert cigar to string
203
+ kstring_t mc = { 0, 0, NULL };
204
+ if (bam_format_cigar(src, &mc) < 0) return -1;
205
+
206
+ bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc));
207
+ free(mc.s);
208
+ }
209
+ return 0;
210
+ }
211
+
212
+ // Copy flags.
213
+ // Returns 0 on success, -1 on failure.
214
+ static int sync_mate(bam1_t* a, bam1_t* b)
215
+ {
216
+ sync_unmapped_pos_inner(a,b);
217
+ sync_unmapped_pos_inner(b,a);
218
+ sync_mate_inner(a,b);
219
+ sync_mate_inner(b,a);
220
+ if (sync_mq_mc(a,b) < 0) return -1;
221
+ if (sync_mq_mc(b,a) < 0) return -1;
222
+ return 0;
223
+ }
224
+
225
+
226
+ static uint32_t calc_mate_score(bam1_t *b)
227
+ {
228
+ uint32_t score = 0;
229
+ uint8_t *qual = bam_get_qual(b);
230
+ int i;
231
+
232
+ for (i = 0; i < b->core.l_qseq; i++) {
233
+ if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
234
+ }
235
+
236
+ return score;
237
+ }
238
+
239
+
240
+ static int add_mate_score(bam1_t *src, bam1_t *dest)
241
+ {
242
+ uint8_t *data_ms;
243
+ uint32_t mate_score = calc_mate_score(src);
244
+
245
+ if ((data_ms = bam_aux_get(dest, "ms")) != NULL) {
246
+ bam_aux_del(dest, data_ms);
247
+ }
248
+
249
+ if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) {
250
+ return -1;
251
+ }
252
+
253
+ return 0;
254
+ }
255
+
256
+ // Completely delete the CIGAR field
257
+ static void clear_cigar(bam1_t *b) {
258
+ memmove(bam_get_cigar(b), bam_get_seq(b),
259
+ b->data + b->l_data - bam_get_seq(b));
260
+ b->l_data -= 4*b->core.n_cigar;
261
+ b->core.n_cigar = 0;
262
+ }
263
+
264
+ // Trim a CIGAR field to end on reference position "end". Remaining bases
265
+ // are turned to soft clips.
266
+ static int bam_trim(bam1_t *b, hts_pos_t end) {
267
+ hts_pos_t pos = b->core.pos;
268
+ int n_cigar = b->core.n_cigar, i;
269
+ uint32_t new_cigar_a[1024];
270
+ uint32_t *new_cigar = new_cigar_a;
271
+ uint32_t *cigar = bam_get_cigar(b);
272
+
273
+ // Find end of alignment or end of ref
274
+ int op = 0, oplen = 0;
275
+ for (i = 0; i < n_cigar; i++) {
276
+ op = bam_cigar_op(cigar[i]);
277
+ oplen = bam_cigar_oplen(cigar[i]);
278
+ if (!(bam_cigar_type(op) & 2))
279
+ continue;
280
+ pos += oplen;
281
+ if (pos > end)
282
+ break;
283
+ }
284
+
285
+ if (i == n_cigar)
286
+ // looks fine already
287
+ return 0;
288
+
289
+ int old_i = i, j = 0;
290
+ // At worst we grow by 1 element (eg 100M -> 70M30S)
291
+ if (n_cigar-i >= 1024-1) {
292
+ new_cigar = malloc(4*(n_cigar-i+1));
293
+ if (!new_cigar)
294
+ return -1;
295
+ }
296
+
297
+ // We fill out to new_cigar from here on.
298
+ if (pos-oplen < end) {
299
+ // Partial CIGAR op? Split existing tag.
300
+ cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op);
301
+ new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP);
302
+ } else if (pos > end) {
303
+ // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0
304
+ b->core.flag |= BAM_FUNMAP;
305
+ b->core.flag &= ~BAM_FPROPER_PAIR;
306
+ } else {
307
+ // CIGAR op started on the trim junction
308
+ new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP);
309
+ }
310
+
311
+ // Replace trailing elements.
312
+ for (i++; i < n_cigar; i++) {
313
+ op = bam_cigar_op(cigar[i]);
314
+ oplen = bam_cigar_oplen(cigar[i]);
315
+ if (op == BAM_CHARD_CLIP) {
316
+ new_cigar[j++] = cigar[i];
317
+ } else {
318
+ new_cigar[j-1] =
319
+ bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen,
320
+ BAM_CSOFT_CLIP);
321
+ }
322
+ }
323
+
324
+ // We now have cigar[0..old_i-1] for existing CIGAR
325
+ // and new_cigar[0..j-1] for new CIGAR trailing component.
326
+
327
+ if (old_i+j == n_cigar) {
328
+ // Fits and no data move needed
329
+ memcpy(&cigar[old_i], new_cigar, j*4);
330
+ } else {
331
+ uint8_t *seq_old = bam_get_seq(b);
332
+ uint8_t *aux_end = b->data + b->l_data;
333
+ int nshift;
334
+ if (old_i+j < n_cigar) {
335
+ // Smaller, and can move data down
336
+ nshift = -4*(n_cigar - (old_i+j));
337
+ } else {
338
+ // Bigger, so grow BAM and move data up
339
+ nshift = 4*(old_i+j - n_cigar);
340
+ // FIXME: make htslib's sam_realloc_bam_data public
341
+ if (b->l_data + nshift > b->m_data) {
342
+ uint8_t *new_data = realloc(b->data, b->l_data + nshift);
343
+ if (!new_data) {
344
+ if (new_cigar != new_cigar_a)
345
+ free(new_cigar);
346
+ return -1;
347
+ }
348
+ b->m_data = b->l_data + nshift;
349
+ if (b->data != new_data) {
350
+ b->data = new_data;
351
+ seq_old = bam_get_seq(b);
352
+ aux_end = b->data + b->l_data;
353
+ cigar = bam_get_cigar(b);
354
+ }
355
+ }
356
+ }
357
+ memmove(seq_old+nshift, seq_old, aux_end - seq_old);
358
+ b->l_data += nshift;
359
+ memcpy(&cigar[old_i], new_cigar, j*4);
360
+ b->core.n_cigar = old_i+j;
361
+ }
362
+
363
+ if (new_cigar != new_cigar_a)
364
+ free(new_cigar);
365
+
366
+ return 0;
367
+ }
368
+
369
+ // Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux"
370
+ // keywords for the bam sanitizer.
371
+ int bam_sanitize_options(const char *str) {
372
+ int opt = 0;
373
+
374
+ while (str && *str) {
375
+ const char *str_start;
376
+ while(*str && *str == ',')
377
+ str++;
378
+
379
+ for (str_start = str; *str && *str != ','; str++);
380
+ int len = str - str_start;
381
+ if (strncmp(str_start, "all", 3) == 0 || *str_start == '*')
382
+ opt = FIX_ALL;
383
+ else if (strncmp(str_start, "none", 4) == 0 ||
384
+ strncmp(str_start, "off", 3) == 0)
385
+ opt = 0;
386
+ else if (strncmp(str_start, "on", 2) == 0)
387
+ // default for position sorted data
388
+ opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX;
389
+ else if (strncmp(str_start, "pos", 3) == 0)
390
+ opt |= FIX_POS;
391
+ else if (strncmp(str_start, "mqual", 5) == 0)
392
+ opt |= FIX_MQUAL;
393
+ else if (strncmp(str_start, "unmap", 5) == 0)
394
+ opt |= FIX_UNMAP;
395
+ else if (strncmp(str_start, "cigar", 5) == 0)
396
+ opt |= FIX_CIGAR;
397
+ else if (strncmp(str_start, "aux", 3) == 0)
398
+ opt |= FIX_AUX;
399
+ else {
400
+ print_error("sanitize", "Unrecognised keyword %.*s\n",
401
+ len, str_start);
402
+ return -1;
403
+ }
404
+ }
405
+
406
+ return opt;
407
+ }
408
+
409
+ int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) {
410
+ if ((flags & FIX_POS) && b->core.tid < 0) {
411
+ // RNAME * => pos 0. NB can break alignment chr/pos sort order
412
+ b->core.pos = -1;
413
+ if (flags & FIX_UNMAP)
414
+ b->core.flag |= BAM_FUNMAP;
415
+ }
416
+
417
+ if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) {
418
+ // Mapped => unmapped correction
419
+ if (b->core.pos < 0 && (flags & FIX_UNMAP)) {
420
+ b->core.flag |= BAM_FUNMAP;
421
+ } else {
422
+ hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid);
423
+ if (b->core.pos >= rlen && (flags & FIX_UNMAP)) {
424
+ b->core.flag |= BAM_FUNMAP;
425
+ if (flags & FIX_POS)
426
+ b->core.tid = b->core.pos = -1;
427
+ } else if ((cur_end = bam_endpos(b)) > rlen) {
428
+ if (bam_trim(b, rlen) < 0)
429
+ return -1;
430
+ }
431
+ }
432
+ }
433
+
434
+ if (b->core.flag & BAM_FUNMAP) {
435
+ // Unmapped -> cigar/qual correctoins
436
+ if ((flags & FIX_CIGAR) && b->core.n_cigar > 0)
437
+ clear_cigar(b);
438
+
439
+ if (flags & FIX_MQUAL)
440
+ b->core.qual = 0;
441
+
442
+ // Remove NM, MD, CG, SM tags.
443
+ if (flags & FIX_AUX) {
444
+ uint8_t *from = bam_aux_first(b);
445
+ uint8_t *end = b->data + b->l_data;
446
+ uint8_t *to = from ? from-2 : end;
447
+
448
+ #define XTAG(a) (((a)[0]<<8) + (a)[1])
449
+ while (from) {
450
+ uint8_t *next = bam_aux_next(b, from);
451
+ if (!next && errno != ENOENT)
452
+ return -1;
453
+
454
+ // Keep tag unless one of a specific set.
455
+ // NB "to" always points to an aux tag start, while
456
+ // "from" is after key.
457
+ from -= 2;
458
+ int key = (int)from[0]<<8 | from[1];
459
+ if (key != XTAG("NM") && key != XTAG("MD") &&
460
+ key != XTAG("CG") && key != XTAG("SM")) {
461
+ ptrdiff_t len = (next ? next-2 : end) - from;
462
+ if (from != to)
463
+ memmove(to, from, len);
464
+ to += len;
465
+ }
466
+ from = next;
467
+ }
468
+ b->l_data = to - b->data;
469
+ }
470
+ }
471
+
472
+ return 0;
473
+ }
474
+
475
+ // currently, this function ONLY works if each read has one hit
476
+ static int bam_mating_core(samFile *in, samFile *out, int remove_reads,
477
+ int proper_pair_check, int add_ct,
478
+ int do_mate_scoring, char *arg_list, int no_pg,
479
+ int sanitize_flags)
480
+ {
481
+ sam_hdr_t *header;
482
+ bam1_t *b[2] = { NULL, NULL };
483
+ int curr, has_prev, result;
484
+ hts_pos_t pre_end = 0, cur_end = 0;
485
+ kstring_t str = KS_INITIALIZE;
486
+
487
+ header = sam_hdr_read(in);
488
+ if (header == NULL) {
489
+ fprintf(stderr, "[bam_mating_core] ERROR: Couldn't read header\n");
490
+ return 1;
491
+ }
492
+
493
+ // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted.
494
+ if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) {
495
+ fprintf(stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n");
496
+ goto fail;
497
+ }
498
+ ks_free(&str);
499
+
500
+ if (!no_pg && sam_hdr_add_pg(header, "samtools",
501
+ "VN", samtools_version(),
502
+ arg_list ? "CL": NULL,
503
+ arg_list ? arg_list : NULL,
504
+ NULL))
505
+ goto fail;
506
+
507
+ if (sam_hdr_write(out, header) < 0) goto write_fail;
508
+
509
+ b[0] = bam_init1();
510
+ b[1] = bam_init1();
511
+ curr = 0; has_prev = 0;
512
+ while ((result = sam_read1(in, header, b[curr])) >= 0) {
513
+ bam1_t *cur = b[curr], *pre = b[1-curr];
514
+ if (bam_sanitize(header, cur, sanitize_flags) < 0)
515
+ goto fail;
516
+ if (cur->core.flag & BAM_FSECONDARY)
517
+ {
518
+ if ( !remove_reads ) {
519
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
520
+ }
521
+ continue; // skip secondary alignments
522
+ }
523
+ if (cur->core.flag & BAM_FSUPPLEMENTARY)
524
+ {
525
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
526
+ continue; // pass supplementary alignments through unchanged (TODO:make them match read they came from)
527
+ }
528
+ if ((cur->core.flag&BAM_FUNMAP) == 0) // If mapped calculate end
529
+ {
530
+ cur_end = bam_endpos(cur);
531
+ }
532
+
533
+ if (has_prev) { // do we have a pair of reads to examine?
534
+ if (strcmp(bam_get_qname(cur), bam_get_qname(pre)) == 0) { // identical pair name
535
+ pre->core.flag |= BAM_FPAIRED;
536
+ cur->core.flag |= BAM_FPAIRED;
537
+ if (sync_mate(pre, cur)) goto fail;
538
+
539
+ if (pre->core.tid == cur->core.tid && !(cur->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))
540
+ && !(pre->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))) // if safe set TLEN/ISIZE
541
+ {
542
+ hts_pos_t cur5, pre5;
543
+ cur5 = (cur->core.flag&BAM_FREVERSE)? cur_end : cur->core.pos;
544
+ pre5 = (pre->core.flag&BAM_FREVERSE)? pre_end : pre->core.pos;
545
+ cur->core.isize = pre5 - cur5; pre->core.isize = cur5 - pre5;
546
+ } else cur->core.isize = pre->core.isize = 0;
547
+ if (add_ct) bam_template_cigar(pre, cur, &str);
548
+ // TODO: Add code to properly check if read is in a proper pair based on ISIZE distribution
549
+ if (proper_pair_check && !plausibly_properly_paired(pre,cur)) {
550
+ pre->core.flag &= ~BAM_FPROPER_PAIR;
551
+ cur->core.flag &= ~BAM_FPROPER_PAIR;
552
+ }
553
+
554
+ if (do_mate_scoring) {
555
+ if ((add_mate_score(pre, cur) == -1) || (add_mate_score(cur, pre) == -1)) {
556
+ fprintf(stderr, "[bam_mating_core] ERROR: unable to add mate score.\n");
557
+ goto fail;
558
+ }
559
+ }
560
+
561
+ // Write out result
562
+ if ( !remove_reads ) {
563
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
564
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
565
+ } else {
566
+ // If we have to remove reads make sure we do it in a way that doesn't create orphans with bad flags
567
+ if(pre->core.flag&BAM_FUNMAP) cur->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
568
+ if(cur->core.flag&BAM_FUNMAP) pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
569
+ if(!(pre->core.flag&BAM_FUNMAP)) {
570
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
571
+ }
572
+ if(!(cur->core.flag&BAM_FUNMAP)) {
573
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
574
+ }
575
+ }
576
+ has_prev = 0;
577
+ } else { // unpaired? clear bad info and write it out
578
+ pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0;
579
+ pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
580
+ if ( !remove_reads || !(pre->core.flag&BAM_FUNMAP) ) {
581
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
582
+ }
583
+ }
584
+ } else has_prev = 1;
585
+ curr = 1 - curr;
586
+ pre_end = cur_end;
587
+ }
588
+ if (result < -1) goto read_fail;
589
+ if (has_prev && !remove_reads) { // If we still have a BAM in the buffer it must be unpaired
590
+ bam1_t *pre = b[1-curr];
591
+ if (pre->core.tid < 0 || pre->core.pos < 0 || pre->core.flag&BAM_FUNMAP) { // If unmapped
592
+ pre->core.flag |= BAM_FUNMAP;
593
+ pre->core.tid = -1;
594
+ pre->core.pos = -1;
595
+ }
596
+ pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0;
597
+ pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
598
+
599
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
600
+ }
601
+ sam_hdr_destroy(header);
602
+ bam_destroy1(b[0]);
603
+ bam_destroy1(b[1]);
604
+ ks_free(&str);
605
+ return 0;
606
+
607
+ read_fail:
608
+ print_error("fixmate", "Couldn't read from input file");
609
+ goto fail;
610
+
611
+ write_fail:
612
+ print_error_errno("fixmate", "Couldn't write to output file");
613
+ fail:
614
+ sam_hdr_destroy(header);
615
+ bam_destroy1(b[0]);
616
+ bam_destroy1(b[1]);
617
+ ks_free(&str);
618
+ return 1;
619
+ }
620
+
621
+ void usage(FILE* where)
622
+ {
623
+ fprintf(where,
624
+ "Usage: samtools fixmate <in.nameSrt.bam> <out.nameSrt.bam>\n"
625
+ "Options:\n"
626
+ " -r Remove unmapped reads and secondary alignments\n"
627
+ " -p Disable FR proper pair check\n"
628
+ " -c Add template cigar ct tag\n"
629
+ " -m Add mate score tag\n"
630
+ " -u Uncompressed output\n"
631
+ " -z, --sanitize FLAG[,FLAG]\n"
632
+ " Sanitize alignment fields [defaults to all types]\n"
633
+ " --no-PG do not add a PG line\n");
634
+
635
+ sam_global_opt_help(where, "-.O..@-.");
636
+
637
+ fprintf(where,
638
+ "\n"
639
+ "As elsewhere in samtools, use '-' as the filename for stdin/stdout. The input\n"
640
+ "file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n"
641
+ "input is not accepted.\n");
642
+ }
643
+
644
+ int bam_mating(int argc, char *argv[])
645
+ {
646
+ htsThreadPool p = {NULL, 0};
647
+ samFile *in = NULL, *out = NULL;
648
+ int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1,
649
+ mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL;
650
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
651
+ char wmode[4] = {'w', 'b', 0, 0};
652
+ static const struct option lopts[] = {
653
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
654
+ {"no-PG", no_argument, NULL, 1},
655
+ { NULL, 0, NULL, 0 }
656
+ };
657
+ char *arg_list = NULL;
658
+
659
+ // parse args
660
+ if (argc == 1) { usage(stdout); return 0; }
661
+ while ((c = getopt_long(argc, argv, "rpcmO:@:uz:", lopts, NULL)) >= 0) {
662
+ switch (c) {
663
+ case 'r': remove_reads = 1; break;
664
+ case 'p': proper_pair_check = 0; break;
665
+ case 'c': add_ct = 1; break;
666
+ case 'm': mate_score = 1; break;
667
+ case 'u': wmode[2] = '0'; break;
668
+ case 1: no_pg = 1; break;
669
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
670
+ /* else fall-through */
671
+ case '?': usage(stderr); goto fail;
672
+ case 'z':
673
+ if ((sanitize_flags = bam_sanitize_options(optarg)) < 0)
674
+ exit(1);
675
+ break;
676
+ }
677
+ }
678
+ if (optind+1 >= argc) { usage(stderr); goto fail; }
679
+
680
+ if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
681
+ goto fail;
682
+
683
+ // init
684
+ if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
685
+ print_error_errno("fixmate", "cannot open input file");
686
+ goto fail;
687
+ }
688
+ sam_open_mode(wmode+1, argv[optind+1], NULL);
689
+ if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) {
690
+ print_error_errno("fixmate", "cannot open output file");
691
+ goto fail;
692
+ }
693
+
694
+ if (ga.nthreads > 0) {
695
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
696
+ fprintf(stderr, "Error creating thread pool\n");
697
+ goto fail;
698
+ }
699
+ hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
700
+ hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
701
+ }
702
+
703
+ // run
704
+ res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct,
705
+ mate_score, arg_list, no_pg, sanitize_flags);
706
+
707
+ // cleanup
708
+ sam_close(in);
709
+ if (sam_close(out) < 0) {
710
+ fprintf(stderr, "[bam_mating] error while closing output file\n");
711
+ res = 1;
712
+ }
713
+
714
+ if (p.pool) hts_tpool_destroy(p.pool);
715
+ free(arg_list);
716
+ sam_global_args_free(&ga);
717
+ return res;
718
+
719
+ fail:
720
+ if (in) sam_close(in);
721
+ if (out) sam_close(out);
722
+ if (p.pool) hts_tpool_destroy(p.pool);
723
+ free(arg_list);
724
+ sam_global_args_free(&ga);
725
+ return 1;
726
+ }
727
+
728
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c.pysam.c ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_mate.c -- fix mate pairing information and clean up flags.
4
+
5
+ Copyright (C) 2009, 2011-2017, 2019, 2022 Genome Research Ltd.
6
+ Portions copyright (C) 2011 Broad Institute.
7
+ Portions copyright (C) 2012 Peter Cock, The James Hutton Institute.
8
+
9
+ Author: Heng Li <lh3@sanger.ac.uk>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notices and this permission notice shall be included in
19
+ all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
+ DEALINGS IN THE SOFTWARE. */
28
+
29
+ #include <config.h>
30
+
31
+ #include <assert.h>
32
+ #include <stdbool.h>
33
+ #include <stdlib.h>
34
+ #include <string.h>
35
+ #include <unistd.h>
36
+ #include "htslib/thread_pool.h"
37
+ #include "sam_opts.h"
38
+ #include "htslib/kstring.h"
39
+ #include "htslib/sam.h"
40
+ #include "samtools.h"
41
+
42
+
43
+ #define MD_MIN_QUALITY 15
44
+
45
+ /*
46
+ * This function calculates ct tag for two bams, it assumes they are from the same template and
47
+ * writes the tag to the first read in position terms.
48
+ */
49
+ static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str)
50
+ {
51
+ bam1_t *swap;
52
+ int i;
53
+ hts_pos_t end;
54
+ uint32_t *cigar;
55
+ str->l = 0;
56
+ if (b1->core.tid != b2->core.tid || b1->core.tid < 0 || b1->core.pos < 0 || b2->core.pos < 0 || b1->core.flag&BAM_FUNMAP || b2->core.flag&BAM_FUNMAP) return; // coordinateless or not on the same chr; skip
57
+ if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate
58
+ kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
59
+ kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
60
+ for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) {
61
+ kputw(bam_cigar_oplen(cigar[i]), str);
62
+ kputc(bam_cigar_opchr(cigar[i]), str);
63
+ }
64
+ end = bam_endpos(b1);
65
+ kputw(b2->core.pos - end, str);
66
+ kputc('T', str);
67
+ kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
68
+ kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
69
+ for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) {
70
+ kputw(bam_cigar_oplen(cigar[i]), str);
71
+ kputc(bam_cigar_opchr(cigar[i]), str);
72
+ }
73
+
74
+ uint8_t* data;
75
+ if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data);
76
+ if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data);
77
+
78
+ bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s);
79
+ }
80
+
81
+ /*
82
+ * What This Program is Supposed To Do:
83
+ * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted
84
+ * alignment.
85
+ *
86
+ * How We Handle Input
87
+ *
88
+ * Secondary and supplementary Reads:
89
+ * -write to output unchanged
90
+ * All Reads:
91
+ * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag
92
+ * single Reads:
93
+ * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0,
94
+ * tid = -1
95
+ * -clear bad flags (PAIRED, MREVERSE, PROPER_PAIR)
96
+ * -set mpos = 0 (1 based), mtid = -1 and isize = 0
97
+ * -write to output
98
+ * Paired Reads:
99
+ * -if read is unmapped and mate is not, set pos and tid to equal that of mate
100
+ * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid
101
+ * -recalculate ISIZE if possible, otherwise set it to 0
102
+ * -optionally clear PROPER_PAIR flag from reads where mapping or orientation
103
+ * indicate this is not possible (Illumina orientation only)
104
+ * -calculate ct and apply to lowest positioned read
105
+ * -write to output
106
+ * Limitations
107
+ * -Does not handle tandem reads
108
+ * -Should mark supplementary reads the same as primary.
109
+ * Notes
110
+ * -CT definition appears to be something else in spec, this was in here before
111
+ * I started tampering with it, anyone know what is going on here? To work
112
+ * around this I have demoted the CT this tool generates to ct.
113
+ */
114
+
115
+ static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) {
116
+ if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) {
117
+ // Set unmapped read's RNAME and POS to those of its mapped mate
118
+ // (recommended best practice, ensures if coord sort will be together)
119
+ dest->core.tid = src->core.tid;
120
+ dest->core.pos = src->core.pos;
121
+ }
122
+ }
123
+
124
+ static void sync_mate_inner(bam1_t* src, bam1_t* dest)
125
+ {
126
+ // sync mate pos information
127
+ dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos;
128
+ // sync flag info
129
+ if (src->core.flag&BAM_FREVERSE)
130
+ dest->core.flag |= BAM_FMREVERSE;
131
+ else
132
+ dest->core.flag &= ~BAM_FMREVERSE;
133
+ if (src->core.flag & BAM_FUNMAP) {
134
+ dest->core.flag |= BAM_FMUNMAP;
135
+ }
136
+ }
137
+
138
+ // Is it plausible that these reads are properly paired?
139
+ // Can't really give definitive answer without checking isize
140
+ static bool plausibly_properly_paired(bam1_t* a, bam1_t* b)
141
+ {
142
+ if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false;
143
+ assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly
144
+
145
+ if (a->core.tid != b->core.tid) return false;
146
+
147
+ bam1_t* first = a;
148
+ bam1_t* second = b;
149
+ hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos;
150
+ hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos;
151
+ if (a_pos > b_pos) {
152
+ first = b;
153
+ second = a;
154
+ } else {
155
+ first = a;
156
+ second = b;
157
+ }
158
+
159
+ if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE))
160
+ return true;
161
+ else
162
+ return false;
163
+ }
164
+
165
+ // Returns 0 on success, -1 on failure.
166
+ static int bam_format_cigar(const bam1_t* b, kstring_t* str)
167
+ {
168
+ // An empty cigar is a special case return "*" rather than ""
169
+ if (b->core.n_cigar == 0) {
170
+ return (kputc('*', str) == EOF) ? -1 : 0;
171
+ }
172
+
173
+ const uint32_t *cigar = bam_get_cigar(b);
174
+ uint32_t i;
175
+
176
+ for (i = 0; i < b->core.n_cigar; ++i) {
177
+ if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1;
178
+ if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1;
179
+ }
180
+
181
+ return 0;
182
+ }
183
+
184
+ // Returns 0 on success, -1 on failure.
185
+ static int sync_mq_mc(bam1_t* src, bam1_t* dest)
186
+ {
187
+ if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped
188
+ // Copy Mate Mapping Quality
189
+ uint32_t mq = src->core.qual;
190
+ uint8_t* data;
191
+ if ((data = bam_aux_get(dest,"MQ")) != NULL) {
192
+ bam_aux_del(dest, data);
193
+ }
194
+
195
+ bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq);
196
+ }
197
+ // Copy mate cigar if either read is mapped
198
+ if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) {
199
+ uint8_t* data_mc;
200
+ if ((data_mc = bam_aux_get(dest,"MC")) != NULL) {
201
+ bam_aux_del(dest, data_mc);
202
+ }
203
+
204
+ // Convert cigar to string
205
+ kstring_t mc = { 0, 0, NULL };
206
+ if (bam_format_cigar(src, &mc) < 0) return -1;
207
+
208
+ bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc));
209
+ free(mc.s);
210
+ }
211
+ return 0;
212
+ }
213
+
214
+ // Copy flags.
215
+ // Returns 0 on success, -1 on failure.
216
+ static int sync_mate(bam1_t* a, bam1_t* b)
217
+ {
218
+ sync_unmapped_pos_inner(a,b);
219
+ sync_unmapped_pos_inner(b,a);
220
+ sync_mate_inner(a,b);
221
+ sync_mate_inner(b,a);
222
+ if (sync_mq_mc(a,b) < 0) return -1;
223
+ if (sync_mq_mc(b,a) < 0) return -1;
224
+ return 0;
225
+ }
226
+
227
+
228
+ static uint32_t calc_mate_score(bam1_t *b)
229
+ {
230
+ uint32_t score = 0;
231
+ uint8_t *qual = bam_get_qual(b);
232
+ int i;
233
+
234
+ for (i = 0; i < b->core.l_qseq; i++) {
235
+ if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
236
+ }
237
+
238
+ return score;
239
+ }
240
+
241
+
242
+ static int add_mate_score(bam1_t *src, bam1_t *dest)
243
+ {
244
+ uint8_t *data_ms;
245
+ uint32_t mate_score = calc_mate_score(src);
246
+
247
+ if ((data_ms = bam_aux_get(dest, "ms")) != NULL) {
248
+ bam_aux_del(dest, data_ms);
249
+ }
250
+
251
+ if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) {
252
+ return -1;
253
+ }
254
+
255
+ return 0;
256
+ }
257
+
258
+ // Completely delete the CIGAR field
259
+ static void clear_cigar(bam1_t *b) {
260
+ memmove(bam_get_cigar(b), bam_get_seq(b),
261
+ b->data + b->l_data - bam_get_seq(b));
262
+ b->l_data -= 4*b->core.n_cigar;
263
+ b->core.n_cigar = 0;
264
+ }
265
+
266
+ // Trim a CIGAR field to end on reference position "end". Remaining bases
267
+ // are turned to soft clips.
268
+ static int bam_trim(bam1_t *b, hts_pos_t end) {
269
+ hts_pos_t pos = b->core.pos;
270
+ int n_cigar = b->core.n_cigar, i;
271
+ uint32_t new_cigar_a[1024];
272
+ uint32_t *new_cigar = new_cigar_a;
273
+ uint32_t *cigar = bam_get_cigar(b);
274
+
275
+ // Find end of alignment or end of ref
276
+ int op = 0, oplen = 0;
277
+ for (i = 0; i < n_cigar; i++) {
278
+ op = bam_cigar_op(cigar[i]);
279
+ oplen = bam_cigar_oplen(cigar[i]);
280
+ if (!(bam_cigar_type(op) & 2))
281
+ continue;
282
+ pos += oplen;
283
+ if (pos > end)
284
+ break;
285
+ }
286
+
287
+ if (i == n_cigar)
288
+ // looks fine already
289
+ return 0;
290
+
291
+ int old_i = i, j = 0;
292
+ // At worst we grow by 1 element (eg 100M -> 70M30S)
293
+ if (n_cigar-i >= 1024-1) {
294
+ new_cigar = malloc(4*(n_cigar-i+1));
295
+ if (!new_cigar)
296
+ return -1;
297
+ }
298
+
299
+ // We fill out to new_cigar from here on.
300
+ if (pos-oplen < end) {
301
+ // Partial CIGAR op? Split existing tag.
302
+ cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op);
303
+ new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP);
304
+ } else if (pos > end) {
305
+ // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0
306
+ b->core.flag |= BAM_FUNMAP;
307
+ b->core.flag &= ~BAM_FPROPER_PAIR;
308
+ } else {
309
+ // CIGAR op started on the trim junction
310
+ new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP);
311
+ }
312
+
313
+ // Replace trailing elements.
314
+ for (i++; i < n_cigar; i++) {
315
+ op = bam_cigar_op(cigar[i]);
316
+ oplen = bam_cigar_oplen(cigar[i]);
317
+ if (op == BAM_CHARD_CLIP) {
318
+ new_cigar[j++] = cigar[i];
319
+ } else {
320
+ new_cigar[j-1] =
321
+ bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen,
322
+ BAM_CSOFT_CLIP);
323
+ }
324
+ }
325
+
326
+ // We now have cigar[0..old_i-1] for existing CIGAR
327
+ // and new_cigar[0..j-1] for new CIGAR trailing component.
328
+
329
+ if (old_i+j == n_cigar) {
330
+ // Fits and no data move needed
331
+ memcpy(&cigar[old_i], new_cigar, j*4);
332
+ } else {
333
+ uint8_t *seq_old = bam_get_seq(b);
334
+ uint8_t *aux_end = b->data + b->l_data;
335
+ int nshift;
336
+ if (old_i+j < n_cigar) {
337
+ // Smaller, and can move data down
338
+ nshift = -4*(n_cigar - (old_i+j));
339
+ } else {
340
+ // Bigger, so grow BAM and move data up
341
+ nshift = 4*(old_i+j - n_cigar);
342
+ // FIXME: make htslib's sam_realloc_bam_data public
343
+ if (b->l_data + nshift > b->m_data) {
344
+ uint8_t *new_data = realloc(b->data, b->l_data + nshift);
345
+ if (!new_data) {
346
+ if (new_cigar != new_cigar_a)
347
+ free(new_cigar);
348
+ return -1;
349
+ }
350
+ b->m_data = b->l_data + nshift;
351
+ if (b->data != new_data) {
352
+ b->data = new_data;
353
+ seq_old = bam_get_seq(b);
354
+ aux_end = b->data + b->l_data;
355
+ cigar = bam_get_cigar(b);
356
+ }
357
+ }
358
+ }
359
+ memmove(seq_old+nshift, seq_old, aux_end - seq_old);
360
+ b->l_data += nshift;
361
+ memcpy(&cigar[old_i], new_cigar, j*4);
362
+ b->core.n_cigar = old_i+j;
363
+ }
364
+
365
+ if (new_cigar != new_cigar_a)
366
+ free(new_cigar);
367
+
368
+ return 0;
369
+ }
370
+
371
+ // Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux"
372
+ // keywords for the bam sanitizer.
373
+ int bam_sanitize_options(const char *str) {
374
+ int opt = 0;
375
+
376
+ while (str && *str) {
377
+ const char *str_start;
378
+ while(*str && *str == ',')
379
+ str++;
380
+
381
+ for (str_start = str; *str && *str != ','; str++);
382
+ int len = str - str_start;
383
+ if (strncmp(str_start, "all", 3) == 0 || *str_start == '*')
384
+ opt = FIX_ALL;
385
+ else if (strncmp(str_start, "none", 4) == 0 ||
386
+ strncmp(str_start, "off", 3) == 0)
387
+ opt = 0;
388
+ else if (strncmp(str_start, "on", 2) == 0)
389
+ // default for position sorted data
390
+ opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX;
391
+ else if (strncmp(str_start, "pos", 3) == 0)
392
+ opt |= FIX_POS;
393
+ else if (strncmp(str_start, "mqual", 5) == 0)
394
+ opt |= FIX_MQUAL;
395
+ else if (strncmp(str_start, "unmap", 5) == 0)
396
+ opt |= FIX_UNMAP;
397
+ else if (strncmp(str_start, "cigar", 5) == 0)
398
+ opt |= FIX_CIGAR;
399
+ else if (strncmp(str_start, "aux", 3) == 0)
400
+ opt |= FIX_AUX;
401
+ else {
402
+ print_error("sanitize", "Unrecognised keyword %.*s\n",
403
+ len, str_start);
404
+ return -1;
405
+ }
406
+ }
407
+
408
+ return opt;
409
+ }
410
+
411
+ int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) {
412
+ if ((flags & FIX_POS) && b->core.tid < 0) {
413
+ // RNAME * => pos 0. NB can break alignment chr/pos sort order
414
+ b->core.pos = -1;
415
+ if (flags & FIX_UNMAP)
416
+ b->core.flag |= BAM_FUNMAP;
417
+ }
418
+
419
+ if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) {
420
+ // Mapped => unmapped correction
421
+ if (b->core.pos < 0 && (flags & FIX_UNMAP)) {
422
+ b->core.flag |= BAM_FUNMAP;
423
+ } else {
424
+ hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid);
425
+ if (b->core.pos >= rlen && (flags & FIX_UNMAP)) {
426
+ b->core.flag |= BAM_FUNMAP;
427
+ if (flags & FIX_POS)
428
+ b->core.tid = b->core.pos = -1;
429
+ } else if ((cur_end = bam_endpos(b)) > rlen) {
430
+ if (bam_trim(b, rlen) < 0)
431
+ return -1;
432
+ }
433
+ }
434
+ }
435
+
436
+ if (b->core.flag & BAM_FUNMAP) {
437
+ // Unmapped -> cigar/qual correctoins
438
+ if ((flags & FIX_CIGAR) && b->core.n_cigar > 0)
439
+ clear_cigar(b);
440
+
441
+ if (flags & FIX_MQUAL)
442
+ b->core.qual = 0;
443
+
444
+ // Remove NM, MD, CG, SM tags.
445
+ if (flags & FIX_AUX) {
446
+ uint8_t *from = bam_aux_first(b);
447
+ uint8_t *end = b->data + b->l_data;
448
+ uint8_t *to = from ? from-2 : end;
449
+
450
+ #define XTAG(a) (((a)[0]<<8) + (a)[1])
451
+ while (from) {
452
+ uint8_t *next = bam_aux_next(b, from);
453
+ if (!next && errno != ENOENT)
454
+ return -1;
455
+
456
+ // Keep tag unless one of a specific set.
457
+ // NB "to" always points to an aux tag start, while
458
+ // "from" is after key.
459
+ from -= 2;
460
+ int key = (int)from[0]<<8 | from[1];
461
+ if (key != XTAG("NM") && key != XTAG("MD") &&
462
+ key != XTAG("CG") && key != XTAG("SM")) {
463
+ ptrdiff_t len = (next ? next-2 : end) - from;
464
+ if (from != to)
465
+ memmove(to, from, len);
466
+ to += len;
467
+ }
468
+ from = next;
469
+ }
470
+ b->l_data = to - b->data;
471
+ }
472
+ }
473
+
474
+ return 0;
475
+ }
476
+
477
+ // currently, this function ONLY works if each read has one hit
478
+ static int bam_mating_core(samFile *in, samFile *out, int remove_reads,
479
+ int proper_pair_check, int add_ct,
480
+ int do_mate_scoring, char *arg_list, int no_pg,
481
+ int sanitize_flags)
482
+ {
483
+ sam_hdr_t *header;
484
+ bam1_t *b[2] = { NULL, NULL };
485
+ int curr, has_prev, result;
486
+ hts_pos_t pre_end = 0, cur_end = 0;
487
+ kstring_t str = KS_INITIALIZE;
488
+
489
+ header = sam_hdr_read(in);
490
+ if (header == NULL) {
491
+ fprintf(samtools_stderr, "[bam_mating_core] ERROR: Couldn't read header\n");
492
+ return 1;
493
+ }
494
+
495
+ // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted.
496
+ if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) {
497
+ fprintf(samtools_stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n");
498
+ goto fail;
499
+ }
500
+ ks_free(&str);
501
+
502
+ if (!no_pg && sam_hdr_add_pg(header, "samtools",
503
+ "VN", samtools_version(),
504
+ arg_list ? "CL": NULL,
505
+ arg_list ? arg_list : NULL,
506
+ NULL))
507
+ goto fail;
508
+
509
+ if (sam_hdr_write(out, header) < 0) goto write_fail;
510
+
511
+ b[0] = bam_init1();
512
+ b[1] = bam_init1();
513
+ curr = 0; has_prev = 0;
514
+ while ((result = sam_read1(in, header, b[curr])) >= 0) {
515
+ bam1_t *cur = b[curr], *pre = b[1-curr];
516
+ if (bam_sanitize(header, cur, sanitize_flags) < 0)
517
+ goto fail;
518
+ if (cur->core.flag & BAM_FSECONDARY)
519
+ {
520
+ if ( !remove_reads ) {
521
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
522
+ }
523
+ continue; // skip secondary alignments
524
+ }
525
+ if (cur->core.flag & BAM_FSUPPLEMENTARY)
526
+ {
527
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
528
+ continue; // pass supplementary alignments through unchanged (TODO:make them match read they came from)
529
+ }
530
+ if ((cur->core.flag&BAM_FUNMAP) == 0) // If mapped calculate end
531
+ {
532
+ cur_end = bam_endpos(cur);
533
+ }
534
+
535
+ if (has_prev) { // do we have a pair of reads to examine?
536
+ if (strcmp(bam_get_qname(cur), bam_get_qname(pre)) == 0) { // identical pair name
537
+ pre->core.flag |= BAM_FPAIRED;
538
+ cur->core.flag |= BAM_FPAIRED;
539
+ if (sync_mate(pre, cur)) goto fail;
540
+
541
+ if (pre->core.tid == cur->core.tid && !(cur->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))
542
+ && !(pre->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))) // if safe set TLEN/ISIZE
543
+ {
544
+ hts_pos_t cur5, pre5;
545
+ cur5 = (cur->core.flag&BAM_FREVERSE)? cur_end : cur->core.pos;
546
+ pre5 = (pre->core.flag&BAM_FREVERSE)? pre_end : pre->core.pos;
547
+ cur->core.isize = pre5 - cur5; pre->core.isize = cur5 - pre5;
548
+ } else cur->core.isize = pre->core.isize = 0;
549
+ if (add_ct) bam_template_cigar(pre, cur, &str);
550
+ // TODO: Add code to properly check if read is in a proper pair based on ISIZE distribution
551
+ if (proper_pair_check && !plausibly_properly_paired(pre,cur)) {
552
+ pre->core.flag &= ~BAM_FPROPER_PAIR;
553
+ cur->core.flag &= ~BAM_FPROPER_PAIR;
554
+ }
555
+
556
+ if (do_mate_scoring) {
557
+ if ((add_mate_score(pre, cur) == -1) || (add_mate_score(cur, pre) == -1)) {
558
+ fprintf(samtools_stderr, "[bam_mating_core] ERROR: unable to add mate score.\n");
559
+ goto fail;
560
+ }
561
+ }
562
+
563
+ // Write out result
564
+ if ( !remove_reads ) {
565
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
566
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
567
+ } else {
568
+ // If we have to remove reads make sure we do it in a way that doesn't create orphans with bad flags
569
+ if(pre->core.flag&BAM_FUNMAP) cur->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
570
+ if(cur->core.flag&BAM_FUNMAP) pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
571
+ if(!(pre->core.flag&BAM_FUNMAP)) {
572
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
573
+ }
574
+ if(!(cur->core.flag&BAM_FUNMAP)) {
575
+ if (sam_write1(out, header, cur) < 0) goto write_fail;
576
+ }
577
+ }
578
+ has_prev = 0;
579
+ } else { // unpaired? clear bad info and write it out
580
+ pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0;
581
+ pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
582
+ if ( !remove_reads || !(pre->core.flag&BAM_FUNMAP) ) {
583
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
584
+ }
585
+ }
586
+ } else has_prev = 1;
587
+ curr = 1 - curr;
588
+ pre_end = cur_end;
589
+ }
590
+ if (result < -1) goto read_fail;
591
+ if (has_prev && !remove_reads) { // If we still have a BAM in the buffer it must be unpaired
592
+ bam1_t *pre = b[1-curr];
593
+ if (pre->core.tid < 0 || pre->core.pos < 0 || pre->core.flag&BAM_FUNMAP) { // If unmapped
594
+ pre->core.flag |= BAM_FUNMAP;
595
+ pre->core.tid = -1;
596
+ pre->core.pos = -1;
597
+ }
598
+ pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0;
599
+ pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR);
600
+
601
+ if (sam_write1(out, header, pre) < 0) goto write_fail;
602
+ }
603
+ sam_hdr_destroy(header);
604
+ bam_destroy1(b[0]);
605
+ bam_destroy1(b[1]);
606
+ ks_free(&str);
607
+ return 0;
608
+
609
+ read_fail:
610
+ print_error("fixmate", "Couldn't read from input file");
611
+ goto fail;
612
+
613
+ write_fail:
614
+ print_error_errno("fixmate", "Couldn't write to output file");
615
+ fail:
616
+ sam_hdr_destroy(header);
617
+ bam_destroy1(b[0]);
618
+ bam_destroy1(b[1]);
619
+ ks_free(&str);
620
+ return 1;
621
+ }
622
+
623
+ void usage(FILE* where)
624
+ {
625
+ fprintf(where,
626
+ "Usage: samtools fixmate <in.nameSrt.bam> <out.nameSrt.bam>\n"
627
+ "Options:\n"
628
+ " -r Remove unmapped reads and secondary alignments\n"
629
+ " -p Disable FR proper pair check\n"
630
+ " -c Add template cigar ct tag\n"
631
+ " -m Add mate score tag\n"
632
+ " -u Uncompressed output\n"
633
+ " -z, --sanitize FLAG[,FLAG]\n"
634
+ " Sanitize alignment fields [defaults to all types]\n"
635
+ " --no-PG do not add a PG line\n");
636
+
637
+ sam_global_opt_help(where, "-.O..@-.");
638
+
639
+ fprintf(where,
640
+ "\n"
641
+ "As elsewhere in samtools, use '-' as the filename for stdin/samtools_stdout. The input\n"
642
+ "file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n"
643
+ "input is not accepted.\n");
644
+ }
645
+
646
+ int bam_mating(int argc, char *argv[])
647
+ {
648
+ htsThreadPool p = {NULL, 0};
649
+ samFile *in = NULL, *out = NULL;
650
+ int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1,
651
+ mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL;
652
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
653
+ char wmode[4] = {'w', 'b', 0, 0};
654
+ static const struct option lopts[] = {
655
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
656
+ {"no-PG", no_argument, NULL, 1},
657
+ { NULL, 0, NULL, 0 }
658
+ };
659
+ char *arg_list = NULL;
660
+
661
+ // parse args
662
+ if (argc == 1) { usage(samtools_stdout); return 0; }
663
+ while ((c = getopt_long(argc, argv, "rpcmO:@:uz:", lopts, NULL)) >= 0) {
664
+ switch (c) {
665
+ case 'r': remove_reads = 1; break;
666
+ case 'p': proper_pair_check = 0; break;
667
+ case 'c': add_ct = 1; break;
668
+ case 'm': mate_score = 1; break;
669
+ case 'u': wmode[2] = '0'; break;
670
+ case 1: no_pg = 1; break;
671
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
672
+ /* else fall-through */
673
+ case '?': usage(samtools_stderr); goto fail;
674
+ case 'z':
675
+ if ((sanitize_flags = bam_sanitize_options(optarg)) < 0)
676
+ samtools_exit(1);
677
+ break;
678
+ }
679
+ }
680
+ if (optind+1 >= argc) { usage(samtools_stderr); goto fail; }
681
+
682
+ if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
683
+ goto fail;
684
+
685
+ // init
686
+ if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
687
+ print_error_errno("fixmate", "cannot open input file");
688
+ goto fail;
689
+ }
690
+ sam_open_mode(wmode+1, argv[optind+1], NULL);
691
+ if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) {
692
+ print_error_errno("fixmate", "cannot open output file");
693
+ goto fail;
694
+ }
695
+
696
+ if (ga.nthreads > 0) {
697
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
698
+ fprintf(samtools_stderr, "Error creating thread pool\n");
699
+ goto fail;
700
+ }
701
+ hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
702
+ hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
703
+ }
704
+
705
+ // run
706
+ res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct,
707
+ mate_score, arg_list, no_pg, sanitize_flags);
708
+
709
+ // cleanup
710
+ sam_close(in);
711
+ if (sam_close(out) < 0) {
712
+ fprintf(samtools_stderr, "[bam_mating] error while closing output file\n");
713
+ res = 1;
714
+ }
715
+
716
+ if (p.pool) hts_tpool_destroy(p.pool);
717
+ free(arg_list);
718
+ sam_global_args_free(&ga);
719
+ return res;
720
+
721
+ fail:
722
+ if (in) sam_close(in);
723
+ if (out) sam_close(out);
724
+ if (p.pool) hts_tpool_destroy(p.pool);
725
+ free(arg_list);
726
+ sam_global_args_free(&ga);
727
+ return 1;
728
+ }
729
+
730
+
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_md.c.pysam.c ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_md.c -- calmd subcommand.
4
+
5
+ Copyright (C) 2009-2011, 2014-2015, 2019-2020, 2022 Genome Research Ltd.
6
+ Portions copyright (C) 2009-2011 Broad Institute.
7
+
8
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <stdio.h>
31
+ #include <stdlib.h>
32
+ #include <string.h>
33
+ #include <ctype.h>
34
+ #include <limits.h>
35
+ #include <errno.h>
36
+ #include <assert.h>
37
+ #include "htslib/faidx.h"
38
+ #include "htslib/sam.h"
39
+ #include "htslib/kstring.h"
40
+ #include "htslib/thread_pool.h"
41
+ #include "sam_opts.h"
42
+ #include "samtools.h"
43
+
44
+ #define USE_EQUAL 1
45
+ #define DROP_TAG 2
46
+ #define BIN_QUAL 4
47
+ #define UPDATE_NM 8
48
+ #define UPDATE_MD 16
49
+ #define HASH_QNM 32
50
+
51
+ typedef struct cached_ref_entry {
52
+ char *ref;
53
+ hts_pos_t len;
54
+ } cached_ref_entry;
55
+
56
+ typedef struct ref_cache {
57
+ cached_ref_entry *refs;
58
+ char *last_ref;
59
+ hts_pos_t last_len;
60
+ int nref;
61
+ int last_tid;
62
+ } ref_cache;
63
+
64
+ int bam_aux_drop_other(bam1_t *b, uint8_t *s);
65
+
66
+ static int bam_fillmd1_core(const char *ref_name, bam1_t *b, char *ref,
67
+ hts_pos_t ref_len, int flag, int max_nm,
68
+ int quiet_mode, uint32_t *skipped)
69
+ {
70
+ uint8_t *seq = bam_get_seq(b);
71
+ uint32_t *cigar = bam_get_cigar(b);
72
+ bam1_core_t *c = &b->core;
73
+ int i, qpos, matched = 0;
74
+ hts_pos_t rpos;
75
+ kstring_t str = KS_INITIALIZE;
76
+ int32_t old_nm_i = -1, nm = 0;
77
+ uint32_t err = 0;
78
+
79
+ if (c->l_qseq == 0) {
80
+ if (!quiet_mode) {
81
+ if (ref_name) {
82
+ fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment "
83
+ "record for '%s' at %s:%"PRIhts_pos", skipped\n",
84
+ bam_get_qname(b), ref_name, c->pos + 1);
85
+ } else {
86
+ fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment "
87
+ "record for '%s', skipped", bam_get_qname(b));
88
+ }
89
+ }
90
+ if (skipped) (*skipped)++;
91
+ return 0;
92
+ }
93
+
94
+ for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) {
95
+ int j, oplen = cigar[i]>>4, op = cigar[i]&0xf;
96
+ if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
97
+ for (j = 0; j < oplen; ++j) {
98
+ int c1, c2, z = qpos + j;
99
+ if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0')
100
+ break; // out of bounds
101
+ c1 = bam_seqi(seq, z);
102
+ c2 = seq_nt16_table[(uint8_t)ref[rpos+j]];
103
+ if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
104
+ if (flag&USE_EQUAL) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
105
+ ++matched;
106
+ } else {
107
+ err |= kputw(matched, &str) < 0;
108
+ err |= kputc(toupper(ref[rpos+j]), &str) < 0;
109
+ matched = 0; ++nm;
110
+ }
111
+ }
112
+ if (j < oplen) break;
113
+ rpos += oplen; qpos += oplen;
114
+ } else if (op == BAM_CDEL) {
115
+ err |= kputw(matched, &str) < 0;
116
+ err |= kputc('^', &str) < 0;
117
+ for (j = 0; j < oplen; ++j) {
118
+ if (rpos+j >= ref_len || ref[rpos+j] == '\0') break;
119
+ err |= kputc(toupper(ref[rpos+j]), &str) < 0;
120
+ }
121
+ matched = 0;
122
+ rpos += j; nm += j;
123
+ if (j < oplen) break;
124
+ } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
125
+ qpos += oplen;
126
+ if (op == BAM_CINS) nm += oplen;
127
+ } else if (op == BAM_CREF_SKIP) {
128
+ rpos += oplen;
129
+ }
130
+ }
131
+ err |= kputw(matched, &str) < 0;
132
+ if (err) {
133
+ print_error_errno("calmd", "Couldn't build new MD string");
134
+ goto fail;
135
+ }
136
+ // apply max_nm
137
+ if (max_nm > 0 && nm >= max_nm) {
138
+ for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) {
139
+ int j, oplen = cigar[i]>>4, op = cigar[i]&0xf;
140
+ if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
141
+ for (j = 0; j < oplen; ++j) {
142
+ int c1, c2, z = qpos + j;
143
+ if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0')
144
+ break; // out of bounds
145
+ c1 = bam_seqi(seq, z);
146
+ c2 = seq_nt16_table[(uint8_t)ref[rpos+j]];
147
+ if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match
148
+ seq[z/2] |= (z&1)? 0x0f : 0xf0;
149
+ bam_get_qual(b)[z] = 0;
150
+ }
151
+ }
152
+ if (j < oplen) break;
153
+ rpos += oplen; qpos += oplen;
154
+ } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) rpos += oplen;
155
+ else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) qpos += oplen;
156
+ }
157
+ }
158
+ // update NM
159
+ if ((flag & UPDATE_NM) && !(c->flag & BAM_FUNMAP)) {
160
+ uint8_t *old_nm = bam_aux_get(b, "NM");
161
+ if (old_nm) old_nm_i = bam_aux2i(old_nm);
162
+ if (!old_nm) {
163
+ if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0)
164
+ goto aux_fail;
165
+ }
166
+ else if (nm != old_nm_i) {
167
+ if (!quiet_mode) {
168
+ fprintf(samtools_stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam_get_qname(b), old_nm_i, nm);
169
+ }
170
+ if (bam_aux_del(b, old_nm) < 0) goto aux_fail;
171
+ if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0)
172
+ goto aux_fail;
173
+ }
174
+ }
175
+ // update MD
176
+ if ((flag & UPDATE_MD) && !(c->flag & BAM_FUNMAP)) {
177
+ uint8_t *old_md = bam_aux_get(b, "MD");
178
+ if (!old_md) {
179
+ if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0)
180
+ goto aux_fail;
181
+ } else {
182
+ int is_diff = 0;
183
+ if (strlen((char*)old_md+1) == str.l) {
184
+ for (i = 0; i < str.l; ++i)
185
+ if (toupper(old_md[i+1]) != toupper(str.s[i]))
186
+ break;
187
+ if (i < str.l) is_diff = 1;
188
+ } else is_diff = 1;
189
+ if (is_diff) {
190
+ if (!quiet_mode) {
191
+ fprintf(samtools_stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam_get_qname(b), old_md+1, str.s);
192
+ }
193
+ if (bam_aux_del(b, old_md) < 0) goto aux_fail;
194
+ if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0)
195
+ goto aux_fail;
196
+ }
197
+ }
198
+ }
199
+
200
+ // drop all tags but RG
201
+ if (flag&DROP_TAG) {
202
+ uint8_t *q = bam_aux_get(b, "RG");
203
+ bam_aux_drop_other(b, q);
204
+ }
205
+ // reduce the resolution of base quality
206
+ if (flag&BIN_QUAL) {
207
+ uint8_t *qual = bam_get_qual(b);
208
+ for (i = 0; i < b->core.l_qseq; ++i)
209
+ if (qual[i] >= 3) qual[i] = qual[i]/10*10 + 7;
210
+ }
211
+
212
+ free(str.s);
213
+ return 0;
214
+
215
+ aux_fail:
216
+ if (errno == ENOMEM) {
217
+ print_error("calmd", "Couldn't add aux tag (too long)");
218
+ } else if (errno == EINVAL) {
219
+ print_error("calmd", "Corrupt aux data");
220
+ } else {
221
+ print_error_errno("calmd", "Couldn't add aux tag");
222
+ }
223
+ fail:
224
+ free(str.s);
225
+ return -1;
226
+ }
227
+
228
+ int bam_fillmd1(bam1_t *b, char *ref, int flag, int quiet_mode)
229
+ {
230
+ return bam_fillmd1_core(NULL, b, ref, INT_MAX, flag, 0, quiet_mode, NULL);
231
+ }
232
+
233
+ // Get a new reference sequence.
234
+ // For position-sorted inputs, the previous reference should never be
235
+ // needed again and can be discarded to save memory. For other orderings,
236
+ // references are stored in a cache in case they're required in the future.
237
+ // The caching mode is turned on if the requested tid is less than the last
238
+ // one used, indicating the file ordering doesn't match the sequence dictionary.
239
+ static int get_ref(faidx_t *fai, sam_hdr_t *header, ref_cache *cache,
240
+ int tid, char **ref_out, const char **ref_name_out,
241
+ hts_pos_t *len_out)
242
+ {
243
+ char *ref = NULL;
244
+ const char *ref_name;
245
+ hts_pos_t len = 0;
246
+
247
+ // This should only be called when tid changes
248
+ assert(tid != cache->last_tid);
249
+
250
+ // Array lookup, should be fast
251
+ ref_name = sam_hdr_tid2name(header, tid);
252
+ *ref_name_out = ref_name;
253
+
254
+ // Return a cached entry, if available
255
+ if (cache->refs && tid >= 0 && tid < cache->nref
256
+ && cache->refs[tid].ref) {
257
+ assert(cache->last_ref == NULL);
258
+ *ref_out = cache->refs[tid].ref;
259
+ *len_out = cache->refs[tid].len;
260
+ cache->last_tid = tid;
261
+ return 0;
262
+ }
263
+
264
+ // Try to get the reference
265
+ if (ref_name)
266
+ ref = fai_fetch64(fai, ref_name, &len);
267
+
268
+ if (!ref) {
269
+ // Historically, calmd doesn't worry too much about missing refs
270
+ *ref_out = NULL;
271
+ *len_out = 0;
272
+ return 0;
273
+ }
274
+
275
+ if (!cache->refs && cache->last_tid > tid) {
276
+ // Going backwards throught the list of tids implies
277
+ // a non-position-ordered file, so turn on caching mode
278
+ cache->nref = sam_hdr_nref(header);
279
+ if (cache->nref < 0) {
280
+ print_error("calmd", "couldn't get number of refs from header");
281
+ return -1;
282
+ }
283
+ if (cache->nref > 0) {
284
+ cache->refs = calloc(cache->nref, sizeof(cache->refs[0]));
285
+ if (!cache->refs) {
286
+ print_error_errno("calmd",
287
+ "couldn't allocate reference cache");
288
+ return -1;
289
+ }
290
+ // Add the reference we already have as the first entry
291
+ if (cache->last_tid >= 0 && cache->last_tid < cache->nref) {
292
+ cache->refs[cache->last_tid].ref = cache->last_ref;
293
+ cache->refs[cache->last_tid].len = cache->last_len;
294
+ } else {
295
+ free(cache->last_ref);
296
+ }
297
+ cache->last_ref = NULL;
298
+ }
299
+ }
300
+
301
+ if (cache->refs) {
302
+ assert(cache->last_ref == NULL); // Shouldn't be set when caching
303
+ // Add the new reference to the cache
304
+ if (tid >= 0 && tid < cache->nref) {
305
+ cache->refs[tid].ref = ref;
306
+ cache->refs[tid].len = len;
307
+ }
308
+ } else {
309
+ // Streaming mode - free the last ref and replace it with this one
310
+ free(cache->last_ref);
311
+ cache->last_ref = ref;
312
+ cache->last_len = len;
313
+ }
314
+
315
+ *ref_out = ref;
316
+ *len_out = len;
317
+ cache->last_tid = tid;
318
+ return 0;
319
+ }
320
+
321
+ static void refs_destroy(ref_cache *cache) {
322
+ if (cache->refs) {
323
+ int i;
324
+ assert(cache->last_ref == NULL);
325
+ for (i = 0; i < cache->nref; i++)
326
+ free(cache->refs[i].ref);
327
+ free(cache->refs);
328
+ } else {
329
+ free(cache->last_ref);
330
+ }
331
+ }
332
+
333
+ int calmd_usage() {
334
+ fprintf(samtools_stderr,
335
+ "Usage: samtools calmd [-eubrAESQ] <aln.bam> <ref.fasta>\n"
336
+ "Options:\n"
337
+ " -e change identical bases to '='\n"
338
+ " -u uncompressed BAM output (for piping)\n"
339
+ " -b compressed BAM output\n"
340
+ " -S ignored (input format is auto-detected)\n"
341
+ " -A modify the quality string\n"
342
+ " -Q use quiet mode to output less debug info to samtools_stdout\n"
343
+ " -r compute the BQ tag (without -A) or cap baseQ by BAQ (with -A)\n"
344
+ " -E extended BAQ for better sensitivity but lower specificity\n"
345
+ " --no-PG do not add a PG line\n");
346
+
347
+ sam_global_opt_help(samtools_stderr, "-....@-.");
348
+ return 1;
349
+ }
350
+
351
+ int bam_fillmd(int argc, char *argv[])
352
+ {
353
+ int c, flt_flag, ret, is_bam_out, is_uncompressed, max_nm, is_realn, capQ, baq_flag, quiet_mode, no_pg = 0;
354
+ hts_pos_t len = 0;
355
+ htsThreadPool p = {NULL, 0};
356
+ samFile *fp = NULL, *fpout = NULL;
357
+ sam_hdr_t *header = NULL;
358
+ faidx_t *fai = NULL;
359
+ char *ref = NULL, mode_w[8], *ref_file, *arg_list = NULL;
360
+ ref_cache refs = { NULL, NULL, 0, 0, -2 };
361
+ const char *ref_name = NULL;
362
+ bam1_t *b = NULL;
363
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
364
+ uint32_t skipped = 0;
365
+
366
+ static const struct option lopts[] = {
367
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0,'@'),
368
+ {"no-PG", no_argument, NULL, 1},
369
+ { NULL, 0, NULL, 0 }
370
+ };
371
+
372
+ flt_flag = UPDATE_NM | UPDATE_MD;
373
+ is_bam_out = is_uncompressed = is_realn = max_nm = capQ = baq_flag = quiet_mode = 0;
374
+ strcpy(mode_w, "w");
375
+ while ((c = getopt_long(argc, argv, "EqQreuNhbSC:n:Ad@:", lopts, NULL)) >= 0) {
376
+ switch (c) {
377
+ case 'r': is_realn = 1; break;
378
+ case 'e': flt_flag |= USE_EQUAL; break;
379
+ case 'd': flt_flag |= DROP_TAG; break;
380
+ case 'q': flt_flag |= BIN_QUAL; break;
381
+ case 'h': flt_flag |= HASH_QNM; break;
382
+ case 'N': flt_flag &= ~(UPDATE_MD|UPDATE_NM); break;
383
+ case 'b': is_bam_out = 1; break;
384
+ case 'u': is_uncompressed = is_bam_out = 1; break;
385
+ case 'S': break;
386
+ case 'n': max_nm = atoi(optarg); break;
387
+ case 'C': capQ = atoi(optarg); break;
388
+ case 'A': baq_flag |= 1; break;
389
+ case 'E': baq_flag |= 2; break;
390
+ case 'Q': quiet_mode = 1; break;
391
+ case 1: no_pg = 1; break;
392
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
393
+ fprintf(samtools_stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c);
394
+ /* else fall-through */
395
+ case '?': return calmd_usage();
396
+ }
397
+ }
398
+ if (is_bam_out) strcat(mode_w, "b");
399
+ else strcat(mode_w, "h");
400
+ if (is_uncompressed) strcat(mode_w, "0");
401
+ if (optind + (ga.reference == NULL) >= argc)
402
+ return calmd_usage();
403
+ fp = sam_open_format(argv[optind], "r", &ga.in);
404
+ if (fp == NULL) {
405
+ print_error_errno("calmd", "Failed to open input file '%s'", argv[optind]);
406
+ return 1;
407
+ }
408
+
409
+ if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
410
+ print_error("calmd", "failed to create arg_list");
411
+ return 1;
412
+ }
413
+
414
+ header = sam_hdr_read(fp);
415
+ if (header == NULL || sam_hdr_nref(header) == 0) {
416
+ // NB: if we have no SQ headers but have aligned data, then this will
417
+ // be caught during processing with e.g.
418
+ // "[E::sam_parse1] no SQ lines present in the header"
419
+ fprintf(samtools_stderr, "[bam_fillmd] warning: input SAM does not have "
420
+ "header, performing a no-op.\n");
421
+ }
422
+
423
+ fpout = sam_open_format(samtools_stdout_fn, mode_w, &ga.out);
424
+ if (fpout == NULL) {
425
+ print_error_errno("calmd", "Failed to open output");
426
+ goto fail;
427
+ }
428
+ if (!no_pg && sam_hdr_add_pg(header, "samtools",
429
+ "VN", samtools_version(),
430
+ arg_list ? "CL": NULL,
431
+ arg_list ? arg_list : NULL,
432
+ NULL)) {
433
+ print_error("calmd", "failed to add PG line to header");
434
+ goto fail;
435
+ }
436
+ if (sam_hdr_write(fpout, header) < 0) {
437
+ print_error_errno("calmd", "Failed to write sam header");
438
+ goto fail;
439
+ }
440
+
441
+ if (ga.nthreads > 0) {
442
+ if (!(p.pool = hts_tpool_init(ga.nthreads))) {
443
+ fprintf(samtools_stderr, "Error creating thread pool\n");
444
+ goto fail;
445
+ }
446
+ hts_set_opt(fp, HTS_OPT_THREAD_POOL, &p);
447
+ hts_set_opt(fpout, HTS_OPT_THREAD_POOL, &p);
448
+ }
449
+
450
+ ref_file = argc > optind + 1 ? argv[optind+1] : ga.reference;
451
+ fai = fai_load(ref_file);
452
+
453
+ if (!fai) {
454
+ print_error_errno("calmd", "Failed to open reference file '%s'", ref_file);
455
+ goto fail;
456
+ }
457
+
458
+ b = bam_init1();
459
+ if (!b) {
460
+ fprintf(samtools_stderr, "[bam_fillmd] Failed to allocate bam struct\n");
461
+ goto fail;
462
+ }
463
+ while ((ret = sam_read1(fp, header, b)) >= 0) {
464
+ if (b->core.tid >= 0) {
465
+ if (refs.last_tid != b->core.tid) {
466
+ if (get_ref(fai, header, &refs, b->core.tid,
467
+ &ref, &ref_name, &len) < 0) {
468
+ goto fail;
469
+ }
470
+ if (ref == 0) { // FIXME: Should this always be fatal?
471
+ fprintf(samtools_stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n",
472
+ ref_name ? ref_name : "(unknown)");
473
+ if (is_realn || capQ > 10) goto fail; // Would otherwise crash
474
+ }
475
+ }
476
+ if (is_realn) {
477
+ if (sam_prob_realn(b, ref, len, baq_flag) < -3) {
478
+ print_error_errno("calmd", "BAQ alignment failed");
479
+ goto fail;
480
+ }
481
+ }
482
+ if (capQ > 10) {
483
+ int q = sam_cap_mapq(b, ref, len, capQ);
484
+ if (b->core.qual > q) b->core.qual = q;
485
+ }
486
+ if (ref) {
487
+ if (bam_fillmd1_core(ref_name, b, ref, len, flt_flag, max_nm,
488
+ quiet_mode, &skipped) < 0)
489
+ goto fail;
490
+ }
491
+ }
492
+ if (sam_write1(fpout, header, b) < 0) {
493
+ print_error_errno("calmd", "failed to write to output file");
494
+ goto fail;
495
+ }
496
+ }
497
+ if (ret < -1) {
498
+ fprintf(samtools_stderr, "[bam_fillmd] Error reading input.\n");
499
+ goto fail;
500
+ }
501
+
502
+ if (skipped) {
503
+ fprintf(samtools_stderr, "[calmd] Warning: %"PRIu32" records skipped due "
504
+ "to no query sequence\n",
505
+ skipped);
506
+ }
507
+
508
+ bam_destroy1(b);
509
+ sam_hdr_destroy(header);
510
+
511
+ free(arg_list);
512
+ refs_destroy(&refs);
513
+ fai_destroy(fai);
514
+ sam_close(fp);
515
+ if (sam_close(fpout) < 0) {
516
+ fprintf(samtools_stderr, "[bam_fillmd] error when closing output file\n");
517
+ return 1;
518
+ }
519
+ if (p.pool) hts_tpool_destroy(p.pool);
520
+
521
+ return 0;
522
+
523
+ fail:
524
+ free(arg_list);
525
+ refs_destroy(&refs);
526
+ if (b) bam_destroy1(b);
527
+ if (header) sam_hdr_destroy(header);
528
+ if (fai) fai_destroy(fai);
529
+ if (fp) sam_close(fp);
530
+ if (fpout) sam_close(fpout);
531
+ if (p.pool) hts_tpool_destroy(p.pool);
532
+
533
+ return 1;
534
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_quickcheck.c ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_quickcheck.c -- quickcheck subcommand.
2
+
3
+ Copyright (C) 2015-2017 Genome Research Ltd.
4
+
5
+ Author: Joshua C. Randall <jcrandall@alum.mit.edu>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <htslib/hts.h>
28
+ #include <htslib/sam.h>
29
+ #include <stdio.h>
30
+ #include <stdlib.h>
31
+ #include <unistd.h>
32
+
33
+ /* File status flags (zero means OK). It's possible for more than one to be
34
+ * set on a single file. The final exit status is the bitwise-or of the
35
+ * status of all the files. */
36
+ #define QC_FAIL_OPEN 2
37
+ #define QC_NOT_SEQUENCE 4
38
+ #define QC_BAD_HEADER 8
39
+ #define QC_NO_EOF_BLOCK 16
40
+ #define QC_FAIL_CLOSE 32
41
+
42
+ static void usage_quickcheck(FILE *write_to)
43
+ {
44
+ fprintf(write_to,
45
+ "Usage: samtools quickcheck [options] <input> [...]\n"
46
+ "Options:\n"
47
+ " -v verbose output (repeat for more verbosity)\n"
48
+ " -q suppress warning messages\n"
49
+ " -u unmapped input (do not require targets in header)\n"
50
+ "\n"
51
+ "Notes:\n"
52
+ "\n"
53
+ "1. By default quickcheck will emit a warning message if and only if a file\n"
54
+ " fails the checks, in which case the exit status is non-zero. Under normal\n"
55
+ " behaviour with valid data it will be silent and has a zero exit status.\n"
56
+ " The warning messages are purely for manual inspection and should not be \n"
57
+ " parsed by scripts.\n"
58
+ "\n"
59
+ "2. In order to use this command programmatically, you should check its exit\n"
60
+ " status. One way to use quickcheck might be as a check that all BAM files in\n"
61
+ " a directory are okay:\n"
62
+ "\n"
63
+ "\tsamtools quickcheck *.bam && echo 'all ok' \\\n"
64
+ "\t || echo 'fail!'\n"
65
+ "\n"
66
+ " The first level of verbosity lists only files that fail to stdout.\n"
67
+ " To obtain a parsable list of files that have failed, use this option:\n"
68
+ "\n"
69
+ "\tsamtools quickcheck -qv *.bam > bad_bams.fofn \\\n"
70
+ "\t && echo 'all ok' \\\n"
71
+ "\t || echo 'some files failed check, see bad_bams.fofn'\n"
72
+ );
73
+ }
74
+
75
+ #define QC_ERR(state, v, msg, arg1) \
76
+ file_state |= (state); \
77
+ if (!quiet || verbose >= (v)) fprintf(stderr, (msg), (arg1))
78
+
79
+ int main_quickcheck(int argc, char** argv)
80
+ {
81
+ int verbose = 0, quiet = 0, unmapped = 0;
82
+ hts_verbose = 0;
83
+
84
+ const char* optstring = "vqu";
85
+ int opt;
86
+ while ((opt = getopt(argc, argv, optstring)) != -1) {
87
+ switch (opt) {
88
+ case 'u':
89
+ unmapped = 1;
90
+ break;
91
+ case 'v':
92
+ verbose++;
93
+ break;
94
+ case 'q':
95
+ quiet = 1;
96
+ break;
97
+ default:
98
+ usage_quickcheck(stderr);
99
+ return 1;
100
+ }
101
+ }
102
+
103
+ argc -= optind;
104
+ argv += optind;
105
+
106
+ if (argc < 1) {
107
+ usage_quickcheck(stdout);
108
+ return 1;
109
+ }
110
+
111
+ if (verbose >= 2) {
112
+ fprintf(stderr, "verbosity set to %d\n", verbose);
113
+ }
114
+
115
+ if (verbose >= 4) {
116
+ hts_verbose = 3;
117
+ }
118
+
119
+ int ret = 0;
120
+ int i;
121
+
122
+ for (i = 0; i < argc; i++) {
123
+ char* fn = argv[i];
124
+ int file_state = 0;
125
+
126
+ if (verbose >= 3) fprintf(stderr, "checking %s\n", fn);
127
+
128
+ // attempt to open
129
+ htsFile *hts_fp = hts_open(fn, "r");
130
+ if (hts_fp == NULL) {
131
+ QC_ERR(QC_FAIL_OPEN, 2, "%s could not be opened for reading.\n", fn);
132
+ }
133
+ else {
134
+ if (verbose >= 3) fprintf(stderr, "opened %s\n", fn);
135
+ // make sure we have sequence data
136
+ const htsFormat *fmt = hts_get_format(hts_fp);
137
+ if (fmt->category != sequence_data ) {
138
+ QC_ERR(QC_NOT_SEQUENCE, 2, "%s was not identified as sequence data.\n", fn);
139
+ }
140
+ else {
141
+ if (verbose >= 3) fprintf(stderr, "%s is sequence data\n", fn);
142
+ // check header
143
+ sam_hdr_t *header = sam_hdr_read(hts_fp);
144
+ if (header == NULL) {
145
+ QC_ERR(QC_BAD_HEADER, 2, "%s caused an error whilst reading its header.\n", fn);
146
+ } else {
147
+ if (!unmapped && sam_hdr_nref(header) <= 0) {
148
+ QC_ERR(QC_BAD_HEADER, 2, "%s had no targets in header.\n", fn);
149
+ }
150
+ else {
151
+ if (verbose >= 3) fprintf(stderr, "%s has %d targets in header.\n", fn, sam_hdr_nref(header));
152
+ }
153
+ sam_hdr_destroy(header);
154
+ }
155
+ }
156
+ // check EOF on formats that support this
157
+ int ret;
158
+ if ((ret = hts_check_EOF(hts_fp)) < 0) {
159
+ QC_ERR(QC_NO_EOF_BLOCK, 2, "%s caused an error whilst checking for EOF block.\n", fn);
160
+ }
161
+ else {
162
+ switch (ret) {
163
+ case 0:
164
+ QC_ERR(QC_NO_EOF_BLOCK, 2, "%s was missing EOF block when one should be present.\n", fn);
165
+ break;
166
+ case 1:
167
+ if (verbose >= 3) fprintf(stderr, "%s has good EOF block.\n", fn);
168
+ break;
169
+ case 2:
170
+ if (verbose >= 3) fprintf(stderr, "%s cannot be checked for EOF block as it is not seekable.\n", fn);
171
+ break;
172
+ case 3:
173
+ if (verbose >= 3) fprintf(stderr, "%s cannot be checked for EOF block because its filetype does not contain one.\n", fn);
174
+ break;
175
+ }
176
+ }
177
+
178
+ if (hts_close(hts_fp) < 0) {
179
+ QC_ERR(QC_FAIL_CLOSE, 2, "%s did not close cleanly.\n", fn);
180
+ }
181
+ }
182
+
183
+ if (file_state > 0 && verbose >= 1) {
184
+ fprintf(stdout, "%s\n", fn);
185
+ }
186
+ ret |= file_state;
187
+ }
188
+
189
+ return ret;
190
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_reheader.c ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_reheader.c -- reheader subcommand.
2
+
3
+ Copyright (C) 2010 Broad Institute.
4
+ Copyright (C) 2012-2019 Genome Research Ltd.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <stdio.h>
29
+ #include <stdlib.h>
30
+ #include <assert.h>
31
+ #include <getopt.h>
32
+ #include <unistd.h>
33
+
34
+ #include "htslib/bgzf.h"
35
+ #include "htslib/sam.h"
36
+ #include "htslib/hfile.h"
37
+ #include "htslib/cram.h"
38
+ #include "samtools.h"
39
+
40
+ #define BUF_SIZE 0x10000
41
+
42
+ /*
43
+ * Reads a file and outputs a new BAM file to fd with 'h' replaced as
44
+ * the header. No checks are made to the validity.
45
+ */
46
+ int bam_reheader(BGZF *in, sam_hdr_t *h, int fd,
47
+ const char *arg_list, int no_pg, int skip_header)
48
+ {
49
+ BGZF *fp = NULL;
50
+ ssize_t len;
51
+ uint8_t *buf = NULL;
52
+ sam_hdr_t *tmp;
53
+ if (!h)
54
+ return -1;
55
+
56
+ if (in->is_write) return -1;
57
+ buf = malloc(BUF_SIZE);
58
+ if (!buf) {
59
+ fprintf(stderr, "Out of memory\n");
60
+ return -1;
61
+ }
62
+
63
+ if (!skip_header) {
64
+ if ((tmp = bam_hdr_read(in)) == NULL) {
65
+ fprintf(stderr, "Couldn't read header\n");
66
+ goto fail;
67
+ }
68
+ sam_hdr_destroy(tmp);
69
+ }
70
+
71
+ fp = bgzf_fdopen(fd, "w");
72
+ if (!fp) {
73
+ print_error_errno("reheader", "Couldn't open output file");
74
+ goto fail;
75
+ }
76
+
77
+ if (!no_pg && sam_hdr_add_pg(h, "samtools",
78
+ "VN", samtools_version(),
79
+ arg_list ? "CL": NULL,
80
+ arg_list ? arg_list : NULL,
81
+ NULL) != 0)
82
+ goto fail;
83
+
84
+ if (bam_hdr_write(fp, h) < 0) {
85
+ print_error_errno("reheader", "Couldn't write header");
86
+ goto fail;
87
+ }
88
+ if (in->block_offset < in->block_length) {
89
+ if (bgzf_write(fp, (char *)in->uncompressed_block + in->block_offset, in->block_length - in->block_offset) < 0) goto write_fail;
90
+ if (bgzf_flush(fp) < 0) goto write_fail;
91
+ }
92
+ while ((len = bgzf_raw_read(in, buf, BUF_SIZE)) > 0) {
93
+ if (bgzf_raw_write(fp, buf, len) < 0) goto write_fail;
94
+ }
95
+ if (len < 0) {
96
+ fprintf(stderr, "[%s] Error reading input file\n", __func__);
97
+ goto fail;
98
+ }
99
+ free(buf);
100
+ fp->block_offset = in->block_offset = 0;
101
+ if (bgzf_close(fp) < 0) {
102
+ fprintf(stderr, "[%s] Error closing output file\n", __func__);
103
+ return -1;
104
+ }
105
+ return 0;
106
+
107
+ write_fail:
108
+ print_error_errno("reheader", "Error writing to output file");
109
+ fail:
110
+ bgzf_close(fp);
111
+ free(buf);
112
+ return -1;
113
+ }
114
+
115
+ /*
116
+ * Reads a file and outputs a new CRAM file to stdout with 'h'
117
+ * replaced as the header. No checks are made to the validity.
118
+ *
119
+ * FIXME: error checking
120
+ */
121
+ int cram_reheader(cram_fd *in, sam_hdr_t *h, const char *arg_list, int no_pg)
122
+ {
123
+ htsFile *h_out = hts_open("-", "wc");
124
+ cram_fd *out = h_out->fp.cram;
125
+ cram_container *c = NULL;
126
+ int ret = -1;
127
+ if (!h)
128
+ return ret;
129
+
130
+ // Match output version number with input file.
131
+ char vers[99];
132
+ sprintf(vers, "%d.%d", cram_major_vers(in), cram_minor_vers(in));
133
+ cram_set_option(out, CRAM_OPT_VERSION, vers);
134
+
135
+ // Attempt to fill out a cram->refs[] array from @SQ headers
136
+ sam_hdr_t *cram_h = sam_hdr_dup(h);
137
+ if (!cram_h)
138
+ return -1;
139
+ cram_fd_set_header(out, cram_h);
140
+ if (!no_pg && sam_hdr_add_pg(cram_fd_get_header(out), "samtools",
141
+ "VN", samtools_version(),
142
+ arg_list ? "CL": NULL,
143
+ arg_list ? arg_list : NULL,
144
+ NULL))
145
+ goto err;
146
+
147
+ if (sam_hdr_write(h_out, cram_h) != 0)
148
+ goto err;
149
+ cram_set_option(out, CRAM_OPT_REFERENCE, NULL);
150
+
151
+ while ((c = cram_read_container(in))) {
152
+ int32_t i, num_blocks = cram_container_get_num_blocks(c);
153
+ if (cram_write_container(out, c) != 0)
154
+ goto err;
155
+
156
+ for (i = 0; i < num_blocks; i++) {
157
+ cram_block *blk = cram_read_block(in);
158
+ if (!blk || cram_write_block(out, blk) != 0) {
159
+ if (blk) cram_free_block(blk);
160
+ goto err;
161
+ }
162
+ cram_free_block(blk);
163
+ }
164
+ cram_free_container(c);
165
+ }
166
+
167
+ ret = 0;
168
+
169
+ err:
170
+ if (hts_close(h_out) != 0)
171
+ ret = -1;
172
+
173
+ return ret;
174
+ }
175
+
176
+
177
+
178
+ /*
179
+ * Reads a version 2 CRAM file and replaces the header in-place,
180
+ * provided the header is small enough to fit without growing the
181
+ * entire file.
182
+ *
183
+ * Version 2 format has an uncompressed SAM header with multiple nul
184
+ * termination bytes to permit inline header editing.
185
+ *
186
+ * Returns 0 on success;
187
+ * -1 on general failure;
188
+ * -2 on failure due to insufficient size
189
+ */
190
+ int cram_reheader_inplace2(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
191
+ int no_pg)
192
+ {
193
+ cram_container *c = NULL;
194
+ cram_block *b = NULL;
195
+ sam_hdr_t *cram_h = NULL;
196
+ off_t start;
197
+ int ret = -1;
198
+ if (!h)
199
+ goto err;
200
+
201
+ if (cram_major_vers(fd) < 2 ||
202
+ cram_major_vers(fd) > 3) {
203
+ fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__,
204
+ cram_major_vers(fd));
205
+ goto err;
206
+ }
207
+
208
+ cram_h = sam_hdr_dup(h);
209
+ if (!cram_h)
210
+ goto err;
211
+
212
+ if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(),
213
+ arg_list ? "CL": NULL,
214
+ arg_list ? arg_list : NULL,
215
+ NULL))
216
+ goto err;
217
+
218
+ int header_len = sam_hdr_length(cram_h);
219
+ /* Fix M5 strings? Maybe out of scope for this tool */
220
+
221
+ // Load the existing header
222
+ if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26)
223
+ goto err;
224
+
225
+ if (!(c = cram_read_container(fd)))
226
+ goto err;
227
+
228
+ // Version 2.1 has a single uncompressed block which is nul
229
+ // terminated with many nuls to permit growth.
230
+ //
231
+ // So load old block and keep all contents identical bar the
232
+ // header text itself
233
+ if (!(b = cram_read_block(fd)))
234
+ goto err;
235
+
236
+ if (cram_block_get_uncomp_size(b) < header_len+4) {
237
+ fprintf(stderr, "New header will not fit. Use non-inplace version (%d > %d)\n",
238
+ header_len+4, cram_block_get_uncomp_size(b));
239
+ ret = -2;
240
+ goto err;
241
+ }
242
+
243
+ cram_block_set_offset(b, 0); // rewind block
244
+ int32_put_blk(b, header_len);
245
+ cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len);
246
+ // Zero the remaining block
247
+ memset((char *)cram_block_get_data(b)+cram_block_get_offset(b), 0,
248
+ cram_block_get_uncomp_size(b) - cram_block_get_offset(b));
249
+ // Make sure all sizes and byte-offsets are consistent after memset
250
+ cram_block_set_offset(b, cram_block_get_uncomp_size(b));
251
+ cram_block_set_comp_size(b, cram_block_get_uncomp_size(b));
252
+
253
+ if (hseek(cram_fd_get_fp(fd), start, SEEK_SET) != start)
254
+ goto err;
255
+
256
+ if (cram_write_container(fd, c) == -1)
257
+ goto err;
258
+
259
+ if (cram_write_block(fd, b) == -1)
260
+ goto err;
261
+
262
+ ret = 0;
263
+ err:
264
+ if (c) cram_free_container(c);
265
+ if (b) cram_free_block(b);
266
+ if (cram_h) sam_hdr_destroy(cram_h);
267
+
268
+ return ret;
269
+ }
270
+
271
+
272
+ /*
273
+ * Reads a version 3 CRAM file and replaces the header in-place,
274
+ * provided the header is small enough to fit without growing the
275
+ * entire file.
276
+ *
277
+ * Version 3 format has a SAM header held as an (optionally)
278
+ * compressed block within the header container. Additional
279
+ * uncompressed blocks or simply unallocated space (the difference
280
+ * between total block sizes and the container size) are used to
281
+ * provide room for growth or contraction of the compressed header.
282
+ *
283
+ * Returns 0 on success;
284
+ * -1 on general failure;
285
+ * -2 on failure due to insufficient size
286
+ */
287
+ int cram_reheader_inplace3(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
288
+ int no_pg)
289
+ {
290
+ cram_container *c = NULL;
291
+ cram_block *b = NULL;
292
+ sam_hdr_t *cram_h = NULL;
293
+ off_t start, sz, end;
294
+ int container_sz, max_container_sz;
295
+ char *buf = NULL;
296
+ int ret = -1;
297
+ if (!h)
298
+ goto err;
299
+
300
+ if (cram_major_vers(fd) < 2 ||
301
+ cram_major_vers(fd) > 3) {
302
+ fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__,
303
+ cram_major_vers(fd));
304
+ goto err;
305
+ }
306
+
307
+ cram_h = sam_hdr_dup(h);
308
+ if (!cram_h)
309
+ goto err;
310
+
311
+ if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(),
312
+ arg_list ? "CL": NULL,
313
+ arg_list ? arg_list : NULL,
314
+ NULL))
315
+ goto err;
316
+
317
+ int header_len = sam_hdr_length(cram_h);
318
+ /* Fix M5 strings? Maybe out of scope for this tool */
319
+
320
+ // Find current size of SAM header block
321
+ if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26)
322
+ goto err;
323
+
324
+ if (!(c = cram_read_container(fd)))
325
+ goto err;
326
+
327
+ // +5 allows num_landmarks to increase from 0 to 1 (Cramtools)
328
+ max_container_sz = cram_container_size(c)+5;
329
+
330
+ sz = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c) - start;
331
+ end = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c);
332
+
333
+ // We force 1 block instead of (optionally) 2. C CRAM
334
+ // implementations for v3 were writing 1 compressed block followed
335
+ // by 1 uncompressed block. However this is tricky to deal with
336
+ // as changing block sizes can mean the block header also changes
337
+ // size due to itf8 and variable size integers.
338
+ //
339
+ // If we had 1 block, this doesn't change anything.
340
+ // If we had 2 blocks, the new container header will be smaller by
341
+ // 1+ bytes, requiring the cram_container_get_length(c) to be larger in value.
342
+ // However this is an int32 instead of itf8 so the container
343
+ // header structure stays the same size. This means we can always
344
+ // reduce the number of blocks without running into size problems.
345
+ cram_container_set_num_blocks(c, 1);
346
+ int32_t *landmark;
347
+ int32_t num_landmarks;
348
+ landmark = cram_container_get_landmarks(c, &num_landmarks);
349
+ if (num_landmarks && landmark) {
350
+ num_landmarks = 1;
351
+ landmark[0] = 0;
352
+ } else {
353
+ num_landmarks = 0;
354
+ }
355
+ cram_container_set_landmarks(c, num_landmarks, landmark);
356
+
357
+ buf = malloc(max_container_sz);
358
+ container_sz = max_container_sz;
359
+ if (cram_store_container(fd, c, buf, &container_sz) != 0)
360
+ goto err;
361
+
362
+ if (!buf)
363
+ goto err;
364
+
365
+ // Proposed new length, but changing cram_container_get_length(c) may change the
366
+ // container_sz and thus the remainder (cram_container_get_length(c) itself).
367
+ cram_container_set_length(c, sz - container_sz);
368
+
369
+ int old_container_sz = container_sz;
370
+ container_sz = max_container_sz;
371
+ if (cram_store_container(fd, c, buf, &container_sz) != 0)
372
+ goto err;
373
+
374
+ if (old_container_sz != container_sz) {
375
+ fprintf(stderr, "Quirk of fate makes this troublesome! "
376
+ "Please use non-inplace version.\n");
377
+ goto err;
378
+ }
379
+
380
+
381
+
382
+ // Version 3.0 supports compressed header
383
+ b = cram_new_block(FILE_HEADER, 0);
384
+ int32_put_blk(b, header_len);
385
+ cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len);
386
+ cram_block_update_size(b);
387
+
388
+ cram_compress_block(fd, b, NULL, -1, 9);
389
+
390
+ if (hseek(cram_fd_get_fp(fd), 26, SEEK_SET) != 26)
391
+ goto err;
392
+
393
+ if (cram_block_size(b) > cram_container_get_length(c)) {
394
+ fprintf(stderr, "New header will not fit. Use non-inplace version"
395
+ " (%d > %d)\n",
396
+ (int)cram_block_size(b), cram_container_get_length(c));
397
+ ret = -2;
398
+ goto err;
399
+ }
400
+
401
+ if (cram_write_container(fd, c) == -1)
402
+ goto err;
403
+
404
+ if (cram_write_block(fd, b) == -1)
405
+ goto err;
406
+
407
+ // Blank out the remainder
408
+ int rsz = end - htell(cram_fd_get_fp(fd));
409
+ assert(rsz >= 0);
410
+ if (rsz) {
411
+ char *rem = calloc(1, rsz);
412
+ ret = hwrite(cram_fd_get_fp(fd), rem, rsz) == rsz ? 0 : -1;
413
+ free(rem);
414
+ }
415
+
416
+ err:
417
+ if (c) cram_free_container(c);
418
+ if (buf) free(buf);
419
+ if (b) cram_free_block(b);
420
+ if (cram_h) sam_hdr_destroy(cram_h);
421
+
422
+ return ret;
423
+ }
424
+
425
+ int cram_reheader_inplace(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
426
+ int no_pg)
427
+ {
428
+ switch (cram_major_vers(fd)) {
429
+ case 2: return cram_reheader_inplace2(fd, h, arg_list, no_pg);
430
+ case 3: return cram_reheader_inplace3(fd, h, arg_list, no_pg);
431
+ default:
432
+ fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__,
433
+ cram_major_vers(fd));
434
+ return -1;
435
+ }
436
+ }
437
+
438
+ static void usage(FILE *fp, int ret) {
439
+ fprintf(fp,
440
+ "Usage: samtools reheader [-P] in.header.sam in.bam > out.bam\n"
441
+ " or samtools reheader [-P] -i in.header.sam file.cram\n"
442
+ " or samtools reheader -c CMD in.bam\n"
443
+ " or samtools reheader -c CMD in.cram\n"
444
+ "\n"
445
+ "Options:\n"
446
+ " -P, --no-PG Do not generate a @PG header line.\n"
447
+ " -i, --in-place Modify the CRAM file directly, if possible.\n"
448
+ " (Defaults to outputting to stdout.)\n"
449
+ " -c, --command CMD Pass the header in SAM format to external program CMD.\n");
450
+ exit(ret);
451
+ }
452
+
453
+ static sam_hdr_t* external_reheader(samFile* in, const char* external) {
454
+ char *command = NULL;
455
+ sam_hdr_t* h = NULL;
456
+ sam_hdr_t* ih = sam_hdr_read(in);
457
+ if (ih == NULL) {
458
+ fprintf(stderr, "[%s] failed to read the header for '%s'.\n", __func__, in->fn);
459
+ return NULL;
460
+ }
461
+ char tmp_fn[] = "reheaderXXXXXX";
462
+ int tmp_fd = mkstemp(tmp_fn);
463
+ if (tmp_fd < 0) {
464
+ print_error_errno("reheader", "fail to open temp file '%s'", tmp_fn);
465
+ return NULL;
466
+ }
467
+ hFILE* tmp_hf = hdopen(tmp_fd, "w");
468
+ if (!tmp_hf) {
469
+ fprintf(stderr, "[%s] failed to convert to hFILE.\n", __func__);
470
+ goto cleanup;
471
+ }
472
+ samFile* tmp_sf = hts_hopen(tmp_hf, tmp_fn, "w");
473
+ if (!tmp_sf) {
474
+ fprintf(stderr, "[%s] failed to convert to samFile.\n", __func__);
475
+ goto cleanup;
476
+ }
477
+ if (-1 == sam_hdr_write(tmp_sf, ih)) {
478
+ fprintf(stderr, "[%s] failed to write the header to the temp file.\n", __func__);
479
+ goto cleanup;
480
+ }
481
+ sam_close(tmp_sf);
482
+ sam_hdr_destroy(ih);
483
+ int comm_len = strlen(external) + strlen(tmp_fn) + 8;
484
+ command = calloc(comm_len, 1);
485
+ if (!command || snprintf(command, comm_len, "( %s ) < %s", external, tmp_fn) != comm_len - 1) {
486
+ fprintf(stderr, "[%s] failed to create command string.\n", __func__);
487
+ goto cleanup;
488
+ }
489
+ FILE* nh = popen(command, "r");
490
+ if (!nh) {
491
+ print_error_errno("reheader", "[%s] failed to run external command '%s'.\n", __func__, command);
492
+ goto cleanup;
493
+ }
494
+
495
+ int nh_fd = dup(fileno(nh));
496
+ if (nh_fd < 0) {
497
+ fprintf(stderr, "[%s] failed to get the file descriptor.\n", __func__);
498
+ goto cleanup;
499
+ }
500
+ hFILE* nh_hf = hdopen(nh_fd, "r");
501
+ if (!nh_hf) {
502
+ fprintf(stderr, "[%s] failed to convert to hFILE.\n", __func__);
503
+ goto cleanup;
504
+ }
505
+ samFile* nh_sf = hts_hopen(nh_hf, tmp_fn, "r");
506
+ if (!nh_sf) {
507
+ fprintf(stderr, "[%s] failed to convert to samFile.\n", __func__);
508
+ goto cleanup;
509
+ }
510
+
511
+ h = sam_hdr_read(nh_sf);
512
+ sam_close(nh_sf);
513
+ if (h == NULL) {
514
+ fprintf(stderr, "[%s] failed to read the header from the temp file.\n", __func__);
515
+ }
516
+ int res = pclose(nh);
517
+ if (res != 0) {
518
+ if (res < 0) {
519
+ print_error_errno("reheader",
520
+ "Error on closing pipe from command '%s'.\n",
521
+ command);
522
+ } else {
523
+ print_error("reheader",
524
+ "Non-zero exit code returned by command '%s'\n",
525
+ command);
526
+ }
527
+ if (h) sam_hdr_destroy(h);
528
+ h = NULL;
529
+ }
530
+ cleanup:
531
+ free(command);
532
+ if (unlink(tmp_fn) != 0) {
533
+ print_error_errno("reheader", "failed to remove the temp file '%s'", tmp_fn);
534
+ }
535
+
536
+ return h;
537
+ }
538
+
539
+ int main_reheader(int argc, char *argv[])
540
+ {
541
+ int inplace = 0, r, no_pg = 0, c, skip_header = 0;
542
+ sam_hdr_t *h;
543
+ samFile *in;
544
+ char *arg_list = NULL, *external = NULL;
545
+
546
+ static const struct option lopts[] = {
547
+ {"help", no_argument, NULL, 'h'},
548
+ {"in-place", no_argument, NULL, 'i'},
549
+ {"no-PG", no_argument, NULL, 'P'},
550
+ {"command", required_argument, NULL, 'c'},
551
+ {NULL, 0, NULL, 0}
552
+ };
553
+
554
+ while ((c = getopt_long(argc, argv, "hiPc:", lopts, NULL)) >= 0) {
555
+ switch (c) {
556
+ case 'P': no_pg = 1; break;
557
+ case 'i': inplace = 1; break;
558
+ case 'c': external = optarg; break;
559
+ case 'h': usage(stdout, 0); break;
560
+ default:
561
+ fprintf(stderr, "Invalid option '%c'\n", c);
562
+ usage(stderr, 1);
563
+ }
564
+ }
565
+
566
+ if ((argc - optind != 2 || external) && (argc - optind != 1 || !external))
567
+ usage(stderr, 1);
568
+
569
+ if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
570
+ print_error("reheader", "failed to create arg_list");
571
+ return 1;
572
+ }
573
+
574
+ if (external) {
575
+ skip_header = 1;
576
+ in = sam_open(argv[optind], inplace?"r+":"r");
577
+ if (in == 0) {
578
+ print_error_errno("reheader", "fail to open file '%s'", argv[optind]);
579
+ return 1;
580
+ }
581
+
582
+ h = external_reheader(in, external);
583
+ if (h == NULL) {
584
+ fprintf(stderr, "[%s] failed to read the header from '%s'.\n", __func__, external);
585
+ sam_close(in);
586
+ return 1;
587
+ }
588
+ } else { // read the header from a separate file
589
+ samFile *fph = sam_open(argv[optind], "r");
590
+ if (fph == 0) {
591
+ print_error_errno("reheader", "fail to read the header from '%s'", argv[optind]);
592
+ return 1;
593
+ }
594
+ h = sam_hdr_read(fph);
595
+ sam_close(fph);
596
+ if (h == NULL) {
597
+ fprintf(stderr, "[%s] failed to read the header for '%s'.\n",
598
+ __func__, argv[1]);
599
+ return 1;
600
+ }
601
+ in = sam_open(argv[optind+1], inplace?"r+":"r");
602
+ if (in == 0) {
603
+ print_error_errno("reheader", "fail to open file '%s'", argv[optind+1]);
604
+ return 1;
605
+ }
606
+ }
607
+
608
+ if (hts_get_format(in)->format == bam) {
609
+ if (inplace) {
610
+ print_error("reheader", "cannot reheader BAM '%s' in-place", argv[optind+1]);
611
+ r = -1;
612
+ } else {
613
+ r = bam_reheader(in->fp.bgzf, h, fileno(stdout), arg_list, no_pg, skip_header);
614
+ }
615
+ } else if (hts_get_format(in)->format == cram) {
616
+ if (inplace)
617
+ r = cram_reheader_inplace(in->fp.cram, h, arg_list, no_pg);
618
+ else
619
+ r = cram_reheader(in->fp.cram, h, arg_list, no_pg);
620
+ } else {
621
+ print_error("reheader", "input file '%s' must be BAM or CRAM", argv[optind+1]);
622
+ r = -1;
623
+ }
624
+
625
+ if (sam_close(in) != 0)
626
+ r = -1;
627
+
628
+ sam_hdr_destroy(h);
629
+
630
+ if (arg_list)
631
+ free(arg_list);
632
+
633
+ return -r;
634
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdup.c.pysam.c ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_rmdup.c -- duplicate read detection.
4
+
5
+ Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd.
6
+ Portions copyright (C) 2009 Broad Institute.
7
+
8
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <string.h>
32
+ #include <stdio.h>
33
+ #include <zlib.h>
34
+ #include <unistd.h>
35
+ #include "htslib/sam.h"
36
+ #include "sam_opts.h"
37
+ #include "samtools.h"
38
+ #include "bam.h" // for bam_get_library
39
+
40
+ typedef bam1_t *bam1_p;
41
+
42
+ #include "htslib/khash.h"
43
+ KHASH_SET_INIT_STR(name)
44
+ KHASH_MAP_INIT_INT64(pos, bam1_p)
45
+
46
+ #define BUFFER_SIZE 0x40000
47
+
48
+ typedef struct {
49
+ uint64_t n_checked, n_removed;
50
+ khash_t(pos) *best_hash;
51
+ } lib_aux_t;
52
+ KHASH_MAP_INIT_STR(lib, lib_aux_t)
53
+
54
+ typedef struct {
55
+ int n, max;
56
+ bam1_t **a;
57
+ } tmp_stack_t;
58
+
59
+ static inline void stack_insert(tmp_stack_t *stack, bam1_t *b)
60
+ {
61
+ if (stack->n == stack->max) {
62
+ stack->max = stack->max? stack->max<<1 : 0x10000;
63
+ stack->a = (bam1_t**)realloc(stack->a, sizeof(bam1_t*) * stack->max);
64
+ }
65
+ stack->a[stack->n++] = b;
66
+ }
67
+
68
+ static inline int dump_best(tmp_stack_t *stack, samFile *out, sam_hdr_t *hdr)
69
+ {
70
+ int i;
71
+ for (i = 0; i != stack->n; ++i) {
72
+ if (sam_write1(out, hdr, stack->a[i]) < 0) return -1;
73
+ bam_destroy1(stack->a[i]);
74
+ stack->a[i] = NULL;
75
+ }
76
+ stack->n = 0;
77
+ return 0;
78
+ }
79
+
80
+ static inline void clear_stack(tmp_stack_t *stack) {
81
+ int i;
82
+ if (!stack->a) return;
83
+ for (i = 0; i != stack->n; ++i) {
84
+ bam_destroy1(stack->a[i]);
85
+ }
86
+ }
87
+
88
+ static void clear_del_set(khash_t(name) *del_set)
89
+ {
90
+ khint_t k;
91
+ for (k = kh_begin(del_set); k < kh_end(del_set); ++k)
92
+ if (kh_exist(del_set, k))
93
+ free((char*)kh_key(del_set, k));
94
+ kh_clear(name, del_set);
95
+ }
96
+
97
+ static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib)
98
+ {
99
+ khint_t k = kh_get(lib, aux, lib);
100
+ if (k == kh_end(aux)) {
101
+ int ret;
102
+ char *p = strdup(lib);
103
+ lib_aux_t *q;
104
+ k = kh_put(lib, aux, p, &ret);
105
+ q = &kh_val(aux, k);
106
+ q->n_checked = q->n_removed = 0;
107
+ q->best_hash = kh_init(pos);
108
+ return q;
109
+ } else return &kh_val(aux, k);
110
+ }
111
+
112
+ static void clear_best(khash_t(lib) *aux, int max)
113
+ {
114
+ khint_t k;
115
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
116
+ if (kh_exist(aux, k)) {
117
+ lib_aux_t *q = &kh_val(aux, k);
118
+ if (kh_size(q->best_hash) >= max)
119
+ kh_clear(pos, q->best_hash);
120
+ }
121
+ }
122
+ }
123
+
124
+ static inline int sum_qual(const bam1_t *b)
125
+ {
126
+ int i, q;
127
+ uint8_t *qual = bam_get_qual(b);
128
+ for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i];
129
+ return q;
130
+ }
131
+
132
+ int bam_rmdup_core(samFile *in, sam_hdr_t *hdr, samFile *out)
133
+ {
134
+ bam1_t *b = NULL;
135
+ int last_tid = -1, last_pos = -1, r;
136
+ tmp_stack_t stack;
137
+ khint_t k;
138
+ khash_t(lib) *aux = NULL;
139
+ khash_t(name) *del_set = NULL;
140
+
141
+ memset(&stack, 0, sizeof(tmp_stack_t));
142
+ aux = kh_init(lib);
143
+ del_set = kh_init(name);
144
+ b = bam_init1();
145
+ if (!aux || !del_set || !b) {
146
+ perror(__func__);
147
+ goto fail;
148
+ }
149
+
150
+ kh_resize(name, del_set, 4 * BUFFER_SIZE);
151
+ while ((r = sam_read1(in, hdr, b)) >= 0) {
152
+ bam1_core_t *c = &b->core;
153
+ if (c->tid != last_tid || last_pos != c->pos) {
154
+ if (dump_best(&stack, out, hdr) < 0) goto write_fail; // write the result
155
+ clear_best(aux, BUFFER_SIZE);
156
+ if (c->tid != last_tid) {
157
+ clear_best(aux, 0);
158
+ if (kh_size(del_set)) { // check
159
+ fprintf(samtools_stderr, "[bam_rmdup_core] %llu unmatched pairs\n", (long long)kh_size(del_set));
160
+ clear_del_set(del_set);
161
+ }
162
+ if ((int)c->tid == -1) { // append unmapped reads
163
+ if (sam_write1(out, hdr, b) < 0) goto write_fail;
164
+ while ((r = sam_read1(in, hdr, b)) >= 0) {
165
+ if (sam_write1(out, hdr, b) < 0) goto write_fail;
166
+ }
167
+ break;
168
+ }
169
+ last_tid = c->tid;
170
+ fprintf(samtools_stderr, "[bam_rmdup_core] processing reference %s...\n", sam_hdr_tid2name(hdr, c->tid));
171
+ }
172
+ }
173
+ if (!(c->flag&BAM_FPAIRED) || (c->flag&(BAM_FUNMAP|BAM_FMUNMAP)) || (c->mtid >= 0 && c->tid != c->mtid)) {
174
+ if (sam_write1(out, hdr, b) < 0) goto write_fail;
175
+ } else if (c->isize > 0) { // paired, head
176
+ uint64_t key = (uint64_t)c->pos<<32 | c->isize;
177
+ const char *lib;
178
+ lib_aux_t *q;
179
+ int ret;
180
+ lib = bam_get_library(hdr, b);
181
+ q = lib? get_aux(aux, lib) : get_aux(aux, "\t");
182
+ ++q->n_checked;
183
+ k = kh_put(pos, q->best_hash, key, &ret);
184
+ if (ret < 0) goto fail;
185
+ if (ret == 0) { // found in best_hash
186
+ bam1_t *p = kh_val(q->best_hash, k);
187
+ ++q->n_removed;
188
+ if (sum_qual(p) < sum_qual(b)) { // the current alignment is better; this can be accelerated in principle
189
+ kh_put(name, del_set, strdup(bam_get_qname(p)), &ret); // p will be removed
190
+ if (ret < 0) goto fail;
191
+ if (bam_copy1(p, b) == NULL) goto fail; // replaced as b
192
+ } else kh_put(name, del_set, strdup(bam_get_qname(b)), &ret); // b will be removed
193
+ if (ret < 0) goto fail;
194
+ if (ret == 0)
195
+ fprintf(samtools_stderr, "[bam_rmdup_core] inconsistent BAM file for pair '%s'. Continue anyway.\n", bam_get_qname(b));
196
+ } else { // not found in best_hash
197
+ kh_val(q->best_hash, k) = bam_dup1(b);
198
+ stack_insert(&stack, kh_val(q->best_hash, k));
199
+ }
200
+ } else { // paired, tail
201
+ k = kh_get(name, del_set, bam_get_qname(b));
202
+ if (k != kh_end(del_set)) {
203
+ free((char*)kh_key(del_set, k));
204
+ kh_del(name, del_set, k);
205
+ } else {
206
+ if (sam_write1(out, hdr, b) < 0) goto write_fail;
207
+ }
208
+ }
209
+ last_pos = c->pos;
210
+ }
211
+ if (r < -1) {
212
+ fprintf(samtools_stderr, "[%s] failed to read input file\n", __func__);
213
+ goto fail;
214
+ }
215
+
216
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
217
+ if (kh_exist(aux, k)) {
218
+ lib_aux_t *q = &kh_val(aux, k);
219
+ if (dump_best(&stack, out, hdr) < 0) goto write_fail;
220
+ fprintf(samtools_stderr, "[bam_rmdup_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed,
221
+ (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k));
222
+ kh_destroy(pos, q->best_hash);
223
+ free((char*)kh_key(aux, k));
224
+ kh_del(lib, aux, k);
225
+ }
226
+ }
227
+ kh_destroy(lib, aux);
228
+
229
+ clear_del_set(del_set);
230
+ kh_destroy(name, del_set);
231
+ free(stack.a);
232
+ bam_destroy1(b);
233
+ return 0;
234
+
235
+ write_fail:
236
+ print_error_errno("rmdup", "failed to write record");
237
+ fail:
238
+ clear_stack(&stack);
239
+ free(stack.a);
240
+ if (aux) {
241
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
242
+ if (kh_exist(aux, k)) {
243
+ lib_aux_t *q = &kh_val(aux, k);
244
+ kh_destroy(pos, q->best_hash);
245
+ free((char*)kh_key(aux, k));
246
+ }
247
+ }
248
+ kh_destroy(lib, aux);
249
+ }
250
+ if (del_set) {
251
+ clear_del_set(del_set);
252
+ kh_destroy(name, del_set);
253
+ }
254
+ bam_destroy1(b);
255
+ return 1;
256
+ }
257
+
258
+ int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se);
259
+
260
+ static int rmdup_usage(void) {
261
+ fprintf(samtools_stderr, "\n");
262
+ fprintf(samtools_stderr, "Usage: samtools rmdup [-sS] <input.srt.bam> <output.bam>\n\n");
263
+ fprintf(samtools_stderr, "Option: -s rmdup for SE reads\n");
264
+ fprintf(samtools_stderr, " -S treat PE reads as SE in rmdup (force -s)\n");
265
+
266
+ sam_global_opt_help(samtools_stderr, "-....--.");
267
+ return 1;
268
+ }
269
+
270
+ int bam_rmdup(int argc, char *argv[])
271
+ {
272
+ int c, ret, is_se = 0, force_se = 0;
273
+ samFile *in, *out;
274
+ sam_hdr_t *header;
275
+ char wmode[3] = {'w', 'b', 0};
276
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
277
+
278
+ static const struct option lopts[] = {
279
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'),
280
+ { NULL, 0, NULL, 0 }
281
+ };
282
+
283
+ while ((c = getopt_long(argc, argv, "sS", lopts, NULL)) >= 0) {
284
+ switch (c) {
285
+ case 's': is_se = 1; break;
286
+ case 'S': force_se = is_se = 1; break;
287
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
288
+ /* else fall-through */
289
+ case '?': return rmdup_usage();
290
+ }
291
+ }
292
+ if (optind + 2 > argc)
293
+ return rmdup_usage();
294
+
295
+ in = sam_open_format(argv[optind], "r", &ga.in);
296
+ if (!in) {
297
+ print_error_errno("rmdup", "failed to open \"%s\" for input", argv[optind]);
298
+ return 1;
299
+ }
300
+ header = sam_hdr_read(in);
301
+ if (header == NULL || sam_hdr_nref(header) == 0) {
302
+ fprintf(samtools_stderr, "[bam_rmdup] input SAM does not have header. Abort!\n");
303
+ return 1;
304
+ }
305
+
306
+ sam_open_mode(wmode+1, argv[optind+1], NULL);
307
+ out = sam_open_format(argv[optind+1], wmode, &ga.out);
308
+ if (!out) {
309
+ print_error_errno("rmdup", "failed to open \"%s\" for output", argv[optind+1]);
310
+ return 1;
311
+ }
312
+ if (sam_hdr_write(out, header) < 0) {
313
+ print_error_errno("rmdup", "failed to write header");
314
+ return 1;
315
+ }
316
+
317
+ if (is_se) ret = bam_rmdupse_core(in, header, out, force_se);
318
+ else ret = bam_rmdup_core(in, header, out);
319
+
320
+ sam_hdr_destroy(header);
321
+ sam_close(in);
322
+ if (sam_close(out) < 0) {
323
+ fprintf(samtools_stderr, "[bam_rmdup] error closing output file\n");
324
+ ret = 1;
325
+ }
326
+ return ret;
327
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_rmdupse.c -- duplicate read detection for unpaired reads.
2
+
3
+ Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd.
4
+ Portions copyright (C) 2009 Broad Institute.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <math.h>
29
+ #include <stdio.h>
30
+ #include "bam.h" // for bam_get_library
31
+ #include "htslib/sam.h"
32
+ #include "htslib/khash.h"
33
+ #include "htslib/klist.h"
34
+ #include "samtools.h"
35
+
36
+ #define QUEUE_CLEAR_SIZE 0x100000
37
+ #define MAX_POS 0x7fffffff
38
+
39
+ typedef struct {
40
+ int endpos;
41
+ uint32_t score:31, discarded:1;
42
+ bam1_t *b;
43
+ } elem_t, *elem_p;
44
+ #define __free_elem(p) bam_destroy1((p)->data.b)
45
+ KLIST_INIT(q, elem_t, __free_elem)
46
+ typedef klist_t(q) queue_t;
47
+
48
+ KHASH_MAP_INIT_INT(best, elem_p)
49
+ typedef khash_t(best) besthash_t;
50
+
51
+ typedef struct {
52
+ uint64_t n_checked, n_removed;
53
+ besthash_t *left, *rght;
54
+ } lib_aux_t;
55
+ KHASH_MAP_INIT_STR(lib, lib_aux_t)
56
+
57
+ static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib)
58
+ {
59
+ khint_t k = kh_get(lib, aux, lib);
60
+ if (k == kh_end(aux)) {
61
+ int ret;
62
+ char *p = strdup(lib);
63
+ lib_aux_t *q;
64
+ k = kh_put(lib, aux, p, &ret);
65
+ q = &kh_val(aux, k);
66
+ q->left = kh_init(best);
67
+ q->rght = kh_init(best);
68
+ q->n_checked = q->n_removed = 0;
69
+ return q;
70
+ } else return &kh_val(aux, k);
71
+ }
72
+
73
+ static inline int sum_qual(const bam1_t *b)
74
+ {
75
+ int i, q;
76
+ uint8_t *qual = bam_get_qual(b);
77
+ for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i];
78
+ return q;
79
+ }
80
+
81
+ static inline elem_t *push_queue(queue_t *queue, const bam1_t *b, int endpos, int score)
82
+ {
83
+ elem_t *p = kl_pushp(q, queue);
84
+ p->discarded = 0;
85
+ p->endpos = endpos; p->score = score;
86
+ if (p->b == 0) p->b = bam_init1();
87
+ if (!p->b) { perror(NULL); exit(EXIT_FAILURE); }
88
+ if (bam_copy1(p->b, b) == NULL) { perror(NULL); exit(EXIT_FAILURE); }
89
+ return p;
90
+ }
91
+
92
+ static void clear_besthash(besthash_t *h, int32_t pos)
93
+ {
94
+ khint_t k;
95
+ for (k = kh_begin(h); k != kh_end(h); ++k)
96
+ if (kh_exist(h, k) && kh_val(h, k)->endpos <= pos)
97
+ kh_del(best, h, k);
98
+ }
99
+
100
+ static int dump_alignment(samFile *out, sam_hdr_t *hdr,
101
+ queue_t *queue, int32_t pos, khash_t(lib) *h)
102
+ {
103
+ if (queue->size > QUEUE_CLEAR_SIZE || pos == MAX_POS) {
104
+ khint_t k;
105
+ while (1) {
106
+ elem_t *q;
107
+ if (queue->head == queue->tail) break;
108
+ q = &kl_val(queue->head);
109
+ if (q->discarded) {
110
+ q->b->l_data = 0;
111
+ kl_shift(q, queue, 0);
112
+ continue;
113
+ }
114
+ if ((q->b->core.flag&BAM_FREVERSE) && q->endpos > pos) break;
115
+ if (sam_write1(out, hdr, q->b) < 0) return -1;
116
+ q->b->l_data = 0;
117
+ kl_shift(q, queue, 0);
118
+ }
119
+ for (k = kh_begin(h); k != kh_end(h); ++k) {
120
+ if (kh_exist(h, k)) {
121
+ clear_besthash(kh_val(h, k).left, pos);
122
+ clear_besthash(kh_val(h, k).rght, pos);
123
+ }
124
+ }
125
+ }
126
+ return 0;
127
+ }
128
+
129
+ int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se)
130
+ {
131
+ bam1_t *b = NULL;
132
+ queue_t *queue = NULL;
133
+ khint_t k;
134
+ int last_tid = -2, r;
135
+ khash_t(lib) *aux = NULL;
136
+
137
+ aux = kh_init(lib);
138
+ b = bam_init1();
139
+ queue = kl_init(q);
140
+ if (!aux || !b || !queue) {
141
+ perror(__func__);
142
+ goto fail;
143
+ }
144
+
145
+ while ((r = sam_read1(in, hdr, b)) >= 0) {
146
+ bam1_core_t *c = &b->core;
147
+ int endpos = bam_endpos(b);
148
+ int score = sum_qual(b);
149
+
150
+ if (last_tid != c->tid) {
151
+ if (last_tid >= 0) {
152
+ if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0)
153
+ goto write_fail;
154
+ }
155
+ last_tid = c->tid;
156
+ } else {
157
+ if (dump_alignment(out, hdr, queue, c->pos, aux) < 0)
158
+ goto write_fail;
159
+ }
160
+ if ((c->flag&BAM_FUNMAP) || ((c->flag&BAM_FPAIRED) && !force_se)) {
161
+ push_queue(queue, b, endpos, score);
162
+ } else {
163
+ const char *lib;
164
+ lib_aux_t *q;
165
+ besthash_t *h;
166
+ uint32_t key;
167
+ int ret;
168
+ lib = bam_get_library(hdr, b);
169
+ q = lib? get_aux(aux, lib) : get_aux(aux, "\t");
170
+ ++q->n_checked;
171
+ h = (c->flag&BAM_FREVERSE)? q->rght : q->left;
172
+ key = (c->flag&BAM_FREVERSE)? endpos : c->pos;
173
+ k = kh_put(best, h, key, &ret);
174
+ if (ret == 0) { // in the hash table
175
+ elem_t *p = kh_val(h, k);
176
+ ++q->n_removed;
177
+ if (p->score < score) {
178
+ if (c->flag&BAM_FREVERSE) { // mark "discarded" and push the queue
179
+ p->discarded = 1;
180
+ kh_val(h, k) = push_queue(queue, b, endpos, score);
181
+ } else { // replace
182
+ p->score = score; p->endpos = endpos;
183
+ if (bam_copy1(p->b, b) == NULL) {
184
+ perror(NULL); exit(EXIT_FAILURE);
185
+ }
186
+ }
187
+ } // otherwise, discard the alignment
188
+ } else kh_val(h, k) = push_queue(queue, b, endpos, score);
189
+ }
190
+ }
191
+ if (r < -1) {
192
+ fprintf(stderr, "[%s] error reading input file\n", __func__);
193
+ goto fail;
194
+ }
195
+
196
+ if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) goto write_fail;
197
+
198
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
199
+ if (kh_exist(aux, k)) {
200
+ lib_aux_t *q = &kh_val(aux, k);
201
+ fprintf(stderr, "[bam_rmdupse_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed,
202
+ (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k));
203
+ kh_destroy(best, q->left); kh_destroy(best, q->rght);
204
+ free((char*)kh_key(aux, k));
205
+ kh_del(lib, aux, k);
206
+ }
207
+ }
208
+ kh_destroy(lib, aux);
209
+ bam_destroy1(b);
210
+ kl_destroy(q, queue);
211
+ return 0;
212
+
213
+ write_fail:
214
+ print_error_errno("rmdup", "failed to write record");
215
+ fail:
216
+ if (aux) {
217
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
218
+ if (kh_exist(aux, k)) {
219
+ lib_aux_t *q = &kh_val(aux, k);
220
+ kh_destroy(best, q->left);
221
+ kh_destroy(best, q->rght);
222
+ free((char*)kh_key(aux, k));
223
+ }
224
+ }
225
+ kh_destroy(lib, aux);
226
+ }
227
+ bam_destroy1(b);
228
+ kl_destroy(q, queue);
229
+ return 1;
230
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c.pysam.c ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_rmdupse.c -- duplicate read detection for unpaired reads.
4
+
5
+ Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd.
6
+ Portions copyright (C) 2009 Broad Institute.
7
+
8
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <math.h>
31
+ #include <stdio.h>
32
+ #include "bam.h" // for bam_get_library
33
+ #include "htslib/sam.h"
34
+ #include "htslib/khash.h"
35
+ #include "htslib/klist.h"
36
+ #include "samtools.h"
37
+
38
+ #define QUEUE_CLEAR_SIZE 0x100000
39
+ #define MAX_POS 0x7fffffff
40
+
41
+ typedef struct {
42
+ int endpos;
43
+ uint32_t score:31, discarded:1;
44
+ bam1_t *b;
45
+ } elem_t, *elem_p;
46
+ #define __free_elem(p) bam_destroy1((p)->data.b)
47
+ KLIST_INIT(q, elem_t, __free_elem)
48
+ typedef klist_t(q) queue_t;
49
+
50
+ KHASH_MAP_INIT_INT(best, elem_p)
51
+ typedef khash_t(best) besthash_t;
52
+
53
+ typedef struct {
54
+ uint64_t n_checked, n_removed;
55
+ besthash_t *left, *rght;
56
+ } lib_aux_t;
57
+ KHASH_MAP_INIT_STR(lib, lib_aux_t)
58
+
59
+ static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib)
60
+ {
61
+ khint_t k = kh_get(lib, aux, lib);
62
+ if (k == kh_end(aux)) {
63
+ int ret;
64
+ char *p = strdup(lib);
65
+ lib_aux_t *q;
66
+ k = kh_put(lib, aux, p, &ret);
67
+ q = &kh_val(aux, k);
68
+ q->left = kh_init(best);
69
+ q->rght = kh_init(best);
70
+ q->n_checked = q->n_removed = 0;
71
+ return q;
72
+ } else return &kh_val(aux, k);
73
+ }
74
+
75
+ static inline int sum_qual(const bam1_t *b)
76
+ {
77
+ int i, q;
78
+ uint8_t *qual = bam_get_qual(b);
79
+ for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i];
80
+ return q;
81
+ }
82
+
83
+ static inline elem_t *push_queue(queue_t *queue, const bam1_t *b, int endpos, int score)
84
+ {
85
+ elem_t *p = kl_pushp(q, queue);
86
+ p->discarded = 0;
87
+ p->endpos = endpos; p->score = score;
88
+ if (p->b == 0) p->b = bam_init1();
89
+ if (!p->b) { perror(NULL); samtools_exit(EXIT_FAILURE); }
90
+ if (bam_copy1(p->b, b) == NULL) { perror(NULL); samtools_exit(EXIT_FAILURE); }
91
+ return p;
92
+ }
93
+
94
+ static void clear_besthash(besthash_t *h, int32_t pos)
95
+ {
96
+ khint_t k;
97
+ for (k = kh_begin(h); k != kh_end(h); ++k)
98
+ if (kh_exist(h, k) && kh_val(h, k)->endpos <= pos)
99
+ kh_del(best, h, k);
100
+ }
101
+
102
+ static int dump_alignment(samFile *out, sam_hdr_t *hdr,
103
+ queue_t *queue, int32_t pos, khash_t(lib) *h)
104
+ {
105
+ if (queue->size > QUEUE_CLEAR_SIZE || pos == MAX_POS) {
106
+ khint_t k;
107
+ while (1) {
108
+ elem_t *q;
109
+ if (queue->head == queue->tail) break;
110
+ q = &kl_val(queue->head);
111
+ if (q->discarded) {
112
+ q->b->l_data = 0;
113
+ kl_shift(q, queue, 0);
114
+ continue;
115
+ }
116
+ if ((q->b->core.flag&BAM_FREVERSE) && q->endpos > pos) break;
117
+ if (sam_write1(out, hdr, q->b) < 0) return -1;
118
+ q->b->l_data = 0;
119
+ kl_shift(q, queue, 0);
120
+ }
121
+ for (k = kh_begin(h); k != kh_end(h); ++k) {
122
+ if (kh_exist(h, k)) {
123
+ clear_besthash(kh_val(h, k).left, pos);
124
+ clear_besthash(kh_val(h, k).rght, pos);
125
+ }
126
+ }
127
+ }
128
+ return 0;
129
+ }
130
+
131
+ int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se)
132
+ {
133
+ bam1_t *b = NULL;
134
+ queue_t *queue = NULL;
135
+ khint_t k;
136
+ int last_tid = -2, r;
137
+ khash_t(lib) *aux = NULL;
138
+
139
+ aux = kh_init(lib);
140
+ b = bam_init1();
141
+ queue = kl_init(q);
142
+ if (!aux || !b || !queue) {
143
+ perror(__func__);
144
+ goto fail;
145
+ }
146
+
147
+ while ((r = sam_read1(in, hdr, b)) >= 0) {
148
+ bam1_core_t *c = &b->core;
149
+ int endpos = bam_endpos(b);
150
+ int score = sum_qual(b);
151
+
152
+ if (last_tid != c->tid) {
153
+ if (last_tid >= 0) {
154
+ if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0)
155
+ goto write_fail;
156
+ }
157
+ last_tid = c->tid;
158
+ } else {
159
+ if (dump_alignment(out, hdr, queue, c->pos, aux) < 0)
160
+ goto write_fail;
161
+ }
162
+ if ((c->flag&BAM_FUNMAP) || ((c->flag&BAM_FPAIRED) && !force_se)) {
163
+ push_queue(queue, b, endpos, score);
164
+ } else {
165
+ const char *lib;
166
+ lib_aux_t *q;
167
+ besthash_t *h;
168
+ uint32_t key;
169
+ int ret;
170
+ lib = bam_get_library(hdr, b);
171
+ q = lib? get_aux(aux, lib) : get_aux(aux, "\t");
172
+ ++q->n_checked;
173
+ h = (c->flag&BAM_FREVERSE)? q->rght : q->left;
174
+ key = (c->flag&BAM_FREVERSE)? endpos : c->pos;
175
+ k = kh_put(best, h, key, &ret);
176
+ if (ret == 0) { // in the hash table
177
+ elem_t *p = kh_val(h, k);
178
+ ++q->n_removed;
179
+ if (p->score < score) {
180
+ if (c->flag&BAM_FREVERSE) { // mark "discarded" and push the queue
181
+ p->discarded = 1;
182
+ kh_val(h, k) = push_queue(queue, b, endpos, score);
183
+ } else { // replace
184
+ p->score = score; p->endpos = endpos;
185
+ if (bam_copy1(p->b, b) == NULL) {
186
+ perror(NULL); samtools_exit(EXIT_FAILURE);
187
+ }
188
+ }
189
+ } // otherwise, discard the alignment
190
+ } else kh_val(h, k) = push_queue(queue, b, endpos, score);
191
+ }
192
+ }
193
+ if (r < -1) {
194
+ fprintf(samtools_stderr, "[%s] error reading input file\n", __func__);
195
+ goto fail;
196
+ }
197
+
198
+ if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) goto write_fail;
199
+
200
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
201
+ if (kh_exist(aux, k)) {
202
+ lib_aux_t *q = &kh_val(aux, k);
203
+ fprintf(samtools_stderr, "[bam_rmdupse_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed,
204
+ (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k));
205
+ kh_destroy(best, q->left); kh_destroy(best, q->rght);
206
+ free((char*)kh_key(aux, k));
207
+ kh_del(lib, aux, k);
208
+ }
209
+ }
210
+ kh_destroy(lib, aux);
211
+ bam_destroy1(b);
212
+ kl_destroy(q, queue);
213
+ return 0;
214
+
215
+ write_fail:
216
+ print_error_errno("rmdup", "failed to write record");
217
+ fail:
218
+ if (aux) {
219
+ for (k = kh_begin(aux); k != kh_end(aux); ++k) {
220
+ if (kh_exist(aux, k)) {
221
+ lib_aux_t *q = &kh_val(aux, k);
222
+ kh_destroy(best, q->left);
223
+ kh_destroy(best, q->rght);
224
+ free((char*)kh_key(aux, k));
225
+ }
226
+ }
227
+ kh_destroy(lib, aux);
228
+ }
229
+ bam_destroy1(b);
230
+ kl_destroy(q, queue);
231
+ return 1;
232
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_samples.c ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_samples -- print samples in a set of BAM files
2
+
3
+ Copyright (C) 2021 Pierre Lindenbaum
4
+ Institut du Thorax. u1087 Nantes. France.
5
+ @yokofakun
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+ #include <htslib/hts.h>
27
+ #include <htslib/sam.h>
28
+ #include <htslib/faidx.h>
29
+ #include <htslib/khash.h>
30
+ #include <htslib/kseq.h>
31
+ #include <samtools.h>
32
+ #include <stdio.h>
33
+ #include <stdlib.h>
34
+ #include <unistd.h>
35
+ #include <getopt.h>
36
+
37
+ KHASH_MAP_INIT_STR(sm, int)
38
+
39
+ /** and chained struct containing the faidx and the fasta filename
40
+ will be compared with the @SQ lines in the SAM header
41
+ */
42
+ typedef struct FaidxPath {
43
+ /** path to reference */
44
+ char* filename;
45
+ /** fasta index */
46
+ faidx_t* faidx;
47
+ struct FaidxPath* next;
48
+ } FaidxPath;
49
+
50
+ /** program parameters */
51
+ typedef struct Params {
52
+ /** output stream */
53
+ FILE* out;
54
+ /** tag in @RG line. default is "SM" */
55
+ char tag[3];
56
+ /** first faidx/path in chained list */
57
+ FaidxPath* faidx;
58
+ /** show whether the bam is indexed */
59
+ int test_index;
60
+ } Params;
61
+
62
+ /** print usage */
63
+ static void usage_samples(FILE *write_to) {
64
+ fprintf(write_to,
65
+ "Usage: samtools samples [options] <input> [...]\n"
66
+ " samtools samples [options] -X f1.bam f2.bam f1.bam.bai f2.bai \n"
67
+ " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.cram\" \\) | samtools samples [options]\n"
68
+ " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.bai\" \\) | sort | paste - - | samtools samples -X [options]\n"
69
+ "\n"
70
+ "Options:\n"
71
+ " -? print help and exit\n"
72
+ " -h add the columns header before printing the results\n"
73
+ " -i test if the file is indexed.\n"
74
+ " -T <tag> provide the sample tag name from the @RG line [SM].\n"
75
+ " -o <file> output file [stdout].\n"
76
+ " -f <file.fa> load an indexed fasta file in the collection of references. Can be used multiple times.\n"
77
+ " -F <file.txt> read a file containing the paths to indexed fasta files. One path per line.\n"
78
+ " -X use a custom index file.\n"
79
+ "\n"
80
+ " Using -f or -F will add a column containing the path to the reference or \".\" if the reference was not found.\n"
81
+ "\n"
82
+ );
83
+ }
84
+
85
+
86
+ /** loads fasta fai file into FaidxPath, add it to params->faidx */
87
+ static int load_dictionary(struct Params* params, const char* filename) {
88
+ FaidxPath* head = params->faidx;
89
+ FaidxPath* ptr = (FaidxPath*)malloc(sizeof(FaidxPath));
90
+ if (ptr == NULL) {
91
+ print_error_errno("samples", "Out of memory");
92
+ return EXIT_FAILURE;
93
+ }
94
+ ptr->filename = strdup(filename);
95
+ if (ptr->filename == NULL) {
96
+ free(ptr);
97
+ print_error_errno("samples", "Out of memory");
98
+ return EXIT_FAILURE;
99
+ }
100
+ ptr->faidx = fai_load(filename);
101
+ if (ptr->faidx == NULL) {
102
+ free(ptr->filename);
103
+ free(ptr);
104
+ print_error_errno("samples", "Cannot load index from \"%s\"", filename);
105
+ return EXIT_FAILURE;
106
+ }
107
+ /* insert at the beginning of the linked list */
108
+ params->faidx = ptr;
109
+ ptr->next = head;
110
+ return EXIT_SUCCESS;
111
+ }
112
+
113
+ /** load a faidx file and append it to params */
114
+ static int load_dictionaries(Params* params, const char* filename) {
115
+ int ret;
116
+ htsFile* in;
117
+ int status = EXIT_SUCCESS;
118
+
119
+ in = hts_open(filename, "r");
120
+ if (in == NULL) {
121
+ print_error_errno("samples", "Cannot open \"%s\"", filename);
122
+ status = EXIT_FAILURE;
123
+ } else {
124
+ kstring_t ks = KS_INITIALIZE;
125
+ while ((ret = hts_getline(in, KS_SEP_LINE, &ks)) >= 0) {
126
+ if (load_dictionary(params, ks_str(&ks)) != EXIT_SUCCESS) {
127
+ status = EXIT_FAILURE;
128
+ break;
129
+ }
130
+ }
131
+ ks_free(&ks);
132
+ hts_close(in);
133
+ }
134
+ return status;
135
+ }
136
+
137
+ /** print the sample information, search for a reference */
138
+ static int print_sample(
139
+ Params* params,
140
+ sam_hdr_t *header,
141
+ int has_index,
142
+ const char* sample,
143
+ const char* fname) {
144
+ fputs(sample, params->out);
145
+ fputc('\t', params->out);
146
+ fputs(fname, params->out);
147
+ if (params->test_index) {
148
+ fprintf(params->out, "\t%c", has_index ? 'Y' : 'N');
149
+ }
150
+ if (params->faidx != NULL) {
151
+ FaidxPath* ref = NULL;
152
+ FaidxPath* curr = params->faidx;
153
+ while (curr != NULL) {
154
+ /** check names and length are the same in the same order */
155
+ if (faidx_nseq(curr->faidx) == header->n_targets) {
156
+ int i;
157
+ for (i = 0; i < faidx_nseq(curr->faidx); i++) {
158
+ /** check name is the same */
159
+ if (strcmp(faidx_iseq(curr->faidx, i), header->target_name[i]) != 0) break;
160
+ /** check length is the same */
161
+ if (faidx_seq_len(curr->faidx, faidx_iseq(curr->faidx, i)) != header->target_len[i]) break;
162
+ }
163
+ /* the ref was found */
164
+ if (i == faidx_nseq(curr->faidx)) {
165
+ ref = curr;
166
+ break;
167
+ }
168
+ }
169
+ curr = curr->next;
170
+ }
171
+ fputc('\t', params->out);
172
+ if (ref == NULL) {
173
+ fputc('.', params->out);
174
+ } else {
175
+ fputs(curr->filename, params->out);
176
+ }
177
+ }
178
+ fputc('\n', params->out);
179
+ return 0;
180
+ }
181
+
182
+ /** open a sam file. Search for all samples in the @RG lines */
183
+ static int print_samples(Params* params, const char* fname, const char* baifname) {
184
+ samFile *in = 0;
185
+ sam_hdr_t *header = NULL;
186
+ int n_rg;
187
+ int status = EXIT_SUCCESS;
188
+ khash_t(sm) *sample_set = NULL;
189
+ khint_t k;
190
+ int count_samples = 0;
191
+ int has_index = 0;
192
+
193
+ if ((sample_set = kh_init(sm)) == NULL) {
194
+ print_error("samples", "Failed to initialise sample hash");
195
+ status = EXIT_FAILURE;
196
+ goto end_print;
197
+ }
198
+
199
+ if ((in = sam_open_format(fname, "r", NULL)) == 0) {
200
+ print_error_errno("samples", "Failed to open \"%s\" for reading", fname);
201
+ status = EXIT_FAILURE;
202
+ goto end_print;
203
+ }
204
+ if ((header = sam_hdr_read(in)) == 0) {
205
+ print_error("samples", "Failed to read the header from \"%s\"", fname);
206
+ status = EXIT_FAILURE;
207
+ goto end_print;
208
+ }
209
+
210
+ /* try to load index if required */
211
+ if (params->test_index) {
212
+ hts_idx_t *bam_idx;
213
+ /* path to bam index was specified */
214
+ if (baifname != NULL) {
215
+ bam_idx = sam_index_load3(in, fname, baifname, HTS_IDX_SILENT_FAIL);
216
+ }
217
+ /* get default index */
218
+ else {
219
+ bam_idx = sam_index_load3(in, fname, NULL, HTS_IDX_SILENT_FAIL);
220
+ }
221
+ has_index = bam_idx != NULL;
222
+ if (bam_idx != NULL) hts_idx_destroy(bam_idx);
223
+ /* and we continue... we have tested the index file but we always test for the samples and the references */
224
+ }
225
+
226
+ /* get the RG lines */
227
+ n_rg = sam_hdr_count_lines(header, "RG");
228
+ if (n_rg > 0) {
229
+ int i, r, ret;
230
+ char* sample;
231
+ kstring_t sm_val = KS_INITIALIZE;
232
+ for (i = 0; i < n_rg; i++) {
233
+ r = sam_hdr_find_tag_pos(header, "RG", i, params->tag, &sm_val);
234
+ if (r < 0) continue;
235
+ k = kh_get(sm, sample_set, ks_str(&sm_val));
236
+ if (k != kh_end(sample_set)) continue;
237
+ sample = strdup(ks_str(&sm_val));
238
+ if (sample == NULL) {
239
+ print_error_errno("samples", "Out of memory");
240
+ status = EXIT_FAILURE;
241
+ goto end_print;
242
+ }
243
+ kh_put(sm, sample_set, sample, &ret);
244
+ if (ret < 0) {
245
+ print_error("samples", "Failed to insert key '%s' into sample_set", sample);
246
+ free(sample);
247
+ status = EXIT_FAILURE;
248
+ goto end_print;
249
+ }
250
+ ++count_samples;
251
+ }
252
+ ks_free(&sm_val);
253
+ }
254
+ if (count_samples == 0) {
255
+ print_sample(params, header, has_index, ".", fname);
256
+ } else {
257
+ for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) {
258
+ if (kh_exist(sample_set, k)) {
259
+ char* sample = (char*)kh_key(sample_set, k);
260
+ print_sample(params, header, has_index, sample, fname);
261
+ }
262
+ }
263
+ }
264
+
265
+ end_print:
266
+ if (sample_set != NULL) {
267
+ for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) {
268
+ if (kh_exist(sample_set, k)) {
269
+ char* sample = (char*)kh_key(sample_set, k);
270
+ free(sample);
271
+ }
272
+ }
273
+ kh_destroy(sm, sample_set);
274
+ }
275
+ if (header != NULL) sam_hdr_destroy(header);
276
+ if (in != NULL) sam_close(in);
277
+
278
+ return status;
279
+ }
280
+
281
+
282
+ int main_samples(int argc, char** argv) {
283
+ int status = EXIT_SUCCESS;
284
+ int print_header = 0;
285
+ int has_index_file = 0;
286
+ Params params;
287
+ char* out_filename = NULL;
288
+ FaidxPath* fai;
289
+
290
+ strcpy(params.tag, "SM");
291
+ params.faidx = NULL;
292
+ params.test_index =0;
293
+
294
+ int opt;
295
+ while ((opt = getopt_long(argc, argv, "?hiXo:f:F:T:", NULL, NULL)) != -1) {
296
+ switch (opt) {
297
+ case 'h':
298
+ print_header = 1;
299
+ break;
300
+ case 'o':
301
+ out_filename = optarg;
302
+ break;
303
+ case 'i':
304
+ params.test_index = 1;
305
+ break;
306
+ case 'f':
307
+ if (load_dictionary(&params, optarg) != EXIT_SUCCESS) {
308
+ return EXIT_FAILURE;
309
+ }
310
+ break;
311
+ case 'F':
312
+ if (load_dictionaries(&params, optarg) != EXIT_SUCCESS) {
313
+ return EXIT_FAILURE;
314
+ }
315
+ break;
316
+ case 'T':
317
+ if (strlen(optarg) != 2) {
318
+ print_error("samples", "Length of tag \"%s\" is not 2.", optarg);
319
+ return EXIT_FAILURE;
320
+ }
321
+ strcpy(params.tag, optarg);
322
+ break;
323
+ case '?':
324
+ usage_samples(stdout);
325
+ return EXIT_SUCCESS;
326
+ case 'X':
327
+ has_index_file = 1;
328
+ break;
329
+ default:
330
+ usage_samples(stderr);
331
+ return EXIT_FAILURE;
332
+ }
333
+ }
334
+
335
+ /* if no file was provided and input is the terminal, print the usage and exit */
336
+ if (argc == optind && isatty(STDIN_FILENO)) {
337
+ usage_samples(stderr);
338
+ return EXIT_FAILURE;
339
+ }
340
+
341
+ if (out_filename != NULL) {
342
+ params.out = fopen(out_filename, "w");
343
+ if (params.out == NULL) {
344
+ print_error_errno("samples", "Cannot open \"%s\" for writing", out_filename);
345
+ return EXIT_FAILURE;
346
+ }
347
+ } else {
348
+ params.out = stdout;
349
+ }
350
+
351
+ if (print_header) {
352
+ fprintf(params.out, "#%s\tPATH", params.tag);
353
+ if (params.test_index) fprintf(params.out, "\tINDEX");
354
+ if (params.faidx != NULL) fprintf(params.out, "\tREFERENCE");
355
+ fprintf(params.out, "\n");
356
+ }
357
+
358
+ /* no file was provided, input is stdin, each line contains the path to a bam file */
359
+ if (argc == optind) {
360
+ htsFile* fp = hts_open("-", "r");
361
+ if (fp == NULL) {
362
+ print_error_errno("samples", "Cannot read from stdin");
363
+ status = EXIT_FAILURE;
364
+ } else {
365
+ kstring_t ks = KS_INITIALIZE;
366
+ int ret;
367
+ while ((ret = hts_getline(fp, KS_SEP_LINE, &ks)) >= 0) {
368
+ char* bai_path = NULL;
369
+ if (has_index_file) {
370
+ /* bam path and bam index file are separated by a tab */
371
+ char* tab = strchr(ks_str(&ks), '\t');
372
+ if (tab == NULL || *(tab+1) == '\0') {
373
+ print_error_errno("samples", "Expected path-to-bam(tab)path-to-index but got \"%s\"", ks_str(&ks));
374
+ status = EXIT_FAILURE;
375
+ break;
376
+ }
377
+ *tab=0;
378
+ bai_path = (tab + 1);
379
+ }
380
+ if (print_samples(&params, ks_str(&ks), bai_path) != EXIT_SUCCESS) {
381
+ status = EXIT_FAILURE;
382
+ break;
383
+ }
384
+ }
385
+ ks_free(&ks);
386
+ hts_close(fp);
387
+ }
388
+ }
389
+ /* loop over each file in argc/argv bam index provided */
390
+ else if (has_index_file) {
391
+ /* calculate number of input BAM files */
392
+ if ((argc - optind) % 2 != 0) {
393
+ print_error("samples","Odd number of filenames detected! Each BAM file should have an index file");
394
+ status = EXIT_FAILURE;
395
+ } else {
396
+ int i;
397
+ int n = (argc - optind ) / 2;
398
+ for (i = 0; i < n; i++) {
399
+ if (print_samples(&params, argv[optind+i], argv[optind+i+n]) != EXIT_SUCCESS) {
400
+ status = EXIT_FAILURE;
401
+ break;
402
+ }
403
+ }
404
+ }
405
+ } else {
406
+ int i;
407
+ for (i = optind; i < argc; i++) {
408
+ if (print_samples(&params, argv[i], NULL) != EXIT_SUCCESS) {
409
+ status = EXIT_FAILURE;
410
+ break;
411
+ }
412
+ }
413
+ }
414
+
415
+ fai = params.faidx;
416
+ while (fai != NULL) {
417
+ FaidxPath* next = fai -> next;
418
+ free(fai->filename);
419
+ fai_destroy(fai->faidx);
420
+ free(fai);
421
+ fai = next;
422
+ }
423
+
424
+ if (fflush(params.out) != 0) {
425
+ print_error_errno("samples", "Cannot flush output");
426
+ status = EXIT_FAILURE;
427
+ }
428
+ if (out_filename != NULL) {
429
+ fclose(params.out);
430
+ }
431
+
432
+ return status;
433
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_sort.c.pysam.c ADDED
The diff for this file is too large to render. See raw diff
 
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_split.c -- split subcommand.
2
+
3
+ Copyright (C) 2013-2016,2018-2019,2023 Genome Research Ltd.
4
+
5
+ Author: Martin Pollard <mp15@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <string.h>
28
+ #include <stdio.h>
29
+ #include <stdlib.h>
30
+ #include <stdbool.h>
31
+ #include <limits.h>
32
+ #include <unistd.h>
33
+ #include <regex.h>
34
+ #include <assert.h>
35
+ #include <htslib/sam.h>
36
+ #include <htslib/khash.h>
37
+ #include <htslib/kstring.h>
38
+ #include <htslib/cram.h>
39
+ #include "htslib/thread_pool.h"
40
+ #include "sam_opts.h"
41
+ #include "samtools.h"
42
+
43
+
44
+ KHASH_MAP_INIT_STR(c2i, int)
45
+
46
+ struct parsed_opts {
47
+ const char *merged_input_name;
48
+ const char *unaccounted_header_name;
49
+ const char *unaccounted_name;
50
+ const char *output_format_string;
51
+ bool verbose;
52
+ int no_pg;
53
+ sam_global_args ga;
54
+ };
55
+
56
+ typedef struct parsed_opts parsed_opts_t;
57
+
58
+ struct state {
59
+ samFile* merged_input_file;
60
+ sam_hdr_t* merged_input_header;
61
+ samFile* unaccounted_file;
62
+ sam_hdr_t* unaccounted_header;
63
+ size_t output_count;
64
+ char** rg_id;
65
+ char **rg_index_file_name;
66
+ char **rg_output_file_name;
67
+ samFile** rg_output_file;
68
+ sam_hdr_t** rg_output_header;
69
+ kh_c2i_t* rg_hash;
70
+ htsThreadPool p;
71
+ int write_index;
72
+ };
73
+
74
+ typedef struct state state_t;
75
+
76
+ static int cleanup_state(state_t* status, bool check_close);
77
+ static void cleanup_opts(parsed_opts_t* opts);
78
+
79
+ static void usage(FILE *write_to)
80
+ {
81
+ fprintf(write_to,
82
+ "Usage: samtools split [-u <unaccounted.bam>] [-h <unaccounted_header.sam>]\n"
83
+ " [-f <format_string>] [-v] <merged.bam>\n"
84
+ "Options:\n"
85
+ " -f STRING output filename format string [\"%%*_%%#.%%.\"]\n"
86
+ " -u FILE1 put reads with no RG tag or an unrecognised RG tag in FILE1\n"
87
+ " -h FILE2 ... and override the header with FILE2 (-u file only)\n"
88
+ " -v verbose output\n"
89
+ " --no-PG do not add a PG line\n");
90
+ sam_global_opt_help(write_to, "-....@..");
91
+ fprintf(write_to,
92
+ "\n"
93
+ "Format string expansions:\n"
94
+ " %%%% %%\n"
95
+ " %%* basename\n"
96
+ " %%# @RG index\n"
97
+ " %%! @RG ID\n"
98
+ " %%. filename extension for output format\n"
99
+ );
100
+ }
101
+
102
+ // Takes the command line options and turns them into something we can understand
103
+ static parsed_opts_t* parse_args(int argc, char** argv)
104
+ {
105
+ if (argc == 1) { usage(stdout); return NULL; }
106
+
107
+ const char *optstring = "vf:h:u:@:";
108
+
109
+ static const struct option lopts[] = {
110
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'),
111
+ {"no-PG", no_argument, NULL, 1},
112
+ { NULL, 0, NULL, 0 }
113
+ };
114
+
115
+ parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1);
116
+ if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; }
117
+
118
+ sam_global_args_init(&retval->ga);
119
+
120
+ int opt;
121
+ while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) {
122
+ switch (opt) {
123
+ case 'f':
124
+ retval->output_format_string = optarg;
125
+ break;
126
+ case 'h':
127
+ retval->unaccounted_header_name = optarg;
128
+ break;
129
+ case 'v':
130
+ retval->verbose = true;
131
+ break;
132
+ case 'u':
133
+ retval->unaccounted_name = optarg;
134
+ break;
135
+ case 1:
136
+ retval->no_pg = 1;
137
+ break;
138
+ default:
139
+ if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break;
140
+ /* else fall-through */
141
+ case '?':
142
+ usage(stdout);
143
+ free(retval);
144
+ return NULL;
145
+ }
146
+ }
147
+
148
+ if (retval->output_format_string == NULL) retval->output_format_string = "%*_%#.%.";
149
+
150
+ argc -= optind;
151
+ argv += optind;
152
+
153
+ if (argc != 1) {
154
+ print_error("split", "Invalid number of arguments: %d", argc);
155
+ usage(stderr);
156
+ free(retval);
157
+ return NULL;
158
+ }
159
+
160
+ retval->merged_input_name = argv[0];
161
+
162
+ return retval;
163
+ }
164
+
165
+ // Expands a output filename format string
166
+ static char* expand_format_string(const char* format_string, const char* basename, const char* rg_id, const int rg_idx, const htsFormat *format)
167
+ {
168
+ kstring_t str = { 0, 0, NULL };
169
+ const char* pointer = format_string;
170
+ const char* next;
171
+ while ((next = strchr(pointer, '%')) != NULL) {
172
+ if (kputsn(pointer, next-pointer, &str) < 0) goto memfail;
173
+ ++next;
174
+ switch (*next) {
175
+ case '%':
176
+ if (kputc('%', &str) < 0) goto memfail;
177
+ break;
178
+ case '*':
179
+ if (kputs(basename, &str) < 0) goto memfail;
180
+ break;
181
+ case '#':
182
+ if (kputl(rg_idx, &str) < 0) goto memfail;
183
+ break;
184
+ case '!':
185
+ if (kputs(rg_id, &str) < 0) goto memfail;
186
+ break;
187
+ case '.':
188
+ // Only really need to cope with sam, bam, cram
189
+ if (format->format != unknown_format) {
190
+ if (kputs(hts_format_file_extension(format), &str) < 0)
191
+ goto memfail;
192
+ } else {
193
+ if (kputs("bam", &str) < 0) goto memfail;
194
+ }
195
+ break;
196
+ case '\0':
197
+ print_error("split", "Trailing %% in filename format string");
198
+ goto fail;
199
+ default:
200
+ // Error is: fprintf(stderr, "bad format string, unknown format specifier\n");
201
+ print_error("split", "Unknown specifier %%%c in filename format string", *next);
202
+ goto fail;
203
+ }
204
+ pointer = next + 1;
205
+ }
206
+ if (kputs(pointer, &str) < 0) goto memfail;
207
+ return ks_release(&str);
208
+
209
+ memfail:
210
+ print_error_errno("split", "Couldn't build output filename");
211
+ fail:
212
+ free(str.s);
213
+ return NULL;
214
+ }
215
+
216
+ // Parse the header, count the number of RG tags and return a list of their names
217
+ static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name)
218
+ {
219
+ char **names = NULL;
220
+ kstring_t id_val = KS_INITIALIZE;
221
+ int i, n_rg = sam_hdr_count_lines(hdr, "RG");
222
+
223
+ if (n_rg < 0) {
224
+ print_error("split", "Failed to get @RG IDs");
225
+ *count = 0;
226
+ *output_name = NULL;
227
+ return false;
228
+ }
229
+
230
+ if (n_rg == 0) {
231
+ *count = 0;
232
+ *output_name = NULL;
233
+ return true;
234
+ }
235
+
236
+ names = calloc(n_rg, sizeof(names[0]));
237
+ if (!names) goto memfail;
238
+
239
+ for (i = 0; i < n_rg; i++) {
240
+ if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail;
241
+ names[i] = ks_release(&id_val);
242
+ }
243
+
244
+ *count = n_rg;
245
+ *output_name = names;
246
+ return true;
247
+
248
+ memfail:
249
+ print_error_errno("split", "Failed to get @RG IDs");
250
+ *count = 0;
251
+ *output_name = NULL;
252
+ ks_free(&id_val);
253
+ free(names);
254
+ return false;
255
+ }
256
+
257
+ static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2)
258
+ {
259
+ size_t n;
260
+ if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) {
261
+ print_error("split",
262
+ "Unaccounted header contains wrong number of references");
263
+ return -1;
264
+ }
265
+ for (n = 0; n < sam_hdr_nref(hdr1); n++) {
266
+ hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n);
267
+ hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n);
268
+ if (h1_len != h2_len) {
269
+ print_error("split",
270
+ "Unaccounted header reference %zu \"%s\" is not the same length as in the input file",
271
+ n + 1, sam_hdr_tid2name(hdr2, n));
272
+ return -1;
273
+ }
274
+ }
275
+ return 0;
276
+ }
277
+
278
+ // Set the initial state
279
+ static state_t* init(parsed_opts_t* opts, const char *arg_list)
280
+ {
281
+ state_t* retval = calloc(sizeof(state_t), 1);
282
+ if (!retval) {
283
+ print_error_errno("split", "Initialisation failed");
284
+ return NULL;
285
+ }
286
+
287
+ if (opts->ga.nthreads > 0) {
288
+ if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) {
289
+ fprintf(stderr, "Error creating thread pool\n");
290
+ cleanup_state(retval, false);
291
+ return NULL;
292
+ }
293
+ }
294
+
295
+ retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in);
296
+ if (!retval->merged_input_file) {
297
+ print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name);
298
+ cleanup_state(retval, false);
299
+ return NULL;
300
+ }
301
+ if (retval->p.pool)
302
+ hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p);
303
+ retval->merged_input_header = sam_hdr_read(retval->merged_input_file);
304
+ if (retval->merged_input_header == NULL) {
305
+ print_error("split", "Could not read header from \"%s\"", opts->merged_input_name);
306
+ cleanup_state(retval, false);
307
+ return NULL;
308
+ }
309
+
310
+ if (opts->unaccounted_name) {
311
+ if (opts->unaccounted_header_name) {
312
+ samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in);
313
+ if (!hdr_load) {
314
+ print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name);
315
+ cleanup_state(retval, false);
316
+ return NULL;
317
+ }
318
+ retval->unaccounted_header = sam_hdr_read(hdr_load);
319
+ if (retval->unaccounted_header == NULL) {
320
+ print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name);
321
+ cleanup_state(retval, false);
322
+ sam_close(hdr_load);
323
+ return NULL;
324
+ }
325
+ sam_close(hdr_load);
326
+ if (header_compatible(retval->merged_input_header,
327
+ retval->unaccounted_header) != 0) {
328
+ cleanup_state(retval, false);
329
+ return NULL;
330
+ }
331
+ } else {
332
+ retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header);
333
+ if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools",
334
+ "VN", samtools_version(),
335
+ arg_list ? "CL": NULL,
336
+ arg_list ? arg_list : NULL,
337
+ NULL)) {
338
+ print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name);
339
+ cleanup_state(retval, false);
340
+ return NULL;
341
+ }
342
+ }
343
+
344
+ char outmode[4] = "w";
345
+ sam_open_mode(outmode + 1, opts->unaccounted_name, NULL);
346
+ retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out);
347
+
348
+ if (retval->unaccounted_file == NULL) {
349
+ print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name);
350
+ cleanup_state(retval, false);
351
+ return NULL;
352
+ }
353
+ if (retval->p.pool)
354
+ hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p);
355
+ }
356
+
357
+ // Open output files for RGs
358
+ if (!count_RG(retval->merged_input_header, &retval->output_count, &retval->rg_id)) return NULL;
359
+ if (opts->verbose) fprintf(stderr, "@RG's found %zu\n",retval->output_count);
360
+ // Prevent calloc(0, size);
361
+ size_t num = retval->output_count ? retval->output_count : 1;
362
+ retval->rg_index_file_name = (char **)calloc(num, sizeof(char *));
363
+ retval->rg_output_file_name = (char **)calloc(num, sizeof(char *));
364
+ retval->rg_output_file = (samFile**)calloc(num, sizeof(samFile*));
365
+ retval->rg_output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*));
366
+ retval->rg_hash = kh_init_c2i();
367
+ if (!retval->rg_output_file_name || !retval->rg_output_file || !retval->rg_output_header ||
368
+ !retval->rg_hash || !retval->rg_index_file_name) {
369
+ print_error_errno("split", "Could not initialise output file array");
370
+ cleanup_state(retval, false);
371
+ return NULL;
372
+ }
373
+
374
+ char* dirsep = strrchr(opts->merged_input_name, '/');
375
+ char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
376
+ if (!input_base_name) {
377
+ print_error_errno("split", "Filename manipulation failed");
378
+ cleanup_state(retval, false);
379
+ return NULL;
380
+ }
381
+ char* extension = strrchr(input_base_name, '.');
382
+ if (extension) *extension = '\0';
383
+
384
+ size_t i;
385
+ for (i = 0; i < retval->output_count; i++) {
386
+ char* output_filename = NULL;
387
+ char outmode[4] = "w";
388
+
389
+ output_filename = expand_format_string(opts->output_format_string,
390
+ input_base_name,
391
+ retval->rg_id[i], i,
392
+ &opts->ga.out);
393
+
394
+ if ( output_filename == NULL ) {
395
+ cleanup_state(retval, false);
396
+ free(input_base_name);
397
+ return NULL;
398
+ }
399
+
400
+ retval->rg_output_file_name[i] = output_filename;
401
+
402
+ sam_open_mode(outmode + 1, output_filename, NULL);
403
+ retval->rg_output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out);
404
+
405
+ if (retval->rg_output_file[i] == NULL) {
406
+ print_error_errno("split", "Could not open \"%s\"", output_filename);
407
+ cleanup_state(retval, false);
408
+ free(input_base_name);
409
+ return NULL;
410
+ }
411
+ if (retval->p.pool)
412
+ hts_set_opt(retval->rg_output_file[i], HTS_OPT_THREAD_POOL, &retval->p);
413
+
414
+ // Record index in hash
415
+ int ret;
416
+ khiter_t iter = kh_put_c2i(retval->rg_hash, retval->rg_id[i], &ret);
417
+ if (ret < 0) {
418
+ print_error_errno("split", "Couldn't add @RG ID to look-up table");
419
+ cleanup_state(retval, false);
420
+ free(input_base_name);
421
+ return NULL;
422
+ }
423
+ kh_val(retval->rg_hash,iter) = i;
424
+
425
+ // Set and edit header
426
+ retval->rg_output_header[i] = sam_hdr_dup(retval->merged_input_header);
427
+ if (sam_hdr_remove_except(retval->rg_output_header[i], "RG", "ID", retval->rg_id[i]) ||
428
+ (!opts->no_pg &&
429
+ sam_hdr_add_pg(retval->rg_output_header[i], "samtools",
430
+ "VN", samtools_version(),
431
+ arg_list ? "CL": NULL,
432
+ arg_list ? arg_list : NULL,
433
+ NULL))) {
434
+ print_error("split", "Could not rewrite header for \"%s\"", output_filename);
435
+ cleanup_state(retval, false);
436
+ free(input_base_name);
437
+ return NULL;
438
+ }
439
+ }
440
+
441
+ free(input_base_name);
442
+ retval->write_index = opts->ga.write_index;
443
+
444
+ return retval;
445
+ }
446
+
447
+ static bool split(state_t* state)
448
+ {
449
+ if (state->unaccounted_file && sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) {
450
+ print_error_errno("split", "Could not write output file header");
451
+ return false;
452
+ }
453
+ size_t i;
454
+ for (i = 0; i < state->output_count; i++) {
455
+ if (sam_hdr_write(state->rg_output_file[i], state->rg_output_header[i]) != 0) {
456
+ print_error_errno("split", "Could not write file header to \"%s\"", state->rg_output_file_name[i]);
457
+ return false;
458
+ }
459
+ if (state->write_index) {
460
+ state->rg_index_file_name[i] = auto_index(state->rg_output_file[i],
461
+ state->rg_output_file_name[i],
462
+ state->rg_output_header[i]);
463
+ if (!state->rg_index_file_name[i]) {
464
+ print_error_errno("split", "Could not create index for file \"%s\"", state->rg_output_file_name[i]);
465
+ return false;
466
+ }
467
+ }
468
+ }
469
+
470
+ bam1_t* file_read = bam_init1();
471
+ // Read the first record
472
+ int r;
473
+ if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
474
+ // Nothing more to read? Ignore this file
475
+ bam_destroy1(file_read);
476
+ file_read = NULL;
477
+ if (r < -1) {
478
+ print_error("split", "Could not read first input record");
479
+ return false;
480
+ }
481
+ }
482
+
483
+ while (file_read != NULL) {
484
+ // Get RG tag from read and look it up in hash to find file to output it to
485
+ uint8_t* tag = bam_aux_get(file_read, "RG");
486
+ khiter_t iter;
487
+ if ( tag != NULL ) {
488
+ char* rg = bam_aux2Z(tag);
489
+ iter = kh_get_c2i(state->rg_hash, rg);
490
+ } else {
491
+ iter = kh_end(state->rg_hash);
492
+ }
493
+
494
+ // Write the read out to correct file
495
+ if (iter != kh_end(state->rg_hash)) {
496
+ // if found write to the appropriate untangled bam
497
+ int i = kh_val(state->rg_hash,iter);
498
+ if (sam_write1(state->rg_output_file[i], state->rg_output_header[i], file_read) < 0) {
499
+ print_error_errno("split", "Could not write to \"%s\"", state->rg_output_file_name[i]);
500
+ bam_destroy1(file_read);
501
+ return false;
502
+ }
503
+ } else {
504
+ // otherwise write to the unaccounted bam if there is one or fail
505
+ if (state->unaccounted_file == NULL) {
506
+ if (tag) {
507
+ fprintf(stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag));
508
+ } else {
509
+ fprintf(stderr, "Read \"%s\" has no RG tag.\n", bam_get_qname(file_read));
510
+ }
511
+ bam_destroy1(file_read);
512
+ return false;
513
+ } else {
514
+ if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) {
515
+ print_error_errno("split", "Could not write to unaccounted output file");
516
+ bam_destroy1(file_read);
517
+ return false;
518
+ }
519
+ }
520
+ }
521
+
522
+ // Replace written read with the next one to process
523
+ if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
524
+ // Nothing more to read? Ignore this file in future
525
+ bam_destroy1(file_read);
526
+ file_read = NULL;
527
+ if (r < -1) {
528
+ print_error("split", "Could not read input record");
529
+ return false;
530
+ }
531
+ }
532
+ }
533
+
534
+ if (state->write_index) {
535
+ for (i = 0; i < state->output_count; i++) {
536
+ if (sam_idx_save(state->rg_output_file[i]) < 0) {
537
+ print_error_errno("split", "writing index failed");
538
+ return false;
539
+ }
540
+ free(state->rg_index_file_name[i]);
541
+ }
542
+ }
543
+
544
+ return true;
545
+ }
546
+
547
+ static int cleanup_state(state_t* status, bool check_close)
548
+ {
549
+ int ret = 0;
550
+
551
+ if (!status) return 0;
552
+ if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header);
553
+ if (status->unaccounted_file) {
554
+ if (sam_close(status->unaccounted_file) < 0 && check_close) {
555
+ print_error("split", "Error on closing unaccounted file");
556
+ ret = -1;
557
+ }
558
+ }
559
+ sam_close(status->merged_input_file);
560
+ size_t i;
561
+ for (i = 0; i < status->output_count; i++) {
562
+ if (status->rg_output_header && status->rg_output_header[i])
563
+ sam_hdr_destroy(status->rg_output_header[i]);
564
+ if (status->rg_output_file && status->rg_output_file[i]) {
565
+ if (sam_close(status->rg_output_file[i]) < 0 && check_close) {
566
+ print_error("split", "Error on closing output file \"%s\"", status->rg_output_file_name[i]);
567
+ ret = -1;
568
+ }
569
+ }
570
+ if (status->rg_id) free(status->rg_id[i]);
571
+ if (status->rg_output_file_name) free(status->rg_output_file_name[i]);
572
+ }
573
+ if (status->merged_input_header)
574
+ sam_hdr_destroy(status->merged_input_header);
575
+ free(status->rg_output_header);
576
+ free(status->rg_output_file);
577
+ free(status->rg_output_file_name);
578
+ free(status->rg_index_file_name);
579
+ kh_destroy_c2i(status->rg_hash);
580
+ free(status->rg_id);
581
+ if (status->p.pool)
582
+ hts_tpool_destroy(status->p.pool);
583
+ free(status);
584
+
585
+ return ret;
586
+ }
587
+
588
+ static void cleanup_opts(parsed_opts_t* opts)
589
+ {
590
+ if (!opts) return;
591
+ sam_global_args_free(&opts->ga);
592
+ free(opts);
593
+ }
594
+
595
+ int main_split(int argc, char** argv)
596
+ {
597
+ int ret = 1;
598
+ char *arg_list = NULL;
599
+ parsed_opts_t* opts = parse_args(argc, argv);
600
+ if (!opts) goto cleanup_opts;
601
+ if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
602
+ goto cleanup_opts;
603
+ state_t* status = init(opts, arg_list);
604
+ if (!status) goto cleanup_opts;
605
+
606
+ if (!split(status)) {
607
+ cleanup_state(status, false);
608
+ goto cleanup_opts;
609
+ }
610
+
611
+ ret = cleanup_state(status, true);
612
+
613
+ cleanup_opts:
614
+ cleanup_opts(opts);
615
+ free(arg_list);
616
+
617
+ return ret;
618
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c.pysam.c ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* bam_split.c -- split subcommand.
4
+
5
+ Copyright (C) 2013-2016,2018-2019,2023 Genome Research Ltd.
6
+
7
+ Author: Martin Pollard <mp15@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ #include <config.h>
28
+
29
+ #include <string.h>
30
+ #include <stdio.h>
31
+ #include <stdlib.h>
32
+ #include <stdbool.h>
33
+ #include <limits.h>
34
+ #include <unistd.h>
35
+ #include <regex.h>
36
+ #include <assert.h>
37
+ #include <htslib/sam.h>
38
+ #include <htslib/khash.h>
39
+ #include <htslib/kstring.h>
40
+ #include <htslib/cram.h>
41
+ #include "htslib/thread_pool.h"
42
+ #include "sam_opts.h"
43
+ #include "samtools.h"
44
+
45
+
46
+ KHASH_MAP_INIT_STR(c2i, int)
47
+
48
+ struct parsed_opts {
49
+ const char *merged_input_name;
50
+ const char *unaccounted_header_name;
51
+ const char *unaccounted_name;
52
+ const char *output_format_string;
53
+ bool verbose;
54
+ int no_pg;
55
+ sam_global_args ga;
56
+ };
57
+
58
+ typedef struct parsed_opts parsed_opts_t;
59
+
60
+ struct state {
61
+ samFile* merged_input_file;
62
+ sam_hdr_t* merged_input_header;
63
+ samFile* unaccounted_file;
64
+ sam_hdr_t* unaccounted_header;
65
+ size_t output_count;
66
+ char** rg_id;
67
+ char **rg_index_file_name;
68
+ char **rg_output_file_name;
69
+ samFile** rg_output_file;
70
+ sam_hdr_t** rg_output_header;
71
+ kh_c2i_t* rg_hash;
72
+ htsThreadPool p;
73
+ int write_index;
74
+ };
75
+
76
+ typedef struct state state_t;
77
+
78
+ static int cleanup_state(state_t* status, bool check_close);
79
+ static void cleanup_opts(parsed_opts_t* opts);
80
+
81
+ static void usage(FILE *write_to)
82
+ {
83
+ fprintf(write_to,
84
+ "Usage: samtools split [-u <unaccounted.bam>] [-h <unaccounted_header.sam>]\n"
85
+ " [-f <format_string>] [-v] <merged.bam>\n"
86
+ "Options:\n"
87
+ " -f STRING output filename format string [\"%%*_%%#.%%.\"]\n"
88
+ " -u FILE1 put reads with no RG tag or an unrecognised RG tag in FILE1\n"
89
+ " -h FILE2 ... and override the header with FILE2 (-u file only)\n"
90
+ " -v verbose output\n"
91
+ " --no-PG do not add a PG line\n");
92
+ sam_global_opt_help(write_to, "-....@..");
93
+ fprintf(write_to,
94
+ "\n"
95
+ "Format string expansions:\n"
96
+ " %%%% %%\n"
97
+ " %%* basename\n"
98
+ " %%# @RG index\n"
99
+ " %%! @RG ID\n"
100
+ " %%. filename extension for output format\n"
101
+ );
102
+ }
103
+
104
+ // Takes the command line options and turns them into something we can understand
105
+ static parsed_opts_t* parse_args(int argc, char** argv)
106
+ {
107
+ if (argc == 1) { usage(samtools_stdout); return NULL; }
108
+
109
+ const char *optstring = "vf:h:u:@:";
110
+
111
+ static const struct option lopts[] = {
112
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'),
113
+ {"no-PG", no_argument, NULL, 1},
114
+ { NULL, 0, NULL, 0 }
115
+ };
116
+
117
+ parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1);
118
+ if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; }
119
+
120
+ sam_global_args_init(&retval->ga);
121
+
122
+ int opt;
123
+ while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) {
124
+ switch (opt) {
125
+ case 'f':
126
+ retval->output_format_string = optarg;
127
+ break;
128
+ case 'h':
129
+ retval->unaccounted_header_name = optarg;
130
+ break;
131
+ case 'v':
132
+ retval->verbose = true;
133
+ break;
134
+ case 'u':
135
+ retval->unaccounted_name = optarg;
136
+ break;
137
+ case 1:
138
+ retval->no_pg = 1;
139
+ break;
140
+ default:
141
+ if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break;
142
+ /* else fall-through */
143
+ case '?':
144
+ usage(samtools_stdout);
145
+ free(retval);
146
+ return NULL;
147
+ }
148
+ }
149
+
150
+ if (retval->output_format_string == NULL) retval->output_format_string = "%*_%#.%.";
151
+
152
+ argc -= optind;
153
+ argv += optind;
154
+
155
+ if (argc != 1) {
156
+ print_error("split", "Invalid number of arguments: %d", argc);
157
+ usage(samtools_stderr);
158
+ free(retval);
159
+ return NULL;
160
+ }
161
+
162
+ retval->merged_input_name = argv[0];
163
+
164
+ return retval;
165
+ }
166
+
167
+ // Expands a output filename format string
168
+ static char* expand_format_string(const char* format_string, const char* basename, const char* rg_id, const int rg_idx, const htsFormat *format)
169
+ {
170
+ kstring_t str = { 0, 0, NULL };
171
+ const char* pointer = format_string;
172
+ const char* next;
173
+ while ((next = strchr(pointer, '%')) != NULL) {
174
+ if (kputsn(pointer, next-pointer, &str) < 0) goto memfail;
175
+ ++next;
176
+ switch (*next) {
177
+ case '%':
178
+ if (kputc('%', &str) < 0) goto memfail;
179
+ break;
180
+ case '*':
181
+ if (kputs(basename, &str) < 0) goto memfail;
182
+ break;
183
+ case '#':
184
+ if (kputl(rg_idx, &str) < 0) goto memfail;
185
+ break;
186
+ case '!':
187
+ if (kputs(rg_id, &str) < 0) goto memfail;
188
+ break;
189
+ case '.':
190
+ // Only really need to cope with sam, bam, cram
191
+ if (format->format != unknown_format) {
192
+ if (kputs(hts_format_file_extension(format), &str) < 0)
193
+ goto memfail;
194
+ } else {
195
+ if (kputs("bam", &str) < 0) goto memfail;
196
+ }
197
+ break;
198
+ case '\0':
199
+ print_error("split", "Trailing %% in filename format string");
200
+ goto fail;
201
+ default:
202
+ // Error is: fprintf(samtools_stderr, "bad format string, unknown format specifier\n");
203
+ print_error("split", "Unknown specifier %%%c in filename format string", *next);
204
+ goto fail;
205
+ }
206
+ pointer = next + 1;
207
+ }
208
+ if (kputs(pointer, &str) < 0) goto memfail;
209
+ return ks_release(&str);
210
+
211
+ memfail:
212
+ print_error_errno("split", "Couldn't build output filename");
213
+ fail:
214
+ free(str.s);
215
+ return NULL;
216
+ }
217
+
218
+ // Parse the header, count the number of RG tags and return a list of their names
219
+ static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name)
220
+ {
221
+ char **names = NULL;
222
+ kstring_t id_val = KS_INITIALIZE;
223
+ int i, n_rg = sam_hdr_count_lines(hdr, "RG");
224
+
225
+ if (n_rg < 0) {
226
+ print_error("split", "Failed to get @RG IDs");
227
+ *count = 0;
228
+ *output_name = NULL;
229
+ return false;
230
+ }
231
+
232
+ if (n_rg == 0) {
233
+ *count = 0;
234
+ *output_name = NULL;
235
+ return true;
236
+ }
237
+
238
+ names = calloc(n_rg, sizeof(names[0]));
239
+ if (!names) goto memfail;
240
+
241
+ for (i = 0; i < n_rg; i++) {
242
+ if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail;
243
+ names[i] = ks_release(&id_val);
244
+ }
245
+
246
+ *count = n_rg;
247
+ *output_name = names;
248
+ return true;
249
+
250
+ memfail:
251
+ print_error_errno("split", "Failed to get @RG IDs");
252
+ *count = 0;
253
+ *output_name = NULL;
254
+ ks_free(&id_val);
255
+ free(names);
256
+ return false;
257
+ }
258
+
259
+ static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2)
260
+ {
261
+ size_t n;
262
+ if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) {
263
+ print_error("split",
264
+ "Unaccounted header contains wrong number of references");
265
+ return -1;
266
+ }
267
+ for (n = 0; n < sam_hdr_nref(hdr1); n++) {
268
+ hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n);
269
+ hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n);
270
+ if (h1_len != h2_len) {
271
+ print_error("split",
272
+ "Unaccounted header reference %zu \"%s\" is not the same length as in the input file",
273
+ n + 1, sam_hdr_tid2name(hdr2, n));
274
+ return -1;
275
+ }
276
+ }
277
+ return 0;
278
+ }
279
+
280
+ // Set the initial state
281
+ static state_t* init(parsed_opts_t* opts, const char *arg_list)
282
+ {
283
+ state_t* retval = calloc(sizeof(state_t), 1);
284
+ if (!retval) {
285
+ print_error_errno("split", "Initialisation failed");
286
+ return NULL;
287
+ }
288
+
289
+ if (opts->ga.nthreads > 0) {
290
+ if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) {
291
+ fprintf(samtools_stderr, "Error creating thread pool\n");
292
+ cleanup_state(retval, false);
293
+ return NULL;
294
+ }
295
+ }
296
+
297
+ retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in);
298
+ if (!retval->merged_input_file) {
299
+ print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name);
300
+ cleanup_state(retval, false);
301
+ return NULL;
302
+ }
303
+ if (retval->p.pool)
304
+ hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p);
305
+ retval->merged_input_header = sam_hdr_read(retval->merged_input_file);
306
+ if (retval->merged_input_header == NULL) {
307
+ print_error("split", "Could not read header from \"%s\"", opts->merged_input_name);
308
+ cleanup_state(retval, false);
309
+ return NULL;
310
+ }
311
+
312
+ if (opts->unaccounted_name) {
313
+ if (opts->unaccounted_header_name) {
314
+ samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in);
315
+ if (!hdr_load) {
316
+ print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name);
317
+ cleanup_state(retval, false);
318
+ return NULL;
319
+ }
320
+ retval->unaccounted_header = sam_hdr_read(hdr_load);
321
+ if (retval->unaccounted_header == NULL) {
322
+ print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name);
323
+ cleanup_state(retval, false);
324
+ sam_close(hdr_load);
325
+ return NULL;
326
+ }
327
+ sam_close(hdr_load);
328
+ if (header_compatible(retval->merged_input_header,
329
+ retval->unaccounted_header) != 0) {
330
+ cleanup_state(retval, false);
331
+ return NULL;
332
+ }
333
+ } else {
334
+ retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header);
335
+ if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools",
336
+ "VN", samtools_version(),
337
+ arg_list ? "CL": NULL,
338
+ arg_list ? arg_list : NULL,
339
+ NULL)) {
340
+ print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name);
341
+ cleanup_state(retval, false);
342
+ return NULL;
343
+ }
344
+ }
345
+
346
+ char outmode[4] = "w";
347
+ sam_open_mode(outmode + 1, opts->unaccounted_name, NULL);
348
+ retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out);
349
+
350
+ if (retval->unaccounted_file == NULL) {
351
+ print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name);
352
+ cleanup_state(retval, false);
353
+ return NULL;
354
+ }
355
+ if (retval->p.pool)
356
+ hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p);
357
+ }
358
+
359
+ // Open output files for RGs
360
+ if (!count_RG(retval->merged_input_header, &retval->output_count, &retval->rg_id)) return NULL;
361
+ if (opts->verbose) fprintf(samtools_stderr, "@RG's found %zu\n",retval->output_count);
362
+ // Prevent calloc(0, size);
363
+ size_t num = retval->output_count ? retval->output_count : 1;
364
+ retval->rg_index_file_name = (char **)calloc(num, sizeof(char *));
365
+ retval->rg_output_file_name = (char **)calloc(num, sizeof(char *));
366
+ retval->rg_output_file = (samFile**)calloc(num, sizeof(samFile*));
367
+ retval->rg_output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*));
368
+ retval->rg_hash = kh_init_c2i();
369
+ if (!retval->rg_output_file_name || !retval->rg_output_file || !retval->rg_output_header ||
370
+ !retval->rg_hash || !retval->rg_index_file_name) {
371
+ print_error_errno("split", "Could not initialise output file array");
372
+ cleanup_state(retval, false);
373
+ return NULL;
374
+ }
375
+
376
+ char* dirsep = strrchr(opts->merged_input_name, '/');
377
+ char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
378
+ if (!input_base_name) {
379
+ print_error_errno("split", "Filename manipulation failed");
380
+ cleanup_state(retval, false);
381
+ return NULL;
382
+ }
383
+ char* extension = strrchr(input_base_name, '.');
384
+ if (extension) *extension = '\0';
385
+
386
+ size_t i;
387
+ for (i = 0; i < retval->output_count; i++) {
388
+ char* output_filename = NULL;
389
+ char outmode[4] = "w";
390
+
391
+ output_filename = expand_format_string(opts->output_format_string,
392
+ input_base_name,
393
+ retval->rg_id[i], i,
394
+ &opts->ga.out);
395
+
396
+ if ( output_filename == NULL ) {
397
+ cleanup_state(retval, false);
398
+ free(input_base_name);
399
+ return NULL;
400
+ }
401
+
402
+ retval->rg_output_file_name[i] = output_filename;
403
+
404
+ sam_open_mode(outmode + 1, output_filename, NULL);
405
+ retval->rg_output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out);
406
+
407
+ if (retval->rg_output_file[i] == NULL) {
408
+ print_error_errno("split", "Could not open \"%s\"", output_filename);
409
+ cleanup_state(retval, false);
410
+ free(input_base_name);
411
+ return NULL;
412
+ }
413
+ if (retval->p.pool)
414
+ hts_set_opt(retval->rg_output_file[i], HTS_OPT_THREAD_POOL, &retval->p);
415
+
416
+ // Record index in hash
417
+ int ret;
418
+ khiter_t iter = kh_put_c2i(retval->rg_hash, retval->rg_id[i], &ret);
419
+ if (ret < 0) {
420
+ print_error_errno("split", "Couldn't add @RG ID to look-up table");
421
+ cleanup_state(retval, false);
422
+ free(input_base_name);
423
+ return NULL;
424
+ }
425
+ kh_val(retval->rg_hash,iter) = i;
426
+
427
+ // Set and edit header
428
+ retval->rg_output_header[i] = sam_hdr_dup(retval->merged_input_header);
429
+ if (sam_hdr_remove_except(retval->rg_output_header[i], "RG", "ID", retval->rg_id[i]) ||
430
+ (!opts->no_pg &&
431
+ sam_hdr_add_pg(retval->rg_output_header[i], "samtools",
432
+ "VN", samtools_version(),
433
+ arg_list ? "CL": NULL,
434
+ arg_list ? arg_list : NULL,
435
+ NULL))) {
436
+ print_error("split", "Could not rewrite header for \"%s\"", output_filename);
437
+ cleanup_state(retval, false);
438
+ free(input_base_name);
439
+ return NULL;
440
+ }
441
+ }
442
+
443
+ free(input_base_name);
444
+ retval->write_index = opts->ga.write_index;
445
+
446
+ return retval;
447
+ }
448
+
449
+ static bool split(state_t* state)
450
+ {
451
+ if (state->unaccounted_file && sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) {
452
+ print_error_errno("split", "Could not write output file header");
453
+ return false;
454
+ }
455
+ size_t i;
456
+ for (i = 0; i < state->output_count; i++) {
457
+ if (sam_hdr_write(state->rg_output_file[i], state->rg_output_header[i]) != 0) {
458
+ print_error_errno("split", "Could not write file header to \"%s\"", state->rg_output_file_name[i]);
459
+ return false;
460
+ }
461
+ if (state->write_index) {
462
+ state->rg_index_file_name[i] = auto_index(state->rg_output_file[i],
463
+ state->rg_output_file_name[i],
464
+ state->rg_output_header[i]);
465
+ if (!state->rg_index_file_name[i]) {
466
+ print_error_errno("split", "Could not create index for file \"%s\"", state->rg_output_file_name[i]);
467
+ return false;
468
+ }
469
+ }
470
+ }
471
+
472
+ bam1_t* file_read = bam_init1();
473
+ // Read the first record
474
+ int r;
475
+ if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
476
+ // Nothing more to read? Ignore this file
477
+ bam_destroy1(file_read);
478
+ file_read = NULL;
479
+ if (r < -1) {
480
+ print_error("split", "Could not read first input record");
481
+ return false;
482
+ }
483
+ }
484
+
485
+ while (file_read != NULL) {
486
+ // Get RG tag from read and look it up in hash to find file to output it to
487
+ uint8_t* tag = bam_aux_get(file_read, "RG");
488
+ khiter_t iter;
489
+ if ( tag != NULL ) {
490
+ char* rg = bam_aux2Z(tag);
491
+ iter = kh_get_c2i(state->rg_hash, rg);
492
+ } else {
493
+ iter = kh_end(state->rg_hash);
494
+ }
495
+
496
+ // Write the read out to correct file
497
+ if (iter != kh_end(state->rg_hash)) {
498
+ // if found write to the appropriate untangled bam
499
+ int i = kh_val(state->rg_hash,iter);
500
+ if (sam_write1(state->rg_output_file[i], state->rg_output_header[i], file_read) < 0) {
501
+ print_error_errno("split", "Could not write to \"%s\"", state->rg_output_file_name[i]);
502
+ bam_destroy1(file_read);
503
+ return false;
504
+ }
505
+ } else {
506
+ // otherwise write to the unaccounted bam if there is one or fail
507
+ if (state->unaccounted_file == NULL) {
508
+ if (tag) {
509
+ fprintf(samtools_stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag));
510
+ } else {
511
+ fprintf(samtools_stderr, "Read \"%s\" has no RG tag.\n", bam_get_qname(file_read));
512
+ }
513
+ bam_destroy1(file_read);
514
+ return false;
515
+ } else {
516
+ if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) {
517
+ print_error_errno("split", "Could not write to unaccounted output file");
518
+ bam_destroy1(file_read);
519
+ return false;
520
+ }
521
+ }
522
+ }
523
+
524
+ // Replace written read with the next one to process
525
+ if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
526
+ // Nothing more to read? Ignore this file in future
527
+ bam_destroy1(file_read);
528
+ file_read = NULL;
529
+ if (r < -1) {
530
+ print_error("split", "Could not read input record");
531
+ return false;
532
+ }
533
+ }
534
+ }
535
+
536
+ if (state->write_index) {
537
+ for (i = 0; i < state->output_count; i++) {
538
+ if (sam_idx_save(state->rg_output_file[i]) < 0) {
539
+ print_error_errno("split", "writing index failed");
540
+ return false;
541
+ }
542
+ free(state->rg_index_file_name[i]);
543
+ }
544
+ }
545
+
546
+ return true;
547
+ }
548
+
549
+ static int cleanup_state(state_t* status, bool check_close)
550
+ {
551
+ int ret = 0;
552
+
553
+ if (!status) return 0;
554
+ if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header);
555
+ if (status->unaccounted_file) {
556
+ if (sam_close(status->unaccounted_file) < 0 && check_close) {
557
+ print_error("split", "Error on closing unaccounted file");
558
+ ret = -1;
559
+ }
560
+ }
561
+ sam_close(status->merged_input_file);
562
+ size_t i;
563
+ for (i = 0; i < status->output_count; i++) {
564
+ if (status->rg_output_header && status->rg_output_header[i])
565
+ sam_hdr_destroy(status->rg_output_header[i]);
566
+ if (status->rg_output_file && status->rg_output_file[i]) {
567
+ if (sam_close(status->rg_output_file[i]) < 0 && check_close) {
568
+ print_error("split", "Error on closing output file \"%s\"", status->rg_output_file_name[i]);
569
+ ret = -1;
570
+ }
571
+ }
572
+ if (status->rg_id) free(status->rg_id[i]);
573
+ if (status->rg_output_file_name) free(status->rg_output_file_name[i]);
574
+ }
575
+ if (status->merged_input_header)
576
+ sam_hdr_destroy(status->merged_input_header);
577
+ free(status->rg_output_header);
578
+ free(status->rg_output_file);
579
+ free(status->rg_output_file_name);
580
+ free(status->rg_index_file_name);
581
+ kh_destroy_c2i(status->rg_hash);
582
+ free(status->rg_id);
583
+ if (status->p.pool)
584
+ hts_tpool_destroy(status->p.pool);
585
+ free(status);
586
+
587
+ return ret;
588
+ }
589
+
590
+ static void cleanup_opts(parsed_opts_t* opts)
591
+ {
592
+ if (!opts) return;
593
+ sam_global_args_free(&opts->ga);
594
+ free(opts);
595
+ }
596
+
597
+ int main_split(int argc, char** argv)
598
+ {
599
+ int ret = 1;
600
+ char *arg_list = NULL;
601
+ parsed_opts_t* opts = parse_args(argc, argv);
602
+ if (!opts) goto cleanup_opts;
603
+ if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
604
+ goto cleanup_opts;
605
+ state_t* status = init(opts, arg_list);
606
+ if (!status) goto cleanup_opts;
607
+
608
+ if (!split(status)) {
609
+ cleanup_state(status, false);
610
+ goto cleanup_opts;
611
+ }
612
+
613
+ ret = cleanup_state(status, true);
614
+
615
+ cleanup_opts:
616
+ cleanup_opts(opts);
617
+ free(arg_list);
618
+
619
+ return ret;
620
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_stat.c ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bam_stat.c -- flagstat subcommand.
2
+
3
+ Copyright (C) 2009, 2011, 2013-2015, 2019, 2021 Genome Research Ltd.
4
+
5
+ Author: Heng Li <lh3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <unistd.h>
28
+ #include <stdint.h>
29
+ #include <stdlib.h>
30
+ #include <string.h>
31
+ #include <stdio.h>
32
+ #include <limits.h>
33
+ #include <getopt.h>
34
+
35
+ #include "htslib/sam.h"
36
+ #include "samtools.h"
37
+ #include "sam_opts.h"
38
+
39
+ typedef struct {
40
+ long long n_reads[2], n_mapped[2], n_pair_all[2], n_pair_map[2], n_pair_good[2];
41
+ long long n_sgltn[2], n_read1[2], n_read2[2];
42
+ long long n_dup[2];
43
+ long long n_diffchr[2], n_diffhigh[2];
44
+ long long n_secondary[2], n_supp[2];
45
+ long long n_primary[2], n_pmapped[2], n_pdup[2];
46
+ } bam_flagstat_t;
47
+
48
+ inline static void flagstat_loop(bam_flagstat_t *s, bam1_core_t *c)
49
+ {
50
+ int w = (c->flag & BAM_FQCFAIL)? 1 : 0;
51
+ ++s->n_reads[w];
52
+ if (c->flag & BAM_FSECONDARY ) {
53
+ ++s->n_secondary[w];
54
+ } else if (c->flag & BAM_FSUPPLEMENTARY ) {
55
+ ++s->n_supp[w];
56
+ } else {
57
+ ++s->n_primary[w];
58
+
59
+ if (c->flag & BAM_FPAIRED) {
60
+ ++s->n_pair_all[w];
61
+ if ((c->flag & BAM_FPROPER_PAIR) && !(c->flag & BAM_FUNMAP) ) ++s->n_pair_good[w];
62
+ if (c->flag & BAM_FREAD1) ++s->n_read1[w];
63
+ if (c->flag & BAM_FREAD2) ++s->n_read2[w];
64
+ if ((c->flag & BAM_FMUNMAP) && !(c->flag & BAM_FUNMAP)) ++s->n_sgltn[w];
65
+ if (!(c->flag & BAM_FUNMAP) && !(c->flag & BAM_FMUNMAP)) {
66
+ ++s->n_pair_map[w];
67
+ if (c->mtid != c->tid) {
68
+ ++s->n_diffchr[w];
69
+ if (c->qual >= 5) ++s->n_diffhigh[w];
70
+ }
71
+ }
72
+ }
73
+
74
+ if (!(c->flag & BAM_FUNMAP)) ++s->n_pmapped[w];
75
+ if (c->flag & BAM_FDUP) ++s->n_pdup[w];
76
+ }
77
+ if (!(c->flag & BAM_FUNMAP)) ++s->n_mapped[w];
78
+ if (c->flag & BAM_FDUP) ++s->n_dup[w];
79
+ }
80
+
81
+ bam_flagstat_t *bam_flagstat_core(samFile *fp, sam_hdr_t *h)
82
+ {
83
+ bam_flagstat_t *s;
84
+ bam1_t *b;
85
+ bam1_core_t *c;
86
+ int ret;
87
+ s = (bam_flagstat_t*)calloc(1, sizeof(bam_flagstat_t));
88
+ b = bam_init1();
89
+ c = &b->core;
90
+ while ((ret = sam_read1(fp, h, b)) >= 0)
91
+ flagstat_loop(s, c);
92
+ bam_destroy1(b);
93
+ if (ret != -1) {
94
+ free(s);
95
+ return NULL;
96
+ }
97
+ return s;
98
+ }
99
+
100
+ static const char *percent(char *buffer, long long n, long long total)
101
+ {
102
+ if (total != 0) sprintf(buffer, "%.2f%%", (float)n / total * 100.0);
103
+ else strcpy(buffer, "N/A");
104
+ return buffer;
105
+ }
106
+
107
+ static const char *percent_json(char *buffer, long long n, long long total)
108
+ {
109
+ if (total != 0) sprintf(buffer, "%.2f", (float)n / total * 100.0);
110
+ else strcpy(buffer, "null");
111
+ return buffer;
112
+ }
113
+
114
+ static void usage_exit(FILE *fp, int exit_status)
115
+ {
116
+ fprintf(fp, "Usage: samtools flagstat [options] <in.bam>\n");
117
+ sam_global_opt_help(fp, "-.---@-.");
118
+ fprintf(fp, " -O, --");
119
+ fprintf(fp, "output-fmt FORMAT[,OPT[=VAL]]...\n"
120
+ " Specify output format (json, tsv)\n");
121
+ exit(exit_status);
122
+ }
123
+
124
+ static void out_fmt_default(bam_flagstat_t *s)
125
+ {
126
+ char b0[16], b1[16];
127
+ printf("%lld + %lld in total (QC-passed reads + QC-failed reads)\n", s->n_reads[0], s->n_reads[1]);
128
+ printf("%lld + %lld primary\n", s->n_primary[0], s->n_primary[1]);
129
+ printf("%lld + %lld secondary\n", s->n_secondary[0], s->n_secondary[1]);
130
+ printf("%lld + %lld supplementary\n", s->n_supp[0], s->n_supp[1]);
131
+ printf("%lld + %lld duplicates\n", s->n_dup[0], s->n_dup[1]);
132
+ printf("%lld + %lld primary duplicates\n", s->n_pdup[0], s->n_pdup[1]);
133
+ printf("%lld + %lld mapped (%s : %s)\n", s->n_mapped[0], s->n_mapped[1], percent(b0, s->n_mapped[0], s->n_reads[0]), percent(b1, s->n_mapped[1], s->n_reads[1]));
134
+ printf("%lld + %lld primary mapped (%s : %s)\n", s->n_pmapped[0], s->n_pmapped[1], percent(b0, s->n_pmapped[0], s->n_primary[0]), percent(b1, s->n_pmapped[1], s->n_primary[1]));
135
+ printf("%lld + %lld paired in sequencing\n", s->n_pair_all[0], s->n_pair_all[1]);
136
+ printf("%lld + %lld read1\n", s->n_read1[0], s->n_read1[1]);
137
+ printf("%lld + %lld read2\n", s->n_read2[0], s->n_read2[1]);
138
+ printf("%lld + %lld properly paired (%s : %s)\n", s->n_pair_good[0], s->n_pair_good[1], percent(b0, s->n_pair_good[0], s->n_pair_all[0]), percent(b1, s->n_pair_good[1], s->n_pair_all[1]));
139
+ printf("%lld + %lld with itself and mate mapped\n", s->n_pair_map[0], s->n_pair_map[1]);
140
+ printf("%lld + %lld singletons (%s : %s)\n", s->n_sgltn[0], s->n_sgltn[1], percent(b0, s->n_sgltn[0], s->n_pair_all[0]), percent(b1, s->n_sgltn[1], s->n_pair_all[1]));
141
+ printf("%lld + %lld with mate mapped to a different chr\n", s->n_diffchr[0], s->n_diffchr[1]);
142
+ printf("%lld + %lld with mate mapped to a different chr (mapQ>=5)\n", s->n_diffhigh[0], s->n_diffhigh[1]);
143
+ }
144
+
145
+ static void out_fmt_json(bam_flagstat_t *s) {
146
+ char b0[16], b1[16], p0[16], p1[16], pp0[16], pp1[16], s0[16], s1[16];
147
+ printf("{\n \"QC-passed reads\": { \n"
148
+ " \"total\": %lld, \n"
149
+ " \"primary\": %lld, \n"
150
+ " \"secondary\": %lld, \n"
151
+ " \"supplementary\": %lld, \n"
152
+ " \"duplicates\": %lld, \n"
153
+ " \"primary duplicates\": %lld, \n"
154
+ " \"mapped\": %lld, \n"
155
+ " \"mapped %%\": %s, \n"
156
+ " \"primary mapped\": %lld, \n"
157
+ " \"primary mapped %%\": %s, \n"
158
+ " \"paired in sequencing\": %lld, \n"
159
+ " \"read1\": %lld, \n"
160
+ " \"read2\": %lld, \n"
161
+ " \"properly paired\": %lld, \n"
162
+ " \"properly paired %%\": %s, \n"
163
+ " \"with itself and mate mapped\": %lld, \n"
164
+ " \"singletons\": %lld, \n"
165
+ " \"singletons %%\": %s, \n"
166
+ " \"with mate mapped to a different chr\": %lld, \n"
167
+ " \"with mate mapped to a different chr (mapQ >= 5)\": %lld \n"
168
+ " },"
169
+ "\n \"QC-failed reads\": { \n"
170
+ " \"total\": %lld, \n"
171
+ " \"primary\": %lld, \n"
172
+ " \"secondary\": %lld, \n"
173
+ " \"supplementary\": %lld, \n"
174
+ " \"duplicates\": %lld, \n"
175
+ " \"primary duplicates\": %lld, \n"
176
+ " \"mapped\": %lld, \n"
177
+ " \"mapped %%\": %s, \n"
178
+ " \"primary mapped\": %lld, \n"
179
+ " \"primary mapped %%\": %s, \n"
180
+ " \"paired in sequencing\": %lld, \n"
181
+ " \"read1\": %lld, \n"
182
+ " \"read2\": %lld, \n"
183
+ " \"properly paired\": %lld, \n"
184
+ " \"properly paired %%\": %s, \n"
185
+ " \"with itself and mate mapped\": %lld, \n"
186
+ " \"singletons\": %lld, \n"
187
+ " \"singletons %%\": %s, \n"
188
+ " \"with mate mapped to a different chr\": %lld, \n"
189
+ " \"with mate mapped to a different chr (mapQ >= 5)\": %lld \n"
190
+ " }\n"
191
+ "}\n",
192
+ s->n_reads[0],
193
+ s->n_primary[0],
194
+ s->n_secondary[0],
195
+ s->n_supp[0],
196
+ s->n_dup[0],
197
+ s->n_pdup[0],
198
+ s->n_mapped[0],
199
+ percent_json(b0, s->n_mapped[0], s->n_reads[0]),
200
+ s->n_pmapped[0],
201
+ percent_json(p0, s->n_pmapped[0], s->n_primary[0]),
202
+ s->n_pair_all[0],
203
+ s->n_read1[0],
204
+ s->n_read2[0],
205
+ s->n_pair_good[0],
206
+ percent_json(pp0, s->n_pair_good[0], s->n_pair_all[0]),
207
+ s->n_pair_map[0],
208
+ s->n_sgltn[0],
209
+ percent_json(s0, s->n_sgltn[0], s->n_pair_all[0]),
210
+ s->n_diffchr[0],
211
+ s->n_diffhigh[0],
212
+ s->n_reads[1],
213
+ s->n_primary[1],
214
+ s->n_secondary[1],
215
+ s->n_supp[1],
216
+ s->n_dup[1],
217
+ s->n_pdup[1],
218
+ s->n_mapped[1],
219
+ percent_json(b1, s->n_mapped[1], s->n_reads[1]),
220
+ s->n_pmapped[1],
221
+ percent_json(p1, s->n_pmapped[1], s->n_primary[1]),
222
+ s->n_pair_all[1],
223
+ s->n_read1[1],
224
+ s->n_read2[1],
225
+ s->n_pair_good[1],
226
+ percent_json(pp1, s->n_pair_good[1], s->n_pair_all[1]),
227
+ s->n_pair_map[1],
228
+ s->n_sgltn[1],
229
+ percent_json(s1, s->n_sgltn[1], s->n_pair_all[1]),
230
+ s->n_diffchr[1],
231
+ s->n_diffhigh[1]
232
+ );
233
+ }
234
+
235
+ static void out_fmt_tsv(bam_flagstat_t *s) {
236
+ char b0[16], b1[16];
237
+ printf("%lld\t%lld\ttotal (QC-passed reads + QC-failed reads)\n", s->n_reads[0], s->n_reads[1]);
238
+ printf("%lld\t%lld\tprimary\n", s->n_primary[0], s->n_primary[1]);
239
+ printf("%lld\t%lld\tsecondary\n", s->n_secondary[0], s->n_secondary[1]);
240
+ printf("%lld\t%lld\tsupplementary\n", s->n_supp[0], s->n_supp[1]);
241
+ printf("%lld\t%lld\tduplicates\n", s->n_dup[0], s->n_dup[1]);
242
+ printf("%lld\t%lld\tprimary duplicates\n", s->n_pdup[0], s->n_pdup[1]);
243
+ printf("%lld\t%lld\tmapped\n", s->n_mapped[0], s->n_mapped[1]);
244
+ printf("%s\t%s\tmapped %%\n", percent(b0, s->n_mapped[0], s->n_reads[0]), percent(b1, s->n_mapped[1], s->n_reads[1]));
245
+ printf("%lld\t%lld\tprimary mapped\n", s->n_pmapped[0], s->n_pmapped[1]);
246
+ printf("%s\t%s\tprimary mapped %%\n", percent(b0, s->n_pmapped[0], s->n_primary[0]), percent(b1, s->n_pmapped[1], s->n_primary[1]));
247
+ printf("%lld\t%lld\tpaired in sequencing\n", s->n_pair_all[0], s->n_pair_all[1]);
248
+ printf("%lld\t%lld\tread1\n", s->n_read1[0], s->n_read1[1]);
249
+ printf("%lld\t%lld\tread2\n", s->n_read2[0], s->n_read2[1]);
250
+ printf("%lld\t%lld\tproperly paired\n", s->n_pair_good[0], s->n_pair_good[1]);
251
+ printf("%s\t%s\tproperly paired %%\n", percent(b0, s->n_pair_good[0], s->n_pair_all[0]), percent(b1, s->n_pair_good[1], s->n_pair_all[1]));
252
+ printf("%lld\t%lld\twith itself and mate mapped\n", s->n_pair_map[0], s->n_pair_map[1]);
253
+ printf("%lld\t%lld\tsingletons\n", s->n_sgltn[0], s->n_sgltn[1]);
254
+ printf("%s\t%s\tsingletons %%\n", percent(b0, s->n_sgltn[0], s->n_pair_all[0]), percent(b1, s->n_sgltn[1], s->n_pair_all[1]));
255
+ printf("%lld\t%lld\twith mate mapped to a different chr\n", s->n_diffchr[0], s->n_diffchr[1]);
256
+ printf("%lld\t%lld\twith mate mapped to a different chr (mapQ>=5)\n", s->n_diffhigh[0], s->n_diffhigh[1]);
257
+ }
258
+
259
+ /*
260
+ * Select flagstats output format to print.
261
+ */
262
+ static void output_fmt(bam_flagstat_t *s, const char *out_fmt)
263
+ {
264
+ if (strcmp(out_fmt, "json") == 0 || strcmp(out_fmt, "JSON") == 0) {
265
+ out_fmt_json(s);
266
+ } else if (strcmp(out_fmt, "tsv") == 0 || strcmp(out_fmt, "TSV") == 0) {
267
+ out_fmt_tsv(s);
268
+ } else {
269
+ out_fmt_default(s);
270
+ }
271
+ }
272
+
273
+ int bam_flagstat(int argc, char *argv[])
274
+ {
275
+ samFile *fp;
276
+ sam_hdr_t *header;
277
+ bam_flagstat_t *s;
278
+ const char *out_fmt = "default";
279
+ int c, status = EXIT_SUCCESS;
280
+
281
+ enum {
282
+ INPUT_FMT_OPTION = CHAR_MAX+1,
283
+ };
284
+
285
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
286
+ static const struct option lopts[] = {
287
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', '-', '-', '@'),
288
+ {NULL, 0, NULL, 0}
289
+ };
290
+
291
+ while ((c = getopt_long(argc, argv, "@:O:", lopts, NULL)) >= 0) {
292
+ switch (c) {
293
+ case 'O':
294
+ out_fmt = optarg;
295
+ break;
296
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
297
+ /* else fall-through */
298
+ case '?':
299
+ usage_exit(stderr, EXIT_FAILURE);
300
+ }
301
+ }
302
+
303
+ if (argc != optind+1) {
304
+ if (argc == optind) usage_exit(stdout, EXIT_SUCCESS);
305
+ else usage_exit(stderr, EXIT_FAILURE);
306
+ }
307
+ fp = sam_open_format(argv[optind], "r", &ga.in);
308
+ if (fp == NULL) {
309
+ print_error_errno("flagstat", "Cannot open input file \"%s\"", argv[optind]);
310
+ return 1;
311
+ }
312
+ if (ga.nthreads > 0)
313
+ hts_set_threads(fp, ga.nthreads);
314
+
315
+ if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS,
316
+ SAM_FLAG | SAM_MAPQ | SAM_RNEXT)) {
317
+ fprintf(stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n");
318
+ return 1;
319
+ }
320
+
321
+ if (hts_set_opt(fp, CRAM_OPT_DECODE_MD, 0)) {
322
+ fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
323
+ return 1;
324
+ }
325
+
326
+ header = sam_hdr_read(fp);
327
+ if (header == NULL) {
328
+ fprintf(stderr, "Failed to read header for \"%s\"\n", argv[optind]);
329
+ return 1;
330
+ }
331
+
332
+ s = bam_flagstat_core(fp, header);
333
+ if (s) {
334
+ output_fmt(s, out_fmt);
335
+ free(s);
336
+ }
337
+ else {
338
+ print_error("flagstat", "error reading from \"%s\"", argv[optind]);
339
+ status = EXIT_FAILURE;
340
+ }
341
+
342
+ sam_hdr_destroy(header);
343
+ sam_close(fp);
344
+ sam_global_args_free(&ga);
345
+ return status;
346
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bamtk.c ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bamtk.c -- main samtools command front-end.
2
+
3
+ Copyright (C) 2008-2023 Genome Research Ltd.
4
+
5
+ Author: Heng Li <lh3@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <config.h>
26
+
27
+ #include <stdio.h>
28
+ #include <unistd.h>
29
+ #include <fcntl.h>
30
+ #include <string.h>
31
+
32
+ #include "htslib/hts.h"
33
+ #include "htslib/hfile.h"
34
+ #include "samtools.h"
35
+ #include "version.h"
36
+
37
+ int bam_taf2baf(int argc, char *argv[]);
38
+ int bam_mpileup(int argc, char *argv[]);
39
+ int bam_merge(int argc, char *argv[]);
40
+ int bam_index(int argc, char *argv[]);
41
+ int bam_sort(int argc, char *argv[]);
42
+ int bam_tview_main(int argc, char *argv[]);
43
+ int bam_mating(int argc, char *argv[]);
44
+ int bam_rmdup(int argc, char *argv[]);
45
+ int bam_flagstat(int argc, char *argv[]);
46
+ int bam_fillmd(int argc, char *argv[]);
47
+ int bam_idxstats(int argc, char *argv[]);
48
+ int bam_markdup(int argc, char *argv[]);
49
+ int main_samview(int argc, char *argv[]);
50
+ int main_head(int argc, char *argv[]);
51
+ int main_reheader(int argc, char *argv[]);
52
+ int main_cut_target(int argc, char *argv[]);
53
+ int main_phase(int argc, char *argv[]);
54
+ int main_cat(int argc, char *argv[]);
55
+ int main_depth(int argc, char *argv[]);
56
+ int main_coverage(int argc, char *argv[]);
57
+ int main_bam2fq(int argc, char *argv[]);
58
+ int main_pad2unpad(int argc, char *argv[]);
59
+ int main_bedcov(int argc, char *argv[]);
60
+ int main_bamshuf(int argc, char *argv[]);
61
+ int main_stats(int argc, char *argv[]);
62
+ int main_flags(int argc, char *argv[]);
63
+ int main_split(int argc, char *argv[]);
64
+ int main_quickcheck(int argc, char *argv[]);
65
+ int main_addreplacerg(int argc, char *argv[]);
66
+ int faidx_main(int argc, char *argv[]);
67
+ int dict_main(int argc, char *argv[]);
68
+ int fqidx_main(int argc, char *argv[]);
69
+ int amplicon_clip_main(int argc, char *argv[]);
70
+ int main_ampliconstats(int argc, char *argv[]);
71
+ int main_import(int argc, char *argv[]);
72
+ int main_samples(int argc, char *argv[]);
73
+ int main_consensus(int argc, char *argv[]);
74
+ int main_reference(int argc, char *argv[]);
75
+ int main_reset(int argc, char *argv[]);
76
+ int main_cram_size(int argc, char *argv[]);
77
+
78
+ const char *samtools_version()
79
+ {
80
+ return SAMTOOLS_VERSION;
81
+ }
82
+
83
+ // These come out of the config.h file built by autoconf or Makefile
84
+ const char *samtools_feature_string(void) {
85
+ const char *fmt =
86
+
87
+ #ifdef PACKAGE_URL
88
+ "build=configure "
89
+ #else
90
+ "build=Makefile "
91
+ #endif
92
+
93
+ #ifdef HAVE_CURSES
94
+ "curses=yes "
95
+ #else
96
+ "curses=no "
97
+ #endif
98
+ ;
99
+
100
+ return fmt;
101
+ }
102
+
103
+ static void long_version(void) {
104
+ printf("samtools %s\n"
105
+ "Using htslib %s\n"
106
+ "Copyright (C) 2023 Genome Research Ltd.\n",
107
+ samtools_version(), hts_version());
108
+
109
+ printf("\nSamtools compilation details:\n");
110
+ printf(" Features: %s\n", samtools_feature_string());
111
+ printf(" CC: %s\n", SAMTOOLS_CC);
112
+ printf(" CPPFLAGS: %s\n", SAMTOOLS_CPPFLAGS);
113
+ printf(" CFLAGS: %s\n", SAMTOOLS_CFLAGS);
114
+ printf(" LDFLAGS: %s\n", SAMTOOLS_LDFLAGS);
115
+ printf(" HTSDIR: %s\n", SAMTOOLS_HTSDIR);
116
+ printf(" LIBS: %s\n", SAMTOOLS_LIBS);
117
+ printf(" CURSES_LIB: %s\n", SAMTOOLS_CURSES_LIB);
118
+
119
+ printf("\nHTSlib compilation details:\n");
120
+ printf(" Features: %s\n", hts_feature_string());
121
+ printf(" CC: %s\n", hts_test_feature(HTS_FEATURE_CC));
122
+ printf(" CPPFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CPPFLAGS));
123
+ printf(" CFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CFLAGS));
124
+ printf(" LDFLAGS: %s\n", hts_test_feature(HTS_FEATURE_LDFLAGS));
125
+
126
+ // Plugins and schemes
127
+ printf("\nHTSlib URL scheme handlers present:\n");
128
+ const char *plugins[100];
129
+ int np = 100, i, j;
130
+
131
+ if (hfile_list_plugins(plugins, &np) < 0)
132
+ return;
133
+
134
+ for (i = 0; i < np; i++) {
135
+ const char *sc_list[100];
136
+ int nschemes = 100;
137
+ if (hfile_list_schemes(plugins[i], sc_list, &nschemes) < 0)
138
+ return;
139
+
140
+ printf(" %s:\t", plugins[i]);
141
+ for (j = 0; j < nschemes; j++)
142
+ printf(" %s%c", sc_list[j], ",\n"[j+1==nschemes]);
143
+ }
144
+ }
145
+
146
+ static void usage(FILE *fp)
147
+ {
148
+ /* Please improve the grouping */
149
+
150
+ fprintf(fp,
151
+ "\n"
152
+ "Program: samtools (Tools for alignments in the SAM format)\n"
153
+ "Version: %s (using htslib %s)\n\n", samtools_version(), hts_version());
154
+ fprintf(fp,
155
+ "Usage: samtools <command> [options]\n"
156
+ "\n"
157
+ "Commands:\n"
158
+ " -- Indexing\n"
159
+ " dict create a sequence dictionary file\n"
160
+ " faidx index/extract FASTA\n"
161
+ " fqidx index/extract FASTQ\n"
162
+ " index index alignment\n"
163
+ "\n"
164
+ " -- Editing\n"
165
+ " calmd recalculate MD/NM tags and '=' bases\n"
166
+ " fixmate fix mate information\n"
167
+ " reheader replace BAM header\n"
168
+ " targetcut cut fosmid regions (for fosmid pool only)\n"
169
+ " addreplacerg adds or replaces RG tags\n"
170
+ " markdup mark duplicates\n"
171
+ " ampliconclip clip oligos from the end of reads\n"
172
+ "\n"
173
+ " -- File operations\n"
174
+ " collate shuffle and group alignments by name\n"
175
+ " cat concatenate BAMs\n"
176
+ " consensus produce a consensus Pileup/FASTA/FASTQ\n"
177
+ " merge merge sorted alignments\n"
178
+ " mpileup multi-way pileup\n"
179
+ " sort sort alignment file\n"
180
+ " split splits a file by read group\n"
181
+ " quickcheck quickly check if SAM/BAM/CRAM file appears intact\n"
182
+ " fastq converts a BAM to a FASTQ\n"
183
+ " fasta converts a BAM to a FASTA\n"
184
+ " import Converts FASTA or FASTQ files to SAM/BAM/CRAM\n"
185
+ " reference Generates a reference from aligned data\n"
186
+ " reset Reverts aligner changes in reads\n"
187
+ "\n"
188
+ " -- Statistics\n"
189
+ " bedcov read depth per BED region\n"
190
+ " coverage alignment depth and percent coverage\n"
191
+ " depth compute the depth\n"
192
+ " flagstat simple stats\n"
193
+ " idxstats BAM index stats\n"
194
+ " cram-size list CRAM Content-ID and Data-Series sizes\n"
195
+ " phase phase heterozygotes\n"
196
+ " stats generate stats (former bamcheck)\n"
197
+ " ampliconstats generate amplicon specific stats\n"
198
+ "\n"
199
+ " -- Viewing\n"
200
+ " flags explain BAM flags\n"
201
+ " head header viewer\n"
202
+ " tview text alignment viewer\n"
203
+ " view SAM<->BAM<->CRAM conversion\n"
204
+ " depad convert padded BAM to unpadded BAM\n"
205
+ " samples list the samples in a set of SAM/BAM/CRAM files\n"
206
+ "\n"
207
+ " -- Misc\n"
208
+ " help [cmd] display this help message or help for [cmd]\n"
209
+ " version detailed version information\n"
210
+ "\n");
211
+ }
212
+
213
+ // This is a tricky one, but on Windows the filename wildcard expansion is done by
214
+ // the application and not by the shell, as traditionally it never had a "shell".
215
+ // Even now, DOS and Powershell do not do this expansion (but bash does).
216
+ //
217
+ // This means that Mingw/Msys implements code before main() that takes e.g. "*" and
218
+ // expands it up to a list of matching filenames. This in turn breaks things like
219
+ // specifying "*" as a region (all the unmapped reads). We take a hard line here -
220
+ // filename expansion is the task of the shell, not our application!
221
+ #ifdef _WIN32
222
+ int _CRT_glob = 0;
223
+ #endif
224
+
225
+ int main(int argc, char *argv[])
226
+ {
227
+ #ifdef _WIN32
228
+ setmode(fileno(stdout), O_BINARY);
229
+ setmode(fileno(stdin), O_BINARY);
230
+ #endif
231
+ if (argc < 2) { usage(stderr); return 1; }
232
+
233
+ if (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "--help") == 0) {
234
+ if (argc == 2) { usage(stdout); return 0; }
235
+
236
+ // Otherwise change "samtools help COMMAND [...]" to "samtools COMMAND";
237
+ // main_xyz() functions by convention display the subcommand's usage
238
+ // when invoked without any arguments.
239
+ argv++;
240
+ argc = 2;
241
+ }
242
+
243
+ int ret = 0;
244
+ if (strcmp(argv[1], "view") == 0) ret = main_samview(argc-1, argv+1);
245
+ else if (strcmp(argv[1], "import") == 0) ret = main_import(argc-1, argv+1);
246
+ else if (strcmp(argv[1], "mpileup") == 0) ret = bam_mpileup(argc-1, argv+1);
247
+ else if (strcmp(argv[1], "merge") == 0) ret = bam_merge(argc-1, argv+1);
248
+ else if (strcmp(argv[1], "sort") == 0) ret = bam_sort(argc-1, argv+1);
249
+ else if (strcmp(argv[1], "index") == 0) ret = bam_index(argc-1, argv+1);
250
+ else if (strcmp(argv[1], "idxstat") == 0 ||
251
+ strcmp(argv[1], "idxstats") == 0) ret = bam_idxstats(argc-1, argv+1);
252
+ else if (strcmp(argv[1], "faidx") == 0) ret = faidx_main(argc-1, argv+1);
253
+ else if (strcmp(argv[1], "fqidx") == 0) ret = fqidx_main(argc-1, argv+1);
254
+ else if (strcmp(argv[1], "dict") == 0) ret = dict_main(argc-1, argv+1);
255
+ else if (strcmp(argv[1], "head") == 0) ret = main_head(argc-1, argv+1);
256
+ else if (strcmp(argv[1], "fixmate") == 0) ret = bam_mating(argc-1, argv+1);
257
+ else if (strcmp(argv[1], "rmdup") == 0) ret = bam_rmdup(argc-1, argv+1);
258
+ else if (strcmp(argv[1], "markdup") == 0) ret = bam_markdup(argc-1, argv+1);
259
+ else if (strcmp(argv[1], "ampliconclip") == 0) ret = amplicon_clip_main(argc-1, argv+1);
260
+ else if (strcmp(argv[1], "flagstat") == 0 ||
261
+ strcmp(argv[1], "flagstats") == 0) ret = bam_flagstat(argc-1, argv+1);
262
+ else if (strcmp(argv[1], "calmd") == 0) ret = bam_fillmd(argc-1, argv+1);
263
+ else if (strcmp(argv[1], "fillmd") == 0) ret = bam_fillmd(argc-1, argv+1);
264
+ else if (strcmp(argv[1], "reheader") == 0) ret = main_reheader(argc-1, argv+1);
265
+ else if (strcmp(argv[1], "cat") == 0) ret = main_cat(argc-1, argv+1);
266
+ else if (strcmp(argv[1], "targetcut") == 0) ret = main_cut_target(argc-1, argv+1);
267
+ else if (strcmp(argv[1], "phase") == 0) ret = main_phase(argc-1, argv+1);
268
+ else if (strcmp(argv[1], "depth") == 0) ret = main_depth(argc-1, argv+1);
269
+ else if (strcmp(argv[1], "coverage") == 0) ret = main_coverage(argc-1, argv+1);
270
+ else if (strcmp(argv[1], "bam2fq") == 0 ||
271
+ strcmp(argv[1], "fastq") == 0 ||
272
+ strcmp(argv[1], "fasta") == 0) ret = main_bam2fq(argc-1, argv+1);
273
+ else if (strcmp(argv[1], "pad2unpad") == 0) ret = main_pad2unpad(argc-1, argv+1);
274
+ else if (strcmp(argv[1], "depad") == 0) ret = main_pad2unpad(argc-1, argv+1);
275
+ else if (strcmp(argv[1], "bedcov") == 0) ret = main_bedcov(argc-1, argv+1);
276
+ else if (strcmp(argv[1], "bamshuf") == 0) ret = main_bamshuf(argc-1, argv+1);
277
+ else if (strcmp(argv[1], "collate") == 0) ret = main_bamshuf(argc-1, argv+1);
278
+ else if (strcmp(argv[1], "stat") == 0 ||
279
+ strcmp(argv[1], "stats") == 0) ret = main_stats(argc-1, argv+1);
280
+ else if (strcmp(argv[1], "flag") == 0 ||
281
+ strcmp(argv[1], "flags") == 0) ret = main_flags(argc-1, argv+1);
282
+ else if (strcmp(argv[1], "split") == 0) ret = main_split(argc-1, argv+1);
283
+ else if (strcmp(argv[1], "quickcheck") == 0) ret = main_quickcheck(argc-1, argv+1);
284
+ else if (strcmp(argv[1], "addreplacerg") == 0) ret = main_addreplacerg(argc-1, argv+1);
285
+ else if (strcmp(argv[1], "pileup") == 0) {
286
+ fprintf(stderr, "[main] The `pileup' command has been removed. Please use `mpileup' instead.\n");
287
+ return 1;
288
+ }
289
+ else if (strcmp(argv[1], "tview") == 0) ret = bam_tview_main(argc-1, argv+1);
290
+ else if (strcmp(argv[1], "ampliconstats") == 0) ret = main_ampliconstats(argc-1, argv+1);
291
+ else if (strcmp(argv[1], "samples") == 0) ret = main_samples(argc-1, argv+1);
292
+ else if (strcmp(argv[1], "consensus") == 0) ret = main_consensus(argc-1, argv+1);
293
+ else if (strcmp(argv[1], "reference") == 0) ret = main_reference(argc-1, argv+1);
294
+ else if (strcmp(argv[1], "cram-size") == 0) ret = main_cram_size(argc-1, argv+1);
295
+ else if (strcmp(argv[1], "version") == 0 || \
296
+ strcmp(argv[1], "--version") == 0)
297
+ long_version();
298
+ else if (strcmp(argv[1], "--version-only") == 0) {
299
+ printf("%s+htslib-%s\n", samtools_version(), hts_version());
300
+ }
301
+ else if (strcmp(argv[1], "reset") == 0) ret = main_reset(argc-1, argv+1);
302
+ else {
303
+ fprintf(stderr, "[main] unrecognized command '%s'\n", argv[1]);
304
+ return 1;
305
+ }
306
+ return ret;
307
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bedidx.c -- BED file indexing.
2
+
3
+ Copyright (C) 2011 Broad Institute.
4
+ Copyright (C) 2014, 2017-2019 Genome Research Ltd.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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
+ } bed_reglist_t;
62
+
63
+ #include "htslib/khash.h"
64
+ KHASH_MAP_INIT_STR(reg, bed_reglist_t)
65
+
66
+ typedef kh_reg_t reghash_t;
67
+
68
+ #if 0
69
+ // Debug function
70
+ static void bed_print(void *reg_hash) {
71
+ reghash_t *h = (reghash_t *)reg_hash;
72
+ bed_reglist_t *p;
73
+ khint_t k;
74
+ int i;
75
+ const char *reg;
76
+
77
+ if (!h) {
78
+ printf("Hash table is empty!\n");
79
+ return;
80
+ }
81
+ for (k = kh_begin(h); k < kh_end(h); k++) {
82
+ if (kh_exist(h,k)) {
83
+ reg = kh_key(h,k);
84
+ printf("Region: '%s'\n", reg);
85
+ if ((p = &kh_val(h,k)) != NULL && p->n > 0) {
86
+ printf("Filter: %d\n", p->filter);
87
+ for (i=0; i<p->n; i++) {
88
+ printf("\tinterval[%d]: %"PRIhts_pos"-%"PRIhts_pos"\n",
89
+ i,p->a[i].beg,p->a[i].end);
90
+ }
91
+ } else {
92
+ printf("Region '%s' has no intervals!\n", reg);
93
+ }
94
+ }
95
+ }
96
+ }
97
+ #endif
98
+
99
+ static int *bed_index_core(int n, hts_pair_pos_t *a)
100
+ {
101
+ int i, j, l, *idx, *new_idx;
102
+ l = 0; idx = 0;
103
+ for (i = 0; i < n; ++i) {
104
+ hts_pos_t beg, end;
105
+ beg = a[i].beg >> LIDX_SHIFT; end = a[i].end >> LIDX_SHIFT;
106
+ if (l < end + 1) {
107
+ int old_l = l;
108
+ l = end + 1;
109
+ kroundup32(l);
110
+ new_idx = realloc(idx, l * sizeof(*idx));
111
+ if (!new_idx) {
112
+ free(idx);
113
+ return NULL;
114
+ }
115
+ idx = new_idx;
116
+
117
+ for (j = old_l; j < l; ++j)
118
+ idx[j] = -1;
119
+ }
120
+
121
+ for (j = beg; j < end+1; ++j)
122
+ if (idx[j] < 0)
123
+ idx[j] = i;
124
+ }
125
+ return idx;
126
+ }
127
+
128
+ static void bed_index(void *_h)
129
+ {
130
+ reghash_t *h = (reghash_t*)_h;
131
+ khint_t k;
132
+ for (k = 0; k < kh_end(h); ++k) {
133
+ if (kh_exist(h, k)) {
134
+ bed_reglist_t *p = &kh_val(h, k);
135
+ if (p->idx) free(p->idx);
136
+ ks_introsort(hts_pair_pos_t, p->n, p->a);
137
+ p->idx = bed_index_core(p->n, p->a);
138
+ }
139
+ }
140
+ }
141
+
142
+ static int bed_minoff(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) {
143
+ int i, min_off=0;
144
+
145
+ if (p && p->idx) {
146
+ min_off = (beg>>LIDX_SHIFT >= p->n)? p->idx[p->n-1] : p->idx[beg>>LIDX_SHIFT];
147
+ if (min_off < 0) { // TODO: this block can be improved, but speed should not matter too much here
148
+ hts_pos_t n = beg>>LIDX_SHIFT;
149
+ if (n > p->n)
150
+ n = p->n;
151
+ for (i = n - 1; i >= 0; --i)
152
+ if (p->idx[i] >= 0)
153
+ break;
154
+ min_off = i >= 0? p->idx[i] : 0;
155
+ }
156
+ }
157
+
158
+ return min_off;
159
+ }
160
+
161
+ static int bed_overlap_core(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end)
162
+ {
163
+ int i, min_off;
164
+ if (p->n == 0) return 0;
165
+ min_off = bed_minoff(p, beg, end);
166
+
167
+ for (i = min_off; i < p->n; ++i) {
168
+ if (p->a[i].beg >= end) break; // out of range; no need to proceed
169
+ if (p->a[i].end > beg && p->a[i].beg < end)
170
+ return 1; // find the overlap; return
171
+ }
172
+ return 0;
173
+ }
174
+
175
+ int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end)
176
+ {
177
+ const reghash_t *h = (const reghash_t*)_h;
178
+ khint_t k;
179
+ if (!h) return 0;
180
+ k = kh_get(reg, h, chr);
181
+ if (k == kh_end(h)) return 0;
182
+ return bed_overlap_core(&kh_val(h, k), beg, end);
183
+ }
184
+
185
+ /** @brief Trim a sorted interval list, inside a region hash table,
186
+ * by removing completely contained intervals and merging adjacent or
187
+ * overlapping intervals.
188
+ * @param reg_hash the region hash table with interval lists as values
189
+ */
190
+
191
+ void bed_unify(void *reg_hash) {
192
+
193
+ int i, j, new_n;
194
+ reghash_t *h;
195
+ bed_reglist_t *p;
196
+
197
+ if (!reg_hash)
198
+ return;
199
+
200
+ h = (reghash_t *)reg_hash;
201
+
202
+ for (i = kh_begin(h); i < kh_end(h); i++) {
203
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || !(p->n))
204
+ continue;
205
+
206
+ for (new_n = 0, j = 1; j < p->n; j++) {
207
+ if (p->a[new_n].end < p->a[j].beg) {
208
+ p->a[++new_n] = p->a[j];
209
+ } else {
210
+ if (p->a[new_n].end < p->a[j].end)
211
+ p->a[new_n].end = p->a[j].end;
212
+ }
213
+ }
214
+
215
+ p->n = ++new_n;
216
+ }
217
+ }
218
+
219
+ /* "BED" file reader, which actually reads two different formats.
220
+
221
+ BED files contain between three and nine fields per line, of which
222
+ only the first three (reference, start, end) are of interest to us.
223
+ BED counts positions from base 0, and the end is the base after the
224
+ region of interest. While not properly documented in the specification,
225
+ it is also possible to have 'browser' and 'track' lines in BED files that
226
+ do not follow the standard format and should be ignored. Examination
227
+ of the BED file reading code in
228
+ http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git shows that BED
229
+ files can also have comment lines starting with '#', leading whitespace
230
+ is stripped, and that fields are separated by one or more consecutive
231
+ whitespace characters.
232
+
233
+ The alternative format was originally for reading positions in VCF
234
+ format. This expects two columns, which indicate the reference and
235
+ a position. The position corresponds to a single base, and unlike
236
+ BED counts from 1.
237
+
238
+ Which format is in use is determined based on whether one or two
239
+ numbers can be decoded on the line. As this choice is made line-by-line
240
+ in this implementation, it is possible (but probably a bad idea) to mix
241
+ both formats in the same file. If trying to read a VCF file by this
242
+ method, it would be important to ensure that the third column (ID) does
243
+ not contain any entries that start with a digit, to avoid the line
244
+ erroneously being parsed as a BED file entry.
245
+
246
+ The BED specification is at http://www.genome.ucsc.edu/FAQ/FAQformat.html
247
+ The VCF specification is at https://github.com/samtools/hts-specs
248
+ */
249
+
250
+ void *bed_read(const char *fn)
251
+ {
252
+ reghash_t *h = kh_init(reg);
253
+ gzFile fp;
254
+ kstream_t *ks = NULL;
255
+ int dret;
256
+ unsigned int line = 0, save_errno;
257
+ kstring_t str = { 0, 0, NULL };
258
+
259
+ if (NULL == h) return NULL;
260
+ // read the list
261
+ fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
262
+ if (fp == 0) return 0;
263
+ ks = ks_init(fp);
264
+ if (NULL == ks) goto fail; // In case ks_init ever gets error checking...
265
+ int ks_len;
266
+ while ((ks_len = ks_getuntil(ks, KS_SEP_LINE, &str, &dret)) >= 0) { // read a line
267
+ char *ref = str.s, *ref_end;
268
+ uint64_t beg = 0, end = 0;
269
+ int num = 0;
270
+ khint_t k;
271
+ bed_reglist_t *p;
272
+
273
+ if (ks_len == 0)
274
+ continue; // skip blank lines
275
+
276
+ line++;
277
+ while (*ref && isspace(*ref)) ref++;
278
+ if ('\0' == *ref) continue; // Skip blank lines
279
+ if ('#' == *ref) continue; // Skip BED file comments
280
+ ref_end = ref; // look for the end of the reference name
281
+ while (*ref_end && !isspace(*ref_end)) ref_end++;
282
+ if ('\0' != *ref_end) {
283
+ *ref_end = '\0'; // terminate ref and look for start, end
284
+ num = sscanf(ref_end + 1, "%"SCNu64" %"SCNu64, &beg, &end);
285
+ }
286
+ if (1 == num) { // VCF-style format
287
+ end = beg--; // Counts from 1 instead of 0 for BED files
288
+ }
289
+ if (num < 1 || end < beg) {
290
+ // These two are special lines that can occur in BED files.
291
+ // Check for them here instead of earlier in case someone really
292
+ // has called their reference "browser" or "track".
293
+ if (0 == strcmp(ref, "browser")) continue;
294
+ if (0 == strcmp(ref, "track")) continue;
295
+ if (num < 1) {
296
+ fprintf(stderr,
297
+ "[bed_read] Parse error reading \"%s\" at line %u\n",
298
+ fn, line);
299
+ } else {
300
+ fprintf(stderr,
301
+ "[bed_read] Parse error reading \"%s\" at line %u : "
302
+ "end (%"PRIu64") must not be less "
303
+ "than start (%"PRIu64")\n",
304
+ fn, line, end, beg);
305
+ }
306
+ errno = 0; // Prevent caller from printing misleading error messages
307
+ goto fail;
308
+ }
309
+
310
+ // Put reg in the hash table if not already there
311
+ k = kh_get(reg, h, ref);
312
+ if (k == kh_end(h)) { // absent from the hash table
313
+ int ret;
314
+ char *s = strdup(ref);
315
+ if (NULL == s) goto fail;
316
+ k = kh_put(reg, h, s, &ret);
317
+ if (-1 == ret) {
318
+ free(s);
319
+ goto fail;
320
+ }
321
+ memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
322
+ }
323
+ p = &kh_val(h, k);
324
+
325
+ // Add begin,end to the list
326
+ if (p->n == p->m) {
327
+ p->m = p->m ? p->m<<1 : 4;
328
+ hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
329
+ if (NULL == new_a) goto fail;
330
+ p->a = new_a;
331
+ }
332
+ p->a[p->n].beg = beg;
333
+ p->a[p->n++].end = end;
334
+ }
335
+ // FIXME: Need to check for errors in ks_getuntil. At the moment it
336
+ // doesn't look like it can return one. Possibly use gzgets instead?
337
+
338
+ if (gzclose(fp) != Z_OK) {
339
+ fp = NULL;
340
+ goto fail;
341
+ }
342
+ ks_destroy(ks);
343
+ free(str.s);
344
+ bed_index(h);
345
+ //bed_unify(h);
346
+ return h;
347
+ fail:
348
+ save_errno = errno;
349
+ if (ks) ks_destroy(ks);
350
+ if (fp) gzclose(fp);
351
+ free(str.s);
352
+ bed_destroy(h);
353
+ errno = save_errno;
354
+ return NULL;
355
+ }
356
+
357
+ void bed_destroy(void *_h)
358
+ {
359
+ reghash_t *h;
360
+ khint_t k;
361
+
362
+ if (!_h)
363
+ return;
364
+
365
+ h = (reghash_t*)_h;
366
+ for (k = 0; k < kh_end(h); ++k) {
367
+ if (kh_exist(h, k)) {
368
+ free(kh_val(h, k).a);
369
+ free(kh_val(h, k).idx);
370
+ free((char*)kh_key(h, k));
371
+ }
372
+ }
373
+ kh_destroy(reg, h);
374
+ }
375
+
376
+ static void *bed_insert(void *reg_hash, char *reg, hts_pos_t beg, hts_pos_t end) {
377
+
378
+ reghash_t *h;
379
+ khint_t k;
380
+ bed_reglist_t *p;
381
+
382
+ if (!reg_hash)
383
+ return NULL;
384
+
385
+ h = (reghash_t *)reg_hash;
386
+
387
+ // Put reg in the hash table if not already there
388
+ k = kh_get(reg, h, reg); //looks strange, but only the second reg is the actual region name.
389
+ if (k == kh_end(h)) { // absent from the hash table
390
+ int ret;
391
+ char *s = strdup(reg);
392
+ if (NULL == s) goto fail;
393
+ k = kh_put(reg, h, s, &ret);
394
+ if (-1 == ret) {
395
+ free(s);
396
+ goto fail;
397
+ }
398
+ memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
399
+ }
400
+ p = &kh_val(h, k);
401
+
402
+ // Add beg and end to the list
403
+ if (p->n == p->m) {
404
+ p->m = p->m ? p->m<<1 : 4;
405
+ hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
406
+ if (NULL == new_a) goto fail;
407
+ p->a = new_a;
408
+ }
409
+ p->a[p->n].beg = beg;
410
+ p->a[p->n++].end = end;
411
+
412
+ fail:
413
+ return h;
414
+ }
415
+
416
+ /* @brief Filter a region hash table (coming from the BED file) by another
417
+ * region hash table (coming from CLI), so that only intervals contained in
418
+ * both hash tables are kept.
419
+ * @param reg_hash the target region hash table
420
+ * @param tmp_hash the filter region hash table
421
+ * @return pointer to the filtered hash table
422
+ */
423
+
424
+ static void *bed_filter(void *reg_hash, void *tmp_hash) {
425
+
426
+ reghash_t *h;
427
+ reghash_t *t;
428
+ bed_reglist_t *p, *q;
429
+ khint_t l, k;
430
+ hts_pair_pos_t *new_a;
431
+ int i, j, new_n, min_off;
432
+ const char *reg;
433
+ hts_pos_t beg, end;
434
+
435
+ h = (reghash_t *)reg_hash;
436
+ t = (reghash_t *)tmp_hash;
437
+ if (!h)
438
+ return NULL;
439
+ if (!t)
440
+ return h;
441
+
442
+ for (l = kh_begin(t); l < kh_end(t); l++) {
443
+ if (!kh_exist(t,l) || !(q = &kh_val(t,l)) || !(q->n))
444
+ continue;
445
+
446
+ reg = kh_key(t,l);
447
+ k = kh_get(reg, h, reg); //looks strange, but only the second reg is a proper argument.
448
+ if (k == kh_end(h) || !(p = &kh_val(h, k)) || !(p->n))
449
+ continue;
450
+
451
+ new_a = calloc(q->n + p->n, sizeof(new_a[0]));
452
+ if (!new_a)
453
+ return NULL;
454
+ new_n = 0;
455
+
456
+ for (i = 0; i < q->n; i++) {
457
+ beg = q->a[i].beg;
458
+ end = q->a[i].end;
459
+
460
+ min_off = bed_minoff(p, beg, end);
461
+ for (j = min_off; j < p->n; ++j) {
462
+ if (p->a[j].beg >= end) break; // out of range; no need to proceed
463
+ if (p->a[j].end > beg && p->a[j].beg < end) {
464
+ new_a[new_n].beg = MAX(p->a[j].beg, beg);
465
+ new_a[new_n++].end = MIN(p->a[j].end, end);
466
+ }
467
+ }
468
+ }
469
+
470
+ if (new_n > 0) {
471
+ free(p->a);
472
+ p->a = new_a;
473
+ p->n = new_n;
474
+ p->m = new_n;
475
+ p->filter = FILTERED;
476
+ } else {
477
+ free(new_a);
478
+ p->filter = ALL;
479
+ }
480
+ }
481
+
482
+ return h;
483
+ }
484
+
485
+ void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op) {
486
+
487
+ reghash_t *h = (reghash_t *)reg_hash;
488
+ reghash_t *t = NULL;
489
+
490
+ int i;
491
+ char reg[1024];
492
+ const char *q;
493
+ int beg, end;
494
+
495
+ if (h) {
496
+ t = kh_init(reg);
497
+ if (!t) {
498
+ fprintf(stderr, "Error when creating the temporary region hash table!\n");
499
+ return NULL;
500
+ }
501
+ } else {
502
+ h = kh_init(reg);
503
+ if (!h) {
504
+ fprintf(stderr, "Error when creating the region hash table!\n");
505
+ return NULL;
506
+ }
507
+ *op = 1;
508
+ }
509
+
510
+ for (i=first; i<last; i++) {
511
+
512
+ // Note, ideally we would call sam_parse_region here, but it's complicated by not
513
+ // having the sam header known and the likelihood of the bed file containing data for other
514
+ // references too which we currently just ignore.
515
+ //
516
+ // TO DO...
517
+ q = hts_parse_reg(regs[i], &beg, &end);
518
+ if (q) {
519
+ if ((int)(q - regs[i] + 1) > 1024) {
520
+ fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
521
+ continue;
522
+ }
523
+ strncpy(reg, regs[i], q - regs[i]);
524
+ reg[q - regs[i]] = 0;
525
+ } else {
526
+ // not parsable as a region, but possibly a sequence named "foo:a"
527
+ if (strlen(regs[i]) + 1 > 1024) {
528
+ fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
529
+ continue;
530
+ }
531
+ strcpy(reg, regs[i]);
532
+ beg = 0; end = INT_MAX;
533
+ }
534
+
535
+ //if op==1 insert reg to the bed hash table
536
+ if (*op && !(bed_insert(h, reg, beg, end))) {
537
+ fprintf(stderr, "Error when inserting region='%s' in the bed hash table at address=%p!\n", regs[i], h);
538
+ }
539
+ //if op==0, first insert the regions in the temporary hash table,
540
+ //then filter the bed hash table using it
541
+ if (!(*op) && !(bed_insert(t, reg, beg, end))) {
542
+ fprintf(stderr, "Error when inserting region='%s' in the temporary hash table at address=%p!\n", regs[i], t);
543
+ }
544
+ }
545
+
546
+ if (!(*op)) {
547
+ bed_index(t);
548
+ bed_unify(t);
549
+ h = bed_filter(h, t);
550
+ bed_destroy(t);
551
+ }
552
+
553
+ if (h) {
554
+ bed_index(h);
555
+ bed_unify(h);
556
+ }
557
+
558
+ return h;
559
+ }
560
+
561
+ const char* bed_get(void *reg_hash, int i, int filter) {
562
+
563
+ reghash_t *h;
564
+ bed_reglist_t *p;
565
+
566
+ if (!reg_hash)
567
+ return NULL;
568
+
569
+ h = (reghash_t *)reg_hash;
570
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
571
+ return NULL;
572
+
573
+ return kh_key(h, i);
574
+ }
575
+
576
+ /**
577
+ * Create a region list from a the region hash table
578
+ * @param reg_hash The region hash table
579
+ * @param filter 0 - allow all regions, 1 - allow only selected regions
580
+ * @param n_reg Pointer to the returned region number
581
+ * @return The regions list as a hts_reglist_t
582
+ */
583
+
584
+ hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *n_reg) {
585
+
586
+ reghash_t *h;
587
+ bed_reglist_t *p;
588
+ khint_t i;
589
+ hts_reglist_t *reglist = NULL;
590
+ int count = 0;
591
+ int j;
592
+
593
+ if (!reg_hash)
594
+ return NULL;
595
+
596
+ h = (reghash_t *)reg_hash;
597
+
598
+ for (i = kh_begin(h); i < kh_end(h); i++) {
599
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
600
+ continue;
601
+ count++;
602
+ }
603
+ if (!count)
604
+ return NULL;
605
+
606
+ reglist = (hts_reglist_t *)calloc(count, sizeof(hts_reglist_t));
607
+ if (!reglist)
608
+ return NULL;
609
+
610
+ *n_reg = count;
611
+ count = 0;
612
+
613
+ for (i = kh_begin(h); i < kh_end(h) && count < *n_reg; i++) {
614
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
615
+ continue;
616
+
617
+ reglist[count].reg = kh_key(h,i);
618
+ reglist[count].intervals = (hts_pair32_t *)calloc(p->n, sizeof(hts_pair32_t));
619
+ if(!(reglist[count].intervals)) {
620
+ hts_reglist_free(reglist, count);
621
+ return NULL;
622
+ }
623
+ reglist[count].count = p->n;
624
+ reglist[count].max_end = 0;
625
+
626
+ for (j = 0; j < p->n; j++) {
627
+ reglist[count].intervals[j].beg = p->a[j].beg;
628
+ reglist[count].intervals[j].end = p->a[j].end;
629
+
630
+ if (reglist[count].intervals[j].end > reglist[count].max_end)
631
+ reglist[count].max_end = reglist[count].intervals[j].end;
632
+ }
633
+ count++;
634
+ }
635
+
636
+ return reglist;
637
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c.pysam.c ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Genome Research Ltd.
7
+
8
+ Author: Heng Li <lh3@sanger.ac.uk>
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
+ } bed_reglist_t;
64
+
65
+ #include "htslib/khash.h"
66
+ KHASH_MAP_INIT_STR(reg, bed_reglist_t)
67
+
68
+ typedef kh_reg_t reghash_t;
69
+
70
+ #if 0
71
+ // Debug function
72
+ static void bed_print(void *reg_hash) {
73
+ reghash_t *h = (reghash_t *)reg_hash;
74
+ bed_reglist_t *p;
75
+ khint_t k;
76
+ int i;
77
+ const char *reg;
78
+
79
+ if (!h) {
80
+ fprintf(samtools_stdout, "Hash table is empty!\n");
81
+ return;
82
+ }
83
+ for (k = kh_begin(h); k < kh_end(h); k++) {
84
+ if (kh_exist(h,k)) {
85
+ reg = kh_key(h,k);
86
+ fprintf(samtools_stdout, "Region: '%s'\n", reg);
87
+ if ((p = &kh_val(h,k)) != NULL && p->n > 0) {
88
+ fprintf(samtools_stdout, "Filter: %d\n", p->filter);
89
+ for (i=0; i<p->n; i++) {
90
+ fprintf(samtools_stdout, "\tinterval[%d]: %"PRIhts_pos"-%"PRIhts_pos"\n",
91
+ i,p->a[i].beg,p->a[i].end);
92
+ }
93
+ } else {
94
+ fprintf(samtools_stdout, "Region '%s' has no intervals!\n", reg);
95
+ }
96
+ }
97
+ }
98
+ }
99
+ #endif
100
+
101
+ static int *bed_index_core(int n, hts_pair_pos_t *a)
102
+ {
103
+ int i, j, l, *idx, *new_idx;
104
+ l = 0; idx = 0;
105
+ for (i = 0; i < n; ++i) {
106
+ hts_pos_t beg, end;
107
+ beg = a[i].beg >> LIDX_SHIFT; end = a[i].end >> LIDX_SHIFT;
108
+ if (l < end + 1) {
109
+ int old_l = l;
110
+ l = end + 1;
111
+ kroundup32(l);
112
+ new_idx = realloc(idx, l * sizeof(*idx));
113
+ if (!new_idx) {
114
+ free(idx);
115
+ return NULL;
116
+ }
117
+ idx = new_idx;
118
+
119
+ for (j = old_l; j < l; ++j)
120
+ idx[j] = -1;
121
+ }
122
+
123
+ for (j = beg; j < end+1; ++j)
124
+ if (idx[j] < 0)
125
+ idx[j] = i;
126
+ }
127
+ return idx;
128
+ }
129
+
130
+ static void bed_index(void *_h)
131
+ {
132
+ reghash_t *h = (reghash_t*)_h;
133
+ khint_t k;
134
+ for (k = 0; k < kh_end(h); ++k) {
135
+ if (kh_exist(h, k)) {
136
+ bed_reglist_t *p = &kh_val(h, k);
137
+ if (p->idx) free(p->idx);
138
+ ks_introsort(hts_pair_pos_t, p->n, p->a);
139
+ p->idx = bed_index_core(p->n, p->a);
140
+ }
141
+ }
142
+ }
143
+
144
+ static int bed_minoff(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) {
145
+ int i, min_off=0;
146
+
147
+ if (p && p->idx) {
148
+ min_off = (beg>>LIDX_SHIFT >= p->n)? p->idx[p->n-1] : p->idx[beg>>LIDX_SHIFT];
149
+ if (min_off < 0) { // TODO: this block can be improved, but speed should not matter too much here
150
+ hts_pos_t n = beg>>LIDX_SHIFT;
151
+ if (n > p->n)
152
+ n = p->n;
153
+ for (i = n - 1; i >= 0; --i)
154
+ if (p->idx[i] >= 0)
155
+ break;
156
+ min_off = i >= 0? p->idx[i] : 0;
157
+ }
158
+ }
159
+
160
+ return min_off;
161
+ }
162
+
163
+ static int bed_overlap_core(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end)
164
+ {
165
+ int i, min_off;
166
+ if (p->n == 0) return 0;
167
+ min_off = bed_minoff(p, beg, end);
168
+
169
+ for (i = min_off; i < p->n; ++i) {
170
+ if (p->a[i].beg >= end) break; // out of range; no need to proceed
171
+ if (p->a[i].end > beg && p->a[i].beg < end)
172
+ return 1; // find the overlap; return
173
+ }
174
+ return 0;
175
+ }
176
+
177
+ int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end)
178
+ {
179
+ const reghash_t *h = (const reghash_t*)_h;
180
+ khint_t k;
181
+ if (!h) return 0;
182
+ k = kh_get(reg, h, chr);
183
+ if (k == kh_end(h)) return 0;
184
+ return bed_overlap_core(&kh_val(h, k), beg, end);
185
+ }
186
+
187
+ /** @brief Trim a sorted interval list, inside a region hash table,
188
+ * by removing completely contained intervals and merging adjacent or
189
+ * overlapping intervals.
190
+ * @param reg_hash the region hash table with interval lists as values
191
+ */
192
+
193
+ void bed_unify(void *reg_hash) {
194
+
195
+ int i, j, new_n;
196
+ reghash_t *h;
197
+ bed_reglist_t *p;
198
+
199
+ if (!reg_hash)
200
+ return;
201
+
202
+ h = (reghash_t *)reg_hash;
203
+
204
+ for (i = kh_begin(h); i < kh_end(h); i++) {
205
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || !(p->n))
206
+ continue;
207
+
208
+ for (new_n = 0, j = 1; j < p->n; j++) {
209
+ if (p->a[new_n].end < p->a[j].beg) {
210
+ p->a[++new_n] = p->a[j];
211
+ } else {
212
+ if (p->a[new_n].end < p->a[j].end)
213
+ p->a[new_n].end = p->a[j].end;
214
+ }
215
+ }
216
+
217
+ p->n = ++new_n;
218
+ }
219
+ }
220
+
221
+ /* "BED" file reader, which actually reads two different formats.
222
+
223
+ BED files contain between three and nine fields per line, of which
224
+ only the first three (reference, start, end) are of interest to us.
225
+ BED counts positions from base 0, and the end is the base after the
226
+ region of interest. While not properly documented in the specification,
227
+ it is also possible to have 'browser' and 'track' lines in BED files that
228
+ do not follow the standard format and should be ignored. Examination
229
+ of the BED file reading code in
230
+ http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git shows that BED
231
+ files can also have comment lines starting with '#', leading whitespace
232
+ is stripped, and that fields are separated by one or more consecutive
233
+ whitespace characters.
234
+
235
+ The alternative format was originally for reading positions in VCF
236
+ format. This expects two columns, which indicate the reference and
237
+ a position. The position corresponds to a single base, and unlike
238
+ BED counts from 1.
239
+
240
+ Which format is in use is determined based on whether one or two
241
+ numbers can be decoded on the line. As this choice is made line-by-line
242
+ in this implementation, it is possible (but probably a bad idea) to mix
243
+ both formats in the same file. If trying to read a VCF file by this
244
+ method, it would be important to ensure that the third column (ID) does
245
+ not contain any entries that start with a digit, to avoid the line
246
+ erroneously being parsed as a BED file entry.
247
+
248
+ The BED specification is at http://www.genome.ucsc.edu/FAQ/FAQformat.html
249
+ The VCF specification is at https://github.com/samtools/hts-specs
250
+ */
251
+
252
+ void *bed_read(const char *fn)
253
+ {
254
+ reghash_t *h = kh_init(reg);
255
+ gzFile fp;
256
+ kstream_t *ks = NULL;
257
+ int dret;
258
+ unsigned int line = 0, save_errno;
259
+ kstring_t str = { 0, 0, NULL };
260
+
261
+ if (NULL == h) return NULL;
262
+ // read the list
263
+ fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
264
+ if (fp == 0) return 0;
265
+ ks = ks_init(fp);
266
+ if (NULL == ks) goto fail; // In case ks_init ever gets error checking...
267
+ int ks_len;
268
+ while ((ks_len = ks_getuntil(ks, KS_SEP_LINE, &str, &dret)) >= 0) { // read a line
269
+ char *ref = str.s, *ref_end;
270
+ uint64_t beg = 0, end = 0;
271
+ int num = 0;
272
+ khint_t k;
273
+ bed_reglist_t *p;
274
+
275
+ if (ks_len == 0)
276
+ continue; // skip blank lines
277
+
278
+ line++;
279
+ while (*ref && isspace(*ref)) ref++;
280
+ if ('\0' == *ref) continue; // Skip blank lines
281
+ if ('#' == *ref) continue; // Skip BED file comments
282
+ ref_end = ref; // look for the end of the reference name
283
+ while (*ref_end && !isspace(*ref_end)) ref_end++;
284
+ if ('\0' != *ref_end) {
285
+ *ref_end = '\0'; // terminate ref and look for start, end
286
+ num = sscanf(ref_end + 1, "%"SCNu64" %"SCNu64, &beg, &end);
287
+ }
288
+ if (1 == num) { // VCF-style format
289
+ end = beg--; // Counts from 1 instead of 0 for BED files
290
+ }
291
+ if (num < 1 || end < beg) {
292
+ // These two are special lines that can occur in BED files.
293
+ // Check for them here instead of earlier in case someone really
294
+ // has called their reference "browser" or "track".
295
+ if (0 == strcmp(ref, "browser")) continue;
296
+ if (0 == strcmp(ref, "track")) continue;
297
+ if (num < 1) {
298
+ fprintf(samtools_stderr,
299
+ "[bed_read] Parse error reading \"%s\" at line %u\n",
300
+ fn, line);
301
+ } else {
302
+ fprintf(samtools_stderr,
303
+ "[bed_read] Parse error reading \"%s\" at line %u : "
304
+ "end (%"PRIu64") must not be less "
305
+ "than start (%"PRIu64")\n",
306
+ fn, line, end, beg);
307
+ }
308
+ errno = 0; // Prevent caller from printing misleading error messages
309
+ goto fail;
310
+ }
311
+
312
+ // Put reg in the hash table if not already there
313
+ k = kh_get(reg, h, ref);
314
+ if (k == kh_end(h)) { // absent from the hash table
315
+ int ret;
316
+ char *s = strdup(ref);
317
+ if (NULL == s) goto fail;
318
+ k = kh_put(reg, h, s, &ret);
319
+ if (-1 == ret) {
320
+ free(s);
321
+ goto fail;
322
+ }
323
+ memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
324
+ }
325
+ p = &kh_val(h, k);
326
+
327
+ // Add begin,end to the list
328
+ if (p->n == p->m) {
329
+ p->m = p->m ? p->m<<1 : 4;
330
+ hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
331
+ if (NULL == new_a) goto fail;
332
+ p->a = new_a;
333
+ }
334
+ p->a[p->n].beg = beg;
335
+ p->a[p->n++].end = end;
336
+ }
337
+ // FIXME: Need to check for errors in ks_getuntil. At the moment it
338
+ // doesn't look like it can return one. Possibly use gzgets instead?
339
+
340
+ if (gzclose(fp) != Z_OK) {
341
+ fp = NULL;
342
+ goto fail;
343
+ }
344
+ ks_destroy(ks);
345
+ free(str.s);
346
+ bed_index(h);
347
+ //bed_unify(h);
348
+ return h;
349
+ fail:
350
+ save_errno = errno;
351
+ if (ks) ks_destroy(ks);
352
+ if (fp) gzclose(fp);
353
+ free(str.s);
354
+ bed_destroy(h);
355
+ errno = save_errno;
356
+ return NULL;
357
+ }
358
+
359
+ void bed_destroy(void *_h)
360
+ {
361
+ reghash_t *h;
362
+ khint_t k;
363
+
364
+ if (!_h)
365
+ return;
366
+
367
+ h = (reghash_t*)_h;
368
+ for (k = 0; k < kh_end(h); ++k) {
369
+ if (kh_exist(h, k)) {
370
+ free(kh_val(h, k).a);
371
+ free(kh_val(h, k).idx);
372
+ free((char*)kh_key(h, k));
373
+ }
374
+ }
375
+ kh_destroy(reg, h);
376
+ }
377
+
378
+ static void *bed_insert(void *reg_hash, char *reg, hts_pos_t beg, hts_pos_t end) {
379
+
380
+ reghash_t *h;
381
+ khint_t k;
382
+ bed_reglist_t *p;
383
+
384
+ if (!reg_hash)
385
+ return NULL;
386
+
387
+ h = (reghash_t *)reg_hash;
388
+
389
+ // Put reg in the hash table if not already there
390
+ k = kh_get(reg, h, reg); //looks strange, but only the second reg is the actual region name.
391
+ if (k == kh_end(h)) { // absent from the hash table
392
+ int ret;
393
+ char *s = strdup(reg);
394
+ if (NULL == s) goto fail;
395
+ k = kh_put(reg, h, s, &ret);
396
+ if (-1 == ret) {
397
+ free(s);
398
+ goto fail;
399
+ }
400
+ memset(&kh_val(h, k), 0, sizeof(bed_reglist_t));
401
+ }
402
+ p = &kh_val(h, k);
403
+
404
+ // Add beg and end to the list
405
+ if (p->n == p->m) {
406
+ p->m = p->m ? p->m<<1 : 4;
407
+ hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0]));
408
+ if (NULL == new_a) goto fail;
409
+ p->a = new_a;
410
+ }
411
+ p->a[p->n].beg = beg;
412
+ p->a[p->n++].end = end;
413
+
414
+ fail:
415
+ return h;
416
+ }
417
+
418
+ /* @brief Filter a region hash table (coming from the BED file) by another
419
+ * region hash table (coming from CLI), so that only intervals contained in
420
+ * both hash tables are kept.
421
+ * @param reg_hash the target region hash table
422
+ * @param tmp_hash the filter region hash table
423
+ * @return pointer to the filtered hash table
424
+ */
425
+
426
+ static void *bed_filter(void *reg_hash, void *tmp_hash) {
427
+
428
+ reghash_t *h;
429
+ reghash_t *t;
430
+ bed_reglist_t *p, *q;
431
+ khint_t l, k;
432
+ hts_pair_pos_t *new_a;
433
+ int i, j, new_n, min_off;
434
+ const char *reg;
435
+ hts_pos_t beg, end;
436
+
437
+ h = (reghash_t *)reg_hash;
438
+ t = (reghash_t *)tmp_hash;
439
+ if (!h)
440
+ return NULL;
441
+ if (!t)
442
+ return h;
443
+
444
+ for (l = kh_begin(t); l < kh_end(t); l++) {
445
+ if (!kh_exist(t,l) || !(q = &kh_val(t,l)) || !(q->n))
446
+ continue;
447
+
448
+ reg = kh_key(t,l);
449
+ k = kh_get(reg, h, reg); //looks strange, but only the second reg is a proper argument.
450
+ if (k == kh_end(h) || !(p = &kh_val(h, k)) || !(p->n))
451
+ continue;
452
+
453
+ new_a = calloc(q->n + p->n, sizeof(new_a[0]));
454
+ if (!new_a)
455
+ return NULL;
456
+ new_n = 0;
457
+
458
+ for (i = 0; i < q->n; i++) {
459
+ beg = q->a[i].beg;
460
+ end = q->a[i].end;
461
+
462
+ min_off = bed_minoff(p, beg, end);
463
+ for (j = min_off; j < p->n; ++j) {
464
+ if (p->a[j].beg >= end) break; // out of range; no need to proceed
465
+ if (p->a[j].end > beg && p->a[j].beg < end) {
466
+ new_a[new_n].beg = MAX(p->a[j].beg, beg);
467
+ new_a[new_n++].end = MIN(p->a[j].end, end);
468
+ }
469
+ }
470
+ }
471
+
472
+ if (new_n > 0) {
473
+ free(p->a);
474
+ p->a = new_a;
475
+ p->n = new_n;
476
+ p->m = new_n;
477
+ p->filter = FILTERED;
478
+ } else {
479
+ free(new_a);
480
+ p->filter = ALL;
481
+ }
482
+ }
483
+
484
+ return h;
485
+ }
486
+
487
+ void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op) {
488
+
489
+ reghash_t *h = (reghash_t *)reg_hash;
490
+ reghash_t *t = NULL;
491
+
492
+ int i;
493
+ char reg[1024];
494
+ const char *q;
495
+ int beg, end;
496
+
497
+ if (h) {
498
+ t = kh_init(reg);
499
+ if (!t) {
500
+ fprintf(samtools_stderr, "Error when creating the temporary region hash table!\n");
501
+ return NULL;
502
+ }
503
+ } else {
504
+ h = kh_init(reg);
505
+ if (!h) {
506
+ fprintf(samtools_stderr, "Error when creating the region hash table!\n");
507
+ return NULL;
508
+ }
509
+ *op = 1;
510
+ }
511
+
512
+ for (i=first; i<last; i++) {
513
+
514
+ // Note, ideally we would call sam_parse_region here, but it's complicated by not
515
+ // having the sam header known and the likelihood of the bed file containing data for other
516
+ // references too which we currently just ignore.
517
+ //
518
+ // TO DO...
519
+ q = hts_parse_reg(regs[i], &beg, &end);
520
+ if (q) {
521
+ if ((int)(q - regs[i] + 1) > 1024) {
522
+ fprintf(samtools_stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
523
+ continue;
524
+ }
525
+ strncpy(reg, regs[i], q - regs[i]);
526
+ reg[q - regs[i]] = 0;
527
+ } else {
528
+ // not parsable as a region, but possibly a sequence named "foo:a"
529
+ if (strlen(regs[i]) + 1 > 1024) {
530
+ fprintf(samtools_stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024);
531
+ continue;
532
+ }
533
+ strcpy(reg, regs[i]);
534
+ beg = 0; end = INT_MAX;
535
+ }
536
+
537
+ //if op==1 insert reg to the bed hash table
538
+ if (*op && !(bed_insert(h, reg, beg, end))) {
539
+ fprintf(samtools_stderr, "Error when inserting region='%s' in the bed hash table at address=%p!\n", regs[i], h);
540
+ }
541
+ //if op==0, first insert the regions in the temporary hash table,
542
+ //then filter the bed hash table using it
543
+ if (!(*op) && !(bed_insert(t, reg, beg, end))) {
544
+ fprintf(samtools_stderr, "Error when inserting region='%s' in the temporary hash table at address=%p!\n", regs[i], t);
545
+ }
546
+ }
547
+
548
+ if (!(*op)) {
549
+ bed_index(t);
550
+ bed_unify(t);
551
+ h = bed_filter(h, t);
552
+ bed_destroy(t);
553
+ }
554
+
555
+ if (h) {
556
+ bed_index(h);
557
+ bed_unify(h);
558
+ }
559
+
560
+ return h;
561
+ }
562
+
563
+ const char* bed_get(void *reg_hash, int i, int filter) {
564
+
565
+ reghash_t *h;
566
+ bed_reglist_t *p;
567
+
568
+ if (!reg_hash)
569
+ return NULL;
570
+
571
+ h = (reghash_t *)reg_hash;
572
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
573
+ return NULL;
574
+
575
+ return kh_key(h, i);
576
+ }
577
+
578
+ /**
579
+ * Create a region list from a the region hash table
580
+ * @param reg_hash The region hash table
581
+ * @param filter 0 - allow all regions, 1 - allow only selected regions
582
+ * @param n_reg Pointer to the returned region number
583
+ * @return The regions list as a hts_reglist_t
584
+ */
585
+
586
+ hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *n_reg) {
587
+
588
+ reghash_t *h;
589
+ bed_reglist_t *p;
590
+ khint_t i;
591
+ hts_reglist_t *reglist = NULL;
592
+ int count = 0;
593
+ int j;
594
+
595
+ if (!reg_hash)
596
+ return NULL;
597
+
598
+ h = (reghash_t *)reg_hash;
599
+
600
+ for (i = kh_begin(h); i < kh_end(h); i++) {
601
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
602
+ continue;
603
+ count++;
604
+ }
605
+ if (!count)
606
+ return NULL;
607
+
608
+ reglist = (hts_reglist_t *)calloc(count, sizeof(hts_reglist_t));
609
+ if (!reglist)
610
+ return NULL;
611
+
612
+ *n_reg = count;
613
+ count = 0;
614
+
615
+ for (i = kh_begin(h); i < kh_end(h) && count < *n_reg; i++) {
616
+ if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter))
617
+ continue;
618
+
619
+ reglist[count].reg = kh_key(h,i);
620
+ reglist[count].intervals = (hts_pair32_t *)calloc(p->n, sizeof(hts_pair32_t));
621
+ if(!(reglist[count].intervals)) {
622
+ hts_reglist_free(reglist, count);
623
+ return NULL;
624
+ }
625
+ reglist[count].count = p->n;
626
+ reglist[count].max_end = 0;
627
+
628
+ for (j = 0; j < p->n; j++) {
629
+ reglist[count].intervals[j].beg = p->a[j].beg;
630
+ reglist[count].intervals[j].end = p->a[j].end;
631
+
632
+ if (reglist[count].intervals[j].end > reglist[count].max_end)
633
+ reglist[count].max_end = reglist[count].intervals[j].end;
634
+ }
635
+ count++;
636
+ }
637
+
638
+ return reglist;
639
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* bedidx.h -- BED file indexing header file.
2
+
3
+ Copyright (C) 2017 Genome Research Ltd.
4
+
5
+ Author: Valeriu Ohan <vo2@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #ifndef BEDIDX_H
26
+ #define BEDIDX_H
27
+
28
+ #include "htslib/hts.h"
29
+
30
+ #define LIDX_SHIFT 13
31
+ #define ALL 0
32
+ #define FILTERED 1
33
+
34
+ #define MIN(A,B) ( ( (A) < (B) ) ? (A) : (B) )
35
+ #define MAX(A,B) ( ( (A) > (B) ) ? (A) : (B) )
36
+
37
+ void *bed_read(const char *fn);
38
+ void bed_destroy(void *_h);
39
+ int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end);
40
+ void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op);
41
+ const char* bed_get(void *reg_hash, int index, int filter);
42
+ hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *count_regs);
43
+ void bed_unify(void *_h);
44
+
45
+ #endif
falcon/lib/python3.10/site-packages/pysam/include/samtools/consensus_pileup.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* consensus_pileup.h -- Pileup orientated data per consensus column
2
+
3
+ Copyright (C) 2013-2016, 2020-2022 Genome Research Ltd.
4
+
5
+ Author: James Bonfied <jkb@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notices and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ #include <htslib/sam.h>
26
+
27
+ typedef struct pileup {
28
+ // commonly used things together, to fit in a cache line (64 bytes)
29
+ struct pileup *next; // A link list, for active seqs
30
+ void *cd; // General purpose per-seq client-data
31
+ int eof; // True if this sequence has finished
32
+ int qual; // Current qual (for active seq only)
33
+ char start; // True if this is a new sequence
34
+ char base; // Current base (for active seq only) in ASCII
35
+ char ref_skip; // True if the cause of eof or start is cigar N
36
+ char padding; // True if the base was added due to another seq
37
+ int base4; // Base in 4-bit notation (0-15)
38
+ hts_pos_t pos; // Current unpadded position in seq
39
+ int nth; // nth base at unpadded position 'pos'
40
+ int b_is_rev; // 0 => fwd, 1 => rev
41
+ int seq_offset; // Current base position in s->seq[] array.
42
+
43
+ unsigned char *b_qual;// cached bam_qual
44
+ unsigned char *b_seq; // cached bam_seq
45
+
46
+ // --- 64 bytes
47
+ struct pileup *eofn; // p->eof set, next eof member
48
+ struct pileup *eofl; // last non-eof that points to p with p->eof
49
+
50
+ uint32_t *b_cigar; // cached bam_cigar
51
+
52
+ int cigar_ind; // Current location in s->alignment cigar str
53
+ int cigar_op; // Current cigar operation
54
+ int cigar_len; // Remaining length of this cigar op
55
+
56
+ int first_del; // Used when first base is a deletion
57
+
58
+ bam1_t b; // Bam entry associated with struct
59
+ } pileup_t;
60
+
61
+ /*
62
+ * The pileup loop executes and calls callbacks to perform the work.
63
+ *
64
+ * seq_fetch returns the next sequence. Return 0 from this indicates no
65
+ * more data.
66
+ *
67
+ * seq_init is called, if non-NULL, when a sequence is added to the pileup,
68
+ * seq_free likewise, if non-NULL, is called when a sequence is removed
69
+ * from the pileup.
70
+ * These two functions are akin to the constructor and destructors added
71
+ * to mpileup.
72
+ *
73
+ * seq_column is the primary work horse which is executed for each
74
+ * reference position, and for each inserted base per ref pos.
75
+ *
76
+ * If we were to invert this from a loop generating callbacks to a polled
77
+ * style interface like mpileup, then the seq_column bit would be dropped
78
+ * and replaced by the returned pileup and associated parameters.
79
+ */
80
+ int pileup_loop(samFile *fp,
81
+ sam_hdr_t *h,
82
+ int (*seq_fetch)(void *client_data,
83
+ samFile *fp,
84
+ sam_hdr_t *h,
85
+ bam1_t *b),
86
+ int (*seq_init)(void *client_data,
87
+ samFile *fp,
88
+ sam_hdr_t *h,
89
+ pileup_t *p),
90
+ int (*seq_column)(void *client_data,
91
+ samFile *fp,
92
+ sam_hdr_t *h,
93
+ pileup_t *p,
94
+ int depth,
95
+ hts_pos_t pos,
96
+ int nth,
97
+ int is_insert),
98
+ void (*seq_free)(void *client_data,
99
+ samFile *fp,
100
+ sam_hdr_t *h,
101
+ pileup_t *p),
102
+ void *client_data);
falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c ADDED
@@ -0,0 +1,665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* cram_size.c -- produces summary of the size of each cram data-series
2
+
3
+ Copyright (C) 2023 Genome Research Ltd.
4
+
5
+ Author: James Bonfield <jkb@sanger.ac.uk>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE. */
24
+
25
+ // TODO: add range query. Eg the ability to look at size for "*" only
26
+ // (unmapped), or in a specific region such as a centromere.
27
+
28
+ #include <config.h>
29
+
30
+ #include <stdio.h>
31
+ #include <stdlib.h>
32
+ #include <unistd.h>
33
+ #include <string.h>
34
+ #include <strings.h>
35
+
36
+ #include "htslib/bgzf.h"
37
+ #include "htslib/sam.h"
38
+ #include "htslib/cram.h"
39
+ #include "htslib/kstring.h"
40
+ #include "htslib/khash.h"
41
+ #include "samtools.h"
42
+ #include "sam_opts.h"
43
+ #include "htslib/hfile.h"
44
+
45
+ /*----------------------------------------------------------------------
46
+ * Compression method handling
47
+ */
48
+
49
+ // A numeric version of the cram_method_details struct.
50
+ // We expand the myriad of struct field combinations into a single
51
+ // enumerated type so we can index and accumulate statistics for
52
+ // purposes of reporting.
53
+ //
54
+ // These expanded numeric values have no definition within CRAM itself
55
+ // and never occur within the file format.
56
+ enum comp_expanded {
57
+ //----
58
+ // Copies from htslib cram_block_method enum
59
+ COMP_RAW = CRAM_COMP_RAW,
60
+ COMP_GZIP = CRAM_COMP_GZIP,
61
+ COMP_BZIP2 = CRAM_COMP_BZIP2,
62
+ COMP_LZMA = CRAM_COMP_LZMA,
63
+ COMP_RANS8 = CRAM_COMP_RANS4x8,
64
+ COMP_RANS16 = CRAM_COMP_RANSNx16,
65
+ COMP_ARITH = CRAM_COMP_ARITH,
66
+ COMP_FQZ = CRAM_COMP_FQZ,
67
+ COMP_TOK3 = CRAM_COMP_TOK3,
68
+
69
+ //----
70
+ // Localised variants.
71
+
72
+ // Gzip
73
+ COMP_GZIP_1,
74
+ COMP_GZIP_9,
75
+
76
+ // Bzip2
77
+ COMP_BZIP2_1,
78
+ COMP_BZIP2_2,
79
+ COMP_BZIP2_3,
80
+ COMP_BZIP2_4,
81
+ COMP_BZIP2_5,
82
+ COMP_BZIP2_6,
83
+ COMP_BZIP2_7,
84
+ COMP_BZIP2_8,
85
+ COMP_BZIP2_9,
86
+
87
+ // rans 4x8
88
+ COMP_RANS4x8_O0,
89
+ COMP_RANS4x8_O1,
90
+
91
+ // rans Nx16. Note order here is to enable selection via bit-fields
92
+ // bit 0: O0/O1
93
+ // bit 1: RLE
94
+ // bit 2: PACK
95
+ // bit 3: 32x16
96
+ COMP_RANS4x16_O0,
97
+ COMP_RANS4x16_O1,
98
+ COMP_RANS4x16_O0R, // +RLE
99
+ COMP_RANS4x16_O1R,
100
+ COMP_RANS4x16_O0P, // +PACK
101
+ COMP_RANS4x16_O1P,
102
+ COMP_RANS4x16_O0PR, // +PACK+RLE
103
+ COMP_RANS4x16_O1PR,
104
+ COMP_RANS32x16_O0, // SIMD variants
105
+ COMP_RANS32x16_O1,
106
+ COMP_RANS32x16_O0R, // +RLE
107
+ COMP_RANS32x16_O1R,
108
+ COMP_RANS32x16_O0P, // +PACK
109
+ COMP_RANS32x16_O1P,
110
+ COMP_RANS32x16_O0PR, // +PACK+RLE
111
+ COMP_RANS32x16_O1PR,
112
+ COMP_RANSNx16_STRIPE,
113
+ COMP_RANSNx16_CAT,
114
+
115
+ // Arith
116
+ COMP_ARITH_O0,
117
+ COMP_ARITH_O1,
118
+ COMP_ARITH_O0R, // +RLE
119
+ COMP_ARITH_O1R,
120
+ COMP_ARITH_O0P, // +PACK
121
+ COMP_ARITH_O1P,
122
+ COMP_ARITH_O0PR, // +PACK+RLE
123
+ COMP_ARITH_O1PR,
124
+ COMP_ARITH_STRIPE,
125
+ COMP_ARITH_CAT, // no entropy encoder
126
+ COMP_ARITH_EXT, // external entropy encode
127
+
128
+ // Nake tokeniser
129
+ COMP_TOK3_RANS,
130
+ COMP_TOK3_ARITH,
131
+
132
+ // To mark maximum size
133
+ COMP_MAX,
134
+ };
135
+
136
+ static enum comp_expanded comp_method2expanded(cram_method_details *cm) {
137
+ switch (cm->method) {
138
+ case CRAM_COMP_GZIP:
139
+ switch (cm->level) {
140
+ case 1: return COMP_GZIP_1;
141
+ case 9: return COMP_GZIP_9;
142
+ default: return COMP_GZIP;
143
+ }
144
+ break;
145
+
146
+ case CRAM_COMP_BZIP2:
147
+ if (cm->level >= 1 && cm->level <= 9)
148
+ return COMP_BZIP2_1 + cm->level-1;
149
+ else
150
+ return COMP_BZIP2;
151
+ break;
152
+
153
+ case CRAM_COMP_RANS4x8:
154
+ return cm->order ? COMP_RANS4x8_O1 : COMP_RANS4x8_O0;
155
+
156
+ case CRAM_COMP_RANSNx16: {
157
+ // 8 4x16, 8 32x16 and 2 stripe/cat
158
+ if (cm->stripe) return COMP_RANSNx16_STRIPE;
159
+ if (cm->cat) return COMP_RANSNx16_CAT;
160
+ int c = COMP_RANS4x16_O0;
161
+ c += 1*cm->order;
162
+ c += 2*cm->rle;
163
+ c += 4*cm->pack;
164
+ c += 8*(cm->Nway==32);
165
+ return c;
166
+ }
167
+
168
+ case CRAM_COMP_ARITH: {
169
+ // 8 4x16, 8 32x16 and 2 stripe/cat
170
+ if (cm->stripe) return COMP_ARITH_STRIPE;
171
+ if (cm->cat) return COMP_ARITH_CAT;
172
+ if (cm->ext) return COMP_ARITH_EXT;
173
+ int c = COMP_ARITH_O0;
174
+ c += 1*cm->order;
175
+ c += 2*cm->rle;
176
+ c += 4*cm->pack;
177
+ return c;
178
+ }
179
+
180
+ case CRAM_COMP_TOK3:
181
+ return cm->level < 10
182
+ ? COMP_TOK3_RANS
183
+ : COMP_TOK3_ARITH;
184
+
185
+ default:
186
+ // Any unspecialised method
187
+ return (enum comp_expanded)cm->method;
188
+ }
189
+ }
190
+
191
+ // Short form of cram_block_method_int type
192
+ static char comp_method2char[COMP_MAX] =
193
+ ".gblr0afn" // standard CRAM methods
194
+ "_G" // gzip
195
+ "bbbbbbbbB" // bzip2
196
+ "rR" // rans4x8
197
+ "010101014545454582" // ransNx16
198
+ "aAaAaAaAaaa" // arith
199
+ "nN"; // tok3
200
+
201
+ // Long form of cram_block_method_int type
202
+ static char *comp_method2str[COMP_MAX] = {
203
+ // Standard CRAM methods
204
+ "raw", "gzip", "bzip2", "lzma", "r4x8", "rNx16",
205
+ "arith", "fqzcomp", "tok3",
206
+
207
+ // custom gzip
208
+ "gzip-min", "gzip-max",
209
+
210
+ // custom bzip2
211
+ "bzip2-1", "bzip2-2", "bzip2-3", "bzip2-4", "bzip2-5",
212
+ "bzip2-6", "bzip2-7", "bzip2-8", "bzip2-9",
213
+
214
+ // rANS 4x8
215
+ "r4x8-o0", "r4x8-o1",
216
+
217
+ // rANS 4x16
218
+ "r4x16-o0", "r4x16-o1",
219
+
220
+ "r4x16-o0R", "r4x16-o1R",
221
+ "r4x16-o0P", "r4x16-o1P",
222
+ "r4x16-o0PR", "r4x16-o1PR",
223
+ "r32x16-o0", "r32x16-o1",
224
+ "r32x16-o0R", "r32x16-o1R",
225
+ "r32x16-o0P", "r32x16-o1P",
226
+ "r32x16-o0PR","r32x16-o1PR",
227
+ "rNx16-xo0", "rNx16-cat",
228
+
229
+ // Arith
230
+ "arith-o0", "arith-o1",
231
+ "arith-o0R", "arith-o1R",
232
+ "arith-o0P", "arith-o1P",
233
+ "arith-o0PR", "arith-o1PR",
234
+ "arith-stripe", "arith-cat", "arith-ext",
235
+
236
+ // Name tokeniser
237
+ "tok3-rans", "tok3-arith",
238
+ };
239
+
240
+ /*----------------------------------------------------------------------
241
+ * Manipulation and sorting of Block Content-ID arrays and hashes
242
+ */
243
+
244
+ typedef struct {
245
+ int64_t csize[COMP_MAX];
246
+ int64_t usize[COMP_MAX];
247
+ } cusize_t;
248
+
249
+ static int64_t total_csize(cusize_t *cu) {
250
+ int i;
251
+ int64_t tot = 0;
252
+ for (i = 0; i < COMP_MAX; i++)
253
+ tot += cu->csize[i];
254
+ return tot;
255
+ }
256
+
257
+ static int64_t total_usize(cusize_t *cu) {
258
+ int i;
259
+ int64_t tot = 0;
260
+ for (i = 0; i < COMP_MAX; i++)
261
+ tot += cu->usize[i];
262
+ return tot;
263
+ }
264
+
265
+ // cusize_t array and sorting by compressed size
266
+ static cusize_t *sort_cusize_global; // avoids a messy extra data type
267
+ static int sort_cusize_compar(const void *i1, const void *i2) {
268
+ int64_t n = sort_cusize_global->csize[*(const int *)i2] -
269
+ sort_cusize_global->csize[*(const int *)i1];
270
+ return n > 0 ? 1 : (n < 0 ? -1 : *(const int *)i1 - *(const int *)i2);
271
+ }
272
+
273
+ // Sort a cusize array by size of used method.
274
+ // Returns cu->csize[comp] indices in descending size, as static mem
275
+ static int *sort_cusize(cusize_t *cu) {
276
+ static int idx[COMP_MAX];
277
+ int i;
278
+ for (i = 0; i < COMP_MAX; i++)
279
+ idx[i] = i;
280
+ sort_cusize_global = cu;
281
+ qsort(idx, COMP_MAX, sizeof(*idx), sort_cusize_compar);
282
+
283
+ return idx;
284
+ }
285
+
286
+ // Hash table of cusize_t and sorting by key (content-id)
287
+ KHASH_MAP_INIT_INT(cu, cusize_t)
288
+
289
+ /* Sort by hash key. Global due to rubbish qsort API, but it's simple. */
290
+ static khash_t(cu) *global_cu_hash = NULL;
291
+ static int cu_compar(const void *i1, const void *i2) {
292
+ return kh_key(global_cu_hash, *(const int *)i1) -
293
+ kh_key(global_cu_hash, *(const int *)i2);
294
+ }
295
+
296
+ /*----------------------------------------------------------------------
297
+ * Main cram_size reporting and aggregation
298
+ */
299
+ static off_t report_size(FILE *outfp, int verbose, int ref_seq_blk,
300
+ khash_t(cu) *cu_size, cram_cid2ds_t *cid2ds) {
301
+ if (!cu_size || !cid2ds)
302
+ return -1;
303
+
304
+ khiter_t k;
305
+ off_t tot_size = 0;
306
+
307
+ fprintf(outfp, "# Content_ID Uncomp.size Comp.size Ratio Method%.*s Data_series\n", verbose ? 4 : 0, " ");
308
+ int *sorted_blocks = malloc(kh_end(cu_size)*sizeof(int));
309
+ if (!sorted_blocks)
310
+ return -1;
311
+ int nblocks = 0;
312
+ for (k = kh_begin(cu_size); k != kh_end(cu_size); k++) {
313
+ if (!kh_exist(cu_size, k))
314
+ continue;
315
+ sorted_blocks[nblocks++] = k;
316
+ }
317
+ global_cu_hash = cu_size;
318
+ qsort(sorted_blocks, nblocks, sizeof(int), cu_compar);
319
+
320
+ int i;
321
+ for (i = 0; i < nblocks; i++) {
322
+ k = sorted_blocks[i];
323
+
324
+ if (verbose) {
325
+ // FULL output
326
+ int *comp_idx = sort_cusize(&kh_value(cu_size, k));
327
+ int first_line = 1, c, j;
328
+ for (c = 0; c < COMP_MAX; c++) {
329
+ int comp = comp_idx[c];
330
+ if (!kh_value(cu_size, k).csize[comp] && c)
331
+ break;
332
+
333
+ if (!first_line)
334
+ fprintf(outfp, "\n");
335
+ first_line = 0;
336
+
337
+ if ((int)kh_key(cu_size, k) < 0)
338
+ fprintf(outfp, "BLOCK %8s", "CORE");
339
+ else
340
+ fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
341
+
342
+ fprintf(outfp, " %12"PRId64" %12"PRId64,
343
+ kh_value(cu_size, k).usize[comp],
344
+ kh_value(cu_size, k).csize[comp]);
345
+ double f = (100.0*(kh_value(cu_size, k).csize[comp]+.0001)) /
346
+ (kh_value(cu_size, k).usize[comp]+.0001);
347
+ if (f > 999)
348
+ fprintf(outfp, " >999%% %-11s", comp_method2str[comp]);
349
+ else
350
+ fprintf(outfp, " %6.2f%% %-11s",f, comp_method2str[comp]);
351
+
352
+ int n, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
353
+ for (j = 0; j < n; j++) {
354
+ int d = dsa[j];
355
+ if (d > 65535)
356
+ fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
357
+ else
358
+ fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
359
+ }
360
+ }
361
+ } else {
362
+ // aggregate by compression type.
363
+ int64_t csize = total_csize(&kh_value(cu_size, k));
364
+ int64_t usize = total_usize(&kh_value(cu_size, k));
365
+ int *comp_idx = sort_cusize(&kh_value(cu_size, k));
366
+
367
+ char cstr[COMP_MAX+1] = {0};
368
+ int cidx = 0, c;
369
+ for (c = 0; c < COMP_MAX; c++) {
370
+ if (!kh_value(cu_size, k).csize[comp_idx[c]])
371
+ break;
372
+ cstr[cidx++] = comp_method2char[comp_idx[c]];
373
+ }
374
+ if (!*cstr) *cstr = '.';
375
+
376
+ if ((int)kh_key(cu_size, k) < 0)
377
+ fprintf(outfp, "BLOCK %8s", "CORE");
378
+ else
379
+ fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
380
+ fprintf(outfp, " %12"PRId64" %12"PRId64, usize, csize);
381
+ double f = 100*(csize+.0001)/(usize+.0001);
382
+ if (f > 999)
383
+ fprintf(outfp, " >999%% %-7s", cstr);
384
+ else
385
+ fprintf(outfp, " %6.2f%% %-7s", f, cstr);
386
+
387
+ int n, j, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
388
+ for (j = 0; j < n; j++) {
389
+ int d = dsa[j];
390
+ if (d > 65535)
391
+ fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
392
+ else
393
+ fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
394
+ }
395
+ }
396
+
397
+ if ((int)kh_key(cu_size, k) >= 0 &&
398
+ (int)kh_key(cu_size, k) == ref_seq_blk) {
399
+ fprintf(outfp, " embedded_ref");
400
+ }
401
+ fprintf(outfp, "\n");
402
+
403
+ tot_size += total_csize(&kh_value(cu_size, k));
404
+ }
405
+
406
+ free(sorted_blocks);
407
+
408
+ return tot_size;
409
+ }
410
+
411
+ /* Main processing loop */
412
+ static int cram_size(hFILE *hf_in, samFile *in, sam_hdr_t *h, FILE *outfp,
413
+ int verbose, int encodings) {
414
+ cram_fd *in_c;
415
+ cram_container *c = NULL;
416
+ cram_block *blk = NULL;
417
+ cram_block_slice_hdr *shdr = NULL;
418
+ khiter_t k;
419
+ int ret;
420
+ cram_cid2ds_t *cid2ds = NULL;
421
+ khash_t(cu) *cu_size = kh_init(cu);
422
+ int ref_seq_blk_used = -1;
423
+ int64_t nseqs = 0, nbases = 0, ncont = 0, nslice = 0;
424
+
425
+ if (!in->is_cram) {
426
+ print_error("cram_size", "Input is not a CRAM file");
427
+ goto err;
428
+ }
429
+ in_c = in->fp.cram; // low level htslib abuse?
430
+ while ((c = cram_read_container(in_c))) {
431
+ if (cram_container_is_empty(in_c)) {
432
+ cram_block *blk;
433
+ // Container compression header
434
+ if (!(blk = cram_read_block(in_c)))
435
+ goto err;
436
+ cram_free_block(blk);
437
+ cram_free_container(c);
438
+ c = NULL; blk = NULL;
439
+ continue;
440
+ }
441
+
442
+ nseqs += cram_container_get_num_records(c);
443
+ nbases += cram_container_get_num_bases(c);
444
+
445
+ // Container compression header
446
+ int32_t num_slices;
447
+ if (!(blk = cram_read_block(in_c)))
448
+ goto err;
449
+
450
+ // Decode compression header...
451
+ cram_block_compression_hdr *chdr;
452
+ chdr = cram_decode_compression_header(in_c, blk);
453
+
454
+ if (encodings) {
455
+ kstring_t ks = KS_INITIALIZE;
456
+ if (cram_describe_encodings(chdr, &ks) < 0)
457
+ goto err;
458
+
459
+ fprintf(outfp, "Container encodings\n%s\n", ks_str(&ks));
460
+
461
+ ks_free(&ks);
462
+ }
463
+
464
+ cid2ds = cram_update_cid2ds_map(chdr, cid2ds);
465
+
466
+ cram_free_block(blk);
467
+ blk = NULL;
468
+
469
+ cram_free_compression_header(chdr);
470
+
471
+ // Container num_blocks can be invalid, due to a bug.
472
+ // Instead we iterate in slice context instead.
473
+ (void)cram_container_get_landmarks(c, &num_slices);
474
+ ncont++;
475
+ nslice += num_slices;
476
+
477
+ int i, j;
478
+ for (i = 0; i < num_slices; i++) {
479
+ // Slice header
480
+ if (!(blk = cram_read_block(in_c)))
481
+ goto err;
482
+ if (!(shdr = cram_decode_slice_header(in_c, blk)))
483
+ goto err;
484
+ cram_free_block(blk);
485
+ blk = NULL;
486
+
487
+ int ref_seq_blk = cram_slice_hdr_get_embed_ref_id(shdr);
488
+ int num_blocks = cram_slice_hdr_get_num_blocks(shdr);
489
+
490
+ // Embedded reference. Check it's consistent (if used this is
491
+ // an almost guaranteed certainty, so we take the easy route).
492
+ if (ref_seq_blk >= 0) {
493
+ if (ref_seq_blk_used == -1)
494
+ ref_seq_blk_used = ref_seq_blk;
495
+ else if (ref_seq_blk_used != ref_seq_blk)
496
+ fprintf(stderr, "Embedded reference is not consistently using the same Content-Id.\n"
497
+ "Reported figures for reference will be invalid.\n");
498
+ }
499
+
500
+ // Slice data blocks
501
+ for (j = 0; j < num_blocks; j++) {
502
+ // read and discard, unless it's the ref-ID block
503
+ if (!(blk = cram_read_block(in_c)))
504
+ goto err;
505
+
506
+ int32_t csize = cram_block_get_comp_size(blk);
507
+ int32_t usize = cram_block_get_uncomp_size(blk);
508
+ int cid = cram_block_get_content_id(blk);
509
+ enum cram_block_method method = cram_block_get_method(blk);
510
+
511
+ // Expand comp to the internal sub-formats, eg
512
+ // rANS order-0/1, PACK+RLE, etc.
513
+ cram_method_details *cm;
514
+ cm = cram_expand_method(cram_block_get_data(blk),
515
+ cram_block_get_comp_size(blk),
516
+ method);
517
+ if (!cm)
518
+ goto err;
519
+ enum comp_expanded comp
520
+ = comp_method2expanded(cm);
521
+ free(cm);
522
+
523
+ k = kh_put(cu, cu_size, cid, &ret);
524
+ if (ret < 0)
525
+ goto err;
526
+ if (ret == 0) {
527
+ kh_value(cu_size, k).csize[comp] += csize;
528
+ kh_value(cu_size, k).usize[comp] += usize;
529
+ } else {
530
+ memset(&kh_value(cu_size, k), 0, sizeof(cusize_t));
531
+ kh_value(cu_size, k).csize[comp] = csize;
532
+ kh_value(cu_size, k).usize[comp] = usize;
533
+ }
534
+
535
+ cram_free_block(blk);
536
+ blk = NULL;
537
+ }
538
+ cram_free_slice_header(shdr);
539
+ shdr = NULL;
540
+ }
541
+
542
+ cram_free_container(c);
543
+ c = NULL;
544
+ }
545
+
546
+ off_t tot_size = report_size(outfp, verbose, ref_seq_blk_used,
547
+ cu_size, cid2ds);
548
+ if (tot_size < 0)
549
+ goto err;
550
+
551
+ kh_destroy(cu, cu_size);
552
+ cram_cid2ds_free(cid2ds);
553
+
554
+ off_t end = htell(hf_in);
555
+
556
+ fprintf(outfp, "\n");
557
+ fprintf(outfp, "Number of containers %18"PRId64"\n", ncont);
558
+ fprintf(outfp, "Number of slices %18"PRId64"\n", nslice);
559
+ fprintf(outfp, "Number of sequences %18"PRId64"\n", nseqs);
560
+ fprintf(outfp, "Number of bases %18"PRId64"\n", nbases);
561
+ fprintf(outfp, "Total file size %18"PRId64"\n", (int64_t) end);
562
+ fprintf(outfp, "Format overhead size %18"PRId64"\n", (int64_t) (end - tot_size));
563
+
564
+ return 0;
565
+
566
+ err:
567
+ // Report anyway so we can get stats on partial files, but be
568
+ // sure to error too.
569
+ report_size(outfp, verbose, ref_seq_blk_used, cu_size, cid2ds);
570
+
571
+ print_error("cram_size", "Failed in decoding CRAM file");
572
+ if (blk)
573
+ cram_free_block(blk);
574
+ if (shdr)
575
+ cram_free_slice_header(shdr);
576
+ if (c)
577
+ cram_free_container(c);
578
+ if (cid2ds)
579
+ cram_cid2ds_free(cid2ds);
580
+
581
+ return -1;
582
+ }
583
+
584
+ /* main() for cram_size */
585
+ int main_cram_size(int argc, char *argv[]) {
586
+ int c, usage = 0, verbose = 0, encodings = 0;
587
+ sam_hdr_t *h = 0;
588
+ hFILE *hf_in = NULL;
589
+ samFile *in = NULL;
590
+ sam_global_args ga;
591
+ FILE *outfp = stdout;
592
+
593
+ static const struct option lopts[] = {
594
+ {"output", required_argument, NULL, 'o'},
595
+ {"verbose", no_argument, NULL, 'v'},
596
+ {"encodings", no_argument, NULL, 'e'},
597
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '-'),
598
+ { NULL, 0, NULL, 0 }
599
+ };
600
+
601
+ sam_global_args_init(&ga);
602
+
603
+ while ((c = getopt_long(argc, argv, "vo:e", lopts, NULL)) >= 0) {
604
+ switch (c) {
605
+ case 'o':
606
+ if (!(outfp = fopen(optarg, "w"))) {
607
+ perror(optarg);
608
+ goto err;
609
+ }
610
+ break;
611
+
612
+ case 'v':
613
+ verbose++;
614
+ break;
615
+
616
+ case 'e':
617
+ encodings++;
618
+ break;
619
+
620
+ default:
621
+ if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
622
+ /* else fall-through */
623
+ case '?': usage=1; break;
624
+ }
625
+ }
626
+
627
+ if ((optind == argc && isatty(0)) || usage) {
628
+ printf("Usage: samtools cram_size [-ve] [-o out.size] [in.cram]\n");
629
+ return 0;
630
+ }
631
+
632
+ char *fn = optind < argc ? argv[optind] : "-";
633
+
634
+ // We want access to in->fp.cram->fp, but this is an opaque struct so we
635
+ // can't get that. However we opened with hopen and then reopen as
636
+ // CRAM with hts_hopen, which will swallow the initial hFILE and take
637
+ // owenership of it. Hence we now know in->fp.cram->fp.
638
+ if (!(hf_in = hopen(fn, "r"))) {
639
+ print_error_errno("cram_size", "failed to open file '%s'", fn);
640
+ return 1;
641
+ }
642
+ if (!(in = hts_hopen(hf_in, fn, "r"))) {
643
+ print_error_errno("cram_size", "failed to open file '%s'", fn);
644
+ goto err;
645
+ }
646
+
647
+ if (!(h = sam_hdr_read(in)))
648
+ goto err;
649
+
650
+ int ret = cram_size(hf_in, in, h, outfp, verbose, encodings);
651
+ sam_hdr_destroy(h);
652
+ sam_close(in);
653
+ if (outfp != stdout)
654
+ fclose(outfp);
655
+
656
+ return ret ? 1 : 0;
657
+
658
+ err:
659
+ if (in)
660
+ sam_close(in);
661
+ if (h)
662
+ sam_hdr_destroy(h);
663
+
664
+ return 1;
665
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c.pysam.c ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* cram_size.c -- produces summary of the size of each cram data-series
4
+
5
+ Copyright (C) 2023 Genome Research Ltd.
6
+
7
+ Author: James Bonfield <jkb@sanger.ac.uk>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in
17
+ all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE. */
26
+
27
+ // TODO: add range query. Eg the ability to look at size for "*" only
28
+ // (unmapped), or in a specific region such as a centromere.
29
+
30
+ #include <config.h>
31
+
32
+ #include <stdio.h>
33
+ #include <stdlib.h>
34
+ #include <unistd.h>
35
+ #include <string.h>
36
+ #include <strings.h>
37
+
38
+ #include "htslib/bgzf.h"
39
+ #include "htslib/sam.h"
40
+ #include "htslib/cram.h"
41
+ #include "htslib/kstring.h"
42
+ #include "htslib/khash.h"
43
+ #include "samtools.h"
44
+ #include "sam_opts.h"
45
+ #include "htslib/hfile.h"
46
+
47
+ /*----------------------------------------------------------------------
48
+ * Compression method handling
49
+ */
50
+
51
+ // A numeric version of the cram_method_details struct.
52
+ // We expand the myriad of struct field combinations into a single
53
+ // enumerated type so we can index and accumulate statistics for
54
+ // purposes of reporting.
55
+ //
56
+ // These expanded numeric values have no definition within CRAM itself
57
+ // and never occur within the file format.
58
+ enum comp_expanded {
59
+ //----
60
+ // Copies from htslib cram_block_method enum
61
+ COMP_RAW = CRAM_COMP_RAW,
62
+ COMP_GZIP = CRAM_COMP_GZIP,
63
+ COMP_BZIP2 = CRAM_COMP_BZIP2,
64
+ COMP_LZMA = CRAM_COMP_LZMA,
65
+ COMP_RANS8 = CRAM_COMP_RANS4x8,
66
+ COMP_RANS16 = CRAM_COMP_RANSNx16,
67
+ COMP_ARITH = CRAM_COMP_ARITH,
68
+ COMP_FQZ = CRAM_COMP_FQZ,
69
+ COMP_TOK3 = CRAM_COMP_TOK3,
70
+
71
+ //----
72
+ // Localised variants.
73
+
74
+ // Gzip
75
+ COMP_GZIP_1,
76
+ COMP_GZIP_9,
77
+
78
+ // Bzip2
79
+ COMP_BZIP2_1,
80
+ COMP_BZIP2_2,
81
+ COMP_BZIP2_3,
82
+ COMP_BZIP2_4,
83
+ COMP_BZIP2_5,
84
+ COMP_BZIP2_6,
85
+ COMP_BZIP2_7,
86
+ COMP_BZIP2_8,
87
+ COMP_BZIP2_9,
88
+
89
+ // rans 4x8
90
+ COMP_RANS4x8_O0,
91
+ COMP_RANS4x8_O1,
92
+
93
+ // rans Nx16. Note order here is to enable selection via bit-fields
94
+ // bit 0: O0/O1
95
+ // bit 1: RLE
96
+ // bit 2: PACK
97
+ // bit 3: 32x16
98
+ COMP_RANS4x16_O0,
99
+ COMP_RANS4x16_O1,
100
+ COMP_RANS4x16_O0R, // +RLE
101
+ COMP_RANS4x16_O1R,
102
+ COMP_RANS4x16_O0P, // +PACK
103
+ COMP_RANS4x16_O1P,
104
+ COMP_RANS4x16_O0PR, // +PACK+RLE
105
+ COMP_RANS4x16_O1PR,
106
+ COMP_RANS32x16_O0, // SIMD variants
107
+ COMP_RANS32x16_O1,
108
+ COMP_RANS32x16_O0R, // +RLE
109
+ COMP_RANS32x16_O1R,
110
+ COMP_RANS32x16_O0P, // +PACK
111
+ COMP_RANS32x16_O1P,
112
+ COMP_RANS32x16_O0PR, // +PACK+RLE
113
+ COMP_RANS32x16_O1PR,
114
+ COMP_RANSNx16_STRIPE,
115
+ COMP_RANSNx16_CAT,
116
+
117
+ // Arith
118
+ COMP_ARITH_O0,
119
+ COMP_ARITH_O1,
120
+ COMP_ARITH_O0R, // +RLE
121
+ COMP_ARITH_O1R,
122
+ COMP_ARITH_O0P, // +PACK
123
+ COMP_ARITH_O1P,
124
+ COMP_ARITH_O0PR, // +PACK+RLE
125
+ COMP_ARITH_O1PR,
126
+ COMP_ARITH_STRIPE,
127
+ COMP_ARITH_CAT, // no entropy encoder
128
+ COMP_ARITH_EXT, // external entropy encode
129
+
130
+ // Nake tokeniser
131
+ COMP_TOK3_RANS,
132
+ COMP_TOK3_ARITH,
133
+
134
+ // To mark maximum size
135
+ COMP_MAX,
136
+ };
137
+
138
+ static enum comp_expanded comp_method2expanded(cram_method_details *cm) {
139
+ switch (cm->method) {
140
+ case CRAM_COMP_GZIP:
141
+ switch (cm->level) {
142
+ case 1: return COMP_GZIP_1;
143
+ case 9: return COMP_GZIP_9;
144
+ default: return COMP_GZIP;
145
+ }
146
+ break;
147
+
148
+ case CRAM_COMP_BZIP2:
149
+ if (cm->level >= 1 && cm->level <= 9)
150
+ return COMP_BZIP2_1 + cm->level-1;
151
+ else
152
+ return COMP_BZIP2;
153
+ break;
154
+
155
+ case CRAM_COMP_RANS4x8:
156
+ return cm->order ? COMP_RANS4x8_O1 : COMP_RANS4x8_O0;
157
+
158
+ case CRAM_COMP_RANSNx16: {
159
+ // 8 4x16, 8 32x16 and 2 stripe/cat
160
+ if (cm->stripe) return COMP_RANSNx16_STRIPE;
161
+ if (cm->cat) return COMP_RANSNx16_CAT;
162
+ int c = COMP_RANS4x16_O0;
163
+ c += 1*cm->order;
164
+ c += 2*cm->rle;
165
+ c += 4*cm->pack;
166
+ c += 8*(cm->Nway==32);
167
+ return c;
168
+ }
169
+
170
+ case CRAM_COMP_ARITH: {
171
+ // 8 4x16, 8 32x16 and 2 stripe/cat
172
+ if (cm->stripe) return COMP_ARITH_STRIPE;
173
+ if (cm->cat) return COMP_ARITH_CAT;
174
+ if (cm->ext) return COMP_ARITH_EXT;
175
+ int c = COMP_ARITH_O0;
176
+ c += 1*cm->order;
177
+ c += 2*cm->rle;
178
+ c += 4*cm->pack;
179
+ return c;
180
+ }
181
+
182
+ case CRAM_COMP_TOK3:
183
+ return cm->level < 10
184
+ ? COMP_TOK3_RANS
185
+ : COMP_TOK3_ARITH;
186
+
187
+ default:
188
+ // Any unspecialised method
189
+ return (enum comp_expanded)cm->method;
190
+ }
191
+ }
192
+
193
+ // Short form of cram_block_method_int type
194
+ static char comp_method2char[COMP_MAX] =
195
+ ".gblr0afn" // standard CRAM methods
196
+ "_G" // gzip
197
+ "bbbbbbbbB" // bzip2
198
+ "rR" // rans4x8
199
+ "010101014545454582" // ransNx16
200
+ "aAaAaAaAaaa" // arith
201
+ "nN"; // tok3
202
+
203
+ // Long form of cram_block_method_int type
204
+ static char *comp_method2str[COMP_MAX] = {
205
+ // Standard CRAM methods
206
+ "raw", "gzip", "bzip2", "lzma", "r4x8", "rNx16",
207
+ "arith", "fqzcomp", "tok3",
208
+
209
+ // custom gzip
210
+ "gzip-min", "gzip-max",
211
+
212
+ // custom bzip2
213
+ "bzip2-1", "bzip2-2", "bzip2-3", "bzip2-4", "bzip2-5",
214
+ "bzip2-6", "bzip2-7", "bzip2-8", "bzip2-9",
215
+
216
+ // rANS 4x8
217
+ "r4x8-o0", "r4x8-o1",
218
+
219
+ // rANS 4x16
220
+ "r4x16-o0", "r4x16-o1",
221
+
222
+ "r4x16-o0R", "r4x16-o1R",
223
+ "r4x16-o0P", "r4x16-o1P",
224
+ "r4x16-o0PR", "r4x16-o1PR",
225
+ "r32x16-o0", "r32x16-o1",
226
+ "r32x16-o0R", "r32x16-o1R",
227
+ "r32x16-o0P", "r32x16-o1P",
228
+ "r32x16-o0PR","r32x16-o1PR",
229
+ "rNx16-xo0", "rNx16-cat",
230
+
231
+ // Arith
232
+ "arith-o0", "arith-o1",
233
+ "arith-o0R", "arith-o1R",
234
+ "arith-o0P", "arith-o1P",
235
+ "arith-o0PR", "arith-o1PR",
236
+ "arith-stripe", "arith-cat", "arith-ext",
237
+
238
+ // Name tokeniser
239
+ "tok3-rans", "tok3-arith",
240
+ };
241
+
242
+ /*----------------------------------------------------------------------
243
+ * Manipulation and sorting of Block Content-ID arrays and hashes
244
+ */
245
+
246
+ typedef struct {
247
+ int64_t csize[COMP_MAX];
248
+ int64_t usize[COMP_MAX];
249
+ } cusize_t;
250
+
251
+ static int64_t total_csize(cusize_t *cu) {
252
+ int i;
253
+ int64_t tot = 0;
254
+ for (i = 0; i < COMP_MAX; i++)
255
+ tot += cu->csize[i];
256
+ return tot;
257
+ }
258
+
259
+ static int64_t total_usize(cusize_t *cu) {
260
+ int i;
261
+ int64_t tot = 0;
262
+ for (i = 0; i < COMP_MAX; i++)
263
+ tot += cu->usize[i];
264
+ return tot;
265
+ }
266
+
267
+ // cusize_t array and sorting by compressed size
268
+ static cusize_t *sort_cusize_global; // avoids a messy extra data type
269
+ static int sort_cusize_compar(const void *i1, const void *i2) {
270
+ int64_t n = sort_cusize_global->csize[*(const int *)i2] -
271
+ sort_cusize_global->csize[*(const int *)i1];
272
+ return n > 0 ? 1 : (n < 0 ? -1 : *(const int *)i1 - *(const int *)i2);
273
+ }
274
+
275
+ // Sort a cusize array by size of used method.
276
+ // Returns cu->csize[comp] indices in descending size, as static mem
277
+ static int *sort_cusize(cusize_t *cu) {
278
+ static int idx[COMP_MAX];
279
+ int i;
280
+ for (i = 0; i < COMP_MAX; i++)
281
+ idx[i] = i;
282
+ sort_cusize_global = cu;
283
+ qsort(idx, COMP_MAX, sizeof(*idx), sort_cusize_compar);
284
+
285
+ return idx;
286
+ }
287
+
288
+ // Hash table of cusize_t and sorting by key (content-id)
289
+ KHASH_MAP_INIT_INT(cu, cusize_t)
290
+
291
+ /* Sort by hash key. Global due to rubbish qsort API, but it's simple. */
292
+ static khash_t(cu) *global_cu_hash = NULL;
293
+ static int cu_compar(const void *i1, const void *i2) {
294
+ return kh_key(global_cu_hash, *(const int *)i1) -
295
+ kh_key(global_cu_hash, *(const int *)i2);
296
+ }
297
+
298
+ /*----------------------------------------------------------------------
299
+ * Main cram_size reporting and aggregation
300
+ */
301
+ static off_t report_size(FILE *outfp, int verbose, int ref_seq_blk,
302
+ khash_t(cu) *cu_size, cram_cid2ds_t *cid2ds) {
303
+ if (!cu_size || !cid2ds)
304
+ return -1;
305
+
306
+ khiter_t k;
307
+ off_t tot_size = 0;
308
+
309
+ fprintf(outfp, "# Content_ID Uncomp.size Comp.size Ratio Method%.*s Data_series\n", verbose ? 4 : 0, " ");
310
+ int *sorted_blocks = malloc(kh_end(cu_size)*sizeof(int));
311
+ if (!sorted_blocks)
312
+ return -1;
313
+ int nblocks = 0;
314
+ for (k = kh_begin(cu_size); k != kh_end(cu_size); k++) {
315
+ if (!kh_exist(cu_size, k))
316
+ continue;
317
+ sorted_blocks[nblocks++] = k;
318
+ }
319
+ global_cu_hash = cu_size;
320
+ qsort(sorted_blocks, nblocks, sizeof(int), cu_compar);
321
+
322
+ int i;
323
+ for (i = 0; i < nblocks; i++) {
324
+ k = sorted_blocks[i];
325
+
326
+ if (verbose) {
327
+ // FULL output
328
+ int *comp_idx = sort_cusize(&kh_value(cu_size, k));
329
+ int first_line = 1, c, j;
330
+ for (c = 0; c < COMP_MAX; c++) {
331
+ int comp = comp_idx[c];
332
+ if (!kh_value(cu_size, k).csize[comp] && c)
333
+ break;
334
+
335
+ if (!first_line)
336
+ fprintf(outfp, "\n");
337
+ first_line = 0;
338
+
339
+ if ((int)kh_key(cu_size, k) < 0)
340
+ fprintf(outfp, "BLOCK %8s", "CORE");
341
+ else
342
+ fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
343
+
344
+ fprintf(outfp, " %12"PRId64" %12"PRId64,
345
+ kh_value(cu_size, k).usize[comp],
346
+ kh_value(cu_size, k).csize[comp]);
347
+ double f = (100.0*(kh_value(cu_size, k).csize[comp]+.0001)) /
348
+ (kh_value(cu_size, k).usize[comp]+.0001);
349
+ if (f > 999)
350
+ fprintf(outfp, " >999%% %-11s", comp_method2str[comp]);
351
+ else
352
+ fprintf(outfp, " %6.2f%% %-11s",f, comp_method2str[comp]);
353
+
354
+ int n, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
355
+ for (j = 0; j < n; j++) {
356
+ int d = dsa[j];
357
+ if (d > 65535)
358
+ fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
359
+ else
360
+ fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
361
+ }
362
+ }
363
+ } else {
364
+ // aggregate by compression type.
365
+ int64_t csize = total_csize(&kh_value(cu_size, k));
366
+ int64_t usize = total_usize(&kh_value(cu_size, k));
367
+ int *comp_idx = sort_cusize(&kh_value(cu_size, k));
368
+
369
+ char cstr[COMP_MAX+1] = {0};
370
+ int cidx = 0, c;
371
+ for (c = 0; c < COMP_MAX; c++) {
372
+ if (!kh_value(cu_size, k).csize[comp_idx[c]])
373
+ break;
374
+ cstr[cidx++] = comp_method2char[comp_idx[c]];
375
+ }
376
+ if (!*cstr) *cstr = '.';
377
+
378
+ if ((int)kh_key(cu_size, k) < 0)
379
+ fprintf(outfp, "BLOCK %8s", "CORE");
380
+ else
381
+ fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k));
382
+ fprintf(outfp, " %12"PRId64" %12"PRId64, usize, csize);
383
+ double f = 100*(csize+.0001)/(usize+.0001);
384
+ if (f > 999)
385
+ fprintf(outfp, " >999%% %-7s", cstr);
386
+ else
387
+ fprintf(outfp, " %6.2f%% %-7s", f, cstr);
388
+
389
+ int n, j, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n);
390
+ for (j = 0; j < n; j++) {
391
+ int d = dsa[j];
392
+ if (d > 65535)
393
+ fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff);
394
+ else
395
+ fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff);
396
+ }
397
+ }
398
+
399
+ if ((int)kh_key(cu_size, k) >= 0 &&
400
+ (int)kh_key(cu_size, k) == ref_seq_blk) {
401
+ fprintf(outfp, " embedded_ref");
402
+ }
403
+ fprintf(outfp, "\n");
404
+
405
+ tot_size += total_csize(&kh_value(cu_size, k));
406
+ }
407
+
408
+ free(sorted_blocks);
409
+
410
+ return tot_size;
411
+ }
412
+
413
+ /* Main processing loop */
414
+ static int cram_size(hFILE *hf_in, samFile *in, sam_hdr_t *h, FILE *outfp,
415
+ int verbose, int encodings) {
416
+ cram_fd *in_c;
417
+ cram_container *c = NULL;
418
+ cram_block *blk = NULL;
419
+ cram_block_slice_hdr *shdr = NULL;
420
+ khiter_t k;
421
+ int ret;
422
+ cram_cid2ds_t *cid2ds = NULL;
423
+ khash_t(cu) *cu_size = kh_init(cu);
424
+ int ref_seq_blk_used = -1;
425
+ int64_t nseqs = 0, nbases = 0, ncont = 0, nslice = 0;
426
+
427
+ if (!in->is_cram) {
428
+ print_error("cram_size", "Input is not a CRAM file");
429
+ goto err;
430
+ }
431
+ in_c = in->fp.cram; // low level htslib abuse?
432
+ while ((c = cram_read_container(in_c))) {
433
+ if (cram_container_is_empty(in_c)) {
434
+ cram_block *blk;
435
+ // Container compression header
436
+ if (!(blk = cram_read_block(in_c)))
437
+ goto err;
438
+ cram_free_block(blk);
439
+ cram_free_container(c);
440
+ c = NULL; blk = NULL;
441
+ continue;
442
+ }
443
+
444
+ nseqs += cram_container_get_num_records(c);
445
+ nbases += cram_container_get_num_bases(c);
446
+
447
+ // Container compression header
448
+ int32_t num_slices;
449
+ if (!(blk = cram_read_block(in_c)))
450
+ goto err;
451
+
452
+ // Decode compression header...
453
+ cram_block_compression_hdr *chdr;
454
+ chdr = cram_decode_compression_header(in_c, blk);
455
+
456
+ if (encodings) {
457
+ kstring_t ks = KS_INITIALIZE;
458
+ if (cram_describe_encodings(chdr, &ks) < 0)
459
+ goto err;
460
+
461
+ fprintf(outfp, "Container encodings\n%s\n", ks_str(&ks));
462
+
463
+ ks_free(&ks);
464
+ }
465
+
466
+ cid2ds = cram_update_cid2ds_map(chdr, cid2ds);
467
+
468
+ cram_free_block(blk);
469
+ blk = NULL;
470
+
471
+ cram_free_compression_header(chdr);
472
+
473
+ // Container num_blocks can be invalid, due to a bug.
474
+ // Instead we iterate in slice context instead.
475
+ (void)cram_container_get_landmarks(c, &num_slices);
476
+ ncont++;
477
+ nslice += num_slices;
478
+
479
+ int i, j;
480
+ for (i = 0; i < num_slices; i++) {
481
+ // Slice header
482
+ if (!(blk = cram_read_block(in_c)))
483
+ goto err;
484
+ if (!(shdr = cram_decode_slice_header(in_c, blk)))
485
+ goto err;
486
+ cram_free_block(blk);
487
+ blk = NULL;
488
+
489
+ int ref_seq_blk = cram_slice_hdr_get_embed_ref_id(shdr);
490
+ int num_blocks = cram_slice_hdr_get_num_blocks(shdr);
491
+
492
+ // Embedded reference. Check it's consistent (if used this is
493
+ // an almost guaranteed certainty, so we take the easy route).
494
+ if (ref_seq_blk >= 0) {
495
+ if (ref_seq_blk_used == -1)
496
+ ref_seq_blk_used = ref_seq_blk;
497
+ else if (ref_seq_blk_used != ref_seq_blk)
498
+ fprintf(samtools_stderr, "Embedded reference is not consistently using the same Content-Id.\n"
499
+ "Reported figures for reference will be invalid.\n");
500
+ }
501
+
502
+ // Slice data blocks
503
+ for (j = 0; j < num_blocks; j++) {
504
+ // read and discard, unless it's the ref-ID block
505
+ if (!(blk = cram_read_block(in_c)))
506
+ goto err;
507
+
508
+ int32_t csize = cram_block_get_comp_size(blk);
509
+ int32_t usize = cram_block_get_uncomp_size(blk);
510
+ int cid = cram_block_get_content_id(blk);
511
+ enum cram_block_method method = cram_block_get_method(blk);
512
+
513
+ // Expand comp to the internal sub-formats, eg
514
+ // rANS order-0/1, PACK+RLE, etc.
515
+ cram_method_details *cm;
516
+ cm = cram_expand_method(cram_block_get_data(blk),
517
+ cram_block_get_comp_size(blk),
518
+ method);
519
+ if (!cm)
520
+ goto err;
521
+ enum comp_expanded comp
522
+ = comp_method2expanded(cm);
523
+ free(cm);
524
+
525
+ k = kh_put(cu, cu_size, cid, &ret);
526
+ if (ret < 0)
527
+ goto err;
528
+ if (ret == 0) {
529
+ kh_value(cu_size, k).csize[comp] += csize;
530
+ kh_value(cu_size, k).usize[comp] += usize;
531
+ } else {
532
+ memset(&kh_value(cu_size, k), 0, sizeof(cusize_t));
533
+ kh_value(cu_size, k).csize[comp] = csize;
534
+ kh_value(cu_size, k).usize[comp] = usize;
535
+ }
536
+
537
+ cram_free_block(blk);
538
+ blk = NULL;
539
+ }
540
+ cram_free_slice_header(shdr);
541
+ shdr = NULL;
542
+ }
543
+
544
+ cram_free_container(c);
545
+ c = NULL;
546
+ }
547
+
548
+ off_t tot_size = report_size(outfp, verbose, ref_seq_blk_used,
549
+ cu_size, cid2ds);
550
+ if (tot_size < 0)
551
+ goto err;
552
+
553
+ kh_destroy(cu, cu_size);
554
+ cram_cid2ds_free(cid2ds);
555
+
556
+ off_t end = htell(hf_in);
557
+
558
+ fprintf(outfp, "\n");
559
+ fprintf(outfp, "Number of containers %18"PRId64"\n", ncont);
560
+ fprintf(outfp, "Number of slices %18"PRId64"\n", nslice);
561
+ fprintf(outfp, "Number of sequences %18"PRId64"\n", nseqs);
562
+ fprintf(outfp, "Number of bases %18"PRId64"\n", nbases);
563
+ fprintf(outfp, "Total file size %18"PRId64"\n", (int64_t) end);
564
+ fprintf(outfp, "Format overhead size %18"PRId64"\n", (int64_t) (end - tot_size));
565
+
566
+ return 0;
567
+
568
+ err:
569
+ // Report anyway so we can get stats on partial files, but be
570
+ // sure to error too.
571
+ report_size(outfp, verbose, ref_seq_blk_used, cu_size, cid2ds);
572
+
573
+ print_error("cram_size", "Failed in decoding CRAM file");
574
+ if (blk)
575
+ cram_free_block(blk);
576
+ if (shdr)
577
+ cram_free_slice_header(shdr);
578
+ if (c)
579
+ cram_free_container(c);
580
+ if (cid2ds)
581
+ cram_cid2ds_free(cid2ds);
582
+
583
+ return -1;
584
+ }
585
+
586
+ /* main() for cram_size */
587
+ int main_cram_size(int argc, char *argv[]) {
588
+ int c, usage = 0, verbose = 0, encodings = 0;
589
+ sam_hdr_t *h = 0;
590
+ hFILE *hf_in = NULL;
591
+ samFile *in = NULL;
592
+ sam_global_args ga;
593
+ FILE *outfp = samtools_stdout;
594
+
595
+ static const struct option lopts[] = {
596
+ {"output", required_argument, NULL, 'o'},
597
+ {"verbose", no_argument, NULL, 'v'},
598
+ {"encodings", no_argument, NULL, 'e'},
599
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '-'),
600
+ { NULL, 0, NULL, 0 }
601
+ };
602
+
603
+ sam_global_args_init(&ga);
604
+
605
+ while ((c = getopt_long(argc, argv, "vo:e", lopts, NULL)) >= 0) {
606
+ switch (c) {
607
+ case 'o':
608
+ if (!(outfp = fopen(optarg, "w"))) {
609
+ perror(optarg);
610
+ goto err;
611
+ }
612
+ break;
613
+
614
+ case 'v':
615
+ verbose++;
616
+ break;
617
+
618
+ case 'e':
619
+ encodings++;
620
+ break;
621
+
622
+ default:
623
+ if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
624
+ /* else fall-through */
625
+ case '?': usage=1; break;
626
+ }
627
+ }
628
+
629
+ if ((optind == argc && isatty(0)) || usage) {
630
+ fprintf(samtools_stdout, "Usage: samtools cram_size [-ve] [-o out.size] [in.cram]\n");
631
+ return 0;
632
+ }
633
+
634
+ char *fn = optind < argc ? argv[optind] : "-";
635
+
636
+ // We want access to in->fp.cram->fp, but this is an opaque struct so we
637
+ // can't get that. However we opened with hopen and then reopen as
638
+ // CRAM with hts_hopen, which will swallow the initial hFILE and take
639
+ // owenership of it. Hence we now know in->fp.cram->fp.
640
+ if (!(hf_in = hopen(fn, "r"))) {
641
+ print_error_errno("cram_size", "failed to open file '%s'", fn);
642
+ return 1;
643
+ }
644
+ if (!(in = hts_hopen(hf_in, fn, "r"))) {
645
+ print_error_errno("cram_size", "failed to open file '%s'", fn);
646
+ goto err;
647
+ }
648
+
649
+ if (!(h = sam_hdr_read(in)))
650
+ goto err;
651
+
652
+ int ret = cram_size(hf_in, in, h, outfp, verbose, encodings);
653
+ sam_hdr_destroy(h);
654
+ sam_close(in);
655
+ if (outfp != samtools_stdout)
656
+ fclose(outfp);
657
+
658
+ return ret ? 1 : 0;
659
+
660
+ err:
661
+ if (in)
662
+ sam_close(in);
663
+ if (h)
664
+ sam_hdr_destroy(h);
665
+
666
+ return 1;
667
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* cut_target.c -- targetcut subcommand.
2
+
3
+ Copyright (C) 2011 Broad Institute.
4
+ Copyright (C) 2012-2013, 2015, 2016, 2019 Genome Research Ltd.
5
+
6
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <unistd.h>
29
+ #include <stdlib.h>
30
+ #include <string.h>
31
+ #include "htslib/hts.h"
32
+ #include "htslib/sam.h"
33
+ #include "htslib/faidx.h"
34
+ #include "samtools.h"
35
+ #include "sam_opts.h"
36
+
37
+ #define ERR_DEP 0.83
38
+
39
+ typedef struct {
40
+ int e[2][3], p[2][2];
41
+ } score_param_t;
42
+
43
+ /* Note that although the two matrics have 10 parameters in total, only 4
44
+ * (probably 3) are free. Changing the scoring matrices in a sort of symmetric
45
+ * way will not change the result. */
46
+ static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} };
47
+
48
+ typedef struct {
49
+ int min_baseQ, tid, max_bases;
50
+ uint16_t *bases;
51
+ samFile *fp;
52
+ sam_hdr_t *h;
53
+ char *ref;
54
+ hts_pos_t len;
55
+ faidx_t *fai;
56
+ errmod_t *em;
57
+ } ct_t;
58
+
59
+ static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp)
60
+ {
61
+ int i, j, ret, tmp, k, sum[4], qual;
62
+ float q[16];
63
+ if (n > g->max_bases) { // enlarge g->bases
64
+ g->max_bases = n;
65
+ kroundup32(g->max_bases);
66
+ g->bases = realloc(g->bases, (size_t) g->max_bases * 2);
67
+ }
68
+ for (i = k = 0; i < n; ++i) {
69
+ const bam_pileup1_t *p = plp + i;
70
+ uint8_t *seq;
71
+ int q, baseQ, b;
72
+ if (p->is_refskip || p->is_del) continue;
73
+ baseQ = bam_get_qual(p->b)[p->qpos];
74
+ if (baseQ < g->min_baseQ) continue;
75
+ seq = bam_get_seq(p->b);
76
+ b = seq_nt16_int[bam_seqi(seq, p->qpos)];
77
+ if (b > 3) continue;
78
+ q = baseQ < p->b->core.qual? baseQ : p->b->core.qual;
79
+ if (q < 4) q = 4;
80
+ if (q > 63) q = 63;
81
+ g->bases[k++] = q<<5 | bam_is_rev(p->b)<<4 | b;
82
+ }
83
+ if (k == 0) return 0;
84
+ errmod_cal(g->em, k, 4, g->bases, q);
85
+ for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i;
86
+ for (i = 1; i < 4; ++i) // insertion sort
87
+ for (j = i; j > 0 && sum[j] < sum[j-1]; --j)
88
+ tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp;
89
+ qual = (sum[1]>>2) - (sum[0]>>2);
90
+ k = k < 256? k : 255;
91
+ ret = (qual < 63? qual : 63) << 2 | (sum[0]&3);
92
+ return ret<<8|k;
93
+ }
94
+
95
+ static void process_cns(sam_hdr_t *h, int tid, hts_pos_t l, uint16_t *cns)
96
+ {
97
+ int64_t i, s;
98
+ int f[2][2], *prev, *curr, *swap_tmp;
99
+ uint8_t *b; // backtrack array
100
+ b = calloc(l, 1);
101
+ f[0][0] = f[0][1] = 0;
102
+ prev = f[0]; curr = f[1];
103
+ // fill the backtrack matrix
104
+ for (i = 0; i < l; ++i) {
105
+ int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2;
106
+ int tmp0, tmp1;
107
+ // compute f[0]
108
+ tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0)
109
+ tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1)
110
+ if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0;
111
+ else curr[0] = tmp1, b[i] = 1;
112
+ // compute f[1]
113
+ tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0)
114
+ tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1)
115
+ if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1;
116
+ else curr[1] = tmp1, b[i] |= 1<<1;
117
+ // swap
118
+ swap_tmp = prev; prev = curr; curr = swap_tmp;
119
+ }
120
+ // backtrack
121
+ s = prev[0] > prev[1]? 0 : 1;
122
+ for (i = l - 1; i > 0; --i) {
123
+ b[i] |= s<<2;
124
+ s = b[i]>>s&1;
125
+ }
126
+ // print
127
+ for (i = 0, s = -1; i < INT64_MAX && i <= l; ++i) {
128
+ if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) {
129
+ if (s >= 0) {
130
+ int64_t j;
131
+ printf("%s:%"PRId64"-%"PRId64"\t0\t%s\t%"PRId64"\t60\t%"PRId64"M\t*\t0\t0\t", sam_hdr_tid2name(h, tid), s+1, i, sam_hdr_tid2name(h, tid), s+1, i-s);
132
+ for (j = s; j < i; ++j) {
133
+ int c = cns[j]>>8;
134
+ if (c == 0) putchar('N');
135
+ else putchar("ACGT"[c&3]);
136
+ }
137
+ putchar('\t');
138
+ for (j = s; j < i; ++j)
139
+ putchar(33 + (cns[j]>>8>>2));
140
+ putchar('\n');
141
+ }
142
+ //if (s >= 0) printf("%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s);
143
+ s = -1;
144
+ } else if ((b[i]>>2&3) && s < 0) s = i;
145
+ }
146
+ free(b);
147
+ }
148
+
149
+ static int read_aln(void *data, bam1_t *b)
150
+ {
151
+ ct_t *g = (ct_t*)data;
152
+ int ret;
153
+ while (1)
154
+ {
155
+ ret = sam_read1(g->fp, g->h, b);
156
+ if ( ret<0 ) break;
157
+ if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
158
+ if ( g->fai && b->core.tid >= 0 ) {
159
+ if (b->core.tid != g->tid) { // then load the sequence
160
+ free(g->ref);
161
+ g->ref = fai_fetch64(g->fai, sam_hdr_tid2name(g->h, b->core.tid), &g->len);
162
+ g->tid = b->core.tid;
163
+ }
164
+ sam_prob_realn(b, g->ref, g->len, 1<<1|1);
165
+ }
166
+ break;
167
+ }
168
+ return ret;
169
+ }
170
+
171
+ int main_cut_target(int argc, char *argv[])
172
+ {
173
+ int c, tid, pos, n, lasttid = -1, usage = 0, status = EXIT_SUCCESS;
174
+ hts_pos_t l, max_l;
175
+ const bam_pileup1_t *p;
176
+ bam_plp_t plp;
177
+ uint16_t *cns;
178
+ ct_t g;
179
+
180
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
181
+ static const struct option lopts[] = {
182
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'f', '-'),
183
+ { NULL, 0, NULL, 0 }
184
+ };
185
+
186
+ memset(&g, 0, sizeof(ct_t));
187
+ g.min_baseQ = 13; g.tid = -1;
188
+ while ((c = getopt_long(argc, argv, "f:Q:i:o:0:1:2:", lopts, NULL)) >= 0) {
189
+ switch (c) {
190
+ case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff
191
+ case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY
192
+ case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE
193
+ case '1': g_param.e[1][1] = atoi(optarg); break;
194
+ case '2': g_param.e[1][2] = atoi(optarg); break;
195
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
196
+ /* else fall-through */
197
+ case '?': usage=1; break;
198
+ }
199
+ }
200
+ if (ga.reference) {
201
+ g.fai = fai_load(ga.reference);
202
+ if (g.fai == 0) fprintf(stderr, "[%s] fail to load the fasta index.\n", __func__);
203
+ }
204
+ if (usage || argc == optind) {
205
+ fprintf(stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] <in.bam>\n");
206
+ sam_global_opt_help(stderr, "-.--f--.");
207
+ return 1;
208
+ }
209
+ l = max_l = 0; cns = 0;
210
+ g.fp = sam_open_format(argv[optind], "r", &ga.in);
211
+ if (g.fp == NULL) {
212
+ print_error_errno("targetcut", "can't open \"%s\"", argv[optind]);
213
+ return 1;
214
+ }
215
+
216
+ g.h = sam_hdr_read(g.fp);
217
+ if (g.h == NULL) {
218
+ print_error("targetcut", "couldn't read header for \"%s\"", argv[optind]);
219
+ sam_close(g.fp);
220
+ return 1;
221
+ }
222
+ g.em = errmod_init(1. - ERR_DEP);
223
+ plp = bam_plp_init(read_aln, &g);
224
+ while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) {
225
+ if (tid < 0) break;
226
+ if (tid != lasttid) { // change of chromosome
227
+ if (cns) process_cns(g.h, lasttid, l, cns);
228
+ if (max_l < sam_hdr_tid2len(g.h, tid)) {
229
+ max_l = sam_hdr_tid2len(g.h, tid);
230
+ kroundup32(max_l);
231
+ cns = realloc(cns, max_l * 2);
232
+ }
233
+ l = sam_hdr_tid2len(g.h, tid);
234
+ memset(cns, 0, max_l * 2);
235
+ lasttid = tid;
236
+ }
237
+ cns[pos] = gencns(&g, n, p);
238
+ }
239
+ process_cns(g.h, lasttid, l, cns);
240
+
241
+ if (n < 0) {
242
+ print_error("targetcut", "error reading from \"%s\"", argv[optind]);
243
+ status = EXIT_FAILURE;
244
+ }
245
+
246
+ free(cns);
247
+ sam_hdr_destroy(g.h);
248
+ bam_plp_destroy(plp);
249
+ sam_close(g.fp);
250
+ if (g.fai) {
251
+ fai_destroy(g.fai); free(g.ref);
252
+ }
253
+ errmod_destroy(g.em);
254
+ free(g.bases);
255
+ sam_global_args_free(&ga);
256
+ return status;
257
+ }
falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c.pysam.c ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "samtools.pysam.h"
2
+
3
+ /* cut_target.c -- targetcut subcommand.
4
+
5
+ Copyright (C) 2011 Broad Institute.
6
+ Copyright (C) 2012-2013, 2015, 2016, 2019 Genome Research Ltd.
7
+
8
+ Author: Heng Li <lh3@sanger.ac.uk>
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 <unistd.h>
31
+ #include <stdlib.h>
32
+ #include <string.h>
33
+ #include "htslib/hts.h"
34
+ #include "htslib/sam.h"
35
+ #include "htslib/faidx.h"
36
+ #include "samtools.h"
37
+ #include "sam_opts.h"
38
+
39
+ #define ERR_DEP 0.83
40
+
41
+ typedef struct {
42
+ int e[2][3], p[2][2];
43
+ } score_param_t;
44
+
45
+ /* Note that although the two matrics have 10 parameters in total, only 4
46
+ * (probably 3) are free. Changing the scoring matrices in a sort of symmetric
47
+ * way will not change the result. */
48
+ static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} };
49
+
50
+ typedef struct {
51
+ int min_baseQ, tid, max_bases;
52
+ uint16_t *bases;
53
+ samFile *fp;
54
+ sam_hdr_t *h;
55
+ char *ref;
56
+ hts_pos_t len;
57
+ faidx_t *fai;
58
+ errmod_t *em;
59
+ } ct_t;
60
+
61
+ static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp)
62
+ {
63
+ int i, j, ret, tmp, k, sum[4], qual;
64
+ float q[16];
65
+ if (n > g->max_bases) { // enlarge g->bases
66
+ g->max_bases = n;
67
+ kroundup32(g->max_bases);
68
+ g->bases = realloc(g->bases, (size_t) g->max_bases * 2);
69
+ }
70
+ for (i = k = 0; i < n; ++i) {
71
+ const bam_pileup1_t *p = plp + i;
72
+ uint8_t *seq;
73
+ int q, baseQ, b;
74
+ if (p->is_refskip || p->is_del) continue;
75
+ baseQ = bam_get_qual(p->b)[p->qpos];
76
+ if (baseQ < g->min_baseQ) continue;
77
+ seq = bam_get_seq(p->b);
78
+ b = seq_nt16_int[bam_seqi(seq, p->qpos)];
79
+ if (b > 3) continue;
80
+ q = baseQ < p->b->core.qual? baseQ : p->b->core.qual;
81
+ if (q < 4) q = 4;
82
+ if (q > 63) q = 63;
83
+ g->bases[k++] = q<<5 | bam_is_rev(p->b)<<4 | b;
84
+ }
85
+ if (k == 0) return 0;
86
+ errmod_cal(g->em, k, 4, g->bases, q);
87
+ for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i;
88
+ for (i = 1; i < 4; ++i) // insertion sort
89
+ for (j = i; j > 0 && sum[j] < sum[j-1]; --j)
90
+ tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp;
91
+ qual = (sum[1]>>2) - (sum[0]>>2);
92
+ k = k < 256? k : 255;
93
+ ret = (qual < 63? qual : 63) << 2 | (sum[0]&3);
94
+ return ret<<8|k;
95
+ }
96
+
97
+ static void process_cns(sam_hdr_t *h, int tid, hts_pos_t l, uint16_t *cns)
98
+ {
99
+ int64_t i, s;
100
+ int f[2][2], *prev, *curr, *swap_tmp;
101
+ uint8_t *b; // backtrack array
102
+ b = calloc(l, 1);
103
+ f[0][0] = f[0][1] = 0;
104
+ prev = f[0]; curr = f[1];
105
+ // fill the backtrack matrix
106
+ for (i = 0; i < l; ++i) {
107
+ int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2;
108
+ int tmp0, tmp1;
109
+ // compute f[0]
110
+ tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0)
111
+ tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1)
112
+ if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0;
113
+ else curr[0] = tmp1, b[i] = 1;
114
+ // compute f[1]
115
+ tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0)
116
+ tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1)
117
+ if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1;
118
+ else curr[1] = tmp1, b[i] |= 1<<1;
119
+ // swap
120
+ swap_tmp = prev; prev = curr; curr = swap_tmp;
121
+ }
122
+ // backtrack
123
+ s = prev[0] > prev[1]? 0 : 1;
124
+ for (i = l - 1; i > 0; --i) {
125
+ b[i] |= s<<2;
126
+ s = b[i]>>s&1;
127
+ }
128
+ // print
129
+ for (i = 0, s = -1; i < INT64_MAX && i <= l; ++i) {
130
+ if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) {
131
+ if (s >= 0) {
132
+ int64_t j;
133
+ fprintf(samtools_stdout, "%s:%"PRId64"-%"PRId64"\t0\t%s\t%"PRId64"\t60\t%"PRId64"M\t*\t0\t0\t", sam_hdr_tid2name(h, tid), s+1, i, sam_hdr_tid2name(h, tid), s+1, i-s);
134
+ for (j = s; j < i; ++j) {
135
+ int c = cns[j]>>8;
136
+ if (c == 0) fputc('N', samtools_stdout);
137
+ else fputc("ACGT"[c&3], samtools_stdout);
138
+ }
139
+ fputc('\t', samtools_stdout);
140
+ for (j = s; j < i; ++j)
141
+ fputc(33 + (cns[j]>>8>>2), samtools_stdout);
142
+ fputc('\n', samtools_stdout);
143
+ }
144
+ //if (s >= 0) fprintf(samtools_stdout, "%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s);
145
+ s = -1;
146
+ } else if ((b[i]>>2&3) && s < 0) s = i;
147
+ }
148
+ free(b);
149
+ }
150
+
151
+ static int read_aln(void *data, bam1_t *b)
152
+ {
153
+ ct_t *g = (ct_t*)data;
154
+ int ret;
155
+ while (1)
156
+ {
157
+ ret = sam_read1(g->fp, g->h, b);
158
+ if ( ret<0 ) break;
159
+ if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
160
+ if ( g->fai && b->core.tid >= 0 ) {
161
+ if (b->core.tid != g->tid) { // then load the sequence
162
+ free(g->ref);
163
+ g->ref = fai_fetch64(g->fai, sam_hdr_tid2name(g->h, b->core.tid), &g->len);
164
+ g->tid = b->core.tid;
165
+ }
166
+ sam_prob_realn(b, g->ref, g->len, 1<<1|1);
167
+ }
168
+ break;
169
+ }
170
+ return ret;
171
+ }
172
+
173
+ int main_cut_target(int argc, char *argv[])
174
+ {
175
+ int c, tid, pos, n, lasttid = -1, usage = 0, status = EXIT_SUCCESS;
176
+ hts_pos_t l, max_l;
177
+ const bam_pileup1_t *p;
178
+ bam_plp_t plp;
179
+ uint16_t *cns;
180
+ ct_t g;
181
+
182
+ sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
183
+ static const struct option lopts[] = {
184
+ SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'f', '-'),
185
+ { NULL, 0, NULL, 0 }
186
+ };
187
+
188
+ memset(&g, 0, sizeof(ct_t));
189
+ g.min_baseQ = 13; g.tid = -1;
190
+ while ((c = getopt_long(argc, argv, "f:Q:i:o:0:1:2:", lopts, NULL)) >= 0) {
191
+ switch (c) {
192
+ case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff
193
+ case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY
194
+ case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE
195
+ case '1': g_param.e[1][1] = atoi(optarg); break;
196
+ case '2': g_param.e[1][2] = atoi(optarg); break;
197
+ default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
198
+ /* else fall-through */
199
+ case '?': usage=1; break;
200
+ }
201
+ }
202
+ if (ga.reference) {
203
+ g.fai = fai_load(ga.reference);
204
+ if (g.fai == 0) fprintf(samtools_stderr, "[%s] fail to load the fasta index.\n", __func__);
205
+ }
206
+ if (usage || argc == optind) {
207
+ fprintf(samtools_stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] <in.bam>\n");
208
+ sam_global_opt_help(samtools_stderr, "-.--f--.");
209
+ return 1;
210
+ }
211
+ l = max_l = 0; cns = 0;
212
+ g.fp = sam_open_format(argv[optind], "r", &ga.in);
213
+ if (g.fp == NULL) {
214
+ print_error_errno("targetcut", "can't open \"%s\"", argv[optind]);
215
+ return 1;
216
+ }
217
+
218
+ g.h = sam_hdr_read(g.fp);
219
+ if (g.h == NULL) {
220
+ print_error("targetcut", "couldn't read header for \"%s\"", argv[optind]);
221
+ sam_close(g.fp);
222
+ return 1;
223
+ }
224
+ g.em = errmod_init(1. - ERR_DEP);
225
+ plp = bam_plp_init(read_aln, &g);
226
+ while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) {
227
+ if (tid < 0) break;
228
+ if (tid != lasttid) { // change of chromosome
229
+ if (cns) process_cns(g.h, lasttid, l, cns);
230
+ if (max_l < sam_hdr_tid2len(g.h, tid)) {
231
+ max_l = sam_hdr_tid2len(g.h, tid);
232
+ kroundup32(max_l);
233
+ cns = realloc(cns, max_l * 2);
234
+ }
235
+ l = sam_hdr_tid2len(g.h, tid);
236
+ memset(cns, 0, max_l * 2);
237
+ lasttid = tid;
238
+ }
239
+ cns[pos] = gencns(&g, n, p);
240
+ }
241
+ process_cns(g.h, lasttid, l, cns);
242
+
243
+ if (n < 0) {
244
+ print_error("targetcut", "error reading from \"%s\"", argv[optind]);
245
+ status = EXIT_FAILURE;
246
+ }
247
+
248
+ free(cns);
249
+ sam_hdr_destroy(g.h);
250
+ bam_plp_destroy(plp);
251
+ sam_close(g.fp);
252
+ if (g.fai) {
253
+ fai_destroy(g.fai); free(g.ref);
254
+ }
255
+ errmod_destroy(g.em);
256
+ free(g.bases);
257
+ sam_global_args_free(&ga);
258
+ return status;
259
+ }