Debian Codegraph @

src/BWAWrapper.cpp

raw symbols SCIP
1 /*
2 A significant portion of this code is derived from Heng Li's BWA
3 repository: https://github.com/lh3/bwa
4
5 BWA is copyrighted by Heng Li with the Apache2 License
6
7 */
8
9 #include "SeqLib/BWAWrapper.h"
10
11 #include <stdexcept>
12 #include <sstream>
13 #include <iostream>
14
15 extern "C" {
16 #include <string.h>
17 }
18
19 // custom sort
20 bool aln_sort(const mem_aln_t& lhs, const mem_aln_t& rhs)
21 {
22 if (lhs.mapq > rhs.mapq) //want descending order of mapq
23 return true;
24 else if (lhs.mapq < rhs.mapq)
25 return false;
26 // break tied mapq with position
27 if (lhs.rid < rhs.rid)
28 return true;
29 else if (lhs.rid > rhs.rid)
30 return false;
31 if (lhs.pos < rhs.pos)
32 return true;
33 else if (lhs.pos > rhs.pos)
34 return false;
35 return false;
36 }
37
38 //#define DEBUG_BWATOOLS 1
39
40 #define _set_pac(pac, l, c) ((pac)[(l)>>2] |= (c)<<((~(l)&3)<<1))
41 #define _get_pac(pac, l) ((pac)[(l)>>2]>>((~(l)&3)<<1)&3)
42
43 namespace SeqLib {
44
45 int BWAWrapper::NumSequences() const {
46
47 if (!idx)
48 return 0;
49
50 return idx->bns->n_seqs;
51
52 }
53
54 std::string BWAWrapper::ChrIDToName(int id) const {
55
56 if (!idx)
57 throw std::runtime_error("Index has not be loaded / constructed");
58 if (id < 0 || id >= idx->bns->n_seqs)
59 throw std::out_of_range("BWAWrapper::ChrIDToName - id out of bounds of refs in index for id of " + tostring(id) + " on IDX of size " + tostring(idx->bns->n_seqs));
60
61 return std::string(idx->bns->anns[id].name);
62 }
63
64 BamHeader BWAWrapper::HeaderFromIndex() const
65 {
66
67 std::string my_hdr = bwa_print_sam_hdr2(idx->bns, "");
68
69 BamHeader hdr(my_hdr);
70 //bam_hdr_t * hdr = bam_hdr_init();
71 //bam_hdr_t * hdr = sam_hdr_read2(my_hdr);
72 //hdr->n_targets = idx->bns->n_seqs;
73 //hdr->target_name = (char**)malloc(hdr->n_targets * sizeof(char*));
74 //for (int i = 0; i < idx->bns->n_seqs; ++i) {
75 // hdr->target_name[i] = (char*)malloc( (strlen(idx->bns->anns[i].name) + 1) * sizeof(char));
76 // strcpy(hdr->target_name[i], idx->bns->anns[i].name);
77 //}
78 return hdr;
79 }
80
81 std::string BWAWrapper::bwa_print_sam_hdr2(const bntseq_t *bns, const char *hdr_line) const
82 {
83 std::string out;
84 int i, n_SQ = 0;
85 //extern char *bwa_pg;
86 if (hdr_line) {
87 const char *p = hdr_line;
88 while ((p = strstr(p, "@SQ\t")) != 0) {
89 if (p == hdr_line || *(p-1) == '\n') ++n_SQ;
90 p += 4;
91 }
92 }
93
94 //JEREMIAH
95 // get makx size
96 size_t max_s = 0;
97 for (i = 0; i < bns->n_seqs; ++i)
98 max_s = std::max(strlen(bns->anns[i].name), max_s);
99
100 if (n_SQ == 0) {
101 char buffer[max_s + 30];
102 for (i = 0; i < bns->n_seqs; ++i) {
103 //err_printf("@SQ\tSN:%s\tLN:%d\n", bns->anns[i].name, bns->anns[i].len);
104 sprintf(buffer, "@SQ\tSN:%s\tLN:%d\n", bns->anns[i].name, bns->anns[i].len);
105 out.append(buffer);
106 }
107 } else if (n_SQ != bns->n_seqs && bwa_verbose >= 2)
108 fprintf(stderr, "[W::%s] %d @SQ lines provided with -H; %d sequences in the index. Continue anyway.\n", __func__, n_SQ, bns->n_seqs);
109
110 if (hdr_line) { char buffer[200]; sprintf(buffer, "%s\n", hdr_line); out.append(buffer); } //err_printf("%s\n", hdr_line);
111 //if (bwa_pg) { char buffer[100]; sprintf(buffer, "%s\n", bwa_pg); out.append(buffer); } // err_printf("%s\n", bwa_pg);
112
113 return out;
114 }
115
116
117
118 void BWAWrapper::ConstructIndex(const UnalignedSequenceVector& v) {
119
120 if (!v.size())
121 return;
122
123 // check the integrity of the input data
124 for (UnalignedSequenceVector::const_iterator i = v.begin(); i != v.end(); ++i)
125 if (i->Name.empty() || i->Seq.empty())
126 throw std::invalid_argument("BWAWrapper::constructIndex - Reference sequences must have non-empty name and seq");
127
128 if (idx) {
129 std::cerr << "...clearing old index" << std::endl;
130 bwa_idx_destroy(idx);
131 idx = 0;
132 }
133
134 // allocate memory for idx
135 idx = (bwaidx_t*)calloc(1, sizeof(bwaidx_t));;
136
137 // construct the forward-only pac
138 uint8_t* fwd_pac = seqlib_make_pac(v, true); //true->for_only
139
140 // construct the forward-reverse pac ("packed" 2 bit sequence)
141 uint8_t* pac = seqlib_make_pac(v, false); // don't write, becasue only used to make BWT
142
143 size_t tlen = 0;
144 for (UnalignedSequenceVector::const_iterator i = v.begin(); i != v.end(); ++i)
145 tlen += i->Seq.length();
146
147 #ifdef DEBUG_BWATOOLS
148 std::cerr << "ref seq length: " << tlen << std::endl;
149 #endif
150
151 // make the bwt
152 bwt_t *bwt;
153 bwt = seqlib_bwt_pac2bwt(pac, tlen*2); // *2 for fwd and rev
154 bwt_bwtupdate_core(bwt);
155 free(pac); // done with fwd-rev pac
156
157 // construct sa from bwt and occ. adds it to bwt struct
158 bwt_cal_sa(bwt, 32);
159 bwt_gen_cnt_table(bwt);
160
161 // make the bns
162 bntseq_t * bns = (bntseq_t*) calloc(1, sizeof(bntseq_t));
163 bns->l_pac = tlen;
164 bns->n_seqs = v.size();
165 bns->seed = 11;
166 bns->n_holes = 0;
167
168 // make the anns
169 bns->anns = (bntann1_t*)calloc(v.size(), sizeof(bntann1_t));
170 size_t offset = 0;
171 for (size_t k = 0; k < v.size(); ++k) {
172 seqlib_add_to_anns(v[k].Name, v[k].Seq, &bns->anns[k], offset);
173 offset += v[k].Seq.length();
174 }
175
176 //ambs is "holes", like N bases
177 bns->ambs = 0; //(bntamb1_t*)calloc(1, sizeof(bntamb1_t));
178
179 // make the in-memory idx struct
180 idx->bwt = bwt;
181 idx->bns = bns;
182 idx->pac = fwd_pac;
183
184 return;
185
186 }
187
188 void BWAWrapper::SetGapOpen(int gap_open) {
189 if (gap_open < 0)
190 throw std::invalid_argument("BWAWrapper::SetGapOpen - gap_open must be >= zero");
191 memopt->o_del = memopt->o_ins = gap_open;
192 }
193
194 void BWAWrapper::SetGapExtension(int gap_ext) {
195 if (gap_ext < 0)
196 throw std::invalid_argument("BWAWrapper::SetGapExtension - gap extension must be >= zero");
197 memopt->e_del = memopt->e_ins = gap_ext;
198 }
199
200 void BWAWrapper::SetMismatchPenalty(int m) {
201 if (m < 0)
202 throw std::invalid_argument("BWAWrapper::SetMismatchPenalty - mismatch must be >= zero");
203 memopt->b = m;
204
205 bwa_fill_scmat(memopt->a, memopt->b, memopt->mat);
206 }
207
208 void BWAWrapper::SetZDropoff(int z) {
209 if (z < 0)
210 throw std::invalid_argument("BWAWrapper::SetZDropoff - dropoff must be >= zero");
211 memopt->zdrop = z;
212 }
213
214 void BWAWrapper::SetAScore(int a) {
215 if (a < 0)
216 throw std::invalid_argument("BWAWrapper::SetAScore - dropoff must be >= zero");
217 memopt->b *= a;
218 memopt->T *= a;
219 memopt->o_del *= a;
220 memopt->o_ins *= a;
221 memopt->e_del *= a;
222 memopt->e_ins *= a;
223 memopt->zdrop *= a;
224 memopt->pen_clip5 *= a;
225 memopt->pen_clip3 *= a;
226 memopt->pen_unpaired *= a;
227 memopt->a = a;
228 }
229
230
231 void BWAWrapper::Set3primeClippingPenalty(int p) {
232 if (p < 0)
233 throw std::invalid_argument("BWAWrapper::Set3primeClippingPenalty - penalty must be >= zero");
234 memopt->pen_clip3 = p;
235 }
236
237 void BWAWrapper::Set5primeClippingPenalty(int p) {
238 if (p < 0)
239 throw std::invalid_argument("BWAWrapper::Set5primeClippingPenalty - penalty must be >= zero");
240 memopt->pen_clip5 = p;
241 }
242
243 void BWAWrapper::SetBandwidth(int w) {
244 if (w < 0)
245 throw std::invalid_argument("BWAWrapper::SetBandwidth - bandwidth must be >= zero");
246 memopt->w = w;
247 }
248
249 void BWAWrapper::SetReseedTrigger(float r) {
250 if (r < 0)
251 throw std::invalid_argument("BWAWrapper::SetReseedTrigger - reseed trigger must be >= zero");
252 memopt->split_factor = r;
253 }
254
255 void BWAWrapper::AlignSequence(const std::string& seq, const std::string& name, BamRecordVector& vec, bool hardclip,
256 double keep_sec_with_frac_of_primary_score, int max_secondary) const {
257
258 // we haven't made an index, just return
259 if (!idx)
260 return;
261
262 mem_alnreg_v ar;
263 ar = mem_align1(memopt, idx->bwt, idx->bns, idx->pac, seq.length(), seq.data()); // get all the hits (was c_str())
264
265 #ifdef DEBUG_BWATOOLS
266 std::cerr << "num hits: " << ar.n << " " << name << std::endl;
267 size_t secondary_count_debug = 0;
268 for (size_t i = 0; i < ar.n; ++i) {
269 if (ar.a[i].secondary >= 0)
270 secondary_count_debug++;
271 }
272 std::cerr << "secondary count " << secondary_count_debug << std::endl;
273 }
274 #endif
275
276 double primary_score = 0;
277
278 int secondary_count = 0;
279
280 //setup a vector to store the hits. Why remake a vector? Because
281 //I want them to be in the same order for all runs. With BWA multithreading,
282 //it may not be so in the initial ar.a vector.
283 std::vector<mem_aln_t> a;
284
285 //size_t num_secondary = 0;
286 // loop through the hits
287 for (size_t i = 0; i < ar.n; ++i) {
288
289 if (ar.a[i].secondary >= 0 && (keep_sec_with_frac_of_primary_score < 0 || keep_sec_with_frac_of_primary_score > 1))
290 continue; // skip secondary alignments
291
292 // get forward-strand position and CIGAR
293 mem_aln_t a_aln;
294
295 a_aln = mem_reg2aln(memopt, idx->bns, idx->pac, seq.length(), seq.c_str(), &ar.a[i]);
296
297 a.push_back(a_aln);
298 }
299
300 // sort it
301 std::sort(a.begin(), a.end(), aln_sort);
302
303 for (size_t i = 0; i < a.size(); ++i) {
304
305 // if score not sufficient or past cap, continue
306 //bool sec_and_low_score = ar.a[i].secondary >= 0 && (primary_score * keep_sec_with_frac_of_primary_score) > a.score;
307 //bool sec_and_cap_hit = ar.a[i].secondary >= 0 && (int)i > max_secondary;
308 bool sec_and_low_score = (a[i].flag&BAM_FSECONDARY) && (primary_score * keep_sec_with_frac_of_primary_score) > a[i].score;
309 bool sec_and_cap_hit = (a[i].flag&BAM_FSECONDARY) && (int)i > max_secondary;
310 if (sec_and_low_score || sec_and_cap_hit) {
311 free(a[i].cigar);
312 continue;
313 } else if (!(a[i].flag&BAM_FSECONDARY)) {
314 primary_score = a[i].score;
315 //num_secondary = 0;
316 }
317
318 // instantiate the read
319 BamRecord b;
320 b.init();
321
322 b.b->core.tid = a[i].rid;
323 b.b->core.pos = a[i].pos;
324 b.b->core.qual = a[i].mapq;
325 b.b->core.flag = a[i].flag;
326 b.b->core.n_cigar = a[i].n_cigar;
327
328 // set dumy mate
329 b.b->core.mtid = -1;
330 b.b->core.mpos = -1;
331 b.b->core.isize = 0;
332
333 // if alignment is reverse, set it
334 if (a[i].is_rev)
335 b.b->core.flag |= BAM_FREVERSE;
336
337 std::string new_seq = seq;
338 // if hardclip, figure out what to clip
339 if (hardclip) {
340 size_t tstart = 0;
341 size_t len = 0;
342 for (int i = 0; i < a[i].n_cigar; ++i) {
343 if (i == 0 && bam_cigar_op(a[i].cigar[i]) == BAM_CREF_SKIP) // first N (e.g. 20N50M)
344 tstart = bam_cigar_oplen(a[i].cigar[i]);
345 else if (bam_cigar_type(bam_cigar_op(a[i].cigar[i]))&1) // consumes query, but not N
346 len += bam_cigar_oplen(a[i].cigar[i]);
347 }
348 assert(len > 0);
349 assert(tstart + len <= seq.length());
350 new_seq = seq.substr(tstart, len);
351 }
352
353 // allocate all the data
354 b.b->core.l_qname = name.length() + 1;
355 b.b->core.l_qseq = new_seq.length(); //(seq.length()>>1) + seq.length() % 2; // 4-bit encoding
356 b.b->l_data = b.b->core.l_qname + (a[i].n_cigar<<2) + ((b.b->core.l_qseq+1)>>1) + (b.b->core.l_qseq);
357 b.b.get()->data = (uint8_t*)malloc(b.b.get()->l_data);
358
359 // allocate the qname
360 memcpy(b.b->data, name.c_str(), name.length() + 1);
361
362 // allocate the cigar. Reverse if aligned to neg strand, since mem_aln_t stores
363 // cigars relative to referemce string oreiatnion, not forward alignment
364 memcpy(b.b->data + b.b->core.l_qname, (uint8_t*)a[i].cigar, a[i].n_cigar<<2);
365
366 // convert N to S or H
367 int new_val = hardclip ? BAM_CHARD_CLIP : BAM_CSOFT_CLIP;
368 uint32_t * cigr = bam_get_cigar(b.b);
369 for (int k = 0; k < b.b->core.n_cigar; ++k) {
370 if ( (cigr[k] & BAM_CIGAR_MASK) == BAM_CREF_SKIP) {
371 cigr[k] &= ~BAM_CIGAR_MASK;
372 cigr[k] |= new_val;
373 }
374 }
375
376 // allocate the sequence
377 uint8_t* m_bases = b.b->data + b.b->core.l_qname + (b.b->core.n_cigar<<2);
378
379 // TODO move this out of bigger loop
380 int slen = new_seq.length();
381 int j = 0;
382 if (a[i].is_rev) {
383 for (int i = slen-1; i >= 0; --i) {
384
385 // bad idea but works for now
386 // this is REV COMP things
387 uint8_t base = 15;
388 if (new_seq.at(i) == 'T')
389 base = 1;
390 else if (new_seq.at(i) == 'G')
391 base = 2;
392 else if (new_seq.at(i) == 'C')
393 base = 4;
394 else if (new_seq.at(i) == 'A')
395 base = 8;
396
397 m_bases[j >> 1] &= ~(0xF << ((~j & 1) << 2)); ///< zero out previous 4-bit base encoding
398 m_bases[j >> 1] |= base << ((~j & 1) << 2); ///< insert new 4-bit base encoding
399 ++j;
400 }
401 } else {
402 for (int i = 0; i < slen; ++i) {
403 // bad idea but works for now
404 uint8_t base = 15;
405 if (new_seq.at(i) == 'A')
406 base = 1;
407 else if (new_seq.at(i) == 'C')
408 base = 2;
409 else if (new_seq.at(i) == 'G')
410 base = 4;
411 else if (new_seq.at(i) == 'T')
412 base = 8;
413
414 m_bases[i >> 1] &= ~(0xF << ((~i & 1) << 2)); ///< zero out previous 4-bit base encoding
415 m_bases[i >> 1] |= base << ((~i & 1) << 2); ///< insert new 4-bit base encoding
416
417 }
418 }
419
420 // allocate the quality to NULL
421 uint8_t* s = bam_get_qual(b.b);
422 s[0] = 0xff;
423
424 b.AddIntTag("NA", ar.n); // number of matches
425 b.AddIntTag("NM", a[i].NM);
426
427 if (a[i].XA)
428 b.AddZTag("XA", std::string(a[i].XA));
429
430 // add num sub opt
431 //b.AddIntTag("SB", ar.a[i].sub_n);
432 b.AddIntTag("AS", a[i].score);
433
434 // count num secondaries
435 if (b.SecondaryFlag())
436 ++secondary_count;
437
438 vec.push_back(b);
439
440 #ifdef DEBUG_BWATOOLS
441 // print alignment
442 printf("\t%c\t%s\t%ld\t%d\t", "+-"[a[i].is_rev], idx->bns->anns[a[i].rid].name, (long)a[i].pos, a[i].mapq);
443 for (int k = 0; k < a[i].n_cigar; ++k) // print CIGAR
444 printf("%d%c", a[i].cigar[k]>>4, "MIDSH"[a[i].cigar[k]&0xf]);
445 printf("\t%d\n", a[i].NM); // print edit distance
446 #endif
447
448 free(a[i].cigar); // don't forget to deallocate CIGAR
449 }
450
451 free (ar.a); // dealloc the hit list
452
453 // add the secondary counts
454 for (BamRecordVector::iterator i = vec.begin(); i != vec.end(); ++i)
455 i->AddIntTag("SQ", secondary_count);
456
457 }
458
459 void BWAWrapper::AlignSequence(const UnalignedSequence& us, BamRecordVector& vec, bool hardclip,
460 double keep_sec_with_frac_of_primary_score, int max_secondary) const{
461 // call overloaded AlignSequence to do alignment
462 AlignSequence(us.Seq, us.Name, vec, hardclip, keep_sec_with_frac_of_primary_score, max_secondary);
463 // append FASTA/Q comment to SAM output if needed
464 for (BamRecordVector::iterator i = vec.begin(); i != vec.end(); ++i)
465 if (copy_comment)
466 i->AddZTag("BC", us.Com);
467 }
468
469 // modified from bwa (heng li)
470 uint8_t* BWAWrapper::seqlib_add1(const kseq_t *seq, bntseq_t *bns, uint8_t *pac, int64_t *m_pac, int *m_seqs, int *m_holes, bntamb1_t **q)
471 {
472 bntann1_t *p;
473 int lasts;
474 if (bns->n_seqs == *m_seqs) {
475 *m_seqs <<= 1;
476 bns->anns = (bntann1_t*)realloc(bns->anns, *m_seqs * sizeof(bntann1_t));
477 }
478 p = bns->anns + bns->n_seqs;
479 p->name = strdup((char*)seq->name.s);
480 p->anno = seq->comment.l > 0? strdup((char*)seq->comment.s) : strdup("(null)");
481 p->gi = 0; p->len = seq->seq.l;
482 p->offset = (bns->n_seqs == 0)? 0 : (p-1)->offset + (p-1)->len;
483 p->n_ambs = 0;
484 for (size_t i = lasts = 0; i < seq->seq.l; ++i) {
485 int c = nst_nt4_table[(int)seq->seq.s[i]];
486 if (c >= 4) { // N
487 if (lasts == seq->seq.s[i]) { // contiguous N
488 ++(*q)->len;
489 } else {
490 if (bns->n_holes == *m_holes) {
491 (*m_holes) <<= 1;
492 bns->ambs = (bntamb1_t*)realloc(bns->ambs, (*m_holes) * sizeof(bntamb1_t));
493 }
494 *q = bns->ambs + bns->n_holes;
495 (*q)->len = 1;
496 (*q)->offset = p->offset + i;
497 (*q)->amb = seq->seq.s[i];
498 ++p->n_ambs;
499 ++bns->n_holes;
500 }
501 }
502 lasts = seq->seq.s[i];
503 { // fill buffer
504 if (c >= 4) c = lrand48()&3;
505 if (bns->l_pac == *m_pac) { // double the pac size
506 *m_pac <<= 1;
507 pac = (uint8_t*)realloc(pac, *m_pac/4);
508 memset(pac + bns->l_pac/4, 0, (*m_pac - bns->l_pac)/4);
509 }
510 _set_pac(pac, bns->l_pac, c);
511 ++bns->l_pac;
512 }
513 }
514 ++bns->n_seqs;
515
516 return pac;
517 }
518
519 // modified from bwa (heng li)
520 uint8_t* BWAWrapper::seqlib_make_pac(const UnalignedSequenceVector& v, bool for_only)
521 {
522
523 bntseq_t * bns = (bntseq_t*)calloc(1, sizeof(bntseq_t));
524 uint8_t *pac = 0;
525 int32_t m_seqs, m_holes;
526 int64_t m_pac, l;
527 bntamb1_t *q;
528
529 bns->seed = 11; // fixed seed for random generator
530 m_seqs = m_holes = 8; m_pac = 0x10000;
531 bns->anns = (bntann1_t*)calloc(m_seqs, sizeof(bntann1_t));
532 bns->ambs = (bntamb1_t*)calloc(m_holes, sizeof(bntamb1_t));
533 pac = (uint8_t*) calloc(m_pac/4, 1);
534 q = bns->ambs;
535
536 // move through the unaligned sequences
537 for (size_t k = 0; k < v.size(); ++k) {
538
539 // make the ref name kstring
540 kstring_t * name = (kstring_t*)malloc(1 * sizeof(kstring_t));
541 name->l = v[k].Name.length() + 1;
542 name->m = v[k].Name.length() + 3;
543 name->s = (char*)calloc(name->m, sizeof(char));
544 memcpy(name->s, v[k].Name.c_str(), v[k].Name.length()+1);
545
546 // make the sequence kstring
547 kstring_t * t = (kstring_t*)malloc(sizeof(kstring_t));
548 t->l = v[k].Seq.length();
549 t->m = v[k].Seq.length() + 2;
550 //t->s = (char*)calloc(v[k].Seq.length(), sizeof(char));
551 t->s = (char*)malloc(t->m);
552 memcpy(t->s, v[k].Seq.c_str(), v[k].Seq.length());
553
554 // put into a kstring
555 kseq_t *ks = (kseq_t*)calloc(1, sizeof(kseq_t));
556 ks->seq = *t;
557 ks->name = *name;
558
559 // make the forward only pac
560 pac = seqlib_add1(ks, bns, pac, &m_pac, &m_seqs, &m_holes, &q);
561
562 // clear it out
563 free(name->s);
564 free(name);
565 free(t->s);
566 free(t);
567 //free(ks->name.s);
568 //free(ks->seq.s);
569 //free(ks->f->buf);
570 //free(
571 free(ks);
572 // NOTE free kstring_t?
573 //kseq_destroy(s);
574 }
575
576 if (!for_only)
577 {
578 // add the reverse complemented sequence
579 m_pac = (bns->l_pac * 2 + 3) / 4 * 4;
580 pac = (uint8_t*)realloc(pac, m_pac/4);
581 memset(pac + (bns->l_pac+3)/4, 0, (m_pac - (bns->l_pac+3)/4*4) / 4);
582 for (l = bns->l_pac - 1; l >= 0; --l, ++bns->l_pac)
583 _set_pac(pac, bns->l_pac, 3-_get_pac(pac, l));
584 }
585
586 bns_destroy(bns);
587
588 return pac;
589 }
590
591 // modified from bwa (heng li)
592 bwt_t *BWAWrapper::seqlib_bwt_pac2bwt(const uint8_t *pac, int bwt_seq_lenr)
593 {
594
595 bwt_t *bwt;
596 ubyte_t *buf;
597 int i;
598 //FILE *fp;
599
600 // initialization
601 bwt = (bwt_t*)calloc(1, sizeof(bwt_t));
602 bwt->seq_len = bwt_seq_lenr; //bwa_seq_len(fn_pac); //dummy
603 bwt->bwt_size = (bwt->seq_len + 15) >> 4;
604 //fp = xopen(fn_pac, "rb");
605
606 // prepare sequence
607 //pac_size = (bwt->seq_len>>2) + ((bwt->seq_len&3) == 0? 0 : 1);
608 //buf2 = (ubyte_t*)calloc(pac_size, 1);
609 //err_fread_noeof(buf2, 1, pac_size, fp);
610 //err_fclose(fp);
611 memset(bwt->L2, 0, 5 * 4);
612 buf = (ubyte_t*)calloc(bwt->seq_len + 1, 1);
613 for (i = 0; i < (int)bwt->seq_len; ++i) {
614 buf[i] = pac[i>>2] >> ((3 - (i&3)) << 1) & 3;
615 ++bwt->L2[1+buf[i]];
616 }
617 for (i = 2; i <= 4; ++i)
618 bwt->L2[i] += bwt->L2[i-1];
619 //free(buf2);
620
621 // Burrows-Wheeler Transform
622 bwt->primary = is_bwt(buf, bwt->seq_len);
623 bwt->bwt = (u_int32_t*)calloc(bwt->bwt_size, 4);
624 for (i = 0; i < (int)bwt->seq_len; ++i)
625 bwt->bwt[i>>4] |= buf[i] << ((15 - (i&15)) << 1);
626 free(buf);
627 return bwt;
628 }
629
630 // modified from bwa (heng li)
631 bntann1_t* BWAWrapper::seqlib_add_to_anns(const std::string& name, const std::string& seq, bntann1_t* ann, size_t offset)
632 {
633
634 ann->offset = offset;
635 ann->name = (char*)malloc(name.length()+1); // +1 for \0
636 strncpy(ann->name, name.c_str(), name.length()+1);
637 ann->anno = (char*)malloc(7);
638 strcpy(ann->anno, "(null)\0");
639 ann->len = seq.length();
640 ann->n_ambs = 0; // number of "holes"
641 ann->gi = 0; // gi?
642 ann->is_alt = 0;
643
644 return ann;
645 }
646
647
648 bool BWAWrapper::LoadIndex(const std::string& file)
649 {
650
651 // read in the bwa index
652 bwaidx_t* idx_new = bwa_idx_load(file.c_str(), BWA_IDX_ALL);
653
654 if (!idx_new)
655 return false;
656
657 if (idx) {
658 std::cerr << "...clearing old index" << std::endl;
659 bwa_idx_destroy(idx);
660 }
661
662 idx = idx_new;
663 return true;
664 }
665
666
667 bool BWAWrapper::WriteIndex(const std::string& index_name) const
668 {
669
670 if (!idx)
671 return false;
672
673 std::string bwt_name = index_name + ".bwt";
674 std::string sa_name = index_name + ".sa";
675 bwt_dump_bwt(bwt_name.c_str(), idx->bwt);
676 bwt_dump_sa(sa_name.c_str(), idx->bwt);
677 bns_dump(idx->bns, index_name.c_str());
678 seqlib_write_pac_to_file(index_name);
679
680 return true;
681 }
682
683 // modified from bwa (heng li)
684 void BWAWrapper::seqlib_write_pac_to_file(const std::string& file) const
685 {
686 // finalize .pac file
687 FILE *fp;
688 std::string nm = file + ".pac";
689 fp = xopen(nm.c_str(), "wb");
690 ubyte_t ct;
691 err_fwrite(idx->pac, 1, (idx->bns->l_pac>>2) + ((idx->bns->l_pac&3) == 0? 0 : 1), fp);
692
693 // the following codes make the pac file size always (l_pac/4+1+1)
694 if (idx->bns->l_pac % 4 == 0) {
695 ct = 0;
696 err_fwrite(&ct, 1, 1, fp);
697 }
698 ct = idx->bns->l_pac % 4;
699 err_fwrite(&ct, 1, 1, fp);
700
701 // close .pac file
702 err_fflush(fp);
703 err_fclose(fp);
704 }
705
706 std::ostream& operator<<(std::ostream& out, const BWAWrapper& b) {
707 out << "BNS: l_pac: " << b.idx->bns->l_pac << " n_seqs: " << b.idx->bns->n_seqs <<
708 " seed: " << b.idx->bns->seed << " n_holes " << b.idx->bns->n_holes;
709 return out;
710 }
711 }
712