diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/call.h b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/call.h new file mode 100644 index 0000000000000000000000000000000000000000..16bf0b68e558064e75a94b37f1ca8e678f7adf3d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/call.h @@ -0,0 +1,149 @@ +/* call.h -- variant calling declarations. + + Copyright (C) 2013-2015, 2019-2020 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#ifndef __CALL_H__ +#define __CALL_H__ + +#include +#include +#include "vcmp.h" + +#define CALL_KEEPALT 1 +#define CALL_VARONLY (1<<1) +#define CALL_CONSTR_TRIO (1<<2) +#define CALL_CONSTR_ALLELES (1<<3) +// +#define CALL_FMT_PV4 (1<<5) +#define CALL_FMT_GQ (1<<6) +#define CALL_FMT_GP (1<<7) + +#define FATHER 0 +#define MOTHER 1 +#define CHILD 2 +typedef struct +{ + char *name; + int sample[3]; // father, mother, child + int type; // see FTYPE_* definitions in mcall.c +} +family_t; + +// For the single-sample and grouped -G calling +typedef struct +{ + double ref_lk, max_lk, lk_sum; + float *qsum; // QS(quality sum) values + int nqsum; + uint32_t *smpl, nsmpl; + uint32_t nals, als; +} +smpl_grp_t; + +// For the `-C alleles -i` constrained calling +typedef struct +{ + uint32_t n:31, used:1; + char **allele; +} +tgt_als_t; + +typedef struct _ccall_t ccall_t; +typedef struct +{ + // mcall only + int npdg; + int *als_map, nals_map; // mapping from full set of alleles to trimmed set of alleles (old -> new) + int *pl_map, npl_map; // same as above for PLs, but reverse (new -> old) + char **als; // array to hold the trimmed set of alleles to appear on output + int nals; // size of the als array + int als_new, nals_new; // bitmask with final alleles and their number + family_t *fams; // list of families and samples for trio calling + int nfams, mfams; + int ntrio[5][5]; // possible trio genotype combinations and their counts; first idx: + uint16_t *trio[5][5]; // family type, second index: allele count (2-4, first two are unused) + double *GLs; + float *GPs; // FORMAT/GP: posterior probabilities + int32_t *GQs, *ADs; // FORMAT/GQ: genotype qualities; AD: allelic depth for -G + int32_t *itmp; // temporary int array, used for new PLs with CALL_CONSTR_ALLELES + int n_itmp, nGPs, nADs; + vcmp_t *vcmp; + double trio_Pm_SNPs, trio_Pm_del, trio_Pm_ins; // P(mendelian) for trio calling, see mcall_call_trio_genotypes() + int32_t *ugts, *cgts; // unconstraind and constrained GTs + uint32_t output_tags; + char *prior_AN, *prior_AC; // reference panel AF tags (AF=AC/AN) + tgt_als_t *tgt_als; // for CALL_CONSTR_ALLELES + char *sample_groups; // for single-sample or grouped calling with -G + char *sample_groups_tag; // for -G [AD|QS:] + smpl_grp_t *smpl_grp; + int nsmpl_grp; + + // ccall only + double indel_frac, min_perm_p, min_lrt; + double prior_type, pref; + int ngrp1_samples, n_perm; + char *prior_file; + ccall_t *cdat; + + // shared + bcf_srs_t *srs; // BCF synced readers holding target alleles for CALL_CONSTR_ALLELES + bcf1_t *rec; + bcf_hdr_t *hdr; + uint32_t flag; // One or more of the CALL_* flags defined above + uint8_t *ploidy, all_diploid, unseen; + + double pl2p[256]; // PL to 10^(-PL/10) table + int32_t *PLs; // VCF PL likelihoods (rw) + int nPLs, mPLs, nac; + int32_t *gts, *ac; // GTs and AC (w) + double *pdg; // PLs converted to P(D|G) + float *anno16; int n16; // see anno[16] in bam2bcf.h + double theta; // prior +} +call_t; + +void error(const char *format, ...); + +/* + * call() - return -1 value on critical error; -2 to skip the site; or the number of non-reference + * alleles on success. + */ +int mcall(call_t *call, bcf1_t *rec); // multiallic and rare-variant calling model +int ccall(call_t *call, bcf1_t *rec); // the default consensus calling model +int qcall(call_t *call, bcf1_t *rec); // QCall output + +void mcall_init(call_t *call); +void ccall_init(call_t *call); +void qcall_init(call_t *call); + +void mcall_destroy(call_t *call); +void ccall_destroy(call_t *call); +void qcall_destroy(call_t *call); + +void call_init_pl2p(call_t *call); +uint32_t *call_trio_prep(int is_x, int is_son); + +void init_allele_trimming_maps(call_t *call, int nals_ori, int als_out); +void mcall_trim_and_update_numberR(call_t *call, bcf1_t *rec, int nals_ori, int nals_new); + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ccall.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ccall.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..eb7c615817e20229bb908cb758aa8689552776d4 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ccall.c.pysam.c @@ -0,0 +1,340 @@ +#include "bcftools.pysam.h" + +/* ccall.c -- consensus variant calling. + + Copyright (C) 2013-2014 Genome Research Ltd. + Portions copyright (C) 2010 Broad Institute. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#include +#include +#include +#include "call.h" +#include "kmin.h" +#include "prob1.h" + +// Most of the original -c calling was moved to bcftools as it was +// and its data structures were wrapped into the ccal_t to make it +// functional quickly. This is not the desired state. +struct _ccall_t +{ + bcf_p1aux_t *p1; +}; + +void ccall_init(call_t *call) +{ + call->cdat = (ccall_t*) calloc(1,sizeof(ccall_t)); + call_init_pl2p(call); + call->cdat->p1 = bcf_p1_init(bcf_hdr_nsamples(call->hdr), call->ploidy); + call->gts = (int*) calloc(bcf_hdr_nsamples(call->hdr)*2,sizeof(int)); // assuming at most diploid everywhere + call->nals_map = 5; + call->als_map = (int*) malloc(sizeof(int)*call->nals_map); + + bcf_hdr_append(call->hdr,"##FORMAT="); + if ( call->output_tags & CALL_FMT_GQ ) + { + bcf_hdr_append(call->hdr,"##FORMAT="); + call->GQs = (int32_t*) malloc(sizeof(int32_t)*bcf_hdr_nsamples(call->hdr)); + } + if ( call->output_tags & CALL_FMT_GP ) + error("Sorry, -f GP is not supported with -c\n"); + bcf_hdr_append(call->hdr,"##INFO="); + // Todo: groups not migrated to 'bcftools call' yet + bcf_hdr_append(call->hdr,"##INFO="); + bcf_hdr_append(call->hdr,"##INFO="); + bcf_hdr_append(call->hdr,"##INFO=\n"); + bcf_hdr_append(call->hdr,"##INFO=\n"); + bcf_hdr_append(call->hdr,"##INFO=\n"); + bcf_hdr_append(call->hdr,"##INFO=\n"); + bcf_hdr_append(call->hdr,"##INFO=\n"); + // bcf_hdr_append(call->hdr,); + // bcf_hdr_append(call->hdr,); + bcf_hdr_append(call->hdr,"##INFO="); + + return; +} +void ccall_destroy(call_t *call) +{ + free(call->itmp); + free(call->als_map); + free(call->gts); + free(call->anno16); + free(call->PLs); + free(call->GQs); + free(call->pdg); + bcf_p1_destroy(call->cdat->p1); + free(call->cdat); + return; +} + +// Inits P(D|G): convert PLs from log space, only two alleles (three PLs) are used. +// NB: The original samtools calling code uses pdgs in reverse order (AA comes +// first, RR last), while the -m calling model uses the canonical order. +static void set_pdg3(double *pl2p, int *PLs, double *pdg, int n_smpl, int n_gt) +{ + int i; + for (i=0; ip[0] = a->p[1] = a->p[2] = a->p[3] = 1.; + for (i=0; i<4; i++) a->d[i] = anno[i]; + a->depth = anno[0] + anno[1] + anno[2] + anno[3]; + a->is_tested = (anno[0] + anno[1] > 0 && anno[2] + anno[3] > 0); + if (a->depth == 0) return -1; + a->mq = (int)(sqrt((anno[9] + anno[11]) / a->depth) + .499); + kt_fisher_exact(anno[0], anno[1], anno[2], anno[3], &left, &right, &a->p[0]); + for (i = 1; i < 4; ++i) + a->p[i] = ttest(anno[0] + anno[1], anno[2] + anno[3], anno+4*i); + return 0; +} + +int test16(float *anno16, anno16_t *a) +{ + a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.; + a->d[0] = a->d[1] = a->d[2] = a->d[3] = 0.; + a->mq = a->depth = a->is_tested = 0; + return test16_core(anno16, a); +} +static int update_bcf1(call_t *call, bcf1_t *rec, const bcf_p1rst_t *pr, double em[10]) +{ + int has_I16, is_var; + float fq, r; + anno16_t a; + float tmpf[4], tmpi; + + bcf_get_info_float(call->hdr, rec, "I16", &call->anno16, &call->n16); + + has_I16 = test16(call->anno16, &a) >= 0? 1 : 0; + + // print EM + if (em[0] >= 0) + { + tmpf[0] = 1 - em[0]; + bcf_update_info_float(call->hdr, rec, "AF1", tmpf, 1); + } + if (em[4] >= 0 && em[4] <= 0.05) + { + tmpf[0] = em[3]; tmpf[1] = em[2]; tmpf[2] = em[1]; tmpf[3] = em[4]; + bcf_update_info_float(call->hdr, rec, "G3", tmpf, 3); + bcf_update_info_float(call->hdr, rec, "HWE", &tmpf[3], 1); + } + if (em[5] >= 0 && em[6] >= 0) + { + tmpf[0] = 1 - em[5]; tmpf[1] = 1 - em[6]; + bcf_update_info_float(call->hdr, rec, "AF2", tmpf, 2); + } + if (em[7] >= 0) + { + tmpf[0] = em[7]; + bcf_update_info_float(call->hdr, rec, "LRT", tmpf, 1); + } + if (em[8] >= 0) + { + tmpf[0] = em[8]; + bcf_update_info_float(call->hdr, rec, "LRT2", tmpf, 1); + } + + bcf_p1aux_t *p1 = call->cdat->p1; + if (p1->cons_llr > 0) + { + tmpi = p1->cons_llr; + bcf_update_info_int32(call->hdr, rec, "CLR", &tmpi, 1); + // todo: trio calling with -c + if (p1->cons_gt > 0) + { + char tmp[4]; + tmp[0] = p1->cons_gt&0xff; tmp[1] = p1->cons_gt>>8&0xff; tmp[2] = p1->cons_gt>>16&0xff; tmp[3] = 0; + bcf_update_info_string(call->hdr, rec, "UGT", tmp); + tmp[0] = p1->cons_gt>>32&0xff; tmp[1] = p1->cons_gt>>40&0xff; tmp[2] = p1->cons_gt>>48&0xff; + bcf_update_info_string(call->hdr, rec, "CGT", tmp); + } + } + is_var = (pr->p_ref < call->pref); + r = is_var? pr->p_ref : pr->p_var; + + bcf_update_info_int32(call->hdr, rec, "AC1", &pr->ac, 1); + int32_t dp[4]; dp[0] = call->anno16[0]; dp[1] = call->anno16[1]; dp[2] = call->anno16[2]; dp[3] = call->anno16[3]; + bcf_update_info_int32(call->hdr, rec, "DP4", dp, 4); + bcf_update_info_int32(call->hdr, rec, "MQ", &a.mq, 1); + + fq = pr->p_ref_folded < 0.5? -4.343 * log(pr->p_ref_folded) : 4.343 * log(pr->p_var_folded); + if (fq < -999) fq = -999; + if (fq > 999) fq = 999; + bcf_update_info_float(call->hdr, rec, "FQ", &fq, 1); + + assert( pr->cmp[0]<0 ); + // todo + // if (pr->cmp[0] >= 0.) { // two sample groups + // int i, q[3]; + // for (i = 1; i < 3; ++i) { + // double x = pr->cmp[i] + pr->cmp[0]/2.; + // q[i] = x == 0? 255 : (int)(-4.343 * log(x) + .499); + // if (q[i] > 255) q[i] = 255; + // } + // if (pr->perm_rank >= 0) ksprintf(&s, "PR=%d;", pr->perm_rank); + // + // ksprintf(&s, "PCHI2=%.3g;PC2=%d,%d;", q[1], q[2], pr->p_chi2); + // } + + if (has_I16 && a.is_tested) + { + int i; + for (i=0; i<4; i++) tmpf[i] = a.p[i]; + bcf_update_info_float(call->hdr, rec, "PV4", tmpf, 4); + } + bcf_update_info_int32(call->hdr, rec, "I16", NULL, 0); // remove I16 tag + bcf_update_info_int32(call->hdr, rec, "QS", NULL, 0); // remove QS tag + + rec->qual = r < 1e-100? 999 : -4.343 * log(r); + if (rec->qual > 999) rec->qual = 999; + + // Remove unused alleles + int nals_ori = rec->n_allele, nals = !is_var && !(call->flag & CALL_KEEPALT) ? 1 : pr->rank0 < 2? 2 : pr->rank0+1; + if ( call->flag & CALL_KEEPALT && call->unseen==nals-1 ) nals--; + + if ( nalsn_allele ) + { + bcf_update_alleles(call->hdr, rec, (const char**)rec->d.allele, nals); + + // Update PLs + int npls_src = call->nPLs / rec->n_sample, npls_dst = nals*(nals+1)/2; + int *pls_src = call->PLs - npls_src, *pls_dst = call->PLs - npls_dst; + int isample, i; + for (isample = 0; isample < rec->n_sample; isample++) + { + pls_src += npls_src; + pls_dst += npls_dst; + if ( !call->ploidy || call->ploidy[isample]==2 ) + { + for (i=0; ihdr, rec, "PL", call->PLs, npls_dst*rec->n_sample); + } + + // Call genotypes + int i; + for (i=0; in_sample; i++) + { + int x = ( is_var || call->output_tags & CALL_FMT_GQ ) ? bcf_p1_call_gt(p1, pr->f_exp, i, is_var) : 2; + int gt = x&3; + if ( !call->ploidy || call->ploidy[i]==2 ) + { + if ( gt==1 ) + { + call->gts[2*i] = bcf_gt_unphased(0); + call->gts[2*i+1] = bcf_gt_unphased(1); + } + else if ( gt==0 ) + { + call->gts[2*i] = bcf_gt_unphased(1); + call->gts[2*i+1] = bcf_gt_unphased(1); + } + else + { + call->gts[2*i] = bcf_gt_unphased(0); + call->gts[2*i+1] = bcf_gt_unphased(0); + } + if ( call->output_tags & CALL_FMT_GQ ) call->GQs[i] = x>>2; + } + else + { + if ( gt==0 ) call->gts[2*i] = bcf_gt_unphased(1); + else call->gts[2*i] = bcf_gt_unphased(0); + call->gts[2*i+1] = bcf_int32_vector_end; + if ( call->output_tags & CALL_FMT_GQ ) call->GQs[i] = bcf_int32_missing; + } + } + bcf_update_genotypes(call->hdr, rec, call->gts, rec->n_sample*2); + if ( call->output_tags & CALL_FMT_GQ ) + bcf_update_format_int32(call->hdr, rec, "GQ", call->GQs, rec->n_sample); + + // trim Number=R tags + int out_als = 0; + for (i=0; ihdr); + + // Get the genotype likelihoods + int nals = rec->n_allele; + call->nPLs = bcf_get_format_int32(call->hdr, rec, "PL", &call->PLs, &call->mPLs); + if ( call->nPLs!=nsmpl*nals*(nals+1)/2 && call->nPLs!=nsmpl*nals ) // diploid+haploid or haploid only + error("Wrong number of PL fields? nals=%d npl=%d\n", nals,call->nPLs); + + // Convert PLs to probabilities, only first two alleles are considered + int ngts = nals*(nals+1)/2; + hts_expand(double, 3*nsmpl, call->npdg, call->pdg); + set_pdg3(call->pl2p, call->PLs, call->pdg, nsmpl, ngts); + + double em[10] = {-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.}; + int ret = bcf_em1(call, rec, call->ngrp1_samples, 0x1ff, em); + + bcf_p1rst_t pr; + int do_contrast = (em[7] >= 0 && em[7] < call->min_lrt) ? 1 : 0; + ret = bcf_p1_cal(call, rec, do_contrast, call->cdat->p1, &pr); + if (pr.p_ref >= call->pref && (call->flag & CALL_VARONLY)) return 0; + if (ret >= 0) ret = update_bcf1(call, rec, &pr, em); + return ret; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/hclust.h b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/hclust.h new file mode 100644 index 0000000000000000000000000000000000000000..43d333f3b1dd3daed62043a0912a863893454c52 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/hclust.h @@ -0,0 +1,77 @@ +/* The MIT License + + Copyright (c) 2016 Genome Research Ltd. + + Author: Petr Danecek + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + */ + +/* + Simple hierarchical clustering +*/ + +#ifndef __HCLUST_H__ +#define __HCLUST_H__ + +#include + +typedef struct _hclust_t hclust_t; + +typedef struct +{ + float dist; + int nmemb, *memb; +} +cluster_t; + +#define PDIST(mat,a,b) (mat)[((a)>(b)?((a)*((a)-1)/2+(b)):((b)*((b)-1)/2+(a)))] + +/* + * hclust_init() - init and run clustering + * @n: number of elements + * @pdist: pairwise distances. The array will be modified by hclust and + * must exist until hclust_destroy() is called + */ +hclust_t *hclust_init(int n, float *pdist); +void hclust_destroy(hclust_t *clust); + +/* + * hclust_create_list() - returns a list of clusters + * @min_inter_dist: minimum inter-cluster distance. If smaller, elements are considered + * homogenous, belonging to the same cluster. + * @max_intra_dist: maximum intra-cluster distance allowed. If smaller than 0, + * the threshold can be heuristically lowered, otherwise considered + * a fixed cutoff. The pointer will be filled to the cutoff actually used. + */ +cluster_t *hclust_create_list(hclust_t *clust, float min_inter_dist, float *max_intra_dist, int *nclust); +void hclust_destroy_list(cluster_t *clust, int nclust); + +/* + * Access debugging data used in the decision making process. Note that this + * must be called immediately after hclust_create_list because other calls, + * such as hclust_create_dot(), invalidate the temporary data structures. + */ +char **hclust_explain(hclust_t *clust, int *nlines); + +char *hclust_create_dot(hclust_t *clust, char **labels, float th); + +#endif + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ploidy.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ploidy.c new file mode 100644 index 0000000000000000000000000000000000000000..550ba876c2961e19638ea9a8e8d07bbd06f8edad --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/ploidy.c @@ -0,0 +1,268 @@ +/* + Copyright (C) 2014-2016 Genome Research Ltd. + + Author: Petr Danecek + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include +#include "bcftools.h" +#include "ploidy.h" + +struct _ploidy_t +{ + int nsex, msex; // number of genders, m:number of allocated elements in id2sex array + int dflt, min, max; // ploidy: default, min and max (only explicitly listed) + int *sex2dflt; + regidx_t *idx; + regitr_t *itr; + void *sex2id; + char **id2sex; + kstring_t tmp_str; +}; + +typedef struct +{ + int sex, ploidy; +} +sex_ploidy_t; + + +regidx_t *ploidy_regions(ploidy_t *ploidy) +{ + return ploidy->idx; +} + +int ploidy_parse(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr) +{ + int i, ret; + ploidy_t *ploidy = (ploidy_t*) usr; + void *sex2id = ploidy->sex2id; + + // Check for special case of default ploidy "* * * " + int default_ploidy_def = 0; + + char *ss = (char*) line; + while ( *ss && isspace(*ss) ) ss++; + if ( ss[0]=='*' && (!ss[1] || isspace(ss[1])) ) + default_ploidy_def = 1; // definition of default ploidy, chr="*" + else + { + // Fill CHR,FROM,TO + ret = regidx_parse_tab(line,chr_beg,chr_end,beg,end,NULL,NULL); + if ( ret!=0 ) return ret; + } + + // Skip the fields already parsed by regidx_parse_tab + ss = (char*) line; + while ( *ss && isspace(*ss) ) ss++; + for (i=0; i<3; i++) + { + while ( *ss && !isspace(*ss) ) ss++; + if ( !*ss ) return -2; // wrong number of fields + while ( *ss && isspace(*ss) ) ss++; + } + if ( !*ss ) return -2; + + // Parse the payload + char *se = ss; + while ( *se && !isspace(*se) ) se++; + if ( !*se || se==ss ) error("Could not parse: %s\n", line); + ploidy->tmp_str.l = 0; + kputsn(ss,se-ss,&ploidy->tmp_str); + + sex_ploidy_t *sp = (sex_ploidy_t*) payload; + if ( khash_str2int_get(sex2id, ploidy->tmp_str.s, &sp->sex) != 0 ) + { + ploidy->nsex++; + hts_expand0(char*,ploidy->nsex,ploidy->msex,ploidy->id2sex); + ploidy->id2sex[ploidy->nsex-1] = strdup(ploidy->tmp_str.s); + sp->sex = khash_str2int_inc(ploidy->sex2id, ploidy->id2sex[ploidy->nsex-1]); + ploidy->sex2dflt = (int*) realloc(ploidy->sex2dflt,sizeof(int)*ploidy->nsex); + ploidy->sex2dflt[ploidy->nsex-1] = -1; + } + + ss = se; + while ( *se && isspace(*se) ) se++; + if ( !*se ) error("Could not parse: %s\n", line); + sp->ploidy = strtol(ss,&se,10); + if ( ss==se ) error("Could not parse: %s\n", line); + if ( ploidy->min<0 || sp->ploidy < ploidy->min ) ploidy->min = sp->ploidy; + if ( ploidy->max<0 || sp->ploidy > ploidy->max ) ploidy->max = sp->ploidy; + + // Special case, chr="*" stands for a default value + if ( default_ploidy_def ) + { + ploidy->sex2dflt[ploidy->nsex-1] = sp->ploidy; + return -1; + } + + return 0; +} + +static void _set_defaults(ploidy_t *ploidy, int dflt) +{ + int i; + if ( khash_str2int_get(ploidy->sex2id, "*", &i) == 0 ) dflt = ploidy->sex2dflt[i]; + for (i=0; insex; i++) + if ( ploidy->sex2dflt[i]==-1 ) ploidy->sex2dflt[i] = dflt; + + ploidy->dflt = dflt; + if ( ploidy->min<0 || dflt < ploidy->min ) ploidy->min = dflt; + if ( ploidy->max<0 || dflt > ploidy->max ) ploidy->max = dflt; +} + +ploidy_t *ploidy_init(const char *fname, int dflt) +{ + ploidy_t *pld = (ploidy_t*) calloc(1,sizeof(ploidy_t)); + if ( !pld ) return NULL; + + pld->min = pld->max = -1; + pld->sex2id = khash_str2int_init(); + pld->idx = regidx_init(fname,ploidy_parse,NULL,sizeof(sex_ploidy_t),pld); + if ( !pld->idx ) + { + ploidy_destroy(pld); + return NULL; + } + pld->itr = regitr_init(pld->idx); + _set_defaults(pld,dflt); + return pld; +} + +ploidy_t *ploidy_init_string(const char *str, int dflt) +{ + ploidy_t *pld = (ploidy_t*) calloc(1,sizeof(ploidy_t)); + if ( !pld ) return NULL; + + pld->min = pld->max = -1; + pld->sex2id = khash_str2int_init(); + pld->idx = regidx_init(NULL,ploidy_parse,NULL,sizeof(sex_ploidy_t),pld); + pld->itr = regitr_init(pld->idx); + + kstring_t tmp = {0,0,0}; + const char *ss = str; + while ( *ss ) + { + while ( *ss && isspace(*ss) ) ss++; + const char *se = ss; + while ( *se && *se!='\r' && *se!='\n' ) se++; + tmp.l = 0; + kputsn(ss, se-ss, &tmp); + regidx_insert(pld->idx,tmp.s); + while ( *se && isspace(*se) ) se++; + ss = se; + } + free(tmp.s); + + _set_defaults(pld,dflt); + return pld; +} + +void ploidy_destroy(ploidy_t *ploidy) +{ + if ( ploidy->sex2id ) khash_str2int_destroy_free(ploidy->sex2id); + if ( ploidy->itr ) regitr_destroy(ploidy->itr); + if ( ploidy->idx ) regidx_destroy(ploidy->idx); + free(ploidy->id2sex); + free(ploidy->tmp_str.s); + free(ploidy->sex2dflt); + free(ploidy); +} + +int ploidy_query(ploidy_t *ploidy, char *seq, int pos, int *sex2ploidy, int *min, int *max) +{ + int i, ret = regidx_overlap(ploidy->idx, seq,pos,pos, ploidy->itr); + + if ( !sex2ploidy && !min && !max ) return ret; + + if ( !ret ) + { + // no overlap + if ( min ) *min = ploidy->dflt; + if ( max ) *max = ploidy->dflt; + if ( sex2ploidy ) + for (i=0; insex; i++) sex2ploidy[i] = ploidy->sex2dflt[i]; + return 0; + } + + int _min = INT_MAX, _max = -1; + if ( sex2ploidy ) for (i=0; insex; i++) sex2ploidy[i] = ploidy->dflt; + + while ( regitr_overlap(ploidy->itr) ) + { + int sex = regitr_payload(ploidy->itr,sex_ploidy_t).sex; + int pld = regitr_payload(ploidy->itr,sex_ploidy_t).ploidy; + if ( pld!=ploidy->dflt ) + { + if ( sex2ploidy ) sex2ploidy[ sex ] = pld; + if ( _min > pld ) _min = pld; + if ( _max < pld ) _max = pld; + } + } + if ( _max==-1 ) _max = _min = ploidy->dflt; + if ( max ) *max = _max; + if ( min ) *min = _min; + + return 1; +} + +int ploidy_nsex(ploidy_t *ploidy) +{ + return ploidy->nsex; +} + +char *ploidy_id2sex(ploidy_t *ploidy, int id) +{ + if ( id<0 || id>=ploidy->nsex ) return NULL; + return ploidy->id2sex[id]; +} + +int ploidy_sex2id(ploidy_t *ploidy, char *sex) +{ + int id; + if ( khash_str2int_get(ploidy->sex2id,sex,&id)!=0 ) return -1; + return id; +} + +int ploidy_add_sex(ploidy_t *ploidy, const char *sex) +{ + int id; + if ( khash_str2int_get(ploidy->sex2id, sex, &id)==0 ) return id; + ploidy->nsex++; + hts_expand0(char*,ploidy->nsex,ploidy->msex,ploidy->id2sex); + ploidy->id2sex[ploidy->nsex-1] = strdup(sex); + ploidy->sex2dflt = (int*) realloc(ploidy->sex2dflt,sizeof(int)*ploidy->nsex); + ploidy->sex2dflt[ploidy->nsex-1] = ploidy->dflt; + return khash_str2int_inc(ploidy->sex2id, ploidy->id2sex[ploidy->nsex-1]); +} + +int ploidy_max(ploidy_t *ploidy) +{ + return ploidy->dflt > ploidy->max ? ploidy->dflt : ploidy->max; +} + +int ploidy_min(ploidy_t *ploidy) +{ + return ploidy->dflt < ploidy->min ? ploidy->dflt : ploidy->min; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/rbuf.h b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/rbuf.h new file mode 100644 index 0000000000000000000000000000000000000000..ef2e206322dbcafdc51d0118d118847b0423da6d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/rbuf.h @@ -0,0 +1,261 @@ +/* rbuf.h -- round buffers. + + Copyright (C) 2013-2014, 2017 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#ifndef __RBUF_H__ +#define __RBUF_H__ + +#include + +typedef struct +{ + int m,n,f; // m: allocated size, n: number of elements in the buffer, f: first element +} +rbuf_t; + +/** + * rbuf_init() - initialize round buffer + * @rbuf: the rbuf_t holder + * @size: the maximum number of elements + * + */ +static inline void rbuf_init(rbuf_t *rbuf, int size) +{ + rbuf->m = size; rbuf->n = rbuf->f = 0; +} +/** + * rbuf_kth() - get index of the k-th element of the round buffer + * @rbuf: the rbuf_t holder + * @k: 0-based index. If negative, return k-th element from the end, 1-based + */ +static inline int rbuf_kth(rbuf_t *rbuf, int k) +{ + if ( k >= rbuf->n ) return -1; + if ( k < 0 ) + { + k = rbuf->n + k; + if ( k < 0 ) return -1; + } + int i = k + rbuf->f; + if ( i >= rbuf->m ) i -= rbuf->m; + return i; +} +/** + * rbuf_last() - get index of the last element of the round buffer + * @rbuf: the rbuf_t holder + */ +#define rbuf_last(rbuf) rbuf_kth(rbuf, -1) + +/** + * rbuf_l2ridx() - get 0-based rbuf index which corresponds to i-th linear index + * @rbuf: the rbuf_t holder + * @idx: 0-based linear index + * + * Returns 0-based circular index or -1 if out of bounds + */ +static inline int rbuf_l2ridx(rbuf_t *rbuf, int idx) +{ + if ( idx < 0 || idx >= rbuf->n ) return -1; + if ( idx >= rbuf->f ) + { + int i = idx - rbuf->f; + if ( i >= rbuf->n ) return -1; + return i; + } + int i = rbuf->m - rbuf->f + idx; + if ( i >= rbuf->n ) return -1; + return i; +} + +/** + * rbuf_next() - get index of the next element in the round buffer + * @rbuf: the rbuf_t holder + * @i: pointer to the last rbuf index. Set to -1 before the first call. + * + * Sets i to the next position in the buffer. The return value indicates if + * the position points to a valid element (1) or if there are no more elements + * after *i (0). When the end is reached, *i is set to the first element in the + * buffer. + */ +static inline int rbuf_next(rbuf_t *rbuf, int *i) +{ + if ( !rbuf->n ) return 0; + if ( *i==-1 ) { *i = rbuf->f; return 1; } + int n = (rbuf->f <= *i) ? *i - rbuf->f + 1 : *i + rbuf->m - rbuf->f + 1; + if ( ++(*i) >= rbuf->m ) *i = 0; + if ( n < rbuf->n ) return 1; + *i = rbuf->f; + return 0; +} +/** + * rbuf_prev() - get index of the previous element in the round buffer + * @rbuf: the rbuf_t holder + * @i: pointer to the last rbuf index. Set to -1 before the first call. + * + * Sets i to the previous position in the buffer. The return value indicates if + * the position points to a valid element (1) or if there are no more elements + * before *i (0). + */ +static inline int rbuf_prev(rbuf_t *rbuf, int *i) +{ + if ( !rbuf->n || *i==rbuf->f ) return 0; + if ( *i==-1 ) + { + *i = rbuf_last(rbuf); + return 1; + } + if ( --(*i) < 0 ) *i = rbuf->m - 1; + return 1; +} +/** + * rbuf_prepend() - register new element at the start of the round buffer + * @rbuf: the rbuf_t holder + * + * Returns index of the newly inserted element. + */ +static inline int rbuf_prepend(rbuf_t *rbuf) +{ + if ( rbuf->n < rbuf->m ) rbuf->n++; + + rbuf->f = rbuf->f > 0 ? rbuf->f - 1 : rbuf->m - 1; + return rbuf->f; +} +/** + * rbuf_append() - register new element at the end of the round buffer + * @rbuf: the rbuf_t holder + * + * Returns index of the newly inserted element. + */ +static inline int rbuf_append(rbuf_t *rbuf) +{ + if ( rbuf->n < rbuf->m ) + { + rbuf->n++; + int i = rbuf->f + rbuf->n; + return i <= rbuf->m ? i - 1 : i - rbuf->m - 1; + } + + rbuf->f++; + if ( rbuf->f >= rbuf->m ) + { + rbuf->f = 0; + return rbuf->m - 1; + } + return rbuf->f - 1; +} +/** + * rbuf_shift() - removes first element from the buffer + * @rbuf: the rbuf_t holder + * + * Returns index of the removed element. + */ +static inline int rbuf_shift(rbuf_t *rbuf) +{ + if ( !rbuf->n ) return -1; + int ret = rbuf->f; + rbuf->f++; + if ( rbuf->f >= rbuf->m ) rbuf->f = 0; + rbuf->n--; + return ret; +} +/** + * rbuf_shift_n() - removes first n elements from the buffer + * @rbuf: the rbuf_t holder + * @n: number of elements to remove + */ +static inline void rbuf_shift_n(rbuf_t *rbuf, int n) +{ + if ( n >= rbuf->n ) + { + rbuf->n = rbuf->f = 0; + return; + } + rbuf->n -= n; + rbuf->f += n; + if ( rbuf->f >= rbuf->m ) rbuf->f -= rbuf->m; +} + +/** + * rbuf_expand0() - expand round buffer and set the newly allocated elements to 0 + * @rbuf: the rbuf holder + * @type_t: data type + * @n: requested number of elements + * @data: data array to be realloced + * + * Note: The new array is linearized and leaves the rbuf.f offset untouched, + * thus the size of the new buffer is determined by the current position. + */ +#define rbuf_expand0(rbuf,type_t,n,data) \ +{ \ + if ( n > (rbuf)->m ) \ + { \ + int m = n + (rbuf)->f; \ + m--, m|=m>>1, m|=m>>2, m|=m>>4, m|=m>>8, m|=m>>16, m++; /* kroundup32 */ \ + data = (type_t*) realloc(data, sizeof(type_t)*m); \ + type_t *ptr = data; \ + memset(ptr+(rbuf)->m,0,sizeof(type_t)*(m-(rbuf)->m)); \ + if ( (rbuf)->f ) \ + { \ + memcpy(ptr+(rbuf)->m,ptr,sizeof(type_t)*(rbuf)->f); \ + memset(ptr,0,sizeof(type_t)*(rbuf)->f); \ + } \ + (rbuf)->m = m; \ + } \ +} + +/** + * rbuf_remove_kth() - remove k-th rbuf element (0-based) and memmove the data block + * @rbuf: the rbuf holder + * @type_t: data type + * @k: k-th element to remove + * @data: data array to be modified + */ +#define rbuf_remove_kth(rbuf, type_t, kth, data) \ +{ \ + int k = rbuf_kth(rbuf, kth); \ + if ( k < (rbuf)->f ) /* shrink from back */ \ + { \ + int l = rbuf_kth(rbuf, -1); \ + if ( k < l ) \ + { \ + type_t tmp = (data)[k]; \ + memmove(data+k, data+k+1, (l - k)*sizeof(type_t)); \ + (data)[l] = tmp; \ + } \ + (rbuf)->n--; \ + } \ + else /* shrink from front */ \ + { \ + if ( k > (rbuf)->f ) \ + { \ + type_t tmp = (data)[k]; \ + memmove(&data[(rbuf)->f+1], &data[(rbuf)->f], (k - (rbuf)->f)*sizeof(type_t)); \ + (data)[(rbuf)->f] = tmp; \ + } \ + (rbuf)->f++; \ + (rbuf)->n--; \ + if ( (rbuf)->f == (rbuf)->m ) (rbuf)->f = 0; \ + } \ +} + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/tsv2vcf.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/tsv2vcf.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..83de6f3ebd4aa03d7ab730f48d9e007177109d82 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/tsv2vcf.c.pysam.c @@ -0,0 +1,137 @@ +#include "bcftools.pysam.h" + +/* tsv2vcf.c -- convert from whitespace-separated fields to VCF + + Copyright (C) 2014-2021 Genome Research Ltd. + + Author: Petr Danecek + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include +#include +#include "tsv2vcf.h" + +tsv_t *tsv_init(const char *str) +{ + tsv_t *tsv = (tsv_t *) calloc(1,sizeof(tsv_t)); + kstring_t tmp = {0,0,0}; + const char *ss = str, *se = ss; + tsv->ncols = 0; + while ( *ss ) + { + if ( *se && *se!=',' ) { se++; continue; } + tsv->ncols++; + tsv->cols = (tsv_col_t*) realloc(tsv->cols,sizeof(tsv_col_t)*tsv->ncols); + tsv->cols[tsv->ncols-1].name = NULL; + tsv->cols[tsv->ncols-1].setter = NULL; + tmp.l = 0; + kputsn(ss, se-ss, &tmp); + if ( strcasecmp("-",tmp.s) ) + tsv->cols[tsv->ncols-1].name = strdup(tmp.s); + if ( !*se ) break; + ss = ++se; + } + free(tmp.s); + return tsv; +} + +void tsv_destroy(tsv_t *tsv) +{ + int i; + for (i=0; incols; i++) free(tsv->cols[i].name); + free(tsv->cols); + free(tsv); +} + +int tsv_register(tsv_t *tsv, const char *id, tsv_setter_t setter, void *usr) +{ + int i; + for (i=0; incols; i++) + { + if ( !tsv->cols[i].name || strcasecmp(tsv->cols[i].name,id) ) continue; + tsv->cols[i].setter = setter; + tsv->cols[i].usr = usr; + return 0; + } + return -1; +} + +int tsv_parse(tsv_t *tsv, bcf1_t *rec, char *str) +{ + int status = 0; + tsv->icol = 0; + tsv->ss = tsv->se = str; + while ( *tsv->ss && tsv->icol < tsv->ncols ) + { + while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++; + if ( tsv->cols[tsv->icol].setter ) + { + int ret = tsv->cols[tsv->icol].setter(tsv,rec,tsv->cols[tsv->icol].usr); + if ( ret<0 ) return -1; + status++; + } + while ( *tsv->se && isspace(*tsv->se) ) tsv->se++; + tsv->ss = tsv->se; + tsv->icol++; + } + return status ? 0 : -1; +} + +int tsv_setter_chrom(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + char tmp = *tsv->se; + *tsv->se = 0; + rec->rid = bcf_hdr_name2id((bcf_hdr_t*)usr, tsv->ss); + *tsv->se = tmp; + return rec->rid==-1 ? -1 : 0; +} + +int tsv_setter_pos(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + char *endptr; + rec->pos = strtol(tsv->ss, &endptr, 10) - 1; + if ( tsv->ss==endptr ) return -1; + return 0; +} + +int tsv_setter_id(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + char tmp = *tsv->se; + *tsv->se = 0; + bcf_update_id((bcf_hdr_t*)usr, rec, tsv->ss); + *tsv->se = tmp; + return 0; +} + +int tsv_setter_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + bcf_hdr_t *hdr = (bcf_hdr_t*)usr; + char *sb = tsv->ss; + while ( *sb && !isspace(*sb) ) sb++; + if ( !*sb ) return -1; + char tmp = *sb; + *sb = ','; + bcf_update_alleles_str(hdr, rec, tsv->ss); + *sb = tmp; + return 0; +} + + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfconvert.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfconvert.c new file mode 100644 index 0000000000000000000000000000000000000000..76c4a325adba2143f0b59f0b0d123e4b2000c4e3 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfconvert.c @@ -0,0 +1,1791 @@ +/* vcfconvert.c -- convert between VCF/BCF and related formats. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "filter.h" +#include "convert.h" +#include "tsv2vcf.h" + +// Logic of the filters: include or exclude sites which match the filters? +#define FLT_INCLUDE 1 +#define FLT_EXCLUDE 2 + +typedef struct _args_t args_t; +struct _args_t +{ + faidx_t *ref; + filter_t *filter; + char *filter_str; + int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE + convert_t *convert; + bcf_srs_t *files; + bcf_hdr_t *header; + void (*convert_func)(struct _args_t *); + struct { + int total, skipped, hom_rr, het_ra, hom_aa, het_aa, missing, written; + } n; + kstring_t str; + int32_t *gts; + float *flt; + int rev_als, output_vcf_ids, hap2dip, gen_3N6; + int nsamples, *samples, sample_is_file, targets_is_file, regions_is_file, output_type; + int regions_overlap, targets_overlap; + char **argv, *sample_list, *targets_list, *regions_list, *tag, *columns; + char *outfname, *infname, *ref_fname, *sex_fname; + int argc, n_threads, record_cmd_line, keep_duplicates, clevel; + char *index_fn; + int write_index; + struct { + kstring_t ref,alt,refalt; + } tsv; +}; + +static void destroy_data(args_t *args) +{ + if ( args->ref ) fai_destroy(args->ref); + if ( args->convert) convert_destroy(args->convert); + if ( args->filter ) filter_destroy(args->filter); + free(args->samples); + if ( args->files ) bcf_sr_destroy(args->files); +} + +static void open_vcf(args_t *args, const char *format_str) +{ + args->files = bcf_sr_init(); + if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)!=0 ) + error("Could not initialize --threads %d\n", args->n_threads); + + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + if ( args->targets_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap); + if ( bcf_sr_set_targets(args->files, args->targets_list, args->targets_is_file, 0)<0 ) + error("Failed to read the targets: %s\n", args->targets_list); + } + if ( !bcf_sr_add_reader(args->files, args->infname) ) + error("Failed to open %s: %s\n", args->infname,bcf_sr_strerror(args->files->errnum)); + + args->header = args->files->readers[0].header; + + if ( args->filter_str ) + args->filter = filter_init(args->header, args->filter_str); + + int i, nsamples = 0, *samples = NULL; + if ( args->sample_list && strcmp("-",args->sample_list) ) + { + for (i=0; ifiles->nreaders; i++) + { + int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file); + if ( ret<0 ) error("Error parsing the sample list\n"); + else if ( ret>0 ) error("Sample name mismatch: sample #%d not found in the header\n", ret); + } + + if ( args->sample_list[0]!='^' ) + { + // the sample ordering may be different if not negated + int n; + char **smpls = hts_readlist(args->sample_list, args->sample_is_file, &n); + if ( !smpls ) error("Could not parse %s\n", args->sample_list); + if ( n!=bcf_hdr_nsamples(args->files->readers[0].header) ) + error("The number of samples does not match, perhaps some are present multiple times?\n"); + nsamples = bcf_hdr_nsamples(args->files->readers[0].header); + samples = (int*) malloc(sizeof(int)*nsamples); + for (i=0; ifiles->readers[0].header, BCF_DT_SAMPLE,smpls[i]); + free(smpls[i]); + } + free(smpls); + } + } + if ( format_str ) args->convert = convert_init(args->header, samples, nsamples, format_str); + free(samples); +} + +static int _set_ref_alt(args_t *args, bcf1_t *rec) +{ + args->tsv.refalt.l = 0; + kputs(args->tsv.ref.s, &args->tsv.refalt); + if ( strcmp(".",args->tsv.alt.s) && strcmp(args->tsv.ref.s,args->tsv.alt.s) ) + { + kputc(',', &args->tsv.refalt); + kputs(args->tsv.alt.s, &args->tsv.refalt); + } + bcf_update_alleles_str(args->header, rec, args->tsv.refalt.s); + args->tsv.ref.l = 0; + args->tsv.alt.l = 0; + args->tsv.refalt.l = 0; + return 0; +} +static int tsv_setter_ref(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.ref); + if ( args->tsv.alt.l ) return _set_ref_alt(args,rec); + return 0; +} +static int tsv_setter_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.alt); + if ( args->tsv.ref.l ) return _set_ref_alt(args,rec); + return 0; +} + +// Try to set CHROM:POS_REF_ALT[_END]. Return 0 on success, -1 on error +static int _set_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + + char tmp, *se = tsv->ss, *ss = tsv->ss; + while ( se < tsv->se && *se!=':' ) se++; + if ( *se!=':' ) return -1; + tmp = *se; *se = 0; + int rid = bcf_hdr_name2id(args->header,ss); + *se = tmp; + if ( rid<0 ) return -1; + + // POS + hts_pos_t pos = strtol(se+1,&ss,10); + if ( ss==se+1 ) return -1; + pos--; + + // REF,ALT + args->str.l = 0; + se = ++ss; + while ( se < tsv->se && *se!='_' ) se++; + if ( *se!='_' ) return -1; + kputsn(ss,se-ss,&args->str); + ss = ++se; + while ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) se++; + if ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) return -1; + kputc(',',&args->str); + kputsn(ss,se-ss,&args->str); + + // END - optional + if (*se && *se=='_') + { + long end = strtol(se+1,&ss,10); + if ( ss==se+1 ) return -1; + bcf_update_info_int32(args->header, rec, "END", &end, 1); + } + + rec->rid = rid; + rec->pos = pos; + bcf_update_alleles_str(args->header, rec, args->str.s); + + return 0; +} +static int tsv_setter_chrom_pos_ref_alt_or_chrom(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + int ret = _set_chrom_pos_ref_alt(tsv,rec,usr); + if ( !ret ) return ret; + return tsv_setter_chrom(tsv,rec,args->header); +} +static int tsv_setter_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + int ret = _set_chrom_pos_ref_alt(tsv,rec,usr); + if ( ret!=0 ) error("Could not parse the CHROM:POS_REF_ALT[_END] string: %s\n", tsv->ss); + return ret; +} +// This function must be called first, then tsv_setter_chrom_pos_ref_alt_id_or_die. +// One of them is expected to find the CHROM:POS_REF_ALT[_END] string, if not, die. +static int tsv_setter_chrom_pos_ref_alt_or_id(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + if ( _set_chrom_pos_ref_alt(tsv,rec,usr)==0 ) return 0; + rec->pos = -1; // mark the record as unset + if ( !args->output_vcf_ids) return 0; + return tsv_setter_id(tsv,rec,usr); +} +static int tsv_setter_chrom_pos_ref_alt_id_or_die(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + if ( rec->pos!=-1 ) + { + if ( !args->output_vcf_ids ) return 0; + return tsv_setter_id(tsv,rec,usr); + } + return tsv_setter_chrom_pos_ref_alt(tsv,rec,usr); +} +static int tsv_setter_verify_pos(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + char *se; + int pos = strtol(tsv->ss,&se,10); + if ( tsv->ss==se ) error("Could not parse POS: %s\n", tsv->ss); + if ( rec->pos != pos-1 ) error("POS mismatch: %s\n", tsv->ss); + return 0; +} +static int tsv_setter_verify_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + args->rev_als = 0; + char tmp = *tsv->se; *tsv->se = 0; + if ( strcmp(tsv->ss,rec->d.allele[0]) ) + { + if ( strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); } + args->rev_als = 1; + } + *tsv->se = tmp; + while ( *tsv->se && isspace(*tsv->se) ) tsv->se++; + tsv->ss = tsv->se; + while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++; + tmp = *tsv->se; *tsv->se = 0; + 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]); } + 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]); } + *tsv->se = tmp; + return 0; +} +static int tsv_setter_gt_gp(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + int i, nsamples = bcf_hdr_nsamples(args->header); + for (i=0; iss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse first value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + ab = strtod(tsv->ss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse second value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + bb = strtod(tsv->ss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse third value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + + if ( args->rev_als ) { float tmp = bb; bb = aa; aa = tmp; } + args->flt[3*i+0] = aa; + args->flt[3*i+1] = ab; + args->flt[3*i+2] = bb; + + if ( aa >= ab ) + { + if ( aa >= bb ) args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(0); + else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1); + } + else if ( ab >= bb ) + { + args->gts[2*i+0] = bcf_gt_unphased(0); + args->gts[2*i+1] = bcf_gt_unphased(1); + } + else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1); + } + if ( *tsv->se ) error("Could not parse: %s\n", tsv->ss); + if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n"); + if ( bcf_update_format_float(args->header,rec,"GP",args->flt,nsamples*3) ) error("Could not update GP field\n"); + return 0; +} +static int tsv_setter_haps(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + int i, nsamples = bcf_hdr_nsamples(args->header); + + int32_t a0, a1; + if ( args->rev_als ) { a0 = bcf_gt_phased(1); a1 = bcf_gt_phased(0); } + else { a0 = bcf_gt_phased(0); a1 = bcf_gt_phased(1); } + + // up is short for "unphased" + int nup = 0; + for (i=0; iss + 4*i + nup; + int up = 0, all; + + for (all=0; all < 2; all++){ + // checking for premature ending + if ( !ss[0] || !ss[1] || !ss[2] || + (up && (!ss[3] || !ss[4]) ) ) + { + fprintf(stderr,"Wrong number of fields at %d-th sample ([%c][%c][%c]). ",i+1,ss[0],ss[1],ss[2]); + return -1; + } + + switch(ss[all*2+up]){ + case '0': + args->gts[2*i+all] = a0; + break; + case '1' : + args->gts[2*i+all] = a1; + break; + case '?' : + // there is no macro to express phased missing allele + args->gts[2*i+all] = bcf_gt_phased(-1); + break; + case '-' : + args->gts[2*i+all] = bcf_int32_vector_end; + break; + default : + fprintf(stderr,"Could not parse: [%c][%s]\n", ss[all*2+up],tsv->ss); + return -1; + } + if( ss[all*2+up+1]=='*' ) up = up + 1; + } + + if(up && up != 2) + { + fprintf(stderr,"Missing unphased marker '*': [%c][%s]", ss[2+up], tsv->ss); + return -1; + } + + // change alleles to unphased if the alleles are unphased + if ( up ) + { + args->gts[2*i] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i])); + args->gts[2*i+1] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i+1])); + } + nup = nup + up; + } + if ( tsv->ss[(nsamples-1)*4+3+nup] ) + { + fprintf(stderr,"nup: %d", nup); + fprintf(stderr,"Wrong number of fields (%d-th column = [%c]). ", nsamples*2,tsv->ss[(nsamples-1)*4+nup]); + return -1; + } + + if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n"); + return 0; +} +static void gensample_to_vcf(args_t *args) +{ + /* + * Inpute: IMPUTE2 output (indentation changed here for clarity): + * + * 20:62116619_C_T 20:62116619 62116619 C T 0.969 0.031 0 ... + * --- 20:62116698_C_A 62116698 C A 1 0 0 ... + * + * Second column is expected in the form of CHROM:POS_REF_ALT. We use second + * column because the first can be empty ("--") when filling sites from reference + * panel. When the option --vcf-ids is given, the first column is used to set the + * VCF ID. + * + * Output: VCF with filled GT,GP + * + */ + kstring_t line = {0,0,0}; + + char *gen_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.gen.gz", args->infname); + gen_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + } + else + { + *sample_fname = 0; + gen_fname = strdup(args->infname); + sample_fname = strdup(sample_fname+1); + } + htsFile *gen_fh = hts_open(gen_fname, "r"); + if ( !gen_fh ) error("Could not read: %s\n", gen_fname); + if ( hts_getline(gen_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", gen_fname); + + // Find out the chromosome name, depending on the format variant (--3N6 or plain) and the ordering + // of the columns (CHROM:POS_REF_ALT comes first or second) + args->str.l = 0; + char *sb = line.s, *se = line.s; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + if ( args->gen_3N6 ) // first column, just CHROM + kputsn(sb, se-sb, &args->str); + else // first or second column, part of CHROM:POS_REF_ALT + { + char *sc = strchr(sb,':'); + if ( !sc || sc > se ) + { + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + sb = ++se; + sc = strchr(sb,':'); + if ( !sc ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + } + kputsn(sb, sc-sb, &args->str); + } + + // Initialize and print the VCF header, args->str.s contains the chr name + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + tsv_t *tsv; + if ( args->gen_3N6 ) + { + tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP"); + tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header); + } + else + tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP"); + tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt_or_id, args); + tsv_register(tsv, "ID", tsv_setter_chrom_pos_ref_alt_id_or_die, args); + tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_register(tsv, "GT_GP", tsv_setter_gt_gp, args); + + // Find out sample names + int i, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nsamples); + if ( !samples ) error("Could not read %s\n", sample_fname); + for (i=2; iheader,samples[i]); + } + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname); + 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); + bcf1_t *rec = bcf_init(); + + nsamples -= 2; + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + args->flt = (float *) malloc(sizeof(float)*nsamples*3); + + do + { + bcf_clear(rec); + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + else + error("Error occurred while parsing: %s\n", line.s); + } + while ( hts_getline(gen_fh, KS_SEP_LINE, &line)>0 ); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(gen_fh) ) error("Close failed: %s\n", gen_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(gen_fname); + free(args->str.s); + free(line.s); + free(args->gts); + free(args->flt); + tsv_destroy(tsv); + + fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +static void haplegendsample_to_vcf(args_t *args) +{ + /* + * Convert from IMPUTE2 hap/legend/sample output files to VCF + * + * hap: + * 0 1 0 1 + * legend: + * id position a0 a1 + * 1:186946386_G_T 186946386 G T + * sample: + * sample population group sex + * sample1 sample1 sample1 2 + * sample2 sample2 sample2 2 + * + * Output: VCF with filled GT + */ + kstring_t line = {0,0,0}; + + if ( args->output_vcf_ids ) + error( + "The option --haplegendsample2vcf cannot be combined with --vcf-ids. This is because the\n" + "ID column must be formatted as \"CHROM:POS_REF_ALT\" to check sanity of the operation\n"); + + char *hap_fname = NULL, *leg_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.hap.gz", args->infname); + hap_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.legend.gz", args->infname); + leg_fname = strdup(args->str.s); + } + else + { + char *ss = sample_fname, *se = strchr(ss+1,','); + if ( !se ) error("Could not parse hap/legend/sample file names: %s\n", args->infname); + *ss = 0; + *se = 0; + hap_fname = strdup(args->infname); + leg_fname = strdup(ss+1); + sample_fname = strdup(se+1); + } + htsFile *hap_fh = hts_open(hap_fname, "r"); + if ( !hap_fh ) error("Could not read: %s\n", hap_fname); + + htsFile *leg_fh = hts_open(leg_fname,"r"); + if ( !leg_fh ) error("Could not read: %s\n", leg_fname); + + // Eat up first legend line, then determine chromosome name + if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname); + if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname); + + // Find out the chromosome name, sample names, init and print the VCF header + args->str.l = 0; + char *se = strchr(line.s,':'); + if ( !se ) error("Expected CHROM:POS_REF_ALT in first column of %s\n", leg_fname); + kputsn(line.s, se-line.s, &args->str); + + tsv_t *leg_tsv = tsv_init("CHROM_POS_REF_ALT,POS,REF_ALT"); + tsv_register(leg_tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args); + tsv_register(leg_tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(leg_tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_t *hap_tsv = tsv_init("HAPS"); + tsv_register(hap_tsv, "HAPS", tsv_setter_haps, args); + + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + int i, nrows, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nrows); + if ( !samples ) error("Could not read %s\n", sample_fname); + nsamples = nrows - 1; + + // sample_fname should contain a header line, so need to ignore first row + // returned from hts_readlist (i=1, and not i=0) + for (i=1; iheader,samples[i]); + } + bcf_hdr_add_sample(args->header,NULL); + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname); + 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); + bcf1_t *rec = bcf_init(); + + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + + while (1) + { + bcf_clear(rec); + args->n.total++; + if ( tsv_parse(leg_tsv, rec, line.s) ) + error("Error occurred while parsing %s: %s\n", leg_fname,line.s); + + if ( hts_getline(hap_fh, KS_SEP_LINE, &line)<=0 ) + error("Different number of records in %s and %s?\n", leg_fname,hap_fname); + + if ( tsv_parse(hap_tsv, rec, line.s) ) + error("Error occurred while parsing %s: %s\n", hap_fname,line.s); + + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + + if ( hts_getline(leg_fh, KS_SEP_LINE, &line)<=0 ) + { + if ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 ) + error("Different number of records in %s and %s?\n", leg_fname,hap_fname); + break; + } + } + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname); + if ( hts_close(leg_fh) ) error("Close failed: %s\n", leg_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(hap_fname); + free(leg_fname); + free(args->str.s); + free(line.s); + free(args->gts); + tsv_destroy(hap_tsv); + tsv_destroy(leg_tsv); + + fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +static void hapsample_to_vcf(args_t *args) +{ + /* + * Input: SHAPEIT output + * + * 20:19995888_A_G rsid1 19995888 A G 0 0 0 0 ... + * 20 20:19995888_A_G 19995888 A G 0 0 0 0 ... + * + * First column is expected in the form of CHROM:POS_REF_ALT + * + * Output: VCF with filled GT + * + */ + kstring_t line = {0,0,0}; + + char *hap_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.hap.gz", args->infname); + hap_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + } + else + { + *sample_fname = 0; + hap_fname = strdup(args->infname); + sample_fname = strdup(sample_fname+1); + } + htsFile *hap_fh = hts_open(hap_fname, "r"); + if ( !hap_fh ) error("Could not read: %s\n", hap_fname); + if ( hts_getline(hap_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", hap_fname); + + // Find out the chromosome name, it can be either in the first or second column + args->str.l = 0; + char *sb = line.s, *se = line.s; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + if ( !args->output_vcf_ids ) + { + // first column should be just CHROM, but the second must be CHROM:POS_REF_ALT, use that + sb = ++se; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + if ( !strchr(sb,':') ) + error("Could not determine CHROM in the second column of %s: %s\n", hap_fname,line.s); + } + // Parse CHROM:POS_REF_ALT + char *sc = strchr(sb,':'); + if ( !sc || sc > se ) + error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + kputsn(sb, sc-sb, &args->str); + + // Initialize and print the VCF header, args->str.s contains the chr name + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + tsv_t *tsv; + if ( args->output_vcf_ids ) + { + tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,HAPS"); + tsv_register(tsv, "ID", tsv_setter_id, args); + } + else + { + tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,POS,REF_ALT,HAPS"); + tsv_register(tsv, "CHROM", tsv_setter_chrom_pos_ref_alt_or_chrom, args); + } + tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args); + tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_register(tsv, "HAPS", tsv_setter_haps, args); + + int i, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nsamples); + if ( !samples ) error("Could not read %s\n", sample_fname); + for (i=2; iheader,samples[i]); + } + bcf_hdr_add_sample(args->header,NULL); + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + 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); + bcf1_t *rec = bcf_init(); + + nsamples -= 2; + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + + do + { + bcf_clear(rec); + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + else + error("Error occurred while parsing: %s\n", line.s); + } + while ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 ); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(hap_fname); + free(args->str.s); + free(line.s); + free(args->gts); + tsv_destroy(tsv); + + fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +char *init_sample2sex(bcf_hdr_t *hdr, char *sex_fname) +{ + int i, nlines; + char *sample2sex = (char*) calloc(bcf_hdr_nsamples(hdr),1); + char **lines = hts_readlist(sex_fname, 1, &nlines); + if ( !lines ) error("Could not read %s\n", sex_fname); + for (i=0; igen_3N6 ) + kputs("%CHROM ", &str); + + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str); + + // insert rsid as second column if needed + if ( args->output_vcf_ids ) + kputs("%ID ", &str); + else + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str); + + kputs("%POS %REF %FIRST_ALT", &str); + if ( !args->tag || !strcmp(args->tag,"GT") ) kputs("%_GT_TO_PROB3",&str); + else if ( !strcmp(args->tag,"PL") ) kputs("%_PL_TO_PROB3",&str); + else if ( !strcmp(args->tag,"GP") ) kputs("%_GP_TO_PROB3",&str); + else error("todo: --tag %s\n", args->tag); + kputs("\n", &str); + open_vcf(args,str.s); + + int ret, gen_compressed = 1, sample_compressed = 0; + char *gen_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".gen.gz",&str); + gen_fname = strdup(str.s); + } + else if ( n_files==2 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) gen_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]); + } + else + { + error("Error parsing --gensample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (gen_fname) fprintf(stderr, "Gen file: %s\n", gen_fname); + if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + if ( sample2sex ) + ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]); + else + ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!gen_fname) { + if ( str.m ) free(str.s); + return; + } + + int prev_rid = -1, prev_pos = -1; + int no_alt = 0, non_biallelic = 0, filtered = 0, ndup = 0, nok = 0; + BGZF *gout = bgzf_open(gen_fname, gen_compressed ? "wg" : "wu"); + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + // skip duplicate lines, or otherwise shapeit complains + if ( !args->keep_duplicates && prev_rid==line->rid && prev_pos==line->pos ) { ndup++; continue; } + prev_rid = line->rid; + prev_pos = line->pos; + + str.l = 0; + convert_line(args->convert, line, &str); + if ( str.l ) + { + int ret = bgzf_write(gout, str.s, str.l); + if ( ret!= str.l ) error("Error writing %s: %s\n", gen_fname,strerror(errno)); + nok++; + } + } + fprintf(stderr, "%d records written, %d skipped: %d/%d/%d/%d no-ALT/non-biallelic/filtered/duplicated\n", + nok, no_alt+non_biallelic+filtered+ndup, no_alt, non_biallelic, filtered, ndup); + + if ( str.m ) free(str.s); + if ( bgzf_close(gout)!=0 ) error("Error closing %s: %s\n", gen_fname,strerror(errno)); + free(gen_fname); +} + +static void vcf_to_haplegendsample(args_t *args) +{ + kstring_t str = {0,0,0}; + if ( args->hap2dip ) + kputs("%_GT_TO_HAP2\n", &str); + else + kputs("%_GT_TO_HAP\n", &str); + open_vcf(args,str.s); + + int ret, hap_compressed = 1, legend_compressed = 1, sample_compressed = 0; + char *hap_fname = NULL, *legend_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".legend.gz",&str); + legend_fname = strdup(str.s); + str.l = l; + kputs(".hap.gz",&str); + hap_fname = strdup(str.s); + } + else if ( n_files==3 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) legend_fname = strdup(files[1]); + if (strlen(files[2]) && strcmp(files[2],".")!=0) sample_fname = strdup(files[2]); + } + else + { + error("Error parsing --hapslegendsample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname); + if (legend_fname) fprintf(stderr, "Legend file: %s\n", legend_fname); + if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs("sample population group sex\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + ksprintf(&str, "%s %s %s %c\n", args->header->samples[i], args->header->samples[i], args->header->samples[i], sample2sex ? sample2sex[i] : '2'); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!hap_fname && !legend_fname) { + if ( str.m ) free(str.s); + return; + } + + // open haps and legend outputs + BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL; + if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize); + BGZF *lout = legend_fname ? bgzf_open(legend_fname, legend_compressed ? "wg" : "wu") : NULL; + if (legend_fname) { + str.l = 0; + kputs("id position a0 a1\n", &str); + ret = bgzf_write(lout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno)); + } + + int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0; + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + str.l = 0; + convert_line(args->convert, line, &str); + if ( !str.l ) continue; + + // write haps file + if (hap_fname) { + ret = bgzf_write(hout, str.s, str.l); // write hap file + if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno)); + } + if (legend_fname) { + str.l = 0; + if ( args->output_vcf_ids && (line->d.id[0]!='.' || line->d.id[1]!=0) ) + ksprintf(&str, "%s %"PRId64" %s %s\n", line->d.id, (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]); + else + 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]); + + // write legend file + ret = bgzf_write(lout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno)); + } + nok++; + } + 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); + if ( str.m ) free(str.s); + if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno)); + if ( lout && bgzf_close(lout)!=0 ) error("Error closing %s: %s\n", legend_fname, strerror(errno)); + if (hap_fname) free(hap_fname); + if (legend_fname) free(legend_fname); +} + +static void vcf_to_hapsample(args_t *args) +{ + /* + * WTCCC style haplotypes file + * see https://mathgen.stats.ox.ac.uk/genetics_software/shapeit/shapeit.html#hapsample + * + * These are essentially the haplotypes from the impute2 format with some + * legend info tacked on to the first 5 columns + * + */ + kstring_t str = {0,0,0}; + + // print ID instead of CHROM:POS_REF_ALT1 + if ( args->output_vcf_ids ) + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT %ID %POS %REF %FIRST_ALT ", &str); + else + kputs("%CHROM %CHROM:%POS\\_%REF\\_%FIRST_ALT %POS %REF %FIRST_ALT ", &str); + + if ( args->hap2dip ) + kputs("%_GT_TO_HAP2\n", &str); + else + kputs("%_GT_TO_HAP\n", &str); + open_vcf(args,str.s); + + int ret, hap_compressed = 1, sample_compressed = 0; + char *hap_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".hap.gz",&str); + hap_fname = strdup(str.s); + } + else if ( n_files==2 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]); + } + else + { + error("Error parsing --hapsample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname); + if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + if ( sample2sex ) + ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]); + else + ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!hap_fname) { + if ( str.m ) free(str.s); + return; + } + + // open haps output + BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL; + if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize); + + int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0; + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + str.l = 0; + convert_line(args->convert, line, &str); + if ( !str.l ) continue; + + // write haps file + if (hap_fname) { + ret = bgzf_write(hout, str.s, str.l); // write hap file + if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno)); + } + nok++; + } + 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); + if ( str.m ) free(str.s); + if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno)); + if (hap_fname) free(hap_fname); +} + +static void bcf_hdr_set_chrs(bcf_hdr_t *hdr, faidx_t *fai) +{ + int i, n = faidx_nseq(fai); + for (i=0; i", seq,len); + } +} +static inline int acgt_to_5(char base) +{ + if ( base=='A' ) return 0; + if ( base=='C' ) return 1; + if ( base=='G' ) return 2; + if ( base=='T' ) return 3; + return 4; +} +static inline int tsv_setter_aa1(args_t *args, char *ss, char *se, int alleles[], int *nals, int ref, int32_t *gts) +{ + if ( se - ss > 2 ) return -1; // currently only SNPs + + if ( ss[0]=='-' || ss[0]=='.' ) + { + // missing GT + gts[0] = bcf_gt_missing; + gts[1] = bcf_gt_missing; + args->n.missing++; + return 0; + } + if ( ss[0]=='I' ) return -2; // skip insertions/deletions for now + if ( ss[0]=='D' ) return -2; + + int a0 = acgt_to_5(toupper(ss[0])); + int a1 = ss[1] ? acgt_to_5(toupper(ss[1])) : a0; + if ( alleles[a0]<0 ) alleles[a0] = (*nals)++; + if ( alleles[a1]<0 ) alleles[a1] = (*nals)++; + + gts[0] = bcf_gt_unphased(alleles[a0]); + gts[1] = ss[1] ? bcf_gt_unphased(alleles[a1]) : bcf_int32_vector_end; + + if ( ref==a0 && ref==a1 ) args->n.hom_rr++; // hom ref: RR + else if ( ref==a0 ) args->n.het_ra++; // het: RA + else if ( ref==a1 ) args->n.het_ra++; // het: AR + else if ( a0==a1 ) args->n.hom_aa++; // hom-alt: AA + else args->n.het_aa++; // non-ref het: AA + + return 0; +} +static int tsv_setter_aa(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + + int len; + char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(args->header,rec->rid), rec->pos, rec->pos, &len); + if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1); + + int nals = 1, alleles[5] = { -1, -1, -1, -1, -1 }; // a,c,g,t,n + ref[0] = toupper(ref[0]); + int iref = acgt_to_5(ref[0]); + alleles[iref] = 0; + + rec->n_sample = bcf_hdr_nsamples(args->header); + + int i, ret; + for (i=0; in_sample; i++) + { + if ( i>0 ) + { + ret = tsv_next(tsv); + 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); + } + ret = tsv_setter_aa1(args, tsv->ss, tsv->se, alleles, &nals, iref, args->gts+i*2); + 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); + if ( ret==-2 ) + { + // something else than a SNP + free(ref); + return -1; + } + } + + args->str.l = 0; + kputc(ref[0], &args->str); + for (i=0; i<5; i++) + { + if ( alleles[i]>0 ) + { + kputc(',', &args->str); + kputc("ACGTN"[i], &args->str); + } + } + bcf_update_alleles_str(args->header, rec, args->str.s); + if ( bcf_update_genotypes(args->header,rec,args->gts,rec->n_sample*2) ) error("Could not update the GT field\n"); + + free(ref); + return 0; +} + +static void tsv_to_vcf(args_t *args) +{ + if ( !args->ref_fname ) error("--tsv2vcf requires the --fasta-ref option\n"); + + args->ref = fai_load(args->ref_fname); + if ( !args->ref ) error("Could not load the reference %s\n", args->ref_fname); + + args->header = bcf_hdr_init("w"); + bcf_hdr_set_chrs(args->header, args->ref); + bcf_hdr_append(args->header, "##FORMAT="); + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + int i, nsmpl; + char **smpl; + if ( args->sample_list ) + { + smpl = hts_readlist(args->sample_list, args->sample_is_file, &nsmpl); + if ( !smpl ) error("Could not parse %s\n", args->sample_list); + for (i=0; iheader, smpl[i]); + free(smpl[i]); + } + free(smpl); + bcf_hdr_add_sample(args->header, NULL); + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsmpl*2); + } + + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + 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); + + tsv_t *tsv = tsv_init(args->columns ? args->columns : "ID,CHROM,POS,AA"); + if ( tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header) < 0 ) error("Expected CHROM column\n"); + if ( tsv_register(tsv, "POS", tsv_setter_pos, NULL) < 0 ) error("Expected POS column\n"); + if ( tsv_register(tsv, "ID", tsv_setter_id, args->header) < 0 && !args->columns ) error("Expected ID column\n"); + if ( tsv_register(tsv, "AA", tsv_setter_aa, args) < 0 ) + { + if ( args->sample_list ) error("Expected AA column with -s/-S\n"); + if ( tsv_register(tsv, "REF", tsv_setter_ref, args) < 0 || tsv_register(tsv, "ALT", tsv_setter_alt, args) < 0 ) + error("Expected REF and ALT columns when AA was not given\n"); + } + + bcf1_t *rec = bcf_init(); + bcf_float_set_missing(rec->qual); + + kstring_t line = {0,0,0}; + htsFile *in_fh = hts_open(args->infname, "r"); + if ( !in_fh ) error("Could not read: %s\n", args->infname); + while ( hts_getline(in_fh, KS_SEP_LINE, &line) > 0 ) + { + if ( line.s[0]=='#' ) continue; // skip comments + bcf_clear(rec); + + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + args->n.written++; + } + else + args->n.skipped++; + } + if ( hts_close(in_fh) ) error("Close failed: %s\n", args->infname); + free(line.s); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + bcf_hdr_destroy(args->header); + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); + tsv_destroy(tsv); + bcf_destroy(rec); + free(args->str.s); + free(args->gts); + free(args->tsv.ref.s); + free(args->tsv.alt.s); + free(args->tsv.refalt.s); + + fprintf(stderr,"Rows total: \t%d\n", args->n.total); + fprintf(stderr,"Rows skipped: \t%d\n", args->n.skipped); + fprintf(stderr,"Sites written: \t%d\n", args->n.written); + if ( args->sample_list ) + { + fprintf(stderr,"Missing GTs: \t%d\n", args->n.missing); + fprintf(stderr,"Hom RR: \t%d\n", args->n.hom_rr); + fprintf(stderr,"Het RA: \t%d\n", args->n.het_ra); + fprintf(stderr,"Hom AA: \t%d\n", args->n.hom_aa); + fprintf(stderr,"Het AA: \t%d\n", args->n.het_aa); + } +} + +static void vcf_to_vcf(args_t *args) +{ + open_vcf(args,NULL); + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0); + if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + 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); + + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) continue; + } + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); +} + +static void gvcf_to_vcf(args_t *args) +{ + if ( !args->ref_fname ) error("--gvcf2vcf requires the --fasta-ref option\n"); + + args->ref = fai_load(args->ref_fname); + if ( !args->ref ) error("Could not load the fai index for reference %s\n", args->ref_fname); + + open_vcf(args,NULL); + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0); + if (args->record_cmd_line) bcf_hdr_append_version(hdr, args->argc, args->argv, "bcftools_convert"); + if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + 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); + + int32_t *itmp = NULL, nitmp = 0; + + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) + { + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + } + + // check if alleles compatible with being a gVCF record + // ALT must be one of ., <*>, , + // check for INFO/END is below + int i, gallele = -1; + if (line->n_allele==1) + gallele = 0; // illumina/bcftools-call gvcf (if INFO/END present) + else if ( line->d.allele[1][0]=='<' ) + { + for (i=1; in_allele; i++) + { + if ( line->d.allele[i][1]=='*' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // mpileup/spec compliant gVCF + if ( line->d.allele[i][1]=='X' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // old mpileup gVCF + if ( strcmp(line->d.allele[i],"")==0 ) { gallele = i; break; } // GATK gVCF + } + } + + // no gVCF compatible alleles + if (gallele<0) + { + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + + int nend = bcf_get_info_int32(hdr,line,"END",&itmp,&nitmp); + if ( nend!=1 ) + { + // No INFO/END => not gVCF record + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + bcf_update_info_int32(hdr,line,"END",NULL,0); + int pos, len; + for (pos=line->pos; pospos = pos; + char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(hdr,line->rid), line->pos, line->pos, &len); + if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(hdr,line->rid),(int64_t) line->pos+1); + strncpy(line->d.allele[0],ref,len); + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + free(ref); + } + } + free(itmp); + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); +} + +static void usage(void) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: Converts VCF/BCF to other formats and back. See man page for file\n"); + fprintf(stderr, " formats details. When specifying output files explicitly instead\n"); + fprintf(stderr, " of with PREFIX, one can use '-' for stdout and '.' to suppress.\n"); + fprintf(stderr, "Usage: bcftools convert [OPTIONS] INPUT_FILE\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "VCF input options:\n"); + fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n"); + fprintf(stderr, " -i, --include EXPR Select sites for which the expression is true\n"); + fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(stderr, " -s, --samples LIST List of samples to include\n"); + fprintf(stderr, " -S, --samples-file FILE File of samples to include\n"); + fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "VCF output options:\n"); + fprintf(stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(stderr, " -o, --output FILE Output file name [stdout]\n"); + 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"); + fprintf(stderr, " --threads INT Use multithreading with INT worker threads [0]\n"); + fprintf(stderr, " --write-index Automatically index the output files [off]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "GEN/SAMPLE conversion (input/output from IMPUTE2):\n"); + fprintf(stderr, " -G, --gensample2vcf ... |,\n"); + fprintf(stderr, " -g, --gensample ... |,\n"); + fprintf(stderr, " --3N6 Use 3*N+6 column format instead of the old 3*N+5 column format\n"); + fprintf(stderr, " --tag STRING Tag to take values for .gen file: GT,PL,GL,GP [GT]\n"); + fprintf(stderr, " --chrom Output chromosome in first column instead of CHROM:POS_REF_ALT\n"); + fprintf(stderr, " --keep-duplicates Keep duplicate positions\n"); + fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(stderr, " --vcf-ids Output VCF IDs in second column instead of CHROM:POS_REF_ALT\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "gVCF conversion:\n"); + fprintf(stderr, " --gvcf2vcf Expand gVCF reference blocks\n"); + fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "HAP/SAMPLE conversion (output from SHAPEIT):\n"); + fprintf(stderr, " --hapsample2vcf ... |,\n"); + fprintf(stderr, " --hapsample ... |,\n"); + fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n"); + fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "HAP/LEGEND/SAMPLE conversion:\n"); + fprintf(stderr, " -H, --haplegendsample2vcf ... |,,\n"); + fprintf(stderr, " -h, --haplegendsample ... |,,\n"); + fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n"); + fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "TSV conversion:\n"); + fprintf(stderr, " --tsv2vcf FILE\n"); + fprintf(stderr, " -c, --columns STRING Columns of the input tsv file, see man page for details [ID,CHROM,POS,AA]\n"); + fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n"); + fprintf(stderr, " -s, --samples LIST List of sample names\n"); + fprintf(stderr, " -S, --samples-file FILE File of sample names\n"); + fprintf(stderr, "\n"); + // fprintf(stderr, "PLINK options:\n"); + // fprintf(stderr, " -p, --plink |,,|,,|,\n"); + // fprintf(stderr, " --tped make tped file instead\n"); + // fprintf(stderr, " --bin make binary bed/fam/bim files\n"); + // fprintf(stderr, "\n"); + // fprintf(stderr, "PBWT options:\n"); + // fprintf(stderr, " -b, --pbwt or ,,,\n"); + // fprintf(stderr, "\n"); + exit(1); +} + +int main_vcfconvert(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->outfname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->regions_overlap = 1; + args->targets_overlap = 0; + args->clevel = -1; + + static struct option loptions[] = + { + {"include",required_argument,NULL,'i'}, + {"exclude",required_argument,NULL,'e'}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,13}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"targets-overlap",required_argument,NULL,14}, + {"samples",required_argument,NULL,'s'}, + {"samples-file",required_argument,NULL,'S'}, + {"sex",required_argument,NULL,11}, + {"gensample",required_argument,NULL,'g'}, + {"gensample2vcf",required_argument,NULL,'G'}, + {"tag",required_argument,NULL,1}, + {"chrom",no_argument,NULL,8}, + {"3N6",no_argument,NULL,15}, + {"tsv2vcf",required_argument,NULL,2}, + {"hapsample",required_argument,NULL,7}, + {"hapsample2vcf",required_argument,NULL,3}, + {"vcf-ids",no_argument,NULL,4}, + {"haploid2diploid",no_argument,NULL,5}, + {"gvcf2vcf",no_argument,NULL,6}, + {"haplegendsample",required_argument,NULL,'h'}, + {"haplegendsample2vcf",required_argument,NULL,'H'}, + {"columns",required_argument,NULL,'c'}, + {"fasta-ref",required_argument,NULL,'f'}, + {"no-version",no_argument,NULL,10}, + {"keep-duplicates",no_argument,NULL,12}, + {"write-index",no_argument,NULL,16}, + {NULL,0,NULL,0} + }; + char *tmp; + 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) { + switch (c) { + case 'e': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break; + case 'i': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; args->regions_is_file = 1; break; + case 't': args->targets_list = optarg; break; + case 'T': args->targets_list = optarg; args->targets_is_file = 1; break; + case 's': args->sample_list = optarg; break; + case 'S': args->sample_list = optarg; args->sample_is_file = 1; break; + case 'g': args->convert_func = vcf_to_gensample; args->outfname = optarg; break; + case 'G': args->convert_func = gensample_to_vcf; args->infname = optarg; break; + case 1 : args->tag = optarg; break; + case 2 : args->convert_func = tsv_to_vcf; args->infname = optarg; break; + case 3 : args->convert_func = hapsample_to_vcf; args->infname = optarg; break; + case 4 : args->output_vcf_ids = 1; break; + case 5 : args->hap2dip = 1; break; + case 6 : args->convert_func = gvcf_to_vcf; break; + case 7 : args->convert_func = vcf_to_hapsample; args->outfname = optarg; break; + case 8 : error("The --chrom option has been deprecated, please use --3N6 instead\n"); break; + case 15 : args->gen_3N6 = 1; break; + case 16 : args->write_index = 1; break; + case 'H': args->convert_func = haplegendsample_to_vcf; args->infname = optarg; break; + case 'f': args->ref_fname = optarg; break; + case 'c': args->columns = optarg; break; + case 'o': args->outfname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'h': args->convert_func = vcf_to_haplegendsample; args->outfname = optarg; break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 10 : args->record_cmd_line = 0; break; + case 11 : args->sex_fname = optarg; break; + case 12 : args->keep_duplicates = 1; break; + case 13 : + args->regions_overlap = parse_overlap_option(optarg); + if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 14 : + args->targets_overlap = parse_overlap_option(optarg); + if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case '?': usage(); break; + default: error("Unknown argument: %s\n", optarg); + } + } + + if ( !args->infname ) + { + if ( optind>=argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) args->infname = "-"; + } + else args->infname = argv[optind]; + } + if ( !args->infname ) usage(); + + if ( args->convert_func ) args->convert_func(args); + else vcf_to_vcf(args); + + destroy_data(args); + free(args); + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfgtcheck.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfgtcheck.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..54568b0544802098070c6c11532560f9fa537d4d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfgtcheck.c.pysam.c @@ -0,0 +1,1286 @@ +#include "bcftools.pysam.h" + +/* vcfgtcheck.c -- Check sample identity. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "extsort.h" +//#include "hclust.h" + +typedef struct +{ + int iqry, igt; +} +pair_t; + +typedef struct +{ + bcf_srs_t *files; // first reader is the query VCF - single sample normally or multi-sample for cross-check + bcf_hdr_t *gt_hdr, *qry_hdr; // VCF with genotypes to compare against and the query VCF + char *cwd, **argv, *gt_samples, *qry_samples, *regions, *targets, *qry_fname, *gt_fname, *pair_samples; + int argc, gt_samples_is_file, qry_samples_is_file, regions_is_file, targets_is_file, pair_samples_is_file; + int regions_overlap, targets_overlap; + int qry_use_GT,gt_use_GT, nqry_smpl,ngt_smpl, *qry_smpl,*gt_smpl; + int nused[2][2]; + double *pdiff, *qry_prob, *gt_prob; + uint32_t *ndiff,*ncnt,ncmp, npairs; + int32_t *qry_arr,*gt_arr, nqry_arr,ngt_arr; + uint8_t *qry_dsg, *gt_dsg; + pair_t *pairs; + double *hwe_prob, dsg2prob[8][3], pl2prob[256]; + double min_inter_err, max_intra_err; + int all_sites, hom_only, ntop, cross_check, calc_hwe_prob, sort_by_hwe, dry_run, use_PLs; + FILE *fp; + unsigned int nskip_no_match, nskip_not_ba, nskip_mono, nskip_no_data, nskip_dip_GT, nskip_dip_PL; + + // for --distinctive-sites + double distinctive_sites; + kbitset_t *kbs_diff; + size_t diff_sites_size; + extsort_t *es; + char *es_tmp_prefix, *es_max_mem; +} +args_t; + +static void set_cwd(args_t *args) +{ + int i; + char *buf; + size_t nbuf = 500; + args->cwd = (char*) malloc(sizeof(char)*nbuf); + for (i=0; i<5; i++) + { + if ( (buf = getcwd(args->cwd, nbuf)) ) break; + nbuf *= 2; + args->cwd = (char*) realloc(args->cwd, sizeof(char)*nbuf); + } + assert(buf); +} +static void print_header(args_t *args, FILE *fp) +{ + fprintf(fp, "# This file was produced by bcftools (%s+htslib-%s), the command line was:\n", bcftools_version(), hts_version()); + fprintf(fp, "# \t bcftools %s ", args->argv[0]); + int i; + for (i=1; iargc; i++) + fprintf(fp, " %s",args->argv[i]); + fprintf(fp, "\n# and the working directory was:\n"); + fprintf(fp, "# \t %s\n#\n", args->cwd); +} + +static int cmp_int(const void *_a, const void *_b) +{ + int a = *((int*)_a); + int b = *((int*)_b); + if ( a < b ) return -1; + if ( a > b ) return 1; + return 0; +} +static int cmp_pair(const void *_a, const void *_b) +{ + pair_t *a = (pair_t*)_a; + pair_t *b = (pair_t*)_b; + if ( a->iqry < b->iqry ) return -1; + if ( a->iqry > b->iqry ) return 1; + if ( a->igt < b->igt ) return -1; + if ( a->igt > b->igt ) return 1; + return 0; +} + +typedef struct +{ + uint32_t ndiff,rid,pos,rand; // rand is to shuffle sites with the same ndiff from across all chromosoms + unsigned long kbs_dat[1]; +} +diff_sites_t; +#if DBG +static void diff_sites_debug_print(args_t *args, diff_sites_t *ds) +{ + int i; + memcpy(args->kbs_diff->b,ds->kbs_dat,args->kbs_diff->n*sizeof(unsigned long)); + fprintf(bcftools_stderr,"%s:%d\t%d\t",bcf_hdr_id2name(args->qry_hdr,ds->rid),ds->pos+1,ds->ndiff); + for (i=0; inpairs; i++) fprintf(bcftools_stderr,"%d",kbs_exists(args->kbs_diff,i)?1:0); + fprintf(bcftools_stderr,"\n"); +} +#endif +static int diff_sites_cmp(const void *aptr, const void *bptr) +{ + diff_sites_t *a = *((diff_sites_t**)aptr); + diff_sites_t *b = *((diff_sites_t**)bptr); + if ( a->ndiff < b->ndiff ) return 1; // descending order + if ( a->ndiff > b->ndiff ) return -1; + if ( a->rand < b->rand ) return -1; + if ( a->rand > b->rand ) return 1; + return 0; +} +static void diff_sites_init(args_t *args) +{ + int nsites = args->distinctive_sites<=1 ? args->npairs*args->distinctive_sites : args->distinctive_sites; + if ( nsites<=0 ) error("The value for --distinctive-sites was set too low: %d\n",nsites); + if ( nsites > args->npairs ) + { + fprintf(bcftools_stderr,"Warning: The value for --distinctive-sites is bigger than is the number of pairs, all discordant sites be printed.\n"); + nsites = args->npairs; + args->distinctive_sites = args->npairs + 1; + } + else + args->distinctive_sites = nsites; + args->kbs_diff = kbs_init(args->npairs); + size_t n = (args->npairs + KBS_ELTBITS-1) / KBS_ELTBITS; + assert( n==args->kbs_diff->n ); + args->diff_sites_size = sizeof(diff_sites_t) + (n-1)*sizeof(unsigned long); + args->es = extsort_alloc(); + extsort_set_opt(args->es,size_t,DAT_SIZE,args->diff_sites_size); + extsort_set_opt(args->es,const char*,TMP_PREFIX,args->es_tmp_prefix); + extsort_set_opt(args->es,const char*,MAX_MEM,args->es_max_mem); + extsort_set_opt(args->es,extsort_cmp_f,FUNC_CMP,diff_sites_cmp); + extsort_init(args->es); +} +static void diff_sites_destroy(args_t *args) +{ + kbs_destroy(args->kbs_diff); + extsort_destroy(args->es); +} +static inline void diff_sites_reset(args_t *args) +{ + kbs_clear(args->kbs_diff); +} +static inline void diff_sites_push(args_t *args, int ndiff, int rid, int pos) +{ + diff_sites_t *dat = (diff_sites_t*) malloc(args->diff_sites_size); + memset(dat,0,sizeof(*dat)); // for debugging: prevent warnings about uninitialized memory coming from struct padding (not needed after rand added) + dat->ndiff = ndiff; + dat->rid = rid; + dat->pos = pos; + dat->rand = hts_lrand48(); + memcpy(dat->kbs_dat,args->kbs_diff->b,args->kbs_diff->n*sizeof(unsigned long)); + extsort_push(args->es,dat); +} +static inline int diff_sites_shift(args_t *args, int *ndiff, int *rid, int *pos) +{ + diff_sites_t *dat = (diff_sites_t*) extsort_shift(args->es); + if ( !dat ) return 0; + *ndiff = dat->ndiff; + *rid = dat->rid; + *pos = dat->pos; + memcpy(args->kbs_diff->b,dat->kbs_dat,args->kbs_diff->n*sizeof(unsigned long)); + return 1; +} + +static void init_samples(char *list, int list_is_file, int **smpl, int *nsmpl, bcf_hdr_t *hdr, char *vcf_fname) +{ + int i; + if ( !strcmp(list,"-") ) + { + *nsmpl = bcf_hdr_nsamples(hdr); + *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl)); + for (i=0; i<*nsmpl; i++) (*smpl)[i] = i; + return; + } + + char **tmp = hts_readlist(list, list_is_file, nsmpl); + if ( !tmp || !*nsmpl ) error("Failed to parse %s\n", list); + *smpl = (int*) malloc(sizeof(**smpl)*(*nsmpl)); + for (i=0; i<*nsmpl; i++) + { + int idx = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, tmp[i]); + if ( idx<0 ) error("No such sample in %s: [%s]\n",vcf_fname,tmp[i]); + (*smpl)[i] = idx; + free(tmp[i]); + } + free(tmp); + qsort(*smpl,*nsmpl,sizeof(**smpl),cmp_int); + // check for duplicates + for (i=1; i<*nsmpl; i++) + if ( (*smpl)[i-1]==(*smpl)[i] ) + error("Error: the sample \"%s\" is listed twice in %s\n", hdr->samples[(*smpl)[i]],list); +} + +static void init_data(args_t *args) +{ + hts_srand48(0); + + args->files = bcf_sr_init(); + if ( args->regions ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions, args->regions_is_file)<0 ) error("Failed to read the regions: %s\n", args->regions); + } + if ( args->targets ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap); + 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); + } + + if ( args->gt_fname ) bcf_sr_set_opt(args->files, BCF_SR_REQUIRE_IDX); + 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)); + if ( args->gt_fname && !bcf_sr_add_reader(args->files, args->gt_fname) ) + error("Failed to read from %s: %s\n", !strcmp("-",args->gt_fname)?"standard input":args->gt_fname,bcf_sr_strerror(args->files->errnum)); + + args->qry_hdr = bcf_sr_get_header(args->files,0); + if ( !bcf_hdr_nsamples(args->qry_hdr) ) error("No samples in %s?\n", args->qry_fname); + if ( args->gt_fname ) + { + args->gt_hdr = bcf_sr_get_header(args->files,1); + if ( !bcf_hdr_nsamples(args->gt_hdr) ) error("No samples in %s?\n", args->gt_fname); + } + + // Determine whether GT or PL will be used + if ( args->qry_use_GT==-1 ) // not set by -u, qry uses PL by default + { + if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")>=0 ) + args->qry_use_GT = 0; + else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")>=0 ) + args->qry_use_GT = 1; + else + error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->qry_fname); + } + else if ( args->qry_use_GT==1 ) + { + if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"GT")<0 ) + error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->qry_fname); + } + else if ( bcf_hdr_id2int(args->qry_hdr,BCF_DT_ID,"PL")<0 ) + error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->qry_fname); + + if ( args->gt_hdr ) + { + if ( args->gt_use_GT==-1 ) // not set by -u, gt uses GT by default + { + if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")>=0 ) + args->gt_use_GT = 1; + else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")>=0 ) + args->gt_use_GT = 0; + else + error("[E::%s] Neither PL nor GT tag is present in the header of %s\n", __func__, args->gt_fname); + } + else if ( args->gt_use_GT==1 ) + { + if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"GT")<0 ) + error("[E::%s] The GT tag is not present in the header of %s\n", __func__, args->gt_fname); + } + else if ( bcf_hdr_id2int(args->gt_hdr,BCF_DT_ID,"PL")<0 ) + error("[E::%s] The PL tag is not present in the header of %s\n", __func__, args->gt_fname); + } + else + args->gt_use_GT = args->qry_use_GT; + + // Prepare samples + int i,j; + args->nqry_smpl = bcf_hdr_nsamples(args->qry_hdr); + if ( args->qry_samples ) + { + init_samples(args->qry_samples, args->qry_samples_is_file, &args->qry_smpl, &args->nqry_smpl, args->qry_hdr, args->qry_fname); + } + if ( args->gt_samples ) + { + init_samples(args->gt_samples, args->gt_samples_is_file, &args->gt_smpl, &args->ngt_smpl, + args->gt_hdr ? args->gt_hdr : args->qry_hdr, + args->gt_fname ? args->gt_fname : args->qry_fname); + } + else if ( args->pair_samples ) + { + int npairs; + char **tmp = hts_readlist(args->pair_samples, args->pair_samples_is_file, &npairs); + if ( !tmp || !npairs ) error("Failed to parse %s\n", args->pair_samples); + if ( !args->pair_samples_is_file && npairs%2 ) error("Expected even number of comma-delimited samples with -p\n"); + args->npairs = args->pair_samples_is_file ? npairs : npairs/2; + args->pairs = (pair_t*) calloc(args->npairs,sizeof(*args->pairs)); + if ( !args->pair_samples_is_file ) + { + for (i=0; inpairs; i++) + { + args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i]); + args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, tmp[2*i+1]); + if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[2*i]); + 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]); + free(tmp[2*i]); + free(tmp[2*i+1]); + } + } + else + { + for (i=0; inpairs; i++) + { + char *ptr = tmp[i]; + while ( *ptr && !isspace(*ptr) ) ptr++; + if ( !*ptr ) error("Could not parse %s: %s\n",args->pair_samples,tmp[i]); + *ptr = 0; + args->pairs[i].iqry = bcf_hdr_id2int(args->qry_hdr, BCF_DT_SAMPLE, tmp[i]); + if ( args->pairs[i].iqry < 0 ) error("No such sample in %s: [%s]\n",args->qry_fname,tmp[i]); + ptr++; + while ( *ptr && isspace(*ptr) ) ptr++; + args->pairs[i].igt = bcf_hdr_id2int(args->gt_hdr?args->gt_hdr:args->qry_hdr, BCF_DT_SAMPLE, ptr); + if ( args->pairs[i].igt < 0 ) error("No such sample in %s: [%s]\n",args->gt_fname?args->gt_fname:args->qry_fname,ptr); + free(tmp[i]); + } + } + free(tmp); + qsort(args->pairs,args->npairs,sizeof(*args->pairs),cmp_pair); + } + else if ( args->gt_hdr ) + args->ngt_smpl = bcf_hdr_nsamples(args->gt_hdr); + if ( !args->ngt_smpl ) + { + args->ngt_smpl = args->nqry_smpl; + args->gt_smpl = args->qry_smpl; + args->cross_check = 1; + } + + // The data arrays + if ( !args->npairs ) args->npairs = args->cross_check ? args->nqry_smpl*(args->nqry_smpl+1)/2 : args->ngt_smpl*args->nqry_smpl; + if ( !args->pair_samples ) + { + args->qry_dsg = (uint8_t*) malloc(args->nqry_smpl); + args->gt_dsg = args->cross_check ? args->qry_dsg : (uint8_t*) malloc(args->ngt_smpl); + } + if ( args->use_PLs ) + { + args->pdiff = (double*) calloc(args->npairs,sizeof(*args->pdiff)); // log probability of pair samples being the same + args->qry_prob = (double*) malloc(3*args->nqry_smpl*sizeof(*args->qry_prob)); + args->gt_prob = args->cross_check ? args->qry_prob : (double*) malloc(3*args->ngt_smpl*sizeof(*args->gt_prob)); + + // dsg2prob: the first index is bitmask of 8 possible dsg combinations (only 1<<0,1<<2,1<<3 are set, accessing + // anything else indicated an error, this is just to reuse gt_to_dsg()); the second index are the corresponding + // probabilities of 0/0, 0/1, and 1/1 genotypes + for (i=0; i<8; i++) + for (j=0; j<3; j++) + args->dsg2prob[i][j] = HUGE_VAL; + args->dsg2prob[1][0] = -log(1-pow(10,-0.1*args->use_PLs)); + args->dsg2prob[1][1] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[1][2] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[2][0] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[2][1] = -log(1-pow(10,-0.1*args->use_PLs)); + args->dsg2prob[2][2] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[4][0] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[4][1] = -log(0.5*pow(10,-0.1*args->use_PLs)); + args->dsg2prob[4][2] = -log(1-pow(10,-0.1*args->use_PLs)); + + // lookup table to avoid exponentiation + for (i=0; i<256; i++) args->pl2prob[i] = pow(10,-0.1*i); + } + else + args->ndiff = (uint32_t*) calloc(args->npairs,sizeof(*args->ndiff)); // number of differing genotypes for each pair of samples + args->ncnt = (uint32_t*) calloc(args->npairs,sizeof(*args->ncnt)); // number of comparisons performed (non-missing data) + if ( !args->ncnt ) error("Error: failed to allocate %.1f Mb\n", args->npairs*sizeof(*args->ncnt)/1e6); + if ( args->calc_hwe_prob ) + { + // prob of the observed sequence of matches given site AFs and HWE + args->hwe_prob = (double*) calloc(args->npairs,sizeof(*args->hwe_prob)); + 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); + } + + if ( args->distinctive_sites ) diff_sites_init(args); + + args->fp = bcftools_stdout; + print_header(args, args->fp); +} + +static void destroy_data(args_t *args) +{ + if ( args->gt_dsg!=args->qry_dsg ) free(args->gt_dsg); + free(args->qry_dsg); + if ( args->gt_prob!=args->qry_prob ) free(args->gt_prob); + free(args->qry_prob); + free(args->es_max_mem); + fclose(args->fp); + if ( args->distinctive_sites ) diff_sites_destroy(args); + free(args->hwe_prob); + free(args->cwd); + free(args->qry_arr); + if ( args->gt_hdr ) free(args->gt_arr); + free(args->pdiff); + free(args->ndiff); + free(args->ncnt); + free(args->qry_smpl); + if ( args->gt_smpl!=args->qry_smpl ) free(args->gt_smpl); + free(args->pairs); + bcf_sr_destroy(args->files); +} + +static inline uint8_t gt_to_dsg(int32_t *ptr) +{ + if ( bcf_gt_is_missing(ptr[0]) || bcf_gt_is_missing(ptr[1]) || ptr[1]==bcf_int32_vector_end ) return 0; + uint8_t dsg = (bcf_gt_allele(ptr[0])?1:0) + (bcf_gt_allele(ptr[1])?1:0); + return 1<dsg2prob[dsg][0]; + prob[1] = args->dsg2prob[dsg][1]; + prob[2] = args->dsg2prob[dsg][2]; + } + return dsg; +} +static inline uint8_t pl_to_prob(args_t *args, int32_t *ptr, double *prob) +{ + uint8_t dsg = pl_to_dsg(ptr); + if ( dsg ) + { + prob[0] = (ptr[0]>=0 && ptr[0]<255) ? args->pl2prob[ptr[0]] : args->pl2prob[255]; + prob[1] = (ptr[1]>=0 && ptr[1]<255) ? args->pl2prob[ptr[1]] : args->pl2prob[255]; + prob[2] = (ptr[2]>=0 && ptr[2]<255) ? args->pl2prob[ptr[2]] : args->pl2prob[255]; + double sum = prob[0] + prob[1] + prob[2]; + prob[0] /= sum; + prob[1] /= sum; + prob[2] /= sum; + prob[0] = -log(prob[0]); + prob[1] = -log(prob[1]); + prob[2] = -log(prob[2]); + } + return dsg; +} +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) +{ + static int warn_dip_GT = 1; + static int warn_dip_PL = 1; + int i; + for (i=0; i<2; i++) + { + if ( *use_GT ) + { + int ret = bcf_get_genotypes(hdr,rec,arr,narr); + if ( ret < 0 ) + { + if ( !i ) { *use_GT = 0; continue; } + args->nskip_no_data++; + return -1; + } + if ( ret != 2*bcf_hdr_nsamples(hdr) ) + { + if ( warn_dip_GT ) + { + 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); + warn_dip_GT = 0; + } + args->nskip_dip_GT++; + return -1; + } + *narr1 = 2; + return 0; + } + + int ret = bcf_get_format_int32(hdr,rec,"PL",arr,narr); + if ( ret < 0 ) + { + if ( !i ) { *use_GT = 1; continue; } + args->nskip_no_data++; + return -1; + } + if ( ret != 3*bcf_hdr_nsamples(hdr) ) + { + if ( warn_dip_PL ) + { + 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); + warn_dip_PL = 0; + } + args->nskip_dip_PL++; + return -1; + } + *narr1 = 3; + return 0; + } + return -1; // should never reach +} +static void process_line(args_t *args) +{ + int i,j,k, nqry1, ngt1, ret; + + bcf1_t *gt_rec = NULL, *qry_rec = bcf_sr_get_line(args->files,0); // the query file + int qry_use_GT = args->qry_use_GT; + int gt_use_GT = args->gt_use_GT; + + ret = set_data(args, args->qry_hdr, qry_rec, &args->qry_arr, &args->nqry_arr, &nqry1, &qry_use_GT); + if ( ret<0 ) return; + + if ( args->gt_hdr ) + { + gt_rec = bcf_sr_get_line(args->files,1); + ret = set_data(args, args->gt_hdr, gt_rec, &args->gt_arr, &args->ngt_arr, &ngt1, >_use_GT); + if ( ret<0 ) return; + } + else + { + ngt1 = nqry1; + args->gt_arr = args->qry_arr; + } + + // stats: number of compared sites, and used tags + args->ncmp++; + args->nused[qry_use_GT][gt_use_GT]++; + + double af,hwe_dsg[8]; + if ( args->calc_hwe_prob ) + { + int ac[2]; + if ( args->gt_hdr ) + { + if ( bcf_calc_ac(args->gt_hdr, gt_rec, ac, BCF_UN_INFO|BCF_UN_FMT)!=1 ) error("todo: bcf_calc_ac() failed\n"); + } + 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"); + + // hwe indexes correspond to the bitmask of eight dsg combinations to account for PL uncertainty + // for in the extreme case we can have uninformative PL=0,0,0. So the values are the minima of e.g. + // hwe[1,2,4] .. dsg=0,1,2 + // hwe[3] .. dsg=0 or 1 + // hwe[6] .. dsg=1 or 2 + + double hwe[3]; + const double min_af = 1e-5; // cap the AF in case we get unrealistic values + af = (double)ac[1]/(ac[0]+ac[1]); + hwe[0] = af>min_af ? -log(af*af) : -log(min_af*min_af); + hwe[1] = af>min_af && af<1-min_af ? -log(2*af*(1-af)) : -log(2*min_af*(1-min_af)); + hwe[2] = af<(1-min_af) ? -log((1-af)*(1-af)) : -log(min_af*min_af); + hwe_dsg[0] = 0; + for (i=1; i<8; i++) + { + hwe_dsg[i] = HUGE_VAL; + for (k=0; k<3; k++) + { + if ( ((1< hwe[k] ) hwe_dsg[i] = hwe[k]; + } + } + } + + // The sample pairs were given explicitly via -p/-P options + if ( args->pairs ) + { + if ( !args->use_PLs ) + { + int ndiff = 0; + if ( args->kbs_diff ) diff_sites_reset(args); + + for (i=0; inpairs; i++) + { + int32_t *ptr; + uint8_t qry_dsg, gt_dsg; + + ptr = args->gt_arr + args->pairs[i].igt*ngt1; + gt_dsg = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr); + if ( !gt_dsg ) continue; // missing value + if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom + + ptr = args->qry_arr + args->pairs[i].iqry*nqry1; + qry_dsg = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr); + if ( !qry_dsg ) continue; // missing value + + int match = qry_dsg & gt_dsg; + if ( !match ) + { + args->ndiff[i]++; + if ( args->kbs_diff ) { ndiff++; kbs_insert(args->kbs_diff, i); } + } + else if ( args->calc_hwe_prob ) args->hwe_prob[i] += hwe_dsg[match]; + args->ncnt[i]++; + } + + if ( ndiff ) diff_sites_push(args, ndiff, qry_rec->rid, qry_rec->pos); + } + else // use_PLs set + { + for (i=0; inpairs; i++) + { + int32_t *ptr; + double qry_prob[3], gt_prob[3]; + uint8_t qry_dsg, gt_dsg; + + ptr = args->gt_arr + args->pairs[i].igt*ngt1; + gt_dsg = gt_use_GT ? gt_to_prob(args,ptr,gt_prob) : pl_to_prob(args,ptr,gt_prob); + if ( !gt_dsg ) continue; // missing value + if ( args->hom_only && !(gt_dsg&5) ) continue; // not a hom + + ptr = args->qry_arr + args->pairs[i].iqry*nqry1; + qry_dsg = qry_use_GT ? gt_to_prob(args,ptr,qry_prob) : pl_to_prob(args,ptr,qry_prob); + if ( !qry_dsg ) continue; // missing value + + double min = qry_prob[0] + gt_prob[0]; + qry_prob[1] += gt_prob[1]; + if ( min > qry_prob[1] ) min = qry_prob[1]; + qry_prob[2] += gt_prob[2]; + if ( min > qry_prob[2] ) min = qry_prob[2]; + args->pdiff[i] += min; + + if ( args->calc_hwe_prob ) + { + int match = qry_dsg & gt_dsg; + args->hwe_prob[i] += hwe_dsg[match]; + } + args->ncnt[i]++; + } + } + return; + } + + int idx=0; + if ( !args->use_PLs ) + { + for (i=0; inqry_smpl; i++) + { + int iqry = args->qry_smpl ? args->qry_smpl[i] : i; + int32_t *ptr = args->qry_arr + nqry1*iqry; + args->qry_dsg[i] = qry_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr); + } + if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg + { + for (i=0; ingt_smpl; i++) + { + int igt = args->gt_smpl ? args->gt_smpl[i] : i; + int32_t *ptr = args->gt_arr + ngt1*igt; + args->gt_dsg[i] = gt_use_GT ? gt_to_dsg(ptr) : pl_to_dsg(ptr); + if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value + } + } + for (i=0; inqry_smpl; i++) + { + int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode? + if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value + for (j=0; jgt_dsg[j] ) { idx++; continue; } // missing value + int match = args->qry_dsg[i] & args->gt_dsg[j]; + if ( !match ) args->ndiff[idx]++; + else if ( args->calc_hwe_prob ) args->hwe_prob[idx] += hwe_dsg[match]; + args->ncnt[idx]++; + idx++; + } + } + } + else // use_PLs set + { + for (i=0; inqry_smpl; i++) + { + int iqry = args->qry_smpl ? args->qry_smpl[i] : i; + int32_t *ptr = args->qry_arr + nqry1*iqry; + 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); + } + if ( !args->cross_check ) // in this case gt_dsg points to qry_dsg + { + for (i=0; ingt_smpl; i++) + { + int igt = args->gt_smpl ? args->gt_smpl[i] : i; + int32_t *ptr = args->gt_arr + ngt1*igt; + 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); + if ( args->hom_only && !(args->gt_dsg[i]&5) ) args->gt_dsg[i] = 0; // not a hom, set to a missing value + } + } + for (i=0; inqry_smpl; i++) + { + int ngt = args->cross_check ? i : args->ngt_smpl; // two files or a sub-diagonal cross-check mode? + if ( !args->qry_dsg[i] ) { idx += ngt; continue; } // missing value + for (j=0; jgt_dsg[j] ) { idx++; continue; } // missing value + + double min = args->qry_prob[i*3] + args->gt_prob[j*3]; + 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]; + 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]; + args->pdiff[idx] += min; + + if ( args->calc_hwe_prob ) + { + int match = args->qry_dsg[i] & args->gt_dsg[j]; + args->hwe_prob[idx] += hwe_dsg[match]; + } + args->ncnt[idx]++; + idx++; + } + } + } +} + + +typedef struct +{ + int ism, idx; + double val; +} +idbl_t; +static int cmp_idbl(const void *_a, const void *_b) +{ + idbl_t *a = (idbl_t*)_a; + idbl_t *b = (idbl_t*)_b; + if ( a->val < b->val ) return -1; + if ( a->val > b->val ) return 1; + return 0; +} +static void report_distinctive_sites(args_t *args) +{ + extsort_sort(args->es); + + fprintf(args->fp,"# DS, distinctive sites:\n"); + fprintf(args->fp,"# - chromosome\n"); + fprintf(args->fp,"# - position\n"); + fprintf(args->fp,"# - cumulative number of pairs distinguished by this block\n"); + fprintf(args->fp,"# - block id\n"); + fprintf(args->fp,"#DS\t[2]Chromosome\t[3]Position\t[4]Cumulative number of distinct pairs\t[5]Block id\n"); + + kbitset_t *kbs_blk = kbs_init(args->npairs); + kbitset_iter_t itr; + int i,ndiff,rid,pos,ndiff_tot = 0, iblock = 0; + int ndiff_min = args->distinctive_sites <= args->npairs ? args->distinctive_sites : args->npairs; + while ( diff_sites_shift(args,&ndiff,&rid,&pos) ) + { + int ndiff_new = 0, ndiff_dbg = 0; + kbs_start(&itr); + while ( (i=kbs_next(args->kbs_diff, &itr))>=0 ) + { + ndiff_dbg++; + if ( kbs_exists(kbs_blk,i) ) continue; // already set + kbs_insert(kbs_blk,i); + ndiff_new++; + } + if ( ndiff_dbg!=ndiff ) error("Corrupted data, fixme: %d vs %d\n",ndiff_dbg,ndiff); + if ( !ndiff_new ) continue; // no new pair distinguished by this site + ndiff_tot += ndiff_new; + 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); + if ( ndiff_tot < ndiff_min ) continue; // fewer than the requested number of pairs can be distinguished at this point + iblock++; + ndiff_tot = 0; + kbs_clear(kbs_blk); + } + kbs_destroy(kbs_blk); +} +static void report(args_t *args) +{ + fprintf(args->fp,"INFO\tsites-compared\t%u\n",args->ncmp); + fprintf(args->fp,"INFO\tsites-skipped-no-match\t%u\n",args->nskip_no_match); + fprintf(args->fp,"INFO\tsites-skipped-multiallelic\t%u\n",args->nskip_not_ba); + fprintf(args->fp,"INFO\tsites-skipped-monoallelic\t%u\n",args->nskip_mono); + fprintf(args->fp,"INFO\tsites-skipped-no-data\t%u\n",args->nskip_no_data); + fprintf(args->fp,"INFO\tsites-skipped-GT-not-diploid\t%u\n",args->nskip_dip_GT); + fprintf(args->fp,"INFO\tsites-skipped-PL-not-diploid\t%u\n",args->nskip_dip_PL); + fprintf(args->fp,"INFO\tsites-used-PL-vs-PL\t%u\n",args->nused[0][0]); + fprintf(args->fp,"INFO\tsites-used-PL-vs-GT\t%u\n",args->nused[0][1]); + fprintf(args->fp,"INFO\tsites-used-GT-vs-PL\t%u\n",args->nused[1][0]); + fprintf(args->fp,"INFO\tsites-used-GT-vs-GT\t%u\n",args->nused[1][1]); + fprintf(args->fp,"# DC, discordance:\n"); + fprintf(args->fp,"# - query sample\n"); + fprintf(args->fp,"# - genotyped sample\n"); + 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"); + fprintf(args->fp,"# - negative log of HWE probability at matching sites (rare genotypes matches are more informative, bigger is better)\n"); + fprintf(args->fp,"# - number of sites compared (bigger is better)\n"); + 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"); + + int trim = args->ntop; + if ( !args->pairs ) + { + if ( !args->ngt_smpl && args->nqry_smpl <= args->ntop ) trim = 0; + if ( args->ngt_smpl && args->ngt_smpl <= args->ntop ) trim = 0; + } + + if ( args->pairs ) + { + int i; + for (i=0; inpairs; i++) + { + int iqry = args->pairs[i].iqry; + int igt = args->pairs[i].igt; + if ( args->ndiff ) + { + fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->ndiff[i], + args->calc_hwe_prob ? args->hwe_prob[i] : 0, + args->ncnt[i]); + } + else + { + fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->pdiff[i], + args->calc_hwe_prob ? args->hwe_prob[i] : 0, + args->ncnt[i]); + } + } + } + else if ( !trim ) + { + int i,j,idx=0; + for (i=0; inqry_smpl; i++) + { + int iqry = args->qry_smpl ? args->qry_smpl[i] : i; + int ngt = args->cross_check ? i : args->ngt_smpl; + for (j=0; jgt_smpl ? args->gt_smpl[j] : j; + if ( args->ndiff ) + { + fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->ndiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + else + { + fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->pdiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + idx++; + } + } + } + else if ( !args->cross_check ) + { + idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*args->ngt_smpl); + int i,j; + for (i=0; inqry_smpl; i++) + { + int idx = i*args->ngt_smpl; + for (j=0; jngt_smpl; j++) + { + if ( args->sort_by_hwe ) + arr[j].val = -args->hwe_prob[idx]; + else if ( args->ndiff ) + arr[j].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0; + else + arr[j].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0; + arr[j].ism = j; + arr[j].idx = idx; + idx++; + } + qsort(arr, args->ngt_smpl, sizeof(*arr), cmp_idbl); + int iqry = args->qry_smpl ? args->qry_smpl[i] : i; + for (j=0; jntop; j++) + { + int idx = arr[j].idx; + int igt = args->gt_smpl ? args->gt_smpl[arr[j].ism] : arr[j].ism; + if ( args->ndiff ) + { + fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->ndiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + else + { + fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->gt_hdr?args->gt_hdr->samples[igt]:args->qry_hdr->samples[igt], + args->pdiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + } + } + free(arr); + } + else + { + int narr = args->nqry_smpl-1; + idbl_t *arr = (idbl_t*)malloc(sizeof(*arr)*narr); + int i,j,k,idx; + for (i=0; inqry_smpl; i++) + { + k = 0, idx = i*(i-1)/2; + for (j=0; jsort_by_hwe ) + arr[k].val = -args->hwe_prob[idx]; + else if ( args->ndiff ) + arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0; + else + arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0; + arr[k].ism = j; + arr[k].idx = idx; + idx++; + k++; + } + for (; jsort_by_hwe ) + arr[k].val = -args->hwe_prob[idx]; + else if ( args->ndiff ) + arr[k].val = args->ncnt[idx] ? (double)args->ndiff[idx]/args->ncnt[idx] : 0; + else + arr[k].val = args->ncnt[idx] ? args->pdiff[idx]/args->ncnt[idx] : 0; + arr[k].ism = j + 1; + arr[k].idx = idx; + k++; + } + qsort(arr, narr, sizeof(*arr), cmp_idbl); + int iqry = args->qry_smpl ? args->qry_smpl[i] : i; + for (j=0; jntop; j++) + { + if ( i <= arr[j].ism ) continue; + int idx = arr[j].idx; + int igt = args->qry_smpl ? args->qry_smpl[arr[j].ism] : arr[j].ism; + if ( args->ndiff ) + { + fprintf(args->fp,"DC\t%s\t%s\t%u\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->qry_hdr->samples[igt], + args->ndiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + else + { + fprintf(args->fp,"DC\t%s\t%s\t%e\t%e\t%u\n", + args->qry_hdr->samples[iqry], + args->qry_hdr->samples[igt], + args->pdiff[idx], + args->calc_hwe_prob ? args->hwe_prob[idx] : 0, + args->ncnt[idx]); + } + } + } + free(arr); + } +} + +static int is_input_okay(args_t *args, int nmatch) +{ + int i; + const char *msg; + bcf_hdr_t *hdr; + bcf1_t *rec; + if ( args->gt_hdr && nmatch!=2 ) + { + if ( args->nskip_no_match++ ) return 0; + for (i=0; i<2; i++) + { + rec = bcf_sr_get_line(args->files,i); + if ( rec ) break; + } + hdr = bcf_sr_get_header(args->files,i); + fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", no record with matching POS+ALT. (This is printed only once.)\n", + bcf_seqname(hdr,rec),rec->pos+1); + return 0; + } + for (i=0; i<2; i++) + { + hdr = bcf_sr_get_header(args->files,i); + rec = bcf_sr_get_line(args->files,i); + if ( rec->n_allele>2 ) + { + if ( args->nskip_not_ba++ ) return 0; + msg = "not a biallelic site, run `bcftools norm -m -` first"; + goto not_okay; + } + if ( bcf_get_variant_types(rec)==VCF_REF ) + { + if ( args->nskip_mono++ ) return 0; + msg = "monoallelic site"; + goto not_okay; + } + if ( !args->gt_hdr ) break; + } + return 1; + +not_okay: + fprintf(bcftools_stderr,"INFO: skipping %s:%"PRIhts_pos", %s. (This is printed only once.)\n", + bcf_seqname(hdr,rec),rec->pos+1,msg); + return 0; +} + +static void usage(void) +{ + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "About: Check sample identity. With no -g BCF given, multi-sample cross-check is performed.\n"); + fprintf(bcftools_stderr, "Usage: bcftools gtcheck [options] [-g ] \n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "Options:\n"); + //fprintf(bcftools_stderr, " -a, --all-sites Output comparison for all sites\n"); + //fprintf(bcftools_stderr, " -c, --cluster MIN,MAX Min inter- and max intra-sample error [0.23,-0.3]\n"); + fprintf(bcftools_stderr, " --distinctive-sites Find sites that can distinguish between at least NUM sample pairs.\n"); + fprintf(bcftools_stderr, " NUM[,MEM[,TMP]] If the number is smaller or equal to 1, it is interpreted as the fraction of pairs.\n"); + fprintf(bcftools_stderr, " The optional MEM string sets the maximum memory used for in-memory sorting [500M]\n"); +#ifdef _WIN32 + fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/bcftools.XXXXXX]\n"); +#else + fprintf(bcftools_stderr, " and TMP is a prefix of temporary files used by external sorting [/tmp/bcftools.XXXXXX]\n"); +#endif + fprintf(bcftools_stderr, " --dry-run Stop after first record to estimate required time\n"); + fprintf(bcftools_stderr, " -e, --error-probability INT Phred-scaled probability of genotyping error, 0 for faster but less accurate results [40]\n"); + fprintf(bcftools_stderr, " -g, --genotypes FILE Genotypes to compare against\n"); + fprintf(bcftools_stderr, " -H, --homs-only Homozygous genotypes only, useful with low coverage data (requires -g)\n"); + fprintf(bcftools_stderr, " --n-matches INT Print only top INT matches for each sample (sorted by average score), 0 for unlimited.\n"); + fprintf(bcftools_stderr, " Use negative value to sort by HWE probability rather than by discordance [0]\n"); + fprintf(bcftools_stderr, " --no-HWE-prob Disable calculation of HWE probability\n"); + 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"); + 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"); + fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + 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"); + fprintf(bcftools_stderr, " -S, --samples-file [qry|gt]:FILE File with the query or -g samples to compare\n"); + fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(bcftools_stderr, " -u, --use TAG1[,TAG2] Which tag to use in the query file (TAG1) and the -g file (TAG2) [PL,GT]\n"); + fprintf(bcftools_stderr, "Examples:\n"); + fprintf(bcftools_stderr, " # Check discordance of all samples from B against all sample in A\n"); + fprintf(bcftools_stderr, " bcftools gtcheck -g A.bcf B.bcf\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, " # Limit comparisons to the fiven list of samples\n"); + fprintf(bcftools_stderr, " bcftools gtcheck -s gt:a1,a2,a3 -s qry:b1,b2 -g A.bcf B.bcf\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, " # Compare only two pairs a1,b1 and a1,b2\n"); + fprintf(bcftools_stderr, " bcftools gtcheck -p a1,b1,a1,b2 -g A.bcf B.bcf\n"); + fprintf(bcftools_stderr, "\n"); + bcftools_exit(1); +} + +int main_vcfgtcheck(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; set_cwd(args); + args->qry_use_GT = -1; + args->gt_use_GT = -1; + args->calc_hwe_prob = 1; + args->use_PLs = 40; + args->regions_overlap = 1; + args->targets_overlap = 0; + + // external sort for --distinctive-sites +#ifdef _WIN32 + args->es_tmp_prefix = NULL; +#else + args->es_tmp_prefix = "/tmp/bcftools-gtcheck"; +#endif + args->es_max_mem = strdup("500M"); + + // In simulated sample swaps the minimum error was 0.3 and maximum intra-sample error was 0.23 + // - min_inter: pairs with smaller err value will be considered identical + // - max_intra: pairs with err value bigger than abs(max_intra_err) will be considered + // different. If negative, the cutoff may be heuristically lowered + args->min_inter_err = 0.23; + args->max_intra_err = -0.3; + + static struct option loptions[] = + { + {"error-probability",1,0,'e'}, + {"use",1,0,'u'}, + {"cluster",1,0,'c'}, + {"GTs-only",1,0,'G'}, + {"all-sites",0,0,'a'}, + {"homs-only",0,0,'H'}, + {"help",0,0,'h'}, + {"genotypes",1,0,'g'}, + {"plot",1,0,'p'}, + {"samples",1,0,'s'}, + {"samples-file",1,0,'S'}, + {"n-matches",1,0,2}, + {"no-HWE-prob",0,0,3}, + {"target-sample",1,0,4}, + {"dry-run",0,0,5}, + {"distinctive-sites",1,0,6}, + {"regions",1,0,'r'}, + {"regions-file",1,0,'R'}, + {"regions-overlap",required_argument,NULL,7}, + {"targets",1,0,'t'}, + {"targets-file",1,0,'T'}, + {"targets-overlap",required_argument,NULL,8}, + {"pairs",1,0,'p'}, + {"pairs-file",1,0,'P'}, + {0,0,0,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "hg:p:s:S:p:P:Hr:R:at:T:G:c:u:e:",loptions,NULL)) >= 0) { + switch (c) { + case 'e': + args->use_PLs = strtol(optarg,&tmp,10); + if ( !tmp || *tmp ) error("Could not parse: --error-probability %s\n", optarg); + break; + case 'u': + { + int i,nlist; + char **list = hts_readlist(optarg, 0, &nlist); + if ( !list || nlist<=0 || nlist>2 ) error("Failed to parse --use %s\n", optarg); + if ( !strcasecmp("GT",list[0]) ) args->qry_use_GT = 1; + else if ( !strcasecmp("PL",list[0]) ) args->qry_use_GT = 0; + else error("Failed to parse --use %s; only GT and PL are supported\n", optarg); + if ( nlist==2 ) + { + if ( !strcasecmp("GT",list[1]) ) args->gt_use_GT = 1; + else if ( !strcasecmp("PL",list[1]) ) args->gt_use_GT = 0; + else error("Failed to parse --use %s; only GT and PL are supported\n", optarg); + } + else args->gt_use_GT = args->qry_use_GT; + for (i=0; intop = strtol(optarg,&tmp,10); + if ( !tmp || *tmp ) error("Could not parse: --n-matches %s\n", optarg); + if ( args->ntop < 0 ) + { + args->sort_by_hwe = 1; + args->ntop *= -1; + } + break; + case 3 : args->calc_hwe_prob = 0; break; + case 4 : error("The option -S, --target-sample has been deprecated\n"); break; + case 5 : args->dry_run = 1; break; + case 6 : + args->distinctive_sites = strtod(optarg,&tmp); + if ( *tmp ) + { + if ( *tmp!=',' ) error("Could not parse: --distinctive-sites %s\n", optarg); + tmp++; + free(args->es_max_mem); + args->es_max_mem = strdup(tmp); + while ( *tmp && *tmp!=',' ) tmp++; + if ( *tmp ) { *tmp = 0; args->es_tmp_prefix = tmp+1; } + } + args->use_PLs = 0; + break; + case 'c': + error("The -c option is to be implemented, please open an issue on github\n"); + args->min_inter_err = strtod(optarg,&tmp); + if ( *tmp ) + { + if ( *tmp!=',') error("Could not parse: -c %s\n", optarg); + args->max_intra_err = strtod(tmp+1,&tmp); + if ( *tmp ) error("Could not parse: -c %s\n", optarg); + } + break; + case 'G': error("The option -G, --GTs-only has been deprecated\n"); break; + case 'a': args->all_sites = 1; error("The -a option is to be implemented, please open an issue on github\n"); break; + case 'H': args->hom_only = 1; break; + case 'g': args->gt_fname = optarg; break; +// case 'p': args->plot = optarg; break; + case 's': + if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3; + else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4; + else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg); + break; + case 'S': + if ( !strncasecmp("gt:",optarg,3) ) args->gt_samples = optarg+3, args->gt_samples_is_file = 1; + else if ( !strncasecmp("qry:",optarg,4) ) args->qry_samples = optarg+4, args->qry_samples_is_file = 1; + else error("Which one? Query samples (qry:%s) or genotype samples (gt:%s)?\n",optarg,optarg); + break; + case 'p': args->pair_samples = optarg; break; + case 'P': args->pair_samples = optarg; args->pair_samples_is_file = 1; break; + case 'r': args->regions = optarg; break; + case 'R': args->regions = optarg; args->regions_is_file = 1; break; + case 't': args->targets = optarg; break; + case 'T': args->targets = optarg; args->targets_is_file = 1; break; + case 7 : + args->regions_overlap = parse_overlap_option(optarg); + if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 8 : + args->targets_overlap = parse_overlap_option(optarg); + if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case 'h': + case '?': usage(); break; + default: error("Unknown argument: %s\n", optarg); + } + } + if ( optind==argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) args->qry_fname = "-"; // reading from stdin + else usage(); // no files given + } + else args->qry_fname = argv[optind]; + if ( argc>optind+1 ) error("Error: too many files given, run with -h for help\n"); // too many files given + if ( args->pair_samples ) + { + if ( args->gt_samples || args->qry_samples ) error("The -p/-P option cannot be combined with -s/-S\n"); + if ( args->ntop ) error("The --n-matches option cannot be combined with -p/-P\n"); + } + if ( args->distinctive_sites && !args->pair_samples ) error("The experimental option --distinctive-sites requires -p/-P\n"); + if ( args->hom_only && !args->gt_fname ) error("The option --homs-only requires --genotypes\n"); + if ( args->distinctive_sites && args->use_PLs ) error("The option --distinctive-sites cannot be combined with --error-probability\n"); + + init_data(args); + + int ret; + while ( (ret=bcf_sr_next_line(args->files)) ) + { + if ( !is_input_okay(args,ret) ) continue; + + // time one record to give the user an estimate with very big files + struct timeval t0, t1; + if ( !args->ncmp ) gettimeofday(&t0, NULL); + + process_line(args); + + if ( args->ncmp==1 ) + { + gettimeofday(&t1, NULL); + double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec); + fprintf(bcftools_stderr,"INFO:\tTime required to process one record .. %f seconds\n",delta/1e6); + fprintf(args->fp,"INFO\tTime required to process one record .. %f seconds\n",delta/1e6); + if ( args->dry_run ) break; + } + } + if ( !args->dry_run ) + { + report(args); + if ( args->distinctive_sites ) report_distinctive_sites(args); + } + + destroy_data(args); + free(args); + return 0; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfmerge.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfmerge.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..7ce5dfa8d1e36bf609844014323dfddb108e0207 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfmerge.c.pysam.c @@ -0,0 +1,3606 @@ +#include "bcftools.pysam.h" + +/* vcfmerge.c -- Merge multiple VCF/BCF files to create one multi-sample file. + + Copyright (C) 2012-2023 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "regidx.h" +#include "vcmp.h" + +#define DBG 0 + +#define COLLAPSE_SNP_INS_DEL (1<<10) + +#include +KHASH_MAP_INIT_STR(strdict, int) +typedef khash_t(strdict) strdict_t; + +#define FLT_LOGIC_ADD 0 +#define FLT_LOGIC_REMOVE 1 + +#define SKIP_DONE 1 // the record was processed +#define SKIP_DIFF 2 // not compatible, merge later + +#define IS_VL_G(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_G) +#define IS_VL_A(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_A) +#define IS_VL_R(hdr,id) (bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_R) + +#define SWAP(type_t,a,b) { type_t tmp = (a); (a) = (b); (b) = tmp; } + +#define PL2PROB_MAX 1024 + +// Rules for merging FORMAT Number=A,G,R vectors with missing values +#define MERGE_MISSING_DOT 0 // leave as is, i.e. use a missing value "." +#define MERGE_MISSING_CONST 1 // use a constant value +#define MERGE_MISSING_MAX 2 // use the existing maximum value + +typedef struct _missing_rule_t +{ + char *hdr_tag; + int type; + float value; +} +missing_rule_t; + +// For merging INFO Number=A,G,R tags +typedef struct +{ + const char *hdr_tag; + int type, nvals; + int nbuf, mbuf; + uint8_t *buf; +} +AGR_info_t; + +// Rules for merging arbitrary INFO tags +typedef struct _info_rule_t +{ + char *hdr_tag; + void (*merger)(bcf_hdr_t *hdr, bcf1_t *line, struct _info_rule_t *rule); + int type; // one of BCF_HT_* + int block_size; // number of values in a block + int type_size; // size of the corresponding BCF_HT_* type + int nblocks; // number of blocks in nvals (the number of merged files) + int nvals, mvals; // used and total size of vals array + void *vals; // the info tag values +} +info_rule_t; + +typedef struct +{ + bcf1_t *line; + int end, active; // end: 0-based INFO/END +} +gvcf_aux_t; + +// Auxiliary merge data for selecting the right combination +// of buffered records across multiple readers. maux1_t +// corresponds to one buffered line. +typedef struct +{ + int skip; + int *map; // mapping from input alleles to the array of output alleles (set by merge_alleles) + int mmap; // size of map array (only buffer[i].n_allele is actually used) + int als_differ; + int var_types; // variant types in this record, shifted by <<1 to account for VCF_REF +} +maux1_t; + +// Buffered lines for a single reader +typedef struct +{ + int rid; // current rid + int beg,end; // valid ranges in reader's buffer [beg,end). Maintained by maux_reset and gvcf_flush. + int unkn_allele;// the index of the unknown allele (<*>, ) + int cur; // current line or -1 if none + int mrec; // allocated size of buf + maux1_t *rec; // buffer to keep reader's lines + bcf1_t **lines; // source buffer: either gvcf or readers' buffer + int var_types; // reader's variant types in the active [beg,end] window +} +buffer_t; +typedef struct +{ + int n, pos, var_types; // number of readers; current position; variant types at this position across all available records + int *als_types, // allele type of each output allele + mals_types; + char *chr; // current chromosome + char **als, **out_als; // merged alleles (temp, may contain empty records) and merged alleles ready for output + int nals, mals, nout_als, mout_als; // size of the output array + int *cnt, ncnt; // number of records that refer to the alleles + int *smpl_ploidy, *smpl_nGsize; // ploidy and derived number of values in Number=G tags, updated for each line (todo: cache for missing cases) + const char **fmt_key;// temporary short-lived array to store output tag names + bcf_fmt_t **fmt_map; // i-th output FORMAT field corresponds in j-th reader to i*nreader+j, first row is reserved for GT + int nfmt_map; // number of rows in the fmt_map array + int *agr_map, nagr_map, magr_map; // mapping between Number=AGR element indexes, from src idxs to dst file idxs + void *tmp_arr; + size_t ntmp_arr; + buffer_t *buf; + AGR_info_t *AGR_info; + int nAGR_info, mAGR_info; + bcf_srs_t *files; + int gvcf_min, // min buffered gvcf END position (NB: gvcf_min is 1-based) or 0 if no active lines are present + gvcf_break; // 0-based position of a next record which breaks a gVCF block + gvcf_aux_t *gvcf; // buffer of gVCF lines, for each reader one line + int nout_smpl; + kstring_t *str; + int32_t *laa; // localized alternate alleles given as input-based indexes in per-sample blocks of (args->local_alleles+1) values, 0 is always first + int nlaa, laa_dirty; // number of LAA alleles actually used at this site, and was any L* added? + int32_t *tmpi, *k2k; + double *tmpd, *pl2prob; // mapping from phred-score likelihoods (PL) to probability + int ntmpi, ntmpd, nk2k; +} +maux_t; + +typedef struct +{ + vcmp_t *vcmp; + maux_t *maux; + regidx_t *regs; // apply regions only after the blocks are expanded + regitr_t *regs_itr; + int header_only, collapse, output_type, force_samples, merge_by_id, do_gvcf, filter_logic, missing_to_ref, no_index; + char *header_fname, *output_fname, *regions_list, *info_rules, *file_list; + faidx_t *gvcf_fai; + info_rule_t *rules; + int nrules; + char *missing_rules_str; + missing_rule_t *missing_rules; // lookup for -M, --missing-rules + int nmissing_rules; + strdict_t *tmph; + kstring_t tmps; + bcf_srs_t *files; + bcf1_t *out_line; + htsFile *out_fh; + bcf_hdr_t *out_hdr; + char **argv; + int argc, n_threads, record_cmd_line, clevel; + int local_alleles; // the value of -L option + int keep_AC_AN; + char *index_fn; + int write_index; +} +args_t; + +static bcf1_t *maux_get_line(args_t *args, int i) +{ + maux_t *ma = args->maux; + int ibuf = ma->buf[i].cur; + if ( ibuf >= 0 ) return ma->buf[i].lines[ibuf]; + return NULL; +} + +static void info_rules_merge_sum(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule) +{ + if ( !rule->nvals ) return; + int i, j, ndim = rule->block_size; + #define BRANCH(type_t,is_missing) { \ + type_t *ptr = (type_t*) rule->vals; \ + for (i=0; invals; i++) if ( is_missing ) ptr[i] = 0; \ + for (i=1; inblocks; i++) \ + { \ + for (j=0; jtype) { + case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break; + case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type); +} +static void info_rules_merge_avg(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule) +{ + if ( !rule->nvals ) return; + int i, j, ndim = rule->block_size; + #define BRANCH(type_t,is_missing) { \ + type_t *ptr = (type_t*) rule->vals; \ + for (i=0; invals; i++) if ( is_missing ) ptr[i] = 0; \ + for (j=0; jnblocks; i++) sum += ptr[j+i*ndim]; \ + ptr[j] = sum / rule->nblocks; \ + } \ + } + switch (rule->type) { + case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing); break; + case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i])); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type); +} +static void info_rules_merge_min(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule) +{ + if ( !rule->nvals ) return; + int i, j, ndim = rule->block_size; + #define BRANCH(type_t,is_missing,set_missing,huge_val) { \ + type_t *ptr = (type_t*) rule->vals; \ + for (i=0; invals; i++) if ( is_missing ) ptr[i] = huge_val; \ + for (i=1; inblocks; i++) \ + { \ + for (j=0; j ptr[j+i*ndim] ) ptr[j] = ptr[j+i*ndim]; \ + } \ + for (i=0; invals; i++) if ( ptr[i]==huge_val ) set_missing; \ + } + switch (rule->type) { + case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MAX); break; + case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), HUGE_VAL); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type); +} +static void info_rules_merge_max(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule) +{ + if ( !rule->nvals ) return; + int i, j, ndim = rule->block_size; + #define BRANCH(type_t,is_missing,set_missing,huge_val) { \ + type_t *ptr = (type_t*) rule->vals; \ + for (i=0; invals; i++) if ( is_missing ) ptr[i] = huge_val; \ + for (i=1; inblocks; i++) \ + { \ + for (j=0; jnvals; i++) if ( ptr[i]==huge_val ) set_missing; \ + } + switch (rule->type) { + case BCF_HT_INT: BRANCH(int32_t, ptr[i]==bcf_int32_missing, ptr[i]=bcf_int32_missing, INT32_MIN); break; + case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[i]), bcf_float_set_missing(ptr[i]), -HUGE_VAL); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,ndim,rule->type); +} +static void info_rules_merge_join(bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule) +{ + if ( !rule->nvals ) return; + if ( rule->type==BCF_HT_STR ) + { + ((char*)rule->vals)[rule->nvals] = 0; + bcf_update_info_string(hdr,line,rule->hdr_tag,rule->vals); + } + else + { + int isrc, idst = 0; + #define BRANCH(type_t,is_missing,is_vector_end) { \ + type_t *ptr = (type_t*) rule->vals; \ + for (isrc=0; isrcnvals; isrc++) \ + { \ + if ( is_vector_end ) break; \ + if ( is_missing ) continue; \ + if ( idst!=isrc ) ptr[idst] = ptr[isrc]; \ + idst++; \ + } \ + } + switch (rule->type) { + case BCF_HT_INT: BRANCH(int32_t, ptr[isrc]==bcf_int32_missing, ptr[isrc]==bcf_int32_vector_end); break; + case BCF_HT_REAL: BRANCH(float, bcf_float_is_missing(ptr[isrc]), bcf_float_is_vector_end(ptr[isrc])); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + rule->nvals = idst; + bcf_update_info(hdr,line,rule->hdr_tag,rule->vals,rule->nvals,rule->type); + } +} + +static int missing_rules_comp_key2(const void *a, const void *b) +{ + missing_rule_t *rule1 = (missing_rule_t*) a; + missing_rule_t *rule2 = (missing_rule_t*) b; + return strcmp(rule1->hdr_tag, rule2->hdr_tag); +} +static int missing_rules_comp_key(const void *a, const void *b) +{ + char *key = (char*) a; + missing_rule_t *rule = (missing_rule_t*) b; + return strcmp(key, rule->hdr_tag); +} +static void missing_rules_init(args_t *args) +{ + kstring_t str = {0,0,0}; + if ( args->missing_rules_str ) + { + if ( !strcmp("-",args->missing_rules_str) ) kputs("PL:.,AD:.",&str); + else kputs(args->missing_rules_str,&str); + } + else if ( args->do_gvcf ) kputs("PL:max,AD:0",&str); + else return; + + args->nmissing_rules = 1; + char *ss = str.s, *tmp = ss; + int n = 0; + while ( *ss ) + { + if ( *ss==':' ) { *ss = 0; n++; if ( n%2==0 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); } + else if ( *ss==',' ) { *ss = 0; args->nmissing_rules++; n++; if ( n%2==1 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); } + ss++; + } + if ( n%2==0 ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); + args->missing_rules = (missing_rule_t*) calloc(args->nmissing_rules,sizeof(missing_rule_t)); + + n = args->nmissing_rules; + args->nmissing_rules = 0; + ss = tmp; + while ( args->nmissing_rules < n ) + { + missing_rule_t *rule = &args->missing_rules[args->nmissing_rules]; + rule->hdr_tag = strdup(ss); + int id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, rule->hdr_tag); + if ( !bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_FMT,id) ) + { + if ( args->missing_rules_str ) error("The FORMAT tag is not defined in the header: \"%s\"\n", rule->hdr_tag); + free(rule->hdr_tag); + n--; + ss = strchr(ss, '\0'); ss++; + if ( !*ss ) error("Could not parse --missing-rules, missing logic of \"%s\"\n", rule->hdr_tag); + ss = strchr(ss, '\0'); ss++; + continue; + } + + ss = strchr(ss, '\0'); ss++; + if ( !*ss ) error("Could not parse --missing-rules, missing logic of \"%s\"\n", rule->hdr_tag); + + if ( !strcasecmp(ss,".") ) rule->type = MERGE_MISSING_DOT; + else if ( !strcasecmp(ss,"max") ) rule->type = MERGE_MISSING_MAX; + else + { + char *tmp = ss; + rule->value = strtod(ss, &tmp); + if ( *tmp ) error("Could not parse --missing-rules: \"%s\"\n", args->missing_rules_str); + rule->type = MERGE_MISSING_CONST; + } + ss = strchr(ss, '\0'); ss++; + args->nmissing_rules++; + } + qsort(args->missing_rules, args->nmissing_rules, sizeof(*args->missing_rules), missing_rules_comp_key2); + free(str.s); +} +static void missing_rules_destroy(args_t *args) +{ + int i; + for (i=0; inmissing_rules; i++) + { + missing_rule_t *rule = &args->missing_rules[i]; + free(rule->hdr_tag); + } + free(args->missing_rules); +} + +static int info_rules_comp_key2(const void *a, const void *b) +{ + info_rule_t *rule1 = (info_rule_t*) a; + info_rule_t *rule2 = (info_rule_t*) b; + return strcmp(rule1->hdr_tag, rule2->hdr_tag); +} +static int info_rules_comp_key(const void *a, const void *b) +{ + char *key = (char*) a; + info_rule_t *rule = (info_rule_t*) b; + return strcmp(key, rule->hdr_tag); +} +static void info_rules_init(args_t *args) +{ + if ( args->info_rules && !strcmp("-",args->info_rules) ) return; + + kstring_t str = {0,0,0}; + if ( !args->info_rules ) + { + if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "DP")) ) kputs("DP:sum",&str); + if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "DP4")) ) + { + if ( str.l ) kputc(',',&str); + kputs("DP4:sum",&str); + } + if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "QS")) ) + { + if ( str.l ) kputc(',',&str); + kputs("QS:sum",&str); + } + if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "MinDP")) ) + { + if ( str.l ) kputc(',',&str); + kputs("MinDP:min",&str); + } + if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "I16")) ) + { + if ( str.l ) kputc(',',&str); + kputs("I16:sum",&str); + } + if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IDV")) ) + { + if ( str.l ) kputc(',',&str); + kputs("IDV:max",&str); + } + if ( args->do_gvcf && bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "IMF")) ) + { + if ( str.l ) kputc(',',&str); + kputs("IMF:max",&str); + } + if ( !bcf_hdr_nsamples(args->out_hdr) ) + { + if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AN")) ) + { + if ( str.l ) kputc(',',&str); + kputs("AN:sum",&str); + } + if ( bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, "AC")) ) + { + if ( str.l ) kputc(',',&str); + kputs("AC:sum",&str); + } + } + + if ( !str.l ) return; + args->info_rules = str.s; + } + + args->nrules = 1; + char *ss = strdup(args->info_rules), *tmp = ss; + int n = 0; + while ( *ss ) + { + if ( *ss==':' ) { *ss = 0; n++; if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); } + else if ( *ss==',' ) { *ss = 0; args->nrules++; n++; if ( n%2==1 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); } + ss++; + } + if ( n%2==0 ) error("Could not parse INFO rules: \"%s\"\n", args->info_rules); + args->rules = (info_rule_t*) calloc(args->nrules,sizeof(info_rule_t)); + + n = 0; + ss = tmp; + while ( n < args->nrules ) + { + info_rule_t *rule = &args->rules[n]; + rule->hdr_tag = strdup(ss); + int id = bcf_hdr_id2int(args->out_hdr, BCF_DT_ID, rule->hdr_tag); + if ( !bcf_hdr_idinfo_exists(args->out_hdr,BCF_HL_INFO,id) ) error("The INFO tag is not defined in the header: \"%s\"\n", rule->hdr_tag); + rule->type = bcf_hdr_id2type(args->out_hdr,BCF_HL_INFO,id); + if ( rule->type==BCF_HT_INT ) rule->type_size = sizeof(int32_t); + else if ( rule->type==BCF_HT_REAL ) rule->type_size = sizeof(float); + else if ( rule->type==BCF_HT_STR ) rule->type_size = sizeof(char); + else error("The INFO rule \"%s\" is not supported; the tag \"%s\" type is %d\n", ss,rule->hdr_tag,rule->type); + + if ( !strcmp(rule->hdr_tag,"AC") || !strcmp(rule->hdr_tag,"AN") ) args->keep_AC_AN = 1; + + ss = strchr(ss, '\0'); ss++; + if ( !*ss ) error("Could not parse INFO rules, missing logic of \"%s\"\n", rule->hdr_tag); + + int is_join = 0; + if ( !strcasecmp(ss,"sum") ) rule->merger = info_rules_merge_sum; + else if ( !strcasecmp(ss,"avg") ) rule->merger = info_rules_merge_avg; + else if ( !strcasecmp(ss,"min") ) rule->merger = info_rules_merge_min; + else if ( !strcasecmp(ss,"max") ) rule->merger = info_rules_merge_max; + else if ( !strcasecmp(ss,"join") ) { rule->merger = info_rules_merge_join; is_join = 1; } + else error("The rule logic \"%s\" not recognised\n", ss); + + if ( !is_join && rule->type==BCF_HT_STR ) + error("Numeric operation \"%s\" requested on non-numeric field: %s\n", ss, rule->hdr_tag); + if ( bcf_hdr_id2number(args->out_hdr,BCF_HL_INFO,id)==0xfffff ) + { + int is_agr = ( + bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_A || + bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_G || + bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)==BCF_VL_R + ) ? 1 : 0; + if ( is_join && bcf_hdr_id2length(args->out_hdr,BCF_HL_INFO,id)!=BCF_VL_VAR ) + { + bcf_hrec_t *hrec = bcf_hdr_get_hrec(args->out_hdr, BCF_HL_INFO, "ID", rule->hdr_tag, NULL); + hrec = bcf_hrec_dup(hrec); + int i = bcf_hrec_find_key(hrec, "Number"); + if ( i<0 ) error("Uh, could not find the entry Number in the header record of %s\n",rule->hdr_tag); + free(hrec->vals[i]); + hrec->vals[i] = strdup("."); + bcf_hdr_remove(args->out_hdr,BCF_HL_INFO, rule->hdr_tag); + bcf_hdr_add_hrec(args->out_hdr, hrec); + } + if ( !is_join && !is_agr ) + error("Only fixed-length vectors are supported with -i %s:%s\n", ss, rule->hdr_tag); + } + + ss = strchr(ss, '\0'); ss++; + n++; + } + free(str.s); + free(tmp); + + qsort(args->rules, args->nrules, sizeof(*args->rules), info_rules_comp_key2); +} +static void info_rules_destroy(args_t *args) +{ + int i; + for (i=0; inrules; i++) + { + info_rule_t *rule = &args->rules[i]; + free(rule->hdr_tag); + free(rule->vals); + } + free(args->rules); +} +static void info_rules_reset(args_t *args) +{ + int i; + for (i=0; inrules; i++) + args->rules[i].nblocks = args->rules[i].nvals = args->rules[i].block_size = 0; +} +static int info_rules_add_values(args_t *args, bcf_hdr_t *hdr, bcf1_t *line, info_rule_t *rule, maux1_t *als, int var_len) +{ + int msize = args->maux->ntmp_arr / rule->type_size; + int ret = bcf_get_info_values(hdr, line, rule->hdr_tag, &args->maux->tmp_arr, &msize, rule->type); + if ( ret<=0 ) error("FIXME: error parsing %s at %s:%"PRId64" .. %d\n", rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1,ret); + args->maux->ntmp_arr = msize * rule->type_size; + + rule->nblocks++; + + if ( rule->type==BCF_HT_STR ) + { + int need_comma = rule->nblocks==1 ? 0 : 1; + hts_expand(char,rule->nvals+ret+need_comma+1,rule->mvals,rule->vals); // 1 for null-termination + char *tmp = (char*) rule->vals + rule->nvals; + if ( rule->nvals>0 ) { *tmp = ','; tmp++; } + strncpy(tmp,(char*)args->maux->tmp_arr,ret); + rule->nvals += ret + need_comma; + return 1; + } + + int i, j; + if ( var_len==BCF_VL_A ) + { + if ( ret!=line->n_allele-1 ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1); + args->maux->nagr_map = ret; + hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map); + // create mapping from source file ALT indexes to dst file indexes + for (i=0; imaux->agr_map[i] = als->map[i+1] - 1; + rule->block_size = args->maux->nout_als - 1; + } + else if ( var_len==BCF_VL_R ) + { + if ( ret!=line->n_allele ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1); + args->maux->nagr_map = ret; + hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map); + for (i=0; imaux->agr_map[i] = als->map[i]; + rule->block_size = args->maux->nout_als; + } + else if ( var_len==BCF_VL_G ) + { + args->maux->nagr_map = bcf_alleles2gt(line->n_allele-1,line->n_allele-1)+1; + if ( ret!=line->n_allele && ret!=args->maux->nagr_map ) error("Wrong number of %s fields at %s:%"PRId64"\n",rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1); + if ( ret==line->n_allele ) // haploid + { + args->maux->nagr_map = line->n_allele; + hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map); + for (i=0; imaux->agr_map[i] = als->map[i]; + rule->block_size = args->maux->nout_als; + } + else + { + hts_expand(int,args->maux->nagr_map,args->maux->magr_map,args->maux->agr_map); + int k_src = 0; + for (i=0; in_allele; i++) + { + for (j=0; j<=i; j++) + { + args->maux->agr_map[k_src] = bcf_alleles2gt(als->map[i],als->map[j]); + k_src++; + } + } + rule->block_size = bcf_alleles2gt(args->maux->nout_als-1,args->maux->nout_als-1)+1; + } + } + else + { + if ( rule->nblocks>1 && ret!=rule->block_size ) + error("Mismatch in number of values for INFO/%s at %s:%"PRId64"\n", rule->hdr_tag,bcf_seqname(hdr,line),(int64_t) line->pos+1); + rule->block_size = ret; + args->maux->nagr_map = 0; + } + + #define BRANCH(src_type_t,dst_type_t,set_missing) { \ + src_type_t *src = (src_type_t *) args->maux->tmp_arr; \ + hts_expand0(dst_type_t,(rule->nvals+rule->block_size),rule->mvals,rule->vals); \ + dst_type_t *dst = (dst_type_t *) rule->vals + rule->nvals; \ + rule->nvals += rule->block_size; \ + if ( !args->maux->nagr_map ) \ + { \ + for (i=0; iblock_size; i++) set_missing; \ + for (i=0; imaux->agr_map[i]] = src[i]; \ + } \ + } + switch (rule->type) { + case BCF_HT_INT: BRANCH(int, int32_t, dst[i] = bcf_int32_missing); break; + case BCF_HT_REAL: BRANCH(float, float, bcf_float_set_missing(dst[i])); break; + default: error("TODO: %s:%d .. type=%d\n", __FILE__,__LINE__, rule->type); + } + #undef BRANCH + + return 1; +} + +int bcf_hdr_sync(bcf_hdr_t *h); + +void merge_headers(bcf_hdr_t *hw, const bcf_hdr_t *hr, const char *clash_prefix, int force_samples) +{ + // header lines + hw = bcf_hdr_merge(hw, hr); + + // samples + int i; + for (i=0; isamples[i]; + while ( bcf_hdr_id2int(hw, BCF_DT_SAMPLE, name)!=-1 ) + { + // there is a sample with the same name + if ( !force_samples ) error("Error: Duplicate sample names (%s), use --force-samples to proceed anyway.\n", name); + + // Resolve conflicting samples names. For example, replace: + // A + A with A,2:A + // A,2:A + A with A,2:A,2:2:A + + int len = strlen(name) + strlen(clash_prefix) + 1; + char *tmp = (char*) malloc(sizeof(char)*(len+1)); + sprintf(tmp,"%s:%s",clash_prefix,name); + free(rmme); + rmme = name = tmp; + } + bcf_hdr_add_sample(hw,name); + free(rmme); + } +} + +void debug_als(char **als, int nals) +{ + int k; for (k=0; k=lens[j] ) done = 1; + if ( als[j][lens[j]-i] != als[0][lens[0]-i] ) { done = 1; break; } + } + if ( done ) break; + i++; + } + if ( i>1 ) + { + i--; + als[0][lens[0]-i] = 0; + for (j=1; j0, + * 1->2, and 2->3. + */ +char **merge_alleles(char **a, int na, int *map, char **b, int *nb, int *mb) +{ + // reference allele never changes + map[0] = 0; + + int i,j; + int rla = !a[0][1] ? 1 : strlen(a[0]); + int rlb = !b[0][1] ? 1 : strlen(b[0]); + + // the most common case: same SNPs + if ( na==2 && *nb==2 && rla==1 && rlb==1 && a[1][0]==b[1][0] && !a[1][1] && !b[1][1] ) + { + map[1] = 1; + return b; + } + + // Sanity check: reference prefixes must be identical + if ( strncmp(a[0],b[0],rlarlb ) + { + for (i=0; i<*nb; i++) + { + if ( b[i][0]=='<' ) continue; // symbolic allele, do not modify + if ( b[i][0]=='*' ) continue; // overlapping deletion (*), do not modify + int l = strlen(b[i]); + b[i] = (char*) realloc(b[i],l+rla-rlb+1); + memcpy(b[i]+l,a[0]+rlb,rla-rlb+1); + } + } + + // now check if the $a alleles are present and if not add them + for (i=1; irla && a[i][0]!='<' && a[i][0]!='*' ) // $a alleles need expanding and not a symbolic allele or * + { + int l = strlen(a[i]); + ai = (char*) malloc(l+rlb-rla+1); + memcpy(ai,a[i],l); + memcpy(ai+l,b[0]+rla,rlb-rla+1); + const_ai = 0; + } + else + ai = a[i]; + + for (j=1; j<*nb; j++) + if ( !strcasecmp(ai,b[j]) ) break; + + if ( j<*nb ) // $b already has the same allele + { + map[i] = j; + if ( !const_ai ) free(ai); + continue; + } + // new allele + map[i] = *nb; + b[*nb] = const_ai ? strdup(ai) : ai; + (*nb)++; + } + return b; +} + +maux_t *maux_init(args_t *args) +{ + bcf_srs_t *files = args->files; + maux_t *ma = (maux_t*) calloc(1,sizeof(maux_t)); + ma->n = files->nreaders; + ma->files = files; + int i, n_smpl = 0; + for (i=0; in; i++) + n_smpl += bcf_hdr_nsamples(files->readers[i].header); + ma->nout_smpl = n_smpl; + assert( n_smpl==bcf_hdr_nsamples(args->out_hdr) ); + if ( args->do_gvcf ) + { + ma->gvcf = (gvcf_aux_t*) calloc(ma->n,sizeof(gvcf_aux_t)); // -Walloc-size-larger-than gives a harmless warning caused by signed integer ma->n + for (i=0; in; i++) + ma->gvcf[i].line = bcf_init1(); + } + ma->smpl_ploidy = (int*) calloc(n_smpl,sizeof(int)); + ma->smpl_nGsize = (int*) malloc(n_smpl*sizeof(int)); + ma->buf = (buffer_t*) calloc(ma->n,sizeof(buffer_t)); + for (i=0; in; i++) + ma->buf[i].rid = -1; + ma->str = (kstring_t*) calloc(n_smpl,sizeof(kstring_t)); + if ( args->local_alleles ) + { + ma->laa = (int32_t*)malloc(sizeof(*ma->laa)*ma->nout_smpl*(1+args->local_alleles)); + ma->pl2prob = (double*)malloc(PL2PROB_MAX*sizeof(*ma->pl2prob)); + for (i=0; ipl2prob[i] = pow(10,-0.1*i); + } + return ma; +} +void maux_destroy(maux_t *ma) +{ + int i,j; + for (i=0; inout_smpl; i++) free(ma->str[i].s); + free(ma->str); + free(ma->als_types); + for (i=0; imals; i++) + { + free(ma->als[i]); + ma->als[i] = NULL; + } + for (i=0; in; i++) // for each reader + { + for (j=0; jbuf[i].mrec; j++) // for each buffered line + free(ma->buf[i].rec[j].map); + free(ma->buf[i].rec); + } + free(ma->buf); + if ( ma->gvcf ) + { + for (i=0; in; i++) bcf_destroy(ma->gvcf[i].line); + free(ma->gvcf); + } + for (i=0; imAGR_info; i++) + free(ma->AGR_info[i].buf); + free(ma->agr_map); + free(ma->AGR_info); + if (ma->ntmp_arr) free(ma->tmp_arr); + if (ma->nfmt_map) free(ma->fmt_map); + free(ma->fmt_key); + // ma->inf freed in bcf_destroy1 + for (i=0; imals; i++) free(ma->als[i]); + if (ma->mout_als) free(ma->out_als); + free(ma->als); + free(ma->cnt); + free(ma->smpl_ploidy); + free(ma->smpl_nGsize); + free(ma->chr); + free(ma->laa); + free(ma->tmpi); + free(ma->k2k); + free(ma->tmpd); + free(ma->pl2prob); + free(ma); +} +void maux_expand1(buffer_t *buf, int size) +{ + if ( buf->mrec < size ) + { + hts_expand0(maux1_t,size,buf->mrec,buf->rec); + buf->mrec = size; + } +} +void maux_reset(maux_t *ma, int *rid_tab) +{ + int i,j; + for (i=0; in; i++) maux_expand1(&ma->buf[i],ma->files->readers[i].nbuffer+1); + for (i=0; imals; i++) + { + free(ma->als[i]); + ma->als[i] = NULL; + } + const char *chr = NULL; + ma->nals = 0; + ma->pos = -1; + for (i=0; in; i++) + { + if ( !bcf_sr_has_line(ma->files,i) ) continue; + bcf1_t *line = bcf_sr_get_line(ma->files,i); + bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i); + chr = bcf_seqname(hdr,line); + ma->pos = line->pos; + break; + } + int new_chr = 0; + if ( chr && (!ma->chr || strcmp(ma->chr,chr)) ) + { + free(ma->chr); + ma->chr = strdup(chr); + new_chr = 1; + } + for (i=0; in; i++) + { + bcf_hdr_t *hdr = bcf_sr_get_header(ma->files,i); + if (new_chr) + rid_tab[i] = bcf_hdr_name2id(hdr,chr); + + ma->buf[i].rid = rid_tab[i]; + ma->buf[i].beg = bcf_sr_has_line(ma->files,i) ? 0 : 1; + for (j=ma->buf[i].beg; j<=ma->files->readers[i].nbuffer; j++) + { + ma->buf[i].rec[j].skip = 0; + ma->buf[i].rec[j].var_types = 0; + bcf1_t *line = ma->files->readers[i].buffer[j]; + if ( line->rid!=ma->buf[i].rid || line->pos!=ma->pos ) break; + } + ma->buf[i].end = j; + ma->buf[i].cur = -1; + if ( ma->buf[i].beg < ma->buf[i].end ) + { + ma->buf[i].lines = ma->files->readers[i].buffer; + if ( ma->gvcf ) ma->gvcf[i].active = 0; // gvcf block cannot overlap with the next record + } + if ( new_chr && ma->gvcf ) ma->gvcf[i].active = 0; // make sure to close active gvcf block on new chr + } +} +void maux_debug(maux_t *ma, int ir, int ib) +{ + fprintf(bcftools_stdout, "[%d,%d]\t", ir,ib); + int i; + for (i=0; inals; i++) + { + fprintf(bcftools_stdout, " %s [%d]", ma->als[i], ma->cnt[i]); + } + fprintf(bcftools_stdout, "\n"); +} + +void merge_chrom2qual(args_t *args, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + + int i, ret; + khiter_t kitr; + strdict_t *tmph = args->tmph; + kh_clear(strdict, tmph); + kstring_t *tmps = &args->tmps; + tmps->l = 0; + + maux_t *ma = args->maux; + int *al_idxs = (int*) calloc(ma->nals,sizeof(int)); + bcf_float_set_missing(out->qual); + + // CHROM, POS, ID, QUAL + out->pos = -1; + for (i=0; inreaders; i++) + { + bcf1_t *line = maux_get_line(args, i); + if ( !line ) continue; + bcf_unpack(line, BCF_UN_ALL); + + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + + // not all maux alleles are always used, mark the ones we'll need + int j; + for (j=1; jn_allele; j++) + { + int irec = ma->buf[i].cur; + al_idxs[ ma->buf[i].rec[irec].map[j] ] = 1; + } + + // position + if ( out->pos==-1 ) + { + const char *chr = hdr->id[BCF_DT_CTG][line->rid].key; + out->rid = bcf_hdr_name2id(out_hdr, chr); + if ( strcmp(chr,out_hdr->id[BCF_DT_CTG][out->rid].key) ) error("Uh\n"); + out->pos = line->pos; + } + + // ID + if ( line->d.id[0]!='.' || line->d.id[1] ) + { + kitr = kh_get(strdict, tmph, line->d.id); + if ( kitr == kh_end(tmph) ) + { + if ( tmps->l ) kputc(';', tmps); + kputs(line->d.id, tmps); + kh_put(strdict, tmph, line->d.id, &ret); + } + } + + // set QUAL to the max qual value. Not exactly correct, but good enough for now + if ( !bcf_float_is_missing(line->qual) ) + { + if ( bcf_float_is_missing(out->qual) || out->qual < line->qual ) out->qual = line->qual; + } + } + + // set ID + if ( !tmps->l ) kputs(".", tmps); + bcf_update_id(out_hdr, out, tmps->s); + + // set alleles + ma->nout_als = 0; + for (i=1; inals; i++) + { + if ( !al_idxs[i] ) continue; + ma->nout_als++; + + // Adjust the indexes, the allele map could be created for multiple collapsed records, + // some of which might be unused for this output line + int ir, j; + for (ir=0; irnreaders; ir++) + { + ma->buf[ir].unkn_allele = 0; + bcf1_t *line = maux_get_line(args,ir); + if ( !line ) continue; + for (j=1; jn_allele; j++) + { + int irec = ma->buf[ir].cur; + if ( ma->buf[ir].rec[irec].map[j]==i ) ma->buf[ir].rec[irec].map[j] = ma->nout_als; + if ( bcf_has_variant_type(line,j,VCF_REF) && line->d.allele[j][0]=='<' ) ma->buf[ir].unkn_allele = j; + } + } + } + // Expand the arrays and realloc the alleles string. Note that all alleles are in a single allocated block. + ma->nout_als++; + hts_expand0(char*, ma->nout_als, ma->mout_als, ma->out_als); + int k = 0; + for (i=0; inals; i++) + if ( i==0 || al_idxs[i] ) ma->out_als[k++] = strdup(ma->als[i]); + if ( k!=ma->nout_als ) error("Error: could not merge alleles at %s:%"PRId64", sanity check failed: %d!=%d\n",bcf_seqname(out_hdr,out),out->pos+1,k,ma->nout_als); + normalize_alleles(ma->out_als, ma->nout_als); + bcf_update_alleles(out_hdr, out, (const char**) ma->out_als, ma->nout_als); + free(al_idxs); + for (i=0; inout_als; i++) free(ma->out_als[i]); +} + +void merge_filter(args_t *args, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + + int i, ret; + if ( args->filter_logic == FLT_LOGIC_REMOVE ) + { + for (i=0; inreaders; i++) + { + bcf1_t *line = maux_get_line(args, i); + if ( !line ) continue; + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + if ( bcf_has_filter(hdr, line, "PASS") ) break; + } + if ( inreaders ) + { + int flt_id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, "PASS"); + bcf_add_filter(out_hdr, out, flt_id); + return; + } + } + + khiter_t kitr; + strdict_t *tmph = args->tmph; + kh_clear(strdict, tmph); + + out->d.n_flt = 0; + for (i=0; inreaders; i++) + { + bcf1_t *line = maux_get_line(args, i); + if ( !line ) continue; + + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + + int k; + for (k=0; kd.n_flt; k++) + { + const char *flt = hdr->id[BCF_DT_ID][line->d.flt[k]].key; + kitr = kh_get(strdict, tmph, flt); + if ( kitr == kh_end(tmph) ) + { + int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, flt); + if ( id==-1 ) error("Error: The filter is not defined in the header: %s\n", flt); + hts_expand(int,out->d.n_flt+1,out->d.m_flt,out->d.flt); + out->d.flt[out->d.n_flt] = id; + out->d.n_flt++; + kh_put(strdict, tmph, flt, &ret); + } + } + } + // Check if PASS is not mixed with other filters + if ( out->d.n_flt>1 ) + { + int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, "PASS"); + for (i=0; id.n_flt; i++) + if ( out->d.flt[i]==id ) break; + if ( id.n_flt ) + { + out->d.n_flt--; + for (; id.n_flt; i++) out->d.flt[i] = out->d.flt[i+1]; + } + } +} + +static void bcf_info_set_id(bcf1_t *line, bcf_info_t *info, int id, kstring_t *tmp_str) +{ + uint8_t *ptr = info->vptr - info->vptr_off; + bcf_dec_typed_int1(ptr, &ptr); + + tmp_str->l = 0; + bcf_enc_int1(tmp_str, id); + + if ( tmp_str->l == ptr - info->vptr + info->vptr_off ) + { + // the new id is represented with the same number of bytes + memcpy(info->vptr - info->vptr_off, tmp_str->s, tmp_str->l); + return; + } + + kputsn_(ptr, info->vptr - ptr, tmp_str); + info->vptr_off = tmp_str->l; + kputsn_(info->vptr, info->len << bcf_type_shift[info->type], tmp_str); + + info->vptr = (uint8_t*) tmp_str->s + info->vptr_off; + tmp_str->s = NULL; + tmp_str->m = 0; + tmp_str->l = 0; +} + +/* + * copy_string_field() - copy a comma-separated field + * @param src: source string + * @param isrc: index of the field to copy + * @param src_len: length of source string (excluding the terminating \0) + * @param dst: destination kstring (must be initialized with missing values, e.g. as ".") + * @param idst: index of the destination field + */ +int copy_string_field(char *src, int isrc, int src_len, kstring_t *dst, int idst) +{ + int ith_src = 0, start_src = 0; // i-th field in src string + while ( ith_srcl ) + { + if ( dst->s[start_dst]==',' ) { ith_dst++; } + start_dst++; + } + if ( ith_dst!=idst ) return -2; + int end_dst = start_dst; + while ( end_dstl && dst->s[end_dst]!=',' ) end_dst++; + + if ( end_dst - start_dst>1 || dst->s[start_dst]!='.' ) return 0; // do not overwrite non-empty values + + // Now start_dst and end_dst are indexes to the destination memory area + // which needs to be replaced with nsrc_cpy + // source bytes, end_dst points just after. + int ndst_shift = nsrc_cpy - (end_dst - start_dst); + int ndst_move = dst->l - end_dst + 1; // how many bytes must be moved (including \0) + if ( ndst_shift ) + { + ks_resize(dst, dst->l + ndst_shift + 1); // plus \0 + memmove(dst->s+end_dst+ndst_shift, dst->s+end_dst, ndst_move); + } + memcpy(dst->s+start_dst, src+start_src, nsrc_cpy); + dst->l += ndst_shift; + return 0; +} + +static void merge_AGR_info_tag(bcf_hdr_t *hdr, bcf1_t *line, bcf_info_t *info, int len, maux1_t *als, AGR_info_t *agr) +{ + int i; + if ( !agr->nbuf ) + { + if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 || info->type==BCF_BT_FLOAT ) + { + agr->nbuf = 4 * agr->nvals; + hts_expand(uint8_t,agr->nbuf,agr->mbuf,agr->buf); + if ( info->type!=BCF_BT_FLOAT ) + { + int32_t *tmp = (int32_t*) agr->buf; + for (i=0; invals; i++) tmp[i] = bcf_int32_missing; + } + else + { + float *tmp = (float*) agr->buf; + for (i=0; invals; i++) bcf_float_set_missing(tmp[i]); + } + } + else if ( info->type==BCF_BT_CHAR ) + { + kstring_t tmp; tmp.l = 0; tmp.m = agr->mbuf; tmp.s = (char*)agr->buf; + kputc('.',&tmp); + for (i=1; invals; i++) kputs(",.",&tmp); + agr->mbuf = tmp.m; agr->nbuf = tmp.l; agr->buf = (uint8_t*)tmp.s; + } + else + error("Not ready for type [%d]: %s at %"PRId64"\n", info->type,agr->hdr_tag,(int64_t) line->pos+1); + } + + if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 || info->type==BCF_BT_FLOAT ) + { + if ( len==BCF_VL_A || len==BCF_VL_R ) + { + int ifrom = len==BCF_VL_A ? 1 : 0; + #define BRANCH(type_t, is_missing, is_vector_end, out_type_t) { \ + type_t *src = (type_t *) info->vptr; \ + out_type_t *tgt = (out_type_t *) agr->buf; \ + int iori, inew; \ + for (iori=ifrom; iorin_allele; iori++) \ + { \ + if ( is_vector_end ) break; \ + if ( is_missing ) continue; \ + inew = als->map[iori] - ifrom; \ + tgt[inew] = *src; \ + src++; \ + } \ + } + switch (info->type) { + case BCF_BT_INT8: BRANCH(int8_t, *src==bcf_int8_missing, *src==bcf_int8_vector_end, int); break; + case BCF_BT_INT16: BRANCH(int16_t, *src==bcf_int16_missing, *src==bcf_int16_vector_end, int); break; + case BCF_BT_INT32: BRANCH(int32_t, *src==bcf_int32_missing, *src==bcf_int32_vector_end, int); break; + case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(*src), bcf_float_is_vector_end(*src), float); break; + default: fprintf(bcftools_stderr,"TODO: %s:%d .. info->type=%d\n", __FILE__,__LINE__, info->type); bcftools_exit(1); + } + #undef BRANCH + } + else + { + #define BRANCH(type_t, is_missing, is_vector_end, out_type_t) { \ + type_t *src = (type_t *) info->vptr; \ + out_type_t *tgt = (out_type_t *) agr->buf; \ + int iori,jori, inew,jnew; \ + for (iori=0; iorin_allele; iori++) \ + { \ + inew = als->map[iori]; \ + for (jori=0; jori<=iori; jori++) \ + { \ + jnew = als->map[jori]; \ + int kori = iori*(iori+1)/2 + jori; \ + if ( is_vector_end ) break; \ + if ( is_missing ) continue; \ + int knew = inew>jnew ? inew*(inew+1)/2 + jnew : jnew*(jnew+1)/2 + inew; \ + tgt[knew] = src[kori]; \ + } \ + if ( jori<=iori ) break; \ + } \ + } + switch (info->type) { + case BCF_BT_INT8: BRANCH(int8_t, src[kori]==bcf_int8_missing, src[kori]==bcf_int8_vector_end, int); break; + case BCF_BT_INT16: BRANCH(int16_t, src[kori]==bcf_int16_missing, src[kori]==bcf_int16_vector_end, int); break; + case BCF_BT_INT32: BRANCH(int32_t, src[kori]==bcf_int32_missing, src[kori]==bcf_int32_vector_end, int); break; + case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(src[kori]), bcf_float_is_vector_end(src[kori]), float); break; + default: fprintf(bcftools_stderr,"TODO: %s:%d .. info->type=%d\n", __FILE__,__LINE__, info->type); bcftools_exit(1); + } + #undef BRANCH + } + } + else + { + kstring_t tmp; tmp.l = agr->nbuf; tmp.m = agr->mbuf; tmp.s = (char*)agr->buf; + if ( len==BCF_VL_A || len==BCF_VL_R ) + { + int iori, ifrom = len==BCF_VL_A ? 1 : 0; + for (iori=ifrom; iorin_allele; iori++) + { + int ret = copy_string_field((char*)info->vptr, iori-ifrom, info->len, &tmp, als->map[iori]-ifrom); + if ( ret ) + error("Error at %s:%"PRId64": wrong number of fields in %s?\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,agr->hdr_tag); + } + } + else + { + int iori,jori, inew,jnew; + for (iori=0; iorin_allele; iori++) + { + inew = als->map[iori]; + for (jori=0; jori<=iori; jori++) + { + jnew = als->map[jori]; + int kori = iori*(iori+1)/2 + jori; + int knew = bcf_alleles2gt(inew,jnew); + int ret = copy_string_field((char*)info->vptr, kori, info->len, &tmp, knew); + if ( ret ) + error("Error at %s:%"PRId64": wrong number of fields in %s?\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,agr->hdr_tag); + } + } + } + agr->mbuf = tmp.m; agr->nbuf = tmp.l; agr->buf = (uint8_t*)tmp.s; + } +} + +void merge_info(args_t *args, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + + int i, j, ret; + khiter_t kitr; + strdict_t *tmph = args->tmph; + kh_clear(strdict, tmph); + + maux_t *ma = args->maux; + ma->nAGR_info = 0; + out->n_info = 0; + info_rules_reset(args); + for (i=0; inreaders; i++) + { + bcf1_t *line = maux_get_line(args,i); + if ( !line ) continue; + int irec = ma->buf[i].cur; + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + for (j=0; jn_info; j++) + { + bcf_info_t *inf = &line->d.info[j]; + + const char *key = hdr->id[BCF_DT_ID][inf->key].key; + // AC and AN are done in merge_format() after genotypes are done + if (!args->keep_AC_AN && + (key[0] == 'A' + && (key[1] == 'C' || key[1] == 'N') + && key[2] == 0)) + continue; + + int id = bcf_hdr_id2int(out_hdr, BCF_DT_ID, key); + if ( id==-1 ) error("Error: The INFO field is not defined in the header: %s\n", key); + + kitr = kh_get(strdict, tmph, key); // have we seen the tag in one of the readers? + int len = bcf_hdr_id2length(hdr,BCF_HL_INFO,inf->key); + if ( args->nrules ) + { + info_rule_t *rule = (info_rule_t*) bsearch(key, args->rules, args->nrules, sizeof(*args->rules), info_rules_comp_key); + if ( rule ) + { + maux1_t *als = ( len==BCF_VL_A || len==BCF_VL_G || len==BCF_VL_R ) ? &ma->buf[i].rec[irec] : NULL; + if ( info_rules_add_values(args, hdr, line, rule, als, len) ) continue; + } + } + + // Todo: Number=AGR tags should use the newer info_rules_* functions (info_rules_merge_first to be added) + // and merge_AGR_info_tag to be made obsolete. + if ( len==BCF_VL_A || len==BCF_VL_G || len==BCF_VL_R ) // Number=R,G,A requires special treatment + { + if ( kitr == kh_end(tmph) ) + { + // seeing this key for the first time + ma->nAGR_info++; + hts_expand0(AGR_info_t,ma->nAGR_info,ma->mAGR_info,ma->AGR_info); + kitr = kh_put(strdict, tmph, key, &ret); + kh_val(tmph,kitr) = ma->nAGR_info - 1; + ma->AGR_info[ma->nAGR_info-1].hdr_tag = key; + ma->AGR_info[ma->nAGR_info-1].type = bcf_hdr_id2type(hdr,BCF_HL_INFO,inf->key); + ma->AGR_info[ma->nAGR_info-1].nbuf = 0; // size of the buffer + switch (len) + { + case BCF_VL_A: ma->AGR_info[ma->nAGR_info-1].nvals = ma->nout_als - 1; break; + case BCF_VL_G: ma->AGR_info[ma->nAGR_info-1].nvals = bcf_alleles2gt(ma->nout_als-1,ma->nout_als-1)+1; break; + case BCF_VL_R: ma->AGR_info[ma->nAGR_info-1].nvals = ma->nout_als; break; + } + } + kitr = kh_get(strdict, tmph, key); + int idx = kh_val(tmph, kitr); + if ( idx<0 ) error("Error occurred while processing INFO tag \"%s\" at %s:%"PRId64"\n", key,bcf_seqname(hdr,line),(int64_t) line->pos+1); + merge_AGR_info_tag(hdr, line,inf,len,&ma->buf[i].rec[irec],&ma->AGR_info[idx]); + continue; + } + + if ( kitr == kh_end(tmph) ) + { + // Seeing this key for the first time. Although quite hacky, + // this is faster than anything else given the data structures.. + + hts_expand0(bcf_info_t,out->n_info+1,out->d.m_info,out->d.info); + out->d.info[out->n_info].key = id; + out->d.info[out->n_info].type = inf->type; + out->d.info[out->n_info].len = inf->len; + out->d.info[out->n_info].v1.i = inf->v1.i; + out->d.info[out->n_info].v1.f = inf->v1.f; + out->d.info[out->n_info].vptr_off = inf->vptr_off; + out->d.info[out->n_info].vptr_len = inf->vptr_len; + out->d.info[out->n_info].vptr_free = 1; + out->d.info[out->n_info].vptr = (uint8_t*) malloc(inf->vptr_len+inf->vptr_off); + memcpy(out->d.info[out->n_info].vptr,inf->vptr-inf->vptr_off, inf->vptr_len+inf->vptr_off); + out->d.info[out->n_info].vptr += inf->vptr_off; + if ( (args->output_type & FT_BCF) && id!=bcf_hdr_id2int(hdr, BCF_DT_ID, key) ) + bcf_info_set_id(out, &out->d.info[out->n_info], id, &args->tmps); + out->d.shared_dirty |= BCF1_DIRTY_INF; + out->n_info++; + kitr = kh_put(strdict, tmph, key, &ret); + kh_val(tmph,kitr) = -(out->n_info-1); // arbitrary negative value + } + } + } + for (i=0; inrules; i++) + args->rules[i].merger(args->out_hdr, out, &args->rules[i]); + for (i=0; inAGR_info; i++) + { + AGR_info_t *agr = &ma->AGR_info[i]; + bcf_update_info(out_hdr,out,agr->hdr_tag,agr->buf,agr->nvals,agr->type); + } +} + +void update_AN_AC(bcf_hdr_t *hdr, bcf1_t *line) +{ + int32_t an = 0, *tmp = (int32_t*) malloc(sizeof(int)*line->n_allele); + int ret = bcf_calc_ac(hdr, line, tmp, BCF_UN_FMT); + if ( ret>0 ) + { + int i; + for (i=0; in_allele; i++) an += tmp[i]; + bcf_update_info_int32(hdr, line, "AN", &an, 1); + bcf_update_info_int32(hdr, line, "AC", tmp+1, line->n_allele-1); + } + free(tmp); +} + +static inline int max_used_gt_ploidy(bcf_fmt_t *fmt, int nsmpl) +{ + int i,j, max_ploidy = 0; + + #define BRANCH(type_t, vector_end) { \ + type_t *ptr = (type_t*) fmt->p; \ + for (i=0; in; j++) \ + if ( ptr[j]==vector_end ) break; \ + if ( j==fmt->n ) \ + { \ + /* all fields were used */ \ + if ( max_ploidy < j ) max_ploidy = j; \ + break; \ + } \ + if ( max_ploidy < j ) max_ploidy = j; \ + ptr += fmt->n; \ + } \ + } + switch (fmt->type) + { + case BCF_BT_INT8: BRANCH(int8_t, bcf_int8_vector_end); break; + case BCF_BT_INT16: BRANCH(int16_t, bcf_int16_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, bcf_int32_vector_end); break; + default: error("Unexpected case: %d\n", fmt->type); + } + #undef BRANCH + return max_ploidy; +} + +// Sets ma->laa to local indexes relevant for each sample or missing/vector_end. +// The indexes are with respect to the source indexes and must be translated as +// the very last step. +void init_local_alleles(args_t *args, bcf1_t *out, int ifmt_PL) +{ + bcf_srs_t *files = args->files; + maux_t *ma = args->maux; + int i,j,k,l, ismpl = 0, nlaa = 0; + static int warned = 0; + + hts_expand(double,out->n_allele,ma->ntmpd,ma->tmpd); // allele probabilities + hts_expand(int,out->n_allele,ma->ntmpi,ma->tmpi); // indexes of the sorted probabilities + + // Let map[] be the mapping from src to output idx. Then k2k[] is mapping from src allele idxs to src allele idxs + // reordered so that if in_allele,ma->nk2k,ma->k2k); + + // Determine local alleles: either take all that are present in the reader or use PL to determine the best + // subset for each sample. The alleles must be listed in the order of the alleles in the output file. + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = ma->fmt_map[files->nreaders*ifmt_PL+i]; + bcf1_t *line = maux_get_line(args, i); + int nsmpl = bcf_hdr_nsamples(hdr); + if ( line ) + { + if ( nlaa < line->n_allele - 1 ) + nlaa = line->n_allele - 1 <= args->local_alleles ? line->n_allele - 1 : args->local_alleles; + + for (j=0; jn_allele; j++) ma->k2k[j] = j; + + if ( line->n_allele <= args->local_alleles + 1 ) + { + // sort to the output order, insertion sort, ascending + int *map = ma->buf[i].rec[ma->buf[i].cur].map; + int *k2k = ma->k2k; + int tmp; + for (k=1; kn_allele; k++) + for (l=k; l>0 && map[k2k[l]] < map[k2k[l-1]]; l--) + tmp = k2k[l], k2k[l] = k2k[l-1], k2k[l-1] = tmp; + + // fewer than the allowed number of alleles, use all alleles from this file + for (j=0; jlaa + (1+args->local_alleles)*ismpl; + for (k=0; kn_allele; k++) ptr[k] = k2k[k]; + for (; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end; + ismpl++; + } + continue; + } + } + if ( !line || !fmt_ori ) + { + // no values, fill in missing values + for (j=0; jlaa + (1+args->local_alleles)*ismpl; + ptr[0] = bcf_int32_missing; + for (k=1; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end; + ismpl++; + } + continue; + } + + // there are more alternate alleles in the input files than is allowed on output, need to subset + if ( ifmt_PL==-1 ) + { + if ( !warned ) + fprintf(bcftools_stderr,"Warning: local alleles are determined from FORMAT/PL but the tag is missing, cannot apply --local-alleles\n"); + warned = 1; + ma->nlaa = 0; + return; + } + + if ( !IS_VL_G(hdr, fmt_ori->id) ) error("FORMAT/PL must be defined as Number=G\n"); + if ( 2*fmt_ori->n != line->n_allele*(line->n_allele+1) ) error("Todo: haploid PL to LPL\n"); + + int *map = ma->buf[i].rec[ma->buf[i].cur].map; + double *allele_prob = ma->tmpd; + int *idx = ma->tmpi; + #define BRANCH(src_type_t, src_is_missing, src_is_vector_end, pl2prob_idx) { \ + src_type_t *src = (src_type_t*) fmt_ori->p; \ + for (j=0; jn_allele; k++) allele_prob[k] = 0; \ + for (k=0; kn_allele; k++) \ + for (l=0; l<=k; l++) \ + { \ + if ( src_is_missing || src_is_vector_end ) { src++; continue; } \ + double prob = ma->pl2prob[pl2prob_idx]; \ + allele_prob[k] += prob; \ + allele_prob[l] += prob; \ + src++; \ + } \ + /* insertion sort by allele probability, descending order, with the twist that REF (idx=0) always comes first */ \ + allele_prob++; idx[0] = -1; idx++; /* keep REF first */ \ + int si,sj,tmp; \ + for (si=0; sin_allele-1; si++) idx[si] = si; \ + for (si=1; sin_allele-1; si++) \ + for (sj=si; sj>0 && allele_prob[idx[sj]] > allele_prob[idx[sj-1]]; sj--) \ + tmp = idx[sj], idx[sj] = idx[sj-1], idx[sj-1] = tmp; \ + /*for debugging only: test order*/ \ + for (si=1; sin_allele-1; si++) \ + assert( allele_prob[idx[si-1]] >= allele_prob[idx[si]] ); \ + allele_prob--; idx--; /* this was to keep REF first */ \ + int32_t *ptr = ma->laa + (1+args->local_alleles)*ismpl; \ + ptr[0] = 0; \ + for (k=1; k<=args->local_alleles && kn_allele; k++) ptr[k] = idx[k]+1; \ + int kmax = k; \ + for (; k<=args->local_alleles; k++) ptr[k] = bcf_int32_vector_end; \ + /* insertion sort by indexes to the output order, ascending */ \ + for (k=1; k0 && map[ptr[l]] < map[ptr[l-1]]; l--) \ + tmp = ptr[l], ptr[l] = ptr[l-1], ptr[l-1] = tmp; \ + ismpl++; \ + } \ + } + switch (fmt_ori->type) + { + case BCF_BT_INT8: BRANCH( int8_t, *src==bcf_int8_missing, *src==bcf_int8_vector_end, *src); break; + case BCF_BT_INT16: BRANCH(int16_t, *src==bcf_int16_missing, *src==bcf_int16_vector_end, *src>=0 && *src=0 && *srctype); + } + #undef BRANCH + } + ma->nlaa = nlaa; +} + +void update_local_alleles(args_t *args, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + maux_t *ma = args->maux; + int i,j,k,ismpl=0,nsamples = bcf_hdr_nsamples(args->out_hdr); + for (i=0; inreaders; i++) + { + int irec = ma->buf[i].cur; + bcf_sr_t *reader = &files->readers[i]; + int nsmpl = bcf_hdr_nsamples(reader->header); + for (k=0; klaa + ismpl*(1+args->local_alleles); + int32_t *dst = ma->laa + ismpl*ma->nlaa; + j = 0; + if ( irec>=0 ) + { + for (; jnlaa; j++) + { + if ( src[j+1]==bcf_int32_missing ) dst[j] = bcf_int32_missing; + else if ( src[j+1]==bcf_int32_vector_end ) break; + else + dst[j] = ma->buf[i].rec[irec].map[src[j+1]]; + } + } + if ( j==0 ) dst[j++] = bcf_int32_missing; + for (; jnlaa; j++) src[j] = bcf_int32_vector_end; + ismpl++; + } + } + bcf_update_format_int32(args->out_hdr, out, "LAA", ma->laa, nsamples*ma->nlaa); +} + +void merge_GT(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + maux_t *ma = args->maux; + int i, ismpl = 0, nsamples = bcf_hdr_nsamples(out_hdr); + static int warned = 0; + + int nsize = 0; + for (i=0; inreaders; i++) + { + bcf_fmt_t *fmt = fmt_map[i]; + if ( !fmt ) continue; + int pld = max_used_gt_ploidy(fmt_map[i], bcf_hdr_nsamples(bcf_sr_get_header(args->files,i))); + if ( nsize < pld ) nsize = pld; + } + if ( nsize==0 ) nsize = 1; + + size_t msize = sizeof(int32_t)*nsize*nsamples; + if ( msize > 2147483647 ) + { + if ( !warned ) fprintf(bcftools_stderr,"Warning: Too many genotypes at %s:%"PRId64", requires %zu bytes, skipping.\n", bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize); + warned = 1; + return; + } + if ( ma->ntmp_arr < msize ) + { + ma->tmp_arr = realloc(ma->tmp_arr, msize); + if ( !ma->tmp_arr ) error("Could not allocate %zu bytes\n",msize); + ma->ntmp_arr = msize; + } + memset(ma->smpl_ploidy,0,nsamples*sizeof(int)); + + int default_gt = args->missing_to_ref ? bcf_gt_unphased(0) : bcf_gt_missing; + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = fmt_map[i]; + int32_t *tmp = (int32_t *) ma->tmp_arr + ismpl*nsize; + int irec = ma->buf[i].cur; + + int j,k; + if ( !fmt_ori ) + { + // missing values: assume maximum ploidy + for (j=0; jsmpl_ploidy[ismpl+j]++; } + tmp += nsize; + } + ismpl += bcf_hdr_nsamples(hdr); + continue; + } + + #define BRANCH(type_t, vector_end) { \ + type_t *p_ori = (type_t*) fmt_ori->p; \ + if ( !ma->buf[i].rec[irec].als_differ ) \ + { \ + /* the allele numbering is unchanged */ \ + for (j=0; jn; k++) \ + { \ + if ( p_ori[k]==vector_end ) break; /* smaller ploidy */ \ + ma->smpl_ploidy[ismpl+j]++; \ + if ( bcf_gt_is_missing(p_ori[k]) ) tmp[k] = 0; /* missing allele */ \ + else tmp[k] = p_ori[k]; \ + } \ + for (; kn; \ + } \ + ismpl += bcf_hdr_nsamples(hdr); \ + continue; \ + } \ + /* allele numbering needs to be changed */ \ + for (j=0; jn; k++) \ + { \ + if ( p_ori[k]==vector_end ) break; /* smaller ploidy */ \ + ma->smpl_ploidy[ismpl+j]++; \ + if ( bcf_gt_is_missing(p_ori[k]) ) tmp[k] = 0; /* missing allele */ \ + else \ + { \ + int al = (p_ori[k]>>1) - 1; \ + al = al<=0 ? al + 1 : ma->buf[i].rec[irec].map[al] + 1; \ + tmp[k] = (al << 1) | ((p_ori[k])&1); \ + } \ + } \ + for (; kn; \ + } \ + ismpl += bcf_hdr_nsamples(hdr); \ + } + switch (fmt_ori->type) + { + case BCF_BT_INT8: BRANCH(int8_t, bcf_int8_vector_end); break; + case BCF_BT_INT16: BRANCH(int16_t, bcf_int16_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, bcf_int32_vector_end); break; + default: error("Unexpected case: %d\n", fmt_ori->type); + } + #undef BRANCH + } + bcf_update_format_int32(out_hdr, out, "GT", (int32_t*)ma->tmp_arr, nsamples*nsize); +} + +void merge_format_string(args_t *args, const char *key, bcf_fmt_t **fmt_map, bcf1_t *out, int length, int nsize) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + maux_t *ma = args->maux; + int i,j, nsamples = bcf_hdr_nsamples(out_hdr); + static int warned = 0; + + // initialize empty strings, a dot for each value, e.g. ".,.,." + int nmax = 0; + for (i=0; istr[i]; + if ( length==BCF_VL_FIXED || length==BCF_VL_VAR ) + { + str->l = 1; + ks_resize(str, str->l+1); + str->s[0] = '.'; + } + else + { + str->l = nsize*2 - 1; + ks_resize(str, str->l+1); + str->s[0] = '.'; + for (j=1; js[j*2-1] = ',', str->s[j*2] = '.'; + } + str->s[str->l] = 0; + if ( nmax < str->l ) nmax = str->l; + } + + // fill in values for each sample + int ismpl = 0; + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = fmt_map[i]; + if ( !fmt_ori ) + { + // the field is not present in this file + ismpl += bcf_hdr_nsamples(hdr); + continue; + } + + bcf1_t *line = maux_get_line(args, i); + int irec = ma->buf[i].cur; + char *src = (char*) fmt_ori->p; + + if ( length==BCF_VL_FIXED || length==BCF_VL_VAR || (line->n_allele==out->n_allele && !ma->buf[i].rec[irec].als_differ) ) + { + // alleles unchanged, copy over + for (j=0; jstr[ismpl++]; + str->l = 0; + kputsn(src, fmt_ori->n, str); + if ( nmax < str->l ) nmax = str->l; + src += fmt_ori->n; + } + continue; + } + // NB, what is below is not the fastest way, copy_string_field() keeps + // finding the indexes repeatedly at multiallelic sites + if ( length==BCF_VL_A || length==BCF_VL_R ) + { + int ifrom = length==BCF_VL_A ? 1 : 0; + for (j=0; jstr[ismpl++]; + int iori,inew; + for (iori=ifrom; iorin_allele; iori++) + { + inew = ma->buf[i].rec[irec].map[iori] - ifrom; + int ret = copy_string_field(src, iori - ifrom, fmt_ori->size, str, inew); + if ( ret<-1 ) error("[E::%s] fixme: internal error at %s:%"PRId64" .. %d\n",__func__,bcf_seqname(hdr,line),(int64_t) line->pos+1,ret); + } + if ( nmax < str->l ) nmax = str->l; + src += fmt_ori->size; + } + continue; + } + assert( length==BCF_VL_G ); + error("[E::%s] Merging of Number=G FORMAT strings (in your case FORMAT/%s) is not supported yet, sorry!\n" + "Please open an issue on github if this feature is essential for you. However, note that using FORMAT strings is not\n" + "a good idea in general - it is slow to parse and does not compress well, it is better to use integer codes instead.\n" + "If you don't really need it, use `bcftools annotate -x` to remove the annotation before merging.\n", __func__,key); + } + // update the record + size_t msize = nsamples*nmax; + if ( msize > 2147483647 ) + { + if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize); + warned = 1; + return; + } + if ( ma->ntmp_arr < msize ) + { + ma->tmp_arr = realloc(ma->tmp_arr, msize); + if ( !ma->tmp_arr ) error("Could not allocate %zu bytes\n",msize); + ma->ntmp_arr = msize; + } + char *tgt = (char*) ma->tmp_arr; + for (i=0; istr[i].s, ma->str[i].l); + if ( ma->str[i].l < nmax ) memset(tgt + ma->str[i].l, 0, nmax - ma->str[i].l); + tgt += nmax; + } + bcf_update_format_char(out_hdr, out, key, (float*)ma->tmp_arr, nsamples*nmax); +} + +// Note: only diploid Number=G tags only for now +void merge_localized_numberG_format_field(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out, int irdr) +{ + int i,j,k, nsamples = bcf_hdr_nsamples(args->out_hdr); + bcf_srs_t *files = args->files; + maux_t *ma = args->maux; + bcf_fmt_t *fmt = fmt_map[irdr]; + const char *key = files->readers[irdr].header->id[BCF_DT_ID][fmt_map[irdr]->id].key; + size_t nsize = (ma->nlaa+1)*(ma->nlaa+2)/2; // max number of Number=G localized fields + size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t); + msize *= nsamples*nsize; + if ( msize > 2147483647 ) + { + static int warned = 0; + if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,msize); + warned = 1; + return; + } + if ( ma->ntmp_arr < msize ) + { + ma->tmp_arr = realloc(ma->tmp_arr, msize); + if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key); + ma->ntmp_arr = msize; + } + int ismpl = 0; + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = fmt_map[i]; + bcf1_t *line = maux_get_line(args, i); + int nsmpl = bcf_hdr_nsamples(hdr); + + if ( !fmt_ori ) + { + // fill missing values + #define BRANCH(tgt_type_t, tgt_set_missing, tgt_set_vector_end) { \ + for (j=0; jtmp_arr + ismpl*nsize; \ + tgt_set_missing; \ + for (k=1; ktype) + { + case BCF_BT_INT8: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT16: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_FLOAT: BRANCH(float, bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break; + default: error("Unexpected case: %d, %s\n", fmt->type, key); + } + #undef BRANCH + continue; + } + if ( 2*fmt_ori->n!=line->n_allele*(line->n_allele+1) ) error("Todo: localization of missing or haploid Number=G tags\n"); + + // localize + #define BRANCH(tgt_type_t, src_type_t, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \ + for (j=0; jp + j*fmt_ori->n; \ + tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \ + int *laa = ma->laa + (1+args->local_alleles)*ismpl; \ + int ii,ij,tgt_idx = 0; \ + for (ii=0; ii<=ma->nlaa; ii++) \ + { \ + if ( laa[ii]==bcf_int32_missing || laa[ii]==bcf_int32_vector_end ) break; \ + for (ij=0; ij<=ii; ij++) \ + { \ + int src_idx = bcf_alleles2gt(laa[ii],laa[ij]); \ + if ( src_is_missing ) tgt_set_missing; \ + else if ( src_is_vector_end ) break; \ + else tgt[tgt_idx] = src[src_idx]; \ + tgt_idx++; \ + } \ + } \ + if ( !tgt_idx ) { tgt_set_missing; tgt_idx++; } \ + for (; tgt_idxtype) + { + case BCF_BT_INT8: BRANCH(int32_t, int8_t, src[src_idx]==bcf_int8_missing, src[src_idx]==bcf_int8_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_INT16: BRANCH(int32_t, int16_t, src[src_idx]==bcf_int16_missing, src[src_idx]==bcf_int16_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, int32_t, src[src_idx]==bcf_int32_missing, src[src_idx]==bcf_int32_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_FLOAT: BRANCH(float, float, bcf_float_is_missing(src[src_idx]), bcf_float_is_vector_end(src[src_idx]), bcf_float_set_missing(tgt[tgt_idx]), bcf_float_set_vector_end(tgt[tgt_idx])); break; + default: error("Unexpected case: %d, %s\n", fmt_ori->type, key); + } + #undef BRANCH + } + args->tmps.l = 0; + kputc('L',&args->tmps); + kputs(key,&args->tmps); + if ( fmt_map[irdr]->type==BCF_BT_FLOAT ) + bcf_update_format_float(args->out_hdr, out, args->tmps.s, (float*)ma->tmp_arr, nsamples*nsize); + else + bcf_update_format_int32(args->out_hdr, out, args->tmps.s, (int32_t*)ma->tmp_arr, nsamples*nsize); + ma->laa_dirty = 1; +} +void merge_localized_numberAR_format_field(args_t *args, bcf_fmt_t **fmt_map, bcf1_t *out, int irdr) +{ + int i,j,k, nsamples = bcf_hdr_nsamples(args->out_hdr); + bcf_srs_t *files = args->files; + maux_t *ma = args->maux; + bcf_fmt_t *fmt = fmt_map[irdr]; + const char *key = files->readers[irdr].header->id[BCF_DT_ID][fmt->id].key; + size_t nsize = IS_VL_R(files->readers[irdr].header, fmt->id) ? ma->nlaa + 1 : ma->nlaa; + size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t); + msize *= nsamples*nsize; + if ( msize > 2147483647 ) + { + static int warned = 0; + if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,msize); + warned = 1; + return; + } + if ( ma->ntmp_arr < msize ) + { + ma->tmp_arr = realloc(ma->tmp_arr, msize); + if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key); + ma->ntmp_arr = msize; + } + int ismpl = 0, ibeg = IS_VL_R(files->readers[irdr].header, fmt->id) ? 0 : 1;; + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = fmt_map[i]; + int nsmpl = bcf_hdr_nsamples(hdr); + + if ( !fmt_ori ) + { + // fill missing values + #define BRANCH(tgt_type_t, tgt_set_missing, tgt_set_vector_end) { \ + for (j=0; jtmp_arr + ismpl*nsize; \ + tgt_set_missing; \ + for (k=1; ktype) + { + case BCF_BT_INT8: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT16: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_FLOAT: BRANCH(float, bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break; + default: error("Unexpected case: %d, %s\n", fmt->type, key); + } + #undef BRANCH + continue; + } + + // localize + #define BRANCH(tgt_type_t, src_type_t, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \ + for (j=0; jp + j*fmt_ori->n; \ + tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \ + int *laa = ma->laa + (1+args->local_alleles)*ismpl; \ + int ii,tgt_idx = 0; \ + for (ii=ibeg; ii<=ma->nlaa; ii++) \ + { \ + if ( laa[ii]==bcf_int32_missing || laa[ii]==bcf_int32_vector_end ) break; \ + int src_idx = laa[ii] - ibeg; \ + if ( src_is_missing ) tgt_set_missing; \ + else if ( src_is_vector_end ) break; \ + else tgt[tgt_idx] = src[src_idx]; \ + tgt_idx++; \ + } \ + if ( !tgt_idx ) { tgt_set_missing; tgt_idx++; } \ + for (; tgt_idxtype) + { + case BCF_BT_INT8: BRANCH(int32_t, int8_t, src[src_idx]==bcf_int8_missing, src[src_idx]==bcf_int8_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_INT16: BRANCH(int32_t, int16_t, src[src_idx]==bcf_int16_missing, src[src_idx]==bcf_int16_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, int32_t, src[src_idx]==bcf_int32_missing, src[src_idx]==bcf_int32_vector_end, tgt[tgt_idx]=bcf_int32_missing, tgt[tgt_idx]=bcf_int32_vector_end); break; + case BCF_BT_FLOAT: BRANCH(float, float, bcf_float_is_missing(src[src_idx]), bcf_float_is_vector_end(src[src_idx]), bcf_float_set_missing(tgt[tgt_idx]), bcf_float_set_vector_end(tgt[tgt_idx])); break; + default: error("Unexpected case: %d, %s\n", fmt_ori->type, key); + } + #undef BRANCH + } + args->tmps.l = 0; + kputc('L',&args->tmps); + kputs(key,&args->tmps); + if ( fmt_map[irdr]->type==BCF_BT_FLOAT ) + bcf_update_format_float(args->out_hdr, out, args->tmps.s, (float*)ma->tmp_arr, nsamples*nsize); + else + bcf_update_format_int32(args->out_hdr, out, args->tmps.s, (int32_t*)ma->tmp_arr, nsamples*nsize); + ma->laa_dirty = 1; +} +void merge_format_field(args_t *args, bcf_fmt_t **fmt_map, missing_rule_t *mrule, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + maux_t *ma = args->maux; + int i, ismpl = 0, nsamples = bcf_hdr_nsamples(out_hdr); + static int warned = 0; + + const char *key = NULL; + size_t nsize = 0, length = BCF_VL_FIXED; + int type = -1; + for (i=0; inreaders; i++) + { + if ( !maux_get_line(args,i) ) continue; + if ( !fmt_map[i] ) continue; + if ( !key ) key = files->readers[i].header->id[BCF_DT_ID][fmt_map[i]->id].key; + type = fmt_map[i]->type; + if ( IS_VL_G(files->readers[i].header, fmt_map[i]->id) ) + { + length = BCF_VL_G; + nsize = out->n_allele*(out->n_allele + 1)/2; + break; + } + if ( IS_VL_A(files->readers[i].header, fmt_map[i]->id) ) + { + length = BCF_VL_A; + nsize = out->n_allele - 1; + break; + } + if ( IS_VL_R(files->readers[i].header, fmt_map[i]->id) ) + { + length = BCF_VL_R; + nsize = out->n_allele; + break; + } + if ( fmt_map[i]->n > nsize ) nsize = fmt_map[i]->n; + } + if ( ma->nlaa && length!=BCF_VL_FIXED ) + { + if ( length==BCF_VL_G ) merge_localized_numberG_format_field(args,fmt_map,out,i); + else if ( length==BCF_VL_A || length==BCF_VL_R ) merge_localized_numberAR_format_field(args,fmt_map,out,i); + return; + } + + if ( type==BCF_BT_CHAR ) + { + merge_format_string(args, key, fmt_map, out, length, nsize); + return; + } + + size_t msize = sizeof(float)>sizeof(int32_t) ? sizeof(float) : sizeof(int32_t); + msize *= nsamples*nsize; + if ( msize > 2147483647 ) + { + if ( !warned ) fprintf(bcftools_stderr,"Warning: The row size is too big for FORMAT/%s at %s:%"PRId64", requires %zu bytes, skipping.\n", key,bcf_seqname(out_hdr,out),(int64_t) out->pos+1,msize); + warned = 1; + return; + } + if ( ma->ntmp_arr < msize ) + { + ma->tmp_arr = realloc(ma->tmp_arr, msize); + if ( !ma->tmp_arr ) error("Failed to allocate %zu bytes at %s:%"PRId64" for FORMAT/%s\n", msize,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,key); + ma->ntmp_arr = msize; + } + + // Fill the temp array for all samples by collecting values from all files + for (i=0; inreaders; i++) + { + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + bcf_fmt_t *fmt_ori = fmt_map[i]; + bcf1_t *line = maux_get_line(args, i); + int irec = ma->buf[i].cur; + + if ( fmt_ori ) + { + type = fmt_ori->type; + int nals_ori = line->n_allele; + if ( length==BCF_VL_G ) + { + // if all fields are missing then n==1 is valid + if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori*(nals_ori+1)/2 && fmt_map[i]->n != nals_ori ) + error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=G, but found\n" + "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n", + key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori); + } + else if ( length==BCF_VL_A ) + { + if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori-1 ) + error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=A, but found\n" + "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n", + key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori); + } + else if ( length==BCF_VL_R ) + { + if ( fmt_ori->n!=1 && fmt_ori->n != nals_ori ) + error("Incorrect number of FORMAT/%s values at %s:%"PRId64", cannot merge. The tag is defined as Number=R, but found\n" + "%d values and %d alleles. See also http://samtools.github.io/bcftools/howtos/FAQ.html#incorrect-nfields\n", + key,bcf_seqname(args->out_hdr,out),(int64_t) out->pos+1,fmt_ori->n,nals_ori); + } + } + + // set the values + #define BRANCH(tgt_type_t, src_type_t, src_is_missing, src_is_vector_end, tgt_set_missing, tgt_set_vector_end) { \ + int j, l, k; \ + tgt_type_t *tgt = (tgt_type_t *) ma->tmp_arr + ismpl*nsize; \ + if ( !fmt_ori ) \ + { \ + /* the field is not present in this file, set missing values */ \ + for (j=0; jp; \ + if ( (length!=BCF_VL_G && length!=BCF_VL_A && length!=BCF_VL_R) || (line->n_allele==out->n_allele && !ma->buf[i].rec[irec].als_differ) ) \ + { \ + /* alleles unchanged, copy over */ \ + for (j=0; jn; l++) \ + { \ + if ( src_is_vector_end ) break; \ + else if ( src_is_missing ) tgt_set_missing; \ + else *tgt = *src; \ + tgt++; src++; \ + } \ + for (k=l; kn - l; \ + } \ + ismpl += bcf_hdr_nsamples(hdr); \ + continue; \ + } \ + /* allele numbering needs to be changed */ \ + if ( length==BCF_VL_G ) \ + { \ + /* Number=G tags */ \ + for (j=0; jtmp_arr + (ismpl+j)*nsize; \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n; \ + if ( (src_is_missing && fmt_ori->n==1) || (++src && src_is_vector_end) ) \ + { \ + /* tag with missing value "." */ \ + tgt_set_missing; \ + for (l=1; lsmpl_ploidy[ismpl+j]==1 ? 1 : 0; \ + int ngsize = haploid ? out->n_allele : out->n_allele*(out->n_allele + 1)/2; \ + if ( ma->buf[i].unkn_allele ) /* Use value from the unknown allele when available */ \ + { \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n; \ + int iunkn = haploid ? ma->buf[i].unkn_allele : (ma->buf[i].unkn_allele+1)*(ma->buf[i].unkn_allele + 2)/2 - 1; \ + for (l=0; ltype==MERGE_MISSING_CONST ) \ + { \ + for (l=0; lvalue; tgt++; } \ + } \ + else if ( mrule && mrule->type==MERGE_MISSING_MAX ) \ + { \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n; \ + src_type_t max = src[0]; \ + for (l=1; ln; l++) if ( max < src[l] ) max = src[l]; \ + for (l=0; ln_allele; iori++) \ + { \ + inew = ma->buf[i].rec[irec].map[iori]; \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n + iori; \ + tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + inew; \ + if ( src_is_vector_end ) break; \ + if ( src_is_missing ) tgt_set_missing; \ + else *tgt = *src; \ + } \ + } \ + else \ + { \ + /* Diploid */ \ + int iori,jori, inew,jnew; \ + for (iori=0; iorin_allele; iori++) \ + { \ + inew = ma->buf[i].rec[irec].map[iori]; \ + for (jori=0; jori<=iori; jori++) \ + { \ + jnew = ma->buf[i].rec[irec].map[jori]; \ + int kori = iori*(iori+1)/2 + jori; \ + int knew = inew>jnew ? inew*(inew+1)/2 + jnew : jnew*(jnew+1)/2 + inew; \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n + kori; \ + tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + knew; \ + if ( src_is_vector_end ) \ + { \ + iori = line->n_allele; \ + break; \ + } \ + if ( src_is_missing ) tgt_set_missing; \ + else *tgt = *src; \ + } \ + } \ + } \ + } \ + } \ + else \ + { \ + /* Number=A or Number=R tags */ \ + int ifrom = length==BCF_VL_A ? 1 : 0; \ + for (j=0; jtmp_arr + (ismpl+j)*nsize; \ + src = (src_type_t*) (fmt_ori->p + j*fmt_ori->size); \ + if ( (src_is_missing && fmt_ori->n==1) || (++src && src_is_vector_end) ) \ + { \ + /* tag with missing value "." */ \ + tgt_set_missing; \ + for (l=1; lp + j*fmt_ori->size); \ + if ( ma->buf[i].unkn_allele ) /* Use value from the unknown allele when available */ \ + { \ + int iunkn = ma->buf[i].unkn_allele; \ + for (l=0; ltype==MERGE_MISSING_CONST ) \ + { \ + for (l=0; lvalue; tgt++; } \ + } \ + else if ( mrule && mrule->type==MERGE_MISSING_MAX ) \ + { \ + src = (src_type_t*) fmt_ori->p + j*fmt_ori->n; \ + src_type_t max = src[0]; \ + for (l=1; ln; l++) if ( max < src[l] ) max = src[l]; \ + for (l=0; ln_allele; iori++) \ + { \ + inew = ma->buf[i].rec[irec].map[iori] - ifrom; \ + tgt = (tgt_type_t *) ma->tmp_arr + (ismpl+j)*nsize + inew; \ + if ( src_is_vector_end ) break; \ + if ( src_is_missing ) tgt_set_missing; \ + else *tgt = *src; \ + src++; \ + } \ + } \ + } \ + ismpl += bcf_hdr_nsamples(hdr); \ + } + switch (type) + { + case BCF_BT_INT8: BRANCH(int32_t, int8_t, *src==bcf_int8_missing, *src==bcf_int8_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT16: BRANCH(int32_t, int16_t, *src==bcf_int16_missing, *src==bcf_int16_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_INT32: BRANCH(int32_t, int32_t, *src==bcf_int32_missing, *src==bcf_int32_vector_end, *tgt=bcf_int32_missing, *tgt=bcf_int32_vector_end); break; + case BCF_BT_FLOAT: BRANCH(float, float, bcf_float_is_missing(*src), bcf_float_is_vector_end(*src), bcf_float_set_missing(*tgt), bcf_float_set_vector_end(*tgt)); break; + default: error("Unexpected case: %d, %s\n", type, key); + } + #undef BRANCH + } + if ( type==BCF_BT_FLOAT ) + bcf_update_format_float(out_hdr, out, key, (float*)ma->tmp_arr, nsamples*nsize); + else + bcf_update_format_int32(out_hdr, out, key, (int32_t*)ma->tmp_arr, nsamples*nsize); +} + +void merge_format(args_t *args, bcf1_t *out) +{ + bcf_srs_t *files = args->files; + bcf_hdr_t *out_hdr = args->out_hdr; + maux_t *ma = args->maux; + if ( !ma->nfmt_map ) + { + ma->nfmt_map = 2; + ma->fmt_map = (bcf_fmt_t**) calloc(ma->nfmt_map*files->nreaders, sizeof(bcf_fmt_t*)); + ma->fmt_key = (const char**) malloc(ma->nfmt_map*sizeof(*ma->fmt_key)); + } + else + memset(ma->fmt_map, 0, ma->nfmt_map*files->nreaders*sizeof(bcf_fmt_t**)); + + khiter_t kitr; + strdict_t *tmph = args->tmph; + kh_clear(strdict, tmph); + int i, j, ret, has_GT = 0, has_PL = -1, max_ifmt = 0; // max fmt index + for (i=0; inreaders; i++) + { + bcf1_t *line = maux_get_line(args,i); + if ( !line ) continue; + bcf_sr_t *reader = &files->readers[i]; + bcf_hdr_t *hdr = reader->header; + for (j=0; jn_fmt; j++) + { + // Was this tag already seen? + bcf_fmt_t *fmt = &line->d.fmt[j]; + const char *key = hdr->id[BCF_DT_ID][fmt->id].key; + kitr = kh_get(strdict, tmph, key); + + int ifmt; + if ( kitr != kh_end(tmph) ) + ifmt = kh_value(tmph, kitr); // seen + else + { + // new FORMAT tag + if ( key[0]=='G' && key[1]=='T' && key[2]==0 ) { has_GT = 1; ifmt = 0; } + else + { + ifmt = ++max_ifmt; + if ( max_ifmt >= ma->nfmt_map ) + { + ma->fmt_map = (bcf_fmt_t**) realloc(ma->fmt_map, sizeof(bcf_fmt_t*)*(max_ifmt+1)*files->nreaders); + memset(ma->fmt_map+ma->nfmt_map*files->nreaders, 0, (max_ifmt-ma->nfmt_map+1)*files->nreaders*sizeof(bcf_fmt_t*)); + ma->fmt_key = (const char**) realloc(ma->fmt_key, sizeof(*ma->fmt_key)*(max_ifmt+1)); + ma->nfmt_map = max_ifmt+1; + } + if ( key[0]=='P' && key[1]=='L' && key[2]==0 ) { has_PL = ifmt; } + ma->fmt_key[max_ifmt] = key; + } + kitr = kh_put(strdict, tmph, key, &ret); + kh_value(tmph, kitr) = ifmt; + } + ma->fmt_map[ifmt*files->nreaders+i] = fmt; + } + // Check if the allele numbering must be changed + int irec = ma->buf[i].cur; + for (j=1; jn_allele; j++) + if ( ma->buf[i].rec[irec].map[j]!=j ) break; + ma->buf[i].rec[irec].als_differ = j==line->n_allele ? 0 : 1; + } + + if ( args->local_alleles ) + { + ma->laa_dirty = ma->nlaa = 0; + if ( out->n_allele > args->local_alleles + 1 ) init_local_alleles(args, out, has_PL); + } + + out->n_sample = bcf_hdr_nsamples(out_hdr); + if ( has_GT ) + merge_GT(args, ma->fmt_map, out); + if ( !args->keep_AC_AN ) + update_AN_AC(out_hdr, out); + + for (i=1; i<=max_ifmt; i++) + { + missing_rule_t *rule = (missing_rule_t*) bsearch(ma->fmt_key[i], args->missing_rules, args->nmissing_rules, sizeof(*args->missing_rules), missing_rules_comp_key); + merge_format_field(args, &ma->fmt_map[i*files->nreaders], rule, out); + } + + if ( ma->laa_dirty ) + update_local_alleles(args, out); + + out->d.indiv_dirty = 1; +} + +void gvcf_set_alleles(args_t *args) +{ + int i,k; + bcf_srs_t *files = args->files; + maux_t *maux = args->maux; + gvcf_aux_t *gaux = maux->gvcf; + for (i=0; inals; i++) + { + free(maux->als[i]); + maux->als[i] = NULL; + } + maux->nals = 0; + + for (i=0; inreaders; i++) + { + if ( !gaux[i].active ) continue; + bcf1_t *line = maux_get_line(args, i); + if ( !line ) continue; + int irec = maux->buf[i].cur; + + hts_expand(int, line->n_allele, maux->buf[i].rec[irec].mmap, maux->buf[i].rec[irec].map); + if ( !maux->nals ) // first record, copy the alleles to the output + { + maux->nals = line->n_allele; + hts_expand0(char*, maux->nals, maux->mals, maux->als); + hts_expand0(int, maux->nals, maux->ncnt, maux->cnt); + for (k=0; knals; k++) + { + if ( maux->als[k] ) free(maux->als[k]); + maux->als[k] = strdup(line->d.allele[k]); + maux->buf[i].rec[irec].map[k] = k; + } + } + else + { + maux->als = merge_alleles(line->d.allele, line->n_allele, maux->buf[i].rec[irec].map, maux->als, &maux->nals, &maux->mals); + if ( !maux->als ) + { + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,i); + error("Failed to merge alleles at %s:%"PRId64"\n",bcf_seqname(hdr,line),(int64_t) line->pos+1); + } + } + } +} + +/* + Output staged gVCF blocks, end is the last position of the block. Assuming + gaux[i].active flags are set and maux_get_line returns correct lines. + Both start,end coordinates are 0-based. +*/ +void gvcf_write_block(args_t *args, int start, int end) +{ + int i; + maux_t *maux = args->maux; + gvcf_aux_t *gaux = maux->gvcf; + assert(gaux); + + // Update POS + int min = INT_MAX; // the minimum active gVCF INFO/END (0-based) + char ref = 'N'; + for (i=0; ifiles->nreaders; i++) + { + if ( !gaux[i].active ) continue; + if ( ref=='N' && gaux[i].line->pos==start ) ref = gaux[i].line->d.allele[0][0]; + gaux[i].line->pos = start; + } + for (i=0; ifiles->nreaders; i++) + { + if ( !gaux[i].active ) continue; + if ( gaux[i].end < start ) + { + gaux[i].active = 0; + maux->buf[i].cur = -1; + continue; + } + gaux[i].line->d.allele[0][0] = ref; + if ( min > gaux[i].end ) min = gaux[i].end; + } + // Check for valid gVCF blocks in this region + if ( min==INT_MAX ) // this probably should not happen + { + assert(0); + maux->gvcf_min = 0; + return; + } + + bcf1_t *out = args->out_line; + + gvcf_set_alleles(args); + + // Merge the staged lines + merge_chrom2qual(args, out); + merge_filter(args, out); + merge_info(args, out); + merge_format(args, out); + + if ( args->gvcf_fai && out->d.allele[0][0]=='N' ) + { + int slen = 0; + char *seq = faidx_fetch_seq(args->gvcf_fai,maux->chr,out->pos,out->pos,&slen); + if (!seq) + bcftools_exit(1); // faidx_fetch_seq has already reported the error. + + if (slen) + { + out->d.allele[0][0] = seq[0]; + free(seq); + } + } + + // Update END boundary + if ( end > start ) + { + end++; + bcf_update_info_int32(args->out_hdr, out, "END", &end, 1); + } + else + bcf_update_info_int32(args->out_hdr, out, "END", NULL, 0); + if ( bcf_write1(args->out_fh, args->out_hdr, out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + bcf_clear1(out); + + + // Inactivate blocks which do not extend beyond END and find new gvcf_min + min = INT_MAX; + for (i=0; ifiles->nreaders; i++) + { + if ( !gaux[i].active ) continue; + if ( gaux[i].end < end ) + { + gaux[i].active = 0; + maux->buf[i].cur = -1; + continue; + } + // next min END position bigger than the current one + if ( maux->gvcf_min < gaux[i].end+1 && min > gaux[i].end+1 ) min = gaux[i].end + 1; + } + maux->gvcf_min = min==INT_MAX ? 0 : min; +} + +/* + Flush staged gVCF blocks. Flush everything if there are no more lines + (done=1) or if there is a new chromosome. If still on the same chromosome, + all hanging blocks must be ended by creating new records: + A + 1 END=10 + B + 3 END=7 + C + 3 END=5 + out + 1 END=2 A . . + 3 END=5 A B C + 6 END=7 A B . + 8 END=10 A . . + +*/ +void gvcf_flush(args_t *args, int done) +{ + int i; + maux_t *maux = args->maux; + + if ( !maux->chr ) return; // first time here, nothing to flush + + int flush_until = INT_MAX; + if ( !done ) + { + // Get current position and chromosome + for (i=0; in; i++) + if ( bcf_sr_has_line(maux->files,i) ) break; + bcf1_t *line = bcf_sr_get_line(maux->files,i); + bcf_hdr_t *hdr = bcf_sr_get_header(maux->files,i); + + if ( !strcmp(maux->chr,bcf_seqname(hdr,line)) ) flush_until = line->pos; // still on the same chr + } + + // When called on a region, trim the blocks accordingly + int start = maux->gvcf_break>=0 ? maux->gvcf_break + 1 : maux->pos; // the start of a new gvcf block to output + if ( args->regs ) + { + int rstart = -1, rend = -1; + if ( regidx_overlap(args->regs,maux->chr,start,flush_until,args->regs_itr) ) + { + // In case there are multiple regions, we treat them as one + rstart = args->regs_itr->beg; + while ( regitr_overlap(args->regs_itr) ) rend = args->regs_itr->end; + } + if ( rstart > start ) start = rstart; + if ( rend < flush_until ) flush_until = rend+1; + } + + // output all finished blocks + while ( maux->gvcf_min && start < flush_until ) + { + // does the block end before the new line or is it interrupted? + int tmp = maux->gvcf_min < flush_until ? maux->gvcf_min : flush_until; + if ( start > tmp-1 ) break; + gvcf_write_block(args,start,tmp-1); // gvcf_min is 1-based, passing 0-based coordinates + start = tmp; + } +} + +static inline int is_gvcf_block(bcf1_t *line) +{ + if ( line->rlen<=1 ) return 0; + if ( strlen(line->d.allele[0])==line->rlen ) return 0; + if ( line->n_allele==1 ) return 1; + + int i; + for (i=1; in_allele; i++) + { + if ( !strcmp(line->d.allele[i],"<*>") ) return 1; + if ( !strcmp(line->d.allele[i],"") ) return 1; + if ( !strcmp(line->d.allele[i],"") ) return 1; + } + return 0; +} + +/* + Check incoming lines for new gVCF blocks, set pointer to the current source + buffer (gvcf or readers). In contrast to gvcf_flush, this function can be + called only after maux_reset as it relies on updated maux buffers. + The coordinate is 0-based +*/ +void gvcf_stage(args_t *args, int pos) +{ + maux_t *maux = args->maux; + gvcf_aux_t *gaux = maux->gvcf; + bcf_srs_t *files = args->files; + int32_t *end = (int32_t*) maux->tmp_arr; + int i, nend = maux->ntmp_arr / sizeof(int32_t); + + maux->gvcf_break = -1; + maux->gvcf_min = INT_MAX; + for (i=0; inreaders; i++) + { + if ( gaux[i].active && gaux[i].end < pos ) gaux[i].active = 0; + if ( gaux[i].active ) + { + // gvcf block should not overlap with another record + if ( maux->gvcf_min > gaux[i].end+1 ) maux->gvcf_min = gaux[i].end + 1; + maux->buf[i].beg = 0; + maux->buf[i].end = 1; + maux->buf[i].cur = 0; + continue; + } + + // Does any of the lines have END set? It is enough to check only the + // first line, there should be no duplicate records with END in gVCF + + if ( maux->buf[i].beg==maux->buf[i].end ) continue; // no new record + + int irec = maux->buf[i].beg; + bcf_hdr_t *hdr = bcf_sr_get_header(files, i); + bcf1_t *line = args->files->readers[i].buffer[irec]; + int ret = is_gvcf_block(line) ? bcf_get_info_int32(hdr,line,"END",&end,&nend) : 0; + if ( ret==1 ) + { + if ( end[0] == line->pos + 1 ) // POS and INFO/END are identical, treat as if a normal w/o INFO/END + { + maux->gvcf_break = line->pos; + continue; + } + if ( end[0] <= line->pos ) error("Error: Incorrect END at %s:%"PRId64" .. END=%d\n", bcf_seqname(hdr,line),(int64_t) line->pos+1,end[0]); + + // END is set, this is a new gVCF block. Cache this line in gaux[i] and swap with + // an empty record: the gaux line must be kept until we reach its END. + + gaux[i].active = 1; + gaux[i].end = end[0] - 1; + SWAP(bcf1_t*,args->files->readers[i].buffer[irec],gaux[i].line); + gaux[i].line->pos = pos; + + maux->buf[i].lines = &gaux[i].line; + maux->buf[i].beg = 0; + maux->buf[i].end = 1; + maux->buf[i].cur = 0; + + // Set the rid,pos of the swapped line in the buffer or else the + // synced reader will have a problem with the next line + // + args->files->readers[i].buffer[irec]->rid = maux->buf[i].rid; + args->files->readers[i].buffer[irec]->pos = maux->pos; + + // Update block offsets + if ( maux->gvcf_min > gaux[i].end+1 ) maux->gvcf_min = gaux[i].end + 1; + } + else + maux->gvcf_break = line->pos; // must break the gvcf block + } + maux->ntmp_arr = nend * sizeof(int32_t); + maux->tmp_arr = end; + if ( maux->gvcf_min==INT_MAX ) maux->gvcf_min = 0; +} + + +void debug_buffers(FILE *fp, bcf_srs_t *files); +void debug_buffer(FILE *fp, bcf_srs_t *files, int reader); + +/* + Flush all buffered and processed records with the same coordinate. + Note that synced reader discards buffer[0], so that needs to stay + untouched. +*/ +void clean_buffer(args_t *args) +{ + maux_t *ma = args->maux; + + int ir; + for (ir=0; irn; ir++) + { + // Invalidate pointer to reader's buffer or else gvcf_flush will attempt + // to use the old lines via maux_get_line() + if ( ma->gvcf ) + { + if ( ma->gvcf[ir].active ) + { + if ( ma->pos > ma->gvcf[ir].end ) ma->gvcf[ir].active = 0; + else if ( ma->buf[ir].cur==-1 ) ma->buf[ir].cur = ma->buf[ir].beg; // re-activate interrupted gVCF block + } + if ( !ma->gvcf[ir].active ) ma->buf[ir].cur = -1; + } + + bcf_sr_t *reader = bcf_sr_get_reader(args->files,ir); + if ( !reader->nbuffer ) continue; // nothing to clean + + bcf1_t **buf = reader->buffer; + if ( buf[1]->rid!=ma->buf[ir].rid || buf[1]->pos!=ma->pos ) continue; // nothing to flush + + int a = 1, b = 2; + while ( b<=reader->nbuffer && buf[b]->rid==ma->buf[ir].rid && buf[b]->pos==ma->pos ) b++; + // b now points to the first line we want to preserve + while ( b<=reader->nbuffer ) + { + SWAP(bcf1_t*, buf[a], buf[b]); + a++; b++; + } + reader->nbuffer -= b-a; + } +} + +void debug_maux(args_t *args) +{ + bcf_srs_t *files = args->files; + maux_t *maux = args->maux; + int j,k,l; + + fprintf(bcftools_stderr,"Alleles to merge at %d, nals=%d\n", maux->pos+1,maux->nals); + for (j=0; jnreaders; j++) + { + bcf_sr_t *reader = &files->readers[j]; + buffer_t *buf = &maux->buf[j]; + fprintf(bcftools_stderr," reader %d (k=%d-%d): ", j,buf->beg,buf->end); + for (k=buf->beg; kend; k++) + { + if ( buf->rec[k].skip & SKIP_DONE ) { fprintf(bcftools_stderr," DONE"); continue; } + bcf1_t *line = reader->buffer[k]; // selected for merging by can_merge + fprintf(bcftools_stderr,"\t"); + if ( buf->cur==k ) fprintf(bcftools_stderr,"!"); // selected for merging by stage_line + if ( buf->rec[k].skip ) fprintf(bcftools_stderr,"["); // this record cannot be merged in this round + if ( !line->n_allele && maux->gvcf[j].active ) + fprintf(bcftools_stderr,"<*>"); + for (l=0; ln_allele; l++) + fprintf(bcftools_stderr,"%s%s", l==0?"":",", line->d.allele[l]); + if ( buf->rec[k].skip ) fprintf(bcftools_stderr,"]"); + } + fprintf(bcftools_stderr,"\n"); + } + fprintf(bcftools_stderr," counts: "); + for (j=0; jnals; j++) fprintf(bcftools_stderr,"%s %dx %s", j==0?"":",",maux->cnt[j], maux->als[j]); + fprintf(bcftools_stderr,"\n\n"); +} + +void debug_state(args_t *args) +{ + maux_t *maux = args->maux; + int i,j; + fprintf(bcftools_stderr,"State after position=%d done:\n",maux->pos+1); + for (i=0; ifiles->nreaders; i++) + { + fprintf(bcftools_stderr,"\treader %d:\tcur,beg,end=% d,%d,%d", i,maux->buf[i].cur,maux->buf[i].beg,maux->buf[i].end); + if ( maux->buf[i].cur >=0 ) + { + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,i); + const char *chr = bcf_hdr_id2name(hdr, maux->buf[i].rid); + fprintf(bcftools_stderr,"\t"); + for (j=maux->buf[i].beg; jbuf[i].end; j++) fprintf(bcftools_stderr," %s:%"PRId64,chr,(int64_t) maux->buf[i].lines[j]->pos+1); + } + fprintf(bcftools_stderr,"\n"); + } + fprintf(bcftools_stderr,"\tgvcf_min=%d\n", args->maux->gvcf_min); + for (i=0; ifiles->nreaders; i++) + { + fprintf(bcftools_stderr,"\t\treader %d:\tgvcf_active=%d", i,maux->gvcf[i].active); + if ( maux->gvcf[i].active ) fprintf(bcftools_stderr,"\tpos,end=%"PRId64",%"PRId64, (int64_t) maux->gvcf[i].line->pos+1,(int64_t) maux->gvcf[i].end+1); + fprintf(bcftools_stderr,"\n"); + } + fprintf(bcftools_stderr,"\n"); +} + + +// Lines can come with any combination of variant types. We use a subset of types defined in vcf.h +// but shift by two bits to account for VCF_REF defined as 0 (design flaw in vcf.h, my fault) +static const int + snp_mask = (VCF_SNP<<1)|(VCF_MNP<<1), + indel_mask = (VCF_INDEL<<1), + ins_mask = VCF_INS<<1, + del_mask = VCF_DEL<<1, + ref_mask = 1; + +// Can these types be merged given the -m settings? Despite the function's name, its focus is on +// excluding incompatible records, there will be a finer matching later in stage_line() +static inline int types_compatible(args_t *args, int selected_types, buffer_t *buf, int irec) +{ + int k; + maux_t *maux = args->maux; + bcf1_t *rec = buf->lines[irec]; + int rec_types = buf->rec[irec].var_types; + + assert( selected_types ); // this is trivially true, set in can_merge() + + if ( args->collapse & COLLAPSE_ANY ) return 1; // can merge anything with anything + + // REF and gVCF_REF with no other alleles present can be merged with anything + if ( (selected_types&ref_mask) && !(selected_types&(~ref_mask)) ) return 1; + if ( (rec_types&ref_mask) && !(rec_types&(~ref_mask)) ) return 1; + + if ( args->collapse!=COLLAPSE_NONE ) + { + // If we are here, one the following modes must have been set: both,snps,indels,snp-ins-del + // Include the new record if + // - rec has SNV, we already have SNV, and -m is both,snps,snp-ins-del + // - rec has indel, we already have an indel, and -m both,indels,snp-ins-del + if ( args->collapse&(COLLAPSE_SNPS|COLLAPSE_SNP_INS_DEL) ) + { + if ( (rec_types&snp_mask) && (selected_types&snp_mask) ) return 1; + } + if ( args->collapse&COLLAPSE_INDELS ) + { + if ( (rec_types&indel_mask) && (selected_types&indel_mask) ) return 1; + } + if ( args->collapse&COLLAPSE_SNP_INS_DEL ) + { + if ( (rec_types&ins_mask) && (selected_types&ins_mask) ) return 1; + if ( (rec_types&del_mask) && (selected_types&del_mask) ) return 1; + } + // Whatever is left, allow to match if the alleles match exactly + } + + // The -m none mode or exact matching requested + // Simple test first: are the variants of the same type? + int x = selected_types >> 1; // remove REF + int y = rec_types >> 1; // remove REF + while ( x && y ) { x>>=1; y>>=1; } + if ( x || y ) return 0; // the types differ + + if ( vcmp_set_ref(args->vcmp,maux->als[0],rec->d.allele[0]) < 0 ) return 0; // refs are not compatible + for (k=1; kn_allele; k++) + { + if ( bcf_has_variant_type(rec,k,VCF_REF) ) continue; // this must be gVCF_REF (<*> or ) + if ( vcmp_find_allele(args->vcmp,maux->als+1,maux->nals-1,rec->d.allele[k])>=0 ) break; + } + if ( k==rec->n_allele ) return 0; // this record has a new allele rec->d.allele[k] + return 1; // all alleles in rec are also in the records selected thus far, perhaps save for gVCF_REF +} + +static void maux_update_alleles(args_t *args, int ireader, int irec) +{ + int k; + bcf_sr_t *reader = &args->files->readers[ireader]; + maux_t *maux = args->maux; + buffer_t *buf = &maux->buf[ireader]; + maux1_t *ma1 = &buf->rec[irec]; + bcf1_t *line = buf->lines[irec]; + hts_expand(int, line->n_allele, ma1->mmap, ma1->map); + if ( !maux->nals ) // first record to be merged, copy the alleles to the output + { + maux->nals = line->n_allele; + hts_expand0(char*, maux->nals, maux->mals, maux->als); + hts_expand0(int, maux->nals, maux->ncnt, maux->cnt); + hts_expand0(int, maux->nals, maux->mals_types, maux->als_types); + for (k=0; knals; k++) + { + free(maux->als[k]); + maux->als[k] = strdup(line->d.allele[k]); + ma1->map[k] = k; + maux->cnt[k] = 1; + int var_type = bcf_has_variant_type(line, k, VCF_ANY); + if ( args->collapse==COLLAPSE_SNP_INS_DEL ) var_type &= ~VCF_INDEL; + maux->als_types[k] = var_type ? var_type<<1 : ref_mask; + } + return; + } + // normalize alleles + maux->als = merge_alleles(line->d.allele, line->n_allele, ma1->map, maux->als, &maux->nals, &maux->mals); + if ( !maux->als ) error("Failed to merge alleles at %s:%"PRId64" in %s\n",maux->chr,(int64_t) line->pos+1,reader->fname); + hts_expand0(int, maux->nals, maux->ncnt, maux->cnt); + hts_expand0(int, maux->nals, maux->mals_types, maux->als_types); + for (k=1; kn_allele; k++) + { + int ik = ma1->map[k]; + int var_type = bcf_has_variant_type(line, k, VCF_ANY); + if ( args->collapse==COLLAPSE_SNP_INS_DEL ) var_type &= ~VCF_INDEL; + maux->als_types[ik] = var_type ? var_type<<1 : ref_mask; + maux->cnt[ik]++; // how many times an allele appears in the files + } + maux->cnt[0]++; +} + +/* + Determine which lines remain to be merged across readers at the current position and + are compatible given the -m criteria. This is indicated by maux1_t.skip: 0=compatible, + SKIP_DONE=the record is done, SKIP_DIFF=not compatible and will be included next time. + + At the same time count how many times is each allele present across the readers and records + so that we can prioritize the records with the same alleles to come first. In the end maximum + one record at a time can be selected from each reader and that witll be done in stage_line(). + + The function maux_reset already initialized structures for this position, so here each + reader comes with the beg,end indexes that point to records with the same maux_t.pos position. + */ +int can_merge(args_t *args) +{ + bcf_srs_t *files = args->files; + maux_t *maux = args->maux; + gvcf_aux_t *gaux = maux->gvcf; + char *id = NULL, ref = 'N'; + int i,j, ntodo = 0; + + for (i=0; inals; i++) + { + free(maux->als[i]); + maux->als[i] = NULL; + maux->cnt[i] = 0; + } + maux->var_types = maux->nals = 0; + + // In this loop we do the following: + // - remember the first encountered ID if matching by ID + // - count the number of unprocessed records at this position + // - collect all variant types at this position. This is to be able to perform -m matching and + // print SNVs first, then indels, then gVCF blocks + // - init the 'skip' variable to SKIP_DIFF for each record that has not been used yet + for (i=0; inreaders; i++) + { + buffer_t *buf = &maux->buf[i]; + buf->var_types = 0; + + if ( gaux && gaux[i].active ) // active gvcf block + { + buf->rec[buf->beg].skip = SKIP_DIFF; + maux->var_types |= ref_mask; + buf->var_types |= ref_mask; + buf->rec[buf->beg].var_types = ref_mask; + continue; + } + + // for gvcf: find out REF at this position + if ( buf->beg < buf->end && ref=='N' ) ref = buf->lines[buf->beg]->d.allele[0][0]; + + for (j=buf->beg; jend; j++) + { + if ( buf->rec[j].skip & SKIP_DONE ) continue; + + buf->rec[j].skip = SKIP_DIFF; + ntodo++; + + bcf1_t *line = buf->lines[j]; + if ( args->merge_by_id && !id ) { id = line->d.id; continue; } // set ID when merging by id + + if ( !buf->rec[j].var_types ) + { + int var_type = bcf_has_variant_types(line, VCF_ANY, bcf_match_overlap); + if ( var_type < 0 ) error("bcf_has_variant_types() failed."); + if ( args->collapse==COLLAPSE_SNP_INS_DEL ) + { + // need to distinguish between ins and del so strip the VCF_INDEL flag + var_type &= ~VCF_INDEL; + } + var_type = var_type ? var_type<<1 : ref_mask; + if ( args->do_gvcf && is_gvcf_block(line) ) var_type |= ref_mask; + buf->rec[j].var_types = var_type; + } + maux->var_types |= buf->rec[j].var_types; + buf->var_types |= buf->rec[j].var_types; + } + } + if ( !ntodo ) return 0; + + int selected_types = 0; + + // In this loop we select from each reader compatible candidate lines. + // (i.e. SNPs or indels). Go through all files and all lines at this + // position and normalize relevant alleles. + // REF-only sites may be associated with both SNPs and indels. + for (i=0; inreaders; i++) + { + buffer_t *buf = &maux->buf[i]; + if ( gaux && gaux[i].active ) + { + // gVCF records inherited from an upstream gVCF block have incorrect or missing allele and position + gaux[i].line->d.allele[0][0] = ref; + gaux[i].line->pos = maux->pos; + maux_update_alleles(args, i, buf->beg); + selected_types |= ref_mask; + continue; + } + for (j=buf->beg; jend; j++) + { + if ( buf->rec[j].skip & SKIP_DONE ) continue; + + bcf1_t *line = buf->lines[j]; // ptr to reader's buffer or gvcf buffer + int line_types = buf->rec[j].var_types; + + // select relevant lines + if ( args->merge_by_id ) + { + if ( strcmp(id,line->d.id) ) continue; // matching by ID and it does not match the selected record + } + else if ( selected_types && !types_compatible(args,selected_types,buf,j) ) continue; + else + { + // First time here, choosing the first line: prioritize SNPs when available in the -m snps,both modes + if ( (args->collapse&COLLAPSE_SNPS || args->collapse==COLLAPSE_NONE) // asked to merge SNVs into multiallelics + && (maux->var_types&snp_mask) // there are SNVs at the current position + && !(buf->rec[j].var_types&(snp_mask|ref_mask)) // and this record is not a SNV nor ref + ) continue; + } + selected_types |= line_types; + + buf->rec[j].skip = 0; // the j-th record from i-th reader can be included. Final decision will be made in stage_line + maux_update_alleles(args, i, j); + } + } + return 1; +} + +/* + Select records that have the same alleles; the input ordering of indels + must not matter. Multiple VCF lines can be emitted from this loop. + We expect only very few alleles and not many records with the same + position in the buffers, therefore the nested loops should not slow us + much. +*/ +void stage_line(args_t *args) +{ + bcf_srs_t *files = args->files; + maux_t *maux = args->maux; + + // Take the most frequent allele present in multiple files, REF and gVCF_REF is skipped. + int i,j,k,icnt = -1; + for (i=1; inals; i++) + { + if ( maux->als_types[i] & ref_mask ) continue; + if ( icnt==-1 || maux->cnt[icnt] < maux->cnt[i] ) icnt = i; + } + int selected_type = icnt>0 ? maux->als_types[icnt] : ref_mask; + + int nout = 0; + for (i=0; inreaders; i++) + { + buffer_t *buf = &maux->buf[i]; + buf->cur = -1; + if ( buf->beg >= buf->end ) continue; // No lines in the buffer at this site + + // find lines with the same allele + for (j=buf->beg; jend; j++) + { + if ( buf->rec[j].skip ) + { + int is_gvcf = maux->gvcf && maux->gvcf[i].active ? 1 : 0; + if ( !is_gvcf && is_gvcf_block(buf->lines[j]) ) is_gvcf = 1; + if ( !is_gvcf ) continue; // done or not compatible + } + if ( args->merge_by_id ) break; // if merging by ID and the line is compatible, the this is THE line + + // skip if the reader has a record that matches the most frequent allele and this record is not it + if ( (selected_type & buf->var_types) && !(selected_type & buf->rec[j].var_types) ) continue; + + // if the reader does not have the most frequent allele type but is a ref, accept + if ( !(selected_type & buf->var_types) && (buf->rec[j].var_types & ref_mask) ) break; + if ( selected_type==ref_mask ) break; + + // accept if the record has the most frequent allele + for (k=0; klines[j]->n_allele; k++) + if ( icnt==buf->rec[j].map[k] ) break; + if ( klines[j]->n_allele ) break; + } + if ( j>=buf->end ) + { + // no matching allele found in this file + if ( args->collapse==COLLAPSE_NONE ) continue; // exact matching requested, skip + + // choose something compatible to create a multiallelic site given the -m criteria + for (j=buf->beg; jend; j++) + { + if ( buf->rec[j].skip ) continue; // done or not compatible + if ( args->collapse&COLLAPSE_ANY ) break; // anything can be merged + int line_type = buf->rec[j].var_types; + if ( maux->var_types&snp_mask && line_type&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break; + if ( maux->var_types&indel_mask && line_type&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break; + if ( maux->var_types&ins_mask && line_type&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + if ( maux->var_types&del_mask && line_type&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + if ( line_type&ref_mask ) + { + if ( maux->var_types&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break; + if ( maux->var_types&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break; + if ( maux->var_types&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + if ( maux->var_types&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + if ( maux->var_types&ref_mask ) break; + } + else if ( maux->var_types&ref_mask ) + { + if ( line_type&snp_mask && (args->collapse&COLLAPSE_SNPS) ) break; + if ( line_type&indel_mask && (args->collapse&COLLAPSE_INDELS) ) break; + if ( line_type&ins_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + if ( line_type&del_mask && (args->collapse&COLLAPSE_SNP_INS_DEL) ) break; + } + } + } + if ( jend ) + { + // found a suitable line for merging + buf->cur = j; + } + } + + // debug_maux(args); + + // Mark lines staged for merging as finished so that they are ignored next time + for (i=0; inreaders; i++) + { + buffer_t *buf = &maux->buf[i]; + if ( buf->cur == -1 ) continue; + + buf->rec[buf->cur].skip = SKIP_DONE; + nout++; + } + + assert( nout ); +} + +void merge_line(args_t *args) +{ + bcf1_t *out = args->out_line; + merge_chrom2qual(args, out); + if ( args->regs && !regidx_overlap(args->regs,args->maux->chr,out->pos,out->pos+out->rlen-1,NULL) ) return; + merge_filter(args, out); + merge_info(args, out); + if ( args->do_gvcf ) + bcf_update_info_int32(args->out_hdr, out, "END", NULL, 0); + merge_format(args, out); + if ( bcf_write1(args->out_fh, args->out_hdr, out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + bcf_clear1(out); +} + +void bcf_hdr_append_version(bcf_hdr_t *hdr, int argc, char **argv, const char *cmd) +{ + kstring_t str = {0,0,0}; + int e = 0; + if (ksprintf(&str,"##%sVersion=%s+htslib-%s\n", cmd, bcftools_version(), hts_version()) < 0) + goto fail; + if (bcf_hdr_append(hdr,str.s) < 0) + goto fail; + + str.l = 0; + e |= ksprintf(&str,"##%sCommand=%s", cmd, argv[0]) < 0; + int i; + for (i=1; inhrec; i++) + { + if ( hdr->hrec[i]->type!=BCF_HL_FMT ) continue; + j = bcf_hrec_find_key(hdr->hrec[i],"ID"); + if ( j<0 ) continue; + char *key = hdr->hrec[i]->vals[j]; + int id = bcf_hdr_id2int(hdr, BCF_DT_ID, key); + assert( id>=0 ); + int localize = 0; + if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_G ) localize = 1; + if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_A ) localize = 1; + if ( bcf_hdr_id2length(hdr,BCF_HL_FMT,id) == BCF_VL_R ) localize = 1; + if ( !localize ) continue; + args->tmps.l = 0; + + uint32_t e = 0, nout = 0; + e |= ksprintf(&args->tmps, "##%s=<", hdr->hrec[i]->key) < 0; + for (j=0; jhrec[i]->nkeys; j++) + { + if ( !strcmp("IDX",hdr->hrec[i]->keys[j]) ) continue; + if ( nout ) e |= kputc(',',&args->tmps) < 0; + if ( !strcmp("ID",hdr->hrec[i]->keys[j]) ) + e |= ksprintf(&args->tmps,"%s=L%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]) < 0; + else if ( !strcmp("Number",hdr->hrec[i]->keys[j]) ) + e |= ksprintf(&args->tmps,"Number=.") < 0; + else if ( !strcmp("Description",hdr->hrec[i]->keys[j]) && hdr->hrec[i]->vals[j][0]=='"' ) + e |= ksprintf(&args->tmps,"Description=\"Localized field: %s", hdr->hrec[i]->vals[j]+1) < 0; + else + e |= ksprintf(&args->tmps,"%s=%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]) < 0; + nout++; + } + e |= ksprintf(&args->tmps,">\n") < 0; + if ( e ) error("Failed to format the header line for %s\n", key); + nstr++; + hts_expand(char*,nstr,mstr,str); + str[nstr-1] = strdup(args->tmps.s); + } + if ( !nstr ) return; + bcf_hdr_append(hdr,"##FORMAT="); + for (i=0; ioutput_type,args->output_fname,args->clevel); + args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno)); + if ( args->n_threads ) hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->files->p); //hts_set_threads(args->out_fh, args->n_threads); + args->out_hdr = bcf_hdr_init("w"); + + if ( args->header_fname ) + { + if ( bcf_hdr_set(args->out_hdr,args->header_fname) ) error("Could not read/parse the header: %s\n", args->header_fname); + } + else + { + int i; + for (i=0; ifiles->nreaders; i++) + { + char buf[24]; snprintf(buf,sizeof buf,"%d",i+1); + merge_headers(args->out_hdr, args->files->readers[i].header,buf,args->force_samples); + } + if ( args->local_alleles ) hdr_add_localized_tags(args, args->out_hdr); + if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_merge"); + if (bcf_hdr_sync(args->out_hdr) < 0) + error_errno("[%s] Failed to update header", __func__); + } + info_rules_init(args); + missing_rules_init(args); + + bcf_hdr_set_version(args->out_hdr, bcf_hdr_get_version(args->files->readers[0].header)); + if ( bcf_hdr_write(args->out_fh, args->out_hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + if ( args->header_only ) + { + bcf_hdr_destroy(args->out_hdr); + if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname); + return; + } + else if ( args->write_index && init_index(args->out_fh,args->out_hdr,args->output_fname,&args->index_fn)<0 ) error("Error: failed to initialise index for %s\n",args->output_fname); + + if ( args->collapse==COLLAPSE_NONE ) args->vcmp = vcmp_init(); + args->maux = maux_init(args); + args->out_line = bcf_init1(); + args->tmph = kh_init(strdict); + + int *rid_tab = calloc(args->maux->n, sizeof(*rid_tab)); + if (!rid_tab) + error("[%s:%d] Could not allocate %zu bytes\n", __FILE__, __LINE__, args->maux->n*sizeof(*rid_tab)); + + while ( bcf_sr_next_line(args->files) ) + { + // output cached gVCF blocks which end before the new record + if ( args->do_gvcf ) + gvcf_flush(args,0); + + maux_reset(args->maux, rid_tab); + + // determine which of the new records are gvcf blocks + if ( args->do_gvcf ) + gvcf_stage(args, args->maux->pos); + + while ( can_merge(args) ) + { + stage_line(args); + merge_line(args); + } + clean_buffer(args); + // debug_state(args); + } + free(rid_tab); + if ( args->do_gvcf ) + gvcf_flush(args,1); + + info_rules_destroy(args); + missing_rules_destroy(args); + maux_destroy(args->maux); + bcf_hdr_destroy(args->out_hdr); + if ( args->write_index ) + { + if ( bcf_idx_save(args->out_fh)<0 ) + { + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname?args->output_fname:"bcftools_stdout"); + bcf_destroy1(args->out_line); + kh_destroy(strdict, args->tmph); + if ( args->tmps.m ) free(args->tmps.s); + if ( args->vcmp ) vcmp_destroy(args->vcmp); +} + +static void usage(void) +{ + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "About: Merge multiple VCF/BCF files from non-overlapping sample sets to create one multi-sample file.\n"); + fprintf(bcftools_stderr, " Note that only records from different files can be merged, never from the same file. For\n"); + fprintf(bcftools_stderr, " \"vertical\" merge take a look at \"bcftools norm\" instead.\n"); + fprintf(bcftools_stderr, "Usage: bcftools merge [options] [...]\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "Options:\n"); + fprintf(bcftools_stderr, " --force-samples Resolve duplicate sample names\n"); + fprintf(bcftools_stderr, " --print-header Print only the merged header and exit\n"); + fprintf(bcftools_stderr, " --use-header FILE Use the provided header\n"); + fprintf(bcftools_stderr, " -0 --missing-to-ref Assume genotypes at missing sites are 0/0\n"); + fprintf(bcftools_stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n"); + fprintf(bcftools_stderr, " -F, --filter-logic x|+ Remove filters if some input is PASS (\"x\"), or apply all filters (\"+\") [+]\n"); + fprintf(bcftools_stderr, " -g, --gvcf -|REF.FA Merge gVCF blocks, INFO/END tag is expected. Implies -i QS:sum,MinDP:min,I16:sum,IDV:max,IMF:max -M PL:max,AD:0\n"); + fprintf(bcftools_stderr, " -i, --info-rules TAG:METHOD,.. Rules for merging INFO fields (method is one of sum,avg,min,max,join) or \"-\" to turn off the default [DP:sum,DP4:sum]\n"); + fprintf(bcftools_stderr, " -l, --file-list FILE Read file names from the file\n"); + fprintf(bcftools_stderr, " -L, --local-alleles INT EXPERIMENTAL: if more than ALT alleles are encountered, drop FMT/PL and output LAA+LPL instead; 0=unlimited [0]\n"); + fprintf(bcftools_stderr, " -m, --merge STRING Allow multiallelic records for , see man page for details [both]\n"); + fprintf(bcftools_stderr, " -M, --missing-rules TAG:METHOD Rules for replacing missing values in numeric vectors (.,0,max) when unknown allele <*> is not present [.]\n"); + fprintf(bcftools_stderr, " --no-index Merge unindexed files, the same chromosomal order is required and -r/-R are not allowed\n"); + fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(bcftools_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"); + fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(bcftools_stderr, " --threads INT Use multithreading with worker threads [0]\n"); + fprintf(bcftools_stderr, " --write-index Automatically index the output files [off]\n"); + fprintf(bcftools_stderr, "\n"); + bcftools_exit(1); +} + +int main_vcfmerge(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->files = bcf_sr_init(); + args->argc = argc; args->argv = argv; + args->output_fname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->collapse = COLLAPSE_BOTH; + args->clevel = -1; + int regions_is_file = 0; + int regions_overlap = 1; + + static struct option loptions[] = + { + {"help",no_argument,NULL,'h'}, + {"merge",required_argument,NULL,'m'}, + {"local-alleles",required_argument,NULL,'L'}, + {"gvcf",required_argument,NULL,'g'}, + {"file-list",required_argument,NULL,'l'}, + {"missing-to-ref",no_argument,NULL,'0'}, + {"apply-filters",required_argument,NULL,'f'}, + {"use-header",required_argument,NULL,1}, + {"print-header",no_argument,NULL,2}, + {"force-samples",no_argument,NULL,3}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,4}, + {"info-rules",required_argument,NULL,'i'}, + {"missing-rules",required_argument,NULL,'M'}, + {"no-version",no_argument,NULL,8}, + {"no-index",no_argument,NULL,10}, + {"filter-logic",required_argument,NULL,'F'}, + {"write-index",no_argument,NULL,11}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "hm:f:r:R:o:O:i:M:l:g:F:0L:",loptions,NULL)) >= 0) { + switch (c) { + case 'L': + args->local_alleles = strtol(optarg,&tmp,10); + if ( *tmp ) error("Could not parse argument: --local-alleles %s\n", optarg); + if ( args->local_alleles < 1 ) + error("Error: \"--local-alleles %s\" makes no sense, expected value bigger or equal than 1\n", optarg); + break; + case 'F': + if ( !strcmp(optarg,"+") ) args->filter_logic = FLT_LOGIC_ADD; + else if ( !strcmp(optarg,"x") ) args->filter_logic = FLT_LOGIC_REMOVE; + else error("Filter logic not recognised: %s\n", optarg); + break; + case '0': args->missing_to_ref = 1; break; + case 'g': + args->do_gvcf = 1; + if ( strcmp("-",optarg) ) + { + args->gvcf_fai = fai_load(optarg); + if ( !args->gvcf_fai ) error("Failed to load the fai index: %s\n", optarg); + } + break; + case 'l': args->file_list = optarg; break; + case 'i': args->info_rules = optarg; break; + case 'M': args->missing_rules_str = optarg; break; + case 'o': args->output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'm': + args->collapse = COLLAPSE_NONE; + if ( !strcmp(optarg,"snps") ) args->collapse |= COLLAPSE_SNPS; + else if ( !strcmp(optarg,"indels") ) args->collapse |= COLLAPSE_INDELS; + else if ( !strcmp(optarg,"both") ) args->collapse |= COLLAPSE_BOTH; + else if ( !strcmp(optarg,"any") ) args->collapse |= COLLAPSE_ANY; + else if ( !strcmp(optarg,"all") ) args->collapse |= COLLAPSE_ANY; + else if ( !strcmp(optarg,"none") ) args->collapse = COLLAPSE_NONE; + else if ( !strcmp(optarg,"snp-ins-del") ) args->collapse = COLLAPSE_SNP_INS_DEL|COLLAPSE_SNPS; + else if ( !strcmp(optarg,"id") ) { args->collapse = COLLAPSE_NONE; args->merge_by_id = 1; } + else error("The -m type \"%s\" is not recognised.\n", optarg); + break; + case 'f': args->files->apply_filters = optarg; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; regions_is_file = 1; break; + case 1 : args->header_fname = optarg; break; + case 2 : args->header_only = 1; break; + case 3 : args->force_samples = 1; break; + case 4 : + regions_overlap = parse_overlap_option(optarg); + if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 8 : args->record_cmd_line = 0; break; + case 10 : args->no_index = 1; break; + case 11 : args->write_index = 1; break; + case 'h': + case '?': usage(); break; + default: error("Unknown argument: %s\n", optarg); + } + } + if ( argc==optind && !args->file_list ) usage(); + if ( argc-optind<2 && !args->file_list ) usage(); + + if ( args->no_index ) + { + if ( args->regions_list ) error("Error: cannot combine --no-index with -r/-R\n"); + bcf_sr_set_opt(args->files,BCF_SR_ALLOW_NO_IDX); + } + else + bcf_sr_set_opt(args->files,BCF_SR_REQUIRE_IDX); + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + if ( regions_is_file ) + args->regs = regidx_init(args->regions_list,NULL,NULL,sizeof(char*),NULL); + else + { + args->regs = regidx_init(NULL,regidx_parse_reg,NULL,sizeof(char*),NULL); + if ( regidx_insert_list(args->regs,args->regions_list,',') !=0 ) error("Could not parse the regions: %s\n", args->regions_list); + regidx_insert(args->regs,NULL); + } + if ( !args->regs ) error("Could not parse the regions: %s\n", args->regions_list); + args->regs_itr = regitr_init(args->regs); + } + + if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n"); + while (optindfiles, argv[optind]) ) error("Failed to open %s: %s\n", argv[optind],bcf_sr_strerror(args->files->errnum)); + optind++; + } + if ( args->file_list ) + { + int nfiles, i; + char **files = hts_readlines(args->file_list, &nfiles); + if ( !files ) error("Failed to read from %s\n", args->file_list); + for (i=0;ifiles, files[i]) ) error("Failed to open %s: %s\n", files[i],bcf_sr_strerror(args->files->errnum)); + for (i=0; ifiles); + if ( args->regs ) regidx_destroy(args->regs); + if ( args->regs_itr ) regitr_destroy(args->regs_itr); + if ( args->gvcf_fai ) fai_destroy(args->gvcf_fai); + free(args); + return 0; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfsort.c b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfsort.c new file mode 100644 index 0000000000000000000000000000000000000000..3b208a0d3f91cb8126b08214dc9565e51390a7d9 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/bcftools/vcfsort.c @@ -0,0 +1,460 @@ +/* vcfsort.c -- sort subcommand + + Copyright (C) 2017-2023 Genome Research Ltd. + + Author: Petr Danecek + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif +#include +#include +#include +#include "kheap.h" +#include "bcftools.h" + +typedef struct +{ + char *fname; + htsFile *fh; + bcf1_t *rec; +} +blk_t; + +typedef struct _args_t +{ + bcf_hdr_t *hdr; + char **argv, *fname, *output_fname, *tmp_dir; + int argc, output_type, clevel; + size_t max_mem, mem; + bcf1_t **buf; + uint8_t *mem_block; + size_t nbuf, mbuf, nblk; + blk_t *blk; + char *index_fn; + int write_index; +} +args_t; + +void clean_files(args_t *args) +{ + int i; + fprintf(stderr,"Cleaning\n"); + for (i=0; inblk; i++) + { + blk_t *blk = args->blk + i; + if ( blk->fname ) + { + unlink(blk->fname); + free(blk->fname); + } + if ( blk->rec ) + bcf_destroy(blk->rec); + } + rmdir(args->tmp_dir); +} +void clean_files_and_throw(args_t *args, const char *format, ...) +{ + va_list ap; + va_start(ap, format); + vfprintf(stderr, format, ap); + va_end(ap); + clean_files(args); + exit(-1); +} + +int cmp_bcf_pos(const void *aptr, const void *bptr) +{ + bcf1_t *a = *((bcf1_t**)aptr); + bcf1_t *b = *((bcf1_t**)bptr); + if ( a->rid < b->rid ) return -1; + if ( a->rid > b->rid ) return 1; + if ( a->pos < b->pos ) return -1; + if ( a->pos > b->pos ) return 1; + + // Sort the same chr:pos records lexicographically by ref,alt. + // This will be called rarely so should not slow the sorting down + // noticeably. + + int i; + for (i=0; in_allele; i++) + { + if ( i >= b->n_allele ) return 1; + int ret = strcasecmp(a->d.allele[i],b->d.allele[i]); + if ( ret ) return ret; + } + if ( a->n_allele < b->n_allele ) return -1; + return 0; +} + +void buf_flush(args_t *args) +{ + if ( !args->nbuf ) return; + + qsort(args->buf, args->nbuf, sizeof(*args->buf), cmp_bcf_pos); + + args->nblk++; + args->blk = (blk_t*) realloc(args->blk, sizeof(blk_t)*args->nblk); + if ( !args->blk ) error("Error: could not allocate %zu bytes of memory, try reducing --max-mem\n",sizeof(blk_t)*args->nblk); + blk_t *blk = args->blk + args->nblk - 1; + + kstring_t str = {0,0,0}; + ksprintf(&str, "%s/%05d.bcf", args->tmp_dir, (int)args->nblk); + blk->fname = str.s; + blk->rec = NULL; + blk->fh = NULL; + + htsFile *fh = hts_open(blk->fname, "wbu"); + if ( fh == NULL ) clean_files_and_throw(args, "Cannot write %s: %s\n", blk->fname, strerror(errno)); + if ( bcf_hdr_write(fh, args->hdr)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,blk->fname); + + int i; + for (i=0; inbuf; i++) + { + 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); + } + if ( hts_close(fh)!=0 ) clean_files_and_throw(args, "[%s] Error: close failed .. %s\n", __func__,blk->fname); + + args->nbuf = 0; + args->mem = 0; +} + + +static inline uint8_t *_align_up(uint8_t *ptr) +{ + return (uint8_t*)(((size_t)ptr + 8 - 1) & ~((size_t)(8 - 1))); +} + +void buf_push(args_t *args, bcf1_t *rec) +{ + size_t delta = sizeof(bcf1_t) + rec->shared.l + rec->indiv.l + rec->unpack_size[0] + rec->unpack_size[1] + + sizeof(*rec->d.allele)*rec->d.m_allele + + sizeof(bcf1_t*) // args->buf + + 8; // the number of _align_up() calls + + if ( delta > args->max_mem - args->mem ) + { + args->nbuf++; + hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf); + args->buf[args->nbuf-1] = rec; + buf_flush(args); + bcf_destroy(rec); + return; + } + + // make sure nothing has changed in htslib + assert( rec->unpacked==BCF_UN_STR && !rec->d.flt && !rec->d.info && !rec->d.fmt && !rec->d.var ); + + uint8_t *ptr_beg = args->mem_block + args->mem; + uint8_t *ptr = _align_up(ptr_beg); + bcf1_t *new_rec = (bcf1_t*)ptr; + memcpy(new_rec,rec,sizeof(*rec)); + ptr += sizeof(*rec); + + // The array of allele pointers does not need alignment as bcf1_t is already padded to the biggest + // data type in the structure + char **allele = (char**)ptr; + ptr += rec->n_allele*sizeof(*allele); + + // This is just to prevent valgrind from complaining about memcpy, unpack_size is a high-water mark + // and the end may be uninitialized + delta = rec->d.allele[rec->n_allele-1] - rec->d.allele[0]; + while ( delta < rec->unpack_size[1] ) if ( !rec->d.als[delta++] ) break; + memcpy(ptr,rec->d.als,delta); + new_rec->d.als = (char*)ptr; + ptr = ptr + delta; + + int i; + for (i=0; in_allele; i++) allele[i] = new_rec->d.als + (ptrdiff_t)(rec->d.allele[i] - rec->d.allele[0]); + new_rec->d.allele = allele; + + memcpy(ptr,rec->shared.s,rec->shared.l); + new_rec->shared.s = (char*)ptr; + new_rec->shared.m = rec->shared.l; + ptr += rec->shared.l; + + memcpy(ptr,rec->indiv.s,rec->indiv.l); + new_rec->indiv.s = (char*)ptr; + new_rec->indiv.m = rec->indiv.l; + ptr += rec->indiv.l; + + // This is just to prevent valgrind from complaining about memcpy, unpack_size is a high-water mark + // and the end may be uninitialized + i = 0; + while ( i < rec->unpack_size[0] ) if ( !rec->d.id[i++] ) break; + memcpy(ptr,rec->d.id,i); + new_rec->d.id = (char*)ptr; + ptr += i; + + args->nbuf++; + hts_expand(bcf1_t*, args->nbuf, args->mbuf, args->buf); + args->buf[args->nbuf-1] = new_rec; + + delta = ptr - ptr_beg; + args->mem += delta; + + assert( args->mem <= args->max_mem ); + + bcf_destroy(rec); +} + +void sort_blocks(args_t *args) +{ + htsFile *in = hts_open(args->fname, "r"); + if ( !in ) clean_files_and_throw(args, "Could not read %s\n", args->fname); + args->hdr = bcf_hdr_read(in); + if ( !args->hdr) clean_files_and_throw(args, "Could not read VCF/BCF headers from %s\n", args->fname); + + while ( 1 ) + { + bcf1_t *rec = bcf_init(); + int ret = bcf_read1(in, args->hdr, rec); + if ( ret < -1 ) clean_files_and_throw(args,"Error encountered while parsing the input\n"); + if ( ret == -1 ) + { + bcf_destroy(rec); + break; + } + 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); + bcf_unpack(rec, BCF_UN_STR); + buf_push(args, rec); + } + buf_flush(args); + free(args->buf); + + if ( hts_close(in)!=0 ) clean_files_and_throw(args,"Close failed: %s\n", args->fname); +} + +static inline int blk_is_smaller(blk_t **aptr, blk_t **bptr) +{ + blk_t *a = *aptr; + blk_t *b = *bptr; + int ret = cmp_bcf_pos(&a->rec, &b->rec); + if ( ret < 0 ) return 1; + return 0; +} +KHEAP_INIT(blk, blk_t*, blk_is_smaller) + +void blk_read(args_t *args, khp_blk_t *bhp, bcf_hdr_t *hdr, blk_t *blk) +{ + if ( !blk->fh ) return; + int ret = bcf_read(blk->fh, hdr, blk->rec); + if ( ret < -1 ) clean_files_and_throw(args, "Error reading %s\n", blk->fname); + if ( ret == -1 ) + { + if ( hts_close(blk->fh)!=0 ) clean_files_and_throw(args, "Close failed: %s\n", blk->fname); + blk->fh = 0; + return; + } + bcf_unpack(blk->rec, BCF_UN_STR); + khp_insert(blk, bhp, &blk); +} + +void merge_blocks(args_t *args) +{ + fprintf(stderr,"Merging %d temporary files\n", (int)args->nblk); + khp_blk_t *bhp = khp_init(blk); + + int i; + for (i=0; inblk; i++) + { + blk_t *blk = args->blk + i; + blk->fh = hts_open(blk->fname, "r"); + if ( !blk->fh ) clean_files_and_throw(args, "Could not read %s: %s\n", blk->fname, strerror(errno)); + bcf_hdr_t *hdr = bcf_hdr_read(blk->fh); + bcf_hdr_destroy(hdr); + blk->rec = bcf_init(); + blk_read(args, bhp, args->hdr, blk); + } + + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + htsFile *out = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( bcf_hdr_write(out, args->hdr)!=0 ) clean_files_and_throw(args, "[%s] Error: cannot write to %s\n", __func__,args->output_fname); + 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); + while ( bhp->ndat ) + { + blk_t *blk = bhp->dat[0]; + 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); + khp_delete(blk, bhp); + blk_read(args, bhp, args->hdr, blk); + } + if ( args->write_index ) + { + if ( bcf_idx_save(out)<0 ) + { + if ( hts_close(out)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out)!=0 ) clean_files_and_throw(args, "Close failed: %s\n", args->output_fname); + + clean_files(args); + + free(args->blk); + khp_destroy(blk, bhp); + fprintf(stderr,"Done\n"); +} + +static void usage(args_t *args) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: Sort VCF/BCF file.\n"); + fprintf(stderr, "Usage: bcftools sort [OPTIONS] \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " -m, --max-mem FLOAT[kMG] maximum memory to use [768M]\n"); // using metric units, 1M=1e6 + fprintf(stderr, " -o, --output FILE output file name [stdout]\n"); + fprintf(stderr, " -O, --output-type b|u|z|v b: compressed BCF, u: uncompressed BCF, z: compressed VCF, v: uncompressed VCF [v]\n"); + 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"); + +#ifdef _WIN32 + fprintf(stderr, " -T, --temp-dir DIR temporary files [/bcftools.XXXXXX]\n"); +#else + fprintf(stderr, " -T, --temp-dir DIR temporary files [/tmp/bcftools.XXXXXX]\n"); +#endif + fprintf(stderr, " --write-index Automatically index the output files [off]\n"); + fprintf(stderr, "\n"); + exit(1); +} + +size_t parse_mem_string(const char *str) +{ + char *tmp; + double mem = strtod(str, &tmp); + if ( tmp==str ) error("Could not parse the memory string: \"%s\"\n", str); + if ( !strcasecmp("k",tmp) ) mem *= 1000; + else if ( !strcasecmp("m",tmp) ) mem *= 1000*1000; + else if ( !strcasecmp("g",tmp) ) mem *= 1000*1000*1000; + return mem; +} + +void mkdir_p(const char *fmt, ...); +static void init(args_t *args) +{ + args->max_mem *= 0.9; + args->mem_block = malloc(args->max_mem); + if ( !args->mem_block ) error("Error: could not allocate %zu bytes of memory, try reducing --max-mem\n",args->max_mem); + args->mem = 0; + + args->tmp_dir = init_tmp_prefix(args->tmp_dir); + +#ifdef _WIN32 + int ret = mkdir(mktemp(args->tmp_dir), 0700); + if ( ret ) error("mkdir(%s) failed: %s\n", args->tmp_dir,strerror(errno)); +#else + char *tmp = mkdtemp(args->tmp_dir); + if ( !tmp ) error("mkdtemp(%s) failed: %s\n", args->tmp_dir,strerror(errno)); + int ret = chmod(tmp, S_IRUSR|S_IWUSR|S_IXUSR); + if ( ret ) error("chmod(%s,S_IRUSR|S_IWUSR|S_IXUSR) failed: %s\n", args->tmp_dir,strerror(errno)); +#endif + + fprintf(stderr,"Writing to %s\n", args->tmp_dir); +} +static void destroy(args_t *args) +{ + bcf_hdr_destroy(args->hdr); + free(args->mem_block); + free(args->tmp_dir); + free(args); +} + +int main_sort(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->max_mem = 768*1000*1000; + args->output_fname = "-"; + args->clevel = -1; + + static struct option loptions[] = + { + {"max-mem",required_argument,NULL,'m'}, + {"temp-dir",required_argument,NULL,'T'}, + {"output-type",required_argument,NULL,'O'}, + {"output-file",required_argument,NULL,'o'}, + {"output",required_argument,NULL,'o'}, + {"help",no_argument,NULL,'h'}, + {"write-index",no_argument,NULL,1}, + {0,0,0,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "m:T:O:o:h?",loptions,NULL)) >= 0) + { + switch (c) + { + case 'm': args->max_mem = parse_mem_string(optarg); break; + case 'T': args->tmp_dir = optarg; break; + case 'o': args->output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + }; + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 1 : args->write_index = 1; break; + case 'h': + case '?': usage(args); break; + default: error("Unknown argument: %s\n", optarg); + } + } + + if ( optind>=argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-"; // reading from stdin + else usage(args); + } + else args->fname = argv[optind]; + + init(args); + sort_blocks(args); + merge_blocks(args); + destroy(args); + + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/amplicon_stats.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/amplicon_stats.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..b71ac4adf1d28c16978debbf3692ab514bf76650 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/amplicon_stats.c.pysam.c @@ -0,0 +1,1758 @@ +#include "samtools.pysam.h" + +/* stats.c -- This is the former bamcheck integrated into samtools/htslib. + + Copyright (C) 2020-2021 Genome Research Ltd. + + Author: James Bonfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +/* + * This tool is designed to give "samtools stats" style output, but dedicated + * to small amplicon sequencing projects. It gathers stats on the + * distribution of reads across amplicons. + */ + +/* + * TODO: + * - Cope with multiple references. What do we do here? Just request one? + * - Permit regions rather than consuming whole file (maybe solves above). + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "samtools.h" +#include "sam_opts.h" +#include "bam_ampliconclip.h" + +KHASH_MAP_INIT_INT64(tcoord, int64_t) +KHASH_MAP_INIT_STR(qname, int64_t) + +#ifndef MIN +#define MIN(a,b) ((a)<(b)?(a):(b)) +#endif + +#ifndef MAX +#define MAX(a,b) ((a)>(b)?(a):(b)) +#endif + +#ifndef ABS +#define ABS(a) ((a)>=0?(a):-(a)) +#endif + +#define TCOORD_MIN_COUNT 10 +#define MAX_AMP 1000 // Default maximum number of amplicons +#define MAX_AMP_LEN 1000 // Default maximum length of any single amplicon +#define MAX_PRIMER_PER_AMPLICON 4 // Max primers per LEFT/RIGHT +#define MAX_DEPTH 5 // Number of different depths permitted + +typedef struct { + sam_global_args ga; + uint32_t flag_require; + uint32_t flag_filter; + int max_delta; // Used for matching read to amplicon primer loc + int min_depth[MAX_DEPTH]; // Used for coverage; must be >= min_depth deep + int use_sample_name; + int max_amp; // Total number of amplicons + int max_amp_len; // Maximum length of an individual amplicon + double depth_bin;// aggregate depth within this fraction + int tlen_adj; // Adjust tlen by this amount, due to clip but no fixmate + FILE *out_fp; + char *argv; + int tcoord_min_count; + int tcoord_bin; + int multi_ref; +} astats_args_t; + +typedef struct { + int nseq; // total sequence count + int nfiltered; // sequence filtered + int nfailprimer;// count of sequences not matching the primer locations + + // Sizes of memory allocated below, to permit reset + int max_amp, max_amp_len, max_len; + + // Summary across all samples, sum(x) plus sum(x^2) for s.d. calc + int64_t *nreads, *nreads2; // [max_amp] + double *nfull_reads; // [max_amp]; 0.5/read if paired. + double *nrperc, *nrperc2; // [max_amp] + int64_t *nbases, *nbases2; // [max_amp] + int64_t *coverage; // [max_amp][max_amp_len] + double (*covered_perc)[MAX_DEPTH]; // [max_amp][MAX_DEPTH] + double (*covered_perc2)[MAX_DEPTH];// [max_amp][MAX_DEPTH]; + khash_t(tcoord) **tcoord; // [max_amp+1] + + // 0 is correct pair, 1 is incorrect pair, 2 is unidentified + int (*amp_dist)[3]; // [MAX_AMP][3]; + + int *depth_valid; // [max_len] + int *depth_all; // [max_len] + khash_t(qname) *qend; // queryname end, for overlap removal +} astats_t; + +// We can have multiple primers for LEFT / RIGHT, so this +// permits detection by any compatible combination. +// One reference: +typedef struct { + int64_t left[MAX_PRIMER_PER_AMPLICON]; + int nleft; + int64_t right[MAX_PRIMER_PER_AMPLICON]; + int nright; + int64_t max_left, min_right; // inner dimensions + int64_t min_left, max_right; // outer dimensions +} amplicon_t; + +// Multiple references, we have an array of amplicons_t - one per used ref. +// We have per reference local and global stats here, as some of the stats +// are coordinate based. However we report them combined together as a single +// list across all references. +// "namp" is the number of amplicons in this reference, but they're +// numbered first_amp to first_amp+namp-1 inclusively. +typedef struct { + int tid, namp; + int64_t len; + bed_entry_list_t *sites; + amplicon_t *amp; + astats_t *lstats, *gstats; // local (1 file) and global (all file) stats + const char *ref; // ref name (pointer to the bed hash table key) + int first_amp; // first amplicon number for this ref +} amplicons_t; + +// Reinitialised for each new reference/chromosome. +// Counts from 1 to namp, -1 for no match and 0 for ?. +static int *pos2start = NULL; +static int *pos2end = NULL; +static int pos2size = 0; // allocated size of pos2start/end + +// Lookup table to go from position to amplicon based on +// read start / end. +static int initialise_amp_pos_lookup(astats_args_t *args, + amplicons_t *amps, + int ref) { + int64_t i, j; + amplicon_t *amp = amps[ref].amp; + int64_t max_len = amps[ref].len; + int namp = amps[ref].namp; + + if (max_len+1 > pos2size) { + if (!(pos2start = realloc(pos2start, (max_len+1)*sizeof(*pos2start)))) + return -1; + if (!(pos2end = realloc(pos2end, (max_len+1)*sizeof(*pos2end)))) + return -1; + pos2size = max_len; + } + for (i = 0; i < max_len; i++) + pos2start[i] = pos2end[i] = -1; + + for (i = 0; i < namp; i++) { + for (j = 0; j < amp[i].nleft; j++) { + int64_t p; + for (p = amp[i].left[j] - args->max_delta; + p <= amp[i].left[j] + args->max_delta; p++) { + if (p < 1 || p > max_len) + continue; + pos2start[p-1] = i; + } + } + for (j = 0; j < amp[i].nright; j++) { + int64_t p; + for (p = amp[i].right[j] - args->max_delta; + p <= amp[i].right[j] + args->max_delta; p++) { + if (p < 1 || p > max_len) + continue; + pos2end[p-1] = i; + } + } + } + + return 0; +} + +// Counts amplicons. +// Assumption: input BED file alternates between LEFT and RIGHT primers +// per amplicon, thus we can count the number based on the switching +// orientation. +static int count_amplicon(bed_entry_list_t *sites) { + int i, namp, last_rev = 0; + for (i = namp = 0; i < sites->length; i++) { + if (sites->bp[i].rev == 0 && last_rev) + namp++; + last_rev = sites->bp[i].rev; + } + + return ++namp; +} + +// We're only interest in the internal part of the amplicon. +// Our bed file has LEFT start/end followed by RIGHT start/end, +// so collapse these to LEFT end / RIGHT start. +// +// Returns right most amplicon position on success, +// < 0 on error +static int64_t bed2amplicon(astats_args_t *args, bed_entry_list_t *sites, + amplicon_t *amp, int *namp, int do_title, + const char *ref, int first_amp) { + int i, j; + int64_t max_right = 0; + FILE *ofp = args->out_fp; + + *namp = 0; + + // Assume all primers for the same amplicon are adjacent in BED + // with all + followed by all -. Thus - to + signifies next primer set. + int last_rev = 0; + amp[0].max_left = 0; + amp[0].min_right = INT64_MAX; + amp[0].min_left = INT64_MAX; + amp[0].max_right = 0; + if (do_title) { + fprintf(ofp, "# Amplicon locations from BED file.\n"); + fprintf(ofp, "# LEFT/RIGHT are - format and " + "comma-separated for alt-primers.\n"); + if (args->multi_ref) + fprintf(ofp, "#\n# AMPLICON\tREF\tNUMBER\tLEFT\tRIGHT\n"); + else + fprintf(ofp, "#\n# AMPLICON\tNUMBER\tLEFT\tRIGHT\n"); + } + for (i = j = 0; i < sites->length; i++) { + if (i == 0 && sites->bp[i].rev != 0) { + fprintf(samtools_stderr, "[ampliconstats] error: BED file should start" + " with the + strand primer\n"); + return -1; + } + if (sites->bp[i].rev == 0 && last_rev) { + j++; + if (j >= args->max_amp) { + fprintf(samtools_stderr, "[ampliconstats] error: too many amplicons" + " (%d). Use -a option to raise this.\n", j); + return -1; + } + amp[j].max_left = 0; + amp[j].min_right = INT64_MAX; + amp[j].min_left = INT64_MAX; + amp[j].max_right = 0; + } + if (sites->bp[i].rev == 0) { + if (i == 0 || last_rev) { + if (j>0) fprintf(ofp, "\n"); + if (args->multi_ref) + fprintf(ofp, "AMPLICON\t%s\t%d", ref, j+1 + first_amp); + else + fprintf(ofp, "AMPLICON\t%d", j+1); + } + if (amp[j].nleft >= MAX_PRIMER_PER_AMPLICON) { + print_error_errno("ampliconstats", + "too many primers per amplicon (%d).\n", + MAX_PRIMER_PER_AMPLICON); + return -1; + } + amp[j].left[amp[j].nleft++] = sites->bp[i].right; + if (amp[j].max_left < sites->bp[i].right+1) + amp[j].max_left = sites->bp[i].right+1; + if (amp[j].min_left > sites->bp[i].right+1) + amp[j].min_left = sites->bp[i].right+1; + // BED file, so left+1 as zero based. right(+1-1) as + // BED goes one beyond end (and we want inclusive range). + fprintf(ofp, "%c%"PRId64"-%"PRId64, "\t,"[amp[j].nleft > 1], + sites->bp[i].left+1, sites->bp[i].right); + } else { + if (amp[j].nright >= MAX_PRIMER_PER_AMPLICON) { + print_error_errno("ampliconstats", + "too many primers per amplicon (%d)", + MAX_PRIMER_PER_AMPLICON); + return -1; + } + amp[j].right[amp[j].nright++] = sites->bp[i].left; + if (amp[j].min_right > sites->bp[i].left-1) + amp[j].min_right = sites->bp[i].left-1; + if (amp[j].max_right < sites->bp[i].left-1) { + amp[j].max_right = sites->bp[i].left-1; + if (amp[j].max_right - amp[j].min_left + 1 >= + args->max_amp_len) { + fprintf(samtools_stderr, "[ampliconstats] error: amplicon " + "longer (%d) than max_amp_len option (%d)\n", + (int)(amp[j].max_right - amp[j].min_left + 2), + args->max_amp_len); + return -1; + } + if (max_right < amp[j].max_right) + max_right = amp[j].max_right; + } + fprintf(ofp, "%c%"PRId64"-%"PRId64, "\t,"[amp[j].nright > 1], + sites->bp[i].left+1, sites->bp[i].right); + } + last_rev = sites->bp[i].rev; + } + if (last_rev != 1) { + fprintf(ofp, "\n"); // useful if going to samtools_stdout + fprintf(samtools_stderr, "[ampliconstats] error: bed file does not end on" + " a reverse strand primer.\n"); + return -1; + } + *namp = ++j; + if (j) fprintf(ofp, "\n"); + + if (j >= args->max_amp) { + fprintf(samtools_stderr, "[ampliconstats] error: " + "too many amplicons (%d). Use -a option to raise this.", j); + return -1; + } + +// for (i = 0; i < *namp; i++) { +// fprintf(samtools_stdout, "%d\t%ld", i, amp[i].length); +// for (j = 0; j < amp[i].nleft; j++) +// fprintf(samtools_stdout, "%c%ld", "\t,"[j>0], amp[i].left[j]); +// for (j = 0; j < amp[i].nright; j++) +// fprintf(samtools_stdout, "%c%ld", "\t,"[j>0], amp[i].right[j]); +// fprintf(samtools_stdout, "\n"); +// } + + return max_right; +} + +void stats_free(astats_t *st) { + if (!st) + return; + + free(st->nreads); + free(st->nreads2); + free(st->nfull_reads); + free(st->nrperc); + free(st->nrperc2); + free(st->nbases); + free(st->nbases2); + free(st->coverage); + free(st->covered_perc); + free(st->covered_perc2); + free(st->amp_dist); + + free(st->depth_valid); + free(st->depth_all); + + if (st->tcoord) { + int i; + for (i = 0; i <= st->max_amp; i++) { + if (st->tcoord[i]) + kh_destroy(tcoord, st->tcoord[i]); + } + free(st->tcoord); + } + + khiter_t k; + for (k = kh_begin(st->qend); k != kh_end(st->qend); k++) + if (kh_exist(st->qend, k)) + free((void *)kh_key(st->qend, k)); + kh_destroy(qname, st->qend); + + free(st); +} + +astats_t *stats_alloc(int64_t max_len, int max_amp, int max_amp_len) { + astats_t *st = calloc(1, sizeof(*st)); + if (!st) + return NULL; + + st->max_amp = max_amp; + st->max_amp_len = max_amp_len; + st->max_len = max_len; + + if (!(st->nreads = calloc(max_amp, sizeof(*st->nreads)))) goto err; + if (!(st->nreads2 = calloc(max_amp, sizeof(*st->nreads2)))) goto err; + if (!(st->nrperc = calloc(max_amp, sizeof(*st->nrperc)))) goto err; + if (!(st->nrperc2 = calloc(max_amp, sizeof(*st->nrperc2)))) goto err; + if (!(st->nbases = calloc(max_amp, sizeof(*st->nbases)))) goto err; + if (!(st->nbases2 = calloc(max_amp, sizeof(*st->nbases2)))) goto err; + + if (!(st->nfull_reads = calloc(max_amp, sizeof(*st->nfull_reads)))) + goto err; + + if (!(st->coverage = calloc(max_amp*max_amp_len, sizeof(*st->coverage)))) + goto err; + + if (!(st->covered_perc = calloc(max_amp, sizeof(*st->covered_perc)))) + goto err; + if (!(st->covered_perc2 = calloc(max_amp, sizeof(*st->covered_perc2)))) + goto err; + + if (!(st->tcoord = calloc(max_amp+1, sizeof(*st->tcoord)))) goto err; + int i; + for (i = 0; i <= st->max_amp; i++) + if (!(st->tcoord[i] = kh_init(tcoord))) + goto err; + + if (!(st->qend = kh_init(qname))) + goto err; + + if (!(st->depth_valid = calloc(max_len, sizeof(*st->depth_valid)))) + goto err; + if (!(st->depth_all = calloc(max_len, sizeof(*st->depth_all)))) + goto err; + + if (!(st->amp_dist = calloc(max_amp, sizeof(*st->amp_dist)))) goto err; + + return st; + + err: + stats_free(st); + return NULL; +} + +static void stats_reset(astats_t *st) { + st->nseq = 0; + st->nfiltered = 0; + st->nfailprimer = 0; + + memset(st->nreads, 0, st->max_amp * sizeof(*st->nreads)); + memset(st->nreads2, 0, st->max_amp * sizeof(*st->nreads2)); + memset(st->nfull_reads, 0, st->max_amp * sizeof(*st->nfull_reads)); + + memset(st->nrperc, 0, st->max_amp * sizeof(*st->nrperc)); + memset(st->nrperc2, 0, st->max_amp * sizeof(*st->nrperc2)); + + memset(st->nbases, 0, st->max_amp * sizeof(*st->nbases)); + memset(st->nbases2, 0, st->max_amp * sizeof(*st->nbases2)); + + memset(st->coverage, 0, st->max_amp * st->max_amp_len + * sizeof(*st->coverage)); + memset(st->covered_perc, 0, st->max_amp * sizeof(*st->covered_perc)); + memset(st->covered_perc2, 0, st->max_amp * sizeof(*st->covered_perc2)); + + // Keep the allocated entries as it's likely all files will share + // the same keys. Instead we reset counters to zero for common ones + // and delete rare ones. + int i; + for (i = 0; i <= st->max_amp; i++) { + khiter_t k; + for (k = kh_begin(st->tcoord[i]); + k != kh_end(st->tcoord[i]); k++) + if (kh_exist(st->tcoord[i], k)) { + if (kh_value(st->tcoord[i], k) < 5) + kh_del(tcoord, st->tcoord[i], k); + else + kh_value(st->tcoord[i], k) = 0; + } + } + + khiter_t k; + for (k = kh_begin(st->qend); k != kh_end(st->qend); k++) + if (kh_exist(st->qend, k)) + free((void *)kh_key(st->qend, k)); + kh_clear(qname, st->qend); + + memset(st->depth_valid, 0, st->max_len * sizeof(*st->depth_valid)); + memset(st->depth_all, 0, st->max_len * sizeof(*st->depth_all)); + memset(st->amp_dist, 0, st->max_amp * sizeof(*st->amp_dist)); +} + +static void amp_stats_reset(amplicons_t *amps, int nref) { + int i; + for (i = 0; i < nref; i++) { + if (!amps[i].sites) + continue; + stats_reset(amps[i].lstats); + } +} + +static int accumulate_stats(astats_args_t *args, amplicons_t *amps, + bam1_t *b) { + int ref = b->core.tid; + amplicon_t *amp = amps[ref].amp; + astats_t *stats = amps[ref].lstats; + int len = amps[ref].len; + + if (!stats) + return 0; + + stats->nseq++; + if ((b->core.flag & args->flag_require) != args->flag_require || + (b->core.flag & args->flag_filter) != 0) { + stats->nfiltered++; + return 0; + } + + int64_t start = b->core.pos, mstart = start; // modified start + int64_t end = bam_endpos(b), i; + + // Compute all-template-depth and valid-template-depth. + // We track current end location per read name so we can remove overlaps. + // Potentially we could use this data for a better amplicon-depth + // count too, but for now it's purely for the per-base plots. + int ret; + khiter_t k; + int prev_start = 0, prev_end = 0; + if ((b->core.flag & BAM_FPAIRED) + && !(b->core.flag & (BAM_FSUPPLEMENTARY | BAM_FSECONDARY))) { + k = kh_put(qname, stats->qend, bam_get_qname(b), &ret); + if (ret == 0) { + prev_start = kh_value(stats->qend, k) & 0xffffffff; + prev_end = kh_value(stats->qend, k)>>32; + mstart = MAX(mstart, prev_end); + // Ideally we'd reuse strings so we don't thrash free/malloc. + // However let's see if the official way of doing that (malloc + // itself) is fast enough first. + free((void *)kh_key(stats->qend, k)); + kh_del(qname, stats->qend, k); + //fprintf(samtools_stderr, "remove overlap %d to %d\n", (int)start, (int)mstart); + } else { + if (!(kh_key(stats->qend, k) = strdup(bam_get_qname(b)))) + return -1; + + kh_value(stats->qend, k) = start | (end << 32); + } + } + for (i = mstart; i < end && i < len; i++) + stats->depth_all[i]++; + if (i < end) { + print_error("ampliconstats", "record %s overhangs end of reference", + bam_get_qname(b)); + // But keep going, as it's harmless. + } + + // On single ended runs, eg ONT or PacBio, we just use the start/end + // of the template to assign. + int anum = (b->core.flag & BAM_FREVERSE) || !(b->core.flag & BAM_FPAIRED) + ? (end-1 >= 0 && end-1 < len ? pos2end[end-1] : -1) + : (start >= 0 && start < len ? pos2start[start] : -1); + + // ivar sometimes soft-clips 100% of the bases. + // This is essentially unmapped + if (end == start && (args->flag_filter & BAM_FUNMAP)) { + stats->nfiltered++; + return 0; + } + + if (anum == -1) + stats->nfailprimer++; + + if (anum >= 0) { + int64_t c = MIN(end,amp[anum].min_right+1) - MAX(start,amp[anum].max_left); + if (c > 0) { + stats->nreads[anum]++; + // NB: ref bases rather than read bases + stats->nbases[anum] += c; + + int64_t i; + if (start < 0) start = 0; + if (end > len) end = len; + + int64_t ostart = MAX(start, amp[anum].min_left-1); + int64_t oend = MIN(end, amp[anum].max_right); + int64_t offset = amp[anum].min_left-1; + for (i = ostart; i < oend; i++) + stats->coverage[anum*stats->max_amp_len + i-offset]++; + } else { + stats->nfailprimer++; + } + } + + // Template length in terms of amplicon number to amplicon number. + // We expect left to right of same amplicon (len 0), but it may go + // to next amplicon (len 1) or prev (len -1), etc. + int64_t t_end; + int oth_anum = -1; + + if (b->core.flag & BAM_FPAIRED) { + t_end = (b->core.flag & BAM_FREVERSE ? end : start) + + b->core.isize; + + // If we've clipped the primers but not followed up with a fixmates + // then our start+TLEN will take us to a location which is + // length(LEFT_PRIMER) + length(RIGHT_PRIMER) too far away. + // + // The correct solution is to run samtools fixmate so TLEN is correct. + // The hacky solution is to fudge the expected tlen by double the + // average primer length (e.g. 50). + t_end += b->core.isize > 0 ? -args->tlen_adj : +args->tlen_adj; + + if (t_end > 0 && t_end < len && b->core.isize != 0) + oth_anum = (b->core.flag & BAM_FREVERSE) + ? pos2start[t_end] + : pos2end[t_end]; + } else { + // Not paired (see int anum = (REV || !PAIR) ?en :st expr above) + oth_anum = pos2start[start]; + t_end = end; + } + + // We don't want to count our pairs twice. + // If both left/right are known, count it on left only. + // If only one is known, we'll only get to this code once + // so we can also count it. + int astatus = 2; + if (anum != -1 && oth_anum != -1) { + astatus = oth_anum == anum ? 0 : 1; + if (start <= t_end) + stats->amp_dist[anum][astatus]++; + } else if (anum >= 0) { + stats->amp_dist[anum][astatus = 2]++; + } + + if (astatus == 0 && !(b->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))) { + if (prev_end && mstart > prev_end) { + // 2nd read with gap to 1st; undo previous increment. + for (i = prev_start; i < prev_end; i++) + stats->depth_valid[i]--; + stats->nfull_reads[anum] -= (b->core.flag & BAM_FPAIRED) ? 0.5 : 1; + } else { + // 1st read, or 2nd read that overlaps 1st + for (i = mstart; i < end; i++) + stats->depth_valid[i]++; + stats->nfull_reads[anum] += (b->core.flag & BAM_FPAIRED) ? 0.5 : 1; + } + } + + // Track template start,end frequencies, so we can give stats on + // amplicon primer usage. + if ((b->core.flag & BAM_FPAIRED) && b->core.isize <= 0) + // left to right only, so we don't double count template positions. + return 0; + + start = b->core.pos; + t_end = b->core.flag & BAM_FPAIRED + ? start + b->core.isize-1 + : end; + uint64_t tcoord = MIN(start+1, UINT32_MAX) | (MIN(t_end+1, UINT32_MAX)<<32); + k = kh_put(tcoord, stats->tcoord[anum+1], tcoord, &ret); + if (ret < 0) + return -1; + if (ret == 0) + kh_value(stats->tcoord[anum+1], k)++; + else + kh_value(stats->tcoord[anum+1], k)=1; + kh_value(stats->tcoord[anum+1], k) |= ((int64_t)astatus<<32); + + return 0; +} + +// Append file local stats to global stats +int append_lstats(astats_t *lstats, astats_t *gstats, int namp, int all_nseq) { + gstats->nseq += lstats->nseq; + gstats->nfiltered += lstats->nfiltered; + gstats->nfailprimer += lstats->nfailprimer; + + int a; + for (a = -1; a < namp; a++) { + // Add khash local (kl) to khash global (kg) + khiter_t kl, kg; + for (kl = kh_begin(lstats->tcoord[a+1]); + kl != kh_end(lstats->tcoord[a+1]); kl++) { + if (!kh_exist(lstats->tcoord[a+1], kl) || + kh_value(lstats->tcoord[a+1], kl) == 0) + continue; + + int ret; + kg = kh_put(tcoord, gstats->tcoord[a+1], + kh_key(lstats->tcoord[a+1], kl), + &ret); + if (ret < 0) + return -1; + + kh_value(gstats->tcoord[a+1], kg) = + (ret == 0 + ? (kh_value(gstats->tcoord[a+1], kg) & 0xFFFFFFFF) + : 0) + + kh_value(lstats->tcoord[a+1], kl); + } + if (a == -1) continue; + + gstats->nreads[a] += lstats->nreads[a]; + gstats->nreads2[a] += lstats->nreads[a] * lstats->nreads[a]; + gstats->nfull_reads[a] += lstats->nfull_reads[a]; + + // To get mean & sd for amplicon read percentage, we need + // to do the divisions here as nseq differs for each sample. + double nrperc = all_nseq ? 100.0 * lstats->nreads[a] / all_nseq : 0; + gstats->nrperc[a] += nrperc; + gstats->nrperc2[a] += nrperc*nrperc; + + gstats->nbases[a] += lstats->nbases[a]; + gstats->nbases2[a] += lstats->nbases[a] * lstats->nbases[a]; + + int d; + for (d = 0; d < MAX_DEPTH; d++) { + gstats->covered_perc[a][d] += lstats->covered_perc[a][d]; + gstats->covered_perc2[a][d] += lstats->covered_perc[a][d] + * lstats->covered_perc[a][d]; + } + + for (d = 0; d < 3; d++) + gstats->amp_dist[a][d] += lstats->amp_dist[a][d]; + } + + for (a = 0; a < lstats->max_len; a++) { + gstats->depth_valid[a] += lstats->depth_valid[a]; + gstats->depth_all[a] += lstats->depth_all[a]; + } + + return 0; +} + +int append_stats(amplicons_t *amps, int nref) { + int i, r, all_nseq = 0; + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = amps[r].lstats; + all_nseq += stats->nseq - stats->nfiltered - stats->nfailprimer; + } + + for (i = 0; i < nref; i++) { + if (!amps[i].sites) + continue; + if (append_lstats(amps[i].lstats, amps[i].gstats, amps[i].namp, + all_nseq) < 0) + return -1; + } + + return 0; +} + +typedef struct { + int32_t start, end; + uint32_t freq; + uint32_t status; +} tcoord_t; + +// Sort tcoord by descending frequency and then ascending start and end. +static int tcoord_freq_sort(const void *vp1, const void *vp2) { + const tcoord_t *t1 = (const tcoord_t *)vp1; + const tcoord_t *t2 = (const tcoord_t *)vp2; + + if (t1->freq != t2->freq) + return t2->freq - t1->freq; + + if (t1->start != t2->start) + return t1->start - t2->start; + + return t1->end - t2->end; +} + + +/* + * Merges tcoord start,end,freq,status tuples if their coordinates are + * close together. We aim to keep the start,end for the most frequent + * value and assume that is the correct coordinate and all others are + * minor fluctuations due to errors or variants. + * + * We sort by frequency first and then merge later items in the list into + * the earlier more frequent ones. It's O(N^2), but sufficient for now + * given current scale of projects. + * + * If we ever need to resolve that then consider sorting by start + * coordinate and scanning the list to find all items within X, find + * the most frequent of those, and then cluster that way. (I'd have + * done that had I thought of it at the time!) + */ +static void aggregate_tcoord(astats_args_t *args, tcoord_t *tpos, size_t *np){ + size_t n = *np, j, j2, j3, k; + + // Sort by frequency and cluster infrequent coords into frequent + // ones provided they're close by. + // This is O(N^2), but we've already binned by tcoord_bin/2 so + // the list isn't intended to be vast at this point. + qsort(tpos, n, sizeof(*tpos), tcoord_freq_sort); + + // For frequency ties, find mid start coord, and then find mid end + // coord of those matching start. + // We make that the first item so we merge into that mid point. + for (j = 0; j < n; j++) { + for (j2 = j+1; j2 < n; j2++) { + if (tpos[j].freq != tpos[j2].freq) + break; + if (tpos[j2].start - tpos[j].start >= args->tcoord_bin) + break; + } + + // j to j2 all within bin of a common start, + // m is the mid start. + if (j2-1 > j) { + size_t m = (j2-1 + j)/2; + + // Find mid end for this same start + while (m > 1 && tpos[m].start == tpos[m-1].start) + m--; + for (j3 = m+1; j3 < j2; j3++) { + if (tpos[m].start != tpos[j3].start) + break; + if (tpos[m].end - tpos[j3].end >= args->tcoord_bin) + break; + } + if (j3-1 > m) + m = (j3-1 + m)/2; + + // Swap with first item. + tcoord_t tmp = tpos[j]; + tpos[j] = tpos[m]; + tpos[m] = tmp; + j = j2-1; + } + } + + // Now merge in coordinates. + // This bit is O(N^2), so consider binning first to reduce the + // size of the list if we have excessive positional variation. + for (k = j = 0; j < n; j++) { + if (!tpos[j].freq) + continue; + + if (k < j) + tpos[k] = tpos[j]; + + for (j2 = j+1; j2 < n; j2++) { + if (ABS(tpos[j].start-tpos[j2].start) < args->tcoord_bin/2 && + ABS(tpos[j].end -tpos[j2].end) < args->tcoord_bin/2 && + tpos[j].status == tpos[j2].status) { + tpos[k].freq += tpos[j2].freq; + tpos[j2].freq = 0; + } + } + k++; + } + + *np = k; +} + +int dump_stats(astats_args_t *args, char type, char *name, int nfile, + amplicons_t *amps, int nref, int local) { + int i, r; + FILE *ofp = args->out_fp; + tcoord_t *tpos = NULL; + size_t ntcoord = 0; + + // summary stats for this sample (or for all samples) + fprintf(ofp, "# Summary stats.\n"); + fprintf(ofp, "# Use 'grep ^%cSS | cut -f 2-' to extract this part.\n", type); + + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + int nmatch = stats->nseq - stats->nfiltered - stats->nfailprimer; + char *name_ref = malloc(strlen(name) + strlen(amps[r].ref) + 2); + if (!name_ref) + return -1; + if (args->multi_ref) + sprintf(name_ref, "%s\t%s", name, amps[r].ref); + else + sprintf(name_ref, "%s", name); + fprintf(ofp, "%cSS\t%s\traw total sequences:\t%d\n", + type, name_ref, stats->nseq); + fprintf(ofp, "%cSS\t%s\tfiltered sequences:\t%d\n", + type, name_ref, stats->nfiltered); + fprintf(ofp, "%cSS\t%s\tfailed primer match:\t%d\n", + type, name_ref, stats->nfailprimer); + fprintf(ofp, "%cSS\t%s\tmatching sequences:\t%d\n", + type, name_ref, nmatch); + + int d = 0; + do { + // From first to last amplicon only, so not entire consensus. + // If contig length is known, maybe we want to add the missing + // count to < DEPTH figures? + int64_t start = 0, covered = 0, total = 0; + amplicon_t *amp = amps[r].amp; + for (i = 0; i < amps[r].namp; i++) { + int64_t j, offset = amp[i].min_left-1; + if (amp[i].min_right - amp[i].min_left > stats->max_amp_len) { + fprintf(samtools_stderr, "[ampliconstats] error: " + "Maximum amplicon length (%d) exceeded for '%s'\n", + stats->max_amp, name); + return -1; + } + for (j = MAX(start, amp[i].max_left-1); + j < MAX(start, amp[i].min_right); j++) { + if (stats->coverage[i*stats->max_amp_len + j-offset] + >= args->min_depth[d]) + covered++; + total++; + } + start = MAX(start, amp[i].min_right); + } + fprintf(ofp, "%cSS\t%s\tconsensus depth count < %d and >= %d:\t%" + PRId64"\t%"PRId64"\n", type, name_ref, + args->min_depth[d], args->min_depth[d], + total-covered, covered); + } while (++d < MAX_DEPTH && args->min_depth[d]); + + free(name_ref); + } + + // Read count + fprintf(ofp, "# Absolute matching read counts per amplicon.\n"); + fprintf(ofp, "# Use 'grep ^%cREADS | cut -f 2-' to extract this part.\n", type); + fprintf(ofp, "%cREADS\t%s", type, name); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + fprintf(ofp, "\t%"PRId64, stats->nreads[i]); + } + } + fprintf(ofp, "\n"); + + // Valid depth is the number of full length reads (already divided + // by the number we expect to cover), so +0.5 per read in pair. + // A.k.a "usable depth" in the plots. + fprintf(ofp, "%cVDEPTH\t%s", type, name); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) + fprintf(ofp, "\t%d", (int)stats->nfull_reads[i]); + } + fprintf(ofp, "\n"); + + if (type == 'C') { + // For combined we can compute mean & standard deviation too + fprintf(ofp, "CREADS\tMEAN"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + fprintf(ofp, "\t%.1f", stats->nreads[i] / (double)nfile); + } + } + fprintf(ofp, "\n"); + + fprintf(ofp, "CREADS\tSTDDEV"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + double n1 = stats->nreads[i]; + fprintf(ofp, "\t%.1f", nfile > 1 && stats->nreads2[i] > 0 + ? sqrt(stats->nreads2[i]/(double)nfile + - (n1/nfile)*(n1/nfile)) + : 0); + } + } + fprintf(ofp, "\n"); + } + + fprintf(ofp, "# Read percentage of distribution between amplicons.\n"); + fprintf(ofp, "# Use 'grep ^%cRPERC | cut -f 2-' to extract this part.\n", type); + fprintf(ofp, "%cRPERC\t%s", type, name); + int all_nseq = 0; + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + all_nseq += stats->nseq - stats->nfiltered - stats->nfailprimer; + } + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + if (type == 'C') { + fprintf(ofp, "\t%.3f", (double)stats->nrperc[i] / nfile); + } else { + fprintf(ofp, "\t%.3f", + all_nseq ? 100.0 * stats->nreads[i] / all_nseq : 0); + } + } + } + fprintf(ofp, "\n"); + + if (type == 'C') { + // For combined we compute mean and standard deviation too + fprintf(ofp, "CRPERC\tMEAN"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + fprintf(ofp, "\t%.3f", stats->nrperc[i] / nfile); + } + } + fprintf(ofp, "\n"); + + fprintf(ofp, "CRPERC\tSTDDEV"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + // variance = SUM(X^2) - ((SUM(X)^2) / N) + double n1 = stats->nrperc[i]; + double v = stats->nrperc2[i]/nfile - (n1/nfile)*(n1/nfile); + fprintf(ofp, "\t%.3f", v>0?sqrt(v):0); + } + } + fprintf(ofp, "\n"); + } + + // Base depth + fprintf(ofp, "# Read depth per amplicon.\n"); + fprintf(ofp, "# Use 'grep ^%cDEPTH | cut -f 2-' to extract this part.\n", type); + fprintf(ofp, "%cDEPTH\t%s", type, name); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + amplicon_t *amp = amps[r].amp; + for (i = 0; i < amps[r].namp; i++) { + int nseq = stats->nseq - stats->nfiltered - stats->nfailprimer; + int64_t alen = amp[i].min_right - amp[i].max_left+1; + fprintf(ofp, "\t%.1f", nseq ? stats->nbases[i] / (double)alen : 0); + } + } + fprintf(ofp, "\n"); + + if (type == 'C') { + // For combined we can compute mean & standard deviation too + fprintf(ofp, "CDEPTH\tMEAN"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + amplicon_t *amp = amps[r].amp; + int nseq = stats->nseq - stats->nfiltered - stats->nfailprimer; + for (i = 0; i < amps[r].namp; i++) { + int64_t alen = amp[i].min_right - amp[i].max_left+1; + fprintf(ofp, "\t%.1f", nseq ? stats->nbases[i] / (double)alen / nfile : 0); + } + } + fprintf(ofp, "\n"); + + fprintf(ofp, "CDEPTH\tSTDDEV"); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + amplicon_t *amp = amps[r].amp; + for (i = 0; i < amps[r].namp; i++) { + double alen = amp[i].min_right - amp[i].max_left+1; + double n1 = stats->nbases[i] / alen; + double v = stats->nbases2[i] / (alen*alen) /nfile + - (n1/nfile)*(n1/nfile); + fprintf(ofp, "\t%.1f", v>0?sqrt(v):0); + } + } + fprintf(ofp, "\n"); + } + + // Percent Coverage + if (type == 'F') { + fprintf(ofp, "# Percentage coverage per amplicon\n"); + fprintf(ofp, "# Use 'grep ^%cPCOV | cut -f 2-' to extract this part.\n", type); + int d = 0; + do { + fprintf(ofp, "%cPCOV-%d\t%s", type, args->min_depth[d], name); + + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + amplicon_t *amp = amps[r].amp; + for (i = 0; i < amps[r].namp; i++) { + int covered = 0; + if (amp[i].min_right - amp[i].min_left > stats->max_amp_len) { + fprintf(samtools_stderr, "[ampliconstats] error: " + "Maximum amplicon length (%d) exceeded for '%s'\n", + stats->max_amp, name); + return -1; + } + int64_t j, offset = amp[i].min_left-1; + for (j = amp[i].max_left-1; j < amp[i].min_right; j++) { + int apos = i*stats->max_amp_len + j-offset; + if (stats->coverage[apos] >= args->min_depth[d]) + covered++; + } + int64_t alen = amp[i].min_right - amp[i].max_left+1; + stats->covered_perc[i][d] = 100.0 * covered / alen; + fprintf(ofp, "\t%.2f", 100.0 * covered / alen); + } + } + fprintf(ofp, "\n"); + } while (++d < MAX_DEPTH && args->min_depth[d]); + + } else if (type == 'C') { + // For combined we can compute mean & standard deviation too + int d = 0; + do { + fprintf(ofp, "CPCOV-%d\tMEAN", args->min_depth[d]); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + fprintf(ofp, "\t%.1f", stats->covered_perc[i][d] / nfile); + } + } + fprintf(ofp, "\n"); + + fprintf(ofp, "CPCOV-%d\tSTDDEV", args->min_depth[d]); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + double n1 = stats->covered_perc[i][d] / nfile; + double v = stats->covered_perc2[i][d] / nfile - n1*n1; + fprintf(ofp, "\t%.1f", v>0?sqrt(v):0); + } + } + fprintf(ofp, "\n"); + } while (++d < MAX_DEPTH && args->min_depth[d]); + } + + // Plus base depth for all reads, irrespective of amplicon. + // This is post overlap removal, if reads in the read-pair overlap. + fprintf(ofp, "# Depth per reference base for ALL data.\n"); + fprintf(ofp, "# Use 'grep ^%cDP_ALL | cut -f 2-' to extract this part.\n", + type); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + if (args->multi_ref) + fprintf(ofp, "%cDP_ALL\t%s\t%s", type, name, amps[r].ref); + else + fprintf(ofp, "%cDP_ALL\t%s", type, name); + + for (i = 0; i < amps[r].len; i++) { + // Basic run-length encoding provided all values are within + // +- depth_bin fraction of the mid-point. + int dmin = stats->depth_all[i], dmax = stats->depth_all[i], j; + double dmid = (dmin + dmax)/2.0; + double low = dmid*(1-args->depth_bin); + double high = dmid*(1+args->depth_bin); + for (j = i+1; j < amps[r].len; j++) { + int d = stats->depth_all[j]; + if (d < low || d > high) + break; + if (dmin > d) { + dmin = d; + dmid = (dmin + dmax)/2.0; + low = dmid*(1-args->depth_bin); + high = dmid*(1+args->depth_bin); + } else if (dmax < d) { + dmax = d; + dmid = (dmin + dmax)/2.0; + low = dmid*(1-args->depth_bin); + high = dmid*(1+args->depth_bin); + } + } + fprintf(ofp, "\t%d,%d", (int)dmid, j-i); + i = j-1; + } + fprintf(ofp, "\n"); + } + + // And depth for only reads matching to a single amplicon for full + // length. This is post read overlap removal. + fprintf(ofp, "# Depth per reference base for full-length valid amplicon data.\n"); + fprintf(ofp, "# Use 'grep ^%cDP_VALID | cut -f 2-' to extract this " + "part.\n", type); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + if (args->multi_ref) + fprintf(ofp, "%cDP_VALID\t%s\t%s", type, name, amps[r].ref); + else + fprintf(ofp, "%cDP_VALID\t%s", type, name); + + for (i = 0; i < amps[r].len; i++) { + int dmin = stats->depth_valid[i], dmax = stats->depth_valid[i], j; + double dmid = (dmin + dmax)/2.0; + double low = dmid*(1-args->depth_bin); + double high = dmid*(1+args->depth_bin); + for (j = i+1; j < amps[r].len; j++) { + int d = stats->depth_valid[j]; + if (d < low || d > high) + break; + if (dmin > d) { + dmin = d; + dmid = (dmin + dmax)/2.0; + low = dmid*(1-args->depth_bin); + high = dmid*(1+args->depth_bin); + } else if (dmax < d) { + dmax = d; + dmid = (dmin + dmax)/2.0; + low = dmid*(1-args->depth_bin); + high = dmid*(1+args->depth_bin); + } + } + fprintf(ofp, "\t%d,%d", (int)dmid, j-i); + i = j-1; + } + fprintf(ofp, "\n"); + } + + // TCOORD (start to end) distribution + fprintf(ofp, "# Distribution of aligned template coordinates.\n"); + fprintf(ofp, "# Use 'grep ^%cTCOORD | cut -f 2-' to extract this part.\n", type); + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0 - (nref==1); i < amps[r].namp; i++) { + if (ntcoord < kh_size(stats->tcoord[i+1])) { + ntcoord = kh_size(stats->tcoord[i+1]); + tcoord_t *tmp = realloc(tpos, ntcoord * sizeof(*tmp)); + if (!tmp) { + free(tpos); + return -1; + } + tpos = tmp; + } + + khiter_t k; + size_t n = 0, j; + for (k = kh_begin(stats->tcoord[i+1]); + k != kh_end(stats->tcoord[i+1]); k++) { + if (!kh_exist(stats->tcoord[i+1], k) || + (kh_value(stats->tcoord[i+1], k) & 0xFFFFFFFF) == 0) + continue; + // Key is start,end in 32-bit quantities. + // Yes this limits us to 4Gb references, but just how + // many primers are we planning on making? Not that many + // I hope. + tpos[n].start = kh_key(stats->tcoord[i+1], k)&0xffffffff; + tpos[n].end = kh_key(stats->tcoord[i+1], k)>>32; + + // Value is frequency (top 32-bits) and status (bottom 32). + tpos[n].freq = kh_value(stats->tcoord[i+1], k)&0xffffffff; + tpos[n].status = kh_value(stats->tcoord[i+1], k)>>32; + n++; + } + + if (args->tcoord_bin > 1) + aggregate_tcoord(args, tpos, &n); + + fprintf(ofp, "%cTCOORD\t%s\t%d", type, name, + i+1+amps[r].first_amp); // per amplicon + for (j = 0; j < n; j++) { + if (tpos[j].freq < args->tcoord_min_count) + continue; + fprintf(ofp, "\t%d,%d,%u,%u", + tpos[j].start, + tpos[j].end, + tpos[j].freq, + tpos[j].status); + } + fprintf(ofp, "\n"); + } + } + + + // AMP length distribution. + // 0 = both ends in this amplicon + // 1 = ends in different amplicons + // 2 = other end matching an unknown amplicon site + // (see tcoord for further analysis of where) + fprintf(ofp, "# Classification of amplicon status. Columns are\n"); + fprintf(ofp, "# number with both primers from this amplicon, number with\n"); + fprintf(ofp, "# primers from different amplicon, and number with a position\n"); + fprintf(ofp, "# not matching any valid amplicon primer site\n"); + fprintf(ofp, "# Use 'grep ^%cAMP | cut -f 2-' to extract this part.\n", type); + + fprintf(ofp, "%cAMP\t%s\t0", type, name); // all merged + int amp_dist[3] = {0}; + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { // accumulate for all amps + amp_dist[0] += stats->amp_dist[i][0]; + amp_dist[1] += stats->amp_dist[i][1]; + amp_dist[2] += stats->amp_dist[i][2]; + } + } + fprintf(ofp, "\t%d\t%d\t%d\n", amp_dist[0], amp_dist[1], amp_dist[2]); + + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + astats_t *stats = local ? amps[r].lstats : amps[r].gstats; + for (i = 0; i < amps[r].namp; i++) { + // per amplicon + fprintf(ofp, "%cAMP\t%s\t%d", type, name, i+1+amps[r].first_amp); + fprintf(ofp, "\t%d\t%d\t%d\n", stats->amp_dist[i][0], + stats->amp_dist[i][1], stats->amp_dist[i][2]); + } + } + + free(tpos); + return 0; +} + +int dump_lstats(astats_args_t *args, char type, char *name, int nfile, + amplicons_t *amps, int nref) { + return dump_stats(args, type, name, nfile, amps, nref, 1); +} + +int dump_gstats(astats_args_t *args, char type, char *name, int nfile, + amplicons_t *amps, int nref) { + return dump_stats(args, type, name, nfile, amps, nref, 0); +} + +char const *get_sample_name(sam_hdr_t *header, char *RG) { + kstring_t ks = {0}; + sam_hdr_find_tag_id(header, "RG", RG?"ID":NULL, RG, "SM", &ks); + return ks.s; +} + +// Return maximum reference length (SQ is NULL) or the length +// of the specified reference in SQ. +int64_t get_ref_len(sam_hdr_t *header, const char *SQ) { + if (SQ) { + int tid = SQ ? sam_hdr_name2tid(header, SQ) : 0; + return tid >= 0 ? sam_hdr_tid2len(header, tid) : -1; + } else { + int nref = sam_hdr_nref(header), tid;; + int64_t len = 0; + for (tid = 0; tid < nref; tid++) { + int64_t rl = sam_hdr_tid2len(header, tid); + if (len < rl) + len = rl; + } + return len; + } +} + +static int amplicon_stats(astats_args_t *args, + khash_t(bed_list_hash) *bed_hash, + char **filev, int filec) { + int i, ref = -1, ref_tid = -1, ret = -1, nref = 0; + samFile *fp = NULL; + sam_hdr_t *header = NULL; + bam1_t *b = bam_init1(); + FILE *ofp = args->out_fp; + char sname_[8192], *sname = NULL; + amplicons_t *amps = NULL; + + // Report initial SS header. We gather data from the bed_hash entries + // as well as from the first SAM header (with the requirement that all + // headers should be compatible). + if (filec) { + if (!(fp = sam_open_format(filev[0], "r", &args->ga.in))) { + print_error_errno("ampliconstats", + "Cannot open input file \"%s\"", + filev[0]); + goto err; + } + if (!(header = sam_hdr_read(fp))) + goto err; + + if (!amps) { + amps = calloc(nref=sam_hdr_nref(header), sizeof(*amps)); + if (!amps) + goto err; + fprintf(ofp, "# Summary statistics, used for scaling the plots.\n"); + fprintf(ofp, "SS\tSamtools version: %s\n", samtools_version()); + fprintf(ofp, "SS\tCommand line: %s\n", args->argv); + fprintf(ofp, "SS\tNumber of files:\t%d\n", filec); + + // Note: order of hash entries will be different to order of + // BED file which may also differ to order of SQ headers. + // SQ header is canonical ordering (pos sorted file). + khiter_t k; + int bam_nref = sam_hdr_nref(header); + for (i = 0; i < bam_nref; i++) { + k = kh_get(bed_list_hash, bed_hash, + sam_hdr_tid2name(header, i)); + if (!kh_exist(bed_hash, k)) + continue; + + bed_entry_list_t *sites = &kh_value(bed_hash, k); + + ref = i; + amps[ref].ref = kh_key(bed_hash, k); + amps[ref].sites = sites; + amps[ref].namp = count_amplicon(sites); + amps[ref].amp = calloc(sites->length, + sizeof(*amps[ref].amp)); + if (!amps[ref].amp) + goto err; + if (args->multi_ref) + fprintf(ofp, "SS\tNumber of amplicons:\t%s\t%d\n", + kh_key(bed_hash, k), amps[ref].namp); + else + fprintf(ofp, "SS\tNumber of amplicons:\t%d\n", + amps[ref].namp); + + amps[ref].tid = ref; + if (ref_tid == -1) + ref_tid = ref; + + int64_t len = get_ref_len(header, kh_key(bed_hash, k)); + amps[ref].len = len; + if (args->multi_ref) + fprintf(ofp, "SS\tReference length:\t%s\t%"PRId64"\n", + kh_key(bed_hash, k), len); + else + fprintf(ofp, "SS\tReference length:\t%"PRId64"\n", + len); + + amps[ref].lstats = stats_alloc(len, args->max_amp, + args->max_amp_len); + amps[ref].gstats = stats_alloc(len, args->max_amp, + args->max_amp_len); + if (!amps[ref].lstats || !amps[ref].gstats) + goto err; + } + } + + sam_hdr_destroy(header); + header = NULL; + if (sam_close(fp) < 0) { + fp = NULL; + goto err; + } + fp = NULL; + } + fprintf(ofp, "SS\tEnd of summary\n"); + + // Extract the bits of amplicon data we need from bed hash and turn + // it into a position-to-amplicon lookup table. + int offset = 0; + for (i = 0; i < nref; i++) { + if (!amps[i].sites) + continue; + + amps[i].first_amp = offset; + if (bed2amplicon(args, amps[i].sites, amps[i].amp, + &s[i].namp, i==0, amps[i].ref, offset) < 0) + goto err; + + offset += amps[i].namp; // cumulative amplicon number across refs + } + + // Now iterate over file contents, one at a time. + for (i = 0; i < filec; i++) { + char *nstart = filev[i]; + + fp = sam_open_format(filev[i], "r", &args->ga.in); + if (!fp) { + print_error_errno("ampliconstats", + "Cannot open input file \"%s\"", + filev[i]); + goto err; + } + + if (args->ga.nthreads > 0) + hts_set_threads(fp, args->ga.nthreads); + + if (!(header = sam_hdr_read(fp))) + goto err; + + if (nref != sam_hdr_nref(header)) { + print_error_errno("ampliconstats", + "SAM headers are not consistent across input files"); + goto err; + } + int r; + for (r = 0; r < nref; r++) { + if (!amps[r].sites) + continue; + if (!amps[r].ref || + strcmp(amps[r].ref, sam_hdr_tid2name(header, r)) != 0 || + amps[r].len != sam_hdr_tid2len(header, r)) { + print_error_errno("ampliconstats", + "SAM headers are not consistent across " + "input files"); + goto err; + } + } + + if (args->use_sample_name) + sname = (char *)get_sample_name(header, NULL); + + if (!sname) { + sname = sname_; + char *nend = filev[i] + strlen(filev[i]), *cp; + if ((cp = strrchr(filev[i], '/'))) + nstart = cp+1; + if ((cp = strrchr(nstart, '.')) && + (strcmp(cp, ".bam") == 0 || + strcmp(cp, ".sam") == 0 || + strcmp(cp, ".cram") == 0)) + nend = cp; + if (nend - nstart >= 8192) nend = nstart+8191; + memcpy(sname, nstart, nend-nstart); + sname[nend-nstart] = 0; + } + + // Stats local to this sample only + amp_stats_reset(amps, nref); + + int last_ref = -9; + while ((r = sam_read1(fp, header, b)) >= 0) { + // Other filter options useful here? + if (b->core.tid < 0) + continue; + + if (last_ref != b->core.tid) { + last_ref = b->core.tid; + if (initialise_amp_pos_lookup(args, amps, last_ref) < 0) + goto err; + } + + if (accumulate_stats(args, amps, b) < 0) + goto err; + } + + if (r < -1) { + print_error_errno("ampliconstats", "Fail reading record"); + goto err; + } + + sam_hdr_destroy(header); + if (sam_close(fp) < 0) { + fp = NULL; + goto err; + } + + fp = NULL; + header = NULL; + + if (dump_lstats(args, 'F', sname, filec, amps, nref) < 0) + goto err; + + if (append_stats(amps, nref) < 0) + goto err; + + if (sname && sname != sname_) + free(sname); + sname = NULL; + } + + if (dump_gstats(args, 'C', "COMBINED", filec, amps, nref) < 0) + goto err; + + ret = 0; + err: + bam_destroy1(b); + if (ret) { + if (header) + sam_hdr_destroy(header); + if (fp) + sam_close(fp); + } + for (i = 0; i < nref; i++) { + stats_free(amps[i].lstats); + stats_free(amps[i].gstats); + free(amps[i].amp); + } + free(amps); + free(pos2start); + free(pos2end); + if (ret) { + if (sname && sname != sname_) + free(sname); + } + + return ret; +} + +static int usage(astats_args_t *args, FILE *fp, int exit_status) { + fprintf(fp, +"\n" +"Usage: samtools ampliconstats [options] primers.bed *.bam > astats.txt\n" +"\n" +"Options:\n"); + fprintf(fp, " -f, --required-flag STR|INT\n" + " Only include reads with all of the FLAGs present [0x%X]\n",args->flag_require); + fprintf(fp, " -F, --filter-flag STR|INT\n" + " Only include reads with none of the FLAGs present [0x%X]\n",args->flag_filter & 0xffff); + fprintf(fp, " -a, --max-amplicons INT\n" + " Change the maximum number of amplicons permitted [%d]\n", MAX_AMP); + fprintf(fp, " -l, --max-amplicon-length INT\n" + " Change the maximum length of an individual amplicon [%d]\n", MAX_AMP_LEN); + fprintf(fp, " -d, --min-depth INT[,INT]...\n" + " Minimum base depth(s) to consider position covered [%d]\n", args->min_depth[0]); + fprintf(fp, " -m, --pos-margin INT\n" + " Margin of error for matching primer positions [%d]\n", args->max_delta); + fprintf(fp, " -o, --output FILE\n" + " Specify output file [samtools_stdout if unset]\n"); + fprintf(fp, " -s, --use-sample-name\n" + " Use the sample name from the first @RG header line\n"); + fprintf(fp, " -t, --tlen-adjust INT\n" + " Add/subtract from TLEN; use when clipping but no fixmate step\n"); + fprintf(fp, " -b, --tcoord-bin INT\n" + " Bin template start,end positions into multiples of INT[1]\n"); + fprintf(fp, " -c, --tcoord-min-count INT\n" + " Minimum template start,end frequency for recording [%d]\n", TCOORD_MIN_COUNT); + fprintf(fp, " -D, --depth-bin FRACTION\n" + " Merge FDP values within +/- FRACTION together\n"); + fprintf(fp, " -S, --single-ref\n" + " Force single-ref (<=1.12) output format\n"); + sam_global_opt_help(fp, "I.--.@"); + + return exit_status; +} + +int main_ampliconstats(int argc, char **argv) { + astats_args_t args = { + .ga = SAM_GLOBAL_ARGS_INIT, + .flag_require = 0, + .flag_filter = 0x10B04, + //.sites = BED_LIST_INIT, + .max_delta = 30, // large enough to cope with alt primers + .min_depth = {1}, + .use_sample_name = 0, + .max_amp = MAX_AMP, + .max_amp_len = MAX_AMP_LEN, + .tlen_adj = 0, + .out_fp = samtools_stdout, + .tcoord_min_count = TCOORD_MIN_COUNT, + .tcoord_bin = 1, + .depth_bin = 0.01, + .multi_ref = 1 + }, oargs = args; + + static const struct option loptions[] = + { + SAM_OPT_GLOBAL_OPTIONS('I', 0, '-', '-', 0, '@'), + {"help", no_argument, NULL, 'h'}, + {"flag-require", required_argument, NULL, 'f'}, + {"flag-filter", required_argument, NULL, 'F'}, + {"min-depth", required_argument, NULL, 'd'}, + {"output", required_argument, NULL, 'o'}, + {"pos-margin", required_argument, NULL, 'm'}, + {"use-sample-name", no_argument, NULL, 's'}, + {"max-amplicons", required_argument, NULL, 'a'}, + {"max-amplicon-length", required_argument, NULL, 'l'}, + {"tlen-adjust", required_argument, NULL, 't'}, + {"tcoord-min-count", required_argument, NULL, 'c'}, + {"tcoord-bin", required_argument, NULL, 'b'}, + {"depth-bin", required_argument, NULL, 'D'}, + {"single-ref", no_argument, NULL, 'S'}, + {NULL, 0, NULL, 0} + }; + int opt; + + while ( (opt=getopt_long(argc,argv,"?hf:F:@:p:m:d:sa:l:t:o:c:b:D:S",loptions,NULL))>0 ) { + switch (opt) { + case 'f': args.flag_require = bam_str2flag(optarg); break; + case 'F': + if (args.flag_filter & 0x10000) + args.flag_filter = 0; // strip default on first -F usage + args.flag_filter |= bam_str2flag(optarg); break; + + case 'm': args.max_delta = atoi(optarg); break; // margin + case 'D': args.depth_bin = atof(optarg); break; // depth bin fraction + case 'd': { + int d = 0; + char *cp = optarg, *ep; + do { + long n = strtol(cp, &ep, 10); + args.min_depth[d++] = n; + if (*ep != ',') + break; + cp = ep+1; + } while (d < MAX_DEPTH); + break; + } + + case 'a': args.max_amp = atoi(optarg)+1;break; + case 'l': args.max_amp_len = atoi(optarg)+1;break; + + case 'c': args.tcoord_min_count = atoi(optarg);break; + case 'b': + args.tcoord_bin = atoi(optarg); + if (args.tcoord_bin < 1) + args.tcoord_bin = 1; + break; + + case 't': args.tlen_adj = atoi(optarg);break; + + case 's': args.use_sample_name = 1;break; + + case 'o': + if (!(args.out_fp = fopen(optarg, "w"))) { + perror(optarg); + return 1; + } + break; + + case 'S': + args.multi_ref = 0; + break; + + case '?': return usage(&oargs, samtools_stderr, EXIT_FAILURE); + case 'h': return usage(&oargs, samtools_stdout, EXIT_SUCCESS); + + default: + if (parse_sam_global_opt(opt, optarg, loptions, &args.ga) != 0) + usage(&oargs,samtools_stderr, EXIT_FAILURE); + break; + } + } + + if (argc <= optind) + return usage(&oargs, samtools_stdout, EXIT_SUCCESS); + if (argc <= optind+1 && isatty(STDIN_FILENO)) + return usage(&oargs, samtools_stderr, EXIT_FAILURE); + + khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash); + if (load_bed_file_multi_ref(argv[optind], 1, 0, bed_hash)) { + print_error_errno("ampliconstats", + "Could not read file \"%s\"", argv[optind]); + return 1; + + } + + khiter_t k, ref_count = 0; + for (k = kh_begin(bed_hash); k != kh_end(bed_hash); k++) { + if (!kh_exist(bed_hash, k)) + continue; + ref_count++; + } + if (ref_count == 0) + return 1; + if (ref_count > 1 && args.multi_ref == 0) { + print_error("ampliconstats", + "Single-ref mode is not permitted for BED files\n" + "containing more than one reference."); + return 1; + } + + args.argv = stringify_argv(argc, argv); + int ret; + if (argc == ++optind) { + char *av = "-"; + ret = amplicon_stats(&args, bed_hash, &av, 1); + } else { + ret = amplicon_stats(&args, bed_hash, &argv[optind], argc-optind); + } + + free(args.argv); + destroy_bed_hash(bed_hash); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.c new file mode 100644 index 0000000000000000000000000000000000000000..f847f89ca3cf80b6f16da4005c787517c6730999 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.c @@ -0,0 +1,267 @@ +/* bam.c -- miscellaneous BAM functions. + + Copyright (C) 2008-2013, 2015, 2019-2020, 2022 Genome Research Ltd. + Portions copyright (C) 2009-2012 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "bam.h" +#include "htslib/kstring.h" + +// FIXME: we should also check the LB tag associated with each alignment +const char *bam_get_library(sam_hdr_t *h, const bam1_t *b) +{ + const char *rg; + kstring_t lib = { 0, 0, NULL }; + rg = (char *)bam_aux_get(b, "RG"); + + if (!rg) + return NULL; + else + rg++; + + if (sam_hdr_find_tag_id(h, "RG", "ID", rg, "LB", &lib) < 0) + return NULL; + + static char LB_text[1024]; + int len = lib.l < sizeof(LB_text) - 1 ? lib.l : sizeof(LB_text) - 1; + + memcpy(LB_text, lib.s, len); + LB_text[len] = 0; + + free(lib.s); + + return LB_text; +} + +/************ + * Remove B * + ************/ + +#define bam1_seq_seti(s, i, c) ( (s)[(i)>>1] = ((s)[(i)>>1] & 0xf<<(((i)&1)<<2)) | (c)<<((~(i)&1)<<2) ) + +int bam_remove_B(bam1_t *b) +{ + int i, j, end_j, k, l, no_qual; + uint32_t *cigar, *new_cigar; + uint8_t *seq, *qual, *p; + // test if removal is necessary + if (b->core.flag & BAM_FUNMAP) return 0; // unmapped; do nothing + cigar = bam_get_cigar(b); + for (k = 0; k < b->core.n_cigar; ++k) + if (bam_cigar_op(cigar[k]) == BAM_CBACK) break; + if (k == b->core.n_cigar) return 0; // no 'B' + if (bam_cigar_op(cigar[0]) == BAM_CBACK) goto rmB_err; // cannot be removed + // allocate memory for the new CIGAR + if (b->l_data + (b->core.n_cigar + 1) * 4 > b->m_data) { // not enough memory + b->m_data = b->l_data + b->core.n_cigar * 4; + kroundup32(b->m_data); + b->data = (uint8_t*)realloc(b->data, b->m_data); + cigar = bam_get_cigar(b); // after realloc, cigar may be changed + } + new_cigar = (uint32_t*)(b->data + (b->m_data - b->core.n_cigar * 4)); // from the end of b->data + // the core loop + seq = bam_get_seq(b); qual = bam_get_qual(b); + no_qual = (qual[0] == 0xff); // test whether base quality is available + i = j = 0; end_j = -1; + for (k = l = 0; k < b->core.n_cigar; ++k) { + int op = bam_cigar_op(cigar[k]); + int len = bam_cigar_oplen(cigar[k]); + if (op == BAM_CBACK) { // the backward operation + int t, u; + if (k == b->core.n_cigar - 1) break; // ignore 'B' at the end of CIGAR + if (len > j) goto rmB_err; // an excessively long backward + for (t = l - 1, u = 0; t >= 0; --t) { // look back + int op1 = bam_cigar_op(new_cigar[t]); + int len1 = bam_cigar_oplen(new_cigar[t]); + if (bam_cigar_type(op1)&1) { // consume the query + if (u + len1 >= len) { // stop + new_cigar[t] -= (len - u) << BAM_CIGAR_SHIFT; + break; + } else u += len1; + } + } + if (bam_cigar_oplen(new_cigar[t]) == 0) --t; // squeeze out the zero-length operation + l = t + 1; + end_j = j; j -= len; + } else { // other CIGAR operations + new_cigar[l++] = cigar[k]; + if (bam_cigar_type(op)&1) { // consume the query + if (i != j) { // no need to copy if i == j + int u, c, c0; + for (u = 0; u < len; ++u) { // construct the consensus + c = bam_seqi(seq, i+u); + if (j + u < end_j) { // in an overlap + c0 = bam_seqi(seq, j+u); + if (c != c0) { // a mismatch; choose the better base + if (qual[j+u] < qual[i+u]) { // the base in the 2nd segment is better + bam1_seq_seti(seq, j+u, c); + qual[j+u] = qual[i+u] - qual[j+u]; + } else qual[j+u] -= qual[i+u]; // the 1st is better; reduce base quality + } else qual[j+u] = qual[j+u] > qual[i+u]? qual[j+u] : qual[i+u]; + } else { // not in an overlap; copy over + bam1_seq_seti(seq, j+u, c); + qual[j+u] = qual[i+u]; + } + } + } + i += len, j += len; + } + } + } + if (no_qual) qual[0] = 0xff; // in very rare cases, this may be modified + // merge adjacent operations if possible + for (k = 1; k < l; ++k) + if (bam_cigar_op(new_cigar[k]) == bam_cigar_op(new_cigar[k-1])) + new_cigar[k] += new_cigar[k-1] >> BAM_CIGAR_SHIFT << BAM_CIGAR_SHIFT, new_cigar[k-1] &= 0xf; + // kill zero length operations + for (k = i = 0; k < l; ++k) + if (new_cigar[k] >> BAM_CIGAR_SHIFT) + new_cigar[i++] = new_cigar[k]; + l = i; + // update b + memcpy(cigar, new_cigar, l * 4); // set CIGAR + p = b->data + b->core.l_qname + l * 4; + memmove(p, seq, (j+1)>>1); p += (j+1)>>1; // set SEQ + memmove(p, qual, j); p += j; // set QUAL + memmove(p, bam_get_aux(b), bam_get_l_aux(b)); p += bam_get_l_aux(b); // set optional fields + b->core.n_cigar = l, b->core.l_qseq = j; // update CIGAR length and query length + b->l_data = p - b->data; // update record length + return 0; + +rmB_err: + b->core.flag |= BAM_FUNMAP; + return -1; +} + +/* Calculate the current read's start based on the stored cigar string. */ +hts_pos_t unclipped_start(bam1_t *b) { + uint32_t *cigar = bam_get_cigar(b); + int64_t clipped = 0; + uint32_t i; + + for (i = 0; i < b->core.n_cigar; i++) { + char c = bam_cigar_opchr(cigar[i]); + + if (c == 'S' || c == 'H') { // clips + clipped += bam_cigar_oplen(cigar[i]); + } else { + break; + } + } + + return b->core.pos - clipped + 1; +} + +/* Calculate the mate's unclipped start based on position and cigar string from MC tag. */ +hts_pos_t unclipped_other_start(hts_pos_t op, char *cigar) { + char *c = cigar; + int64_t clipped = 0; + + while (*c && *c != '*') { + long num = 0; + + if (isdigit((int)*c)) { + num = strtol(c, &c, 10); + } else { + num = 1; + } + + if (*c == 'S' || *c == 'H') { // clips + clipped += num; + } else { + break; + } + + c++; + } + + return op - clipped + 1; +} + +/* Calculate the current read's end based on the stored cigar string. */ +hts_pos_t unclipped_end(bam1_t *b) { + uint32_t *cigar = bam_get_cigar(b); + hts_pos_t end_pos, clipped = 0; + int32_t i; + + end_pos = bam_endpos(b); + + // now get the clipped end bases (if any) + // if we get to the beginning of the cigar string + // without hitting a non-clip then the results are meaningless + for (i = b->core.n_cigar - 1; i >= 0; i--) { + char c = bam_cigar_opchr(cigar[i]); + + if (c == 'S' || c == 'H') { // clips + clipped += bam_cigar_oplen(cigar[i]); + } else { + break; + } + } + + return end_pos + clipped; +} + + +/* Calculate the mate's unclipped end based on start position and cigar string from MC tag.*/ +hts_pos_t unclipped_other_end(int64_t op, char *cigar) { + char *c = cigar; + int64_t refpos = 0; + int skip = 1; + + while (*c && *c != '*') { + long num = 0; + + if (isdigit((int)*c)) { + num = strtol(c, &c, 10); + } else { + num = 1; + } + + switch (*c) { + case 'M': + case 'D': + case 'N': + case '=': + case 'X': + refpos += num; + skip = 0; // ignore initial clips + break; + + case 'S': + case 'H': + if (!skip) { + refpos += num; + } + break; + } + + c++; + } + + return op + refpos; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b43d52033ade975f6f5d139e010a0ebfa2f458 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam.h @@ -0,0 +1,39 @@ +/* bam.h -- miscellaneous BAM functions. + + Copyright (C) 2008-2014, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef BAM_BAM_H +#define BAM_BAM_H + +#include "htslib/sam.h" + +int bam_remove_B(bam1_t *b); + +const char *bam_get_library(sam_hdr_t *header, const bam1_t *b); + +hts_pos_t unclipped_start(bam1_t *b); +hts_pos_t unclipped_other_start(hts_pos_t op, char *cigar); +hts_pos_t unclipped_end(bam1_t *b); +hts_pos_t unclipped_other_end(int64_t op, char *cigar); + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam2depth.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam2depth.c new file mode 100644 index 0000000000000000000000000000000000000000..9266b6199aae60a179cdba992635a88607606460 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam2depth.c @@ -0,0 +1,999 @@ +/* bam2depth.c -- depth subcommand. + + Copyright (C) 2011, 2012 Broad Institute. + Copyright (C) 2012-2016, 2018, 2019-2022 Genome Research Ltd. + + Author: Heng Li (to 2020) + Author: James Bonfield (2021 rewrite) + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +/* This program demonstrates how to generate pileup from multiple BAMs + * simultaneously, to achieve random access and to use the BED interface. + * To compile this program separately, you may: + * + * gcc -g -O2 -Wall -o bam2depth -D_MAIN_BAM2DEPTH bam2depth.c -lhts -lz + */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/sam.h" +#include "samtools.h" +#include "bedidx.h" +#include "sam_opts.h" +#include "htslib/khash.h" + +// From bam_plcmd.c +int read_file_list(const char *file_list, int *n, char **argv[]); + +// We accumulate to hist[pos & (size-1)]. This is a ring-buffer. +// We track where we last got to in output and what the biggest value +// we've written to so far (in absolute unmasked coordinates) in +// "last_output" and "end_pos" respectively. +// For each new record we just flush anything we haven't written yet +// already, between "last_output" and this read's start position, and +// initialise any newly seen positions between "end_pos" and this read's +// end position. +typedef struct { + size_t size; + int **hist; // hist[nfiles][size] + hts_pos_t *end_pos; // end_pos[nfiles] + hts_pos_t last_output; + int last_ref; + int nfiles; + const char *ref; + kstring_t ks; + hts_pos_t beg, end; // limit to region + int tid; +} depth_hist; + +typedef struct { + int header; + int flag; + int incl_flag; + int require_flag; + int min_qual; + int min_mqual; + int min_len; + int skip_del; + int all_pos; + int remove_overlaps; + FILE *out; + char *reg; + void *bed; +} depth_opt; + +static void zero_region(depth_opt *opt, depth_hist *dh, + const char *name, hts_pos_t start, hts_pos_t end) { + hts_pos_t i; + kstring_t *ks = &dh->ks; + + kputs(name, ks_clear(ks)); + kputc('\t', ks); + size_t cur_l = ks->l; + if (dh->beg >= 0 && start < dh->beg) + start = dh->beg; + if (dh->end >= 0 && end > dh->end) + end = dh->end; + + for (i = start; i < end; i++) { + // Could be optimised, but needs better API to skip to next + // bed region. + if (opt->bed && bed_overlap(opt->bed, name, i, i+1) == 0) + continue; + + ks->l = cur_l; + kputll(i+1, ks); + int n; + for (n = 0; n < dh->nfiles; n++) { + kputc_('\t', ks); + kputc_('0', ks); + } + kputc('\n', ks); + fputs(ks->s, opt->out); + } + ks->l = cur_l; +} + +// A variation of bam_cigar2qlen which doesn't count soft-clips in to the +// equation. Basically it's the number of bases in query that are aligned +// in some way to the reference (including insertions, which are considered +// to be aligned by dint of being anchored either side). +hts_pos_t qlen_used(bam1_t *b) { + int n_cigar = b->core.n_cigar; + const uint32_t *cigar = bam_get_cigar(b); + + hts_pos_t l; + + if (b->core.l_qseq) { + // Known SEQ permits of short cut of l_qseq minus CSOFT_CLIPs. + // Full scan not needed, which helps on excessively long CIGARs. + l = b->core.l_qseq; + int kl, kr; + for (kl = 0; kl < n_cigar; kl++) + if (bam_cigar_op(cigar[kl]) == BAM_CSOFT_CLIP) + l -= bam_cigar_oplen(cigar[kl]); + else + break; + + for (kr = n_cigar-1; kr > kl; kr--) + if (bam_cigar_op(cigar[kr]) == BAM_CSOFT_CLIP) + l -= bam_cigar_oplen(cigar[kr]); + else + break; + } else { + // Unknown SEQ ("*") needs a full scan through the CIGAR string. + static int query[16] = { + //M I D N S H P = X B ? ? ? ? ? ? + 1,1,0,0, 0,0,0,1, 1,0,0,0, 0,0,0,0 + }; + int k; + for (k = l = 0; k < n_cigar; k++) + if (query[bam_cigar_op(cigar[k])]) + l += bam_cigar_oplen(cigar[k]); + } + return l; + +} + +// Adds the depth for a single read to a depth_hist struct. +// For just one file, this is easy. We just have a circular buffer +// where we increment values for bits that overlap existing data +// and initialise values for coordinates which we're seeing for the first +// time. This is tracked by "end_pos" to know where we've got to. +// +// As the input is sorted, we can flush output from "last_output" to +// b->core.pos. +// +// With multiple files, we must feed data in sorted order as if all files +// are merged, but track depth per file. This also means "end_pos" is per +// file too, but "last_output" is global as it corresponds to rows printed. +static int add_depth(depth_opt *opt, depth_hist *dh, sam_hdr_t *h, bam1_t *b, + int overlap_clip, int file) { + hts_pos_t i; + size_t hmask = dh->size-1; + int n; + + if (!b || b->core.tid != dh->last_ref) { + // New ref + if (dh->last_ref >= 0) { + // do end + size_t cur_l = dh->ks.l; + int nf = dh->nfiles; + i = dh->last_output; + for (i = dh->last_output; nf; i++) { + nf = 0; + for (n = 0; n < dh->nfiles; n++) { + if (i < dh->end_pos[n]) + nf++; + } + if (!nf) + break; + + if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0) + continue; + + dh->ks.l = cur_l; + kputll(i+1, &dh->ks); + for (n = 0; n < dh->nfiles; n++) { + kputc_('\t', &dh->ks); + int d = i < dh->end_pos[n] + ? dh->hist[n][i & hmask] + : 0; + kputuw(d, &dh->ks); + } + kputc('\n', &dh->ks); + fputs(dh->ks.s, opt->out); + } + if (opt->all_pos) { + // End of last ref + zero_region(opt, dh, + sam_hdr_tid2name(h, dh->last_ref), + i, sam_hdr_tid2len(h, dh->last_ref)); + } + dh->ks.l = cur_l; + } + + if (opt->all_pos > 1 && !opt->reg) { + // Any previous unused refs + int lr = dh->last_ref < 0 ? 0 : dh->last_ref+1; + int rr = b ? b->core.tid : sam_hdr_nref(h), r; + for (r = lr; r < rr; r++) + zero_region(opt, dh, + sam_hdr_tid2name(h, r), + 0, sam_hdr_tid2len(h, r)); + } + + if (!b) { + // we're just flushing to end of file + if (opt->all_pos && opt->reg && dh->last_ref < 0) + // -a or -aa without a single read being output yet + zero_region(opt, dh, sam_hdr_tid2name(h, dh->tid), dh->beg, + MIN(dh->end, sam_hdr_tid2len(h, dh->tid))); + + return 0; + } + + for (n = 0; dh->end_pos && n < dh->nfiles; n++) + dh->end_pos[n] = 0; + dh->last_output = dh->beg >= 0 + ? MAX(b->core.pos, dh->beg) + : b->core.pos; + dh->last_ref = b->core.tid; + dh->ref = sam_hdr_tid2name(h, b->core.tid); + kputs(dh->ref, ks_clear(&dh->ks)); + kputc('\t', &dh->ks); + + if (opt->all_pos) + // Start of ref + zero_region(opt, dh, dh->ref, 0, b->core.pos); + } else { + if (dh->last_output < b->core.pos) { + // Flush any depth outputs up to start of new read + size_t cur_l = dh->ks.l; + int nf = dh->nfiles; + for (i = dh->last_output; i < b->core.pos; i++) { + nf = 0; + for (n = 0; n < dh->nfiles; n++) { + if (i < dh->end_pos[n]) + nf++; + } + if (!nf) + break; + + if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0) + continue; + + dh->ks.l = cur_l; + kputll(i+1, &dh->ks); + for (n = 0; n < dh->nfiles; n++) { + kputc_('\t', &dh->ks); + int d = i < dh->end_pos[n] + ? dh->hist[n][i & hmask] + : 0; + kputuw(d, &dh->ks); + } + kputc('\n', &dh->ks); + fputs(dh->ks.s, opt->out); + } + if (opt->all_pos && i < b->core.pos) + // Hole in middle of ref + zero_region(opt, dh, dh->ref, i, b->core.pos); + + dh->ks.l = cur_l; + dh->last_output = b->core.pos; + } + } + + hts_pos_t end_pos = bam_endpos(b); // 0 based, 1 past end. + //printf("%d %d\n", (int)b->core.pos+1, (int)end_pos); + + if (b->core.tid < dh->last_ref || + (dh->last_ref == b->core.tid && end_pos < dh->last_output)) { + print_error_errno("depth", "Data is not position sorted"); + return -1; + } + + // If needed, grow the circular buffer. + if (end_pos+1 - b->core.pos >= dh->size) { + size_t old_size = dh->size; + size_t old_hmask = hmask; + while (end_pos+1 - b->core.pos >= dh->size) + dh->size = dh->size ? 2*dh->size : 2048; + hmask = dh->size-1; + if (!dh->hist) { + dh->hist = calloc(dh->nfiles, sizeof(*dh->hist)); + dh->end_pos = calloc(dh->nfiles, sizeof(*dh->end_pos)); + if (!dh->hist || !dh->end_pos) + return -1; + } + for (n = 0; n < dh->nfiles; n++) { + int *hist = calloc(dh->size, sizeof(*dh->hist[n])); + if (!hist) + return -1; + + // Simple approach for now; copy over old histogram verbatim. + for (i = dh->last_output; i < dh->last_output + old_size; i++) + hist[i & hmask] = dh->hist[n][i & old_hmask]; + free(dh->hist[n]); + dh->hist[n] = hist; + } + } + + // Accumulate depth, based on CIGAR + uint32_t *cig = bam_get_cigar(b); + int ncig = b->core.n_cigar, j, k, spos = 0; + + // Zero new (previously unseen) coordinates so increment works later. + hts_pos_t end = MAX(dh->end_pos[file], b->core.pos); + if (end_pos > end && (end & hmask) < (end_pos & hmask)) { + memset(&dh->hist[file][end & hmask], 0, + sizeof(**dh->hist) * (end_pos - end)); + } else { + for (i = end; i < end_pos; i++) + dh->hist[file][i & hmask] = 0; + } + + i = b->core.pos; + uint8_t *qual = bam_get_qual(b); + int min_qual = opt->min_qual; + for (j = 0; j < ncig; j++) { + int op = bam_cigar_op(cig[j]); + int oplen = bam_cigar_oplen(cig[j]); + + switch (op) { + case BAM_CDEL: + case BAM_CREF_SKIP: + if (op != BAM_CDEL || opt->skip_del) { + // don't increment reference location + if (i + oplen >= dh->end_pos[file]) { + for (k = 0; k < oplen; k++, i++) { + if (i >= dh->end_pos[file]) + // redundant due to zero new elements above? + dh->hist[file][i & hmask] = 0; + } + } else { + i += oplen; + } + } else { // op == BAM_CDEL and we count them (-J option), + // We don't incr spos here, but we still use qual. + // This doesn't make much sense, but it's for compatibility + // with the old code. Arguably DEL shouldn't have a min + // qual and should always pass (as we've explicitly asked to + // include them). + int *hist = dh->hist[file]; + k = 0; + if (overlap_clip) { + if (i+oplen < overlap_clip) { + i += oplen; + break; + } else if (i < overlap_clip) { + k = overlap_clip - i; + i = overlap_clip; + } + } + + // Question: should we even check quality values for DEL? + // We've explicitly asked to include them, and the quality + // is wrong anyway (it's the neighbouring base). We do this + // for now for compatibility with the old depth command. + + if (spos < b->core.l_qseq) + for (; k < oplen; k++, i++) + hist[i & hmask]+=qual[spos]>=min_qual; + else + for (; k < oplen; k++, i++) + hist[i & hmask]++; + } + break; + + case BAM_CMATCH: + case BAM_CEQUAL: + case BAM_CDIFF: + if ((i & hmask) < ((i+oplen) & hmask)) { + // Optimisation when not wrapping around + + // Unrolling doesn't help clang, but helps gcc, + // especially when not using -O3. + int *hist = &dh->hist[file][i & hmask]; + if (min_qual || overlap_clip) { + k = 0; + if (overlap_clip) { + if (i+oplen < overlap_clip) { + i += oplen; + spos += oplen; + break; + } else if (i < overlap_clip) { + oplen -= overlap_clip - i; + spos += overlap_clip - i; + hist += overlap_clip - i; + i = overlap_clip; + } + } + + // approx 50% of this func cpu time in this loop + for (; k < (oplen & ~7); k+=8) { + hist[k+0]+=qual[spos+0]>=min_qual; + hist[k+1]+=qual[spos+1]>=min_qual; + hist[k+2]+=qual[spos+2]>=min_qual; + hist[k+3]+=qual[spos+3]>=min_qual; + hist[k+4]+=qual[spos+4]>=min_qual; + hist[k+5]+=qual[spos+5]>=min_qual; + hist[k+6]+=qual[spos+6]>=min_qual; + hist[k+7]+=qual[spos+7]>=min_qual; + spos += 8; + } + } else { + // easier to vectorize when no min_qual + for (k = 0; k < (oplen & ~7); k+=8) { + hist[k+0]++; + hist[k+1]++; + hist[k+2]++; + hist[k+3]++; + hist[k+4]++; + hist[k+5]++; + hist[k+6]++; + hist[k+7]++; + } + spos += k; + } + for (; k < oplen && spos < b->core.l_qseq; k++, spos++) + hist[k]+=qual[spos]>=min_qual; + for (; k < oplen; k++, spos++) + hist[k]++; + i += oplen; + } else { + // Simple to understand case, but slower. + // We use this only for reads with wrap-around. + int *hist = dh->hist[file]; + k = 0; + if (overlap_clip) { + if (i+oplen < overlap_clip) { + i += oplen; + break; + } else if (i < overlap_clip) { + oplen -= overlap_clip - i; + spos += overlap_clip - i; + i = overlap_clip; + } + } + for (; k < oplen && spos < b->core.l_qseq; k++, i++, spos++) + hist[i & hmask]+=qual[spos]>=min_qual; + for (; k < oplen; k++, i++, spos++) + hist[i & hmask]++; + } + break; + + case BAM_CINS: + case BAM_CSOFT_CLIP: + spos += oplen; + break; + + case BAM_CPAD: + case BAM_CHARD_CLIP: + // ignore + break; + + default: + print_error("depth", "Unsupported cigar op '%d'", op); + return -1; + } + } + + if (dh->end >= 0 && end_pos > dh->end) + end_pos = dh->end; + if (dh->end_pos[file] < end_pos) + dh->end_pos[file] = end_pos; + + return 0; +} + +// Hash on name -> alignment end pos. This permits a naive overlap removal. +// Note it cannot analyse the overlapping sequence and qualities, so the +// interaction of basecalls/qualities and the -Q parameter cannot be +// applied here (unlike the full mpileup algorithm). +KHASH_MAP_INIT_STR(olap_hash, hts_pos_t) +typedef khash_t(olap_hash) olap_hash_t; + +static int fastdepth_core(depth_opt *opt, uint32_t nfiles, char **fn, + samFile **fp, hts_itr_t **itr, sam_hdr_t **h) { + int ret = -1, err = 1, i; + olap_hash_t **overlaps = NULL; + depth_hist dh = {0}; + + // An array of bam structs, one per input file, to hold the next entry + bam1_t **b = calloc(nfiles, sizeof(*b)); + int *finished = calloc(nfiles, sizeof(*finished)), to_go = nfiles; + if (!b || !finished) + goto err; + + for (i = 0; i < nfiles; i++) + if (!(b[i] = bam_init1())) + goto err; + + // Do we need one overlap hash per file? Or shared? + if (opt->remove_overlaps) { + if (!(overlaps = calloc(nfiles, sizeof(*overlaps)))) + return -1; + for (i = 0; i < nfiles; i++) { + if (!(overlaps[i] = kh_init(olap_hash))) + return -1; + } + } + + // Create the initial histogram + dh.nfiles = nfiles; + dh.size = 0; + dh.hist = NULL; + dh.last_ref = -99; + dh.end_pos = NULL; + dh.last_output = itr && itr[0] ? itr[0]->beg : 0; + ks_initialize(&dh.ks); + + // Clip results to region if specified + dh.beg = -1; + dh.end = -1; + dh.tid = 0; + if (itr && itr[0]) { + dh.tid = itr[0]->tid; + dh.beg = itr[0]->beg; + dh.end = itr[0]->end; + } + + if (opt->header) { + fprintf(opt->out, "#CHROM\tPOS"); + for (i = 0; i < nfiles; i++) + fprintf(opt->out, "\t%s", fn[i]); + fputc('\n', opt->out); + } + + // Populate first record per file + for (i = 0; i < nfiles; i++) { + for(;;) { + ret = itr && itr[i] + ? sam_itr_next(fp[i], itr[i], b[i]) + : sam_read1(fp[i], h[i], b[i]); + if (ret < -1) + goto err; + if (ret == -1) { + to_go--; + finished[i] = 1; + break; + } + + if (b[i]->core.tid < 0) + continue; + if (b[i]->core.flag & opt->flag) + continue; // must have none of the flags set + if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0) + continue; // must have at least one flag set + if ((b[i]->core.flag & opt->require_flag) != opt->require_flag) + continue; // must have all lags set + if (b[i]->core.qual < opt->min_mqual) + continue; + + // Original samtools depth used the total sequence (l_qseq) + // including soft-clips. This doesn't feel like a useful metric + // to be filtering on. We now only count sequence bases that + // form the used part of the alignment. + if (opt->min_len) { + if (qlen_used(b[i]) < opt->min_len) + continue; + } + + break; + } + } + + // Loop through input files, merging in order so we're + // always adding the next record in sequence + while (to_go) { + // Find next record in file list + int best_tid = INT_MAX, best_file = 0; + hts_pos_t best_pos = HTS_POS_MAX; + + for (i = 0; i < nfiles; i++) { + if (finished[i]) + continue; + if (best_tid > b[i]->core.tid) { + best_tid = b[i]->core.tid; + best_pos = b[i]->core.pos; + best_file = i; + } else if (best_tid == b[i]->core.tid && + best_pos > b[i]->core.pos) { + best_pos = b[i]->core.pos; + best_file = i; + } + } + i = best_file; + + hts_pos_t clip = 0; + if (overlaps && (b[i]->core.flag & BAM_FPAIRED) && + !(b[i]->core.flag & BAM_FMUNMAP)) { + khiter_t k = kh_get(olap_hash, overlaps[i], bam_get_qname(b[i])); + if (k == kh_end(overlaps[i])) { + // not seen before + hts_pos_t endpos = bam_endpos(b[i]); + + // Don't add if mate location is known and can't overlap. + if (b[i]->core.mpos == -1 || + (b[i]->core.tid == b[i]->core.mtid && + b[i]->core.mpos <= endpos)) { + k = kh_put(olap_hash, overlaps[i], bam_get_qname(b[i]), + &ret); + if (ret < 0) + return -1; + kh_key(overlaps[i], k) = strdup(bam_get_qname(b[i])); + kh_value(overlaps[i], k) = endpos; + } + } else { + // seen before + clip = kh_value(overlaps[i], k); + free((char *)kh_key(overlaps[i], k)); + kh_del(olap_hash, overlaps[i], k); + } + } + + // Add the next merged BAM record to the depth plot + if ((ret = add_depth(opt, &dh, h[i], b[i], clip, i)) < 0) { + ret = -1; + goto err; + } + + // Populate next record from this file + for(;!finished[i];) { + ret = itr && itr[i] + ? sam_itr_next(fp[i], itr[i], b[i]) + : sam_read1(fp[i], h[i], b[i]); + if (ret < -1) { + ret = -1; + goto err; + } + if (ret == -1) { + to_go--; + finished[i] = 1; + break; + } + + if (b[i]->core.tid < 0) + continue; + if (b[i]->core.flag & opt->flag) + continue; // must have none of the flags set + if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0) + continue; // must have at least one flag set + if ((b[i]->core.flag & opt->require_flag) != opt->require_flag) + continue; // must have all lags set + if (b[i]->core.qual < opt->min_mqual) + continue; + + if (opt->min_len) { + if (qlen_used(b[i]) < opt->min_len) + continue; + } + + break; + } + } + + // Tidy up end. + ret = add_depth(opt, &dh, h[0], NULL, 0, 0); + err = 0; + + err: + if (ret == 0 && err) + ret = -1; + + for (i = 0; i < nfiles; i++) { + if (b[i]) + bam_destroy1(b[i]); + if (dh.hist && dh.hist[i]) + free(dh.hist[i]); + } + free(b); + free(finished); + ks_free(&dh.ks); + free(dh.hist); + free(dh.end_pos); + if (overlaps) { + khiter_t k; + for (i = 0; i < nfiles; i++) { + if (!overlaps[i]) + continue; + for (k = kh_begin(overlaps[i]); k < kh_end(overlaps[i]); k++) + if (kh_exist(overlaps[i], k)) + free((char *)kh_key(overlaps[i], k)); + kh_destroy(olap_hash, overlaps[i]); + } + free(overlaps); + } + + return ret; +} + +static void usage_exit(FILE *fp, int exit_status) +{ + fprintf(fp, "Usage: samtools depth [options] in.bam [in.bam ...]\n"); + fprintf(fp, "\nOptions:\n"); + fprintf(fp, " -a Output all positions (including zero depth)\n"); + fprintf(fp, " -a -a, -aa Output absolutely all positions, including unused ref seqs\n"); + fprintf(fp, " -r REG Specify a region in chr or chr:from-to syntax\n"); + fprintf(fp, " -b FILE Use bed FILE for list of regions\n"); + fprintf(fp, " -f FILE Specify list of input BAM/SAM/CRAM filenames\n"); + fprintf(fp, " -X Use custom index files (in -X *.bam *.bam.bai order)\n"); + fprintf(fp, " -g INT Remove specified flags from default filter-out flag list\n"); + fprintf(fp, " -G, --excl-flags FLAGS\n"); + fprintf(fp, " Add specified flags to the default filter-out flag list\n"); + fprintf(fp, " [UNMAP,SECONDARY,QCFAIL,DUP]\n"); + fprintf(fp, " --incl-flags FLAGS\n"); + fprintf(fp, " Only include records with at least one the FLAGs present [0]\n"); + fprintf(fp, " --require-flags FLAGS\n"); + fprintf(fp, " Only include records with all of the FLAGs present [0]\n"); + fprintf(fp, " -H Print a file header line\n"); + fprintf(fp, " -l INT Minimum read length [0]\n"); + fprintf(fp, " -o FILE Write output to FILE [stdout]\n"); + fprintf(fp, " -q, --min-BQ INT\n" + " Filter bases with base quality smaller than INT [0]\n"); + fprintf(fp, " -Q, --min-MQ INT\n" + " Filter alignments with mapping quality smaller than INT [0]\n"); + fprintf(fp, " -J Include reads with deletions in depth computation\n"); + fprintf(fp, " -s Do not count overlapping reads within a template\n"); + sam_global_opt_help(fp, "-.--.@-."); + exit(exit_status); +} + +int main_depth(int argc, char *argv[]) +{ + int nfiles, i; + samFile **fp; + sam_hdr_t **header; + int c, has_index_file = 0; + char *file_list = NULL, **fn = NULL; + char *out_file = NULL; + depth_opt opt = { + .flag = BAM_FUNMAP | BAM_FSECONDARY | BAM_FDUP | BAM_FQCFAIL, + .incl_flag = 0, + .require_flag = 0, + .min_qual = 0, + .min_mqual = 0, + .skip_del = 1, + .header = 0, + .min_len = 0, + .out = stdout, + .all_pos = 0, + .remove_overlaps = 0, + .reg = NULL, + .bed = NULL, + }; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + {"min-MQ", required_argument, NULL, 'Q'}, + {"min-mq", required_argument, NULL, 'Q'}, + {"min-BQ", required_argument, NULL, 'q'}, + {"min-bq", required_argument, NULL, 'q'}, + {"excl-flags", required_argument, NULL, 'G'}, + {"incl-flags", required_argument, NULL, 1}, + {"require-flags", required_argument, NULL, 2}, + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'), + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "@:q:Q:JHd:m:l:g:G:o:ar:Xf:b:s", + lopts, NULL)) >= 0) { + switch (c) { + case 'a': + opt.all_pos++; + break; + + case 'b': + opt.bed = bed_read(optarg); + if (!opt.bed) { + print_error_errno("depth", "Could not read file \"%s\"", + optarg); + return 1; + } + break; + + case 'f': + file_list = optarg; + break; + + case 'd': + case 'm': + // depth limit - now ignored + break; + + case 'g': + opt.flag &= ~bam_str2flag(optarg); + break; + case 'G': // reject if any set + opt.flag |= bam_str2flag(optarg); + break; + case 1: // reject unless at least one set (0 means ignore option) + opt.incl_flag |= bam_str2flag(optarg); + break; + case 2: // reject unless all set + opt.require_flag |= bam_str2flag(optarg); + break; + + case 'l': + opt.min_len = atoi(optarg); + break; + + case 'H': + opt.header = 1; + break; + + case 'q': + opt.min_qual = atoi(optarg); + break; + case 'Q': + opt.min_mqual = atoi(optarg); + break; + + case 'J': + opt.skip_del = 0; + break; + + case 'o': + if (opt.out != stdout) + break; + opt.out = fopen(out_file = optarg, "w"); + if (!opt.out) { + print_error_errno("depth", "Cannot open \"%s\" for writing.", + optarg); + return EXIT_FAILURE; + } + break; + + case 'r': + opt.reg = optarg; + break; + + case 's': + opt.remove_overlaps = 1; + break; + + case 'X': + has_index_file = 1; + break; + + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + usage_exit(stderr, EXIT_FAILURE); + } + } + + if (argc < optind+1 && !file_list) { + if (argc == optind) + usage_exit(stdout, EXIT_SUCCESS); + else + usage_exit(stderr, EXIT_FAILURE); + } + + if (file_list) { + if (has_index_file) { + print_error("depth", "The -f option cannot be combined with -X"); + return 1; + } + if (read_file_list(file_list, &nfiles, &fn)) + return 1; + argv = fn; + argc = nfiles; + optind = 0; + } else { + nfiles = argc - optind; + } + + if (has_index_file) { + if (nfiles%1) { + print_error("depth", "-X needs one index specified per bam file"); + return 1; + } + nfiles /= 2; + } + fp = malloc(nfiles * sizeof(*fp)); + header = malloc(nfiles * sizeof(*header)); + if (!fp || !header) { + print_error_errno("depth", "Out of memory"); + return 1; + } + + hts_itr_t **itr = NULL; + if (opt.reg) { + itr = calloc(nfiles, sizeof(*itr)); + if (!itr) + return 1; + } + + for (i = 0; i < nfiles; i++, optind++) { + fp[i] = sam_open_format(argv[optind], "r", &ga.in); + if (fp[i] == NULL) { + print_error_errno("depth", + "Cannot open input file \"%s\"", argv[optind]); + return 1; + } + + if (ga.nthreads > 0) + hts_set_threads(fp[i], ga.nthreads); + + if (hts_set_opt(fp[i], CRAM_OPT_REQUIRED_FIELDS, + SAM_FLAG | SAM_RNAME | SAM_POS | SAM_CIGAR + | (opt.remove_overlaps ? SAM_QNAME|SAM_RNEXT|SAM_PNEXT + : 0) + | (opt.min_mqual ? SAM_MAPQ : 0) + | (opt.min_len ? SAM_SEQ : 0) + | (opt.min_qual ? SAM_QUAL : 0))) { + fprintf(stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n"); + return 1; + } + + if (hts_set_opt(fp[i], CRAM_OPT_DECODE_MD, 0)) { + fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n"); + return 1; + } + + // FIXME: what if headers differ? + header[i] = sam_hdr_read(fp[i]); + if (header == NULL) { + fprintf(stderr, "Failed to read header for \"%s\"\n", + argv[optind]); + return 1; + } + + if (opt.reg) { + hts_idx_t *idx = has_index_file + ? sam_index_load2(fp[i], argv[optind], argv[optind+nfiles]) + : sam_index_load(fp[i], argv[optind]); + if (!idx) { + print_error("depth", "cannot load index for \"%s\"", + argv[optind]); + return 1; + } + if (!(itr[i] = sam_itr_querys(idx, header[i], opt.reg))) { + print_error("depth", "cannot parse region \"%s\"", opt.reg); + return 1; + } + hts_idx_destroy(idx); + } + } + + int ret = fastdepth_core(&opt, nfiles, &argv[argc-nfiles], fp, itr, header) + ? 1 : 0; + + for (i = 0; i < nfiles; i++) { + sam_hdr_destroy(header[i]); + sam_close(fp[i]); + if (itr && itr[i]) + hts_itr_destroy(itr[i]); + } + free(header); + free(fp); + free(itr); + if (file_list) { + for (i=0; i + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include "samtools.h" +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include +#include +#include +#include +#include +#include +#include + +typedef enum { + overwrite_all, + orphan_only, +} rg_mode; + +struct parsed_opts { + char* input_name; + char* output_name; + char* rg_id; + char* rg_line; + int no_pg; + rg_mode mode; + sam_global_args ga; + htsThreadPool p; + int uncompressed; + int overwrite_hdr_rg; +}; + +struct state; +typedef struct parsed_opts parsed_opts_t; +typedef struct state state_t; + +struct state { + samFile* input_file; + sam_hdr_t* input_header; + samFile* output_file; + sam_hdr_t* output_header; + char* rg_id; + void (*mode_func)(const state_t*, bam1_t*); +}; + +static void cleanup_opts(parsed_opts_t* opts) +{ + if (!opts) return; + free(opts->rg_id); + free(opts->output_name); + free(opts->input_name); + free(opts->rg_line); + if (opts->p.pool) hts_tpool_destroy(opts->p.pool); + sam_global_args_free(&opts->ga); + free(opts); +} + +static void cleanup_state(state_t* state) +{ + if (!state) return; + free(state->rg_id); + if (state->output_file) sam_close(state->output_file); + sam_hdr_destroy(state->output_header); + if (state->input_file) sam_close(state->input_file); + sam_hdr_destroy(state->input_header); + free(state); +} + +// Converts \t and \n into real tabs and newlines +static char* basic_unescape(const char* in) +{ + assert(in); + char *ptr, *out; + out = ptr = malloc(strlen(in)+1); + size_t size = 0; + while (*in) { + if (*in == '\\') { + ++in; + if (*in == '\0') { + fprintf(stderr, "[%s] Unterminated escape sequence.\n", __func__); + free(out); + return NULL; + } + switch (*in) { + case '\\': + *ptr = '\\'; + break; + case 't': + *ptr = '\t'; + break; + case 'n': + fprintf(stderr, "[%s] \\n in escape sequence is not supported.\n", __func__); + free(out); + return NULL; + default: + fprintf(stderr, "[%s] Unsupported escape sequence.\n", __func__); + free(out); + return NULL; + } + } else { + *ptr = *in; + } + ++in; + ++ptr; + ++size; + } + *ptr = '\0'; + ++size; + char* tmp = (char*)realloc(out, size); + if (!tmp) { + free(out); + } + return tmp; +} + +// Malloc a string containing [s,slim) or to the end of s if slim is NULL. +// If lenp is non-NULL, stores the length of the resulting string there. +static char *dup_substring(const char *s, const char *slim, size_t *lenp) +{ + size_t len = slim? (slim - s) : strlen(s); + char *ns = malloc(len+1); + if (ns == NULL) return NULL; + memcpy(ns, s, len); + ns[len] = '\0'; + if (lenp) *lenp = len; + return ns; +} + + +// Given a @RG line return the id +static char* get_rg_id(const char *line) +{ + const char *id = strstr(line, "\tID:"); + if (! id) return NULL; + + id += 4; + return dup_substring(id, strchr(id, '\t'), NULL); +} + + +static void usage(FILE *fp) +{ + fprintf(fp, + "Usage: samtools addreplacerg [options] [-r <@RG line> | -R ] [-m orphan_only|overwrite_all] [-o ] \n" + "\n" + "Options:\n" + " -m MODE Set the mode of operation from one of overwrite_all, orphan_only [overwrite_all]\n" + " -o FILE Where to write output to [stdout]\n" + " -r STRING @RG line text\n" + " -R STRING ID of @RG line in existing header to use\n" + " -u Output uncompressed data\n" + " -w Overwrite an existing @RG line\n" + " --no-PG Do not add a PG line\n" + ); + sam_global_opt_help(fp, "..O..@.."); +} + +static bool parse_args(int argc, char** argv, parsed_opts_t** opts) +{ + *opts = NULL; + int n; + + if (argc == 1) { usage(stdout); return true; } + + parsed_opts_t* retval = calloc(1, sizeof(parsed_opts_t)); + if (! retval ) { + fprintf(stderr, "[%s] Out of memory allocating parsed_opts_t\n", __func__); + return false; + } + // Set defaults + retval->mode = overwrite_all; + sam_global_args_init(&retval->ga); + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS(0, 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + kstring_t rg_line = {0,0,NULL}; + + while ((n = getopt_long(argc, argv, "r:R:m:o:O:h@:uw", lopts, NULL)) >= 0) { + switch (n) { + case 'r': + // Are we adding to existing rg line? + if (ks_len(&rg_line) == 0) { + if (strlen(optarg)<3 || (optarg[0] != '@' && optarg[1] != 'R' && optarg[2] != 'G')) { + kputs("@RG\t", &rg_line); + } + } else { + kputs("\t", &rg_line); + } + kputs(optarg, &rg_line); + break; + case 'R': + retval->rg_id = strdup(optarg); + break; + case 'm': { + if (strcmp(optarg, "overwrite_all") == 0) { + retval->mode = overwrite_all; + } else if (strcmp(optarg, "orphan_only") == 0) { + retval->mode = orphan_only; + } else { + usage(stderr); + return false; + } + break; + } + case 'o': + retval->output_name = strdup(optarg); + break; + case 'h': + usage(stdout); + free(retval); + return true; + case 1: + retval->no_pg = 1; + break; + case 'u': + retval->uncompressed = 1; + break; + case 'w': + retval->overwrite_hdr_rg = 1; + break; + case '?': + usage(stderr); + free(retval); + return false; + case 'O': + default: + if (parse_sam_global_opt(n, optarg, lopts, &retval->ga) == 0) break; + usage(stderr); + free(retval); + return false; + } + } + retval->rg_line = ks_release(&rg_line); + + if (argc-optind < 1) { + fprintf(stderr, "You must specify an input file.\n"); + usage(stderr); + cleanup_opts(retval); + return false; + } + if (retval->rg_id && retval->rg_line) { + fprintf(stderr, "The options -r and -R are mutually exclusive.\n"); + cleanup_opts(retval); + return false; + } + + if (retval->rg_line) + { + char* tmp = basic_unescape(retval->rg_line); + + if ((retval->rg_id = get_rg_id(tmp)) == NULL) { + fprintf(stderr, "[%s] The supplied RG line lacks an ID tag.\n", __func__); + free(tmp); + cleanup_opts(retval); + return false; + } + free(retval->rg_line); + retval->rg_line = tmp; + } + retval->input_name = strdup(argv[optind+0]); + + if (retval->ga.nthreads > 0) { + if (!(retval->p.pool = hts_tpool_init(retval->ga.nthreads))) { + fprintf(stderr, "Error creating thread pool\n"); + return false; + } + } + + *opts = retval; + return true; +} + +static void overwrite_all_func(const state_t* state, bam1_t* file_read) +{ + uint8_t* data = (uint8_t*)strdup(state->rg_id); + int len = strlen(state->rg_id)+1; + // If the old exists delete it + uint8_t* old = bam_aux_get(file_read, "RG"); + if (old != NULL) { + bam_aux_del(file_read, old); + } + + bam_aux_append(file_read, "RG", 'Z', len, data); + free(data); +} + +static void orphan_only_func(const state_t* state, bam1_t* file_read) +{ + uint8_t* data = (uint8_t*)strdup(state->rg_id); + int len = strlen(state->rg_id)+1; + // If the old exists don't do anything + uint8_t* old = bam_aux_get(file_read, "RG"); + if (old == NULL) { + bam_aux_append(file_read, "RG",'Z',len,data); + } + free(data); +} + +static bool init(const parsed_opts_t* opts, state_t** state_out) { + char output_mode[9] = "w"; + state_t* retval = (state_t*) calloc(1, sizeof(state_t)); + + if (retval == NULL) { + fprintf(stderr, "[init] Out of memory allocating state struct.\n"); + return false; + } + *state_out = retval; + + // Open files + retval->input_file = sam_open_format(opts->input_name, "r", &opts->ga.in); + if (retval->input_file == NULL) { + print_error_errno("addreplacerg", "could not open \"%s\"", opts->input_name); + return false; + } + retval->input_header = sam_hdr_read(retval->input_file); + + retval->output_header = sam_hdr_dup(retval->input_header); + + if (opts->uncompressed) + strcat(output_mode, "0"); + if (opts->output_name) // File format auto-detection + sam_open_mode(output_mode + strlen(output_mode), + opts->output_name, NULL); + retval->output_file = sam_open_format(opts->output_name == NULL?"-":opts->output_name, output_mode, &opts->ga.out); + + if (retval->output_file == NULL) { + print_error_errno("addreplacerg", "could not create \"%s\"", opts->output_name); + return false; + } + + if (opts->p.pool) { + hts_set_opt(retval->input_file, HTS_OPT_THREAD_POOL, &opts->p); + hts_set_opt(retval->output_file, HTS_OPT_THREAD_POOL, &opts->p); + } + + if (opts->rg_line) { + // Append new RG line to header. + // Check does not already exist + kstring_t hdr_line = { 0, 0, NULL }; + if (sam_hdr_find_line_id(retval->output_header, "RG", "ID", opts->rg_id, &hdr_line) == 0) { + if (opts->overwrite_hdr_rg) { + if(-1 == sam_hdr_remove_line_id(retval->output_header, "RG", "ID", opts->rg_id)) { + fprintf(stderr, "[init] Error removing the RG line with ID:%s from the output header.\n", opts->rg_id); + ks_free(&hdr_line); + return false; + } + } else { + fprintf(stderr, "[init] RG line with ID:%s already present in the header. Use -w to overwrite.\n", opts->rg_id); + ks_free(&hdr_line); + return false; + } + } + ks_free(&hdr_line); + + if (-1 == sam_hdr_add_lines(retval->output_header, opts->rg_line, strlen(opts->rg_line))) { + fprintf(stderr, "[init] Error adding RG line with ID:%s to the output header.\n", opts->rg_id); + return false; + } + if (opts->mode == overwrite_all && + -1 == sam_hdr_remove_except(retval->output_header, "RG", "ID", opts->rg_id)) { + fprintf(stderr, "[init] Error removing the old RG lines from the output header.\n"); + return false; + } + retval->rg_id = strdup(opts->rg_id); + } else { + if (opts->rg_id) { + // Confirm what has been supplied exists + kstring_t hdr_line = { 0, 0, NULL }; + if (sam_hdr_find_line_id(retval->output_header, "RG", "ID", opts->rg_id, &hdr_line) < 0) { + fprintf(stderr, "RG ID supplied does not exist in header. Supply full @RG line with -r instead?\n"); + return false; + } + retval->rg_id = strdup(opts->rg_id); + ks_free(&hdr_line); + } else { + kstring_t rg_id = { 0, 0, NULL }; + if (sam_hdr_find_tag_id(retval->output_header, "RG", NULL, NULL, "ID", &rg_id) < 0) { + fprintf(stderr, "No RG specified on command line or in existing header.\n"); + return false; + } + retval->rg_id = ks_release(&rg_id); + } + } + + switch (opts->mode) { + case overwrite_all: + retval->mode_func = &overwrite_all_func; + break; + case orphan_only: + retval->mode_func = &orphan_only_func; + break; + } + + return true; +} + +static bool readgroupise(parsed_opts_t *opts, state_t* state, char *arg_list) +{ + if (!opts->no_pg && sam_hdr_add_pg(state->output_header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + return false; + + if (sam_hdr_write(state->output_file, state->output_header) != 0) { + print_error_errno("addreplacerg", "[%s] Could not write header to output file", __func__); + return false; + } + char *idx_fn = NULL; + if (opts->ga.write_index) { + if (!(idx_fn = auto_index(state->output_file, opts->output_name, state->output_header))) + return false; + } + + bam1_t* file_read = bam_init1(); + int ret; + while ((ret = sam_read1(state->input_file, state->input_header, file_read)) >= 0) { + state->mode_func(state, file_read); + + if (sam_write1(state->output_file, state->output_header, file_read) < 0) { + print_error_errno("addreplacerg", "[%s] Could not write read to output file", __func__); + bam_destroy1(file_read); + free(idx_fn); + return false; + } + } + bam_destroy1(file_read); + if (ret != -1) { + print_error_errno("addreplacerg", "[%s] Error reading from input file", __func__); + free(idx_fn); + return false; + } else { + + if (opts->ga.write_index) { + if (sam_idx_save(state->output_file) < 0) { + print_error_errno("addreplacerg", "[%s] Writing index failed", __func__); + free(idx_fn); + return false; + } + } + free(idx_fn); + return true; + } +} + +int main_addreplacerg(int argc, char** argv) +{ + parsed_opts_t* opts = NULL; + state_t* state = NULL; + char *arg_list = stringify_argv(argc+1, argv-1); + if (!arg_list) + return EXIT_FAILURE; + + if (!parse_args(argc, argv, &opts)) goto error; + if (opts) { // Not an error but user doesn't want us to proceed + if (!init(opts, &state) || !readgroupise(opts, state, arg_list)) + goto error; + } + + cleanup_state(state); + cleanup_opts(opts); + free(arg_list); + + return EXIT_SUCCESS; +error: + cleanup_state(state); + cleanup_opts(opts); + free(arg_list); + + return EXIT_FAILURE; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c new file mode 100644 index 0000000000000000000000000000000000000000..72f39bd5d6888d60d796df9c3b28c4575ff532e4 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c @@ -0,0 +1,1117 @@ +/* bam_ampliconclip.c -- loads amplicon primers from a BED file and cuts reads + from the 5' end. + + Copyright (C) 2020-2023 Genome Research Ltd. + + Authors: Andrew Whitwham + Rob Davies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include +#include "htslib/hfile.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "samtools.h" +#include "bam_ampliconclip.h" + +typedef enum { + soft_clip, + hard_clip +} clipping_type; + +typedef struct { + int add_pg; + int use_strand; + int write_clipped; + int mark_fail; + int both; + int fail_len; + int filter_len; + int unmapped; + int oa_tag; + int del_tag; + int tol; + int unmap_len; + char *arg_list; + char *stats_file; + char *rejects_file; +} cl_param_t; + + +static int bed_entry_sort(const void *av, const void *bv) { + bed_entry_t *a = (bed_entry_t *) av; + bed_entry_t *b = (bed_entry_t *) bv; + return a->right < b->right ? -1 : (a->right == b->right ? 0 : 1); +} + + +int load_bed_file_multi_ref(char *infile, int get_strand, int sort_by_pos, khash_t(bed_list_hash) *bed_lists) { + hFILE *fp; + int line_count = 0, ret; + int64_t left, right; + kstring_t line = KS_INITIALIZE; + bed_entry_list_t *list; + khiter_t bed_itr; + + if ((fp = hopen(infile, "r")) == NULL) { + print_error_errno("amplicon", "unable to open file %s.", infile); + return 1; + } + + char ref[1024]; + + while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) { + line_count++; + int hret; + char strand; + + if (line.l == 0 || *line.s == '#') continue; + if (strncmp(line.s, "track ", 6) == 0) continue; + if (strncmp(line.s, "browser ", 8) == 0) continue; + + if (get_strand) { + if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64" %*s %*s %c", + ref, &left, &right, &strand) != 4) { + fprintf(stderr, "[amplicon] error: bad bed file format in line %d of %s.\n" + "(N.B. ref/chrom name limited to 1023 characters.)\n", + line_count, infile); + ret = 1; + goto error; + } + } else { + if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64, + ref, &left, &right) != 3) { + fprintf(stderr, "[amplicon] error: bad bed file format in line %d of %s\n" + "(N.B. ref/chrom name limited to 1023 characters.)\n", + line_count, infile); + ret = 1; + goto error; + } + } + + bed_itr = kh_get(bed_list_hash, bed_lists, ref); + + if (bed_itr == kh_end(bed_lists)) { // new ref entry + char *ref_name = strdup(ref); // need a copy for the hash key + + if (!ref_name) { + fprintf(stderr, "[amplicon] error: unable to allocate memory for ref name.\n"); + ret = 1; + goto error; + } + + bed_itr = kh_put(bed_list_hash, bed_lists, ref_name, &hret); + + if (hret > 0) { + list = &kh_val(bed_lists, bed_itr); + + // initialise the new hash entry + list->longest = 0; + list->size = 0; + list->length = 0; + list->bp = NULL; + } else { + fprintf(stderr, "[amplicon] error: ref hashing failure.\n"); + ret = 1; + goto error; + } + } else { // existing ref + list = &kh_val(bed_lists, bed_itr); + } + + if (list->length == list->size) { + bed_entry_t *tmp; + + list->size += list->size / 2 + 256; + + if ((tmp = realloc(list->bp, list->size * sizeof(bed_entry_t))) == NULL) { + fprintf(stderr, "[amplicon] error: unable to allocate more memory for bed data.\n"); + ret = 1; + goto error; + } + + list->bp = tmp; + } + + list->bp[list->length].left = left; + list->bp[list->length].right = right; + + if (get_strand) { + if (strand == '+') { + list->bp[list->length].rev = 0; + } else if (strand == '-') { + list->bp[list->length].rev = 1; + } else { + fprintf(stderr, "[amplicon] error: bad strand value in line %d, expecting '+' or '-', found '%c'.\n", + line_count, strand); + ret = 1; + goto error; + } + } + + if (right - left > list->longest) + list->longest = right - left; + + list->length++; + } + + if (sort_by_pos) { + for (bed_itr = kh_begin(bed_lists); bed_itr != kh_end(bed_lists); ++bed_itr) { + if (kh_exist(bed_lists, bed_itr)) { + list = &kh_val(bed_lists, bed_itr); + qsort(list->bp, list->length, sizeof(list->bp[0]), bed_entry_sort); + } + } + } + + if (kh_size(bed_lists) > 0) {// any entries + ret = 0; + } else { + ret = 1; + } + +error: + ks_free(&line); + + if (hclose(fp) != 0) { + fprintf(stderr, "[amplicon] warning: failed to close %s", infile); + } + + return ret; +} + + +void destroy_bed_hash(khash_t(bed_list_hash) *hash) { + khiter_t itr; + + for (itr = kh_begin(hash); itr != kh_end(hash); ++itr) { + if (kh_exist(hash, itr)) { + free(kh_val(hash, itr).bp); + free((char *)kh_key(hash, itr)); + kh_key(hash, itr) = NULL; + } + } + + kh_destroy(bed_list_hash, hash); +} + + +static int matching_clip_site(bed_entry_list_t *sites, hts_pos_t pos, + int is_rev, int use_strand, int64_t longest, + cl_param_t *param) { + int i, size; // may need this to be variable + int tol = param->tol; + int l = 0, mid = sites->length / 2, r = sites->length; + int pos_tol = is_rev ? (pos > tol ? pos - tol : 0) : pos; + + while (r - l > 1) { + if (sites->bp[mid].right <= pos_tol) { + l = mid; + } else { + r = mid; + } + mid = (l + r) / 2; + } + + size = 0; + + for (i = l; i < sites->length; i++) { + hts_pos_t mod_left, mod_right; + + if (use_strand && is_rev != sites->bp[i].rev) + continue; + + if (is_rev) { + mod_left = sites->bp[i].left; + mod_right = sites->bp[i].right + tol; + } else { + if (sites->bp[i].left > tol) { + mod_left = sites->bp[i].left - tol; + } else { + mod_left = 0; + } + mod_right = sites->bp[i].right; + } + + if (pos + longest + tol < mod_right) + break; + + if (pos >= mod_left && pos <= mod_right) { + if (is_rev) { + if (size < pos - sites->bp[i].left) { + size = pos - sites->bp[i].left; + } + } else { + if (size < sites->bp[i].right - pos) { + size = sites->bp[i].right - pos; + } + } + } + } + + return size; +} + + +static int bam_trim_left(bam1_t *rec, bam1_t *rec_out, uint32_t bases, + clipping_type clipping) { + uint32_t *orig_cigar = bam_get_cigar(rec); + uint8_t *orig_seq = bam_get_seq(rec); + uint8_t *orig_qual = bam_get_qual(rec); + uint8_t *orig_aux = bam_get_aux(rec); + uint32_t *new_cigar; + uint8_t *new_qual; + size_t orig_l_aux = bam_get_l_aux(rec); + uint32_t i, j; + uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0; + hts_pos_t new_pos = rec->core.pos; + uint32_t cig_type, cig_op; + + if (rec->l_data + 8 > rec_out->m_data) { + uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8); + if (!new_data) { + fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n"); + return 1; + } + rec_out->data = new_data; + rec_out->m_data = rec->l_data + 8; + } + + // Copy core data & name + memcpy(&rec_out->core, &rec->core, sizeof(rec->core)); + memcpy(rec_out->data, rec->data, rec->core.l_qname); + + // Modify CIGAR + new_cigar = bam_get_cigar(rec_out); + + for (i = 0; i < rec->core.n_cigar; i++) { + cig_op = bam_cigar_op(orig_cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if (cig_op == BAM_CHARD_CLIP) { + hardclip += bam_cigar_oplen(orig_cigar[i]); + } else { + if (cig_type & 2) { + if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) { + ref_remove -= bam_cigar_oplen(orig_cigar[i]); + } else { + break; + } + new_pos += bam_cigar_oplen(orig_cigar[i]); + } + if (cig_type & 1) { + qry_removed += bam_cigar_oplen(orig_cigar[i]); + } + } + } + + if (i < rec->core.n_cigar) { + cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i])); + + // account for the last operation + if (cig_type & 2) { + new_pos += ref_remove; + } + if (cig_type & 1) { + qry_removed += ref_remove; + } + } else { + if (clipping == hard_clip) { + + rec_out->core.l_qseq = 0; + rec_out->core.n_cigar = 0; + + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; + } + + qry_removed = rec->core.l_qseq; + } + + j = 0; + if (clipping == hard_clip && hardclip + qry_removed > 0) { + new_cigar[j++] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP); + } + if (clipping == soft_clip) { + if (hardclip > 0) { + new_cigar[j++] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP); + } + if (qry_removed > 0) { + new_cigar[j++] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP); + } + } + + if (i < rec->core.n_cigar + && bam_cigar_oplen(orig_cigar[i]) > ref_remove) { + new_cigar[j++] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i])); + + // fill in the rest of the cigar + i++; + + for (; i < rec->core.n_cigar; i++) { + new_cigar[j++] = orig_cigar[i]; + } + } + + rec_out->core.n_cigar = j; + + if (clipping == soft_clip) { + qry_removed = 0; // Copy all the sequence and confidence values + } + + new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2; + // Copy remaining SEQ + if ((qry_removed & 1) == 0) { + memcpy(bam_get_seq(rec_out), orig_seq + (qry_removed / 2), + (rec->core.l_qseq - qry_removed + 1) / 2); // +1 to account for odd numbers + } else { + uint8_t *in = orig_seq + qry_removed / 2; + uint8_t *out = bam_get_seq(rec_out); + uint32_t i; + for (i = qry_removed; i < rec->core.l_qseq - 1; i += 2) { + *out++ = ((in[0] & 0x0f) << 4) | ((in[1] & 0xf0) >> 4); + in++; + } + if (i < rec->core.l_qseq) { + *out++ = (in[0] & 0x0f) << 4; + } + assert(out == new_qual); + } + + // Copy remaining QUAL + memmove(new_qual, orig_qual, rec->core.l_qseq - qry_removed); + + // Set new l_qseq + rec_out->core.l_qseq -= qry_removed; + + // Move AUX + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + // Set new l_data + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + // put in new pos + rec_out->core.pos = new_pos; + + return 0; +} + + +static int bam_trim_right(bam1_t *rec, bam1_t *rec_out, uint32_t bases, + clipping_type clipping) { + uint32_t *orig_cigar = bam_get_cigar(rec); + uint8_t *orig_seq = bam_get_seq(rec); + uint8_t *orig_qual = bam_get_qual(rec); + uint8_t *orig_aux = bam_get_aux(rec); + uint32_t *new_cigar; + uint32_t new_n_cigar = 0; + uint8_t *new_qual; + size_t orig_l_aux = bam_get_l_aux(rec); + int32_t i; + int32_t j; + uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0; + uint32_t cig_type, cig_op; + + if (rec->l_data + 8 > rec_out->m_data) { + uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8); + if (!new_data) { + fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n"); + return 1; + } + rec_out->data = new_data; + rec_out->m_data = rec->l_data + 8; + } + + // Copy core data & name + memcpy(&rec_out->core, &rec->core, sizeof(rec->core)); + memcpy(rec_out->data, rec->data, rec->core.l_qname); + + // Modify CIGAR here + new_cigar = bam_get_cigar(rec_out); + + for (i = rec->core.n_cigar - 1; i >= 0; --i) { + cig_op = bam_cigar_op(orig_cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if (cig_op == BAM_CHARD_CLIP) { + hardclip += bam_cigar_oplen(orig_cigar[i]); + } else { + if (cig_type & 2) { + if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) { + ref_remove -= bam_cigar_oplen(orig_cigar[i]); + } else { + break; + } + } + if (cig_type & 1) { + qry_removed += bam_cigar_oplen(orig_cigar[i]); + } + } + } + + if (i >= 0) { + cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i])); + if (cig_type & 1) { + qry_removed += ref_remove; + } + j = i; + if (qry_removed > 0) j++; + if (hardclip > 0 && (clipping == soft_clip || qry_removed == 0)) j++; + } else { + if (clipping == hard_clip) { + + rec_out->core.l_qseq = 0; + rec_out->core.n_cigar = 0; + + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; + } + + qry_removed = rec->core.l_qseq; + j = 0; + if (hardclip > 0 && clipping == soft_clip) j++; + } + + if (clipping == hard_clip && hardclip + qry_removed > 0) { + new_cigar[j] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP); + new_n_cigar++; + } + if (clipping == soft_clip) { + if (hardclip > 0) { + new_cigar[j] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP); + new_n_cigar++; + if (qry_removed > 0) --j; + } + if (qry_removed > 0) { + new_cigar[j] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP); + new_n_cigar++; + } + } + + if (j > 0) { + new_cigar[--j] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i])); + new_n_cigar++; + } + + // fill in the rest of the cigar + while (j > 0) { + new_cigar[--j] = orig_cigar[--i]; + new_n_cigar++; + } + + rec_out->core.n_cigar = new_n_cigar; + + if (clipping == soft_clip) + qry_removed = 0; // Copy all the sequence and confidence values + + new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2; + // Copy remaining SEQ + memcpy(bam_get_seq(rec_out), orig_seq, (rec->core.l_qseq - qry_removed + 1) / 2); + + // Copy remaining QUAL + memcpy(new_qual, orig_qual, rec->core.l_qseq - qry_removed); + + // Set new l_qseq + rec_out->core.l_qseq -= qry_removed; + + // Copy AUX + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + // Set new l_data + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; +} + + +static hts_pos_t active_query_len(bam1_t *b) { + uint32_t *cigar = bam_get_cigar(b); + uint32_t cig_type, cig_op; + hts_pos_t len = 0; + int i; + + for (i = 0; i < b->core.n_cigar; i++) { + cig_op = bam_cigar_op(cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if ((cig_type & 1) && (cig_op != BAM_CSOFT_CLIP)) { + len += bam_cigar_oplen(cigar[i]); + } + } + + return len; +} + + +static inline void swap_bams(bam1_t **a, bam1_t **b) { + bam1_t *tmp = *a; + *a = *b; + *b = tmp; +} + + +// Format OA:Z:(RNAME,POS,strand,CIGAR,MAPQ,NM; +static inline int tag_original_data(bam1_t *orig, kstring_t *oa_tag) { + char strand; + uint8_t *nm_tag, *old_oa_tag; + uint32_t *cigar; + int64_t nm = 0; + int i, res = 0; + + ks_clear(oa_tag); + + // if there is an existing OA tag the new one gets appended to it + if ((old_oa_tag = bam_aux_get(orig, "OA"))) { + res |= ksprintf(oa_tag, "%s", bam_aux2Z(old_oa_tag)) < 0; + } + + if (orig->core.flag & BAM_FREVERSE) + strand = '-'; + else + strand = '+'; + + if ((nm_tag = bam_aux_get(orig, "NM"))) { + nm = bam_aux2i(nm_tag); + } + + res |= ksprintf(oa_tag, "%s,%"PRIhts_pos",%c,", bam_get_qname(orig), orig->core.pos + 1, strand) < 0; + + for (i = 0, cigar = bam_get_cigar(orig); i < orig->core.n_cigar && res == 0; ++i) { + res |= kputw(bam_cigar_oplen(cigar[i]), oa_tag) < 0; + res |= kputc(bam_cigar_opchr(cigar[i]), oa_tag) < 0; + } + + if (nm_tag) { + res |= ksprintf(oa_tag, ",%d,%"PRId64";", orig->core.qual, nm) < 0; + } else { + res |= ksprintf(oa_tag, "%d,;", orig->core.qual) < 0; + } + + return res; +} + + +static int bam_clip(samFile *in, samFile *out, samFile *reject, char *bedfile, + clipping_type clipping, cl_param_t *param) { + int ret = 1, r, file_open = 0; + + bam_hdr_t *header = NULL; + bam1_t *b = NULL, *b_tmp = NULL; + long f_count = 0, r_count = 0, n_count = 0, l_count = 0, l_exclude = 0, b_count = 0; + long filtered = 0, written = 0, failed = 0; + kstring_t str = KS_INITIALIZE; + kstring_t oat = KS_INITIALIZE; + kstring_t seq = KS_INITIALIZE; + bed_entry_list_t *sites; + FILE *stats_fp = stderr; + khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash); + + if (load_bed_file_multi_ref(bedfile, param->use_strand, 1, bed_hash)) { + fprintf(stderr, "[ampliconclip] error: unable to load bed file.\n"); + goto fail; + } + + if ((header = sam_hdr_read(in)) == NULL) { + fprintf(stderr, "[ampliconclip] error: could not read header\n"); + goto fail; + } + + // changing pos can ruin coordinate sort order + if (sam_hdr_find_tag_hd(header, "SO", &str) == 0 && str.s && strcmp(str.s, "coordinate") == 0) { + const char *new_order = "unknown"; + + if (sam_hdr_update_hd(header, "SO", new_order) == -1) { + fprintf(stderr, "[ampliconclip] error: unable to change sort order to 'SO:%s'\n", new_order); + goto fail; + } + } + + ks_free(&str); + + if (param->add_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(), + param->arg_list ? "CL" : NULL, + param->arg_list ? param->arg_list : NULL, + NULL) != 0) { + fprintf(stderr, "[ampliconclip] warning: unable to add @PG line to header.\n"); + } + if (sam_hdr_write(out, header) < 0) { + fprintf(stderr, "[ampliconclip] error: could not write header.\n"); + goto fail; + } + + if (reject) { + if (sam_hdr_write(reject, header) < 0) { + fprintf(stderr, "[ampliconclip] error: could not write header to rejects file.\n"); + goto fail; + } + } + + b = bam_init1(); + b_tmp = bam_init1(); + if (!b || !b_tmp) { + fprintf(stderr, "[ampliconclip] error: out of memory when trying to create record.\n"); + goto fail; + } + + int32_t last_tid = -1; + int ref_found = 0; + + while ((r = sam_read1(in, header, b)) >= 0) { + hts_pos_t pos; + int is_rev; + int p_size; + int been_clipped = 0, filter = 0; + int exclude = (BAM_FUNMAP | BAM_FQCFAIL); + khiter_t itr; + + l_count++; + + if (b->core.tid != last_tid) { + const char *ref_name; + + ref_found = 0; + last_tid = b->core.tid; + + if ((ref_name = sam_hdr_tid2name(header, b->core.tid)) != NULL) { + itr = kh_get(bed_list_hash, bed_hash, ref_name); + + if (itr != kh_end(bed_hash)) { + sites = &kh_val(bed_hash, itr); + ref_found = 1; + } + } + } + + if (!(b->core.flag & exclude) && ref_found) { + if (param->oa_tag) + if (tag_original_data(b, &oat)) + goto fail; + + if (!param->both) { + if (bam_is_rev(b)) { + pos = bam_endpos(b); + is_rev = 1; + } else { + pos = b->core.pos; + is_rev = 0; + } + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (is_rev) { + if (bam_trim_right(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + r_count++; + } else { + if (bam_trim_left(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + f_count++; + } + + if (param->oa_tag) { + if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s)) + goto fail; + } + + if (param->del_tag) { + uint8_t *tag; + + if ((tag = bam_aux_get(b, "NM"))) + bam_aux_del(b, tag); + + if ((tag = bam_aux_get(b, "MD"))) + bam_aux_del(b, tag); + } + + been_clipped = 1; + } else { + if (param->mark_fail) { + b->core.flag |= BAM_FQCFAIL; + } + + n_count++; + } + } else { + int left = 0, right = 0; + + // left first + pos = b->core.pos; + is_rev = 0; + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (bam_trim_left(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + f_count++; + left = 1; + been_clipped = 1; + } + + // the right + pos = bam_endpos(b); + is_rev = 1; + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (bam_trim_right(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + r_count++; + right = 1; + been_clipped = 1; + } + + if (left || right) { + uint8_t *tag; + + if (param->oa_tag) { + if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s)) + goto fail; + } + + if (param->del_tag) { + if ((tag = bam_aux_get(b, "NM"))) + bam_aux_del(b, tag); + + if ((tag = bam_aux_get(b, "MD"))) + bam_aux_del(b, tag); + } + } + + if (left && right) { + b_count++; + } else if (!left && !right) { + if (param->mark_fail) { + b->core.flag |= BAM_FQCFAIL; + } + + n_count++; + } + } + + if (param->fail_len >= 0 || param->filter_len >= 0 || param->unmap_len >= 0) { + hts_pos_t aql = active_query_len(b); + + if (param->fail_len >= 0 && aql <= param->fail_len) { + b->core.flag |= BAM_FQCFAIL; + } + + if (param->filter_len >= 0 && aql <= param->filter_len) { + filter = 1; + } + + if (param->unmap_len >= 0 && aql <= param->unmap_len) { + + if (ks_resize(&seq, b->core.l_qseq) < 0) { + fprintf(stderr, "[ampliconclip] error: allocate memory for sequence %s\n", bam_get_seq(b)); + goto fail; + } + + ks_clear(&seq); + char *sb = ks_str(&seq); + uint8_t *sequence = bam_get_seq(b); + int i; + + for (i = 0; i < b->core.l_qseq ; ++i) { + *sb++ = seq_nt16_str[bam_seqi(sequence, i)]; + } + + if (bam_set1(b_tmp, b->core.l_qname - b->core.l_extranul - 1, bam_get_qname(b), + (b->core.flag | BAM_FUNMAP), b->core.tid, b->core.pos, 0, + 0, NULL, b->core.mtid, b->core.mpos, b->core.isize, + b->core.l_qseq, seq.s, (const char *)bam_get_qual(b), + bam_get_l_aux(b)) < 0) { + fprintf(stderr, "[ampliconclip] error: could not unmap read %s\n", bam_get_seq(b)); + goto fail; + } + + memcpy(bam_get_aux(b_tmp), bam_get_aux(b), bam_get_l_aux(b)); + b_tmp->l_data += bam_get_l_aux(b); + swap_bams(&b, &b_tmp); + } + } + + if (b->core.flag & BAM_FQCFAIL) { + failed++; + } + + if (param->write_clipped && !been_clipped) { + filter = 1; + } + + } else { + l_exclude++; + + if (param->unmapped) { + filter = 1; + } + } + + if (!filter) { + if (sam_write1(out, header, b) < 0) { + fprintf(stderr, "[ampliconclip] error: could not write line %ld.\n", l_count); + goto fail; + } + + written++; + } else { + if (reject) { + if (sam_write1(reject, header, b) < 0) { + fprintf(stderr, "[ampliconclip] error: could not write to reject file %s\n", + param->rejects_file); + goto fail; + } + } + + filtered++; + } + } + + if (r < -1) { + fprintf(stderr, "[ampliconclip] error: failed to read input.\n"); + goto fail; + } + + if (param->stats_file) { + if ((stats_fp = fopen(param->stats_file, "w")) == NULL) { + fprintf(stderr, "[ampliconclip] warning: cannot write stats to %s.\n", param->stats_file); + } else { + file_open = 1; + } + } + + fprintf(stats_fp, "COMMAND: %s\n" + "TOTAL READS: %ld\n" + "TOTAL CLIPPED: %ld\n" + "FORWARD CLIPPED: %ld\n" + "REVERSE CLIPPED: %ld\n" + "BOTH CLIPPED: %ld\n" + "NOT CLIPPED: %ld\n" + "EXCLUDED: %ld\n" + "FILTERED: %ld\n" + "FAILED: %ld\n" + "WRITTEN: %ld\n", param->arg_list, l_count, f_count + r_count, + f_count, r_count, b_count, n_count, l_exclude, + filtered, failed, written); + + if (file_open) { + fclose(stats_fp); + } + + ret = 0; + +fail: + destroy_bed_hash(bed_hash); + ks_free(&oat); + ks_free(&seq); + sam_hdr_destroy(header); + bam_destroy1(b); + bam_destroy1(b_tmp); + return ret; +} + + +static void usage(void) { + fprintf(stderr, "Usage: samtools ampliconclip -b BED file -o \n\n"); + fprintf(stderr, "Option: \n"); + fprintf(stderr, " -b FILE BED file of regions (eg amplicon primers) to be removed.\n"); + fprintf(stderr, " -o FILE output file name (default stdout).\n"); + fprintf(stderr, " -f FILE write stats to file name (default stderr)\n"); + fprintf(stderr, " -u Output uncompressed data\n"); + fprintf(stderr, " --soft-clip soft clip amplicon primers from reads (default)\n"); + fprintf(stderr, " --hard-clip hard clip amplicon primers from reads.\n"); + fprintf(stderr, " --both-ends clip on both 5' and 3' ends.\n"); + fprintf(stderr, " --strand use strand data from BED file to match read direction.\n"); + fprintf(stderr, " --clipped only output clipped reads.\n"); + fprintf(stderr, " --fail mark unclipped, mapped reads as QCFAIL.\n"); + fprintf(stderr, " --filter-len INT do not output reads INT size or shorter.\n"); + fprintf(stderr, " --fail-len INT mark as QCFAIL reads INT size or shorter.\n"); + fprintf(stderr, " --unmap-len INT unmap reads INT size or shorter, default 0.\n"); + fprintf(stderr, " --no-excluded do not write excluded reads (unmapped or QCFAIL).\n"); + fprintf(stderr, " --rejects-file FILE file to write filtered reads.\n"); + fprintf(stderr, " --original for clipped entries add an OA tag with original data.\n"); + fprintf(stderr, " --keep-tag for clipped entries keep the old NM and MD tags.\n"); + fprintf(stderr, " --tolerance match region within this number of bases, default 5.\n"); + fprintf(stderr, " --no-PG do not add an @PG line.\n"); + sam_global_opt_help(stderr, "-.O..@-."); + fprintf(stderr, "\nAbout: Soft clips read alignments where they match BED file defined regions.\n" + "Default clipping is only on the 5' end.\n\n"); +} + + +int amplicon_clip_main(int argc, char **argv) { + int c, ret; + char wmode[4] = {'w', 'b', 0, 0}; + char *bedfile = NULL, *fnout = "-"; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool p = {NULL, 0}; + samFile *in = NULL, *out = NULL, *reject = NULL; + clipping_type clipping = soft_clip; + cl_param_t param = {1, 0, 0, 0, 0, -1, -1, 0, 0, 1, 5, 0, NULL, NULL, NULL}; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1002}, + {"soft-clip", no_argument, NULL, 1003}, + {"hard-clip", no_argument, NULL, 1004}, + {"strand", no_argument, NULL, 1005}, + {"clipped", no_argument, NULL, 1006}, + {"fail", no_argument, NULL, 1007}, + {"both-ends", no_argument, NULL, 1008}, + {"filter-len", required_argument, NULL, 1009}, + {"fail-len", required_argument, NULL, 1010}, + {"no-excluded", no_argument, NULL, 1011}, + {"rejects-file", required_argument, NULL, 1012}, + {"original", no_argument, NULL, 1013}, + {"keep-tag", no_argument, NULL, 1014}, + {"tolerance", required_argument, NULL, 1015}, + {"unmap-len", required_argument, NULL, 1016}, + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "b:@:o:O:f:u", lopts, NULL)) >= 0) { + switch (c) { + case 'b': bedfile = optarg; break; + case 'o': fnout = optarg; break; + case 'f': param.stats_file = optarg; break; + case 'u': wmode[2] = '0'; break; + case 1002: param.add_pg = 0; break; + case 1003: clipping = soft_clip; break; + case 1004: clipping = hard_clip; break; + case 1005: param.use_strand = 1; break; + case 1006: param.write_clipped = 1; break; + case 1007: param.mark_fail = 1; break; + case 1008: param.both = 1; break; + case 1009: param.filter_len = atoi(optarg); break; + case 1010: param.fail_len = atoi(optarg); break; + case 1011: param.unmapped = 1; break; + case 1012: param.rejects_file = optarg; break; + case 1013: param.oa_tag = 1; break; + case 1014: param.del_tag = 0; break; + case 1015: param.tol = atoi(optarg); break; + case 1016: param.unmap_len = atoi(optarg); break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage(); exit(1); + } + } + + if (!bedfile) { + usage(); + return 1; + } + + if (optind + 1 > argc) { + usage(); + return 1; + } + + if (param.tol < 0) { + fprintf(stderr, "[ampliconclip] warning: invalid tolerance of %d," + " resetting tolerance to default of 5.\n", param.tol); + param.tol = 5; + } + + if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) { + print_error_errno("ampliconclip", "cannot open input file"); + return 1; + } + + sam_open_mode(wmode+1, fnout, NULL); + + if ((out = sam_open_format(fnout, wmode, &ga.out)) == NULL) { + print_error_errno("ampliconclip", "cannot open output file"); + return 1; + } + + if (param.rejects_file) { + sam_open_mode(wmode+1, param.rejects_file, NULL); + + if ((reject = sam_open_format(param.rejects_file, wmode, &ga.out)) == NULL) { + print_error_errno("ampliconclip", "cannot open rejects file"); + return 1; + } + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(stderr, "[ampliconclip] error: cannot create thread pool.\n"); + return 1; + } + hts_set_opt(in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(out, HTS_OPT_THREAD_POOL, &p); + + if (reject) { + hts_set_opt(reject, HTS_OPT_THREAD_POOL, &p); + } + } + + param.arg_list = stringify_argv(argc + 1, argv - 1); + + ret = bam_clip(in, out, reject, bedfile, clipping, ¶m); + + // cleanup + sam_close(in); + + if (sam_close(out) < 0) { + fprintf(stderr, "[ampliconclip] error: error while closing output file %s.\n", argv[optind+1]); + ret = 1; + } + + if (reject) { + if (sam_close(reject) < 0) { + fprintf(stderr, "[ampliconclip] error: error while closing reject file %s.\n", param.rejects_file); + ret = 1; + } + } + + if (p.pool) hts_tpool_destroy(p.pool); + + sam_global_args_free(&ga); + free(param.arg_list); + + return ret; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..0c368508e9c7d5d53d31defef7f196cba5a0bf62 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.c.pysam.c @@ -0,0 +1,1119 @@ +#include "samtools.pysam.h" + +/* bam_ampliconclip.c -- loads amplicon primers from a BED file and cuts reads + from the 5' end. + + Copyright (C) 2020-2023 Genome Research Ltd. + + Authors: Andrew Whitwham + Rob Davies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include +#include "htslib/hfile.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "samtools.h" +#include "bam_ampliconclip.h" + +typedef enum { + soft_clip, + hard_clip +} clipping_type; + +typedef struct { + int add_pg; + int use_strand; + int write_clipped; + int mark_fail; + int both; + int fail_len; + int filter_len; + int unmapped; + int oa_tag; + int del_tag; + int tol; + int unmap_len; + char *arg_list; + char *stats_file; + char *rejects_file; +} cl_param_t; + + +static int bed_entry_sort(const void *av, const void *bv) { + bed_entry_t *a = (bed_entry_t *) av; + bed_entry_t *b = (bed_entry_t *) bv; + return a->right < b->right ? -1 : (a->right == b->right ? 0 : 1); +} + + +int load_bed_file_multi_ref(char *infile, int get_strand, int sort_by_pos, khash_t(bed_list_hash) *bed_lists) { + hFILE *fp; + int line_count = 0, ret; + int64_t left, right; + kstring_t line = KS_INITIALIZE; + bed_entry_list_t *list; + khiter_t bed_itr; + + if ((fp = hopen(infile, "r")) == NULL) { + print_error_errno("amplicon", "unable to open file %s.", infile); + return 1; + } + + char ref[1024]; + + while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) { + line_count++; + int hret; + char strand; + + if (line.l == 0 || *line.s == '#') continue; + if (strncmp(line.s, "track ", 6) == 0) continue; + if (strncmp(line.s, "browser ", 8) == 0) continue; + + if (get_strand) { + if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64" %*s %*s %c", + ref, &left, &right, &strand) != 4) { + fprintf(samtools_stderr, "[amplicon] error: bad bed file format in line %d of %s.\n" + "(N.B. ref/chrom name limited to 1023 characters.)\n", + line_count, infile); + ret = 1; + goto error; + } + } else { + if (sscanf(line.s, "%1023s %"SCNd64" %"SCNd64, + ref, &left, &right) != 3) { + fprintf(samtools_stderr, "[amplicon] error: bad bed file format in line %d of %s\n" + "(N.B. ref/chrom name limited to 1023 characters.)\n", + line_count, infile); + ret = 1; + goto error; + } + } + + bed_itr = kh_get(bed_list_hash, bed_lists, ref); + + if (bed_itr == kh_end(bed_lists)) { // new ref entry + char *ref_name = strdup(ref); // need a copy for the hash key + + if (!ref_name) { + fprintf(samtools_stderr, "[amplicon] error: unable to allocate memory for ref name.\n"); + ret = 1; + goto error; + } + + bed_itr = kh_put(bed_list_hash, bed_lists, ref_name, &hret); + + if (hret > 0) { + list = &kh_val(bed_lists, bed_itr); + + // initialise the new hash entry + list->longest = 0; + list->size = 0; + list->length = 0; + list->bp = NULL; + } else { + fprintf(samtools_stderr, "[amplicon] error: ref hashing failure.\n"); + ret = 1; + goto error; + } + } else { // existing ref + list = &kh_val(bed_lists, bed_itr); + } + + if (list->length == list->size) { + bed_entry_t *tmp; + + list->size += list->size / 2 + 256; + + if ((tmp = realloc(list->bp, list->size * sizeof(bed_entry_t))) == NULL) { + fprintf(samtools_stderr, "[amplicon] error: unable to allocate more memory for bed data.\n"); + ret = 1; + goto error; + } + + list->bp = tmp; + } + + list->bp[list->length].left = left; + list->bp[list->length].right = right; + + if (get_strand) { + if (strand == '+') { + list->bp[list->length].rev = 0; + } else if (strand == '-') { + list->bp[list->length].rev = 1; + } else { + fprintf(samtools_stderr, "[amplicon] error: bad strand value in line %d, expecting '+' or '-', found '%c'.\n", + line_count, strand); + ret = 1; + goto error; + } + } + + if (right - left > list->longest) + list->longest = right - left; + + list->length++; + } + + if (sort_by_pos) { + for (bed_itr = kh_begin(bed_lists); bed_itr != kh_end(bed_lists); ++bed_itr) { + if (kh_exist(bed_lists, bed_itr)) { + list = &kh_val(bed_lists, bed_itr); + qsort(list->bp, list->length, sizeof(list->bp[0]), bed_entry_sort); + } + } + } + + if (kh_size(bed_lists) > 0) {// any entries + ret = 0; + } else { + ret = 1; + } + +error: + ks_free(&line); + + if (hclose(fp) != 0) { + fprintf(samtools_stderr, "[amplicon] warning: failed to close %s", infile); + } + + return ret; +} + + +void destroy_bed_hash(khash_t(bed_list_hash) *hash) { + khiter_t itr; + + for (itr = kh_begin(hash); itr != kh_end(hash); ++itr) { + if (kh_exist(hash, itr)) { + free(kh_val(hash, itr).bp); + free((char *)kh_key(hash, itr)); + kh_key(hash, itr) = NULL; + } + } + + kh_destroy(bed_list_hash, hash); +} + + +static int matching_clip_site(bed_entry_list_t *sites, hts_pos_t pos, + int is_rev, int use_strand, int64_t longest, + cl_param_t *param) { + int i, size; // may need this to be variable + int tol = param->tol; + int l = 0, mid = sites->length / 2, r = sites->length; + int pos_tol = is_rev ? (pos > tol ? pos - tol : 0) : pos; + + while (r - l > 1) { + if (sites->bp[mid].right <= pos_tol) { + l = mid; + } else { + r = mid; + } + mid = (l + r) / 2; + } + + size = 0; + + for (i = l; i < sites->length; i++) { + hts_pos_t mod_left, mod_right; + + if (use_strand && is_rev != sites->bp[i].rev) + continue; + + if (is_rev) { + mod_left = sites->bp[i].left; + mod_right = sites->bp[i].right + tol; + } else { + if (sites->bp[i].left > tol) { + mod_left = sites->bp[i].left - tol; + } else { + mod_left = 0; + } + mod_right = sites->bp[i].right; + } + + if (pos + longest + tol < mod_right) + break; + + if (pos >= mod_left && pos <= mod_right) { + if (is_rev) { + if (size < pos - sites->bp[i].left) { + size = pos - sites->bp[i].left; + } + } else { + if (size < sites->bp[i].right - pos) { + size = sites->bp[i].right - pos; + } + } + } + } + + return size; +} + + +static int bam_trim_left(bam1_t *rec, bam1_t *rec_out, uint32_t bases, + clipping_type clipping) { + uint32_t *orig_cigar = bam_get_cigar(rec); + uint8_t *orig_seq = bam_get_seq(rec); + uint8_t *orig_qual = bam_get_qual(rec); + uint8_t *orig_aux = bam_get_aux(rec); + uint32_t *new_cigar; + uint8_t *new_qual; + size_t orig_l_aux = bam_get_l_aux(rec); + uint32_t i, j; + uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0; + hts_pos_t new_pos = rec->core.pos; + uint32_t cig_type, cig_op; + + if (rec->l_data + 8 > rec_out->m_data) { + uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8); + if (!new_data) { + fprintf(samtools_stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n"); + return 1; + } + rec_out->data = new_data; + rec_out->m_data = rec->l_data + 8; + } + + // Copy core data & name + memcpy(&rec_out->core, &rec->core, sizeof(rec->core)); + memcpy(rec_out->data, rec->data, rec->core.l_qname); + + // Modify CIGAR + new_cigar = bam_get_cigar(rec_out); + + for (i = 0; i < rec->core.n_cigar; i++) { + cig_op = bam_cigar_op(orig_cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if (cig_op == BAM_CHARD_CLIP) { + hardclip += bam_cigar_oplen(orig_cigar[i]); + } else { + if (cig_type & 2) { + if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) { + ref_remove -= bam_cigar_oplen(orig_cigar[i]); + } else { + break; + } + new_pos += bam_cigar_oplen(orig_cigar[i]); + } + if (cig_type & 1) { + qry_removed += bam_cigar_oplen(orig_cigar[i]); + } + } + } + + if (i < rec->core.n_cigar) { + cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i])); + + // account for the last operation + if (cig_type & 2) { + new_pos += ref_remove; + } + if (cig_type & 1) { + qry_removed += ref_remove; + } + } else { + if (clipping == hard_clip) { + + rec_out->core.l_qseq = 0; + rec_out->core.n_cigar = 0; + + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; + } + + qry_removed = rec->core.l_qseq; + } + + j = 0; + if (clipping == hard_clip && hardclip + qry_removed > 0) { + new_cigar[j++] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP); + } + if (clipping == soft_clip) { + if (hardclip > 0) { + new_cigar[j++] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP); + } + if (qry_removed > 0) { + new_cigar[j++] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP); + } + } + + if (i < rec->core.n_cigar + && bam_cigar_oplen(orig_cigar[i]) > ref_remove) { + new_cigar[j++] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i])); + + // fill in the rest of the cigar + i++; + + for (; i < rec->core.n_cigar; i++) { + new_cigar[j++] = orig_cigar[i]; + } + } + + rec_out->core.n_cigar = j; + + if (clipping == soft_clip) { + qry_removed = 0; // Copy all the sequence and confidence values + } + + new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2; + // Copy remaining SEQ + if ((qry_removed & 1) == 0) { + memcpy(bam_get_seq(rec_out), orig_seq + (qry_removed / 2), + (rec->core.l_qseq - qry_removed + 1) / 2); // +1 to account for odd numbers + } else { + uint8_t *in = orig_seq + qry_removed / 2; + uint8_t *out = bam_get_seq(rec_out); + uint32_t i; + for (i = qry_removed; i < rec->core.l_qseq - 1; i += 2) { + *out++ = ((in[0] & 0x0f) << 4) | ((in[1] & 0xf0) >> 4); + in++; + } + if (i < rec->core.l_qseq) { + *out++ = (in[0] & 0x0f) << 4; + } + assert(out == new_qual); + } + + // Copy remaining QUAL + memmove(new_qual, orig_qual, rec->core.l_qseq - qry_removed); + + // Set new l_qseq + rec_out->core.l_qseq -= qry_removed; + + // Move AUX + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + // Set new l_data + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + // put in new pos + rec_out->core.pos = new_pos; + + return 0; +} + + +static int bam_trim_right(bam1_t *rec, bam1_t *rec_out, uint32_t bases, + clipping_type clipping) { + uint32_t *orig_cigar = bam_get_cigar(rec); + uint8_t *orig_seq = bam_get_seq(rec); + uint8_t *orig_qual = bam_get_qual(rec); + uint8_t *orig_aux = bam_get_aux(rec); + uint32_t *new_cigar; + uint32_t new_n_cigar = 0; + uint8_t *new_qual; + size_t orig_l_aux = bam_get_l_aux(rec); + int32_t i; + int32_t j; + uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0; + uint32_t cig_type, cig_op; + + if (rec->l_data + 8 > rec_out->m_data) { + uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8); + if (!new_data) { + fprintf(samtools_stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n"); + return 1; + } + rec_out->data = new_data; + rec_out->m_data = rec->l_data + 8; + } + + // Copy core data & name + memcpy(&rec_out->core, &rec->core, sizeof(rec->core)); + memcpy(rec_out->data, rec->data, rec->core.l_qname); + + // Modify CIGAR here + new_cigar = bam_get_cigar(rec_out); + + for (i = rec->core.n_cigar - 1; i >= 0; --i) { + cig_op = bam_cigar_op(orig_cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if (cig_op == BAM_CHARD_CLIP) { + hardclip += bam_cigar_oplen(orig_cigar[i]); + } else { + if (cig_type & 2) { + if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) { + ref_remove -= bam_cigar_oplen(orig_cigar[i]); + } else { + break; + } + } + if (cig_type & 1) { + qry_removed += bam_cigar_oplen(orig_cigar[i]); + } + } + } + + if (i >= 0) { + cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i])); + if (cig_type & 1) { + qry_removed += ref_remove; + } + j = i; + if (qry_removed > 0) j++; + if (hardclip > 0 && (clipping == soft_clip || qry_removed == 0)) j++; + } else { + if (clipping == hard_clip) { + + rec_out->core.l_qseq = 0; + rec_out->core.n_cigar = 0; + + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; + } + + qry_removed = rec->core.l_qseq; + j = 0; + if (hardclip > 0 && clipping == soft_clip) j++; + } + + if (clipping == hard_clip && hardclip + qry_removed > 0) { + new_cigar[j] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP); + new_n_cigar++; + } + if (clipping == soft_clip) { + if (hardclip > 0) { + new_cigar[j] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP); + new_n_cigar++; + if (qry_removed > 0) --j; + } + if (qry_removed > 0) { + new_cigar[j] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP); + new_n_cigar++; + } + } + + if (j > 0) { + new_cigar[--j] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i])); + new_n_cigar++; + } + + // fill in the rest of the cigar + while (j > 0) { + new_cigar[--j] = orig_cigar[--i]; + new_n_cigar++; + } + + rec_out->core.n_cigar = new_n_cigar; + + if (clipping == soft_clip) + qry_removed = 0; // Copy all the sequence and confidence values + + new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2; + // Copy remaining SEQ + memcpy(bam_get_seq(rec_out), orig_seq, (rec->core.l_qseq - qry_removed + 1) / 2); + + // Copy remaining QUAL + memcpy(new_qual, orig_qual, rec->core.l_qseq - qry_removed); + + // Set new l_qseq + rec_out->core.l_qseq -= qry_removed; + + // Copy AUX + if (orig_l_aux) + memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux); + + // Set new l_data + rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux; + + return 0; +} + + +static hts_pos_t active_query_len(bam1_t *b) { + uint32_t *cigar = bam_get_cigar(b); + uint32_t cig_type, cig_op; + hts_pos_t len = 0; + int i; + + for (i = 0; i < b->core.n_cigar; i++) { + cig_op = bam_cigar_op(cigar[i]); + cig_type = bam_cigar_type(cig_op); + + if ((cig_type & 1) && (cig_op != BAM_CSOFT_CLIP)) { + len += bam_cigar_oplen(cigar[i]); + } + } + + return len; +} + + +static inline void swap_bams(bam1_t **a, bam1_t **b) { + bam1_t *tmp = *a; + *a = *b; + *b = tmp; +} + + +// Format OA:Z:(RNAME,POS,strand,CIGAR,MAPQ,NM; +static inline int tag_original_data(bam1_t *orig, kstring_t *oa_tag) { + char strand; + uint8_t *nm_tag, *old_oa_tag; + uint32_t *cigar; + int64_t nm = 0; + int i, res = 0; + + ks_clear(oa_tag); + + // if there is an existing OA tag the new one gets appended to it + if ((old_oa_tag = bam_aux_get(orig, "OA"))) { + res |= ksprintf(oa_tag, "%s", bam_aux2Z(old_oa_tag)) < 0; + } + + if (orig->core.flag & BAM_FREVERSE) + strand = '-'; + else + strand = '+'; + + if ((nm_tag = bam_aux_get(orig, "NM"))) { + nm = bam_aux2i(nm_tag); + } + + res |= ksprintf(oa_tag, "%s,%"PRIhts_pos",%c,", bam_get_qname(orig), orig->core.pos + 1, strand) < 0; + + for (i = 0, cigar = bam_get_cigar(orig); i < orig->core.n_cigar && res == 0; ++i) { + res |= kputw(bam_cigar_oplen(cigar[i]), oa_tag) < 0; + res |= kputc(bam_cigar_opchr(cigar[i]), oa_tag) < 0; + } + + if (nm_tag) { + res |= ksprintf(oa_tag, ",%d,%"PRId64";", orig->core.qual, nm) < 0; + } else { + res |= ksprintf(oa_tag, "%d,;", orig->core.qual) < 0; + } + + return res; +} + + +static int bam_clip(samFile *in, samFile *out, samFile *reject, char *bedfile, + clipping_type clipping, cl_param_t *param) { + int ret = 1, r, file_open = 0; + + bam_hdr_t *header = NULL; + bam1_t *b = NULL, *b_tmp = NULL; + long f_count = 0, r_count = 0, n_count = 0, l_count = 0, l_exclude = 0, b_count = 0; + long filtered = 0, written = 0, failed = 0; + kstring_t str = KS_INITIALIZE; + kstring_t oat = KS_INITIALIZE; + kstring_t seq = KS_INITIALIZE; + bed_entry_list_t *sites; + FILE *stats_fp = samtools_stderr; + khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash); + + if (load_bed_file_multi_ref(bedfile, param->use_strand, 1, bed_hash)) { + fprintf(samtools_stderr, "[ampliconclip] error: unable to load bed file.\n"); + goto fail; + } + + if ((header = sam_hdr_read(in)) == NULL) { + fprintf(samtools_stderr, "[ampliconclip] error: could not read header\n"); + goto fail; + } + + // changing pos can ruin coordinate sort order + if (sam_hdr_find_tag_hd(header, "SO", &str) == 0 && str.s && strcmp(str.s, "coordinate") == 0) { + const char *new_order = "unknown"; + + if (sam_hdr_update_hd(header, "SO", new_order) == -1) { + fprintf(samtools_stderr, "[ampliconclip] error: unable to change sort order to 'SO:%s'\n", new_order); + goto fail; + } + } + + ks_free(&str); + + if (param->add_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(), + param->arg_list ? "CL" : NULL, + param->arg_list ? param->arg_list : NULL, + NULL) != 0) { + fprintf(samtools_stderr, "[ampliconclip] warning: unable to add @PG line to header.\n"); + } + if (sam_hdr_write(out, header) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: could not write header.\n"); + goto fail; + } + + if (reject) { + if (sam_hdr_write(reject, header) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: could not write header to rejects file.\n"); + goto fail; + } + } + + b = bam_init1(); + b_tmp = bam_init1(); + if (!b || !b_tmp) { + fprintf(samtools_stderr, "[ampliconclip] error: out of memory when trying to create record.\n"); + goto fail; + } + + int32_t last_tid = -1; + int ref_found = 0; + + while ((r = sam_read1(in, header, b)) >= 0) { + hts_pos_t pos; + int is_rev; + int p_size; + int been_clipped = 0, filter = 0; + int exclude = (BAM_FUNMAP | BAM_FQCFAIL); + khiter_t itr; + + l_count++; + + if (b->core.tid != last_tid) { + const char *ref_name; + + ref_found = 0; + last_tid = b->core.tid; + + if ((ref_name = sam_hdr_tid2name(header, b->core.tid)) != NULL) { + itr = kh_get(bed_list_hash, bed_hash, ref_name); + + if (itr != kh_end(bed_hash)) { + sites = &kh_val(bed_hash, itr); + ref_found = 1; + } + } + } + + if (!(b->core.flag & exclude) && ref_found) { + if (param->oa_tag) + if (tag_original_data(b, &oat)) + goto fail; + + if (!param->both) { + if (bam_is_rev(b)) { + pos = bam_endpos(b); + is_rev = 1; + } else { + pos = b->core.pos; + is_rev = 0; + } + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (is_rev) { + if (bam_trim_right(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + r_count++; + } else { + if (bam_trim_left(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + f_count++; + } + + if (param->oa_tag) { + if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s)) + goto fail; + } + + if (param->del_tag) { + uint8_t *tag; + + if ((tag = bam_aux_get(b, "NM"))) + bam_aux_del(b, tag); + + if ((tag = bam_aux_get(b, "MD"))) + bam_aux_del(b, tag); + } + + been_clipped = 1; + } else { + if (param->mark_fail) { + b->core.flag |= BAM_FQCFAIL; + } + + n_count++; + } + } else { + int left = 0, right = 0; + + // left first + pos = b->core.pos; + is_rev = 0; + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (bam_trim_left(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + f_count++; + left = 1; + been_clipped = 1; + } + + // the right + pos = bam_endpos(b); + is_rev = 1; + + if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) { + if (bam_trim_right(b, b_tmp, p_size, clipping) != 0) + goto fail; + + swap_bams(&b, &b_tmp); + r_count++; + right = 1; + been_clipped = 1; + } + + if (left || right) { + uint8_t *tag; + + if (param->oa_tag) { + if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s)) + goto fail; + } + + if (param->del_tag) { + if ((tag = bam_aux_get(b, "NM"))) + bam_aux_del(b, tag); + + if ((tag = bam_aux_get(b, "MD"))) + bam_aux_del(b, tag); + } + } + + if (left && right) { + b_count++; + } else if (!left && !right) { + if (param->mark_fail) { + b->core.flag |= BAM_FQCFAIL; + } + + n_count++; + } + } + + if (param->fail_len >= 0 || param->filter_len >= 0 || param->unmap_len >= 0) { + hts_pos_t aql = active_query_len(b); + + if (param->fail_len >= 0 && aql <= param->fail_len) { + b->core.flag |= BAM_FQCFAIL; + } + + if (param->filter_len >= 0 && aql <= param->filter_len) { + filter = 1; + } + + if (param->unmap_len >= 0 && aql <= param->unmap_len) { + + if (ks_resize(&seq, b->core.l_qseq) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: allocate memory for sequence %s\n", bam_get_seq(b)); + goto fail; + } + + ks_clear(&seq); + char *sb = ks_str(&seq); + uint8_t *sequence = bam_get_seq(b); + int i; + + for (i = 0; i < b->core.l_qseq ; ++i) { + *sb++ = seq_nt16_str[bam_seqi(sequence, i)]; + } + + if (bam_set1(b_tmp, b->core.l_qname - b->core.l_extranul - 1, bam_get_qname(b), + (b->core.flag | BAM_FUNMAP), b->core.tid, b->core.pos, 0, + 0, NULL, b->core.mtid, b->core.mpos, b->core.isize, + b->core.l_qseq, seq.s, (const char *)bam_get_qual(b), + bam_get_l_aux(b)) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: could not unmap read %s\n", bam_get_seq(b)); + goto fail; + } + + memcpy(bam_get_aux(b_tmp), bam_get_aux(b), bam_get_l_aux(b)); + b_tmp->l_data += bam_get_l_aux(b); + swap_bams(&b, &b_tmp); + } + } + + if (b->core.flag & BAM_FQCFAIL) { + failed++; + } + + if (param->write_clipped && !been_clipped) { + filter = 1; + } + + } else { + l_exclude++; + + if (param->unmapped) { + filter = 1; + } + } + + if (!filter) { + if (sam_write1(out, header, b) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: could not write line %ld.\n", l_count); + goto fail; + } + + written++; + } else { + if (reject) { + if (sam_write1(reject, header, b) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: could not write to reject file %s\n", + param->rejects_file); + goto fail; + } + } + + filtered++; + } + } + + if (r < -1) { + fprintf(samtools_stderr, "[ampliconclip] error: failed to read input.\n"); + goto fail; + } + + if (param->stats_file) { + if ((stats_fp = fopen(param->stats_file, "w")) == NULL) { + fprintf(samtools_stderr, "[ampliconclip] warning: cannot write stats to %s.\n", param->stats_file); + } else { + file_open = 1; + } + } + + fprintf(stats_fp, "COMMAND: %s\n" + "TOTAL READS: %ld\n" + "TOTAL CLIPPED: %ld\n" + "FORWARD CLIPPED: %ld\n" + "REVERSE CLIPPED: %ld\n" + "BOTH CLIPPED: %ld\n" + "NOT CLIPPED: %ld\n" + "EXCLUDED: %ld\n" + "FILTERED: %ld\n" + "FAILED: %ld\n" + "WRITTEN: %ld\n", param->arg_list, l_count, f_count + r_count, + f_count, r_count, b_count, n_count, l_exclude, + filtered, failed, written); + + if (file_open) { + fclose(stats_fp); + } + + ret = 0; + +fail: + destroy_bed_hash(bed_hash); + ks_free(&oat); + ks_free(&seq); + sam_hdr_destroy(header); + bam_destroy1(b); + bam_destroy1(b_tmp); + return ret; +} + + +static void usage(void) { + fprintf(samtools_stderr, "Usage: samtools ampliconclip -b BED file -o \n\n"); + fprintf(samtools_stderr, "Option: \n"); + fprintf(samtools_stderr, " -b FILE BED file of regions (eg amplicon primers) to be removed.\n"); + fprintf(samtools_stderr, " -o FILE output file name (default samtools_stdout).\n"); + fprintf(samtools_stderr, " -f FILE write stats to file name (default samtools_stderr)\n"); + fprintf(samtools_stderr, " -u Output uncompressed data\n"); + fprintf(samtools_stderr, " --soft-clip soft clip amplicon primers from reads (default)\n"); + fprintf(samtools_stderr, " --hard-clip hard clip amplicon primers from reads.\n"); + fprintf(samtools_stderr, " --both-ends clip on both 5' and 3' ends.\n"); + fprintf(samtools_stderr, " --strand use strand data from BED file to match read direction.\n"); + fprintf(samtools_stderr, " --clipped only output clipped reads.\n"); + fprintf(samtools_stderr, " --fail mark unclipped, mapped reads as QCFAIL.\n"); + fprintf(samtools_stderr, " --filter-len INT do not output reads INT size or shorter.\n"); + fprintf(samtools_stderr, " --fail-len INT mark as QCFAIL reads INT size or shorter.\n"); + fprintf(samtools_stderr, " --unmap-len INT unmap reads INT size or shorter, default 0.\n"); + fprintf(samtools_stderr, " --no-excluded do not write excluded reads (unmapped or QCFAIL).\n"); + fprintf(samtools_stderr, " --rejects-file FILE file to write filtered reads.\n"); + fprintf(samtools_stderr, " --original for clipped entries add an OA tag with original data.\n"); + fprintf(samtools_stderr, " --keep-tag for clipped entries keep the old NM and MD tags.\n"); + fprintf(samtools_stderr, " --tolerance match region within this number of bases, default 5.\n"); + fprintf(samtools_stderr, " --no-PG do not add an @PG line.\n"); + sam_global_opt_help(samtools_stderr, "-.O..@-."); + fprintf(samtools_stderr, "\nAbout: Soft clips read alignments where they match BED file defined regions.\n" + "Default clipping is only on the 5' end.\n\n"); +} + + +int amplicon_clip_main(int argc, char **argv) { + int c, ret; + char wmode[4] = {'w', 'b', 0, 0}; + char *bedfile = NULL, *fnout = "-"; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool p = {NULL, 0}; + samFile *in = NULL, *out = NULL, *reject = NULL; + clipping_type clipping = soft_clip; + cl_param_t param = {1, 0, 0, 0, 0, -1, -1, 0, 0, 1, 5, 0, NULL, NULL, NULL}; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1002}, + {"soft-clip", no_argument, NULL, 1003}, + {"hard-clip", no_argument, NULL, 1004}, + {"strand", no_argument, NULL, 1005}, + {"clipped", no_argument, NULL, 1006}, + {"fail", no_argument, NULL, 1007}, + {"both-ends", no_argument, NULL, 1008}, + {"filter-len", required_argument, NULL, 1009}, + {"fail-len", required_argument, NULL, 1010}, + {"no-excluded", no_argument, NULL, 1011}, + {"rejects-file", required_argument, NULL, 1012}, + {"original", no_argument, NULL, 1013}, + {"keep-tag", no_argument, NULL, 1014}, + {"tolerance", required_argument, NULL, 1015}, + {"unmap-len", required_argument, NULL, 1016}, + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "b:@:o:O:f:u", lopts, NULL)) >= 0) { + switch (c) { + case 'b': bedfile = optarg; break; + case 'o': fnout = optarg; break; + case 'f': param.stats_file = optarg; break; + case 'u': wmode[2] = '0'; break; + case 1002: param.add_pg = 0; break; + case 1003: clipping = soft_clip; break; + case 1004: clipping = hard_clip; break; + case 1005: param.use_strand = 1; break; + case 1006: param.write_clipped = 1; break; + case 1007: param.mark_fail = 1; break; + case 1008: param.both = 1; break; + case 1009: param.filter_len = atoi(optarg); break; + case 1010: param.fail_len = atoi(optarg); break; + case 1011: param.unmapped = 1; break; + case 1012: param.rejects_file = optarg; break; + case 1013: param.oa_tag = 1; break; + case 1014: param.del_tag = 0; break; + case 1015: param.tol = atoi(optarg); break; + case 1016: param.unmap_len = atoi(optarg); break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage(); samtools_exit(1); + } + } + + if (!bedfile) { + usage(); + return 1; + } + + if (optind + 1 > argc) { + usage(); + return 1; + } + + if (param.tol < 0) { + fprintf(samtools_stderr, "[ampliconclip] warning: invalid tolerance of %d," + " resetting tolerance to default of 5.\n", param.tol); + param.tol = 5; + } + + if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) { + print_error_errno("ampliconclip", "cannot open input file"); + return 1; + } + + sam_open_mode(wmode+1, fnout, NULL); + + if ((out = sam_open_format(fnout, wmode, &ga.out)) == NULL) { + print_error_errno("ampliconclip", "cannot open output file"); + return 1; + } + + if (param.rejects_file) { + sam_open_mode(wmode+1, param.rejects_file, NULL); + + if ((reject = sam_open_format(param.rejects_file, wmode, &ga.out)) == NULL) { + print_error_errno("ampliconclip", "cannot open rejects file"); + return 1; + } + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(samtools_stderr, "[ampliconclip] error: cannot create thread pool.\n"); + return 1; + } + hts_set_opt(in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(out, HTS_OPT_THREAD_POOL, &p); + + if (reject) { + hts_set_opt(reject, HTS_OPT_THREAD_POOL, &p); + } + } + + param.arg_list = stringify_argv(argc + 1, argv - 1); + + ret = bam_clip(in, out, reject, bedfile, clipping, ¶m); + + // cleanup + sam_close(in); + + if (sam_close(out) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: error while closing output file %s.\n", argv[optind+1]); + ret = 1; + } + + if (reject) { + if (sam_close(reject) < 0) { + fprintf(samtools_stderr, "[ampliconclip] error: error while closing reject file %s.\n", param.rejects_file); + ret = 1; + } + } + + if (p.pool) hts_tpool_destroy(p.pool); + + sam_global_args_free(&ga); + free(param.arg_list); + + return ret; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.h new file mode 100644 index 0000000000000000000000000000000000000000..ef3535702a5e6762e4a05c8d9b68cc3d8cfcb935 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_ampliconclip.h @@ -0,0 +1,54 @@ +/* bam_ampliconclip.h -- shared functions between amplicon clip/stats + + Copyright (C) 2020-2021 Genome Research Ltd. + + Author: James Bonfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef BAM_AMPLICONCLIP_H +#define BAM_AMPLICONCLIP_H + +#include "htslib/khash.h" + +typedef struct { + int64_t left; + int64_t right; + int rev; +} bed_entry_t; + +typedef struct { + bed_entry_t *bp; + int64_t longest; + int length; + int size; +} bed_entry_list_t; + +KHASH_MAP_INIT_STR(bed_list_hash, bed_entry_list_t); + +#define BED_LIST_INIT {NULL, 0, 0, 0, {0}} + + +int load_bed_file_multi_ref(char *infile, int get_strand, + int sort_by_pos, khash_t(bed_list_hash) *bed_lists); + +void destroy_bed_hash(khash_t(bed_list_hash) *hash); + + +#endif /* BAM_AMPLICONCLIP_H */ diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_aux.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_aux.c new file mode 100644 index 0000000000000000000000000000000000000000..d11ee6e45b24299ff25f9f8b922f7e70b4de2ca8 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_aux.c @@ -0,0 +1,61 @@ +/* bam_aux.c -- remaining aux field handling. + + Copyright (C) 2008-2010, 2013, 2015, 2019 Genome Research Ltd. + Portions copyright (C) 2011 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include "htslib/sam.h" + +static inline int bam_aux_type2size(int x) +{ + if (x == 'C' || x == 'c' || x == 'A') return 1; + else if (x == 'S' || x == 's') return 2; + else if (x == 'I' || x == 'i' || x == 'f' || x == 'F') return 4; + else return 0; +} + +#define __skip_tag(s) do { \ + int type = toupper(*(s)); \ + ++(s); \ + if (type == 'Z' || type == 'H') { while (*(s)) ++(s); ++(s); } \ + else if (type == 'B') (s) += 5 + bam_aux_type2size(*(s)) * (*(int32_t*)((s)+1)); \ + else (s) += bam_aux_type2size(type); \ + } while(0) + + +int bam_aux_drop_other(bam1_t *b, uint8_t *s) +{ + if (s) { + uint8_t *p, *aux; + aux = bam_get_aux(b); + p = s - 2; + __skip_tag(s); + memmove(aux, p, s - p); + b->l_data -= bam_get_l_aux(b) - (s - p); + } else { + b->l_data -= bam_get_l_aux(b); + } + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_color.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_color.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..105cc332769d178affdc6c1bd27a755fda52ea52 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_color.c.pysam.c @@ -0,0 +1,175 @@ +#include "samtools.pysam.h" + +/* bam_color.c -- color-space support. + + Copyright (C) 2009, 2012 University of California - Los Angeles. + + Author: Nils Homer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include + +#include "htslib/sam.h" + +/*! + @abstract Get the color encoding the previous and current base + @param b pointer to an alignment + @param i The i-th position, 0-based + @return color + + @discussion Returns 0 no color information is found. + */ +char bam_aux_getCSi(bam1_t *b, int i) +{ + uint8_t *c = bam_aux_get(b, "CS"); + char *cs = NULL; + + // return the base if the tag was not found + if(0 == c) return 0; + + cs = bam_aux2Z(c); + // adjust for strandedness and leading adaptor + if(bam_is_rev(b)) { + i = strlen(cs) - 1 - i; + // adjust for leading hard clip + uint32_t cigar = bam_get_cigar(b)[0]; + if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { + i -= cigar >> BAM_CIGAR_SHIFT; + } + } else { i++; } + return cs[i]; +} + +/*! + @abstract Get the color quality of the color encoding the previous and current base + @param b pointer to an alignment + @param i The i-th position, 0-based + @return color quality + + @discussion Returns 0 no color information is found. + */ +char bam_aux_getCQi(bam1_t *b, int i) +{ + uint8_t *c = bam_aux_get(b, "CQ"); + char *cq = NULL; + + // return the base if the tag was not found + if(0 == c) return 0; + + cq = bam_aux2Z(c); + // adjust for strandedness + if(bam_is_rev(b)) { + i = strlen(cq) - 1 - i; + // adjust for leading hard clip + uint32_t cigar = bam_get_cigar(b)[0]; + if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { + i -= (cigar >> BAM_CIGAR_SHIFT); + } + } + return cq[i]; +} + +char bam_aux_nt2int(char a) +{ + switch(toupper(a)) { + case 'A': + return 0; + break; + case 'C': + return 1; + break; + case 'G': + return 2; + break; + case 'T': + return 3; + break; + default: + return 4; + break; + } +} + +char bam_aux_ntnt2cs(char a, char b) +{ + a = bam_aux_nt2int(a); + b = bam_aux_nt2int(b); + if(4 == a || 4 == b) return '4'; + return "0123"[(int)(a ^ b)]; +} + +/*! + @abstract Get the color error profile at the give position + @param b pointer to an alignment + @return the original color if the color was an error, '-' (dash) otherwise + + @discussion Returns 0 no color information is found. + */ +char bam_aux_getCEi(bam1_t *b, int i) +{ + int cs_i; + uint8_t *c = bam_aux_get(b, "CS"); + char *cs = NULL; + char prev_b, cur_b; + char cur_color, cor_color; + + // return the base if the tag was not found + if(0 == c) return 0; + + cs = bam_aux2Z(c); + + // adjust for strandedness and leading adaptor + if(bam_is_rev(b)) { //reverse strand + cs_i = strlen(cs) - 1 - i; + // adjust for leading hard clip + uint32_t cigar = bam_get_cigar(b)[0]; + if((cigar & BAM_CIGAR_MASK) == BAM_CHARD_CLIP) { + cs_i -= cigar >> BAM_CIGAR_SHIFT; + } + // get current color + cur_color = cs[cs_i]; + // get previous base. Note: must rc adaptor + prev_b = (cs_i == 1) ? "TGCAN"[(int)bam_aux_nt2int(cs[0])] : seq_nt16_str[bam_seqi(bam_get_seq(b), i+1)]; + // get current base + cur_b = seq_nt16_str[bam_seqi(bam_get_seq(b), i)]; + } + else { + cs_i=i+1; + // get current color + cur_color = cs[cs_i]; + // get previous base + prev_b = (0 == i) ? cs[0] : seq_nt16_str[bam_seqi(bam_get_seq(b), i-1)]; + // get current base + cur_b = seq_nt16_str[bam_seqi(bam_get_seq(b), i)]; + } + + // corrected color + cor_color = bam_aux_ntnt2cs(prev_b, cur_b); + + if(cur_color == cor_color) { + return '-'; + } + else { + return cur_color; + } +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c new file mode 100644 index 0000000000000000000000000000000000000000..78312eee789db3136dae39de5609aaeac1924705 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c @@ -0,0 +1,86 @@ +/* bam_flags.c -- flags subcommand. + + Copyright (C) 2013-2014, 2021 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "samtools.h" + +static void usage(FILE *fp) +{ + static const struct { int bit; const char *desc; } *fl, flags[] = { + { BAM_FPAIRED, "paired-end / multiple-segment sequencing technology" }, + { BAM_FPROPER_PAIR, "each segment properly aligned according to aligner" }, + { BAM_FUNMAP, "segment unmapped" }, + { BAM_FMUNMAP, "next segment in the template unmapped" }, + { BAM_FREVERSE, "SEQ is reverse complemented" }, + { BAM_FMREVERSE, "SEQ of next segment in template is rev.complemented" }, + { BAM_FREAD1, "the first segment in the template" }, + { BAM_FREAD2, "the last segment in the template" }, + { BAM_FSECONDARY, "secondary alignment" }, + { BAM_FQCFAIL, "not passing quality controls or other filters" }, + { BAM_FDUP, "PCR or optical duplicate" }, + { BAM_FSUPPLEMENTARY, "supplementary alignment" }, + { 0, NULL } + }; + + fprintf(fp, +"About: Convert between textual and numeric flag representation\n" +"Usage: samtools flags FLAGS...\n" +"\n" +"Each FLAGS argument is either an INT (in decimal/hexadecimal/octal) representing\n" +"a combination of the following numeric flag values, or a comma-separated string\n" +"NAME,...,NAME representing a combination of the following flag names:\n" +"\n"); + for (fl = flags; fl->desc; fl++) { + char *name = bam_flag2str(fl->bit); + fprintf(fp, "%#6x %5d %-15s%s\n", fl->bit, fl->bit, name, fl->desc); + free(name); + } +} + + +int main_flags(int argc, char *argv[]) +{ + if ( argc < 2 ) { usage(stdout); return 0; } + + int i; + for (i = 1; i < argc; i++) + { + int mask = bam_str2flag(argv[i]); + if ( mask<0 ) { print_error("flags", "Could not parse \"%s\"", argv[i]); usage(stderr); return 1; } + char *str = bam_flag2str(mask); + printf("0x%x\t%d\t%s\n", mask, mask, str); + free(str); + } + return 0; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..b3a9d29d4770b4d8bfa0c3f4f5cf906234dfc66a --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_flags.c.pysam.c @@ -0,0 +1,88 @@ +#include "samtools.pysam.h" + +/* bam_flags.c -- flags subcommand. + + Copyright (C) 2013-2014, 2021 Genome Research Ltd. + + Author: Petr Danecek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "samtools.h" + +static void usage(FILE *fp) +{ + static const struct { int bit; const char *desc; } *fl, flags[] = { + { BAM_FPAIRED, "paired-end / multiple-segment sequencing technology" }, + { BAM_FPROPER_PAIR, "each segment properly aligned according to aligner" }, + { BAM_FUNMAP, "segment unmapped" }, + { BAM_FMUNMAP, "next segment in the template unmapped" }, + { BAM_FREVERSE, "SEQ is reverse complemented" }, + { BAM_FMREVERSE, "SEQ of next segment in template is rev.complemented" }, + { BAM_FREAD1, "the first segment in the template" }, + { BAM_FREAD2, "the last segment in the template" }, + { BAM_FSECONDARY, "secondary alignment" }, + { BAM_FQCFAIL, "not passing quality controls or other filters" }, + { BAM_FDUP, "PCR or optical duplicate" }, + { BAM_FSUPPLEMENTARY, "supplementary alignment" }, + { 0, NULL } + }; + + fprintf(fp, +"About: Convert between textual and numeric flag representation\n" +"Usage: samtools flags FLAGS...\n" +"\n" +"Each FLAGS argument is either an INT (in decimal/hexadecimal/octal) representing\n" +"a combination of the following numeric flag values, or a comma-separated string\n" +"NAME,...,NAME representing a combination of the following flag names:\n" +"\n"); + for (fl = flags; fl->desc; fl++) { + char *name = bam_flag2str(fl->bit); + fprintf(fp, "%#6x %5d %-15s%s\n", fl->bit, fl->bit, name, fl->desc); + free(name); + } +} + + +int main_flags(int argc, char *argv[]) +{ + if ( argc < 2 ) { usage(samtools_stdout); return 0; } + + int i; + for (i = 1; i < argc; i++) + { + int mask = bam_str2flag(argv[i]); + if ( mask<0 ) { print_error("flags", "Could not parse \"%s\"", argv[i]); usage(samtools_stderr); return 1; } + char *str = bam_flag2str(mask); + fprintf(samtools_stdout, "0x%x\t%d\t%s\n", mask, mask, str); + free(str); + } + return 0; +} + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_import.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_import.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..f16a7811fc4718a9375d9657804b2eb9d56b39e3 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_import.c.pysam.c @@ -0,0 +1,525 @@ +#include "samtools.pysam.h" + +/* bam_import -- Import of FASTQ files. + * + * samtools import -1 a_1.fq -2 a_2.fq --i1 a_i1.fq --i2 a_i2.fq + * samtools import a_1.fq a_2.fq + * samtools import a_interleaved.fq + * + * Copyright (C) 2020-2021, 2023 Genome Research Ltd. + * + * Author: James Bonfield + */ + +/* +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + +// TODO: Store other non-aux comments; in new sam tag? + +#include +#include + +#include "htslib/sam.h" +#include "htslib/thread_pool.h" + +#include "samtools.h" +#include "sam_opts.h" + +static int usage(FILE *fp, int exit_status) { + fprintf(fp, "Usage: samtools import [options] [file.fastq ...]\n"); + fprintf(fp, "\n"); + fprintf(fp, "Options:\n"); + fprintf(fp, " -s FILE Read paired-ended data from single FILE\n"); + fprintf(fp, " -0 FILE Read single-ended data from FILE\n"); + fprintf(fp, " -1 FILE Read-1 from FILE\n"); + fprintf(fp, " -2 FILE Read-2 from FILE\n"); + fprintf(fp, " --i1 FILE Index-1 from FILE\n"); + fprintf(fp, " --i2 FILE Index-2 from FILE\n"); + fprintf(fp, " -i Parse CASAVA identifier\n"); + fprintf(fp, " --barcode-tag TAG\n"); + fprintf(fp, " Tag to use with barcode sequences [BC]\n"); + fprintf(fp, " --quality-tag TAG\n"); + fprintf(fp, " Tag to use with barcode qualities [QT]\n"); + fprintf(fp, " -N, --name2 Use 2nd field as read name (SRA format)\n"); + fprintf(fp, " -r STRING Build up a complete @RG line\n"); + fprintf(fp, " -R STRING Add a simple RG line of \"@RG\\tID:STRING\"\n"); + fprintf(fp, " -T TAGLIST Parse tags in SAM format; list of '*' for all\n"); + fprintf(fp, " -o FILE Output to FILE instead of samtools_stdout\n"); + fprintf(fp, " -u Uncompressed output\n"); + fprintf(fp, " --order TAG Store Nth record count in TAG\n"); + fprintf(fp, "\n"); + sam_global_opt_help(fp, "-.O.-@--"); + + fprintf(fp, "\nA single fastq file will be interpreted as -s, -0 or -1 depending on\n"); + fprintf(fp, "file contents, and a pair of fastq files as \"-1 FILE1 -2 FILE2\".\n"); + + return exit_status; +} + +// Order matters here as we want to read index elements before main +// sequences so on reading the seqs we can emit a fully annotated record. +enum fileno { + FQ_I1, FQ_I2, // index seqs for R1 and R2 + FQ_R0, // single file and unpaired data (singled-ended tech). + FQ_R1, FQ_R2, // separate read1 and read2 files + FQ_SINGLE, // single file, but with read1 and/or read2 present. + FQ_END +}; + +typedef struct { + sam_global_args ga; + int no_pg; + char *fn[FQ_END], *fn_out; + int idx_both; // add index to READ2 too, not just READ1 + int casava; + char *barcode_seq; + char *barcode_qual; + char *aux; + char *rg; + char *rg_line; + char *order; + int order_str; + int compress_level; + htsThreadPool p; + int name2; +} opts_t; + +// Append a sequence and quality string from a BAM record to a BC:Z and +// QT:Z style aux tag string. +static int append_index(kstring_t *s, kstring_t *q, bam1_t *b) { + char *sp, *qp; + if (ks_resize(s, s->l + b->core.l_qseq+1 +1) < 0) + return -1; + if (ks_resize(q, q->l + b->core.l_qseq+1 +1) < 0) + return -1; + + sp = s->s + s->l - (s->l > 0); + qp = q->s + q->l - (q->l > 0); + + if (s->l) + *sp++ = '-'; + + if (q->l) + *qp++ = ' '; + + int i; + uint8_t *seq = bam_get_seq(b); + uint8_t *qual = bam_get_qual(b); + for (i = 0; i < b->core.l_qseq; i++) { + *sp++ = seq_nt16_str[bam_seqi(seq, i)]; + *qp++ = qual[i] + '!'; + } + *sp++ = 0; + *qp++ = 0; + + s->l = sp - s->s; + q->l = qp - q->s; + + return 0; +} + +static int import_fastq(int argc, char **argv, opts_t *opts) { + int i, n, ret = 0; + samFile *fp_in[FQ_END] = {NULL}; + bam1_t *b = bam_init1(); + int ids[FQ_END]; + samFile *fp_out = NULL; + sam_hdr_t *hdr_out = NULL; + kstring_t index_str = {0,0}; + kstring_t read_str = {0,0}; + char *rg = opts->rg; + kstring_t rg_line = {0,0}; + uint64_t read_num = 0; + kstring_t idx_seq = {0}; + kstring_t idx_qual = {0}; + + // Any additional arguments are assumed to be r1 r2, as a + // short cut. We support reading index tags out of those too (eg + // Illumina CASAVA format), but if we do that we lack the barcode + // quality string. + // + // We also consider a read name ending in /1 or /2 to be a single + // file containing interleaved fastq records for both ends. + // These will be labeled as fn[FQ_R1] but adjusted during reading. + if (argc == 1) + opts->fn[FQ_SINGLE] = argv[0]; + else + for (i = 0; i < 4; i++) + if (argc > i) + opts->fn[FQ_R1+i] = argv[i]; + + // Open all files + for (i = n = 0; i < FQ_END; i++) { + if (!opts->fn[i]) + continue; + fp_in[i] = sam_open_format(opts->fn[i], "r", &opts->ga.in); + if (!fp_in[i]) { + perror(opts->fn[i]); + ret = -1; + goto err; + } + if (opts->p.pool) + hts_set_thread_pool(fp_in[i], &opts->p); + ids[n++] = i; + + if (opts->name2) + hts_set_opt(fp_in[i], FASTQ_OPT_NAME2, 1); + if (opts->casava) + hts_set_opt(fp_in[i], FASTQ_OPT_CASAVA, 1); + if (opts->barcode_seq) // for auto-CASAVA parsing + hts_set_opt(fp_in[i], FASTQ_OPT_BARCODE, opts->barcode_seq); + if (opts->aux) + hts_set_opt(fp_in[i], FASTQ_OPT_AUX, + *opts->aux == '*' || *opts->aux == '\0' + ? NULL : opts->aux); + + switch (i) { + case FQ_I1: + kputs("--i1 I1.fastq ", &read_str); + kputs("i*", &index_str); + break; + case FQ_I2: + kputs("--i2 I2.fastq ", &read_str); + kputs("i*", &index_str); + break; + + case FQ_R0: + kputs("-0 unpaired.fastq ", &read_str); + break; + + case FQ_R1: + kputs("-1 R1.fastq ", &read_str); + break; + + case FQ_R2: + kputs("-2 R2.fastq ", &read_str); + break; + + case FQ_SINGLE: + kputs("-N -o paired.fastq ", &read_str); + break; + + default: + ks_clear(&read_str); // not reversible + kputs("", &read_str); + } + } + if (n == 0) { + bam_destroy1(b); + return usage(samtools_stdout, EXIT_SUCCESS); + } + + char out_mode[10] = {'w', 0, 0}; + if (opts->compress_level != -1) + out_mode[1] = '0' + opts->compress_level; + sam_open_mode(out_mode+strlen(out_mode), opts->fn_out, NULL); + fp_out = sam_open_format(opts->fn_out, out_mode, &opts->ga.out); + if (!fp_out) { + perror(opts->fn_out); + goto err; + } + autoflush_if_stdout(fp_out, opts->fn_out); + if (opts->p.pool) + hts_set_thread_pool(fp_out, &opts->p); + + // Create header + if (ks_len(&read_str)) { + char CO[2100]; + if (ks_len(&index_str)) + snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s " + "--index-format=\"%s\"\n", + ks_str(&read_str), ks_str(&index_str)); + else + snprintf(CO, sizeof(CO), "@CO\tReverse with: samtools fastq %s\n", + ks_str(&read_str)); + + hdr_out = sam_hdr_parse(strlen(CO), CO); + } else { + hdr_out = sam_hdr_init(); + } + + // Add a version line with the sort order to the output header + if (sam_hdr_add_line(hdr_out, "HD", "VN", SAM_FORMAT_VERSION, "SO", "unsorted", "GO", "query", NULL) < 0) { + fprintf(samtools_stderr, "Could not set SO and GO in the header.\n"); + goto err; + } + + // Read group + if (opts->rg_line) { + if (*opts->rg_line != '@') + ksprintf(&rg_line, "@RG\t%s", opts->rg_line); + else + kputs(opts->rg_line, &rg_line); + } else if (opts->rg) { + ksprintf(&rg_line, "@RG\tID:%s", opts->rg); + } + + if (ks_len(&rg_line)) { + if (sam_hdr_add_lines(hdr_out, ks_str(&rg_line), 0) < 0) + goto err; + rg = strstr(ks_str(&rg_line), "\tID:"); + if (!rg) { + fprintf(samtools_stderr, "\"-r RG-LINE\" option contained no ID field\n"); + goto err; + } + rg += 4; + + i = 0; + while (rg[i] != '\t' && rg[i] != '\0') + i++; + rg[i] = 0; + } + + if ((ret = sam_hdr_write(fp_out, hdr_out)) < 0) + goto err; + + + // Interleave / combine from n files (ids[0..n-1]). + int res; + int eof = 0; + do { + idx_seq.l = idx_qual.l = 0; + for (i = 0; i < n; i++) { + if ((res = sam_read1(fp_in[ids[i]], NULL, b)) < 0) { + if (res == -1) { + eof++; + continue; + } else + break; + } + + // index + if (ids[i] == FQ_I1 || ids[i] == FQ_I2) { + if (append_index(&idx_seq, &idx_qual, b) < 0) { + res = -1; + break; + } + continue; + } + + // full read + if (idx_seq.l) { + if (opts->idx_both || ids[i] == FQ_SINGLE || + ids[i] == FQ_R0 || ids[i] == FQ_R1) { + if (bam_aux_append(b, opts->barcode_seq, 'Z', idx_seq.l, + (uint8_t *)idx_seq.s) || + bam_aux_append(b, opts->barcode_qual, 'Z', idx_qual.l, + (uint8_t *)idx_qual.s)) { + res = -1; + break; + } + } + } + + switch(ids[i]) { + case FQ_R0: + // unpaired; no flags to declare + break; + case FQ_SINGLE: + // paired (but don't know if R1 or R2) or unpaired. + // We rely on the /1 and /2 read suffix parsing in htslib + // to distinguish the two cases, or CASAVA tags if + // explicitly enabled. + break; + case FQ_R1: + if ((b->core.flag & (BAM_FREAD1 | BAM_FREAD2)) == 0) + b->core.flag |= BAM_FREAD1; + b->core.flag |= BAM_FPAIRED; + if (i+1 < n && ids[i+1] == FQ_R2) + b->core.flag |= BAM_FMUNMAP; + break; + case FQ_R2: + b->core.flag |= BAM_FPAIRED | BAM_FREAD2; + if (i > 0 && ids[i-1] == FQ_R1) + b->core.flag |= BAM_FMUNMAP; + break; + } + + if (rg) { + if (bam_aux_append(b, "RG", 'Z', strlen(rg)+1, + (uint8_t *)rg) < 0) { + ret = -1; + goto err; + } + } + + if (opts->order) { + if (opts->order_str) { + char buf[25]; + snprintf(buf, sizeof(buf), "%0*"PRIu64, + opts->order_str, read_num++); + if (bam_aux_update_str(b, opts->order, + strlen(buf), buf) < 0) { + ret = -1; + goto err; + } + } else { + if (bam_aux_update_int(b, opts->order, read_num++) < 0) { + ret = -1; + goto err; + } + if (read_num == UINT_MAX) + fprintf(samtools_stderr, "Warning: --order tag has overflowed." + " Consider using TAG:LENGTH instead\n"); + } + } + + res = sam_write1(fp_out, hdr_out, b); + } + } while (res >= 0); + + if (res != -1) { + print_error("import", "truncated file. Aborting"); + ret = res; + goto err; + } + + if (eof != n) { + print_error("import", "input files with differing number of records"); + ret = -1; + goto err; + } + + // Close and return + ret = 0; +err: + bam_destroy1(b); + sam_hdr_destroy(hdr_out); + ks_free(&rg_line); + ks_free(&index_str); + ks_free(&read_str); + if (fp_out) { + release_autoflush(fp_out); + if (sam_close(fp_out) < 0) { + perror(opts->fn_out); + ret |= -1; + } + } + for (i = 0; i < FQ_END; i++) { + if (fp_in[i] && sam_close(fp_in[i]) < 0) { + perror(opts->fn[i]); + ret |= -1; + } + } + ks_free(&idx_seq); + ks_free(&idx_qual); + + return ret; +} + +int main_import(int argc, char *argv[]) { + int c; + opts_t opts = { + .no_pg = 0, + .ga = SAM_GLOBAL_ARGS_INIT, + .fn = {NULL}, + .fn_out = "-", + .casava = 0, + .barcode_seq = "BC", + .barcode_qual = "QT", + .aux = NULL, + .rg = NULL, + .rg_line = NULL, + .order = NULL, + .order_str = 0, + .compress_level = -1, + .name2 = 0, + }; + kstring_t rg = {0}; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, '-', '@'), + {"no-PG", no_argument, NULL, 9}, + {"i1", required_argument, NULL, 1}, + {"i2", required_argument, NULL, 2}, + {"r1", required_argument, NULL, '1'}, + {"r2", required_argument, NULL, '2'}, + {"rg", required_argument, NULL, 'R'}, + {"rg-line", required_argument, NULL, 'r'}, + {"order", required_argument, NULL, 3}, + {"barcode-tag", required_argument, NULL, 4}, + {"quality-tag", required_argument, NULL, 5}, + {"name2", no_argument, NULL, 'N'}, + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "1:2:s:0:bhiT:r:R:o:O:u@:N", lopts, NULL)) >= 0) { + switch (c) { + case 'b': opts.idx_both = 1; break; + case '0': opts.fn[FQ_R0] = optarg; break; + case '1': opts.fn[FQ_R1] = optarg; break; + case '2': opts.fn[FQ_R2] = optarg; break; + case 1: opts.fn[FQ_I1] = optarg; break; + case 2: opts.fn[FQ_I2] = optarg; break; + case 's': opts.fn[FQ_SINGLE] = optarg; break; + case 'o': opts.fn_out = optarg; break; + case 'i': opts.casava = 1; break; + case 4: opts.barcode_seq = optarg; break; + case 5: opts.barcode_qual = optarg; break; + case 'T': opts.aux = optarg; break; + case 'u': opts.compress_level = 0; break; + case 'R': opts.rg = optarg; break; + case 'r': + if (*optarg != '@' && ks_len(&rg) == 0) + kputs("@RG", &rg); + if (ks_len(&rg)) + kputc_('\t', &rg); + kputs(optarg, &rg); + opts.rg_line = rg.s; + break; + + case 'N': opts.name2 = 1; break; + + case 9: opts.no_pg = 1; break; + case 3: + opts.order = optarg; + if (strlen(optarg) > 3 && optarg[2] == ':') + opts.order_str = atoi(optarg+3); + break; + + case 'h': return usage(samtools_stdout, EXIT_SUCCESS); + case '?': return usage(samtools_stderr, EXIT_FAILURE); + + default: + if (parse_sam_global_opt(c, optarg, lopts, &opts.ga) != 0) + return usage(samtools_stderr, EXIT_FAILURE); + break; + } + } + + if (opts.ga.nthreads > 0) { + if (!(opts.p.pool = hts_tpool_init(opts.ga.nthreads))) { + fprintf(samtools_stderr, "Failed to create thread pool\n"); + if (rg.s) + free(rg.s); + return -1;; + } + } + + int ret = import_fastq(argc-optind, argv+optind, &opts) ? 1 : 0; + + if (rg.s) + free(rg.s); + + if (opts.p.pool) + hts_tpool_destroy(opts.p.pool); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c new file mode 100644 index 0000000000000000000000000000000000000000..0803f3e4244c3bc1247282b0ebe184cff8486621 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c @@ -0,0 +1,289 @@ +/* bam_index.c -- index and idxstats subcommands. + + Copyright (C) 2008-2011, 2013-2016, 2018, 2019, 2023 Genome Research Ltd. + Portions copyright (C) 2010 Broad Institute. + Portions copyright (C) 2013 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "samtools.h" +#include "sam_opts.h" + +#define BAM_LIDX_SHIFT 14 + +static void index_usage(FILE *fp) +{ + fprintf(fp, +"Usage: samtools index -M [-bc] [-m INT] ...\n" +" or: samtools index [-bc] [-m INT] [out.index]\n" +"Options:\n" +" -b, --bai Generate BAI-format index for BAM files [default]\n" +" -c, --csi Generate CSI-format index for BAM files\n" +" -m, --min-shift INT Set minimum interval size for CSI indices to 2^INT [%d]\n" +" -M Interpret all filename arguments as files to be indexed\n" +" -o, --output FILE Write index to FILE [alternative to in args]\n" +" -@, --threads INT Sets the number of threads [none]\n", BAM_LIDX_SHIFT); +} + +// Returns 1 if the file does not exist or can be positively +// identified as an index file. +static int nonexistent_or_index(const char *fn) +{ + int ret1, ret2; + htsFormat fmt; + hFILE *fp = hopen(fn, "r"); + if (fp == NULL) return 1; + + ret1 = hts_detect_format2(fp, fn, &fmt); + ret2 = hclose(fp); + if (ret1 < 0 || ret2 < 0) return 0; + + return fmt.category == index_file; +} + +int bam_index(int argc, char *argv[]) +{ + int csi = 0; + int min_shift = BAM_LIDX_SHIFT; + int multiple = 0; + int n_threads = 0; + int n_files, c, i, ret; + const char *fn_idx = NULL; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'), + {"output", required_argument, NULL, 'o'}, + {"bai", no_argument, NULL, 'b'}, + {"csi", no_argument, NULL, 'c'}, + {"min-shift", required_argument, NULL, 'm'}, + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "bcm:Mo:@:", lopts, NULL)) >= 0) + switch (c) { + case 'b': csi = 0; break; + case 'c': csi = 1; break; + case 'm': csi = 1; min_shift = atoi(optarg); break; + case 'M': multiple = 1; break; + case 'o': fn_idx = optarg; break; + case '@': n_threads = atoi(optarg); break; + default: + index_usage(stderr); + return 1; + } + + n_files = argc - optind; + + if (n_files == 0) { + index_usage(stdout); + return 0; + } + + // Handle legacy synopsis + if (n_files == 2 && !fn_idx && nonexistent_or_index(argv[optind+1])) { + n_files = 1; + fn_idx = argv[optind+1]; + } + + if (n_files > 1 && !multiple) { + print_error("index", "use -M to enable indexing more than one alignment file"); + return EXIT_FAILURE; + } + + if (fn_idx && n_files > 1) { + // TODO In future we may allow %* placeholders or similar + print_error("index", "can't use -o with multiple input alignment files"); + return EXIT_FAILURE; + } + + for (i = optind; i < optind + n_files; i++) { + ret = sam_index_build3(argv[i], fn_idx, csi? min_shift : 0, n_threads); + if (ret < 0) { + if (ret == -2) + print_error_errno("index", "failed to open \"%s\"", argv[i]); + else if (ret == -3) + print_error("index", "\"%s\" is in a format that cannot be usefully indexed", argv[i]); + else if (ret == -4 && fn_idx) + print_error("index", "failed to create or write index \"%s\"", fn_idx); + else if (ret == -4) + print_error("index", "failed to create or write index"); + else + print_error_errno("index", "failed to create index for \"%s\"", argv[i]); + return EXIT_FAILURE; + } + } + + return EXIT_SUCCESS; +} + +/* + * Cram indices do not contain mapped/unmapped record counts, so we have to + * decode each record and count. However we can speed this up as much as + * possible by using the required fields parameter. + * + * This prints the stats to stdout in the same manner than the BAM function + * does. + * + * Returns 0 on success, + * -1 on failure. + */ +int slow_idxstats(samFile *fp, sam_hdr_t *header) { + int ret, last_tid = -2; + bam1_t *b = bam_init1(); + + if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, SAM_RNAME | SAM_FLAG)) + return -1; + + uint64_t (*count0)[2] = calloc(sam_hdr_nref(header)+1, sizeof(*count0)); + uint64_t (*counts)[2] = count0+1; + if (!count0) + return -1; + + while ((ret = sam_read1(fp, header, b)) >= 0) { + if (b->core.tid >= sam_hdr_nref(header) || b->core.tid < -1) { + free(count0); + return -1; + } + + if (b->core.tid != last_tid) { + if (last_tid >= -1) { + if (counts[b->core.tid][0] + counts[b->core.tid][1]) { + print_error("idxstats", "file is not position sorted"); + free(count0); + return -1; + } + } + last_tid = b->core.tid; + } + + counts[b->core.tid][(b->core.flag & BAM_FUNMAP) ? 1 : 0]++; + } + + if (ret == -1) { + int i; + for (i = 0; i < sam_hdr_nref(header); i++) { + printf("%s\t%"PRId64"\t%"PRIu64"\t%"PRIu64"\n", + sam_hdr_tid2name(header, i), + (int64_t) sam_hdr_tid2len(header, i), + counts[i][0], counts[i][1]); + } + printf("*\t0\t%"PRIu64"\t%"PRIu64"\n", counts[-1][0], counts[-1][1]); + } + + free(count0); + + bam_destroy1(b); + + return (ret == -1) ? 0 : -1; +} + +static void usage_exit(FILE *fp, int exit_status) +{ + fprintf(fp, "Usage: samtools idxstats [options] \n"); + sam_global_opt_help(fp, "-.---@-."); + exit(exit_status); +} + +int bam_idxstats(int argc, char *argv[]) +{ + hts_idx_t* idx; + sam_hdr_t* header; + samFile* fp; + int c; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '@'), + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "@:", lopts, NULL)) >= 0) { + switch (c) { + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + usage_exit(stderr, EXIT_FAILURE); + } + } + + if (argc != optind+1) { + if (argc == optind) usage_exit(stdout, EXIT_SUCCESS); + else usage_exit(stderr, EXIT_FAILURE); + } + + fp = sam_open_format(argv[optind], "r", &ga.in); + if (fp == NULL) { + print_error_errno("idxstats", "failed to open \"%s\"", argv[optind]); + return 1; + } + header = sam_hdr_read(fp); + if (header == NULL) { + print_error("idxstats", "failed to read header for \"%s\"", argv[optind]); + return 1; + } + + if (hts_get_format(fp)->format != bam) { + slow_method: + if (ga.nthreads) + hts_set_threads(fp, ga.nthreads); + + if (slow_idxstats(fp, header) < 0) { + print_error("idxstats", "failed to process \"%s\"", argv[optind]); + return 1; + } + } else { + idx = sam_index_load(fp, argv[optind]); + if (idx == NULL) { + print_error("idxstats", "fail to load index for \"%s\", " + "reverting to slow method", argv[optind]); + goto slow_method; + } + + int i; + for (i = 0; i < sam_hdr_nref(header); ++i) { + // Print out contig name and length + printf("%s\t%"PRId64, sam_hdr_tid2name(header, i), (int64_t) sam_hdr_tid2len(header, i)); + // Now fetch info about it from the meta bin + uint64_t u, v; + hts_idx_get_stat(idx, i, &u, &v); + printf("\t%" PRIu64 "\t%" PRIu64 "\n", u, v); + } + // Dump information about unmapped reads + printf("*\t0\t0\t%" PRIu64 "\n", hts_idx_get_n_no_coor(idx)); + hts_idx_destroy(idx); + } + + sam_hdr_destroy(header); + sam_close(fp); + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..3093c01382ff1e509b50281dc5007a78c3ad7a39 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_index.c.pysam.c @@ -0,0 +1,291 @@ +#include "samtools.pysam.h" + +/* bam_index.c -- index and idxstats subcommands. + + Copyright (C) 2008-2011, 2013-2016, 2018, 2019, 2023 Genome Research Ltd. + Portions copyright (C) 2010 Broad Institute. + Portions copyright (C) 2013 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "samtools.h" +#include "sam_opts.h" + +#define BAM_LIDX_SHIFT 14 + +static void index_usage(FILE *fp) +{ + fprintf(fp, +"Usage: samtools index -M [-bc] [-m INT] ...\n" +" or: samtools index [-bc] [-m INT] [out.index]\n" +"Options:\n" +" -b, --bai Generate BAI-format index for BAM files [default]\n" +" -c, --csi Generate CSI-format index for BAM files\n" +" -m, --min-shift INT Set minimum interval size for CSI indices to 2^INT [%d]\n" +" -M Interpret all filename arguments as files to be indexed\n" +" -o, --output FILE Write index to FILE [alternative to in args]\n" +" -@, --threads INT Sets the number of threads [none]\n", BAM_LIDX_SHIFT); +} + +// Returns 1 if the file does not exist or can be positively +// identified as an index file. +static int nonexistent_or_index(const char *fn) +{ + int ret1, ret2; + htsFormat fmt; + hFILE *fp = hopen(fn, "r"); + if (fp == NULL) return 1; + + ret1 = hts_detect_format2(fp, fn, &fmt); + ret2 = hclose(fp); + if (ret1 < 0 || ret2 < 0) return 0; + + return fmt.category == index_file; +} + +int bam_index(int argc, char *argv[]) +{ + int csi = 0; + int min_shift = BAM_LIDX_SHIFT; + int multiple = 0; + int n_threads = 0; + int n_files, c, i, ret; + const char *fn_idx = NULL; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', '-', '-', '@'), + {"output", required_argument, NULL, 'o'}, + {"bai", no_argument, NULL, 'b'}, + {"csi", no_argument, NULL, 'c'}, + {"min-shift", required_argument, NULL, 'm'}, + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "bcm:Mo:@:", lopts, NULL)) >= 0) + switch (c) { + case 'b': csi = 0; break; + case 'c': csi = 1; break; + case 'm': csi = 1; min_shift = atoi(optarg); break; + case 'M': multiple = 1; break; + case 'o': fn_idx = optarg; break; + case '@': n_threads = atoi(optarg); break; + default: + index_usage(samtools_stderr); + return 1; + } + + n_files = argc - optind; + + if (n_files == 0) { + index_usage(samtools_stdout); + return 0; + } + + // Handle legacy synopsis + if (n_files == 2 && !fn_idx && nonexistent_or_index(argv[optind+1])) { + n_files = 1; + fn_idx = argv[optind+1]; + } + + if (n_files > 1 && !multiple) { + print_error("index", "use -M to enable indexing more than one alignment file"); + return EXIT_FAILURE; + } + + if (fn_idx && n_files > 1) { + // TODO In future we may allow %* placeholders or similar + print_error("index", "can't use -o with multiple input alignment files"); + return EXIT_FAILURE; + } + + for (i = optind; i < optind + n_files; i++) { + ret = sam_index_build3(argv[i], fn_idx, csi? min_shift : 0, n_threads); + if (ret < 0) { + if (ret == -2) + print_error_errno("index", "failed to open \"%s\"", argv[i]); + else if (ret == -3) + print_error("index", "\"%s\" is in a format that cannot be usefully indexed", argv[i]); + else if (ret == -4 && fn_idx) + print_error("index", "failed to create or write index \"%s\"", fn_idx); + else if (ret == -4) + print_error("index", "failed to create or write index"); + else + print_error_errno("index", "failed to create index for \"%s\"", argv[i]); + return EXIT_FAILURE; + } + } + + return EXIT_SUCCESS; +} + +/* + * Cram indices do not contain mapped/unmapped record counts, so we have to + * decode each record and count. However we can speed this up as much as + * possible by using the required fields parameter. + * + * This prints the stats to samtools_stdout in the same manner than the BAM function + * does. + * + * Returns 0 on success, + * -1 on failure. + */ +int slow_idxstats(samFile *fp, sam_hdr_t *header) { + int ret, last_tid = -2; + bam1_t *b = bam_init1(); + + if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, SAM_RNAME | SAM_FLAG)) + return -1; + + uint64_t (*count0)[2] = calloc(sam_hdr_nref(header)+1, sizeof(*count0)); + uint64_t (*counts)[2] = count0+1; + if (!count0) + return -1; + + while ((ret = sam_read1(fp, header, b)) >= 0) { + if (b->core.tid >= sam_hdr_nref(header) || b->core.tid < -1) { + free(count0); + return -1; + } + + if (b->core.tid != last_tid) { + if (last_tid >= -1) { + if (counts[b->core.tid][0] + counts[b->core.tid][1]) { + print_error("idxstats", "file is not position sorted"); + free(count0); + return -1; + } + } + last_tid = b->core.tid; + } + + counts[b->core.tid][(b->core.flag & BAM_FUNMAP) ? 1 : 0]++; + } + + if (ret == -1) { + int i; + for (i = 0; i < sam_hdr_nref(header); i++) { + fprintf(samtools_stdout, "%s\t%"PRId64"\t%"PRIu64"\t%"PRIu64"\n", + sam_hdr_tid2name(header, i), + (int64_t) sam_hdr_tid2len(header, i), + counts[i][0], counts[i][1]); + } + fprintf(samtools_stdout, "*\t0\t%"PRIu64"\t%"PRIu64"\n", counts[-1][0], counts[-1][1]); + } + + free(count0); + + bam_destroy1(b); + + return (ret == -1) ? 0 : -1; +} + +static void usage_exit(FILE *fp, int exit_status) +{ + fprintf(fp, "Usage: samtools idxstats [options] \n"); + sam_global_opt_help(fp, "-.---@-."); + samtools_exit(exit_status); +} + +int bam_idxstats(int argc, char *argv[]) +{ + hts_idx_t* idx; + sam_hdr_t* header; + samFile* fp; + int c; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '@'), + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "@:", lopts, NULL)) >= 0) { + switch (c) { + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + usage_exit(samtools_stderr, EXIT_FAILURE); + } + } + + if (argc != optind+1) { + if (argc == optind) usage_exit(samtools_stdout, EXIT_SUCCESS); + else usage_exit(samtools_stderr, EXIT_FAILURE); + } + + fp = sam_open_format(argv[optind], "r", &ga.in); + if (fp == NULL) { + print_error_errno("idxstats", "failed to open \"%s\"", argv[optind]); + return 1; + } + header = sam_hdr_read(fp); + if (header == NULL) { + print_error("idxstats", "failed to read header for \"%s\"", argv[optind]); + return 1; + } + + if (hts_get_format(fp)->format != bam) { + slow_method: + if (ga.nthreads) + hts_set_threads(fp, ga.nthreads); + + if (slow_idxstats(fp, header) < 0) { + print_error("idxstats", "failed to process \"%s\"", argv[optind]); + return 1; + } + } else { + idx = sam_index_load(fp, argv[optind]); + if (idx == NULL) { + print_error("idxstats", "fail to load index for \"%s\", " + "reverting to slow method", argv[optind]); + goto slow_method; + } + + int i; + for (i = 0; i < sam_hdr_nref(header); ++i) { + // Print out contig name and length + fprintf(samtools_stdout, "%s\t%"PRId64, sam_hdr_tid2name(header, i), (int64_t) sam_hdr_tid2len(header, i)); + // Now fetch info about it from the meta bin + uint64_t u, v; + hts_idx_get_stat(idx, i, &u, &v); + fprintf(samtools_stdout, "\t%" PRIu64 "\t%" PRIu64 "\n", u, v); + } + // Dump information about unmapped reads + fprintf(samtools_stdout, "*\t0\t0\t%" PRIu64 "\n", hts_idx_get_n_no_coor(idx)); + hts_idx_destroy(idx); + } + + sam_hdr_destroy(header); + sam_close(fp); + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.c new file mode 100644 index 0000000000000000000000000000000000000000..58c428fc26703b83d73f675095ae7e0efb9bbb59 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.c @@ -0,0 +1,225 @@ +/* bam_lpileup.c -- lplbuf routines. + + Copyright (C) 2008, 2009, 2013 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "bam_plbuf.h" +#include "bam_lpileup.h" +#include "splaysort.h" + +#define TV_GAP 2 + +typedef struct __freenode_t { + uint32_t level:28, cnt:4; + struct __freenode_t *next; +} freenode_t, *freenode_p; + +#define freenode_lt(a,b) ((a)->cnt < (b)->cnt || ((a)->cnt == (b)->cnt && (a)->level < (b)->level)) +SPLAYSORT_INIT(node, freenode_p, freenode_lt) + +/* Memory pool, similar to the one in bam_pileup.c */ +typedef struct { + int cnt, n, max; + freenode_t **buf; +} mempool_t; + +static mempool_t *mp_init(void) +{ + return (mempool_t*)calloc(1, sizeof(mempool_t)); +} +static void mp_destroy(mempool_t *mp) +{ + int k; + for (k = 0; k < mp->n; ++k) free(mp->buf[k]); + free(mp->buf); free(mp); +} +static inline freenode_t *mp_alloc(mempool_t *mp) +{ + ++mp->cnt; + if (mp->n == 0) return (freenode_t*)calloc(1, sizeof(freenode_t)); + else return mp->buf[--mp->n]; +} +static inline void mp_free(mempool_t *mp, freenode_t *p) +{ + --mp->cnt; p->next = 0; p->cnt = TV_GAP; + if (mp->n == mp->max) { + mp->max = mp->max? mp->max<<1 : 256; + mp->buf = (freenode_t**)realloc(mp->buf, sizeof(freenode_t*) * mp->max); + } + mp->buf[mp->n++] = p; +} + +/* core part */ +struct __bam_lplbuf_t { + int max, n_cur, n_pre; + int max_level, *cur_level, *pre_level; + mempool_t *mp; + freenode_t **aux, *head, *tail; + int n_nodes, m_aux; + bam_pileup_f func; + void *user_data; + bam_plbuf_t *plbuf; +}; + +void bam_lplbuf_reset(bam_lplbuf_t *buf) +{ + freenode_t *p, *q; + bam_plbuf_reset(buf->plbuf); + for (p = buf->head; p->next;) { + q = p->next; + mp_free(buf->mp, p); + p = q; + } + buf->head = buf->tail; + buf->max_level = 0; + buf->n_cur = buf->n_pre = 0; + buf->n_nodes = 0; +} + +static int tview_func(uint32_t tid, hts_pos_t pos, int n, const bam_pileup1_t *pl, void *data) +{ + bam_lplbuf_t *tv = (bam_lplbuf_t*)data; + freenode_t *p; + int i, l, max_level; + // allocate memory if necessary + if (tv->max < n) { // enlarge + tv->max = n; + kroundup32(tv->max); + tv->cur_level = (int*)realloc(tv->cur_level, sizeof(int) * tv->max); + tv->pre_level = (int*)realloc(tv->pre_level, sizeof(int) * tv->max); + } + tv->n_cur = n; + // update cnt + for (p = tv->head; p->next; p = p->next) + if (p->cnt > 0) --p->cnt; + // calculate cur_level[] + max_level = 0; + for (i = l = 0; i < n; ++i) { + const bam_pileup1_t *p = pl + i; + if (p->is_head) { + if (tv->head->next && tv->head->cnt == 0) { // then take a free slot + freenode_t *p = tv->head->next; + tv->cur_level[i] = tv->head->level; + mp_free(tv->mp, tv->head); + tv->head = p; + --tv->n_nodes; + } else tv->cur_level[i] = ++tv->max_level; + } else { + tv->cur_level[i] = tv->pre_level[l++]; + if (p->is_tail) { // then return a free slot + tv->tail->level = tv->cur_level[i]; + tv->tail->next = mp_alloc(tv->mp); + tv->tail = tv->tail->next; + ++tv->n_nodes; + } + } + if (tv->cur_level[i] > max_level) max_level = tv->cur_level[i]; + ((bam_pileup1_t*)p)->level = tv->cur_level[i]; + } + assert(l == tv->n_pre); + tv->func(tid, pos, n, pl, tv->user_data); + // sort the linked list + if (tv->n_nodes) { + freenode_t *q; + if (tv->n_nodes + 1 > tv->m_aux) { // enlarge + tv->m_aux = tv->n_nodes + 1; + kroundup32(tv->m_aux); + tv->aux = (freenode_t**)realloc(tv->aux, sizeof(freenode_t*) * tv->m_aux); + } + for (p = tv->head, i = l = 0; p->next;) { + if (p->level > max_level) { // then discard this entry + q = p->next; + mp_free(tv->mp, p); + p = q; + } else { + tv->aux[i++] = p; + p = p->next; + } + } + tv->aux[i] = tv->tail; // add a proper tail for the loop below + tv->n_nodes = i; + if (tv->n_nodes) { + splaysort(node, tv->n_nodes, tv->aux); + for (i = 0; i < tv->n_nodes; ++i) tv->aux[i]->next = tv->aux[i+1]; + tv->head = tv->aux[0]; + } else tv->head = tv->tail; + } + // clean up + tv->max_level = max_level; + memcpy(tv->pre_level, tv->cur_level, tv->n_cur * 4); + // squeeze out terminated levels + for (i = l = 0; i < n; ++i) { + const bam_pileup1_t *p = pl + i; + if (!p->is_tail) + tv->pre_level[l++] = tv->pre_level[i]; + } + tv->n_pre = l; +/* + fprintf(stderr, "%d\t", pos+1); + for (i = 0; i < n; ++i) { + const bam_pileup1_t *p = pl + i; + if (p->is_head) fprintf(stderr, "^"); + if (p->is_tail) fprintf(stderr, "$"); + fprintf(stderr, "%d,", p->level); + } + fprintf(stderr, "\n"); +*/ + return 0; +} + +bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data) +{ + bam_lplbuf_t *tv; + tv = (bam_lplbuf_t*)calloc(1, sizeof(bam_lplbuf_t)); + tv->mp = mp_init(); + tv->head = tv->tail = mp_alloc(tv->mp); + tv->func = func; + tv->user_data = data; + tv->plbuf = bam_plbuf_init(tview_func, tv); + return (bam_lplbuf_t*)tv; +} + +void bam_lplbuf_destroy(bam_lplbuf_t *tv) +{ + freenode_t *p, *q; + free(tv->cur_level); free(tv->pre_level); + bam_plbuf_destroy(tv->plbuf); + free(tv->aux); + for (p = tv->head; p->next;) { + q = p->next; + mp_free(tv->mp, p); p = q; + } + mp_free(tv->mp, p); + assert(tv->mp->cnt == 0); + mp_destroy(tv->mp); + free(tv); +} + +int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *tv) +{ + return bam_plbuf_push(b, tv->plbuf); +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.h new file mode 100644 index 0000000000000000000000000000000000000000..97c7324559a212ba601e5931d6fe9bd1b86b4602 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_lpileup.h @@ -0,0 +1,57 @@ +/* bam_lpileup.h -- lplbuf routines (declarations copied from bam.h). + + Copyright (C) 2008, 2013 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef BAM_LPILEUP_H +#define BAM_LPILEUP_H + + +#include + +struct __bam_lplbuf_t; +typedef struct __bam_lplbuf_t bam_lplbuf_t; + +#ifndef BAM_PILEUP_F_DEFINED +#define BAM_PILEUP_F_DEFINED +typedef int (*bam_pileup_f)(uint32_t tid, hts_pos_t pos, int n, const bam_pileup1_t *pl, void *data); +#endif //BAM_PILEUP_F_DEFINED + + +#ifdef __cplusplus +extern "C" { +#endif + void bam_lplbuf_reset(bam_lplbuf_t *buf); + + /*! @abstract bam_plbuf_init() equivalent with level calculated. */ + bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data); + + /*! @abstract bam_plbuf_destroy() equivalent with level calculated. */ + void bam_lplbuf_destroy(bam_lplbuf_t *tv); + + /*! @abstract bam_plbuf_push() equivalent with level calculated. */ + int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *buf); +#ifdef __cplusplus +} +#endif + +#endif // BAM_LPILEUP_H diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_markdup.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_markdup.c new file mode 100644 index 0000000000000000000000000000000000000000..677a47f8283c19957f6dfc7da041f542af3fec55 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_markdup.c @@ -0,0 +1,2510 @@ +/* bam_markdup.c -- Mark duplicates from a coord sorted file that has gone + through fixmates with the mate scoring option on. + + Copyright (C) 2017-2023 Genome Research Ltd. + + Author: Andrew Whitwham + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE + +Estimate library size derived from Picard DuplicationMetrics.java +Copyright (c) 2009,2018 The Broad Institute. MIT license. +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "htslib/sam.h" +#include "sam_opts.h" +#include "samtools.h" +#include "htslib/khash.h" +#include "htslib/klist.h" +#include "htslib/kstring.h" +#include "tmp_file.h" +#include "bam.h" + + +typedef struct { + samFile *in; + samFile *out; + char *prefix; + int remove_dups; + int32_t max_length; + int do_stats; + int supp; + int tag; + int opt_dist; + int no_pg; + int clear; + int mode; + int write_index; + int include_fails; + int check_chain; + char *stats_file; + char *arg_list; + char *out_fn; + regex_t *rgx; + int rgx_x; + int rgx_y; + int rgx_t; + char *barcode; + regex_t *bc_rgx; + int read_groups; + int json; + int dc; +} md_param_t; + +typedef struct { + hts_pos_t this_coord; + hts_pos_t other_coord; + int32_t this_ref; + int32_t other_ref; + int32_t barcode; + int32_t read_group; + int8_t single; + int8_t leftmost; + int8_t orientation; +} key_data_t; + +typedef struct read_queue_s { + key_data_t pair_key; + key_data_t single_key; + bam1_t *b; + struct read_queue_s *duplicate; + struct read_queue_s *original; + int dc; + hts_pos_t pos; + int dup_checked; + int read_group; +} read_queue_t; + +typedef struct { + read_queue_t *p; +} in_hash_t; + +typedef struct { + char *name; + char type; + int read_group; +} dup_map_t; + +typedef struct { + bam1_t *b; + int64_t score; + int64_t mate_score; + long x; + long y; + int opt; + int beg; + int end; +} check_t; + +typedef struct { + check_t *c; + size_t size; + size_t length; +} check_list_t; + +typedef struct { + long reading; + long writing; + long excluded; + long duplicate; + long single; + long pair; + long single_dup; + long examined; + long optical; + long single_optical; + long np_duplicate; + long np_opt_duplicate; +} stats_block_t; + +static khint32_t do_hash(unsigned char *key, khint32_t len); + +static khint_t hash_key(key_data_t key) { + int i = 0; + khint_t hash; + + if (key.single) { + unsigned char sig[21]; + + memcpy(sig + i, &key.this_ref, 4); i += 4; + memcpy(sig + i, &key.this_coord, 8); i += 8; + memcpy(sig + i, &key.orientation, 1); i += 1; + memcpy(sig + i, &key.barcode, 4); i += 4; + memcpy(sig + i, &key.read_group, 4); i += 4; + + hash = do_hash(sig, i); + } else { + unsigned char sig[34]; + + memcpy(sig + i, &key.this_ref, 4); i += 4; + memcpy(sig + i, &key.this_coord, 8); i += 8; + memcpy(sig + i, &key.other_ref, 4); i += 4; + memcpy(sig + i, &key.other_coord, 8); i += 8; + memcpy(sig + i, &key.leftmost, 1); i += 1; + memcpy(sig + i, &key.orientation, 1); i += 1; + memcpy(sig + i, &key.barcode, 4); i += 4; + memcpy(sig + i, &key.read_group, 4); i += 4; + + hash = do_hash(sig, i); + } + + return hash; +} + + +static int key_equal(key_data_t a, key_data_t b) { + int match = 1; + + if (a.this_coord != b.this_coord) + match = 0; + else if (a.orientation != b.orientation) + match = 0; + else if (a.this_ref != b.this_ref) + match = 0; + else if (a.single != b.single) + match = 0; + else if (a.barcode != b.barcode) + match = 0; + else if (a.read_group != b.read_group) + match = 0; + + if (!a.single) { + if (a.other_coord != b.other_coord) + match = 0; + else if (a.leftmost != b.leftmost) + match = 0; + else if (a.other_ref != b.other_ref) + match = 0; + } + + return match; +} + + +#define __free_queue_element(p) + +// Orientations (prime numbers to feed to hashing algorithm) +#define O_FF 2 +#define O_RR 3 +#define O_FR 5 +#define O_RF 7 + +// Left or rightmost +#define R_LE 11 +#define R_RI 13 + +#define BMD_WARNING_MAX 10 + +#define MD_MIN_QUALITY 15 + +// Duplicate finding mode +#define MD_MODE_TEMPLATE 0 +#define MD_MODE_SEQUENCE 1 + +KHASH_INIT(reads, key_data_t, in_hash_t, 1, hash_key, key_equal) // read map hash +KLIST_INIT(read_queue, read_queue_t, __free_queue_element) // the reads buffer +KHASH_MAP_INIT_STR(duplicates, dup_map_t) // map of duplicates for supplementary dup id +KHASH_MAP_INIT_STR(read_groups, int) // read group lookup + +/* The Bob Jenkins one_at_a_time hash to reduce the key to a 32 bit value. */ + +static khint32_t do_hash(unsigned char *key, khint32_t len) { + khint32_t hash, i; + + for (hash = 0, i = 0; i < len; ++i) { + hash += key[i]; + hash += (hash << 10); + hash ^= (hash >> 6); + } + + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + + return hash; +} + + +/* Get mate score from tag. */ + +static int64_t get_mate_score(bam1_t *b) { + uint8_t *data; + int64_t score; + + if ((data = bam_aux_get(b, "ms"))) { + score = bam_aux2i(data); + } else { + print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n"); + return -1; + } + + return score; +} + + +/* Calc current score from quality. */ + +static int64_t calc_score(bam1_t *b) +{ + int64_t score = 0; + uint8_t *qual = bam_get_qual(b); + int i; + + for (i = 0; i < b->core.l_qseq; i++) { + if (qual[i] >= MD_MIN_QUALITY) score += qual[i]; + } + + return score; +} + + +/* Create a signature hash of the current read and its pair. + Uses the unclipped start (or end depending on orientation), + the reference id, orientation and whether the current + read is leftmost of the pair. */ + + +static int make_pair_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) { + hts_pos_t this_coord, this_end, other_coord, other_end, leftmost; + int32_t this_ref, other_ref, barcode = 0; + int8_t orientation, left_read; + uint8_t *data; + char *cig, *bar; + long incoming_warnings = *warnings; + + this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash + other_ref = bam->core.mtid + 1; + + this_coord = unclipped_start(bam); + this_end = unclipped_end(bam); + + if ((data = bam_aux_get(bam, "MC"))) { + if (!(cig = bam_aux2Z(data))) { + print_error("markdup", "error, MC tag wrong type. Please use the MC tag provided by samtools fixmate.\n"); + return 1; + } + + other_end = unclipped_other_end(bam->core.mpos, cig); + other_coord = unclipped_other_start(bam->core.mpos, cig); + } else { + print_error("markdup", "error, no MC tag. Please run samtools fixmate on file first.\n"); + return 1; + } + + // work out orientations + if (param->mode == MD_MODE_TEMPLATE) { + + if (this_ref != other_ref) { + leftmost = this_ref < other_ref; + } else { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + if (!bam_is_rev(bam)) { + leftmost = this_coord <= other_coord; + } else { + leftmost = this_end <= other_end; + } + } else { + if (bam_is_rev(bam)) { + leftmost = this_end <= other_coord; + } else { + leftmost = this_coord <= other_end; + } + } + } + + // pair orientation + if (leftmost) { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + other_coord = other_end; + + if (!bam_is_rev(bam)) { + if (bam->core.flag & BAM_FREAD1) { + orientation = O_FF; + } else { + orientation = O_RR; + } + } else { + if (bam->core.flag & BAM_FREAD1) { + orientation = O_RR; + } else { + orientation = O_FF; + } + } + } else { + if (!bam_is_rev(bam)) { + orientation = O_FR; + other_coord = other_end; + } else { + orientation = O_RF; + this_coord = this_end; + } + } + } else { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + this_coord = this_end; + + if (!bam_is_rev(bam)) { + if (bam->core.flag & BAM_FREAD1) { + orientation = O_RR; + } else { + orientation = O_FF; + } + } else { + if (bam->core.flag & BAM_FREAD1) { + orientation = O_FF; + } else { + orientation = O_RR; + } + } + } else { + if (!bam_is_rev(bam)) { + orientation = O_RF; + other_coord = other_end; + } else { + orientation = O_FR; + this_coord = this_end; + } + } + } + } else { // MD_MODE_SEQUENCE + + if (this_ref != other_ref) { + leftmost = this_ref - other_ref; + } else { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + if (!bam_is_rev(bam)) { + leftmost = this_coord - other_coord; + } else { + leftmost = this_end - other_end; + } + } else { + if (bam_is_rev(bam)) { + leftmost = this_end - other_coord; + } else { + leftmost = this_coord - other_end; + } + } + } + + if (leftmost < 0) { + leftmost = 1; + } else if (leftmost > 0) { + leftmost = 0; + } else { + // tie breaks + + if (bam->core.pos == bam->core.mpos) { + if (bam->core.flag & BAM_FREAD1) { + leftmost = 1; + } else { + leftmost = 0; + } + } else if (bam->core.pos < bam->core.mpos) { + leftmost = 1; + } else { + leftmost = 0; + } + } + + // pair orientation + if (leftmost) { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + + if (!bam_is_rev(bam)) { + orientation = O_FF; + } else { + orientation = O_RR; + } + } else { + if (!bam_is_rev(bam)) { + orientation = O_FR; + } else { + orientation = O_RF; + } + } + } else { + if (bam_is_rev(bam) == bam_is_mrev(bam)) { + + if (!bam_is_rev(bam)) { + orientation = O_RR; + } else { + orientation = O_FF; + } + } else { + if (!bam_is_rev(bam)) { + orientation = O_RF; + } else { + orientation = O_FR; + } + } + } + + if (!bam_is_rev(bam)) { + this_coord = unclipped_start(bam); + } else { + this_coord = unclipped_end(bam); + } + + if (!bam_is_mrev(bam)) { + other_coord = unclipped_other_start(bam->core.mpos, cig); + } else { + other_coord = unclipped_other_end(bam->core.mpos, cig); + } + } + + if (!leftmost) + left_read = R_RI; + else + left_read = R_LE; + + if (param->barcode) { + if ((data = bam_aux_get(bam, param->barcode))) { + if (!(bar = bam_aux2Z(data))) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode); + } + } else { + barcode = do_hash((unsigned char *)bar, strlen(bar)); + } + } + } else if (param->bc_rgx) { + int result; + regmatch_t matches[3]; + size_t max_matches = 2; + char *qname = bam_get_qname(bam); + + if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) { + int bc_start, bc_end; + + bc_start = matches[1].rm_so; + bc_end = matches[1].rm_eo; + + if (bc_start != -1) { + barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start); + } else { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname); + } + } + } else { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + char warn_msg[256]; + + regerror(result, param->bc_rgx, warn_msg, 256); + print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname); + } + } + } + + if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) { + print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n", + *warnings); + } + + key->single = 0; + key->this_ref = this_ref; + key->this_coord = this_coord; + key->other_ref = other_ref; + key->other_coord = other_coord; + key->leftmost = left_read; + key->orientation = orientation; + key->barcode = barcode; + key->read_group = rg_num; + + return 0; +} + + +/* Create a signature hash of single read (or read with an unmatched pair). + Uses unclipped start (or end depending on orientation), reference id, + and orientation. */ + +static void make_single_key(md_param_t *param, key_data_t *key, bam1_t *bam, int rg_num, long *warnings) { + hts_pos_t this_coord; + int32_t this_ref, barcode = 0; + int8_t orientation; + uint8_t *data; + char *bar; + long incoming_warnings = *warnings; + + this_ref = bam->core.tid + 1; // avoid a 0 being put into the hash + + if (bam_is_rev(bam)) { + this_coord = unclipped_end(bam); + orientation = O_RR; + } else { + this_coord = unclipped_start(bam); + orientation = O_FF; + } + + if (param->barcode) { + if ((data = bam_aux_get(bam, param->barcode))) { + if (!(bar = bam_aux2Z(data))) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, %s tag wrong type. Aux tag needs to be a string type.\n", param->barcode); + } + } else { + barcode = do_hash((unsigned char *)bar, strlen(bar)); + } + } + } else if (param->bc_rgx) { + int result; + regmatch_t matches[3]; + size_t max_matches = 2; + char *qname = bam_get_qname(bam); + + if ((result = regexec(param->bc_rgx, qname, max_matches, matches, 0)) == 0) { + int bc_start, bc_end; + + bc_start = matches[1].rm_so; + bc_end = matches[1].rm_eo; + + if (bc_start != -1) { + barcode = do_hash((unsigned char *)qname + bc_start, bc_end - bc_start); + } else { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, barcode regex unable to match substring on %s.\n", qname); + } + } + } else { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + char warn_msg[256]; + + regerror(result, param->bc_rgx, warn_msg, 256); + print_error("markdup", "warning, barcode regex match error \"%s\" on %s.\n", warn_msg, qname); + } + } + } + + if ((*warnings == BMD_WARNING_MAX) && (incoming_warnings != *warnings)) { + print_error("markdup", "warning, %ld barcode read warnings. New warnings will not be reported.\n", + *warnings); + } + + + key->single = 1; + key->this_ref = this_ref; + key->this_coord = this_coord; + key->orientation = orientation; + key->barcode = barcode; + key->read_group = rg_num; +} + + +/* Add the duplicate name to a hash if it does not exist. */ + +static int add_duplicate(khash_t(duplicates) *d_hash, bam1_t *dupe, char *orig_name, char type, int group) { + khiter_t d; + int ret; + + d = kh_get(duplicates, d_hash, bam_get_qname(dupe)); + + if (d == kh_end(d_hash)) { + char *name = strdup(bam_get_qname(dupe)); + if (name) { + d = kh_put(duplicates, d_hash, name, &ret); + } else { + ret = -1; + } + + if (ret >= 0) { + if (orig_name) { + if (ret == 0) { + // replace old name + free(kh_value(d_hash, d).name); + free(name); + } + + kh_value(d_hash, d).name = strdup(orig_name); + + if (kh_value(d_hash, d).name == NULL) { + print_error("markdup", "error, unable to allocate memory for duplicate original name.\n"); + return 1; + } + } else { + kh_value(d_hash, d).name = NULL; + } + + kh_value(d_hash, d).type = type; + kh_value(d_hash, d).read_group = group; + } else { + print_error("markdup", "error, unable to store supplementary duplicates.\n"); + free(name); + return 1; + } + } + + return 0; +} + + +/* Get coordinates from the standard Illumina style read names. + Returned values are of the x and y coordinates and a section of + the read name to test (t) for string equality e.g. lane and tile part. */ + +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) { + int sep = 0; + int pos = 0; + int xpos = 0, ypos = 0; + char *end; + + while (qname[pos]) { + if (qname[pos] == ':') { + sep++; + + if (sep == 2) { + xpos = pos + 1; + } else if (sep == 3) { + ypos = pos + 1; + } else if (sep == 4) { // HiSeq style names + xpos = ypos; + ypos = pos + 1; + } else if (sep == 5) { // Newer Illumina format + xpos = pos + 1; + } else if (sep == 6) { + ypos = pos + 1; + } + } + + pos++; + } + + /* The most current Illumina read format at time of writing is: + @machine:run:flowcell:lane:tile:x:y:UMI or + @machine:run:flowcell:lane:tile:x:y + + Counting the separating colons gives us a quick format check. + Older name formats have fewer elements. + */ + + if (!(sep == 3 || sep == 4 || sep == 6 || sep == 7)) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, cannot decipher read name %s for optical duplicate marking.\n", qname); + } + + return 1; + } else { + *x_coord = strtol(qname + xpos, &end, 10); + + if ((qname + xpos) == end) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, cannot decipher x coordinate in %s .\n", qname); + } + + return 1; + } + + *y_coord = strtol(qname + ypos, &end, 10); + + if ((qname + ypos) == end) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, cannot decipher y coordinate in %s .\n", qname); + } + + return 1; + } + + *t_beg = 0; + *t_end = xpos; + } + + return 0; +} + +/* Get the coordinates from the read name. + Returned values are of the x and y coordinates and an optional section of + the read name to test (t) for string equality e.g. lane and tile part. */ + +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) { + regmatch_t matches[5]; + size_t max_matches = 5; + int xpos, ypos, xend, yend, xlen, ylen; + char coord[255]; + char *end; + + if (!param->rgx_t) + max_matches = 4; + + if (regexec(param->rgx, qname, max_matches, matches, 0)) + return -1; + + xpos = matches[param->rgx_x].rm_so; + ypos = matches[param->rgx_y].rm_so; + + if (param->rgx_t) { + *t_beg = matches[param->rgx_t].rm_so; + *t_end = matches[param->rgx_t].rm_eo; + } else { + *t_beg = *t_end = 0; + } + + if (xpos == -1 || ypos == -1 || *t_beg == -1) + return -1; + + xend = matches[param->rgx_x].rm_eo; + yend = matches[param->rgx_y].rm_eo; + + if ((xlen = xend - xpos) > 254) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, x coordinate string longer than allowed qname length in %s (%d long).\n", qname, xlen); + } + + return 1; + } + + strncpy(coord, qname + xpos, xlen); + coord[xlen] = '\0'; + *x_coord = strtol(coord, &end, 10); + + if (coord == end) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, cannot decipher x coordinate in %s (%s).\n", qname, coord); + } + + return 1; + } + + if ((ylen = yend - ypos) > 254) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, y coordinate string longer than allowed qname length in %s (%d long).\n", qname, ylen); + } + + return 1; + } + + strncpy(coord, qname + ypos, ylen); + coord[ylen] = '\0'; + *y_coord = strtol(coord, &end, 10); + + if (coord == end) { + (*warnings)++; + + if (*warnings <= BMD_WARNING_MAX) { + print_error("markdup", "warning, cannot decipher y coordinate in %s (%s).\n", qname, coord); + } + + return 1; + } + + return 0; +} + + +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) { + int ret = 1; + + if (param->rgx == NULL) { + ret = get_coordinates_colons(param, name, t_beg, t_end, x_coord, y_coord, warnings); + } else { + ret = get_coordinates_regex(param, name, t_beg, t_end, x_coord, y_coord, warnings); + } + + return ret; +} + + +/* Using the coordinates from the read name, see whether the duplicated read is + close enough (set by max_dist) to the original to be counted as optical.*/ + +static int is_optical_duplicate(md_param_t *param, bam1_t *ori, bam1_t *dup, long max_dist, long *warnings) { + int ret = 0; + char *original, *duplicate; + long ox, oy, dx, dy; + int o_beg = 0, o_end = 0, d_beg = 0, d_end = 0; + + original = bam_get_qname(ori); + duplicate = bam_get_qname(dup); + + if (get_coordinates(param, original, &o_beg, &o_end, &ox, &oy, warnings)) { + return ret; + } + + if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) { + return ret; + } + + if (strncmp(original + o_beg, duplicate + d_beg, o_end - o_beg) == 0) { + long xdiff, ydiff; + + if (ox > dx) { + xdiff = ox - dx; + } else { + xdiff = dx - ox; + } + + if (xdiff <= max_dist) { + // still might be optical + + if (oy > dy) { + ydiff = oy - dy; + } else { + ydiff = dy - oy; + } + + if (ydiff <= max_dist) ret = 1; + } + } + + return ret; +} + + +/* Using the coordinates from the Illumina read name, see whether the duplicated read is + close enough (set by max_dist) to the original to be counted as optical. + + This function needs the values from the first read to be already calculated. */ + +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) { + int ret = 0; + char *duplicate; + int d_beg = 0, d_end = 0; + long dx, dy; + + duplicate = bam_get_qname(dup); + + if (get_coordinates(param, duplicate, &d_beg, &d_end, &dx, &dy, warnings)) { + return ret; + } + + if (strncmp(name + o_beg, duplicate + d_beg, o_end - o_beg) == 0) { + // the initial parts match, look at the numbers + long xdiff, ydiff; + + if (ox > dx) { + xdiff = ox - dx; + } else { + xdiff = dx - ox; + } + + if (xdiff <= max_dist) { + // still might be optical + + if (oy > dy) { + ydiff = oy - dy; + } else { + ydiff = dy - oy; + } + + if (ydiff <= max_dist) ret = 1; + } + } + + c->x = dx; + c->y = dy; + c->beg = d_beg; + c->end = d_end; + + return ret; +} + + +/* Mark the read as a duplicate and update the duplicate hash (if needed) */ +static int mark_duplicates(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *ori, bam1_t *dup, + int read_group, long *optical, long *warn) { + char dup_type = 0; + long incoming_warnings = *warn; + + dup->core.flag |= BAM_FDUP; + + if (param->tag) { + if (bam_aux_update_str(dup, "do", strlen(bam_get_qname(ori)) + 1, bam_get_qname(ori))) { + print_error("markdup", "error, unable to append 'do' tag.\n"); + return -1; + } + } + + if (param->opt_dist) { // mark optical duplicates + if (is_optical_duplicate(param, ori, dup, param->opt_dist, warn)) { + bam_aux_update_str(dup, "dt", 3, "SQ"); + dup_type = 'O'; + (*optical)++; + } else { + // not an optical duplicate + bam_aux_update_str(dup, "dt", 3, "LB"); + } + } + + if ((*warn == BMD_WARNING_MAX) && (incoming_warnings != *warn)) { + print_error("markdup", "warning, %ld decipher read name warnings. New warnings will not be reported.\n", + *warn); + } + + if (param->supp) { + if (bam_aux_get(dup, "SA") || (dup->core.flag & BAM_FMUNMAP) || bam_aux_get(dup, "XA")) { + char *original = NULL; + + if (param->tag) { + original = bam_get_qname(ori); + } + + if (add_duplicate(dup_hash, dup, original, dup_type, read_group)) + return -1; + } + } + + return 0; +} + + +/* If the duplicate type has changed to optical then retag and duplicate hash. */ +static inline int optical_retag(md_param_t *param, khash_t(duplicates) *dup_hash, bam1_t *b, int paired, stats_block_t *stats) { + int ret = 0; + + if (bam_aux_update_str(b, "dt", 3, "SQ")) { + print_error("markdup", "error, unable to update 'dt' tag.\n"); + ret = -1; + } + + if (paired) { + stats->optical++; + } else { + stats->single_optical++; + } + + if (param->supp) { + // Change the duplicate type + + if (bam_aux_get(b, "SA") || (b->core.flag & BAM_FMUNMAP) + || bam_aux_get(b, "XA")) { + khiter_t d; + + d = kh_get(duplicates, dup_hash, bam_get_qname(b)); + + if (d == kh_end(dup_hash)) { + // error, name should already be in dup hash + print_error("markdup", "error, duplicate name %s not found in hash.\n", + bam_get_qname(b)); + ret = -1; + } else { + kh_value(dup_hash, d).type = 'O'; + } + } + } + + return ret; +} + + +/* Check all duplicates of the highest quality read (the "original") for consistancy. Also + pre-calculate any values for use in check_duplicate_chain later. + Returns 0 on success, >0 on coordinate reading error (program can continue) or + <0 on an error (program should not continue. */ +static int check_chain_against_original(md_param_t *param, khash_t(duplicates) *dup_hash, read_queue_t *ori, + check_list_t *list, long *warn, stats_block_t *stats) { + + int ret = 0, coord_fail = 0; + char *ori_name = bam_get_qname(ori->b); + read_queue_t *current = ori->duplicate; + int t_beg = 0, t_end = 0; + long x, y; + + if (param->opt_dist) { + coord_fail = get_coordinates(param, ori_name, &t_beg, &t_end, &x, &y, warn); + } + + list->length = 0; + + while (current) { + check_t *c; + + if (list->length >= list->size) { + check_t *tmp; + + list->size *= 2; + + if (!(tmp = realloc(list->c, list->size * sizeof(check_t)))) { + print_error("markdup", "error, Unable to expand optical check list.\n"); + return -1; + } + + list->c = tmp; + } + + c = &list->c[list->length]; + + c->b = current->b; + c->x = -1; + c->y = -1; + c->opt = 0; + c->score = 0; + c->mate_score = 0; + current->dup_checked = 1; + + if (param->tag) { + uint8_t *data; + + // at this stage all duplicates should have a do tag + if ((data = bam_aux_get(current->b, "do")) != NULL) { + // see if we need to change the tag + char *old_name = bam_aux2Z(data); + + if (old_name) { + if (strcmp(old_name, ori_name) != 0) { + if (bam_aux_update_str(current->b, "do", strlen(ori_name) + 1, (const char *)ori_name)) { + print_error("markdup", "error, unable to update 'do' tag.\n"); + ret = -1; + break; + } + } + } else { + print_error("markdup", "error, 'do' tag has wrong type for read %s.\n", bam_get_qname(current->b)); + ret = -1; + break; + } + } + } + + if (param->opt_dist && !coord_fail) { + uint8_t *data; + char *dup_type; + int is_opt = 0; + int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP); + + if ((data = bam_aux_get(current->b, "dt"))) { + if ((dup_type = bam_aux2Z(data))) { + if (strcmp(dup_type, "SQ") == 0) { + c->opt = 1; + } + } + } + + // need to run this to get the duplicates x and y scores + is_opt = optical_duplicate_partial(param, ori_name, t_beg, t_end, x, y, current->b, c, param->opt_dist, warn); + + if (!c->opt && is_opt) { + if (optical_retag(param, dup_hash, current->b, current_paired, stats)) { + ret = -1; + break; + } + + c->opt = 1; + } + + c->score = calc_score(current->b); + + if (current_paired) { + if ((c->mate_score = get_mate_score(current->b)) == -1) { + print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n"); + ret = -1; + break; + } + } + } + + current = current->duplicate; + list->length++; + } + + if (!ret && coord_fail) + ret = coord_fail; + + ori->dup_checked = 1; + + return ret; +} + + +static int xcoord_sort(const void *a, const void *b) { + check_t *ac = (check_t *) a; + check_t *bc = (check_t *) b; + + return (ac->x - bc->x); +} + + +/* Check all the duplicates against each other to see if they are optical duplicates. */ +static int check_duplicate_chain(md_param_t *param, khash_t(duplicates) *dup_hash, check_list_t *list, + long *warn, stats_block_t *stats) { + int ret = 0; + size_t curr = 0; + + qsort(list->c, list->length, sizeof(list->c[0]), xcoord_sort); + + while (curr < list->length - 1) { + check_t *current = &list->c[curr]; + size_t count = curr; + char *cur_name = bam_get_qname(current->b); + int current_paired = (current->b->core.flag & BAM_FPAIRED) && !(current->b->core.flag & BAM_FMUNMAP); + + while (++count < list->length && (list->c[count].x - current->x <= param->opt_dist)) { + // while close enough along the x coordinate + check_t *chk = &list->c[count]; + + if (current->opt && chk->opt) + continue; + + // if both are already optical duplicates there is no need to check again, otherwise... + + long ydiff; + + if (current->y > chk->y) { + ydiff = current->y - chk->y; + } else { + ydiff = chk->y - current->y; + } + + if (ydiff > param->opt_dist) + continue; + + // the number are right, check the names + if (strncmp(cur_name + current->beg, bam_get_qname(chk->b) + chk->beg, current->end - current->beg) != 0) + continue; + + // optical duplicates + int chk_dup = 0; + int chk_paired = (chk->b->core.flag & BAM_FPAIRED) && !(chk->b->core.flag & BAM_FMUNMAP); + + if (current_paired != chk_paired) { + if (!chk_paired) { + // chk is single vs pair, this is a dup. + chk_dup = 1; + } + } else { + // do it by scores + int64_t cur_score, chk_score; + + if ((current->b->core.flag & BAM_FQCFAIL) != (chk->b->core.flag & BAM_FQCFAIL)) { + if (current->b->core.flag & BAM_FQCFAIL) { + cur_score = 0; + chk_score = 1; + } else { + cur_score = 1; + chk_score = 0; + } + } else { + cur_score = current->score; + chk_score = chk->score; + + if (current_paired) { + // they are pairs so add mate scores. + chk_score += chk->mate_score; + cur_score += current->mate_score; + } + } + + if (cur_score == chk_score) { + if (strcmp(bam_get_qname(chk->b), cur_name) < 0) { + chk_score++; + } else { + chk_score--; + } + } + + if (cur_score > chk_score) { + chk_dup = 1; + } + } + + if (chk_dup) { + // the duplicate is the optical duplicate + if (!chk->opt) { // only change if not already an optical duplicate + if (optical_retag(param, dup_hash, chk->b, chk_paired, stats)) { + ret = -1; + goto fail; + } + + chk->opt = 1; + } + } else { + if (!current->opt) { + if (optical_retag(param, dup_hash, current->b, current_paired, stats)) { + ret = -1; + goto fail; + } + + current->opt = 1; + } + } + } + + curr++; + } + + fail: + return ret; +} + + +/* Where there is more than one duplicate go down the list and check for optical duplicates and change + do tags (where used) to point to original (non-duplicate) read. */ +static int find_duplicate_chains(md_param_t *param, read_queue_t *in_read , khash_t(duplicates) *dup_hash, check_list_t *dup_list, + long *warn, stats_block_t *stats) { + int ret = 0; + + while (in_read->original) in_read = in_read->original; + + // check against the original for tagging and optical duplication + if ((ret = check_chain_against_original(param, dup_hash, in_read, dup_list, warn, stats + in_read->read_group))) { + if (ret < 0) { // real error + ret = -1; + } else { // coordinate decoding error + ret = 0; + } + } else { + // check the rest of the duplicates against each other for optical duplication + if (param->opt_dist && check_duplicate_chain(param, dup_hash, dup_list, warn, stats + in_read->read_group)) { + ret = -1; + } + } + + return ret; +} + + +/* + Function to use when estimating library size. + + This is based on an approximate formula for the coverage of a set + obtained after sampling it a given number of times with replacement. + + x = number of items in the set (the number of unique fragments in the library) + + c = number of unique items (unique read pairs observed) + + n = number of items samples (total number of read pairs) + + c and n are known; x is unknown. + + As n -> infinity, the coverage (c/x) can be given as: + + c / x = 1 - exp(-n / x) (see https://math.stackexchange.com/questions/32800) + + This needs to be solved for x, so it is rearranged to put both terms on the + left side and estimate_library_size() finds a value of x which gives a + result of zero (or as close as it can get). + */ +static inline double coverage_equation(double x, double c, double n) { + return c / x - 1 + exp(-n / x); +} + + +/* estimate the library size, based on the Picard code in DuplicationMetrics.java*/ +static unsigned long estimate_library_size(unsigned long paired_reads, unsigned long paired_duplicate_reads, unsigned long optical) { + unsigned long estimated_size = 0; + unsigned long non_optical_pairs = (paired_reads - optical) / 2; + unsigned long unique_pairs = (paired_reads - paired_duplicate_reads) / 2; + unsigned long duplicate_pairs = (paired_duplicate_reads - optical) / 2; + + if ((non_optical_pairs && duplicate_pairs && unique_pairs) && (non_optical_pairs > duplicate_pairs)) { + double m = 1; + double M = 100; + int i; + + if (coverage_equation(m * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) < 0) { + print_error("markdup", "warning, unable to calculate estimated library size.\n"); + return estimated_size; + } + + while (coverage_equation(M * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs) > 0) { + M *= 10; + } + + for (i = 0; i < 40; i++) { + double r = (m + M) / 2; + double u = coverage_equation(r * (double)unique_pairs, (double)unique_pairs, (double)non_optical_pairs); + + if (u > 0) { + m = r; + } else if (u < 0) { + M = r; + } else { + break; + } + } + + estimated_size = (unsigned long)(unique_pairs * (m + M) / 2); + } else { + print_error("markdup", "warning, unable to calculate estimated library size." + " Read pairs %ld should be greater than duplicate pairs %ld," + " which should both be non zero.\n", + non_optical_pairs, duplicate_pairs); + } + + return estimated_size; +} + + +static void write_stats(FILE *fp, const char *title, const char *title_con, stats_block_t *stats) { + unsigned long els; + + els = estimate_library_size(stats->pair, stats->duplicate, stats->optical); + + if (title) { + fprintf(fp, "%s%s\n", title, title_con); + } + + fprintf(fp, + "READ: %ld\n" + "WRITTEN: %ld\n" + "EXCLUDED: %ld\n" + "EXAMINED: %ld\n" + "PAIRED: %ld\n" + "SINGLE: %ld\n" + "DUPLICATE PAIR: %ld\n" + "DUPLICATE SINGLE: %ld\n" + "DUPLICATE PAIR OPTICAL: %ld\n" + "DUPLICATE SINGLE OPTICAL: %ld\n" + "DUPLICATE NON PRIMARY: %ld\n" + "DUPLICATE NON PRIMARY OPTICAL: %ld\n" + "DUPLICATE PRIMARY TOTAL: %ld\n" + "DUPLICATE TOTAL: %ld\n" + "ESTIMATED_LIBRARY_SIZE: %ld\n", stats->reading, stats->writing, stats->excluded, stats->examined, stats->pair, stats->single, + stats->duplicate, stats->single_dup, stats->optical, stats->single_optical, stats->np_duplicate, stats->np_opt_duplicate, + stats->single_dup + stats->duplicate, stats->single_dup + stats->duplicate + stats->np_duplicate, els); +} + + +static void write_json_stats(FILE *fp, const char *offset, const char *group_name, stats_block_t *stats, const char *end) { + unsigned long els; + + els = estimate_library_size(stats->pair, stats->duplicate, stats->optical); + + if (group_name) { + fprintf(fp, "%s\"READ GROUP\": \"%s\",\n", offset, group_name); + } + + fprintf(fp, "%s\"READ\": %ld,\n", offset, stats->reading); + fprintf(fp, "%s\"WRITTEN\": %ld,\n", offset, stats->writing); + fprintf(fp, "%s\"EXCLUDED\": %ld,\n", offset, stats->excluded); + fprintf(fp, "%s\"EXAMINED\": %ld,\n", offset, stats->examined); + fprintf(fp, "%s\"PAIRED\": %ld,\n", offset, stats->pair); + fprintf(fp, "%s\"SINGLE\": %ld,\n", offset, stats->single); + fprintf(fp, "%s\"DUPLICATE PAIR\": %ld,\n", offset, stats->duplicate); + fprintf(fp, "%s\"DUPLICATE SINGLE\": %ld,\n", offset, stats->single_dup); + fprintf(fp, "%s\"DUPLICATE PAIR OPTICAL\": %ld,\n", offset, stats->optical); + fprintf(fp, "%s\"DUPLICATE SINGLE OPTICAL\": %ld,\n", offset, stats->single_optical); + fprintf(fp, "%s\"DUPLICATE NON PRIMARY\": %ld,\n", offset, stats->np_duplicate); + fprintf(fp, "%s\"DUPLICATE NON PRIMARY OPTICAL\": %ld,\n", offset, stats->np_opt_duplicate); + fprintf(fp, "%s\"DUPLICATE PRIMARY TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate); + fprintf(fp, "%s\"DUPLICATE TOTAL\": %ld,\n", offset, stats->single_dup + stats->duplicate + stats->np_duplicate); + fprintf(fp, "%s\"ESTIMATED_LIBRARY_SIZE\": %ld", offset, els); + + if (end) { + fprintf(fp, "%s", end); + } +} + + +/* Compare the reads near each other (coordinate sorted) and try to spot the duplicates. + Generally the highest quality scoring is chosen as the original and all others the duplicates. + The score is based on the sum of the quality values (<= 15) of the read and its mate (if any). + While single reads are compared to only one read of a pair, the pair will chosen as the original. + The comparison is done on position and orientation, see above for details. + + Marking the supplementary reads of a duplicate as also duplicates takes an extra file read/write + step. This is because the duplicate can occur before the primary read.*/ + +static int bam_mark_duplicates(md_param_t *param) { + bam_hdr_t *header = NULL; + khiter_t k; + khash_t(reads) *pair_hash = kh_init(reads); + khash_t(reads) *single_hash = kh_init(reads); + klist_t(read_queue) *read_buffer = kl_init(read_queue); + kliter_t(read_queue) *rq; + khash_t(duplicates) *dup_hash = kh_init(duplicates); + khash_t(read_groups) *rg_hash = kh_init(read_groups); + int32_t prev_tid; + hts_pos_t prev_coord; + read_queue_t *in_read; + int ret; + stats_block_t *stats, *stat_array = NULL; + int num_groups = 0; + long opt_warnings = 0, bc_warnings = 0; + tmp_file_t temp; + char *idx_fn = NULL; + int exclude = 0; + check_list_t dup_list = {NULL, 0, 0}; + + if (!pair_hash || !single_hash || !read_buffer || !dup_hash || !rg_hash) { + print_error("markdup", "error, unable to allocate memory to initialise structures.\n"); + goto fail; + } + + if ((header = sam_hdr_read(param->in)) == NULL) { + print_error("markdup", "error reading header\n"); + goto fail; + } + + // accept unknown, unsorted or coordinate sort order, but error on queryname sorted. + // only really works on coordinate sorted files. + kstring_t str = KS_INITIALIZE; + if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "queryname")) { + print_error("markdup", "error, queryname sorted, must be sorted by coordinate.\n"); + ks_free(&str); + goto fail; + } + ks_free(&str); + + if (!param->no_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(), + param->arg_list ? "CL" : NULL, + param->arg_list ? param->arg_list : NULL, + NULL) != 0) { + print_error("markdup", "warning, unable to add @PG line to header.\n"); + } + + if (sam_hdr_write(param->out, header) < 0) { + print_error("markdup", "error writing header.\n"); + goto fail; + } + if (param->write_index) { + if (!(idx_fn = auto_index(param->out, param->out_fn, header))) + goto fail; + } + + if (param->read_groups) { + num_groups = sam_hdr_count_lines(header, "RG"); + int g_ret = 0; + + if (num_groups > 0) { + int i; + + for (i = 0; i < num_groups; i++) { + const char *rg_key; + khiter_t rg; + + rg_key = sam_hdr_line_name(header, "RG", i); + + if (rg_key) { + rg = kh_get(read_groups, rg_hash, rg_key); + + if (rg == kh_end(rg_hash)) { // new entry + rg = kh_put(read_groups, rg_hash, rg_key, &g_ret); + + if (g_ret > 0) { + kh_value(rg_hash, rg) = i + 1; + } else { + print_error("markdup", "error, unable to populate read group ids. " + "Read groups will not be used\n"); + g_ret = -1; + break; + } + } else { + print_error("markdup", "error, duplicate read group ids %s." + "Read groups will not be used\n", rg_key); + g_ret = -1; + break; + } + } else { + print_error("markdup", "error, Unable to retrieve read group at position %d." + "Read groups will not be used\n", i); + g_ret = -1; + break; + } + } + } else { + print_error("markdup", "error, no read groups found.\n"); + g_ret = -1; + } + + if (g_ret < 0) { + print_error("markdup", "error, read groups will not be used.\n"); + param->read_groups = 0; + num_groups = 0; + } + } + + // stat_array[0] will be for ungrouped reads + stat_array = calloc(num_groups + 1, sizeof(stats_block_t)); + + if (stat_array == NULL) { + print_error("markdup", "error, unable to allocate memory for stats.\n"); + goto fail; + } + + // used for coordinate order checks + prev_tid = prev_coord = 0; + + // get the buffer going + in_read = kl_pushp(read_queue, read_buffer); + if (!in_read) { + print_error("markdup", "error, unable to allocate memory to hold reads.\n"); + goto fail; + } + + // handling supplementary reads needs a temporary file + if (param->supp) { + if (tmp_file_open_write(&temp, param->prefix, 1)) { + print_error("markdup", "error, unable to open tmp file %s.\n", param->prefix); + goto fail; + } + } + + if ((in_read->b = bam_init1()) == NULL) { + print_error("markdup", "error, unable to allocate memory for alignment.\n"); + goto fail; + } + + if (param->check_chain && !(param->tag || param->opt_dist)) + param->check_chain = 0; + + if (param->check_chain) { + dup_list.size = 128; + dup_list.c = NULL; + + if ((dup_list.c = malloc(dup_list.size * sizeof(check_t))) == NULL) { + print_error("markdup", "error, unable to allocate memory for dup_list.\n"); + goto fail; + } + } + + while ((ret = sam_read1(param->in, header, in_read->b)) >= 0) { + + // do some basic coordinate order checks + if (in_read->b->core.tid >= 0) { // -1 for unmapped reads + if (in_read->b->core.tid < prev_tid || + ((in_read->b->core.tid == prev_tid) && (in_read->b->core.pos < prev_coord))) { + print_error("markdup", "error, not in coordinate sorted order.\n"); + goto fail; + } + } + + prev_coord = in_read->pos = in_read->b->core.pos; + prev_tid = in_read->b->core.tid; + in_read->pair_key.single = 1; + in_read->single_key.single = 0; + in_read->duplicate = NULL; + in_read->original = NULL; + in_read->dup_checked = 0; + in_read->read_group = 0; + in_read->dc = 1; + + if (param->read_groups) { + uint8_t *data; + char *rg; + + if ((data = bam_aux_get(in_read->b, "RG"))) { + if ((rg = bam_aux2Z(data))) { + khiter_t r; + + r = kh_get(read_groups, rg_hash, rg); + + if (r != kh_end(rg_hash)) { + in_read->read_group = kh_value(rg_hash, r); + } + } + } + } + + stats = stat_array + in_read->read_group; + + stats->reading++; + + if (param->clear && (in_read->b->core.flag & BAM_FDUP)) { + uint8_t *data; + + in_read->b->core.flag ^= BAM_FDUP; + + if ((data = bam_aux_get(in_read->b, "dt")) != NULL) { + bam_aux_del(in_read->b, data); + } + + if ((data = bam_aux_get(in_read->b, "do")) != NULL) { + bam_aux_del(in_read->b, data); + } + } + + if (param->include_fails) { + exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP); + } else { + exclude |= (BAM_FSECONDARY | BAM_FSUPPLEMENTARY | BAM_FUNMAP | BAM_FQCFAIL); + } + + // read must not be secondary, supplementary, unmapped or (possibly) failed QC + if (!(in_read->b->core.flag & exclude)) { + stats->examined++; + + + // look at the pairs first + if ((in_read->b->core.flag & BAM_FPAIRED) && !(in_read->b->core.flag & BAM_FMUNMAP)) { + int ret, mate_tmp; + key_data_t pair_key; + key_data_t single_key; + in_hash_t *bp; + + if (make_pair_key(param, &pair_key, in_read->b, in_read->read_group, &bc_warnings)) { + print_error("markdup", "error, unable to assign pair hash key.\n"); + goto fail; + } + + make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings); + + stats->pair++; + in_read->pos = single_key.this_coord; // cigar/orientation modified pos + + // put in singles hash for checking against non paired reads + k = kh_put(reads, single_hash, single_key, &ret); + + if (ret > 0) { // new + // add to single duplicate hash + bp = &kh_val(single_hash, k); + bp->p = in_read; + in_read->single_key = single_key; + } else if (ret == 0) { // exists + // look at singles only for duplication marking + bp = &kh_val(single_hash, k); + + if (!(bp->p->b->core.flag & BAM_FPAIRED) || (bp->p->b->core.flag & BAM_FMUNMAP)) { + // singleton will always be marked duplicate even if + // scores more than one read of the pair + bam1_t *dup = bp->p->b; + + if (param->check_chain) { + in_read->duplicate = bp->p; + bp->p->original = in_read; + } + + bp->p = in_read; + bp->p->dc += 1; + + if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings)) + goto fail; + + stats->single_dup++; + } + } else { + print_error("markdup", "error, single hashing failure for paired read.\n"); + goto fail; + } + + // now do the pair + k = kh_put(reads, pair_hash, pair_key, &ret); + + if (ret > 0) { // new + // add to the pair hash + bp = &kh_val(pair_hash, k); + bp->p = in_read; + in_read->pair_key = pair_key; + } else if (ret == 0) { + int64_t old_score, new_score, tie_add = 0; + bam1_t *dup = NULL; + + bp = &kh_val(pair_hash, k); + + if ((bp->p->b->core.flag & BAM_FQCFAIL) != (in_read->b->core.flag & BAM_FQCFAIL)) { + if (bp->p->b->core.flag & BAM_FQCFAIL) { + old_score = 0; + new_score = 1; + } else { + old_score = 1; + new_score = 0; + } + } else { + if ((mate_tmp = get_mate_score(bp->p->b)) == -1) { + print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n"); + goto fail; + } else { + old_score = calc_score(bp->p->b) + mate_tmp; + } + + if ((mate_tmp = get_mate_score(in_read->b)) == -1) { + print_error("markdup", "error, no ms score tag. Please run samtools fixmate on file first.\n"); + goto fail; + } else { + new_score = calc_score(in_read->b) + mate_tmp; + } + } + + // choose the highest score as the original + // and add it to the pair hash, mark the other as duplicate + + if (new_score == old_score) { + if (strcmp(bam_get_qname(in_read->b), bam_get_qname(bp->p->b)) < 0) { + tie_add = 1; + } else { + tie_add = -1; + } + } + + if (new_score + tie_add > old_score) { // swap reads + dup = bp->p->b; + in_read->dc += bp->p->dc; + + if (param->check_chain) { + + if (in_read->duplicate) { + read_queue_t *current = in_read->duplicate; + + while (current->duplicate) { + current = current->duplicate; + } + + current->duplicate = bp->p; + } else { + in_read->duplicate = bp->p; + } + + bp->p->original = in_read; + } + + bp->p = in_read; + } else { + if (param->check_chain) { + if (bp->p->duplicate) { + if (in_read->duplicate) { + read_queue_t *current = bp->p->duplicate; + + while (current->duplicate) { + current = current->duplicate; + } + + current->duplicate = in_read->duplicate; + } + + in_read->duplicate = bp->p->duplicate; + } + + bp->p->duplicate = in_read; + in_read->original = bp->p; + } + + dup = in_read->b; + bp->p->dc += 1; + } + + if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->optical, &opt_warnings)) + goto fail; + + stats->duplicate++; + } else { + print_error("markdup", "error, pair hashing failure.\n"); + goto fail; + } + } else { // do the single (or effectively single) reads + int ret; + key_data_t single_key; + in_hash_t *bp; + + make_single_key(param, &single_key, in_read->b, in_read->read_group, &bc_warnings); + + stats->single++; + in_read->pos = single_key.this_coord; // cigar/orientation modified pos + + k = kh_put(reads, single_hash, single_key, &ret); + + if (ret > 0) { // new + bp = &kh_val(single_hash, k); + bp->p = in_read; + in_read->single_key = single_key; + } else if (ret == 0) { // exists + bp = &kh_val(single_hash, k); + + if ((bp->p->b->core.flag & BAM_FPAIRED) && !(bp->p->b->core.flag & BAM_FMUNMAP)) { + // if matched against one of a pair just mark as duplicate + + if (param->check_chain) { + if (bp->p->duplicate) { + in_read->duplicate = bp->p->duplicate; + } + + bp->p->duplicate = in_read; + in_read->original = bp->p; + } + + bp->p->dc += 1; + + if (mark_duplicates(param, dup_hash, bp->p->b, in_read->b, in_read->read_group, &stats->single_optical, &opt_warnings)) + goto fail; + + } else { + int64_t old_score, new_score; + bam1_t *dup = NULL; + + old_score = calc_score(bp->p->b); + new_score = calc_score(in_read->b); + + // choose the highest score as the original, add it + // to the single hash and mark the other as duplicate + if (new_score > old_score) { // swap reads + dup = bp->p->b; + in_read->dc += bp->p->dc; + + if (param->check_chain) { + in_read->duplicate = bp->p; + bp->p->original = in_read; + } + + bp->p = in_read; + } else { + if (param->check_chain) { + if (bp->p->duplicate) { + in_read->duplicate = bp->p->duplicate; + } + + bp->p->duplicate = in_read; + in_read->original = bp->p; + } + + bp->p->dc += 1; + dup = in_read->b; + } + + if (mark_duplicates(param, dup_hash, bp->p->b, dup, in_read->read_group, &stats->single_optical, &opt_warnings)) + goto fail; + } + + stats->single_dup++; + } else { + print_error("markdup", "error, single hashing failure for single read.\n"); + goto fail; + } + } + } else { + stats->excluded++; + } + + // loop through the stored reads and write out those we + // no longer need + rq = kl_begin(read_buffer); + while (rq != kl_end(read_buffer)) { + in_read = &kl_val(rq); + + /* keep a moving window of reads based on coordinates and max read length. Any unaligned reads + should just be written as they cannot be matched as duplicates. */ + if (in_read->pos + param->max_length > prev_coord && in_read->b->core.tid == prev_tid && (prev_tid != -1 || prev_coord != -1)) { + break; + } + + if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) { + if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) { + print_error("markdup", "error, duplicate checking failed.\n"); + goto fail; + } + } + + if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) { + if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) { + bam_aux_update_int(in_read->b, "dc", in_read->dc); + } + if (param->supp) { + if (tmp_file_write(&temp, in_read->b)) { + print_error("markdup", "error, writing temp output failed.\n"); + goto fail; + } + } else { + if (sam_write1(param->out, header, in_read->b) < 0) { + print_error("markdup", "error, writing output failed.\n"); + goto fail; + } + } + + stat_array[in_read->read_group].writing++; + } + + // remove from hash + if (in_read->pair_key.single == 0) { + k = kh_get(reads, pair_hash, in_read->pair_key); + kh_del(reads, pair_hash, k); + } + + if (in_read->single_key.single == 1) { + k = kh_get(reads, single_hash, in_read->single_key); + kh_del(reads, single_hash, k); + } + + kl_shift(read_queue, read_buffer, NULL); + bam_destroy1(in_read->b); + rq = kl_begin(read_buffer); + } + + // set the next one up for reading + in_read = kl_pushp(read_queue, read_buffer); + if (!in_read) { + print_error("markdup", "error, unable to allocate memory for read in queue.\n"); + goto fail; + } + + if ((in_read->b = bam_init1()) == NULL) { + print_error("markdup", "error, unable to allocate memory for alignment.\n"); + goto fail; + } + } + + if (ret < -1) { + print_error("markdup", "error, truncated input file.\n"); + goto fail; + } + + // write out the end of the list + rq = kl_begin(read_buffer); + while (rq != kl_end(read_buffer)) { + in_read = &kl_val(rq); + + if (bam_get_qname(in_read->b)) { // last entry will be blank + if (param->check_chain && !in_read->dup_checked && (in_read->original || in_read->duplicate)) { + if (find_duplicate_chains(param, in_read, dup_hash, &dup_list, &opt_warnings, stat_array)) { + print_error("markdup", "error, duplicate checking failed.\n"); + goto fail; + } + } + + if (!param->remove_dups || !(in_read->b->core.flag & BAM_FDUP)) { + if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) { + bam_aux_update_int(in_read->b, "dc", in_read->dc); + } + + if (param->supp) { + if (tmp_file_write(&temp, in_read->b)) { + print_error("markdup", "error, writing temp output failed on final write.\n"); + goto fail; + } + } else { + if (param->dc && !(in_read->b->core.flag & BAM_FDUP)) { + bam_aux_update_int(in_read->b, "dc", in_read->dc); + } + + if (sam_write1(param->out, header, in_read->b) < 0) { + print_error("markdup", "error, writing output failed on final write.\n"); + goto fail; + } + } + + stat_array[in_read->read_group].writing++; + } + } + + kl_shift(read_queue, read_buffer, NULL); + bam_destroy1(in_read->b); + rq = kl_begin(read_buffer); + } + + if (param->supp) { + bam1_t *b; + + if (tmp_file_end_write(&temp)) { + print_error("markdup", "error, unable to end tmp writing.\n"); + goto fail; + } + + // read data from temp file and mark duplicate supplementary alignments + + if (tmp_file_begin_read(&temp)) { + goto fail; + } + + b = bam_init1(); + + while ((ret = tmp_file_read(&temp, b)) > 0) { + + if ((b->core.flag & BAM_FSUPPLEMENTARY) || (b->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FSECONDARY)) { + + k = kh_get(duplicates, dup_hash, bam_get_qname(b)); + + if (k != kh_end(dup_hash)) { + + b->core.flag |= BAM_FDUP; + stat_array[kh_val(dup_hash, k).read_group].np_duplicate++; + + if (param->tag && kh_val(dup_hash, k).name) { + if (bam_aux_update_str(b, "do", strlen(kh_val(dup_hash, k).name) + 1, (char*)kh_val(dup_hash, k).name)) { + print_error("markdup", "error, unable to append supplementary 'do' tag.\n"); + goto fail; + } + } + + if (param->opt_dist) { + if (kh_val(dup_hash, k).type) { + bam_aux_update_str(b, "dt", 3, "SQ"); + stat_array[kh_val(dup_hash, k).read_group].np_opt_duplicate++; + } else { + bam_aux_update_str(b, "dt", 3, "LB"); + } + } + } + } + + if (!param->remove_dups || !(b->core.flag & BAM_FDUP)) { + if (param->dc && (b->core.flag & BAM_FDUP)) { + uint8_t* data = bam_aux_get(b, "dc"); + if(data) bam_aux_del(b, data); + } + if (sam_write1(param->out, header, b) < 0) { + print_error("markdup", "error, writing final output failed.\n"); + goto fail; + } + } + } + + if (ret == -1) { + print_error("markdup", "error, failed to read tmp file.\n"); + goto fail; + } + + for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) { + if (kh_exist(dup_hash, k)) { + free(kh_val(dup_hash, k).name); + free((char *)kh_key(dup_hash, k)); + kh_key(dup_hash, k) = NULL; + } + } + + tmp_file_destroy(&temp); + bam_destroy1(b); + } + + if (opt_warnings) { + print_error("markdup", "warning, number of failed attempts to get coordinates from read names = %ld\n", + opt_warnings); + } + + if (bc_warnings) { + print_error("markdup", "warning, number of failed attempts to get barcodes = %ld\n", bc_warnings); + } + + if (param->do_stats) { + FILE *fp; + int file_open = 0; + stats_block_t total; + int i; + + if (param->stats_file) { + if (NULL == (fp = fopen(param->stats_file, "w"))) { + print_error("markdup", "warning, cannot write stats to %s.\n", param->stats_file); + fp = stderr; + } else { + file_open = 1; + } + } else { + fp = stderr; + } + + total = stat_array[0]; + + if (param->read_groups) { + for (i = 1; i <= num_groups; i++) { + total.reading += stat_array[i].reading; + total.writing += stat_array[i].writing; + total.excluded += stat_array[i].excluded; + total.duplicate += stat_array[i].duplicate; + total.single += stat_array[i].single; + total.pair += stat_array[i].pair; + total.single_dup += stat_array[i].single_dup; + total.examined += stat_array[i].examined; + total.optical += stat_array[i].optical; + total.single_optical += stat_array[i].single_optical; + total.np_duplicate += stat_array[i].np_duplicate; + total.np_opt_duplicate += stat_array[i].np_opt_duplicate; + } + } + + if (!param->json) { + write_stats(fp, "COMMAND: ", param->arg_list, &total); + fprintf(fp, "\n"); + + if (param->read_groups) { + if (stat_array[0].reading) { + write_stats(fp, "READ GROUP: ", "ungrouped", stat_array); + fprintf(fp, "\n"); + } + + for (i = 0; i < num_groups; i++) { + write_stats(fp, "READ GROUP: ", sam_hdr_line_name(header, "RG", i), stat_array + i + 1); + fprintf(fp, "\n"); + } + } + } else { + char space4[] = " "; + char space8[] = " "; + char space12[] = " "; + + fprintf(fp, "{\n"); + fprintf(fp, "%s\"COMMAND\": \"%s\",\n", space4, param->arg_list); + write_json_stats(fp, space4, NULL, &total, param->read_groups ? ",\n" : "\n"); + + if (param->read_groups) { + fprintf(fp, "%s\"READ GROUPS\": [\n", space4); + + if (stat_array[0].reading) { + fprintf(fp, "%s{\n", space8); + write_json_stats(fp, space12, "ungrouped", stat_array, "\n"); + fprintf(fp, "%s},\n", space8); + } + + for (i = 0; i < num_groups; i++) { + fprintf(fp, "%s{\n", space8); + + write_json_stats(fp, space12, sam_hdr_line_name(header, "RG", i), stat_array + i + 1, "\n"); + + if (i < num_groups -1 ) { + fprintf(fp, "%s},\n", space8); + } else { + fprintf(fp, "%s}\n", space8); + } + } + + fprintf(fp, "%s]\n", space4); + } + + fprintf(fp, "}\n"); + } + + if (file_open) { + fclose(fp); + } + } + + if (param->write_index) { + if (sam_idx_save(param->out) < 0) { + print_error_errno("markdup", "error, writing index failed"); + goto fail; + } + } + + if (param->check_chain && (param->tag || param->opt_dist)) + free(dup_list.c); + + free(idx_fn); + free(stat_array); + kh_destroy(reads, pair_hash); + kh_destroy(reads, single_hash); + kl_destroy(read_queue, read_buffer); + kh_destroy(duplicates, dup_hash); + kh_destroy(read_groups, rg_hash); + sam_hdr_destroy(header); + + return 0; + + fail: + for (rq = kl_begin(read_buffer); rq != kl_end(read_buffer); rq = kl_next(rq)) + bam_destroy1(kl_val(rq).b); + kl_destroy(read_queue, read_buffer); + + for (k = kh_begin(dup_hash); k != kh_end(dup_hash); ++k) { + if (kh_exist(dup_hash, k)) { + free((char *)kh_key(dup_hash, k)); + } + } + kh_destroy(duplicates, dup_hash); + kh_destroy(read_groups, rg_hash); + + if (param->check_chain && (param->tag || param->opt_dist)) + free(dup_list.c); + + free(idx_fn); + free(stat_array); + kh_destroy(reads, pair_hash); + kh_destroy(reads, single_hash); + sam_hdr_destroy(header); + return 1; +} + + +static int markdup_usage(void) { + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: samtools markdup \n\n"); + fprintf(stderr, "Option: \n"); + fprintf(stderr, " -r Remove duplicate reads\n"); + fprintf(stderr, " -l INT Max read length (default 300 bases)\n"); + fprintf(stderr, " -S Mark supplementary alignments of duplicates as duplicates (slower).\n"); + fprintf(stderr, " -s Report stats.\n"); + fprintf(stderr, " -f NAME Write stats to named file. Implies -s.\n"); + fprintf(stderr, " --json Output stats in JSON. Also implies -s\n"); + fprintf(stderr, " -T PREFIX Write temporary files to PREFIX.samtools.nnnn.nnnn.tmp.\n"); + fprintf(stderr, " -d INT Optical distance (if set, marks with dt tag)\n"); + fprintf(stderr, " -c Clear previous duplicate settings and tags.\n"); + fprintf(stderr, " -m --mode TYPE Duplicate decision method for paired reads.\n" + " TYPE = t measure positions based on template start/end (default).\n" + " s measure positions based on sequence start.\n"); + fprintf(stderr, " -u Output uncompressed data\n"); + fprintf(stderr, " --include-fails Include quality check failed reads.\n"); + fprintf(stderr, " --no-PG Do not add a PG line\n"); + fprintf(stderr, " --no-multi-dup Reduced duplicates of duplicates checking.\n"); + fprintf(stderr, " --read-coords STR Regex for coords from read name.\n"); + fprintf(stderr, " --coords-order STR Order of regex elements. txy (default). With t being a part of\n" + " the read names that must be equal and x/y being coordinates.\n"); + fprintf(stderr, " --barcode-tag STR Use barcode a tag that duplicates much match.\n"); + fprintf(stderr, " --barcode-name Use the UMI/barcode in the read name (eigth colon delimited part).\n"); + fprintf(stderr, " --barcode-rgx STR Regex for barcode in the readname (alternative to --barcode-name).\n"); + fprintf(stderr, " --use-read-groups Use the read group tags in duplicate matching.\n"); + fprintf(stderr, " -t Mark primary duplicates with the name of the original in a \'do\' tag." + " Mainly for information and debugging.\n"); + fprintf(stderr, " --duplicate-count Record the original primary read duplication count(include itself) in a \'dc\' tag.\n"); + + sam_global_opt_help(stderr, "-.O..@.."); + + fprintf(stderr, "\nThe input file must be coordinate sorted and must have gone" + " through fixmates with the mate scoring option on.\n"); + + return 1; +} + + +int bam_markdup(int argc, char **argv) { + int c, ret, bc_name = 0; + char wmode[4] = {'w', 0, 0, 0}; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool p = {NULL, 0}; + kstring_t tmpprefix = {0, 0, NULL}; + struct stat st; + unsigned int t; + char *regex = NULL, *bc_regex = NULL; + char *regex_order = "txy"; + md_param_t param = {NULL, NULL, NULL, 0, 300, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0}; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"include-fails", no_argument, NULL, 1001}, + {"no-PG", no_argument, NULL, 1002}, + {"mode", required_argument, NULL, 'm'}, + {"no-multi-dup", no_argument, NULL, 1003}, + {"read-coords", required_argument, NULL, 1004}, + {"coords-order", required_argument, NULL, 1005}, + {"barcode-tag", required_argument, NULL, 1006}, + {"barcode-name", no_argument, NULL, 1007}, + {"barcode-rgx", required_argument, NULL, 1008}, + {"use-read-groups", no_argument, NULL, 1009}, + {"json", no_argument, NULL, 1010}, + {"duplicate-count", no_argument, NULL, 1011}, + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "rsl:StT:O:@:f:d:cm:u", lopts, NULL)) >= 0) { + switch (c) { + case 'r': param.remove_dups = 1; break; + case 'l': param.max_length = atoi(optarg); break; + case 's': param.do_stats = 1; break; + case 'T': kputs(optarg, &tmpprefix); break; + case 'S': param.supp = 1; break; + case 't': param.tag = 1; break; + case 'f': param.stats_file = optarg; param.do_stats = 1; break; + case 'd': param.opt_dist = atoi(optarg); break; + case 'c': param.clear = 1; break; + case 'm': + if (strcmp(optarg, "t") == 0) { + param.mode = MD_MODE_TEMPLATE; + } else if (strcmp(optarg, "s") == 0) { + param.mode = MD_MODE_SEQUENCE; + } else { + print_error("markdup", "error, unknown mode '%s'.\n", optarg); + return markdup_usage(); + } + + break; + case 'u': wmode[1] = '0'; break; + case 1001: param.include_fails = 1; break; + case 1002: param.no_pg = 1; break; + case 1003: param.check_chain = 0; break; + case 1004: regex = optarg; break; + case 1005: regex_order = optarg; break; + case 1006: param.barcode = optarg; break; + case 1007: bc_name = 1; break; + case 1008: bc_name = 1, bc_regex = optarg; break; + case 1009: param.read_groups = 1; break; + case 1010: param.json = 1; param.do_stats = 1; break; + case 1011: param.dc = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': return markdup_usage(); + } + } + + if (optind + 2 > argc) + return markdup_usage(); + + if (param.barcode && bc_name) { + print_error("markdup", "error, cannot specify --barcode-tag and " + "--barcode-name (or --barcode-rgx) at same time.\n"); + return 1; + } + + if (param.opt_dist < 0) param.opt_dist = 0; + if (param.max_length < 0) param.max_length = 300; + + if (regex) { + int result; + + // set the order the elements of the regex are assigned to. + // x and y being coordinates, t being any other important part of the read + // e.g. tile and lane + // x and y order does not matter as long as it is consistent + + if ((strncmp(regex_order, "txy", 3) == 0) || (strncmp(regex_order, "tyx", 3) == 0)) { + param.rgx_t = 1; + param.rgx_x = 2; + param.rgx_y = 3; + } else if ((strncmp(regex_order, "xyt", 3) == 0) || (strncmp(regex_order, "yxt", 3) == 0)) { + param.rgx_x = 1; + param.rgx_y = 2; + param.rgx_t = 3; + } else if ((strncmp(regex_order, "xty", 3) == 0) || (strncmp(regex_order, "ytx", 3) == 0)) { + param.rgx_x = 1; + param.rgx_t = 2; + param.rgx_y = 3; + } else if ((strncmp(regex_order, "xy", 2) == 0) || (strncmp(regex_order, "yx", 2) == 0)) { + param.rgx_x = 1; + param.rgx_y = 2; + param.rgx_t = 0; + } else { + print_error("markdup", "error, could not recognise regex coordinate order \"%s\".\n", regex_order); + return 1; + } + + if ((param.rgx = malloc(sizeof(regex_t))) == NULL) { + print_error("markdup", "error, could not allocate memory for regex.\n"); + return 1; + } + + if ((result = regcomp(param.rgx, regex, REG_EXTENDED))) { + char err_msg[256]; + + regerror(result, param.rgx, err_msg, 256); + print_error("markdup", "error, regex fail \"%s\"\n", err_msg); + free(param.rgx); + return 1; + } + } + + if (bc_name) { + int result; + + /* From Illumina UMI documentation: "The UMI sequence is located in the + eighth colon-delimited field of the read name (QNAME)". */ + 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-~]+)"; + + if ((param.bc_rgx = malloc(sizeof(regex_t))) == NULL) { + print_error("markdup", "error, could not allocate memory for barcode regex.\n"); + return 1; + } + + if (bc_regex) { + rgx = bc_regex; + } + + if ((result = regcomp(param.bc_rgx, rgx, REG_EXTENDED))) { + char err_msg[256]; + + regerror(result, param.bc_rgx, err_msg, 256); + print_error("markdup", "error, barcode regex fail \"%s\"\n", err_msg); + free(param.bc_rgx); + return 1; + } + } + + param.in = sam_open_format(argv[optind], "r", &ga.in); + + if (!param.in) { + print_error_errno("markdup", "error, failed to open \"%s\" for input", argv[optind]); + return 1; + } + + strcat(wmode, "b"); // default if unknown suffix + sam_open_mode(wmode + strlen(wmode)-1, argv[optind + 1], NULL); + param.out = sam_open_format(argv[optind + 1], wmode, &ga.out); + + if (!param.out) { + print_error_errno("markdup", "error, failed to open \"%s\" for output", argv[optind + 1]); + return 1; + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + print_error("markdup", "error creating thread pool.\n"); + return 1; + } + + hts_set_opt(param.in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(param.out, HTS_OPT_THREAD_POOL, &p); + } + + // actual stuff happens here + + // we need temp files so fix up the name here + if (tmpprefix.l == 0) { + + if (strcmp(argv[optind + 1], "-") != 0) + ksprintf(&tmpprefix, "%s.", argv[optind + 1]); + else + kputc('.', &tmpprefix); + } + + if (stat(tmpprefix.s, &st) == 0 && S_ISDIR(st.st_mode)) { + if (tmpprefix.s[tmpprefix.l-1] != '/') kputc('/', &tmpprefix); + } + + t = ((unsigned) time(NULL)) ^ ((unsigned) clock()); + ksprintf(&tmpprefix, "samtools.%d.%u.tmp", (int) getpid(), t % 10000); + param.prefix = tmpprefix.s; + + param.arg_list = stringify_argv(argc + 1, argv - 1); + param.write_index = ga.write_index; + param.out_fn = argv[optind + 1]; + + ret = bam_mark_duplicates(¶m); + + sam_close(param.in); + + if (sam_close(param.out) < 0) { + print_error("markdup", "error closing output file.\n"); + ret = 1; + } + + if (p.pool) hts_tpool_destroy(p.pool); + + if (param.rgx) { + regfree(param.rgx); + free(param.rgx); + } + + if (param.bc_rgx) { + regfree(param.bc_rgx); + free(param.bc_rgx); + } + + free(param.arg_list); + free(tmpprefix.s); + sam_global_args_free(&ga); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c new file mode 100644 index 0000000000000000000000000000000000000000..1f2b576a7a0df1d31e13d128d518f0f54207d7d3 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c @@ -0,0 +1,728 @@ +/* bam_mate.c -- fix mate pairing information and clean up flags. + + Copyright (C) 2009, 2011-2017, 2019, 2022 Genome Research Ltd. + Portions copyright (C) 2011 Broad Institute. + Portions copyright (C) 2012 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "samtools.h" + + +#define MD_MIN_QUALITY 15 + +/* + * This function calculates ct tag for two bams, it assumes they are from the same template and + * writes the tag to the first read in position terms. + */ +static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str) +{ + bam1_t *swap; + int i; + hts_pos_t end; + uint32_t *cigar; + str->l = 0; + 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 + if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate + kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + end = bam_endpos(b1); + kputw(b2->core.pos - end, str); + kputc('T', str); + kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + + uint8_t* data; + if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data); + if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data); + + bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s); +} + +/* + * What This Program is Supposed To Do: + * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted + * alignment. + * + * How We Handle Input + * + * Secondary and supplementary Reads: + * -write to output unchanged + * All Reads: + * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag + * single Reads: + * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0, + * tid = -1 + * -clear bad flags (PAIRED, MREVERSE, PROPER_PAIR) + * -set mpos = 0 (1 based), mtid = -1 and isize = 0 + * -write to output + * Paired Reads: + * -if read is unmapped and mate is not, set pos and tid to equal that of mate + * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid + * -recalculate ISIZE if possible, otherwise set it to 0 + * -optionally clear PROPER_PAIR flag from reads where mapping or orientation + * indicate this is not possible (Illumina orientation only) + * -calculate ct and apply to lowest positioned read + * -write to output + * Limitations + * -Does not handle tandem reads + * -Should mark supplementary reads the same as primary. + * Notes + * -CT definition appears to be something else in spec, this was in here before + * I started tampering with it, anyone know what is going on here? To work + * around this I have demoted the CT this tool generates to ct. + */ + +static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) { + if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) { + // Set unmapped read's RNAME and POS to those of its mapped mate + // (recommended best practice, ensures if coord sort will be together) + dest->core.tid = src->core.tid; + dest->core.pos = src->core.pos; + } +} + +static void sync_mate_inner(bam1_t* src, bam1_t* dest) +{ + // sync mate pos information + dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos; + // sync flag info + if (src->core.flag&BAM_FREVERSE) + dest->core.flag |= BAM_FMREVERSE; + else + dest->core.flag &= ~BAM_FMREVERSE; + if (src->core.flag & BAM_FUNMAP) { + dest->core.flag |= BAM_FMUNMAP; + } +} + +// Is it plausible that these reads are properly paired? +// Can't really give definitive answer without checking isize +static bool plausibly_properly_paired(bam1_t* a, bam1_t* b) +{ + if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false; + assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly + + if (a->core.tid != b->core.tid) return false; + + bam1_t* first = a; + bam1_t* second = b; + hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos; + hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos; + if (a_pos > b_pos) { + first = b; + second = a; + } else { + first = a; + second = b; + } + + if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE)) + return true; + else + return false; +} + +// Returns 0 on success, -1 on failure. +static int bam_format_cigar(const bam1_t* b, kstring_t* str) +{ + // An empty cigar is a special case return "*" rather than "" + if (b->core.n_cigar == 0) { + return (kputc('*', str) == EOF) ? -1 : 0; + } + + const uint32_t *cigar = bam_get_cigar(b); + uint32_t i; + + for (i = 0; i < b->core.n_cigar; ++i) { + if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1; + if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1; + } + + return 0; +} + +// Returns 0 on success, -1 on failure. +static int sync_mq_mc(bam1_t* src, bam1_t* dest) +{ + if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped + // Copy Mate Mapping Quality + uint32_t mq = src->core.qual; + uint8_t* data; + if ((data = bam_aux_get(dest,"MQ")) != NULL) { + bam_aux_del(dest, data); + } + + bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq); + } + // Copy mate cigar if either read is mapped + if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) { + uint8_t* data_mc; + if ((data_mc = bam_aux_get(dest,"MC")) != NULL) { + bam_aux_del(dest, data_mc); + } + + // Convert cigar to string + kstring_t mc = { 0, 0, NULL }; + if (bam_format_cigar(src, &mc) < 0) return -1; + + bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc)); + free(mc.s); + } + return 0; +} + +// Copy flags. +// Returns 0 on success, -1 on failure. +static int sync_mate(bam1_t* a, bam1_t* b) +{ + sync_unmapped_pos_inner(a,b); + sync_unmapped_pos_inner(b,a); + sync_mate_inner(a,b); + sync_mate_inner(b,a); + if (sync_mq_mc(a,b) < 0) return -1; + if (sync_mq_mc(b,a) < 0) return -1; + return 0; +} + + +static uint32_t calc_mate_score(bam1_t *b) +{ + uint32_t score = 0; + uint8_t *qual = bam_get_qual(b); + int i; + + for (i = 0; i < b->core.l_qseq; i++) { + if (qual[i] >= MD_MIN_QUALITY) score += qual[i]; + } + + return score; +} + + +static int add_mate_score(bam1_t *src, bam1_t *dest) +{ + uint8_t *data_ms; + uint32_t mate_score = calc_mate_score(src); + + if ((data_ms = bam_aux_get(dest, "ms")) != NULL) { + bam_aux_del(dest, data_ms); + } + + if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) { + return -1; + } + + return 0; +} + +// Completely delete the CIGAR field +static void clear_cigar(bam1_t *b) { + memmove(bam_get_cigar(b), bam_get_seq(b), + b->data + b->l_data - bam_get_seq(b)); + b->l_data -= 4*b->core.n_cigar; + b->core.n_cigar = 0; +} + +// Trim a CIGAR field to end on reference position "end". Remaining bases +// are turned to soft clips. +static int bam_trim(bam1_t *b, hts_pos_t end) { + hts_pos_t pos = b->core.pos; + int n_cigar = b->core.n_cigar, i; + uint32_t new_cigar_a[1024]; + uint32_t *new_cigar = new_cigar_a; + uint32_t *cigar = bam_get_cigar(b); + + // Find end of alignment or end of ref + int op = 0, oplen = 0; + for (i = 0; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (!(bam_cigar_type(op) & 2)) + continue; + pos += oplen; + if (pos > end) + break; + } + + if (i == n_cigar) + // looks fine already + return 0; + + int old_i = i, j = 0; + // At worst we grow by 1 element (eg 100M -> 70M30S) + if (n_cigar-i >= 1024-1) { + new_cigar = malloc(4*(n_cigar-i+1)); + if (!new_cigar) + return -1; + } + + // We fill out to new_cigar from here on. + if (pos-oplen < end) { + // Partial CIGAR op? Split existing tag. + cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op); + new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP); + } else if (pos > end) { + // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0 + b->core.flag |= BAM_FUNMAP; + b->core.flag &= ~BAM_FPROPER_PAIR; + } else { + // CIGAR op started on the trim junction + new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP); + } + + // Replace trailing elements. + for (i++; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (op == BAM_CHARD_CLIP) { + new_cigar[j++] = cigar[i]; + } else { + new_cigar[j-1] = + bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen, + BAM_CSOFT_CLIP); + } + } + + // We now have cigar[0..old_i-1] for existing CIGAR + // and new_cigar[0..j-1] for new CIGAR trailing component. + + if (old_i+j == n_cigar) { + // Fits and no data move needed + memcpy(&cigar[old_i], new_cigar, j*4); + } else { + uint8_t *seq_old = bam_get_seq(b); + uint8_t *aux_end = b->data + b->l_data; + int nshift; + if (old_i+j < n_cigar) { + // Smaller, and can move data down + nshift = -4*(n_cigar - (old_i+j)); + } else { + // Bigger, so grow BAM and move data up + nshift = 4*(old_i+j - n_cigar); + // FIXME: make htslib's sam_realloc_bam_data public + if (b->l_data + nshift > b->m_data) { + uint8_t *new_data = realloc(b->data, b->l_data + nshift); + if (!new_data) { + if (new_cigar != new_cigar_a) + free(new_cigar); + return -1; + } + b->m_data = b->l_data + nshift; + if (b->data != new_data) { + b->data = new_data; + seq_old = bam_get_seq(b); + aux_end = b->data + b->l_data; + cigar = bam_get_cigar(b); + } + } + } + memmove(seq_old+nshift, seq_old, aux_end - seq_old); + b->l_data += nshift; + memcpy(&cigar[old_i], new_cigar, j*4); + b->core.n_cigar = old_i+j; + } + + if (new_cigar != new_cigar_a) + free(new_cigar); + + return 0; +} + +// Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux" +// keywords for the bam sanitizer. +int bam_sanitize_options(const char *str) { + int opt = 0; + + while (str && *str) { + const char *str_start; + while(*str && *str == ',') + str++; + + for (str_start = str; *str && *str != ','; str++); + int len = str - str_start; + if (strncmp(str_start, "all", 3) == 0 || *str_start == '*') + opt = FIX_ALL; + else if (strncmp(str_start, "none", 4) == 0 || + strncmp(str_start, "off", 3) == 0) + opt = 0; + else if (strncmp(str_start, "on", 2) == 0) + // default for position sorted data + opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX; + else if (strncmp(str_start, "pos", 3) == 0) + opt |= FIX_POS; + else if (strncmp(str_start, "mqual", 5) == 0) + opt |= FIX_MQUAL; + else if (strncmp(str_start, "unmap", 5) == 0) + opt |= FIX_UNMAP; + else if (strncmp(str_start, "cigar", 5) == 0) + opt |= FIX_CIGAR; + else if (strncmp(str_start, "aux", 3) == 0) + opt |= FIX_AUX; + else { + print_error("sanitize", "Unrecognised keyword %.*s\n", + len, str_start); + return -1; + } + } + + return opt; +} + +int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) { + if ((flags & FIX_POS) && b->core.tid < 0) { + // RNAME * => pos 0. NB can break alignment chr/pos sort order + b->core.pos = -1; + if (flags & FIX_UNMAP) + b->core.flag |= BAM_FUNMAP; + } + + if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) { + // Mapped => unmapped correction + if (b->core.pos < 0 && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + } else { + hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid); + if (b->core.pos >= rlen && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + if (flags & FIX_POS) + b->core.tid = b->core.pos = -1; + } else if ((cur_end = bam_endpos(b)) > rlen) { + if (bam_trim(b, rlen) < 0) + return -1; + } + } + } + + if (b->core.flag & BAM_FUNMAP) { + // Unmapped -> cigar/qual correctoins + if ((flags & FIX_CIGAR) && b->core.n_cigar > 0) + clear_cigar(b); + + if (flags & FIX_MQUAL) + b->core.qual = 0; + + // Remove NM, MD, CG, SM tags. + if (flags & FIX_AUX) { + uint8_t *from = bam_aux_first(b); + uint8_t *end = b->data + b->l_data; + uint8_t *to = from ? from-2 : end; + +#define XTAG(a) (((a)[0]<<8) + (a)[1]) + while (from) { + uint8_t *next = bam_aux_next(b, from); + if (!next && errno != ENOENT) + return -1; + + // Keep tag unless one of a specific set. + // NB "to" always points to an aux tag start, while + // "from" is after key. + from -= 2; + int key = (int)from[0]<<8 | from[1]; + if (key != XTAG("NM") && key != XTAG("MD") && + key != XTAG("CG") && key != XTAG("SM")) { + ptrdiff_t len = (next ? next-2 : end) - from; + if (from != to) + memmove(to, from, len); + to += len; + } + from = next; + } + b->l_data = to - b->data; + } + } + + return 0; +} + +// currently, this function ONLY works if each read has one hit +static int bam_mating_core(samFile *in, samFile *out, int remove_reads, + int proper_pair_check, int add_ct, + int do_mate_scoring, char *arg_list, int no_pg, + int sanitize_flags) +{ + sam_hdr_t *header; + bam1_t *b[2] = { NULL, NULL }; + int curr, has_prev, result; + hts_pos_t pre_end = 0, cur_end = 0; + kstring_t str = KS_INITIALIZE; + + header = sam_hdr_read(in); + if (header == NULL) { + fprintf(stderr, "[bam_mating_core] ERROR: Couldn't read header\n"); + return 1; + } + + // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted. + if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) { + fprintf(stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n"); + goto fail; + } + ks_free(&str); + + if (!no_pg && sam_hdr_add_pg(header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto fail; + + if (sam_hdr_write(out, header) < 0) goto write_fail; + + b[0] = bam_init1(); + b[1] = bam_init1(); + curr = 0; has_prev = 0; + while ((result = sam_read1(in, header, b[curr])) >= 0) { + bam1_t *cur = b[curr], *pre = b[1-curr]; + if (bam_sanitize(header, cur, sanitize_flags) < 0) + goto fail; + if (cur->core.flag & BAM_FSECONDARY) + { + if ( !remove_reads ) { + if (sam_write1(out, header, cur) < 0) goto write_fail; + } + continue; // skip secondary alignments + } + if (cur->core.flag & BAM_FSUPPLEMENTARY) + { + if (sam_write1(out, header, cur) < 0) goto write_fail; + continue; // pass supplementary alignments through unchanged (TODO:make them match read they came from) + } + if ((cur->core.flag&BAM_FUNMAP) == 0) // If mapped calculate end + { + cur_end = bam_endpos(cur); + } + + if (has_prev) { // do we have a pair of reads to examine? + if (strcmp(bam_get_qname(cur), bam_get_qname(pre)) == 0) { // identical pair name + pre->core.flag |= BAM_FPAIRED; + cur->core.flag |= BAM_FPAIRED; + if (sync_mate(pre, cur)) goto fail; + + if (pre->core.tid == cur->core.tid && !(cur->core.flag&(BAM_FUNMAP|BAM_FMUNMAP)) + && !(pre->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))) // if safe set TLEN/ISIZE + { + hts_pos_t cur5, pre5; + cur5 = (cur->core.flag&BAM_FREVERSE)? cur_end : cur->core.pos; + pre5 = (pre->core.flag&BAM_FREVERSE)? pre_end : pre->core.pos; + cur->core.isize = pre5 - cur5; pre->core.isize = cur5 - pre5; + } else cur->core.isize = pre->core.isize = 0; + if (add_ct) bam_template_cigar(pre, cur, &str); + // TODO: Add code to properly check if read is in a proper pair based on ISIZE distribution + if (proper_pair_check && !plausibly_properly_paired(pre,cur)) { + pre->core.flag &= ~BAM_FPROPER_PAIR; + cur->core.flag &= ~BAM_FPROPER_PAIR; + } + + if (do_mate_scoring) { + if ((add_mate_score(pre, cur) == -1) || (add_mate_score(cur, pre) == -1)) { + fprintf(stderr, "[bam_mating_core] ERROR: unable to add mate score.\n"); + goto fail; + } + } + + // Write out result + if ( !remove_reads ) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + if (sam_write1(out, header, cur) < 0) goto write_fail; + } else { + // If we have to remove reads make sure we do it in a way that doesn't create orphans with bad flags + if(pre->core.flag&BAM_FUNMAP) cur->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if(cur->core.flag&BAM_FUNMAP) pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if(!(pre->core.flag&BAM_FUNMAP)) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + if(!(cur->core.flag&BAM_FUNMAP)) { + if (sam_write1(out, header, cur) < 0) goto write_fail; + } + } + has_prev = 0; + } else { // unpaired? clear bad info and write it out + pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0; + pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if ( !remove_reads || !(pre->core.flag&BAM_FUNMAP) ) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + } + } else has_prev = 1; + curr = 1 - curr; + pre_end = cur_end; + } + if (result < -1) goto read_fail; + if (has_prev && !remove_reads) { // If we still have a BAM in the buffer it must be unpaired + bam1_t *pre = b[1-curr]; + if (pre->core.tid < 0 || pre->core.pos < 0 || pre->core.flag&BAM_FUNMAP) { // If unmapped + pre->core.flag |= BAM_FUNMAP; + pre->core.tid = -1; + pre->core.pos = -1; + } + pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0; + pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + sam_hdr_destroy(header); + bam_destroy1(b[0]); + bam_destroy1(b[1]); + ks_free(&str); + return 0; + + read_fail: + print_error("fixmate", "Couldn't read from input file"); + goto fail; + + write_fail: + print_error_errno("fixmate", "Couldn't write to output file"); + fail: + sam_hdr_destroy(header); + bam_destroy1(b[0]); + bam_destroy1(b[1]); + ks_free(&str); + return 1; +} + +void usage(FILE* where) +{ + fprintf(where, +"Usage: samtools fixmate \n" +"Options:\n" +" -r Remove unmapped reads and secondary alignments\n" +" -p Disable FR proper pair check\n" +" -c Add template cigar ct tag\n" +" -m Add mate score tag\n" +" -u Uncompressed output\n" +" -z, --sanitize FLAG[,FLAG]\n" +" Sanitize alignment fields [defaults to all types]\n" +" --no-PG do not add a PG line\n"); + + sam_global_opt_help(where, "-.O..@-."); + + fprintf(where, +"\n" +"As elsewhere in samtools, use '-' as the filename for stdin/stdout. The input\n" +"file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n" +"input is not accepted.\n"); +} + +int bam_mating(int argc, char *argv[]) +{ + htsThreadPool p = {NULL, 0}; + samFile *in = NULL, *out = NULL; + int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1, + mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + char wmode[4] = {'w', 'b', 0, 0}; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + char *arg_list = NULL; + + // parse args + if (argc == 1) { usage(stdout); return 0; } + while ((c = getopt_long(argc, argv, "rpcmO:@:uz:", lopts, NULL)) >= 0) { + switch (c) { + case 'r': remove_reads = 1; break; + case 'p': proper_pair_check = 0; break; + case 'c': add_ct = 1; break; + case 'm': mate_score = 1; break; + case 'u': wmode[2] = '0'; break; + case 1: no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage(stderr); goto fail; + case 'z': + if ((sanitize_flags = bam_sanitize_options(optarg)) < 0) + exit(1); + break; + } + } + if (optind+1 >= argc) { usage(stderr); goto fail; } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) + goto fail; + + // init + if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) { + print_error_errno("fixmate", "cannot open input file"); + goto fail; + } + sam_open_mode(wmode+1, argv[optind+1], NULL); + if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) { + print_error_errno("fixmate", "cannot open output file"); + goto fail; + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(stderr, "Error creating thread pool\n"); + goto fail; + } + hts_set_opt(in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(out, HTS_OPT_THREAD_POOL, &p); + } + + // run + res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct, + mate_score, arg_list, no_pg, sanitize_flags); + + // cleanup + sam_close(in); + if (sam_close(out) < 0) { + fprintf(stderr, "[bam_mating] error while closing output file\n"); + res = 1; + } + + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return res; + + fail: + if (in) sam_close(in); + if (out) sam_close(out); + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return 1; +} + + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..1796f6e9fb2e3e374787ae33136ea8a357c37917 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_mate.c.pysam.c @@ -0,0 +1,730 @@ +#include "samtools.pysam.h" + +/* bam_mate.c -- fix mate pairing information and clean up flags. + + Copyright (C) 2009, 2011-2017, 2019, 2022 Genome Research Ltd. + Portions copyright (C) 2011 Broad Institute. + Portions copyright (C) 2012 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "samtools.h" + + +#define MD_MIN_QUALITY 15 + +/* + * This function calculates ct tag for two bams, it assumes they are from the same template and + * writes the tag to the first read in position terms. + */ +static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str) +{ + bam1_t *swap; + int i; + hts_pos_t end; + uint32_t *cigar; + str->l = 0; + 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 + if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate + kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + end = bam_endpos(b1); + kputw(b2->core.pos - end, str); + kputc('T', str); + kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index + kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand + for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) { + kputw(bam_cigar_oplen(cigar[i]), str); + kputc(bam_cigar_opchr(cigar[i]), str); + } + + uint8_t* data; + if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data); + if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data); + + bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s); +} + +/* + * What This Program is Supposed To Do: + * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted + * alignment. + * + * How We Handle Input + * + * Secondary and supplementary Reads: + * -write to output unchanged + * All Reads: + * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag + * single Reads: + * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0, + * tid = -1 + * -clear bad flags (PAIRED, MREVERSE, PROPER_PAIR) + * -set mpos = 0 (1 based), mtid = -1 and isize = 0 + * -write to output + * Paired Reads: + * -if read is unmapped and mate is not, set pos and tid to equal that of mate + * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid + * -recalculate ISIZE if possible, otherwise set it to 0 + * -optionally clear PROPER_PAIR flag from reads where mapping or orientation + * indicate this is not possible (Illumina orientation only) + * -calculate ct and apply to lowest positioned read + * -write to output + * Limitations + * -Does not handle tandem reads + * -Should mark supplementary reads the same as primary. + * Notes + * -CT definition appears to be something else in spec, this was in here before + * I started tampering with it, anyone know what is going on here? To work + * around this I have demoted the CT this tool generates to ct. + */ + +static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) { + if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) { + // Set unmapped read's RNAME and POS to those of its mapped mate + // (recommended best practice, ensures if coord sort will be together) + dest->core.tid = src->core.tid; + dest->core.pos = src->core.pos; + } +} + +static void sync_mate_inner(bam1_t* src, bam1_t* dest) +{ + // sync mate pos information + dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos; + // sync flag info + if (src->core.flag&BAM_FREVERSE) + dest->core.flag |= BAM_FMREVERSE; + else + dest->core.flag &= ~BAM_FMREVERSE; + if (src->core.flag & BAM_FUNMAP) { + dest->core.flag |= BAM_FMUNMAP; + } +} + +// Is it plausible that these reads are properly paired? +// Can't really give definitive answer without checking isize +static bool plausibly_properly_paired(bam1_t* a, bam1_t* b) +{ + if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false; + assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly + + if (a->core.tid != b->core.tid) return false; + + bam1_t* first = a; + bam1_t* second = b; + hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos; + hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos; + if (a_pos > b_pos) { + first = b; + second = a; + } else { + first = a; + second = b; + } + + if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE)) + return true; + else + return false; +} + +// Returns 0 on success, -1 on failure. +static int bam_format_cigar(const bam1_t* b, kstring_t* str) +{ + // An empty cigar is a special case return "*" rather than "" + if (b->core.n_cigar == 0) { + return (kputc('*', str) == EOF) ? -1 : 0; + } + + const uint32_t *cigar = bam_get_cigar(b); + uint32_t i; + + for (i = 0; i < b->core.n_cigar; ++i) { + if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1; + if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1; + } + + return 0; +} + +// Returns 0 on success, -1 on failure. +static int sync_mq_mc(bam1_t* src, bam1_t* dest) +{ + if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped + // Copy Mate Mapping Quality + uint32_t mq = src->core.qual; + uint8_t* data; + if ((data = bam_aux_get(dest,"MQ")) != NULL) { + bam_aux_del(dest, data); + } + + bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq); + } + // Copy mate cigar if either read is mapped + if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) { + uint8_t* data_mc; + if ((data_mc = bam_aux_get(dest,"MC")) != NULL) { + bam_aux_del(dest, data_mc); + } + + // Convert cigar to string + kstring_t mc = { 0, 0, NULL }; + if (bam_format_cigar(src, &mc) < 0) return -1; + + bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc)); + free(mc.s); + } + return 0; +} + +// Copy flags. +// Returns 0 on success, -1 on failure. +static int sync_mate(bam1_t* a, bam1_t* b) +{ + sync_unmapped_pos_inner(a,b); + sync_unmapped_pos_inner(b,a); + sync_mate_inner(a,b); + sync_mate_inner(b,a); + if (sync_mq_mc(a,b) < 0) return -1; + if (sync_mq_mc(b,a) < 0) return -1; + return 0; +} + + +static uint32_t calc_mate_score(bam1_t *b) +{ + uint32_t score = 0; + uint8_t *qual = bam_get_qual(b); + int i; + + for (i = 0; i < b->core.l_qseq; i++) { + if (qual[i] >= MD_MIN_QUALITY) score += qual[i]; + } + + return score; +} + + +static int add_mate_score(bam1_t *src, bam1_t *dest) +{ + uint8_t *data_ms; + uint32_t mate_score = calc_mate_score(src); + + if ((data_ms = bam_aux_get(dest, "ms")) != NULL) { + bam_aux_del(dest, data_ms); + } + + if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) { + return -1; + } + + return 0; +} + +// Completely delete the CIGAR field +static void clear_cigar(bam1_t *b) { + memmove(bam_get_cigar(b), bam_get_seq(b), + b->data + b->l_data - bam_get_seq(b)); + b->l_data -= 4*b->core.n_cigar; + b->core.n_cigar = 0; +} + +// Trim a CIGAR field to end on reference position "end". Remaining bases +// are turned to soft clips. +static int bam_trim(bam1_t *b, hts_pos_t end) { + hts_pos_t pos = b->core.pos; + int n_cigar = b->core.n_cigar, i; + uint32_t new_cigar_a[1024]; + uint32_t *new_cigar = new_cigar_a; + uint32_t *cigar = bam_get_cigar(b); + + // Find end of alignment or end of ref + int op = 0, oplen = 0; + for (i = 0; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (!(bam_cigar_type(op) & 2)) + continue; + pos += oplen; + if (pos > end) + break; + } + + if (i == n_cigar) + // looks fine already + return 0; + + int old_i = i, j = 0; + // At worst we grow by 1 element (eg 100M -> 70M30S) + if (n_cigar-i >= 1024-1) { + new_cigar = malloc(4*(n_cigar-i+1)); + if (!new_cigar) + return -1; + } + + // We fill out to new_cigar from here on. + if (pos-oplen < end) { + // Partial CIGAR op? Split existing tag. + cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op); + new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP); + } else if (pos > end) { + // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0 + b->core.flag |= BAM_FUNMAP; + b->core.flag &= ~BAM_FPROPER_PAIR; + } else { + // CIGAR op started on the trim junction + new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP); + } + + // Replace trailing elements. + for (i++; i < n_cigar; i++) { + op = bam_cigar_op(cigar[i]); + oplen = bam_cigar_oplen(cigar[i]); + if (op == BAM_CHARD_CLIP) { + new_cigar[j++] = cigar[i]; + } else { + new_cigar[j-1] = + bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen, + BAM_CSOFT_CLIP); + } + } + + // We now have cigar[0..old_i-1] for existing CIGAR + // and new_cigar[0..j-1] for new CIGAR trailing component. + + if (old_i+j == n_cigar) { + // Fits and no data move needed + memcpy(&cigar[old_i], new_cigar, j*4); + } else { + uint8_t *seq_old = bam_get_seq(b); + uint8_t *aux_end = b->data + b->l_data; + int nshift; + if (old_i+j < n_cigar) { + // Smaller, and can move data down + nshift = -4*(n_cigar - (old_i+j)); + } else { + // Bigger, so grow BAM and move data up + nshift = 4*(old_i+j - n_cigar); + // FIXME: make htslib's sam_realloc_bam_data public + if (b->l_data + nshift > b->m_data) { + uint8_t *new_data = realloc(b->data, b->l_data + nshift); + if (!new_data) { + if (new_cigar != new_cigar_a) + free(new_cigar); + return -1; + } + b->m_data = b->l_data + nshift; + if (b->data != new_data) { + b->data = new_data; + seq_old = bam_get_seq(b); + aux_end = b->data + b->l_data; + cigar = bam_get_cigar(b); + } + } + } + memmove(seq_old+nshift, seq_old, aux_end - seq_old); + b->l_data += nshift; + memcpy(&cigar[old_i], new_cigar, j*4); + b->core.n_cigar = old_i+j; + } + + if (new_cigar != new_cigar_a) + free(new_cigar); + + return 0; +} + +// Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux" +// keywords for the bam sanitizer. +int bam_sanitize_options(const char *str) { + int opt = 0; + + while (str && *str) { + const char *str_start; + while(*str && *str == ',') + str++; + + for (str_start = str; *str && *str != ','; str++); + int len = str - str_start; + if (strncmp(str_start, "all", 3) == 0 || *str_start == '*') + opt = FIX_ALL; + else if (strncmp(str_start, "none", 4) == 0 || + strncmp(str_start, "off", 3) == 0) + opt = 0; + else if (strncmp(str_start, "on", 2) == 0) + // default for position sorted data + opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX; + else if (strncmp(str_start, "pos", 3) == 0) + opt |= FIX_POS; + else if (strncmp(str_start, "mqual", 5) == 0) + opt |= FIX_MQUAL; + else if (strncmp(str_start, "unmap", 5) == 0) + opt |= FIX_UNMAP; + else if (strncmp(str_start, "cigar", 5) == 0) + opt |= FIX_CIGAR; + else if (strncmp(str_start, "aux", 3) == 0) + opt |= FIX_AUX; + else { + print_error("sanitize", "Unrecognised keyword %.*s\n", + len, str_start); + return -1; + } + } + + return opt; +} + +int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) { + if ((flags & FIX_POS) && b->core.tid < 0) { + // RNAME * => pos 0. NB can break alignment chr/pos sort order + b->core.pos = -1; + if (flags & FIX_UNMAP) + b->core.flag |= BAM_FUNMAP; + } + + if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) { + // Mapped => unmapped correction + if (b->core.pos < 0 && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + } else { + hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid); + if (b->core.pos >= rlen && (flags & FIX_UNMAP)) { + b->core.flag |= BAM_FUNMAP; + if (flags & FIX_POS) + b->core.tid = b->core.pos = -1; + } else if ((cur_end = bam_endpos(b)) > rlen) { + if (bam_trim(b, rlen) < 0) + return -1; + } + } + } + + if (b->core.flag & BAM_FUNMAP) { + // Unmapped -> cigar/qual correctoins + if ((flags & FIX_CIGAR) && b->core.n_cigar > 0) + clear_cigar(b); + + if (flags & FIX_MQUAL) + b->core.qual = 0; + + // Remove NM, MD, CG, SM tags. + if (flags & FIX_AUX) { + uint8_t *from = bam_aux_first(b); + uint8_t *end = b->data + b->l_data; + uint8_t *to = from ? from-2 : end; + +#define XTAG(a) (((a)[0]<<8) + (a)[1]) + while (from) { + uint8_t *next = bam_aux_next(b, from); + if (!next && errno != ENOENT) + return -1; + + // Keep tag unless one of a specific set. + // NB "to" always points to an aux tag start, while + // "from" is after key. + from -= 2; + int key = (int)from[0]<<8 | from[1]; + if (key != XTAG("NM") && key != XTAG("MD") && + key != XTAG("CG") && key != XTAG("SM")) { + ptrdiff_t len = (next ? next-2 : end) - from; + if (from != to) + memmove(to, from, len); + to += len; + } + from = next; + } + b->l_data = to - b->data; + } + } + + return 0; +} + +// currently, this function ONLY works if each read has one hit +static int bam_mating_core(samFile *in, samFile *out, int remove_reads, + int proper_pair_check, int add_ct, + int do_mate_scoring, char *arg_list, int no_pg, + int sanitize_flags) +{ + sam_hdr_t *header; + bam1_t *b[2] = { NULL, NULL }; + int curr, has_prev, result; + hts_pos_t pre_end = 0, cur_end = 0; + kstring_t str = KS_INITIALIZE; + + header = sam_hdr_read(in); + if (header == NULL) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: Couldn't read header\n"); + return 1; + } + + // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted. + if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n"); + goto fail; + } + ks_free(&str); + + if (!no_pg && sam_hdr_add_pg(header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto fail; + + if (sam_hdr_write(out, header) < 0) goto write_fail; + + b[0] = bam_init1(); + b[1] = bam_init1(); + curr = 0; has_prev = 0; + while ((result = sam_read1(in, header, b[curr])) >= 0) { + bam1_t *cur = b[curr], *pre = b[1-curr]; + if (bam_sanitize(header, cur, sanitize_flags) < 0) + goto fail; + if (cur->core.flag & BAM_FSECONDARY) + { + if ( !remove_reads ) { + if (sam_write1(out, header, cur) < 0) goto write_fail; + } + continue; // skip secondary alignments + } + if (cur->core.flag & BAM_FSUPPLEMENTARY) + { + if (sam_write1(out, header, cur) < 0) goto write_fail; + continue; // pass supplementary alignments through unchanged (TODO:make them match read they came from) + } + if ((cur->core.flag&BAM_FUNMAP) == 0) // If mapped calculate end + { + cur_end = bam_endpos(cur); + } + + if (has_prev) { // do we have a pair of reads to examine? + if (strcmp(bam_get_qname(cur), bam_get_qname(pre)) == 0) { // identical pair name + pre->core.flag |= BAM_FPAIRED; + cur->core.flag |= BAM_FPAIRED; + if (sync_mate(pre, cur)) goto fail; + + if (pre->core.tid == cur->core.tid && !(cur->core.flag&(BAM_FUNMAP|BAM_FMUNMAP)) + && !(pre->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))) // if safe set TLEN/ISIZE + { + hts_pos_t cur5, pre5; + cur5 = (cur->core.flag&BAM_FREVERSE)? cur_end : cur->core.pos; + pre5 = (pre->core.flag&BAM_FREVERSE)? pre_end : pre->core.pos; + cur->core.isize = pre5 - cur5; pre->core.isize = cur5 - pre5; + } else cur->core.isize = pre->core.isize = 0; + if (add_ct) bam_template_cigar(pre, cur, &str); + // TODO: Add code to properly check if read is in a proper pair based on ISIZE distribution + if (proper_pair_check && !plausibly_properly_paired(pre,cur)) { + pre->core.flag &= ~BAM_FPROPER_PAIR; + cur->core.flag &= ~BAM_FPROPER_PAIR; + } + + if (do_mate_scoring) { + if ((add_mate_score(pre, cur) == -1) || (add_mate_score(cur, pre) == -1)) { + fprintf(samtools_stderr, "[bam_mating_core] ERROR: unable to add mate score.\n"); + goto fail; + } + } + + // Write out result + if ( !remove_reads ) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + if (sam_write1(out, header, cur) < 0) goto write_fail; + } else { + // If we have to remove reads make sure we do it in a way that doesn't create orphans with bad flags + if(pre->core.flag&BAM_FUNMAP) cur->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if(cur->core.flag&BAM_FUNMAP) pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if(!(pre->core.flag&BAM_FUNMAP)) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + if(!(cur->core.flag&BAM_FUNMAP)) { + if (sam_write1(out, header, cur) < 0) goto write_fail; + } + } + has_prev = 0; + } else { // unpaired? clear bad info and write it out + pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0; + pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + if ( !remove_reads || !(pre->core.flag&BAM_FUNMAP) ) { + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + } + } else has_prev = 1; + curr = 1 - curr; + pre_end = cur_end; + } + if (result < -1) goto read_fail; + if (has_prev && !remove_reads) { // If we still have a BAM in the buffer it must be unpaired + bam1_t *pre = b[1-curr]; + if (pre->core.tid < 0 || pre->core.pos < 0 || pre->core.flag&BAM_FUNMAP) { // If unmapped + pre->core.flag |= BAM_FUNMAP; + pre->core.tid = -1; + pre->core.pos = -1; + } + pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0; + pre->core.flag &= ~(BAM_FPAIRED|BAM_FMREVERSE|BAM_FPROPER_PAIR); + + if (sam_write1(out, header, pre) < 0) goto write_fail; + } + sam_hdr_destroy(header); + bam_destroy1(b[0]); + bam_destroy1(b[1]); + ks_free(&str); + return 0; + + read_fail: + print_error("fixmate", "Couldn't read from input file"); + goto fail; + + write_fail: + print_error_errno("fixmate", "Couldn't write to output file"); + fail: + sam_hdr_destroy(header); + bam_destroy1(b[0]); + bam_destroy1(b[1]); + ks_free(&str); + return 1; +} + +void usage(FILE* where) +{ + fprintf(where, +"Usage: samtools fixmate \n" +"Options:\n" +" -r Remove unmapped reads and secondary alignments\n" +" -p Disable FR proper pair check\n" +" -c Add template cigar ct tag\n" +" -m Add mate score tag\n" +" -u Uncompressed output\n" +" -z, --sanitize FLAG[,FLAG]\n" +" Sanitize alignment fields [defaults to all types]\n" +" --no-PG do not add a PG line\n"); + + sam_global_opt_help(where, "-.O..@-."); + + fprintf(where, +"\n" +"As elsewhere in samtools, use '-' as the filename for stdin/samtools_stdout. The input\n" +"file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n" +"input is not accepted.\n"); +} + +int bam_mating(int argc, char *argv[]) +{ + htsThreadPool p = {NULL, 0}; + samFile *in = NULL, *out = NULL; + int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1, + mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + char wmode[4] = {'w', 'b', 0, 0}; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + char *arg_list = NULL; + + // parse args + if (argc == 1) { usage(samtools_stdout); return 0; } + while ((c = getopt_long(argc, argv, "rpcmO:@:uz:", lopts, NULL)) >= 0) { + switch (c) { + case 'r': remove_reads = 1; break; + case 'p': proper_pair_check = 0; break; + case 'c': add_ct = 1; break; + case 'm': mate_score = 1; break; + case 'u': wmode[2] = '0'; break; + case 1: no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage(samtools_stderr); goto fail; + case 'z': + if ((sanitize_flags = bam_sanitize_options(optarg)) < 0) + samtools_exit(1); + break; + } + } + if (optind+1 >= argc) { usage(samtools_stderr); goto fail; } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) + goto fail; + + // init + if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) { + print_error_errno("fixmate", "cannot open input file"); + goto fail; + } + sam_open_mode(wmode+1, argv[optind+1], NULL); + if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) { + print_error_errno("fixmate", "cannot open output file"); + goto fail; + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(samtools_stderr, "Error creating thread pool\n"); + goto fail; + } + hts_set_opt(in, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(out, HTS_OPT_THREAD_POOL, &p); + } + + // run + res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct, + mate_score, arg_list, no_pg, sanitize_flags); + + // cleanup + sam_close(in); + if (sam_close(out) < 0) { + fprintf(samtools_stderr, "[bam_mating] error while closing output file\n"); + res = 1; + } + + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return res; + + fail: + if (in) sam_close(in); + if (out) sam_close(out); + if (p.pool) hts_tpool_destroy(p.pool); + free(arg_list); + sam_global_args_free(&ga); + return 1; +} + + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_md.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_md.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..795eccb21c5074892b692c924f475cb314cad60c --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_md.c.pysam.c @@ -0,0 +1,534 @@ +#include "samtools.pysam.h" + +/* bam_md.c -- calmd subcommand. + + Copyright (C) 2009-2011, 2014-2015, 2019-2020, 2022 Genome Research Ltd. + Portions copyright (C) 2009-2011 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "htslib/faidx.h" +#include "htslib/sam.h" +#include "htslib/kstring.h" +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "samtools.h" + +#define USE_EQUAL 1 +#define DROP_TAG 2 +#define BIN_QUAL 4 +#define UPDATE_NM 8 +#define UPDATE_MD 16 +#define HASH_QNM 32 + +typedef struct cached_ref_entry { + char *ref; + hts_pos_t len; +} cached_ref_entry; + +typedef struct ref_cache { + cached_ref_entry *refs; + char *last_ref; + hts_pos_t last_len; + int nref; + int last_tid; +} ref_cache; + +int bam_aux_drop_other(bam1_t *b, uint8_t *s); + +static int bam_fillmd1_core(const char *ref_name, bam1_t *b, char *ref, + hts_pos_t ref_len, int flag, int max_nm, + int quiet_mode, uint32_t *skipped) +{ + uint8_t *seq = bam_get_seq(b); + uint32_t *cigar = bam_get_cigar(b); + bam1_core_t *c = &b->core; + int i, qpos, matched = 0; + hts_pos_t rpos; + kstring_t str = KS_INITIALIZE; + int32_t old_nm_i = -1, nm = 0; + uint32_t err = 0; + + if (c->l_qseq == 0) { + if (!quiet_mode) { + if (ref_name) { + fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment " + "record for '%s' at %s:%"PRIhts_pos", skipped\n", + bam_get_qname(b), ref_name, c->pos + 1); + } else { + fprintf(samtools_stderr, "[bam_fillmd1] no sequence in alignment " + "record for '%s', skipped", bam_get_qname(b)); + } + } + if (skipped) (*skipped)++; + return 0; + } + + for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) { + int j, oplen = cigar[i]>>4, op = cigar[i]&0xf; + if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { + for (j = 0; j < oplen; ++j) { + int c1, c2, z = qpos + j; + if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0') + break; // out of bounds + c1 = bam_seqi(seq, z); + c2 = seq_nt16_table[(uint8_t)ref[rpos+j]]; + if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match + if (flag&USE_EQUAL) seq[z/2] &= (z&1)? 0xf0 : 0x0f; + ++matched; + } else { + err |= kputw(matched, &str) < 0; + err |= kputc(toupper(ref[rpos+j]), &str) < 0; + matched = 0; ++nm; + } + } + if (j < oplen) break; + rpos += oplen; qpos += oplen; + } else if (op == BAM_CDEL) { + err |= kputw(matched, &str) < 0; + err |= kputc('^', &str) < 0; + for (j = 0; j < oplen; ++j) { + if (rpos+j >= ref_len || ref[rpos+j] == '\0') break; + err |= kputc(toupper(ref[rpos+j]), &str) < 0; + } + matched = 0; + rpos += j; nm += j; + if (j < oplen) break; + } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) { + qpos += oplen; + if (op == BAM_CINS) nm += oplen; + } else if (op == BAM_CREF_SKIP) { + rpos += oplen; + } + } + err |= kputw(matched, &str) < 0; + if (err) { + print_error_errno("calmd", "Couldn't build new MD string"); + goto fail; + } + // apply max_nm + if (max_nm > 0 && nm >= max_nm) { + for (i = qpos = 0, rpos = c->pos; i < c->n_cigar; ++i) { + int j, oplen = cigar[i]>>4, op = cigar[i]&0xf; + if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { + for (j = 0; j < oplen; ++j) { + int c1, c2, z = qpos + j; + if (rpos+j >= ref_len || z >= c->l_qseq || ref[rpos+j] == '\0') + break; // out of bounds + c1 = bam_seqi(seq, z); + c2 = seq_nt16_table[(uint8_t)ref[rpos+j]]; + if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match + seq[z/2] |= (z&1)? 0x0f : 0xf0; + bam_get_qual(b)[z] = 0; + } + } + if (j < oplen) break; + rpos += oplen; qpos += oplen; + } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) rpos += oplen; + else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) qpos += oplen; + } + } + // update NM + if ((flag & UPDATE_NM) && !(c->flag & BAM_FUNMAP)) { + uint8_t *old_nm = bam_aux_get(b, "NM"); + if (old_nm) old_nm_i = bam_aux2i(old_nm); + if (!old_nm) { + if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0) + goto aux_fail; + } + else if (nm != old_nm_i) { + if (!quiet_mode) { + fprintf(samtools_stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam_get_qname(b), old_nm_i, nm); + } + if (bam_aux_del(b, old_nm) < 0) goto aux_fail; + if (bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm) < 0) + goto aux_fail; + } + } + // update MD + if ((flag & UPDATE_MD) && !(c->flag & BAM_FUNMAP)) { + uint8_t *old_md = bam_aux_get(b, "MD"); + if (!old_md) { + if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0) + goto aux_fail; + } else { + int is_diff = 0; + if (strlen((char*)old_md+1) == str.l) { + for (i = 0; i < str.l; ++i) + if (toupper(old_md[i+1]) != toupper(str.s[i])) + break; + if (i < str.l) is_diff = 1; + } else is_diff = 1; + if (is_diff) { + if (!quiet_mode) { + fprintf(samtools_stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam_get_qname(b), old_md+1, str.s); + } + if (bam_aux_del(b, old_md) < 0) goto aux_fail; + if (bam_aux_append(b, "MD", 'Z', str.l + 1, (uint8_t*)str.s) < 0) + goto aux_fail; + } + } + } + + // drop all tags but RG + if (flag&DROP_TAG) { + uint8_t *q = bam_aux_get(b, "RG"); + bam_aux_drop_other(b, q); + } + // reduce the resolution of base quality + if (flag&BIN_QUAL) { + uint8_t *qual = bam_get_qual(b); + for (i = 0; i < b->core.l_qseq; ++i) + if (qual[i] >= 3) qual[i] = qual[i]/10*10 + 7; + } + + free(str.s); + return 0; + + aux_fail: + if (errno == ENOMEM) { + print_error("calmd", "Couldn't add aux tag (too long)"); + } else if (errno == EINVAL) { + print_error("calmd", "Corrupt aux data"); + } else { + print_error_errno("calmd", "Couldn't add aux tag"); + } + fail: + free(str.s); + return -1; +} + +int bam_fillmd1(bam1_t *b, char *ref, int flag, int quiet_mode) +{ + return bam_fillmd1_core(NULL, b, ref, INT_MAX, flag, 0, quiet_mode, NULL); +} + +// Get a new reference sequence. +// For position-sorted inputs, the previous reference should never be +// needed again and can be discarded to save memory. For other orderings, +// references are stored in a cache in case they're required in the future. +// The caching mode is turned on if the requested tid is less than the last +// one used, indicating the file ordering doesn't match the sequence dictionary. +static int get_ref(faidx_t *fai, sam_hdr_t *header, ref_cache *cache, + int tid, char **ref_out, const char **ref_name_out, + hts_pos_t *len_out) +{ + char *ref = NULL; + const char *ref_name; + hts_pos_t len = 0; + + // This should only be called when tid changes + assert(tid != cache->last_tid); + + // Array lookup, should be fast + ref_name = sam_hdr_tid2name(header, tid); + *ref_name_out = ref_name; + + // Return a cached entry, if available + if (cache->refs && tid >= 0 && tid < cache->nref + && cache->refs[tid].ref) { + assert(cache->last_ref == NULL); + *ref_out = cache->refs[tid].ref; + *len_out = cache->refs[tid].len; + cache->last_tid = tid; + return 0; + } + + // Try to get the reference + if (ref_name) + ref = fai_fetch64(fai, ref_name, &len); + + if (!ref) { + // Historically, calmd doesn't worry too much about missing refs + *ref_out = NULL; + *len_out = 0; + return 0; + } + + if (!cache->refs && cache->last_tid > tid) { + // Going backwards throught the list of tids implies + // a non-position-ordered file, so turn on caching mode + cache->nref = sam_hdr_nref(header); + if (cache->nref < 0) { + print_error("calmd", "couldn't get number of refs from header"); + return -1; + } + if (cache->nref > 0) { + cache->refs = calloc(cache->nref, sizeof(cache->refs[0])); + if (!cache->refs) { + print_error_errno("calmd", + "couldn't allocate reference cache"); + return -1; + } + // Add the reference we already have as the first entry + if (cache->last_tid >= 0 && cache->last_tid < cache->nref) { + cache->refs[cache->last_tid].ref = cache->last_ref; + cache->refs[cache->last_tid].len = cache->last_len; + } else { + free(cache->last_ref); + } + cache->last_ref = NULL; + } + } + + if (cache->refs) { + assert(cache->last_ref == NULL); // Shouldn't be set when caching + // Add the new reference to the cache + if (tid >= 0 && tid < cache->nref) { + cache->refs[tid].ref = ref; + cache->refs[tid].len = len; + } + } else { + // Streaming mode - free the last ref and replace it with this one + free(cache->last_ref); + cache->last_ref = ref; + cache->last_len = len; + } + + *ref_out = ref; + *len_out = len; + cache->last_tid = tid; + return 0; +} + +static void refs_destroy(ref_cache *cache) { + if (cache->refs) { + int i; + assert(cache->last_ref == NULL); + for (i = 0; i < cache->nref; i++) + free(cache->refs[i].ref); + free(cache->refs); + } else { + free(cache->last_ref); + } +} + +int calmd_usage() { + fprintf(samtools_stderr, +"Usage: samtools calmd [-eubrAESQ] \n" +"Options:\n" +" -e change identical bases to '='\n" +" -u uncompressed BAM output (for piping)\n" +" -b compressed BAM output\n" +" -S ignored (input format is auto-detected)\n" +" -A modify the quality string\n" +" -Q use quiet mode to output less debug info to samtools_stdout\n" +" -r compute the BQ tag (without -A) or cap baseQ by BAQ (with -A)\n" +" -E extended BAQ for better sensitivity but lower specificity\n" +" --no-PG do not add a PG line\n"); + + sam_global_opt_help(samtools_stderr, "-....@-."); + return 1; +} + +int bam_fillmd(int argc, char *argv[]) +{ + int c, flt_flag, ret, is_bam_out, is_uncompressed, max_nm, is_realn, capQ, baq_flag, quiet_mode, no_pg = 0; + hts_pos_t len = 0; + htsThreadPool p = {NULL, 0}; + samFile *fp = NULL, *fpout = NULL; + sam_hdr_t *header = NULL; + faidx_t *fai = NULL; + char *ref = NULL, mode_w[8], *ref_file, *arg_list = NULL; + ref_cache refs = { NULL, NULL, 0, 0, -2 }; + const char *ref_name = NULL; + bam1_t *b = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + uint32_t skipped = 0; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0,'@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + flt_flag = UPDATE_NM | UPDATE_MD; + is_bam_out = is_uncompressed = is_realn = max_nm = capQ = baq_flag = quiet_mode = 0; + strcpy(mode_w, "w"); + while ((c = getopt_long(argc, argv, "EqQreuNhbSC:n:Ad@:", lopts, NULL)) >= 0) { + switch (c) { + case 'r': is_realn = 1; break; + case 'e': flt_flag |= USE_EQUAL; break; + case 'd': flt_flag |= DROP_TAG; break; + case 'q': flt_flag |= BIN_QUAL; break; + case 'h': flt_flag |= HASH_QNM; break; + case 'N': flt_flag &= ~(UPDATE_MD|UPDATE_NM); break; + case 'b': is_bam_out = 1; break; + case 'u': is_uncompressed = is_bam_out = 1; break; + case 'S': break; + case 'n': max_nm = atoi(optarg); break; + case 'C': capQ = atoi(optarg); break; + case 'A': baq_flag |= 1; break; + case 'E': baq_flag |= 2; break; + case 'Q': quiet_mode = 1; break; + case 1: no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + fprintf(samtools_stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c); + /* else fall-through */ + case '?': return calmd_usage(); + } + } + if (is_bam_out) strcat(mode_w, "b"); + else strcat(mode_w, "h"); + if (is_uncompressed) strcat(mode_w, "0"); + if (optind + (ga.reference == NULL) >= argc) + return calmd_usage(); + fp = sam_open_format(argv[optind], "r", &ga.in); + if (fp == NULL) { + print_error_errno("calmd", "Failed to open input file '%s'", argv[optind]); + return 1; + } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("calmd", "failed to create arg_list"); + return 1; + } + + header = sam_hdr_read(fp); + if (header == NULL || sam_hdr_nref(header) == 0) { + // NB: if we have no SQ headers but have aligned data, then this will + // be caught during processing with e.g. + // "[E::sam_parse1] no SQ lines present in the header" + fprintf(samtools_stderr, "[bam_fillmd] warning: input SAM does not have " + "header, performing a no-op.\n"); + } + + fpout = sam_open_format(samtools_stdout_fn, mode_w, &ga.out); + if (fpout == NULL) { + print_error_errno("calmd", "Failed to open output"); + goto fail; + } + if (!no_pg && sam_hdr_add_pg(header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error("calmd", "failed to add PG line to header"); + goto fail; + } + if (sam_hdr_write(fpout, header) < 0) { + print_error_errno("calmd", "Failed to write sam header"); + goto fail; + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(samtools_stderr, "Error creating thread pool\n"); + goto fail; + } + hts_set_opt(fp, HTS_OPT_THREAD_POOL, &p); + hts_set_opt(fpout, HTS_OPT_THREAD_POOL, &p); + } + + ref_file = argc > optind + 1 ? argv[optind+1] : ga.reference; + fai = fai_load(ref_file); + + if (!fai) { + print_error_errno("calmd", "Failed to open reference file '%s'", ref_file); + goto fail; + } + + b = bam_init1(); + if (!b) { + fprintf(samtools_stderr, "[bam_fillmd] Failed to allocate bam struct\n"); + goto fail; + } + while ((ret = sam_read1(fp, header, b)) >= 0) { + if (b->core.tid >= 0) { + if (refs.last_tid != b->core.tid) { + if (get_ref(fai, header, &refs, b->core.tid, + &ref, &ref_name, &len) < 0) { + goto fail; + } + if (ref == 0) { // FIXME: Should this always be fatal? + fprintf(samtools_stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n", + ref_name ? ref_name : "(unknown)"); + if (is_realn || capQ > 10) goto fail; // Would otherwise crash + } + } + if (is_realn) { + if (sam_prob_realn(b, ref, len, baq_flag) < -3) { + print_error_errno("calmd", "BAQ alignment failed"); + goto fail; + } + } + if (capQ > 10) { + int q = sam_cap_mapq(b, ref, len, capQ); + if (b->core.qual > q) b->core.qual = q; + } + if (ref) { + if (bam_fillmd1_core(ref_name, b, ref, len, flt_flag, max_nm, + quiet_mode, &skipped) < 0) + goto fail; + } + } + if (sam_write1(fpout, header, b) < 0) { + print_error_errno("calmd", "failed to write to output file"); + goto fail; + } + } + if (ret < -1) { + fprintf(samtools_stderr, "[bam_fillmd] Error reading input.\n"); + goto fail; + } + + if (skipped) { + fprintf(samtools_stderr, "[calmd] Warning: %"PRIu32" records skipped due " + "to no query sequence\n", + skipped); + } + + bam_destroy1(b); + sam_hdr_destroy(header); + + free(arg_list); + refs_destroy(&refs); + fai_destroy(fai); + sam_close(fp); + if (sam_close(fpout) < 0) { + fprintf(samtools_stderr, "[bam_fillmd] error when closing output file\n"); + return 1; + } + if (p.pool) hts_tpool_destroy(p.pool); + + return 0; + + fail: + free(arg_list); + refs_destroy(&refs); + if (b) bam_destroy1(b); + if (header) sam_hdr_destroy(header); + if (fai) fai_destroy(fai); + if (fp) sam_close(fp); + if (fpout) sam_close(fpout); + if (p.pool) hts_tpool_destroy(p.pool); + + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_quickcheck.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_quickcheck.c new file mode 100644 index 0000000000000000000000000000000000000000..29d88854d788a1043714a272ea58cb3c32d6b7ee --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_quickcheck.c @@ -0,0 +1,190 @@ +/* bam_quickcheck.c -- quickcheck subcommand. + + Copyright (C) 2015-2017 Genome Research Ltd. + + Author: Joshua C. Randall + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include + +/* File status flags (zero means OK). It's possible for more than one to be + * set on a single file. The final exit status is the bitwise-or of the + * status of all the files. */ +#define QC_FAIL_OPEN 2 +#define QC_NOT_SEQUENCE 4 +#define QC_BAD_HEADER 8 +#define QC_NO_EOF_BLOCK 16 +#define QC_FAIL_CLOSE 32 + +static void usage_quickcheck(FILE *write_to) +{ + fprintf(write_to, +"Usage: samtools quickcheck [options] [...]\n" +"Options:\n" +" -v verbose output (repeat for more verbosity)\n" +" -q suppress warning messages\n" +" -u unmapped input (do not require targets in header)\n" +"\n" +"Notes:\n" +"\n" +"1. By default quickcheck will emit a warning message if and only if a file\n" +" fails the checks, in which case the exit status is non-zero. Under normal\n" +" behaviour with valid data it will be silent and has a zero exit status.\n" +" The warning messages are purely for manual inspection and should not be \n" +" parsed by scripts.\n" +"\n" +"2. In order to use this command programmatically, you should check its exit\n" +" status. One way to use quickcheck might be as a check that all BAM files in\n" +" a directory are okay:\n" +"\n" +"\tsamtools quickcheck *.bam && echo 'all ok' \\\n" +"\t || echo 'fail!'\n" +"\n" +" The first level of verbosity lists only files that fail to stdout.\n" +" To obtain a parsable list of files that have failed, use this option:\n" +"\n" +"\tsamtools quickcheck -qv *.bam > bad_bams.fofn \\\n" +"\t && echo 'all ok' \\\n" +"\t || echo 'some files failed check, see bad_bams.fofn'\n" + ); +} + +#define QC_ERR(state, v, msg, arg1) \ + file_state |= (state); \ + if (!quiet || verbose >= (v)) fprintf(stderr, (msg), (arg1)) + +int main_quickcheck(int argc, char** argv) +{ + int verbose = 0, quiet = 0, unmapped = 0; + hts_verbose = 0; + + const char* optstring = "vqu"; + int opt; + while ((opt = getopt(argc, argv, optstring)) != -1) { + switch (opt) { + case 'u': + unmapped = 1; + break; + case 'v': + verbose++; + break; + case 'q': + quiet = 1; + break; + default: + usage_quickcheck(stderr); + return 1; + } + } + + argc -= optind; + argv += optind; + + if (argc < 1) { + usage_quickcheck(stdout); + return 1; + } + + if (verbose >= 2) { + fprintf(stderr, "verbosity set to %d\n", verbose); + } + + if (verbose >= 4) { + hts_verbose = 3; + } + + int ret = 0; + int i; + + for (i = 0; i < argc; i++) { + char* fn = argv[i]; + int file_state = 0; + + if (verbose >= 3) fprintf(stderr, "checking %s\n", fn); + + // attempt to open + htsFile *hts_fp = hts_open(fn, "r"); + if (hts_fp == NULL) { + QC_ERR(QC_FAIL_OPEN, 2, "%s could not be opened for reading.\n", fn); + } + else { + if (verbose >= 3) fprintf(stderr, "opened %s\n", fn); + // make sure we have sequence data + const htsFormat *fmt = hts_get_format(hts_fp); + if (fmt->category != sequence_data ) { + QC_ERR(QC_NOT_SEQUENCE, 2, "%s was not identified as sequence data.\n", fn); + } + else { + if (verbose >= 3) fprintf(stderr, "%s is sequence data\n", fn); + // check header + sam_hdr_t *header = sam_hdr_read(hts_fp); + if (header == NULL) { + QC_ERR(QC_BAD_HEADER, 2, "%s caused an error whilst reading its header.\n", fn); + } else { + if (!unmapped && sam_hdr_nref(header) <= 0) { + QC_ERR(QC_BAD_HEADER, 2, "%s had no targets in header.\n", fn); + } + else { + if (verbose >= 3) fprintf(stderr, "%s has %d targets in header.\n", fn, sam_hdr_nref(header)); + } + sam_hdr_destroy(header); + } + } + // check EOF on formats that support this + int ret; + if ((ret = hts_check_EOF(hts_fp)) < 0) { + QC_ERR(QC_NO_EOF_BLOCK, 2, "%s caused an error whilst checking for EOF block.\n", fn); + } + else { + switch (ret) { + case 0: + QC_ERR(QC_NO_EOF_BLOCK, 2, "%s was missing EOF block when one should be present.\n", fn); + break; + case 1: + if (verbose >= 3) fprintf(stderr, "%s has good EOF block.\n", fn); + break; + case 2: + if (verbose >= 3) fprintf(stderr, "%s cannot be checked for EOF block as it is not seekable.\n", fn); + break; + case 3: + if (verbose >= 3) fprintf(stderr, "%s cannot be checked for EOF block because its filetype does not contain one.\n", fn); + break; + } + } + + if (hts_close(hts_fp) < 0) { + QC_ERR(QC_FAIL_CLOSE, 2, "%s did not close cleanly.\n", fn); + } + } + + if (file_state > 0 && verbose >= 1) { + fprintf(stdout, "%s\n", fn); + } + ret |= file_state; + } + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_reheader.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_reheader.c new file mode 100644 index 0000000000000000000000000000000000000000..f84c805385fd2fde742fed6810093d6ce7b1ba6e --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_reheader.c @@ -0,0 +1,634 @@ +/* bam_reheader.c -- reheader subcommand. + + Copyright (C) 2010 Broad Institute. + Copyright (C) 2012-2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include + +#include "htslib/bgzf.h" +#include "htslib/sam.h" +#include "htslib/hfile.h" +#include "htslib/cram.h" +#include "samtools.h" + +#define BUF_SIZE 0x10000 + +/* + * Reads a file and outputs a new BAM file to fd with 'h' replaced as + * the header. No checks are made to the validity. + */ +int bam_reheader(BGZF *in, sam_hdr_t *h, int fd, + const char *arg_list, int no_pg, int skip_header) +{ + BGZF *fp = NULL; + ssize_t len; + uint8_t *buf = NULL; + sam_hdr_t *tmp; + if (!h) + return -1; + + if (in->is_write) return -1; + buf = malloc(BUF_SIZE); + if (!buf) { + fprintf(stderr, "Out of memory\n"); + return -1; + } + + if (!skip_header) { + if ((tmp = bam_hdr_read(in)) == NULL) { + fprintf(stderr, "Couldn't read header\n"); + goto fail; + } + sam_hdr_destroy(tmp); + } + + fp = bgzf_fdopen(fd, "w"); + if (!fp) { + print_error_errno("reheader", "Couldn't open output file"); + goto fail; + } + + if (!no_pg && sam_hdr_add_pg(h, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL) != 0) + goto fail; + + if (bam_hdr_write(fp, h) < 0) { + print_error_errno("reheader", "Couldn't write header"); + goto fail; + } + if (in->block_offset < in->block_length) { + if (bgzf_write(fp, (char *)in->uncompressed_block + in->block_offset, in->block_length - in->block_offset) < 0) goto write_fail; + if (bgzf_flush(fp) < 0) goto write_fail; + } + while ((len = bgzf_raw_read(in, buf, BUF_SIZE)) > 0) { + if (bgzf_raw_write(fp, buf, len) < 0) goto write_fail; + } + if (len < 0) { + fprintf(stderr, "[%s] Error reading input file\n", __func__); + goto fail; + } + free(buf); + fp->block_offset = in->block_offset = 0; + if (bgzf_close(fp) < 0) { + fprintf(stderr, "[%s] Error closing output file\n", __func__); + return -1; + } + return 0; + + write_fail: + print_error_errno("reheader", "Error writing to output file"); + fail: + bgzf_close(fp); + free(buf); + return -1; +} + +/* + * Reads a file and outputs a new CRAM file to stdout with 'h' + * replaced as the header. No checks are made to the validity. + * + * FIXME: error checking + */ +int cram_reheader(cram_fd *in, sam_hdr_t *h, const char *arg_list, int no_pg) +{ + htsFile *h_out = hts_open("-", "wc"); + cram_fd *out = h_out->fp.cram; + cram_container *c = NULL; + int ret = -1; + if (!h) + return ret; + + // Match output version number with input file. + char vers[99]; + sprintf(vers, "%d.%d", cram_major_vers(in), cram_minor_vers(in)); + cram_set_option(out, CRAM_OPT_VERSION, vers); + + // Attempt to fill out a cram->refs[] array from @SQ headers + sam_hdr_t *cram_h = sam_hdr_dup(h); + if (!cram_h) + return -1; + cram_fd_set_header(out, cram_h); + if (!no_pg && sam_hdr_add_pg(cram_fd_get_header(out), "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto err; + + if (sam_hdr_write(h_out, cram_h) != 0) + goto err; + cram_set_option(out, CRAM_OPT_REFERENCE, NULL); + + while ((c = cram_read_container(in))) { + int32_t i, num_blocks = cram_container_get_num_blocks(c); + if (cram_write_container(out, c) != 0) + goto err; + + for (i = 0; i < num_blocks; i++) { + cram_block *blk = cram_read_block(in); + if (!blk || cram_write_block(out, blk) != 0) { + if (blk) cram_free_block(blk); + goto err; + } + cram_free_block(blk); + } + cram_free_container(c); + } + + ret = 0; + + err: + if (hts_close(h_out) != 0) + ret = -1; + + return ret; +} + + + +/* + * Reads a version 2 CRAM file and replaces the header in-place, + * provided the header is small enough to fit without growing the + * entire file. + * + * Version 2 format has an uncompressed SAM header with multiple nul + * termination bytes to permit inline header editing. + * + * Returns 0 on success; + * -1 on general failure; + * -2 on failure due to insufficient size + */ +int cram_reheader_inplace2(cram_fd *fd, sam_hdr_t *h, const char *arg_list, + int no_pg) +{ + cram_container *c = NULL; + cram_block *b = NULL; + sam_hdr_t *cram_h = NULL; + off_t start; + int ret = -1; + if (!h) + goto err; + + if (cram_major_vers(fd) < 2 || + cram_major_vers(fd) > 3) { + fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__, + cram_major_vers(fd)); + goto err; + } + + cram_h = sam_hdr_dup(h); + if (!cram_h) + goto err; + + if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto err; + + int header_len = sam_hdr_length(cram_h); + /* Fix M5 strings? Maybe out of scope for this tool */ + + // Load the existing header + if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26) + goto err; + + if (!(c = cram_read_container(fd))) + goto err; + + // Version 2.1 has a single uncompressed block which is nul + // terminated with many nuls to permit growth. + // + // So load old block and keep all contents identical bar the + // header text itself + if (!(b = cram_read_block(fd))) + goto err; + + if (cram_block_get_uncomp_size(b) < header_len+4) { + fprintf(stderr, "New header will not fit. Use non-inplace version (%d > %d)\n", + header_len+4, cram_block_get_uncomp_size(b)); + ret = -2; + goto err; + } + + cram_block_set_offset(b, 0); // rewind block + int32_put_blk(b, header_len); + cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len); + // Zero the remaining block + memset((char *)cram_block_get_data(b)+cram_block_get_offset(b), 0, + cram_block_get_uncomp_size(b) - cram_block_get_offset(b)); + // Make sure all sizes and byte-offsets are consistent after memset + cram_block_set_offset(b, cram_block_get_uncomp_size(b)); + cram_block_set_comp_size(b, cram_block_get_uncomp_size(b)); + + if (hseek(cram_fd_get_fp(fd), start, SEEK_SET) != start) + goto err; + + if (cram_write_container(fd, c) == -1) + goto err; + + if (cram_write_block(fd, b) == -1) + goto err; + + ret = 0; + err: + if (c) cram_free_container(c); + if (b) cram_free_block(b); + if (cram_h) sam_hdr_destroy(cram_h); + + return ret; +} + + +/* + * Reads a version 3 CRAM file and replaces the header in-place, + * provided the header is small enough to fit without growing the + * entire file. + * + * Version 3 format has a SAM header held as an (optionally) + * compressed block within the header container. Additional + * uncompressed blocks or simply unallocated space (the difference + * between total block sizes and the container size) are used to + * provide room for growth or contraction of the compressed header. + * + * Returns 0 on success; + * -1 on general failure; + * -2 on failure due to insufficient size + */ +int cram_reheader_inplace3(cram_fd *fd, sam_hdr_t *h, const char *arg_list, + int no_pg) +{ + cram_container *c = NULL; + cram_block *b = NULL; + sam_hdr_t *cram_h = NULL; + off_t start, sz, end; + int container_sz, max_container_sz; + char *buf = NULL; + int ret = -1; + if (!h) + goto err; + + if (cram_major_vers(fd) < 2 || + cram_major_vers(fd) > 3) { + fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__, + cram_major_vers(fd)); + goto err; + } + + cram_h = sam_hdr_dup(h); + if (!cram_h) + goto err; + + if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) + goto err; + + int header_len = sam_hdr_length(cram_h); + /* Fix M5 strings? Maybe out of scope for this tool */ + + // Find current size of SAM header block + if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26) + goto err; + + if (!(c = cram_read_container(fd))) + goto err; + + // +5 allows num_landmarks to increase from 0 to 1 (Cramtools) + max_container_sz = cram_container_size(c)+5; + + sz = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c) - start; + end = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c); + + // We force 1 block instead of (optionally) 2. C CRAM + // implementations for v3 were writing 1 compressed block followed + // by 1 uncompressed block. However this is tricky to deal with + // as changing block sizes can mean the block header also changes + // size due to itf8 and variable size integers. + // + // If we had 1 block, this doesn't change anything. + // If we had 2 blocks, the new container header will be smaller by + // 1+ bytes, requiring the cram_container_get_length(c) to be larger in value. + // However this is an int32 instead of itf8 so the container + // header structure stays the same size. This means we can always + // reduce the number of blocks without running into size problems. + cram_container_set_num_blocks(c, 1); + int32_t *landmark; + int32_t num_landmarks; + landmark = cram_container_get_landmarks(c, &num_landmarks); + if (num_landmarks && landmark) { + num_landmarks = 1; + landmark[0] = 0; + } else { + num_landmarks = 0; + } + cram_container_set_landmarks(c, num_landmarks, landmark); + + buf = malloc(max_container_sz); + container_sz = max_container_sz; + if (cram_store_container(fd, c, buf, &container_sz) != 0) + goto err; + + if (!buf) + goto err; + + // Proposed new length, but changing cram_container_get_length(c) may change the + // container_sz and thus the remainder (cram_container_get_length(c) itself). + cram_container_set_length(c, sz - container_sz); + + int old_container_sz = container_sz; + container_sz = max_container_sz; + if (cram_store_container(fd, c, buf, &container_sz) != 0) + goto err; + + if (old_container_sz != container_sz) { + fprintf(stderr, "Quirk of fate makes this troublesome! " + "Please use non-inplace version.\n"); + goto err; + } + + + + // Version 3.0 supports compressed header + b = cram_new_block(FILE_HEADER, 0); + int32_put_blk(b, header_len); + cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len); + cram_block_update_size(b); + + cram_compress_block(fd, b, NULL, -1, 9); + + if (hseek(cram_fd_get_fp(fd), 26, SEEK_SET) != 26) + goto err; + + if (cram_block_size(b) > cram_container_get_length(c)) { + fprintf(stderr, "New header will not fit. Use non-inplace version" + " (%d > %d)\n", + (int)cram_block_size(b), cram_container_get_length(c)); + ret = -2; + goto err; + } + + if (cram_write_container(fd, c) == -1) + goto err; + + if (cram_write_block(fd, b) == -1) + goto err; + + // Blank out the remainder + int rsz = end - htell(cram_fd_get_fp(fd)); + assert(rsz >= 0); + if (rsz) { + char *rem = calloc(1, rsz); + ret = hwrite(cram_fd_get_fp(fd), rem, rsz) == rsz ? 0 : -1; + free(rem); + } + + err: + if (c) cram_free_container(c); + if (buf) free(buf); + if (b) cram_free_block(b); + if (cram_h) sam_hdr_destroy(cram_h); + + return ret; +} + +int cram_reheader_inplace(cram_fd *fd, sam_hdr_t *h, const char *arg_list, + int no_pg) +{ + switch (cram_major_vers(fd)) { + case 2: return cram_reheader_inplace2(fd, h, arg_list, no_pg); + case 3: return cram_reheader_inplace3(fd, h, arg_list, no_pg); + default: + fprintf(stderr, "[%s] unsupported CRAM version %d\n", __func__, + cram_major_vers(fd)); + return -1; + } +} + +static void usage(FILE *fp, int ret) { + fprintf(fp, + "Usage: samtools reheader [-P] in.header.sam in.bam > out.bam\n" + " or samtools reheader [-P] -i in.header.sam file.cram\n" + " or samtools reheader -c CMD in.bam\n" + " or samtools reheader -c CMD in.cram\n" + "\n" + "Options:\n" + " -P, --no-PG Do not generate a @PG header line.\n" + " -i, --in-place Modify the CRAM file directly, if possible.\n" + " (Defaults to outputting to stdout.)\n" + " -c, --command CMD Pass the header in SAM format to external program CMD.\n"); + exit(ret); +} + +static sam_hdr_t* external_reheader(samFile* in, const char* external) { + char *command = NULL; + sam_hdr_t* h = NULL; + sam_hdr_t* ih = sam_hdr_read(in); + if (ih == NULL) { + fprintf(stderr, "[%s] failed to read the header for '%s'.\n", __func__, in->fn); + return NULL; + } + char tmp_fn[] = "reheaderXXXXXX"; + int tmp_fd = mkstemp(tmp_fn); + if (tmp_fd < 0) { + print_error_errno("reheader", "fail to open temp file '%s'", tmp_fn); + return NULL; + } + hFILE* tmp_hf = hdopen(tmp_fd, "w"); + if (!tmp_hf) { + fprintf(stderr, "[%s] failed to convert to hFILE.\n", __func__); + goto cleanup; + } + samFile* tmp_sf = hts_hopen(tmp_hf, tmp_fn, "w"); + if (!tmp_sf) { + fprintf(stderr, "[%s] failed to convert to samFile.\n", __func__); + goto cleanup; + } + if (-1 == sam_hdr_write(tmp_sf, ih)) { + fprintf(stderr, "[%s] failed to write the header to the temp file.\n", __func__); + goto cleanup; + } + sam_close(tmp_sf); + sam_hdr_destroy(ih); + int comm_len = strlen(external) + strlen(tmp_fn) + 8; + command = calloc(comm_len, 1); + if (!command || snprintf(command, comm_len, "( %s ) < %s", external, tmp_fn) != comm_len - 1) { + fprintf(stderr, "[%s] failed to create command string.\n", __func__); + goto cleanup; + } + FILE* nh = popen(command, "r"); + if (!nh) { + print_error_errno("reheader", "[%s] failed to run external command '%s'.\n", __func__, command); + goto cleanup; + } + + int nh_fd = dup(fileno(nh)); + if (nh_fd < 0) { + fprintf(stderr, "[%s] failed to get the file descriptor.\n", __func__); + goto cleanup; + } + hFILE* nh_hf = hdopen(nh_fd, "r"); + if (!nh_hf) { + fprintf(stderr, "[%s] failed to convert to hFILE.\n", __func__); + goto cleanup; + } + samFile* nh_sf = hts_hopen(nh_hf, tmp_fn, "r"); + if (!nh_sf) { + fprintf(stderr, "[%s] failed to convert to samFile.\n", __func__); + goto cleanup; + } + + h = sam_hdr_read(nh_sf); + sam_close(nh_sf); + if (h == NULL) { + fprintf(stderr, "[%s] failed to read the header from the temp file.\n", __func__); + } + int res = pclose(nh); + if (res != 0) { + if (res < 0) { + print_error_errno("reheader", + "Error on closing pipe from command '%s'.\n", + command); + } else { + print_error("reheader", + "Non-zero exit code returned by command '%s'\n", + command); + } + if (h) sam_hdr_destroy(h); + h = NULL; + } +cleanup: + free(command); + if (unlink(tmp_fn) != 0) { + print_error_errno("reheader", "failed to remove the temp file '%s'", tmp_fn); + } + + return h; +} + +int main_reheader(int argc, char *argv[]) +{ + int inplace = 0, r, no_pg = 0, c, skip_header = 0; + sam_hdr_t *h; + samFile *in; + char *arg_list = NULL, *external = NULL; + + static const struct option lopts[] = { + {"help", no_argument, NULL, 'h'}, + {"in-place", no_argument, NULL, 'i'}, + {"no-PG", no_argument, NULL, 'P'}, + {"command", required_argument, NULL, 'c'}, + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "hiPc:", lopts, NULL)) >= 0) { + switch (c) { + case 'P': no_pg = 1; break; + case 'i': inplace = 1; break; + case 'c': external = optarg; break; + case 'h': usage(stdout, 0); break; + default: + fprintf(stderr, "Invalid option '%c'\n", c); + usage(stderr, 1); + } + } + + if ((argc - optind != 2 || external) && (argc - optind != 1 || !external)) + usage(stderr, 1); + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("reheader", "failed to create arg_list"); + return 1; + } + + if (external) { + skip_header = 1; + in = sam_open(argv[optind], inplace?"r+":"r"); + if (in == 0) { + print_error_errno("reheader", "fail to open file '%s'", argv[optind]); + return 1; + } + + h = external_reheader(in, external); + if (h == NULL) { + fprintf(stderr, "[%s] failed to read the header from '%s'.\n", __func__, external); + sam_close(in); + return 1; + } + } else { // read the header from a separate file + samFile *fph = sam_open(argv[optind], "r"); + if (fph == 0) { + print_error_errno("reheader", "fail to read the header from '%s'", argv[optind]); + return 1; + } + h = sam_hdr_read(fph); + sam_close(fph); + if (h == NULL) { + fprintf(stderr, "[%s] failed to read the header for '%s'.\n", + __func__, argv[1]); + return 1; + } + in = sam_open(argv[optind+1], inplace?"r+":"r"); + if (in == 0) { + print_error_errno("reheader", "fail to open file '%s'", argv[optind+1]); + return 1; + } + } + + if (hts_get_format(in)->format == bam) { + if (inplace) { + print_error("reheader", "cannot reheader BAM '%s' in-place", argv[optind+1]); + r = -1; + } else { + r = bam_reheader(in->fp.bgzf, h, fileno(stdout), arg_list, no_pg, skip_header); + } + } else if (hts_get_format(in)->format == cram) { + if (inplace) + r = cram_reheader_inplace(in->fp.cram, h, arg_list, no_pg); + else + r = cram_reheader(in->fp.cram, h, arg_list, no_pg); + } else { + print_error("reheader", "input file '%s' must be BAM or CRAM", argv[optind+1]); + r = -1; + } + + if (sam_close(in) != 0) + r = -1; + + sam_hdr_destroy(h); + + if (arg_list) + free(arg_list); + + return -r; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdup.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdup.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..a748e47ce2be27c94892897602302e35ee0a1697 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdup.c.pysam.c @@ -0,0 +1,327 @@ +#include "samtools.pysam.h" + +/* bam_rmdup.c -- duplicate read detection. + + Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd. + Portions copyright (C) 2009 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/sam.h" +#include "sam_opts.h" +#include "samtools.h" +#include "bam.h" // for bam_get_library + +typedef bam1_t *bam1_p; + +#include "htslib/khash.h" +KHASH_SET_INIT_STR(name) +KHASH_MAP_INIT_INT64(pos, bam1_p) + +#define BUFFER_SIZE 0x40000 + +typedef struct { + uint64_t n_checked, n_removed; + khash_t(pos) *best_hash; +} lib_aux_t; +KHASH_MAP_INIT_STR(lib, lib_aux_t) + +typedef struct { + int n, max; + bam1_t **a; +} tmp_stack_t; + +static inline void stack_insert(tmp_stack_t *stack, bam1_t *b) +{ + if (stack->n == stack->max) { + stack->max = stack->max? stack->max<<1 : 0x10000; + stack->a = (bam1_t**)realloc(stack->a, sizeof(bam1_t*) * stack->max); + } + stack->a[stack->n++] = b; +} + +static inline int dump_best(tmp_stack_t *stack, samFile *out, sam_hdr_t *hdr) +{ + int i; + for (i = 0; i != stack->n; ++i) { + if (sam_write1(out, hdr, stack->a[i]) < 0) return -1; + bam_destroy1(stack->a[i]); + stack->a[i] = NULL; + } + stack->n = 0; + return 0; +} + +static inline void clear_stack(tmp_stack_t *stack) { + int i; + if (!stack->a) return; + for (i = 0; i != stack->n; ++i) { + bam_destroy1(stack->a[i]); + } +} + +static void clear_del_set(khash_t(name) *del_set) +{ + khint_t k; + for (k = kh_begin(del_set); k < kh_end(del_set); ++k) + if (kh_exist(del_set, k)) + free((char*)kh_key(del_set, k)); + kh_clear(name, del_set); +} + +static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) +{ + khint_t k = kh_get(lib, aux, lib); + if (k == kh_end(aux)) { + int ret; + char *p = strdup(lib); + lib_aux_t *q; + k = kh_put(lib, aux, p, &ret); + q = &kh_val(aux, k); + q->n_checked = q->n_removed = 0; + q->best_hash = kh_init(pos); + return q; + } else return &kh_val(aux, k); +} + +static void clear_best(khash_t(lib) *aux, int max) +{ + khint_t k; + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + if (kh_size(q->best_hash) >= max) + kh_clear(pos, q->best_hash); + } + } +} + +static inline int sum_qual(const bam1_t *b) +{ + int i, q; + uint8_t *qual = bam_get_qual(b); + for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; + return q; +} + +int bam_rmdup_core(samFile *in, sam_hdr_t *hdr, samFile *out) +{ + bam1_t *b = NULL; + int last_tid = -1, last_pos = -1, r; + tmp_stack_t stack; + khint_t k; + khash_t(lib) *aux = NULL; + khash_t(name) *del_set = NULL; + + memset(&stack, 0, sizeof(tmp_stack_t)); + aux = kh_init(lib); + del_set = kh_init(name); + b = bam_init1(); + if (!aux || !del_set || !b) { + perror(__func__); + goto fail; + } + + kh_resize(name, del_set, 4 * BUFFER_SIZE); + while ((r = sam_read1(in, hdr, b)) >= 0) { + bam1_core_t *c = &b->core; + if (c->tid != last_tid || last_pos != c->pos) { + if (dump_best(&stack, out, hdr) < 0) goto write_fail; // write the result + clear_best(aux, BUFFER_SIZE); + if (c->tid != last_tid) { + clear_best(aux, 0); + if (kh_size(del_set)) { // check + fprintf(samtools_stderr, "[bam_rmdup_core] %llu unmatched pairs\n", (long long)kh_size(del_set)); + clear_del_set(del_set); + } + if ((int)c->tid == -1) { // append unmapped reads + if (sam_write1(out, hdr, b) < 0) goto write_fail; + while ((r = sam_read1(in, hdr, b)) >= 0) { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } + break; + } + last_tid = c->tid; + fprintf(samtools_stderr, "[bam_rmdup_core] processing reference %s...\n", sam_hdr_tid2name(hdr, c->tid)); + } + } + if (!(c->flag&BAM_FPAIRED) || (c->flag&(BAM_FUNMAP|BAM_FMUNMAP)) || (c->mtid >= 0 && c->tid != c->mtid)) { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } else if (c->isize > 0) { // paired, head + uint64_t key = (uint64_t)c->pos<<32 | c->isize; + const char *lib; + lib_aux_t *q; + int ret; + lib = bam_get_library(hdr, b); + q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); + ++q->n_checked; + k = kh_put(pos, q->best_hash, key, &ret); + if (ret < 0) goto fail; + if (ret == 0) { // found in best_hash + bam1_t *p = kh_val(q->best_hash, k); + ++q->n_removed; + if (sum_qual(p) < sum_qual(b)) { // the current alignment is better; this can be accelerated in principle + kh_put(name, del_set, strdup(bam_get_qname(p)), &ret); // p will be removed + if (ret < 0) goto fail; + if (bam_copy1(p, b) == NULL) goto fail; // replaced as b + } else kh_put(name, del_set, strdup(bam_get_qname(b)), &ret); // b will be removed + if (ret < 0) goto fail; + if (ret == 0) + fprintf(samtools_stderr, "[bam_rmdup_core] inconsistent BAM file for pair '%s'. Continue anyway.\n", bam_get_qname(b)); + } else { // not found in best_hash + kh_val(q->best_hash, k) = bam_dup1(b); + stack_insert(&stack, kh_val(q->best_hash, k)); + } + } else { // paired, tail + k = kh_get(name, del_set, bam_get_qname(b)); + if (k != kh_end(del_set)) { + free((char*)kh_key(del_set, k)); + kh_del(name, del_set, k); + } else { + if (sam_write1(out, hdr, b) < 0) goto write_fail; + } + } + last_pos = c->pos; + } + if (r < -1) { + fprintf(samtools_stderr, "[%s] failed to read input file\n", __func__); + goto fail; + } + + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + if (dump_best(&stack, out, hdr) < 0) goto write_fail; + fprintf(samtools_stderr, "[bam_rmdup_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, + (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); + kh_destroy(pos, q->best_hash); + free((char*)kh_key(aux, k)); + kh_del(lib, aux, k); + } + } + kh_destroy(lib, aux); + + clear_del_set(del_set); + kh_destroy(name, del_set); + free(stack.a); + bam_destroy1(b); + return 0; + + write_fail: + print_error_errno("rmdup", "failed to write record"); + fail: + clear_stack(&stack); + free(stack.a); + if (aux) { + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + kh_destroy(pos, q->best_hash); + free((char*)kh_key(aux, k)); + } + } + kh_destroy(lib, aux); + } + if (del_set) { + clear_del_set(del_set); + kh_destroy(name, del_set); + } + bam_destroy1(b); + return 1; +} + +int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se); + +static int rmdup_usage(void) { + fprintf(samtools_stderr, "\n"); + fprintf(samtools_stderr, "Usage: samtools rmdup [-sS] \n\n"); + fprintf(samtools_stderr, "Option: -s rmdup for SE reads\n"); + fprintf(samtools_stderr, " -S treat PE reads as SE in rmdup (force -s)\n"); + + sam_global_opt_help(samtools_stderr, "-....--."); + return 1; +} + +int bam_rmdup(int argc, char *argv[]) +{ + int c, ret, is_se = 0, force_se = 0; + samFile *in, *out; + sam_hdr_t *header; + char wmode[3] = {'w', 'b', 0}; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'), + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "sS", lopts, NULL)) >= 0) { + switch (c) { + case 's': is_se = 1; break; + case 'S': force_se = is_se = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': return rmdup_usage(); + } + } + if (optind + 2 > argc) + return rmdup_usage(); + + in = sam_open_format(argv[optind], "r", &ga.in); + if (!in) { + print_error_errno("rmdup", "failed to open \"%s\" for input", argv[optind]); + return 1; + } + header = sam_hdr_read(in); + if (header == NULL || sam_hdr_nref(header) == 0) { + fprintf(samtools_stderr, "[bam_rmdup] input SAM does not have header. Abort!\n"); + return 1; + } + + sam_open_mode(wmode+1, argv[optind+1], NULL); + out = sam_open_format(argv[optind+1], wmode, &ga.out); + if (!out) { + print_error_errno("rmdup", "failed to open \"%s\" for output", argv[optind+1]); + return 1; + } + if (sam_hdr_write(out, header) < 0) { + print_error_errno("rmdup", "failed to write header"); + return 1; + } + + if (is_se) ret = bam_rmdupse_core(in, header, out, force_se); + else ret = bam_rmdup_core(in, header, out); + + sam_hdr_destroy(header); + sam_close(in); + if (sam_close(out) < 0) { + fprintf(samtools_stderr, "[bam_rmdup] error closing output file\n"); + ret = 1; + } + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c new file mode 100644 index 0000000000000000000000000000000000000000..181213689403ed38c4f1b2c177072724d97a1ffd --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c @@ -0,0 +1,230 @@ +/* bam_rmdupse.c -- duplicate read detection for unpaired reads. + + Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd. + Portions copyright (C) 2009 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include "bam.h" // for bam_get_library +#include "htslib/sam.h" +#include "htslib/khash.h" +#include "htslib/klist.h" +#include "samtools.h" + +#define QUEUE_CLEAR_SIZE 0x100000 +#define MAX_POS 0x7fffffff + +typedef struct { + int endpos; + uint32_t score:31, discarded:1; + bam1_t *b; +} elem_t, *elem_p; +#define __free_elem(p) bam_destroy1((p)->data.b) +KLIST_INIT(q, elem_t, __free_elem) +typedef klist_t(q) queue_t; + +KHASH_MAP_INIT_INT(best, elem_p) +typedef khash_t(best) besthash_t; + +typedef struct { + uint64_t n_checked, n_removed; + besthash_t *left, *rght; +} lib_aux_t; +KHASH_MAP_INIT_STR(lib, lib_aux_t) + +static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) +{ + khint_t k = kh_get(lib, aux, lib); + if (k == kh_end(aux)) { + int ret; + char *p = strdup(lib); + lib_aux_t *q; + k = kh_put(lib, aux, p, &ret); + q = &kh_val(aux, k); + q->left = kh_init(best); + q->rght = kh_init(best); + q->n_checked = q->n_removed = 0; + return q; + } else return &kh_val(aux, k); +} + +static inline int sum_qual(const bam1_t *b) +{ + int i, q; + uint8_t *qual = bam_get_qual(b); + for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; + return q; +} + +static inline elem_t *push_queue(queue_t *queue, const bam1_t *b, int endpos, int score) +{ + elem_t *p = kl_pushp(q, queue); + p->discarded = 0; + p->endpos = endpos; p->score = score; + if (p->b == 0) p->b = bam_init1(); + if (!p->b) { perror(NULL); exit(EXIT_FAILURE); } + if (bam_copy1(p->b, b) == NULL) { perror(NULL); exit(EXIT_FAILURE); } + return p; +} + +static void clear_besthash(besthash_t *h, int32_t pos) +{ + khint_t k; + for (k = kh_begin(h); k != kh_end(h); ++k) + if (kh_exist(h, k) && kh_val(h, k)->endpos <= pos) + kh_del(best, h, k); +} + +static int dump_alignment(samFile *out, sam_hdr_t *hdr, + queue_t *queue, int32_t pos, khash_t(lib) *h) +{ + if (queue->size > QUEUE_CLEAR_SIZE || pos == MAX_POS) { + khint_t k; + while (1) { + elem_t *q; + if (queue->head == queue->tail) break; + q = &kl_val(queue->head); + if (q->discarded) { + q->b->l_data = 0; + kl_shift(q, queue, 0); + continue; + } + if ((q->b->core.flag&BAM_FREVERSE) && q->endpos > pos) break; + if (sam_write1(out, hdr, q->b) < 0) return -1; + q->b->l_data = 0; + kl_shift(q, queue, 0); + } + for (k = kh_begin(h); k != kh_end(h); ++k) { + if (kh_exist(h, k)) { + clear_besthash(kh_val(h, k).left, pos); + clear_besthash(kh_val(h, k).rght, pos); + } + } + } + return 0; +} + +int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se) +{ + bam1_t *b = NULL; + queue_t *queue = NULL; + khint_t k; + int last_tid = -2, r; + khash_t(lib) *aux = NULL; + + aux = kh_init(lib); + b = bam_init1(); + queue = kl_init(q); + if (!aux || !b || !queue) { + perror(__func__); + goto fail; + } + + while ((r = sam_read1(in, hdr, b)) >= 0) { + bam1_core_t *c = &b->core; + int endpos = bam_endpos(b); + int score = sum_qual(b); + + if (last_tid != c->tid) { + if (last_tid >= 0) { + if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) + goto write_fail; + } + last_tid = c->tid; + } else { + if (dump_alignment(out, hdr, queue, c->pos, aux) < 0) + goto write_fail; + } + if ((c->flag&BAM_FUNMAP) || ((c->flag&BAM_FPAIRED) && !force_se)) { + push_queue(queue, b, endpos, score); + } else { + const char *lib; + lib_aux_t *q; + besthash_t *h; + uint32_t key; + int ret; + lib = bam_get_library(hdr, b); + q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); + ++q->n_checked; + h = (c->flag&BAM_FREVERSE)? q->rght : q->left; + key = (c->flag&BAM_FREVERSE)? endpos : c->pos; + k = kh_put(best, h, key, &ret); + if (ret == 0) { // in the hash table + elem_t *p = kh_val(h, k); + ++q->n_removed; + if (p->score < score) { + if (c->flag&BAM_FREVERSE) { // mark "discarded" and push the queue + p->discarded = 1; + kh_val(h, k) = push_queue(queue, b, endpos, score); + } else { // replace + p->score = score; p->endpos = endpos; + if (bam_copy1(p->b, b) == NULL) { + perror(NULL); exit(EXIT_FAILURE); + } + } + } // otherwise, discard the alignment + } else kh_val(h, k) = push_queue(queue, b, endpos, score); + } + } + if (r < -1) { + fprintf(stderr, "[%s] error reading input file\n", __func__); + goto fail; + } + + if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) goto write_fail; + + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + fprintf(stderr, "[bam_rmdupse_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, + (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); + kh_destroy(best, q->left); kh_destroy(best, q->rght); + free((char*)kh_key(aux, k)); + kh_del(lib, aux, k); + } + } + kh_destroy(lib, aux); + bam_destroy1(b); + kl_destroy(q, queue); + return 0; + + write_fail: + print_error_errno("rmdup", "failed to write record"); + fail: + if (aux) { + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + kh_destroy(best, q->left); + kh_destroy(best, q->rght); + free((char*)kh_key(aux, k)); + } + } + kh_destroy(lib, aux); + } + bam_destroy1(b); + kl_destroy(q, queue); + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..65689d7dfb3c83b5218ba899bab0f76156d5b4ae --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_rmdupse.c.pysam.c @@ -0,0 +1,232 @@ +#include "samtools.pysam.h" + +/* bam_rmdupse.c -- duplicate read detection for unpaired reads. + + Copyright (C) 2009, 2015, 2016, 2019 Genome Research Ltd. + Portions copyright (C) 2009 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include "bam.h" // for bam_get_library +#include "htslib/sam.h" +#include "htslib/khash.h" +#include "htslib/klist.h" +#include "samtools.h" + +#define QUEUE_CLEAR_SIZE 0x100000 +#define MAX_POS 0x7fffffff + +typedef struct { + int endpos; + uint32_t score:31, discarded:1; + bam1_t *b; +} elem_t, *elem_p; +#define __free_elem(p) bam_destroy1((p)->data.b) +KLIST_INIT(q, elem_t, __free_elem) +typedef klist_t(q) queue_t; + +KHASH_MAP_INIT_INT(best, elem_p) +typedef khash_t(best) besthash_t; + +typedef struct { + uint64_t n_checked, n_removed; + besthash_t *left, *rght; +} lib_aux_t; +KHASH_MAP_INIT_STR(lib, lib_aux_t) + +static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) +{ + khint_t k = kh_get(lib, aux, lib); + if (k == kh_end(aux)) { + int ret; + char *p = strdup(lib); + lib_aux_t *q; + k = kh_put(lib, aux, p, &ret); + q = &kh_val(aux, k); + q->left = kh_init(best); + q->rght = kh_init(best); + q->n_checked = q->n_removed = 0; + return q; + } else return &kh_val(aux, k); +} + +static inline int sum_qual(const bam1_t *b) +{ + int i, q; + uint8_t *qual = bam_get_qual(b); + for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; + return q; +} + +static inline elem_t *push_queue(queue_t *queue, const bam1_t *b, int endpos, int score) +{ + elem_t *p = kl_pushp(q, queue); + p->discarded = 0; + p->endpos = endpos; p->score = score; + if (p->b == 0) p->b = bam_init1(); + if (!p->b) { perror(NULL); samtools_exit(EXIT_FAILURE); } + if (bam_copy1(p->b, b) == NULL) { perror(NULL); samtools_exit(EXIT_FAILURE); } + return p; +} + +static void clear_besthash(besthash_t *h, int32_t pos) +{ + khint_t k; + for (k = kh_begin(h); k != kh_end(h); ++k) + if (kh_exist(h, k) && kh_val(h, k)->endpos <= pos) + kh_del(best, h, k); +} + +static int dump_alignment(samFile *out, sam_hdr_t *hdr, + queue_t *queue, int32_t pos, khash_t(lib) *h) +{ + if (queue->size > QUEUE_CLEAR_SIZE || pos == MAX_POS) { + khint_t k; + while (1) { + elem_t *q; + if (queue->head == queue->tail) break; + q = &kl_val(queue->head); + if (q->discarded) { + q->b->l_data = 0; + kl_shift(q, queue, 0); + continue; + } + if ((q->b->core.flag&BAM_FREVERSE) && q->endpos > pos) break; + if (sam_write1(out, hdr, q->b) < 0) return -1; + q->b->l_data = 0; + kl_shift(q, queue, 0); + } + for (k = kh_begin(h); k != kh_end(h); ++k) { + if (kh_exist(h, k)) { + clear_besthash(kh_val(h, k).left, pos); + clear_besthash(kh_val(h, k).rght, pos); + } + } + } + return 0; +} + +int bam_rmdupse_core(samFile *in, sam_hdr_t *hdr, samFile *out, int force_se) +{ + bam1_t *b = NULL; + queue_t *queue = NULL; + khint_t k; + int last_tid = -2, r; + khash_t(lib) *aux = NULL; + + aux = kh_init(lib); + b = bam_init1(); + queue = kl_init(q); + if (!aux || !b || !queue) { + perror(__func__); + goto fail; + } + + while ((r = sam_read1(in, hdr, b)) >= 0) { + bam1_core_t *c = &b->core; + int endpos = bam_endpos(b); + int score = sum_qual(b); + + if (last_tid != c->tid) { + if (last_tid >= 0) { + if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) + goto write_fail; + } + last_tid = c->tid; + } else { + if (dump_alignment(out, hdr, queue, c->pos, aux) < 0) + goto write_fail; + } + if ((c->flag&BAM_FUNMAP) || ((c->flag&BAM_FPAIRED) && !force_se)) { + push_queue(queue, b, endpos, score); + } else { + const char *lib; + lib_aux_t *q; + besthash_t *h; + uint32_t key; + int ret; + lib = bam_get_library(hdr, b); + q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); + ++q->n_checked; + h = (c->flag&BAM_FREVERSE)? q->rght : q->left; + key = (c->flag&BAM_FREVERSE)? endpos : c->pos; + k = kh_put(best, h, key, &ret); + if (ret == 0) { // in the hash table + elem_t *p = kh_val(h, k); + ++q->n_removed; + if (p->score < score) { + if (c->flag&BAM_FREVERSE) { // mark "discarded" and push the queue + p->discarded = 1; + kh_val(h, k) = push_queue(queue, b, endpos, score); + } else { // replace + p->score = score; p->endpos = endpos; + if (bam_copy1(p->b, b) == NULL) { + perror(NULL); samtools_exit(EXIT_FAILURE); + } + } + } // otherwise, discard the alignment + } else kh_val(h, k) = push_queue(queue, b, endpos, score); + } + } + if (r < -1) { + fprintf(samtools_stderr, "[%s] error reading input file\n", __func__); + goto fail; + } + + if (dump_alignment(out, hdr, queue, MAX_POS, aux) < 0) goto write_fail; + + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + fprintf(samtools_stderr, "[bam_rmdupse_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, + (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); + kh_destroy(best, q->left); kh_destroy(best, q->rght); + free((char*)kh_key(aux, k)); + kh_del(lib, aux, k); + } + } + kh_destroy(lib, aux); + bam_destroy1(b); + kl_destroy(q, queue); + return 0; + + write_fail: + print_error_errno("rmdup", "failed to write record"); + fail: + if (aux) { + for (k = kh_begin(aux); k != kh_end(aux); ++k) { + if (kh_exist(aux, k)) { + lib_aux_t *q = &kh_val(aux, k); + kh_destroy(best, q->left); + kh_destroy(best, q->rght); + free((char*)kh_key(aux, k)); + } + } + kh_destroy(lib, aux); + } + bam_destroy1(b); + kl_destroy(q, queue); + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_samples.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_samples.c new file mode 100644 index 0000000000000000000000000000000000000000..f72ca6e0ad41a3d4960cdbd25d1adb72a1c1db8e --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_samples.c @@ -0,0 +1,433 @@ +/* bam_samples -- print samples in a set of BAM files + + Copyright (C) 2021 Pierre Lindenbaum + Institut du Thorax. u1087 Nantes. France. + @yokofakun + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +KHASH_MAP_INIT_STR(sm, int) + +/** and chained struct containing the faidx and the fasta filename + will be compared with the @SQ lines in the SAM header + */ +typedef struct FaidxPath { + /** path to reference */ + char* filename; + /** fasta index */ + faidx_t* faidx; + struct FaidxPath* next; +} FaidxPath; + +/** program parameters */ +typedef struct Params { + /** output stream */ + FILE* out; + /** tag in @RG line. default is "SM" */ + char tag[3]; + /** first faidx/path in chained list */ + FaidxPath* faidx; + /** show whether the bam is indexed */ + int test_index; +} Params; + +/** print usage */ +static void usage_samples(FILE *write_to) { + fprintf(write_to, + "Usage: samtools samples [options] [...]\n" + " samtools samples [options] -X f1.bam f2.bam f1.bam.bai f2.bai \n" + " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.cram\" \\) | samtools samples [options]\n" + " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.bai\" \\) | sort | paste - - | samtools samples -X [options]\n" + "\n" + "Options:\n" + " -? print help and exit\n" + " -h add the columns header before printing the results\n" + " -i test if the file is indexed.\n" + " -T provide the sample tag name from the @RG line [SM].\n" + " -o output file [stdout].\n" + " -f load an indexed fasta file in the collection of references. Can be used multiple times.\n" + " -F read a file containing the paths to indexed fasta files. One path per line.\n" + " -X use a custom index file.\n" + "\n" + " Using -f or -F will add a column containing the path to the reference or \".\" if the reference was not found.\n" + "\n" + ); +} + + +/** loads fasta fai file into FaidxPath, add it to params->faidx */ +static int load_dictionary(struct Params* params, const char* filename) { + FaidxPath* head = params->faidx; + FaidxPath* ptr = (FaidxPath*)malloc(sizeof(FaidxPath)); + if (ptr == NULL) { + print_error_errno("samples", "Out of memory"); + return EXIT_FAILURE; + } + ptr->filename = strdup(filename); + if (ptr->filename == NULL) { + free(ptr); + print_error_errno("samples", "Out of memory"); + return EXIT_FAILURE; + } + ptr->faidx = fai_load(filename); + if (ptr->faidx == NULL) { + free(ptr->filename); + free(ptr); + print_error_errno("samples", "Cannot load index from \"%s\"", filename); + return EXIT_FAILURE; + } + /* insert at the beginning of the linked list */ + params->faidx = ptr; + ptr->next = head; + return EXIT_SUCCESS; +} + +/** load a faidx file and append it to params */ +static int load_dictionaries(Params* params, const char* filename) { + int ret; + htsFile* in; + int status = EXIT_SUCCESS; + + in = hts_open(filename, "r"); + if (in == NULL) { + print_error_errno("samples", "Cannot open \"%s\"", filename); + status = EXIT_FAILURE; + } else { + kstring_t ks = KS_INITIALIZE; + while ((ret = hts_getline(in, KS_SEP_LINE, &ks)) >= 0) { + if (load_dictionary(params, ks_str(&ks)) != EXIT_SUCCESS) { + status = EXIT_FAILURE; + break; + } + } + ks_free(&ks); + hts_close(in); + } + return status; +} + +/** print the sample information, search for a reference */ +static int print_sample( + Params* params, + sam_hdr_t *header, + int has_index, + const char* sample, + const char* fname) { + fputs(sample, params->out); + fputc('\t', params->out); + fputs(fname, params->out); + if (params->test_index) { + fprintf(params->out, "\t%c", has_index ? 'Y' : 'N'); + } + if (params->faidx != NULL) { + FaidxPath* ref = NULL; + FaidxPath* curr = params->faidx; + while (curr != NULL) { + /** check names and length are the same in the same order */ + if (faidx_nseq(curr->faidx) == header->n_targets) { + int i; + for (i = 0; i < faidx_nseq(curr->faidx); i++) { + /** check name is the same */ + if (strcmp(faidx_iseq(curr->faidx, i), header->target_name[i]) != 0) break; + /** check length is the same */ + if (faidx_seq_len(curr->faidx, faidx_iseq(curr->faidx, i)) != header->target_len[i]) break; + } + /* the ref was found */ + if (i == faidx_nseq(curr->faidx)) { + ref = curr; + break; + } + } + curr = curr->next; + } + fputc('\t', params->out); + if (ref == NULL) { + fputc('.', params->out); + } else { + fputs(curr->filename, params->out); + } + } + fputc('\n', params->out); + return 0; +} + +/** open a sam file. Search for all samples in the @RG lines */ +static int print_samples(Params* params, const char* fname, const char* baifname) { + samFile *in = 0; + sam_hdr_t *header = NULL; + int n_rg; + int status = EXIT_SUCCESS; + khash_t(sm) *sample_set = NULL; + khint_t k; + int count_samples = 0; + int has_index = 0; + + if ((sample_set = kh_init(sm)) == NULL) { + print_error("samples", "Failed to initialise sample hash"); + status = EXIT_FAILURE; + goto end_print; + } + + if ((in = sam_open_format(fname, "r", NULL)) == 0) { + print_error_errno("samples", "Failed to open \"%s\" for reading", fname); + status = EXIT_FAILURE; + goto end_print; + } + if ((header = sam_hdr_read(in)) == 0) { + print_error("samples", "Failed to read the header from \"%s\"", fname); + status = EXIT_FAILURE; + goto end_print; + } + + /* try to load index if required */ + if (params->test_index) { + hts_idx_t *bam_idx; + /* path to bam index was specified */ + if (baifname != NULL) { + bam_idx = sam_index_load3(in, fname, baifname, HTS_IDX_SILENT_FAIL); + } + /* get default index */ + else { + bam_idx = sam_index_load3(in, fname, NULL, HTS_IDX_SILENT_FAIL); + } + has_index = bam_idx != NULL; + if (bam_idx != NULL) hts_idx_destroy(bam_idx); + /* and we continue... we have tested the index file but we always test for the samples and the references */ + } + + /* get the RG lines */ + n_rg = sam_hdr_count_lines(header, "RG"); + if (n_rg > 0) { + int i, r, ret; + char* sample; + kstring_t sm_val = KS_INITIALIZE; + for (i = 0; i < n_rg; i++) { + r = sam_hdr_find_tag_pos(header, "RG", i, params->tag, &sm_val); + if (r < 0) continue; + k = kh_get(sm, sample_set, ks_str(&sm_val)); + if (k != kh_end(sample_set)) continue; + sample = strdup(ks_str(&sm_val)); + if (sample == NULL) { + print_error_errno("samples", "Out of memory"); + status = EXIT_FAILURE; + goto end_print; + } + kh_put(sm, sample_set, sample, &ret); + if (ret < 0) { + print_error("samples", "Failed to insert key '%s' into sample_set", sample); + free(sample); + status = EXIT_FAILURE; + goto end_print; + } + ++count_samples; + } + ks_free(&sm_val); + } + if (count_samples == 0) { + print_sample(params, header, has_index, ".", fname); + } else { + for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) { + if (kh_exist(sample_set, k)) { + char* sample = (char*)kh_key(sample_set, k); + print_sample(params, header, has_index, sample, fname); + } + } + } + +end_print: + if (sample_set != NULL) { + for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) { + if (kh_exist(sample_set, k)) { + char* sample = (char*)kh_key(sample_set, k); + free(sample); + } + } + kh_destroy(sm, sample_set); + } + if (header != NULL) sam_hdr_destroy(header); + if (in != NULL) sam_close(in); + + return status; +} + + +int main_samples(int argc, char** argv) { + int status = EXIT_SUCCESS; + int print_header = 0; + int has_index_file = 0; + Params params; + char* out_filename = NULL; + FaidxPath* fai; + + strcpy(params.tag, "SM"); + params.faidx = NULL; + params.test_index =0; + + int opt; + while ((opt = getopt_long(argc, argv, "?hiXo:f:F:T:", NULL, NULL)) != -1) { + switch (opt) { + case 'h': + print_header = 1; + break; + case 'o': + out_filename = optarg; + break; + case 'i': + params.test_index = 1; + break; + case 'f': + if (load_dictionary(¶ms, optarg) != EXIT_SUCCESS) { + return EXIT_FAILURE; + } + break; + case 'F': + if (load_dictionaries(¶ms, optarg) != EXIT_SUCCESS) { + return EXIT_FAILURE; + } + break; + case 'T': + if (strlen(optarg) != 2) { + print_error("samples", "Length of tag \"%s\" is not 2.", optarg); + return EXIT_FAILURE; + } + strcpy(params.tag, optarg); + break; + case '?': + usage_samples(stdout); + return EXIT_SUCCESS; + case 'X': + has_index_file = 1; + break; + default: + usage_samples(stderr); + return EXIT_FAILURE; + } + } + + /* if no file was provided and input is the terminal, print the usage and exit */ + if (argc == optind && isatty(STDIN_FILENO)) { + usage_samples(stderr); + return EXIT_FAILURE; + } + + if (out_filename != NULL) { + params.out = fopen(out_filename, "w"); + if (params.out == NULL) { + print_error_errno("samples", "Cannot open \"%s\" for writing", out_filename); + return EXIT_FAILURE; + } + } else { + params.out = stdout; + } + + if (print_header) { + fprintf(params.out, "#%s\tPATH", params.tag); + if (params.test_index) fprintf(params.out, "\tINDEX"); + if (params.faidx != NULL) fprintf(params.out, "\tREFERENCE"); + fprintf(params.out, "\n"); + } + + /* no file was provided, input is stdin, each line contains the path to a bam file */ + if (argc == optind) { + htsFile* fp = hts_open("-", "r"); + if (fp == NULL) { + print_error_errno("samples", "Cannot read from stdin"); + status = EXIT_FAILURE; + } else { + kstring_t ks = KS_INITIALIZE; + int ret; + while ((ret = hts_getline(fp, KS_SEP_LINE, &ks)) >= 0) { + char* bai_path = NULL; + if (has_index_file) { + /* bam path and bam index file are separated by a tab */ + char* tab = strchr(ks_str(&ks), '\t'); + if (tab == NULL || *(tab+1) == '\0') { + print_error_errno("samples", "Expected path-to-bam(tab)path-to-index but got \"%s\"", ks_str(&ks)); + status = EXIT_FAILURE; + break; + } + *tab=0; + bai_path = (tab + 1); + } + if (print_samples(¶ms, ks_str(&ks), bai_path) != EXIT_SUCCESS) { + status = EXIT_FAILURE; + break; + } + } + ks_free(&ks); + hts_close(fp); + } + } + /* loop over each file in argc/argv bam index provided */ + else if (has_index_file) { + /* calculate number of input BAM files */ + if ((argc - optind) % 2 != 0) { + print_error("samples","Odd number of filenames detected! Each BAM file should have an index file"); + status = EXIT_FAILURE; + } else { + int i; + int n = (argc - optind ) / 2; + for (i = 0; i < n; i++) { + if (print_samples(¶ms, argv[optind+i], argv[optind+i+n]) != EXIT_SUCCESS) { + status = EXIT_FAILURE; + break; + } + } + } + } else { + int i; + for (i = optind; i < argc; i++) { + if (print_samples(¶ms, argv[i], NULL) != EXIT_SUCCESS) { + status = EXIT_FAILURE; + break; + } + } + } + + fai = params.faidx; + while (fai != NULL) { + FaidxPath* next = fai -> next; + free(fai->filename); + fai_destroy(fai->faidx); + free(fai); + fai = next; + } + + if (fflush(params.out) != 0) { + print_error_errno("samples", "Cannot flush output"); + status = EXIT_FAILURE; + } + if (out_filename != NULL) { + fclose(params.out); + } + + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_sort.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_sort.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..80aa4d8076d7abea0994be7684bb43159d85e690 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_sort.c.pysam.c @@ -0,0 +1,3802 @@ +#include "samtools.pysam.h" + +/* bam_sort.c -- sorting and merging. + + Copyright (C) 2008-2023 Genome Research Ltd. + Portions copyright (C) 2009-2012 Broad Institute. + + Author: Heng Li + Author: Martin Pollard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/ksort.h" +#include "htslib/hts_os.h" +#include "htslib/khash.h" +#include "htslib/klist.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" +#include "htslib/hts_endian.h" +#include "htslib/cram.h" +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "samtools.h" +#include "bedidx.h" +#include "bam.h" + +//#define DEBUG_MINHASH + +#define BAM_BLOCK_SIZE 2*1024*1024 +#define MAX_TMP_FILES 64 + +// Struct which contains the sorting key for TemplateCoordinate sort. +typedef struct { + int tid1; + int tid2; + hts_pos_t pos1; + hts_pos_t pos2; + bool neg1; + bool neg2; + const char *library; + char *mid; + char *name; + bool is_upper_of_pair; +} template_coordinate_key_t; + +// Struct to store fixed buffers of template coordinate keys +typedef struct { + size_t n; // the # of keys stored + size_t m; // the # of buffers allocated + size_t buffer_size; // # the fixed size of each buffer + template_coordinate_key_t **buffers; // the list of buffers +} template_coordinate_keys_t; + +// Gets the idx'th key; does not OOB check +static template_coordinate_key_t* template_coordinate_keys_get(template_coordinate_keys_t *keys, size_t idx) { + size_t buffer_idx = idx / keys->buffer_size; // the index of the buffer to retrieve in buffer + size_t buffer_offset = idx % keys->buffer_size; // the offset into the given buffer to retrieve + //assert(buffer_idx < keys->m); + //assert(buffer_offset < keys->buffer_size); + return &keys->buffers[buffer_idx][buffer_offset]; +} + +// Rellocates the buffers to hold at least max_k entries +static int template_coordinate_keys_realloc(template_coordinate_keys_t *keys, int max_k) { + size_t cur_m = keys->m; + keys->m += 0x100; + //assert(keys->m > cur_m); + //assert(keys->m * keys->buffer_size >= max_k); + if ((keys->buffers = realloc(keys->buffers, keys->m * sizeof(template_coordinate_key_t*))) == NULL) { + print_error("sort", "couldn't reallocate memory for template coordinate key buffers"); + return -1; + } + // allocate space for new buffers + int j; + for (j = cur_m; j < keys->m; ++j) { + if ((keys->buffers[j]= malloc(sizeof(template_coordinate_key_t) * keys->buffer_size)) == NULL) { + print_error("sort", "couldn't allocate memory for template coordinate key buffer"); + return -1; + } + } + return 0; +} + + +// Struct which contains the a record, and the pointer to the sort tag (if any) or +// a combined ref / position / strand. +// Used to speed up sorts (coordinate, by-tag, and template-coordinate). +typedef struct bam1_tag { + bam1_t *bam_record; + union { + const uint8_t *tag; + uint8_t pos_tid[12]; + template_coordinate_key_t *key; + } u; +} bam1_tag; + +/* Minimum memory required in megabytes before sort will attempt to run. This + is to prevent accidents where failing to use the -m option correctly results + in the creation of a temporary file for each read in the input file. + Don't forget to update the man page if you change this. */ +const size_t SORT_MIN_MEGS_PER_THREAD = 1; + +/* Default per-thread memory for sort. Must be >= SORT_MIN_MEGS_PER_THREAD. + Don't forget to update the man page if you change this. */ +const size_t SORT_DEFAULT_MEGS_PER_THREAD = 768; + +#if !defined(__DARWIN_C_LEVEL) || __DARWIN_C_LEVEL < 900000L +#define NEED_MEMSET_PATTERN4 +#endif + +#ifdef NEED_MEMSET_PATTERN4 +void memset_pattern4(void *target, const void *pattern, size_t size) { + uint32_t* target_iter = target; + size_t loops = size/4; + size_t i; + for (i = 0; i < loops; ++i) { + memcpy(target_iter, pattern, 4); + ++target_iter; + } + if (size%4 != 0) + memcpy(target_iter, pattern, size%4); +} +#endif + +KHASH_INIT(c2c, char*, char*, 1, kh_str_hash_func, kh_str_hash_equal) +KHASH_INIT(cset, char*, char, 0, kh_str_hash_func, kh_str_hash_equal) +KHASH_MAP_INIT_STR(c2i, int) +KHASH_MAP_INIT_STR(const_c2c, char *) + +#define hdrln_free_char(p) +KLIST_INIT(hdrln, char*, hdrln_free_char) + +static template_coordinate_key_t* template_coordinate_key(bam1_t *b, template_coordinate_key_t *key, sam_hdr_t *hdr, khash_t(const_c2c) *lib_lookup); + +typedef enum {Coordinate, QueryName, TagCoordinate, TagQueryName, MinHash, TemplateCoordinate} SamOrder; +static SamOrder g_sam_order = Coordinate; +static char g_sort_tag[2] = {0,0}; + +#define is_digit(c) ((c)<='9' && (c)>='0') +static int strnum_cmp(const char *_a, const char *_b) +{ + const unsigned char *a = (const unsigned char*)_a, *b = (const unsigned char*)_b; + const unsigned char *pa = a, *pb = b; + while (*pa && *pb) { + if (!is_digit(*pa) || !is_digit(*pb)) { + if (*pa != *pb) + return (int)*pa - (int)*pb; + ++pa; ++pb; + } else { + // skip leading zeros + while (*pa == '0') ++pa; + while (*pb == '0') ++pb; + + // skip matching digits + while (is_digit(*pa) && *pa == *pb) + pa++, pb++; + + // Now mismatching, so see which ends the number sooner + int diff = (int)*pa - (int)*pb; + while (is_digit(*pa) && is_digit(*pb)) + pa++, pb++; + + if (is_digit(*pa)) + return 1; // pa still going, so larger + else if (is_digit(*pb)) + return -1; // pb still going, so larger + else if (diff) + return diff; // same length, so earlier diff + } + } + return *pa? 1 : *pb? -1 : 0; +} + +#define HEAP_EMPTY (UINT64_MAX >> 1) + +typedef struct { + int i; + uint32_t tid; + uint64_t pos:63, rev:1, idx; + bam1_tag entry; +} heap1_t; + +static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b); +static inline int bam1_cmp_by_minhash(const bam1_tag a, const bam1_tag b); +static inline int bam1_cmp_template_coordinate(const bam1_tag a, const bam1_tag b); +static khash_t(const_c2c) * lookup_libraries(sam_hdr_t *header); +static void lib_lookup_destroy(khash_t(const_c2c) *lib_lookup); + +// Function to compare reads in the heap and determine which one is < the other +// Note, unlike the bam1_cmp_by_X functions which return <0, 0, >0 this +// is strictly 0 or 1 only. +static inline int heap_lt(const heap1_t a, const heap1_t b) +{ + if (!a.entry.bam_record) + return 1; + if (!b.entry.bam_record) + return 0; + + int t, fa, fb; + switch (g_sam_order) { + case Coordinate: + if (a.tid != b.tid) return a.tid > b.tid; + if (a.pos != b.pos) return a.pos > b.pos; + if (a.rev != b.rev) return a.rev > b.rev; + break; + case QueryName: + t = strnum_cmp(bam_get_qname(a.entry.bam_record), bam_get_qname(b.entry.bam_record)); + if (t != 0) return t > 0; + fa = a.entry.bam_record->core.flag & 0xc0; + fb = b.entry.bam_record->core.flag & 0xc0; + if (fa != fb) return fa > fb; + break; + case TagQueryName: + case TagCoordinate: + t = bam1_cmp_by_tag(a.entry, b.entry); + if (t != 0) return t > 0; + break; + case MinHash: + t = bam1_cmp_by_minhash(a.entry, b.entry); + if (t != 0) return t > 0; + break; + case TemplateCoordinate: + t = bam1_cmp_template_coordinate(a.entry, b.entry); + if (t != 0) return t > 0; + break; + default: + print_error("heap_lt", "unknown sort order: %d", g_sam_order); + break; + } + + // This compares by position in the input file(s) + if (a.i != b.i) return a.i > b.i; + return a.idx > b.idx; +} + +KSORT_INIT(heap, heap1_t, heap_lt) + +typedef struct merged_header { + sam_hdr_t *hdr; + kstring_t out_rg; + kstring_t out_pg; + kstring_t out_co; + char **target_name; + uint32_t *target_len; + size_t n_targets; + size_t targets_sz; + khash_t(c2i) *sq_tids; + khash_t(cset) *rg_ids; + khash_t(cset) *pg_ids; + bool have_hd; +} merged_header_t; + +typedef struct trans_tbl { + int32_t n_targets; + int* tid_trans; + kh_c2c_t* rg_trans; + kh_c2c_t* pg_trans; + bool lost_coord_sort; +} trans_tbl_t; + +static void trans_tbl_destroy(trans_tbl_t *tbl) { + khiter_t iter; + + free(tbl->tid_trans); + + /* + * The values for the tbl->rg_trans and tbl->pg_trans hashes are pointers + * to keys in the rg_ids and pg_ids sets of the merged_header_t, so + * they should not be freed here. + * + * The keys are unique to each hash entry, so they do have to go. + */ + + for (iter = kh_begin(tbl->rg_trans); iter != kh_end(tbl->rg_trans); ++iter) { + if (kh_exist(tbl->rg_trans, iter)) { + free(kh_key(tbl->rg_trans, iter)); + } + } + for (iter = kh_begin(tbl->pg_trans); iter != kh_end(tbl->pg_trans); ++iter) { + if (kh_exist(tbl->pg_trans, iter)) { + free(kh_key(tbl->pg_trans, iter)); + } + } + + kh_destroy(c2c,tbl->rg_trans); + kh_destroy(c2c,tbl->pg_trans); +} + +/* + * Create a merged_header_t struct. + */ + +static merged_header_t * init_merged_header() { + merged_header_t *merged_hdr; + + merged_hdr = calloc(1, sizeof(*merged_hdr)); + if (merged_hdr == NULL) return NULL; + + merged_hdr->hdr = sam_hdr_init(); + if (!merged_hdr->hdr) goto fail; + + merged_hdr->targets_sz = 16; + merged_hdr->target_name = malloc(merged_hdr->targets_sz + * sizeof(*merged_hdr->target_name)); + if (NULL == merged_hdr->target_name) goto fail; + + merged_hdr->target_len = malloc(merged_hdr->targets_sz + * sizeof(*merged_hdr->target_len)); + if (NULL == merged_hdr->target_len) goto fail; + + merged_hdr->sq_tids = kh_init(c2i); + if (merged_hdr->sq_tids == NULL) goto fail; + + merged_hdr->rg_ids = kh_init(cset); + if (merged_hdr->rg_ids == NULL) goto fail; + + merged_hdr->pg_ids = kh_init(cset); + if (merged_hdr->pg_ids == NULL) goto fail; + + return merged_hdr; + + fail: + perror("[init_merged_header]"); + kh_destroy(cset, merged_hdr->pg_ids); + kh_destroy(cset, merged_hdr->rg_ids); + kh_destroy(c2i, merged_hdr->sq_tids); + free(merged_hdr->target_name); + free(merged_hdr->target_len); + sam_hdr_destroy(merged_hdr->hdr); + free(merged_hdr); + return NULL; +} + +/* Some handy kstring manipulating functions */ + +// Append char range to kstring +static inline int range_to_ks(const char *src, int from, int to, + kstring_t *dest) { + return kputsn(src + from, to - from, dest) != to - from; +} + +// Append a kstring to a kstring +static inline int ks_to_ks(kstring_t *src, kstring_t *dest) { + return kputsn(ks_str(src), ks_len(src), dest) != ks_len(src); +} + +/* + * Generate a unique ID by appending a random suffix to a given prefix. + * existing_ids is the set of IDs that are already in use. + * If always_add_suffix is true, the suffix will always be included. + * If false, prefix will be returned unchanged if it isn't in existing_ids. + */ + +static int gen_unique_id(char *prefix, khash_t(cset) *existing_ids, + bool always_add_suffix, kstring_t *dest) { + khiter_t iter; + + if (!always_add_suffix) { + // Try prefix on its own first + iter = kh_get(cset, existing_ids, prefix); + if (iter == kh_end(existing_ids)) { // prefix isn't used yet + dest->l = 0; + if (kputs(prefix, dest) == EOF) return -1; + return 0; + } + } + + do { + dest->l = 0; + ksprintf(dest, "%s-%0lX", prefix, lrand48()); + iter = kh_get(cset, existing_ids, ks_str(dest)); + } while (iter != kh_end(existing_ids)); + + return 0; +} + +/* + * Add the @HD line to the new header + * In practice the @HD line will come from the first input header. + */ + +static int trans_tbl_add_hd(merged_header_t* merged_hdr, + sam_hdr_t *translate) { + kstring_t hd_line = { 0, 0, NULL }; + int res; + + // TODO: handle case when @HD needs merging. + if (merged_hdr->have_hd) return 0; + + res = sam_hdr_find_hd(translate, &hd_line); + if (res < -1) { + print_error("merge", "failed to get @HD line from header"); + return -1; + } + + if (res < 0) // Not found + return 0; + + if (sam_hdr_add_lines(merged_hdr->hdr, hd_line.s, hd_line.l) < 0) { + print_error("merge", "failed to add @HD line to new header"); + free(hd_line.s); + return -1; + } + + free(hd_line.s); + merged_hdr->have_hd = true; + + return 0; +} + +/* + * Add @SQ records to the translation table. + * + * Go through the target list for the input header. Any new targets found + * are added to the output header target list. At the same time, a mapping + * from the input to output target ids is stored in tbl. + * + * If any new targets are found, the header text is scanned to find the + * corresponding @SQ records. They are then copied into the + * merged_hdr->out_text kstring (which will eventually become the + * output header text). + * + * Returns 0 on success, -1 on failure. + */ + +static int trans_tbl_add_sq(merged_header_t* merged_hdr, sam_hdr_t *translate, + trans_tbl_t* tbl) { + int32_t i; + int min_tid = -1, res; + kstring_t sq_line = { 0, 0, NULL }, sq_sn = { 0, 0, NULL }; + + // Fill in the tid part of the translation table, adding new targets + // to the merged header as we go. + + for (i = 0; i < sam_hdr_nref(translate); ++i) { + int trans_tid; + sq_sn.l = 0; + res = sam_hdr_find_tag_pos(translate, "SQ", i, "SN", &sq_sn); + if (res < 0) { + print_error("merge", "failed to get @SQ SN #%d from header", i + 1); + goto fail; + } + + trans_tid = sam_hdr_name2tid(merged_hdr->hdr, sq_sn.s); + if (trans_tid < -1) { + print_error("merge", "failed to lookup ref"); + goto fail; + } + + if (trans_tid < 0) { + // Append missing entries to out_hdr + sq_line.l = 0; + res = sam_hdr_find_line_id(translate, "SQ", "SN", sq_sn.s, &sq_line); + if (res < 0) { + print_error("merge", "failed to get @SQ SN:%s from header", sq_sn.s); + goto fail; + } + + trans_tid = sam_hdr_nref(merged_hdr->hdr); + + res = sam_hdr_add_lines(merged_hdr->hdr, sq_line.s, sq_line.l); + if (res < 0) { + print_error("merge", "failed to add @SQ SN:%s to new header", sq_sn.s); + goto fail; + } + } + tbl->tid_trans[i] = trans_tid; + + if (tbl->tid_trans[i] > min_tid) { + min_tid = tbl->tid_trans[i]; + } else { + tbl->lost_coord_sort = true; + } + } + + free(sq_line.s); + free(sq_sn.s); + + return 0; + + fail: + free(sq_line.s); + free(sq_sn.s); + return -1; +} + +/* + * Common code for setting up RG and PG record ID tag translation. + * + * is_rg is true for RG translation, false for PG. + * translate is the input bam header + * merge is true if tags with the same ID are to be merged. + * known_ids is the set of IDs already in the output header. + * id_map is the translation map from input header IDs to output header IDs + * If override is set, it will be used to replace the existing ID (RG only) + * + * known_ids and id_map have entries for the new IDs added to them. + * + * Return value is a linked list of header lines with the translated IDs, + * or NULL if something went wrong (probably out of memory). + * + */ + +static klist_t(hdrln) * trans_rg_pg(bool is_rg, sam_hdr_t *translate, + bool merge, khash_t(cset)* known_ids, + khash_t(c2c)* id_map, char *override) { + khiter_t iter; + int num_ids, i; + const char *rec_type = is_rg ? "RG" : "PG"; + klist_t(hdrln) *hdr_lines; + + hdr_lines = kl_init(hdrln); + + // Search through translate's header + num_ids = sam_hdr_count_lines(translate, rec_type); + if (num_ids < 0) + goto fail; + + for (i = 0; i < num_ids; i++) { + kstring_t orig_id = { 0, 0, NULL }; // ID in original header + kstring_t transformed_id = { 0, 0, NULL }; // ID in output header + char *map_value; // Value to store in id_map + bool id_changed; // Have we changed the ID? + bool not_found_in_output; // ID isn't in the output header (yet) + + if (sam_hdr_find_tag_pos(translate, rec_type, i, "ID", &orig_id) < 0) + goto fail; + + // is our matched ID in our output ID set already? + iter = kh_get(cset, known_ids, ks_str(&orig_id)); + not_found_in_output = (iter == kh_end(known_ids)); + + if (override) { + // Override original ID (RG only) +#ifdef OVERRIDE_DOES_NOT_MERGE + if (gen_unique_id(override, known_ids, false, &transformed_id)) + goto memfail; + not_found_in_output = true; // As ID now unique +#else + if (kputs(override, &transformed_id) == EOF) goto memfail; + // Know about override already? + iter = kh_get(cset, known_ids, ks_str(&transformed_id)); + not_found_in_output = (iter == kh_end(known_ids)); +#endif + id_changed = true; + } else { + if ( not_found_in_output || merge) { + // Not in there or merging so can add it as 1-1 mapping + if (ks_to_ks(&orig_id, &transformed_id)) goto memfail; + id_changed = false; + } else { + // It's in there so we need to transform it by appending + // a random number to the id + if (gen_unique_id(ks_str(&orig_id), known_ids, + true, &transformed_id)) + goto memfail; + id_changed = true; + not_found_in_output = true; // As ID now unique + } + } + + // Does this line need to go into our output header? + if (not_found_in_output) { + // Take matched line and replace ID with transformed_id + kstring_t new_hdr_line = { 0, 0, NULL }; + if (sam_hdr_find_line_id(translate, rec_type, + "ID", ks_str(&orig_id), &new_hdr_line) < 0){ + goto fail; + } + + if (id_changed) { + char *idp = strstr(ks_str(&new_hdr_line), "\tID:"), *id_end; + ptrdiff_t id_offset, id_len; + if (!idp) { + print_error("merge", "failed to find ID in \"%s\"\n", + ks_str(&new_hdr_line)); + goto fail; + } + idp += 4; + for (id_end = idp; *id_end >= '\n'; id_end++) {} + + id_offset = idp - new_hdr_line.s; + id_len = id_end - idp; + + if (id_len < transformed_id.l) { + if (ks_resize(&new_hdr_line, new_hdr_line.l + + transformed_id.l - id_len + 1/*nul*/)) + goto fail; + } + if (id_len != transformed_id.l) { + memmove(new_hdr_line.s + id_offset + transformed_id.l, + new_hdr_line.s + id_offset + id_len, + new_hdr_line.l - id_offset - id_len + 1); + } + memcpy(new_hdr_line.s + id_offset, transformed_id.s, + transformed_id.l); + } + + // append line to output linked list + char** ln = kl_pushp(hdrln, hdr_lines); + *ln = ks_release(&new_hdr_line); // Give away to linked list + + // Need to add it to known_ids set + int in_there = 0; + iter = kh_put(cset, known_ids, ks_str(&transformed_id), &in_there); + if (in_there < 0) goto memfail; + assert(in_there > 0); // Should not already be in the map + map_value = ks_release(&transformed_id); + } else { + // Use existing string in id_map + assert(kh_exist(known_ids, iter)); + map_value = kh_key(known_ids, iter); + free(ks_release(&transformed_id)); + } + + // Insert it into our translation map + int in_there = 0; + iter = kh_put(c2c, id_map, ks_release(&orig_id), &in_there); + kh_value(id_map, iter) = map_value; + } + + // If there are no RG lines in the file and we are overriding add one + if (is_rg && override && hdr_lines->size == 0) { + kstring_t new_id = {0, 0, NULL}; + kstring_t line = {0, 0, NULL}; + kstring_t empty = {0, 0, NULL}; + int in_there = 0; + char** ln; + + // Get the new ID + if (gen_unique_id(override, known_ids, false, &new_id)) + goto memfail; + + // Make into a header line and add to linked list + ksprintf(&line, "@RG\tID:%s", ks_str(&new_id)); + ln = kl_pushp(hdrln, hdr_lines); + *ln = ks_release(&line); + + // Put into known_ids set + iter = kh_put(cset, known_ids, ks_str(&new_id), &in_there); + if (in_there < 0) goto memfail; + assert(in_there > 0); // Should be a new entry + + // Put into translation map (key is empty string) + if (kputs("", &empty) == EOF) goto memfail; + iter = kh_put(c2c, id_map, ks_release(&empty), &in_there); + if (in_there < 0) goto memfail; + assert(in_there > 0); // Should be a new entry + kh_value(id_map, iter) = ks_release(&new_id); + } + + return hdr_lines; + + memfail: + perror(__func__); + fail: + if (hdr_lines) kl_destroy(hdrln, hdr_lines); + return NULL; +} + +/* + * Common code for completing RG and PG record translation. + * + * Input is a list of header lines, and the mapping from input to + * output @PG record IDs. + * + * RG and PG records can contain tags that cross-reference to other @PG + * records. This fixes the tags to contain the new IDs before adding + * them to the output header text. + */ + +static int finish_rg_pg(bool is_rg, klist_t(hdrln) *hdr_lines, + khash_t(c2c)* pg_map, kstring_t *out_text) { + const char *search = is_rg ? "\tPG:" : "\tPP:"; + khiter_t idx; + char *line = NULL; + + while ((kl_shift(hdrln, hdr_lines, &line)) == 0) { + char *id = strstr(line, search); // Look for tag to fix + int pos1 = 0, pos2 = 0; + char *new_id = NULL; + + if (id) { + // Found a tag. Look up the value in the translation map + // to see what it should be changed to in the output file. + char *end, tmp; + + id += 4; // Point to value + end = strchr(id, '\t'); // Find end of tag + if (!end) end = id + strlen(id); + + tmp = *end; + *end = '\0'; // Temporarily get the value on its own. + + // Look-up in translation table + idx = kh_get(c2c, pg_map, id); + if (idx == kh_end(pg_map)) { + // Not found, warn. + fprintf(samtools_stderr, "[W::%s] Tag %s%s not found in @PG records\n", + __func__, search + 1, id); + } else { + // Remember new id and splice points on original string + new_id = kh_value(pg_map, idx); + pos1 = id - line; + pos2 = end - line; + } + + *end = tmp; // Restore string + } + + // Copy line to output: + // line[0..pos1), new_id (if not NULL), line[pos2..end), '\n' + + if (pos1 && range_to_ks(line, 0, pos1, out_text)) goto memfail; + if (new_id && kputs(new_id, out_text) == EOF) goto memfail; + if (kputs(line + pos2, out_text) == EOF) goto memfail; + if (kputc('\n', out_text) == EOF) goto memfail; + free(line); // No longer needed + line = NULL; + } + + return 0; + + memfail: + perror(__func__); + free(line); // Prevent leakage as no longer on list + return -1; +} + +/* + * Build the translation table for an input *am file. This stores mappings + * which allow IDs to be converted from those used in the input file + * to the ones which will be used in the output. The mappings are for: + * Reference sequence IDs (for @SQ records) + * @RG record ID tags + * @PG record ID tags + * + * At the same time, new header text is built up by copying records + * from the input bam file. This will eventually become the header for + * the output file. When copied, the ID tags for @RG and @PG records + * are replaced with their values. The @PG PP: and @RG PG: tags + * are also modified if necessary. + * + * merged_hdr holds state on the output header (which IDs are present, etc.) + * translate is the input header + * tbl is the translation table that gets filled in. + * merge_rg controls merging of @RG records + * merge_pg controls merging of @PG records + * If rg_override is not NULL, it will be used to replace the existing @RG ID + * + * Returns 0 on success, -1 on failure. + */ + +static int trans_tbl_init(merged_header_t* merged_hdr, sam_hdr_t* translate, + trans_tbl_t* tbl, bool merge_rg, bool merge_pg, + bool copy_co, char* rg_override) +{ + kstring_t lines = { 0, 0, NULL }; + klist_t(hdrln) *rg_list = NULL; + klist_t(hdrln) *pg_list = NULL; + + tbl->n_targets = sam_hdr_nref(translate); + tbl->rg_trans = tbl->pg_trans = NULL; + tbl->tid_trans = (int*)calloc(tbl->n_targets ? tbl->n_targets : 1, + sizeof(int)); + if (tbl->tid_trans == NULL) goto memfail; + tbl->rg_trans = kh_init(c2c); + if (tbl->rg_trans == NULL) goto memfail; + tbl->pg_trans = kh_init(c2c); + if (tbl->pg_trans == NULL) goto memfail; + + tbl->lost_coord_sort = false; + + // Get the @HD record (if not there already). + if (trans_tbl_add_hd(merged_hdr, translate)) goto fail; + + // Fill in map and add header lines for @SQ records + if (trans_tbl_add_sq(merged_hdr, translate, tbl)) goto fail; + + // Get translated header lines and fill in map for @RG records + rg_list = trans_rg_pg(true, translate, merge_rg, merged_hdr->rg_ids, + tbl->rg_trans, rg_override); + if (!rg_list) goto fail; + + // Get translated header lines and fill in map for @PG records + pg_list = trans_rg_pg(false, translate, merge_pg, merged_hdr->pg_ids, + tbl->pg_trans, NULL); + if (!pg_list) goto fail; + + // Fix-up PG: tags in the new @RG records and add to output + if (finish_rg_pg(true, rg_list, tbl->pg_trans, &merged_hdr->out_rg)) + goto fail; + + // Fix-up PP: tags in the new @PG records and add to output + lines.l = 0; + if (finish_rg_pg(false, pg_list, tbl->pg_trans, &merged_hdr->out_pg)) + goto fail; + + kl_destroy(hdrln, rg_list); rg_list = NULL; + kl_destroy(hdrln, pg_list); pg_list = NULL; + + if (copy_co) { + // Just append @CO headers without translation + int num_co = sam_hdr_count_lines(translate, "CO"), i; + if (num_co < 0) + goto fail; + + for (i = 0; i < num_co; i++) { + if (sam_hdr_find_line_pos(translate, "CO", i, &lines) < 0) + goto fail; + if (ks_to_ks(&lines, &merged_hdr->out_co)) + goto fail; + if (kputc('\n', &merged_hdr->out_co) < 0) + goto fail; + } + } + + free(lines.s); + + return 0; + + memfail: + perror(__func__); + fail: + trans_tbl_destroy(tbl); + if (rg_list) kl_destroy(hdrln, rg_list); + if (pg_list) kl_destroy(hdrln, pg_list); + free(lines.s); + return -1; +} + +static int finish_merged_header(merged_header_t *merged_hdr) { + if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_rg), + ks_len(&merged_hdr->out_rg)) < 0) + return -1; + if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_pg), + ks_len(&merged_hdr->out_pg)) < 0) + return -1; + if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_co), + ks_len(&merged_hdr->out_co)) < 0) + return -1; + + return 0; +} + +/* + * Free a merged_header_t struct and all associated data. + * + * Note that the keys to the rg_ids and pg_ids sets are also used as + * values in the translation tables. This function should therefore not + * be called until the translation tables are no longer needed. + */ + +static void free_merged_header(merged_header_t *merged_hdr) { + size_t i; + khiter_t iter; + if (!merged_hdr) return; + free(ks_release(&merged_hdr->out_rg)); + free(ks_release(&merged_hdr->out_pg)); + free(ks_release(&merged_hdr->out_co)); + if (merged_hdr->target_name) { + for (i = 0; i < merged_hdr->n_targets; i++) { + free(merged_hdr->target_name[i]); + } + free(merged_hdr->target_name); + } + free(merged_hdr->target_len); + kh_destroy(c2i, merged_hdr->sq_tids); + + if (merged_hdr->rg_ids) { + for (iter = kh_begin(merged_hdr->rg_ids); + iter != kh_end(merged_hdr->rg_ids); ++iter) { + if (kh_exist(merged_hdr->rg_ids, iter)) + free(kh_key(merged_hdr->rg_ids, iter)); + } + kh_destroy(cset, merged_hdr->rg_ids); + } + + if (merged_hdr->pg_ids) { + for (iter = kh_begin(merged_hdr->pg_ids); + iter != kh_end(merged_hdr->pg_ids); ++iter) { + if (kh_exist(merged_hdr->pg_ids, iter)) + free(kh_key(merged_hdr->pg_ids, iter)); + } + kh_destroy(cset, merged_hdr->pg_ids); + } + + free(merged_hdr); +} + +static void bam_translate(bam1_t* b, trans_tbl_t* tbl) +{ + // Update target id if not unmapped tid + if ( b->core.tid >= 0 ) { b->core.tid = tbl->tid_trans[b->core.tid]; } + if ( b->core.mtid >= 0 ) { b->core.mtid = tbl->tid_trans[b->core.mtid]; } + + // If we have a RG update it + uint8_t *rg = bam_aux_get(b, "RG"); + if (rg) { + char* decoded_rg = bam_aux2Z(rg); + khiter_t k = kh_get(c2c, tbl->rg_trans, decoded_rg); + if (k != kh_end(tbl->rg_trans)) { + char* translate_rg = kh_value(tbl->rg_trans,k); + bam_aux_del(b, rg); + if (translate_rg) { + bam_aux_append(b, "RG", 'Z', strlen(translate_rg) + 1, + (uint8_t*)translate_rg); + } + } else { + char *tmp = strdup(decoded_rg); + fprintf(samtools_stderr, + "[bam_translate] RG tag \"%s\" on read \"%s\" encountered " + "with no corresponding entry in header, tag lost. " + "Unknown tags are only reported once per input file for " + "each tag ID.\n", + decoded_rg, bam_get_qname(b)); + bam_aux_del(b, rg); + // Prevent future whinges + if (tmp) { + int in_there = 0; + k = kh_put(c2c, tbl->rg_trans, tmp, &in_there); + if (in_there > 0) kh_value(tbl->rg_trans, k) = NULL; + } + } + } + + // If we have a PG update it + uint8_t *pg = bam_aux_get(b, "PG"); + if (pg) { + char* decoded_pg = bam_aux2Z(pg); + khiter_t k = kh_get(c2c, tbl->pg_trans, decoded_pg); + if (k != kh_end(tbl->pg_trans)) { + char* translate_pg = kh_value(tbl->pg_trans,k); + bam_aux_del(b, pg); + if (translate_pg) { + bam_aux_append(b, "PG", 'Z', strlen(translate_pg) + 1, + (uint8_t*)translate_pg); + } + } else { + char *tmp = strdup(decoded_pg); + fprintf(samtools_stderr, + "[bam_translate] PG tag \"%s\" on read \"%s\" encountered " + "with no corresponding entry in header, tag lost. " + "Unknown tags are only reported once per input file for " + "each tag ID.\n", + decoded_pg, bam_get_qname(b)); + bam_aux_del(b, pg); + // Prevent future whinges + if (tmp) { + int in_there = 0; + k = kh_put(c2c, tbl->pg_trans, tmp, &in_there); + if (in_there > 0) kh_value(tbl->pg_trans, k) = NULL; + } + } + } +} + +int* rtrans_build(int n, int n_targets, trans_tbl_t* translation_tbl) +{ + // Create reverse translation table for tids + int* rtrans = (int*)malloc(sizeof(int32_t)*n*n_targets); + const int32_t NOTID = INT32_MIN; + if (!rtrans) return NULL; + memset_pattern4((void*)rtrans, &NOTID, sizeof(int32_t)*n*n_targets); + int i; + for (i = 0; i < n; ++i) { + int j; + for (j = 0; j < (translation_tbl+i)->n_targets; ++j) { + if ((translation_tbl+i)->tid_trans[j] != -1) { + rtrans[i*n_targets + (translation_tbl+i)->tid_trans[j]] = j; + } + } + } + + return rtrans; +} + +#define MERGE_RG 1 // Attach RG tag based on filename +#define MERGE_UNCOMP 2 // Generate uncompressed BAM +#define MERGE_LEVEL1 4 // Compress the BAM at level 1 (fast) mode +#define MERGE_FORCE 8 // Overwrite output BAM if it exists +#define MERGE_COMBINE_RG 16 // Combine RG tags frather than redefining them +#define MERGE_COMBINE_PG 32 // Combine PG tags frather than redefining them +#define MERGE_FIRST_CO 64 // Use only first file's @CO headers (sort cmd only) + + +static hts_reglist_t *duplicate_reglist(const hts_reglist_t *rl, int rn) { + if (!rl) + return NULL; + + hts_reglist_t *new_rl = calloc(rn, sizeof(hts_reglist_t)); + if (!new_rl) + return NULL; + + int i; + for (i=0; i < rn; i++) { + new_rl[i].tid = rl[i].tid; + new_rl[i].count = rl[i].count; + new_rl[i].min_beg = rl[i].min_beg; + new_rl[i].max_end = rl[i].max_end; + + new_rl[i].reg = rl[i].reg; + new_rl[i].intervals = malloc(new_rl[i].count * sizeof(hts_pair_pos_t)); + if (!new_rl[i].intervals) { + hts_reglist_free(new_rl, i); + return NULL; + } + memcpy(new_rl[i].intervals, rl[i].intervals, new_rl[i].count * sizeof(hts_pair_pos_t)); + } + + return new_rl; +} + +/* + * How merging is handled + * + * If a header is defined use we will use that as our output header + * otherwise we use the first header from the first input file. + * + * Now go through each file and create a translation table for that file for: + * -RG + * -tid + * -PG tags + * + * Then whenever we read a record from a bam we translate that read before + * stashing it in the hash. + * + * In the actual merge, a read is read from each input file, translated and + * stashed in the hash. This assumes that all input files are sorted in the + * same way. Next we just extract the next position ordered read from the + * hash, and replace it if there are still reads left in it's source input + * file. Finally we write our chosen read it to the output file. + */ + +/*! + @abstract Merge multiple sorted BAM. + @param sam_order the order in which the data was sorted + @param sort_tag if non-null, the tag that data was sorted by + @param out output BAM file name + @param mode sam_open() mode to be used to create the final output file + (overrides level settings from UNCOMP and LEVEL1 flags) + @param headers name of SAM file from which to copy '@' header lines, + or NULL to copy them from the first file to be merged + @param n number of files to be merged + @param fn names of files to be merged + @param flag flags that control how the merge is undertaken + @param reg region to merge + @param n_threads number of threads to use (passed to htslib) + @param cmd command name (used in print_error() etc) + @param in_fmt format options for input files + @param out_fmt output file format and options + @param write_index create the index, together with the output file + @param arg_list command string for PG line + @param no_pg if 1, do not add a new PG line + @discussion Padding information may NOT correctly maintained. This + function is NOT thread safe. + */ +int bam_merge_core2(SamOrder sam_order, char* sort_tag, const char *out, const char *mode, + const char *headers, int n, char * const *fn, char * const *fn_idx, + const char *fn_bed, int flag, const char *reg, int n_threads, + const char *cmd, const htsFormat *in_fmt, const htsFormat *out_fmt, + int write_index, char *arg_list, int no_pg) +{ + samFile *fpout, **fp = NULL; + heap1_t *heap = NULL; + sam_hdr_t *hout = NULL; + sam_hdr_t *hin = NULL; + int i, j, *RG_len = NULL; + uint64_t idx = 0; + char **RG = NULL; + hts_itr_t **iter = NULL; + sam_hdr_t **hdr = NULL; + trans_tbl_t *translation_tbl = NULL; + int *rtrans = NULL; + char *out_idx_fn = NULL; + void *hreg = NULL; + hts_reglist_t *lreg = NULL; + merged_header_t *merged_hdr = init_merged_header(); + if (!merged_hdr) return -1; + refs_t *refs = NULL; + template_coordinate_keys_t *keys = NULL; + khash_t(const_c2c) *lib_lookup = NULL; + + // Is there a specified pre-prepared header to use for output? + if (headers) { + samFile* fpheaders = sam_open(headers, "r"); + if (fpheaders == NULL) { + print_error_errno(cmd, "cannot open \"%s\"", headers); + return -1; + } + hin = sam_hdr_read(fpheaders); + sam_close(fpheaders); + if (hin == NULL) { + print_error(cmd, "couldn't read headers from \"%s\"", headers); + goto mem_fail; + } + } + + g_sam_order = sam_order; + if (sam_order == TagQueryName || sam_order == TagCoordinate) { + g_sort_tag[0] = sort_tag[0]; + g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0'; + } + + fp = (samFile**)calloc(n, sizeof(samFile*)); + if (!fp) goto mem_fail; + heap = (heap1_t*)calloc(n, sizeof(heap1_t)); + if (!heap) goto mem_fail; + iter = (hts_itr_t**)calloc(n, sizeof(hts_itr_t*)); + if (!iter) goto mem_fail; + hdr = (sam_hdr_t**)calloc(n, sizeof(sam_hdr_t*)); + if (!hdr) goto mem_fail; + translation_tbl = (trans_tbl_t*)calloc(n, sizeof(trans_tbl_t)); + if (!translation_tbl) goto mem_fail; + RG = (char**)calloc(n, sizeof(char*)); + if (!RG) goto mem_fail; + + // prepare RG tag from file names + if (flag & MERGE_RG) { + RG_len = (int*)calloc(n, sizeof(int)); + if (!RG_len) goto mem_fail; + for (i = 0; i != n; ++i) { + int l = strlen(fn[i]); + const char *s = fn[i]; + if (l > 4 && (strcmp(s + l - 4, ".bam") == 0 || strcmp(s + l - 4, ".sam") == 0)) l -= 4; + if (l > 5 && strcmp(s + l - 5, ".cram") == 0) l -= 5; + for (j = l - 1; j >= 0; --j) if (s[j] == '/') break; + ++j; l -= j; + RG[i] = (char*)calloc(l + 1, 1); + if (!RG[i]) goto mem_fail; + RG_len[i] = l; + strncpy(RG[i], s + j, l); + } + } + + if (hin) { + // Populate merged_hdr from the pre-prepared header + trans_tbl_t dummy; + int res; + res = trans_tbl_init(merged_hdr, hin, &dummy, flag & MERGE_COMBINE_RG, + flag & MERGE_COMBINE_PG, true, NULL); + trans_tbl_destroy(&dummy); + if (res) return -1; // FIXME: memory leak + } + + // open and read the header from each file + for (i = 0; i < n; ++i) { + sam_hdr_t *hin; + fp[i] = sam_open_format(fn[i], "r", in_fmt); + if (fp[i] == NULL) { + print_error_errno(cmd, "fail to open \"%s\"", fn[i]); + goto fail; + } + hts_set_opt(fp[i], HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + hin = sam_hdr_read(fp[i]); + if (hin == NULL) { + print_error(cmd, "failed to read header from \"%s\"", fn[i]); + goto fail; + } + + if (trans_tbl_init(merged_hdr, hin, translation_tbl+i, + flag & MERGE_COMBINE_RG, flag & MERGE_COMBINE_PG, + (flag & MERGE_FIRST_CO)? (i == 0) : true, + RG[i])) + goto fail; + + hdr[i] = hin; + + int order_ok = 1; + if ((translation_tbl+i)->lost_coord_sort && (sam_order == Coordinate || sam_order == MinHash)) { + fprintf(samtools_stderr, "[bam_merge_core] Order of targets in file %s caused coordinate sort to be lost\n", fn[i]); + order_ok = 0; + } + + if (!refs) + refs = cram_get_refs(fp[i]); + + if (order_ok && refs && hts_set_opt(fp[i], CRAM_OPT_SHARED_REF, refs)) + goto fail; + } + + // Did we get an @HD line? + if (!merged_hdr->have_hd) { + fprintf(samtools_stderr, "[W::%s] No @HD tag found.\n", __func__); + /* FIXME: Should we add an @HD line here, and if so what should + we put in it? Ideally we want a way of getting htslib to tell + us the SAM version number to assume given no @HD line. Is + it also safe to assume that the output is coordinate sorted? + SO: is optional so we don't have to have it.*/ + /* ksprintf(&merged_hdr->out_hd, "@HD\tVN:1.5\tSO:coordinate\n"); */ + } + + // Transform the header into standard form + if (finish_merged_header(merged_hdr) < 0) + goto fail; + + hout = merged_hdr->hdr; + if (!hout) + goto fail; + + // If we're only merging a specified region move our iters to start at that point + int tid, nreg; + hts_pos_t beg, end; + + if (fn_bed) { + hreg = bed_read(fn_bed); + if (!hreg) { + fprintf(samtools_stderr, "[%s] Could not read BED file: \"%s\"\n", __func__, fn_bed); + goto fail; + } + bed_unify(hreg); + lreg = bed_reglist(hreg, ALL, &nreg); + if (!lreg || !nreg) { + fprintf(samtools_stderr, "[%s] Null or empty region list\n", __func__); + goto fail; + } + } else if (reg) { + rtrans = rtrans_build(n, sam_hdr_nref(hout), translation_tbl); + if (!rtrans) goto mem_fail; + + if (!sam_parse_region(hout, reg, &tid, &beg, &end, 0)) { + fprintf(samtools_stderr, "[%s] Badly formatted region or unknown reference name: \"%s\"\n", __func__, reg); + goto fail; + } + + } + + if (reg || fn_bed) { + hts_idx_t *reg_idx = NULL; + for (i = 0; i < n; ++i) { + + // If index filename has not been specified, look in the BAM folder + if (fn_idx != NULL) { + reg_idx = sam_index_load2(fp[i], fn[i], fn_idx[i]); + } else { + reg_idx = sam_index_load(fp[i], fn[i]); + } + if (reg_idx == NULL) { + fprintf(samtools_stderr, "[%s] failed to load index for %s. Random alignment retrieval only works for indexed BAM or CRAM files.\n", + __func__, fn[i]); + free(rtrans); + rtrans = NULL; + goto fail; + } + + int mapped_tid = INT32_MIN; + if (fn_bed) { + hts_reglist_t *rl = duplicate_reglist(lreg, nreg); + iter[i] = sam_itr_regions(reg_idx, hdr[i], rl, nreg); + } else { + // (rtrans[i*n+tid]) Look up what hout tid translates to in input tid space + mapped_tid = rtrans[i*sam_hdr_nref(hout)+tid]; + if (mapped_tid != INT32_MIN) { + iter[i] = sam_itr_queryi(reg_idx, mapped_tid, beg, end); + } else { + iter[i] = sam_itr_queryi(reg_idx, HTS_IDX_NONE, 0, 0); + } + } + + if (iter[i] == NULL) { + if (fn_bed) { + fprintf(samtools_stderr, "[%s] failed to get multi-region iterator " + "{%s, %s}\n", __func__, fn[i], fn_bed); + } else { + if (mapped_tid != INT32_MIN) { + fprintf(samtools_stderr, + "[%s] failed to get iterator over " + "{%s, %d, %"PRIhts_pos", %"PRIhts_pos"}\n", + __func__, fn[i], mapped_tid, beg, end); + } else { + fprintf(samtools_stderr, + "[%s] failed to get iterator over " + "{%s, HTS_IDX_NONE, 0, 0}\n", + __func__, fn[i]); + } + } + hts_idx_destroy(reg_idx); + free(rtrans); + rtrans = NULL; + goto fail; + } + + hts_idx_destroy(reg_idx); + } + + free(rtrans); + rtrans = NULL; + } + + // Make sure that there's enough memory for template coordinate keys, one per file to read + if (sam_order == TemplateCoordinate) { + if ((keys = malloc(sizeof(template_coordinate_keys_t))) == NULL) { + print_error("sort", "could not allocate memory for the top-level keys"); + goto mem_fail; + } + keys->n = 0; + keys->m = 0; + keys->buffer_size = 0x10000; + keys->buffers = NULL; + // Make sure that there's enough memory for template coordinate keys, one per file to read + if (keys->n + n >= keys->m * keys->buffer_size) { + if (template_coordinate_keys_realloc(keys, keys->n + n) < 0) goto mem_fail; + } + lib_lookup = lookup_libraries(hout); + if (!lib_lookup) { + goto mem_fail; + } + } + + // Load the first read from each file into the heap + for (i = 0; i < n; ++i) { + heap1_t *h = heap + i; + int res; + h->i = i; + h->entry.bam_record = bam_init1(); + h->entry.u.tag = NULL; + if (!h->entry.bam_record) goto mem_fail; + res = iter[i] ? sam_itr_next(fp[i], iter[i], h->entry.bam_record) : sam_read1(fp[i], hdr[i], h->entry.bam_record); + if (res >= 0) { + bam_translate(h->entry.bam_record, translation_tbl + i); + h->tid = h->entry.bam_record->core.tid; + h->pos = (uint64_t)(h->entry.bam_record->core.pos + 1); + h->rev = bam_is_rev(h->entry.bam_record); + h->idx = idx++; + if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) { + h->entry.u.tag = bam_aux_get(h->entry.bam_record, g_sort_tag); + } else if (g_sam_order == TemplateCoordinate) { + template_coordinate_key_t *key = template_coordinate_keys_get(keys, i); // get the next key to use + h->entry.u.key = template_coordinate_key(heap->entry.bam_record, key, hout, lib_lookup); // update the key + if (heap->entry.u.key == NULL) goto mem_fail; // key could not be created, error out + } else { + h->entry.u.tag = NULL; + } + } + else if (res == -1 && (!iter[i] || iter[i]->finished)) { + h->pos = HEAP_EMPTY; + bam_destroy1(h->entry.bam_record); + h->entry.bam_record = NULL; + h->entry.u.tag = NULL; + h->entry.u.key = NULL; + } else { + print_error(cmd, "failed to read first record from \"%s\"", fn[i]); + goto fail; + } + } + + // Open output file and write header + if ((fpout = sam_open_format(out, mode, out_fmt)) == 0) { + print_error_errno(cmd, "failed to create \"%s\"", out); + return -1; + } + hts_set_opt(fpout, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + if (!no_pg && sam_hdr_add_pg(hout, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error(cmd, "failed to add PG line to the header of \"%s\"", out); + sam_close(fpout); + return -1; + } + if (sam_hdr_write(fpout, hout) != 0) { + print_error_errno(cmd, "failed to write header to \"%s\"", out); + sam_close(fpout); + return -1; + } + if (write_index) { + if (!(out_idx_fn = auto_index(fpout, out, hout))){ + sam_close(fpout); + return -1; + } + } + if (!(flag & MERGE_UNCOMP)) hts_set_threads(fpout, n_threads); + + if (refs && hts_set_opt(fpout, CRAM_OPT_SHARED_REF, refs)) + goto fail; + + // Begin the actual merge + ks_heapmake(heap, n, heap); + while (heap->pos != HEAP_EMPTY) { + bam1_t *b = heap->entry.bam_record; + if (flag & MERGE_RG) { + uint8_t *rg = bam_aux_get(b, "RG"); + if (rg) bam_aux_del(b, rg); + bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]); + } + if (sam_write1(fpout, hout, b) < 0) { + print_error_errno(cmd, "failed writing to \"%s\"", out); + sam_close(fpout); + free(out_idx_fn); + return -1; + } + if ((j = (iter[heap->i]? sam_itr_next(fp[heap->i], iter[heap->i], b) : sam_read1(fp[heap->i], hdr[heap->i], b))) >= 0) { + bam_translate(b, translation_tbl + heap->i); + heap->tid = b->core.tid; + heap->pos = (uint64_t)(b->core.pos + 1); + heap->rev = bam_is_rev(b); + heap->idx = idx++; + if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) { + heap->entry.u.tag = bam_aux_get(heap->entry.bam_record, g_sort_tag); + } else if (g_sam_order == TemplateCoordinate) { + template_coordinate_key_t *key = template_coordinate_keys_get(keys, heap->i); // get the next key to use + heap->entry.u.key = template_coordinate_key(heap->entry.bam_record, key, hout, lib_lookup); // update the key + if (heap->entry.u.key == NULL) goto mem_fail; // key could not be created, error out + } else { + heap->entry.u.tag = NULL; + } + } else if (j == -1 && (!iter[heap->i] || iter[heap->i]->finished)) { + heap->pos = HEAP_EMPTY; + bam_destroy1(heap->entry.bam_record); + heap->entry.bam_record = NULL; + heap->entry.u.tag = NULL; + } else { + print_error(cmd, "\"%s\" is truncated", fn[heap->i]); + goto fail; + } + ks_heapadjust(heap, 0, n, heap); + } + + if (write_index) { + if (sam_idx_save(fpout) < 0) { + print_error_errno("merge", "writing index failed"); + goto fail; + } + } + free(out_idx_fn); + + // Clean up and close + if (flag & MERGE_RG) { + for (i = 0; i != n; ++i) free(RG[i]); + free(RG_len); + } + for (i = 0; i < n; ++i) { + trans_tbl_destroy(translation_tbl + i); + hts_itr_destroy(iter[i]); + sam_hdr_destroy(hdr[i]); + sam_close(fp[i]); + } + sam_hdr_destroy(hin); + sam_hdr_destroy(hout); + free_merged_header(merged_hdr); + hts_reglist_free(lreg, nreg); + bed_destroy(hreg); + free(RG); free(translation_tbl); free(fp); free(heap); free(iter); free(hdr); + if (sam_close(fpout) < 0) { + print_error(cmd, "error closing output file"); + return -1; + } + return 0; + + mem_fail: + print_error(cmd, "Out of memory"); + + fail: + if (flag & MERGE_RG) { + if (RG) { + for (i = 0; i != n; ++i) free(RG[i]); + } + free(RG_len); + } + for (i = 0; i < n; ++i) { + if (translation_tbl && translation_tbl[i].tid_trans) trans_tbl_destroy(translation_tbl + i); + if (iter && iter[i]) hts_itr_destroy(iter[i]); + if (hdr && hdr[i]) sam_hdr_destroy(hdr[i]); + if (fp && fp[i]) sam_close(fp[i]); + if (heap && heap[i].entry.bam_record) bam_destroy1(heap[i].entry.bam_record); + } + if (hout) sam_hdr_destroy(hout); + free(RG); + free(translation_tbl); + free(hdr); + hts_reglist_free(lreg, nreg); + bed_destroy(hreg); + free(iter); + free(heap); + free(fp); + free(rtrans); + free(out_idx_fn); + if (keys != NULL) { + for (i = 0; i < keys->m; ++i) { + free(keys->buffers[i]); + } + free(keys->buffers); + free(keys); + } + lib_lookup_destroy(lib_lookup); + return -1; +} + +// Unused here but may be used by legacy samtools-using third-party code +int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn, int flag, const char *reg) +{ + char mode[12]; + strcpy(mode, "wb"); + if (flag & MERGE_UNCOMP) strcat(mode, "0"); + else if (flag & MERGE_LEVEL1) strcat(mode, "1"); + SamOrder sam_order = by_qname ? QueryName : Coordinate; + return bam_merge_core2(sam_order, NULL, out, mode, headers, n, fn, NULL, NULL, flag, reg, 0, "merge", NULL, NULL, 0, NULL, 1); +} + +static void merge_usage(FILE *to) +{ + fprintf(to, +"Usage: samtools merge [options] -o [options] ... \n" +" or: samtools merge [options] ... \n" +"\n" +"Options:\n" +" -n Input files are sorted by read name\n" +" -t TAG Input files are sorted by TAG value\n" +" -r Attach RG tag (inferred from file names)\n" +" -u Uncompressed BAM output\n" +" -f Overwrite the output BAM if exist\n" +" -o FILE Specify output file via option instead of argument\n" +" -1 Compress level 1\n" +" -l INT Compression level, from 0 to 9 [-1]\n" +" -R STR Merge file in the specified region STR [all]\n" +" -h FILE Copy the header in FILE to [in1.bam]\n" +" -c Combine @RG headers with colliding IDs [alter IDs to be distinct]\n" +" -p Combine @PG headers with colliding IDs [alter IDs to be distinct]\n" +" -s VALUE Override random seed\n" +" -b FILE List of input BAM filenames, one per line [null]\n" +" -X Use customized index files\n" +" -L FILE Specify a BED file for multiple region filtering [null]\n" +" --no-PG do not add a PG line\n" +" --template-coordinate Input files are sorted by template-coordinate\n"); + sam_global_opt_help(to, "-.O..@.."); +} + +int bam_merge(int argc, char *argv[]) +{ + int c, flag = 0, ret = 0, level = -1, has_index_file = 0; + char *fn_headers = NULL, *reg = NULL, mode[12]; + char *sort_tag = NULL, *fnout = NULL, *arg_list = NULL; + long random_seed = (long)time(NULL); + char** fn = NULL; + char** fn_idx = NULL, *fn_bed = NULL; + int fn_size = 0, no_pg = 0; + SamOrder sam_order = Coordinate; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + { "threads", required_argument, NULL, '@' }, + {"no-PG", no_argument, NULL, 1}, + { "template-coordinate", no_argument, NULL, 2}, + { NULL, 0, NULL, 0 } + }; + + if (argc == 1) { + merge_usage(samtools_stdout); + return 0; + } + + while ((c = getopt_long(argc, argv, "h:nru1R:o:f@:l:cps:b:O:t:XL:", lopts, NULL)) >= 0) { + switch (c) { + case 'r': flag |= MERGE_RG; break; + case 'f': flag |= MERGE_FORCE; break; + case 'h': fn_headers = optarg; break; + case 'n': sam_order = QueryName; break; + case 'o': fnout = optarg; break; + case 't': sort_tag = optarg; break; + case '1': flag |= MERGE_LEVEL1; level = 1; break; + case 'u': flag |= MERGE_UNCOMP; level = 0; break; + case 'R': reg = strdup(optarg); break; + case 'l': level = atoi(optarg); break; + case 'c': flag |= MERGE_COMBINE_RG; break; + case 'p': flag |= MERGE_COMBINE_PG; break; + case 's': random_seed = atol(optarg); break; + case 'X': has_index_file = 1; break; // -X flag for index filename + case 'L': fn_bed = optarg; break; + case 'b': { + // load the list of files to read + if (has_index_file) { + fprintf(samtools_stderr,"Error: The -b option cannot be combined with -X\n"); + ret = 1; goto end; + } + int nfiles; + char **fn_read = hts_readlines(optarg, &nfiles); + if (fn_read) { + // Append to end of array + fn = realloc(fn, (fn_size+nfiles) * sizeof(char*)); + if (fn == NULL) { ret = 1; goto end; } + memcpy(fn+fn_size, fn_read, nfiles * sizeof(char*)); + fn_size += nfiles; + free(fn_read); + } + else { + print_error("merge", "Invalid file list \"%s\"", optarg); + ret = 1; + } + break; + } + case 1: no_pg = 1; break; + case 2: sam_order = TemplateCoordinate; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': merge_usage(samtools_stderr); return 1; + } + } + + if (sort_tag != NULL) { + sam_order = sam_order == QueryName ? TagQueryName : TagCoordinate; + } + + if (fnout == NULL && argc - optind >= 1) { + fnout = argv[optind]; + optind++; + } + if (fnout == NULL) { + print_error("merge", "You must at least specify the output file"); + merge_usage(samtools_stderr); + return 1; + } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("merge", "failed to create arg_list"); + return 1; + } + + hts_srand48(random_seed); + if (!(flag & MERGE_FORCE) && strcmp(fnout, "-") != 0) { + struct stat sbuf; + if (stat(fnout, &sbuf) == 0 && S_ISREG(sbuf.st_mode)) { + fprintf(samtools_stderr, "[%s] File '%s' exists. Please apply '-f' to overwrite. Abort.\n", __func__, fnout); + ret = 1; + goto end; + } + } + + int nargcfiles = 0; + if (has_index_file) { // Calculate # of input BAM files + if ((argc - optind) % 2 != 0) { + fprintf(samtools_stderr, "Odd number of filenames detected! Each BAM file should have an index file\n"); + ret = 1; + goto end; + } + nargcfiles = (argc - optind) / 2; + } else { + nargcfiles = argc - optind; + } + + if (nargcfiles > 0) { + // Add argc files to end of array + fn = realloc(fn, (fn_size+nargcfiles) * sizeof(char*)); + if (fn == NULL) { ret = 1; goto end; } + memcpy(fn+fn_size, argv + optind, nargcfiles * sizeof(char*)); + + if(has_index_file) { + fn_idx = realloc(fn_idx, nargcfiles * sizeof(char*)); + if (fn_idx == NULL) { ret = 1; goto end; } + memcpy(fn_idx+fn_size, argv + nargcfiles + optind, nargcfiles * sizeof(char*)); + } + } + if (fn_size+nargcfiles < 1) { + print_error("merge", "You must specify at least one (and usually two or more) input files"); + merge_usage(samtools_stderr); + ret = 1; + goto end; + } + + if (reg && fn_bed) { + print_error("merge", "You must specify either a BED file or a region"); + ret = 1; + goto end; + } + strcpy(mode, "wb"); + sam_open_mode(mode+1, fnout, NULL); + if (level >= 0) sprintf(strchr(mode, '\0'), "%d", level < 9? level : 9); + if (bam_merge_core2(sam_order, sort_tag, fnout, mode, fn_headers, + fn_size+nargcfiles, fn, fn_idx, fn_bed, flag, reg, ga.nthreads, + "merge", &ga.in, &ga.out, ga.write_index, arg_list, no_pg) < 0) + ret = 1; + +end: + if (fn_size > 0) { + int i; + for (i=0; ii, res; + if (i < nfiles) { // read from file + res = sam_read1(fp[i], hout, heap->entry.bam_record); + if (res >= 0 && g_sam_order == TemplateCoordinate) { // file read OK and TemplateCoordinate order + // It is assumed that there are nfiles more keys allocated than keys->n; see allocation in bam_merge_simple + template_coordinate_key_t *key = template_coordinate_keys_get(keys, keys->n + i); // get the next key to use + heap->entry.u.key = template_coordinate_key(heap->entry.bam_record, key, hout, lib_lookup); // update the key + if (heap->entry.u.key == NULL) res = -1; // key could not be created, error out + } + } else { // read from memory + if (in_mem[i - nfiles].from < in_mem[i - nfiles].to) { + size_t from = in_mem[i - nfiles].from; + heap->entry.bam_record = buf[from].bam_record; + if (g_sam_order == TemplateCoordinate) heap->entry.u.key = buf[from].u.key; + in_mem[i - nfiles].from++; + res = 0; + } else { + res = -1; + } + } + if (res >= 0) { + heap->tid = heap->entry.bam_record->core.tid; + heap->pos = (uint64_t)(heap->entry.bam_record->core.pos + 1); + heap->rev = bam_is_rev(heap->entry.bam_record); + heap->idx = (*idx)++; + if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) { + heap->entry.u.tag = bam_aux_get(heap->entry.bam_record, g_sort_tag); + } else if (g_sam_order != TemplateCoordinate) { + heap->entry.u.tag = NULL; + heap->entry.u.key = NULL; + } + } else if (res == -1) { + heap->pos = HEAP_EMPTY; + if (i < nfiles) bam_destroy1(heap->entry.bam_record); + heap->entry.bam_record = NULL; + heap->entry.u.tag = NULL; + heap->entry.u.key = NULL; + } else { + return -1; + } + return 0; +} + +static int bam_merge_simple(SamOrder sam_order, char *sort_tag, const char *out, + const char *mode, sam_hdr_t *hout, + int n, char * const *fn, int num_in_mem, + buf_region *in_mem, bam1_tag *buf, + template_coordinate_keys_t *keys, + khash_t(const_c2c) *lib_lookup, + htsThreadPool *htspool, + const char *cmd, const htsFormat *in_fmt, + const htsFormat *out_fmt, char *arg_list, int no_pg, + int write_index, int final_out) { + samFile *fpout = NULL, **fp = NULL; + heap1_t *heap = NULL; + uint64_t idx = 0; + int i, heap_size = n + num_in_mem; + char *out_idx_fn = NULL; + + if (sam_order == TagQueryName || sam_order == TagCoordinate) { + g_sort_tag[0] = sort_tag[0]; + g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0'; + } + if (n > 0) { + fp = (samFile**)calloc(n, sizeof(samFile*)); + if (!fp) goto mem_fail; + } + heap = (heap1_t*)calloc(heap_size, sizeof(heap1_t)); + if (!heap) goto mem_fail; + + // Make sure that there's enough memory for template coordinate keys, one per file to read + if (keys && keys->n + n >= keys->m * keys->buffer_size) { + if (template_coordinate_keys_realloc(keys, keys->n + n) < 0) goto mem_fail; + } + + // Open each file, read the header and put the first read into the heap + for (i = 0; i < heap_size; i++) { + sam_hdr_t *hin; + heap1_t *h = &heap[i]; + + if (i < n) { + fp[i] = sam_open_format(fn[i], "r", in_fmt); + if (fp[i] == NULL) { + print_error_errno(cmd, "fail to open \"%s\"", fn[i]); + goto fail; + } + hts_set_opt(fp[i], HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + if (htspool->pool) + hts_set_opt(fp[i], HTS_OPT_THREAD_POOL, htspool); + + // Read header ... + hin = sam_hdr_read(fp[i]); + if (hin == NULL) { + print_error(cmd, "failed to read header from \"%s\"", fn[i]); + goto fail; + } + // ... and throw it away as we don't really need it + sam_hdr_destroy(hin); + } + + // Get a read into the heap + h->i = i; + h->entry.u.tag = NULL; + h->entry.u.key = NULL; + if (i < n) { + h->entry.bam_record = bam_init1(); + if (!h->entry.bam_record) goto mem_fail; + } + if (heap_add_read(h, n, fp, num_in_mem, in_mem, buf, keys, &idx, hout, + lib_lookup) < 0) { + assert(i < n); + print_error(cmd, "failed to read first record from \"%s\"", fn[i]); + goto fail; + } + } + + // Open output file and write header + if ((fpout = sam_open_format(out, mode, out_fmt)) == 0) { + print_error_errno(cmd, "failed to create \"%s\"", out); + return -1; + } + hts_set_opt(fpout, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + + if (!no_pg && sam_hdr_add_pg(hout, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error(cmd, "failed to add PG line to the header of \"%s\"", out); + sam_close(fpout); + return -1; + } + + if (htspool->pool) + hts_set_opt(fpout, HTS_OPT_THREAD_POOL, htspool); + + if (sam_hdr_write(fpout, hout) != 0) { + print_error_errno(cmd, "failed to write header to \"%s\"", out); + sam_close(fpout); + return -1; + } + + if (write_index) { + if (!(out_idx_fn = auto_index(fpout, out, hout))){ + sam_close(fpout); + return -1; + } + } + + // Now do the merge + ks_heapmake(heap, heap_size, heap); + while (heap->pos != HEAP_EMPTY) { + bam1_t *b = heap->entry.bam_record; + if (g_sam_order == MinHash && b->core.tid == -1 && final_out) { + // Remove the cached minhash value + b->core.pos = -1; + b->core.mpos = -1; + b->core.isize = 0; + } + if (sam_write1(fpout, hout, b) < 0) { + print_error_errno(cmd, "failed writing to \"%s\"", out); + goto fail; + } + if (heap_add_read(heap, n, fp, num_in_mem, in_mem, buf, keys, &idx, + hout, lib_lookup) < 0) { + assert(heap->i < n); + print_error(cmd, "Error reading \"%s\" : %s", + fn[heap->i], strerror(errno)); + goto fail; + } + ks_heapadjust(heap, 0, heap_size, heap); + } + // Clean up and close + for (i = 0; i < n; i++) { + if (sam_close(fp[i]) != 0) { + print_error(cmd, "Error on closing \"%s\" : %s", + fn[i], strerror(errno)); + } + } + free(fp); + free(heap); + + if (write_index) { + if (sam_idx_save(fpout) < 0) { + print_error_errno("merge", "writing index failed"); + goto fail; + } + free(out_idx_fn); + } + + if (sam_close(fpout) < 0) { + print_error(cmd, "error closing output file"); + return -1; + } + return 0; + mem_fail: + print_error(cmd, "Out of memory"); + + fail: + for (i = 0; i < n; i++) { + if (fp && fp[i]) sam_close(fp[i]); + } + for (i = 0; i < heap_size; i++) { + if (heap && heap[i].i < n && heap[i].entry.bam_record) + bam_destroy1(heap[i].entry.bam_record); + } + free(fp); + free(heap); + if (fpout) sam_close(fpout); + free(out_idx_fn); + return -1; +} + +// Function to compare reads and determine which one is < or > the other +// Handle sort-by-pos and sort-by-name. Used as the secondary sort in bam1_lt_by_tag, if reads are equivalent by tag. +// Returns a value less than, equal to or greater than zero if a is less than, +// equal to or greater than b, respectively. +static inline int bam1_cmp_core(const bam1_tag a, const bam1_tag b) +{ + uint64_t pa, pb; + if (!a.bam_record) return 1; + if (!b.bam_record) return 0; + + if (g_sam_order == QueryName || g_sam_order == TagQueryName) { + int t = strnum_cmp(bam_get_qname(a.bam_record), bam_get_qname(b.bam_record)); + if (t != 0) return t; + return (int) (a.bam_record->core.flag&0xc0) - (int) (b.bam_record->core.flag&0xc0); + } else { + pa = a.bam_record->core.tid; + pb = b.bam_record->core.tid; + + if (pa == pb) { + pa = (uint64_t)(a.bam_record->core.pos+1); + pb = (uint64_t)(b.bam_record->core.pos+1); + } + + if (pa == pb) { + pa = bam_is_rev(a.bam_record); + pb = bam_is_rev(b.bam_record); + } + + return pa < pb ? -1 : (pa > pb ? 1 : 0); + } +} + +uint8_t normalize_type(const uint8_t* aux) { + if (*aux == 'c' || *aux == 'C' || *aux == 's' || *aux == 'S' || *aux == 'i' || *aux == 'I') { + return 'c'; + } else if (*aux == 'f' || *aux == 'd') { + return 'f'; + } else if (*aux == 'H' || *aux == 'Z') { + return 'H'; + } else { + return *aux; + } +} + +// Sort record by tag, using pos or read name as a secondary key if tags are identical. Reads not carrying the tag sort first. +// Tags are first sorted by the type character (in case the types differ), or by the appropriate comparator for that type if they agree. +// Returns a value less than, equal to or greater than zero if a is less than, +// equal to or greater than b, respectively. +static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b) +{ + const uint8_t* aux_a = a.u.tag; + const uint8_t* aux_b = b.u.tag; + + if (aux_a == NULL && aux_b != NULL) { + return -1; + } else if (aux_a != NULL && aux_b == NULL) { + return 1; + } else if (aux_a == NULL && aux_b == NULL) { + return bam1_cmp_core(a,b); + } + + // 'Normalize' the letters of the datatypes to a canonical letter, + // so that comparison of different types + // forms a correct total ordering. + uint8_t a_type = normalize_type(aux_a); + uint8_t b_type = normalize_type(aux_b); + + if (a_type != b_type) { + // Fix int to float comparisons by using bam_aux2f() to read the int + if (a_type == 'c' && b_type == 'f') { + a_type = 'f'; + } else if (a_type == 'f' && b_type == 'c') { + b_type = 'f'; + } else { + // Unfixable mismatched types + return a_type < b_type ? -1 : 1; + } + } + + if (a_type == 'c') { + int64_t va = bam_aux2i(aux_a); + int64_t vb = bam_aux2i(aux_b); + if (va != vb) return va < vb ? -1 : 1; + return bam1_cmp_core(a, b); + } else if (a_type == 'f') { + double va = bam_aux2f(aux_a); + double vb = bam_aux2f(aux_b); + if (va != vb) return va < vb ? -1 : 1; + return bam1_cmp_core(a, b); + } else if (a_type == 'A') { + unsigned char va = bam_aux2A(aux_a); + unsigned char vb = bam_aux2A(aux_b); + if (va != vb) return va < vb ? -1 : 1; + return bam1_cmp_core(a, b); + } else if (a_type == 'H') { + int t = strcmp(bam_aux2Z(aux_a), bam_aux2Z(aux_b)); + if (t) return t; + return bam1_cmp_core(a, b); + } else { + return bam1_cmp_core(a,b); + } +} + +// Sort by minimiser (stored in bam1_tag.u.pos). +// If equal, sort by position. +// +// The 64-bit sort key is split over the bam pos and isize fields. +// This permits it to survive writing to temporary file and coming back. + +#ifdef DEBUG_MINHASH +static int ntot = 0, nmis = 0, ndup = 0; +#endif + +static inline int bam1_cmp_by_minhash(const bam1_tag a, const bam1_tag b) +{ + const bam1_t *A = a.bam_record; + const bam1_t *B = b.bam_record; + + if (!A) return 1; + if (!B) return 0; + + if (A->core.tid != -1 || B->core.tid != -1) return bam1_cmp_core(a,b); + + const uint64_t m_a = (((uint64_t)A->core.pos)<<31)|(uint32_t)A->core.mpos; + const uint64_t m_b = (((uint64_t)B->core.pos)<<31)|(uint32_t)B->core.mpos; + + if (m_a < m_b) // by hash + return -1; + else if (m_a > m_b) + return 1; + + // Bigger pos with size minhash means starts further to left + else if (A->core.isize > B->core.isize) // by hash location in seq + return -1; + else if (A->core.isize < B->core.isize) + return 1; + else + return bam1_cmp_core(a,b); +} + +// compares to molecular identifiers, ignoring any trailing slash and subsequent single-character +// * if mid1 is less than mid2, then -1 will be returned +// * if mid1 is greater than mid2, then 1 will be returned +static inline int template_coordinate_key_compare_mid(const char* mid1, const char* mid2) { + size_t i = 0; + size_t len1 = strlen(mid1); + size_t len2 = strlen(mid2); + size_t shortest; + + // Snip off trailing slash followed by a single character, if present + if (len1 >= 2 && mid1[len1-2] == '/') len1 -= 2; + if (len2 >= 2 && mid2[len2-2] == '/') len2 -= 2; + shortest = len1 < len2 ? len1 : len2; + + // find first mismatching character + while (i < shortest && mid1[i] == mid2[i]) i++; + + // compare last characters + if (i == len1 && i < len2) return -1; // mid1 shorter + if (i == len2 && i < len1) return 1; // mid2 shorter + if (i == len1 && i == len2) return 0; // all characters match + if (mid1[i] < mid2[i]) return -1; // mid1 earlier + else return 1; +} + + +// Builds a key use to sort in TemplateCoordinate order. Returns NULL if the key could not be created (e.g. MC +// tag is missing), otherwise the pointer to the provided key. +static template_coordinate_key_t* template_coordinate_key(bam1_t *b, template_coordinate_key_t *key, sam_hdr_t *hdr, khash_t(const_c2c) *lib_lookup) { + uint8_t *data; + char *rg; + khiter_t k; + + // defaults + key->tid1 = key->tid2 = INT32_MAX; + key->pos1 = key->pos2 = HTS_POS_MAX; + key->neg1 = key->neg2 = false; + key->mid = ""; + + // update values + rg = (char *)bam_aux_get(b, "RG"); + if (rg && rg[0] == 'Z' + &&(k = kh_get(const_c2c, lib_lookup, rg + 1)) < kh_end(lib_lookup)) { + key->library = kh_value(lib_lookup, k); + } else { + key->library = ""; + } + key->name = bam_get_qname(b); + if (!(b->core.flag & BAM_FUNMAP)) { // read is mapped, update coordinates + key->tid1 = b->core.tid; + key->neg1 = bam_is_rev(b); + key->pos1 = (key->neg1) ? unclipped_end(b) : unclipped_start(b); + } + if (b->core.flag & BAM_FPAIRED && !(b->core.flag & BAM_FMUNMAP)) { // mate is mapped, update coordinates + char *cigar; + if ((data = bam_aux_get(b, "MC"))) { + if (!(cigar = bam_aux2Z(data))) { + fprintf(samtools_stderr, "[bam_sort] error: MC tag wrong type. Please use the MC tag provided by samtools fixmate.\n"); + return NULL; + } + } else { + fprintf(samtools_stderr, "[bam_sort] error: no MC tag. Please run samtools fixmate on file first.\n"); + return NULL; + } + key->tid2 = b->core.mtid; + key->neg2 = bam_is_mrev(b); + key->pos2 = (key->neg2) ? unclipped_other_end(b->core.mpos, cigar) : unclipped_other_start(b->core.mpos, cigar); + } + + if ((data = bam_aux_get(b, "MI"))) { + if (!(key->mid=bam_aux2Z(data))) { + fprintf(samtools_stderr, "[bam_sort] error: MI tag wrong type (not a string).\n"); + return NULL; + } + } + + // set is_upper_of_pair, and swap if we get the same key regardless of which end + // of the pair it is + if (key->tid1 < key->tid2 + || (key->tid1 == key->tid2 && key->pos1 < key->pos2) + || (key->tid1 == key->tid2 && key->pos1 == key->pos2 && !key->neg1)) { + key->is_upper_of_pair = false; + } else { + key->is_upper_of_pair = true; + // swap + int tmp_tid; + hts_pos_t tmp_pos; + bool tmp_neg; + tmp_tid = key->tid1; + key->tid1 = key->tid2; + key->tid2 = tmp_tid; + tmp_pos = key->pos1; + key->pos1 = key->pos2; + key->pos2 = tmp_pos; + tmp_neg = key->neg1; + key->neg1 = key->neg2; + key->neg2 = tmp_neg; + } + + return key; +} + +// Function to compare reads and determine which one is < or > the other +// Handles template-coordinate, which sorts by: +// 1. the earlier unclipped 5' coordinate of the read pair +// 2. the higher unclipped 5' coordinate of the read pair +// 3. library (from read group) +// 4. the molecular identifier (if present) +// 5. read name +// 6. if unpaired, or if R1 has the lower coordinates of the pair +// Returns a value less than, equal to or greater than zero if a is less than, +// equal to or greater than b, respectively. +static inline int bam1_cmp_template_coordinate(const bam1_tag a, const bam1_tag b) +{ + if (!a.bam_record) return 1; + if (!b.bam_record) return 0; + + const template_coordinate_key_t* key_a = a.u.key; + const template_coordinate_key_t* key_b = b.u.key; + + int retval = 0; + if (0 == retval) retval = key_a->tid1 - key_b->tid1; + if (0 == retval) retval = key_a->tid2 - key_b->tid2; + if (0 == retval) retval = key_a->pos1 < key_b->pos1 ? -1 : (key_a->pos1 > key_b->pos1 ? 1 : 0); + if (0 == retval) retval = key_a->pos2 < key_b->pos2 ? -1 : (key_a->pos2 > key_b->pos2 ? 1 : 0); + if (0 == retval) retval = key_a->neg1 == key_b->neg1 ? 0 : (key_a->neg1 ? -1 : 1); + if (0 == retval) retval = key_a->neg2 == key_b->neg2 ? 0 : (key_a->neg2 ? -1 : 1); + if (0 == retval) retval = strcmp(key_a->library, key_b->library); + if (0 == retval) retval = template_coordinate_key_compare_mid(key_a->mid, key_b->mid); + if (0 == retval) retval = strcmp(key_a->name, key_b->name); + if (0 == retval) retval = key_a->is_upper_of_pair == key_b->is_upper_of_pair ? 0 : (key_a->is_upper_of_pair ? 1 : -1); + return retval < 0 ? -1 : (retval > 0 ? 1 : 0); +} + + +// Function to compare reads and determine which one is < the other +// Handle sort-by-pos, sort-by-name, sort-by-tag, or sort-by-template-coordinate. +static inline int bam1_lt(const bam1_tag a, const bam1_tag b) +{ + switch (g_sam_order) { + case Coordinate: + case QueryName: + return bam1_cmp_core(a, b) < 0; + case TagQueryName: + case TagCoordinate: + return bam1_cmp_by_tag(a, b) < 0; + case MinHash: + return bam1_cmp_by_minhash(a, b) < 0; + case TemplateCoordinate: + return bam1_cmp_template_coordinate(a, b) < 0; + default: + return bam1_cmp_core(a,b) < 0; + } +} + + + +KSORT_INIT(sort, bam1_tag, bam1_lt) + +typedef struct { + size_t buf_len; + bam1_tag *buf; + const sam_hdr_t *h; + int error; + int large_pos; + int minimiser_kmer; + bool try_rev; + bool no_squash; +} worker_t; + +// Returns 0 for success +// -1 for failure +static int write_buffer(const char *fn, const char *mode, size_t l, bam1_tag *buf, + const sam_hdr_t *h, int n_threads, const htsFormat *fmt, + int clear_minhash, char *arg_list, int no_pg, int write_index) +{ + size_t i; + samFile* fp; + char *out_idx_fn = NULL; + + fp = sam_open_format(fn, mode, fmt); + if (fp == NULL) return -1; + hts_set_opt(fp, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + if (!no_pg && sam_hdr_add_pg((sam_hdr_t *)h, "samtools", "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + goto fail; + } + if (sam_hdr_write(fp, h) != 0) goto fail; + + if (write_index) + if (!(out_idx_fn = auto_index(fp, fn, (sam_hdr_t *)h))) goto fail; + + if (n_threads > 1) hts_set_threads(fp, n_threads); + for (i = 0; i < l; ++i) { + bam1_t *b = buf[i].bam_record; + if (clear_minhash && b->core.tid == -1) { + // To see the position for debugging + // b->core.pos = ((((uint64_t)b->core.pos)<<31)|(uint32_t)b->core.mpos) + b->core.isize; + // Remove the cached minhash value + b->core.pos = -1; + b->core.mpos = -1; + b->core.isize = 0; + } + if (sam_write1(fp, h, b) < 0) goto fail; + } + + if (write_index) { + if (sam_idx_save(fp) < 0) { + print_error_errno("merge", "writing index failed"); + goto fail; + } + free(out_idx_fn); + } + + + if (sam_close(fp) < 0) return -1; + return 0; + fail: + sam_close(fp); + free(out_idx_fn); + return -1; +} + +#define NUMBASE 256 + +static int ks_radixsort(size_t n, bam1_tag *buf, const sam_hdr_t *h) +{ + int curr = 0, ret = -1; + ssize_t i; + bam1_tag *buf_ar2[2], *bam_a, *bam_b; + uint64_t max_pos = 1; + uint32_t max_tid = 1, tid_bytes = 0, pos_bytes = 0, byte = 0; + uint32_t tid_shift_l, tid_shift_r; + int nref = sam_hdr_nref(h); + + // Count number of bytes needed for biggest tid and pos + // Notes: Add 1 to core.pos so always positive. + // Convert unmapped tid (-1) to number of references so unmapped + // sort to the end. + for (i = 0; i < n; i++) { + bam1_t *b = buf[i].bam_record; + uint32_t tid = b->core.tid == -1 ? nref : b->core.tid; + uint64_t pos = ((uint64_t)(b->core.pos + 1) << 1) | bam_is_rev(b); + if (max_tid < tid) + max_tid = tid; + if (max_pos < pos) + max_pos = pos; + } + + for (; max_pos > 0; max_pos >>= 8) pos_bytes++; + for (; max_tid > 0; max_tid >>= 8) tid_bytes++; + assert(pos_bytes + tid_bytes < sizeof(buf[0].u.pos_tid)); + + tid_shift_l = pos_bytes * 8; + tid_shift_r = 64 - tid_shift_l; + + // Write position and tid into bam1_tag::u::pos_tid using minimum number + // of bytes required. Values are stored little-endian so that we + // get a least-significant digit (byte) radix sort. + for (i = 0; i < n; i++) { + bam1_t *b = buf[i].bam_record; + uint32_t tid = b->core.tid == -1 ? nref : b->core.tid; + // 'pos' here includes as many bytes of tid as will fit + // in the space remaining above pos_bytes. The rest of tid + // is written out separately. + uint64_t pos = (bam_is_rev(b) | + ((uint64_t)(b->core.pos + 1) << 1) | + (tid_shift_l < 64 ? (uint64_t) tid << tid_shift_l : 0)); + u64_to_le(pos, buf[i].u.pos_tid); + u32_to_le(tid_shift_r < 32 ? tid >> tid_shift_r : 0, + &buf[i].u.pos_tid[8]); + } + + buf_ar2[0] = buf; + buf_ar2[1] = (bam1_tag *)malloc(sizeof(bam1_tag) * n); + if (buf_ar2[1] == NULL) { + print_error("sort", "couldn't allocate memory for temporary buf"); + goto err; + } + + // Least-significant digit radix sort (where "digits" are bytes) + for (byte = 0; byte < pos_bytes + tid_bytes; byte++) { + size_t remainders[NUMBASE] = { 0 }; + bam_a = buf_ar2[curr]; bam_b = buf_ar2[1-curr]; + for (i = 0; i < n; ++i) + remainders[bam_a[i].u.pos_tid[byte]]++; + for (i = 1; i < NUMBASE; ++i) + remainders[i] += remainders[i - 1]; + for (i = n - 1; i >= 0; i--) { + size_t j = --remainders[bam_a[i].u.pos_tid[byte]]; + bam_b[j] = bam_a[i]; + } + curr = 1 - curr; + } + if (curr == 1) { + bam1_tag *end = buf + n; + bam_a = buf_ar2[0]; bam_b = buf_ar2[1]; + while (bam_a < end) *bam_a++ = *bam_b++; + } + + ret = 0; +err: + free(buf_ar2[1]); + return ret; +} + +KHASH_MAP_INIT_INT64(kmer, int64_t) +static khash_t(kmer) *kmer_h = NULL; + +// Punt homopolymers somewhere central in the hash space +#define XOR 0xdead7878beef7878 + +/* + * Computes the minhash of a sequence using forward strand and if requested + * reverse strand. + * + * This is used as a sort key for unmapped data, to collate like sequences + * together and to improve compression ratio. + * + * The minhash is returned and *pos filled out with location of this hash + * key in the sequence if pos != NULL. + */ +static uint64_t minhash(bam1_t *b, int kmer, int window, int *curr_pos, + int *end, int *is_rev, int try_fwd, int try_rev, + int no_squash) { + uint64_t hashf = 0, minhashf = UINT64_MAX; + int minhashpf = *curr_pos, i, j; + uint64_t mask = (1L<<(2*kmer))-1; + uint8_t *seq = bam_get_seq(b); + int len = b->core.l_qseq; + uint64_t xor = XOR & mask; + + if (is_rev) *is_rev = 0; + + // Lookup tables for bam_seqi to 0123 fwd/rev hashes + // =ACM GRSV TWYH KDBN +#define X 0 + static unsigned char L[16] = { + X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X, + }; + uint64_t R[16] = { + X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X, + }; + for (i = 0; i < 16; i++) + R[i] <<= 2*(kmer-1); + + int i_start = *curr_pos; + int i_end = MIN(i_start + window, len); + int last_base = -1; + + if (try_fwd) { + // Initialise hash keys + for (i = i_start, j = 0; j < kmer-1 && i < i_end; i++) { + int base = bam_seqi(seq, i); + // collapse homopolymers + if (no_squash || last_base != base) { + last_base = base; + hashf = (hashf<<2) | L[base]; + j++; + } + } + + // Loop to find minimum + if (no_squash) { + for (; i < i_end; i++) { + int base = bam_seqi(seq, i); + hashf = (hashf<<2) | L[base]; + uint64_t hashfx = (hashf ^ XOR) & mask; + if (minhashf > hashfx) + minhashf = hashfx, minhashpf = i; + } + } else { + for (; i < i_end; i++) { + int base = bam_seqi(seq, i); + if (last_base != base) { + last_base = base; + hashf = (hashf<<2) | L[base]; + uint64_t hashfx = (hashf ^ XOR) & mask; + if (minhashf > hashfx) + minhashf = hashfx, minhashpf = i; + } + } + } + } + + // Same as above for the reverse strand. + // Not used for now, but we may wish to consider indexing in both + // strands, recording the strand in value (pos), and comparing in one + // strand only. Right now we compare on both against a single-stranded + // index. + if (try_rev) { + uint64_t hashr = 0, minhashr = UINT64_MAX; + int minhashpr = *curr_pos; + int last_base = -1; + + for (i = i_start, j = 0; j < kmer-1 && i < len; i++) { + int base = bam_seqi(seq, i); + if (no_squash || last_base != base) { + last_base = base; + hashr = (hashr>>2) | R[base]; + j++; + } + } + + if (no_squash) { + for (; i < i_end; i++) { + int base = bam_seqi(seq, i); + hashr = (hashr>>2) | R[base]; + if (minhashr > (hashr^xor)) + minhashr = (hashr^xor), minhashpr = len-i+kmer-2; + } + } else { + for (; i < i_end; i++) { + int base = bam_seqi(seq, i); + if (last_base != base) { + last_base = base; + hashr = (hashr>>2) | R[base]; + if (minhashr > (hashr^xor)) + minhashr = (hashr^xor), minhashpr = len-i+kmer-2; + } + } + } + + if (minhashr < minhashf) { + minhashf = minhashr; + minhashpf = minhashpr; + if (is_rev) *is_rev = 1; + } + } + + // "*curr_pos = minhashpf" is faster here, but is sometimes + // poorer in compression. Eg 10 million novaseq records with + // 75.1MB vs 76.9MB cram BA field. + //*curr_pos = minhashpf; + *curr_pos = minhashpf - (kmer-1); + if (end) *end = (i_end == len); + return minhashf; +} + +#define UNIQ_BIT 60 +#define UNIQ_TEST(x) (((x) & (1ULL<= 0) { + //fprintf(samtools_stderr, "LEN\t%d\t%s\n", b->core.l_qseq, bam_get_qname(b)); + uint64_t hashf; + int pos = 0, end = 0; + khiter_t k; + int ret; + + if (b->core.l_qseq < window) + continue; + + // fwd + while (!end) { + int last_pos = pos; + hashf = minhash(b, kmer, window, &pos, &end, NULL, 1, 0, + no_squash); + k = kh_put(kmer, kmer_h, hashf, &ret); + kh_value(kmer_h, k) = tpos+pos + (((uint64_t)!ret)<core.l_qseq; + +// We could also add reverse keys to the index here. +// This would avoid reverse complementing during the matching stage. +// We'd need to add a flag (another high bit of kh_value) to indicate +// strand. +// I'm unsure if this is a good trade-off or not. + +// // rev +// pos = 0; end = 0; +// while (!end) { +// hashf = minhash(b, kmer, window, &pos, &end, NULL, 0, 1, +// no_squash); +// k = kh_put(kmer, kmer_h, hashf, &ret); +// kh_value(kmer_h, k) = tpos+pos + (((uint64_t)!ret)<core.l_qseq; + } + if (r < -1) + goto err; + + ret = 0; + err: + if (b) bam_destroy1(b); + if (h) sam_hdr_destroy(h); + sam_close(in); + + return ret; +} + +/* + * A variant of minhash that compares against a previously built index. + * + * We follow the same steps of scanning through this sequence to find the + * minimum hash, but we prefer hash keys that have unique placement in the + * index, or if not unique, then non-uniquely placed, over ones that + * are absent from the index. + */ +static uint64_t minhash_with_idx(bam1_t *b, int kmer, int *pos, int *rev, + bool try_rev) { + uint64_t hashf = 0, minhashf = UINT64_MAX, minhashfi = UINT64_MAX; + uint64_t minhashfd = UINT64_MAX; + int minhashpf = 0, minhashpfi = 0, minhashpfd = 0, i, j; + uint64_t mask = (1L<<(2*kmer))-1; + unsigned char *seq = bam_get_seq(b); + int len = b->core.l_qseq; + const uint64_t xor = XOR & mask; + + // Lookup tables for bam_seqi to 0123 fwd/rev hashes + // =ACM GRSV TWYH KDBN +#define X 0 + unsigned char L[16] = { + X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X, + }; + uint64_t R[16] = { + X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X, + }; + for (i = 0; i < 16; i++) + R[i] <<= 2*(kmer-1); + + // Initialise hash keys + for (i = j = 0; j < kmer-1 && i < len; i++, j++) { + int base = bam_seqi(seq, i); + hashf = (hashf<<2) | L[base]; + } + + // Loop to find minimum + int found_f = 0, found_r = 0; + for (; i < len; i++) { + int base = bam_seqi(seq, i); + hashf = ((hashf<<2) | L[base]) & mask; + const uint64_t hashfx = hashf^xor; + + // Priority for sorting + // 1. Unique key in index + // 2. Dup key in index + // 3. Everything else + int index = 0; + if (minhashfi > hashfx || (found_f < 2 && minhashfd > hashfx)) { + khiter_t k = kh_get(kmer, kmer_h, hashfx); + if (k != kh_end(kmer_h)) + index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1; + } + found_f |= index; + switch (index) { + case 2: minhashfi = hashfx, minhashpfi = i; break; + case 1: minhashfd = hashfx, minhashpfd = i; break; + + default: + if (minhashf > hashfx) + minhashf = hashfx, minhashpf = i; + } + } + + if (minhashfi != UINT64_MAX) + minhashf = minhashfi, minhashpf = minhashpfi; + else if (minhashfd != UINT64_MAX) + minhashf = minhashfd, minhashpf = minhashpfd; + + // Same as above for the reverse strand + int dir = 0; + if (try_rev) { + uint64_t hashr = 0, minhashr = UINT64_MAX, minhashri = UINT64_MAX; + uint64_t minhashrd = UINT64_MAX; + int minhashpr = 0, minhashpri = 0, minhashprd = 0; + + for (i = j = 0; j < kmer-1 && i < len; i++, j++) { + int base = bam_seqi(seq, i); + hashr = (hashr>>2) | R[base]; + } + for (; i < len; i++) { + int base = bam_seqi(seq, i); + hashr = (hashr>>2) | R[base]; + const uint64_t hashrx = hashr^xor; + + int index = 0; + if (minhashri > hashrx || (found_r < 2 && minhashrd > hashrx)) { + khiter_t k = kh_get(kmer, kmer_h, hashrx); + if (k != kh_end(kmer_h)) + index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1; + } + found_r |= index; + switch (index) { + case 2: minhashri = hashrx, minhashpri = i; break; + case 1: minhashrd = hashrx, minhashprd = i; break; + + default: + if (minhashr > hashrx) + minhashr = hashrx, minhashpr = i; + } + } + if (minhashri != UINT64_MAX) + minhashr = minhashri, minhashpr = minhashpri; + else if (minhashrd != UINT64_MAX) + minhashr = minhashrd, minhashpr = minhashprd; + + // Pick reverse if better mapping + if ((minhashf > minhashr) || (!found_f && found_r)) { + if (!found_f || found_r) { + minhashf = minhashr; + minhashpf = b->core.l_qseq - minhashpr + kmer - 2; + dir = 1; + } + } + } + +#ifdef DEBUG_MINHASH + ntot++; + khiter_t k = kh_get(kmer, kmer_h, minhashf); + if (k != kh_end(kmer_h)) { + if (!UNIQ_TEST(kh_value(kmer_h, k))) + ndup++; + minhashf = kh_value(kmer_h, k) & UNIQ_MASK; + } else { + nmis++; + } +#else + // For indexed kmers, our hash key is the position the kmer + // occurs in the concatenated reference rather than the hash itself. + khiter_t k = kh_get(kmer, kmer_h, minhashf); + if (k != kh_end(kmer_h)) + minhashf = kh_value(kmer_h, k) & UNIQ_MASK; +#endif + + if (rev) *rev = dir; + if (pos) *pos = minhashpf; + + return minhashf != UINT64_MAX ? minhashf : 0; +} + +// As per minhash_with_idx but with homopolymer squashing enabled. +// This function is duplicated to remove conditionals and speed up the +// hashing code. (Minus the ifdef-ed out code, which is kept above mainly +// for posterity.) +static uint64_t minhash_with_idx_squash(bam1_t *b, int kmer, int *pos, + int *rev, bool try_rev) { + uint64_t hashf = 0, minhashf = UINT64_MAX, minhashfi = UINT64_MAX; + uint64_t minhashfd = UINT64_MAX; + int minhashpf = 0, minhashpfi = 0, minhashpfd = 0, i, j; + uint64_t mask = (1L<<(2*kmer))-1; + unsigned char *seq = bam_get_seq(b); + int len = b->core.l_qseq; + const uint64_t xor = XOR & mask; + + // Lookup tables for bam_seqi to 0123 fwd/rev hashes + // =ACM GRSV TWYH KDBN +#define X 0 + unsigned char L[16] = { + X,0,1,X, 2,X,X,X, 3,X,X,X, X,X,X,X, + }; + uint64_t R[16] = { + X,3,2,X, 1,X,X,X, 0,X,X,X, X,X,X,X, + }; + for (i = 0; i < 16; i++) + R[i] <<= 2*(kmer-1); + + // Initialise hash keys + int last_base = -1; + for (i = j = 0; j < kmer-1 && i < len; i++) { + int base = bam_seqi(seq, i); + if (base == last_base) + continue; + last_base = base; + j++; + hashf = (hashf<<2) | L[base]; + } + + // Loop to find minimum + int found_f = 0, found_r = 0; + for (; i < len; i++) { + int base = bam_seqi(seq, i); + if (base == last_base) + continue; + last_base = base; + hashf = ((hashf<<2) | L[base]) & mask; + const uint64_t hashfx = hashf^xor; + + // Priority for sorting + // 1. Unique key in index + // 2. Dup key in index + // 3. Everything else + int index = 0; + if (minhashfi > hashfx || (found_f < 2 && minhashfd > hashfx)) { + khiter_t k = kh_get(kmer, kmer_h, hashfx); + if (k != kh_end(kmer_h)) + index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1; + } + found_f |= index; + switch (index) { + case 2: minhashfi = hashfx, minhashpfi = i; break; + case 1: minhashfd = hashfx, minhashpfd = i; break; + + default: + if (minhashf > hashfx) + minhashf = hashfx, minhashpf = i; + } + } + + if (minhashfi != UINT64_MAX) + minhashf = minhashfi, minhashpf = minhashpfi; + else if (minhashfd != UINT64_MAX) + minhashf = minhashfd, minhashpf = minhashpfd; + + // Same as above for the reverse strand + int dir = 0; + if (try_rev) { + uint64_t hashr = 0, minhashr = UINT64_MAX, minhashri = UINT64_MAX; + uint64_t minhashrd = UINT64_MAX; + int minhashpr = 0, minhashpri = 0, minhashprd = 0; + int last_base = -1; + + for (i = j = 0; j < kmer-1 && i < len; i++) { + int base = bam_seqi(seq, i); + if (base == last_base) + continue; + last_base = base; + j++; + hashr = (hashr>>2) | R[base]; + } + for (; i < len; i++) { + int base = bam_seqi(seq, i); + if (base == last_base) + continue; + last_base = base; + hashr = (hashr>>2) | R[base]; + const uint64_t hashrx = hashr^xor; + + int index = 0; + if (minhashri > hashrx || (found_r < 2 && minhashrd > hashrx)) { + khiter_t k = kh_get(kmer, kmer_h, hashrx); + if (k != kh_end(kmer_h)) + index = UNIQ_TEST(kh_value(kmer_h, k)) ? 2 : 1; + } + found_r |= index; + switch (index) { + case 2: minhashri = hashrx, minhashpri = i; break; + case 1: minhashrd = hashrx, minhashprd = i; break; + + default: + if (minhashr > hashrx) + minhashr = hashrx, minhashpr = i; + } + } + if (minhashri != UINT64_MAX) + minhashr = minhashri, minhashpr = minhashpri; + else if (minhashrd != UINT64_MAX) + minhashr = minhashrd, minhashpr = minhashprd; + + // Pick reverse if better mapping + if ((minhashf > minhashr) || (!found_f && found_r)) { + if (!found_f || found_r) { + minhashf = minhashr; + minhashpf = b->core.l_qseq - minhashpr + kmer - 2; + dir = 1; + } + } + } + +#ifdef DEBUG_MINHASH + ntot++; + khiter_t k = kh_get(kmer, kmer_h, minhashf); + if (k != kh_end(kmer_h)) { + if (!UNIQ_TEST(kh_value(kmer_h, k))) + ndup++; + minhashf = kh_value(kmer_h, k) & UNIQ_MASK; + } else { + nmis++; + } +#else + // For indexed kmers, our hash key is the position the kmer + // occurs in the concatenated reference rather than the hash itself. + khiter_t k = kh_get(kmer, kmer_h, minhashf); + if (k != kh_end(kmer_h)) + minhashf = kh_value(kmer_h, k) & UNIQ_MASK; +#endif + + if (rev) *rev = dir; + if (pos) *pos = minhashpf; + + return minhashf != UINT64_MAX ? minhashf : 0; +} + +//--- Start of candidates to punt to htslib +/*! + * @abstract + * Extracts the sequence (in current alignment orientation) from + * a bam record and places it in buf, which is nul terminated. + * + * @param b The bam structure + * @param buf A buffer at least b->core.l_qseq+1 bytes long + */ +static void bam_to_seq(bam1_t *b, char *buf) { + int i; + uint8_t *seq = bam_get_seq(b); + for (i = 0; i < b->core.l_qseq; i++) + buf[i] = seq_nt16_str[bam_seqi(seq, i)]; + buf[i] = 0; +} + +/*! + * @abstract + * Writes a new sequence, of length b->core.l_qseq, to a BAM record. + * + * If a sequence of a new length is required the caller must first make + * room for it by updating the bam1_t struct. + * + * @param b The bam structure + * @param buf A buffer at least b->core.l_qseq bytes long + */ +static void seq_to_bam(bam1_t *b, char *buf) { + int i; + uint8_t *seq = bam_get_seq(b); + for (i = 0; i < b->core.l_qseq; i++) + bam_set_seqi(seq, i, seq_nt16_table[(unsigned char)buf[i]]); +} + +/*! + * @abstract Reverse complements a BAM record. + * + * It's possible to do this inline, but complex due to the 4-bit sequence + * encoding. For now I take the dumb approach. + * + * @param b Pointer to a BAM alignment + * + * @return 0 on success, -1 on failure (ENOMEM) + */ +static int reverse_complement(bam1_t *b) { + static char comp[256] = { + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//00 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//10 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//20 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//30 + + // * * * * E F * * I J * L * * O + '@','T','V','G', 'H','E','F','C', 'D','I','H','M', 'L','K','N','O',//40 + //P Q * * * * * * X Y Z [ \ ] ^ _ + 'P','Q','Y','S', 'A','A','B','W', 'X','Y','Z','[','\\','[','^','_',//50 + //` * * * * E F * * I J * L * * O + '`','t','v','g', 'h','e','f','c', 'd','i','j','m', 'l','k','n','o',//60 + //P Q * * * * * * X Y Z { | } ~ DEL + 'p','q','y','s', 'a','a','b','w', 'x','y','z','{', '|','}','~',127,//70 + + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//80 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//90 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//A0 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//B0 + + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//C0 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//D0 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//E0 + 'N','N','N','N', 'N','N','N','N', 'N','N','N','N', 'N','N','N','N',//F0 + }; + char seq_[10000], *seq = seq_; + uint8_t *qual = bam_get_qual(b); + int i, j; + + if (b->core.l_qseq >= 10000) + if (!(seq = malloc(b->core.l_qseq+1))) + return -1; + + bam_to_seq(b, seq); + + for (i = 0, j = b->core.l_qseq-1; i < j; i++, j--) { + unsigned char tmp = seq[i]; + seq[i] = comp[(unsigned char)seq[j]]; + seq[j] = comp[tmp]; + tmp = qual[i]; + qual[i] = qual[j]; + qual[j] = tmp; + } + if (i ==j) + seq[i] = comp[(unsigned char)seq[i]]; + + seq_to_bam(b, seq); + + if (seq != seq_) + free(seq); + + b->core.flag ^= 0x10; + + return 0; +} +//--- End of candidates to punt to htslib + + +static inline void worker_minhash(worker_t *w) { + int i; + for (i = 0; i < w->buf_len; i++) { + bam1_t *b = w->buf[i].bam_record; + if (b->core.tid != -1) + continue; + + int pos = 0, rev = 0; + uint64_t mh = kmer_h + ? (w->no_squash + ? minhash_with_idx(b, w->minimiser_kmer, &pos, &rev, + w->try_rev) + : minhash_with_idx_squash(b, w->minimiser_kmer, &pos, &rev, + w->try_rev) + ) + : minhash(b, w->minimiser_kmer, b->core.l_qseq, + &pos, NULL, &rev, 1, w->try_rev, w->no_squash); + if (rev) + reverse_complement(b); + + if (!kmer_h) { + mh += 1LL<<30; + pos = 65535-pos >= 0 ? 65535-pos : 0; + } else { + mh -= pos; + pos = 0; + } + + + // Store 64-bit hash in unmapped pos and mpos fields. + // The position of hash is in isize, which we use for + // resolving ties when sorting by hash key. + // These are unused for completely unmapped data and + // will be reset during final output. + b->core.pos = (mh>>31) & 0x7fffffff; + b->core.mpos = mh&0x7fffffff; + b->core.isize = pos; + } +} + +static void *worker(void *data) +{ + worker_t *w = (worker_t*)data; + w->error = 0; + + switch (g_sam_order) { + case Coordinate: + if (ks_radixsort(w->buf_len, w->buf, w->h) < 0) { + w->error = errno; + return NULL; + } + break; + case MinHash: + worker_minhash(w); + // no break, go to merge sort + default: + ks_mergesort(sort, w->buf_len, w->buf, 0); + } + + return 0; +} + +static int sort_blocks(size_t k, bam1_tag *buf, const sam_hdr_t *h, + int n_threads, buf_region *in_mem, + int large_pos, int minimiser_kmer, bool try_rev, + bool no_squash) +{ + int i; + size_t pos, rest; + pthread_t *tid; + pthread_attr_t attr; + worker_t *w; + int n_failed = 0; + + if (n_threads < 1) n_threads = 1; + if (k < n_threads * 64) n_threads = 1; // use a single thread if we only sort a small batch of records + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + w = (worker_t*)calloc(n_threads, sizeof(worker_t)); + if (!w) return -1; + tid = (pthread_t*)calloc(n_threads, sizeof(pthread_t)); + if (!tid) { free(w); return -1; } + pos = 0; rest = k; + for (i = 0; i < n_threads; ++i) { + w[i].buf_len = rest / (n_threads - i); + w[i].buf = &buf[pos]; + w[i].h = h; + w[i].large_pos = large_pos; + w[i].minimiser_kmer = minimiser_kmer; + w[i].try_rev = try_rev; + w[i].no_squash = no_squash; + in_mem[i].from = pos; + in_mem[i].to = pos + w[i].buf_len; + pos += w[i].buf_len; rest -= w[i].buf_len; + pthread_create(&tid[i], &attr, worker, &w[i]); + } + for (i = 0; i < n_threads; ++i) { + pthread_join(tid[i], 0); + if (w[i].error != 0) { + errno = w[i].error; + print_error_errno("sort", "failed to sort block %d", i); + n_failed++; + } + } + free(w); + free(tid); + + return n_failed ? -1 : n_threads; +} + +static void lib_lookup_destroy(khash_t(const_c2c) *lib_lookup) { + khiter_t k; + if (lib_lookup == NULL) + return; + for (k = kh_begin(lib_lookup); k < kh_end(lib_lookup); k++) { + if (kh_exist(lib_lookup, k)) + free(kh_value(lib_lookup, k)); + } + kh_destroy(const_c2c, lib_lookup); +} + +// Build an RG to LB lookup table, for the template coordinate sort. +// Returns a populated hash table (which may be empty) on success; +// NULL on failure. +static khash_t(const_c2c) * lookup_libraries(sam_hdr_t *header) +{ + khash_t(const_c2c) *lib_lookup = kh_init(const_c2c); + kstring_t lib_name = KS_INITIALIZE; + int num_rg, i, res; + if (!lib_lookup) + return NULL; + + // Iterate through any RG lines and look for library information + num_rg = sam_hdr_count_lines(header, "RG"); + if (num_rg < 0) + goto fail; + + for (i = 0; i < num_rg; i++) { + const char *rg_id = sam_hdr_line_name(header, "RG", i); + khiter_t k; + if (!rg_id) + goto fail; + res = sam_hdr_find_tag_pos(header, "RG", i, "LB", &lib_name); + if (res < -1) // Error + goto fail; + if (res < 0 || !lib_name.s) // No LB tag + continue; + // Add to lookup table + k = kh_put(const_c2c, lib_lookup, rg_id, &res); + if (res < 0) // Error + goto fail; + if (res > 0) { // Inserted + kh_value(lib_lookup, k) = ks_release(&lib_name); + } + } + + free(lib_name.s); + + return lib_lookup; + + fail: + lib_lookup_destroy(lib_lookup); + free(lib_name.s); + return NULL; +} + +/*! + @abstract Sort an unsorted BAM file based on the provided sort order + + @param sam_order the order in which the sort should occur + @param sort_tag the tag to use if sorting by Tag + @param minimiser_kmer the kmer size when sorting by MinHash + @param try_rev try reverse strand when sorting by MinHash + @param fn name of the file to be sorted + @param prefix prefix of the temporary files (prefix.NNNN.bam are written) + @param fnout name of the final output file to be written + @param modeout sam_open() mode to be used to create the final output file + @param max_mem approxiate maximum memory (very inaccurate) + @param in_fmt input file format options + @param out_fmt output file format and options + @param arg_list command string for PG line + @param no_pg if 1, do not add a new PG line + @paran write_index create index for the output file + @return 0 for successful sorting, negative on errors + + @discussion It may create multiple temporary subalignment files + and then merge them by calling bam_merge_simple(). This function is + NOT thread safe. + */ +int bam_sort_core_ext(SamOrder sam_order, char* sort_tag, int minimiser_kmer, + bool try_rev, bool no_squash, const char *fn, + const char *prefix, const char *fnout, + const char *modeout, size_t _max_mem, int n_threads, + const htsFormat *in_fmt, const htsFormat *out_fmt, + char *arg_list, int no_pg, int write_index) +{ + int ret = -1, res, i, nref, n_files = 0, n_big_files = 0, fn_counter = 0; + size_t max_k, k, max_mem, bam_mem_offset; + sam_hdr_t *header = NULL; + samFile *fp = NULL; + bam1_tag *buf = NULL; + template_coordinate_keys_t *keys = NULL; + bam1_t *b = bam_init1(); + uint8_t *bam_mem = NULL; + char **fns = NULL; + size_t fns_size = 0; + const char *new_so = NULL; + const char *new_go = NULL; + const char *new_ss = NULL; + buf_region *in_mem = NULL; + khash_t(const_c2c) *lib_lookup = NULL; + htsThreadPool htspool = { NULL, 0 }; + int num_in_mem = 0; + int large_pos = 0; + + if (!b) { + print_error("sort", "couldn't allocate memory for bam record"); + return -1; + } + + if (n_threads < 2) n_threads = 1; + g_sam_order = sam_order; + if (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) { + g_sort_tag[0] = sort_tag[0]; + g_sort_tag[1] = sort_tag[0] ? sort_tag[1] : '\0'; + } + + if (sam_order == TemplateCoordinate) { + if ((keys = malloc(sizeof(template_coordinate_keys_t))) == NULL) { + print_error("sort", "could not allocate memory for the top-level keys"); + goto err; + } + keys->n = 0; + keys->m = 0; + keys->buffer_size = 0x10000; + keys->buffers = NULL; + } + + max_mem = _max_mem * n_threads; + buf = NULL; + fp = sam_open_format(fn, "r", in_fmt); + if (fp == NULL) { + print_error_errno("sort", "can't open \"%s\"", fn); + goto err; + } + hts_set_opt(fp, HTS_OPT_BLOCK_SIZE, BAM_BLOCK_SIZE); + header = sam_hdr_read(fp); + if (header == NULL) { + print_error("sort", "failed to read header from \"%s\"", fn); + goto err; + } + + // Inspect the header looking for long chromosomes + // If there is one, we need to write temporary files in SAM format + nref = sam_hdr_nref(header); + for (i = 0; i < nref; i++) { + if (sam_hdr_tid2len(header, i) > INT32_MAX) + large_pos = 1; + } + + // Also check the output format is large position compatible + if (large_pos) { + int compatible = (out_fmt->format == sam + || (out_fmt->format == cram + && out_fmt->version.major >= 4) + || (out_fmt->format == unknown_format + && modeout[0] == 'w' + && (modeout[1] == 'z' || modeout[1] == '\0'))); + if (!compatible) { + print_error("sort", "output format is not compatible with very large references"); + goto err; + } + } + + if (g_sam_order == TemplateCoordinate) { + lib_lookup = lookup_libraries(header); + if (!lib_lookup) + goto err; + } + + switch (g_sam_order) { + case Coordinate: + new_so = "coordinate"; + break; + case QueryName: + new_so = "queryname"; + break; + case MinHash: + new_so = "coordinate"; + new_ss = "coordinate:minhash"; + break; + case TagQueryName: + case TagCoordinate: + new_so = "unknown"; + break; + case TemplateCoordinate: + new_so = "unsorted"; + new_go = "query"; + new_ss = "unsorted:template-coordinate"; + break; + default: + new_so = "unknown"; + break; + } + + if (new_ss == NULL && new_go == NULL) { // just SO + if ((-1 == sam_hdr_update_hd(header, "SO", new_so)) + && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION, "SO", new_so, NULL)) + ) { + print_error("sort", "failed to change sort order header to 'SO:%s'\n", new_so); + goto err; + } + } else if (new_ss != NULL && new_go == NULL) { // update SO and SS, but not GO + if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "SS", new_ss)) + && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION, + "SO", new_so, "SS", new_ss, NULL)) + ) { + print_error("sort", "failed to change sort order header to 'SO:%s SS:%s'\n", + new_so, new_ss); + goto err; + } + } else if (new_ss == NULL && new_go != NULL) { // update SO and GO, but not SS + if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "GO", new_go)) + && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION, + "SO", new_so, "GO", new_go, NULL)) + ) { + print_error("sort", "failed to change sort order header to 'SO:%s GO:%s'\n", + new_so, new_go); + goto err; + } + } else { // update SO, GO, and SS + if ((-1 == sam_hdr_update_hd(header, "SO", new_so, "GO", new_go, "SS", new_ss)) + && (-1 == sam_hdr_add_line(header, "HD", "VN", SAM_FORMAT_VERSION, + "SO", new_so, "GO", new_go, "SS", new_ss, NULL)) + ) { + print_error("sort", "failed to change sort order header to 'SO:%s GO:%s SS:%s'\n", + new_so, new_go, new_ss); + goto err; + } + } + + if (new_go == NULL) { + if (-1 == sam_hdr_remove_tag_hd(header, "GO")) { + print_error("sort", "failed to delete group order in header\n"); + goto err; + } + } + if (new_ss == NULL) { + if (-1 == sam_hdr_remove_tag_hd(header, "SS")) { + print_error("sort", "failed to delete sub sort in header\n"); + goto err; + } + } + + if (n_threads > 1) { + htspool.pool = hts_tpool_init(n_threads); + if (!htspool.pool) { + print_error_errno("sort", "failed to set up thread pool"); + goto err; + } + hts_set_opt(fp, HTS_OPT_THREAD_POOL, &htspool); + } + + if ((bam_mem = malloc(max_mem)) == NULL) { + print_error("sort", "couldn't allocate memory for bam_mem"); + goto err; + } + + in_mem = calloc(n_threads > 0 ? n_threads : 1, sizeof(in_mem[0])); + if (!in_mem) goto err; + + // write sub files + k = max_k = bam_mem_offset = 0; + size_t name_len = strlen(prefix) + 30; + while ((res = sam_read1(fp, header, b)) >= 0) { + int mem_full = 0; + + if (k == max_k) { + bam1_tag *new_buf; + max_k = max_k? max_k<<1 : 0x10000; + if ((new_buf = realloc(buf, max_k * sizeof(bam1_tag))) == NULL) { + print_error("sort", "couldn't allocate memory for buf"); + goto err; + } + buf = new_buf; + } + if (sam_order == TemplateCoordinate && k >= keys->m * keys->buffer_size) { + if (template_coordinate_keys_realloc(keys, k + 1) == -1) { + goto err; + } + } + + // Check if the BAM record will fit in the memory limit + if (bam_mem_offset + sizeof(*b) + b->l_data < max_mem) { + // Copy record into the memory block + buf[k].bam_record = (bam1_t *)(bam_mem + bam_mem_offset); + *buf[k].bam_record = *b; + buf[k].bam_record->data = (uint8_t *)((char *)buf[k].bam_record + sizeof(bam1_t)); + memcpy(buf[k].bam_record->data, b->data, b->l_data); + // store next BAM record in next 8-byte-aligned address after + // current one + bam_mem_offset = (bam_mem_offset + sizeof(*b) + b->l_data + 8 - 1) & ~((size_t)(8 - 1)); + } else { + // Add a pointer to the remaining record + buf[k].bam_record = b; + mem_full = 1; + } + + // Set the tag if sorting by tag, or the key for template cooridinate sorting + switch (g_sam_order) { + case TagQueryName: + case TagCoordinate: + buf[k].u.tag = bam_aux_get(buf[k].bam_record, g_sort_tag); + break; + case TemplateCoordinate: + ++keys->n; + template_coordinate_key_t *key = template_coordinate_keys_get(keys, k); + buf[k].u.key = template_coordinate_key(buf[k].bam_record, key, header, lib_lookup); + if (buf[k].u.key == NULL) goto err; + break; + default: + buf[k].u.tag = NULL; + buf[k].u.key = NULL; + } + ++k; + + if (mem_full) { + if (hts_resize(char *, n_files + 1, &fns_size, &fns, 0) < 0) + goto err; + + int sort_res = sort_blocks(k, buf, header, n_threads, + in_mem, large_pos, minimiser_kmer, + try_rev, no_squash); + if (sort_res < 0) + goto err; + + fns[n_files] = calloc(name_len, 1); + if (!fns[n_files]) + goto err; + const int MAX_TRIES = 1000; + int tries = 0, merge_res = -1; + char *sort_by_tag = (g_sam_order == TagQueryName || g_sam_order == TagCoordinate) ? sort_tag : NULL; + int consolidate_from = n_files; + if (n_files - n_big_files >= MAX_TMP_FILES/2) + consolidate_from = n_big_files; + else if (n_files >= MAX_TMP_FILES) + consolidate_from = 0; + + for (;;) { + if (tries) { + snprintf(fns[n_files], name_len, "%s.%.4d-%.3d.bam", + prefix, fn_counter, tries); + } else { + snprintf(fns[n_files], name_len, "%s.%.4d.bam", prefix, + fn_counter); + } + if (bam_merge_simple(g_sam_order, sort_by_tag, fns[n_files], + large_pos ? "wzx1" : "wbx1", header, + n_files - consolidate_from, + &fns[consolidate_from], n_threads, + in_mem, buf, keys, + lib_lookup, &htspool, "sort", NULL, NULL, + NULL, 1, 0, 0) >= 0) { + merge_res = 0; + break; + } + if (errno == EEXIST && tries < MAX_TRIES) { + tries++; + } else { + break; + } + } + fn_counter++; + if (merge_res < 0) { + if (errno != EEXIST) + unlink(fns[n_files]); + free(fns[n_files]); + goto err; + } + + if (consolidate_from < n_files) { + for (i = consolidate_from; i < n_files; i++) { + unlink(fns[i]); + free(fns[i]); + } + fns[consolidate_from] = fns[n_files]; + n_files = consolidate_from; + n_big_files = consolidate_from + 1; + } + + n_files++; + k = 0; + if (keys != NULL) keys->n = 0; + bam_mem_offset = 0; + + } + } + if (res != -1) { + print_error("sort", "truncated file. Aborting"); + goto err; + } + + // Sort last records + if (k > 0) { + num_in_mem = sort_blocks(k, buf, header, n_threads, + in_mem, large_pos, minimiser_kmer, try_rev, + no_squash); + if (num_in_mem < 0) goto err; + } else { + num_in_mem = 0; + } + + // write the final output + if (n_files == 0 && num_in_mem < 2) { // a single block + if (write_buffer(fnout, modeout, k, buf, header, n_threads, out_fmt, + minimiser_kmer, arg_list, no_pg, write_index) != 0) { + print_error_errno("sort", "failed to create \"%s\"", fnout); + goto err; + } + } else { // then merge + fprintf(samtools_stderr, + "[bam_sort_core] merging from %d files and %d in-memory blocks...\n", + n_files, num_in_mem); + // Paranoia check - all temporary files should have a name + for (i = 0; i < n_files; ++i) { + if (!fns[i]) { + print_error("sort", + "BUG: no name stored for temporary file %d", i); + abort(); + } + } + char *sort_by_tag = (sam_order == TagQueryName || sam_order == TagCoordinate) ? sort_tag : NULL; + if (bam_merge_simple(sam_order, sort_by_tag, fnout, modeout, header, + n_files, fns, num_in_mem, in_mem, buf, keys, + lib_lookup, &htspool, "sort", in_fmt, out_fmt, + arg_list, no_pg, write_index, 1) < 0) { + // Propagate bam_merge_simple() failure; it has already emitted a + // message explaining the failure, so no further message is needed. + goto err; + } + } + + ret = 0; + + err: + // free + if (fns) { + for (i = 0; i < n_files; ++i) { + if (fns[i]) { + unlink(fns[i]); + free(fns[i]); + } + } + free(fns); + } + bam_destroy1(b); + free(buf); + if (keys != NULL) { + for (i = 0; i < keys->m; ++i) { + free(keys->buffers[i]); + } + free(keys->buffers); + free(keys); + } + free(bam_mem); + free(in_mem); + lib_lookup_destroy(lib_lookup); + sam_hdr_destroy(header); + if (fp) sam_close(fp); + if (htspool.pool) + hts_tpool_destroy(htspool.pool); + + return ret; +} + +// Unused here but may be used by legacy samtools-using third-party code +int bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem) +{ + int ret; + char *fnout = calloc(strlen(prefix) + 4 + 1, 1); + if (!fnout) return -1; + sprintf(fnout, "%s.bam", prefix); + SamOrder sam_order = is_by_qname ? QueryName : Coordinate; + g_sam_order = sam_order; + ret = bam_sort_core_ext(sam_order, NULL, 0, false, true, fn, prefix, + fnout, "wb", max_mem, 0, NULL, NULL, NULL, 1, 0); + free(fnout); + return ret; +} + +static void sort_usage(FILE *fp) +{ + fprintf(fp, +"Usage: samtools sort [options...] [in.bam]\n" +"Options:\n" +" -l INT Set compression level, from 0 (uncompressed) to 9 (best)\n" +" -u Output uncompressed data (equivalent to -l 0)\n" +" -m INT Set maximum memory per thread; suffix K/M/G recognized [768M]\n" +" -M Use minimiser for clustering unaligned/unplaced reads\n" +" -R Do not use reverse strand (only compatible with -M)\n" +" -K INT Kmer size to use for minimiser [20]\n" +" -I FILE Order minimisers by their position in FILE FASTA\n" +" -w INT Window size for minimiser indexing via -I ref.fa [100]\n" +" -H Squash homopolymers when computing minimiser\n" +" -n Sort by read name (not compatible with samtools index command)\n" +" -t TAG Sort by value of TAG. Uses position as secondary index (or read name if -n is set)\n" +" -o FILE Write final output to FILE rather than standard output\n" +" -T PREFIX Write temporary files to PREFIX.nnnn.bam\n" +" --no-PG\n" +" Do not add a PG line\n" +" --template-coordinate\n" +" Sort by template-coordinate\n"); + sam_global_opt_help(fp, "-.O..@.."); +} + +static void complain_about_memory_setting(size_t max_mem) { + char *suffix = ""; + const size_t nine_k = 9<<10; + if (max_mem > nine_k) { max_mem >>= 10; suffix = "K"; } + if (max_mem > nine_k) { max_mem >>= 10; suffix = "M"; } + + fprintf(samtools_stderr, +"[bam_sort] -m setting (%zu%s bytes) is less than the minimum required (%zuM).\n\n" +"Trying to run with -m too small can lead to the creation of a very large number\n" +"of temporary files. This may make sort fail due to it exceeding limits on the\n" +"number of files it can have open at the same time.\n\n" +"Please check your -m parameter. It should be an integer followed by one of the\n" +"letters K (for kilobytes), M (megabytes) or G (gigabytes). You should ensure it\n" +"is at least the minimum above, and much higher if you are sorting a large file.\n", + max_mem, suffix, SORT_MIN_MEGS_PER_THREAD); +} + +int bam_sort(int argc, char *argv[]) +{ + size_t max_mem = SORT_DEFAULT_MEGS_PER_THREAD << 20; + int c, nargs, ret, o_seen = 0, level = -1, no_pg = 0; + SamOrder sam_order = Coordinate; + bool by_tag = false; + int minimiser_kmer = 20; + bool try_rev = true; + char* sort_tag = NULL, *arg_list = NULL; + char *fnout = "-", modeout[12]; + kstring_t tmpprefix = { 0, 0, NULL }; + struct stat st; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + int window = 100; + char *minimiser_ref = NULL; + int no_squash = 1; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'), + { "threads", required_argument, NULL, '@' }, + {"no-PG", no_argument, NULL, 1}, + { "template-coordinate", no_argument, NULL, 2}, + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "l:m:no:O:T:@:t:MI:K:uRw:H", lopts, NULL)) >= 0) { + switch (c) { + case 'o': fnout = optarg; o_seen = 1; break; + case 'n': sam_order = QueryName; break; + case 't': by_tag = true; sort_tag = optarg; break; + case 'm': { + char *q; + max_mem = strtol(optarg, &q, 0); + if (*q == 'k' || *q == 'K') max_mem <<= 10; + else if (*q == 'm' || *q == 'M') max_mem <<= 20; + else if (*q == 'g' || *q == 'G') max_mem <<= 30; + break; + } + case 'T': kputs(optarg, &tmpprefix); break; + case 'l': level = atoi(optarg); break; + case 'u': level = 0; break; + case 1: no_pg = 1; break; + case 2: sam_order = TemplateCoordinate; break; + case 'M': sam_order = MinHash; break; + case 'I': + sam_order = MinHash; // implicit option + minimiser_ref = optarg; + break; + case 'H': no_squash = 0; break; + + case 'w': window = atoi(optarg); break; + + case 'R': try_rev = false; break; + case 'K': + minimiser_kmer = atoi(optarg); + if (minimiser_kmer < 1) + minimiser_kmer = 1; + else if (minimiser_kmer > 31) + minimiser_kmer = 31; + break; + + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': sort_usage(samtools_stderr); ret = EXIT_FAILURE; goto sort_end; + } + } + + if (minimiser_ref) { + fprintf(samtools_stderr, "Building index ... "); + fflush(samtools_stderr); + if (build_minhash_index(minimiser_ref, minimiser_kmer, window, + no_squash)) { + ret = EXIT_FAILURE; + goto sort_end; + } + fprintf(samtools_stderr, "done\n"); + } + + // Change sort order if tag sorting is requested. Must update based on secondary index + if (by_tag) { + sam_order = sam_order == QueryName ? TagQueryName : TagCoordinate; + } + + nargs = argc - optind; + if (nargs == 0 && isatty(STDIN_FILENO)) { + sort_usage(samtools_stdout); + ret = EXIT_SUCCESS; + goto sort_end; + } + else if (nargs >= 2) { + // If exactly two, user probably tried to specify legacy + if (nargs == 2) + fprintf(samtools_stderr, "[bam_sort] Use -T PREFIX / -o FILE to specify temporary and final output files\n"); + + sort_usage(samtools_stderr); + ret = EXIT_FAILURE; + goto sort_end; + } + + if (ga.write_index && (sam_order == QueryName || sam_order == TagQueryName || sam_order == TagCoordinate || sam_order == TemplateCoordinate)) { + fprintf(samtools_stderr, "[W::bam_sort] Ignoring --write-index as it only works for position sorted files.\n"); + ga.write_index = 0; + } + + if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("sort", "failed to create arg_list"); + return 1; + } + + if (max_mem < (SORT_MIN_MEGS_PER_THREAD << 20)) { + complain_about_memory_setting(max_mem); + ret = EXIT_FAILURE; + goto sort_end; + } + + strcpy(modeout, "wb"); + sam_open_mode(modeout+1, fnout, NULL); + if (level >= 0) sprintf(strchr(modeout, '\0'), "%d", level < 9? level : 9); + + if (tmpprefix.l == 0) { + if (strcmp(fnout, "-") != 0) { + char *idx = strstr(fnout, HTS_IDX_DELIM); + kputsn(fnout, idx ? idx - fnout : strlen(fnout), &tmpprefix); + kputs(".tmp", &tmpprefix); + } else { + kputc('.', &tmpprefix); + } + } + if (stat(tmpprefix.s, &st) == 0 && S_ISDIR(st.st_mode)) { + unsigned t = ((unsigned) time(NULL)) ^ ((unsigned) clock()); + if (tmpprefix.s[tmpprefix.l-1] != '/') kputc('/', &tmpprefix); + ksprintf(&tmpprefix, "samtools.%d.%u.tmp", (int) getpid(), t % 10000); + } + + ret = bam_sort_core_ext(sam_order, sort_tag, + (sam_order == MinHash) ? minimiser_kmer : 0, + try_rev, no_squash, + (nargs > 0) ? argv[optind] : "-", + tmpprefix.s, fnout, modeout, max_mem, ga.nthreads, + &ga.in, &ga.out, arg_list, no_pg, ga.write_index); + if (ret >= 0) + ret = EXIT_SUCCESS; + else { + char dummy[4]; + // If we failed on opening the input file & it has no .bam/.cram/etc + // extension, the user probably tried legacy -o + if (ret == -2 && o_seen && nargs > 0 && sam_open_mode(dummy, argv[optind], NULL) < 0) + fprintf(samtools_stderr, "[bam_sort] Note the argument has been replaced by -T/-o options\n"); + + ret = EXIT_FAILURE; + } + +#ifdef DEBUG_MINHASH + fprintf(samtools_stderr, "Missed %.1f%%, dup %.1f%%\n", + 100.0*nmis/(ntot+.1), + 100.0*ndup/(ntot+.1)); +#endif + +sort_end: + free(tmpprefix.s); + free(arg_list); + sam_global_args_free(&ga); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c new file mode 100644 index 0000000000000000000000000000000000000000..e9f0fb591f8f0b712150d0100431773d7df37949 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c @@ -0,0 +1,618 @@ +/* bam_split.c -- split subcommand. + + Copyright (C) 2013-2016,2018-2019,2023 Genome Research Ltd. + + Author: Martin Pollard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "samtools.h" + + +KHASH_MAP_INIT_STR(c2i, int) + +struct parsed_opts { + const char *merged_input_name; + const char *unaccounted_header_name; + const char *unaccounted_name; + const char *output_format_string; + bool verbose; + int no_pg; + sam_global_args ga; +}; + +typedef struct parsed_opts parsed_opts_t; + +struct state { + samFile* merged_input_file; + sam_hdr_t* merged_input_header; + samFile* unaccounted_file; + sam_hdr_t* unaccounted_header; + size_t output_count; + char** rg_id; + char **rg_index_file_name; + char **rg_output_file_name; + samFile** rg_output_file; + sam_hdr_t** rg_output_header; + kh_c2i_t* rg_hash; + htsThreadPool p; + int write_index; +}; + +typedef struct state state_t; + +static int cleanup_state(state_t* status, bool check_close); +static void cleanup_opts(parsed_opts_t* opts); + +static void usage(FILE *write_to) +{ + fprintf(write_to, +"Usage: samtools split [-u ] [-h ]\n" +" [-f ] [-v] \n" +"Options:\n" +" -f STRING output filename format string [\"%%*_%%#.%%.\"]\n" +" -u FILE1 put reads with no RG tag or an unrecognised RG tag in FILE1\n" +" -h FILE2 ... and override the header with FILE2 (-u file only)\n" +" -v verbose output\n" +" --no-PG do not add a PG line\n"); + sam_global_opt_help(write_to, "-....@.."); + fprintf(write_to, +"\n" +"Format string expansions:\n" +" %%%% %%\n" +" %%* basename\n" +" %%# @RG index\n" +" %%! @RG ID\n" +" %%. filename extension for output format\n" + ); +} + +// Takes the command line options and turns them into something we can understand +static parsed_opts_t* parse_args(int argc, char** argv) +{ + if (argc == 1) { usage(stdout); return NULL; } + + const char *optstring = "vf:h:u:@:"; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1); + if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; } + + sam_global_args_init(&retval->ga); + + int opt; + while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) { + switch (opt) { + case 'f': + retval->output_format_string = optarg; + break; + case 'h': + retval->unaccounted_header_name = optarg; + break; + case 'v': + retval->verbose = true; + break; + case 'u': + retval->unaccounted_name = optarg; + break; + case 1: + retval->no_pg = 1; + break; + default: + if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break; + /* else fall-through */ + case '?': + usage(stdout); + free(retval); + return NULL; + } + } + + if (retval->output_format_string == NULL) retval->output_format_string = "%*_%#.%."; + + argc -= optind; + argv += optind; + + if (argc != 1) { + print_error("split", "Invalid number of arguments: %d", argc); + usage(stderr); + free(retval); + return NULL; + } + + retval->merged_input_name = argv[0]; + + return retval; +} + +// Expands a output filename format string +static char* expand_format_string(const char* format_string, const char* basename, const char* rg_id, const int rg_idx, const htsFormat *format) +{ + kstring_t str = { 0, 0, NULL }; + const char* pointer = format_string; + const char* next; + while ((next = strchr(pointer, '%')) != NULL) { + if (kputsn(pointer, next-pointer, &str) < 0) goto memfail; + ++next; + switch (*next) { + case '%': + if (kputc('%', &str) < 0) goto memfail; + break; + case '*': + if (kputs(basename, &str) < 0) goto memfail; + break; + case '#': + if (kputl(rg_idx, &str) < 0) goto memfail; + break; + case '!': + if (kputs(rg_id, &str) < 0) goto memfail; + break; + case '.': + // Only really need to cope with sam, bam, cram + if (format->format != unknown_format) { + if (kputs(hts_format_file_extension(format), &str) < 0) + goto memfail; + } else { + if (kputs("bam", &str) < 0) goto memfail; + } + break; + case '\0': + print_error("split", "Trailing %% in filename format string"); + goto fail; + default: + // Error is: fprintf(stderr, "bad format string, unknown format specifier\n"); + print_error("split", "Unknown specifier %%%c in filename format string", *next); + goto fail; + } + pointer = next + 1; + } + if (kputs(pointer, &str) < 0) goto memfail; + return ks_release(&str); + + memfail: + print_error_errno("split", "Couldn't build output filename"); + fail: + free(str.s); + return NULL; +} + +// Parse the header, count the number of RG tags and return a list of their names +static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name) +{ + char **names = NULL; + kstring_t id_val = KS_INITIALIZE; + int i, n_rg = sam_hdr_count_lines(hdr, "RG"); + + if (n_rg < 0) { + print_error("split", "Failed to get @RG IDs"); + *count = 0; + *output_name = NULL; + return false; + } + + if (n_rg == 0) { + *count = 0; + *output_name = NULL; + return true; + } + + names = calloc(n_rg, sizeof(names[0])); + if (!names) goto memfail; + + for (i = 0; i < n_rg; i++) { + if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail; + names[i] = ks_release(&id_val); + } + + *count = n_rg; + *output_name = names; + return true; + + memfail: + print_error_errno("split", "Failed to get @RG IDs"); + *count = 0; + *output_name = NULL; + ks_free(&id_val); + free(names); + return false; +} + +static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2) +{ + size_t n; + if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) { + print_error("split", + "Unaccounted header contains wrong number of references"); + return -1; + } + for (n = 0; n < sam_hdr_nref(hdr1); n++) { + hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n); + hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n); + if (h1_len != h2_len) { + print_error("split", + "Unaccounted header reference %zu \"%s\" is not the same length as in the input file", + n + 1, sam_hdr_tid2name(hdr2, n)); + return -1; + } + } + return 0; +} + +// Set the initial state +static state_t* init(parsed_opts_t* opts, const char *arg_list) +{ + state_t* retval = calloc(sizeof(state_t), 1); + if (!retval) { + print_error_errno("split", "Initialisation failed"); + return NULL; + } + + if (opts->ga.nthreads > 0) { + if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) { + fprintf(stderr, "Error creating thread pool\n"); + cleanup_state(retval, false); + return NULL; + } + } + + retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in); + if (!retval->merged_input_file) { + print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name); + cleanup_state(retval, false); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p); + retval->merged_input_header = sam_hdr_read(retval->merged_input_file); + if (retval->merged_input_header == NULL) { + print_error("split", "Could not read header from \"%s\"", opts->merged_input_name); + cleanup_state(retval, false); + return NULL; + } + + if (opts->unaccounted_name) { + if (opts->unaccounted_header_name) { + samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in); + if (!hdr_load) { + print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name); + cleanup_state(retval, false); + return NULL; + } + retval->unaccounted_header = sam_hdr_read(hdr_load); + if (retval->unaccounted_header == NULL) { + print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name); + cleanup_state(retval, false); + sam_close(hdr_load); + return NULL; + } + sam_close(hdr_load); + if (header_compatible(retval->merged_input_header, + retval->unaccounted_header) != 0) { + cleanup_state(retval, false); + return NULL; + } + } else { + retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header); + if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name); + cleanup_state(retval, false); + return NULL; + } + } + + char outmode[4] = "w"; + sam_open_mode(outmode + 1, opts->unaccounted_name, NULL); + retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out); + + if (retval->unaccounted_file == NULL) { + print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name); + cleanup_state(retval, false); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p); + } + + // Open output files for RGs + if (!count_RG(retval->merged_input_header, &retval->output_count, &retval->rg_id)) return NULL; + if (opts->verbose) fprintf(stderr, "@RG's found %zu\n",retval->output_count); + // Prevent calloc(0, size); + size_t num = retval->output_count ? retval->output_count : 1; + retval->rg_index_file_name = (char **)calloc(num, sizeof(char *)); + retval->rg_output_file_name = (char **)calloc(num, sizeof(char *)); + retval->rg_output_file = (samFile**)calloc(num, sizeof(samFile*)); + retval->rg_output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*)); + retval->rg_hash = kh_init_c2i(); + if (!retval->rg_output_file_name || !retval->rg_output_file || !retval->rg_output_header || + !retval->rg_hash || !retval->rg_index_file_name) { + print_error_errno("split", "Could not initialise output file array"); + cleanup_state(retval, false); + return NULL; + } + + char* dirsep = strrchr(opts->merged_input_name, '/'); + char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name); + if (!input_base_name) { + print_error_errno("split", "Filename manipulation failed"); + cleanup_state(retval, false); + return NULL; + } + char* extension = strrchr(input_base_name, '.'); + if (extension) *extension = '\0'; + + size_t i; + for (i = 0; i < retval->output_count; i++) { + char* output_filename = NULL; + char outmode[4] = "w"; + + output_filename = expand_format_string(opts->output_format_string, + input_base_name, + retval->rg_id[i], i, + &opts->ga.out); + + if ( output_filename == NULL ) { + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + + retval->rg_output_file_name[i] = output_filename; + + sam_open_mode(outmode + 1, output_filename, NULL); + retval->rg_output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out); + + if (retval->rg_output_file[i] == NULL) { + print_error_errno("split", "Could not open \"%s\"", output_filename); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->rg_output_file[i], HTS_OPT_THREAD_POOL, &retval->p); + + // Record index in hash + int ret; + khiter_t iter = kh_put_c2i(retval->rg_hash, retval->rg_id[i], &ret); + if (ret < 0) { + print_error_errno("split", "Couldn't add @RG ID to look-up table"); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + kh_val(retval->rg_hash,iter) = i; + + // Set and edit header + retval->rg_output_header[i] = sam_hdr_dup(retval->merged_input_header); + if (sam_hdr_remove_except(retval->rg_output_header[i], "RG", "ID", retval->rg_id[i]) || + (!opts->no_pg && + sam_hdr_add_pg(retval->rg_output_header[i], "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL))) { + print_error("split", "Could not rewrite header for \"%s\"", output_filename); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + } + + free(input_base_name); + retval->write_index = opts->ga.write_index; + + return retval; +} + +static bool split(state_t* state) +{ + if (state->unaccounted_file && sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) { + print_error_errno("split", "Could not write output file header"); + return false; + } + size_t i; + for (i = 0; i < state->output_count; i++) { + if (sam_hdr_write(state->rg_output_file[i], state->rg_output_header[i]) != 0) { + print_error_errno("split", "Could not write file header to \"%s\"", state->rg_output_file_name[i]); + return false; + } + if (state->write_index) { + state->rg_index_file_name[i] = auto_index(state->rg_output_file[i], + state->rg_output_file_name[i], + state->rg_output_header[i]); + if (!state->rg_index_file_name[i]) { + print_error_errno("split", "Could not create index for file \"%s\"", state->rg_output_file_name[i]); + return false; + } + } + } + + bam1_t* file_read = bam_init1(); + // Read the first record + int r; + if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) { + // Nothing more to read? Ignore this file + bam_destroy1(file_read); + file_read = NULL; + if (r < -1) { + print_error("split", "Could not read first input record"); + return false; + } + } + + while (file_read != NULL) { + // Get RG tag from read and look it up in hash to find file to output it to + uint8_t* tag = bam_aux_get(file_read, "RG"); + khiter_t iter; + if ( tag != NULL ) { + char* rg = bam_aux2Z(tag); + iter = kh_get_c2i(state->rg_hash, rg); + } else { + iter = kh_end(state->rg_hash); + } + + // Write the read out to correct file + if (iter != kh_end(state->rg_hash)) { + // if found write to the appropriate untangled bam + int i = kh_val(state->rg_hash,iter); + if (sam_write1(state->rg_output_file[i], state->rg_output_header[i], file_read) < 0) { + print_error_errno("split", "Could not write to \"%s\"", state->rg_output_file_name[i]); + bam_destroy1(file_read); + return false; + } + } else { + // otherwise write to the unaccounted bam if there is one or fail + if (state->unaccounted_file == NULL) { + if (tag) { + fprintf(stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag)); + } else { + fprintf(stderr, "Read \"%s\" has no RG tag.\n", bam_get_qname(file_read)); + } + bam_destroy1(file_read); + return false; + } else { + if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) { + print_error_errno("split", "Could not write to unaccounted output file"); + bam_destroy1(file_read); + return false; + } + } + } + + // Replace written read with the next one to process + if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) { + // Nothing more to read? Ignore this file in future + bam_destroy1(file_read); + file_read = NULL; + if (r < -1) { + print_error("split", "Could not read input record"); + return false; + } + } + } + + if (state->write_index) { + for (i = 0; i < state->output_count; i++) { + if (sam_idx_save(state->rg_output_file[i]) < 0) { + print_error_errno("split", "writing index failed"); + return false; + } + free(state->rg_index_file_name[i]); + } + } + + return true; +} + +static int cleanup_state(state_t* status, bool check_close) +{ + int ret = 0; + + if (!status) return 0; + if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header); + if (status->unaccounted_file) { + if (sam_close(status->unaccounted_file) < 0 && check_close) { + print_error("split", "Error on closing unaccounted file"); + ret = -1; + } + } + sam_close(status->merged_input_file); + size_t i; + for (i = 0; i < status->output_count; i++) { + if (status->rg_output_header && status->rg_output_header[i]) + sam_hdr_destroy(status->rg_output_header[i]); + if (status->rg_output_file && status->rg_output_file[i]) { + if (sam_close(status->rg_output_file[i]) < 0 && check_close) { + print_error("split", "Error on closing output file \"%s\"", status->rg_output_file_name[i]); + ret = -1; + } + } + if (status->rg_id) free(status->rg_id[i]); + if (status->rg_output_file_name) free(status->rg_output_file_name[i]); + } + if (status->merged_input_header) + sam_hdr_destroy(status->merged_input_header); + free(status->rg_output_header); + free(status->rg_output_file); + free(status->rg_output_file_name); + free(status->rg_index_file_name); + kh_destroy_c2i(status->rg_hash); + free(status->rg_id); + if (status->p.pool) + hts_tpool_destroy(status->p.pool); + free(status); + + return ret; +} + +static void cleanup_opts(parsed_opts_t* opts) +{ + if (!opts) return; + sam_global_args_free(&opts->ga); + free(opts); +} + +int main_split(int argc, char** argv) +{ + int ret = 1; + char *arg_list = NULL; + parsed_opts_t* opts = parse_args(argc, argv); + if (!opts) goto cleanup_opts; + if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) + goto cleanup_opts; + state_t* status = init(opts, arg_list); + if (!status) goto cleanup_opts; + + if (!split(status)) { + cleanup_state(status, false); + goto cleanup_opts; + } + + ret = cleanup_state(status, true); + +cleanup_opts: + cleanup_opts(opts); + free(arg_list); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..6c48466da729b35e22850fec99c935b57a56b389 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_split.c.pysam.c @@ -0,0 +1,620 @@ +#include "samtools.pysam.h" + +/* bam_split.c -- split subcommand. + + Copyright (C) 2013-2016,2018-2019,2023 Genome Research Ltd. + + Author: Martin Pollard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/thread_pool.h" +#include "sam_opts.h" +#include "samtools.h" + + +KHASH_MAP_INIT_STR(c2i, int) + +struct parsed_opts { + const char *merged_input_name; + const char *unaccounted_header_name; + const char *unaccounted_name; + const char *output_format_string; + bool verbose; + int no_pg; + sam_global_args ga; +}; + +typedef struct parsed_opts parsed_opts_t; + +struct state { + samFile* merged_input_file; + sam_hdr_t* merged_input_header; + samFile* unaccounted_file; + sam_hdr_t* unaccounted_header; + size_t output_count; + char** rg_id; + char **rg_index_file_name; + char **rg_output_file_name; + samFile** rg_output_file; + sam_hdr_t** rg_output_header; + kh_c2i_t* rg_hash; + htsThreadPool p; + int write_index; +}; + +typedef struct state state_t; + +static int cleanup_state(state_t* status, bool check_close); +static void cleanup_opts(parsed_opts_t* opts); + +static void usage(FILE *write_to) +{ + fprintf(write_to, +"Usage: samtools split [-u ] [-h ]\n" +" [-f ] [-v] \n" +"Options:\n" +" -f STRING output filename format string [\"%%*_%%#.%%.\"]\n" +" -u FILE1 put reads with no RG tag or an unrecognised RG tag in FILE1\n" +" -h FILE2 ... and override the header with FILE2 (-u file only)\n" +" -v verbose output\n" +" --no-PG do not add a PG line\n"); + sam_global_opt_help(write_to, "-....@.."); + fprintf(write_to, +"\n" +"Format string expansions:\n" +" %%%% %%\n" +" %%* basename\n" +" %%# @RG index\n" +" %%! @RG ID\n" +" %%. filename extension for output format\n" + ); +} + +// Takes the command line options and turns them into something we can understand +static parsed_opts_t* parse_args(int argc, char** argv) +{ + if (argc == 1) { usage(samtools_stdout); return NULL; } + + const char *optstring = "vf:h:u:@:"; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1); + if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; } + + sam_global_args_init(&retval->ga); + + int opt; + while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) { + switch (opt) { + case 'f': + retval->output_format_string = optarg; + break; + case 'h': + retval->unaccounted_header_name = optarg; + break; + case 'v': + retval->verbose = true; + break; + case 'u': + retval->unaccounted_name = optarg; + break; + case 1: + retval->no_pg = 1; + break; + default: + if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break; + /* else fall-through */ + case '?': + usage(samtools_stdout); + free(retval); + return NULL; + } + } + + if (retval->output_format_string == NULL) retval->output_format_string = "%*_%#.%."; + + argc -= optind; + argv += optind; + + if (argc != 1) { + print_error("split", "Invalid number of arguments: %d", argc); + usage(samtools_stderr); + free(retval); + return NULL; + } + + retval->merged_input_name = argv[0]; + + return retval; +} + +// Expands a output filename format string +static char* expand_format_string(const char* format_string, const char* basename, const char* rg_id, const int rg_idx, const htsFormat *format) +{ + kstring_t str = { 0, 0, NULL }; + const char* pointer = format_string; + const char* next; + while ((next = strchr(pointer, '%')) != NULL) { + if (kputsn(pointer, next-pointer, &str) < 0) goto memfail; + ++next; + switch (*next) { + case '%': + if (kputc('%', &str) < 0) goto memfail; + break; + case '*': + if (kputs(basename, &str) < 0) goto memfail; + break; + case '#': + if (kputl(rg_idx, &str) < 0) goto memfail; + break; + case '!': + if (kputs(rg_id, &str) < 0) goto memfail; + break; + case '.': + // Only really need to cope with sam, bam, cram + if (format->format != unknown_format) { + if (kputs(hts_format_file_extension(format), &str) < 0) + goto memfail; + } else { + if (kputs("bam", &str) < 0) goto memfail; + } + break; + case '\0': + print_error("split", "Trailing %% in filename format string"); + goto fail; + default: + // Error is: fprintf(samtools_stderr, "bad format string, unknown format specifier\n"); + print_error("split", "Unknown specifier %%%c in filename format string", *next); + goto fail; + } + pointer = next + 1; + } + if (kputs(pointer, &str) < 0) goto memfail; + return ks_release(&str); + + memfail: + print_error_errno("split", "Couldn't build output filename"); + fail: + free(str.s); + return NULL; +} + +// Parse the header, count the number of RG tags and return a list of their names +static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name) +{ + char **names = NULL; + kstring_t id_val = KS_INITIALIZE; + int i, n_rg = sam_hdr_count_lines(hdr, "RG"); + + if (n_rg < 0) { + print_error("split", "Failed to get @RG IDs"); + *count = 0; + *output_name = NULL; + return false; + } + + if (n_rg == 0) { + *count = 0; + *output_name = NULL; + return true; + } + + names = calloc(n_rg, sizeof(names[0])); + if (!names) goto memfail; + + for (i = 0; i < n_rg; i++) { + if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail; + names[i] = ks_release(&id_val); + } + + *count = n_rg; + *output_name = names; + return true; + + memfail: + print_error_errno("split", "Failed to get @RG IDs"); + *count = 0; + *output_name = NULL; + ks_free(&id_val); + free(names); + return false; +} + +static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2) +{ + size_t n; + if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) { + print_error("split", + "Unaccounted header contains wrong number of references"); + return -1; + } + for (n = 0; n < sam_hdr_nref(hdr1); n++) { + hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n); + hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n); + if (h1_len != h2_len) { + print_error("split", + "Unaccounted header reference %zu \"%s\" is not the same length as in the input file", + n + 1, sam_hdr_tid2name(hdr2, n)); + return -1; + } + } + return 0; +} + +// Set the initial state +static state_t* init(parsed_opts_t* opts, const char *arg_list) +{ + state_t* retval = calloc(sizeof(state_t), 1); + if (!retval) { + print_error_errno("split", "Initialisation failed"); + return NULL; + } + + if (opts->ga.nthreads > 0) { + if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) { + fprintf(samtools_stderr, "Error creating thread pool\n"); + cleanup_state(retval, false); + return NULL; + } + } + + retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in); + if (!retval->merged_input_file) { + print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name); + cleanup_state(retval, false); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p); + retval->merged_input_header = sam_hdr_read(retval->merged_input_file); + if (retval->merged_input_header == NULL) { + print_error("split", "Could not read header from \"%s\"", opts->merged_input_name); + cleanup_state(retval, false); + return NULL; + } + + if (opts->unaccounted_name) { + if (opts->unaccounted_header_name) { + samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in); + if (!hdr_load) { + print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name); + cleanup_state(retval, false); + return NULL; + } + retval->unaccounted_header = sam_hdr_read(hdr_load); + if (retval->unaccounted_header == NULL) { + print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name); + cleanup_state(retval, false); + sam_close(hdr_load); + return NULL; + } + sam_close(hdr_load); + if (header_compatible(retval->merged_input_header, + retval->unaccounted_header) != 0) { + cleanup_state(retval, false); + return NULL; + } + } else { + retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header); + if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name); + cleanup_state(retval, false); + return NULL; + } + } + + char outmode[4] = "w"; + sam_open_mode(outmode + 1, opts->unaccounted_name, NULL); + retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out); + + if (retval->unaccounted_file == NULL) { + print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name); + cleanup_state(retval, false); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p); + } + + // Open output files for RGs + if (!count_RG(retval->merged_input_header, &retval->output_count, &retval->rg_id)) return NULL; + if (opts->verbose) fprintf(samtools_stderr, "@RG's found %zu\n",retval->output_count); + // Prevent calloc(0, size); + size_t num = retval->output_count ? retval->output_count : 1; + retval->rg_index_file_name = (char **)calloc(num, sizeof(char *)); + retval->rg_output_file_name = (char **)calloc(num, sizeof(char *)); + retval->rg_output_file = (samFile**)calloc(num, sizeof(samFile*)); + retval->rg_output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*)); + retval->rg_hash = kh_init_c2i(); + if (!retval->rg_output_file_name || !retval->rg_output_file || !retval->rg_output_header || + !retval->rg_hash || !retval->rg_index_file_name) { + print_error_errno("split", "Could not initialise output file array"); + cleanup_state(retval, false); + return NULL; + } + + char* dirsep = strrchr(opts->merged_input_name, '/'); + char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name); + if (!input_base_name) { + print_error_errno("split", "Filename manipulation failed"); + cleanup_state(retval, false); + return NULL; + } + char* extension = strrchr(input_base_name, '.'); + if (extension) *extension = '\0'; + + size_t i; + for (i = 0; i < retval->output_count; i++) { + char* output_filename = NULL; + char outmode[4] = "w"; + + output_filename = expand_format_string(opts->output_format_string, + input_base_name, + retval->rg_id[i], i, + &opts->ga.out); + + if ( output_filename == NULL ) { + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + + retval->rg_output_file_name[i] = output_filename; + + sam_open_mode(outmode + 1, output_filename, NULL); + retval->rg_output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out); + + if (retval->rg_output_file[i] == NULL) { + print_error_errno("split", "Could not open \"%s\"", output_filename); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + if (retval->p.pool) + hts_set_opt(retval->rg_output_file[i], HTS_OPT_THREAD_POOL, &retval->p); + + // Record index in hash + int ret; + khiter_t iter = kh_put_c2i(retval->rg_hash, retval->rg_id[i], &ret); + if (ret < 0) { + print_error_errno("split", "Couldn't add @RG ID to look-up table"); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + kh_val(retval->rg_hash,iter) = i; + + // Set and edit header + retval->rg_output_header[i] = sam_hdr_dup(retval->merged_input_header); + if (sam_hdr_remove_except(retval->rg_output_header[i], "RG", "ID", retval->rg_id[i]) || + (!opts->no_pg && + sam_hdr_add_pg(retval->rg_output_header[i], "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL))) { + print_error("split", "Could not rewrite header for \"%s\"", output_filename); + cleanup_state(retval, false); + free(input_base_name); + return NULL; + } + } + + free(input_base_name); + retval->write_index = opts->ga.write_index; + + return retval; +} + +static bool split(state_t* state) +{ + if (state->unaccounted_file && sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) { + print_error_errno("split", "Could not write output file header"); + return false; + } + size_t i; + for (i = 0; i < state->output_count; i++) { + if (sam_hdr_write(state->rg_output_file[i], state->rg_output_header[i]) != 0) { + print_error_errno("split", "Could not write file header to \"%s\"", state->rg_output_file_name[i]); + return false; + } + if (state->write_index) { + state->rg_index_file_name[i] = auto_index(state->rg_output_file[i], + state->rg_output_file_name[i], + state->rg_output_header[i]); + if (!state->rg_index_file_name[i]) { + print_error_errno("split", "Could not create index for file \"%s\"", state->rg_output_file_name[i]); + return false; + } + } + } + + bam1_t* file_read = bam_init1(); + // Read the first record + int r; + if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) { + // Nothing more to read? Ignore this file + bam_destroy1(file_read); + file_read = NULL; + if (r < -1) { + print_error("split", "Could not read first input record"); + return false; + } + } + + while (file_read != NULL) { + // Get RG tag from read and look it up in hash to find file to output it to + uint8_t* tag = bam_aux_get(file_read, "RG"); + khiter_t iter; + if ( tag != NULL ) { + char* rg = bam_aux2Z(tag); + iter = kh_get_c2i(state->rg_hash, rg); + } else { + iter = kh_end(state->rg_hash); + } + + // Write the read out to correct file + if (iter != kh_end(state->rg_hash)) { + // if found write to the appropriate untangled bam + int i = kh_val(state->rg_hash,iter); + if (sam_write1(state->rg_output_file[i], state->rg_output_header[i], file_read) < 0) { + print_error_errno("split", "Could not write to \"%s\"", state->rg_output_file_name[i]); + bam_destroy1(file_read); + return false; + } + } else { + // otherwise write to the unaccounted bam if there is one or fail + if (state->unaccounted_file == NULL) { + if (tag) { + fprintf(samtools_stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag)); + } else { + fprintf(samtools_stderr, "Read \"%s\" has no RG tag.\n", bam_get_qname(file_read)); + } + bam_destroy1(file_read); + return false; + } else { + if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) { + print_error_errno("split", "Could not write to unaccounted output file"); + bam_destroy1(file_read); + return false; + } + } + } + + // Replace written read with the next one to process + if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) { + // Nothing more to read? Ignore this file in future + bam_destroy1(file_read); + file_read = NULL; + if (r < -1) { + print_error("split", "Could not read input record"); + return false; + } + } + } + + if (state->write_index) { + for (i = 0; i < state->output_count; i++) { + if (sam_idx_save(state->rg_output_file[i]) < 0) { + print_error_errno("split", "writing index failed"); + return false; + } + free(state->rg_index_file_name[i]); + } + } + + return true; +} + +static int cleanup_state(state_t* status, bool check_close) +{ + int ret = 0; + + if (!status) return 0; + if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header); + if (status->unaccounted_file) { + if (sam_close(status->unaccounted_file) < 0 && check_close) { + print_error("split", "Error on closing unaccounted file"); + ret = -1; + } + } + sam_close(status->merged_input_file); + size_t i; + for (i = 0; i < status->output_count; i++) { + if (status->rg_output_header && status->rg_output_header[i]) + sam_hdr_destroy(status->rg_output_header[i]); + if (status->rg_output_file && status->rg_output_file[i]) { + if (sam_close(status->rg_output_file[i]) < 0 && check_close) { + print_error("split", "Error on closing output file \"%s\"", status->rg_output_file_name[i]); + ret = -1; + } + } + if (status->rg_id) free(status->rg_id[i]); + if (status->rg_output_file_name) free(status->rg_output_file_name[i]); + } + if (status->merged_input_header) + sam_hdr_destroy(status->merged_input_header); + free(status->rg_output_header); + free(status->rg_output_file); + free(status->rg_output_file_name); + free(status->rg_index_file_name); + kh_destroy_c2i(status->rg_hash); + free(status->rg_id); + if (status->p.pool) + hts_tpool_destroy(status->p.pool); + free(status); + + return ret; +} + +static void cleanup_opts(parsed_opts_t* opts) +{ + if (!opts) return; + sam_global_args_free(&opts->ga); + free(opts); +} + +int main_split(int argc, char** argv) +{ + int ret = 1; + char *arg_list = NULL; + parsed_opts_t* opts = parse_args(argc, argv); + if (!opts) goto cleanup_opts; + if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) + goto cleanup_opts; + state_t* status = init(opts, arg_list); + if (!status) goto cleanup_opts; + + if (!split(status)) { + cleanup_state(status, false); + goto cleanup_opts; + } + + ret = cleanup_state(status, true); + +cleanup_opts: + cleanup_opts(opts); + free(arg_list); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_stat.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..31dc8fe4e453b49b11acaee942bffdcb6dca80f4 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bam_stat.c @@ -0,0 +1,346 @@ +/* bam_stat.c -- flagstat subcommand. + + Copyright (C) 2009, 2011, 2013-2015, 2019, 2021 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "htslib/sam.h" +#include "samtools.h" +#include "sam_opts.h" + +typedef struct { + long long n_reads[2], n_mapped[2], n_pair_all[2], n_pair_map[2], n_pair_good[2]; + long long n_sgltn[2], n_read1[2], n_read2[2]; + long long n_dup[2]; + long long n_diffchr[2], n_diffhigh[2]; + long long n_secondary[2], n_supp[2]; + long long n_primary[2], n_pmapped[2], n_pdup[2]; +} bam_flagstat_t; + +inline static void flagstat_loop(bam_flagstat_t *s, bam1_core_t *c) +{ + int w = (c->flag & BAM_FQCFAIL)? 1 : 0; + ++s->n_reads[w]; + if (c->flag & BAM_FSECONDARY ) { + ++s->n_secondary[w]; + } else if (c->flag & BAM_FSUPPLEMENTARY ) { + ++s->n_supp[w]; + } else { + ++s->n_primary[w]; + + if (c->flag & BAM_FPAIRED) { + ++s->n_pair_all[w]; + if ((c->flag & BAM_FPROPER_PAIR) && !(c->flag & BAM_FUNMAP) ) ++s->n_pair_good[w]; + if (c->flag & BAM_FREAD1) ++s->n_read1[w]; + if (c->flag & BAM_FREAD2) ++s->n_read2[w]; + if ((c->flag & BAM_FMUNMAP) && !(c->flag & BAM_FUNMAP)) ++s->n_sgltn[w]; + if (!(c->flag & BAM_FUNMAP) && !(c->flag & BAM_FMUNMAP)) { + ++s->n_pair_map[w]; + if (c->mtid != c->tid) { + ++s->n_diffchr[w]; + if (c->qual >= 5) ++s->n_diffhigh[w]; + } + } + } + + if (!(c->flag & BAM_FUNMAP)) ++s->n_pmapped[w]; + if (c->flag & BAM_FDUP) ++s->n_pdup[w]; + } + if (!(c->flag & BAM_FUNMAP)) ++s->n_mapped[w]; + if (c->flag & BAM_FDUP) ++s->n_dup[w]; +} + +bam_flagstat_t *bam_flagstat_core(samFile *fp, sam_hdr_t *h) +{ + bam_flagstat_t *s; + bam1_t *b; + bam1_core_t *c; + int ret; + s = (bam_flagstat_t*)calloc(1, sizeof(bam_flagstat_t)); + b = bam_init1(); + c = &b->core; + while ((ret = sam_read1(fp, h, b)) >= 0) + flagstat_loop(s, c); + bam_destroy1(b); + if (ret != -1) { + free(s); + return NULL; + } + return s; +} + +static const char *percent(char *buffer, long long n, long long total) +{ + if (total != 0) sprintf(buffer, "%.2f%%", (float)n / total * 100.0); + else strcpy(buffer, "N/A"); + return buffer; +} + +static const char *percent_json(char *buffer, long long n, long long total) +{ + if (total != 0) sprintf(buffer, "%.2f", (float)n / total * 100.0); + else strcpy(buffer, "null"); + return buffer; +} + +static void usage_exit(FILE *fp, int exit_status) +{ + fprintf(fp, "Usage: samtools flagstat [options] \n"); + sam_global_opt_help(fp, "-.---@-."); + fprintf(fp, " -O, --"); + fprintf(fp, "output-fmt FORMAT[,OPT[=VAL]]...\n" + " Specify output format (json, tsv)\n"); + exit(exit_status); +} + +static void out_fmt_default(bam_flagstat_t *s) +{ + char b0[16], b1[16]; + printf("%lld + %lld in total (QC-passed reads + QC-failed reads)\n", s->n_reads[0], s->n_reads[1]); + printf("%lld + %lld primary\n", s->n_primary[0], s->n_primary[1]); + printf("%lld + %lld secondary\n", s->n_secondary[0], s->n_secondary[1]); + printf("%lld + %lld supplementary\n", s->n_supp[0], s->n_supp[1]); + printf("%lld + %lld duplicates\n", s->n_dup[0], s->n_dup[1]); + printf("%lld + %lld primary duplicates\n", s->n_pdup[0], s->n_pdup[1]); + 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])); + 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])); + printf("%lld + %lld paired in sequencing\n", s->n_pair_all[0], s->n_pair_all[1]); + printf("%lld + %lld read1\n", s->n_read1[0], s->n_read1[1]); + printf("%lld + %lld read2\n", s->n_read2[0], s->n_read2[1]); + 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])); + printf("%lld + %lld with itself and mate mapped\n", s->n_pair_map[0], s->n_pair_map[1]); + 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])); + printf("%lld + %lld with mate mapped to a different chr\n", s->n_diffchr[0], s->n_diffchr[1]); + printf("%lld + %lld with mate mapped to a different chr (mapQ>=5)\n", s->n_diffhigh[0], s->n_diffhigh[1]); +} + +static void out_fmt_json(bam_flagstat_t *s) { + char b0[16], b1[16], p0[16], p1[16], pp0[16], pp1[16], s0[16], s1[16]; + printf("{\n \"QC-passed reads\": { \n" + " \"total\": %lld, \n" + " \"primary\": %lld, \n" + " \"secondary\": %lld, \n" + " \"supplementary\": %lld, \n" + " \"duplicates\": %lld, \n" + " \"primary duplicates\": %lld, \n" + " \"mapped\": %lld, \n" + " \"mapped %%\": %s, \n" + " \"primary mapped\": %lld, \n" + " \"primary mapped %%\": %s, \n" + " \"paired in sequencing\": %lld, \n" + " \"read1\": %lld, \n" + " \"read2\": %lld, \n" + " \"properly paired\": %lld, \n" + " \"properly paired %%\": %s, \n" + " \"with itself and mate mapped\": %lld, \n" + " \"singletons\": %lld, \n" + " \"singletons %%\": %s, \n" + " \"with mate mapped to a different chr\": %lld, \n" + " \"with mate mapped to a different chr (mapQ >= 5)\": %lld \n" + " }," + "\n \"QC-failed reads\": { \n" + " \"total\": %lld, \n" + " \"primary\": %lld, \n" + " \"secondary\": %lld, \n" + " \"supplementary\": %lld, \n" + " \"duplicates\": %lld, \n" + " \"primary duplicates\": %lld, \n" + " \"mapped\": %lld, \n" + " \"mapped %%\": %s, \n" + " \"primary mapped\": %lld, \n" + " \"primary mapped %%\": %s, \n" + " \"paired in sequencing\": %lld, \n" + " \"read1\": %lld, \n" + " \"read2\": %lld, \n" + " \"properly paired\": %lld, \n" + " \"properly paired %%\": %s, \n" + " \"with itself and mate mapped\": %lld, \n" + " \"singletons\": %lld, \n" + " \"singletons %%\": %s, \n" + " \"with mate mapped to a different chr\": %lld, \n" + " \"with mate mapped to a different chr (mapQ >= 5)\": %lld \n" + " }\n" + "}\n", + s->n_reads[0], + s->n_primary[0], + s->n_secondary[0], + s->n_supp[0], + s->n_dup[0], + s->n_pdup[0], + s->n_mapped[0], + percent_json(b0, s->n_mapped[0], s->n_reads[0]), + s->n_pmapped[0], + percent_json(p0, s->n_pmapped[0], s->n_primary[0]), + s->n_pair_all[0], + s->n_read1[0], + s->n_read2[0], + s->n_pair_good[0], + percent_json(pp0, s->n_pair_good[0], s->n_pair_all[0]), + s->n_pair_map[0], + s->n_sgltn[0], + percent_json(s0, s->n_sgltn[0], s->n_pair_all[0]), + s->n_diffchr[0], + s->n_diffhigh[0], + s->n_reads[1], + s->n_primary[1], + s->n_secondary[1], + s->n_supp[1], + s->n_dup[1], + s->n_pdup[1], + s->n_mapped[1], + percent_json(b1, s->n_mapped[1], s->n_reads[1]), + s->n_pmapped[1], + percent_json(p1, s->n_pmapped[1], s->n_primary[1]), + s->n_pair_all[1], + s->n_read1[1], + s->n_read2[1], + s->n_pair_good[1], + percent_json(pp1, s->n_pair_good[1], s->n_pair_all[1]), + s->n_pair_map[1], + s->n_sgltn[1], + percent_json(s1, s->n_sgltn[1], s->n_pair_all[1]), + s->n_diffchr[1], + s->n_diffhigh[1] + ); +} + +static void out_fmt_tsv(bam_flagstat_t *s) { + char b0[16], b1[16]; + printf("%lld\t%lld\ttotal (QC-passed reads + QC-failed reads)\n", s->n_reads[0], s->n_reads[1]); + printf("%lld\t%lld\tprimary\n", s->n_primary[0], s->n_primary[1]); + printf("%lld\t%lld\tsecondary\n", s->n_secondary[0], s->n_secondary[1]); + printf("%lld\t%lld\tsupplementary\n", s->n_supp[0], s->n_supp[1]); + printf("%lld\t%lld\tduplicates\n", s->n_dup[0], s->n_dup[1]); + printf("%lld\t%lld\tprimary duplicates\n", s->n_pdup[0], s->n_pdup[1]); + printf("%lld\t%lld\tmapped\n", s->n_mapped[0], s->n_mapped[1]); + 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])); + printf("%lld\t%lld\tprimary mapped\n", s->n_pmapped[0], s->n_pmapped[1]); + 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])); + printf("%lld\t%lld\tpaired in sequencing\n", s->n_pair_all[0], s->n_pair_all[1]); + printf("%lld\t%lld\tread1\n", s->n_read1[0], s->n_read1[1]); + printf("%lld\t%lld\tread2\n", s->n_read2[0], s->n_read2[1]); + printf("%lld\t%lld\tproperly paired\n", s->n_pair_good[0], s->n_pair_good[1]); + 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])); + printf("%lld\t%lld\twith itself and mate mapped\n", s->n_pair_map[0], s->n_pair_map[1]); + printf("%lld\t%lld\tsingletons\n", s->n_sgltn[0], s->n_sgltn[1]); + 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])); + printf("%lld\t%lld\twith mate mapped to a different chr\n", s->n_diffchr[0], s->n_diffchr[1]); + printf("%lld\t%lld\twith mate mapped to a different chr (mapQ>=5)\n", s->n_diffhigh[0], s->n_diffhigh[1]); +} + +/* + * Select flagstats output format to print. + */ +static void output_fmt(bam_flagstat_t *s, const char *out_fmt) +{ + if (strcmp(out_fmt, "json") == 0 || strcmp(out_fmt, "JSON") == 0) { + out_fmt_json(s); + } else if (strcmp(out_fmt, "tsv") == 0 || strcmp(out_fmt, "TSV") == 0) { + out_fmt_tsv(s); + } else { + out_fmt_default(s); + } +} + +int bam_flagstat(int argc, char *argv[]) +{ + samFile *fp; + sam_hdr_t *header; + bam_flagstat_t *s; + const char *out_fmt = "default"; + int c, status = EXIT_SUCCESS; + + enum { + INPUT_FMT_OPTION = CHAR_MAX+1, + }; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', '-', '-', '@'), + {NULL, 0, NULL, 0} + }; + + while ((c = getopt_long(argc, argv, "@:O:", lopts, NULL)) >= 0) { + switch (c) { + case 'O': + out_fmt = optarg; + break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + usage_exit(stderr, EXIT_FAILURE); + } + } + + if (argc != optind+1) { + if (argc == optind) usage_exit(stdout, EXIT_SUCCESS); + else usage_exit(stderr, EXIT_FAILURE); + } + fp = sam_open_format(argv[optind], "r", &ga.in); + if (fp == NULL) { + print_error_errno("flagstat", "Cannot open input file \"%s\"", argv[optind]); + return 1; + } + if (ga.nthreads > 0) + hts_set_threads(fp, ga.nthreads); + + if (hts_set_opt(fp, CRAM_OPT_REQUIRED_FIELDS, + SAM_FLAG | SAM_MAPQ | SAM_RNEXT)) { + fprintf(stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n"); + return 1; + } + + if (hts_set_opt(fp, CRAM_OPT_DECODE_MD, 0)) { + fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n"); + return 1; + } + + header = sam_hdr_read(fp); + if (header == NULL) { + fprintf(stderr, "Failed to read header for \"%s\"\n", argv[optind]); + return 1; + } + + s = bam_flagstat_core(fp, header); + if (s) { + output_fmt(s, out_fmt); + free(s); + } + else { + print_error("flagstat", "error reading from \"%s\"", argv[optind]); + status = EXIT_FAILURE; + } + + sam_hdr_destroy(header); + sam_close(fp); + sam_global_args_free(&ga); + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bamtk.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bamtk.c new file mode 100644 index 0000000000000000000000000000000000000000..e05ea18162885b249c7f4b4c544e2e1b99162d68 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bamtk.c @@ -0,0 +1,307 @@ +/* bamtk.c -- main samtools command front-end. + + Copyright (C) 2008-2023 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include + +#include "htslib/hts.h" +#include "htslib/hfile.h" +#include "samtools.h" +#include "version.h" + +int bam_taf2baf(int argc, char *argv[]); +int bam_mpileup(int argc, char *argv[]); +int bam_merge(int argc, char *argv[]); +int bam_index(int argc, char *argv[]); +int bam_sort(int argc, char *argv[]); +int bam_tview_main(int argc, char *argv[]); +int bam_mating(int argc, char *argv[]); +int bam_rmdup(int argc, char *argv[]); +int bam_flagstat(int argc, char *argv[]); +int bam_fillmd(int argc, char *argv[]); +int bam_idxstats(int argc, char *argv[]); +int bam_markdup(int argc, char *argv[]); +int main_samview(int argc, char *argv[]); +int main_head(int argc, char *argv[]); +int main_reheader(int argc, char *argv[]); +int main_cut_target(int argc, char *argv[]); +int main_phase(int argc, char *argv[]); +int main_cat(int argc, char *argv[]); +int main_depth(int argc, char *argv[]); +int main_coverage(int argc, char *argv[]); +int main_bam2fq(int argc, char *argv[]); +int main_pad2unpad(int argc, char *argv[]); +int main_bedcov(int argc, char *argv[]); +int main_bamshuf(int argc, char *argv[]); +int main_stats(int argc, char *argv[]); +int main_flags(int argc, char *argv[]); +int main_split(int argc, char *argv[]); +int main_quickcheck(int argc, char *argv[]); +int main_addreplacerg(int argc, char *argv[]); +int faidx_main(int argc, char *argv[]); +int dict_main(int argc, char *argv[]); +int fqidx_main(int argc, char *argv[]); +int amplicon_clip_main(int argc, char *argv[]); +int main_ampliconstats(int argc, char *argv[]); +int main_import(int argc, char *argv[]); +int main_samples(int argc, char *argv[]); +int main_consensus(int argc, char *argv[]); +int main_reference(int argc, char *argv[]); +int main_reset(int argc, char *argv[]); +int main_cram_size(int argc, char *argv[]); + +const char *samtools_version() +{ + return SAMTOOLS_VERSION; +} + +// These come out of the config.h file built by autoconf or Makefile +const char *samtools_feature_string(void) { + const char *fmt = + +#ifdef PACKAGE_URL + "build=configure " +#else + "build=Makefile " +#endif + +#ifdef HAVE_CURSES + "curses=yes " +#else + "curses=no " +#endif + ; + + return fmt; +} + +static void long_version(void) { + printf("samtools %s\n" + "Using htslib %s\n" + "Copyright (C) 2023 Genome Research Ltd.\n", + samtools_version(), hts_version()); + + printf("\nSamtools compilation details:\n"); + printf(" Features: %s\n", samtools_feature_string()); + printf(" CC: %s\n", SAMTOOLS_CC); + printf(" CPPFLAGS: %s\n", SAMTOOLS_CPPFLAGS); + printf(" CFLAGS: %s\n", SAMTOOLS_CFLAGS); + printf(" LDFLAGS: %s\n", SAMTOOLS_LDFLAGS); + printf(" HTSDIR: %s\n", SAMTOOLS_HTSDIR); + printf(" LIBS: %s\n", SAMTOOLS_LIBS); + printf(" CURSES_LIB: %s\n", SAMTOOLS_CURSES_LIB); + + printf("\nHTSlib compilation details:\n"); + printf(" Features: %s\n", hts_feature_string()); + printf(" CC: %s\n", hts_test_feature(HTS_FEATURE_CC)); + printf(" CPPFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CPPFLAGS)); + printf(" CFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CFLAGS)); + printf(" LDFLAGS: %s\n", hts_test_feature(HTS_FEATURE_LDFLAGS)); + + // Plugins and schemes + printf("\nHTSlib URL scheme handlers present:\n"); + const char *plugins[100]; + int np = 100, i, j; + + if (hfile_list_plugins(plugins, &np) < 0) + return; + + for (i = 0; i < np; i++) { + const char *sc_list[100]; + int nschemes = 100; + if (hfile_list_schemes(plugins[i], sc_list, &nschemes) < 0) + return; + + printf(" %s:\t", plugins[i]); + for (j = 0; j < nschemes; j++) + printf(" %s%c", sc_list[j], ",\n"[j+1==nschemes]); + } +} + +static void usage(FILE *fp) +{ + /* Please improve the grouping */ + + fprintf(fp, +"\n" +"Program: samtools (Tools for alignments in the SAM format)\n" +"Version: %s (using htslib %s)\n\n", samtools_version(), hts_version()); + fprintf(fp, +"Usage: samtools [options]\n" +"\n" +"Commands:\n" +" -- Indexing\n" +" dict create a sequence dictionary file\n" +" faidx index/extract FASTA\n" +" fqidx index/extract FASTQ\n" +" index index alignment\n" +"\n" +" -- Editing\n" +" calmd recalculate MD/NM tags and '=' bases\n" +" fixmate fix mate information\n" +" reheader replace BAM header\n" +" targetcut cut fosmid regions (for fosmid pool only)\n" +" addreplacerg adds or replaces RG tags\n" +" markdup mark duplicates\n" +" ampliconclip clip oligos from the end of reads\n" +"\n" +" -- File operations\n" +" collate shuffle and group alignments by name\n" +" cat concatenate BAMs\n" +" consensus produce a consensus Pileup/FASTA/FASTQ\n" +" merge merge sorted alignments\n" +" mpileup multi-way pileup\n" +" sort sort alignment file\n" +" split splits a file by read group\n" +" quickcheck quickly check if SAM/BAM/CRAM file appears intact\n" +" fastq converts a BAM to a FASTQ\n" +" fasta converts a BAM to a FASTA\n" +" import Converts FASTA or FASTQ files to SAM/BAM/CRAM\n" +" reference Generates a reference from aligned data\n" +" reset Reverts aligner changes in reads\n" +"\n" +" -- Statistics\n" +" bedcov read depth per BED region\n" +" coverage alignment depth and percent coverage\n" +" depth compute the depth\n" +" flagstat simple stats\n" +" idxstats BAM index stats\n" +" cram-size list CRAM Content-ID and Data-Series sizes\n" +" phase phase heterozygotes\n" +" stats generate stats (former bamcheck)\n" +" ampliconstats generate amplicon specific stats\n" +"\n" +" -- Viewing\n" +" flags explain BAM flags\n" +" head header viewer\n" +" tview text alignment viewer\n" +" view SAM<->BAM<->CRAM conversion\n" +" depad convert padded BAM to unpadded BAM\n" +" samples list the samples in a set of SAM/BAM/CRAM files\n" +"\n" +" -- Misc\n" +" help [cmd] display this help message or help for [cmd]\n" +" version detailed version information\n" +"\n"); +} + +// This is a tricky one, but on Windows the filename wildcard expansion is done by +// the application and not by the shell, as traditionally it never had a "shell". +// Even now, DOS and Powershell do not do this expansion (but bash does). +// +// This means that Mingw/Msys implements code before main() that takes e.g. "*" and +// expands it up to a list of matching filenames. This in turn breaks things like +// specifying "*" as a region (all the unmapped reads). We take a hard line here - +// filename expansion is the task of the shell, not our application! +#ifdef _WIN32 +int _CRT_glob = 0; +#endif + +int main(int argc, char *argv[]) +{ +#ifdef _WIN32 + setmode(fileno(stdout), O_BINARY); + setmode(fileno(stdin), O_BINARY); +#endif + if (argc < 2) { usage(stderr); return 1; } + + if (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "--help") == 0) { + if (argc == 2) { usage(stdout); return 0; } + + // Otherwise change "samtools help COMMAND [...]" to "samtools COMMAND"; + // main_xyz() functions by convention display the subcommand's usage + // when invoked without any arguments. + argv++; + argc = 2; + } + + int ret = 0; + if (strcmp(argv[1], "view") == 0) ret = main_samview(argc-1, argv+1); + else if (strcmp(argv[1], "import") == 0) ret = main_import(argc-1, argv+1); + else if (strcmp(argv[1], "mpileup") == 0) ret = bam_mpileup(argc-1, argv+1); + else if (strcmp(argv[1], "merge") == 0) ret = bam_merge(argc-1, argv+1); + else if (strcmp(argv[1], "sort") == 0) ret = bam_sort(argc-1, argv+1); + else if (strcmp(argv[1], "index") == 0) ret = bam_index(argc-1, argv+1); + else if (strcmp(argv[1], "idxstat") == 0 || + strcmp(argv[1], "idxstats") == 0) ret = bam_idxstats(argc-1, argv+1); + else if (strcmp(argv[1], "faidx") == 0) ret = faidx_main(argc-1, argv+1); + else if (strcmp(argv[1], "fqidx") == 0) ret = fqidx_main(argc-1, argv+1); + else if (strcmp(argv[1], "dict") == 0) ret = dict_main(argc-1, argv+1); + else if (strcmp(argv[1], "head") == 0) ret = main_head(argc-1, argv+1); + else if (strcmp(argv[1], "fixmate") == 0) ret = bam_mating(argc-1, argv+1); + else if (strcmp(argv[1], "rmdup") == 0) ret = bam_rmdup(argc-1, argv+1); + else if (strcmp(argv[1], "markdup") == 0) ret = bam_markdup(argc-1, argv+1); + else if (strcmp(argv[1], "ampliconclip") == 0) ret = amplicon_clip_main(argc-1, argv+1); + else if (strcmp(argv[1], "flagstat") == 0 || + strcmp(argv[1], "flagstats") == 0) ret = bam_flagstat(argc-1, argv+1); + else if (strcmp(argv[1], "calmd") == 0) ret = bam_fillmd(argc-1, argv+1); + else if (strcmp(argv[1], "fillmd") == 0) ret = bam_fillmd(argc-1, argv+1); + else if (strcmp(argv[1], "reheader") == 0) ret = main_reheader(argc-1, argv+1); + else if (strcmp(argv[1], "cat") == 0) ret = main_cat(argc-1, argv+1); + else if (strcmp(argv[1], "targetcut") == 0) ret = main_cut_target(argc-1, argv+1); + else if (strcmp(argv[1], "phase") == 0) ret = main_phase(argc-1, argv+1); + else if (strcmp(argv[1], "depth") == 0) ret = main_depth(argc-1, argv+1); + else if (strcmp(argv[1], "coverage") == 0) ret = main_coverage(argc-1, argv+1); + else if (strcmp(argv[1], "bam2fq") == 0 || + strcmp(argv[1], "fastq") == 0 || + strcmp(argv[1], "fasta") == 0) ret = main_bam2fq(argc-1, argv+1); + else if (strcmp(argv[1], "pad2unpad") == 0) ret = main_pad2unpad(argc-1, argv+1); + else if (strcmp(argv[1], "depad") == 0) ret = main_pad2unpad(argc-1, argv+1); + else if (strcmp(argv[1], "bedcov") == 0) ret = main_bedcov(argc-1, argv+1); + else if (strcmp(argv[1], "bamshuf") == 0) ret = main_bamshuf(argc-1, argv+1); + else if (strcmp(argv[1], "collate") == 0) ret = main_bamshuf(argc-1, argv+1); + else if (strcmp(argv[1], "stat") == 0 || + strcmp(argv[1], "stats") == 0) ret = main_stats(argc-1, argv+1); + else if (strcmp(argv[1], "flag") == 0 || + strcmp(argv[1], "flags") == 0) ret = main_flags(argc-1, argv+1); + else if (strcmp(argv[1], "split") == 0) ret = main_split(argc-1, argv+1); + else if (strcmp(argv[1], "quickcheck") == 0) ret = main_quickcheck(argc-1, argv+1); + else if (strcmp(argv[1], "addreplacerg") == 0) ret = main_addreplacerg(argc-1, argv+1); + else if (strcmp(argv[1], "pileup") == 0) { + fprintf(stderr, "[main] The `pileup' command has been removed. Please use `mpileup' instead.\n"); + return 1; + } + else if (strcmp(argv[1], "tview") == 0) ret = bam_tview_main(argc-1, argv+1); + else if (strcmp(argv[1], "ampliconstats") == 0) ret = main_ampliconstats(argc-1, argv+1); + else if (strcmp(argv[1], "samples") == 0) ret = main_samples(argc-1, argv+1); + else if (strcmp(argv[1], "consensus") == 0) ret = main_consensus(argc-1, argv+1); + else if (strcmp(argv[1], "reference") == 0) ret = main_reference(argc-1, argv+1); + else if (strcmp(argv[1], "cram-size") == 0) ret = main_cram_size(argc-1, argv+1); + else if (strcmp(argv[1], "version") == 0 || \ + strcmp(argv[1], "--version") == 0) + long_version(); + else if (strcmp(argv[1], "--version-only") == 0) { + printf("%s+htslib-%s\n", samtools_version(), hts_version()); + } + else if (strcmp(argv[1], "reset") == 0) ret = main_reset(argc-1, argv+1); + else { + fprintf(stderr, "[main] unrecognized command '%s'\n", argv[1]); + return 1; + } + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c new file mode 100644 index 0000000000000000000000000000000000000000..6b22d4efce1f9a8aa5c499a8fc94a136aff1a4f6 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c @@ -0,0 +1,637 @@ +/* bedidx.c -- BED file indexing. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2014, 2017-2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include "bedidx.h" + +#include "htslib/ksort.h" + +#include "htslib/kseq.h" +KSTREAM_INIT(gzFile, gzread, 8192) + +static inline int lt_pair_pos(hts_pair_pos_t a, hts_pair_pos_t b) { + if (a.beg == b.beg) return a.end < b.end; + return a.beg < b.beg; +} +KSORT_INIT_STATIC(hts_pair_pos_t, hts_pair_pos_t, lt_pair_pos) + +/*! @typedef + * @abstract bed_reglist_t - value type of the BED hash table + * This structure encodes the list of intervals (ranges) for the regions provided via BED file or + * command line arguments. + * @field *a pointer to the array of intervals. + * @field n actual number of elements contained by a + * @field m number of allocated elements to a (n <= m) + * @field *idx index array for computing the minimum offset + */ +typedef struct { + int n, m; + hts_pair_pos_t *a; + int *idx; + int filter; +} bed_reglist_t; + +#include "htslib/khash.h" +KHASH_MAP_INIT_STR(reg, bed_reglist_t) + +typedef kh_reg_t reghash_t; + +#if 0 +// Debug function +static void bed_print(void *reg_hash) { + reghash_t *h = (reghash_t *)reg_hash; + bed_reglist_t *p; + khint_t k; + int i; + const char *reg; + + if (!h) { + printf("Hash table is empty!\n"); + return; + } + for (k = kh_begin(h); k < kh_end(h); k++) { + if (kh_exist(h,k)) { + reg = kh_key(h,k); + printf("Region: '%s'\n", reg); + if ((p = &kh_val(h,k)) != NULL && p->n > 0) { + printf("Filter: %d\n", p->filter); + for (i=0; in; i++) { + printf("\tinterval[%d]: %"PRIhts_pos"-%"PRIhts_pos"\n", + i,p->a[i].beg,p->a[i].end); + } + } else { + printf("Region '%s' has no intervals!\n", reg); + } + } + } +} +#endif + +static int *bed_index_core(int n, hts_pair_pos_t *a) +{ + int i, j, l, *idx, *new_idx; + l = 0; idx = 0; + for (i = 0; i < n; ++i) { + hts_pos_t beg, end; + beg = a[i].beg >> LIDX_SHIFT; end = a[i].end >> LIDX_SHIFT; + if (l < end + 1) { + int old_l = l; + l = end + 1; + kroundup32(l); + new_idx = realloc(idx, l * sizeof(*idx)); + if (!new_idx) { + free(idx); + return NULL; + } + idx = new_idx; + + for (j = old_l; j < l; ++j) + idx[j] = -1; + } + + for (j = beg; j < end+1; ++j) + if (idx[j] < 0) + idx[j] = i; + } + return idx; +} + +static void bed_index(void *_h) +{ + reghash_t *h = (reghash_t*)_h; + khint_t k; + for (k = 0; k < kh_end(h); ++k) { + if (kh_exist(h, k)) { + bed_reglist_t *p = &kh_val(h, k); + if (p->idx) free(p->idx); + ks_introsort(hts_pair_pos_t, p->n, p->a); + p->idx = bed_index_core(p->n, p->a); + } + } +} + +static int bed_minoff(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) { + int i, min_off=0; + + if (p && p->idx) { + min_off = (beg>>LIDX_SHIFT >= p->n)? p->idx[p->n-1] : p->idx[beg>>LIDX_SHIFT]; + if (min_off < 0) { // TODO: this block can be improved, but speed should not matter too much here + hts_pos_t n = beg>>LIDX_SHIFT; + if (n > p->n) + n = p->n; + for (i = n - 1; i >= 0; --i) + if (p->idx[i] >= 0) + break; + min_off = i >= 0? p->idx[i] : 0; + } + } + + return min_off; +} + +static int bed_overlap_core(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) +{ + int i, min_off; + if (p->n == 0) return 0; + min_off = bed_minoff(p, beg, end); + + for (i = min_off; i < p->n; ++i) { + if (p->a[i].beg >= end) break; // out of range; no need to proceed + if (p->a[i].end > beg && p->a[i].beg < end) + return 1; // find the overlap; return + } + return 0; +} + +int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end) +{ + const reghash_t *h = (const reghash_t*)_h; + khint_t k; + if (!h) return 0; + k = kh_get(reg, h, chr); + if (k == kh_end(h)) return 0; + return bed_overlap_core(&kh_val(h, k), beg, end); +} + +/** @brief Trim a sorted interval list, inside a region hash table, + * by removing completely contained intervals and merging adjacent or + * overlapping intervals. + * @param reg_hash the region hash table with interval lists as values + */ + +void bed_unify(void *reg_hash) { + + int i, j, new_n; + reghash_t *h; + bed_reglist_t *p; + + if (!reg_hash) + return; + + h = (reghash_t *)reg_hash; + + for (i = kh_begin(h); i < kh_end(h); i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || !(p->n)) + continue; + + for (new_n = 0, j = 1; j < p->n; j++) { + if (p->a[new_n].end < p->a[j].beg) { + p->a[++new_n] = p->a[j]; + } else { + if (p->a[new_n].end < p->a[j].end) + p->a[new_n].end = p->a[j].end; + } + } + + p->n = ++new_n; + } +} + +/* "BED" file reader, which actually reads two different formats. + + BED files contain between three and nine fields per line, of which + only the first three (reference, start, end) are of interest to us. + BED counts positions from base 0, and the end is the base after the + region of interest. While not properly documented in the specification, + it is also possible to have 'browser' and 'track' lines in BED files that + do not follow the standard format and should be ignored. Examination + of the BED file reading code in + http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git shows that BED + files can also have comment lines starting with '#', leading whitespace + is stripped, and that fields are separated by one or more consecutive + whitespace characters. + + The alternative format was originally for reading positions in VCF + format. This expects two columns, which indicate the reference and + a position. The position corresponds to a single base, and unlike + BED counts from 1. + + Which format is in use is determined based on whether one or two + numbers can be decoded on the line. As this choice is made line-by-line + in this implementation, it is possible (but probably a bad idea) to mix + both formats in the same file. If trying to read a VCF file by this + method, it would be important to ensure that the third column (ID) does + not contain any entries that start with a digit, to avoid the line + erroneously being parsed as a BED file entry. + + The BED specification is at http://www.genome.ucsc.edu/FAQ/FAQformat.html + The VCF specification is at https://github.com/samtools/hts-specs + */ + +void *bed_read(const char *fn) +{ + reghash_t *h = kh_init(reg); + gzFile fp; + kstream_t *ks = NULL; + int dret; + unsigned int line = 0, save_errno; + kstring_t str = { 0, 0, NULL }; + + if (NULL == h) return NULL; + // read the list + fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); + if (fp == 0) return 0; + ks = ks_init(fp); + if (NULL == ks) goto fail; // In case ks_init ever gets error checking... + int ks_len; + while ((ks_len = ks_getuntil(ks, KS_SEP_LINE, &str, &dret)) >= 0) { // read a line + char *ref = str.s, *ref_end; + uint64_t beg = 0, end = 0; + int num = 0; + khint_t k; + bed_reglist_t *p; + + if (ks_len == 0) + continue; // skip blank lines + + line++; + while (*ref && isspace(*ref)) ref++; + if ('\0' == *ref) continue; // Skip blank lines + if ('#' == *ref) continue; // Skip BED file comments + ref_end = ref; // look for the end of the reference name + while (*ref_end && !isspace(*ref_end)) ref_end++; + if ('\0' != *ref_end) { + *ref_end = '\0'; // terminate ref and look for start, end + num = sscanf(ref_end + 1, "%"SCNu64" %"SCNu64, &beg, &end); + } + if (1 == num) { // VCF-style format + end = beg--; // Counts from 1 instead of 0 for BED files + } + if (num < 1 || end < beg) { + // These two are special lines that can occur in BED files. + // Check for them here instead of earlier in case someone really + // has called their reference "browser" or "track". + if (0 == strcmp(ref, "browser")) continue; + if (0 == strcmp(ref, "track")) continue; + if (num < 1) { + fprintf(stderr, + "[bed_read] Parse error reading \"%s\" at line %u\n", + fn, line); + } else { + fprintf(stderr, + "[bed_read] Parse error reading \"%s\" at line %u : " + "end (%"PRIu64") must not be less " + "than start (%"PRIu64")\n", + fn, line, end, beg); + } + errno = 0; // Prevent caller from printing misleading error messages + goto fail; + } + + // Put reg in the hash table if not already there + k = kh_get(reg, h, ref); + if (k == kh_end(h)) { // absent from the hash table + int ret; + char *s = strdup(ref); + if (NULL == s) goto fail; + k = kh_put(reg, h, s, &ret); + if (-1 == ret) { + free(s); + goto fail; + } + memset(&kh_val(h, k), 0, sizeof(bed_reglist_t)); + } + p = &kh_val(h, k); + + // Add begin,end to the list + if (p->n == p->m) { + p->m = p->m ? p->m<<1 : 4; + hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0])); + if (NULL == new_a) goto fail; + p->a = new_a; + } + p->a[p->n].beg = beg; + p->a[p->n++].end = end; + } + // FIXME: Need to check for errors in ks_getuntil. At the moment it + // doesn't look like it can return one. Possibly use gzgets instead? + + if (gzclose(fp) != Z_OK) { + fp = NULL; + goto fail; + } + ks_destroy(ks); + free(str.s); + bed_index(h); + //bed_unify(h); + return h; + fail: + save_errno = errno; + if (ks) ks_destroy(ks); + if (fp) gzclose(fp); + free(str.s); + bed_destroy(h); + errno = save_errno; + return NULL; +} + +void bed_destroy(void *_h) +{ + reghash_t *h; + khint_t k; + + if (!_h) + return; + + h = (reghash_t*)_h; + for (k = 0; k < kh_end(h); ++k) { + if (kh_exist(h, k)) { + free(kh_val(h, k).a); + free(kh_val(h, k).idx); + free((char*)kh_key(h, k)); + } + } + kh_destroy(reg, h); +} + +static void *bed_insert(void *reg_hash, char *reg, hts_pos_t beg, hts_pos_t end) { + + reghash_t *h; + khint_t k; + bed_reglist_t *p; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + + // Put reg in the hash table if not already there + k = kh_get(reg, h, reg); //looks strange, but only the second reg is the actual region name. + if (k == kh_end(h)) { // absent from the hash table + int ret; + char *s = strdup(reg); + if (NULL == s) goto fail; + k = kh_put(reg, h, s, &ret); + if (-1 == ret) { + free(s); + goto fail; + } + memset(&kh_val(h, k), 0, sizeof(bed_reglist_t)); + } + p = &kh_val(h, k); + + // Add beg and end to the list + if (p->n == p->m) { + p->m = p->m ? p->m<<1 : 4; + hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0])); + if (NULL == new_a) goto fail; + p->a = new_a; + } + p->a[p->n].beg = beg; + p->a[p->n++].end = end; + +fail: + return h; +} + +/* @brief Filter a region hash table (coming from the BED file) by another + * region hash table (coming from CLI), so that only intervals contained in + * both hash tables are kept. + * @param reg_hash the target region hash table + * @param tmp_hash the filter region hash table + * @return pointer to the filtered hash table + */ + +static void *bed_filter(void *reg_hash, void *tmp_hash) { + + reghash_t *h; + reghash_t *t; + bed_reglist_t *p, *q; + khint_t l, k; + hts_pair_pos_t *new_a; + int i, j, new_n, min_off; + const char *reg; + hts_pos_t beg, end; + + h = (reghash_t *)reg_hash; + t = (reghash_t *)tmp_hash; + if (!h) + return NULL; + if (!t) + return h; + + for (l = kh_begin(t); l < kh_end(t); l++) { + if (!kh_exist(t,l) || !(q = &kh_val(t,l)) || !(q->n)) + continue; + + reg = kh_key(t,l); + k = kh_get(reg, h, reg); //looks strange, but only the second reg is a proper argument. + if (k == kh_end(h) || !(p = &kh_val(h, k)) || !(p->n)) + continue; + + new_a = calloc(q->n + p->n, sizeof(new_a[0])); + if (!new_a) + return NULL; + new_n = 0; + + for (i = 0; i < q->n; i++) { + beg = q->a[i].beg; + end = q->a[i].end; + + min_off = bed_minoff(p, beg, end); + for (j = min_off; j < p->n; ++j) { + if (p->a[j].beg >= end) break; // out of range; no need to proceed + if (p->a[j].end > beg && p->a[j].beg < end) { + new_a[new_n].beg = MAX(p->a[j].beg, beg); + new_a[new_n++].end = MIN(p->a[j].end, end); + } + } + } + + if (new_n > 0) { + free(p->a); + p->a = new_a; + p->n = new_n; + p->m = new_n; + p->filter = FILTERED; + } else { + free(new_a); + p->filter = ALL; + } + } + + return h; +} + +void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op) { + + reghash_t *h = (reghash_t *)reg_hash; + reghash_t *t = NULL; + + int i; + char reg[1024]; + const char *q; + int beg, end; + + if (h) { + t = kh_init(reg); + if (!t) { + fprintf(stderr, "Error when creating the temporary region hash table!\n"); + return NULL; + } + } else { + h = kh_init(reg); + if (!h) { + fprintf(stderr, "Error when creating the region hash table!\n"); + return NULL; + } + *op = 1; + } + + for (i=first; i 1024) { + fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024); + continue; + } + strncpy(reg, regs[i], q - regs[i]); + reg[q - regs[i]] = 0; + } else { + // not parsable as a region, but possibly a sequence named "foo:a" + if (strlen(regs[i]) + 1 > 1024) { + fprintf(stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024); + continue; + } + strcpy(reg, regs[i]); + beg = 0; end = INT_MAX; + } + + //if op==1 insert reg to the bed hash table + if (*op && !(bed_insert(h, reg, beg, end))) { + fprintf(stderr, "Error when inserting region='%s' in the bed hash table at address=%p!\n", regs[i], h); + } + //if op==0, first insert the regions in the temporary hash table, + //then filter the bed hash table using it + if (!(*op) && !(bed_insert(t, reg, beg, end))) { + fprintf(stderr, "Error when inserting region='%s' in the temporary hash table at address=%p!\n", regs[i], t); + } + } + + if (!(*op)) { + bed_index(t); + bed_unify(t); + h = bed_filter(h, t); + bed_destroy(t); + } + + if (h) { + bed_index(h); + bed_unify(h); + } + + return h; +} + +const char* bed_get(void *reg_hash, int i, int filter) { + + reghash_t *h; + bed_reglist_t *p; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + return NULL; + + return kh_key(h, i); +} + +/** + * Create a region list from a the region hash table + * @param reg_hash The region hash table + * @param filter 0 - allow all regions, 1 - allow only selected regions + * @param n_reg Pointer to the returned region number + * @return The regions list as a hts_reglist_t + */ + +hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *n_reg) { + + reghash_t *h; + bed_reglist_t *p; + khint_t i; + hts_reglist_t *reglist = NULL; + int count = 0; + int j; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + + for (i = kh_begin(h); i < kh_end(h); i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + continue; + count++; + } + if (!count) + return NULL; + + reglist = (hts_reglist_t *)calloc(count, sizeof(hts_reglist_t)); + if (!reglist) + return NULL; + + *n_reg = count; + count = 0; + + for (i = kh_begin(h); i < kh_end(h) && count < *n_reg; i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + continue; + + reglist[count].reg = kh_key(h,i); + reglist[count].intervals = (hts_pair32_t *)calloc(p->n, sizeof(hts_pair32_t)); + if(!(reglist[count].intervals)) { + hts_reglist_free(reglist, count); + return NULL; + } + reglist[count].count = p->n; + reglist[count].max_end = 0; + + for (j = 0; j < p->n; j++) { + reglist[count].intervals[j].beg = p->a[j].beg; + reglist[count].intervals[j].end = p->a[j].end; + + if (reglist[count].intervals[j].end > reglist[count].max_end) + reglist[count].max_end = reglist[count].intervals[j].end; + } + count++; + } + + return reglist; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..533b42a92c202b0d367a169cbeff9c8f6734fcf3 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.c.pysam.c @@ -0,0 +1,639 @@ +#include "samtools.pysam.h" + +/* bedidx.c -- BED file indexing. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2014, 2017-2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include "bedidx.h" + +#include "htslib/ksort.h" + +#include "htslib/kseq.h" +KSTREAM_INIT(gzFile, gzread, 8192) + +static inline int lt_pair_pos(hts_pair_pos_t a, hts_pair_pos_t b) { + if (a.beg == b.beg) return a.end < b.end; + return a.beg < b.beg; +} +KSORT_INIT_STATIC(hts_pair_pos_t, hts_pair_pos_t, lt_pair_pos) + +/*! @typedef + * @abstract bed_reglist_t - value type of the BED hash table + * This structure encodes the list of intervals (ranges) for the regions provided via BED file or + * command line arguments. + * @field *a pointer to the array of intervals. + * @field n actual number of elements contained by a + * @field m number of allocated elements to a (n <= m) + * @field *idx index array for computing the minimum offset + */ +typedef struct { + int n, m; + hts_pair_pos_t *a; + int *idx; + int filter; +} bed_reglist_t; + +#include "htslib/khash.h" +KHASH_MAP_INIT_STR(reg, bed_reglist_t) + +typedef kh_reg_t reghash_t; + +#if 0 +// Debug function +static void bed_print(void *reg_hash) { + reghash_t *h = (reghash_t *)reg_hash; + bed_reglist_t *p; + khint_t k; + int i; + const char *reg; + + if (!h) { + fprintf(samtools_stdout, "Hash table is empty!\n"); + return; + } + for (k = kh_begin(h); k < kh_end(h); k++) { + if (kh_exist(h,k)) { + reg = kh_key(h,k); + fprintf(samtools_stdout, "Region: '%s'\n", reg); + if ((p = &kh_val(h,k)) != NULL && p->n > 0) { + fprintf(samtools_stdout, "Filter: %d\n", p->filter); + for (i=0; in; i++) { + fprintf(samtools_stdout, "\tinterval[%d]: %"PRIhts_pos"-%"PRIhts_pos"\n", + i,p->a[i].beg,p->a[i].end); + } + } else { + fprintf(samtools_stdout, "Region '%s' has no intervals!\n", reg); + } + } + } +} +#endif + +static int *bed_index_core(int n, hts_pair_pos_t *a) +{ + int i, j, l, *idx, *new_idx; + l = 0; idx = 0; + for (i = 0; i < n; ++i) { + hts_pos_t beg, end; + beg = a[i].beg >> LIDX_SHIFT; end = a[i].end >> LIDX_SHIFT; + if (l < end + 1) { + int old_l = l; + l = end + 1; + kroundup32(l); + new_idx = realloc(idx, l * sizeof(*idx)); + if (!new_idx) { + free(idx); + return NULL; + } + idx = new_idx; + + for (j = old_l; j < l; ++j) + idx[j] = -1; + } + + for (j = beg; j < end+1; ++j) + if (idx[j] < 0) + idx[j] = i; + } + return idx; +} + +static void bed_index(void *_h) +{ + reghash_t *h = (reghash_t*)_h; + khint_t k; + for (k = 0; k < kh_end(h); ++k) { + if (kh_exist(h, k)) { + bed_reglist_t *p = &kh_val(h, k); + if (p->idx) free(p->idx); + ks_introsort(hts_pair_pos_t, p->n, p->a); + p->idx = bed_index_core(p->n, p->a); + } + } +} + +static int bed_minoff(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) { + int i, min_off=0; + + if (p && p->idx) { + min_off = (beg>>LIDX_SHIFT >= p->n)? p->idx[p->n-1] : p->idx[beg>>LIDX_SHIFT]; + if (min_off < 0) { // TODO: this block can be improved, but speed should not matter too much here + hts_pos_t n = beg>>LIDX_SHIFT; + if (n > p->n) + n = p->n; + for (i = n - 1; i >= 0; --i) + if (p->idx[i] >= 0) + break; + min_off = i >= 0? p->idx[i] : 0; + } + } + + return min_off; +} + +static int bed_overlap_core(const bed_reglist_t *p, hts_pos_t beg, hts_pos_t end) +{ + int i, min_off; + if (p->n == 0) return 0; + min_off = bed_minoff(p, beg, end); + + for (i = min_off; i < p->n; ++i) { + if (p->a[i].beg >= end) break; // out of range; no need to proceed + if (p->a[i].end > beg && p->a[i].beg < end) + return 1; // find the overlap; return + } + return 0; +} + +int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end) +{ + const reghash_t *h = (const reghash_t*)_h; + khint_t k; + if (!h) return 0; + k = kh_get(reg, h, chr); + if (k == kh_end(h)) return 0; + return bed_overlap_core(&kh_val(h, k), beg, end); +} + +/** @brief Trim a sorted interval list, inside a region hash table, + * by removing completely contained intervals and merging adjacent or + * overlapping intervals. + * @param reg_hash the region hash table with interval lists as values + */ + +void bed_unify(void *reg_hash) { + + int i, j, new_n; + reghash_t *h; + bed_reglist_t *p; + + if (!reg_hash) + return; + + h = (reghash_t *)reg_hash; + + for (i = kh_begin(h); i < kh_end(h); i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || !(p->n)) + continue; + + for (new_n = 0, j = 1; j < p->n; j++) { + if (p->a[new_n].end < p->a[j].beg) { + p->a[++new_n] = p->a[j]; + } else { + if (p->a[new_n].end < p->a[j].end) + p->a[new_n].end = p->a[j].end; + } + } + + p->n = ++new_n; + } +} + +/* "BED" file reader, which actually reads two different formats. + + BED files contain between three and nine fields per line, of which + only the first three (reference, start, end) are of interest to us. + BED counts positions from base 0, and the end is the base after the + region of interest. While not properly documented in the specification, + it is also possible to have 'browser' and 'track' lines in BED files that + do not follow the standard format and should be ignored. Examination + of the BED file reading code in + http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git shows that BED + files can also have comment lines starting with '#', leading whitespace + is stripped, and that fields are separated by one or more consecutive + whitespace characters. + + The alternative format was originally for reading positions in VCF + format. This expects two columns, which indicate the reference and + a position. The position corresponds to a single base, and unlike + BED counts from 1. + + Which format is in use is determined based on whether one or two + numbers can be decoded on the line. As this choice is made line-by-line + in this implementation, it is possible (but probably a bad idea) to mix + both formats in the same file. If trying to read a VCF file by this + method, it would be important to ensure that the third column (ID) does + not contain any entries that start with a digit, to avoid the line + erroneously being parsed as a BED file entry. + + The BED specification is at http://www.genome.ucsc.edu/FAQ/FAQformat.html + The VCF specification is at https://github.com/samtools/hts-specs + */ + +void *bed_read(const char *fn) +{ + reghash_t *h = kh_init(reg); + gzFile fp; + kstream_t *ks = NULL; + int dret; + unsigned int line = 0, save_errno; + kstring_t str = { 0, 0, NULL }; + + if (NULL == h) return NULL; + // read the list + fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); + if (fp == 0) return 0; + ks = ks_init(fp); + if (NULL == ks) goto fail; // In case ks_init ever gets error checking... + int ks_len; + while ((ks_len = ks_getuntil(ks, KS_SEP_LINE, &str, &dret)) >= 0) { // read a line + char *ref = str.s, *ref_end; + uint64_t beg = 0, end = 0; + int num = 0; + khint_t k; + bed_reglist_t *p; + + if (ks_len == 0) + continue; // skip blank lines + + line++; + while (*ref && isspace(*ref)) ref++; + if ('\0' == *ref) continue; // Skip blank lines + if ('#' == *ref) continue; // Skip BED file comments + ref_end = ref; // look for the end of the reference name + while (*ref_end && !isspace(*ref_end)) ref_end++; + if ('\0' != *ref_end) { + *ref_end = '\0'; // terminate ref and look for start, end + num = sscanf(ref_end + 1, "%"SCNu64" %"SCNu64, &beg, &end); + } + if (1 == num) { // VCF-style format + end = beg--; // Counts from 1 instead of 0 for BED files + } + if (num < 1 || end < beg) { + // These two are special lines that can occur in BED files. + // Check for them here instead of earlier in case someone really + // has called their reference "browser" or "track". + if (0 == strcmp(ref, "browser")) continue; + if (0 == strcmp(ref, "track")) continue; + if (num < 1) { + fprintf(samtools_stderr, + "[bed_read] Parse error reading \"%s\" at line %u\n", + fn, line); + } else { + fprintf(samtools_stderr, + "[bed_read] Parse error reading \"%s\" at line %u : " + "end (%"PRIu64") must not be less " + "than start (%"PRIu64")\n", + fn, line, end, beg); + } + errno = 0; // Prevent caller from printing misleading error messages + goto fail; + } + + // Put reg in the hash table if not already there + k = kh_get(reg, h, ref); + if (k == kh_end(h)) { // absent from the hash table + int ret; + char *s = strdup(ref); + if (NULL == s) goto fail; + k = kh_put(reg, h, s, &ret); + if (-1 == ret) { + free(s); + goto fail; + } + memset(&kh_val(h, k), 0, sizeof(bed_reglist_t)); + } + p = &kh_val(h, k); + + // Add begin,end to the list + if (p->n == p->m) { + p->m = p->m ? p->m<<1 : 4; + hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0])); + if (NULL == new_a) goto fail; + p->a = new_a; + } + p->a[p->n].beg = beg; + p->a[p->n++].end = end; + } + // FIXME: Need to check for errors in ks_getuntil. At the moment it + // doesn't look like it can return one. Possibly use gzgets instead? + + if (gzclose(fp) != Z_OK) { + fp = NULL; + goto fail; + } + ks_destroy(ks); + free(str.s); + bed_index(h); + //bed_unify(h); + return h; + fail: + save_errno = errno; + if (ks) ks_destroy(ks); + if (fp) gzclose(fp); + free(str.s); + bed_destroy(h); + errno = save_errno; + return NULL; +} + +void bed_destroy(void *_h) +{ + reghash_t *h; + khint_t k; + + if (!_h) + return; + + h = (reghash_t*)_h; + for (k = 0; k < kh_end(h); ++k) { + if (kh_exist(h, k)) { + free(kh_val(h, k).a); + free(kh_val(h, k).idx); + free((char*)kh_key(h, k)); + } + } + kh_destroy(reg, h); +} + +static void *bed_insert(void *reg_hash, char *reg, hts_pos_t beg, hts_pos_t end) { + + reghash_t *h; + khint_t k; + bed_reglist_t *p; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + + // Put reg in the hash table if not already there + k = kh_get(reg, h, reg); //looks strange, but only the second reg is the actual region name. + if (k == kh_end(h)) { // absent from the hash table + int ret; + char *s = strdup(reg); + if (NULL == s) goto fail; + k = kh_put(reg, h, s, &ret); + if (-1 == ret) { + free(s); + goto fail; + } + memset(&kh_val(h, k), 0, sizeof(bed_reglist_t)); + } + p = &kh_val(h, k); + + // Add beg and end to the list + if (p->n == p->m) { + p->m = p->m ? p->m<<1 : 4; + hts_pair_pos_t *new_a = realloc(p->a, p->m * sizeof(p->a[0])); + if (NULL == new_a) goto fail; + p->a = new_a; + } + p->a[p->n].beg = beg; + p->a[p->n++].end = end; + +fail: + return h; +} + +/* @brief Filter a region hash table (coming from the BED file) by another + * region hash table (coming from CLI), so that only intervals contained in + * both hash tables are kept. + * @param reg_hash the target region hash table + * @param tmp_hash the filter region hash table + * @return pointer to the filtered hash table + */ + +static void *bed_filter(void *reg_hash, void *tmp_hash) { + + reghash_t *h; + reghash_t *t; + bed_reglist_t *p, *q; + khint_t l, k; + hts_pair_pos_t *new_a; + int i, j, new_n, min_off; + const char *reg; + hts_pos_t beg, end; + + h = (reghash_t *)reg_hash; + t = (reghash_t *)tmp_hash; + if (!h) + return NULL; + if (!t) + return h; + + for (l = kh_begin(t); l < kh_end(t); l++) { + if (!kh_exist(t,l) || !(q = &kh_val(t,l)) || !(q->n)) + continue; + + reg = kh_key(t,l); + k = kh_get(reg, h, reg); //looks strange, but only the second reg is a proper argument. + if (k == kh_end(h) || !(p = &kh_val(h, k)) || !(p->n)) + continue; + + new_a = calloc(q->n + p->n, sizeof(new_a[0])); + if (!new_a) + return NULL; + new_n = 0; + + for (i = 0; i < q->n; i++) { + beg = q->a[i].beg; + end = q->a[i].end; + + min_off = bed_minoff(p, beg, end); + for (j = min_off; j < p->n; ++j) { + if (p->a[j].beg >= end) break; // out of range; no need to proceed + if (p->a[j].end > beg && p->a[j].beg < end) { + new_a[new_n].beg = MAX(p->a[j].beg, beg); + new_a[new_n++].end = MIN(p->a[j].end, end); + } + } + } + + if (new_n > 0) { + free(p->a); + p->a = new_a; + p->n = new_n; + p->m = new_n; + p->filter = FILTERED; + } else { + free(new_a); + p->filter = ALL; + } + } + + return h; +} + +void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op) { + + reghash_t *h = (reghash_t *)reg_hash; + reghash_t *t = NULL; + + int i; + char reg[1024]; + const char *q; + int beg, end; + + if (h) { + t = kh_init(reg); + if (!t) { + fprintf(samtools_stderr, "Error when creating the temporary region hash table!\n"); + return NULL; + } + } else { + h = kh_init(reg); + if (!h) { + fprintf(samtools_stderr, "Error when creating the region hash table!\n"); + return NULL; + } + *op = 1; + } + + for (i=first; i 1024) { + fprintf(samtools_stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024); + continue; + } + strncpy(reg, regs[i], q - regs[i]); + reg[q - regs[i]] = 0; + } else { + // not parsable as a region, but possibly a sequence named "foo:a" + if (strlen(regs[i]) + 1 > 1024) { + fprintf(samtools_stderr, "Region name '%s' is too long (bigger than %d).\n", regs[i], 1024); + continue; + } + strcpy(reg, regs[i]); + beg = 0; end = INT_MAX; + } + + //if op==1 insert reg to the bed hash table + if (*op && !(bed_insert(h, reg, beg, end))) { + fprintf(samtools_stderr, "Error when inserting region='%s' in the bed hash table at address=%p!\n", regs[i], h); + } + //if op==0, first insert the regions in the temporary hash table, + //then filter the bed hash table using it + if (!(*op) && !(bed_insert(t, reg, beg, end))) { + fprintf(samtools_stderr, "Error when inserting region='%s' in the temporary hash table at address=%p!\n", regs[i], t); + } + } + + if (!(*op)) { + bed_index(t); + bed_unify(t); + h = bed_filter(h, t); + bed_destroy(t); + } + + if (h) { + bed_index(h); + bed_unify(h); + } + + return h; +} + +const char* bed_get(void *reg_hash, int i, int filter) { + + reghash_t *h; + bed_reglist_t *p; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + return NULL; + + return kh_key(h, i); +} + +/** + * Create a region list from a the region hash table + * @param reg_hash The region hash table + * @param filter 0 - allow all regions, 1 - allow only selected regions + * @param n_reg Pointer to the returned region number + * @return The regions list as a hts_reglist_t + */ + +hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *n_reg) { + + reghash_t *h; + bed_reglist_t *p; + khint_t i; + hts_reglist_t *reglist = NULL; + int count = 0; + int j; + + if (!reg_hash) + return NULL; + + h = (reghash_t *)reg_hash; + + for (i = kh_begin(h); i < kh_end(h); i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + continue; + count++; + } + if (!count) + return NULL; + + reglist = (hts_reglist_t *)calloc(count, sizeof(hts_reglist_t)); + if (!reglist) + return NULL; + + *n_reg = count; + count = 0; + + for (i = kh_begin(h); i < kh_end(h) && count < *n_reg; i++) { + if (!kh_exist(h,i) || !(p = &kh_val(h,i)) || (p->filter < filter)) + continue; + + reglist[count].reg = kh_key(h,i); + reglist[count].intervals = (hts_pair32_t *)calloc(p->n, sizeof(hts_pair32_t)); + if(!(reglist[count].intervals)) { + hts_reglist_free(reglist, count); + return NULL; + } + reglist[count].count = p->n; + reglist[count].max_end = 0; + + for (j = 0; j < p->n; j++) { + reglist[count].intervals[j].beg = p->a[j].beg; + reglist[count].intervals[j].end = p->a[j].end; + + if (reglist[count].intervals[j].end > reglist[count].max_end) + reglist[count].max_end = reglist[count].intervals[j].end; + } + count++; + } + + return reglist; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.h new file mode 100644 index 0000000000000000000000000000000000000000..05ab48f0387bbdc793a2ac2022a98613c33cb432 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/bedidx.h @@ -0,0 +1,45 @@ +/* bedidx.h -- BED file indexing header file. + + Copyright (C) 2017 Genome Research Ltd. + + Author: Valeriu Ohan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef BEDIDX_H +#define BEDIDX_H + +#include "htslib/hts.h" + +#define LIDX_SHIFT 13 +#define ALL 0 +#define FILTERED 1 + +#define MIN(A,B) ( ( (A) < (B) ) ? (A) : (B) ) +#define MAX(A,B) ( ( (A) > (B) ) ? (A) : (B) ) + +void *bed_read(const char *fn); +void bed_destroy(void *_h); +int bed_overlap(const void *_h, const char *chr, hts_pos_t beg, hts_pos_t end); +void *bed_hash_regions(void *reg_hash, char **regs, int first, int last, int *op); +const char* bed_get(void *reg_hash, int index, int filter); +hts_reglist_t *bed_reglist(void *reg_hash, int filter, int *count_regs); +void bed_unify(void *_h); + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/consensus_pileup.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/consensus_pileup.h new file mode 100644 index 0000000000000000000000000000000000000000..cc400aa2e9cd867681a0d26fd8529ac55de9840a --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/consensus_pileup.h @@ -0,0 +1,102 @@ +/* consensus_pileup.h -- Pileup orientated data per consensus column + + Copyright (C) 2013-2016, 2020-2022 Genome Research Ltd. + + Author: James Bonfied + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +typedef struct pileup { + // commonly used things together, to fit in a cache line (64 bytes) + struct pileup *next; // A link list, for active seqs + void *cd; // General purpose per-seq client-data + int eof; // True if this sequence has finished + int qual; // Current qual (for active seq only) + char start; // True if this is a new sequence + char base; // Current base (for active seq only) in ASCII + char ref_skip; // True if the cause of eof or start is cigar N + char padding; // True if the base was added due to another seq + int base4; // Base in 4-bit notation (0-15) + hts_pos_t pos; // Current unpadded position in seq + int nth; // nth base at unpadded position 'pos' + int b_is_rev; // 0 => fwd, 1 => rev + int seq_offset; // Current base position in s->seq[] array. + + unsigned char *b_qual;// cached bam_qual + unsigned char *b_seq; // cached bam_seq + + // --- 64 bytes + struct pileup *eofn; // p->eof set, next eof member + struct pileup *eofl; // last non-eof that points to p with p->eof + + uint32_t *b_cigar; // cached bam_cigar + + int cigar_ind; // Current location in s->alignment cigar str + int cigar_op; // Current cigar operation + int cigar_len; // Remaining length of this cigar op + + int first_del; // Used when first base is a deletion + + bam1_t b; // Bam entry associated with struct +} pileup_t; + +/* + * The pileup loop executes and calls callbacks to perform the work. + * + * seq_fetch returns the next sequence. Return 0 from this indicates no + * more data. + * + * seq_init is called, if non-NULL, when a sequence is added to the pileup, + * seq_free likewise, if non-NULL, is called when a sequence is removed + * from the pileup. + * These two functions are akin to the constructor and destructors added + * to mpileup. + * + * seq_column is the primary work horse which is executed for each + * reference position, and for each inserted base per ref pos. + * + * If we were to invert this from a loop generating callbacks to a polled + * style interface like mpileup, then the seq_column bit would be dropped + * and replaced by the returned pileup and associated parameters. + */ +int pileup_loop(samFile *fp, + sam_hdr_t *h, + int (*seq_fetch)(void *client_data, + samFile *fp, + sam_hdr_t *h, + bam1_t *b), + int (*seq_init)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p), + int (*seq_column)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p, + int depth, + hts_pos_t pos, + int nth, + int is_insert), + void (*seq_free)(void *client_data, + samFile *fp, + sam_hdr_t *h, + pileup_t *p), + void *client_data); diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c new file mode 100644 index 0000000000000000000000000000000000000000..54a987c6cb6d3ef28fe56dc7e810205212127937 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c @@ -0,0 +1,665 @@ +/* cram_size.c -- produces summary of the size of each cram data-series + + Copyright (C) 2023 Genome Research Ltd. + + Author: James Bonfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +// TODO: add range query. Eg the ability to look at size for "*" only +// (unmapped), or in a specific region such as a centromere. + +#include + +#include +#include +#include +#include +#include + +#include "htslib/bgzf.h" +#include "htslib/sam.h" +#include "htslib/cram.h" +#include "htslib/kstring.h" +#include "htslib/khash.h" +#include "samtools.h" +#include "sam_opts.h" +#include "htslib/hfile.h" + +/*---------------------------------------------------------------------- + * Compression method handling + */ + +// A numeric version of the cram_method_details struct. +// We expand the myriad of struct field combinations into a single +// enumerated type so we can index and accumulate statistics for +// purposes of reporting. +// +// These expanded numeric values have no definition within CRAM itself +// and never occur within the file format. +enum comp_expanded { + //---- + // Copies from htslib cram_block_method enum + COMP_RAW = CRAM_COMP_RAW, + COMP_GZIP = CRAM_COMP_GZIP, + COMP_BZIP2 = CRAM_COMP_BZIP2, + COMP_LZMA = CRAM_COMP_LZMA, + COMP_RANS8 = CRAM_COMP_RANS4x8, + COMP_RANS16 = CRAM_COMP_RANSNx16, + COMP_ARITH = CRAM_COMP_ARITH, + COMP_FQZ = CRAM_COMP_FQZ, + COMP_TOK3 = CRAM_COMP_TOK3, + + //---- + // Localised variants. + + // Gzip + COMP_GZIP_1, + COMP_GZIP_9, + + // Bzip2 + COMP_BZIP2_1, + COMP_BZIP2_2, + COMP_BZIP2_3, + COMP_BZIP2_4, + COMP_BZIP2_5, + COMP_BZIP2_6, + COMP_BZIP2_7, + COMP_BZIP2_8, + COMP_BZIP2_9, + + // rans 4x8 + COMP_RANS4x8_O0, + COMP_RANS4x8_O1, + + // rans Nx16. Note order here is to enable selection via bit-fields + // bit 0: O0/O1 + // bit 1: RLE + // bit 2: PACK + // bit 3: 32x16 + COMP_RANS4x16_O0, + COMP_RANS4x16_O1, + COMP_RANS4x16_O0R, // +RLE + COMP_RANS4x16_O1R, + COMP_RANS4x16_O0P, // +PACK + COMP_RANS4x16_O1P, + COMP_RANS4x16_O0PR, // +PACK+RLE + COMP_RANS4x16_O1PR, + COMP_RANS32x16_O0, // SIMD variants + COMP_RANS32x16_O1, + COMP_RANS32x16_O0R, // +RLE + COMP_RANS32x16_O1R, + COMP_RANS32x16_O0P, // +PACK + COMP_RANS32x16_O1P, + COMP_RANS32x16_O0PR, // +PACK+RLE + COMP_RANS32x16_O1PR, + COMP_RANSNx16_STRIPE, + COMP_RANSNx16_CAT, + + // Arith + COMP_ARITH_O0, + COMP_ARITH_O1, + COMP_ARITH_O0R, // +RLE + COMP_ARITH_O1R, + COMP_ARITH_O0P, // +PACK + COMP_ARITH_O1P, + COMP_ARITH_O0PR, // +PACK+RLE + COMP_ARITH_O1PR, + COMP_ARITH_STRIPE, + COMP_ARITH_CAT, // no entropy encoder + COMP_ARITH_EXT, // external entropy encode + + // Nake tokeniser + COMP_TOK3_RANS, + COMP_TOK3_ARITH, + + // To mark maximum size + COMP_MAX, +}; + +static enum comp_expanded comp_method2expanded(cram_method_details *cm) { + switch (cm->method) { + case CRAM_COMP_GZIP: + switch (cm->level) { + case 1: return COMP_GZIP_1; + case 9: return COMP_GZIP_9; + default: return COMP_GZIP; + } + break; + + case CRAM_COMP_BZIP2: + if (cm->level >= 1 && cm->level <= 9) + return COMP_BZIP2_1 + cm->level-1; + else + return COMP_BZIP2; + break; + + case CRAM_COMP_RANS4x8: + return cm->order ? COMP_RANS4x8_O1 : COMP_RANS4x8_O0; + + case CRAM_COMP_RANSNx16: { + // 8 4x16, 8 32x16 and 2 stripe/cat + if (cm->stripe) return COMP_RANSNx16_STRIPE; + if (cm->cat) return COMP_RANSNx16_CAT; + int c = COMP_RANS4x16_O0; + c += 1*cm->order; + c += 2*cm->rle; + c += 4*cm->pack; + c += 8*(cm->Nway==32); + return c; + } + + case CRAM_COMP_ARITH: { + // 8 4x16, 8 32x16 and 2 stripe/cat + if (cm->stripe) return COMP_ARITH_STRIPE; + if (cm->cat) return COMP_ARITH_CAT; + if (cm->ext) return COMP_ARITH_EXT; + int c = COMP_ARITH_O0; + c += 1*cm->order; + c += 2*cm->rle; + c += 4*cm->pack; + return c; + } + + case CRAM_COMP_TOK3: + return cm->level < 10 + ? COMP_TOK3_RANS + : COMP_TOK3_ARITH; + + default: + // Any unspecialised method + return (enum comp_expanded)cm->method; + } +} + +// Short form of cram_block_method_int type +static char comp_method2char[COMP_MAX] = + ".gblr0afn" // standard CRAM methods + "_G" // gzip + "bbbbbbbbB" // bzip2 + "rR" // rans4x8 + "010101014545454582" // ransNx16 + "aAaAaAaAaaa" // arith + "nN"; // tok3 + +// Long form of cram_block_method_int type +static char *comp_method2str[COMP_MAX] = { + // Standard CRAM methods + "raw", "gzip", "bzip2", "lzma", "r4x8", "rNx16", + "arith", "fqzcomp", "tok3", + + // custom gzip + "gzip-min", "gzip-max", + + // custom bzip2 + "bzip2-1", "bzip2-2", "bzip2-3", "bzip2-4", "bzip2-5", + "bzip2-6", "bzip2-7", "bzip2-8", "bzip2-9", + + // rANS 4x8 + "r4x8-o0", "r4x8-o1", + + // rANS 4x16 + "r4x16-o0", "r4x16-o1", + + "r4x16-o0R", "r4x16-o1R", + "r4x16-o0P", "r4x16-o1P", + "r4x16-o0PR", "r4x16-o1PR", + "r32x16-o0", "r32x16-o1", + "r32x16-o0R", "r32x16-o1R", + "r32x16-o0P", "r32x16-o1P", + "r32x16-o0PR","r32x16-o1PR", + "rNx16-xo0", "rNx16-cat", + + // Arith + "arith-o0", "arith-o1", + "arith-o0R", "arith-o1R", + "arith-o0P", "arith-o1P", + "arith-o0PR", "arith-o1PR", + "arith-stripe", "arith-cat", "arith-ext", + + // Name tokeniser + "tok3-rans", "tok3-arith", +}; + +/*---------------------------------------------------------------------- + * Manipulation and sorting of Block Content-ID arrays and hashes + */ + +typedef struct { + int64_t csize[COMP_MAX]; + int64_t usize[COMP_MAX]; +} cusize_t; + +static int64_t total_csize(cusize_t *cu) { + int i; + int64_t tot = 0; + for (i = 0; i < COMP_MAX; i++) + tot += cu->csize[i]; + return tot; +} + +static int64_t total_usize(cusize_t *cu) { + int i; + int64_t tot = 0; + for (i = 0; i < COMP_MAX; i++) + tot += cu->usize[i]; + return tot; +} + +// cusize_t array and sorting by compressed size +static cusize_t *sort_cusize_global; // avoids a messy extra data type +static int sort_cusize_compar(const void *i1, const void *i2) { + int64_t n = sort_cusize_global->csize[*(const int *)i2] - + sort_cusize_global->csize[*(const int *)i1]; + return n > 0 ? 1 : (n < 0 ? -1 : *(const int *)i1 - *(const int *)i2); +} + +// Sort a cusize array by size of used method. +// Returns cu->csize[comp] indices in descending size, as static mem +static int *sort_cusize(cusize_t *cu) { + static int idx[COMP_MAX]; + int i; + for (i = 0; i < COMP_MAX; i++) + idx[i] = i; + sort_cusize_global = cu; + qsort(idx, COMP_MAX, sizeof(*idx), sort_cusize_compar); + + return idx; +} + +// Hash table of cusize_t and sorting by key (content-id) +KHASH_MAP_INIT_INT(cu, cusize_t) + +/* Sort by hash key. Global due to rubbish qsort API, but it's simple. */ +static khash_t(cu) *global_cu_hash = NULL; +static int cu_compar(const void *i1, const void *i2) { + return kh_key(global_cu_hash, *(const int *)i1) - + kh_key(global_cu_hash, *(const int *)i2); +} + +/*---------------------------------------------------------------------- + * Main cram_size reporting and aggregation + */ +static off_t report_size(FILE *outfp, int verbose, int ref_seq_blk, + khash_t(cu) *cu_size, cram_cid2ds_t *cid2ds) { + if (!cu_size || !cid2ds) + return -1; + + khiter_t k; + off_t tot_size = 0; + + fprintf(outfp, "# Content_ID Uncomp.size Comp.size Ratio Method%.*s Data_series\n", verbose ? 4 : 0, " "); + int *sorted_blocks = malloc(kh_end(cu_size)*sizeof(int)); + if (!sorted_blocks) + return -1; + int nblocks = 0; + for (k = kh_begin(cu_size); k != kh_end(cu_size); k++) { + if (!kh_exist(cu_size, k)) + continue; + sorted_blocks[nblocks++] = k; + } + global_cu_hash = cu_size; + qsort(sorted_blocks, nblocks, sizeof(int), cu_compar); + + int i; + for (i = 0; i < nblocks; i++) { + k = sorted_blocks[i]; + + if (verbose) { + // FULL output + int *comp_idx = sort_cusize(&kh_value(cu_size, k)); + int first_line = 1, c, j; + for (c = 0; c < COMP_MAX; c++) { + int comp = comp_idx[c]; + if (!kh_value(cu_size, k).csize[comp] && c) + break; + + if (!first_line) + fprintf(outfp, "\n"); + first_line = 0; + + if ((int)kh_key(cu_size, k) < 0) + fprintf(outfp, "BLOCK %8s", "CORE"); + else + fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k)); + + fprintf(outfp, " %12"PRId64" %12"PRId64, + kh_value(cu_size, k).usize[comp], + kh_value(cu_size, k).csize[comp]); + double f = (100.0*(kh_value(cu_size, k).csize[comp]+.0001)) / + (kh_value(cu_size, k).usize[comp]+.0001); + if (f > 999) + fprintf(outfp, " >999%% %-11s", comp_method2str[comp]); + else + fprintf(outfp, " %6.2f%% %-11s",f, comp_method2str[comp]); + + int n, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n); + for (j = 0; j < n; j++) { + int d = dsa[j]; + if (d > 65535) + fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff); + else + fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff); + } + } + } else { + // aggregate by compression type. + int64_t csize = total_csize(&kh_value(cu_size, k)); + int64_t usize = total_usize(&kh_value(cu_size, k)); + int *comp_idx = sort_cusize(&kh_value(cu_size, k)); + + char cstr[COMP_MAX+1] = {0}; + int cidx = 0, c; + for (c = 0; c < COMP_MAX; c++) { + if (!kh_value(cu_size, k).csize[comp_idx[c]]) + break; + cstr[cidx++] = comp_method2char[comp_idx[c]]; + } + if (!*cstr) *cstr = '.'; + + if ((int)kh_key(cu_size, k) < 0) + fprintf(outfp, "BLOCK %8s", "CORE"); + else + fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k)); + fprintf(outfp, " %12"PRId64" %12"PRId64, usize, csize); + double f = 100*(csize+.0001)/(usize+.0001); + if (f > 999) + fprintf(outfp, " >999%% %-7s", cstr); + else + fprintf(outfp, " %6.2f%% %-7s", f, cstr); + + int n, j, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n); + for (j = 0; j < n; j++) { + int d = dsa[j]; + if (d > 65535) + fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff); + else + fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff); + } + } + + if ((int)kh_key(cu_size, k) >= 0 && + (int)kh_key(cu_size, k) == ref_seq_blk) { + fprintf(outfp, " embedded_ref"); + } + fprintf(outfp, "\n"); + + tot_size += total_csize(&kh_value(cu_size, k)); + } + + free(sorted_blocks); + + return tot_size; +} + +/* Main processing loop */ +static int cram_size(hFILE *hf_in, samFile *in, sam_hdr_t *h, FILE *outfp, + int verbose, int encodings) { + cram_fd *in_c; + cram_container *c = NULL; + cram_block *blk = NULL; + cram_block_slice_hdr *shdr = NULL; + khiter_t k; + int ret; + cram_cid2ds_t *cid2ds = NULL; + khash_t(cu) *cu_size = kh_init(cu); + int ref_seq_blk_used = -1; + int64_t nseqs = 0, nbases = 0, ncont = 0, nslice = 0; + + if (!in->is_cram) { + print_error("cram_size", "Input is not a CRAM file"); + goto err; + } + in_c = in->fp.cram; // low level htslib abuse? + while ((c = cram_read_container(in_c))) { + if (cram_container_is_empty(in_c)) { + cram_block *blk; + // Container compression header + if (!(blk = cram_read_block(in_c))) + goto err; + cram_free_block(blk); + cram_free_container(c); + c = NULL; blk = NULL; + continue; + } + + nseqs += cram_container_get_num_records(c); + nbases += cram_container_get_num_bases(c); + + // Container compression header + int32_t num_slices; + if (!(blk = cram_read_block(in_c))) + goto err; + + // Decode compression header... + cram_block_compression_hdr *chdr; + chdr = cram_decode_compression_header(in_c, blk); + + if (encodings) { + kstring_t ks = KS_INITIALIZE; + if (cram_describe_encodings(chdr, &ks) < 0) + goto err; + + fprintf(outfp, "Container encodings\n%s\n", ks_str(&ks)); + + ks_free(&ks); + } + + cid2ds = cram_update_cid2ds_map(chdr, cid2ds); + + cram_free_block(blk); + blk = NULL; + + cram_free_compression_header(chdr); + + // Container num_blocks can be invalid, due to a bug. + // Instead we iterate in slice context instead. + (void)cram_container_get_landmarks(c, &num_slices); + ncont++; + nslice += num_slices; + + int i, j; + for (i = 0; i < num_slices; i++) { + // Slice header + if (!(blk = cram_read_block(in_c))) + goto err; + if (!(shdr = cram_decode_slice_header(in_c, blk))) + goto err; + cram_free_block(blk); + blk = NULL; + + int ref_seq_blk = cram_slice_hdr_get_embed_ref_id(shdr); + int num_blocks = cram_slice_hdr_get_num_blocks(shdr); + + // Embedded reference. Check it's consistent (if used this is + // an almost guaranteed certainty, so we take the easy route). + if (ref_seq_blk >= 0) { + if (ref_seq_blk_used == -1) + ref_seq_blk_used = ref_seq_blk; + else if (ref_seq_blk_used != ref_seq_blk) + fprintf(stderr, "Embedded reference is not consistently using the same Content-Id.\n" + "Reported figures for reference will be invalid.\n"); + } + + // Slice data blocks + for (j = 0; j < num_blocks; j++) { + // read and discard, unless it's the ref-ID block + if (!(blk = cram_read_block(in_c))) + goto err; + + int32_t csize = cram_block_get_comp_size(blk); + int32_t usize = cram_block_get_uncomp_size(blk); + int cid = cram_block_get_content_id(blk); + enum cram_block_method method = cram_block_get_method(blk); + + // Expand comp to the internal sub-formats, eg + // rANS order-0/1, PACK+RLE, etc. + cram_method_details *cm; + cm = cram_expand_method(cram_block_get_data(blk), + cram_block_get_comp_size(blk), + method); + if (!cm) + goto err; + enum comp_expanded comp + = comp_method2expanded(cm); + free(cm); + + k = kh_put(cu, cu_size, cid, &ret); + if (ret < 0) + goto err; + if (ret == 0) { + kh_value(cu_size, k).csize[comp] += csize; + kh_value(cu_size, k).usize[comp] += usize; + } else { + memset(&kh_value(cu_size, k), 0, sizeof(cusize_t)); + kh_value(cu_size, k).csize[comp] = csize; + kh_value(cu_size, k).usize[comp] = usize; + } + + cram_free_block(blk); + blk = NULL; + } + cram_free_slice_header(shdr); + shdr = NULL; + } + + cram_free_container(c); + c = NULL; + } + + off_t tot_size = report_size(outfp, verbose, ref_seq_blk_used, + cu_size, cid2ds); + if (tot_size < 0) + goto err; + + kh_destroy(cu, cu_size); + cram_cid2ds_free(cid2ds); + + off_t end = htell(hf_in); + + fprintf(outfp, "\n"); + fprintf(outfp, "Number of containers %18"PRId64"\n", ncont); + fprintf(outfp, "Number of slices %18"PRId64"\n", nslice); + fprintf(outfp, "Number of sequences %18"PRId64"\n", nseqs); + fprintf(outfp, "Number of bases %18"PRId64"\n", nbases); + fprintf(outfp, "Total file size %18"PRId64"\n", (int64_t) end); + fprintf(outfp, "Format overhead size %18"PRId64"\n", (int64_t) (end - tot_size)); + + return 0; + + err: + // Report anyway so we can get stats on partial files, but be + // sure to error too. + report_size(outfp, verbose, ref_seq_blk_used, cu_size, cid2ds); + + print_error("cram_size", "Failed in decoding CRAM file"); + if (blk) + cram_free_block(blk); + if (shdr) + cram_free_slice_header(shdr); + if (c) + cram_free_container(c); + if (cid2ds) + cram_cid2ds_free(cid2ds); + + return -1; +} + +/* main() for cram_size */ +int main_cram_size(int argc, char *argv[]) { + int c, usage = 0, verbose = 0, encodings = 0; + sam_hdr_t *h = 0; + hFILE *hf_in = NULL; + samFile *in = NULL; + sam_global_args ga; + FILE *outfp = stdout; + + static const struct option lopts[] = { + {"output", required_argument, NULL, 'o'}, + {"verbose", no_argument, NULL, 'v'}, + {"encodings", no_argument, NULL, 'e'}, + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '-'), + { NULL, 0, NULL, 0 } + }; + + sam_global_args_init(&ga); + + while ((c = getopt_long(argc, argv, "vo:e", lopts, NULL)) >= 0) { + switch (c) { + case 'o': + if (!(outfp = fopen(optarg, "w"))) { + perror(optarg); + goto err; + } + break; + + case 'v': + verbose++; + break; + + case 'e': + encodings++; + break; + + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + } + + if ((optind == argc && isatty(0)) || usage) { + printf("Usage: samtools cram_size [-ve] [-o out.size] [in.cram]\n"); + return 0; + } + + char *fn = optind < argc ? argv[optind] : "-"; + + // We want access to in->fp.cram->fp, but this is an opaque struct so we + // can't get that. However we opened with hopen and then reopen as + // CRAM with hts_hopen, which will swallow the initial hFILE and take + // owenership of it. Hence we now know in->fp.cram->fp. + if (!(hf_in = hopen(fn, "r"))) { + print_error_errno("cram_size", "failed to open file '%s'", fn); + return 1; + } + if (!(in = hts_hopen(hf_in, fn, "r"))) { + print_error_errno("cram_size", "failed to open file '%s'", fn); + goto err; + } + + if (!(h = sam_hdr_read(in))) + goto err; + + int ret = cram_size(hf_in, in, h, outfp, verbose, encodings); + sam_hdr_destroy(h); + sam_close(in); + if (outfp != stdout) + fclose(outfp); + + return ret ? 1 : 0; + + err: + if (in) + sam_close(in); + if (h) + sam_hdr_destroy(h); + + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..b3031d00eeb2cd53288db051fc50d3442c0f4838 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cram_size.c.pysam.c @@ -0,0 +1,667 @@ +#include "samtools.pysam.h" + +/* cram_size.c -- produces summary of the size of each cram data-series + + Copyright (C) 2023 Genome Research Ltd. + + Author: James Bonfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +// TODO: add range query. Eg the ability to look at size for "*" only +// (unmapped), or in a specific region such as a centromere. + +#include + +#include +#include +#include +#include +#include + +#include "htslib/bgzf.h" +#include "htslib/sam.h" +#include "htslib/cram.h" +#include "htslib/kstring.h" +#include "htslib/khash.h" +#include "samtools.h" +#include "sam_opts.h" +#include "htslib/hfile.h" + +/*---------------------------------------------------------------------- + * Compression method handling + */ + +// A numeric version of the cram_method_details struct. +// We expand the myriad of struct field combinations into a single +// enumerated type so we can index and accumulate statistics for +// purposes of reporting. +// +// These expanded numeric values have no definition within CRAM itself +// and never occur within the file format. +enum comp_expanded { + //---- + // Copies from htslib cram_block_method enum + COMP_RAW = CRAM_COMP_RAW, + COMP_GZIP = CRAM_COMP_GZIP, + COMP_BZIP2 = CRAM_COMP_BZIP2, + COMP_LZMA = CRAM_COMP_LZMA, + COMP_RANS8 = CRAM_COMP_RANS4x8, + COMP_RANS16 = CRAM_COMP_RANSNx16, + COMP_ARITH = CRAM_COMP_ARITH, + COMP_FQZ = CRAM_COMP_FQZ, + COMP_TOK3 = CRAM_COMP_TOK3, + + //---- + // Localised variants. + + // Gzip + COMP_GZIP_1, + COMP_GZIP_9, + + // Bzip2 + COMP_BZIP2_1, + COMP_BZIP2_2, + COMP_BZIP2_3, + COMP_BZIP2_4, + COMP_BZIP2_5, + COMP_BZIP2_6, + COMP_BZIP2_7, + COMP_BZIP2_8, + COMP_BZIP2_9, + + // rans 4x8 + COMP_RANS4x8_O0, + COMP_RANS4x8_O1, + + // rans Nx16. Note order here is to enable selection via bit-fields + // bit 0: O0/O1 + // bit 1: RLE + // bit 2: PACK + // bit 3: 32x16 + COMP_RANS4x16_O0, + COMP_RANS4x16_O1, + COMP_RANS4x16_O0R, // +RLE + COMP_RANS4x16_O1R, + COMP_RANS4x16_O0P, // +PACK + COMP_RANS4x16_O1P, + COMP_RANS4x16_O0PR, // +PACK+RLE + COMP_RANS4x16_O1PR, + COMP_RANS32x16_O0, // SIMD variants + COMP_RANS32x16_O1, + COMP_RANS32x16_O0R, // +RLE + COMP_RANS32x16_O1R, + COMP_RANS32x16_O0P, // +PACK + COMP_RANS32x16_O1P, + COMP_RANS32x16_O0PR, // +PACK+RLE + COMP_RANS32x16_O1PR, + COMP_RANSNx16_STRIPE, + COMP_RANSNx16_CAT, + + // Arith + COMP_ARITH_O0, + COMP_ARITH_O1, + COMP_ARITH_O0R, // +RLE + COMP_ARITH_O1R, + COMP_ARITH_O0P, // +PACK + COMP_ARITH_O1P, + COMP_ARITH_O0PR, // +PACK+RLE + COMP_ARITH_O1PR, + COMP_ARITH_STRIPE, + COMP_ARITH_CAT, // no entropy encoder + COMP_ARITH_EXT, // external entropy encode + + // Nake tokeniser + COMP_TOK3_RANS, + COMP_TOK3_ARITH, + + // To mark maximum size + COMP_MAX, +}; + +static enum comp_expanded comp_method2expanded(cram_method_details *cm) { + switch (cm->method) { + case CRAM_COMP_GZIP: + switch (cm->level) { + case 1: return COMP_GZIP_1; + case 9: return COMP_GZIP_9; + default: return COMP_GZIP; + } + break; + + case CRAM_COMP_BZIP2: + if (cm->level >= 1 && cm->level <= 9) + return COMP_BZIP2_1 + cm->level-1; + else + return COMP_BZIP2; + break; + + case CRAM_COMP_RANS4x8: + return cm->order ? COMP_RANS4x8_O1 : COMP_RANS4x8_O0; + + case CRAM_COMP_RANSNx16: { + // 8 4x16, 8 32x16 and 2 stripe/cat + if (cm->stripe) return COMP_RANSNx16_STRIPE; + if (cm->cat) return COMP_RANSNx16_CAT; + int c = COMP_RANS4x16_O0; + c += 1*cm->order; + c += 2*cm->rle; + c += 4*cm->pack; + c += 8*(cm->Nway==32); + return c; + } + + case CRAM_COMP_ARITH: { + // 8 4x16, 8 32x16 and 2 stripe/cat + if (cm->stripe) return COMP_ARITH_STRIPE; + if (cm->cat) return COMP_ARITH_CAT; + if (cm->ext) return COMP_ARITH_EXT; + int c = COMP_ARITH_O0; + c += 1*cm->order; + c += 2*cm->rle; + c += 4*cm->pack; + return c; + } + + case CRAM_COMP_TOK3: + return cm->level < 10 + ? COMP_TOK3_RANS + : COMP_TOK3_ARITH; + + default: + // Any unspecialised method + return (enum comp_expanded)cm->method; + } +} + +// Short form of cram_block_method_int type +static char comp_method2char[COMP_MAX] = + ".gblr0afn" // standard CRAM methods + "_G" // gzip + "bbbbbbbbB" // bzip2 + "rR" // rans4x8 + "010101014545454582" // ransNx16 + "aAaAaAaAaaa" // arith + "nN"; // tok3 + +// Long form of cram_block_method_int type +static char *comp_method2str[COMP_MAX] = { + // Standard CRAM methods + "raw", "gzip", "bzip2", "lzma", "r4x8", "rNx16", + "arith", "fqzcomp", "tok3", + + // custom gzip + "gzip-min", "gzip-max", + + // custom bzip2 + "bzip2-1", "bzip2-2", "bzip2-3", "bzip2-4", "bzip2-5", + "bzip2-6", "bzip2-7", "bzip2-8", "bzip2-9", + + // rANS 4x8 + "r4x8-o0", "r4x8-o1", + + // rANS 4x16 + "r4x16-o0", "r4x16-o1", + + "r4x16-o0R", "r4x16-o1R", + "r4x16-o0P", "r4x16-o1P", + "r4x16-o0PR", "r4x16-o1PR", + "r32x16-o0", "r32x16-o1", + "r32x16-o0R", "r32x16-o1R", + "r32x16-o0P", "r32x16-o1P", + "r32x16-o0PR","r32x16-o1PR", + "rNx16-xo0", "rNx16-cat", + + // Arith + "arith-o0", "arith-o1", + "arith-o0R", "arith-o1R", + "arith-o0P", "arith-o1P", + "arith-o0PR", "arith-o1PR", + "arith-stripe", "arith-cat", "arith-ext", + + // Name tokeniser + "tok3-rans", "tok3-arith", +}; + +/*---------------------------------------------------------------------- + * Manipulation and sorting of Block Content-ID arrays and hashes + */ + +typedef struct { + int64_t csize[COMP_MAX]; + int64_t usize[COMP_MAX]; +} cusize_t; + +static int64_t total_csize(cusize_t *cu) { + int i; + int64_t tot = 0; + for (i = 0; i < COMP_MAX; i++) + tot += cu->csize[i]; + return tot; +} + +static int64_t total_usize(cusize_t *cu) { + int i; + int64_t tot = 0; + for (i = 0; i < COMP_MAX; i++) + tot += cu->usize[i]; + return tot; +} + +// cusize_t array and sorting by compressed size +static cusize_t *sort_cusize_global; // avoids a messy extra data type +static int sort_cusize_compar(const void *i1, const void *i2) { + int64_t n = sort_cusize_global->csize[*(const int *)i2] - + sort_cusize_global->csize[*(const int *)i1]; + return n > 0 ? 1 : (n < 0 ? -1 : *(const int *)i1 - *(const int *)i2); +} + +// Sort a cusize array by size of used method. +// Returns cu->csize[comp] indices in descending size, as static mem +static int *sort_cusize(cusize_t *cu) { + static int idx[COMP_MAX]; + int i; + for (i = 0; i < COMP_MAX; i++) + idx[i] = i; + sort_cusize_global = cu; + qsort(idx, COMP_MAX, sizeof(*idx), sort_cusize_compar); + + return idx; +} + +// Hash table of cusize_t and sorting by key (content-id) +KHASH_MAP_INIT_INT(cu, cusize_t) + +/* Sort by hash key. Global due to rubbish qsort API, but it's simple. */ +static khash_t(cu) *global_cu_hash = NULL; +static int cu_compar(const void *i1, const void *i2) { + return kh_key(global_cu_hash, *(const int *)i1) - + kh_key(global_cu_hash, *(const int *)i2); +} + +/*---------------------------------------------------------------------- + * Main cram_size reporting and aggregation + */ +static off_t report_size(FILE *outfp, int verbose, int ref_seq_blk, + khash_t(cu) *cu_size, cram_cid2ds_t *cid2ds) { + if (!cu_size || !cid2ds) + return -1; + + khiter_t k; + off_t tot_size = 0; + + fprintf(outfp, "# Content_ID Uncomp.size Comp.size Ratio Method%.*s Data_series\n", verbose ? 4 : 0, " "); + int *sorted_blocks = malloc(kh_end(cu_size)*sizeof(int)); + if (!sorted_blocks) + return -1; + int nblocks = 0; + for (k = kh_begin(cu_size); k != kh_end(cu_size); k++) { + if (!kh_exist(cu_size, k)) + continue; + sorted_blocks[nblocks++] = k; + } + global_cu_hash = cu_size; + qsort(sorted_blocks, nblocks, sizeof(int), cu_compar); + + int i; + for (i = 0; i < nblocks; i++) { + k = sorted_blocks[i]; + + if (verbose) { + // FULL output + int *comp_idx = sort_cusize(&kh_value(cu_size, k)); + int first_line = 1, c, j; + for (c = 0; c < COMP_MAX; c++) { + int comp = comp_idx[c]; + if (!kh_value(cu_size, k).csize[comp] && c) + break; + + if (!first_line) + fprintf(outfp, "\n"); + first_line = 0; + + if ((int)kh_key(cu_size, k) < 0) + fprintf(outfp, "BLOCK %8s", "CORE"); + else + fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k)); + + fprintf(outfp, " %12"PRId64" %12"PRId64, + kh_value(cu_size, k).usize[comp], + kh_value(cu_size, k).csize[comp]); + double f = (100.0*(kh_value(cu_size, k).csize[comp]+.0001)) / + (kh_value(cu_size, k).usize[comp]+.0001); + if (f > 999) + fprintf(outfp, " >999%% %-11s", comp_method2str[comp]); + else + fprintf(outfp, " %6.2f%% %-11s",f, comp_method2str[comp]); + + int n, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n); + for (j = 0; j < n; j++) { + int d = dsa[j]; + if (d > 65535) + fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff); + else + fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff); + } + } + } else { + // aggregate by compression type. + int64_t csize = total_csize(&kh_value(cu_size, k)); + int64_t usize = total_usize(&kh_value(cu_size, k)); + int *comp_idx = sort_cusize(&kh_value(cu_size, k)); + + char cstr[COMP_MAX+1] = {0}; + int cidx = 0, c; + for (c = 0; c < COMP_MAX; c++) { + if (!kh_value(cu_size, k).csize[comp_idx[c]]) + break; + cstr[cidx++] = comp_method2char[comp_idx[c]]; + } + if (!*cstr) *cstr = '.'; + + if ((int)kh_key(cu_size, k) < 0) + fprintf(outfp, "BLOCK %8s", "CORE"); + else + fprintf(outfp, "BLOCK %8d", kh_key(cu_size, k)); + fprintf(outfp, " %12"PRId64" %12"PRId64, usize, csize); + double f = 100*(csize+.0001)/(usize+.0001); + if (f > 999) + fprintf(outfp, " >999%% %-7s", cstr); + else + fprintf(outfp, " %6.2f%% %-7s", f, cstr); + + int n, j, *dsa = cram_cid2ds_query(cid2ds, kh_key(cu_size, k), &n); + for (j = 0; j < n; j++) { + int d = dsa[j]; + if (d > 65535) + fprintf(outfp, " %c%c%c", d>>16, (d>>8)&0xff, d&0xff); + else + fprintf(outfp, " %c%c", (d>>8)&0xff, d&0xff); + } + } + + if ((int)kh_key(cu_size, k) >= 0 && + (int)kh_key(cu_size, k) == ref_seq_blk) { + fprintf(outfp, " embedded_ref"); + } + fprintf(outfp, "\n"); + + tot_size += total_csize(&kh_value(cu_size, k)); + } + + free(sorted_blocks); + + return tot_size; +} + +/* Main processing loop */ +static int cram_size(hFILE *hf_in, samFile *in, sam_hdr_t *h, FILE *outfp, + int verbose, int encodings) { + cram_fd *in_c; + cram_container *c = NULL; + cram_block *blk = NULL; + cram_block_slice_hdr *shdr = NULL; + khiter_t k; + int ret; + cram_cid2ds_t *cid2ds = NULL; + khash_t(cu) *cu_size = kh_init(cu); + int ref_seq_blk_used = -1; + int64_t nseqs = 0, nbases = 0, ncont = 0, nslice = 0; + + if (!in->is_cram) { + print_error("cram_size", "Input is not a CRAM file"); + goto err; + } + in_c = in->fp.cram; // low level htslib abuse? + while ((c = cram_read_container(in_c))) { + if (cram_container_is_empty(in_c)) { + cram_block *blk; + // Container compression header + if (!(blk = cram_read_block(in_c))) + goto err; + cram_free_block(blk); + cram_free_container(c); + c = NULL; blk = NULL; + continue; + } + + nseqs += cram_container_get_num_records(c); + nbases += cram_container_get_num_bases(c); + + // Container compression header + int32_t num_slices; + if (!(blk = cram_read_block(in_c))) + goto err; + + // Decode compression header... + cram_block_compression_hdr *chdr; + chdr = cram_decode_compression_header(in_c, blk); + + if (encodings) { + kstring_t ks = KS_INITIALIZE; + if (cram_describe_encodings(chdr, &ks) < 0) + goto err; + + fprintf(outfp, "Container encodings\n%s\n", ks_str(&ks)); + + ks_free(&ks); + } + + cid2ds = cram_update_cid2ds_map(chdr, cid2ds); + + cram_free_block(blk); + blk = NULL; + + cram_free_compression_header(chdr); + + // Container num_blocks can be invalid, due to a bug. + // Instead we iterate in slice context instead. + (void)cram_container_get_landmarks(c, &num_slices); + ncont++; + nslice += num_slices; + + int i, j; + for (i = 0; i < num_slices; i++) { + // Slice header + if (!(blk = cram_read_block(in_c))) + goto err; + if (!(shdr = cram_decode_slice_header(in_c, blk))) + goto err; + cram_free_block(blk); + blk = NULL; + + int ref_seq_blk = cram_slice_hdr_get_embed_ref_id(shdr); + int num_blocks = cram_slice_hdr_get_num_blocks(shdr); + + // Embedded reference. Check it's consistent (if used this is + // an almost guaranteed certainty, so we take the easy route). + if (ref_seq_blk >= 0) { + if (ref_seq_blk_used == -1) + ref_seq_blk_used = ref_seq_blk; + else if (ref_seq_blk_used != ref_seq_blk) + fprintf(samtools_stderr, "Embedded reference is not consistently using the same Content-Id.\n" + "Reported figures for reference will be invalid.\n"); + } + + // Slice data blocks + for (j = 0; j < num_blocks; j++) { + // read and discard, unless it's the ref-ID block + if (!(blk = cram_read_block(in_c))) + goto err; + + int32_t csize = cram_block_get_comp_size(blk); + int32_t usize = cram_block_get_uncomp_size(blk); + int cid = cram_block_get_content_id(blk); + enum cram_block_method method = cram_block_get_method(blk); + + // Expand comp to the internal sub-formats, eg + // rANS order-0/1, PACK+RLE, etc. + cram_method_details *cm; + cm = cram_expand_method(cram_block_get_data(blk), + cram_block_get_comp_size(blk), + method); + if (!cm) + goto err; + enum comp_expanded comp + = comp_method2expanded(cm); + free(cm); + + k = kh_put(cu, cu_size, cid, &ret); + if (ret < 0) + goto err; + if (ret == 0) { + kh_value(cu_size, k).csize[comp] += csize; + kh_value(cu_size, k).usize[comp] += usize; + } else { + memset(&kh_value(cu_size, k), 0, sizeof(cusize_t)); + kh_value(cu_size, k).csize[comp] = csize; + kh_value(cu_size, k).usize[comp] = usize; + } + + cram_free_block(blk); + blk = NULL; + } + cram_free_slice_header(shdr); + shdr = NULL; + } + + cram_free_container(c); + c = NULL; + } + + off_t tot_size = report_size(outfp, verbose, ref_seq_blk_used, + cu_size, cid2ds); + if (tot_size < 0) + goto err; + + kh_destroy(cu, cu_size); + cram_cid2ds_free(cid2ds); + + off_t end = htell(hf_in); + + fprintf(outfp, "\n"); + fprintf(outfp, "Number of containers %18"PRId64"\n", ncont); + fprintf(outfp, "Number of slices %18"PRId64"\n", nslice); + fprintf(outfp, "Number of sequences %18"PRId64"\n", nseqs); + fprintf(outfp, "Number of bases %18"PRId64"\n", nbases); + fprintf(outfp, "Total file size %18"PRId64"\n", (int64_t) end); + fprintf(outfp, "Format overhead size %18"PRId64"\n", (int64_t) (end - tot_size)); + + return 0; + + err: + // Report anyway so we can get stats on partial files, but be + // sure to error too. + report_size(outfp, verbose, ref_seq_blk_used, cu_size, cid2ds); + + print_error("cram_size", "Failed in decoding CRAM file"); + if (blk) + cram_free_block(blk); + if (shdr) + cram_free_slice_header(shdr); + if (c) + cram_free_container(c); + if (cid2ds) + cram_cid2ds_free(cid2ds); + + return -1; +} + +/* main() for cram_size */ +int main_cram_size(int argc, char *argv[]) { + int c, usage = 0, verbose = 0, encodings = 0; + sam_hdr_t *h = 0; + hFILE *hf_in = NULL; + samFile *in = NULL; + sam_global_args ga; + FILE *outfp = samtools_stdout; + + static const struct option lopts[] = { + {"output", required_argument, NULL, 'o'}, + {"verbose", no_argument, NULL, 'v'}, + {"encodings", no_argument, NULL, 'e'}, + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', '-', '-'), + { NULL, 0, NULL, 0 } + }; + + sam_global_args_init(&ga); + + while ((c = getopt_long(argc, argv, "vo:e", lopts, NULL)) >= 0) { + switch (c) { + case 'o': + if (!(outfp = fopen(optarg, "w"))) { + perror(optarg); + goto err; + } + break; + + case 'v': + verbose++; + break; + + case 'e': + encodings++; + break; + + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + } + + if ((optind == argc && isatty(0)) || usage) { + fprintf(samtools_stdout, "Usage: samtools cram_size [-ve] [-o out.size] [in.cram]\n"); + return 0; + } + + char *fn = optind < argc ? argv[optind] : "-"; + + // We want access to in->fp.cram->fp, but this is an opaque struct so we + // can't get that. However we opened with hopen and then reopen as + // CRAM with hts_hopen, which will swallow the initial hFILE and take + // owenership of it. Hence we now know in->fp.cram->fp. + if (!(hf_in = hopen(fn, "r"))) { + print_error_errno("cram_size", "failed to open file '%s'", fn); + return 1; + } + if (!(in = hts_hopen(hf_in, fn, "r"))) { + print_error_errno("cram_size", "failed to open file '%s'", fn); + goto err; + } + + if (!(h = sam_hdr_read(in))) + goto err; + + int ret = cram_size(hf_in, in, h, outfp, verbose, encodings); + sam_hdr_destroy(h); + sam_close(in); + if (outfp != samtools_stdout) + fclose(outfp); + + return ret ? 1 : 0; + + err: + if (in) + sam_close(in); + if (h) + sam_hdr_destroy(h); + + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c new file mode 100644 index 0000000000000000000000000000000000000000..7c8387ca6848f6be8adf8ae6a794f0b3b6073d38 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c @@ -0,0 +1,257 @@ +/* cut_target.c -- targetcut subcommand. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2012-2013, 2015, 2016, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "samtools.h" +#include "sam_opts.h" + +#define ERR_DEP 0.83 + +typedef struct { + int e[2][3], p[2][2]; +} score_param_t; + +/* Note that although the two matrics have 10 parameters in total, only 4 + * (probably 3) are free. Changing the scoring matrices in a sort of symmetric + * way will not change the result. */ +static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} }; + +typedef struct { + int min_baseQ, tid, max_bases; + uint16_t *bases; + samFile *fp; + sam_hdr_t *h; + char *ref; + hts_pos_t len; + faidx_t *fai; + errmod_t *em; +} ct_t; + +static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp) +{ + int i, j, ret, tmp, k, sum[4], qual; + float q[16]; + if (n > g->max_bases) { // enlarge g->bases + g->max_bases = n; + kroundup32(g->max_bases); + g->bases = realloc(g->bases, (size_t) g->max_bases * 2); + } + for (i = k = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint8_t *seq; + int q, baseQ, b; + if (p->is_refskip || p->is_del) continue; + baseQ = bam_get_qual(p->b)[p->qpos]; + if (baseQ < g->min_baseQ) continue; + seq = bam_get_seq(p->b); + b = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (b > 3) continue; + q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; + if (q < 4) q = 4; + if (q > 63) q = 63; + g->bases[k++] = q<<5 | bam_is_rev(p->b)<<4 | b; + } + if (k == 0) return 0; + errmod_cal(g->em, k, 4, g->bases, q); + for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i; + for (i = 1; i < 4; ++i) // insertion sort + for (j = i; j > 0 && sum[j] < sum[j-1]; --j) + tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp; + qual = (sum[1]>>2) - (sum[0]>>2); + k = k < 256? k : 255; + ret = (qual < 63? qual : 63) << 2 | (sum[0]&3); + return ret<<8|k; +} + +static void process_cns(sam_hdr_t *h, int tid, hts_pos_t l, uint16_t *cns) +{ + int64_t i, s; + int f[2][2], *prev, *curr, *swap_tmp; + uint8_t *b; // backtrack array + b = calloc(l, 1); + f[0][0] = f[0][1] = 0; + prev = f[0]; curr = f[1]; + // fill the backtrack matrix + for (i = 0; i < l; ++i) { + int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2; + int tmp0, tmp1; + // compute f[0] + tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0) + tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1) + if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0; + else curr[0] = tmp1, b[i] = 1; + // compute f[1] + tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0) + tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1) + if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1; + else curr[1] = tmp1, b[i] |= 1<<1; + // swap + swap_tmp = prev; prev = curr; curr = swap_tmp; + } + // backtrack + s = prev[0] > prev[1]? 0 : 1; + for (i = l - 1; i > 0; --i) { + b[i] |= s<<2; + s = b[i]>>s&1; + } + // print + for (i = 0, s = -1; i < INT64_MAX && i <= l; ++i) { + if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) { + if (s >= 0) { + int64_t j; + 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); + for (j = s; j < i; ++j) { + int c = cns[j]>>8; + if (c == 0) putchar('N'); + else putchar("ACGT"[c&3]); + } + putchar('\t'); + for (j = s; j < i; ++j) + putchar(33 + (cns[j]>>8>>2)); + putchar('\n'); + } + //if (s >= 0) printf("%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s); + s = -1; + } else if ((b[i]>>2&3) && s < 0) s = i; + } + free(b); +} + +static int read_aln(void *data, bam1_t *b) +{ + ct_t *g = (ct_t*)data; + int ret; + while (1) + { + ret = sam_read1(g->fp, g->h, b); + if ( ret<0 ) break; + if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue; + if ( g->fai && b->core.tid >= 0 ) { + if (b->core.tid != g->tid) { // then load the sequence + free(g->ref); + g->ref = fai_fetch64(g->fai, sam_hdr_tid2name(g->h, b->core.tid), &g->len); + g->tid = b->core.tid; + } + sam_prob_realn(b, g->ref, g->len, 1<<1|1); + } + break; + } + return ret; +} + +int main_cut_target(int argc, char *argv[]) +{ + int c, tid, pos, n, lasttid = -1, usage = 0, status = EXIT_SUCCESS; + hts_pos_t l, max_l; + const bam_pileup1_t *p; + bam_plp_t plp; + uint16_t *cns; + ct_t g; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'f', '-'), + { NULL, 0, NULL, 0 } + }; + + memset(&g, 0, sizeof(ct_t)); + g.min_baseQ = 13; g.tid = -1; + while ((c = getopt_long(argc, argv, "f:Q:i:o:0:1:2:", lopts, NULL)) >= 0) { + switch (c) { + case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff + case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY + case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE + case '1': g_param.e[1][1] = atoi(optarg); break; + case '2': g_param.e[1][2] = atoi(optarg); break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + } + if (ga.reference) { + g.fai = fai_load(ga.reference); + if (g.fai == 0) fprintf(stderr, "[%s] fail to load the fasta index.\n", __func__); + } + if (usage || argc == optind) { + fprintf(stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] \n"); + sam_global_opt_help(stderr, "-.--f--."); + return 1; + } + l = max_l = 0; cns = 0; + g.fp = sam_open_format(argv[optind], "r", &ga.in); + if (g.fp == NULL) { + print_error_errno("targetcut", "can't open \"%s\"", argv[optind]); + return 1; + } + + g.h = sam_hdr_read(g.fp); + if (g.h == NULL) { + print_error("targetcut", "couldn't read header for \"%s\"", argv[optind]); + sam_close(g.fp); + return 1; + } + g.em = errmod_init(1. - ERR_DEP); + plp = bam_plp_init(read_aln, &g); + while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) { + if (tid < 0) break; + if (tid != lasttid) { // change of chromosome + if (cns) process_cns(g.h, lasttid, l, cns); + if (max_l < sam_hdr_tid2len(g.h, tid)) { + max_l = sam_hdr_tid2len(g.h, tid); + kroundup32(max_l); + cns = realloc(cns, max_l * 2); + } + l = sam_hdr_tid2len(g.h, tid); + memset(cns, 0, max_l * 2); + lasttid = tid; + } + cns[pos] = gencns(&g, n, p); + } + process_cns(g.h, lasttid, l, cns); + + if (n < 0) { + print_error("targetcut", "error reading from \"%s\"", argv[optind]); + status = EXIT_FAILURE; + } + + free(cns); + sam_hdr_destroy(g.h); + bam_plp_destroy(plp); + sam_close(g.fp); + if (g.fai) { + fai_destroy(g.fai); free(g.ref); + } + errmod_destroy(g.em); + free(g.bases); + sam_global_args_free(&ga); + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..babe42b751e46887fa31729ee892d34e3cc2fccf --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/cut_target.c.pysam.c @@ -0,0 +1,259 @@ +#include "samtools.pysam.h" + +/* cut_target.c -- targetcut subcommand. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2012-2013, 2015, 2016, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "samtools.h" +#include "sam_opts.h" + +#define ERR_DEP 0.83 + +typedef struct { + int e[2][3], p[2][2]; +} score_param_t; + +/* Note that although the two matrics have 10 parameters in total, only 4 + * (probably 3) are free. Changing the scoring matrices in a sort of symmetric + * way will not change the result. */ +static score_param_t g_param = { {{0,0,0},{-4,1,6}}, {{0,-14000}, {0,0}} }; + +typedef struct { + int min_baseQ, tid, max_bases; + uint16_t *bases; + samFile *fp; + sam_hdr_t *h; + char *ref; + hts_pos_t len; + faidx_t *fai; + errmod_t *em; +} ct_t; + +static uint16_t gencns(ct_t *g, int n, const bam_pileup1_t *plp) +{ + int i, j, ret, tmp, k, sum[4], qual; + float q[16]; + if (n > g->max_bases) { // enlarge g->bases + g->max_bases = n; + kroundup32(g->max_bases); + g->bases = realloc(g->bases, (size_t) g->max_bases * 2); + } + for (i = k = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint8_t *seq; + int q, baseQ, b; + if (p->is_refskip || p->is_del) continue; + baseQ = bam_get_qual(p->b)[p->qpos]; + if (baseQ < g->min_baseQ) continue; + seq = bam_get_seq(p->b); + b = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (b > 3) continue; + q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; + if (q < 4) q = 4; + if (q > 63) q = 63; + g->bases[k++] = q<<5 | bam_is_rev(p->b)<<4 | b; + } + if (k == 0) return 0; + errmod_cal(g->em, k, 4, g->bases, q); + for (i = 0; i < 4; ++i) sum[i] = (int)(q[i<<2|i] + .499) << 2 | i; + for (i = 1; i < 4; ++i) // insertion sort + for (j = i; j > 0 && sum[j] < sum[j-1]; --j) + tmp = sum[j], sum[j] = sum[j-1], sum[j-1] = tmp; + qual = (sum[1]>>2) - (sum[0]>>2); + k = k < 256? k : 255; + ret = (qual < 63? qual : 63) << 2 | (sum[0]&3); + return ret<<8|k; +} + +static void process_cns(sam_hdr_t *h, int tid, hts_pos_t l, uint16_t *cns) +{ + int64_t i, s; + int f[2][2], *prev, *curr, *swap_tmp; + uint8_t *b; // backtrack array + b = calloc(l, 1); + f[0][0] = f[0][1] = 0; + prev = f[0]; curr = f[1]; + // fill the backtrack matrix + for (i = 0; i < l; ++i) { + int c = (cns[i] == 0)? 0 : (cns[i]>>8 == 0)? 1 : 2; + int tmp0, tmp1; + // compute f[0] + tmp0 = prev[0] + g_param.e[0][c] + g_param.p[0][0]; // (s[i+1],s[i])=(0,0) + tmp1 = prev[1] + g_param.e[0][c] + g_param.p[1][0]; // (0,1) + if (tmp0 > tmp1) curr[0] = tmp0, b[i] = 0; + else curr[0] = tmp1, b[i] = 1; + // compute f[1] + tmp0 = prev[0] + g_param.e[1][c] + g_param.p[0][1]; // (s[i+1],s[i])=(1,0) + tmp1 = prev[1] + g_param.e[1][c] + g_param.p[1][1]; // (1,1) + if (tmp0 > tmp1) curr[1] = tmp0, b[i] |= 0<<1; + else curr[1] = tmp1, b[i] |= 1<<1; + // swap + swap_tmp = prev; prev = curr; curr = swap_tmp; + } + // backtrack + s = prev[0] > prev[1]? 0 : 1; + for (i = l - 1; i > 0; --i) { + b[i] |= s<<2; + s = b[i]>>s&1; + } + // print + for (i = 0, s = -1; i < INT64_MAX && i <= l; ++i) { + if (i == l || ((b[i]>>2&3) == 0 && s >= 0)) { + if (s >= 0) { + int64_t j; + 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); + for (j = s; j < i; ++j) { + int c = cns[j]>>8; + if (c == 0) fputc('N', samtools_stdout); + else fputc("ACGT"[c&3], samtools_stdout); + } + fputc('\t', samtools_stdout); + for (j = s; j < i; ++j) + fputc(33 + (cns[j]>>8>>2), samtools_stdout); + fputc('\n', samtools_stdout); + } + //if (s >= 0) fprintf(samtools_stdout, "%s\t%d\t%d\t%d\n", h->target_name[tid], s, i, i - s); + s = -1; + } else if ((b[i]>>2&3) && s < 0) s = i; + } + free(b); +} + +static int read_aln(void *data, bam1_t *b) +{ + ct_t *g = (ct_t*)data; + int ret; + while (1) + { + ret = sam_read1(g->fp, g->h, b); + if ( ret<0 ) break; + if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue; + if ( g->fai && b->core.tid >= 0 ) { + if (b->core.tid != g->tid) { // then load the sequence + free(g->ref); + g->ref = fai_fetch64(g->fai, sam_hdr_tid2name(g->h, b->core.tid), &g->len); + g->tid = b->core.tid; + } + sam_prob_realn(b, g->ref, g->len, 1<<1|1); + } + break; + } + return ret; +} + +int main_cut_target(int argc, char *argv[]) +{ + int c, tid, pos, n, lasttid = -1, usage = 0, status = EXIT_SUCCESS; + hts_pos_t l, max_l; + const bam_pileup1_t *p; + bam_plp_t plp; + uint16_t *cns; + ct_t g; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'f', '-'), + { NULL, 0, NULL, 0 } + }; + + memset(&g, 0, sizeof(ct_t)); + g.min_baseQ = 13; g.tid = -1; + while ((c = getopt_long(argc, argv, "f:Q:i:o:0:1:2:", lopts, NULL)) >= 0) { + switch (c) { + case 'Q': g.min_baseQ = atoi(optarg); break; // quality cutoff + case 'i': g_param.p[0][1] = -atoi(optarg); break; // 0->1 transition (in) PENALTY + case '0': g_param.e[1][0] = atoi(optarg); break; // emission SCORE + case '1': g_param.e[1][1] = atoi(optarg); break; + case '2': g_param.e[1][2] = atoi(optarg); break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + } + if (ga.reference) { + g.fai = fai_load(ga.reference); + if (g.fai == 0) fprintf(samtools_stderr, "[%s] fail to load the fasta index.\n", __func__); + } + if (usage || argc == optind) { + fprintf(samtools_stderr, "Usage: samtools targetcut [-Q minQ] [-i inPen] [-0 em0] [-1 em1] [-2 em2] \n"); + sam_global_opt_help(samtools_stderr, "-.--f--."); + return 1; + } + l = max_l = 0; cns = 0; + g.fp = sam_open_format(argv[optind], "r", &ga.in); + if (g.fp == NULL) { + print_error_errno("targetcut", "can't open \"%s\"", argv[optind]); + return 1; + } + + g.h = sam_hdr_read(g.fp); + if (g.h == NULL) { + print_error("targetcut", "couldn't read header for \"%s\"", argv[optind]); + sam_close(g.fp); + return 1; + } + g.em = errmod_init(1. - ERR_DEP); + plp = bam_plp_init(read_aln, &g); + while ((p = bam_plp_auto(plp, &tid, &pos, &n)) != 0) { + if (tid < 0) break; + if (tid != lasttid) { // change of chromosome + if (cns) process_cns(g.h, lasttid, l, cns); + if (max_l < sam_hdr_tid2len(g.h, tid)) { + max_l = sam_hdr_tid2len(g.h, tid); + kroundup32(max_l); + cns = realloc(cns, max_l * 2); + } + l = sam_hdr_tid2len(g.h, tid); + memset(cns, 0, max_l * 2); + lasttid = tid; + } + cns[pos] = gencns(&g, n, p); + } + process_cns(g.h, lasttid, l, cns); + + if (n < 0) { + print_error("targetcut", "error reading from \"%s\"", argv[optind]); + status = EXIT_FAILURE; + } + + free(cns); + sam_hdr_destroy(g.h); + bam_plp_destroy(plp); + sam_close(g.fp); + if (g.fai) { + fai_destroy(g.fai); free(g.ref); + } + errmod_destroy(g.em); + free(g.bases); + sam_global_args_free(&ga); + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/dict.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/dict.c new file mode 100644 index 0000000000000000000000000000000000000000..47cb842f3578ba32483f7e246f541446c98e5225 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/dict.c @@ -0,0 +1,229 @@ +/* dict.c -- create a sequence dictionary file. + + Copyright (C) 2015, 2020 Genome Research Ltd. + + Author: Shane McCarthy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include "htslib/khash.h" +#include "htslib/kseq.h" +#include "htslib/hts.h" +#include "samtools.h" + +KHASH_SET_INIT_STR(str) +KSEQ_INIT(gzFile, gzread) + +typedef struct _args_t +{ + char *output_fname, *alt_fname; + char *assembly, *species, *uri; + int alias, header; + khash_t(str) *is_alt; +} +args_t; + +static void write_dict(const char *fn, args_t *args) +{ + hts_md5_context *md5; + int l, i, k; + gzFile fp; + kseq_t *seq; + unsigned char digest[16]; + char hex[33]; + + fp = strcmp(fn, "-") ? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); + if (fp == 0) { + print_error_errno("dict", "Cannot open %s", fn); + exit(1); + } + FILE *out = stdout; + if (args->output_fname) { + out = fopen(args->output_fname, "w"); + if (out == NULL) { + print_error_errno("dict", "Cannot open %s for writing", args->output_fname); + exit(1); + } + } + + if (!(md5 = hts_md5_init())) + exit(1); + + seq = kseq_init(fp); + if (args->header) fprintf(out, "@HD\tVN:1.0\tSO:unsorted\n"); + while ((l = kseq_read(seq)) >= 0) { + for (i = k = 0; i < seq->seq.l; ++i) { + if (seq->seq.s[i] >= '!' && seq->seq.s[i] <= '~') + seq->seq.s[k++] = toupper(seq->seq.s[i]); + } + hts_md5_reset(md5); + hts_md5_update(md5, (unsigned char*)seq->seq.s, k); + hts_md5_final(digest, md5); + hts_md5_hex(hex, digest); + fprintf(out, "@SQ\tSN:%s\tLN:%d\tM5:%s", seq->name.s, k, hex); + if (args->is_alt && kh_get(str, args->is_alt, seq->name.s) != kh_end(args->is_alt)) + fprintf(out, "\tAH:*"); + if (args->alias) { + const char *name = seq->name.s; + if (strncmp(name, "chr", 3) == 0) { + name += 3; + fprintf(out, "\tAN:%s", name); + } + else + fprintf(out, "\tAN:chr%s", name); + + if (strcmp(name, "M") == 0) + fprintf(out, ",chrMT,MT"); + else if (strcmp(name, "MT") == 0) + fprintf(out, ",chrM,M"); + } + if (args->uri) + fprintf(out, "\tUR:%s", args->uri); + else if (strcmp(fn, "-") != 0) { +#ifdef _WIN32 + char *real_path = _fullpath(NULL, fn, PATH_MAX); +#else + char *real_path = realpath(fn, NULL); +#endif + fprintf(out, "\tUR:file://%s", real_path); + free(real_path); + } + if (args->assembly) fprintf(out, "\tAS:%s", args->assembly); + if (args->species) fprintf(out, "\tSP:%s", args->species); + fprintf(out, "\n"); + } + kseq_destroy(seq); + hts_md5_destroy(md5); + + if (args->output_fname) fclose(out); + gzclose(fp); +} + +static void read_alt_file(khash_t(str) *is_alt, const char *fname) +{ + htsFile *fp = hts_open(fname, "r"); + if (fp == NULL) { + print_error_errno("dict", "Cannot open %s", fname); + exit(1); + } + + // .alt files are in a SAM-like format, but we don't use sam_read1() + // as these files may not have a complete set of @SQ headers. + + kstring_t str = KS_INITIALIZE; + while (hts_getline(fp, KS_SEP_LINE, &str) >= 0) { + if (str.l == 0 || str.s[0] == '@') continue; + + char *tab = strchr(str.s, '\t'); + if (tab) *tab = '\0'; + + int ret; + char *seqname = strdup(str.s); + kh_put(str, is_alt, seqname, &ret); + if (ret == 0) free(seqname); // Already present + } + + ks_free(&str); + hts_close(fp); +} + +static int dict_usage(void) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: Create a sequence dictionary file from a fasta file\n"); + fprintf(stderr, "Usage: samtools dict [options] \n\n"); + fprintf(stderr, "Options: -a, --assembly STR assembly\n"); + fprintf(stderr, " -A, --alias, --alternative-name\n"); + fprintf(stderr, " add AN tag by adding/removing 'chr'\n"); + fprintf(stderr, " -H, --no-header do not print @HD line\n"); + fprintf(stderr, " -l, --alt FILE add AH:* tag to alternate locus sequences\n"); + fprintf(stderr, " -o, --output FILE file to write out dict file [stdout]\n"); + fprintf(stderr, " -s, --species STR species\n"); + fprintf(stderr, " -u, --uri STR URI [file:///abs/path/to/file.fa]\n"); + fprintf(stderr, "\n"); + return 1; +} + +int dict_main(int argc, char *argv[]) +{ + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->header = 1; + + static const struct option loptions[] = + { + {"help", no_argument, NULL, 'h'}, + {"no-header", no_argument, NULL, 'H'}, + {"alias", no_argument, NULL, 'A'}, + {"alt", required_argument, NULL, 'l'}, + {"alternative-name", no_argument, NULL, 'A'}, + {"assembly", required_argument, NULL, 'a'}, + {"species", required_argument, NULL, 's'}, + {"uri", required_argument, NULL, 'u'}, + {"output", required_argument, NULL, 'o'}, + {NULL, 0, NULL, 0} + }; + int c; + while ( (c=getopt_long(argc,argv,"?AhHa:l:s:u:o:",loptions,NULL))>0 ) + { + switch (c) + { + case 'A': args->alias = 1; break; + case 'a': args->assembly = optarg; break; + case 'l': args->alt_fname = optarg; break; + case 's': args->species = optarg; break; + case 'u': args->uri = optarg; break; + case 'o': args->output_fname = optarg; break; + case 'H': args->header = 0; break; + case 'h': return dict_usage(); + default: return dict_usage(); + } + } + + char *fname = NULL; + if ( optind>=argc ) + { + if ( !isatty(STDIN_FILENO) ) fname = "-"; // reading from stdin + else return dict_usage(); + } + else fname = argv[optind]; + + if (args->alt_fname) { + args->is_alt = kh_init(str); + read_alt_file(args->is_alt, args->alt_fname); + } + + write_dict(fname, args); + + if (args->is_alt) { + khint_t k; + for (k = 0; k < kh_end(args->is_alt); ++k) + if (kh_exist(args->is_alt, k)) free((char *) kh_key(args->is_alt, k)); + kh_destroy(str, args->is_alt); + } + + free(args); + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/faidx.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/faidx.c new file mode 100644 index 0000000000000000000000000000000000000000..63204d1460f786aaa07e467b88244a19a44b73e9 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/faidx.c @@ -0,0 +1,424 @@ +/* faidx.c -- faidx subcommand. + + Copyright (C) 2008, 2009, 2013, 2016, 2018-2020, 2022 Genome Research Ltd. + Portions copyright (C) 2011 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +History: + + * 2016-01-12: Pierre Lindenbaum @yokofakun : added options -o -n + +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "samtools.h" + +// Negative indicates the same as input data +#define DEFAULT_FASTA_LINE_LEN -60 + +#ifndef ABS +# define ABS(x) ((x)>=0?(x):-(x)) +#endif + +static unsigned char comp_base[256] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, '!', '"', '#', '$', '%', '&', '\'','(', ')', '*', '+', ',', '-', '.', '/', +'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', +'@', 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O', +'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', '[', '\\',']', '^', '_', +'`', 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o', +'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', '{', '|', '}', '~', 127, +128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, +144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, +160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, +176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, +192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, +208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, +224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, +240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, +}; + +static void reverse_complement(char *str, const hts_pos_t len) { + char c; + hts_pos_t i = 0, j = len - 1; + + while (i <= j) { + c = str[i]; + str[i] = comp_base[(unsigned char)str[j]]; + str[j] = comp_base[(unsigned char)c]; + i++; + j--; + } +} + +static void reverse(char *str, const hts_pos_t len) { + char c; + hts_pos_t i = 0, j = len - 1; + + while (i < j) { + c = str[i]; + str[i] = str[j]; + str[j] = c; + i++; + j--; + } +} + + +static int write_line(faidx_t *faid, FILE *file, const char *line, const char *name, + const int ignore, const hts_pos_t length, const hts_pos_t seq_len) { + int id; + hts_pos_t beg, end; + + if (seq_len < 0) { + fprintf(stderr, "[faidx] Failed to fetch sequence in %s\n", name); + + if (ignore && seq_len == -2) { + return EXIT_SUCCESS; + } else { + return EXIT_FAILURE; + } + } else if (seq_len == 0) { + fprintf(stderr, "[faidx] Zero length sequence: %s\n", name); + } else if (fai_parse_region(faid, name, &id, &beg, &end, 0) + && (end < HTS_POS_MAX) && (seq_len != end - beg)) { + fprintf(stderr, "[faidx] Truncated sequence: %s\n", name); + } + + hts_pos_t i, seq_sz = seq_len; + + for (i = 0; i < seq_sz; i += length) + { + hts_pos_t len = i + length < seq_sz ? length : seq_sz - i; + if (fwrite(line + i, 1, len, file) < len || + fputc('\n', file) == EOF) { + print_error_errno("faidx", "failed to write output"); + return EXIT_FAILURE; + } + } + + return EXIT_SUCCESS; +} + + +static int write_output(faidx_t *faid, FILE *file, const char *name, const int ignore, + const hts_pos_t length, const int rev, + const char *pos_strand_name, const char *neg_strand_name, + enum fai_format_options format) { + hts_pos_t seq_len, wrap_len = length; + if (wrap_len < 0) + wrap_len = fai_line_length(faid, name); + if (wrap_len <= 0) + wrap_len = HTS_POS_MAX; + char *seq = fai_fetch64(faid, name, &seq_len); + + if (format == FAI_FASTA) { + fprintf(file, ">%s%s\n", name, rev ? neg_strand_name : pos_strand_name); + } else { + fprintf(file, "@%s%s\n", name, rev ? neg_strand_name : pos_strand_name); + } + + if (rev && seq_len > 0) { + reverse_complement(seq, seq_len); + } + + if (write_line(faid, file, seq, name, ignore, wrap_len, seq_len) + == EXIT_FAILURE) { + free(seq); + return EXIT_FAILURE; + } + + free(seq); + + if (format == FAI_FASTQ) { + fprintf(file, "+\n"); + + char *qual = fai_fetchqual64(faid, name, &seq_len); + + if (rev && seq_len > 0) { + reverse(qual, seq_len); + } + + if (write_line(faid, file, qual, name, ignore, wrap_len, seq_len) + == EXIT_FAILURE) { + free(qual); + return EXIT_FAILURE; + } + + free(qual); + } + + return EXIT_SUCCESS; +} + + +static int read_regions_from_file(faidx_t *faid, hFILE *in_file, FILE *file, const int ignore, + const hts_pos_t length, const int rev, + const char *pos_strand_name, + const char *neg_strand_name, + enum fai_format_options format) { + kstring_t line = {0, 0, NULL}; + int ret = EXIT_FAILURE; + + while (line.l = 0, kgetline(&line, (kgets_func *)hgets, in_file) >= 0) { + if ((ret = write_output(faid, file, line.s, ignore, length, rev, pos_strand_name, neg_strand_name, format)) == EXIT_FAILURE) { + break; + } + } + + free(line.s); + + return ret; +} + +static int usage(FILE *fp, enum fai_format_options format, int exit_status) +{ + char *tool, *file_type, *index_name; + + if (format == FAI_FASTA) { + tool = "faidx "; + file_type = "FASTA"; + index_name = "file.fa"; + } else { + tool = "fqidx "; + file_type = "FASTQ"; + index_name = "file.fq"; + } + + fprintf(fp, "Usage: samtools %s [ [...]]\n", tool); + fprintf(fp, "Option: \n" + " -o, --output FILE Write %s to file.\n" + " -n, --length INT Length of %s sequence line. [60]\n" + " -c, --continue Continue after trying to retrieve missing region.\n" + " -r, --region-file FILE File of regions. Format is chr:from-to. One per line.\n" + " -i, --reverse-complement Reverse complement sequences.\n" + " --mark-strand TYPE Add strand indicator to sequence name\n" + " TYPE = rc for /rc on negative strand (default)\n" + " no for no strand indicator\n" + " sign for (+) / (-)\n" + " custom,, for custom indicator\n" + " --fai-idx FILE name of the index file (default %s.fai).\n" + " --gzi-idx FILE name of compressed file index (default %s.gz.gzi).\n", + file_type, file_type, index_name, index_name); + + + if (format == FAI_FASTA) { + fprintf(fp, " -f, --fastq File and index in FASTQ format.\n"); + } + + fprintf(fp, " -h, --help This message.\n"); + + return exit_status; +} + +int faidx_core(int argc, char *argv[], enum fai_format_options format) +{ + int c, ignore_error = 0, rev = 0; + hts_pos_t line_len = DEFAULT_FASTA_LINE_LEN ;/* fasta line len */ + char* output_file = NULL; /* output file (default is stdout ) */ + char *region_file = NULL; // list of regions from file, one per line + char *pos_strand_name = ""; // Extension to add to name for +ve strand + char *neg_strand_name = "/rc"; // Extension to add to name for -ve strand + char *strand_names = NULL; // Used for custom strand annotation + char *fai_name = NULL; // specified index name + char *gzi_name = NULL; // specified compressed index name + FILE* file_out = stdout;/* output stream */ + + static const struct option lopts[] = { + { "output", required_argument, NULL, 'o' }, + { "help", no_argument, NULL, 'h' }, + { "length", required_argument, NULL, 'n' }, + { "continue", no_argument, NULL, 'c' }, + { "region-file", required_argument, NULL, 'r' }, + { "fastq", no_argument, NULL, 'f' }, + { "reverse-complement", no_argument, NULL, 'i' }, + { "mark-strand", required_argument, NULL, 1000 }, + { "fai-idx", required_argument, NULL, 1001 }, + { "gzi-idx", required_argument, NULL, 1002 }, + { NULL, 0, NULL, 0 } + }; + + while ((c = getopt_long(argc, argv, "ho:n:cr:fi", lopts, NULL)) >= 0) { + switch (c) { + case 'o': output_file = optarg; break; + case 'n': line_len = strtol(optarg, NULL, 10); + if (line_len < 0) { + fprintf(stderr,"[faidx] bad line length '%s', using default:%d\n",optarg,ABS(DEFAULT_FASTA_LINE_LEN)); + line_len= ABS(DEFAULT_FASTA_LINE_LEN); + } + break; + case 'c': ignore_error = 1; break; + case 'r': region_file = optarg; break; + case 'f': format = FAI_FASTQ; break; + case 'i': rev = 1; break; + case '?': return usage(stderr, format, EXIT_FAILURE); + case 'h': return usage(stdout, format, EXIT_SUCCESS); + case 1000: + if (strcmp(optarg, "no") == 0) { + pos_strand_name = neg_strand_name = ""; + } else if (strcmp(optarg, "sign") == 0) { + pos_strand_name = "(+)"; + neg_strand_name = "(-)"; + } else if (strcmp(optarg, "rc") == 0) { + pos_strand_name = ""; + neg_strand_name = "/rc"; + } else if (strncmp(optarg, "custom,", 7) == 0) { + size_t len = strlen(optarg + 7); + size_t comma = strcspn(optarg + 7, ","); + free(strand_names); + strand_names = pos_strand_name = malloc(len + 2); + if (!strand_names) { + fprintf(stderr, "[faidx] Out of memory\n"); + return EXIT_FAILURE; + } + neg_strand_name = pos_strand_name + comma + 1; + memcpy(pos_strand_name, optarg + 7, comma); + pos_strand_name[comma] = '\0'; + if (comma < len) + memcpy(neg_strand_name, optarg + 7 + comma + 1, + len - comma); + neg_strand_name[len - comma] = '\0'; + } else { + fprintf(stderr, "[faidx] Unknown --mark-strand option \"%s\"\n", optarg); + return usage(stderr, format, EXIT_FAILURE); + } + break; + case 1001: fai_name = optarg; break; + case 1002: gzi_name = optarg; break; + default: break; + } + } + + if ( argc==optind ) + return usage(stdout, format, EXIT_SUCCESS); + + if (optind+1 == argc && !region_file) { + if (output_file && !fai_name) + fai_name = output_file; + + if (fai_build3(argv[optind], fai_name, gzi_name) != 0) { + if (fai_name) + fprintf(stderr, "[faidx] Could not build fai index %s", fai_name); + else + fprintf(stderr, "[faidx] Could not build fai index %s.fai", argv[optind]); + + if (gzi_name) + fprintf(stderr, " or compressed index %s\n", gzi_name); + else + fprintf(stderr, "\n"); + + return EXIT_FAILURE; + } + + return 0; + } + + faidx_t *fai = fai_load3_format(argv[optind], fai_name, gzi_name, FAI_CREATE, format); + + if (!fai) { + if (fai_name) + fprintf(stderr, "[faidx] Could not load fai index %s", fai_name); + else + fprintf(stderr, "[faidx] Could not build fai index %s.fai", argv[optind]); + + if (gzi_name) + fprintf(stderr, " or compressed index %s\n", gzi_name); + else + fprintf(stderr, "\n"); + + return EXIT_FAILURE; + } + + /** output file provided by user */ + if( output_file != NULL ) { + if( strcmp( output_file, argv[optind] ) == 0 ) { + fprintf(stderr,"[faidx] Same input/output : %s\n", output_file); + return EXIT_FAILURE; + } + + file_out = fopen( output_file, "w" ); + + if( file_out == NULL) { + fprintf(stderr,"[faidx] Cannot open \"%s\" for writing :%s.\n", output_file, strerror(errno) ); + return EXIT_FAILURE; + } + } + + int exit_status = EXIT_SUCCESS; + + if (region_file) { + hFILE *rf; + + if ((rf = hopen(region_file, "r"))) { + exit_status = read_regions_from_file(fai, rf, file_out, ignore_error, line_len, rev, pos_strand_name, neg_strand_name, format); + + if (hclose(rf) != 0) { + fprintf(stderr, "[faidx] Warning: failed to close %s", region_file); + } + } else { + fprintf(stderr, "[faidx] Failed to open \"%s\" for reading.\n", region_file); + exit_status = EXIT_FAILURE; + } + } + + while ( ++optind + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "sam_opts.h" +#include "samtools.h" + +#define bam_reg2bin(b,e) hts_reg2bin((b),(e), 14, 5) + +static int replace_cigar(bam1_t *b, uint32_t n, uint32_t *cigar) +{ + int diff = 0; + if (n != b->core.n_cigar) { + int o = b->core.l_qname + b->core.n_cigar * 4; + if (n > b->core.n_cigar) { + diff = (n - b->core.n_cigar) * 4; + if ((INT_MAX - b->l_data)/4 < (n - b->core.n_cigar)) { + fprintf(stderr, "[depad] ERROR: BAM record too big\n"); + return -1; + } + if (b->l_data + diff > b->m_data) { + b->m_data = b->l_data + diff; + kroundup32(b->m_data); + uint8_t *tmp = (uint8_t*)realloc(b->data, b->m_data); + if (!tmp) { + fprintf(stderr, "[depad] ERROR: Memory allocation failure.\n"); + return -1; + } + b->data = tmp; + } + } else { + diff = -(int)((b->core.n_cigar - n) * 4); + } + memmove(b->data + b->core.l_qname + n * 4, b->data + o, b->l_data - o); + b->core.n_cigar = n; + } + + memcpy(b->data + b->core.l_qname, cigar, n * 4); + b->l_data += diff; + + return 0; +} + +#define write_cigar(_c, _n, _m, _v) do { \ + if (_n == _m) { \ + _m = _m? _m<<1 : 4; \ + _c = (uint32_t*)realloc(_c, _m * 4); \ + if (!(_c)) { \ + fprintf(stderr, "[depad] ERROR: Memory allocation failure.\n"); \ + return -1; \ + } \ + } \ + _c[_n++] = (_v); \ + } while (0) + +static int unpad_seq(bam1_t *b, kstring_t *s) +{ + // Returns 0 on success, -1 on an error + int k, j, i; + int length; + int cigar_n_warning = 0; /* Make this a global and limit to one CIGAR N warning? */ + uint32_t *cigar = bam_get_cigar(b); + uint8_t *seq = bam_get_seq(b); + + // b->core.l_qseq gives length of the SEQ entry (including soft clips, S) + // We need the padded length after alignment from the CIGAR (excluding + // soft clips S, but including pads from CIGAR D operations) + length = bam_cigar2rlen(b->core.n_cigar, cigar); + ks_resize(s, length); + for (k = 0, s->l = 0, j = 0; k < b->core.n_cigar; ++k) { + int op, ol; + op = bam_cigar_op(cigar[k]); + ol = bam_cigar_oplen(cigar[k]); + if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { + for (i = 0; i < ol; ++i, ++j) s->s[s->l++] = bam_seqi(seq, j); + } else if (op == BAM_CSOFT_CLIP) { + j += ol; + } else if (op == BAM_CHARD_CLIP) { + /* do nothing */ + } else if (op == BAM_CDEL) { + for (i = 0; i < ol; ++i) s->s[s->l++] = 0; + } else if (op == BAM_CREF_SKIP) { + /* Treat CIGAR N as D (not ideal, but better than ignoring it) */ + for (i = 0; i < ol; ++i) s->s[s->l++] = 0; + if (0 == cigar_n_warning) { + cigar_n_warning = -1; + fprintf(stderr, "[depad] WARNING: CIGAR op N treated as op D in read %s\n", bam_get_qname(b)); + } + } else { + fprintf(stderr, "[depad] ERROR: Didn't expect CIGAR op %c in read %s\n", BAM_CIGAR_STR[op], bam_get_qname(b)); + return -1; + } + } + return length != s->l; +} + +int load_unpadded_ref(faidx_t *fai, const char *ref_name, hts_pos_t ref_len, kstring_t *seq) +{ + char base; + char *fai_ref = 0; + hts_pos_t fai_ref_len = 0, k; + + fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len); + if (fai_ref_len != ref_len) { + fprintf(stderr, "[depad] ERROR: FASTA sequence %s length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, ref_len); + free(fai_ref); + return -1; + } + ks_resize(seq, ref_len); + seq->l = 0; + for (k = 0; k < ref_len; ++k) { + base = fai_ref[k]; + if (base == '-' || base == '*') { + // Map gaps to null to match unpad_seq function + seq->s[seq->l++] = 0; + } else { + int i = seq_nt16_table[(int)base]; + if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 + fprintf(stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence %s\n", base, (int)base, ref_name); + free(fai_ref); + return -1; + } + seq->s[seq->l++] = i; + } + } + assert(ref_len == seq->l); + free(fai_ref); + return 0; +} + +hts_pos_t get_unpadded_len(faidx_t *fai, const char *ref_name, hts_pos_t padded_len) +{ + char base; + char *fai_ref = 0; + hts_pos_t fai_ref_len = 0, k; + hts_pos_t bases=0, gaps=0; + + fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len); + if (fai_ref_len != padded_len) { + fprintf(stderr, "[depad] ERROR: FASTA sequence '%s' length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, padded_len); + free(fai_ref); + return -1; + } + for (k = 0; k < padded_len; ++k) { + //fprintf(stderr, "[depad] checking base %i of %i or %i\n", k+1, ref_len, strlen(fai_ref)); + base = fai_ref[k]; + if (base == '-' || base == '*') { + gaps += 1; + } else { + int i = seq_nt16_table[(int)base]; + if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 + fprintf(stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence '%s'\n", base, (int)base, ref_name); + free(fai_ref); + return -1; + } + bases += 1; + } + } + free(fai_ref); + assert (padded_len == bases + gaps); + return bases; +} + +static inline int * update_posmap(int *posmap, kstring_t ref) +{ + int i, k; + posmap = realloc(posmap, ref.m * sizeof(int)); + for (i = k = 0; i < ref.l; ++i) { + posmap[i] = k; + if (ref.s[i]) ++k; + } + return posmap; +} + +int bam_pad2unpad(samFile *in, samFile *out, sam_hdr_t *h, faidx_t *fai) +{ + bam1_t *b = 0; + kstring_t r, q; + int r_tid = -1; + uint32_t *cigar2 = 0; + int ret = 0, *posmap = 0; + uint32_t n2 = 0, m2 = 0; + + b = bam_init1(); + if (!b) { + fprintf(stderr, "[depad] Couldn't allocate bam struct\n"); + return -1; + } + r.l = r.m = q.l = q.m = 0; r.s = q.s = 0; + int read_ret; + while ((read_ret = sam_read1(in, h, b)) >= 0) { // read one alignment from `in' + // Cannot depad unmapped CRAM data + if (b->core.flag & BAM_FUNMAP) + goto next_seq; + + uint32_t *cigar = bam_get_cigar(b); + n2 = 0; + if (b->core.pos == 0 && b->core.tid >= 0 && strcmp(bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid)) == 0) { + // fprintf(stderr, "[depad] Found embedded reference '%s'\n", bam_get_qname(b)); + r_tid = b->core.tid; + if (0!=unpad_seq(b, &r)) { + fprintf(stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in reference %s\n", bam_get_qname(b)); + return -1; + }; + if (sam_hdr_tid2len(h, r_tid) != r.l) { + fprintf(stderr, "[depad] ERROR: (Padded) length of '%s' is %"PRId64" in BAM header, but %zu in embedded reference\n", bam_get_qname(b), (int64_t) sam_hdr_tid2len(h, r_tid), r.l); + return -1; + } + if (fai) { + // Check the embedded reference matches the FASTA file + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &q)) { + fprintf(stderr, "[depad] ERROR: Failed to load embedded reference '%s' from FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + assert(r.l == q.l); + int i; + for (i = 0; i < r.l; ++i) { + if (r.s[i] != q.s[i]) { + // Show gaps as ASCII 45 + fprintf(stderr, "[depad] ERROR: Embedded sequence and reference FASTA don't match for %s base %i, '%c' vs '%c'\n", + sam_hdr_tid2name(h, b->core.tid), i+1, + r.s[i] ? seq_nt16_str[(int)r.s[i]] : 45, + q.s[i] ? seq_nt16_str[(int)q.s[i]] : 45); + return -1; + } + } + } + write_cigar(cigar2, n2, m2, bam_cigar_gen(b->core.l_qseq, BAM_CMATCH)); + if (replace_cigar(b, n2, cigar2) < 0) + return -1; + posmap = update_posmap(posmap, r); + } else if (b->core.n_cigar > 0) { + int i, k, op; + if (b->core.tid < 0) { + fprintf(stderr, "[depad] ERROR: Read '%s' has CIGAR but no RNAME\n", bam_get_qname(b)); + return -1; + } else if (b->core.tid == r_tid) { + ; // good case, reference available + //fprintf(stderr, "[depad] Have ref '%s' for read '%s'\n", h->target_name[b->core.tid], bam_get_qname(b)); + } else if (fai) { + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) { + fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + posmap = update_posmap(posmap, r); + r_tid = b->core.tid; + // fprintf(stderr, "[depad] Loaded %s from FASTA file\n", h->target_name[b->core.tid]); + } else { + fprintf(stderr, "[depad] ERROR: Missing %s embedded reference sequence (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + if (0!=unpad_seq(b, &q)) { + fprintf(stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in read %s\n", bam_get_qname(b)); + return -1; + }; + if (bam_cigar_op(cigar[0]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[0]); + } else if (bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) { + write_cigar(cigar2, n2, m2, cigar[0]); + if (b->core.n_cigar > 2 && bam_cigar_op(cigar[1]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[1]); + } + } + /* Determine CIGAR operator for each base in the aligned read */ + for (i = 0, k = b->core.pos; i < q.l; ++i, ++k) + q.s[i] = q.s[i]? (r.s[k]? BAM_CMATCH : BAM_CINS) : (r.s[k]? BAM_CDEL : BAM_CPAD); + /* Include any pads if starts with an insert */ + if (q.s[0] == BAM_CINS) { + for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k); + if (k) write_cigar(cigar2, n2, m2, bam_cigar_gen(k, BAM_CPAD)); + k = 0; + } else if (q.s[0] == BAM_CPAD) { + // Join 'k' CPAD to our first cigar op CPAD too. + for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k); + } else { + k = 0; + } + /* Count consecutive CIGAR operators to turn into a CIGAR string */ + for (i = 1, k++, op = q.s[0]; i < q.l; ++i) { + if (op != q.s[i]) { + write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); + op = q.s[i]; k = 1; + } else ++k; + } + write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); + if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); + } else if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CHARD_CLIP) { + if (b->core.n_cigar > 2 && bam_cigar_op(cigar[b->core.n_cigar-2]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-2]); + } + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); + } + /* Remove redundant P operators between M/X/=/D operators, e.g. 5M2P10M -> 15M */ + int pre_op, post_op; + for (i = 2; i < n2; ++i) + if (bam_cigar_op(cigar2[i-1]) == BAM_CPAD) { + pre_op = bam_cigar_op(cigar2[i-2]); + post_op = bam_cigar_op(cigar2[i]); + /* Note don't need to check for X/= as code above will use M only */ + if ((pre_op == BAM_CMATCH || pre_op == BAM_CDEL) && (post_op == BAM_CMATCH || post_op == BAM_CDEL)) { + /* This is a redundant P operator */ + cigar2[i-1] = 0; // i.e. 0M + /* If had same operator either side, combine them in post_op */ + if (pre_op == post_op) { + /* If CIGAR M, could treat as simple integers since BAM_CMATCH is zero*/ + cigar2[i] = bam_cigar_gen(bam_cigar_oplen(cigar2[i-2]) + bam_cigar_oplen(cigar2[i]), post_op); + cigar2[i-2] = 0; // i.e. 0M + } + } + } + /* Remove the zero'd operators (0M) */ + for (i = k = 0; i < n2; ++i) + if (cigar2[i]) cigar2[k++] = cigar2[i]; + n2 = k; + if (replace_cigar(b, n2, cigar2) < 0) + return -1; + } + /* Even unmapped reads can have a POS value, e.g. if their mate was mapped */ + if (b->core.pos != -1) b->core.pos = posmap[b->core.pos]; + if (b->core.mtid < 0 || b->core.mpos < 0) { + /* Nice case, no mate to worry about*/ + // fprintf(stderr, "[depad] Read '%s' mate not mapped\n", bam_get_qname(b)); + /* TODO - Warning if FLAG says mate should be mapped? */ + /* Clean up funny input where mate position is given but mate reference is missing: */ + b->core.mtid = -1; + b->core.mpos = -1; + } else if (b->core.mtid == b->core.tid) { + /* Nice case, same reference */ + // fprintf(stderr, "[depad] Read '%s' mate mapped to same ref\n", bam_get_qname(b)); + b->core.mpos = posmap[b->core.mpos]; + } else { + /* Nasty case, Must load alternative posmap */ + // fprintf(stderr, "[depad] Loading reference '%s' temporarily\n", h->target_name[b->core.mtid]); + if (!fai) { + fprintf(stderr, "[depad] ERROR: Needed reference %s sequence for mate (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.mtid)); + return -1; + } + /* Temporarily load the other reference sequence */ + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.mtid), sam_hdr_tid2len(h, b->core.mtid), &r)) { + fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.mtid)); + return -1; + } + posmap = update_posmap(posmap, r); + b->core.mpos = posmap[b->core.mpos]; + /* Restore the reference and posmap*/ + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) { + fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + posmap = update_posmap(posmap, r); + } + /* Most reads will have been moved so safest to always recalculate the BIN value */ + b->core.bin = bam_reg2bin(b->core.pos, bam_endpos(b)); + + next_seq: + if (sam_write1(out, h, b) < 0) { + print_error_errno("depad", "error writing to output"); + return -1; + } + } + if (read_ret < -1) { + fprintf(stderr, "[depad] truncated file.\n"); + ret = 1; + } + free(r.s); free(q.s); free(posmap); + free(cigar2); + bam_destroy1(b); + return ret; +} + +sam_hdr_t * fix_header(sam_hdr_t *old, faidx_t *fai) +{ + int i = 0, ret = 0; + hts_pos_t unpadded_len = 0; + sam_hdr_t *header = sam_hdr_dup(old); + if (!header) + return NULL; + + int nref = sam_hdr_nref(old); + char len_buf[64]; + + for (i = 0; i < nref; ++i) { + unpadded_len = get_unpadded_len(fai, sam_hdr_tid2name(old, i), sam_hdr_tid2len(old, i)); + if (unpadded_len < 0) { + fprintf(stderr, "[depad] ERROR getting unpadded length of '%s', padded length %"PRIhts_pos"\n", sam_hdr_tid2name(old, i), (hts_pos_t) sam_hdr_tid2len(old, i)); + } else if (unpadded_len > sam_hdr_tid2len(old, i)) { + fprintf(stderr, "[depad] New unpadded length of '%s' is larger than the padded length (%"PRIhts_pos" > %"PRIhts_pos")\n", + sam_hdr_tid2name(old, i), unpadded_len, + (hts_pos_t) sam_hdr_tid2len(old, i)); + ret = 1; + } else { + sprintf(len_buf, "%"PRIhts_pos"", unpadded_len); + if ((ret |= sam_hdr_update_line(header, "SQ", "SN", sam_hdr_tid2name(header, i), "LN", len_buf, NULL))) + fprintf(stderr, "[depad] Error updating length of '%s' from %"PRIhts_pos" to %"PRIhts_pos"\n", + sam_hdr_tid2name(header, i), + (hts_pos_t) sam_hdr_tid2len(header, i), + unpadded_len); + //fprintf(stderr, "[depad] Recalculating '%s' length %i -> %i\n", old->target_name[i], old->target_len[i], header->target_len[i]); + } + } + + if (ret) { + sam_hdr_destroy(header); + return NULL; + } + + return header; +} + +static int usage(int is_long_help); + +int main_pad2unpad(int argc, char *argv[]) +{ + samFile *in = 0, *out = 0; + sam_hdr_t *h = 0, *h_fix = 0; + faidx_t *fai = 0; + int c, compress_level = -1, is_long_help = 0, no_pg = 0; + char in_mode[5], out_mode[6], *fn_out = 0, *fn_fai = 0, *fn_out_idx = NULL; + int ret=0; + char *arg_list = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 'T', '-'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + /* parse command-line options */ + strcpy(in_mode, "r"); strcpy(out_mode, "w"); + while ((c = getopt_long(argc, argv, "SCso:u1T:?", lopts, NULL)) >= 0) { + switch (c) { + case 'S': break; + case 'C': hts_parse_format(&ga.out, "cram"); break; + case 's': assert(compress_level == -1); hts_parse_format(&ga.out, "sam"); break; + case 'o': fn_out = strdup(optarg); break; + case 'u': + compress_level = 0; + if (ga.out.format == unknown_format) + hts_parse_format(&ga.out, "bam"); + break; + case '1': + compress_level = 1; + if (ga.out.format == unknown_format) + hts_parse_format(&ga.out, "bam"); + break; + case 1: no_pg = 1; break; + case '?': is_long_help = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c); + return usage(is_long_help); + } + } + if (argc == optind) return usage(is_long_help); + + strcat(out_mode, "h"); + if (compress_level >= 0) { + char tmp[2]; + tmp[0] = compress_level + '0'; tmp[1] = '\0'; + strcat(out_mode, tmp); + } + + // Load FASTA reference (also needed for SAM -> BAM if missing header) + if (ga.reference) { + fn_fai = fai_path(ga.reference); + fai = fai_load3(ga.reference, fn_fai, NULL, FAI_CREATE); + } + // open file handlers + if ((in = sam_open_format(argv[optind], in_mode, &ga.in)) == 0) { + print_error_errno("depad", "failed to open \"%s\" for reading", argv[optind]); + ret = 1; + goto depad_end; + } + if (fn_fai && hts_set_fai_filename(in, fn_fai) != 0) { + fprintf(stderr, "[depad] failed to load reference file \"%s\".\n", fn_fai); + ret = 1; + goto depad_end; + } + if ((h = sam_hdr_read(in)) == 0) { + fprintf(stderr, "[depad] failed to read the header from \"%s\".\n", argv[optind]); + ret = 1; + goto depad_end; + } + if (fai) { + if (!(h_fix = fix_header(h, fai))){ + fprintf(stderr, "[depad] failed to fix the header from\n"); + ret = 1; + goto depad_end; + } + } else { + fprintf(stderr, "[depad] Warning - reference lengths will not be corrected without FASTA reference\n"); + h_fix = h; + } + char wmode[2]; + strcat(out_mode, sam_open_mode(wmode, fn_out, NULL)==0 ? wmode : "b"); + if ((out = sam_open_format(fn_out? fn_out : "-", out_mode, &ga.out)) == 0) { + print_error_errno("depad", "failed to open \"%s\" for writing", fn_out? fn_out : "standard output"); + ret = 1; + goto depad_end; + } + + // Reference-based CRAM won't work unless we also create a new reference. + // We could embed this, but for now we take the easy option. + if (ga.out.format == cram) + hts_set_opt(out, CRAM_OPT_NO_REF, 1); + + if (!no_pg) { + if(!(arg_list = stringify_argv(argc+1, argv-1))) { + fprintf(stderr, "[depad] failed to create arg_list\n"); + ret = 1; + goto depad_end; + } + + if (sam_hdr_add_pg(h_fix, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + fprintf(stderr, "[depad] failed to add PG line to header\n"); + ret = 1; + goto depad_end; + } + } + + if (sam_hdr_write(out, h_fix) != 0) { + fprintf(stderr, "[depad] failed to write header.\n"); + ret = 1; + goto depad_end; + } + if (ga.write_index) { + if (!(fn_out_idx = auto_index(out, fn_out, h_fix))) { + ret = 1; + goto depad_end; + } + } + + // Do the depad + if (bam_pad2unpad(in, out, h, fai) != 0) ret = 1; + + if (ga.write_index) { + if (sam_idx_save(out) < 0) { + print_error_errno("depad", "writing index failed"); + ret = 1; + } + } + +depad_end: + // close files, free and return + free(arg_list); + if (fai) fai_destroy(fai); + if (h) sam_hdr_destroy(h); + if (h_fix && h_fix != h) sam_hdr_destroy(h_fix); + if (in) sam_close(in); + if (out && sam_close(out) < 0) { + fprintf(stderr, "[depad] error on closing output file.\n"); + ret = 1; + } + free(fn_fai); free(fn_out); + if (fn_out_idx) + free(fn_out_idx); + sam_global_args_free(&ga); + return ret; +} + +static int usage(int is_long_help) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: samtools depad \n\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " -s Output is SAM (default is BAM)\n"); + fprintf(stderr, " -S Input is SAM (default is BAM)\n"); + fprintf(stderr, " -u Uncompressed BAM output (can't use with -s)\n"); + fprintf(stderr, " -1 Fast compression BAM output (can't use with -s)\n"); + fprintf(stderr, " -T, --reference FILE\n"); + fprintf(stderr, " Padded reference sequence file [null]\n"); + fprintf(stderr, " -o FILE Output file name [stdout]\n"); + fprintf(stderr, " --no-PG do not add a PG line\n"); + fprintf(stderr, " -? Longer help\n"); + sam_global_opt_help(stderr, "-...--.."); + + if (is_long_help) + fprintf(stderr, +"Notes:\n" +"\n" +"1. Requires embedded reference sequences (before the reads for that reference),\n" +" or ideally a FASTA file of the padded reference sequences (via a -T option).\n" +"\n" +"2. Input padded alignment reads' CIGAR strings must not use P or I operators.\n" +"\n"); + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/padding.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/padding.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..e90255fb38fd7c92af4f7192da9023ee198ddc34 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/padding.c.pysam.c @@ -0,0 +1,625 @@ +#include "samtools.pysam.h" + +/* padding.c -- depad subcommand. + + Copyright (C) 2011, 2012 Broad Institute. + Copyright (C) 2014-2016, 2019-2020 Genome Research Ltd. + Portions copyright (C) 2012, 2013 Peter Cock, The James Hutton Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include "sam_opts.h" +#include "samtools.h" + +#define bam_reg2bin(b,e) hts_reg2bin((b),(e), 14, 5) + +static int replace_cigar(bam1_t *b, uint32_t n, uint32_t *cigar) +{ + int diff = 0; + if (n != b->core.n_cigar) { + int o = b->core.l_qname + b->core.n_cigar * 4; + if (n > b->core.n_cigar) { + diff = (n - b->core.n_cigar) * 4; + if ((INT_MAX - b->l_data)/4 < (n - b->core.n_cigar)) { + fprintf(samtools_stderr, "[depad] ERROR: BAM record too big\n"); + return -1; + } + if (b->l_data + diff > b->m_data) { + b->m_data = b->l_data + diff; + kroundup32(b->m_data); + uint8_t *tmp = (uint8_t*)realloc(b->data, b->m_data); + if (!tmp) { + fprintf(samtools_stderr, "[depad] ERROR: Memory allocation failure.\n"); + return -1; + } + b->data = tmp; + } + } else { + diff = -(int)((b->core.n_cigar - n) * 4); + } + memmove(b->data + b->core.l_qname + n * 4, b->data + o, b->l_data - o); + b->core.n_cigar = n; + } + + memcpy(b->data + b->core.l_qname, cigar, n * 4); + b->l_data += diff; + + return 0; +} + +#define write_cigar(_c, _n, _m, _v) do { \ + if (_n == _m) { \ + _m = _m? _m<<1 : 4; \ + _c = (uint32_t*)realloc(_c, _m * 4); \ + if (!(_c)) { \ + fprintf(samtools_stderr, "[depad] ERROR: Memory allocation failure.\n"); \ + return -1; \ + } \ + } \ + _c[_n++] = (_v); \ + } while (0) + +static int unpad_seq(bam1_t *b, kstring_t *s) +{ + // Returns 0 on success, -1 on an error + int k, j, i; + int length; + int cigar_n_warning = 0; /* Make this a global and limit to one CIGAR N warning? */ + uint32_t *cigar = bam_get_cigar(b); + uint8_t *seq = bam_get_seq(b); + + // b->core.l_qseq gives length of the SEQ entry (including soft clips, S) + // We need the padded length after alignment from the CIGAR (excluding + // soft clips S, but including pads from CIGAR D operations) + length = bam_cigar2rlen(b->core.n_cigar, cigar); + ks_resize(s, length); + for (k = 0, s->l = 0, j = 0; k < b->core.n_cigar; ++k) { + int op, ol; + op = bam_cigar_op(cigar[k]); + ol = bam_cigar_oplen(cigar[k]); + if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { + for (i = 0; i < ol; ++i, ++j) s->s[s->l++] = bam_seqi(seq, j); + } else if (op == BAM_CSOFT_CLIP) { + j += ol; + } else if (op == BAM_CHARD_CLIP) { + /* do nothing */ + } else if (op == BAM_CDEL) { + for (i = 0; i < ol; ++i) s->s[s->l++] = 0; + } else if (op == BAM_CREF_SKIP) { + /* Treat CIGAR N as D (not ideal, but better than ignoring it) */ + for (i = 0; i < ol; ++i) s->s[s->l++] = 0; + if (0 == cigar_n_warning) { + cigar_n_warning = -1; + fprintf(samtools_stderr, "[depad] WARNING: CIGAR op N treated as op D in read %s\n", bam_get_qname(b)); + } + } else { + fprintf(samtools_stderr, "[depad] ERROR: Didn't expect CIGAR op %c in read %s\n", BAM_CIGAR_STR[op], bam_get_qname(b)); + return -1; + } + } + return length != s->l; +} + +int load_unpadded_ref(faidx_t *fai, const char *ref_name, hts_pos_t ref_len, kstring_t *seq) +{ + char base; + char *fai_ref = 0; + hts_pos_t fai_ref_len = 0, k; + + fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len); + if (fai_ref_len != ref_len) { + fprintf(samtools_stderr, "[depad] ERROR: FASTA sequence %s length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, ref_len); + free(fai_ref); + return -1; + } + ks_resize(seq, ref_len); + seq->l = 0; + for (k = 0; k < ref_len; ++k) { + base = fai_ref[k]; + if (base == '-' || base == '*') { + // Map gaps to null to match unpad_seq function + seq->s[seq->l++] = 0; + } else { + int i = seq_nt16_table[(int)base]; + if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 + fprintf(samtools_stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence %s\n", base, (int)base, ref_name); + free(fai_ref); + return -1; + } + seq->s[seq->l++] = i; + } + } + assert(ref_len == seq->l); + free(fai_ref); + return 0; +} + +hts_pos_t get_unpadded_len(faidx_t *fai, const char *ref_name, hts_pos_t padded_len) +{ + char base; + char *fai_ref = 0; + hts_pos_t fai_ref_len = 0, k; + hts_pos_t bases=0, gaps=0; + + fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len); + if (fai_ref_len != padded_len) { + fprintf(samtools_stderr, "[depad] ERROR: FASTA sequence '%s' length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, padded_len); + free(fai_ref); + return -1; + } + for (k = 0; k < padded_len; ++k) { + //fprintf(samtools_stderr, "[depad] checking base %i of %i or %i\n", k+1, ref_len, strlen(fai_ref)); + base = fai_ref[k]; + if (base == '-' || base == '*') { + gaps += 1; + } else { + int i = seq_nt16_table[(int)base]; + if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 + fprintf(samtools_stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence '%s'\n", base, (int)base, ref_name); + free(fai_ref); + return -1; + } + bases += 1; + } + } + free(fai_ref); + assert (padded_len == bases + gaps); + return bases; +} + +static inline int * update_posmap(int *posmap, kstring_t ref) +{ + int i, k; + posmap = realloc(posmap, ref.m * sizeof(int)); + for (i = k = 0; i < ref.l; ++i) { + posmap[i] = k; + if (ref.s[i]) ++k; + } + return posmap; +} + +int bam_pad2unpad(samFile *in, samFile *out, sam_hdr_t *h, faidx_t *fai) +{ + bam1_t *b = 0; + kstring_t r, q; + int r_tid = -1; + uint32_t *cigar2 = 0; + int ret = 0, *posmap = 0; + uint32_t n2 = 0, m2 = 0; + + b = bam_init1(); + if (!b) { + fprintf(samtools_stderr, "[depad] Couldn't allocate bam struct\n"); + return -1; + } + r.l = r.m = q.l = q.m = 0; r.s = q.s = 0; + int read_ret; + while ((read_ret = sam_read1(in, h, b)) >= 0) { // read one alignment from `in' + // Cannot depad unmapped CRAM data + if (b->core.flag & BAM_FUNMAP) + goto next_seq; + + uint32_t *cigar = bam_get_cigar(b); + n2 = 0; + if (b->core.pos == 0 && b->core.tid >= 0 && strcmp(bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid)) == 0) { + // fprintf(samtools_stderr, "[depad] Found embedded reference '%s'\n", bam_get_qname(b)); + r_tid = b->core.tid; + if (0!=unpad_seq(b, &r)) { + fprintf(samtools_stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in reference %s\n", bam_get_qname(b)); + return -1; + }; + if (sam_hdr_tid2len(h, r_tid) != r.l) { + fprintf(samtools_stderr, "[depad] ERROR: (Padded) length of '%s' is %"PRId64" in BAM header, but %zu in embedded reference\n", bam_get_qname(b), (int64_t) sam_hdr_tid2len(h, r_tid), r.l); + return -1; + } + if (fai) { + // Check the embedded reference matches the FASTA file + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &q)) { + fprintf(samtools_stderr, "[depad] ERROR: Failed to load embedded reference '%s' from FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + assert(r.l == q.l); + int i; + for (i = 0; i < r.l; ++i) { + if (r.s[i] != q.s[i]) { + // Show gaps as ASCII 45 + fprintf(samtools_stderr, "[depad] ERROR: Embedded sequence and reference FASTA don't match for %s base %i, '%c' vs '%c'\n", + sam_hdr_tid2name(h, b->core.tid), i+1, + r.s[i] ? seq_nt16_str[(int)r.s[i]] : 45, + q.s[i] ? seq_nt16_str[(int)q.s[i]] : 45); + return -1; + } + } + } + write_cigar(cigar2, n2, m2, bam_cigar_gen(b->core.l_qseq, BAM_CMATCH)); + if (replace_cigar(b, n2, cigar2) < 0) + return -1; + posmap = update_posmap(posmap, r); + } else if (b->core.n_cigar > 0) { + int i, k, op; + if (b->core.tid < 0) { + fprintf(samtools_stderr, "[depad] ERROR: Read '%s' has CIGAR but no RNAME\n", bam_get_qname(b)); + return -1; + } else if (b->core.tid == r_tid) { + ; // good case, reference available + //fprintf(samtools_stderr, "[depad] Have ref '%s' for read '%s'\n", h->target_name[b->core.tid], bam_get_qname(b)); + } else if (fai) { + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) { + fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + posmap = update_posmap(posmap, r); + r_tid = b->core.tid; + // fprintf(samtools_stderr, "[depad] Loaded %s from FASTA file\n", h->target_name[b->core.tid]); + } else { + fprintf(samtools_stderr, "[depad] ERROR: Missing %s embedded reference sequence (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + if (0!=unpad_seq(b, &q)) { + fprintf(samtools_stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in read %s\n", bam_get_qname(b)); + return -1; + }; + if (bam_cigar_op(cigar[0]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[0]); + } else if (bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) { + write_cigar(cigar2, n2, m2, cigar[0]); + if (b->core.n_cigar > 2 && bam_cigar_op(cigar[1]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[1]); + } + } + /* Determine CIGAR operator for each base in the aligned read */ + for (i = 0, k = b->core.pos; i < q.l; ++i, ++k) + q.s[i] = q.s[i]? (r.s[k]? BAM_CMATCH : BAM_CINS) : (r.s[k]? BAM_CDEL : BAM_CPAD); + /* Include any pads if starts with an insert */ + if (q.s[0] == BAM_CINS) { + for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k); + if (k) write_cigar(cigar2, n2, m2, bam_cigar_gen(k, BAM_CPAD)); + k = 0; + } else if (q.s[0] == BAM_CPAD) { + // Join 'k' CPAD to our first cigar op CPAD too. + for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k); + } else { + k = 0; + } + /* Count consecutive CIGAR operators to turn into a CIGAR string */ + for (i = 1, k++, op = q.s[0]; i < q.l; ++i) { + if (op != q.s[i]) { + write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); + op = q.s[i]; k = 1; + } else ++k; + } + write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); + if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); + } else if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CHARD_CLIP) { + if (b->core.n_cigar > 2 && bam_cigar_op(cigar[b->core.n_cigar-2]) == BAM_CSOFT_CLIP) { + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-2]); + } + write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); + } + /* Remove redundant P operators between M/X/=/D operators, e.g. 5M2P10M -> 15M */ + int pre_op, post_op; + for (i = 2; i < n2; ++i) + if (bam_cigar_op(cigar2[i-1]) == BAM_CPAD) { + pre_op = bam_cigar_op(cigar2[i-2]); + post_op = bam_cigar_op(cigar2[i]); + /* Note don't need to check for X/= as code above will use M only */ + if ((pre_op == BAM_CMATCH || pre_op == BAM_CDEL) && (post_op == BAM_CMATCH || post_op == BAM_CDEL)) { + /* This is a redundant P operator */ + cigar2[i-1] = 0; // i.e. 0M + /* If had same operator either side, combine them in post_op */ + if (pre_op == post_op) { + /* If CIGAR M, could treat as simple integers since BAM_CMATCH is zero*/ + cigar2[i] = bam_cigar_gen(bam_cigar_oplen(cigar2[i-2]) + bam_cigar_oplen(cigar2[i]), post_op); + cigar2[i-2] = 0; // i.e. 0M + } + } + } + /* Remove the zero'd operators (0M) */ + for (i = k = 0; i < n2; ++i) + if (cigar2[i]) cigar2[k++] = cigar2[i]; + n2 = k; + if (replace_cigar(b, n2, cigar2) < 0) + return -1; + } + /* Even unmapped reads can have a POS value, e.g. if their mate was mapped */ + if (b->core.pos != -1) b->core.pos = posmap[b->core.pos]; + if (b->core.mtid < 0 || b->core.mpos < 0) { + /* Nice case, no mate to worry about*/ + // fprintf(samtools_stderr, "[depad] Read '%s' mate not mapped\n", bam_get_qname(b)); + /* TODO - Warning if FLAG says mate should be mapped? */ + /* Clean up funny input where mate position is given but mate reference is missing: */ + b->core.mtid = -1; + b->core.mpos = -1; + } else if (b->core.mtid == b->core.tid) { + /* Nice case, same reference */ + // fprintf(samtools_stderr, "[depad] Read '%s' mate mapped to same ref\n", bam_get_qname(b)); + b->core.mpos = posmap[b->core.mpos]; + } else { + /* Nasty case, Must load alternative posmap */ + // fprintf(samtools_stderr, "[depad] Loading reference '%s' temporarily\n", h->target_name[b->core.mtid]); + if (!fai) { + fprintf(samtools_stderr, "[depad] ERROR: Needed reference %s sequence for mate (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.mtid)); + return -1; + } + /* Temporarily load the other reference sequence */ + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.mtid), sam_hdr_tid2len(h, b->core.mtid), &r)) { + fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.mtid)); + return -1; + } + posmap = update_posmap(posmap, r); + b->core.mpos = posmap[b->core.mpos]; + /* Restore the reference and posmap*/ + if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) { + fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid)); + return -1; + } + posmap = update_posmap(posmap, r); + } + /* Most reads will have been moved so safest to always recalculate the BIN value */ + b->core.bin = bam_reg2bin(b->core.pos, bam_endpos(b)); + + next_seq: + if (sam_write1(out, h, b) < 0) { + print_error_errno("depad", "error writing to output"); + return -1; + } + } + if (read_ret < -1) { + fprintf(samtools_stderr, "[depad] truncated file.\n"); + ret = 1; + } + free(r.s); free(q.s); free(posmap); + free(cigar2); + bam_destroy1(b); + return ret; +} + +sam_hdr_t * fix_header(sam_hdr_t *old, faidx_t *fai) +{ + int i = 0, ret = 0; + hts_pos_t unpadded_len = 0; + sam_hdr_t *header = sam_hdr_dup(old); + if (!header) + return NULL; + + int nref = sam_hdr_nref(old); + char len_buf[64]; + + for (i = 0; i < nref; ++i) { + unpadded_len = get_unpadded_len(fai, sam_hdr_tid2name(old, i), sam_hdr_tid2len(old, i)); + if (unpadded_len < 0) { + fprintf(samtools_stderr, "[depad] ERROR getting unpadded length of '%s', padded length %"PRIhts_pos"\n", sam_hdr_tid2name(old, i), (hts_pos_t) sam_hdr_tid2len(old, i)); + } else if (unpadded_len > sam_hdr_tid2len(old, i)) { + fprintf(samtools_stderr, "[depad] New unpadded length of '%s' is larger than the padded length (%"PRIhts_pos" > %"PRIhts_pos")\n", + sam_hdr_tid2name(old, i), unpadded_len, + (hts_pos_t) sam_hdr_tid2len(old, i)); + ret = 1; + } else { + sprintf(len_buf, "%"PRIhts_pos"", unpadded_len); + if ((ret |= sam_hdr_update_line(header, "SQ", "SN", sam_hdr_tid2name(header, i), "LN", len_buf, NULL))) + fprintf(samtools_stderr, "[depad] Error updating length of '%s' from %"PRIhts_pos" to %"PRIhts_pos"\n", + sam_hdr_tid2name(header, i), + (hts_pos_t) sam_hdr_tid2len(header, i), + unpadded_len); + //fprintf(samtools_stderr, "[depad] Recalculating '%s' length %i -> %i\n", old->target_name[i], old->target_len[i], header->target_len[i]); + } + } + + if (ret) { + sam_hdr_destroy(header); + return NULL; + } + + return header; +} + +static int usage(int is_long_help); + +int main_pad2unpad(int argc, char *argv[]) +{ + samFile *in = 0, *out = 0; + sam_hdr_t *h = 0, *h_fix = 0; + faidx_t *fai = 0; + int c, compress_level = -1, is_long_help = 0, no_pg = 0; + char in_mode[5], out_mode[6], *fn_out = 0, *fn_fai = 0, *fn_out_idx = NULL; + int ret=0; + char *arg_list = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 'T', '-'), + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + /* parse command-line options */ + strcpy(in_mode, "r"); strcpy(out_mode, "w"); + while ((c = getopt_long(argc, argv, "SCso:u1T:?", lopts, NULL)) >= 0) { + switch (c) { + case 'S': break; + case 'C': hts_parse_format(&ga.out, "cram"); break; + case 's': assert(compress_level == -1); hts_parse_format(&ga.out, "sam"); break; + case 'o': fn_out = strdup(optarg); break; + case 'u': + compress_level = 0; + if (ga.out.format == unknown_format) + hts_parse_format(&ga.out, "bam"); + break; + case '1': + compress_level = 1; + if (ga.out.format == unknown_format) + hts_parse_format(&ga.out, "bam"); + break; + case 1: no_pg = 1; break; + case '?': is_long_help = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + fprintf(samtools_stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c); + return usage(is_long_help); + } + } + if (argc == optind) return usage(is_long_help); + + strcat(out_mode, "h"); + if (compress_level >= 0) { + char tmp[2]; + tmp[0] = compress_level + '0'; tmp[1] = '\0'; + strcat(out_mode, tmp); + } + + // Load FASTA reference (also needed for SAM -> BAM if missing header) + if (ga.reference) { + fn_fai = fai_path(ga.reference); + fai = fai_load3(ga.reference, fn_fai, NULL, FAI_CREATE); + } + // open file handlers + if ((in = sam_open_format(argv[optind], in_mode, &ga.in)) == 0) { + print_error_errno("depad", "failed to open \"%s\" for reading", argv[optind]); + ret = 1; + goto depad_end; + } + if (fn_fai && hts_set_fai_filename(in, fn_fai) != 0) { + fprintf(samtools_stderr, "[depad] failed to load reference file \"%s\".\n", fn_fai); + ret = 1; + goto depad_end; + } + if ((h = sam_hdr_read(in)) == 0) { + fprintf(samtools_stderr, "[depad] failed to read the header from \"%s\".\n", argv[optind]); + ret = 1; + goto depad_end; + } + if (fai) { + if (!(h_fix = fix_header(h, fai))){ + fprintf(samtools_stderr, "[depad] failed to fix the header from\n"); + ret = 1; + goto depad_end; + } + } else { + fprintf(samtools_stderr, "[depad] Warning - reference lengths will not be corrected without FASTA reference\n"); + h_fix = h; + } + char wmode[2]; + strcat(out_mode, sam_open_mode(wmode, fn_out, NULL)==0 ? wmode : "b"); + if ((out = sam_open_format(fn_out? fn_out : "-", out_mode, &ga.out)) == 0) { + print_error_errno("depad", "failed to open \"%s\" for writing", fn_out? fn_out : "standard output"); + ret = 1; + goto depad_end; + } + + // Reference-based CRAM won't work unless we also create a new reference. + // We could embed this, but for now we take the easy option. + if (ga.out.format == cram) + hts_set_opt(out, CRAM_OPT_NO_REF, 1); + + if (!no_pg) { + if(!(arg_list = stringify_argv(argc+1, argv-1))) { + fprintf(samtools_stderr, "[depad] failed to create arg_list\n"); + ret = 1; + goto depad_end; + } + + if (sam_hdr_add_pg(h_fix, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + fprintf(samtools_stderr, "[depad] failed to add PG line to header\n"); + ret = 1; + goto depad_end; + } + } + + if (sam_hdr_write(out, h_fix) != 0) { + fprintf(samtools_stderr, "[depad] failed to write header.\n"); + ret = 1; + goto depad_end; + } + if (ga.write_index) { + if (!(fn_out_idx = auto_index(out, fn_out, h_fix))) { + ret = 1; + goto depad_end; + } + } + + // Do the depad + if (bam_pad2unpad(in, out, h, fai) != 0) ret = 1; + + if (ga.write_index) { + if (sam_idx_save(out) < 0) { + print_error_errno("depad", "writing index failed"); + ret = 1; + } + } + +depad_end: + // close files, free and return + free(arg_list); + if (fai) fai_destroy(fai); + if (h) sam_hdr_destroy(h); + if (h_fix && h_fix != h) sam_hdr_destroy(h_fix); + if (in) sam_close(in); + if (out && sam_close(out) < 0) { + fprintf(samtools_stderr, "[depad] error on closing output file.\n"); + ret = 1; + } + free(fn_fai); free(fn_out); + if (fn_out_idx) + free(fn_out_idx); + sam_global_args_free(&ga); + return ret; +} + +static int usage(int is_long_help) +{ + fprintf(samtools_stderr, "\n"); + fprintf(samtools_stderr, "Usage: samtools depad \n\n"); + fprintf(samtools_stderr, "Options:\n"); + fprintf(samtools_stderr, " -s Output is SAM (default is BAM)\n"); + fprintf(samtools_stderr, " -S Input is SAM (default is BAM)\n"); + fprintf(samtools_stderr, " -u Uncompressed BAM output (can't use with -s)\n"); + fprintf(samtools_stderr, " -1 Fast compression BAM output (can't use with -s)\n"); + fprintf(samtools_stderr, " -T, --reference FILE\n"); + fprintf(samtools_stderr, " Padded reference sequence file [null]\n"); + fprintf(samtools_stderr, " -o FILE Output file name [samtools_stdout]\n"); + fprintf(samtools_stderr, " --no-PG do not add a PG line\n"); + fprintf(samtools_stderr, " -? Longer help\n"); + sam_global_opt_help(samtools_stderr, "-...--.."); + + if (is_long_help) + fprintf(samtools_stderr, +"Notes:\n" +"\n" +"1. Requires embedded reference sequences (before the reads for that reference),\n" +" or ideally a FASTA file of the padded reference sequences (via a -T option).\n" +"\n" +"2. Input padded alignment reads' CIGAR strings must not use P or I operators.\n" +"\n"); + return 1; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c new file mode 100644 index 0000000000000000000000000000000000000000..a4a735136befbfa74ef85c5a155b6644bed33d81 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c @@ -0,0 +1,823 @@ +/* phase.c -- phase subcommand. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2013-2016, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/kstring.h" +#include "sam_opts.h" +#include "samtools.h" +#include "htslib/hts_os.h" + +#include "htslib/kseq.h" +KSTREAM_INIT(gzFile, gzread, 16384) + +#define MAX_VARS 256 +#define FLIP_PENALTY 2 +#define FLIP_THRES 4 +#define MASK_THRES 3 + +#define FLAG_FIX_CHIMERA 0x1 +#define FLAG_LIST_EXCL 0x4 +#define FLAG_DROP_AMBI 0x8 + +typedef struct { + // configurations, initialized in the main function + int flag, k, min_baseQ, min_varLOD, max_depth, no_pg; + // other global variables + int vpos_shift; + samFile* fp; + sam_hdr_t* fp_hdr; + char *pre, *arg_list; + char *out_name[3]; + samFile* out[3]; + sam_hdr_t* out_hdr[3]; + // alignment queue + int n, m; + bam1_t **b; +} phaseg_t; + +typedef struct { + int8_t seq[MAX_VARS]; // TODO: change to dynamic memory allocation! + int vpos, beg, end; + uint32_t vlen:16, single:1, flip:1, phase:1, phased:1, ambig:1; + uint32_t in:16, out:16; // in-phase and out-phase +} frag_t, *frag_p; + +#define rseq_lt(a,b) ((a)->vpos < (b)->vpos) + +#include "htslib/khash.h" +KHASH_SET_INIT_INT64(set64) +KHASH_MAP_INIT_INT64(64, frag_t) + +typedef khash_t(64) nseq_t; + +#include "htslib/ksort.h" +KSORT_INIT(rseq, frag_p, rseq_lt) + +static inline uint64_t X31_hash_string(const char *s) +{ + uint64_t h = *s; + if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s; + return h; +} + +static void count1(int l, const uint8_t *seq, int *cnt) +{ + int i, j, n_ambi; + uint32_t z, x; + if (seq[l-1] == 0) return; // do nothing is the last base is ambiguous + for (i = n_ambi = 0; i < l; ++i) // collect ambiguous bases + if (seq[i] == 0) ++n_ambi; + if (l - n_ambi <= 1) return; // only one SNP + for (x = 0; x < 1u<>j&1; + ++j; + } + z = z<<1 | c; + } + ++cnt[z]; + } +} + +static int **count_all(int l, int vpos, nseq_t *hash) +{ + khint_t k; + int i, j, **cnt; + uint8_t *seq; + seq = calloc(l, 1); + cnt = calloc(vpos, sizeof(int*)); + for (i = 0; i < vpos; ++i) cnt[i] = calloc(1<vpos >= vpos || f->single) continue; // out of region; or singleton + if (f->vlen == 1) { // such reads should be flagged as deleted previously if everything is right + f->single = 1; + continue; + } + for (j = 1; j < f->vlen; ++j) { + for (i = 0; i < l; ++i) + seq[i] = j < l - 1 - i? 0 : f->seq[j - (l - 1 - i)]; + count1(l, seq, cnt[f->vpos + j]); + } + } + } + free(seq); + return cnt; +} + +// phasing +static int8_t *dynaprog(int l, int vpos, int **w) +{ + int *f[2], *curr, *prev, max, i; + int8_t **b, *h = 0; + uint32_t x, z = 1u<<(l-1), mask = (1u<>1; y1 = xc>>1; + c0 = prev[y0] + wi[x] + wi[xc]; + c1 = prev[y1] + wi[x] + wi[xc]; + if (c0 > c1) bi[x] = 0, curr[x] = c0; + else bi[x] = 1, curr[x] = c1; + } + tmp = prev; prev = curr; curr = tmp; // swap + } + { // backtrack + uint32_t max_x = 0; + int which = 0; + h = calloc(vpos, 1); + for (x = 0, max = 0, max_x = 0; x < z; ++x) + if (prev[x] > max) max = prev[x], max_x = x; + for (i = vpos - 1, x = max_x; i >= 0; --i) { + h[i] = which? (~x&1) : (x&1); + which = b[i][x]? !which : which; + x = b[i][x]? (~x&mask)>>1 : x>>1; + } + } + // free + for (i = 0; i < vpos; ++i) free(b[i]); + free(f[0]); free(f[1]); free(b); + return h; +} + +// phase each fragment +static uint64_t *fragphase(int vpos, const int8_t *path, nseq_t *hash, int flip) +{ + khint_t k; + uint64_t *pcnt; + uint32_t *left, *rght, max; + left = rght = 0; max = 0; + pcnt = calloc(vpos, 8); + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + int i, c[2]; + frag_t *f = &kh_val(hash, k); + if (f->vpos >= vpos) continue; + // get the phase + c[0] = c[1] = 0; + for (i = 0; i < f->vlen; ++i) { + if (f->seq[i] == 0) continue; + ++c[f->seq[i] == path[f->vpos + i] + 1? 0 : 1]; + } + f->phase = c[0] > c[1]? 0 : 1; + f->in = c[f->phase]; f->out = c[1 - f->phase]; + f->phased = f->in == f->out? 0 : 1; + f->ambig = (f->in && f->out && f->out < 3 && f->in <= f->out + 1)? 1 : 0; + // fix chimera + f->flip = 0; + if (flip && c[0] >= 3 && c[1] >= 3) { + int sum[2], m, mi, md; + if (f->vlen > max) { // enlarge the array + max = f->vlen; + kroundup32(max); + left = realloc(left, max * 4); + rght = realloc(rght, max * 4); + } + for (i = 0, sum[0] = sum[1] = 0; i < f->vlen; ++i) { // get left counts + if (f->seq[i]) { + int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + ++sum[c == path[f->vpos + i]? 0 : 1]; + } + left[i] = sum[1]<<16 | sum[0]; + } + for (i = f->vlen - 1, sum[0] = sum[1] = 0; i >= 0; --i) { // get right counts + if (f->seq[i]) { + int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + ++sum[c == path[f->vpos + i]? 0 : 1]; + } + rght[i] = sum[1]<<16 | sum[0]; + } + // find the best flip point + for (i = m = 0, mi = -1, md = -1; i < f->vlen - 1; ++i) { + int a[2]; + a[0] = (left[i]&0xffff) + (rght[i+1]>>16&0xffff) - (rght[i+1]&0xffff) * FLIP_PENALTY; + a[1] = (left[i]>>16&0xffff) + (rght[i+1]&0xffff) - (rght[i+1]>>16&0xffff) * FLIP_PENALTY; + if (a[0] > a[1]) { + if (a[0] > m) m = a[0], md = 0, mi = i; + } else { + if (a[1] > m) m = a[1], md = 1, mi = i; + } + } + if (m - c[0] >= FLIP_THRES && m - c[1] >= FLIP_THRES) { // then flip + f->flip = 1; + if (md == 0) { // flip the tail + for (i = mi + 1; i < f->vlen; ++i) + if (f->seq[i] == 1) f->seq[i] = 2; + else if (f->seq[i] == 2) f->seq[i] = 1; + } else { // flip the head + for (i = 0; i <= mi; ++i) + if (f->seq[i] == 1) f->seq[i] = 2; + else if (f->seq[i] == 2) f->seq[i] = 1; + } + } + } + // update pcnt[] + if (!f->single) { + for (i = 0; i < f->vlen; ++i) { + int c; + if (f->seq[i] == 0) continue; + c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + if (c == path[f->vpos + i]) { + if (f->phase == 0) ++pcnt[f->vpos + i]; + else pcnt[f->vpos + i] += 1ull<<32; + } else { + if (f->phase == 0) pcnt[f->vpos + i] += 1<<16; + else pcnt[f->vpos + i] += 1ull<<48; + } + } + } + } + } + free(left); free(rght); + return pcnt; +} + +static uint64_t *genmask(int vpos, const uint64_t *pcnt, int *_n) +{ + int i, max = 0, max_i = -1, m = 0, n = 0, beg = 0, score = 0; + uint64_t *list = 0; + for (i = 0; i < vpos; ++i) { + uint64_t x = pcnt[i]; + int c[4], pre = score, s; + c[0] = x&0xffff; c[1] = x>>16&0xffff; c[2] = x>>32&0xffff; c[3] = x>>48&0xffff; + s = (c[1] + c[3] == 0)? -(c[0] + c[2]) : (c[1] + c[3] - 1); + if (c[3] > c[2]) s += c[3] - c[2]; + if (c[1] > c[0]) s += c[1] - c[0]; + score += s; + if (score < 0) score = 0; + if (pre == 0 && score > 0) beg = i; // change from zero to non-zero + if ((i == vpos - 1 || score == 0) && max >= MASK_THRES) { + if (n == m) { + m = m? m<<1 : 4; + list = realloc(list, m * 8); + } + list[n++] = (uint64_t)beg<<32 | max_i; + i = max_i; // reset i to max_i + score = 0; + } else if (score > max) max = score, max_i = i; + if (score == 0) max = 0; + } + *_n = n; + return list; +} + +// trim heading and tailing ambiguous bases; mark deleted and remove sequence +static int clean_seqs(int vpos, nseq_t *hash) +{ + khint_t k; + int ret = 0; + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + int beg, end, i; + if (f->vpos >= vpos) { + ret = 1; + continue; + } + for (i = 0; i < f->vlen; ++i) + if (f->seq[i] != 0) break; + beg = i; + for (i = f->vlen - 1; i >= 0; --i) + if (f->seq[i] != 0) break; + end = i + 1; + if (end - beg <= 0) kh_del(64, hash, k); + else { + if (beg != 0) memmove(f->seq, f->seq + beg, end - beg); + f->vpos += beg; f->vlen = end - beg; + f->single = f->vlen == 1? 1 : 0; + } + } + } + return ret; +} + +static int dump_aln(phaseg_t *g, int min_pos, const nseq_t *hash) +{ + int i, is_flip, drop_ambi; + drop_ambi = g->flag & FLAG_DROP_AMBI; + is_flip = (drand48() < 0.5); + for (i = 0; i < g->n; ++i) { + int end, which; + uint64_t key; + khint_t k; + bam1_t *b = g->b[i]; + key = X31_hash_string(bam_get_qname(b)); + end = bam_endpos(b); + if (end > min_pos) break; + k = kh_get(64, hash, key); + if (k == kh_end(hash)) which = 3; + else { + frag_t *f = &kh_val(hash, k); + if (f->ambig) which = drop_ambi? 2 : 3; + else if (f->phased && f->flip) which = 2; + else if (f->phased == 0) which = 3; + else { // phased and not flipped + char c = 'Y'; + which = f->phase; + bam_aux_append(b, "ZP", 'A', 1, (uint8_t*)&c); + } + if (which < 2 && is_flip) which = 1 - which; // increase the randomness + } + if (which == 3) which = (drand48() < 0.5); + if (sam_write1(g->out[which], g->out_hdr[which], b) < 0) { + print_error_errno("phase", "error writing to '%s'", g->out_name[which]); + return -1; + } + bam_destroy1(b); + g->b[i] = 0; + } + memmove(g->b, g->b + i, (g->n - i) * sizeof(void*)); + g->n -= i; + return 0; +} + +static int phase(phaseg_t *g, const char *chr, int vpos, uint64_t *cns, nseq_t *hash) +{ + int i, j, n_seqs = kh_size(hash), n_masked = 0, min_pos; + khint_t k; + frag_t **seqs; + int8_t *path, *sitemask; + uint64_t *pcnt, *regmask; + + if (vpos == 0) return 0; + i = clean_seqs(vpos, hash); // i is true if hash has an element with its vpos >= vpos + min_pos = i? cns[vpos]>>32 : 0x7fffffff; + if (vpos == 1) { + printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1); + printf("M0\t%s\t%d\t%d\t%c\t%c\t%d\t0\t0\t0\t0\n//\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1, + "ACGTX"[cns[0]&3], "ACGTX"[cns[0]>>16&3], g->vpos_shift + 1); + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + if (f->vpos) continue; + f->flip = 0; + if (f->seq[0] == 0) f->phased = 0; + else f->phased = 1, f->phase = f->seq[0] - 1; + } + } + if (dump_aln(g, min_pos, hash) < 0) return -1; + ++g->vpos_shift; + return 1; + } + { // phase + int **cnt; + uint64_t *mask; + printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[vpos-1]>>32) + 1); + sitemask = calloc(vpos, 1); + cnt = count_all(g->k, vpos, hash); + path = dynaprog(g->k, vpos, cnt); + for (i = 0; i < vpos; ++i) free(cnt[i]); + free(cnt); + pcnt = fragphase(vpos, path, hash, 0); // do not fix chimeras when masking + mask = genmask(vpos, pcnt, &n_masked); + regmask = calloc(n_masked, 8); + for (i = 0; i < n_masked; ++i) { + regmask[i] = cns[mask[i]>>32]>>32<<32 | cns[(uint32_t)mask[i]]>>32; + for (j = mask[i]>>32; j <= (int32_t)mask[i]; ++j) + sitemask[j] = 1; + } + free(mask); + if (g->flag & FLAG_FIX_CHIMERA) { + free(pcnt); + pcnt = fragphase(vpos, path, hash, 1); + } + } + for (i = 0; i < n_masked; ++i) + printf("FL\t%s\t%d\t%d\n", chr, (int)(regmask[i]>>32) + 1, (int)regmask[i] + 1); + for (i = 0; i < vpos; ++i) { + uint64_t x = pcnt[i]; + int8_t c[2]; + c[0] = (cns[i]&0xffff)>>2 == 0? 4 : (cns[i]&3); + c[1] = (cns[i]>>16&0xffff)>>2 == 0? 4 : (cns[i]>>16&3); + printf("M%d\t%s\t%d\t%d\t%c\t%c\t%d\t%d\t%d\t%d\t%d\n", sitemask[i]+1, chr, (int)(cns[0]>>32) + 1, (int)(cns[i]>>32) + 1, "ACGTX"[c[path[i]]], "ACGTX"[c[1-path[i]]], + i + g->vpos_shift + 1, (int)(x&0xffff), (int)(x>>16&0xffff), (int)(x>>32&0xffff), (int)(x>>48&0xffff)); + } + free(path); free(pcnt); free(regmask); free(sitemask); + seqs = calloc(n_seqs, sizeof(frag_t*)); + for (k = 0, i = 0; k < kh_end(hash); ++k) + if (kh_exist(hash, k) && kh_val(hash, k).vpos < vpos && !kh_val(hash, k).single) + seqs[i++] = &kh_val(hash, k); + n_seqs = i; + ks_introsort_rseq(n_seqs, seqs); + for (i = 0; i < n_seqs; ++i) { + frag_t *f = seqs[i]; + printf("EV\t0\t%s\t%d\t40\t%dM\t*\t0\t0\t", chr, f->vpos + 1 + g->vpos_shift, f->vlen); + for (j = 0; j < f->vlen; ++j) { + uint32_t c = cns[f->vpos + j]; + if (f->seq[j] == 0) putchar('N'); + else putchar("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)]); + } + printf("\t*\tYP:i:%d\tYF:i:%d\tYI:i:%d\tYO:i:%d\tYS:i:%d\n", f->phase, f->flip, f->in, f->out, f->beg+1); + } + free(seqs); + printf("//\n"); + fflush(stdout); + g->vpos_shift += vpos; + if (dump_aln(g, min_pos, hash) < 0) return -1; + return vpos; +} + +static void update_vpos(int vpos, nseq_t *hash) +{ + khint_t k; + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + if (f->vpos < vpos) kh_del(64, hash, k); // TODO: if frag_t::seq is allocated dynamically, free it + else f->vpos -= vpos; + } + } +} + +static nseq_t *shrink_hash(nseq_t *hash) // TODO: to implement +{ + return hash; +} + +static int readaln(void *data, bam1_t *b) +{ + phaseg_t *g = (phaseg_t*)data; + int ret; + while (1) + { + ret = sam_read1(g->fp, g->fp_hdr, b); + if (ret < 0) break; + if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue; + if ( g->pre ) { + if (g->n == g->m) { + g->m = g->m? g->m<<1 : 16; + g->b = realloc(g->b, g->m * sizeof(bam1_t*)); + } + g->b[g->n++] = bam_dup1(b); + } + break; + } + return ret; +} + +static khash_t(set64) *loadpos(const char *fn, sam_hdr_t *h) +{ + gzFile fp; + kstream_t *ks; + int ret, dret; + kstring_t *str; + khash_t(set64) *hash; + + fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); + if (fp == NULL) { + print_error_errno("phase", "Couldn't open site file '%s'", fn); + return NULL; + } + + hash = kh_init(set64); + str = calloc(1, sizeof(kstring_t)); + + ks = ks_init(fp); + while (ks_getuntil(ks, 0, str, &dret) >= 0) { + int tid = bam_name2id(h, str->s); + if (tid >= 0 && dret != '\n') { + if (ks_getuntil(ks, 0, str, &dret) >= 0) { + uint64_t x = (uint64_t)tid<<32 | (atoi(str->s) - 1); + kh_put(set64, hash, x, &ret); + } else break; + } + if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n'); + if (dret < 0) break; + } + ks_destroy(ks); + gzclose(fp); + free(str->s); free(str); + return hash; +} + +static int gl2cns(float q[16]) +{ + int i, j, min_ij; + float min, min2; + min = min2 = 1e30; min_ij = -1; + for (i = 0; i < 4; ++i) { + for (j = i; j < 4; ++j) { + if (q[i<<2|j] < min) min_ij = i<<2|j, min2 = min, min = q[i<<2|j]; + else if (q[i<<2|j] < min2) min2 = q[i<<2|j]; + } + } + return (min_ij>>2&3) == (min_ij&3)? 0 : 1<<18 | (min_ij>>2&3)<<16 | (min_ij&3) | (int)(min2 - min + .499) << 2; +} + +static int start_output(phaseg_t *g, int c, const char *middle, const htsFormat *fmt) +{ + kstring_t s = { 0, 0, NULL }; + ksprintf(&s, "%s.%s.%s", g->pre, middle, hts_format_file_extension(fmt)); + g->out_name[c] = ks_release(&s); + g->out[c] = sam_open_format(g->out_name[c], "wb", fmt); + if (! g->out[c]) { + print_error_errno("phase", "Failed to open output file '%s'", g->out_name[c]); + return -1; + } + + g->out_hdr[c] = sam_hdr_dup(g->fp_hdr); + if (!g->no_pg && sam_hdr_add_pg(g->out_hdr[c], "samtools", + "VN", samtools_version(), + g->arg_list ? "CL": NULL, + g->arg_list ? g->arg_list : NULL, + NULL)) { + print_error("phase", "failed to add PG line to header"); + return -1; + } + if (sam_hdr_write(g->out[c], g->out_hdr[c]) < 0) { + print_error_errno("phase", "Failed to write header for '%s'", g->out_name[c]); + return -1; + } + + return 0; +} + +int main_phase(int argc, char *argv[]) +{ + int c, tid, pos, vpos = 0, n, lasttid = -1, max_vpos = 0, usage = 0; + int status = EXIT_SUCCESS; + const bam_pileup1_t *plp; + bam_plp_t iter; + nseq_t *seqs; + uint64_t *cns = 0; + phaseg_t g; + char *fn_list = 0; + khash_t(set64) *set = 0; + errmod_t *em; + uint16_t *bases; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'), + {"min-BQ", required_argument, NULL, 'Q'}, + {"min-bq", required_argument, NULL, 'Q'}, + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + // FIXME Leaks galore in the case of error returns + + memset(&g, 0, sizeof(phaseg_t)); + g.flag = FLAG_FIX_CHIMERA; + g.min_varLOD = 37; g.k = 13; g.min_baseQ = 13; g.max_depth = 256; + while ((c = getopt_long(argc, argv, "Q:eFq:k:b:l:D:A", lopts, NULL)) >= 0) { + switch (c) { + case 'D': g.max_depth = atoi(optarg); break; + case 'q': g.min_varLOD = atoi(optarg); break; + case 'Q': g.min_baseQ = atoi(optarg); break; + case 'k': g.k = atoi(optarg); break; + case 'F': g.flag &= ~FLAG_FIX_CHIMERA; break; + case 'e': g.flag |= FLAG_LIST_EXCL; break; + case 'A': g.flag |= FLAG_DROP_AMBI; break; + case 'b': g.pre = strdup(optarg); break; + case 'l': fn_list = strdup(optarg); break; + case 1: g.no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + if (usage) break; + } + if (usage || argc == optind) { + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: samtools phase [options] \n\n"); + fprintf(stderr, "Options: -k INT block length [%d]\n", g.k); + fprintf(stderr, " -b STR prefix of BAMs to output [null]\n"); + fprintf(stderr, " -q INT min het phred-LOD [%d]\n", g.min_varLOD); + fprintf(stderr, " -Q, --min-BQ INT\n" + " min base quality in het calling [%d]\n", g.min_baseQ); + fprintf(stderr, " -D INT max read depth [%d]\n", g.max_depth); +// fprintf(stderr, " -l FILE list of sites to phase [null]\n"); + fprintf(stderr, " -F do not attempt to fix chimeras\n"); + fprintf(stderr, " -A drop reads with ambiguous phase\n"); + fprintf(stderr, " --no-PG do not add a PG line\n"); +// fprintf(stderr, " -e do not discover SNPs (effective with -l)\n"); + fprintf(stderr, "\n"); + + sam_global_opt_help(stderr, "-....--."); + + return 1; + } + g.fp = sam_open_format(argv[optind], "r", &ga.in); + if (!g.fp) { + print_error_errno("phase", "Couldn't open '%s'", argv[optind]); + return 1; + } + g.fp_hdr = sam_hdr_read(g.fp); + if (g.fp_hdr == NULL) { + fprintf(stderr, "[%s] Failed to read header for '%s'\n", + __func__, argv[optind]); + return 1; + } + if (!g.no_pg && !(g.arg_list = stringify_argv(argc+1, argv-1))) { + print_error("phase", "failed to create arg_list"); + return 1; + } + if (fn_list) { // read the list of sites to phase + set = loadpos(fn_list, g.fp_hdr); + if (set == NULL) return 1; + free(fn_list); + } else g.flag &= ~FLAG_LIST_EXCL; + if (g.pre) { // open BAMs to write + if (ga.out.format == unknown_format) + ga.out.format = bam; // default via "wb". + + // Open each output file g.out[0..2], dupping and writing the header + if (start_output(&g, 0, "0", &ga.out) < 0 || + start_output(&g, 1, "1", &ga.out) < 0 || + start_output(&g, 2, "chimera", &ga.out) < 0) return 1; + } + + iter = bam_plp_init(readaln, &g); + g.vpos_shift = 0; + seqs = kh_init(64); + em = errmod_init(1. - 0.83); + bases = calloc(g.max_depth, 2); + printf("CC\n"); + printf("CC\tDescriptions:\nCC\n"); + printf("CC\t CC comments\n"); + printf("CC\t PS start of a phase set\n"); + printf("CC\t FL filtered region\n"); + printf("CC\t M[012] markers; 0 for singletons, 1 for phased and 2 for filtered\n"); + printf("CC\t EV supporting reads; SAM format\n"); + printf("CC\t // end of a phase set\nCC\n"); + printf("CC\tFormats of PS, FL and M[012] lines (1-based coordinates):\nCC\n"); + printf("CC\t PS chr phaseSetStart phaseSetEnd\n"); + printf("CC\t FL chr filterStart filterEnd\n"); + printf("CC\t M? chr PS pos allele0 allele1 hetIndex #supports0 #errors0 #supp1 #err1\n"); + printf("CC\nCC\n"); + fflush(stdout); + while ((plp = bam_plp_auto(iter, &tid, &pos, &n)) != 0) { + int i, k, c, tmp, dophase = 1, in_set = 0; + float q[16]; + if (tid < 0) break; + if (tid != lasttid) { // change of chromosome + g.vpos_shift = 0; + if (lasttid >= 0) { + seqs = shrink_hash(seqs); + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, lasttid), + vpos, cns, seqs) < 0) { + return 1; + } + update_vpos(0x7fffffff, seqs); + } + lasttid = tid; + vpos = 0; + } + if (set && kh_get(set64, set, (uint64_t)tid<<32 | pos) != kh_end(set)) in_set = 1; + if (n > g.max_depth) continue; // do not proceed if the depth is too high + // fill the bases array and check if there is a variant + for (i = k = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint8_t *seq; + int q, baseQ, b; + if (p->is_del || p->is_refskip) continue; + baseQ = bam_get_qual(p->b)[p->qpos]; + if (baseQ < g.min_baseQ) continue; + seq = bam_get_seq(p->b); + b = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (b > 3) continue; + q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; + if (q < 4) q = 4; + if (q > 63) q = 63; + bases[k++] = q<<5 | (int)bam_is_rev(p->b)<<4 | b; + } + if (k == 0) continue; + errmod_cal(em, k, 4, bases, q); // compute genotype likelihood + c = gl2cns(q); // get the consensus + // tell if to proceed + if (set && (g.flag&FLAG_LIST_EXCL) && !in_set) continue; // not in the list + if (!in_set && (c&0xffff)>>2 < g.min_varLOD) continue; // not a variant + // add the variant + if (vpos == max_vpos) { + max_vpos = max_vpos? max_vpos<<1 : 128; + cns = realloc(cns, max_vpos * 8); + } + cns[vpos] = (uint64_t)pos<<32 | c; + for (i = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint64_t key; + khint_t k; + uint8_t *seq = bam_get_seq(p->b); + frag_t *f; + if (p->is_del || p->is_refskip) continue; + if (p->b->core.qual == 0) continue; + // get the base code + c = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (c == (cns[vpos]&3)) c = 1; + else if (c == (cns[vpos]>>16&3)) c = 2; + else c = 0; + // write to seqs + key = X31_hash_string(bam_get_qname(p->b)); + k = kh_put(64, seqs, key, &tmp); + f = &kh_val(seqs, k); + if (tmp == 0) { // present in the hash table + if (vpos - f->vpos + 1 < MAX_VARS) { + f->vlen = vpos - f->vpos + 1; + f->seq[f->vlen-1] = c; + f->end = bam_endpos(p->b); + } + dophase = 0; + } else { // absent + memset(f->seq, 0, MAX_VARS); + f->beg = p->b->core.pos; + f->end = bam_endpos(p->b); + f->vpos = vpos, f->vlen = 1, f->seq[0] = c, f->single = f->phased = f->flip = f->ambig = 0; + } + } + if (dophase) { + seqs = shrink_hash(seqs); + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) { + return 1; + } + update_vpos(vpos, seqs); + cns[0] = cns[vpos]; + vpos = 0; + } + ++vpos; + } + if (tid >= 0) { + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) { + return 1; + } + } + + if (n < 0) { + print_error("phase", "error reading from '%s'", argv[optind]); + status = EXIT_FAILURE; + } + + sam_hdr_destroy(g.fp_hdr); + bam_plp_destroy(iter); + sam_close(g.fp); + kh_destroy(64, seqs); + kh_destroy(set64, set); + free(cns); + errmod_destroy(em); + free(bases); + if (g.pre) { + int res = 0; + for (c = 0; c <= 2; ++c) { + if (sam_close(g.out[c]) < 0) { + fprintf(stderr, "[%s] error on closing '%s'\n", + __func__, g.out_name[c]); + res = 1; + } + sam_hdr_destroy(g.out_hdr[c]); + free(g.out_name[c]); + } + free(g.pre); free(g.b); + if (res) return 1; + } + free(g.arg_list); + sam_global_args_free(&ga); + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..b0b525767735adb2d866835398ce5670bd3f8a6b --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/phase.c.pysam.c @@ -0,0 +1,825 @@ +#include "samtools.pysam.h" + +/* phase.c -- phase subcommand. + + Copyright (C) 2011 Broad Institute. + Copyright (C) 2013-2016, 2019 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/kstring.h" +#include "sam_opts.h" +#include "samtools.h" +#include "htslib/hts_os.h" + +#include "htslib/kseq.h" +KSTREAM_INIT(gzFile, gzread, 16384) + +#define MAX_VARS 256 +#define FLIP_PENALTY 2 +#define FLIP_THRES 4 +#define MASK_THRES 3 + +#define FLAG_FIX_CHIMERA 0x1 +#define FLAG_LIST_EXCL 0x4 +#define FLAG_DROP_AMBI 0x8 + +typedef struct { + // configurations, initialized in the main function + int flag, k, min_baseQ, min_varLOD, max_depth, no_pg; + // other global variables + int vpos_shift; + samFile* fp; + sam_hdr_t* fp_hdr; + char *pre, *arg_list; + char *out_name[3]; + samFile* out[3]; + sam_hdr_t* out_hdr[3]; + // alignment queue + int n, m; + bam1_t **b; +} phaseg_t; + +typedef struct { + int8_t seq[MAX_VARS]; // TODO: change to dynamic memory allocation! + int vpos, beg, end; + uint32_t vlen:16, single:1, flip:1, phase:1, phased:1, ambig:1; + uint32_t in:16, out:16; // in-phase and out-phase +} frag_t, *frag_p; + +#define rseq_lt(a,b) ((a)->vpos < (b)->vpos) + +#include "htslib/khash.h" +KHASH_SET_INIT_INT64(set64) +KHASH_MAP_INIT_INT64(64, frag_t) + +typedef khash_t(64) nseq_t; + +#include "htslib/ksort.h" +KSORT_INIT(rseq, frag_p, rseq_lt) + +static inline uint64_t X31_hash_string(const char *s) +{ + uint64_t h = *s; + if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s; + return h; +} + +static void count1(int l, const uint8_t *seq, int *cnt) +{ + int i, j, n_ambi; + uint32_t z, x; + if (seq[l-1] == 0) return; // do nothing is the last base is ambiguous + for (i = n_ambi = 0; i < l; ++i) // collect ambiguous bases + if (seq[i] == 0) ++n_ambi; + if (l - n_ambi <= 1) return; // only one SNP + for (x = 0; x < 1u<>j&1; + ++j; + } + z = z<<1 | c; + } + ++cnt[z]; + } +} + +static int **count_all(int l, int vpos, nseq_t *hash) +{ + khint_t k; + int i, j, **cnt; + uint8_t *seq; + seq = calloc(l, 1); + cnt = calloc(vpos, sizeof(int*)); + for (i = 0; i < vpos; ++i) cnt[i] = calloc(1<vpos >= vpos || f->single) continue; // out of region; or singleton + if (f->vlen == 1) { // such reads should be flagged as deleted previously if everything is right + f->single = 1; + continue; + } + for (j = 1; j < f->vlen; ++j) { + for (i = 0; i < l; ++i) + seq[i] = j < l - 1 - i? 0 : f->seq[j - (l - 1 - i)]; + count1(l, seq, cnt[f->vpos + j]); + } + } + } + free(seq); + return cnt; +} + +// phasing +static int8_t *dynaprog(int l, int vpos, int **w) +{ + int *f[2], *curr, *prev, max, i; + int8_t **b, *h = 0; + uint32_t x, z = 1u<<(l-1), mask = (1u<>1; y1 = xc>>1; + c0 = prev[y0] + wi[x] + wi[xc]; + c1 = prev[y1] + wi[x] + wi[xc]; + if (c0 > c1) bi[x] = 0, curr[x] = c0; + else bi[x] = 1, curr[x] = c1; + } + tmp = prev; prev = curr; curr = tmp; // swap + } + { // backtrack + uint32_t max_x = 0; + int which = 0; + h = calloc(vpos, 1); + for (x = 0, max = 0, max_x = 0; x < z; ++x) + if (prev[x] > max) max = prev[x], max_x = x; + for (i = vpos - 1, x = max_x; i >= 0; --i) { + h[i] = which? (~x&1) : (x&1); + which = b[i][x]? !which : which; + x = b[i][x]? (~x&mask)>>1 : x>>1; + } + } + // free + for (i = 0; i < vpos; ++i) free(b[i]); + free(f[0]); free(f[1]); free(b); + return h; +} + +// phase each fragment +static uint64_t *fragphase(int vpos, const int8_t *path, nseq_t *hash, int flip) +{ + khint_t k; + uint64_t *pcnt; + uint32_t *left, *rght, max; + left = rght = 0; max = 0; + pcnt = calloc(vpos, 8); + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + int i, c[2]; + frag_t *f = &kh_val(hash, k); + if (f->vpos >= vpos) continue; + // get the phase + c[0] = c[1] = 0; + for (i = 0; i < f->vlen; ++i) { + if (f->seq[i] == 0) continue; + ++c[f->seq[i] == path[f->vpos + i] + 1? 0 : 1]; + } + f->phase = c[0] > c[1]? 0 : 1; + f->in = c[f->phase]; f->out = c[1 - f->phase]; + f->phased = f->in == f->out? 0 : 1; + f->ambig = (f->in && f->out && f->out < 3 && f->in <= f->out + 1)? 1 : 0; + // fix chimera + f->flip = 0; + if (flip && c[0] >= 3 && c[1] >= 3) { + int sum[2], m, mi, md; + if (f->vlen > max) { // enlarge the array + max = f->vlen; + kroundup32(max); + left = realloc(left, max * 4); + rght = realloc(rght, max * 4); + } + for (i = 0, sum[0] = sum[1] = 0; i < f->vlen; ++i) { // get left counts + if (f->seq[i]) { + int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + ++sum[c == path[f->vpos + i]? 0 : 1]; + } + left[i] = sum[1]<<16 | sum[0]; + } + for (i = f->vlen - 1, sum[0] = sum[1] = 0; i >= 0; --i) { // get right counts + if (f->seq[i]) { + int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + ++sum[c == path[f->vpos + i]? 0 : 1]; + } + rght[i] = sum[1]<<16 | sum[0]; + } + // find the best flip point + for (i = m = 0, mi = -1, md = -1; i < f->vlen - 1; ++i) { + int a[2]; + a[0] = (left[i]&0xffff) + (rght[i+1]>>16&0xffff) - (rght[i+1]&0xffff) * FLIP_PENALTY; + a[1] = (left[i]>>16&0xffff) + (rght[i+1]&0xffff) - (rght[i+1]>>16&0xffff) * FLIP_PENALTY; + if (a[0] > a[1]) { + if (a[0] > m) m = a[0], md = 0, mi = i; + } else { + if (a[1] > m) m = a[1], md = 1, mi = i; + } + } + if (m - c[0] >= FLIP_THRES && m - c[1] >= FLIP_THRES) { // then flip + f->flip = 1; + if (md == 0) { // flip the tail + for (i = mi + 1; i < f->vlen; ++i) + if (f->seq[i] == 1) f->seq[i] = 2; + else if (f->seq[i] == 2) f->seq[i] = 1; + } else { // flip the head + for (i = 0; i <= mi; ++i) + if (f->seq[i] == 1) f->seq[i] = 2; + else if (f->seq[i] == 2) f->seq[i] = 1; + } + } + } + // update pcnt[] + if (!f->single) { + for (i = 0; i < f->vlen; ++i) { + int c; + if (f->seq[i] == 0) continue; + c = f->phase? 2 - f->seq[i] : f->seq[i] - 1; + if (c == path[f->vpos + i]) { + if (f->phase == 0) ++pcnt[f->vpos + i]; + else pcnt[f->vpos + i] += 1ull<<32; + } else { + if (f->phase == 0) pcnt[f->vpos + i] += 1<<16; + else pcnt[f->vpos + i] += 1ull<<48; + } + } + } + } + } + free(left); free(rght); + return pcnt; +} + +static uint64_t *genmask(int vpos, const uint64_t *pcnt, int *_n) +{ + int i, max = 0, max_i = -1, m = 0, n = 0, beg = 0, score = 0; + uint64_t *list = 0; + for (i = 0; i < vpos; ++i) { + uint64_t x = pcnt[i]; + int c[4], pre = score, s; + c[0] = x&0xffff; c[1] = x>>16&0xffff; c[2] = x>>32&0xffff; c[3] = x>>48&0xffff; + s = (c[1] + c[3] == 0)? -(c[0] + c[2]) : (c[1] + c[3] - 1); + if (c[3] > c[2]) s += c[3] - c[2]; + if (c[1] > c[0]) s += c[1] - c[0]; + score += s; + if (score < 0) score = 0; + if (pre == 0 && score > 0) beg = i; // change from zero to non-zero + if ((i == vpos - 1 || score == 0) && max >= MASK_THRES) { + if (n == m) { + m = m? m<<1 : 4; + list = realloc(list, m * 8); + } + list[n++] = (uint64_t)beg<<32 | max_i; + i = max_i; // reset i to max_i + score = 0; + } else if (score > max) max = score, max_i = i; + if (score == 0) max = 0; + } + *_n = n; + return list; +} + +// trim heading and tailing ambiguous bases; mark deleted and remove sequence +static int clean_seqs(int vpos, nseq_t *hash) +{ + khint_t k; + int ret = 0; + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + int beg, end, i; + if (f->vpos >= vpos) { + ret = 1; + continue; + } + for (i = 0; i < f->vlen; ++i) + if (f->seq[i] != 0) break; + beg = i; + for (i = f->vlen - 1; i >= 0; --i) + if (f->seq[i] != 0) break; + end = i + 1; + if (end - beg <= 0) kh_del(64, hash, k); + else { + if (beg != 0) memmove(f->seq, f->seq + beg, end - beg); + f->vpos += beg; f->vlen = end - beg; + f->single = f->vlen == 1? 1 : 0; + } + } + } + return ret; +} + +static int dump_aln(phaseg_t *g, int min_pos, const nseq_t *hash) +{ + int i, is_flip, drop_ambi; + drop_ambi = g->flag & FLAG_DROP_AMBI; + is_flip = (drand48() < 0.5); + for (i = 0; i < g->n; ++i) { + int end, which; + uint64_t key; + khint_t k; + bam1_t *b = g->b[i]; + key = X31_hash_string(bam_get_qname(b)); + end = bam_endpos(b); + if (end > min_pos) break; + k = kh_get(64, hash, key); + if (k == kh_end(hash)) which = 3; + else { + frag_t *f = &kh_val(hash, k); + if (f->ambig) which = drop_ambi? 2 : 3; + else if (f->phased && f->flip) which = 2; + else if (f->phased == 0) which = 3; + else { // phased and not flipped + char c = 'Y'; + which = f->phase; + bam_aux_append(b, "ZP", 'A', 1, (uint8_t*)&c); + } + if (which < 2 && is_flip) which = 1 - which; // increase the randomness + } + if (which == 3) which = (drand48() < 0.5); + if (sam_write1(g->out[which], g->out_hdr[which], b) < 0) { + print_error_errno("phase", "error writing to '%s'", g->out_name[which]); + return -1; + } + bam_destroy1(b); + g->b[i] = 0; + } + memmove(g->b, g->b + i, (g->n - i) * sizeof(void*)); + g->n -= i; + return 0; +} + +static int phase(phaseg_t *g, const char *chr, int vpos, uint64_t *cns, nseq_t *hash) +{ + int i, j, n_seqs = kh_size(hash), n_masked = 0, min_pos; + khint_t k; + frag_t **seqs; + int8_t *path, *sitemask; + uint64_t *pcnt, *regmask; + + if (vpos == 0) return 0; + i = clean_seqs(vpos, hash); // i is true if hash has an element with its vpos >= vpos + min_pos = i? cns[vpos]>>32 : 0x7fffffff; + if (vpos == 1) { + fprintf(samtools_stdout, "PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1); + fprintf(samtools_stdout, "M0\t%s\t%d\t%d\t%c\t%c\t%d\t0\t0\t0\t0\n//\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1, + "ACGTX"[cns[0]&3], "ACGTX"[cns[0]>>16&3], g->vpos_shift + 1); + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + if (f->vpos) continue; + f->flip = 0; + if (f->seq[0] == 0) f->phased = 0; + else f->phased = 1, f->phase = f->seq[0] - 1; + } + } + if (dump_aln(g, min_pos, hash) < 0) return -1; + ++g->vpos_shift; + return 1; + } + { // phase + int **cnt; + uint64_t *mask; + fprintf(samtools_stdout, "PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[vpos-1]>>32) + 1); + sitemask = calloc(vpos, 1); + cnt = count_all(g->k, vpos, hash); + path = dynaprog(g->k, vpos, cnt); + for (i = 0; i < vpos; ++i) free(cnt[i]); + free(cnt); + pcnt = fragphase(vpos, path, hash, 0); // do not fix chimeras when masking + mask = genmask(vpos, pcnt, &n_masked); + regmask = calloc(n_masked, 8); + for (i = 0; i < n_masked; ++i) { + regmask[i] = cns[mask[i]>>32]>>32<<32 | cns[(uint32_t)mask[i]]>>32; + for (j = mask[i]>>32; j <= (int32_t)mask[i]; ++j) + sitemask[j] = 1; + } + free(mask); + if (g->flag & FLAG_FIX_CHIMERA) { + free(pcnt); + pcnt = fragphase(vpos, path, hash, 1); + } + } + for (i = 0; i < n_masked; ++i) + fprintf(samtools_stdout, "FL\t%s\t%d\t%d\n", chr, (int)(regmask[i]>>32) + 1, (int)regmask[i] + 1); + for (i = 0; i < vpos; ++i) { + uint64_t x = pcnt[i]; + int8_t c[2]; + c[0] = (cns[i]&0xffff)>>2 == 0? 4 : (cns[i]&3); + c[1] = (cns[i]>>16&0xffff)>>2 == 0? 4 : (cns[i]>>16&3); + fprintf(samtools_stdout, "M%d\t%s\t%d\t%d\t%c\t%c\t%d\t%d\t%d\t%d\t%d\n", sitemask[i]+1, chr, (int)(cns[0]>>32) + 1, (int)(cns[i]>>32) + 1, "ACGTX"[c[path[i]]], "ACGTX"[c[1-path[i]]], + i + g->vpos_shift + 1, (int)(x&0xffff), (int)(x>>16&0xffff), (int)(x>>32&0xffff), (int)(x>>48&0xffff)); + } + free(path); free(pcnt); free(regmask); free(sitemask); + seqs = calloc(n_seqs, sizeof(frag_t*)); + for (k = 0, i = 0; k < kh_end(hash); ++k) + if (kh_exist(hash, k) && kh_val(hash, k).vpos < vpos && !kh_val(hash, k).single) + seqs[i++] = &kh_val(hash, k); + n_seqs = i; + ks_introsort_rseq(n_seqs, seqs); + for (i = 0; i < n_seqs; ++i) { + frag_t *f = seqs[i]; + fprintf(samtools_stdout, "EV\t0\t%s\t%d\t40\t%dM\t*\t0\t0\t", chr, f->vpos + 1 + g->vpos_shift, f->vlen); + for (j = 0; j < f->vlen; ++j) { + uint32_t c = cns[f->vpos + j]; + if (f->seq[j] == 0) fputc('N', samtools_stdout); + else fputc("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)], samtools_stdout); + } + fprintf(samtools_stdout, "\t*\tYP:i:%d\tYF:i:%d\tYI:i:%d\tYO:i:%d\tYS:i:%d\n", f->phase, f->flip, f->in, f->out, f->beg+1); + } + free(seqs); + fprintf(samtools_stdout, "//\n"); + fflush(samtools_stdout); + g->vpos_shift += vpos; + if (dump_aln(g, min_pos, hash) < 0) return -1; + return vpos; +} + +static void update_vpos(int vpos, nseq_t *hash) +{ + khint_t k; + for (k = 0; k < kh_end(hash); ++k) { + if (kh_exist(hash, k)) { + frag_t *f = &kh_val(hash, k); + if (f->vpos < vpos) kh_del(64, hash, k); // TODO: if frag_t::seq is allocated dynamically, free it + else f->vpos -= vpos; + } + } +} + +static nseq_t *shrink_hash(nseq_t *hash) // TODO: to implement +{ + return hash; +} + +static int readaln(void *data, bam1_t *b) +{ + phaseg_t *g = (phaseg_t*)data; + int ret; + while (1) + { + ret = sam_read1(g->fp, g->fp_hdr, b); + if (ret < 0) break; + if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue; + if ( g->pre ) { + if (g->n == g->m) { + g->m = g->m? g->m<<1 : 16; + g->b = realloc(g->b, g->m * sizeof(bam1_t*)); + } + g->b[g->n++] = bam_dup1(b); + } + break; + } + return ret; +} + +static khash_t(set64) *loadpos(const char *fn, sam_hdr_t *h) +{ + gzFile fp; + kstream_t *ks; + int ret, dret; + kstring_t *str; + khash_t(set64) *hash; + + fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); + if (fp == NULL) { + print_error_errno("phase", "Couldn't open site file '%s'", fn); + return NULL; + } + + hash = kh_init(set64); + str = calloc(1, sizeof(kstring_t)); + + ks = ks_init(fp); + while (ks_getuntil(ks, 0, str, &dret) >= 0) { + int tid = bam_name2id(h, str->s); + if (tid >= 0 && dret != '\n') { + if (ks_getuntil(ks, 0, str, &dret) >= 0) { + uint64_t x = (uint64_t)tid<<32 | (atoi(str->s) - 1); + kh_put(set64, hash, x, &ret); + } else break; + } + if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n'); + if (dret < 0) break; + } + ks_destroy(ks); + gzclose(fp); + free(str->s); free(str); + return hash; +} + +static int gl2cns(float q[16]) +{ + int i, j, min_ij; + float min, min2; + min = min2 = 1e30; min_ij = -1; + for (i = 0; i < 4; ++i) { + for (j = i; j < 4; ++j) { + if (q[i<<2|j] < min) min_ij = i<<2|j, min2 = min, min = q[i<<2|j]; + else if (q[i<<2|j] < min2) min2 = q[i<<2|j]; + } + } + return (min_ij>>2&3) == (min_ij&3)? 0 : 1<<18 | (min_ij>>2&3)<<16 | (min_ij&3) | (int)(min2 - min + .499) << 2; +} + +static int start_output(phaseg_t *g, int c, const char *middle, const htsFormat *fmt) +{ + kstring_t s = { 0, 0, NULL }; + ksprintf(&s, "%s.%s.%s", g->pre, middle, hts_format_file_extension(fmt)); + g->out_name[c] = ks_release(&s); + g->out[c] = sam_open_format(g->out_name[c], "wb", fmt); + if (! g->out[c]) { + print_error_errno("phase", "Failed to open output file '%s'", g->out_name[c]); + return -1; + } + + g->out_hdr[c] = sam_hdr_dup(g->fp_hdr); + if (!g->no_pg && sam_hdr_add_pg(g->out_hdr[c], "samtools", + "VN", samtools_version(), + g->arg_list ? "CL": NULL, + g->arg_list ? g->arg_list : NULL, + NULL)) { + print_error("phase", "failed to add PG line to header"); + return -1; + } + if (sam_hdr_write(g->out[c], g->out_hdr[c]) < 0) { + print_error_errno("phase", "Failed to write header for '%s'", g->out_name[c]); + return -1; + } + + return 0; +} + +int main_phase(int argc, char *argv[]) +{ + int c, tid, pos, vpos = 0, n, lasttid = -1, max_vpos = 0, usage = 0; + int status = EXIT_SUCCESS; + const bam_pileup1_t *plp; + bam_plp_t iter; + nseq_t *seqs; + uint64_t *cns = 0; + phaseg_t g; + char *fn_list = 0; + khash_t(set64) *set = 0; + errmod_t *em; + uint16_t *bases; + + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'), + {"min-BQ", required_argument, NULL, 'Q'}, + {"min-bq", required_argument, NULL, 'Q'}, + {"no-PG", no_argument, NULL, 1}, + { NULL, 0, NULL, 0 } + }; + + // FIXME Leaks galore in the case of error returns + + memset(&g, 0, sizeof(phaseg_t)); + g.flag = FLAG_FIX_CHIMERA; + g.min_varLOD = 37; g.k = 13; g.min_baseQ = 13; g.max_depth = 256; + while ((c = getopt_long(argc, argv, "Q:eFq:k:b:l:D:A", lopts, NULL)) >= 0) { + switch (c) { + case 'D': g.max_depth = atoi(optarg); break; + case 'q': g.min_varLOD = atoi(optarg); break; + case 'Q': g.min_baseQ = atoi(optarg); break; + case 'k': g.k = atoi(optarg); break; + case 'F': g.flag &= ~FLAG_FIX_CHIMERA; break; + case 'e': g.flag |= FLAG_LIST_EXCL; break; + case 'A': g.flag |= FLAG_DROP_AMBI; break; + case 'b': g.pre = strdup(optarg); break; + case 'l': fn_list = strdup(optarg); break; + case 1: g.no_pg = 1; break; + default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': usage=1; break; + } + if (usage) break; + } + if (usage || argc == optind) { + fprintf(samtools_stderr, "\n"); + fprintf(samtools_stderr, "Usage: samtools phase [options] \n\n"); + fprintf(samtools_stderr, "Options: -k INT block length [%d]\n", g.k); + fprintf(samtools_stderr, " -b STR prefix of BAMs to output [null]\n"); + fprintf(samtools_stderr, " -q INT min het phred-LOD [%d]\n", g.min_varLOD); + fprintf(samtools_stderr, " -Q, --min-BQ INT\n" + " min base quality in het calling [%d]\n", g.min_baseQ); + fprintf(samtools_stderr, " -D INT max read depth [%d]\n", g.max_depth); +// fprintf(samtools_stderr, " -l FILE list of sites to phase [null]\n"); + fprintf(samtools_stderr, " -F do not attempt to fix chimeras\n"); + fprintf(samtools_stderr, " -A drop reads with ambiguous phase\n"); + fprintf(samtools_stderr, " --no-PG do not add a PG line\n"); +// fprintf(samtools_stderr, " -e do not discover SNPs (effective with -l)\n"); + fprintf(samtools_stderr, "\n"); + + sam_global_opt_help(samtools_stderr, "-....--."); + + return 1; + } + g.fp = sam_open_format(argv[optind], "r", &ga.in); + if (!g.fp) { + print_error_errno("phase", "Couldn't open '%s'", argv[optind]); + return 1; + } + g.fp_hdr = sam_hdr_read(g.fp); + if (g.fp_hdr == NULL) { + fprintf(samtools_stderr, "[%s] Failed to read header for '%s'\n", + __func__, argv[optind]); + return 1; + } + if (!g.no_pg && !(g.arg_list = stringify_argv(argc+1, argv-1))) { + print_error("phase", "failed to create arg_list"); + return 1; + } + if (fn_list) { // read the list of sites to phase + set = loadpos(fn_list, g.fp_hdr); + if (set == NULL) return 1; + free(fn_list); + } else g.flag &= ~FLAG_LIST_EXCL; + if (g.pre) { // open BAMs to write + if (ga.out.format == unknown_format) + ga.out.format = bam; // default via "wb". + + // Open each output file g.out[0..2], dupping and writing the header + if (start_output(&g, 0, "0", &ga.out) < 0 || + start_output(&g, 1, "1", &ga.out) < 0 || + start_output(&g, 2, "chimera", &ga.out) < 0) return 1; + } + + iter = bam_plp_init(readaln, &g); + g.vpos_shift = 0; + seqs = kh_init(64); + em = errmod_init(1. - 0.83); + bases = calloc(g.max_depth, 2); + fprintf(samtools_stdout, "CC\n"); + fprintf(samtools_stdout, "CC\tDescriptions:\nCC\n"); + fprintf(samtools_stdout, "CC\t CC comments\n"); + fprintf(samtools_stdout, "CC\t PS start of a phase set\n"); + fprintf(samtools_stdout, "CC\t FL filtered region\n"); + fprintf(samtools_stdout, "CC\t M[012] markers; 0 for singletons, 1 for phased and 2 for filtered\n"); + fprintf(samtools_stdout, "CC\t EV supporting reads; SAM format\n"); + fprintf(samtools_stdout, "CC\t // end of a phase set\nCC\n"); + fprintf(samtools_stdout, "CC\tFormats of PS, FL and M[012] lines (1-based coordinates):\nCC\n"); + fprintf(samtools_stdout, "CC\t PS chr phaseSetStart phaseSetEnd\n"); + fprintf(samtools_stdout, "CC\t FL chr filterStart filterEnd\n"); + fprintf(samtools_stdout, "CC\t M? chr PS pos allele0 allele1 hetIndex #supports0 #errors0 #supp1 #err1\n"); + fprintf(samtools_stdout, "CC\nCC\n"); + fflush(samtools_stdout); + while ((plp = bam_plp_auto(iter, &tid, &pos, &n)) != 0) { + int i, k, c, tmp, dophase = 1, in_set = 0; + float q[16]; + if (tid < 0) break; + if (tid != lasttid) { // change of chromosome + g.vpos_shift = 0; + if (lasttid >= 0) { + seqs = shrink_hash(seqs); + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, lasttid), + vpos, cns, seqs) < 0) { + return 1; + } + update_vpos(0x7fffffff, seqs); + } + lasttid = tid; + vpos = 0; + } + if (set && kh_get(set64, set, (uint64_t)tid<<32 | pos) != kh_end(set)) in_set = 1; + if (n > g.max_depth) continue; // do not proceed if the depth is too high + // fill the bases array and check if there is a variant + for (i = k = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint8_t *seq; + int q, baseQ, b; + if (p->is_del || p->is_refskip) continue; + baseQ = bam_get_qual(p->b)[p->qpos]; + if (baseQ < g.min_baseQ) continue; + seq = bam_get_seq(p->b); + b = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (b > 3) continue; + q = baseQ < p->b->core.qual? baseQ : p->b->core.qual; + if (q < 4) q = 4; + if (q > 63) q = 63; + bases[k++] = q<<5 | (int)bam_is_rev(p->b)<<4 | b; + } + if (k == 0) continue; + errmod_cal(em, k, 4, bases, q); // compute genotype likelihood + c = gl2cns(q); // get the consensus + // tell if to proceed + if (set && (g.flag&FLAG_LIST_EXCL) && !in_set) continue; // not in the list + if (!in_set && (c&0xffff)>>2 < g.min_varLOD) continue; // not a variant + // add the variant + if (vpos == max_vpos) { + max_vpos = max_vpos? max_vpos<<1 : 128; + cns = realloc(cns, max_vpos * 8); + } + cns[vpos] = (uint64_t)pos<<32 | c; + for (i = 0; i < n; ++i) { + const bam_pileup1_t *p = plp + i; + uint64_t key; + khint_t k; + uint8_t *seq = bam_get_seq(p->b); + frag_t *f; + if (p->is_del || p->is_refskip) continue; + if (p->b->core.qual == 0) continue; + // get the base code + c = seq_nt16_int[bam_seqi(seq, p->qpos)]; + if (c == (cns[vpos]&3)) c = 1; + else if (c == (cns[vpos]>>16&3)) c = 2; + else c = 0; + // write to seqs + key = X31_hash_string(bam_get_qname(p->b)); + k = kh_put(64, seqs, key, &tmp); + f = &kh_val(seqs, k); + if (tmp == 0) { // present in the hash table + if (vpos - f->vpos + 1 < MAX_VARS) { + f->vlen = vpos - f->vpos + 1; + f->seq[f->vlen-1] = c; + f->end = bam_endpos(p->b); + } + dophase = 0; + } else { // absent + memset(f->seq, 0, MAX_VARS); + f->beg = p->b->core.pos; + f->end = bam_endpos(p->b); + f->vpos = vpos, f->vlen = 1, f->seq[0] = c, f->single = f->phased = f->flip = f->ambig = 0; + } + } + if (dophase) { + seqs = shrink_hash(seqs); + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) { + return 1; + } + update_vpos(vpos, seqs); + cns[0] = cns[vpos]; + vpos = 0; + } + ++vpos; + } + if (tid >= 0) { + if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) { + return 1; + } + } + + if (n < 0) { + print_error("phase", "error reading from '%s'", argv[optind]); + status = EXIT_FAILURE; + } + + sam_hdr_destroy(g.fp_hdr); + bam_plp_destroy(iter); + sam_close(g.fp); + kh_destroy(64, seqs); + kh_destroy(set64, set); + free(cns); + errmod_destroy(em); + free(bases); + if (g.pre) { + int res = 0; + for (c = 0; c <= 2; ++c) { + if (sam_close(g.out[c]) < 0) { + fprintf(samtools_stderr, "[%s] error on closing '%s'\n", + __func__, g.out_name[c]); + res = 1; + } + sam_hdr_destroy(g.out_hdr[c]); + free(g.out_name[c]); + } + free(g.pre); free(g.b); + if (res) return 1; + } + free(g.arg_list); + sam_global_args_free(&ga); + return status; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c new file mode 100644 index 0000000000000000000000000000000000000000..4e522cddf13a59b4575476a632aa23b28555f442 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c @@ -0,0 +1,587 @@ +/* reset.c -- removes aligner updates and reference data from input sam / + bam / cram file and makes read data raw for new processing + + Copyright (C) 2022, 2023 Genome Research Ltd. + + Author: Vasudeva Sarma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE + +*/ + +#include + +#include "samtools.h" +#include "htslib/sam.h" +#include "sam_opts.h" +#include "htslib/thread_pool.h" +#include "htslib/khash.h" +#include "sam_utils.h" +#include + +#define TAGNUM(X) (((X)[0] << 8) | (X)[1]) //to create key for aux tags, like type key in htslib +#define LONG_OPT(X) (128 + (X)) //to handle long and short options with same char + +typedef struct conf_data +{ + int keepRGs; //RG line handling + int noPGentry; //PG line for reset op or not + auxhash_t aux_keep; //SET that holds the aux tags to be retained + auxhash_t aux_remove; //SET that holds the aux tags to be removed + char *pgid; //PG id onwards which to be removed +} conf_data; + +/// usage - print the usage +/** @param fp pointer to the file / terminal to which usage to be dumped +returns nothing +*/ +static void usage(FILE *fp) +{ + fprintf(fp, "Usage: samtools reset [options]\n\ + -o FILE Output file\n\ + -x, --remove-tag STR\n\ + Aux tags to be removed\n\ + --keep-tag STR\n\ + Aux tags to be retained. Equivalent to -x ^STR\n\ + --reject-PG ID\n\ + Removes PG line with ID matching to input and succeeding PG lines\n\ + --no-RG To have RG lines or not\n\ + --no-PG To have PG entry or not for reset operation\n"); + + sam_global_opt_help(fp, "--O--@--"); + return; +} + +/// removeauxtags - remove aux tags in bam data which are not present in acceptable tag set +/** @param bamdata - pointer to the bamdata from which needs the filtering + * @param config - pointer to conf_data +returns nothing +*/ +void removeauxtags(bam1_t *bamdata, conf_data *config) +{ + uint8_t *auxdata = NULL; + const char *tag = NULL, rg[] = "RG"; + khint_t iter = 0; + int ret = 0; + + if (!bamdata || !config || (!config->aux_keep && !config->aux_remove && config->keepRGs)) + return; + + //remove RG tags from bamdata if keepRG is false + if (!config->keepRGs) { + if (!config->aux_keep && !config->aux_remove) { + //none of aux tag filter in use, create remove filter + config->aux_remove = kh_init(aux_exists); + } + + if (config->aux_keep) { + //keep set in use, remove RG if present + iter = kh_get(aux_exists, config->aux_keep, TAGNUM(rg)); + if (iter != kh_end(config->aux_keep)) { + kh_del(aux_exists, config->aux_keep, iter); + } + } + if (config->aux_remove) { + //remove set in use, add RG if not present + iter = kh_get(aux_exists, config->aux_remove, TAGNUM(rg)); + if (iter == kh_end(config->aux_remove)) { + kh_put(aux_exists, config->aux_remove, TAGNUM(rg), &ret); + } + } + } + + for (auxdata = bam_aux_first(bamdata); auxdata; ) { + tag = bam_aux_tag(auxdata); + if (config->aux_keep) { //keep option or remove option with ^ in use + iter = kh_get(aux_exists, config->aux_keep, TAGNUM(tag)); + if (iter == kh_end(config->aux_keep)) { //not present in keep, remove + auxdata = bam_aux_remove(bamdata, auxdata); + } + else { //present, keep + auxdata = bam_aux_next(bamdata, auxdata); + } + } + else if (config->aux_remove) { //remove option in use + iter = kh_get(aux_exists, config->aux_remove, TAGNUM(tag)); + if (iter != kh_end(config->aux_remove)) { //present in remove, remove + auxdata = bam_aux_remove(bamdata, auxdata); + } + else { //not present, keep + auxdata = bam_aux_next(bamdata, auxdata); + } + } + //else impossible + } +} + +/// getRGlines - add RG lines from input header to output header +/** @param in_samhdr - pointer to input sam header data + * @param out_samhdr - pointer to output sam header data +returns 1 on failure 0 on success +*/ +int getRGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr) +{ + kstring_t line = KS_INITIALIZE; + int i = 0, ret = 0, count = 0; + const char rg[] = "RG"; + + if (!in_samhdr || !out_samhdr) { + fprintf(stderr, "Invalid parameters in getRGlines!\n"); + return 1; + } + + if (-1 == (count = sam_hdr_count_lines(in_samhdr, rg))) { + fprintf(stderr, "Failed to get RG count!\n"); + return 1; + } + + for (i = 0; i < count; ++i) + { + ks_clear(&line); + if (sam_hdr_find_line_pos(in_samhdr, rg, i, &line)) { + fprintf(stderr, "Failed to get RG data!\n"); + ret = 1; + break; + } + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(stderr, "Failed to add RG data!\n"); + ret = 1; + break; + } + } + ks_free(&line); + + return ret; +} + +/// getPGlines - add PG lines from input header to output header based on user option +/** @param in_samhdr - pointer to input sam header data + * @param out_samhdr - pointer to output sam header data + * @param config - pointer to internal configuration data + * @param argdump - string containing dump of command line invocation +returns 1 on failure 0 on success +*/ +int getPGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr, conf_data *config, const char *argdump) +{ + kstring_t line = KS_INITIALIZE, id = KS_INITIALIZE; + int i = 0, ret = 0, count = 0; + const char pg[] = "PG"; + + if (!in_samhdr || !out_samhdr || !config) { + fprintf(stderr, "Invalid parameters in getPGlines!\n"); + return 1; + } + + if (-1 == (count = sam_hdr_count_lines(in_samhdr, pg))) { + fprintf(stderr, "Failed to get PG count!\n"); + return 1; + } + + if (config->pgid && config->pgid[0]) { //when reject-PG is given, and is not empty, remove given pg onwards + for (i = 0; i < count; ++i) { + if (sam_hdr_find_tag_pos(in_samhdr, pg, i, "ID", &id)) { + fprintf(stderr, "Failed to get PG entry fields for line %d!\n", i + 1); + break; + } + + if (!strcmp(id.s, config->pgid)) + break; + + //either current PG is prior to rejected one or all PGs are in, get PG line and add + ks_clear(&line); + if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) { + fprintf(stderr, "Failed to get PG data at %d!\n", i + 1); + ret = 1; + break; + } + + //add to output + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(stderr, "Failed to add PG data!\n"); + ret = 1; + break; + } + } + } + else { //keep all + for (i = 0; i < count; ++i) { + if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) { + fprintf(stderr, "Failed to get PG data at %d!\n", i + 1); + ret = 1; + break; + } + //line has the required PG data + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(stderr, "Failed to add PG data!\n"); + ret = 1; + break; + } + } + } + + if (!ret && !config->noPGentry) { + //add PG entry with reset command + if (-1 == (ret = sam_hdr_add_pg(out_samhdr, "samtools", "CL", argdump, NULL))) { + fprintf(stderr, "Failed to set PG entry!\n"); + } + } + ks_free(&line); + ks_free(&id); + + return ret; +} + +/// reset - do the reset of data and create output; create output header with required rg/pg data, add bamdata with flags set to unmapped, pair info and orientation reset, +// reerse and complement alignment if required +/** @param infile - input samfile pointer + * @param outfile - output sam file pointer + * @param config - pointer to internal configuration data + * @param args - string containing dump of command line invocation +returns 1 on failure 0 on success +*/ +int reset(samFile *infile, samFile *outfile, conf_data *config, char *args) +{ + sam_hdr_t *in_samhdr = NULL, *out_samhdr = NULL; + int ret = EXIT_FAILURE, ret_r = 0, ret_w = 0, i = 0; + bam1_t *bamdata = NULL, *outdata = NULL; + kstring_t querydata = KS_INITIALIZE, qualdata = KS_INITIALIZE; + char *sp = NULL, *qp = NULL; + uint8_t *bamquery = NULL, *bamqual = NULL; + + if (!infile || !outfile) { + fprintf(stderr, "Invalid parameters in reset!\n"); + goto error; + } + + //read input header + in_samhdr = sam_hdr_read(infile); + if (!in_samhdr) + { + fprintf(stderr, "Failed to read header from file!\n"); + goto error; + } + //create output header + if (!(out_samhdr = sam_hdr_init())) + { + fprintf(stderr, "Failed to create output header!\n"); + goto error; + } + + //add version to output header + if (-1 == sam_hdr_add_line(out_samhdr,"HD", "VN", SAM_FORMAT_VERSION, NULL)) { + fprintf(stderr, "Failed to set header data!\n"); + goto error; + } + //add RG / PG lines if configured + if ((config->keepRGs && getRGlines(in_samhdr, out_samhdr)) || + getPGlines(in_samhdr, out_samhdr, config, args)) { + goto error; + } + + //write output header + if (sam_hdr_write(outfile, out_samhdr)) { + print_error_errno("reset", "Output header write failed (%d)!\n", errno); + goto error; + } + + bamdata = bam_init1(); //input bam + outdata = bam_init1(); //output bam + if (!bamdata || !outdata) + { + fprintf(stderr, "Failed to allocate data memory!\n"); + goto error; + } + + errno = 0; i = 0; + sp = NULL; qp = NULL; + bamquery = NULL; bamqual = NULL; + + //get bam data, make updates and dump to output + while (0 <= (ret_r = sam_read1(infile, in_samhdr, bamdata))) + { + sp = NULL; qp = NULL; + bamquery = NULL; bamqual = NULL; + + // read data + if (bamdata->core.flag & BAM_FSECONDARY || bamdata->core.flag & BAM_FSUPPLEMENTARY) { + continue; + } + + //update flags + uint16_t flags = bamdata->core.flag & ~BAM_FPROPER_PAIR; //reset pair info + flags |= BAM_FUNMAP; //mark as unmapped + if (bamdata->core.flag & BAM_FPAIRED) { + flags |= BAM_FMUNMAP; //mark mate as unmapped, if it was a pair + } + flags &= ~BAM_FMREVERSE; //reset mate orientation + + if (0 > ks_resize(&querydata, bamdata->core.l_qseq) || + 0 > ks_resize(&qualdata, bamdata->core.l_qseq)) { + fprintf(stderr, "Failed to get allocate memory!\n"); + ret_r = -4; + break; + } + ks_clear(&querydata); + ks_clear(&qualdata); + + sp = ks_str(&querydata); + qp = ks_str(&qualdata); + bamquery = bam_get_seq(bamdata); + bamqual = bam_get_qual(bamdata); + if (bamdata->core.flag & BAM_FREVERSE) { + //sequence data ordered as reverse complemented, reorder/complement sequence and quality data as read and clear the flag + for (i = bamdata->core.l_qseq - 1; i >= 0; --i) { + *sp++ = "=TGKCYSBAWRDMHVN"[bam_seqi(bamquery, i)]; + *qp++ = bamqual[i]; + } + flags &= ~BAM_FREVERSE; //reset flag as well + } + else { + //data in read order itself + for (i = 0; i < bamdata->core.l_qseq ; ++i) { + *sp++ = seq_nt16_str[bam_seqi(bamquery, i)]; + } + memcpy(qp, bam_get_qual(bamdata), bamdata->core.l_qseq); + } + + removeauxtags(bamdata, config); + if (0 > (ret_w = bam_set1(outdata, bamdata->core.l_qname - bamdata->core.l_extranul - 1, bam_get_qname(bamdata), flags, -1, -1, 0, 0, NULL, -1, -1, 0, bamdata->core.l_qseq, querydata.s, qualdata.s, bam_get_l_aux(bamdata)))) { + print_error_errno("reset", "Failed to set output data (%d)!\n", errno); + break; + } + + memcpy(bam_get_aux(outdata), bam_get_aux(bamdata), bam_get_l_aux(bamdata)); + outdata->l_data += bam_get_l_aux(bamdata); + + errno = 0; + //write bam data to output + if (0 > (ret_w = sam_write1(outfile, out_samhdr, outdata))) + { + print_error_errno("reset", "Failed to write output data (%d)!\n", errno); + break; + } + // wrote the data, continue read/write cycle + errno = 0; + } + + if (-1 > ret_r || 0 > ret_w) { + //some error + fprintf(stderr, "Error during %s!\n", (-1 > ret_r)? "read" : "write"); + } + else { + // no error! + ret = EXIT_SUCCESS; + } + +error: + // clean up and return result + if (in_samhdr) + sam_hdr_destroy(in_samhdr); + if (out_samhdr) + sam_hdr_destroy(out_samhdr); + + if (bamdata) + bam_destroy1(bamdata); + if (outdata) + bam_destroy1(outdata); + + if (qualdata.s) + ks_free(&qualdata); + if (querydata.s) + ks_free(&querydata); + return ret; +} + +/// cleanup - free up allocations made +/** @param config - pointer to internal configuration data +returns nothing +*/ +void cleanup(conf_data *config) +{ + if (config->aux_keep) { + kh_destroy(aux_exists, config->aux_keep); + config->aux_keep = NULL; + } + if (config->aux_remove) { + kh_destroy(aux_exists, config->aux_remove); + config->aux_remove = NULL; + } +} + +/// main_reset - starts the reset of data +/** @param argc - count of arguments + * @param argv - pointer to array of arguments +returns 1 on failure 0 on success +*/ +int main_reset(int argc, char *argv[]) +{ + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', '-', 'O', '-', '-', '@'), //let output format and thread count be given by user - long options + {"keep-tag", required_argument, NULL, LONG_OPT('x')}, //aux tags to be retained, supports ^ STR + {"remove-tag", required_argument, NULL, 'x'}, //aux tags to be removed + {"no-RG", no_argument, NULL, 1}, //no RG lines in output, default is to keep them + //reject PG lines from input, default is to keep them (i.e. option not given); without optional filename, all PGs removed and those given in file are filtered when optional filename is given + {"reject-PG", required_argument, NULL, 'p'}, //reject entries from this PG onwards + {"no-PG", no_argument, NULL, 2}, //do not add PG entry for reset operation, default is to add it + {NULL, 0, NULL, 0} + }; + samFile *infile = NULL, *outfile = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool tpool = {NULL, 0}; + const char *inname = NULL, *outname = NULL; + int c = 0, ret = EXIT_FAILURE; + char outmode[4] = "w", *args = NULL; + conf_data resetconf = {1, 0, NULL, NULL, NULL}; //keep RGs and PGs by default + + + //samtools reset -o outfile -x/--remove-tag ... --keep-tag ... --threads=n --output-fmt=fmt --no-RG --reject-PG pgid --no-PG [] + while ((c = getopt_long(argc, argv, "o:@:x:O:", lopts, NULL)) >= 0) + { + switch (c) + { + case 1: //--no-RG + if (!resetconf.keepRGs) { + usage(stderr); //already given! + goto exit; + } + resetconf.keepRGs = 0; + break; + case 2: //--no-PG + if (resetconf.noPGentry) { + usage(stderr); //already given! + goto exit; + } + resetconf.noPGentry = 1; + break; + case 'p': //--reject-PG= + if (resetconf.pgid) { + usage(stderr); //already given! + goto exit; + } + resetconf.pgid = optarg; + break; + case 'o': //output file name + if (outname) { //already given! + usage(stderr); + goto exit; + + } + outname = optarg; + break; + case 'x': //remove aux tag + if (*optarg == '^') { //remove all except given ones! + if (parse_aux_list(&resetconf.aux_keep, optarg+1, "main_reset")) { + usage(stderr); + goto exit; + } + } + else { //remove given ones + if (parse_aux_list(&resetconf.aux_remove, optarg, "main_reset")) { + usage(stderr); + goto exit; + } + } + break; + case LONG_OPT('x'): //keep aux tags + if (parse_aux_list(&resetconf.aux_keep, optarg, "main_reset")) { + usage(stderr); + goto exit; + } + break; + // handle standard samtool options like thread count, verbosity... + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) + break; + // else fall-through + // couldn't parse or unknown options, show usage! + case '?': //unknown options found! + usage(stderr); + goto exit; + break; + } + } + + if (argc == 1 && isatty(STDIN_FILENO)) { + //no args and input is stdin -- it is the usage check + usage(stdout); + ret = EXIT_SUCCESS; + goto exit; + } + //else have other args or input from redirection/pipe/other device -- validate and work + + if (!outname) + outname = "-"; + + //check and fail if unnecessary parameters are given + c = argc - optind; + if (c > 1) { + usage(stderr); + goto exit; + } + + if (c == 1) { + inname = argv[optind]; + } + else { + inname = "-"; + } + + //set output file format based on name + sam_open_mode(outmode + 1, outname, NULL); + + //open input and output files + infile = sam_open(inname, "r"); + outfile = sam_open_format(outname, outmode, &ga.out); + if (!infile || !outfile) { + fprintf(stderr, "Could not open %s%s%s\n", !infile ? inname : "", (!infile && !outfile)? ", " : "", !outfile ? outname : ""); + goto exit; + } + + // set the thread count if given as argument + if (ga.nthreads > 0) + { + if (!(tpool.pool = hts_tpool_init(ga.nthreads))) + { + fprintf(stderr, "\nFailed to setup thread pool\n"); + goto exit; + } + + hts_set_opt(infile, HTS_OPT_THREAD_POOL, &tpool); + hts_set_opt(outfile, HTS_OPT_THREAD_POOL, &tpool); + } + + args = stringify_argv(argc + 1, argv - 1); //to dump invocation in PG line + + //do the reset! + ret = reset(infile, outfile, &resetconf, args); + +exit: + if (args) + free(args); + if (infile) + sam_close(infile); + if (outfile) + sam_close(outfile); + if (tpool.pool) + hts_tpool_destroy(tpool.pool); + cleanup(&resetconf); + sam_global_args_free(&ga); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..c98946f0228ff81bac07e6fe149efc95c83bf12a --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/reset.c.pysam.c @@ -0,0 +1,589 @@ +#include "samtools.pysam.h" + +/* reset.c -- removes aligner updates and reference data from input sam / + bam / cram file and makes read data raw for new processing + + Copyright (C) 2022, 2023 Genome Research Ltd. + + Author: Vasudeva Sarma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE + +*/ + +#include + +#include "samtools.h" +#include "htslib/sam.h" +#include "sam_opts.h" +#include "htslib/thread_pool.h" +#include "htslib/khash.h" +#include "sam_utils.h" +#include + +#define TAGNUM(X) (((X)[0] << 8) | (X)[1]) //to create key for aux tags, like type key in htslib +#define LONG_OPT(X) (128 + (X)) //to handle long and short options with same char + +typedef struct conf_data +{ + int keepRGs; //RG line handling + int noPGentry; //PG line for reset op or not + auxhash_t aux_keep; //SET that holds the aux tags to be retained + auxhash_t aux_remove; //SET that holds the aux tags to be removed + char *pgid; //PG id onwards which to be removed +} conf_data; + +/// usage - print the usage +/** @param fp pointer to the file / terminal to which usage to be dumped +returns nothing +*/ +static void usage(FILE *fp) +{ + fprintf(fp, "Usage: samtools reset [options]\n\ + -o FILE Output file\n\ + -x, --remove-tag STR\n\ + Aux tags to be removed\n\ + --keep-tag STR\n\ + Aux tags to be retained. Equivalent to -x ^STR\n\ + --reject-PG ID\n\ + Removes PG line with ID matching to input and succeeding PG lines\n\ + --no-RG To have RG lines or not\n\ + --no-PG To have PG entry or not for reset operation\n"); + + sam_global_opt_help(fp, "--O--@--"); + return; +} + +/// removeauxtags - remove aux tags in bam data which are not present in acceptable tag set +/** @param bamdata - pointer to the bamdata from which needs the filtering + * @param config - pointer to conf_data +returns nothing +*/ +void removeauxtags(bam1_t *bamdata, conf_data *config) +{ + uint8_t *auxdata = NULL; + const char *tag = NULL, rg[] = "RG"; + khint_t iter = 0; + int ret = 0; + + if (!bamdata || !config || (!config->aux_keep && !config->aux_remove && config->keepRGs)) + return; + + //remove RG tags from bamdata if keepRG is false + if (!config->keepRGs) { + if (!config->aux_keep && !config->aux_remove) { + //none of aux tag filter in use, create remove filter + config->aux_remove = kh_init(aux_exists); + } + + if (config->aux_keep) { + //keep set in use, remove RG if present + iter = kh_get(aux_exists, config->aux_keep, TAGNUM(rg)); + if (iter != kh_end(config->aux_keep)) { + kh_del(aux_exists, config->aux_keep, iter); + } + } + if (config->aux_remove) { + //remove set in use, add RG if not present + iter = kh_get(aux_exists, config->aux_remove, TAGNUM(rg)); + if (iter == kh_end(config->aux_remove)) { + kh_put(aux_exists, config->aux_remove, TAGNUM(rg), &ret); + } + } + } + + for (auxdata = bam_aux_first(bamdata); auxdata; ) { + tag = bam_aux_tag(auxdata); + if (config->aux_keep) { //keep option or remove option with ^ in use + iter = kh_get(aux_exists, config->aux_keep, TAGNUM(tag)); + if (iter == kh_end(config->aux_keep)) { //not present in keep, remove + auxdata = bam_aux_remove(bamdata, auxdata); + } + else { //present, keep + auxdata = bam_aux_next(bamdata, auxdata); + } + } + else if (config->aux_remove) { //remove option in use + iter = kh_get(aux_exists, config->aux_remove, TAGNUM(tag)); + if (iter != kh_end(config->aux_remove)) { //present in remove, remove + auxdata = bam_aux_remove(bamdata, auxdata); + } + else { //not present, keep + auxdata = bam_aux_next(bamdata, auxdata); + } + } + //else impossible + } +} + +/// getRGlines - add RG lines from input header to output header +/** @param in_samhdr - pointer to input sam header data + * @param out_samhdr - pointer to output sam header data +returns 1 on failure 0 on success +*/ +int getRGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr) +{ + kstring_t line = KS_INITIALIZE; + int i = 0, ret = 0, count = 0; + const char rg[] = "RG"; + + if (!in_samhdr || !out_samhdr) { + fprintf(samtools_stderr, "Invalid parameters in getRGlines!\n"); + return 1; + } + + if (-1 == (count = sam_hdr_count_lines(in_samhdr, rg))) { + fprintf(samtools_stderr, "Failed to get RG count!\n"); + return 1; + } + + for (i = 0; i < count; ++i) + { + ks_clear(&line); + if (sam_hdr_find_line_pos(in_samhdr, rg, i, &line)) { + fprintf(samtools_stderr, "Failed to get RG data!\n"); + ret = 1; + break; + } + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(samtools_stderr, "Failed to add RG data!\n"); + ret = 1; + break; + } + } + ks_free(&line); + + return ret; +} + +/// getPGlines - add PG lines from input header to output header based on user option +/** @param in_samhdr - pointer to input sam header data + * @param out_samhdr - pointer to output sam header data + * @param config - pointer to internal configuration data + * @param argdump - string containing dump of command line invocation +returns 1 on failure 0 on success +*/ +int getPGlines(sam_hdr_t *in_samhdr, sam_hdr_t *out_samhdr, conf_data *config, const char *argdump) +{ + kstring_t line = KS_INITIALIZE, id = KS_INITIALIZE; + int i = 0, ret = 0, count = 0; + const char pg[] = "PG"; + + if (!in_samhdr || !out_samhdr || !config) { + fprintf(samtools_stderr, "Invalid parameters in getPGlines!\n"); + return 1; + } + + if (-1 == (count = sam_hdr_count_lines(in_samhdr, pg))) { + fprintf(samtools_stderr, "Failed to get PG count!\n"); + return 1; + } + + if (config->pgid && config->pgid[0]) { //when reject-PG is given, and is not empty, remove given pg onwards + for (i = 0; i < count; ++i) { + if (sam_hdr_find_tag_pos(in_samhdr, pg, i, "ID", &id)) { + fprintf(samtools_stderr, "Failed to get PG entry fields for line %d!\n", i + 1); + break; + } + + if (!strcmp(id.s, config->pgid)) + break; + + //either current PG is prior to rejected one or all PGs are in, get PG line and add + ks_clear(&line); + if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) { + fprintf(samtools_stderr, "Failed to get PG data at %d!\n", i + 1); + ret = 1; + break; + } + + //add to output + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(samtools_stderr, "Failed to add PG data!\n"); + ret = 1; + break; + } + } + } + else { //keep all + for (i = 0; i < count; ++i) { + if (sam_hdr_find_line_pos(in_samhdr, "PG", i, &line)) { + fprintf(samtools_stderr, "Failed to get PG data at %d!\n", i + 1); + ret = 1; + break; + } + //line has the required PG data + if (sam_hdr_add_lines(out_samhdr, line.s, line.l)) { + fprintf(samtools_stderr, "Failed to add PG data!\n"); + ret = 1; + break; + } + } + } + + if (!ret && !config->noPGentry) { + //add PG entry with reset command + if (-1 == (ret = sam_hdr_add_pg(out_samhdr, "samtools", "CL", argdump, NULL))) { + fprintf(samtools_stderr, "Failed to set PG entry!\n"); + } + } + ks_free(&line); + ks_free(&id); + + return ret; +} + +/// reset - do the reset of data and create output; create output header with required rg/pg data, add bamdata with flags set to unmapped, pair info and orientation reset, +// reerse and complement alignment if required +/** @param infile - input samfile pointer + * @param outfile - output sam file pointer + * @param config - pointer to internal configuration data + * @param args - string containing dump of command line invocation +returns 1 on failure 0 on success +*/ +int reset(samFile *infile, samFile *outfile, conf_data *config, char *args) +{ + sam_hdr_t *in_samhdr = NULL, *out_samhdr = NULL; + int ret = EXIT_FAILURE, ret_r = 0, ret_w = 0, i = 0; + bam1_t *bamdata = NULL, *outdata = NULL; + kstring_t querydata = KS_INITIALIZE, qualdata = KS_INITIALIZE; + char *sp = NULL, *qp = NULL; + uint8_t *bamquery = NULL, *bamqual = NULL; + + if (!infile || !outfile) { + fprintf(samtools_stderr, "Invalid parameters in reset!\n"); + goto error; + } + + //read input header + in_samhdr = sam_hdr_read(infile); + if (!in_samhdr) + { + fprintf(samtools_stderr, "Failed to read header from file!\n"); + goto error; + } + //create output header + if (!(out_samhdr = sam_hdr_init())) + { + fprintf(samtools_stderr, "Failed to create output header!\n"); + goto error; + } + + //add version to output header + if (-1 == sam_hdr_add_line(out_samhdr,"HD", "VN", SAM_FORMAT_VERSION, NULL)) { + fprintf(samtools_stderr, "Failed to set header data!\n"); + goto error; + } + //add RG / PG lines if configured + if ((config->keepRGs && getRGlines(in_samhdr, out_samhdr)) || + getPGlines(in_samhdr, out_samhdr, config, args)) { + goto error; + } + + //write output header + if (sam_hdr_write(outfile, out_samhdr)) { + print_error_errno("reset", "Output header write failed (%d)!\n", errno); + goto error; + } + + bamdata = bam_init1(); //input bam + outdata = bam_init1(); //output bam + if (!bamdata || !outdata) + { + fprintf(samtools_stderr, "Failed to allocate data memory!\n"); + goto error; + } + + errno = 0; i = 0; + sp = NULL; qp = NULL; + bamquery = NULL; bamqual = NULL; + + //get bam data, make updates and dump to output + while (0 <= (ret_r = sam_read1(infile, in_samhdr, bamdata))) + { + sp = NULL; qp = NULL; + bamquery = NULL; bamqual = NULL; + + // read data + if (bamdata->core.flag & BAM_FSECONDARY || bamdata->core.flag & BAM_FSUPPLEMENTARY) { + continue; + } + + //update flags + uint16_t flags = bamdata->core.flag & ~BAM_FPROPER_PAIR; //reset pair info + flags |= BAM_FUNMAP; //mark as unmapped + if (bamdata->core.flag & BAM_FPAIRED) { + flags |= BAM_FMUNMAP; //mark mate as unmapped, if it was a pair + } + flags &= ~BAM_FMREVERSE; //reset mate orientation + + if (0 > ks_resize(&querydata, bamdata->core.l_qseq) || + 0 > ks_resize(&qualdata, bamdata->core.l_qseq)) { + fprintf(samtools_stderr, "Failed to get allocate memory!\n"); + ret_r = -4; + break; + } + ks_clear(&querydata); + ks_clear(&qualdata); + + sp = ks_str(&querydata); + qp = ks_str(&qualdata); + bamquery = bam_get_seq(bamdata); + bamqual = bam_get_qual(bamdata); + if (bamdata->core.flag & BAM_FREVERSE) { + //sequence data ordered as reverse complemented, reorder/complement sequence and quality data as read and clear the flag + for (i = bamdata->core.l_qseq - 1; i >= 0; --i) { + *sp++ = "=TGKCYSBAWRDMHVN"[bam_seqi(bamquery, i)]; + *qp++ = bamqual[i]; + } + flags &= ~BAM_FREVERSE; //reset flag as well + } + else { + //data in read order itself + for (i = 0; i < bamdata->core.l_qseq ; ++i) { + *sp++ = seq_nt16_str[bam_seqi(bamquery, i)]; + } + memcpy(qp, bam_get_qual(bamdata), bamdata->core.l_qseq); + } + + removeauxtags(bamdata, config); + if (0 > (ret_w = bam_set1(outdata, bamdata->core.l_qname - bamdata->core.l_extranul - 1, bam_get_qname(bamdata), flags, -1, -1, 0, 0, NULL, -1, -1, 0, bamdata->core.l_qseq, querydata.s, qualdata.s, bam_get_l_aux(bamdata)))) { + print_error_errno("reset", "Failed to set output data (%d)!\n", errno); + break; + } + + memcpy(bam_get_aux(outdata), bam_get_aux(bamdata), bam_get_l_aux(bamdata)); + outdata->l_data += bam_get_l_aux(bamdata); + + errno = 0; + //write bam data to output + if (0 > (ret_w = sam_write1(outfile, out_samhdr, outdata))) + { + print_error_errno("reset", "Failed to write output data (%d)!\n", errno); + break; + } + // wrote the data, continue read/write cycle + errno = 0; + } + + if (-1 > ret_r || 0 > ret_w) { + //some error + fprintf(samtools_stderr, "Error during %s!\n", (-1 > ret_r)? "read" : "write"); + } + else { + // no error! + ret = EXIT_SUCCESS; + } + +error: + // clean up and return result + if (in_samhdr) + sam_hdr_destroy(in_samhdr); + if (out_samhdr) + sam_hdr_destroy(out_samhdr); + + if (bamdata) + bam_destroy1(bamdata); + if (outdata) + bam_destroy1(outdata); + + if (qualdata.s) + ks_free(&qualdata); + if (querydata.s) + ks_free(&querydata); + return ret; +} + +/// cleanup - free up allocations made +/** @param config - pointer to internal configuration data +returns nothing +*/ +void cleanup(conf_data *config) +{ + if (config->aux_keep) { + kh_destroy(aux_exists, config->aux_keep); + config->aux_keep = NULL; + } + if (config->aux_remove) { + kh_destroy(aux_exists, config->aux_remove); + config->aux_remove = NULL; + } +} + +/// main_reset - starts the reset of data +/** @param argc - count of arguments + * @param argv - pointer to array of arguments +returns 1 on failure 0 on success +*/ +int main_reset(int argc, char *argv[]) +{ + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', '-', 'O', '-', '-', '@'), //let output format and thread count be given by user - long options + {"keep-tag", required_argument, NULL, LONG_OPT('x')}, //aux tags to be retained, supports ^ STR + {"remove-tag", required_argument, NULL, 'x'}, //aux tags to be removed + {"no-RG", no_argument, NULL, 1}, //no RG lines in output, default is to keep them + //reject PG lines from input, default is to keep them (i.e. option not given); without optional filename, all PGs removed and those given in file are filtered when optional filename is given + {"reject-PG", required_argument, NULL, 'p'}, //reject entries from this PG onwards + {"no-PG", no_argument, NULL, 2}, //do not add PG entry for reset operation, default is to add it + {NULL, 0, NULL, 0} + }; + samFile *infile = NULL, *outfile = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool tpool = {NULL, 0}; + const char *inname = NULL, *outname = NULL; + int c = 0, ret = EXIT_FAILURE; + char outmode[4] = "w", *args = NULL; + conf_data resetconf = {1, 0, NULL, NULL, NULL}; //keep RGs and PGs by default + + + //samtools reset -o outfile -x/--remove-tag ... --keep-tag ... --threads=n --output-fmt=fmt --no-RG --reject-PG pgid --no-PG [] + while ((c = getopt_long(argc, argv, "o:@:x:O:", lopts, NULL)) >= 0) + { + switch (c) + { + case 1: //--no-RG + if (!resetconf.keepRGs) { + usage(samtools_stderr); //already given! + goto exit; + } + resetconf.keepRGs = 0; + break; + case 2: //--no-PG + if (resetconf.noPGentry) { + usage(samtools_stderr); //already given! + goto exit; + } + resetconf.noPGentry = 1; + break; + case 'p': //--reject-PG= + if (resetconf.pgid) { + usage(samtools_stderr); //already given! + goto exit; + } + resetconf.pgid = optarg; + break; + case 'o': //output file name + if (outname) { //already given! + usage(samtools_stderr); + goto exit; + + } + outname = optarg; + break; + case 'x': //remove aux tag + if (*optarg == '^') { //remove all except given ones! + if (parse_aux_list(&resetconf.aux_keep, optarg+1, "main_reset")) { + usage(samtools_stderr); + goto exit; + } + } + else { //remove given ones + if (parse_aux_list(&resetconf.aux_remove, optarg, "main_reset")) { + usage(samtools_stderr); + goto exit; + } + } + break; + case LONG_OPT('x'): //keep aux tags + if (parse_aux_list(&resetconf.aux_keep, optarg, "main_reset")) { + usage(samtools_stderr); + goto exit; + } + break; + // handle standard samtool options like thread count, verbosity... + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) + break; + // else fall-through + // couldn't parse or unknown options, show usage! + case '?': //unknown options found! + usage(samtools_stderr); + goto exit; + break; + } + } + + if (argc == 1 && isatty(STDIN_FILENO)) { + //no args and input is stdin -- it is the usage check + usage(samtools_stdout); + ret = EXIT_SUCCESS; + goto exit; + } + //else have other args or input from redirection/pipe/other device -- validate and work + + if (!outname) + outname = "-"; + + //check and fail if unnecessary parameters are given + c = argc - optind; + if (c > 1) { + usage(samtools_stderr); + goto exit; + } + + if (c == 1) { + inname = argv[optind]; + } + else { + inname = "-"; + } + + //set output file format based on name + sam_open_mode(outmode + 1, outname, NULL); + + //open input and output files + infile = sam_open(inname, "r"); + outfile = sam_open_format(outname, outmode, &ga.out); + if (!infile || !outfile) { + fprintf(samtools_stderr, "Could not open %s%s%s\n", !infile ? inname : "", (!infile && !outfile)? ", " : "", !outfile ? outname : ""); + goto exit; + } + + // set the thread count if given as argument + if (ga.nthreads > 0) + { + if (!(tpool.pool = hts_tpool_init(ga.nthreads))) + { + fprintf(samtools_stderr, "\nFailed to setup thread pool\n"); + goto exit; + } + + hts_set_opt(infile, HTS_OPT_THREAD_POOL, &tpool); + hts_set_opt(outfile, HTS_OPT_THREAD_POOL, &tpool); + } + + args = stringify_argv(argc + 1, argv - 1); //to dump invocation in PG line + + //do the reset! + ret = reset(infile, outfile, &resetconf, args); + +exit: + if (args) + free(args); + if (infile) + sam_close(infile); + if (outfile) + sam_close(outfile); + if (tpool.pool) + hts_tpool_destroy(tpool.pool); + cleanup(&resetconf); + sam_global_args_free(&ga); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_opts.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_opts.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..99bb1694ca1621cc080803e84185ba7a69c093cf --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_opts.c.pysam.c @@ -0,0 +1,196 @@ +#include "samtools.pysam.h" + +/* sam_opts.c -- utilities to aid parsing common command line options. + + Copyright (C) 2015, 2019 Genome Research Ltd. + + Author: James Bonfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include "sam_opts.h" + +/* + * Processes a standard "global" samtools long option. + * + * The 'c' value is the return value from a getopt_long() call. It is checked + * against the lopt[] array to find the corresponding value as this may have + * been reassigned by the individual subcommand. + * + * Having found the entry, the corresponding long form is used to apply the + * option, storing the setting in sam_global_args *ga. + * + * Returns 0 on success, + * -1 on failure. + */ +int parse_sam_global_opt(int c, const char *optarg, const struct option *lopt, + sam_global_args *ga) { + int r = 0; + + while (lopt->name) { + if (c != lopt->val) { + lopt++; + continue; + } + + if (strcmp(lopt->name, "input-fmt") == 0) { + r = hts_parse_format(&ga->in, optarg); + break; + } else if (strcmp(lopt->name, "input-fmt-option") == 0) { + r = hts_opt_add((hts_opt **)&ga->in.specific, optarg); + break; + } else if (strcmp(lopt->name, "output-fmt") == 0) { + r = hts_parse_format(&ga->out, optarg); + break; + } else if (strcmp(lopt->name, "output-fmt-option") == 0) { + r = hts_opt_add((hts_opt **)&ga->out.specific, optarg); + break; + } else if (strcmp(lopt->name, "reference") == 0) { + char *ref = malloc(10 + strlen(optarg) + 1); + + if (!ref) { + fprintf(samtools_stderr, "Unable to allocate memory in " + "parse_sam_global_opt.\n"); + + return -1; + } + + sprintf(ref, "reference=%s", optarg); + + if (!(ga->reference = strdup(optarg))) { + fprintf(samtools_stderr, "Unable to allocate memory in " + "parse_sam_global_opt.\n"); + + return -1; + } + + r = hts_opt_add((hts_opt **)&ga->in.specific, ref); + r |= hts_opt_add((hts_opt **)&ga->out.specific, ref); + free(ref); + break; + } else if (strcmp(lopt->name, "threads") == 0) { + ga->nthreads = atoi(optarg); + break; + } else if (strcmp(lopt->name, "write-index") == 0) { + ga->write_index = 1; + break; + } else if (strcmp(lopt->name, "verbosity") == 0) { + hts_verbose = atoi(optarg); + break; + } + } + + if (!lopt->name) { + fprintf(samtools_stderr, "Unexpected global option.\n"); + return -1; + } + + /* + * SAM format with compression enabled implies SAM.bgzf + */ + if (ga->out.format == sam) { + hts_opt *opts = (hts_opt *)ga->out.specific; + while (opts) { + if (opts->opt == HTS_OPT_COMPRESSION_LEVEL) + ga->out.compression = bgzf; + opts = opts->next; + } + } + + return r; +} + +/* + * Report the usage for global options. + * + * This accepts a string with one character per SAM_OPT_GLOBAL_OPTIONS option + * to determine which options need to be printed and how. + * Each character should be one of: + * '.' No short option has been assigned. Use --long-opt only. + * '-' The long (and short) option has been disabled. + * Otherwise the short option is character . + */ +void sam_global_opt_help(FILE *fp, const char *shortopts) { + int i = 0; + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS(0,0,0,0,0,0), + { NULL, 0, NULL, 0 } + }; + + for (i = 0; shortopts && shortopts[i] && lopts[i].name; i++) { + if (shortopts[i] == '-') + continue; + + if (shortopts[i] == '.') + fprintf(fp, " --"); + else + fprintf(fp, " -%c, --", shortopts[i]); + + if (strcmp(lopts[i].name, "input-fmt") == 0) + fprintf(fp,"input-fmt FORMAT[,OPT[=VAL]]...\n" + " Specify input format (SAM, BAM, CRAM)\n"); + else if (strcmp(lopts[i].name, "input-fmt-option") == 0) + fprintf(fp,"input-fmt-option OPT[=VAL]\n" + " Specify a single input file format option in the form\n" + " of OPTION or OPTION=VALUE\n"); + else if (strcmp(lopts[i].name, "output-fmt") == 0) + fprintf(fp,"output-fmt FORMAT[,OPT[=VAL]]...\n" + " Specify output format (SAM, BAM, CRAM)\n"); + else if (strcmp(lopts[i].name, "output-fmt-option") == 0) + fprintf(fp,"output-fmt-option OPT[=VAL]\n" + " Specify a single output file format option in the form\n" + " of OPTION or OPTION=VALUE\n"); + else if (strcmp(lopts[i].name, "reference") == 0) + fprintf(fp,"reference FILE\n" + " Reference sequence FASTA FILE [null]\n"); + else if (strcmp(lopts[i].name, "threads") == 0) + fprintf(fp,"threads INT\n" + " Number of additional threads to use [0]\n"); + else if (strcmp(lopts[i].name, "write-index") == 0) + fprintf(fp,"write-index\n" + " Automatically index the output files [off]\n"); + else if (strcmp(lopts[i].name, "verbosity") == 0) + fprintf(fp,"verbosity INT\n" + " Set level of verbosity\n"); + } +} + +void sam_global_args_init(sam_global_args *ga) { + if (!ga) + return; + + memset(ga, 0, sizeof(*ga)); +} + +void sam_global_args_free(sam_global_args *ga) { + if (ga->in.specific) + hts_opt_free(ga->in.specific); + + if (ga->out.specific) + hts_opt_free(ga->out.specific); + + if (ga->reference) + free(ga->reference); +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..d7178b2e524f8479f999cc2e77dd4ad62eb3d271 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.c @@ -0,0 +1,192 @@ +/* sam_utils.c -- various utilities internal to samtools. + + Copyright (C) 2014-2016, 2018, 2019, 2023 Genome Research Ltd. + + Author: John Marshall + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include +#include + +#include +#include +#include +#include + +#include "sam_utils.h" + +static htsFile *samtools_stdout = NULL; + +void autoflush_if_stdout(htsFile *fp, const char *fname) { + if (fname == NULL || strcmp(fname, "-") == 0) samtools_stdout = fp; +} + +void release_autoflush(htsFile *fp) { + if (samtools_stdout == fp) samtools_stdout = NULL; +} + +static void vprint_error_core(const char *subcommand, const char *format, va_list args, const char *extra) +{ + fflush(stdout); + if (samtools_stdout) hts_flush(samtools_stdout); + + if (subcommand && *subcommand) fprintf(stderr, "samtools %s: ", subcommand); + else fprintf(stderr, "samtools: "); + vfprintf(stderr, format, args); + if (extra) fprintf(stderr, ": %s\n", extra); + else fprintf(stderr, "\n"); + fflush(stderr); +} + +void print_error(const char *subcommand, const char *format, ...) +{ + va_list args; + va_start(args, format); + vprint_error_core(subcommand, format, args, NULL); + va_end(args); +} + +void print_error_errno(const char *subcommand, const char *format, ...) +{ + int err = errno; + va_list args; + va_start(args, format); + vprint_error_core(subcommand, format, args, err? strerror(err) : NULL); + va_end(args); +} + +void check_sam_close(const char *subcmd, samFile *fp, const char *fname, const char *null_fname, int *retp) +{ + release_autoflush(fp); + int r = sam_close(fp); + if (r >= 0) return; + + // TODO Need error infrastructure so we can print a message instead of r + if (fname) print_error(subcmd, "error closing \"%s\": %d", fname, r); + else print_error(subcmd, "error closing %s: %d", null_fname, r); + + *retp = EXIT_FAILURE; +} + +/* Pick an index suffix based on the output file descriptor type. */ +static char *idx_suffix(htsFile *fp) { + switch (fp->format.format) { + case sam: + case bam: + // Tough cheese if you wanted bai! + // New feature => mandatory new index too, for simplicity of CLI. + return "csi"; + + case cram: + return "crai"; + + default: + return NULL; + } +} + +/* + * Utility function to add an index to a file we've opened for write. + * NB: Call this after writing the header and before writing sequences. + * + * The returned index filename should be freed by the caller, but only + * after sam_idx_save has been called. + * + * Returns index filename on success, + * NULL on failure. + */ +char *auto_index(htsFile *fp, const char *fn, bam_hdr_t *header) { + char *fn_idx; + int min_shift = 14; /* CSI */ + if (!fn || !*fn || strcmp(fn, "-") == 0) + return NULL; + + char *delim = strstr(fn, HTS_IDX_DELIM); + if (delim != NULL) { + delim += strlen(HTS_IDX_DELIM); + + fn_idx = strdup(delim); + if (!fn_idx) + return NULL; + + size_t l = strlen(fn_idx); + if (l >= 4 && strcmp(fn_idx + l - 4, ".bai") == 0) + min_shift = 0; + } else { + char *suffix = idx_suffix(fp); + if (!suffix) + return NULL; + + fn_idx = malloc(strlen(fn)+6); + if (!fn_idx) + return NULL; + + sprintf(fn_idx, "%s.%s", fn, suffix); + } + + if (sam_idx_init(fp, header, min_shift, fn_idx) < 0) { + print_error_errno("auto_index", "failed to open index \"%s\" for writing", fn_idx); + free(fn_idx); + return NULL; + } + + return fn_idx; +} + + +/// parse_aux_list - parses given string for aux tags which are ',' separated +/** @param h - pointer to a SET holding aux tags + * @param optarg - string having the ',' separated aux tags + * @param msgheader - string to be used during error output as a header +returns -1 on failure and 0 on success +moved from sam_view.c to here for common usage at different source files +*/ +int parse_aux_list(auxhash_t *h, char *optarg, const char *msgheader) +{ + if (!*h) + *h = kh_init(aux_exists); + + while (strlen(optarg) >= 2) { + int x = optarg[0]<<8 | optarg[1]; + int ret = 0; + kh_put(aux_exists, *h, x, &ret); + if (ret < 0) { + kh_destroy(aux_exists, *h); + *h = NULL; + return -1; + } + + optarg += 2; + if (*optarg == ',') // allow white-space too for easy `cat file`? + optarg++; + else if (*optarg != 0) + break; + } + + if (strlen(optarg) != 0) { + fprintf(stderr, "%s: Error parsing option, " + "auxiliary tags should be exactly two characters long.\n", msgheader ? msgheader : ""); + kh_destroy(aux_exists, *h); + *h = NULL; + return -1; + } + + return 0; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..061c2a2b8cb164173a209428d78dc70b671f3ca8 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_utils.h @@ -0,0 +1,83 @@ +/* sam_utils.c -- to hold utility functions and types + + Copyright (C) 2023 Genome Research Ltd. + + Author: Vasudeva Sarma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef SAM_UTIL_H +#define SAM_UTIL_H + +#include "htslib/khash.h" +#include "htslib/sam.h" + +//this file may contain any utility functions and data types to be shared across + +/*below parse_aux_list and aux_exists are moved from sam_view.c to here for common + *usage at different source files + */ + +KHASH_SET_INIT_INT(aux_exists) //SET data type to hold aux tags +typedef khash_t(aux_exists) *auxhash_t; + +/// parse_aux_list - parses given string for aux tags which are ',' separated +/** @param h - pointer to a SET holding aux tags + * @param optarg - string having the ',' separated aux tags + * @param msgheader - string to be used during error output as a header +returns -1 on failure and 0 on success +moved from sam_view.c to here for common usage at different source files +*/ +int parse_aux_list(auxhash_t *h, char *optarg, const char *msgheader); + + +// below utility function declarations moved from samtools.h to here and this header is included in samtools.h + +#define CHECK_PRINTF(fmt,args) HTS_FORMAT(HTS_PRINTF_FMT, (fmt), (args)) + +void print_error(const char *subcommand, const char *format, ...) CHECK_PRINTF(2, 3); +void print_error_errno(const char *subcommand, const char *format, ...) CHECK_PRINTF(2, 3); + +void check_sam_close(const char *subcmd, samFile *fp, const char *fname, const char *null_fname, int *retp); + +/* Utility functions to register an output htsFile/samFile/vcfFile that + * might be stdout. If FNAME is "-" or NULL, records FP so that print_error() + * et al can automatically flush it before printing an error message. + */ +void autoflush_if_stdout(htsFile *fp, const char *fname); + +/* Call this before closing FP; check_sam_close() does this automatically. + */ +void release_autoflush(htsFile *fp); + +/* + * Utility function to add an index to a file we've opened for write. + * NB: Call this after writing the header and before writing sequences. + * + * The returned index filename should be freed by the caller, but only + * after sam_idx_save has been called. + * + * Returns index filename on success, + * NULL on failure. + */ +char *auto_index(htsFile *fp, const char *fn, bam_hdr_t *header); + +#endif //SAM_UTIL_H + + diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c new file mode 100644 index 0000000000000000000000000000000000000000..aa5b92310dce313f56cee4409062bada951562f2 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c @@ -0,0 +1,1666 @@ +/* sam_view.c -- SAM<->BAM<->CRAM conversion. + + Copyright (C) 2009-2023 Genome Research Ltd. + Portions copyright (C) 2009, 2011, 2012 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "htslib/khash.h" +#include "htslib/kstring.h" +#include "htslib/thread_pool.h" +#include "htslib/hts_expr.h" +#include "samtools.h" +#include "sam_opts.h" +#include "bam.h" // for bam_get_library and bam_remove_B +#include "bedidx.h" +#include "sam_utils.h" + +KHASH_SET_INIT_STR(str) +typedef khash_t(str) *strhash_t; + +// This structure contains the settings for a samview run +typedef struct samview_settings { + strhash_t rghash; + strhash_t rnhash; + strhash_t tvhash; + int min_mapQ; + + // Described here in the same terms as the usage statement. + // The code however always negates to "reject if" keep if: + int flag_on; // keep if (FLAG & N) == N (all on) + int flag_off; // keep if (FLAG & N) == 0 (all off) + int flag_anyon; // keep if (FLAG & N) != 0 (any on) + int flag_alloff; // reject if (FLAG & N) == N (any off) + + int min_qlen; + int remove_B; + uint32_t subsam_seed; + double subsam_frac; + char* library; + void* bed; + size_t remove_aux_len; + char** remove_aux; + int multi_region; + char* tag; + hts_filter_t *filter; + int remove_flag; + int add_flag; + int unmap; + auxhash_t remove_tag; + auxhash_t keep_tag; + + hts_idx_t *hts_idx; + sam_hdr_t *header; + samFile *in, *out, *un_out; + int64_t count; + int is_count; + char *fn_in, *fn_idx_in, *fn_out, *fn_fai, *fn_un_out, *fn_out_idx, *fn_un_out_idx; + int fetch_pairs, nreglist; + hts_reglist_t *reglist; + int sanitize; + int count_rf; // CRAM_OPT_REQUIRED_FIELDS for view -c +} samview_settings_t; + +// Copied from htslib/sam.c. +// TODO: we need a proper interface to find the length of an aux tag, +// or at the very make exportable versions of these in htslib. +static inline int aux_type2size(uint8_t type) +{ + switch (type) { + case 'A': case 'c': case 'C': + return 1; + case 's': case 'S': + return 2; + case 'i': case 'I': case 'f': + return 4; + case 'd': + return 8; + case 'Z': case 'H': case 'B': + return type; + default: + return 0; + } +} + +// Copied from htslib/sam.c. +static inline uint8_t *skip_aux(uint8_t *s, uint8_t *end) +{ + int size; + uint32_t n; + if (s >= end) return end; + size = aux_type2size(*s); ++s; // skip type + switch (size) { + case 'Z': + case 'H': + while (s < end && *s) ++s; + return s < end ? s + 1 : end; + case 'B': + if (end - s < 5) return NULL; + size = aux_type2size(*s); ++s; + n = le_to_u32(s); + s += 4; + if (size == 0 || end - s < size * n) return NULL; + return s + size * n; + case 0: + return NULL; + default: + if (end - s < size) return NULL; + return s + size; + } +} + +// Returns 0 to indicate read should be output 1 otherwise, +// and -1 on error. +static int process_aln(const sam_hdr_t *h, bam1_t *b, samview_settings_t* settings) +{ + if (settings->filter) { + int r = sam_passes_filter(h, b, settings->filter); + if (r < 0) // err + return -1; + if (r == 0) // filter-out + return 1; + } + + if (settings->remove_B) bam_remove_B(b); + if (settings->min_qlen > 0) { + int k, qlen = 0; + uint32_t *cigar = bam_get_cigar(b); + for (k = 0; k < b->core.n_cigar; ++k) + if ((bam_cigar_type(bam_cigar_op(cigar[k]))&1) || bam_cigar_op(cigar[k]) == BAM_CHARD_CLIP) + qlen += bam_cigar_oplen(cigar[k]); + if (qlen < settings->min_qlen) return 1; + } + if (b->core.qual < settings->min_mapQ || ((b->core.flag & settings->flag_on) != settings->flag_on) || (b->core.flag & settings->flag_off)) + return 1; + if (settings->flag_alloff && ((b->core.flag & settings->flag_alloff) == settings->flag_alloff)) + return 1; + if (settings->flag_anyon && ((b->core.flag & settings->flag_anyon) == 0)) + return 1; + if (!settings->multi_region && settings->bed && (b->core.tid < 0 || !bed_overlap(settings->bed, sam_hdr_tid2name(h, b->core.tid), b->core.pos, bam_endpos(b)))) + return 1; + if (settings->subsam_frac > 0.) { + uint32_t k = __ac_Wang_hash(__ac_X31_hash_string(bam_get_qname(b)) ^ settings->subsam_seed); + if ((double)(k&0xffffff) / 0x1000000 >= settings->subsam_frac) return 1; + } + if (settings->rghash) { + uint8_t *s = bam_aux_get(b, "RG"); + if (s) { + khint_t k = kh_get(str, settings->rghash, (char*)(s + 1)); + if (k == kh_end(settings->rghash)) return 1; + } + } + if (settings->tag) { + uint8_t *s = bam_aux_get(b, settings->tag); + if (s) { + if (settings->tvhash) { + char t[32], *val; + if (*s == 'i' || *s == 'I' || *s == 's' || *s == 'S' || *s == 'c' || *s == 'C') { + int ret = snprintf(t, 32, "%"PRId64, bam_aux2i(s)); + if (ret > 0) val = t; + else return 1; + } else if (*s == 'A') { + t[0] = *(s+1); + t[1] = 0; + val = t; + } else { + val = (char *)(s+1); + } + khint_t k = kh_get(str, settings->tvhash, val); + if (k == kh_end(settings->tvhash)) return 1; + } + } else { + return 1; + } + } + if (settings->rnhash) { + const char* rn = bam_get_qname(b); + if (!rn || kh_get(str, settings->rnhash, rn) == kh_end(settings->rnhash)) { + return 1; + } + } + if (settings->library) { + const char *p = bam_get_library((sam_hdr_t*)h, b); + if (!p || strcmp(p, settings->library) != 0) return 1; + } + return 0; +} + +static int adjust_tags(const sam_hdr_t *h, bam1_t *b, + samview_settings_t* settings) { + if (settings->keep_tag) { + uint8_t *s_from, *s_to, *end = b->data + b->l_data; + auxhash_t h = settings->keep_tag; + + s_from = s_to = bam_get_aux(b); + while (s_from < end) { + int x = (int)s_from[0]<<8 | s_from[1]; + uint8_t *s = skip_aux(s_from+2, end); + if (s == NULL) { + print_error("view", "malformed aux data for record \"%s\"", + bam_get_qname(b)); + return -1; + } + + if (kh_get(aux_exists, h, x) != kh_end(h) ) { + if (s_to != s_from) memmove(s_to, s_from, s - s_from); + s_to += s - s_from; + } + s_from = s; + } + b->l_data = s_to - b->data; + + } else if (settings->remove_tag) { + uint8_t *s_from, *s_to, *end = b->data + b->l_data; + auxhash_t h = settings->remove_tag; + + s_from = s_to = bam_get_aux(b); + while (s_from < end) { + int x = (int)s_from[0]<<8 | s_from[1]; + uint8_t *s = skip_aux(s_from+2, end); + if (s == NULL) { + print_error("view", "malformed aux data for record \"%s\"", + bam_get_qname(b)); + return -1; + } + + if (kh_get(aux_exists, h, x) == kh_end(h) ) { + if (s_to != s_from) memmove(s_to, s_from, s - s_from); + s_to += s - s_from; + } + s_from = s; + } + b->l_data = s_to - b->data; + } + + return 0; +} + +static int usage(FILE *fp, int exit_status, int is_long_help); + +static int populate_lookup_from_file(const char *subcmd, strhash_t lookup, char *fn) +{ + FILE *fp; + char buf[1024]; + int ret = 0; + fp = fopen(fn, "r"); + if (fp == NULL) { + print_error_errno(subcmd, "failed to open \"%s\" for reading", fn); + return -1; + } + + while (ret != -1 && !feof(fp) && fscanf(fp, "%1023s", buf) > 0) { + char *d = strdup(buf); + if (d != NULL) { + kh_put(str, lookup, d, &ret); + if (ret == 0) free(d); /* Duplicate */ + } else { + ret = -1; + } + } + if (ferror(fp)) ret = -1; + if (ret == -1) { + print_error_errno(subcmd, "failed to read \"%s\"", fn); + } + fclose(fp); + return (ret != -1) ? 0 : -1; +} + +static int add_read_group_single(const char *subcmd, samview_settings_t *settings, char *name) +{ + char *d = strdup(name); + int ret = 0; + + if (d == NULL) goto err; + + if (settings->rghash == NULL) { + settings->rghash = kh_init(str); + if (settings->rghash == NULL) goto err; + } + + kh_put(str, settings->rghash, d, &ret); + if (ret == -1) goto err; + if (ret == 0) free(d); /* Duplicate */ + return 0; + + err: + print_error(subcmd, "Couldn't add \"%s\" to read group list: memory exhausted?", name); + free(d); + return -1; +} + +static int add_read_names_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->rnhash == NULL) { + settings->rnhash = kh_init(str); + if (settings->rnhash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->rnhash, fn); +} + +static int add_read_groups_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->rghash == NULL) { + settings->rghash = kh_init(str); + if (settings->rghash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->rghash, fn); +} + +static int add_tag_value_single(const char *subcmd, samview_settings_t *settings, char *name) +{ + char *d = strdup(name); + int ret = 0; + + if (d == NULL) goto err; + + if (settings->tvhash == NULL) { + settings->tvhash = kh_init(str); + if (settings->tvhash == NULL) goto err; + } + + kh_put(str, settings->tvhash, d, &ret); + if (ret == -1) goto err; + if (ret == 0) free(d); /* Duplicate */ + return 0; + + err: + print_error(subcmd, "Couldn't add \"%s\" to tag values list: memory exhausted?", name); + free(d); + return -1; +} + +static int add_tag_values_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->tvhash == NULL) { + settings->tvhash = kh_init(str); + if (settings->tvhash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->tvhash, fn); +} + +static inline int check_sam_write1(samFile *fp, const sam_hdr_t *h, const bam1_t *b, const char *fname, int *retp) +{ + int r = sam_write1(fp, h, b); + if (r >= 0) return r; + + if (fname) print_error_errno("view", "writing to \"%s\" failed", fname); + else print_error_errno("view", "writing to standard output failed"); + + *retp = EXIT_FAILURE; + return r; +} + +static inline void change_flag(bam1_t *b, samview_settings_t *settings) +{ + if (settings->add_flag) + b->core.flag |= settings->add_flag; + + if (settings->remove_flag) + b->core.flag &= ~settings->remove_flag; +} + +static int cmp_reglist_intervals(const void *aptr, const void *bptr) +{ + hts_pair_pos_t *a = (hts_pair_pos_t*)aptr; + hts_pair_pos_t *b = (hts_pair_pos_t*)bptr; + if ( a->beg < b->beg ) return -1; + if ( a->beg > b->beg ) return 1; + if ( a->end < b->end ) return -1; + if ( a->end > b->end ) return 1; + return 0; +} +static int cmp_reglist_tids(const void *aptr, const void *bptr) +{ + hts_reglist_t *a = (hts_reglist_t*)aptr; + hts_reglist_t *b = (hts_reglist_t*)bptr; + if ( b->tid==HTS_IDX_NOCOOR || a->tid < b->tid ) return -1; + if ( a->tid==HTS_IDX_NOCOOR || a->tid > b->tid ) return 1; + return 0; +} + +static hts_reglist_t *_reglist_dup(sam_hdr_t *hdr, hts_reglist_t *src, int nsrc) +{ + int i,j; + hts_reglist_t *dst = (hts_reglist_t*)calloc(nsrc,sizeof(hts_reglist_t)); + if ( !dst ) { + print_error_errno("view", "[%s:%d] could not allocate region list" + ,__FILE__ ,__LINE__); + return NULL; + } + for (i=0; i tid ) imax = i - 1; + else break; + } + if ( i<0 || reg[i].tid < tid ) i++; // not found, i will be the index of the inserted element + return i; +} +static int _reglist_push(hts_reglist_t **_reg, int *_nreg, int tid, hts_pos_t beg, hts_pos_t end) +{ + hts_reglist_t *reg = *_reg; + int nreg = *_nreg; + int i = _reglist_find_tid(reg,nreg,tid); + if ( i>=nreg || reg[i].tid!=tid ) { + nreg++; + reg = (hts_reglist_t*)realloc(reg,sizeof(hts_reglist_t)*nreg); + if ( !reg ) { + print_error_errno("view", "[%s:%d] could not extend region list", + __FILE__, __LINE__); + return -1; + } + if ( i+1 < nreg ) + memmove(reg + i + 1, reg + i, sizeof(hts_reglist_t)*(nreg - i - 1)); + reg[i].reg = NULL; + reg[i].tid = tid; + reg[i].min_beg = beg; + reg[i].max_end = end; + reg[i].intervals = NULL; + reg[i].count = 0; + } + *_reg = reg; + *_nreg = nreg; + if ( reg[i].count > 0 + && reg[i].intervals[reg[i].count - 1].beg==beg + && reg[i].intervals[reg[i].count - 1].end==end ) { + return 0; + } + hts_pair_pos_t *new_intervals = realloc(reg[i].intervals, sizeof(hts_pair_pos_t)*(reg[i].count + 1)); + if (!new_intervals) { + print_error_errno("view", "[%s:%d] could not extend region list", + __FILE__, __LINE__); + return -1; + } + reg[i].intervals = new_intervals; + reg[i].intervals[reg[i].count].beg = beg; + reg[i].intervals[reg[i].count].end = end; + reg[i].count++; + return 0; +} + +static void _reglist_merge(hts_reglist_t *reg, int nreg) +{ + int i,j; + for (i=0; ibed = bed_hash_regions(conf->bed, regs, 0, nregs, &filter_op); // insert(1) or filter out(0) the regions from the command line in the same hash table as the bed file + if ( !filter_op ) + filter_state = FILTERED; + } + else + bed_unify(conf->bed); + if ( !conf->bed) { // index is unavailable or no regions have been specified + print_error("view", "No regions or BED file have been provided. Aborting."); + return NULL; + } + + int regcount = 0; + hts_reglist_t *reglist = bed_reglist(conf->bed, filter_state, ®count); + if (!reglist) { + print_error("view", "Region list is empty or could not be created. Aborting."); + return NULL; + } + + if ( conf->fetch_pairs ) { + conf->reglist = _reglist_dup(conf->header,reglist,regcount); + if (!conf->reglist) + return NULL; + conf->nreglist = regcount; + } + + iter = sam_itr_regions(conf->hts_idx, conf->header, reglist, regcount); + if ( !iter ) { + print_error("view", "Iterator could not be created. Aborting."); + return NULL; + } + return iter; +} + +KHASH_SET_INIT_STR(names) + +static int fetch_pairs_collect_mates(samview_settings_t *conf, hts_itr_multi_t *iter) +{ + khint_t k; + int nunmap = 0, r = 0, nmates = 0, write_error = 0, retval = EXIT_FAILURE; + kh_names_t *mate_names = kh_init(names); + bam1_t *rec = bam_init1(); + + if (!mate_names) { + print_error_errno("view", "could not allocate mate names table"); + goto out; + } + if (!rec) { + print_error_errno("view", "could not allocate bam record"); + goto out; + } + + while ((r =sam_itr_multi_next(conf->in, iter, rec))>=0) { + if ( (rec->core.flag & BAM_FPAIRED) == 0 ) continue; + if ( rec->core.mtid>=0 && bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.mtid), rec->core.mpos, rec->core.mpos) ) continue; + int p = process_aln(conf->header, rec, conf); + if (p < 0) goto out; + if (p == 1) continue; + + nmates++; + + k = kh_get(names,mate_names,bam_get_qname(rec)); + if ( k == kh_end(mate_names) ) { + int ret = 0; + char *name_copy = strdup(bam_get_qname(rec)); + if (!name_copy) { + print_error_errno("view", "[%s:%d] could not store sample name, %d elements", __FILE__,__LINE__,nmates); + goto out; + } + kh_put(names, mate_names, name_copy, &ret); + if ( ret<0 ) { + print_error_errno("view", "[%s:%d] could not store sample name, %d elements",__FILE__,__LINE__,nmates); + free(name_copy); + goto out; + } + } + + if ( rec->core.mtid < 0 || (rec->core.flag & BAM_FMUNMAP) ) nunmap = 1; + if ( rec->core.mtid >= 0 ) { + if (_reglist_push(&conf->reglist, &conf->nreglist, rec->core.mtid, rec->core.mpos,rec->core.mpos+1) != 0) + goto out; + } + } + + if (r < -1) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + goto out; + } + + _reglist_merge(conf->reglist, conf->nreglist); + if ( nunmap ) { + if (_reglist_push(&conf->reglist,&conf->nreglist,HTS_IDX_NOCOOR,0,HTS_POS_MAX) != 0) + goto out; + } + hts_itr_multi_destroy(iter); + iter = sam_itr_regions(conf->hts_idx, conf->header, conf->reglist, conf->nreglist); + if ( !iter ) { + print_error_errno("view", "[%s:%d] iterator could not be created",__FILE__,__LINE__); + goto out; + } + while ((r = sam_itr_multi_next(conf->in, iter, rec))>=0) { + int drop = 1; + if (rec->core.tid >=0 && + bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.tid), rec->core.pos, bam_endpos(rec))) drop = 0; + if ( drop ) { + k = kh_get(names,mate_names,bam_get_qname(rec)); + if ( k != kh_end(mate_names) ) drop = 0; + } + int p = 0; + if (!drop && (p=process_aln(conf->header, rec, conf))== 0) { + if (adjust_tags(conf->header, rec, conf) != 0) + goto out; + if (check_sam_write1(conf->out, conf->header, rec, conf->fn_out, + &write_error) < 0) + goto out; + } + if (p < 0) + goto out; + } + + if (r < -1) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + goto out; + } + + retval = EXIT_SUCCESS; + + out: + hts_itr_multi_destroy(iter); + hts_idx_destroy(conf->hts_idx); // destroy the BAM index + conf->hts_idx = NULL; + if (mate_names) { + // free khash keys + for (k = 0; k < kh_end(mate_names); ++k) + if ( kh_exist(mate_names,k) ) free((char*)kh_key(mate_names, k)); + kh_destroy(names,mate_names); + } + bam_destroy1(rec); + return retval; +} + +// Common code for processing and writing a record +static inline int process_one_record(samview_settings_t *conf, bam1_t *b, + int *write_error) { + if (conf->sanitize) + if (bam_sanitize(conf->header, b, conf->sanitize) < 0) + return -1; + + int p; + if ((p = process_aln(conf->header, b, conf)) < 0) { + // error + return -1; + } else if (p == 0) { + // emit read + if (!conf->is_count) { + change_flag(b, conf); + if (adjust_tags(conf->header, b, conf) != 0) + return -1; + if (check_sam_write1(conf->out, conf->header, + b, conf->fn_out, write_error) < 0) { + return -1; + } + } + conf->count++; + } else if (conf->unmap) { + b->core.flag |= BAM_FUNMAP; + b->core.qual = 0; + b->core.isize = 0; + + // remove CIGAR + if (b->core.n_cigar) { + memmove(bam_get_cigar(b), bam_get_seq(b), + b->data + b->l_data - bam_get_seq(b)); + b->l_data -= 4*b->core.n_cigar; + b->core.n_cigar = 0; + } + + if (check_sam_write1(conf->out, conf->header, + b, conf->fn_out, write_error) < 0) { + return -1; + } + } else { + if (conf->un_out) { + if (check_sam_write1(conf->un_out, conf->header, + b, conf->fn_un_out, write_error) < 0) { + return -1; + } + } + } + return 0; +} + +static int stream_view(samview_settings_t *conf) { + bam1_t *b = bam_init1(); + int write_error = 0, r, p = 0; + if (!b) { + print_error_errno("view", "could not allocate bam record"); + return 1; + } + errno = 0; // prevent false error messages. + while ((r = sam_read1(conf->in, conf->header, b)) >= 0) { + if ((p = process_one_record(conf, b, &write_error)) < 0) break; + } + bam_destroy1(b); + if (r < -1 || p < 0) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + return 1; + } + return write_error; +} + +static int multi_region_view(samview_settings_t *conf, hts_itr_multi_t *iter) +{ + bam1_t *b = bam_init1(); + int write_error = 0, result; + if (!b) { + print_error_errno("view", "could not allocate bam record"); + return 1; + } + // fetch alignments + while ((result = sam_itr_multi_next(conf->in, iter, b)) >= 0) { + if (process_one_record(conf, b, &write_error) < 0) break; + } + hts_itr_multi_destroy(iter); + bam_destroy1(b); + + if (result < -1) { + print_error("view", "retrieval of region #%d failed", iter->curr_tid); + return 1; + } + return write_error; +} + +// Make mnemonic distinct values for longoption-only options +#define LONGOPT(c) ((c) + 128) + +// Check for ".sam" filenames as sam_open_mode cannot distinguish between +// foo.sam and foo.unknown, both getting mode "". +static int is_sam(const char *fn) { + if (!fn) + return 0; + size_t l = strlen(fn); + return (l >= 4 && strcasecmp(fn + l-4, ".sam") == 0); +} + +static void aux_list_free(samview_settings_t *settings) { + if (settings->keep_tag) + kh_destroy(aux_exists, settings->keep_tag); + if (settings->remove_tag) + kh_destroy(aux_exists, settings->remove_tag); +} + +int main_samview(int argc, char *argv[]) +{ + samview_settings_t settings; + int c, is_header = 0, is_header_only = 0, ret = 0, compress_level = -1, has_index_file = 0, no_pg = 0; + FILE *fp_out = NULL; + char out_mode[6] = {0}, out_un_mode[6] = {0}; + char *out_format = ""; + char *arg_list = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool p = {NULL, 0}; + + memset(&settings,0,sizeof(settings)); + settings.subsam_frac = -1.0; + settings.count_rf = SAM_FLAG; // don't want 0, and this is quick + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 'T', '@'), + {"add-flags", required_argument, NULL, LONGOPT('a')}, + {"bam", no_argument, NULL, 'b'}, + {"count", no_argument, NULL, 'c'}, + {"cram", no_argument, NULL, 'C'}, + {"customised-index", no_argument, NULL, 'X'}, + {"customized-index", no_argument, NULL, 'X'}, + {"excl-flags", required_argument, NULL, 'F'}, + {"exclude-flags", required_argument, NULL, 'F'}, + {"expr", required_argument, NULL, 'e'}, + {"expression", required_argument, NULL, 'e'}, + {"fai-reference", required_argument, NULL, 't'}, + {"fast", no_argument, NULL, '1'}, + {"fetch-pairs", no_argument, NULL, 'P'}, + {"header-only", no_argument, NULL, 'H'}, + {"help", no_argument, NULL, LONGOPT('?')}, + {"incl-flags", required_argument, NULL, LONGOPT('g')}, + {"include-flags", required_argument, NULL, LONGOPT('g')}, + {"rf", required_argument, NULL, LONGOPT('g')}, // aka incl-flags + {"keep-tag", required_argument, NULL, LONGOPT('x') }, + {"library", required_argument, NULL, 'l'}, + {"min-mapq", required_argument, NULL, 'q'}, + {"min-MQ", required_argument, NULL, 'q'}, + {"min-mq", required_argument, NULL, 'q'}, + {"min-qlen", required_argument, NULL, 'm'}, + {"no-header", no_argument, NULL, LONGOPT('H')}, + {"no-PG", no_argument, NULL, LONGOPT('P')}, + {"output", required_argument, NULL, 'o'}, + {"output-unselected", required_argument, NULL, 'U'}, + {"QNAME-file", required_argument, NULL, 'N'}, + {"qname-file", required_argument, NULL, 'N'}, + {"read-group", required_argument, NULL, 'r'}, + {"read-group-file", required_argument, NULL, 'R'}, + {"readgroup", required_argument, NULL, 'r'}, + {"readgroup-file", required_argument, NULL, 'R'}, + {"region-file", required_argument, NULL, LONGOPT('L')}, + {"regions-file", required_argument, NULL, LONGOPT('L')}, + {"remove-B", no_argument, NULL, 'B'}, + {"remove-flags", required_argument, NULL, LONGOPT('r')}, + {"remove-tag", required_argument, NULL, 'x'}, + {"require-flags", required_argument, NULL, 'f'}, + {"subsample", required_argument, NULL, LONGOPT('s')}, + {"subsample-seed", required_argument, NULL, LONGOPT('S')}, + {"tag", required_argument, NULL, 'd'}, + {"tag-file", required_argument, NULL, 'D'}, + {"target-file", required_argument, NULL, 'L'}, + {"targets-file", required_argument, NULL, 'L'}, + {"uncompressed", no_argument, NULL, 'u'}, + {"unmap", no_argument, NULL, 'p'}, + {"unoutput", required_argument, NULL, 'U'}, + {"use-index", no_argument, NULL, 'M'}, + {"with-header", no_argument, NULL, 'h'}, + {"sanitize", required_argument, NULL, 'z'}, + }; + + /* parse command-line options */ + strcpy(out_mode, "w"); + strcpy(out_un_mode, "w"); + if (argc == 1 && isatty(STDIN_FILENO)) + return usage(stdout, EXIT_SUCCESS, 0); + + // Suppress complaints about '?' being an unrecognised option. Without + // this we have to put '?' in the options list, which makes it hard to + // tell a bad long option from the use of '-?' (both return '?' and + // set optopt to '\0'). + opterr = 0; + + char *tmp; + while ((c = getopt_long(argc, argv, + "SbBcCt:h1Ho:O:q:f:F:G:ul:r:T:R:N:d:D:L:s:@:m:x:U:MXe:pPz:", + lopts, NULL)) >= 0) { + switch (c) { + case 's': + settings.subsam_seed = strtol(optarg, &tmp, 10); + if (tmp && *tmp == '.') { + settings.subsam_frac = strtod(tmp, &tmp); + if (*tmp) ret = 1; + } else { + ret = 1; + } + + if (ret == 1) { + print_error("view", "Incorrect sampling argument \"%s\"", optarg); + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + case LONGOPT('s'): + settings.subsam_frac = strtod(optarg, &tmp); + if (*tmp || settings.subsam_frac < 0.0 || settings.subsam_frac > 1.0) { + print_error("view", "Incorrect sampling argument \"%s\"", optarg); + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + case LONGOPT('S'): settings.subsam_seed = atoi(optarg); break; + case 'm': + settings.min_qlen = atoi(optarg); + settings.count_rf |= SAM_SEQ; + break; + case 'c': settings.is_count = 1; break; + case 'S': break; + case 'b': out_format = "b"; break; + case 'C': out_format = "c"; break; + case 't': settings.fn_fai = strdup(optarg); break; + case 'h': is_header = 1; break; + case 'H': is_header_only = 1; break; + case LONGOPT('H'): is_header = is_header_only = 0; break; + case 'o': settings.fn_out = strdup(optarg); break; + case 'U': settings.fn_un_out = strdup(optarg); break; + case 'X': has_index_file = 1; break; + case 'f': + settings.flag_on |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'F': + settings.flag_off |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case LONGOPT('g'): + settings.flag_anyon |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'G': + settings.flag_alloff |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'q': + settings.min_mapQ = atoi(optarg); + settings.count_rf |= SAM_MAPQ; + break; + case 'u': compress_level = 0; break; + case '1': compress_level = 1; break; + case 'l': + settings.library = strdup(optarg); + settings.count_rf |= SAM_RGAUX; + break; + case 'p': settings.unmap = 1; break; + case 'P': settings.fetch_pairs = 1; settings.multi_region = 1; break; + case 'z': + if ((settings.sanitize = bam_sanitize_options(optarg)) < 0) { + ret = 1; + goto view_end; + } + break; + case LONGOPT('L'): + settings.multi_region = 1; + // fall through + case 'L': + if ((settings.bed = bed_read(optarg)) == NULL) { + print_error_errno("view", "Could not read file \"%s\"", optarg); + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR; + break; + case 'r': + if (add_read_group_single("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_RGAUX; + break; + case 'R': + if (add_read_groups_file("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_RGAUX; + break; + case 'N': + if (add_read_names_file("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + + case 'd': + if (strlen(optarg) < 2 || (strlen(optarg) > 2 && optarg[2] != ':')) { + print_error("view", "Invalid \"tag:value\" option: \"%s\"", optarg); + ret = 1; + goto view_end; + } + + if (settings.tag) { + if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) { + print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg); + ret = 1; + goto view_end; + } + } else { + if (!(settings.tag = calloc(3, 1))) { + print_error("view", "Could not allocate memory for tag: \"%s\"", optarg); + ret = 1; + goto view_end; + } + memcpy(settings.tag, optarg, 2); + } + + if (strlen(optarg) > 3 && add_tag_value_single("view", &settings, optarg+3) != 0) { + print_error("view", "Could not add tag:value \"%s\"", optarg); + ret = 1; + goto view_end; + } + // Some tag filtering affects other fields + if (memcmp(settings.tag, "NM", 2) == 0 || + memcmp(settings.tag, "MD", 2) == 0) + settings.count_rf |= SAM_AUX | SAM_SEQ; + else if (memcmp(settings.tag, "RG", 2) == 0) + settings.count_rf |= SAM_RGAUX; + else + settings.count_rf |= SAM_AUX; + break; + + case 'D': + // Allow ";" as delimiter besides ":" to support MinGW CLI POSIX + // path translation as described at: + // http://www.mingw.org/wiki/Posix_path_conversion + if (strlen(optarg) < 4 || (optarg[2] != ':' && optarg[2] != ';')) { + print_error("view", "Invalid \"tag:file\" option: \"%s\"", optarg); + ret = 1; + goto view_end; + } + + if (settings.tag) { + if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) { + print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg); + ret = 1; + goto view_end; + } + } else { + if (!(settings.tag = calloc(3, 1))) { + print_error("view", "Could not allocate memory for tag: \"%s\"", optarg); + ret = 1; + goto view_end; + } + memcpy(settings.tag, optarg, 2); + } + + if (add_tag_values_file("view", &settings, optarg+3) != 0) { + ret = 1; + goto view_end; + } + // Some tag filtering affects other fields + if (memcmp(settings.tag, "NM", 2) == 0 || + memcmp(settings.tag, "MD", 2) == 0) + settings.count_rf |= SAM_AUX | SAM_SEQ; + else if (memcmp(settings.tag, "RG", 2) == 0) + settings.count_rf |= SAM_RGAUX; + else + settings.count_rf |= SAM_AUX; + break; + + case LONGOPT('?'): + return usage(stdout, EXIT_SUCCESS, 1); + case '?': + if (optopt == '?') { // '-?' appeared on command line + return usage(stdout, EXIT_SUCCESS, 1); + } else { + if (optopt) { // Bad short option + print_error("view", "invalid option -- '%c'", optopt); + } else { // Bad long option + // Do our best. There is no good solution to finding + // out what the bad option was. + // See, e.g. https://stackoverflow.com/questions/2723888/where-does-getopt-long-store-an-unrecognized-option + if (optind > 0 && strncmp(argv[optind - 1], "--", 2) == 0) { + print_error("view", "unrecognised option '%s'", + argv[optind - 1]); + } + } + return usage(stderr, EXIT_FAILURE, 0); + } + case 'B': settings.remove_B = 1; break; + + case 'M': settings.multi_region = 1; break; + case LONGOPT('P'): no_pg = 1; break; + case 'e': + if (!(settings.filter = hts_filter_init(optarg))) { + print_error("main_samview", "Couldn't initialise filter"); + return 1; + } + settings.count_rf = INT_MAX; // no way to know what we need + break; + case LONGOPT('r'): settings.remove_flag |= bam_str2flag(optarg); break; + case LONGOPT('a'): settings.add_flag |= bam_str2flag(optarg); break; + + case 'x': + if (*optarg == '^') { + if (parse_aux_list(&settings.keep_tag, optarg+1, "main_samview")) { + aux_list_free(&settings); + return usage(stderr, EXIT_FAILURE, 0); + } + } else { + if (parse_aux_list(&settings.remove_tag, optarg, "main_samview")) { + aux_list_free(&settings); + return usage(stderr, EXIT_FAILURE, 0); + } + } + break; + + case LONGOPT('x'): + if (parse_aux_list(&settings.keep_tag, optarg, "main_samview")) { + aux_list_free(&settings); + return usage(stderr, EXIT_FAILURE, 0); + } + break; + + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) != 0) + return usage(stderr, EXIT_FAILURE, 0); + break; + } + } + if (settings.is_count && settings.fetch_pairs) + { + print_error("view","The options -P and -c cannot be combined\n"); + return 1; + } + if (settings.fn_fai == 0 && ga.reference) settings.fn_fai = fai_path(ga.reference); + if (is_header_only) is_header = 1; + // File format auto-detection first + if (settings.fn_out) sam_open_mode(out_mode+1, settings.fn_out, NULL); + if (settings.fn_un_out) sam_open_mode(out_un_mode+1, settings.fn_un_out, NULL); + + // -1 or -u without an explicit format (-b, -C) => check fn extensions + if (!*out_format && compress_level >= 0) { + if (compress_level == 0 && + (out_mode[strlen(out_mode)-1] == 'z' || + out_un_mode[strlen(out_un_mode)-1] == 'z')) + // z, fz, Fz sanity check + fprintf(stderr, "[view] Warning option -u ignored due to" + " filename suffix\n"); + + // If known extension, use it, otherwise BAM + if (!(out_mode[1] || is_sam(settings.fn_out))) + out_mode[1] = 'b'; + + if (!(out_un_mode[1] || is_sam(settings.fn_un_out))) + out_un_mode[1] = 'b'; + } else if (*out_format) { + out_mode[1] = out_un_mode[1] = *out_format; + } + + if (compress_level >= 0) { + char tmp[2]; + tmp[0] = compress_level + '0'; tmp[1] = '\0'; + strcat(out_mode, tmp); + strcat(out_un_mode, tmp); + } + if (argc == optind && isatty(STDIN_FILENO)) { + print_error("view", "No input provided or missing option argument."); + return usage(stderr, EXIT_FAILURE, 0); // potential memory leak... + } + + if (settings.unmap && settings.fn_un_out) { + print_error("view", "Options --unoutput and --unmap are mutually exclusive."); + ret = 1; + goto view_end; + } + + if (settings.subsam_seed != 0) { + // Convert likely user input 1,2,... to pseudo-random + // values with more entropy and more bits set + srand(settings.subsam_seed); + settings.subsam_seed = rand(); + } + + settings.fn_in = (optind < argc)? argv[optind] : "-"; + if ((settings.in = sam_open_format(settings.fn_in, "r", &ga.in)) == 0) { + print_error_errno("view", "failed to open \"%s\" for reading", settings.fn_in); + ret = 1; + goto view_end; + } + + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.in, settings.fn_fai) != 0) { + fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + if ((settings.header = sam_hdr_read(settings.in)) == 0) { + fprintf(stderr, "[main_samview] fail to read the header from \"%s\".\n", settings.fn_in); + ret = 1; + goto view_end; + } + if (settings.rghash) { + sam_hdr_remove_lines(settings.header, "RG", "ID", settings.rghash); + } + if (!settings.is_count) { + if ((settings.out = sam_open_format(settings.fn_out? settings.fn_out : "-", out_mode, &ga.out)) == 0) { + print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_out? settings.fn_out : "standard output"); + ret = 1; + goto view_end; + } + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.out, settings.fn_fai) != 0) { + fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + autoflush_if_stdout(settings.out, settings.fn_out); + + if (!no_pg) { + if (!(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("view", "failed to create arg_list"); + ret = 1; + goto view_end; + } + if (sam_hdr_add_pg(settings.header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error("view", "failed to add PG line to the header"); + ret = 1; + goto view_end; + } + } + + if (ga.write_index || is_header || + out_mode[1] == 'b' || out_mode[1] == 'c' || + (ga.out.format != sam && ga.out.format != unknown_format)) { + if (sam_hdr_write(settings.out, settings.header) != 0) { + fprintf(stderr, "[main_samview] failed to write the SAM header\n"); + ret = 1; + goto view_end; + } + } + if (ga.write_index) { + if (!(settings.fn_out_idx = auto_index(settings.out, settings.fn_out, settings.header))) { + ret = 1; + goto view_end; + } + } + + if (settings.fn_un_out) { + if ((settings.un_out = sam_open_format(settings.fn_un_out, out_un_mode, &ga.out)) == 0) { + print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_un_out); + ret = 1; + goto view_end; + } + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.un_out, settings.fn_fai) != 0) { + fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + autoflush_if_stdout(settings.un_out, settings.fn_un_out); + if (ga.write_index || is_header || + out_un_mode[1] == 'b' || out_un_mode[1] == 'c' || + (ga.out.format != sam && ga.out.format != unknown_format)) { + if (sam_hdr_write(settings.un_out, settings.header) != 0) { + fprintf(stderr, "[main_samview] failed to write the SAM header\n"); + ret = 1; + goto view_end; + } + } + if (ga.write_index) { + if (!(settings.fn_un_out_idx = auto_index(settings.un_out, settings.fn_un_out, settings.header))) { + ret = 1; + goto view_end; + } + } + } + } + else { + if (settings.fn_out) { + fp_out = fopen(settings.fn_out, "w"); + if (fp_out == NULL) { + print_error_errno("view", "can't create \"%s\"", settings.fn_out); + ret = EXIT_FAILURE; + goto view_end; + } + } + settings.unmap = 0; // Not valid in counting mode + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(stderr, "Error creating thread pool\n"); + ret = 1; + goto view_end; + } + hts_set_opt(settings.in, HTS_OPT_THREAD_POOL, &p); + if (settings.out) hts_set_opt(settings.out, HTS_OPT_THREAD_POOL, &p); + } + if (is_header_only) goto view_end; // no need to print alignments + + + // Initialize BAM/CRAM index + char **regs = NULL; + int nregs = 0; + if ( has_index_file && optind <= argc - 2 ) { + regs = optind < argc-2 ? &argv[optind+2] : NULL; + nregs = argc - optind - 2; + settings.fn_idx_in = argv[optind+1]; + } else if (!has_index_file && optind < argc - 1 ) { + regs = &argv[optind+1]; + nregs = argc - optind - 1; + } else if ( has_index_file && argc-optind < 2) { + print_error("view", "Incorrect number of arguments for -X option. Aborting."); + return 1; + } + if (regs) + settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR; + + if ( settings.fn_idx_in || nregs || settings.multi_region ) + { + settings.hts_idx = settings.fn_idx_in ? sam_index_load2(settings.in, settings.fn_in, settings.fn_idx_in) : sam_index_load(settings.in, settings.fn_in); + if ( !settings.hts_idx ) + { + print_error("view", "Random alignment retrieval only works for indexed SAM.gz, BAM or CRAM files."); + return 1; + } + } + + if (settings.is_count) + // Won't fail, but also wouldn't matter if it did + hts_set_opt(settings.in, CRAM_OPT_REQUIRED_FIELDS, settings.count_rf); + + if ( settings.fetch_pairs ) + { + hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs); + ret = iter ? fetch_pairs_collect_mates(&settings, iter) : 1; + if (ret) goto view_end; + } + else if ( settings.multi_region ) + { + hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs); + ret = iter ? multi_region_view(&settings, iter) : 1; + if (ret) goto view_end; + } + else if ( !settings.hts_idx || optind+1 >= argc-has_index_file ) { + // stream through the entire file + ret = stream_view(&settings); + if (ret) goto view_end; + } else { // retrieve alignments in specified regions + int i; + for (i = (has_index_file)? optind+2 : optind+1; i < argc; ++i) { + hts_itr_t *iter = sam_itr_querys(settings.hts_idx, settings.header, argv[i]); // parse a region in the format like `chr2:100-200' + if (iter == NULL) { // region invalid or reference name not found + fprintf(stderr, "[main_samview] region \"%s\" specifies an invalid region or unknown reference. Continue anyway.\n", argv[i]); + continue; + } + // fetch alignments + ret = multi_region_view(&settings, iter); + if (ret) goto view_end; + } + } + + if ( settings.hts_idx ) hts_idx_destroy(settings.hts_idx); + + if (ga.write_index) { + if (sam_idx_save(settings.out) < 0) { + print_error_errno("view", "writing index failed"); + ret = 1; + } + if (settings.un_out && sam_idx_save(settings.un_out) < 0) { + print_error_errno("view", "writing index failed"); + ret = 1; + } + } + +view_end: + if (settings.is_count && ret == 0) { + if (fprintf(settings.fn_out? fp_out : stdout, "%" PRId64 "\n", settings.count) < 0) { + if (settings.fn_out) print_error_errno("view", "writing to \"%s\" failed", settings.fn_out); + else print_error_errno("view", "writing to standard output failed"); + ret = EXIT_FAILURE; + } + } + + // close files, free and return + if (settings.in) check_sam_close("view", settings.in, settings.fn_in, "standard input", &ret); + if (settings.out) check_sam_close("view", settings.out, settings.fn_out, "standard output", &ret); + if (settings.un_out) check_sam_close("view", settings.un_out, settings.fn_un_out, "file", &ret); + if (fp_out) fclose(fp_out); + + free(settings.fn_fai); free(settings.fn_out); free(settings.library); free(settings.fn_un_out); + sam_global_args_free(&ga); + if ( settings.header ) sam_hdr_destroy(settings.header); + if (settings.bed) bed_destroy(settings.bed); + if (settings.rghash) { + khint_t k; + for (k = 0; k < kh_end(settings.rghash); ++k) + if (kh_exist(settings.rghash, k)) free((char*)kh_key(settings.rghash, k)); + kh_destroy(str, settings.rghash); + } + if (settings.rnhash) { + khint_t k; + for (k = 0; k < kh_end(settings.rnhash); ++k) + if (kh_exist(settings.rnhash, k)) free((char*)kh_key(settings.rnhash, k)); + kh_destroy(str, settings.rnhash); + } + if (settings.tvhash) { + khint_t k; + for (k = 0; k < kh_end(settings.tvhash); ++k) + if (kh_exist(settings.tvhash, k)) free((char*)kh_key(settings.tvhash, k)); + kh_destroy(str, settings.tvhash); + } + + if (settings.remove_aux_len) { + free(settings.remove_aux); + } + if (settings.tag) { + free(settings.tag); + } + if (settings.filter) + hts_filter_free(settings.filter); + + if (p.pool) + hts_tpool_destroy(p.pool); + + if (settings.fn_out_idx) + free(settings.fn_out_idx); + if (settings.fn_un_out_idx) + free(settings.fn_un_out_idx); + free(arg_list); + + aux_list_free(&settings); + + return ret; +} + +static int usage(FILE *fp, int exit_status, int is_long_help) +{ + fprintf(fp, +"\n" +"Usage: samtools view [options] || [region ...]\n" +"\n" + +"Output options:\n" +" -b, --bam Output BAM\n" +" -C, --cram Output CRAM (requires -T)\n" +" -1, --fast Use fast BAM compression (and default to --bam)\n" +" -u, --uncompressed Uncompressed BAM output (and default to --bam)\n" +" -h, --with-header Include header in SAM output\n" +" -H, --header-only Print SAM header only (no alignments)\n" +" --no-header Print SAM alignment records only [default]\n" +" -c, --count Print only the count of matching records\n" +" -o, --output FILE Write output to FILE [standard output]\n" +" -U, --unoutput FILE, --output-unselected FILE\n" +" Output reads not selected by filters to FILE\n" +" -p, --unmap Set flag to UNMAP on reads not selected\n" +" then write to output file.\n" +" -P, --fetch-pairs Retrieve complete pairs even when outside of region\n" +"Input options:\n" +" -t, --fai-reference FILE FILE listing reference names and lengths\n" +" -M, --use-index Use index and multi-region iterator for regions\n" +" --region[s]-file FILE Use index to include only reads overlapping FILE\n" +" -X, --customized-index Expect extra index file argument after \n" +"\n" +"Filtering options (Only include in output reads that...):\n" +" -L, --target[s]-file FILE ...overlap (BED) regions in FILE\n" +" -r, --read-group STR ...are in read group STR\n" +" -R, --read-group-file FILE ...are in a read group listed in FILE\n" +" -N, --qname-file FILE ...whose read name is listed in FILE\n" +" -d, --tag STR1[:STR2] ...have a tag STR1 (with associated value STR2)\n" +" -D, --tag-file STR:FILE ...have a tag STR whose value is listed in FILE\n" +" -q, --min-MQ INT ...have mapping quality >= INT\n" +" -l, --library STR ...are in library STR\n" +" -m, --min-qlen INT ...cover >= INT query bases (as measured via CIGAR)\n" +" -e, --expr STR ...match the filter expression STR\n" +" -f, --require-flags FLAG ...have all of the FLAGs present\n" // F&x == x +" -F, --excl[ude]-flags FLAG ...have none of the FLAGs present\n" // F&x == 0 +" --rf, --incl-flags, --include-flags FLAG\n" +" ...have some of the FLAGs present\n" +" -G FLAG EXCLUDE reads with all of the FLAGs present\n" // !(F&x == x) TODO long option +" --subsample FLOAT Keep only FLOAT fraction of templates/read pairs\n" +" --subsample-seed INT Influence WHICH reads are kept in subsampling [0]\n" +" -s INT.FRAC Same as --subsample 0.FRAC --subsample-seed INT\n" +"\n" +"Processing options:\n" +" --add-flags FLAG Add FLAGs to reads\n" +" --remove-flags FLAG Remove FLAGs from reads\n" +" -x, --remove-tag STR\n" +" Comma-separated read tags to strip (repeatable) [null]\n" +" --keep-tag STR\n" +" Comma-separated read tags to preserve (repeatable) [null].\n" +" Equivalent to \"-x ^STR\"\n" +" -B, --remove-B Collapse the backward CIGAR operation\n" +" -z, --sanitize FLAGS Perform sanitity checking and fixing on records.\n" +" FLAGS is comma separated (see manual). [off]\n" +"\n" +"General options:\n" +" -?, --help Print long help, including note about region specification\n" +" -S Ignored (input format is auto-detected)\n" +" --no-PG Do not add a PG line\n"); + + sam_global_opt_help(fp, "-.O.T@.."); + fprintf(fp, "\n"); + + if (is_long_help) + fprintf(fp, +"Notes:\n" +"\n" +"1. This command now auto-detects the input format (BAM/CRAM/SAM).\n" +" Further control over the CRAM format can be specified by using the\n" +" --output-fmt-option, e.g. to specify the number of sequences per slice\n" +" and to use avoid reference based compression:\n" +"\n" +"\tsamtools view -C --output-fmt-option seqs_per_slice=5000 \\\n" +"\t --output-fmt-option no_ref -o out.cram in.bam\n" +"\n" +" Options can also be specified as a comma separated list within the\n" +" --output-fmt value too. For example this is equivalent to the above\n" +"\n" +"\tsamtools view --output-fmt cram,seqs_per_slice=5000,no_ref \\\n" +"\t -o out.cram in.bam\n" +"\n" +"2. The file supplied with `-t' is SPACE/TAB delimited with the first\n" +" two fields of each line consisting of the reference name and the\n" +" corresponding sequence length. The `.fai' file generated by \n" +" `samtools faidx' is suitable for use as this file. This may be an\n" +" empty file if reads are unaligned.\n" +"\n" +"3. SAM->BAM conversion: samtools view -bT ref.fa in.sam.gz\n" +"\n" +"4. BAM->SAM conversion: samtools view -h in.bam\n" +"\n" +"5. A region should be presented in one of the following formats:\n" +" `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n" +" specified, the input alignment file must be a sorted and indexed\n" +" alignment (BAM/CRAM) file.\n" +"\n" +"6. Option `-u' is preferred over `-b' when the output is piped to\n" +" another samtools command.\n" +"\n" +"7. Option `-M`/`--use-index` causes overlaps with `-L` BED file regions and\n" +" command-line region arguments to be computed using the multi-region iterator\n" +" and an index. This increases speed, omits duplicates, and outputs the reads\n" +" as they are ordered in the input SAM/BAM/CRAM file.\n" +"\n" +"8. Options `-L`/`--target[s]-file` and `--region[s]-file` may not be used\n" +" together. `--region[s]-file FILE` is simply equivalent to `-M -L FILE`,\n" +" so using both causes one of the specified BED files to be ignored.\n" +"\n"); + + return exit_status; +} + +static int head_usage(FILE *fp, int exit_status) +{ + fprintf(fp, +"Usage: samtools head [OPTION]... [FILE]\n" +"Options:\n" +" -h, --headers INT Display INT header lines [all]\n" +" -n, --records INT Display INT alignment record lines [none]\n" +); + sam_global_opt_help(fp, "-.--T@-."); + return exit_status; +} + +int main_head(int argc, char *argv[]) +{ + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'T', '@'), + { "headers", required_argument, NULL, 'h' }, + { "records", required_argument, NULL, 'n' }, + { NULL, 0, NULL, 0 } + }; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + int all_headers = 1; + uint64_t nheaders = 0; + uint64_t nrecords = 0; + + int c, nargs; + while ((c = getopt_long(argc, argv, "h:n:T:@:", lopts, NULL)) >= 0) + switch (c) { + case 'h': all_headers = 0; nheaders = strtoull(optarg, NULL, 0); break; + case 'n': nrecords = strtoull(optarg, NULL, 0); break; + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + return head_usage(stderr, EXIT_FAILURE); + } + + nargs = argc - optind; + if (nargs == 0 && isatty(STDIN_FILENO)) + return head_usage(stdout, EXIT_SUCCESS); + else if (nargs > 1) + return head_usage(stderr, EXIT_FAILURE); + + samFile *fp = NULL; + sam_hdr_t *hdr = NULL; + kstring_t str = KS_INITIALIZE; + bam1_t *b = NULL; + + const char *fname = (nargs == 1)? argv[optind] : "-"; + fp = sam_open_format(fname, "r", &ga.in); + if (fp == NULL) { + if (strcmp(fname, "-") != 0) + print_error_errno("head", "failed to open \"%s\" for reading", fname); + else + print_error_errno("head", "failed to open standard input for reading"); + goto err; + } + + if (ga.nthreads > 0) hts_set_threads(fp, ga.nthreads); + + hdr = sam_hdr_read(fp); + if (hdr == NULL) { + if (strcmp(fname, "-") != 0) + print_error("head", "failed to read the header from \"%s\"", fname); + else + print_error("head", "failed to read the header"); + goto err; + } + + if (all_headers) { + fputs(sam_hdr_str(hdr), stdout); + } + else if (nheaders > 0) { + const char *text = sam_hdr_str(hdr); + const char *lim = text; + uint64_t n; + for (n = 0; n < nheaders; n++) { + lim = strchr(lim, '\n'); + if (lim) lim++; + else break; + } + if (lim) fwrite(text, lim - text, 1, stdout); + else fputs(text, stdout); + } + + if (nrecords > 0) { + b = bam_init1(); + uint64_t n; + int r; + for (n = 0; n < nrecords && (r = sam_read1(fp, hdr, b)) >= 0; n++) { + if (sam_format1(hdr, b, &str) < 0) { + print_error_errno("head", "couldn't format record"); + goto err; + } + puts(ks_str(&str)); + } + if (r < -1) { + print_error("head", "\"%s\" is truncated", fname); + goto err; + } + bam_destroy1(b); + ks_free(&str); + } + + sam_hdr_destroy(hdr); + sam_close(fp); + sam_global_args_free(&ga); + + return EXIT_SUCCESS; + +err: + if (fp) sam_close(fp); + sam_hdr_destroy(hdr); + bam_destroy1(b); + ks_free(&str); + sam_global_args_free(&ga); + return EXIT_FAILURE; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..e1b681b820ac50bc105d39bdaf63609c4110f28f --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sam_view.c.pysam.c @@ -0,0 +1,1668 @@ +#include "samtools.pysam.h" + +/* sam_view.c -- SAM<->BAM<->CRAM conversion. + + Copyright (C) 2009-2023 Genome Research Ltd. + Portions copyright (C) 2009, 2011, 2012 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notices and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "htslib/khash.h" +#include "htslib/kstring.h" +#include "htslib/thread_pool.h" +#include "htslib/hts_expr.h" +#include "samtools.h" +#include "sam_opts.h" +#include "bam.h" // for bam_get_library and bam_remove_B +#include "bedidx.h" +#include "sam_utils.h" + +KHASH_SET_INIT_STR(str) +typedef khash_t(str) *strhash_t; + +// This structure contains the settings for a samview run +typedef struct samview_settings { + strhash_t rghash; + strhash_t rnhash; + strhash_t tvhash; + int min_mapQ; + + // Described here in the same terms as the usage statement. + // The code however always negates to "reject if" keep if: + int flag_on; // keep if (FLAG & N) == N (all on) + int flag_off; // keep if (FLAG & N) == 0 (all off) + int flag_anyon; // keep if (FLAG & N) != 0 (any on) + int flag_alloff; // reject if (FLAG & N) == N (any off) + + int min_qlen; + int remove_B; + uint32_t subsam_seed; + double subsam_frac; + char* library; + void* bed; + size_t remove_aux_len; + char** remove_aux; + int multi_region; + char* tag; + hts_filter_t *filter; + int remove_flag; + int add_flag; + int unmap; + auxhash_t remove_tag; + auxhash_t keep_tag; + + hts_idx_t *hts_idx; + sam_hdr_t *header; + samFile *in, *out, *un_out; + int64_t count; + int is_count; + char *fn_in, *fn_idx_in, *fn_out, *fn_fai, *fn_un_out, *fn_out_idx, *fn_un_out_idx; + int fetch_pairs, nreglist; + hts_reglist_t *reglist; + int sanitize; + int count_rf; // CRAM_OPT_REQUIRED_FIELDS for view -c +} samview_settings_t; + +// Copied from htslib/sam.c. +// TODO: we need a proper interface to find the length of an aux tag, +// or at the very make exportable versions of these in htslib. +static inline int aux_type2size(uint8_t type) +{ + switch (type) { + case 'A': case 'c': case 'C': + return 1; + case 's': case 'S': + return 2; + case 'i': case 'I': case 'f': + return 4; + case 'd': + return 8; + case 'Z': case 'H': case 'B': + return type; + default: + return 0; + } +} + +// Copied from htslib/sam.c. +static inline uint8_t *skip_aux(uint8_t *s, uint8_t *end) +{ + int size; + uint32_t n; + if (s >= end) return end; + size = aux_type2size(*s); ++s; // skip type + switch (size) { + case 'Z': + case 'H': + while (s < end && *s) ++s; + return s < end ? s + 1 : end; + case 'B': + if (end - s < 5) return NULL; + size = aux_type2size(*s); ++s; + n = le_to_u32(s); + s += 4; + if (size == 0 || end - s < size * n) return NULL; + return s + size * n; + case 0: + return NULL; + default: + if (end - s < size) return NULL; + return s + size; + } +} + +// Returns 0 to indicate read should be output 1 otherwise, +// and -1 on error. +static int process_aln(const sam_hdr_t *h, bam1_t *b, samview_settings_t* settings) +{ + if (settings->filter) { + int r = sam_passes_filter(h, b, settings->filter); + if (r < 0) // err + return -1; + if (r == 0) // filter-out + return 1; + } + + if (settings->remove_B) bam_remove_B(b); + if (settings->min_qlen > 0) { + int k, qlen = 0; + uint32_t *cigar = bam_get_cigar(b); + for (k = 0; k < b->core.n_cigar; ++k) + if ((bam_cigar_type(bam_cigar_op(cigar[k]))&1) || bam_cigar_op(cigar[k]) == BAM_CHARD_CLIP) + qlen += bam_cigar_oplen(cigar[k]); + if (qlen < settings->min_qlen) return 1; + } + if (b->core.qual < settings->min_mapQ || ((b->core.flag & settings->flag_on) != settings->flag_on) || (b->core.flag & settings->flag_off)) + return 1; + if (settings->flag_alloff && ((b->core.flag & settings->flag_alloff) == settings->flag_alloff)) + return 1; + if (settings->flag_anyon && ((b->core.flag & settings->flag_anyon) == 0)) + return 1; + if (!settings->multi_region && settings->bed && (b->core.tid < 0 || !bed_overlap(settings->bed, sam_hdr_tid2name(h, b->core.tid), b->core.pos, bam_endpos(b)))) + return 1; + if (settings->subsam_frac > 0.) { + uint32_t k = __ac_Wang_hash(__ac_X31_hash_string(bam_get_qname(b)) ^ settings->subsam_seed); + if ((double)(k&0xffffff) / 0x1000000 >= settings->subsam_frac) return 1; + } + if (settings->rghash) { + uint8_t *s = bam_aux_get(b, "RG"); + if (s) { + khint_t k = kh_get(str, settings->rghash, (char*)(s + 1)); + if (k == kh_end(settings->rghash)) return 1; + } + } + if (settings->tag) { + uint8_t *s = bam_aux_get(b, settings->tag); + if (s) { + if (settings->tvhash) { + char t[32], *val; + if (*s == 'i' || *s == 'I' || *s == 's' || *s == 'S' || *s == 'c' || *s == 'C') { + int ret = snprintf(t, 32, "%"PRId64, bam_aux2i(s)); + if (ret > 0) val = t; + else return 1; + } else if (*s == 'A') { + t[0] = *(s+1); + t[1] = 0; + val = t; + } else { + val = (char *)(s+1); + } + khint_t k = kh_get(str, settings->tvhash, val); + if (k == kh_end(settings->tvhash)) return 1; + } + } else { + return 1; + } + } + if (settings->rnhash) { + const char* rn = bam_get_qname(b); + if (!rn || kh_get(str, settings->rnhash, rn) == kh_end(settings->rnhash)) { + return 1; + } + } + if (settings->library) { + const char *p = bam_get_library((sam_hdr_t*)h, b); + if (!p || strcmp(p, settings->library) != 0) return 1; + } + return 0; +} + +static int adjust_tags(const sam_hdr_t *h, bam1_t *b, + samview_settings_t* settings) { + if (settings->keep_tag) { + uint8_t *s_from, *s_to, *end = b->data + b->l_data; + auxhash_t h = settings->keep_tag; + + s_from = s_to = bam_get_aux(b); + while (s_from < end) { + int x = (int)s_from[0]<<8 | s_from[1]; + uint8_t *s = skip_aux(s_from+2, end); + if (s == NULL) { + print_error("view", "malformed aux data for record \"%s\"", + bam_get_qname(b)); + return -1; + } + + if (kh_get(aux_exists, h, x) != kh_end(h) ) { + if (s_to != s_from) memmove(s_to, s_from, s - s_from); + s_to += s - s_from; + } + s_from = s; + } + b->l_data = s_to - b->data; + + } else if (settings->remove_tag) { + uint8_t *s_from, *s_to, *end = b->data + b->l_data; + auxhash_t h = settings->remove_tag; + + s_from = s_to = bam_get_aux(b); + while (s_from < end) { + int x = (int)s_from[0]<<8 | s_from[1]; + uint8_t *s = skip_aux(s_from+2, end); + if (s == NULL) { + print_error("view", "malformed aux data for record \"%s\"", + bam_get_qname(b)); + return -1; + } + + if (kh_get(aux_exists, h, x) == kh_end(h) ) { + if (s_to != s_from) memmove(s_to, s_from, s - s_from); + s_to += s - s_from; + } + s_from = s; + } + b->l_data = s_to - b->data; + } + + return 0; +} + +static int usage(FILE *fp, int exit_status, int is_long_help); + +static int populate_lookup_from_file(const char *subcmd, strhash_t lookup, char *fn) +{ + FILE *fp; + char buf[1024]; + int ret = 0; + fp = fopen(fn, "r"); + if (fp == NULL) { + print_error_errno(subcmd, "failed to open \"%s\" for reading", fn); + return -1; + } + + while (ret != -1 && !feof(fp) && fscanf(fp, "%1023s", buf) > 0) { + char *d = strdup(buf); + if (d != NULL) { + kh_put(str, lookup, d, &ret); + if (ret == 0) free(d); /* Duplicate */ + } else { + ret = -1; + } + } + if (ferror(fp)) ret = -1; + if (ret == -1) { + print_error_errno(subcmd, "failed to read \"%s\"", fn); + } + fclose(fp); + return (ret != -1) ? 0 : -1; +} + +static int add_read_group_single(const char *subcmd, samview_settings_t *settings, char *name) +{ + char *d = strdup(name); + int ret = 0; + + if (d == NULL) goto err; + + if (settings->rghash == NULL) { + settings->rghash = kh_init(str); + if (settings->rghash == NULL) goto err; + } + + kh_put(str, settings->rghash, d, &ret); + if (ret == -1) goto err; + if (ret == 0) free(d); /* Duplicate */ + return 0; + + err: + print_error(subcmd, "Couldn't add \"%s\" to read group list: memory exhausted?", name); + free(d); + return -1; +} + +static int add_read_names_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->rnhash == NULL) { + settings->rnhash = kh_init(str); + if (settings->rnhash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->rnhash, fn); +} + +static int add_read_groups_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->rghash == NULL) { + settings->rghash = kh_init(str); + if (settings->rghash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->rghash, fn); +} + +static int add_tag_value_single(const char *subcmd, samview_settings_t *settings, char *name) +{ + char *d = strdup(name); + int ret = 0; + + if (d == NULL) goto err; + + if (settings->tvhash == NULL) { + settings->tvhash = kh_init(str); + if (settings->tvhash == NULL) goto err; + } + + kh_put(str, settings->tvhash, d, &ret); + if (ret == -1) goto err; + if (ret == 0) free(d); /* Duplicate */ + return 0; + + err: + print_error(subcmd, "Couldn't add \"%s\" to tag values list: memory exhausted?", name); + free(d); + return -1; +} + +static int add_tag_values_file(const char *subcmd, samview_settings_t *settings, char *fn) +{ + if (settings->tvhash == NULL) { + settings->tvhash = kh_init(str); + if (settings->tvhash == NULL) { + perror(NULL); + return -1; + } + } + return populate_lookup_from_file(subcmd, settings->tvhash, fn); +} + +static inline int check_sam_write1(samFile *fp, const sam_hdr_t *h, const bam1_t *b, const char *fname, int *retp) +{ + int r = sam_write1(fp, h, b); + if (r >= 0) return r; + + if (fname) print_error_errno("view", "writing to \"%s\" failed", fname); + else print_error_errno("view", "writing to standard output failed"); + + *retp = EXIT_FAILURE; + return r; +} + +static inline void change_flag(bam1_t *b, samview_settings_t *settings) +{ + if (settings->add_flag) + b->core.flag |= settings->add_flag; + + if (settings->remove_flag) + b->core.flag &= ~settings->remove_flag; +} + +static int cmp_reglist_intervals(const void *aptr, const void *bptr) +{ + hts_pair_pos_t *a = (hts_pair_pos_t*)aptr; + hts_pair_pos_t *b = (hts_pair_pos_t*)bptr; + if ( a->beg < b->beg ) return -1; + if ( a->beg > b->beg ) return 1; + if ( a->end < b->end ) return -1; + if ( a->end > b->end ) return 1; + return 0; +} +static int cmp_reglist_tids(const void *aptr, const void *bptr) +{ + hts_reglist_t *a = (hts_reglist_t*)aptr; + hts_reglist_t *b = (hts_reglist_t*)bptr; + if ( b->tid==HTS_IDX_NOCOOR || a->tid < b->tid ) return -1; + if ( a->tid==HTS_IDX_NOCOOR || a->tid > b->tid ) return 1; + return 0; +} + +static hts_reglist_t *_reglist_dup(sam_hdr_t *hdr, hts_reglist_t *src, int nsrc) +{ + int i,j; + hts_reglist_t *dst = (hts_reglist_t*)calloc(nsrc,sizeof(hts_reglist_t)); + if ( !dst ) { + print_error_errno("view", "[%s:%d] could not allocate region list" + ,__FILE__ ,__LINE__); + return NULL; + } + for (i=0; i tid ) imax = i - 1; + else break; + } + if ( i<0 || reg[i].tid < tid ) i++; // not found, i will be the index of the inserted element + return i; +} +static int _reglist_push(hts_reglist_t **_reg, int *_nreg, int tid, hts_pos_t beg, hts_pos_t end) +{ + hts_reglist_t *reg = *_reg; + int nreg = *_nreg; + int i = _reglist_find_tid(reg,nreg,tid); + if ( i>=nreg || reg[i].tid!=tid ) { + nreg++; + reg = (hts_reglist_t*)realloc(reg,sizeof(hts_reglist_t)*nreg); + if ( !reg ) { + print_error_errno("view", "[%s:%d] could not extend region list", + __FILE__, __LINE__); + return -1; + } + if ( i+1 < nreg ) + memmove(reg + i + 1, reg + i, sizeof(hts_reglist_t)*(nreg - i - 1)); + reg[i].reg = NULL; + reg[i].tid = tid; + reg[i].min_beg = beg; + reg[i].max_end = end; + reg[i].intervals = NULL; + reg[i].count = 0; + } + *_reg = reg; + *_nreg = nreg; + if ( reg[i].count > 0 + && reg[i].intervals[reg[i].count - 1].beg==beg + && reg[i].intervals[reg[i].count - 1].end==end ) { + return 0; + } + hts_pair_pos_t *new_intervals = realloc(reg[i].intervals, sizeof(hts_pair_pos_t)*(reg[i].count + 1)); + if (!new_intervals) { + print_error_errno("view", "[%s:%d] could not extend region list", + __FILE__, __LINE__); + return -1; + } + reg[i].intervals = new_intervals; + reg[i].intervals[reg[i].count].beg = beg; + reg[i].intervals[reg[i].count].end = end; + reg[i].count++; + return 0; +} + +static void _reglist_merge(hts_reglist_t *reg, int nreg) +{ + int i,j; + for (i=0; ibed = bed_hash_regions(conf->bed, regs, 0, nregs, &filter_op); // insert(1) or filter out(0) the regions from the command line in the same hash table as the bed file + if ( !filter_op ) + filter_state = FILTERED; + } + else + bed_unify(conf->bed); + if ( !conf->bed) { // index is unavailable or no regions have been specified + print_error("view", "No regions or BED file have been provided. Aborting."); + return NULL; + } + + int regcount = 0; + hts_reglist_t *reglist = bed_reglist(conf->bed, filter_state, ®count); + if (!reglist) { + print_error("view", "Region list is empty or could not be created. Aborting."); + return NULL; + } + + if ( conf->fetch_pairs ) { + conf->reglist = _reglist_dup(conf->header,reglist,regcount); + if (!conf->reglist) + return NULL; + conf->nreglist = regcount; + } + + iter = sam_itr_regions(conf->hts_idx, conf->header, reglist, regcount); + if ( !iter ) { + print_error("view", "Iterator could not be created. Aborting."); + return NULL; + } + return iter; +} + +KHASH_SET_INIT_STR(names) + +static int fetch_pairs_collect_mates(samview_settings_t *conf, hts_itr_multi_t *iter) +{ + khint_t k; + int nunmap = 0, r = 0, nmates = 0, write_error = 0, retval = EXIT_FAILURE; + kh_names_t *mate_names = kh_init(names); + bam1_t *rec = bam_init1(); + + if (!mate_names) { + print_error_errno("view", "could not allocate mate names table"); + goto out; + } + if (!rec) { + print_error_errno("view", "could not allocate bam record"); + goto out; + } + + while ((r =sam_itr_multi_next(conf->in, iter, rec))>=0) { + if ( (rec->core.flag & BAM_FPAIRED) == 0 ) continue; + if ( rec->core.mtid>=0 && bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.mtid), rec->core.mpos, rec->core.mpos) ) continue; + int p = process_aln(conf->header, rec, conf); + if (p < 0) goto out; + if (p == 1) continue; + + nmates++; + + k = kh_get(names,mate_names,bam_get_qname(rec)); + if ( k == kh_end(mate_names) ) { + int ret = 0; + char *name_copy = strdup(bam_get_qname(rec)); + if (!name_copy) { + print_error_errno("view", "[%s:%d] could not store sample name, %d elements", __FILE__,__LINE__,nmates); + goto out; + } + kh_put(names, mate_names, name_copy, &ret); + if ( ret<0 ) { + print_error_errno("view", "[%s:%d] could not store sample name, %d elements",__FILE__,__LINE__,nmates); + free(name_copy); + goto out; + } + } + + if ( rec->core.mtid < 0 || (rec->core.flag & BAM_FMUNMAP) ) nunmap = 1; + if ( rec->core.mtid >= 0 ) { + if (_reglist_push(&conf->reglist, &conf->nreglist, rec->core.mtid, rec->core.mpos,rec->core.mpos+1) != 0) + goto out; + } + } + + if (r < -1) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + goto out; + } + + _reglist_merge(conf->reglist, conf->nreglist); + if ( nunmap ) { + if (_reglist_push(&conf->reglist,&conf->nreglist,HTS_IDX_NOCOOR,0,HTS_POS_MAX) != 0) + goto out; + } + hts_itr_multi_destroy(iter); + iter = sam_itr_regions(conf->hts_idx, conf->header, conf->reglist, conf->nreglist); + if ( !iter ) { + print_error_errno("view", "[%s:%d] iterator could not be created",__FILE__,__LINE__); + goto out; + } + while ((r = sam_itr_multi_next(conf->in, iter, rec))>=0) { + int drop = 1; + if (rec->core.tid >=0 && + bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.tid), rec->core.pos, bam_endpos(rec))) drop = 0; + if ( drop ) { + k = kh_get(names,mate_names,bam_get_qname(rec)); + if ( k != kh_end(mate_names) ) drop = 0; + } + int p = 0; + if (!drop && (p=process_aln(conf->header, rec, conf))== 0) { + if (adjust_tags(conf->header, rec, conf) != 0) + goto out; + if (check_sam_write1(conf->out, conf->header, rec, conf->fn_out, + &write_error) < 0) + goto out; + } + if (p < 0) + goto out; + } + + if (r < -1) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + goto out; + } + + retval = EXIT_SUCCESS; + + out: + hts_itr_multi_destroy(iter); + hts_idx_destroy(conf->hts_idx); // destroy the BAM index + conf->hts_idx = NULL; + if (mate_names) { + // free khash keys + for (k = 0; k < kh_end(mate_names); ++k) + if ( kh_exist(mate_names,k) ) free((char*)kh_key(mate_names, k)); + kh_destroy(names,mate_names); + } + bam_destroy1(rec); + return retval; +} + +// Common code for processing and writing a record +static inline int process_one_record(samview_settings_t *conf, bam1_t *b, + int *write_error) { + if (conf->sanitize) + if (bam_sanitize(conf->header, b, conf->sanitize) < 0) + return -1; + + int p; + if ((p = process_aln(conf->header, b, conf)) < 0) { + // error + return -1; + } else if (p == 0) { + // emit read + if (!conf->is_count) { + change_flag(b, conf); + if (adjust_tags(conf->header, b, conf) != 0) + return -1; + if (check_sam_write1(conf->out, conf->header, + b, conf->fn_out, write_error) < 0) { + return -1; + } + } + conf->count++; + } else if (conf->unmap) { + b->core.flag |= BAM_FUNMAP; + b->core.qual = 0; + b->core.isize = 0; + + // remove CIGAR + if (b->core.n_cigar) { + memmove(bam_get_cigar(b), bam_get_seq(b), + b->data + b->l_data - bam_get_seq(b)); + b->l_data -= 4*b->core.n_cigar; + b->core.n_cigar = 0; + } + + if (check_sam_write1(conf->out, conf->header, + b, conf->fn_out, write_error) < 0) { + return -1; + } + } else { + if (conf->un_out) { + if (check_sam_write1(conf->un_out, conf->header, + b, conf->fn_un_out, write_error) < 0) { + return -1; + } + } + } + return 0; +} + +static int stream_view(samview_settings_t *conf) { + bam1_t *b = bam_init1(); + int write_error = 0, r, p = 0; + if (!b) { + print_error_errno("view", "could not allocate bam record"); + return 1; + } + errno = 0; // prevent false error messages. + while ((r = sam_read1(conf->in, conf->header, b)) >= 0) { + if ((p = process_one_record(conf, b, &write_error)) < 0) break; + } + bam_destroy1(b); + if (r < -1 || p < 0) { + print_error_errno("view", "error reading file \"%s\"", conf->fn_in); + return 1; + } + return write_error; +} + +static int multi_region_view(samview_settings_t *conf, hts_itr_multi_t *iter) +{ + bam1_t *b = bam_init1(); + int write_error = 0, result; + if (!b) { + print_error_errno("view", "could not allocate bam record"); + return 1; + } + // fetch alignments + while ((result = sam_itr_multi_next(conf->in, iter, b)) >= 0) { + if (process_one_record(conf, b, &write_error) < 0) break; + } + hts_itr_multi_destroy(iter); + bam_destroy1(b); + + if (result < -1) { + print_error("view", "retrieval of region #%d failed", iter->curr_tid); + return 1; + } + return write_error; +} + +// Make mnemonic distinct values for longoption-only options +#define LONGOPT(c) ((c) + 128) + +// Check for ".sam" filenames as sam_open_mode cannot distinguish between +// foo.sam and foo.unknown, both getting mode "". +static int is_sam(const char *fn) { + if (!fn) + return 0; + size_t l = strlen(fn); + return (l >= 4 && strcasecmp(fn + l-4, ".sam") == 0); +} + +static void aux_list_free(samview_settings_t *settings) { + if (settings->keep_tag) + kh_destroy(aux_exists, settings->keep_tag); + if (settings->remove_tag) + kh_destroy(aux_exists, settings->remove_tag); +} + +int main_samview(int argc, char *argv[]) +{ + samview_settings_t settings; + int c, is_header = 0, is_header_only = 0, ret = 0, compress_level = -1, has_index_file = 0, no_pg = 0; + FILE *fp_out = NULL; + char out_mode[6] = {0}, out_un_mode[6] = {0}; + char *out_format = ""; + char *arg_list = NULL; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + htsThreadPool p = {NULL, 0}; + + memset(&settings,0,sizeof(settings)); + settings.subsam_frac = -1.0; + settings.count_rf = SAM_FLAG; // don't want 0, and this is quick + + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 'T', '@'), + {"add-flags", required_argument, NULL, LONGOPT('a')}, + {"bam", no_argument, NULL, 'b'}, + {"count", no_argument, NULL, 'c'}, + {"cram", no_argument, NULL, 'C'}, + {"customised-index", no_argument, NULL, 'X'}, + {"customized-index", no_argument, NULL, 'X'}, + {"excl-flags", required_argument, NULL, 'F'}, + {"exclude-flags", required_argument, NULL, 'F'}, + {"expr", required_argument, NULL, 'e'}, + {"expression", required_argument, NULL, 'e'}, + {"fai-reference", required_argument, NULL, 't'}, + {"fast", no_argument, NULL, '1'}, + {"fetch-pairs", no_argument, NULL, 'P'}, + {"header-only", no_argument, NULL, 'H'}, + {"help", no_argument, NULL, LONGOPT('?')}, + {"incl-flags", required_argument, NULL, LONGOPT('g')}, + {"include-flags", required_argument, NULL, LONGOPT('g')}, + {"rf", required_argument, NULL, LONGOPT('g')}, // aka incl-flags + {"keep-tag", required_argument, NULL, LONGOPT('x') }, + {"library", required_argument, NULL, 'l'}, + {"min-mapq", required_argument, NULL, 'q'}, + {"min-MQ", required_argument, NULL, 'q'}, + {"min-mq", required_argument, NULL, 'q'}, + {"min-qlen", required_argument, NULL, 'm'}, + {"no-header", no_argument, NULL, LONGOPT('H')}, + {"no-PG", no_argument, NULL, LONGOPT('P')}, + {"output", required_argument, NULL, 'o'}, + {"output-unselected", required_argument, NULL, 'U'}, + {"QNAME-file", required_argument, NULL, 'N'}, + {"qname-file", required_argument, NULL, 'N'}, + {"read-group", required_argument, NULL, 'r'}, + {"read-group-file", required_argument, NULL, 'R'}, + {"readgroup", required_argument, NULL, 'r'}, + {"readgroup-file", required_argument, NULL, 'R'}, + {"region-file", required_argument, NULL, LONGOPT('L')}, + {"regions-file", required_argument, NULL, LONGOPT('L')}, + {"remove-B", no_argument, NULL, 'B'}, + {"remove-flags", required_argument, NULL, LONGOPT('r')}, + {"remove-tag", required_argument, NULL, 'x'}, + {"require-flags", required_argument, NULL, 'f'}, + {"subsample", required_argument, NULL, LONGOPT('s')}, + {"subsample-seed", required_argument, NULL, LONGOPT('S')}, + {"tag", required_argument, NULL, 'd'}, + {"tag-file", required_argument, NULL, 'D'}, + {"target-file", required_argument, NULL, 'L'}, + {"targets-file", required_argument, NULL, 'L'}, + {"uncompressed", no_argument, NULL, 'u'}, + {"unmap", no_argument, NULL, 'p'}, + {"unoutput", required_argument, NULL, 'U'}, + {"use-index", no_argument, NULL, 'M'}, + {"with-header", no_argument, NULL, 'h'}, + {"sanitize", required_argument, NULL, 'z'}, + }; + + /* parse command-line options */ + strcpy(out_mode, "w"); + strcpy(out_un_mode, "w"); + if (argc == 1 && isatty(STDIN_FILENO)) + return usage(samtools_stdout, EXIT_SUCCESS, 0); + + // Suppress complaints about '?' being an unrecognised option. Without + // this we have to put '?' in the options list, which makes it hard to + // tell a bad long option from the use of '-?' (both return '?' and + // set optopt to '\0'). + opterr = 0; + + char *tmp; + while ((c = getopt_long(argc, argv, + "SbBcCt:h1Ho:O:q:f:F:G:ul:r:T:R:N:d:D:L:s:@:m:x:U:MXe:pPz:", + lopts, NULL)) >= 0) { + switch (c) { + case 's': + settings.subsam_seed = strtol(optarg, &tmp, 10); + if (tmp && *tmp == '.') { + settings.subsam_frac = strtod(tmp, &tmp); + if (*tmp) ret = 1; + } else { + ret = 1; + } + + if (ret == 1) { + print_error("view", "Incorrect sampling argument \"%s\"", optarg); + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + case LONGOPT('s'): + settings.subsam_frac = strtod(optarg, &tmp); + if (*tmp || settings.subsam_frac < 0.0 || settings.subsam_frac > 1.0) { + print_error("view", "Incorrect sampling argument \"%s\"", optarg); + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + case LONGOPT('S'): settings.subsam_seed = atoi(optarg); break; + case 'm': + settings.min_qlen = atoi(optarg); + settings.count_rf |= SAM_SEQ; + break; + case 'c': settings.is_count = 1; break; + case 'S': break; + case 'b': out_format = "b"; break; + case 'C': out_format = "c"; break; + case 't': settings.fn_fai = strdup(optarg); break; + case 'h': is_header = 1; break; + case 'H': is_header_only = 1; break; + case LONGOPT('H'): is_header = is_header_only = 0; break; + case 'o': settings.fn_out = strdup(optarg); break; + case 'U': settings.fn_un_out = strdup(optarg); break; + case 'X': has_index_file = 1; break; + case 'f': + settings.flag_on |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'F': + settings.flag_off |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case LONGOPT('g'): + settings.flag_anyon |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'G': + settings.flag_alloff |= bam_str2flag(optarg); + settings.count_rf |= SAM_FLAG | SAM_RNEXT; + break; + case 'q': + settings.min_mapQ = atoi(optarg); + settings.count_rf |= SAM_MAPQ; + break; + case 'u': compress_level = 0; break; + case '1': compress_level = 1; break; + case 'l': + settings.library = strdup(optarg); + settings.count_rf |= SAM_RGAUX; + break; + case 'p': settings.unmap = 1; break; + case 'P': settings.fetch_pairs = 1; settings.multi_region = 1; break; + case 'z': + if ((settings.sanitize = bam_sanitize_options(optarg)) < 0) { + ret = 1; + goto view_end; + } + break; + case LONGOPT('L'): + settings.multi_region = 1; + // fall through + case 'L': + if ((settings.bed = bed_read(optarg)) == NULL) { + print_error_errno("view", "Could not read file \"%s\"", optarg); + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR; + break; + case 'r': + if (add_read_group_single("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_RGAUX; + break; + case 'R': + if (add_read_groups_file("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_RGAUX; + break; + case 'N': + if (add_read_names_file("view", &settings, optarg) != 0) { + ret = 1; + goto view_end; + } + settings.count_rf |= SAM_QNAME; + break; + + case 'd': + if (strlen(optarg) < 2 || (strlen(optarg) > 2 && optarg[2] != ':')) { + print_error("view", "Invalid \"tag:value\" option: \"%s\"", optarg); + ret = 1; + goto view_end; + } + + if (settings.tag) { + if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) { + print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg); + ret = 1; + goto view_end; + } + } else { + if (!(settings.tag = calloc(3, 1))) { + print_error("view", "Could not allocate memory for tag: \"%s\"", optarg); + ret = 1; + goto view_end; + } + memcpy(settings.tag, optarg, 2); + } + + if (strlen(optarg) > 3 && add_tag_value_single("view", &settings, optarg+3) != 0) { + print_error("view", "Could not add tag:value \"%s\"", optarg); + ret = 1; + goto view_end; + } + // Some tag filtering affects other fields + if (memcmp(settings.tag, "NM", 2) == 0 || + memcmp(settings.tag, "MD", 2) == 0) + settings.count_rf |= SAM_AUX | SAM_SEQ; + else if (memcmp(settings.tag, "RG", 2) == 0) + settings.count_rf |= SAM_RGAUX; + else + settings.count_rf |= SAM_AUX; + break; + + case 'D': + // Allow ";" as delimiter besides ":" to support MinGW CLI POSIX + // path translation as described at: + // http://www.mingw.org/wiki/Posix_path_conversion + if (strlen(optarg) < 4 || (optarg[2] != ':' && optarg[2] != ';')) { + print_error("view", "Invalid \"tag:file\" option: \"%s\"", optarg); + ret = 1; + goto view_end; + } + + if (settings.tag) { + if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) { + print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg); + ret = 1; + goto view_end; + } + } else { + if (!(settings.tag = calloc(3, 1))) { + print_error("view", "Could not allocate memory for tag: \"%s\"", optarg); + ret = 1; + goto view_end; + } + memcpy(settings.tag, optarg, 2); + } + + if (add_tag_values_file("view", &settings, optarg+3) != 0) { + ret = 1; + goto view_end; + } + // Some tag filtering affects other fields + if (memcmp(settings.tag, "NM", 2) == 0 || + memcmp(settings.tag, "MD", 2) == 0) + settings.count_rf |= SAM_AUX | SAM_SEQ; + else if (memcmp(settings.tag, "RG", 2) == 0) + settings.count_rf |= SAM_RGAUX; + else + settings.count_rf |= SAM_AUX; + break; + + case LONGOPT('?'): + return usage(samtools_stdout, EXIT_SUCCESS, 1); + case '?': + if (optopt == '?') { // '-?' appeared on command line + return usage(samtools_stdout, EXIT_SUCCESS, 1); + } else { + if (optopt) { // Bad short option + print_error("view", "invalid option -- '%c'", optopt); + } else { // Bad long option + // Do our best. There is no good solution to finding + // out what the bad option was. + // See, e.g. https://stackoverflow.com/questions/2723888/where-does-getopt-long-store-an-unrecognized-option + if (optind > 0 && strncmp(argv[optind - 1], "--", 2) == 0) { + print_error("view", "unrecognised option '%s'", + argv[optind - 1]); + } + } + return usage(samtools_stderr, EXIT_FAILURE, 0); + } + case 'B': settings.remove_B = 1; break; + + case 'M': settings.multi_region = 1; break; + case LONGOPT('P'): no_pg = 1; break; + case 'e': + if (!(settings.filter = hts_filter_init(optarg))) { + print_error("main_samview", "Couldn't initialise filter"); + return 1; + } + settings.count_rf = INT_MAX; // no way to know what we need + break; + case LONGOPT('r'): settings.remove_flag |= bam_str2flag(optarg); break; + case LONGOPT('a'): settings.add_flag |= bam_str2flag(optarg); break; + + case 'x': + if (*optarg == '^') { + if (parse_aux_list(&settings.keep_tag, optarg+1, "main_samview")) { + aux_list_free(&settings); + return usage(samtools_stderr, EXIT_FAILURE, 0); + } + } else { + if (parse_aux_list(&settings.remove_tag, optarg, "main_samview")) { + aux_list_free(&settings); + return usage(samtools_stderr, EXIT_FAILURE, 0); + } + } + break; + + case LONGOPT('x'): + if (parse_aux_list(&settings.keep_tag, optarg, "main_samview")) { + aux_list_free(&settings); + return usage(samtools_stderr, EXIT_FAILURE, 0); + } + break; + + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) != 0) + return usage(samtools_stderr, EXIT_FAILURE, 0); + break; + } + } + if (settings.is_count && settings.fetch_pairs) + { + print_error("view","The options -P and -c cannot be combined\n"); + return 1; + } + if (settings.fn_fai == 0 && ga.reference) settings.fn_fai = fai_path(ga.reference); + if (is_header_only) is_header = 1; + // File format auto-detection first + if (settings.fn_out) sam_open_mode(out_mode+1, settings.fn_out, NULL); + if (settings.fn_un_out) sam_open_mode(out_un_mode+1, settings.fn_un_out, NULL); + + // -1 or -u without an explicit format (-b, -C) => check fn extensions + if (!*out_format && compress_level >= 0) { + if (compress_level == 0 && + (out_mode[strlen(out_mode)-1] == 'z' || + out_un_mode[strlen(out_un_mode)-1] == 'z')) + // z, fz, Fz sanity check + fprintf(samtools_stderr, "[view] Warning option -u ignored due to" + " filename suffix\n"); + + // If known extension, use it, otherwise BAM + if (!(out_mode[1] || is_sam(settings.fn_out))) + out_mode[1] = 'b'; + + if (!(out_un_mode[1] || is_sam(settings.fn_un_out))) + out_un_mode[1] = 'b'; + } else if (*out_format) { + out_mode[1] = out_un_mode[1] = *out_format; + } + + if (compress_level >= 0) { + char tmp[2]; + tmp[0] = compress_level + '0'; tmp[1] = '\0'; + strcat(out_mode, tmp); + strcat(out_un_mode, tmp); + } + if (argc == optind && isatty(STDIN_FILENO)) { + print_error("view", "No input provided or missing option argument."); + return usage(samtools_stderr, EXIT_FAILURE, 0); // potential memory leak... + } + + if (settings.unmap && settings.fn_un_out) { + print_error("view", "Options --unoutput and --unmap are mutually exclusive."); + ret = 1; + goto view_end; + } + + if (settings.subsam_seed != 0) { + // Convert likely user input 1,2,... to pseudo-random + // values with more entropy and more bits set + srand(settings.subsam_seed); + settings.subsam_seed = rand(); + } + + settings.fn_in = (optind < argc)? argv[optind] : "-"; + if ((settings.in = sam_open_format(settings.fn_in, "r", &ga.in)) == 0) { + print_error_errno("view", "failed to open \"%s\" for reading", settings.fn_in); + ret = 1; + goto view_end; + } + + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.in, settings.fn_fai) != 0) { + fprintf(samtools_stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + if ((settings.header = sam_hdr_read(settings.in)) == 0) { + fprintf(samtools_stderr, "[main_samview] fail to read the header from \"%s\".\n", settings.fn_in); + ret = 1; + goto view_end; + } + if (settings.rghash) { + sam_hdr_remove_lines(settings.header, "RG", "ID", settings.rghash); + } + if (!settings.is_count) { + if ((settings.out = sam_open_format(settings.fn_out? settings.fn_out : "-", out_mode, &ga.out)) == 0) { + print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_out? settings.fn_out : "standard output"); + ret = 1; + goto view_end; + } + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.out, settings.fn_fai) != 0) { + fprintf(samtools_stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + autoflush_if_stdout(settings.out, settings.fn_out); + + if (!no_pg) { + if (!(arg_list = stringify_argv(argc+1, argv-1))) { + print_error("view", "failed to create arg_list"); + ret = 1; + goto view_end; + } + if (sam_hdr_add_pg(settings.header, "samtools", + "VN", samtools_version(), + arg_list ? "CL": NULL, + arg_list ? arg_list : NULL, + NULL)) { + print_error("view", "failed to add PG line to the header"); + ret = 1; + goto view_end; + } + } + + if (ga.write_index || is_header || + out_mode[1] == 'b' || out_mode[1] == 'c' || + (ga.out.format != sam && ga.out.format != unknown_format)) { + if (sam_hdr_write(settings.out, settings.header) != 0) { + fprintf(samtools_stderr, "[main_samview] failed to write the SAM header\n"); + ret = 1; + goto view_end; + } + } + if (ga.write_index) { + if (!(settings.fn_out_idx = auto_index(settings.out, settings.fn_out, settings.header))) { + ret = 1; + goto view_end; + } + } + + if (settings.fn_un_out) { + if ((settings.un_out = sam_open_format(settings.fn_un_out, out_un_mode, &ga.out)) == 0) { + print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_un_out); + ret = 1; + goto view_end; + } + if (settings.fn_fai) { + if (hts_set_fai_filename(settings.un_out, settings.fn_fai) != 0) { + fprintf(samtools_stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai); + ret = 1; + goto view_end; + } + } + autoflush_if_stdout(settings.un_out, settings.fn_un_out); + if (ga.write_index || is_header || + out_un_mode[1] == 'b' || out_un_mode[1] == 'c' || + (ga.out.format != sam && ga.out.format != unknown_format)) { + if (sam_hdr_write(settings.un_out, settings.header) != 0) { + fprintf(samtools_stderr, "[main_samview] failed to write the SAM header\n"); + ret = 1; + goto view_end; + } + } + if (ga.write_index) { + if (!(settings.fn_un_out_idx = auto_index(settings.un_out, settings.fn_un_out, settings.header))) { + ret = 1; + goto view_end; + } + } + } + } + else { + if (settings.fn_out) { + fp_out = fopen(settings.fn_out, "w"); + if (fp_out == NULL) { + print_error_errno("view", "can't create \"%s\"", settings.fn_out); + ret = EXIT_FAILURE; + goto view_end; + } + } + settings.unmap = 0; // Not valid in counting mode + } + + if (ga.nthreads > 0) { + if (!(p.pool = hts_tpool_init(ga.nthreads))) { + fprintf(samtools_stderr, "Error creating thread pool\n"); + ret = 1; + goto view_end; + } + hts_set_opt(settings.in, HTS_OPT_THREAD_POOL, &p); + if (settings.out) hts_set_opt(settings.out, HTS_OPT_THREAD_POOL, &p); + } + if (is_header_only) goto view_end; // no need to print alignments + + + // Initialize BAM/CRAM index + char **regs = NULL; + int nregs = 0; + if ( has_index_file && optind <= argc - 2 ) { + regs = optind < argc-2 ? &argv[optind+2] : NULL; + nregs = argc - optind - 2; + settings.fn_idx_in = argv[optind+1]; + } else if (!has_index_file && optind < argc - 1 ) { + regs = &argv[optind+1]; + nregs = argc - optind - 1; + } else if ( has_index_file && argc-optind < 2) { + print_error("view", "Incorrect number of arguments for -X option. Aborting."); + return 1; + } + if (regs) + settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR; + + if ( settings.fn_idx_in || nregs || settings.multi_region ) + { + settings.hts_idx = settings.fn_idx_in ? sam_index_load2(settings.in, settings.fn_in, settings.fn_idx_in) : sam_index_load(settings.in, settings.fn_in); + if ( !settings.hts_idx ) + { + print_error("view", "Random alignment retrieval only works for indexed SAM.gz, BAM or CRAM files."); + return 1; + } + } + + if (settings.is_count) + // Won't fail, but also wouldn't matter if it did + hts_set_opt(settings.in, CRAM_OPT_REQUIRED_FIELDS, settings.count_rf); + + if ( settings.fetch_pairs ) + { + hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs); + ret = iter ? fetch_pairs_collect_mates(&settings, iter) : 1; + if (ret) goto view_end; + } + else if ( settings.multi_region ) + { + hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs); + ret = iter ? multi_region_view(&settings, iter) : 1; + if (ret) goto view_end; + } + else if ( !settings.hts_idx || optind+1 >= argc-has_index_file ) { + // stream through the entire file + ret = stream_view(&settings); + if (ret) goto view_end; + } else { // retrieve alignments in specified regions + int i; + for (i = (has_index_file)? optind+2 : optind+1; i < argc; ++i) { + hts_itr_t *iter = sam_itr_querys(settings.hts_idx, settings.header, argv[i]); // parse a region in the format like `chr2:100-200' + if (iter == NULL) { // region invalid or reference name not found + fprintf(samtools_stderr, "[main_samview] region \"%s\" specifies an invalid region or unknown reference. Continue anyway.\n", argv[i]); + continue; + } + // fetch alignments + ret = multi_region_view(&settings, iter); + if (ret) goto view_end; + } + } + + if ( settings.hts_idx ) hts_idx_destroy(settings.hts_idx); + + if (ga.write_index) { + if (sam_idx_save(settings.out) < 0) { + print_error_errno("view", "writing index failed"); + ret = 1; + } + if (settings.un_out && sam_idx_save(settings.un_out) < 0) { + print_error_errno("view", "writing index failed"); + ret = 1; + } + } + +view_end: + if (settings.is_count && ret == 0) { + if (fprintf(settings.fn_out? fp_out : samtools_stdout, "%" PRId64 "\n", settings.count) < 0) { + if (settings.fn_out) print_error_errno("view", "writing to \"%s\" failed", settings.fn_out); + else print_error_errno("view", "writing to standard output failed"); + ret = EXIT_FAILURE; + } + } + + // close files, free and return + if (settings.in) check_sam_close("view", settings.in, settings.fn_in, "standard input", &ret); + if (settings.out) check_sam_close("view", settings.out, settings.fn_out, "standard output", &ret); + if (settings.un_out) check_sam_close("view", settings.un_out, settings.fn_un_out, "file", &ret); + if (fp_out) fclose(fp_out); + + free(settings.fn_fai); free(settings.fn_out); free(settings.library); free(settings.fn_un_out); + sam_global_args_free(&ga); + if ( settings.header ) sam_hdr_destroy(settings.header); + if (settings.bed) bed_destroy(settings.bed); + if (settings.rghash) { + khint_t k; + for (k = 0; k < kh_end(settings.rghash); ++k) + if (kh_exist(settings.rghash, k)) free((char*)kh_key(settings.rghash, k)); + kh_destroy(str, settings.rghash); + } + if (settings.rnhash) { + khint_t k; + for (k = 0; k < kh_end(settings.rnhash); ++k) + if (kh_exist(settings.rnhash, k)) free((char*)kh_key(settings.rnhash, k)); + kh_destroy(str, settings.rnhash); + } + if (settings.tvhash) { + khint_t k; + for (k = 0; k < kh_end(settings.tvhash); ++k) + if (kh_exist(settings.tvhash, k)) free((char*)kh_key(settings.tvhash, k)); + kh_destroy(str, settings.tvhash); + } + + if (settings.remove_aux_len) { + free(settings.remove_aux); + } + if (settings.tag) { + free(settings.tag); + } + if (settings.filter) + hts_filter_free(settings.filter); + + if (p.pool) + hts_tpool_destroy(p.pool); + + if (settings.fn_out_idx) + free(settings.fn_out_idx); + if (settings.fn_un_out_idx) + free(settings.fn_un_out_idx); + free(arg_list); + + aux_list_free(&settings); + + return ret; +} + +static int usage(FILE *fp, int exit_status, int is_long_help) +{ + fprintf(fp, +"\n" +"Usage: samtools view [options] || [region ...]\n" +"\n" + +"Output options:\n" +" -b, --bam Output BAM\n" +" -C, --cram Output CRAM (requires -T)\n" +" -1, --fast Use fast BAM compression (and default to --bam)\n" +" -u, --uncompressed Uncompressed BAM output (and default to --bam)\n" +" -h, --with-header Include header in SAM output\n" +" -H, --header-only Print SAM header only (no alignments)\n" +" --no-header Print SAM alignment records only [default]\n" +" -c, --count Print only the count of matching records\n" +" -o, --output FILE Write output to FILE [standard output]\n" +" -U, --unoutput FILE, --output-unselected FILE\n" +" Output reads not selected by filters to FILE\n" +" -p, --unmap Set flag to UNMAP on reads not selected\n" +" then write to output file.\n" +" -P, --fetch-pairs Retrieve complete pairs even when outside of region\n" +"Input options:\n" +" -t, --fai-reference FILE FILE listing reference names and lengths\n" +" -M, --use-index Use index and multi-region iterator for regions\n" +" --region[s]-file FILE Use index to include only reads overlapping FILE\n" +" -X, --customized-index Expect extra index file argument after \n" +"\n" +"Filtering options (Only include in output reads that...):\n" +" -L, --target[s]-file FILE ...overlap (BED) regions in FILE\n" +" -r, --read-group STR ...are in read group STR\n" +" -R, --read-group-file FILE ...are in a read group listed in FILE\n" +" -N, --qname-file FILE ...whose read name is listed in FILE\n" +" -d, --tag STR1[:STR2] ...have a tag STR1 (with associated value STR2)\n" +" -D, --tag-file STR:FILE ...have a tag STR whose value is listed in FILE\n" +" -q, --min-MQ INT ...have mapping quality >= INT\n" +" -l, --library STR ...are in library STR\n" +" -m, --min-qlen INT ...cover >= INT query bases (as measured via CIGAR)\n" +" -e, --expr STR ...match the filter expression STR\n" +" -f, --require-flags FLAG ...have all of the FLAGs present\n" // F&x == x +" -F, --excl[ude]-flags FLAG ...have none of the FLAGs present\n" // F&x == 0 +" --rf, --incl-flags, --include-flags FLAG\n" +" ...have some of the FLAGs present\n" +" -G FLAG EXCLUDE reads with all of the FLAGs present\n" // !(F&x == x) TODO long option +" --subsample FLOAT Keep only FLOAT fraction of templates/read pairs\n" +" --subsample-seed INT Influence WHICH reads are kept in subsampling [0]\n" +" -s INT.FRAC Same as --subsample 0.FRAC --subsample-seed INT\n" +"\n" +"Processing options:\n" +" --add-flags FLAG Add FLAGs to reads\n" +" --remove-flags FLAG Remove FLAGs from reads\n" +" -x, --remove-tag STR\n" +" Comma-separated read tags to strip (repeatable) [null]\n" +" --keep-tag STR\n" +" Comma-separated read tags to preserve (repeatable) [null].\n" +" Equivalent to \"-x ^STR\"\n" +" -B, --remove-B Collapse the backward CIGAR operation\n" +" -z, --sanitize FLAGS Perform sanitity checking and fixing on records.\n" +" FLAGS is comma separated (see manual). [off]\n" +"\n" +"General options:\n" +" -?, --help Print long help, including note about region specification\n" +" -S Ignored (input format is auto-detected)\n" +" --no-PG Do not add a PG line\n"); + + sam_global_opt_help(fp, "-.O.T@.."); + fprintf(fp, "\n"); + + if (is_long_help) + fprintf(fp, +"Notes:\n" +"\n" +"1. This command now auto-detects the input format (BAM/CRAM/SAM).\n" +" Further control over the CRAM format can be specified by using the\n" +" --output-fmt-option, e.g. to specify the number of sequences per slice\n" +" and to use avoid reference based compression:\n" +"\n" +"\tsamtools view -C --output-fmt-option seqs_per_slice=5000 \\\n" +"\t --output-fmt-option no_ref -o out.cram in.bam\n" +"\n" +" Options can also be specified as a comma separated list within the\n" +" --output-fmt value too. For example this is equivalent to the above\n" +"\n" +"\tsamtools view --output-fmt cram,seqs_per_slice=5000,no_ref \\\n" +"\t -o out.cram in.bam\n" +"\n" +"2. The file supplied with `-t' is SPACE/TAB delimited with the first\n" +" two fields of each line consisting of the reference name and the\n" +" corresponding sequence length. The `.fai' file generated by \n" +" `samtools faidx' is suitable for use as this file. This may be an\n" +" empty file if reads are unaligned.\n" +"\n" +"3. SAM->BAM conversion: samtools view -bT ref.fa in.sam.gz\n" +"\n" +"4. BAM->SAM conversion: samtools view -h in.bam\n" +"\n" +"5. A region should be presented in one of the following formats:\n" +" `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n" +" specified, the input alignment file must be a sorted and indexed\n" +" alignment (BAM/CRAM) file.\n" +"\n" +"6. Option `-u' is preferred over `-b' when the output is piped to\n" +" another samtools command.\n" +"\n" +"7. Option `-M`/`--use-index` causes overlaps with `-L` BED file regions and\n" +" command-line region arguments to be computed using the multi-region iterator\n" +" and an index. This increases speed, omits duplicates, and outputs the reads\n" +" as they are ordered in the input SAM/BAM/CRAM file.\n" +"\n" +"8. Options `-L`/`--target[s]-file` and `--region[s]-file` may not be used\n" +" together. `--region[s]-file FILE` is simply equivalent to `-M -L FILE`,\n" +" so using both causes one of the specified BED files to be ignored.\n" +"\n"); + + return exit_status; +} + +static int head_usage(FILE *fp, int exit_status) +{ + fprintf(fp, +"Usage: samtools head [OPTION]... [FILE]\n" +"Options:\n" +" -h, --headers INT Display INT header lines [all]\n" +" -n, --records INT Display INT alignment record lines [none]\n" +); + sam_global_opt_help(fp, "-.--T@-."); + return exit_status; +} + +int main_head(int argc, char *argv[]) +{ + static const struct option lopts[] = { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'T', '@'), + { "headers", required_argument, NULL, 'h' }, + { "records", required_argument, NULL, 'n' }, + { NULL, 0, NULL, 0 } + }; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + int all_headers = 1; + uint64_t nheaders = 0; + uint64_t nrecords = 0; + + int c, nargs; + while ((c = getopt_long(argc, argv, "h:n:T:@:", lopts, NULL)) >= 0) + switch (c) { + case 'h': all_headers = 0; nheaders = strtoull(optarg, NULL, 0); break; + case 'n': nrecords = strtoull(optarg, NULL, 0); break; + default: + if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break; + /* else fall-through */ + case '?': + return head_usage(samtools_stderr, EXIT_FAILURE); + } + + nargs = argc - optind; + if (nargs == 0 && isatty(STDIN_FILENO)) + return head_usage(samtools_stdout, EXIT_SUCCESS); + else if (nargs > 1) + return head_usage(samtools_stderr, EXIT_FAILURE); + + samFile *fp = NULL; + sam_hdr_t *hdr = NULL; + kstring_t str = KS_INITIALIZE; + bam1_t *b = NULL; + + const char *fname = (nargs == 1)? argv[optind] : "-"; + fp = sam_open_format(fname, "r", &ga.in); + if (fp == NULL) { + if (strcmp(fname, "-") != 0) + print_error_errno("head", "failed to open \"%s\" for reading", fname); + else + print_error_errno("head", "failed to open standard input for reading"); + goto err; + } + + if (ga.nthreads > 0) hts_set_threads(fp, ga.nthreads); + + hdr = sam_hdr_read(fp); + if (hdr == NULL) { + if (strcmp(fname, "-") != 0) + print_error("head", "failed to read the header from \"%s\"", fname); + else + print_error("head", "failed to read the header"); + goto err; + } + + if (all_headers) { + fputs(sam_hdr_str(hdr), samtools_stdout); + } + else if (nheaders > 0) { + const char *text = sam_hdr_str(hdr); + const char *lim = text; + uint64_t n; + for (n = 0; n < nheaders; n++) { + lim = strchr(lim, '\n'); + if (lim) lim++; + else break; + } + if (lim) fwrite(text, lim - text, 1, samtools_stdout); + else fputs(text, samtools_stdout); + } + + if (nrecords > 0) { + b = bam_init1(); + uint64_t n; + int r; + for (n = 0; n < nrecords && (r = sam_read1(fp, hdr, b)) >= 0; n++) { + if (sam_format1(hdr, b, &str) < 0) { + print_error_errno("head", "couldn't format record"); + goto err; + } + samtools_puts(ks_str(&str)); + } + if (r < -1) { + print_error("head", "\"%s\" is truncated", fname); + goto err; + } + bam_destroy1(b); + ks_free(&str); + } + + sam_hdr_destroy(hdr); + sam_close(fp); + sam_global_args_free(&ga); + + return EXIT_SUCCESS; + +err: + if (fp) sam_close(fp); + sam_hdr_destroy(hdr); + bam_destroy1(b); + ks_free(&str); + sam_global_args_free(&ga); + return EXIT_FAILURE; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.c new file mode 100644 index 0000000000000000000000000000000000000000..4cc89ce9b5fc7556900c398d89f6a06f1ddca26b --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.c @@ -0,0 +1,134 @@ +/* sample.c -- group data by sample. + + Copyright (C) 2010, 2011 Broad Institute. + Copyright (C) 2013 Genome Research Ltd. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include +#include "sample.h" +#include "htslib/khash.h" +KHASH_MAP_INIT_STR(sm, int) + +bam_sample_t *bam_smpl_init(void) +{ + bam_sample_t *s; + s = calloc(1, sizeof(bam_sample_t)); + s->rg2smid = kh_init(sm); + s->sm2id = kh_init(sm); + return s; +} + +void bam_smpl_destroy(bam_sample_t *sm) +{ + int i; + khint_t k; + khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; + if (sm == 0) return; + for (i = 0; i < sm->n; ++i) free(sm->smpl[i]); + free(sm->smpl); + for (k = kh_begin(rg2smid); k != kh_end(rg2smid); ++k) + if (kh_exist(rg2smid, k)) free((char*)kh_key(rg2smid, k)); + kh_destroy(sm, sm->rg2smid); + kh_destroy(sm, sm->sm2id); + free(sm); +} + +static void add_pair(bam_sample_t *sm, khash_t(sm) *sm2id, const char *key, const char *val) +{ + khint_t k_rg, k_sm; + int ret; + khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; + k_rg = kh_get(sm, rg2smid, key); + if (k_rg != kh_end(rg2smid)) return; // duplicated @RG-ID + k_rg = kh_put(sm, rg2smid, strdup(key), &ret); + k_sm = kh_get(sm, sm2id, val); + if (k_sm == kh_end(sm2id)) { // absent + if (sm->n == sm->m) { + sm->m = sm->m? sm->m<<1 : 1; + sm->smpl = realloc(sm->smpl, sizeof(char*) * sm->m); + } + sm->smpl[sm->n] = strdup(val); + k_sm = kh_put(sm, sm2id, sm->smpl[sm->n], &ret); + kh_val(sm2id, k_sm) = sm->n++; + } + kh_val(rg2smid, k_rg) = kh_val(sm2id, k_sm); +} + +int bam_smpl_add(bam_sample_t *sm, const char *fn, const char *txt) +{ + const char *p = txt, *q, *r; + kstring_t buf, first_sm; + int n = 0; + khash_t(sm) *sm2id = (khash_t(sm)*)sm->sm2id; + if (txt == 0) { + add_pair(sm, sm2id, fn, fn); + return 0; + } + memset(&buf, 0, sizeof(kstring_t)); + memset(&first_sm, 0, sizeof(kstring_t)); + while ((q = strstr(p, "@RG")) != 0) { + p = q + 3; + r = q = 0; + if ((q = strstr(p, "\tID:")) != 0) q += 4; + if ((r = strstr(p, "\tSM:")) != 0) r += 4; + if (r && q) { + char *u, *v; + int oq, or; + for (u = (char*)q; *u && *u != '\t' && *u != '\n'; ++u); + for (v = (char*)r; *v && *v != '\t' && *v != '\n'; ++v); + oq = *u; or = *v; *u = *v = '\0'; + buf.l = 0; kputs(fn, &buf); kputc('/', &buf); kputs(q, &buf); + add_pair(sm, sm2id, buf.s, r); + if ( !first_sm.s ) + kputs(r,&first_sm); + *u = oq; *v = or; + } else break; + p = q > r? q : r; + ++n; + } + if (n == 0) add_pair(sm, sm2id, fn, fn); + // If there is only one RG tag present in the header and reads are not annotated, don't refuse to work but + // use the tag instead. + else if ( n==1 && first_sm.s ) + add_pair(sm,sm2id,fn,first_sm.s); + if ( first_sm.s ) + free(first_sm.s); + +// add_pair(sm, sm2id, fn, fn); + free(buf.s); + return 0; +} + +int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str) +{ + khint_t k; + khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; + if (rg) { + str->l = 0; + kputs(fn, str); kputc('/', str); kputs(rg, str); + k = kh_get(sm, rg2smid, str->s); + } else k = kh_get(sm, rg2smid, fn); + return k == kh_end(rg2smid)? -1 : kh_val(rg2smid, k); +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.h new file mode 100644 index 0000000000000000000000000000000000000000..8e8efa5b781a9f7807f262241a0f67e0bad5cde6 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/sample.h @@ -0,0 +1,41 @@ +/* sample.h -- group data by sample. + + Copyright (C) 2010 Broad Institute. + + Author: Heng Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#ifndef BAM_SAMPLE_H +#define BAM_SAMPLE_H + +#include "htslib/kstring.h" + +typedef struct { + int n, m; + char **smpl; + void *rg2smid, *sm2id; +} bam_sample_t; + +bam_sample_t *bam_smpl_init(void); +int bam_smpl_add(bam_sample_t *sm, const char *abs, const char *txt); +int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str); +void bam_smpl_destroy(bam_sample_t *sm); + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..10740a4848109786f40a0bea17c3f0c723e8cd08 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include +#include +#include + +#include "samtools.pysam.h" + +FILE * samtools_stderr = NULL; +FILE * samtools_stdout = NULL; +const char * samtools_stdout_fn = NULL; + + +FILE * samtools_set_stderr(int fd) +{ + if (samtools_stderr != NULL) + fclose(samtools_stderr); + samtools_stderr = fdopen(fd, "w"); + return samtools_stderr; +} + +void samtools_close_stderr(void) +{ + fclose(samtools_stderr); + samtools_stderr = NULL; +} + +FILE * samtools_set_stdout(int fd) +{ + if (samtools_stdout != NULL) + fclose(samtools_stdout); + samtools_stdout = fdopen(fd, "w"); + if (samtools_stdout == NULL) + { + fprintf(samtools_stderr, "could not set stdout to fd %i", fd); + } + return samtools_stdout; +} + +void samtools_set_stdout_fn(const char *fn) +{ + samtools_stdout_fn = fn; +} + +void samtools_close_stdout(void) +{ + fclose(samtools_stdout); + samtools_stdout = NULL; +} + +int samtools_puts(const char *s) +{ + if (fputs(s, samtools_stdout) == EOF) return EOF; + return putc('\n', samtools_stdout); +} + + +static jmp_buf samtools_jmpbuf; +static int samtools_status = 0; + +int samtools_dispatch(int argc, char *argv[]) +{ + /* Reset getopt()/getopt_long() processing. */ +#if defined __GLIBC__ + optind = 0; +#elif defined _OPTRESET || defined _OPTRESET_DECLARED + optreset = optind = 1; +#else + optind = 1; +#endif + + if (setjmp(samtools_jmpbuf) == 0) + return samtools_main(argc, argv); + else + return samtools_status; +} + +void samtools_exit(int status) +{ + samtools_status = status; + longjmp(samtools_jmpbuf, 1); +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.h new file mode 100644 index 0000000000000000000000000000000000000000..cb63b60aa3ca867f1cb1943cf42ef7a88d532707 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/samtools.pysam.h @@ -0,0 +1,74 @@ +#ifndef samtools_PYSAM_H +#define samtools_PYSAM_H + +#include + +#ifndef __has_attribute +#define __has_attribute(attribute) 0 +#endif +#ifndef PYSAM_NORETURN +#if __has_attribute(__noreturn__) || __GNUC__ >= 3 +#define PYSAM_NORETURN __attribute__((__noreturn__)) +#else +#define PYSAM_NORETURN +#endif +#endif + +extern FILE * samtools_stderr; + +extern FILE * samtools_stdout; + +extern const char * samtools_stdout_fn; + +/*! set pysam standard error to point to file descriptor + + Setting the stderr will close the previous stderr. + */ +FILE * samtools_set_stderr(int fd); + +/*! set pysam standard output to point to file descriptor + + Setting the stdout will close the previous stdout. + */ +FILE * samtools_set_stdout(int fd); + +/*! set pysam standard output to point to filename + + */ +void samtools_set_stdout_fn(const char * fn); + +/*! close pysam standard error and set to NULL + + */ +void samtools_close_stderr(void); + +/*! close pysam standard output and set to NULL + + */ +void samtools_close_stdout(void); + +int samtools_puts(const char *s); + +int samtools_dispatch(int argc, char *argv[]); + +void PYSAM_NORETURN samtools_exit(int status); + +extern int samtools_main(int argc, char *argv[]); + +/* Define these only in samtools/bcftools C source, not Cython code. */ +#if !(defined CYTHON_ABI || defined CYTHON_HEX_VERSION) + +/*! Several non-static function names are used in both samtools and bcftools. + Both libcsamtools.so and libcbcftools.so are loaded simultaneously, leading + to collisions and wrong functions being called. #define these names so the + actual symbol names include distinct prefixes to avoid collisions. + */ +#define main_consensus samtools_main_consensus +#define main_reheader samtools_main_reheader +#define bam_smpl_init samtools_bam_smpl_init +#define bam_smpl_destroy samtools_bam_smpl_destroy +#define read_file_list samtools_read_file_list + +#endif + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/splaysort.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/splaysort.h new file mode 100644 index 0000000000000000000000000000000000000000..af8353325410400fe04cd83345aa392c02cf8b1d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/splaysort.h @@ -0,0 +1,200 @@ +/* The MIT License + + Copyright (c) 2021 Genome Research Ltd (GRL). + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#ifndef SPLAYSORT_H +#define SPLAYSORT_H + +#define SPLAYSORT_INIT(name, type_t, __sort_lt) \ + typedef struct splaynode_##name { \ + type_t value; \ + struct splaynode_##name *left; \ + struct splaynode_##name *right; \ + struct splaynode_##name *parent; \ + } splaynode_##name; \ + \ + void rotate_left_##name(splaynode_##name *node); \ + void rotate_right_##name(splaynode_##name *node); \ + int splay_sort_##name(size_t n, type_t array[] ); \ + int splay_flatten_##name(splaynode_##name *node, type_t dest[], size_t n);\ + splaynode_##name *splay_tree_##name(splaynode_##name *node); \ + splaynode_##name *splay_insert_##name(splaynode_##name *node, \ + type_t value, \ + splaynode_##name *node_ptr); \ + \ + void rotate_left_##name(splaynode_##name *node) { \ + splaynode_##name *parent = node->parent; \ + splaynode_##name *grandparent = parent->parent; \ + parent->right = node->left; \ + if (node->left != NULL) { \ + node->left->parent = parent; \ + } \ + node->left = parent; \ + parent->parent = node; \ + node->parent = grandparent; \ + \ + if (grandparent != NULL) { \ + if (grandparent->left == parent) { \ + grandparent->left = node; \ + } else { \ + grandparent->right = node; \ + } \ + } \ + } \ + \ + void rotate_right_##name(splaynode_##name *node) { \ + splaynode_##name *parent = node->parent; \ + splaynode_##name *grandparent = parent->parent; \ + parent->left = node->right; \ + \ + if (node->right != NULL) { \ + node->right->parent = parent; \ + } \ + node->right = parent; \ + parent->parent = node; \ + node->parent = grandparent; \ + \ + if (grandparent != NULL) { \ + if (grandparent->left == parent) { \ + grandparent->left = node; \ + } else { \ + grandparent->right = node; \ + } \ + } \ + } \ + int splay_sort_##name(size_t n, type_t array[] ) { \ + if (n < 1) { \ + return 0; \ + } \ + int i; \ + splaynode_##name *node_pool = malloc(sizeof(splaynode_##name) * n); \ + if (node_pool == NULL) return -1; \ + splaynode_##name *head = node_pool; \ + head->value = array[0]; \ + head->left = NULL; head->right = NULL; head->parent = NULL; \ + for (i = 1; i < n; i++) { \ + head = splay_insert_##name(head, array[i], node_pool + i ); \ + } \ + \ + if (splay_flatten_##name(head, array, n) == -1) { \ + free(node_pool); \ + return -1; \ + } \ + free(node_pool); \ + return 0; \ + } \ + \ + int splay_flatten_##name(splaynode_##name *head, type_t *dest, size_t n) {\ + int sp = 0, i = 0; \ + splaynode_##name *current = head; \ + splaynode_##name **stack = malloc(sizeof(current)*n); \ + if (stack == NULL) return -1; \ + \ + do { \ + while (current != NULL && sp < n) { \ + stack[sp++] = current; \ + current = current->left; \ + } \ + if (sp != 0) { \ + sp--; \ + dest[i++] = stack[sp]->value; \ + current = stack[sp]->right; \ + } \ + } while (!(current == NULL && sp == 0)); \ + \ + free(stack); \ + return 0; \ + } \ + splaynode_##name *splay_insert_##name(splaynode_##name *head, \ + type_t value, \ + splaynode_##name *node_ptr) { \ + splaynode_##name *parent = NULL; \ + while (head != NULL) { \ + parent = head; \ + if (__sort_lt(value, head->value)) { \ + head = head->left; \ + } else { \ + head = head->right; \ + } \ + } \ + splaynode_##name *new_node = node_ptr; \ + new_node->value = value; \ + new_node->left = NULL; \ + new_node->right = NULL; \ + new_node->parent = parent; \ + if (parent) { \ + if (__sort_lt(value, parent->value)) { \ + parent->left = new_node; \ + } else { \ + parent->right = new_node; \ + } \ + } \ + new_node = splay_tree_##name(new_node); \ + return new_node; \ + } \ + \ + splaynode_##name *splay_tree_##name(splaynode_##name *node) { \ + splaynode_##name *parent = node->parent; \ + \ + if (node->parent == NULL) { \ + return node; \ + } \ + if (node == parent->left) { \ + if (parent->parent == NULL) { \ + /* zig */ \ + rotate_right_##name(node); \ + } else if (parent->parent->left == parent) { \ + /* left zig zig */ \ + rotate_right_##name(node); \ + rotate_right_##name(node); \ + } else { \ + /* right left zig zag */ \ + rotate_right_##name(node); \ + rotate_left_##name(node); \ + } \ + } else { \ + if (parent->parent == NULL) { \ + /* zig */ \ + rotate_left_##name(node); \ + } else if (parent->parent->right == parent) { \ + /* right zig zig */ \ + rotate_left_##name(node); \ + rotate_left_##name(node); \ + } else { \ + /* left right zig zag */ \ + rotate_left_##name(node); \ + rotate_right_##name(node); \ + } \ + } \ + \ + if (node->parent != NULL) { \ + return splay_tree_##name(node); \ + } \ + return node; \ + } \ + + +#define splaysort(name, n, array) splay_sort_##name(n, array) + +#endif diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..b3462ccb20e9ef90f21dc51924b43e6458ef2481 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats.c.pysam.c @@ -0,0 +1,2616 @@ +#include "samtools.pysam.h" + +/* stats.c -- This is the former bamcheck integrated into samtools/htslib. + + Copyright (C) 2012-2022 Genome Research Ltd. + + Author: Petr Danecek + Author: Sam Nicholls + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +/* Assumptions, approximations and other issues: + - GC-depth graph does not split reads, the starting position determines which bin is incremented. + There are small overlaps between bins (max readlen-1). However, the bins are big (20k). + - coverage distribution ignores softclips and deletions + - some stats require sorted BAMs + - GC content graph can have an untidy, step-like pattern when BAM contains multiple read lengths. + - 'bases mapped' (stats->nbases_mapped) is calculated from read lengths given by BAM (core.l_qseq) + - With the -t option, the whole reads are used. Except for the number of mapped bases (cigar) + counts, no splicing is done, no indels or soft clips are considered, even small overlap is + good enough to include the read in the stats. + - GC content of reads not calculated for "=" sequences + +*/ + +#include + +#include // for isatty() +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for crc32 +#include +#include +#include +#include +#include "samtools.h" +#include +#include +#include "stats_isize.h" +#include "sam_opts.h" +#include "bedidx.h" + +#define BWA_MIN_RDLEN 35 +#define DEFAULT_CHUNK_NO 8 +#define DEFAULT_PAIR_MAX 10000 +#define ERROR_LIMIT 200 +// From the spec +// If 0x4 is set, no assumptions can be made about RNAME, POS, CIGAR, MAPQ, bits 0x2, 0x10, 0x100 and 0x800, and the bit 0x20 of the previous read in the template. +#define IS_PAIRED(bam) ((bam)->core.flag&BAM_FPAIRED) +#define IS_PAIRED_AND_MAPPED(bam) (((bam)->core.flag&BAM_FPAIRED) && !((bam)->core.flag&BAM_FUNMAP) && !((bam)->core.flag&BAM_FMUNMAP)) +#define IS_PROPERLYPAIRED(bam) (((bam)->core.flag&(BAM_FPAIRED|BAM_FPROPER_PAIR)) == (BAM_FPAIRED|BAM_FPROPER_PAIR) && !((bam)->core.flag&BAM_FUNMAP)) +#define IS_UNMAPPED(bam) ((bam)->core.flag&BAM_FUNMAP) +#define IS_REVERSE(bam) ((bam)->core.flag&BAM_FREVERSE) +#define IS_MATE_REVERSE(bam) ((bam)->core.flag&BAM_FMREVERSE) +#define IS_READ1(bam) ((bam)->core.flag&BAM_FREAD1) +#define IS_READ2(bam) ((bam)->core.flag&BAM_FREAD2) +#define IS_DUP(bam) ((bam)->core.flag&BAM_FDUP) +#define IS_ORIGINAL(bam) (((bam)->core.flag&(BAM_FSECONDARY|BAM_FSUPPLEMENTARY)) == 0) + +#define READ_ORDER_NONE 0 +#define READ_ORDER_FIRST 1 +#define READ_ORDER_LAST 2 +#define READ_ORDER_MIDDLE 3 + +#define REG_INC 100 +#define POS_INC 1000 + +// The GC-depth graph works as follows: split the reference sequence into +// segments and calculate GC content and depth in each bin. Then sort +// these segments by their GC and plot the depth distribution by means +// of 10th, 25th, etc. depth percentiles. +typedef struct +{ + float gc; + uint32_t depth; +} +gc_depth_t; + +// For coverage distribution, a simple pileup +typedef struct +{ + hts_pos_t pos; + int size, start; + int *buffer; +} +round_buffer_t; + +typedef struct +{ + int npos, mpos, cpos; + hts_pair_pos_t *pos; +} +regions_t; + +typedef struct +{ + uint64_t a; + uint64_t c; + uint64_t g; + uint64_t t; + uint64_t n; + uint64_t other; +} +acgtno_count_t; + +typedef struct +{ + char tag_name[3]; + char qual_name[3]; + uint32_t nbases; + int32_t tag_sep; // Index of the separator (if present) + int32_t max_qual; + uint32_t offset; // Where the tag stats info is located in the allocated memory +} +barcode_info_t; + +typedef struct +{ + // Auxiliary data + int flag_require, flag_filter; + faidx_t *fai; // Reference sequence for GC-depth graph + int argc; // Command line arguments to be printed on the output + char **argv; + int gcd_bin_size; // The size of GC-depth bin + int nisize; // The maximum insert size that the allocated array can hold - 0 indicates no limit + int trim_qual; // bwa trim quality + float isize_main_bulk; // There are always some unrealistically big insert sizes, report only the main part + int cov_min,cov_max,cov_step; // Minimum, maximum coverage and size of the coverage bins + samFile* sam; + sam_hdr_t* sam_header; + + // Filters + int filter_readlen; + + // Misc + char *split_tag; // Tag on which to perform stats splitting + char *split_prefix; // Path or string prefix for filenames created when splitting + int remove_overlaps; + int cov_threshold; +} +stats_info_t; + +typedef struct +{ + // Dimensions of the quality histogram holder (quals_1st,quals_2nd), GC content holder (gc_1st,gc_2nd), + // insert size histogram holder + int nquals; // The number of quality bins + int nbases; // The maximum sequence length the allocated array can hold + int ngc; // The size of gc_1st and gc_2nd + int nindels; // The maximum indel length for indel distribution + + // Arrays for the histogram data + uint64_t *quals_1st, *quals_2nd; + uint64_t *gc_1st, *gc_2nd; + acgtno_count_t *acgtno_cycles_1st, *acgtno_cycles_2nd; + acgtno_count_t *acgtno_revcomp; + uint64_t *read_lengths, *read_lengths_1st, *read_lengths_2nd; + uint64_t *insertions, *deletions; + uint64_t *ins_cycles_1st, *ins_cycles_2nd, *del_cycles_1st, *del_cycles_2nd; + isize_t *isize; + uint64_t* mapping_qualities; + + // The extremes encountered + int max_len; // Maximum read length + int max_len_1st; // Maximum read length for forward reads + int max_len_2nd; // Maximum read length for reverse reads + int max_qual; // Maximum quality + int is_sorted; + + // Summary numbers + uint64_t total_len; + uint64_t total_len_1st; + uint64_t total_len_2nd; + uint64_t total_len_dup; + uint64_t nreads_1st; + uint64_t nreads_2nd; + uint64_t nreads_other; + uint64_t nreads_filtered; + uint64_t nreads_dup; + uint64_t nreads_unmapped; + uint64_t nreads_single_mapped; + uint64_t nreads_paired_and_mapped; + uint64_t nreads_properly_paired; + uint64_t nreads_paired_tech; + uint64_t nreads_anomalous; + uint64_t nreads_mq0; + uint64_t nbases_mapped; + uint64_t nbases_mapped_cigar; + uint64_t nbases_trimmed; // bwa trimmed bases + uint64_t nmismatches; + uint64_t nreads_QCfailed, nreads_secondary, nreads_supplementary; + struct { + uint32_t names, reads, quals; + } checksum; + + // GC-depth related data + uint32_t ngcd, igcd; // The maximum number of GC depth bins and index of the current bin + gc_depth_t *gcd; // The GC-depth bins holder + int32_t tid; // Position of the current bin + hts_pos_t gcd_pos, pos; // Position of the last read + + // Coverage distribution related data + int ncov; // The number of coverage bins + uint64_t *cov; // The coverage frequencies + round_buffer_t cov_rbuf; // Pileup round buffer + + // Mismatches by read cycle + uint8_t *rseq_buf; // A buffer for reference sequence to check the mismatches against + int mrseq_buf; // The size of the buffer + hts_pos_t rseq_pos; // The coordinate of the first base in the buffer + int64_t nrseq_buf; // The used part of the buffer + uint64_t *mpc_buf; // Mismatches per cycle + + // Target regions + int nregions; + hts_pos_t reg_from, reg_to; + regions_t *regions; + + // Auxiliary data + double sum_qual; // For calculating average quality value + void *rg_hash; // Read groups to include, the array is null-terminated + + // Split + char* split_name; + + stats_info_t* info; // Pointer to options and settings struct + hts_pair_pos_t *chunks; + uint32_t nchunks; + + uint32_t pair_count; // Number of active pairs in the pairing hash table + uint64_t target_count; // Number of bases covered by the target file + uint32_t last_pair_tid; + uint32_t last_read_flush; + + // Barcode statistics + acgtno_count_t *acgtno_barcode; + uint64_t *quals_barcode; + barcode_info_t *tags_barcode; + uint32_t ntags; + uint32_t error_number; +} +stats_t; +KHASH_MAP_INIT_STR(c2stats, stats_t*) + +typedef struct { + uint32_t first; // 1 - first read, 2 - second read + uint32_t n, m; // number of chunks, allocated chunks + hts_pair_pos_t *chunks; // chunk array of size m +} pair_t; +KHASH_MAP_INIT_STR(qn2pair, pair_t*) + +KHASH_SET_INIT_STR(rg) + + +static void HTS_NORETURN error(const char *format, ...); +int is_in_regions(bam1_t *bam_line, stats_t *stats); +void realloc_buffers(stats_t *stats, int seq_len); + +static int regions_lt(const void *r1, const void *r2) { + int64_t from_diff = ((hts_pair_pos_t *)r1)->beg - ((hts_pair_pos_t *)r2)->beg; + int64_t to_diff = ((hts_pair_pos_t *)r1)->end - ((hts_pair_pos_t *)r2)->end; + + return from_diff > 0 ? 1 : from_diff < 0 ? -1 : to_diff > 0 ? 1 : to_diff < 0 ? -1 : 0; +} + +// Coverage distribution methods +static inline int coverage_idx(int min, int max, int n, int step, int depth) +{ + if ( depth < min ) + return 0; + + if ( depth > max ) + return n-1; + + return 1 + (depth - min) / step; +} + +static inline int round_buffer_lidx2ridx(int offset, int size, hts_pos_t refpos, hts_pos_t pos) +{ + return (offset + (pos-refpos) % size) % size; +} + +void round_buffer_flush(stats_t *stats, hts_pos_t pos) +{ + int ibuf,idp; + + if ( pos==stats->cov_rbuf.pos ) + return; + + hts_pos_t new_pos = pos; + if ( pos==-1 || pos - stats->cov_rbuf.pos >= stats->cov_rbuf.size ) + { + // Flush the whole buffer, but in sequential order, + pos = stats->cov_rbuf.pos + stats->cov_rbuf.size - 1; + } + + if ( pos < stats->cov_rbuf.pos ) + error("Expected coordinates in ascending order, got %"PRIhts_pos" after %"PRIhts_pos"\n", pos, stats->cov_rbuf.pos); + + int ifrom = stats->cov_rbuf.start; + int ito = round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos-1); + if ( ifrom>ito ) + { + for (ibuf=ifrom; ibufcov_rbuf.size; ibuf++) + { + if ( !stats->cov_rbuf.buffer[ibuf] ) + continue; + idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]); + stats->cov[idp]++; + stats->cov_rbuf.buffer[ibuf] = 0; + } + ifrom = 0; + } + for (ibuf=ifrom; ibuf<=ito; ibuf++) + { + if ( !stats->cov_rbuf.buffer[ibuf] ) + continue; + idp = coverage_idx(stats->info->cov_min,stats->info->cov_max,stats->ncov,stats->info->cov_step,stats->cov_rbuf.buffer[ibuf]); + stats->cov[idp]++; + stats->cov_rbuf.buffer[ibuf] = 0; + } + stats->cov_rbuf.start = (new_pos==-1) ? 0 : round_buffer_lidx2ridx(stats->cov_rbuf.start, stats->cov_rbuf.size, stats->cov_rbuf.pos, pos); + stats->cov_rbuf.pos = new_pos; +} + +/** + * [from, to) - 0 based half-open + */ +static void round_buffer_insert_read(round_buffer_t *rbuf, hts_pos_t from, hts_pos_t to) +{ + if ( to-from > rbuf->size ) + error("The read length too big (%"PRIhts_pos"), please increase the buffer length (currently %d)\n", to-from, rbuf->size); + if ( from < rbuf->pos ) + error("The reads are not sorted (%"PRIhts_pos" comes after %"PRIhts_pos").\n", from, rbuf->pos); + + int ifrom, ito, ibuf; + ifrom = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, from); + ito = round_buffer_lidx2ridx(rbuf->start, rbuf->size, rbuf->pos, to); + if ( ifrom>ito ) + { + for (ibuf=ifrom; ibufsize; ibuf++) + rbuf->buffer[ibuf]++; + ifrom = 0; + } + for (ibuf=ifrom; ibufbuffer[ibuf]++; +} + +// Calculate the number of bases in the read trimmed by BWA +int bwa_trim_read(int trim_qual, uint8_t *quals, int len, int reverse) +{ + if ( lenmax_sum ) + { + max_sum = sum; + // This is the correct way, but bwa clips from some reason one base less + // max_l = l+1; + max_l = l; + } + } + return max_l; +} + + +void count_indels(stats_t *stats,bam1_t *bam_line) +{ + int is_fwd = IS_REVERSE(bam_line) ? 0 : 1; + uint32_t order = IS_PAIRED(bam_line) ? (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0) : READ_ORDER_FIRST; + int icig; + int icycle = 0; + int read_len = bam_line->core.l_qseq; + for (icig=0; icigcore.n_cigar; icig++) + { + int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]); + int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]); + if ( !ncig ) continue; // curiously, this can happen: 0D + + if ( cig==BAM_CINS ) + { + int idx = is_fwd ? icycle : read_len-icycle-ncig; + if ( idx<0 ) + error("FIXME: read_len=%d vs icycle=%d\n", read_len,icycle); + if ( idx >= stats->nbases || idx<0 ) error("FIXME: %d vs %d, %s:%"PRIhts_pos" %s\n", idx, stats->nbases, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line)); + if ( order == READ_ORDER_FIRST ) + stats->ins_cycles_1st[idx]++; + if ( order == READ_ORDER_LAST ) + stats->ins_cycles_2nd[idx]++; + icycle += ncig; + if ( ncig<=stats->nindels ) + stats->insertions[ncig-1]++; + continue; + } + if ( cig==BAM_CDEL ) + { + int idx = is_fwd ? icycle-1 : read_len-icycle-1; + if ( idx<0 ) continue; // discard meaningless deletions + if ( idx >= stats->nbases ) error("FIXME: %d vs %d\n", idx,stats->nbases); + if ( order == READ_ORDER_FIRST ) + stats->del_cycles_1st[idx]++; + if ( order == READ_ORDER_LAST ) + stats->del_cycles_2nd[idx]++; + if ( ncig<=stats->nindels ) + stats->deletions[ncig-1]++; + continue; + } + if ( cig!=BAM_CREF_SKIP && cig!=BAM_CHARD_CLIP && cig!=BAM_CPAD ) + icycle += ncig; + } +} + +int unclipped_length(bam1_t *bam_line) +{ + int icig, read_len = bam_line->core.l_qseq; + for (icig=0; icigcore.n_cigar; icig++) + { + int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]); + if ( cig==BAM_CHARD_CLIP ) + read_len += bam_cigar_oplen(bam_get_cigar(bam_line)[icig]); + } + return read_len; +} + +void count_mismatches_per_cycle(stats_t *stats, bam1_t *bam_line, int read_len) +{ + int is_fwd = IS_REVERSE(bam_line) ? 0 : 1; + int icig, iread=0, icycle=0; + hts_pos_t iref = bam_line->core.pos - stats->rseq_pos; + uint8_t *read = bam_get_seq(bam_line); + uint8_t *quals = bam_get_qual(bam_line); + uint64_t *mpc_buf = stats->mpc_buf; + for (icig=0; icigcore.n_cigar; icig++) + { + int cig = bam_cigar_op(bam_get_cigar(bam_line)[icig]); + int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[icig]); + if ( cig==BAM_CINS ) + { + iread += ncig; + icycle += ncig; + continue; + } + if ( cig==BAM_CDEL ) + { + iref += ncig; + continue; + } + if ( cig==BAM_CSOFT_CLIP ) + { + icycle += ncig; + // Soft-clips are present in the sequence, but the position of the read marks a start of the sequence after clipping + // iref += ncig; + iread += ncig; + continue; + } + if ( cig==BAM_CHARD_CLIP ) + { + icycle += ncig; + continue; + } + // Ignore H and N CIGARs. The letter are inserted e.g. by TopHat and often require very large + // chunk of refseq in memory. Not very frequent and not noticeable in the stats. + if ( cig==BAM_CREF_SKIP || cig==BAM_CHARD_CLIP || cig==BAM_CPAD ) continue; + if ( cig!=BAM_CMATCH && cig!=BAM_CEQUAL && cig!=BAM_CDIFF ) // not relying on precalculated diffs + error("TODO: cigar %d, %s:%"PRIhts_pos" %s\n", cig, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line)); + + if ( ncig+iref > stats->nrseq_buf ) + error("FIXME: %d+%"PRIhts_pos" > %"PRId64", %s, %s:%"PRIhts_pos"\n", ncig, iref, stats->nrseq_buf, bam_get_qname(bam_line), sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1); + + int im; + for (im=0; imrseq_buf[iref]; + + // ---------------15 + // =ACMGRSVTWYHKDBN + if ( cread==15 ) + { + int idx = is_fwd ? icycle : read_len-icycle-1; + if ( idx>stats->max_len ) + error("mpc: %d>%d\n",idx,stats->max_len); + idx = idx*stats->nquals; + if ( idx>=stats->nquals*stats->nbases ) + error("FIXME: mpc_buf overflow\n"); + mpc_buf[idx]++; + } + else if ( cref && cread && cref!=cread ) + { + uint8_t qual = quals[iread] + 1; + if ( qual>=stats->nquals ) + error("TODO: quality too high %d>=%d (%s %"PRIhts_pos" %s)\n", qual, stats->nquals, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line)); + + int idx = is_fwd ? icycle : read_len-icycle-1; + if ( idx>stats->max_len ) + error("mpc: %d>%d (%s %"PRIhts_pos" %s)\n", idx, stats->max_len, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line)); + + idx = idx*stats->nquals + qual; + if ( idx>=stats->nquals*stats->nbases ) + error("FIXME: mpc_buf overflow\n"); + mpc_buf[idx]++; + } + + iref++; + iread++; + icycle++; + } + } +} + +void read_ref_seq(stats_t *stats, int32_t tid, hts_pos_t pos, hts_pos_t end) +{ + int i; + hts_pos_t fai_ref_len; + char *fai_ref; + + if (end < pos+stats->mrseq_buf-1) + end = pos+stats->mrseq_buf-1; + else if (stats->mrseq_buf < end - pos) { + size_t sz = end - pos; + uint8_t *new_rseq = realloc(stats->rseq_buf, sz); + if (!new_rseq) + error("Couldn't expand the reference sequence buffer\n"); + stats->rseq_buf = new_rseq; + stats->mrseq_buf = sz; + } + + fai_ref = faidx_fetch_seq64(stats->info->fai, sam_hdr_tid2name(stats->info->sam_header, tid), pos, pos+stats->mrseq_buf-1, &fai_ref_len); + if ( fai_ref_len < 0 ) error("Failed to fetch the sequence \"%s\"\n", sam_hdr_tid2name(stats->info->sam_header, tid)); + + uint8_t *ptr = stats->rseq_buf; + for (i=0; imrseq_buf ) memset(ptr,0, stats->mrseq_buf - fai_ref_len); + stats->nrseq_buf = fai_ref_len; + stats->rseq_pos = pos; + stats->tid = tid; +} + +float fai_gc_content(stats_t *stats, hts_pos_t pos, int len) +{ + uint32_t gc,count,c; + hts_pos_t i = pos - stats->rseq_pos, ito = i + len; + assert( i>=0 ); + + if ( ito > stats->nrseq_buf ) ito = stats->nrseq_buf; + + // Count GC content + gc = count = 0; + for (; irseq_buf[i]; + if ( c==2 || c==4 ) + { + gc++; + count++; + } + else if ( c==1 || c==8 ) + count++; + } + return count ? (float)gc/count : 0; +} + +void realloc_rseq_buffer(stats_t *stats) +{ + int n = stats->nbases*10; + if ( stats->info->gcd_bin_size > n ) n = stats->info->gcd_bin_size; + if ( stats->mrseq_bufrseq_buf = realloc(stats->rseq_buf,sizeof(uint8_t)*n); + if (!stats->rseq_buf) { + error("Could not reallocate reference sequence buffer"); + } + stats->mrseq_buf = n; + } +} + +void realloc_gcd_buffer(stats_t *stats, int seq_len) +{ + hts_expand0(gc_depth_t,stats->igcd+1,stats->ngcd,stats->gcd); + realloc_rseq_buffer(stats); +} + +void realloc_buffers(stats_t *stats, int seq_len) +{ + int n = 2*(1 + seq_len - stats->nbases) + stats->nbases; + + stats->quals_1st = realloc(stats->quals_1st, n*stats->nquals*sizeof(uint64_t)); + if ( !stats->quals_1st ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); + memset(stats->quals_1st + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); + + stats->quals_2nd = realloc(stats->quals_2nd, n*stats->nquals*sizeof(uint64_t)); + if ( !stats->quals_2nd ) + error("Could not realloc buffers, the sequence too long: %d (2x%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); + memset(stats->quals_2nd + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); + + if ( stats->mpc_buf ) + { + stats->mpc_buf = realloc(stats->mpc_buf, n*stats->nquals*sizeof(uint64_t)); + if ( !stats->mpc_buf ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*stats->nquals*sizeof(uint64_t)); + memset(stats->mpc_buf + stats->nbases*stats->nquals, 0, (n-stats->nbases)*stats->nquals*sizeof(uint64_t)); + } + + stats->acgtno_cycles_1st = realloc(stats->acgtno_cycles_1st, n*sizeof(acgtno_count_t)); + if ( !stats->acgtno_cycles_1st ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t)); + memset(stats->acgtno_cycles_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t)); + + stats->acgtno_cycles_2nd = realloc(stats->acgtno_cycles_2nd, n*sizeof(acgtno_count_t)); + if ( !stats->acgtno_cycles_2nd ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t)); + memset(stats->acgtno_cycles_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t)); + + stats->acgtno_revcomp = realloc(stats->acgtno_revcomp, n*sizeof(acgtno_count_t)); + if ( !stats->acgtno_revcomp ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len, n*sizeof(acgtno_count_t)); + memset(stats->acgtno_revcomp + stats->nbases, 0, (n-stats->nbases)*sizeof(acgtno_count_t)); + + stats->read_lengths = realloc(stats->read_lengths, n*sizeof(uint64_t)); + if ( !stats->read_lengths ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); + memset(stats->read_lengths + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->read_lengths_1st = realloc(stats->read_lengths_1st, n*sizeof(uint64_t)); + if ( !stats->read_lengths_1st ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); + memset(stats->read_lengths_1st + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->read_lengths_2nd = realloc(stats->read_lengths_2nd, n*sizeof(uint64_t)); + if ( !stats->read_lengths_2nd ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); + memset(stats->read_lengths_2nd + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->insertions = realloc(stats->insertions, n*sizeof(uint64_t)); + if ( !stats->insertions ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); + memset(stats->insertions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->deletions = realloc(stats->deletions, n*sizeof(uint64_t)); + if ( !stats->deletions ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,n*sizeof(uint64_t)); + memset(stats->deletions + stats->nbases, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->ins_cycles_1st = realloc(stats->ins_cycles_1st, (n+1)*sizeof(uint64_t)); + if ( !stats->ins_cycles_1st ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); + memset(stats->ins_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->ins_cycles_2nd = realloc(stats->ins_cycles_2nd, (n+1)*sizeof(uint64_t)); + if ( !stats->ins_cycles_2nd ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); + memset(stats->ins_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->del_cycles_1st = realloc(stats->del_cycles_1st, (n+1)*sizeof(uint64_t)); + if ( !stats->del_cycles_1st ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); + memset(stats->del_cycles_1st + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->del_cycles_2nd = realloc(stats->del_cycles_2nd, (n+1)*sizeof(uint64_t)); + if ( !stats->del_cycles_2nd ) + error("Could not realloc buffers, the sequence too long: %d (%ld)\n", seq_len,(n+1)*sizeof(uint64_t)); + memset(stats->del_cycles_2nd + stats->nbases + 1, 0, (n-stats->nbases)*sizeof(uint64_t)); + + stats->nbases = n; + + // Realloc the coverage distribution buffer + int *rbuffer = calloc(sizeof(int),seq_len*5); + if (!rbuffer) { + error("Could not allocate coverage distribution buffer"); + } + n = stats->cov_rbuf.size-stats->cov_rbuf.start; + memcpy(rbuffer,stats->cov_rbuf.buffer+stats->cov_rbuf.start,n); + if ( stats->cov_rbuf.start>1 ) + memcpy(rbuffer+n,stats->cov_rbuf.buffer,stats->cov_rbuf.start); + stats->cov_rbuf.start = 0; + free(stats->cov_rbuf.buffer); + stats->cov_rbuf.buffer = rbuffer; + stats->cov_rbuf.size = seq_len*5; + + realloc_rseq_buffer(stats); +} + +void update_checksum(bam1_t *bam_line, stats_t *stats) +{ + uint8_t *name = (uint8_t*) bam_get_qname(bam_line); + int len = 0; + while ( name[len] ) len++; + stats->checksum.names += crc32(0L, name, len); + + int seq_len = bam_line->core.l_qseq; + if ( !seq_len ) return; + + uint8_t *seq = bam_get_seq(bam_line); + stats->checksum.reads += crc32(0L, seq, (seq_len+1)/2); + + uint8_t *qual = bam_get_qual(bam_line); + stats->checksum.quals += crc32(0L, qual, (seq_len+1)/2); +} + +// Collect statistics about the barcode tags specified by init_barcode_tags method +static void collect_barcode_stats(bam1_t* bam_line, stats_t* stats) { + uint32_t nbases, tag, i; + acgtno_count_t *acgtno; + uint64_t *quals; + int32_t *separator, *maxqual; + + for (tag = 0; tag < stats->ntags; tag++) { + const char *barcode_tag = stats->tags_barcode[tag].tag_name, *qual_tag = stats->tags_barcode[tag].qual_name; + uint8_t* bc = bam_aux_get(bam_line, barcode_tag); + if (!bc) + continue; + + char* barcode = bam_aux2Z(bc); + if (!barcode) + continue; + + uint32_t barcode_len = strlen(barcode); + if (!stats->tags_barcode[tag].nbases) { // tag seen for the first time + uint32_t offset = 0; + for (i = 0; i < stats->ntags; i++) + offset += stats->tags_barcode[i].nbases; + + stats->tags_barcode[tag].offset = offset; + stats->tags_barcode[tag].nbases = barcode_len; + stats->acgtno_barcode = realloc(stats->acgtno_barcode, (offset + barcode_len) * sizeof(acgtno_count_t)); + stats->quals_barcode = realloc(stats->quals_barcode, (offset + barcode_len) * stats->nquals * sizeof(uint64_t)); + + if (!stats->acgtno_barcode || !stats->quals_barcode) + error("Error allocating memory. Aborting!\n"); + + memset(stats->acgtno_barcode + offset, 0, barcode_len*sizeof(acgtno_count_t)); + memset(stats->quals_barcode + offset*stats->nquals, 0, barcode_len*stats->nquals*sizeof(uint64_t)); + } + + nbases = stats->tags_barcode[tag].nbases; + if (barcode_len > nbases) { + fprintf(samtools_stderr, "Barcodes with tag %s differ in length at sequence '%s'\n", barcode_tag, bam_get_qname(bam_line)); + continue; + } + + acgtno = stats->acgtno_barcode + stats->tags_barcode[tag].offset; + quals = stats->quals_barcode + stats->tags_barcode[tag].offset*stats->nquals; + maxqual = &stats->tags_barcode[tag].max_qual; + separator = &stats->tags_barcode[tag].tag_sep; + int error_flag = 0; + + for (i = 0; i < barcode_len; i++) { + switch (barcode[i]) { + case 'A': + acgtno[i].a++; + break; + case 'C': + acgtno[i].c++; + break; + case 'G': + acgtno[i].g++; + break; + case 'T': + acgtno[i].t++; + break; + case 'N': + acgtno[i].n++; + break; + default: + if (*separator >= 0) { + if (*separator != i) { + if (stats->error_number < ERROR_LIMIT) { + fprintf(samtools_stderr, "Barcode separator for tag %s is in a different position or wrong barcode content('%s') at sequence '%s'\n", barcode_tag, barcode, bam_get_qname(bam_line)); + stats->error_number++; + } + error_flag = 1; + } + } else { + *separator = i; + } + } + + /* don't process the rest of the tag bases */ + if (error_flag) + break; + } + + /* skip to the next tag */ + if (error_flag) + continue; + + uint8_t* qt = bam_aux_get(bam_line, qual_tag); + if (!qt) + continue; + + char* barqual = bam_aux2Z(qt); + if (!barqual) + continue; + + uint32_t barqual_len = strlen(barqual); + if (barqual_len == barcode_len) { + for (i = 0; i < barcode_len; i++) { + int32_t qual = (int32_t)barqual[i] - '!'; // Phred + 33 + if (qual >= 0 && qual < stats->nquals) { + quals[i * stats->nquals + qual]++; + if (qual > *maxqual) + *maxqual = qual; + } + } + } else { + if (stats->error_number++ < ERROR_LIMIT) { + fprintf(samtools_stderr, "%s length and %s length don't match for sequence '%s'\n", barcode_tag, qual_tag, bam_get_qname(bam_line)); + } + } + } +} + +// These stats should only be calculated for the original reads ignoring +// supplementary artificial reads otherwise we'll accidentally double count +void collect_orig_read_stats(bam1_t *bam_line, stats_t *stats, int* gc_count_out) +{ + int seq_len = bam_line->core.l_qseq; + stats->total_len += seq_len; // This ignores clipping so only count primary + + if ( bam_line->core.flag & BAM_FQCFAIL ) stats->nreads_QCfailed++; + if ( bam_line->core.flag & BAM_FPAIRED ) stats->nreads_paired_tech++; + + uint32_t order = IS_PAIRED(bam_line) ? (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0) : READ_ORDER_FIRST; + + // Count GC and ACGT per cycle. Note that cycle is approximate, clipping is ignored + uint8_t *seq = bam_get_seq(bam_line); + int i, read_cycle, gc_count = 0, reverse = IS_REVERSE(bam_line); + + acgtno_count_t *acgtno_cycles = (order == READ_ORDER_FIRST) ? stats->acgtno_cycles_1st : (order == READ_ORDER_LAST) ? stats->acgtno_cycles_2nd : NULL ; + if (acgtno_cycles) { + for (i=0; iacgtno_revcomp[ read_cycle ].t++ : stats->acgtno_revcomp[ read_cycle ].a++; + break; + case 2: + acgtno_cycles[ read_cycle ].c++; + reverse ? stats->acgtno_revcomp[ read_cycle ].g++ : stats->acgtno_revcomp[ read_cycle ].c++; + gc_count++; + break; + case 4: + acgtno_cycles[ read_cycle ].g++; + reverse ? stats->acgtno_revcomp[ read_cycle ].c++ : stats->acgtno_revcomp[ read_cycle ].g++; + gc_count++; + break; + case 8: + reverse ? stats->acgtno_revcomp[ read_cycle ].a++ : stats->acgtno_revcomp[ read_cycle ].t++; + acgtno_cycles[ read_cycle ].t++; + break; + case 15: + acgtno_cycles[ read_cycle ].n++; + break; + default: + /* + * count "=" sequences in "other" along + * with MRSVWYHKDB ambiguity codes + */ + acgtno_cycles[ read_cycle ].other++; + break; + } + } + } + int gc_idx_min = gc_count*(stats->ngc-1)/seq_len; + int gc_idx_max = (gc_count+1)*(stats->ngc-1)/seq_len; + if ( gc_idx_max >= stats->ngc ) gc_idx_max = stats->ngc - 1; + + // Determine which array (1st or 2nd read) will these stats go to, + // trim low quality bases from end the same way BWA does, + // fill GC histogram + uint64_t *quals = NULL; + uint8_t *bam_quals = bam_get_qual(bam_line); + + switch (order) { + case READ_ORDER_FIRST: + quals = stats->quals_1st; + stats->nreads_1st++; + stats->total_len_1st += seq_len; + for (i=gc_idx_min; igc_1st[i]++; + break; + case READ_ORDER_LAST: + quals = stats->quals_2nd; + stats->nreads_2nd++; + stats->total_len_2nd += seq_len; + for (i=gc_idx_min; igc_2nd[i]++; + break; + default: + stats->nreads_other++; + } + if ( stats->info->trim_qual>0 ) + stats->nbases_trimmed += bwa_trim_read(stats->info->trim_qual, bam_quals, seq_len, reverse); + + // Quality histogram and average quality. Clipping is neglected. + if (quals) { + for (i=0; i=stats->nquals ) + error("TODO: quality too high %d>=%d (%s %"PRIhts_pos" %s)\n", qual, stats->nquals, sam_hdr_tid2name(stats->info->sam_header, bam_line->core.tid), bam_line->core.pos+1, bam_get_qname(bam_line)); + if ( qual>stats->max_qual ) + stats->max_qual = qual; + + quals[ i*stats->nquals+qual ]++; + stats->sum_qual += qual; + } + } + + // Barcode statistics + if (order == READ_ORDER_FIRST) { + collect_barcode_stats(bam_line, stats); + } + + // Look at the flags and increment appropriate counters (mapped, paired, etc) + if ( IS_UNMAPPED(bam_line) ) + { + stats->nreads_unmapped++; + } + else + { + stats->nbases_mapped += seq_len; // This ignores clipping so only count primary + + if ( !bam_line->core.qual ) + stats->nreads_mq0++; + if ( !IS_PAIRED_AND_MAPPED(bam_line) ) + stats->nreads_single_mapped++; + else + { + stats->nreads_paired_and_mapped++; + + if (IS_PROPERLYPAIRED(bam_line)) stats->nreads_properly_paired++; + + if ( bam_line->core.tid!=bam_line->core.mtid ) + stats->nreads_anomalous++; + } + } + *gc_count_out = gc_count; +} + +static int cleanup_overlaps(khash_t(qn2pair) *read_pairs, hts_pos_t max) { + if ( !read_pairs ) + return 0; + + int count = 0; + khint_t k; + for (k = kh_begin(read_pairs); k < kh_end(read_pairs); k++) { + if ( kh_exist(read_pairs, k) ) { + char *key = (char *)kh_key(read_pairs, k); + pair_t *val = kh_val(read_pairs, k); + if ( val && val->chunks ) { + if ( val->chunks[val->n-1].end < max ) { + free(val->chunks); + free(val); + free(key); + kh_del(qn2pair, read_pairs, k); + count++; + } + } else { + free(key); + kh_del(qn2pair, read_pairs, k); + count++; + } + } + } + if ( max == INT64_MAX ) + kh_destroy(qn2pair, read_pairs); + + return count; +} + +/** + * [pmin, pmax) - 0 based half-open + */ +static void remove_overlaps(bam1_t *bam_line, khash_t(qn2pair) *read_pairs, stats_t *stats, hts_pos_t pmin, hts_pos_t pmax) { + if ( !bam_line || !read_pairs || !stats ) + return; + + uint32_t order = (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0); + if ( !(bam_line->core.flag & BAM_FPAIRED) || + (bam_line->core.flag & BAM_FMUNMAP) || + (llabs(bam_line->core.isize) >= 2*bam_line->core.l_qseq) || + (order != READ_ORDER_FIRST && order != READ_ORDER_LAST) ) { + if ( pmin >= 0 ) + round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax); + return; + } + + char *qname = bam_get_qname(bam_line); + if ( !qname ) { + fprintf(samtools_stderr, "Error retrieving qname for line starting at pos %"PRIhts_pos"\n", bam_line->core.pos); + return; + } + + khint_t k = kh_get(qn2pair, read_pairs, qname); + if ( k == kh_end(read_pairs) ) { //first chunk from this template + if ( pmin == -1 ) + return; + + int ret; + char *s = strdup(qname); + if ( !s ) { + fprintf(samtools_stderr, "Error allocating memory\n"); + return; + } + + k = kh_put(qn2pair, read_pairs, s, &ret); + if ( -1 == ret ) { + error("Error inserting read '%s' in pair hash table\n", qname); + } + + pair_t *pc = calloc(1, sizeof(pair_t)); + if ( !pc ) { + fprintf(samtools_stderr, "Error allocating memory\n"); + return; + } + + pc->m = DEFAULT_CHUNK_NO; + pc->chunks = calloc(pc->m, sizeof(hts_pair_pos_t)); + if ( !pc->chunks ) { + fprintf(samtools_stderr, "Error allocating memory\n"); + free(pc); + return; + } + + pc->chunks[0].beg = pmin; + pc->chunks[0].end = pmax; + pc->n = 1; + pc->first = order; + + kh_val(read_pairs, k) = pc; + stats->pair_count++; + } else { //template already present + pair_t *pc = kh_val(read_pairs, k); + if ( !pc ) { + fprintf(samtools_stderr, "Invalid hash table entry\n"); + return; + } + + if ( order == pc->first ) { //chunk from an existing line + if ( pmin == -1 ) + return; + + if ( pc->n == pc->m ) { + hts_pair_pos_t *tmp = realloc(pc->chunks, (pc->m<<1)*sizeof(hts_pair_pos_t)); + if ( !tmp ) { + fprintf(samtools_stderr, "Error allocating memory\n"); + return; + } + pc->chunks = tmp; + pc->m<<=1; + } + + pc->chunks[pc->n].beg = pmin; + pc->chunks[pc->n].end = pmax; + pc->n++; + } else { //the other line, check for overlapping + if ( pmin == -1 && kh_exist(read_pairs, k) ) { //job done, delete entry + char *key = (char *)kh_key(read_pairs, k); + pair_t *val = kh_val(read_pairs, k); + if ( val) { + free(val->chunks); + free(val); + } + free(key); + kh_del(qn2pair, read_pairs, k); + stats->pair_count--; + return; + } + + int i; + for (i=0; in; i++) { + if ( pmin >= pc->chunks[i].end ) + continue; + + if ( pmax <= pc->chunks[i].beg ) //no overlap + break; + + if ( pmin < pc->chunks[i].beg ) { //overlap at the beginning + round_buffer_insert_read(&(stats->cov_rbuf), pmin, pc->chunks[i].beg); + pmin = pc->chunks[i].beg; + } + + if ( pmax <= pc->chunks[i].end ) { //completely contained + stats->nbases_mapped_cigar -= (pmax - pmin); + return; + } else { //overlap at the end + stats->nbases_mapped_cigar -= (pc->chunks[i].end - pmin); + pmin = pc->chunks[i].end; + } + } + } + } + round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax); +} + +void collect_stats(bam1_t *bam_line, stats_t *stats, khash_t(qn2pair) *read_pairs) +{ + if ( !is_in_regions(bam_line,stats) ) + return; + if ( stats->rg_hash ) + { + const uint8_t *rg = bam_aux_get(bam_line, "RG"); + if ( !rg ) return; // certain read groups were requested but this record has none + khint_t k = kh_get(rg, stats->rg_hash, (const char*)(rg + 1)); + if ( k == kh_end((kh_rg_t *)stats->rg_hash) ) return; + } + if ( stats->info->flag_require && (bam_line->core.flag & stats->info->flag_require)!=stats->info->flag_require ) + { + stats->nreads_filtered++; + return; + } + if ( stats->info->flag_filter && (bam_line->core.flag & stats->info->flag_filter) ) + { + stats->nreads_filtered++; + return; + } + if ( stats->info->filter_readlen!=-1 && bam_line->core.l_qseq!=stats->info->filter_readlen ) + return; + + update_checksum(bam_line, stats); + + // Secondary reads don't count for most stats purposes + if ( bam_line->core.flag & BAM_FSECONDARY ) + { + stats->nreads_secondary++; + return; + } + + if ( bam_line->core.flag & BAM_FSUPPLEMENTARY ) + { + stats->nreads_supplementary++; + } + + // If line has no sequence cannot continue + int seq_len = bam_line->core.l_qseq; + if ( !seq_len ) return; + + if ( IS_DUP(bam_line) ) + { + stats->total_len_dup += seq_len; + stats->nreads_dup++; + } + + uint32_t order = IS_PAIRED(bam_line) ? (IS_READ1(bam_line) ? READ_ORDER_FIRST : 0) + (IS_READ2(bam_line) ? READ_ORDER_LAST : 0) : READ_ORDER_FIRST; + + int read_len = unclipped_length(bam_line); + if ( read_len >= stats->nbases ) + realloc_buffers(stats,read_len); + // Update max_len observed + if ( stats->max_lenmax_len = read_len; + if ( order == READ_ORDER_FIRST && stats->max_len_1st < read_len ) + stats->max_len_1st = read_len; + if ( order == READ_ORDER_LAST && stats->max_len_2nd < read_len ) + stats->max_len_2nd = read_len; + if ( ( bam_line->core.flag & (BAM_FUNMAP|BAM_FSECONDARY|BAM_FSUPPLEMENTARY|BAM_FQCFAIL|BAM_FDUP) ) == 0 ) + stats->mapping_qualities[bam_line->core.qual]++; + + int i; + int gc_count = 0; + + // These stats should only be calculated for the original reads ignoring supplementary artificial reads + // otherwise we'll accidentally double count + if ( IS_ORIGINAL(bam_line) ) { + stats->read_lengths[read_len]++; + if ( order == READ_ORDER_FIRST ) stats->read_lengths_1st[read_len]++; + if ( order == READ_ORDER_LAST ) stats->read_lengths_2nd[read_len]++; + collect_orig_read_stats(bam_line, stats, &gc_count); + } + + // Look at the flags and increment appropriate counters (mapped, paired, etc) + if ( IS_UNMAPPED(bam_line) ) return; + + count_indels(stats, bam_line); + + if ( IS_PAIRED_AND_MAPPED(bam_line) && IS_ORIGINAL(bam_line) ) + { + // The insert size is tricky, because for long inserts the libraries are + // prepared differently and the pairs point in other direction. BWA does + // not set the paired flag for them. Similar thing is true also for 454 + // reads. Mates mapped to different chromosomes have isize==0. + int32_t isize = bam_line->core.isize; + if ( isize<0 ) isize = -isize; + if ( stats->info->nisize > 0 && isize > stats->info->nisize ) + isize = stats->info->nisize; + if ( isize>0 || bam_line->core.tid==bam_line->core.mtid ) + { + hts_pos_t pos_fst = bam_line->core.mpos - bam_line->core.pos; + int is_fst = IS_READ1(bam_line) ? 1 : -1; + int is_fwd = IS_REVERSE(bam_line) ? -1 : 1; + int is_mfwd = IS_MATE_REVERSE(bam_line) ? -1 : 1; + + if ( is_fwd*is_mfwd>0 ) + stats->isize->inc_other(stats->isize->data, isize); + else if ( is_fst*pos_fst>=0 ) + { + if ( is_fst*is_fwd>0 ) + stats->isize->inc_inward(stats->isize->data, isize); + else + stats->isize->inc_outward(stats->isize->data, isize); + } + else if ( is_fst*pos_fst<0 ) + { + if ( is_fst*is_fwd>0 ) + stats->isize->inc_outward(stats->isize->data, isize); + else + stats->isize->inc_inward(stats->isize->data, isize); + } + } + } + + // Number of mismatches + uint8_t *nm = bam_aux_get(bam_line,"NM"); + if (nm) + stats->nmismatches += bam_aux2i(nm); + + // Number of mapped bases from cigar + if ( bam_line->core.n_cigar == 0) + error("FIXME: mapped read with no cigar?\n"); + int readlen=seq_len; + if ( stats->regions ) + { + // Count only on-target bases + hts_pos_t iref = bam_line->core.pos + 1; + for (i=0; icore.n_cigar; i++) + { + int cig = bam_cigar_op(bam_get_cigar(bam_line)[i]); + int ncig = bam_cigar_oplen(bam_get_cigar(bam_line)[i]); + if ( !ncig ) continue; // curiously, this can happen: 0D + if ( cig==BAM_CDEL ) readlen += ncig; + else if ( cig==BAM_CMATCH || cig==BAM_CEQUAL || cig==BAM_CDIFF ) + { + if ( iref < stats->reg_from ) ncig -= stats->reg_from-iref; + else if ( iref+ncig-1 > stats->reg_to ) ncig -= iref+ncig-1 - stats->reg_to; + if ( ncig<0 ) ncig = 0; + stats->nbases_mapped_cigar += ncig; + iref += bam_cigar_oplen(bam_get_cigar(bam_line)[i]); + } + else if ( cig==BAM_CINS ) + { + iref += ncig; + if ( iref>=stats->reg_from && iref<=stats->reg_to ) + stats->nbases_mapped_cigar += ncig; + } + } + } + else + { + // Count the whole read + for (i=0; icore.n_cigar; i++) + { + int cig = bam_cigar_op(bam_get_cigar(bam_line)[i]); + if ( cig==BAM_CMATCH || cig==BAM_CINS || cig==BAM_CEQUAL || cig==BAM_CDIFF ) + stats->nbases_mapped_cigar += bam_cigar_oplen(bam_get_cigar(bam_line)[i]); + if ( cig==BAM_CDEL ) + readlen += bam_cigar_oplen(bam_get_cigar(bam_line)[i]); + } + } + + if ( stats->tid==bam_line->core.tid && bam_line->core.pospos ) + stats->is_sorted = 0; + stats->pos = bam_line->core.pos; + + if ( stats->is_sorted ) + { + if ( stats->tid==-1 || stats->tid!=bam_line->core.tid ) { + round_buffer_flush(stats, -1); + } + + //cleanup the pair hash table to free memory + stats->last_read_flush++; + if ( stats->pair_count > DEFAULT_PAIR_MAX && stats->last_read_flush > DEFAULT_PAIR_MAX) { + stats->pair_count -= cleanup_overlaps(read_pairs, bam_line->core.pos); + stats->last_read_flush = 0; + } + + if ( stats->last_pair_tid != bam_line->core.tid) { + stats->pair_count -= cleanup_overlaps(read_pairs, INT64_MAX-1); + stats->last_pair_tid = bam_line->core.tid; + stats->last_read_flush = 0; + } + + // Mismatches per cycle and GC-depth graph. For simplicity, reads overlapping GCD bins + // are not splitted which results in up to seq_len-1 overlaps. The default bin size is + // 20kbp, so the effect is negligible. + if ( stats->info->fai ) + { + hts_pos_t inc_ref = 0; + int inc_gcd = 0; + // First pass or new chromosome, or read goes beyond the rseq buffer + if ( stats->rseq_pos==-1 || stats->tid != bam_line->core.tid + || stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+readlen) { + inc_ref=bam_line->core.pos+readlen; + inc_gcd=1; + } + // Read overlaps the next gcd bin + else if ( stats->gcd_pos+stats->info->gcd_bin_size < bam_line->core.pos+readlen ) + { + inc_gcd = 1; + if ( stats->rseq_pos+stats->nrseq_buf < bam_line->core.pos+stats->info->gcd_bin_size ) inc_ref = bam_line->core.pos+stats->info->gcd_bin_size; + } + if ( inc_gcd ) + { + stats->igcd++; + if ( stats->igcd >= stats->ngcd ) + realloc_gcd_buffer(stats, readlen); + if ( inc_ref ) + read_ref_seq(stats, bam_line->core.tid, + bam_line->core.pos, inc_ref); + stats->gcd_pos = bam_line->core.pos; + stats->gcd[ stats->igcd ].gc = fai_gc_content(stats, stats->gcd_pos, stats->info->gcd_bin_size); + } + + count_mismatches_per_cycle(stats,bam_line,read_len); + } + // No reference and first pass, new chromosome or sequence going beyond the end of the gcd bin + else if ( stats->gcd_pos==-1 || stats->tid != bam_line->core.tid || bam_line->core.pos - stats->gcd_pos > stats->info->gcd_bin_size ) + { + // First pass or a new chromosome + stats->tid = bam_line->core.tid; + stats->gcd_pos = bam_line->core.pos; + stats->igcd++; + if ( stats->igcd >= stats->ngcd ) + realloc_gcd_buffer(stats, readlen); + } + stats->gcd[ stats->igcd ].depth++; + // When no reference sequence is given, approximate the GC from the read (much shorter window, but otherwise OK) + if ( !stats->info->fai ) + stats->gcd[ stats->igcd ].gc += (float) gc_count / seq_len; + + // Coverage distribution graph + round_buffer_flush(stats,bam_line->core.pos); + if ( stats->regions ) { + hts_pos_t p = bam_line->core.pos, pnew, pmin = 0, pmax = 0; + uint32_t j = 0; + i = 0; + while ( j < bam_line->core.n_cigar && i < stats->nchunks ) { + int op = bam_cigar_op(bam_get_cigar(bam_line)[j]); + int oplen = bam_cigar_oplen(bam_get_cigar(bam_line)[j]); + switch(op) { + case BAM_CMATCH: + case BAM_CEQUAL: + case BAM_CDIFF: + pmin = MAX(p, stats->chunks[i].beg-1); // 0 based + pmax = MIN(p+oplen, stats->chunks[i].end); // 1 based + if ( pmax > pmin ) { + if ( stats->info->remove_overlaps ) + remove_overlaps(bam_line, read_pairs, stats, pmin, pmax); + else + round_buffer_insert_read(&(stats->cov_rbuf), pmin, pmax); + } + break; + case BAM_CDEL: + break; + } + pnew = p + (bam_cigar_type(op)&2 ? oplen : 0); // consumes reference + + if ( pnew >= stats->chunks[i].end ) { + // go to the next chunk + i++; + } else { + // go to the next CIGAR op + j++; + p = pnew; + } + } + } else { + hts_pos_t p = bam_line->core.pos; + uint32_t j; + for (j = 0; j < bam_line->core.n_cigar; j++) { + int op = bam_cigar_op(bam_get_cigar(bam_line)[j]); + int oplen = bam_cigar_oplen(bam_get_cigar(bam_line)[j]); + switch(op) { + case BAM_CMATCH: + case BAM_CEQUAL: + case BAM_CDIFF: + if ( stats->info->remove_overlaps ) + remove_overlaps(bam_line, read_pairs, stats, p, p+oplen); + else + round_buffer_insert_read(&(stats->cov_rbuf), p, p+oplen); + break; + case BAM_CDEL: + break; + } + p += bam_cigar_type(op)&2 ? oplen : 0; // consumes reference + } + } + if ( stats->info->remove_overlaps ) + remove_overlaps(bam_line, read_pairs, stats, -1LL, -1LL); //remove the line from the hash table + } +} + +// Sort by GC and depth +#define GCD_t(x) ((gc_depth_t *)x) +static int gcd_cmp(const void *a, const void *b) +{ + if ( GCD_t(a)->gc < GCD_t(b)->gc ) return -1; + if ( GCD_t(a)->gc > GCD_t(b)->gc ) return 1; + if ( GCD_t(a)->depth < GCD_t(b)->depth ) return -1; + if ( GCD_t(a)->depth > GCD_t(b)->depth ) return 1; + return 0; +} +#undef GCD_t + +float gcd_percentile(gc_depth_t *gcd, int N, int p) +{ + float n,d; + int k; + + n = (float)p*(N+1)/100; + k = n; + if ( k<=0 ) + return gcd[0].depth; + if ( k>=N ) + return gcd[N-1].depth; + + d = n - k; + return gcd[k-1].depth + d*(gcd[k].depth - gcd[k-1].depth); +} + +void output_stats(FILE *to, stats_t *stats, int sparse) +{ + // Calculate average insert size and standard deviation (from the main bulk data only) + int isize, ibulk=0, icov, imapq=0; + uint64_t nisize=0, nisize_inward=0, nisize_outward=0, nisize_other=0, cov_sum=0; + double bulk=0, avg_isize=0, sd_isize=0; + for (isize=0; isizeisize->nitems(stats->isize->data); isize++) + { + // Each pair was counted twice + stats->isize->set_inward(stats->isize->data, isize, stats->isize->inward(stats->isize->data, isize) * 0.5); + stats->isize->set_outward(stats->isize->data, isize, stats->isize->outward(stats->isize->data, isize) * 0.5); + stats->isize->set_other(stats->isize->data, isize, stats->isize->other(stats->isize->data, isize) * 0.5); + + nisize_inward += stats->isize->inward(stats->isize->data, isize); + nisize_outward += stats->isize->outward(stats->isize->data, isize); + nisize_other += stats->isize->other(stats->isize->data, isize); + nisize += stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize); + } + + for (isize=0; isizeisize->nitems(stats->isize->data); isize++) + { + uint64_t num = stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize); + if (num > 0) ibulk = isize + 1; + bulk += num; + avg_isize += isize * (stats->isize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) + stats->isize->other(stats->isize->data, isize)); + + if ( bulk/nisize > stats->info->isize_main_bulk ) + { + ibulk = isize+1; + nisize = bulk; + break; + } + } + avg_isize /= nisize ? nisize : 1; + for (isize=1; isizeisize->inward(stats->isize->data, isize) + stats->isize->outward(stats->isize->data, isize) +stats->isize->other(stats->isize->data, isize)) * (isize-avg_isize)*(isize-avg_isize) / (nisize ? nisize : 1); + sd_isize = sqrt(sd_isize); + + fprintf(to, "# This file was produced by samtools stats (%s+htslib-%s) and can be plotted using plot-bamstats\n", samtools_version(), hts_version()); + if( stats->split_name != NULL ){ + fprintf(to, "# This file contains statistics only for reads with tag: %s=%s\n", stats->info->split_tag, stats->split_name); + } + else{ + fprintf(to, "# This file contains statistics for all reads.\n"); + } + fprintf(to, "# The command line was: %s",stats->info->argv[0]); + int i; + for (i=1; iinfo->argc; i++) + fprintf(to, " %s", stats->info->argv[i]); + fprintf(to, "\n"); + fprintf(to, "# CHK, Checksum\t[2]Read Names\t[3]Sequences\t[4]Qualities\n"); + fprintf(to, "# CHK, CRC32 of reads which passed filtering followed by addition (32bit overflow)\n"); + fprintf(to, "CHK\t%08x\t%08x\t%08x\n", stats->checksum.names,stats->checksum.reads,stats->checksum.quals); + fprintf(to, "# Summary Numbers. Use `grep ^SN | cut -f 2-` to extract this part.\n"); + fprintf(to, "SN\traw total sequences:\t%ld\t# excluding supplementary and secondary reads\n", (long)(stats->nreads_filtered+stats->nreads_1st+stats->nreads_2nd+stats->nreads_other)); // not counting excluded seqs (and none of the below) + fprintf(to, "SN\tfiltered sequences:\t%ld\n", (long)stats->nreads_filtered); + fprintf(to, "SN\tsequences:\t%ld\n", (long)(stats->nreads_1st+stats->nreads_2nd+stats->nreads_other)); + fprintf(to, "SN\tis sorted:\t%d\n", stats->is_sorted ? 1 : 0); + fprintf(to, "SN\t1st fragments:\t%ld\n", (long)stats->nreads_1st); + fprintf(to, "SN\tlast fragments:\t%ld\n", (long)stats->nreads_2nd); + fprintf(to, "SN\treads mapped:\t%ld\n", (long)(stats->nreads_paired_and_mapped+stats->nreads_single_mapped)); + fprintf(to, "SN\treads mapped and paired:\t%ld\t# paired-end technology bit set + both mates mapped\n", (long)stats->nreads_paired_and_mapped); + fprintf(to, "SN\treads unmapped:\t%ld\n", (long)stats->nreads_unmapped); + fprintf(to, "SN\treads properly paired:\t%ld\t# proper-pair bit set\n", (long)stats->nreads_properly_paired); + fprintf(to, "SN\treads paired:\t%ld\t# paired-end technology bit set\n", (long)stats->nreads_paired_tech); + fprintf(to, "SN\treads duplicated:\t%ld\t# PCR or optical duplicate bit set\n", (long)stats->nreads_dup); + fprintf(to, "SN\treads MQ0:\t%ld\t# mapped and MQ=0\n", (long)stats->nreads_mq0); + fprintf(to, "SN\treads QC failed:\t%ld\n", (long)stats->nreads_QCfailed); + fprintf(to, "SN\tnon-primary alignments:\t%ld\n", (long)stats->nreads_secondary); + fprintf(to, "SN\tsupplementary alignments:\t%ld\n", (long)stats->nreads_supplementary); + fprintf(to, "SN\ttotal length:\t%ld\t# ignores clipping\n", (long)stats->total_len); + fprintf(to, "SN\ttotal first fragment length:\t%ld\t# ignores clipping\n", (long)stats->total_len_1st); + fprintf(to, "SN\ttotal last fragment length:\t%ld\t# ignores clipping\n", (long)stats->total_len_2nd); + fprintf(to, "SN\tbases mapped:\t%ld\t# ignores clipping\n", (long)stats->nbases_mapped); // the length of the whole read goes here, including soft-clips etc. + fprintf(to, "SN\tbases mapped (cigar):\t%ld\t# more accurate\n", (long)stats->nbases_mapped_cigar); // only matched and inserted bases are counted here + fprintf(to, "SN\tbases trimmed:\t%ld\n", (long)stats->nbases_trimmed); + fprintf(to, "SN\tbases duplicated:\t%ld\n", (long)stats->total_len_dup); + fprintf(to, "SN\tmismatches:\t%ld\t# from NM fields\n", (long)stats->nmismatches); + fprintf(to, "SN\terror rate:\t%e\t# mismatches / bases mapped (cigar)\n", stats->nbases_mapped_cigar ? (float)stats->nmismatches/stats->nbases_mapped_cigar : 0); + float avg_read_length = (stats->nreads_1st + + stats->nreads_2nd + + stats->nreads_other) + ? (float)stats->total_len / (stats->nreads_1st + + stats->nreads_2nd + + stats->nreads_other) + : 0; + fprintf(to, "SN\taverage length:\t%.0f\n", avg_read_length); + fprintf(to, "SN\taverage first fragment length:\t%.0f\n", stats->nreads_1st? (float)stats->total_len_1st/stats->nreads_1st:0); + fprintf(to, "SN\taverage last fragment length:\t%.0f\n", stats->nreads_2nd? (float)stats->total_len_2nd/stats->nreads_2nd:0); + fprintf(to, "SN\tmaximum length:\t%d\n", stats->max_len); + fprintf(to, "SN\tmaximum first fragment length:\t%d\n", stats->max_len_1st); + fprintf(to, "SN\tmaximum last fragment length:\t%d\n", stats->max_len_2nd); + fprintf(to, "SN\taverage quality:\t%.1f\n", stats->total_len?stats->sum_qual/stats->total_len:0); + fprintf(to, "SN\tinsert size average:\t%.1f\n", avg_isize); + fprintf(to, "SN\tinsert size standard deviation:\t%.1f\n", sd_isize); + fprintf(to, "SN\tinward oriented pairs:\t%ld\n", (long)nisize_inward); + fprintf(to, "SN\toutward oriented pairs:\t%ld\n", (long)nisize_outward); + fprintf(to, "SN\tpairs with other orientation:\t%ld\n", (long)nisize_other); + fprintf(to, "SN\tpairs on different chromosomes:\t%ld\n", (long)stats->nreads_anomalous/2); + fprintf(to, "SN\tpercentage of properly paired reads (%%):\t%.1f\n", (stats->nreads_1st+stats->nreads_2nd+stats->nreads_other)? (float)(100*stats->nreads_properly_paired)/(stats->nreads_1st+stats->nreads_2nd+stats->nreads_other):0); + if ( stats->target_count ) { + fprintf(to, "SN\tbases inside the target:\t%" PRIu64 "\n", stats->target_count); + for (icov=stats->info->cov_threshold+1; icovncov; icov++) + cov_sum += stats->cov[icov]; + fprintf(to, "SN\tpercentage of target genome with coverage > %d (%%):\t%.2f\n", stats->info->cov_threshold, (float)(100*cov_sum)/stats->target_count); + } + + int ibase,iqual; + if ( stats->max_lennbases ) stats->max_len++; + if ( stats->max_qual+1nquals ) stats->max_qual++; + fprintf(to, "# First Fragment Qualities. Use `grep ^FFQ | cut -f 2-` to extract this part.\n"); + fprintf(to, "# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n"); + for (ibase=0; ibasemax_len_1st; ibase++) + { + fprintf(to, "FFQ\t%d",ibase+1); + for (iqual=0; iqual<=stats->max_qual; iqual++) + { + fprintf(to, "\t%ld", (long)stats->quals_1st[ibase*stats->nquals+iqual]); + } + fprintf(to, "\n"); + } + fprintf(to, "# Last Fragment Qualities. Use `grep ^LFQ | cut -f 2-` to extract this part.\n"); + fprintf(to, "# Columns correspond to qualities and rows to cycles. First column is the cycle number.\n"); + for (ibase=0; ibasemax_len_2nd; ibase++) + { + fprintf(to, "LFQ\t%d",ibase+1); + for (iqual=0; iqual<=stats->max_qual; iqual++) + { + fprintf(to, "\t%ld", (long)stats->quals_2nd[ibase*stats->nquals+iqual]); + } + fprintf(to, "\n"); + } + if ( stats->mpc_buf ) + { + fprintf(to, "# Mismatches per cycle and quality. Use `grep ^MPC | cut -f 2-` to extract this part.\n"); + fprintf(to, "# Columns correspond to qualities, rows to cycles. First column is the cycle number, second\n"); + fprintf(to, "# is the number of N's and the rest is the number of mismatches\n"); + for (ibase=0; ibasemax_len; ibase++) + { + fprintf(to, "MPC\t%d",ibase+1); + for (iqual=0; iqual<=stats->max_qual; iqual++) + { + fprintf(to, "\t%ld", (long)stats->mpc_buf[ibase*stats->nquals+iqual]); + } + fprintf(to, "\n"); + } + } + fprintf(to, "# GC Content of first fragments. Use `grep ^GCF | cut -f 2-` to extract this part.\n"); + int ibase_prev = 0; + for (ibase=0; ibasengc; ibase++) + { + if ( stats->gc_1st[ibase]==stats->gc_1st[ibase_prev] ) continue; + fprintf(to, "GCF\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_1st[ibase_prev]); + ibase_prev = ibase; + } + fprintf(to, "# GC Content of last fragments. Use `grep ^GCL | cut -f 2-` to extract this part.\n"); + ibase_prev = 0; + for (ibase=0; ibasengc; ibase++) + { + if ( stats->gc_2nd[ibase]==stats->gc_2nd[ibase_prev] ) continue; + fprintf(to, "GCL\t%.2f\t%ld\n", (ibase+ibase_prev)*0.5*100./(stats->ngc-1), (long)stats->gc_2nd[ibase_prev]); + ibase_prev = ibase; + } + fprintf(to, "# ACGT content per cycle. Use `grep ^GCC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n"); + for (ibase=0; ibasemax_len; ibase++) + { + acgtno_count_t *acgtno_count_1st = &(stats->acgtno_cycles_1st[ibase]); + acgtno_count_t *acgtno_count_2nd = &(stats->acgtno_cycles_2nd[ibase]); + uint64_t acgt_sum = acgtno_count_1st->a + acgtno_count_1st->c + acgtno_count_1st->g + acgtno_count_1st->t + + acgtno_count_2nd->a + acgtno_count_2nd->c + acgtno_count_2nd->g + acgtno_count_2nd->t; + if ( ! acgt_sum ) continue; + fprintf(to, "GCC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1, + 100.*(acgtno_count_1st->a + acgtno_count_2nd->a)/acgt_sum, + 100.*(acgtno_count_1st->c + acgtno_count_2nd->c)/acgt_sum, + 100.*(acgtno_count_1st->g + acgtno_count_2nd->g)/acgt_sum, + 100.*(acgtno_count_1st->t + acgtno_count_2nd->t)/acgt_sum, + 100.*(acgtno_count_1st->n + acgtno_count_2nd->n)/acgt_sum, + 100.*(acgtno_count_1st->other + acgtno_count_2nd->other)/acgt_sum); + } + fprintf(to, "# ACGT content per cycle, read oriented. Use `grep ^GCT | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]\n"); + for (ibase=0; ibasemax_len; ibase++) + { + acgtno_count_t *acgtno_count = &(stats->acgtno_revcomp[ibase]); + uint64_t acgt_sum = acgtno_count->a + acgtno_count->c + acgtno_count->g + acgtno_count->t; + if ( ! acgt_sum ) continue; + fprintf(to, "GCT\t%d\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1, + 100.*(acgtno_count->a)/acgt_sum, + 100.*(acgtno_count->c)/acgt_sum, + 100.*(acgtno_count->g)/acgt_sum, + 100.*(acgtno_count->t)/acgt_sum); + } + + uint64_t tA=0, tC=0, tG=0, tT=0, tN=0; + fprintf(to, "# ACGT content per cycle for first fragments. Use `grep ^FBC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n"); + for (ibase=0; ibasemax_len; ibase++) + { + acgtno_count_t *acgtno_count_1st = &(stats->acgtno_cycles_1st[ibase]); + uint64_t acgt_sum_1st = acgtno_count_1st->a + acgtno_count_1st->c + acgtno_count_1st->g + acgtno_count_1st->t; + tA += acgtno_count_1st->a; + tC += acgtno_count_1st->c; + tG += acgtno_count_1st->g; + tT += acgtno_count_1st->t; + tN += acgtno_count_1st->n; + + if ( acgt_sum_1st ) + fprintf(to, "FBC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1, + 100.*acgtno_count_1st->a/acgt_sum_1st, + 100.*acgtno_count_1st->c/acgt_sum_1st, + 100.*acgtno_count_1st->g/acgt_sum_1st, + 100.*acgtno_count_1st->t/acgt_sum_1st, + 100.*acgtno_count_1st->n/acgt_sum_1st, + 100.*acgtno_count_1st->other/acgt_sum_1st); + + } + fprintf(to, "# ACGT raw counters for first fragments. Use `grep ^FTC | cut -f 2-` to extract this part. The columns are: A,C,G,T,N base counters\n"); + fprintf(to, "FTC\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n", tA, tC, tG, tT, tN); + tA=0, tC=0, tG=0, tT=0, tN=0; + fprintf(to, "# ACGT content per cycle for last fragments. Use `grep ^LBC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N and O counts as a percentage of all A/C/G/T bases [%%]\n"); + for (ibase=0; ibasemax_len; ibase++) + { + acgtno_count_t *acgtno_count_2nd = &(stats->acgtno_cycles_2nd[ibase]); + uint64_t acgt_sum_2nd = acgtno_count_2nd->a + acgtno_count_2nd->c + acgtno_count_2nd->g + acgtno_count_2nd->t; + tA += acgtno_count_2nd->a; + tC += acgtno_count_2nd->c; + tG += acgtno_count_2nd->g; + tT += acgtno_count_2nd->t; + tN += acgtno_count_2nd->n; + + if ( acgt_sum_2nd ) + fprintf(to, "LBC\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", ibase+1, + 100.*acgtno_count_2nd->a/acgt_sum_2nd, + 100.*acgtno_count_2nd->c/acgt_sum_2nd, + 100.*acgtno_count_2nd->g/acgt_sum_2nd, + 100.*acgtno_count_2nd->t/acgt_sum_2nd, + 100.*acgtno_count_2nd->n/acgt_sum_2nd, + 100.*acgtno_count_2nd->other/acgt_sum_2nd); + + } + fprintf(to, "# ACGT raw counters for last fragments. Use `grep ^LTC | cut -f 2-` to extract this part. The columns are: A,C,G,T,N base counters\n"); + fprintf(to, "LTC\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n", tA, tC, tG, tT, tN); + + int tag; + for (tag=0; tagntags; tag++) { + if (stats->tags_barcode[tag].nbases) { + fprintf(to, "# ACGT content per cycle for barcodes. Use `grep ^%sC | cut -f 2-` to extract this part. The columns are: cycle; A,C,G,T base counts as a percentage of all A/C/G/T bases [%%]; and N counts as a percentage of all A/C/G/T bases [%%]\n", + stats->tags_barcode[tag].tag_name); + for (ibase=0; ibasetags_barcode[tag].nbases; ibase++) + { + if (ibase == stats->tags_barcode[tag].tag_sep) + continue; + + acgtno_count_t *acgtno_count = stats->acgtno_barcode + stats->tags_barcode[tag].offset + ibase; + uint64_t acgt_sum = acgtno_count->a + acgtno_count->c + acgtno_count->g + acgtno_count->t; + + if ( acgt_sum ) + fprintf(to, "%sC%d\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", stats->tags_barcode[tag].tag_name, + stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? 1 : 2, + stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? ibase+1 : ibase-stats->tags_barcode[tag].tag_sep, + 100.*acgtno_count->a/acgt_sum, + 100.*acgtno_count->c/acgt_sum, + 100.*acgtno_count->g/acgt_sum, + 100.*acgtno_count->t/acgt_sum, + 100.*acgtno_count->n/acgt_sum); + } + + fprintf(to, "# Barcode Qualities. Use `grep ^%sQ | cut -f 2-` to extract this part.\n", stats->tags_barcode[tag].qual_name); + fprintf(to, "# Columns correspond to qualities and rows to barcode cycles. First column is the cycle number.\n"); + for (ibase=0; ibasetags_barcode[tag].nbases; ibase++) + { + if (ibase == stats->tags_barcode[tag].tag_sep) + continue; + + fprintf(to, "%sQ%d\t%d", stats->tags_barcode[tag].qual_name, + stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? 1 : 2, + stats->tags_barcode[tag].tag_sep < 0 || ibase < stats->tags_barcode[tag].tag_sep ? ibase+1 : ibase-stats->tags_barcode[tag].tag_sep); + for (iqual=0; iqual<=stats->tags_barcode[tag].max_qual; iqual++) + { + fprintf(to, "\t%ld", (long)stats->quals_barcode[(stats->tags_barcode[tag].offset + ibase)*stats->nquals+iqual]); + } + fprintf(to, "\n"); + } + } + } + + fprintf(to, "# Insert sizes. Use `grep ^IS | cut -f 2-` to extract this part. The columns are: insert size, pairs total, inward oriented pairs, outward oriented pairs, other pairs\n"); + for (isize=0; isizeisize->inward(stats->isize->data, isize)); + long out = (long)(stats->isize->outward(stats->isize->data, isize)); + long other = (long)(stats->isize->other(stats->isize->data, isize)); + if (!sparse || in + out + other > 0) { + fprintf(to, "IS\t%d\t%ld\t%ld\t%ld\t%ld\n", isize, in+out+other, + in , out, other); + } + } + + fprintf(to, "# Read lengths. Use `grep ^RL | cut -f 2-` to extract this part. The columns are: read length, count\n"); + int ilen; + for (ilen=0; ilenmax_len; ilen++) + { + if ( stats->read_lengths[ilen+1]>0 ) + fprintf(to, "RL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths[ilen+1]); + } + + fprintf(to, "# Read lengths - first fragments. Use `grep ^FRL | cut -f 2-` to extract this part. The columns are: read length, count\n"); + for (ilen=0; ilenmax_len_1st; ilen++) + { + if ( stats->read_lengths_1st[ilen+1]>0 ) + fprintf(to, "FRL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths_1st[ilen+1]); + } + + fprintf(to, "# Read lengths - last fragments. Use `grep ^LRL | cut -f 2-` to extract this part. The columns are: read length, count\n"); + for (ilen=0; ilenmax_len_2nd; ilen++) + { + if ( stats->read_lengths_2nd[ilen+1]>0 ) + fprintf(to, "LRL\t%d\t%ld\n", ilen+1, (long)stats->read_lengths_2nd[ilen+1]); + } + + fprintf(to, "# Mapping qualities for reads !(UNMAP|SECOND|SUPPL|QCFAIL|DUP). Use `grep ^MAPQ | cut -f 2-` to extract this part. The columns are: mapq, count\n"); + for (imapq=0; imapq < 256; imapq++) + { + if ( stats->mapping_qualities[imapq]>0 ) + fprintf(to, "MAPQ\t%d\t%ld\n", imapq, (long)stats->mapping_qualities[imapq]); + } + + fprintf(to, "# Indel distribution. Use `grep ^ID | cut -f 2-` to extract this part. The columns are: length, number of insertions, number of deletions\n"); + + for (ilen=0; ilennindels; ilen++) + { + if ( stats->insertions[ilen]>0 || stats->deletions[ilen]>0 ) + fprintf(to, "ID\t%d\t%ld\t%ld\n", ilen+1, (long)stats->insertions[ilen], (long)stats->deletions[ilen]); + } + + fprintf(to, "# Indels per cycle. Use `grep ^IC | cut -f 2-` to extract this part. The columns are: cycle, number of insertions (fwd), .. (rev) , number of deletions (fwd), .. (rev)\n"); + for (ilen=0; ilen<=stats->nbases; ilen++) + { + // For deletions we print the index of the cycle before the deleted base (1-based) and for insertions + // the index of the cycle of the first inserted base (also 1-based) + if ( stats->ins_cycles_1st[ilen]>0 || stats->ins_cycles_2nd[ilen]>0 || stats->del_cycles_1st[ilen]>0 || stats->del_cycles_2nd[ilen]>0 ) + fprintf(to, "IC\t%d\t%ld\t%ld\t%ld\t%ld\n", ilen+1, (long)stats->ins_cycles_1st[ilen], (long)stats->ins_cycles_2nd[ilen], (long)stats->del_cycles_1st[ilen], (long)stats->del_cycles_2nd[ilen]); + } + + fprintf(to, "# Coverage distribution. Use `grep ^COV | cut -f 2-` to extract this part.\n"); + if ( stats->cov[0] ) + fprintf(to, "COV\t[<%d]\t%d\t%ld\n",stats->info->cov_min,stats->info->cov_min-1, (long)stats->cov[0]); + for (icov=1; icovncov-1; icov++) + if ( stats->cov[icov] ) + fprintf(to, "COV\t[%d-%d]\t%d\t%ld\n",stats->info->cov_min + (icov-1)*stats->info->cov_step, stats->info->cov_min + icov*stats->info->cov_step-1,stats->info->cov_min + icov*stats->info->cov_step-1, (long)stats->cov[icov]); + if ( stats->cov[stats->ncov-1] ) + fprintf(to, "COV\t[%d<]\t%d\t%ld\n",stats->info->cov_min + (stats->ncov-2)*stats->info->cov_step-1,stats->info->cov_min + (stats->ncov-2)*stats->info->cov_step-1, (long)stats->cov[stats->ncov-1]); + + // Calculate average GC content, then sort by GC and depth + fprintf(to, "# GC-depth. Use `grep ^GCD | cut -f 2-` to extract this part. The columns are: GC%%, unique sequence percentiles, 10th, 25th, 50th, 75th and 90th depth percentile\n"); + uint32_t igcd; + for (igcd=0; igcdigcd; igcd++) + { + if ( stats->info->fai ) + stats->gcd[igcd].gc = rint(100. * stats->gcd[igcd].gc); + else + if ( stats->gcd[igcd].depth ) + stats->gcd[igcd].gc = rint(100. * stats->gcd[igcd].gc / stats->gcd[igcd].depth); + } + if ( stats->ngcd ) + qsort(stats->gcd, stats->igcd+1, sizeof(gc_depth_t), gcd_cmp); + igcd = 0; + while ( igcd < stats->igcd ) + { + // Calculate percentiles (10,25,50,75,90th) for the current GC content and print + uint32_t nbins=0, itmp=igcd; + float gc = stats->gcd[igcd].gc; + while ( itmpigcd && fabs(stats->gcd[itmp].gc-gc)<0.1 ) + { + nbins++; + itmp++; + } + fprintf(to, "GCD\t%.1f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", gc, (igcd+nbins+1)*100./(stats->igcd+1), + gcd_percentile(&(stats->gcd[igcd]),nbins,10) *avg_read_length/stats->info->gcd_bin_size, + gcd_percentile(&(stats->gcd[igcd]),nbins,25) *avg_read_length/stats->info->gcd_bin_size, + gcd_percentile(&(stats->gcd[igcd]),nbins,50) *avg_read_length/stats->info->gcd_bin_size, + gcd_percentile(&(stats->gcd[igcd]),nbins,75) *avg_read_length/stats->info->gcd_bin_size, + gcd_percentile(&(stats->gcd[igcd]),nbins,90) *avg_read_length/stats->info->gcd_bin_size + ); + igcd += nbins; + } +} + +static void init_regions(stats_t *stats, const char *file, stats_info_t* info) +{ + FILE *fp = fopen(file,"r"); + if ( !fp ) error("%s: %s\n",file,strerror(errno)); + + kstring_t line = { 0, 0, NULL }; + int warned = 0, r, p, new_p; + int prev_tid=-1; + hts_pos_t prev_pos=-1LL; + while (line.l = 0, kgetline(&line, (kgets_func *)fgets, fp) >= 0) + { + if ( line.s[0] == '#' ) continue; + + int i = 0; + while ( i=line.l ) error("Could not parse the file: %s [%s]\n", file, line.s); + line.s[i] = '\0'; + + int tid = bam_name2id(stats->info->sam_header, line.s); + if ( tid < 0 ) + { + if ( !warned ) + fprintf(samtools_stderr,"Warning: Some sequences not present in the BAM, e.g. \"%s\". This message is printed only once.\n", line.s); + warned = 1; + continue; + } + + if ( tid >= stats->nregions ) + { + if(!(stats->regions = realloc(stats->regions,sizeof(regions_t)*(tid+REG_INC)))) + error("Could not allocate memory for region.\n"); + + int j; + for (j=stats->nregions; jregions[j].npos = stats->regions[j].mpos = stats->regions[j].cpos = 0; + stats->regions[j].pos = NULL; + } + stats->nregions = tid+REG_INC; + } + int npos = stats->regions[tid].npos; + if ( npos >= stats->regions[tid].mpos ) + { + stats->regions[tid].mpos = npos+POS_INC; + if (!(stats->regions[tid].pos = realloc(stats->regions[tid].pos, sizeof(hts_pair_pos_t)*stats->regions[tid].mpos))) + error("Could not allocate memory for interval.\n"); + } + + if ( (sscanf(&line.s[i+1],"%"SCNd64" %"SCNd64, &stats->regions[tid].pos[npos].beg, &stats->regions[tid].pos[npos].end))!=2 ) error("Could not parse the region [%s]\n", &line.s[i+1]); + if ( prev_tid==-1 || prev_tid!=tid ) + { + prev_tid = tid; + prev_pos = stats->regions[tid].pos[npos].beg; + } + if ( prev_pos>stats->regions[tid].pos[npos].beg ) + error("The positions are not in chromosomal order (%s:%"PRIhts_pos" comes after %"PRIhts_pos")\n", line.s, stats->regions[tid].pos[npos].beg, prev_pos); + stats->regions[tid].npos++; + if ( stats->regions[tid].npos > stats->nchunks ) + stats->nchunks = stats->regions[tid].npos; + } + free(line.s); + if ( !stats->regions ) error("Unable to map the -t sequences to the BAM sequences.\n"); + fclose(fp); + + // sort region intervals and remove duplicates + for (r = 0; r < stats->nregions; r++) { + regions_t *reg = &stats->regions[r]; + if ( reg->npos > 1 ) { + qsort(reg->pos, reg->npos, sizeof(hts_pair_pos_t), regions_lt); + for (new_p = 0, p = 1; p < reg->npos; p++) { + if ( reg->pos[new_p].end < reg->pos[p].beg ) + reg->pos[++new_p] = reg->pos[p]; + else if ( reg->pos[new_p].end < reg->pos[p].end ) + reg->pos[new_p].end = reg->pos[p].end; + } + reg->npos = ++new_p; + } + for (p = 0; p < reg->npos; p++) { + if (reg->pos[p].end < HTS_POS_MAX) { + stats->target_count += (reg->pos[p].end - reg->pos[p].beg + 1); + } else { + uint64_t hdr_end = sam_hdr_tid2len(info->sam_header, r); + if (hdr_end) + stats->target_count += (hdr_end - reg->pos[p].beg + 1); + } + } + } + + if (!(stats->chunks = calloc(stats->nchunks, sizeof(hts_pair_pos_t)))) + error("Could not allocate memory for chunk.\n"); +} + +void destroy_regions(stats_t *stats) +{ + int i; + for (i=0; inregions; i++) + { + if ( !stats->regions[i].mpos ) continue; + free(stats->regions[i].pos); + } + if ( stats->regions ) free(stats->regions); + if ( stats->chunks ) free(stats->chunks); +} + +void reset_regions(stats_t *stats) +{ + int i; + for (i=0; inregions; i++) + stats->regions[i].cpos = 0; +} + +int is_in_regions(bam1_t *bam_line, stats_t *stats) +{ + if ( !stats->regions ) return 1; + + if ( bam_line->core.tid >= stats->nregions || bam_line->core.tid<0 ) return 0; + if ( !stats->is_sorted ) error("The BAM must be sorted in order for -t to work.\n"); + + regions_t *reg = &stats->regions[bam_line->core.tid]; + if ( reg->cpos==reg->npos ) return 0; // done for this chr + + // Find a matching interval or skip this read. No splicing of reads is done, no indels or soft clips considered, + // even small overlap is enough to include the read in the stats. + int i = reg->cpos; + while ( inpos && reg->pos[i].end<=bam_line->core.pos ) i++; + if ( i>=reg->npos ) { reg->cpos = reg->npos; return 0; } + int64_t endpos = bam_endpos(bam_line); + if ( endpos < reg->pos[i].beg ) return 0; + + //found a read overlapping a region + reg->cpos = i; + stats->reg_from = reg->pos[i].beg; + stats->reg_to = reg->pos[i].end; + + //now find all the overlapping chunks + stats->nchunks = 0; + while (i < reg->npos) { + if (bam_line->core.pos < reg->pos[i].end && endpos >= reg->pos[i].beg) { + stats->chunks[stats->nchunks].beg = MAX(bam_line->core.pos+1, reg->pos[i].beg); + stats->chunks[stats->nchunks].end = MIN(endpos, reg->pos[i].end); + stats->nchunks++; + } + i++; + } + + return 1; +} + +int replicate_regions(stats_t *stats, hts_itr_multi_t *iter, stats_info_t *info) { + if ( !stats || !iter) + return 1; + + int i, j, tid; + stats->nregions = iter->n_reg; + stats->regions = calloc(stats->nregions, sizeof(regions_t)); + stats->chunks = calloc(stats->nchunks, sizeof(hts_pair_pos_t)); + if ( !stats->regions || !stats->chunks ) + return 1; + + for (i = 0; i < iter->n_reg; i++) { + tid = iter->reg_list[i].tid; + if ( tid < 0 ) + continue; + + if ( tid >= stats->nregions ) { + regions_t *tmp = realloc(stats->regions, (tid+10) * sizeof(regions_t)); + if ( !tmp ) + return 1; + stats->regions = tmp; + memset(stats->regions + stats->nregions, 0, + (tid+10-stats->nregions) * sizeof(regions_t)); + stats->nregions = tid+10; + } + + stats->regions[tid].mpos = stats->regions[tid].npos = iter->reg_list[i].count; + stats->regions[tid].pos = calloc(stats->regions[tid].mpos, sizeof(hts_pair_pos_t)); + if ( !stats->regions[tid].pos ) + return 1; + + for (j = 0; j < stats->regions[tid].npos; j++) { + stats->regions[tid].pos[j].beg = iter->reg_list[i].intervals[j].beg+1; + stats->regions[tid].pos[j].end = iter->reg_list[i].intervals[j].end; + if (stats->regions[tid].pos[j].end < HTS_POS_MAX) { + stats->target_count += (stats->regions[tid].pos[j].end - stats->regions[tid].pos[j].beg + 1); + } else { + uint64_t hdr_end = sam_hdr_tid2len(info->sam_header, tid); + if (hdr_end) + stats->target_count += (hdr_end - stats->regions[tid].pos[j].beg + 1); + } + } + } + + return 0; +} + +static void init_group_id(stats_t *stats, stats_info_t *info, const char *id) +{ + stats->rg_hash = kh_init(rg); + if (!stats->rg_hash) error("Could not initialise RG set\n"); + sam_hdr_t *hdr = info->sam_header; + const char *key; + kstring_t sm = KS_INITIALIZE; + int i, ret, nrg = sam_hdr_count_lines(hdr, "RG"); + if (nrg < 0) error("Could not parse header\n"); + + for (i=0; irg_hash, key, &ret); + if (ret == -1) { ks_free(&sm); error("Could not add key \"%s\" to RG set\n", key); } + } else { /* Check for SM name, as per manual */ + if (!sam_hdr_find_tag_pos(hdr, "RG", i, "SM", &sm)) { + if (!strcmp(ks_c_str(&sm), id)) { + kh_put(rg, stats->rg_hash, key, &ret); + if (ret == -1) { ks_free(&sm); error("Could not add key \"%s\" to RG set\n", key); } + } + } + } + } + + ks_free(&sm); +} + + +static void HTS_NORETURN error(const char *format, ...) +{ + if ( !format ) + { + fprintf(samtools_stdout, "About: The program collects statistics from BAM files. The output can be visualized using plot-bamstats.\n"); + fprintf(samtools_stdout, "Usage: samtools stats [OPTIONS] file.bam\n"); + fprintf(samtools_stdout, " samtools stats [OPTIONS] file.bam chr:from-to\n"); + fprintf(samtools_stdout, "Options:\n"); + fprintf(samtools_stdout, " -c, --coverage ,, Coverage distribution min,max,step [1,1000,1]\n"); + fprintf(samtools_stdout, " -d, --remove-dups Exclude from statistics reads marked as duplicates\n"); + fprintf(samtools_stdout, " -X, --customized-index-file Use a customized index file\n"); + fprintf(samtools_stdout, " -f, --required-flag Required flag, 0 for unset. See also `samtools flags` [0]\n"); + fprintf(samtools_stdout, " -F, --filtering-flag Filtering flag, 0 for unset. See also `samtools flags` [0]\n"); + fprintf(samtools_stdout, " --GC-depth the size of GC-depth bins (decreasing bin size increases memory requirement) [2e4]\n"); + fprintf(samtools_stdout, " -h, --help This help message\n"); + fprintf(samtools_stdout, " -i, --insert-size Maximum insert size [8000]\n"); + fprintf(samtools_stdout, " -I, --id Include only listed read group or sample name\n"); + fprintf(samtools_stdout, " -l, --read-length Include in the statistics only reads with the given read length [-1]\n"); + fprintf(samtools_stdout, " -m, --most-inserts Report only the main part of inserts [0.99]\n"); + fprintf(samtools_stdout, " -P, --split-prefix Path or string prefix for filepaths output by -S (default is input filename)\n"); + fprintf(samtools_stdout, " -q, --trim-quality The BWA trimming parameter [0]\n"); + fprintf(samtools_stdout, " -r, --ref-seq Reference sequence (required for GC-depth and mismatches-per-cycle calculation).\n"); + fprintf(samtools_stdout, " -s, --sam Ignored (input format is auto-detected).\n"); + fprintf(samtools_stdout, " -S, --split Also write statistics to separate files split by tagged field.\n"); + fprintf(samtools_stdout, " -t, --target-regions Do stats in these regions only. Tab-delimited file chr,from,to, 1-based, inclusive.\n"); + fprintf(samtools_stdout, " -x, --sparse Suppress outputting IS rows where there are no insertions.\n"); + fprintf(samtools_stdout, " -p, --remove-overlaps Remove overlaps of paired-end reads from coverage and base count computations.\n"); + fprintf(samtools_stdout, " -g, --cov-threshold Only bases with coverage above this value will be included in the target percentage computation [0]\n"); + sam_global_opt_help(samtools_stdout, "-.--.@-."); + fprintf(samtools_stdout, "\n"); + } + else + { + va_list ap; + va_start(ap, format); + vfprintf(samtools_stderr, format, ap); + va_end(ap); + } + samtools_exit(1); +} + +void cleanup_stats_info(stats_info_t* info){ + if (info->fai) fai_destroy(info->fai); + sam_close(info->sam); + free(info); +} + +void cleanup_stats(stats_t* stats) +{ + free(stats->cov_rbuf.buffer); free(stats->cov); + free(stats->quals_1st); free(stats->quals_2nd); + free(stats->gc_1st); free(stats->gc_2nd); + stats->isize->isize_free(stats->isize->data); + free(stats->isize); + free(stats->gcd); + free(stats->rseq_buf); + free(stats->mpc_buf); + free(stats->acgtno_cycles_1st); + free(stats->acgtno_cycles_2nd); + free(stats->acgtno_revcomp); + free(stats->read_lengths); + free(stats->read_lengths_1st); + free(stats->read_lengths_2nd); + free(stats->insertions); + free(stats->deletions); + free(stats->ins_cycles_1st); + free(stats->ins_cycles_2nd); + free(stats->del_cycles_1st); + free(stats->del_cycles_2nd); + if (stats->acgtno_barcode) free(stats->acgtno_barcode); + if (stats->quals_barcode) free(stats->quals_barcode); + free(stats->tags_barcode); + destroy_regions(stats); + if ( stats->rg_hash ) kh_destroy(rg, stats->rg_hash); + free(stats->split_name); + free(stats->mapping_qualities); + free(stats); +} + +void output_split_stats(khash_t(c2stats) *split_hash, char* bam_fname, int sparse) +{ + int i = 0; + kstring_t output_filename = { 0, 0, NULL }; + stats_t *curr_stats = NULL; + for(i = kh_begin(split_hash); i != kh_end(split_hash); ++i){ + if(!kh_exist(split_hash, i)) continue; + curr_stats = kh_value(split_hash, i); + round_buffer_flush(curr_stats, -1); + + output_filename.l = 0; + if (curr_stats->info->split_prefix) + kputs(curr_stats->info->split_prefix, &output_filename); + else + kputs(bam_fname, &output_filename); + kputc('_', &output_filename); + kputs(curr_stats->split_name, &output_filename); + kputs(".bamstat", &output_filename); + + FILE *to = fopen(output_filename.s, "w"); + if(to == NULL){ + error("Could not open '%s' for writing.\n", output_filename.s); + } + output_stats(to, curr_stats, sparse); + fclose(to); + } + + free(output_filename.s); +} + +void destroy_split_stats(khash_t(c2stats) *split_hash) +{ + if (!split_hash) + return; + + int i = 0; + stats_t *curr_stats = NULL; + for(i = kh_begin(split_hash); i != kh_end(split_hash); ++i){ + if(!kh_exist(split_hash, i)) continue; + curr_stats = kh_value(split_hash, i); + cleanup_stats(curr_stats); + } + kh_destroy(c2stats, split_hash); +} + +stats_info_t* stats_info_init(int argc, char *argv[]) +{ + stats_info_t* info = calloc(1, sizeof(stats_info_t)); + if (!info) { + return NULL; + } + + info->nisize = 8000; + info->isize_main_bulk = 0.99; // There are always outliers at the far end + info->gcd_bin_size = 20e3; + info->cov_min = 1; + info->cov_max = 1000; + info->cov_step = 1; + info->filter_readlen = -1; + info->argc = argc; + info->argv = argv; + info->remove_overlaps = 0; + info->cov_threshold = 0; + + return info; +} + +int init_stat_info_fname(stats_info_t* info, const char* bam_fname, const htsFormat* in_fmt) +{ + // .. bam + samFile* sam; + if ((sam = sam_open_format(bam_fname, "r", in_fmt)) == 0) { + print_error_errno("stats", "failed to open \"%s\"", bam_fname); + return 1; + } + info->sam = sam; + info->sam_header = sam_hdr_read(sam); + if (info->sam_header == NULL) { + print_error("stats", "failed to read header for \"%s\"", bam_fname); + return 1; + } + return 0; +} + +stats_t* stats_init() +{ + stats_t *stats = calloc(1,sizeof(stats_t)); + if (!stats) + return NULL; + + stats->ngc = 200; + stats->nquals = 256; + stats->nbases = 300; + stats->rseq_pos = -1; + stats->tid = -1; + stats->gcd_pos = -1LL; + stats->igcd = 0; + stats->is_sorted = 1; + stats->nindels = stats->nbases; + stats->split_name = NULL; + stats->nchunks = 0; + stats->pair_count = 0; + stats->last_pair_tid = -2; + stats->last_read_flush = 0; + stats->target_count = 0; + + return stats; +} + +static int init_barcode_tags(stats_t* stats) { + stats->ntags = 4; + stats->tags_barcode = calloc(stats->ntags, sizeof(barcode_info_t)); + if (!stats->tags_barcode) + return -1; + stats->tags_barcode[0] = (barcode_info_t){"BC", "QT", 0, -1, -1, 0}; + stats->tags_barcode[1] = (barcode_info_t){"CR", "CY", 0, -1, -1, 0}; + stats->tags_barcode[2] = (barcode_info_t){"OX", "BZ", 0, -1, -1, 0}; + stats->tags_barcode[3] = (barcode_info_t){"RX", "QX", 0, -1, -1, 0}; + return 0; +} + +static void init_stat_structs(stats_t* stats, stats_info_t* info, const char* group_id, const char* targets) +{ + // Give stats_t a pointer to the info struct + // This saves us having to pass the stats_info_t to every function + stats->info = info; + + // Init structures + // .. coverage bins and round buffer + if ( info->cov_step > info->cov_max - info->cov_min + 1 ) + { + info->cov_step = info->cov_max - info->cov_min; + if ( info->cov_step <= 0 ) + info->cov_step = 1; + } + stats->ncov = 3 + (info->cov_max-info->cov_min) / info->cov_step; + info->cov_max = info->cov_min + ((info->cov_max-info->cov_min)/info->cov_step +1)*info->cov_step - 1; + stats->cov = calloc(sizeof(uint64_t),stats->ncov); + if (!stats->cov) goto nomem; + stats->cov_rbuf.size = stats->nbases*5; + stats->cov_rbuf.buffer = calloc(sizeof(int32_t),stats->cov_rbuf.size); + if (!stats->cov_rbuf.buffer) goto nomem; + if ( group_id ) init_group_id(stats, info, group_id); + // .. arrays + stats->quals_1st = calloc(stats->nquals*stats->nbases,sizeof(uint64_t)); + if (!stats->quals_1st) goto nomem; + stats->quals_2nd = calloc(stats->nquals*stats->nbases,sizeof(uint64_t)); + if (!stats->quals_2nd) goto nomem; + stats->gc_1st = calloc(stats->ngc,sizeof(uint64_t)); + if (!stats->gc_1st) goto nomem; + stats->gc_2nd = calloc(stats->ngc,sizeof(uint64_t)); + if (!stats->gc_2nd) goto nomem; + stats->isize = init_isize_t(info->nisize ?info->nisize+1 :0); + if (!stats->isize) goto nomem; + stats->gcd = calloc(stats->ngcd,sizeof(gc_depth_t)); + if (!stats->gcd) goto nomem; + if (info->fai) { + stats->mpc_buf = calloc(stats->nquals*stats->nbases,sizeof(uint64_t)); + if (!stats->mpc_buf) goto nomem; + } else { + stats->mpc_buf = NULL; + } + stats->acgtno_cycles_1st = calloc(stats->nbases,sizeof(acgtno_count_t)); + if (!stats->acgtno_cycles_1st) goto nomem; + stats->acgtno_cycles_2nd = calloc(stats->nbases,sizeof(acgtno_count_t)); + if (!stats->acgtno_cycles_2nd) goto nomem; + stats->acgtno_revcomp = calloc(stats->nbases,sizeof(acgtno_count_t)); + if (!stats->acgtno_revcomp) goto nomem; + stats->read_lengths = calloc(stats->nbases,sizeof(uint64_t)); + if (!stats->read_lengths) goto nomem; + stats->read_lengths_1st = calloc(stats->nbases,sizeof(uint64_t)); + if (!stats->read_lengths_1st) goto nomem; + stats->read_lengths_2nd = calloc(stats->nbases,sizeof(uint64_t)); + if (!stats->read_lengths_2nd) goto nomem; + stats->insertions = calloc(stats->nbases,sizeof(uint64_t)); + if (!stats->insertions) goto nomem; + stats->deletions = calloc(stats->nbases,sizeof(uint64_t)); + if (!stats->deletions) goto nomem; + stats->ins_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t)); + if (!stats->ins_cycles_1st) goto nomem; + stats->ins_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t)); + if (!stats->ins_cycles_2nd) goto nomem; + stats->del_cycles_1st = calloc(stats->nbases+1,sizeof(uint64_t)); + if (!stats->del_cycles_1st) goto nomem; + stats->del_cycles_2nd = calloc(stats->nbases+1,sizeof(uint64_t)); + if (!stats->del_cycles_2nd) goto nomem; + stats->mapping_qualities = calloc(256,sizeof(uint64_t)); + if(!stats->mapping_qualities) goto nomem; + if (init_barcode_tags(stats) < 0) + goto nomem; + realloc_rseq_buffer(stats); + if ( targets ) + init_regions(stats, targets, info); + return; + nomem: + error("Out of memory"); +} + +static stats_t* get_curr_split_stats(bam1_t* bam_line, khash_t(c2stats)* split_hash, stats_info_t* info, char* targets) +{ + stats_t *curr_stats = NULL; + const uint8_t *tag_val = bam_aux_get(bam_line, info->split_tag); + if(tag_val == 0){ + error("Tag '%s' not found in bam_line.\n", info->split_tag); + } + char* split_name = strdup(bam_aux2Z(tag_val)); + + // New stats object, under split + khiter_t k = kh_get(c2stats, split_hash, split_name); + if(k == kh_end(split_hash)){ + curr_stats = stats_init(); // mallocs new instance + if (!curr_stats) { + error("Couldn't allocate split stats"); + } + init_stat_structs(curr_stats, info, NULL, targets); + curr_stats->split_name = split_name; + + // Record index in hash + int ret = 0; + khiter_t iter = kh_put(c2stats, split_hash, split_name, &ret); + if( ret < 0 ){ + error("Failed to insert key '%s' into split_hash", split_name); + } + kh_val(split_hash, iter) = curr_stats; // store pointer to stats + } + else{ + curr_stats = kh_value(split_hash, k); + free(split_name); // don't need to hold on to this if it wasn't new + } + return curr_stats; +} + +int main_stats(int argc, char *argv[]) +{ + char *targets = NULL; + char *bam_fname = NULL; + char *bam_idx_fname = NULL; + char *group_id = NULL; + int sparse = 0, has_index_file = 0, ret = 1; + sam_global_args ga = SAM_GLOBAL_ARGS_INIT; + + stats_info_t *info = stats_info_init(argc, argv); + if (!info) { + fprintf(samtools_stderr, "Could not allocate memory for info.\n"); + return 1; + } + + static const struct option loptions[] = + { + SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'), + {"help", no_argument, NULL, 'h'}, + {"remove-dups", no_argument, NULL, 'd'}, + {"sam", no_argument, NULL, 's'}, + {"customized-index-file", required_argument, NULL, 'X'}, + {"ref-seq", required_argument, NULL, 'r'}, + {"coverage", required_argument, NULL, 'c'}, + {"read-length", required_argument, NULL, 'l'}, + {"insert-size", required_argument, NULL, 'i'}, + {"most-inserts", required_argument, NULL, 'm'}, + {"trim-quality", required_argument, NULL, 'q'}, + {"target-regions", required_argument, NULL, 't'}, + {"required-flag", required_argument, NULL, 'f'}, + {"filtering-flag", required_argument, NULL, 'F'}, + {"id", required_argument, NULL, 'I'}, + {"GC-depth", required_argument, NULL, 1}, + {"sparse", no_argument, NULL, 'x'}, + {"split", required_argument, NULL, 'S'}, + {"split-prefix", required_argument, NULL, 'P'}, + {"remove-overlaps", no_argument, NULL, 'p'}, + {"cov-threshold", required_argument, NULL, 'g'}, + {NULL, 0, NULL, 0} + }; + int opt; + + while ( (opt=getopt_long(argc,argv,"?hdsXxpr:c:l:i:t:m:q:f:F:g:I:S:P:@:",loptions,NULL))>0 ) + { + switch (opt) + { + case 'f': info->flag_require = bam_str2flag(optarg); break; + case 'F': info->flag_filter |= bam_str2flag(optarg); break; + case 'd': info->flag_filter |= BAM_FDUP; break; + case 'X': has_index_file = 1; break; + case 's': break; + case 'r': info->fai = fai_load(optarg); + if (info->fai==NULL) + error("Could not load faidx: %s\n", optarg); + break; + case 1 : info->gcd_bin_size = atof(optarg); break; + case 'c': if ( sscanf(optarg,"%d,%d,%d",&info->cov_min,&info->cov_max,&info->cov_step)!= 3 ) + error("Unable to parse -c %s\n", optarg); + break; + case 'l': info->filter_readlen = atoi(optarg); break; + case 'i': info->nisize = atoi(optarg); break; + case 'm': info->isize_main_bulk = atof(optarg); break; + case 'q': info->trim_qual = atoi(optarg); break; + case 't': targets = optarg; break; + case 'I': group_id = optarg; break; + case 'x': sparse = 1; break; + case 'S': info->split_tag = optarg; break; + case 'P': info->split_prefix = optarg; break; + case 'p': info->remove_overlaps = 1; break; + case 'g': info->cov_threshold = atoi(optarg); + if ( info->cov_threshold < 0 || info->cov_threshold == INT_MAX ) + error("Unsupported value for coverage threshold %d\n", info->cov_threshold); + break; + case '?': + case 'h': error(NULL); + /* no break */ + default: + if (parse_sam_global_opt(opt, optarg, loptions, &ga) != 0) + error("Unknown argument: %s\n", optarg); + break; + } + } + + bam_fname = argv[optind++]; + if ( !bam_fname ) + { + if ( isatty(STDIN_FILENO) ) + error(NULL); + bam_fname = "-"; + } + + if (init_stat_info_fname(info, bam_fname, &ga.in)) { + cleanup_stats_info(info); + return 1; + } + + if (has_index_file && !(bam_idx_fname = argv[optind++])) { + fprintf(samtools_stderr, "No index file provided\n"); + cleanup_stats_info(info); + return 1; + } + + if (ga.nthreads > 0) + hts_set_threads(info->sam, ga.nthreads); + + stats_t *all_stats = stats_init(); + if (!all_stats) { + fprintf(samtools_stderr, "Could not allocate memory for stats.\n"); + cleanup_stats_info(info); + return 1; + } + stats_t *curr_stats = NULL; + init_stat_structs(all_stats, info, group_id, targets); + // Init + // .. hash + khash_t(c2stats)* split_hash = kh_init(c2stats); + if (!split_hash) goto cleanup_all_stats; + + khash_t(qn2pair)* read_pairs = kh_init(qn2pair); + if (!read_pairs) goto cleanup_split_hash; + + // Collect statistics + bam1_t *bam_line = bam_init1(); + if (!bam_line) goto cleanup_read_pairs; + + if (optind < argc) { + // Region:interval arguments in the command line + hts_idx_t *bam_idx = NULL; + if (has_index_file) { + bam_idx = sam_index_load2(info->sam, bam_fname, bam_idx_fname); + } else { + // If an index filename has not been specified, look alongside the alignment file + bam_idx = sam_index_load(info->sam, bam_fname); + } + + if (bam_idx) { + hts_itr_multi_t *iter = sam_itr_regarray(bam_idx, info->sam_header, &argv[optind], argc - optind); + if (iter) { + if (!targets) { + all_stats->nchunks = argc-optind; + if (replicate_regions(all_stats, iter, info)) + fprintf(samtools_stderr, "Replications of the regions failed\n"); + } + + if ( all_stats->nregions && all_stats->regions ) { + while ((ret = sam_itr_next(info->sam, iter, bam_line)) >= 0) { + if (info->split_tag) { + curr_stats = get_curr_split_stats(bam_line, split_hash, info, targets); + collect_stats(bam_line, curr_stats, read_pairs); + } + collect_stats(bam_line, all_stats, read_pairs); + } + + if (ret < -1) { + fprintf(samtools_stderr, "Failure while running the iterator\n"); + hts_itr_multi_destroy(iter); + hts_idx_destroy(bam_idx); + goto cleanup; + } + } + hts_itr_multi_destroy(iter); + } else { + fprintf(samtools_stderr, "Multi-region iterator could not be created\n"); + hts_idx_destroy(bam_idx); + goto cleanup; + } + hts_idx_destroy(bam_idx); + } else { + if (has_index_file) + fprintf(samtools_stderr, "Invalid index file '%s'\n", bam_idx_fname); + fprintf(samtools_stderr, "Random alignment retrieval only works for indexed files\n"); + goto cleanup; + } + } else { + if ( info->cov_threshold > 0 && !targets ) { + fprintf(samtools_stderr, "Coverage percentage calculation requires a list of target regions\n"); + goto cleanup; + } + + // Stream through the entire BAM ignoring off-target regions if -t is given + while ((ret = sam_read1(info->sam, info->sam_header, bam_line)) >= 0) { + if (info->split_tag) { + curr_stats = get_curr_split_stats(bam_line, split_hash, info, targets); + collect_stats(bam_line, curr_stats, read_pairs); + } + collect_stats(bam_line, all_stats, read_pairs); + } + + if (ret < -1) { + fprintf(samtools_stderr, "Failure while decoding file\n"); + goto cleanup; + } + } + + round_buffer_flush(all_stats, -1); + output_stats(samtools_stdout, all_stats, sparse); + if (info->split_tag) + output_split_stats(split_hash, bam_fname, sparse); + + ret = 0; +cleanup: + bam_destroy1(bam_line); + sam_hdr_destroy(info->sam_header); + sam_global_args_free(&ga); + +cleanup_read_pairs: + cleanup_overlaps(read_pairs, INT64_MAX); +cleanup_split_hash: + destroy_split_stats(split_hash); +cleanup_all_stats: + cleanup_stats(all_stats); + cleanup_stats_info(info); + + return ret; +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.c.pysam.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..1bb2bd4630cca4525f5a89ece5b67481079050ad --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.c.pysam.c @@ -0,0 +1,241 @@ +#include "samtools.pysam.h" + +/* stats_isize.c -- generalised insert size calculation for samtools stats. + + Copyright (C) 2014, 2018 Genome Research Ltd. + + Author: Nicholas Clarke + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include + +#include +#include "stats_isize.h" +#include + +typedef enum {IN,OUT,OTHER} isize_insert_t; + +static int max(int a, int b) { + if (a < b) { + return b; + } else { + return a; + } +} + +static isize_sparse_record_t * sparse_get_f(isize_data_t data, int at) { + isize_sparse_data_t *a = data.sparse; + khash_t(m32) *h = a->array; + + khint_t k = kh_get(m32, h, at); + if (k != kh_end(h)) { + return kh_value(h, k); + } else { + return NULL; + } +} + +static uint64_t sparse_in_f(isize_data_t data, int at) { + isize_sparse_record_t* a = sparse_get_f(data, at); + if (a != NULL) { + return a->isize_inward; + } else { + return 0; + } +} +static uint64_t sparse_out_f(isize_data_t data, int at) { + isize_sparse_record_t* a = sparse_get_f(data, at); + if (a != NULL) { + return a->isize_outward; + } else { + return 0; + } +} +static uint64_t sparse_other_f(isize_data_t data, int at) { + isize_sparse_record_t* a = sparse_get_f(data, at); + if (a != NULL) { + return a->isize_other; + } else { + return 0; + } +} + +static void sparse_set_f(isize_data_t data, int at, isize_insert_t field, uint64_t value) { + isize_sparse_data_t *a = data.sparse; + khash_t(m32) *h = a->array; + + khint_t k = kh_get(m32, h, at); + isize_sparse_record_t *rec; + if (k != kh_end(h)) { + rec = kh_value(h, k); + } else if (value != 0) { + rec = malloc(sizeof(isize_sparse_record_t)); + if (rec != NULL) { + rec->isize_inward = 0; + rec->isize_outward = 0; + rec->isize_other = 0; + int stupid = 0; + khint_t it = kh_put(m32, h, at, & stupid); + kh_value(h, it) = rec; + a->max = max(at, a->max); + } else { + fprintf(samtools_stderr, "%s\n", "Failed to allocate memory for isize_sparse_record_t"); + samtools_exit(11); + } + } else { + return; + } + if (field == IN) { + rec->isize_inward = value; + } else if (field == OUT) { + rec->isize_outward = value; + } else { + rec->isize_other = value; + } + +} + +static void sparse_set_in_f(isize_data_t data, int at, uint64_t value) { sparse_set_f(data, at, IN, value); } +static void sparse_set_out_f(isize_data_t data, int at, uint64_t value) { sparse_set_f(data, at, OUT, value); } +static void sparse_set_other_f(isize_data_t data, int at, uint64_t value) { sparse_set_f(data, at, OTHER, value); } + +static void sparse_inc_in_f(isize_data_t data, int at) { sparse_set_in_f(data, at, sparse_in_f(data, at) + 1); } +static void sparse_inc_out_f(isize_data_t data, int at) { sparse_set_out_f(data, at, sparse_out_f(data, at) + 1); } +static void sparse_inc_other_f(isize_data_t data, int at) { sparse_set_other_f(data, at, sparse_other_f(data, at) + 1); } + +static void sparse_isize_free(isize_data_t data) { + isize_sparse_data_t *a = data.sparse; + khint_t k; + for (k = 0; k < kh_end(a->array); ++k) + if (kh_exist(a->array, k)) free(kh_val(a->array, k)); + kh_destroy(m32, a->array); + free(a); +} + +static int sparse_nitems(isize_data_t data) { + isize_sparse_data_t *a = data.sparse; + return a->max + 1; +} + +static uint64_t dense_in_f(isize_data_t data, int at) { return data.dense->isize_inward[at]; } +static uint64_t dense_out_f(isize_data_t data, int at) { return data.dense->isize_outward[at]; } +static uint64_t dense_other_f(isize_data_t data, int at) { return data.dense->isize_other[at]; } + +static void dense_set_in_f(isize_data_t data, int at, uint64_t value) { data.dense->isize_inward[at] = value; } +static void dense_set_out_f(isize_data_t data, int at, uint64_t value) { data.dense->isize_outward[at] = value; } +static void dense_set_other_f(isize_data_t data, int at, uint64_t value) { data.dense->isize_other[at] = value; } + +static void dense_inc_in_f(isize_data_t data, int at) { data.dense->isize_inward[at] += 1; } +static void dense_inc_out_f(isize_data_t data, int at) { data.dense->isize_outward[at] += 1; } +static void dense_inc_other_f(isize_data_t data, int at) { data.dense->isize_other[at] += 1; } + +static void dense_isize_free(isize_data_t data) { + isize_dense_data_t *a = data.dense; + free(a->isize_inward); + free(a->isize_outward); + free(a->isize_other); + free(a); +} + +static int dense_nitems(isize_data_t data) { + isize_dense_data_t *a = data.dense; + return a->total; +} + +// Construct a relevant isize_t given the bound. +isize_t *init_isize_t(int bound) { + if (bound <= 0) { + // Use sparse data structure. + isize_sparse_data_t *data = (isize_sparse_data_t *) malloc(sizeof(isize_sparse_data_t)); + if (!data) + return NULL; + + // Initialise + data->max = 0; + data->array = kh_init(m32); + if (!data->array) { + free(data); + return NULL; + } + + isize_t *isize = (isize_t *)malloc(sizeof(isize_t)); + if (!isize) { + kh_destroy(m32, data->array); + free(data); + return NULL; + } + + isize->data.sparse = data; + isize->nitems = & sparse_nitems; + + isize->inward = & sparse_in_f; + isize->outward = & sparse_out_f; + isize->other = & sparse_other_f; + + isize->set_inward = & sparse_set_in_f; + isize->set_outward = & sparse_set_out_f; + isize->set_other = & sparse_set_other_f; + + isize->inc_inward = & sparse_inc_in_f; + isize->inc_outward = & sparse_inc_out_f; + isize->inc_other = & sparse_inc_other_f; + + isize->isize_free = & sparse_isize_free; + + return isize; + } else { + uint64_t* in = calloc(bound,sizeof(uint64_t)); + uint64_t* out = calloc(bound,sizeof(uint64_t)); + uint64_t* other = calloc(bound,sizeof(uint64_t)); + isize_dense_data_t *rec = (isize_dense_data_t *)malloc(sizeof(isize_dense_data_t)); + isize_t *isize = (isize_t *)malloc(sizeof(isize_t)); + if (!in || !out || !other || !rec || !isize) { + free(in); + free(out); + free(other); + free(rec); + free(isize); + return NULL; + } + rec->isize_inward = in; + rec->isize_outward = out; + rec->isize_other = other; + rec->total=bound; + + isize->data.dense = rec; + isize->nitems = & dense_nitems; + + isize->inward = & dense_in_f; + isize->outward = & dense_out_f; + isize->other = & dense_other_f; + + isize->set_inward = & dense_set_in_f; + isize->set_outward = & dense_set_out_f; + isize->set_other = & dense_set_other_f; + + isize->inc_inward = & dense_inc_in_f; + isize->inc_outward = & dense_inc_out_f; + isize->inc_other = & dense_inc_other_f; + + isize->isize_free = & dense_isize_free; + + return isize; + } +} diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.h b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.h new file mode 100644 index 0000000000000000000000000000000000000000..32432221547f8ed373fc5063e3d13247ef7c183d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/stats_isize.h @@ -0,0 +1,83 @@ +/* stats_isize.h -- generalised insert size calculation for samtools stats. + + Copyright (C) 2014 Genome Research Ltd. + + Author: Nicholas Clarke + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. */ + +#include +#include + +typedef struct +{ + int total; + uint64_t *isize_inward, *isize_outward, *isize_other; +} +isize_dense_data_t; + +typedef struct +{ + uint64_t isize_inward, isize_outward, isize_other; +} +isize_sparse_record_t; + +KHASH_MAP_INIT_INT(m32, isize_sparse_record_t *) + +typedef struct +{ + int max; + khash_t(m32) *array; +} +isize_sparse_data_t; + +typedef union { + isize_sparse_data_t *sparse; + isize_dense_data_t *dense; +} isize_data_t; + +// Insert size structure +typedef struct +{ + isize_data_t data; + + // Maximum + int (*nitems)(isize_data_t); + + // Fetch the number of inserts of a given size + uint64_t (*inward)(isize_data_t, int); + uint64_t (*outward)(isize_data_t, int); + uint64_t (*other)(isize_data_t, int); + + // Set the number of inserts of a given size + void (*set_inward)(isize_data_t, int, uint64_t); + void (*set_outward)(isize_data_t, int, uint64_t); + void (*set_other)(isize_data_t, int, uint64_t); + + // Increment the number of inserts of a given size + void (*inc_inward)(isize_data_t, int); + void (*inc_outward)(isize_data_t, int); + void (*inc_other)(isize_data_t, int); + + // Free this structure + void (*isize_free)(isize_data_t); +} +isize_t; + +isize_t *init_isize_t(int bound); diff --git a/falcon/lib/python3.10/site-packages/pysam/include/samtools/tmp_file.c b/falcon/lib/python3.10/site-packages/pysam/include/samtools/tmp_file.c new file mode 100644 index 0000000000000000000000000000000000000000..123f425e18dc366d4c0e2b36c7b58152db32ac37 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/pysam/include/samtools/tmp_file.c @@ -0,0 +1,438 @@ +/* + tmp_file.c - write to and read from a temporary binary file + for fast storage plus added compression. + + Copyright (C) 2017, 2018 Genome Research Ltd. + + Author: Andrew Whitwham + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif /* _WIN32 */ + +#include "tmp_file.h" +#include "htslib/sam.h" + + +static void tmp_print_error(tmp_file_t *tmp, const char *fmt, ...) { + va_list argp; + + if (tmp->verbose) { + va_start(argp, fmt); + vfprintf(stderr, fmt, argp); + va_end(argp); + } +} + + +static int tmp_file_init(tmp_file_t *tmp, int verbose) { + tmp->stream = LZ4_createStream(); + tmp->data_size = 0; + tmp->group_size = TMP_SAM_GROUP_SIZE; + tmp->input_size = 0; + tmp->read_size = 0; + tmp->output_size = 0; + tmp->entry_number = 0; + tmp->offset = 0; + tmp->max_data_size = TMP_SAM_MAX_DATA + sizeof(bam1_t); // arbitrary but growable + tmp->ring_buffer_size = TMP_SAM_RING_SIZE; // arbitrary (min 64K) but growable + tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size * tmp->group_size); + tmp->ring_buffer = malloc(sizeof(uint8_t) * tmp->ring_buffer_size); + tmp->ring_index = tmp->ring_buffer; + tmp->comp_buffer = malloc(tmp->comp_buffer_size); + tmp->verbose = verbose; + tmp->dict = NULL; + tmp->groups_written = 0; + + if (!tmp->ring_buffer || !tmp->comp_buffer || !tmp->stream) { + tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression buffers.\n"); + return TMP_SAM_MEM_ERROR; + } + + return TMP_SAM_OK; +} + + +/* + * Opens the temp file and initialises memory. + * Verbose mode prints out error messages to stderr. + * Returns 0 on success, a negative number on failure. + */ +int tmp_file_open_write(tmp_file_t *tmp, char *tmp_name, int verbose) { + int ret; + unsigned int count = 1; + const unsigned int max_count = 100000; // more tries than this then something else is wrong + int fd; + + if ((ret = tmp_file_init(tmp, verbose))) { + return ret; + } + + // make space to write extended file name + if ((tmp->name = malloc(strlen(tmp_name) + 7)) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for %s.\n", tmp_name); + return TMP_SAM_MEM_ERROR; + } + + // make sure temp file has a unique name + while (count < max_count) { + sprintf(tmp->name, "%s.%d", tmp_name, count); + + + #ifdef _WIN32 + if ((fd = _open(tmp->name, O_RDWR|O_CREAT|O_EXCL|O_BINARY|O_TEMPORARY, 0600)) == -1) { + #else + if ((fd = open(tmp->name, O_RDWR|O_CREAT|O_EXCL, 0600)) == -1) { + #endif /* _WIN32 */ + + if (errno != EEXIST) { + tmp_print_error(tmp, "[tmp_file] Error: unable to create tmp file %s.\n", tmp->name); + return TMP_SAM_FILE_ERROR; + } + + count++; + continue; + } + + break; + } + + if (count >= max_count) { + tmp_print_error(tmp, "[tmp_file] Error: unable to create unique temp file.\n"); + return TMP_SAM_FILE_ERROR; + } + + if ((tmp->fp = fdopen(fd, "w+b")) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to open write file %s.\n", tmp->name); + return TMP_SAM_FILE_ERROR; + } + + #ifndef _WIN32 + unlink(tmp->name); // should auto delete when closed on linux + #endif + + return TMP_SAM_OK; +} + + +/* + * The ring buffer stores precompressionn/post decompression data. LZ4 requires that + * previous data (64K worth) be available for efficient compression. This function grows + * the ring buffer when needed. + * Returns 0 on success, a negative number on failure. + */ +static int tmp_file_grow_ring_buffer(tmp_file_t *tmp, size_t new_size) { + // save the dictionary so lz4 can continue to function + int dict_size = 64 * 1024; // 64K max size + + if (tmp->groups_written) { + // if compression has been done then there is a dictionary to save + + if (tmp->dict == NULL) { + + if ((tmp->dict = malloc(sizeof(char) * dict_size)) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for compression dictionary.\n"); + return TMP_SAM_MEM_ERROR; + } + } + + if (LZ4_saveDict(tmp->stream, tmp->dict, dict_size) == 0) { + tmp_print_error(tmp, "[tmp_file] Error: unable to save compression dictionary.\n"); + return TMP_SAM_LZ4_ERROR; + } + } + + if ((tmp->ring_buffer = realloc(tmp->ring_buffer, sizeof(char) * new_size)) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate ring buffer.\n"); + return TMP_SAM_MEM_ERROR; + } + + tmp->ring_buffer_size = new_size; + + return TMP_SAM_OK; +} + + +/* + * This does the actual compression and writing to a file. The file format consists of a + * single size_t for the size of the compressed data followed by the data itself. + * Returns 0 on success, a negative number on failure. + */ +static int tmp_file_write_to_file(tmp_file_t *tmp) { + size_t comp_size; + + if (tmp->input_size > tmp->max_data_size) { + tmp->max_data_size += tmp->input_size + sizeof(bam1_t); + tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size); + + if ((tmp->comp_buffer = realloc(tmp->comp_buffer, sizeof(char) * tmp->comp_buffer_size)) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate compression buffer.\n"); + return TMP_SAM_MEM_ERROR; + } + + // make sure the ring buffer is big enough to accommodate the new max_data_size + if (tmp->ring_buffer_size < tmp->max_data_size * 5) { + int ret; + if ((ret = tmp_file_grow_ring_buffer(tmp, tmp->max_data_size * 5))) { + return ret; + } + } + } + + tmp->ring_index = tmp->ring_buffer + tmp->offset; + + comp_size = LZ4_compress_fast_continue(tmp->stream, (const char *)tmp->ring_index, + tmp->comp_buffer, tmp->input_size, tmp->comp_buffer_size, 1); + + if (comp_size == 0) { + tmp_print_error(tmp, "[tmp_file] Error: compression failed.\n"); + return TMP_SAM_LZ4_ERROR; + } + + if (fwrite(&comp_size, sizeof(size_t), 1, tmp->fp) < 1) { + tmp_print_error(tmp, "[tmp_file] Error: tmp file write size failed.\n"); + return TMP_SAM_FILE_ERROR; + } + + if (fwrite(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) < comp_size) { + tmp_print_error(tmp, "[tmp_file] Error: tmp file write data failed.\n"); + return TMP_SAM_FILE_ERROR; + } + + tmp->offset += tmp->input_size; + + if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size) + tmp->offset = 0; + + tmp->input_size = 0; + tmp->entry_number = 0; + tmp->groups_written++; + + return TMP_SAM_OK; +} + + +/* + * Stores an in memory bam structure for writing and if enough are gathered together writes + * it to a file. Multiple alignments compress better that single ones though after a certain number + * there is a law of diminishing returns. + * Returns 0 on success, a negative number on failure. + */ +int tmp_file_write(tmp_file_t *tmp, bam1_t *inbam) { + + if ((tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) >= tmp->ring_buffer_size) { + int ret; + + if ((ret = tmp_file_grow_ring_buffer(tmp, (tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) * 2))) { + tmp_print_error(tmp, "[tmp_file] Error: input line too big. (%ld).\n", + (tmp->input_size + inbam->l_data)); + + return ret; + } + } + + tmp->ring_index = tmp->ring_buffer + tmp->offset + tmp->input_size; + + // copy data into the ring buffer + memcpy(tmp->ring_index, inbam, sizeof(bam1_t)); + memcpy(tmp->ring_index + sizeof(bam1_t) , inbam->data, inbam->l_data); + tmp->input_size += sizeof(bam1_t) + inbam->l_data; + tmp->entry_number++; + + if (tmp->entry_number == tmp->group_size) { + // actually write out the data + int ret; + + if ((ret = tmp_file_write_to_file(tmp))) { + return ret; + } + } + + return TMP_SAM_OK; +} + + +/* + * Marks the end of file writing. Adds a size_t 0 to mark the end of + * the file. Companion function to tmp_file_begin_read below. + * Returns 0 on success, a negative number on failure. + */ +int tmp_file_end_write(tmp_file_t *tmp) { + size_t terminator = 0; + + if (tmp->entry_number) { + int ret; + + if ((ret = tmp_file_write_to_file(tmp))) { + return ret; + } + } + + if (fwrite(&terminator, sizeof(size_t), 1, tmp->fp) < 1) { + tmp_print_error(tmp, "[tmp_file] Error: tmp file write terminator failed.\n"); + return TMP_SAM_FILE_ERROR; + } + + fflush(tmp->fp); + + LZ4_freeStream(tmp->stream); + + return TMP_SAM_OK; +} + + +/* + * Prepares the file for reading. + * Companion function to tmp_file_end_write above. + * Returns 0 on success, a negative number on failure. + */ +int tmp_file_begin_read(tmp_file_t *tmp) { + + rewind(tmp->fp); + + tmp->dstream = LZ4_createStreamDecode(); + tmp->offset = 0; + tmp->entry_number = tmp->group_size; + + if (!tmp->dstream) { + tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression stream.\n"); + return TMP_SAM_MEM_ERROR; + } + + return TMP_SAM_OK; +} + + +/* + * Read the next alignment, either from memory or from a file. + * Returns size of entry on success, 0 on end of file or a negative on error. + */ +int tmp_file_read(tmp_file_t *tmp, bam1_t *inbam) { + int entry_size; + uint8_t *data = inbam->data; + + /* while tmp_file_read assumes that the same bam1_t variable + is being used in each call, this may not be the case. So + default to the lowest memory size for safety. */ + if (tmp->data_size > inbam->m_data) { + tmp->data_size = inbam->m_data; + } + + if (tmp->entry_number == tmp->group_size) { + // read more data + size_t comp_size; + + if (fread(&comp_size, sizeof(size_t), 1, tmp->fp) == 0 || comp_size == 0) { + return TMP_SAM_OK; + } + + if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size) + tmp->offset = 0; + + tmp->ring_index = tmp->ring_buffer + tmp->offset; + + if (fread(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) > comp_size) { + tmp_print_error(tmp, "[tmp_file] Error: error reading compressed data.\n"); + return TMP_SAM_FILE_ERROR; + } + + tmp->output_size = LZ4_decompress_safe_continue(tmp->dstream, tmp->comp_buffer, + (char *)tmp->ring_index, comp_size, tmp->max_data_size); + + if (tmp->output_size == 0) { + tmp_print_error(tmp, "[tmp_file] Error: decompression failed.\n"); + return TMP_SAM_LZ4_ERROR; + } + + tmp->entry_number = 0; + tmp->read_size = 0; + } + + tmp->ring_index = tmp->ring_buffer + tmp->offset; + memcpy(inbam, tmp->ring_index, sizeof(bam1_t)); + inbam->data = data; // put the pointer to real bam data back + + if ((unsigned int)inbam->l_data > tmp->data_size) { + uint8_t *tmp_data; + tmp->data_size = inbam->l_data; kroundup32(tmp->data_size); + + if ((tmp_data = realloc(inbam->data, sizeof(uint8_t) * tmp->data_size)) == NULL) { + tmp_print_error(tmp, "[tmp_file] Error: unable to allocate tmp bam data memory.\n"); + return TMP_SAM_MEM_ERROR; + } + + inbam->data = tmp_data; + } + + inbam->m_data = tmp->data_size; // set to the actual data size + + entry_size = sizeof(bam1_t); + + memcpy(inbam->data, tmp->ring_index + entry_size, inbam->l_data); + entry_size += inbam->l_data; + + tmp->offset += entry_size; + tmp->read_size += entry_size; + tmp->entry_number++; + + if (tmp->read_size > tmp->output_size) { + tmp_print_error(tmp, "[tmp_file] Error: wrong size of data returned RS:%ld OS:%ld EN:%ld GS:%ld.\n", + tmp->read_size, tmp->output_size, tmp->entry_number, tmp->group_size); + return TMP_SAM_LZ4_ERROR; + } + + if (tmp->read_size == tmp->output_size && tmp->entry_number != tmp->group_size) { + // hopefully the last entries in the read file + tmp->entry_number = tmp->group_size; + } + + return entry_size; +} + + +/* + * Frees up memory, closes the file and deletes it. + * Returns 0 on success or EOF on failure. + */ +int tmp_file_destroy(tmp_file_t *tmp) { + int ret = 0; + + ret = fclose(tmp->fp); + + LZ4_freeStreamDecode(tmp->dstream); + free(tmp->ring_buffer); + free(tmp->comp_buffer); + free(tmp->name); + free(tmp->dict); + + return ret; +} diff --git a/falcon/lib/python3.10/turtledemo/colormixer.py b/falcon/lib/python3.10/turtledemo/colormixer.py new file mode 100644 index 0000000000000000000000000000000000000000..448db83361a649eff317733a5b932a1989a8697f --- /dev/null +++ b/falcon/lib/python3.10/turtledemo/colormixer.py @@ -0,0 +1,58 @@ +# colormixer + +from turtle import Screen, Turtle, mainloop + +class ColorTurtle(Turtle): + + def __init__(self, x, y): + Turtle.__init__(self) + self.shape("turtle") + self.resizemode("user") + self.shapesize(3,3,5) + self.pensize(10) + self._color = [0,0,0] + self.x = x + self._color[x] = y + self.color(self._color) + self.speed(0) + self.left(90) + self.pu() + self.goto(x,0) + self.pd() + self.sety(1) + self.pu() + self.sety(y) + self.pencolor("gray25") + self.ondrag(self.shift) + + def shift(self, x, y): + self.sety(max(0,min(y,1))) + self._color[self.x] = self.ycor() + self.fillcolor(self._color) + setbgcolor() + +def setbgcolor(): + screen.bgcolor(red.ycor(), green.ycor(), blue.ycor()) + +def main(): + global screen, red, green, blue + screen = Screen() + screen.delay(0) + screen.setworldcoordinates(-1, -0.3, 3, 1.3) + + red = ColorTurtle(0, .5) + green = ColorTurtle(1, .5) + blue = ColorTurtle(2, .5) + setbgcolor() + + writer = Turtle() + writer.ht() + writer.pu() + writer.goto(1,1.15) + writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic"))) + return "EVENTLOOP" + +if __name__ == "__main__": + msg = main() + print(msg) + mainloop() diff --git a/falcon/lib/python3.10/turtledemo/lindenmayer.py b/falcon/lib/python3.10/turtledemo/lindenmayer.py new file mode 100644 index 0000000000000000000000000000000000000000..3925f25da61870d0cf75ede6ddefbef2562afd03 --- /dev/null +++ b/falcon/lib/python3.10/turtledemo/lindenmayer.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" turtle-example-suite: + + xtx_lindenmayer_indian.py + +Each morning women in Tamil Nadu, in southern +India, place designs, created by using rice +flour and known as kolam on the thresholds of +their homes. + +These can be described by Lindenmayer systems, +which can easily be implemented with turtle +graphics and Python. + +Two examples are shown here: +(1) the snake kolam +(2) anklets of Krishna + +Taken from Marcia Ascher: Mathematics +Elsewhere, An Exploration of Ideas Across +Cultures + +""" +################################ +# Mini Lindenmayer tool +############################### + +from turtle import * + +def replace( seq, replacementRules, n ): + for i in range(n): + newseq = "" + for element in seq: + newseq = newseq + replacementRules.get(element,element) + seq = newseq + return seq + +def draw( commands, rules ): + for b in commands: + try: + rules[b]() + except TypeError: + try: + draw(rules[b], rules) + except: + pass + + +def main(): + ################################ + # Example 1: Snake kolam + ################################ + + + def r(): + right(45) + + def l(): + left(45) + + def f(): + forward(7.5) + + snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"} + snake_replacementRules = {"b": "b+f+b--f--b+f+b"} + snake_start = "b--f--b--f" + + drawing = replace(snake_start, snake_replacementRules, 3) + + reset() + speed(3) + tracer(1,0) + ht() + up() + backward(195) + down() + draw(drawing, snake_rules) + + from time import sleep + sleep(3) + + ################################ + # Example 2: Anklets of Krishna + ################################ + + def A(): + color("red") + circle(10,90) + + def B(): + from math import sqrt + color("black") + l = 5/sqrt(2) + forward(l) + circle(l, 270) + forward(l) + + def F(): + color("green") + forward(10) + + krishna_rules = {"a":A, "b":B, "f":F} + krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" } + krishna_start = "fbfbfbfb" + + reset() + speed(0) + tracer(3,0) + ht() + left(45) + drawing = replace(krishna_start, krishna_replacementRules, 3) + draw(drawing, krishna_rules) + tracer(1) + return "Done!" + +if __name__=='__main__': + msg = main() + print(msg) + mainloop() diff --git a/falcon/lib/python3.10/turtledemo/nim.py b/falcon/lib/python3.10/turtledemo/nim.py new file mode 100644 index 0000000000000000000000000000000000000000..9ae6cc5c01b9039981f31f4c28a470ac249ee5dc --- /dev/null +++ b/falcon/lib/python3.10/turtledemo/nim.py @@ -0,0 +1,226 @@ +""" turtle-example-suite: + + tdemo_nim.py + +Play nim against the computer. The player +who takes the last stick is the winner. + +Implements the model-view-controller +design pattern. +""" + + +import turtle +import random +import time + +SCREENWIDTH = 640 +SCREENHEIGHT = 480 + +MINSTICKS = 7 +MAXSTICKS = 31 + +HUNIT = SCREENHEIGHT // 12 +WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) + +SCOLOR = (63, 63, 31) +HCOLOR = (255, 204, 204) +COLOR = (204, 204, 255) + +def randomrow(): + return random.randint(MINSTICKS, MAXSTICKS) + +def computerzug(state): + xored = state[0] ^ state[1] ^ state[2] + if xored == 0: + return randommove(state) + for z in range(3): + s = state[z] ^ xored + if s <= state[z]: + move = (z, s) + return move + +def randommove(state): + m = max(state) + while True: + z = random.randint(0,2) + if state[z] > (m > 1): + break + rand = random.randint(m > 1, state[z]-1) + return z, rand + + +class NimModel(object): + def __init__(self, game): + self.game = game + + def setup(self): + if self.game.state not in [Nim.CREATED, Nim.OVER]: + return + self.sticks = [randomrow(), randomrow(), randomrow()] + self.player = 0 + self.winner = None + self.game.view.setup() + self.game.state = Nim.RUNNING + + def move(self, row, col): + maxspalte = self.sticks[row] + self.sticks[row] = col + self.game.view.notify_move(row, col, maxspalte, self.player) + if self.game_over(): + self.game.state = Nim.OVER + self.winner = self.player + self.game.view.notify_over() + elif self.player == 0: + self.player = 1 + row, col = computerzug(self.sticks) + self.move(row, col) + self.player = 0 + + def game_over(self): + return self.sticks == [0, 0, 0] + + def notify_move(self, row, col): + if self.sticks[row] <= col: + return + self.move(row, col) + + +class Stick(turtle.Turtle): + def __init__(self, row, col, game): + turtle.Turtle.__init__(self, visible=False) + self.row = row + self.col = col + self.game = game + x, y = self.coords(row, col) + self.shape("square") + self.shapesize(HUNIT/10.0, WUNIT/20.0) + self.speed(0) + self.pu() + self.goto(x,y) + self.color("white") + self.showturtle() + + def coords(self, row, col): + packet, remainder = divmod(col, 5) + x = (3 + 11 * packet + 2 * remainder) * WUNIT + y = (2 + 3 * row) * HUNIT + return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 + + def makemove(self, x, y): + if self.game.state != Nim.RUNNING: + return + self.game.controller.notify_move(self.row, self.col) + + +class NimView(object): + def __init__(self, game): + self.game = game + self.screen = game.screen + self.model = game.model + self.screen.colormode(255) + self.screen.tracer(False) + self.screen.bgcolor((240, 240, 255)) + self.writer = turtle.Turtle(visible=False) + self.writer.pu() + self.writer.speed(0) + self.sticks = {} + for row in range(3): + for col in range(MAXSTICKS): + self.sticks[(row, col)] = Stick(row, col, game) + self.display("... a moment please ...") + self.screen.tracer(True) + + def display(self, msg1, msg2=None): + self.screen.tracer(False) + self.writer.clear() + if msg2 is not None: + self.writer.goto(0, - SCREENHEIGHT // 2 + 48) + self.writer.pencolor("red") + self.writer.write(msg2, align="center", font=("Courier",18,"bold")) + self.writer.goto(0, - SCREENHEIGHT // 2 + 20) + self.writer.pencolor("black") + self.writer.write(msg1, align="center", font=("Courier",14,"bold")) + self.screen.tracer(True) + + def setup(self): + self.screen.tracer(False) + for row in range(3): + for col in range(self.model.sticks[row]): + self.sticks[(row, col)].color(SCOLOR) + for row in range(3): + for col in range(self.model.sticks[row], MAXSTICKS): + self.sticks[(row, col)].color("white") + self.display("Your turn! Click leftmost stick to remove.") + self.screen.tracer(True) + + def notify_move(self, row, col, maxspalte, player): + if player == 0: + farbe = HCOLOR + for s in range(col, maxspalte): + self.sticks[(row, s)].color(farbe) + else: + self.display(" ... thinking ... ") + time.sleep(0.5) + self.display(" ... thinking ... aaah ...") + farbe = COLOR + for s in range(maxspalte-1, col-1, -1): + time.sleep(0.2) + self.sticks[(row, s)].color(farbe) + self.display("Your turn! Click leftmost stick to remove.") + + def notify_over(self): + if self.game.model.winner == 0: + msg2 = "Congrats. You're the winner!!!" + else: + msg2 = "Sorry, the computer is the winner." + self.display("To play again press space bar. To leave press ESC.", msg2) + + def clear(self): + if self.game.state == Nim.OVER: + self.screen.clear() + + +class NimController(object): + + def __init__(self, game): + self.game = game + self.sticks = game.view.sticks + self.BUSY = False + for stick in self.sticks.values(): + stick.onclick(stick.makemove) + self.game.screen.onkey(self.game.model.setup, "space") + self.game.screen.onkey(self.game.view.clear, "Escape") + self.game.view.display("Press space bar to start game") + self.game.screen.listen() + + def notify_move(self, row, col): + if self.BUSY: + return + self.BUSY = True + self.game.model.notify_move(row, col) + self.BUSY = False + + +class Nim(object): + CREATED = 0 + RUNNING = 1 + OVER = 2 + def __init__(self, screen): + self.state = Nim.CREATED + self.screen = screen + self.model = NimModel(self) + self.view = NimView(self) + self.controller = NimController(self) + + +def main(): + mainscreen = turtle.Screen() + mainscreen.mode("standard") + mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) + nim = Nim(mainscreen) + return "EVENTLOOP" + +if __name__ == "__main__": + main() + turtle.mainloop()