Debian Codegraph @

src/third-party/sparc/sparc.cpp

raw
1 #include <pbcopper/third-party/sparc/sparc.hpp>
2
3 #include <cmath>
4 #include <cstdint>
5 #include <cstdio>
6 #include <cstdlib>
7 #include <cstring>
8 #include <ctime>
9
10 #include <algorithm>
11 #include <iostream>
12 #include <list>
13 #include <map>
14 #include <memory>
15 #include <string>
16 #include <vector>
17
18 #include <boost/container/small_vector.hpp>
19
20 namespace Sparc {
21 namespace {
22
23 struct Read
24 {
25 std::vector<uint64_t> ReadBits;
26 size_t ReadLen;
27 };
28
29 struct EdgeNode;
30 struct Node;
31
32 using PtrEdgeNode = EdgeNode*;
33 using PtrNode = Node*;
34
35 struct EdgeNode
36 {
37 uint32_t Edge = 0;
38 int32_t EdgeCov = 0;
39 size_t Len = 0;
40 PtrNode NodePtr = nullptr;
41 PtrEdgeNode NextEdge = nullptr;
42 };
43
44 struct Node
45 {
46 uint32_t Kmer = 0;
47 int64_t Score = 0;
48 uint32_t Cov = 0;
49 bool InBackbone = false;
50 PtrEdgeNode Left = nullptr;
51 PtrEdgeNode Right = nullptr;
52 PtrNode LastNode = nullptr;
53 };
54
55 struct Backbone
56 {
57 std::vector<PtrNode> Nodes;
58 std::vector<uint64_t> Covs;
59 int32_t MinCov = 0;
60 int32_t Gap = 0;
61 double Threshold = 0.0;
62 };
63
64 template <typename T>
65 struct Bucket
66 {
67 ~Bucket()
68 {
69 for (auto& item : Data) {
70 if (item) {
71 delete item;
72 }
73 }
74 }
75
76 void Add(T item) { Data.emplace_back(item); }
77
78 std::vector<T> Data;
79 };
80
81 using EdgeBucket = Bucket<PtrEdgeNode>;
82 using NodeBucket = Bucket<PtrNode>;
83
84 //left shift and right shift of shift_sz bits of the whole bit array, arr_sz is the array length
85 static inline void LShiftNB(uint64_t* bitsarr, int shift_sz, int arr_sz)
86 {
87 boost::container::small_vector<uint64_t, 10> temp_arr(arr_sz);
88 int jmp = shift_sz / 64;
89 int offset = shift_sz % 64;
90
91 for (int i = 0; i < arr_sz; ++i) {
92 if (i + jmp + 1 < arr_sz) {
93
94 uint64_t tt = 0;
95 if (offset == 0) {
96 tt = 0;
97 } else {
98 tt = (bitsarr[i + jmp + 1] >> (64 - offset));
99 }
100 temp_arr[i] = ((bitsarr[i + jmp] << offset) | tt);
101 }
102 if (i + jmp + 1 == arr_sz) {
103 temp_arr[i] = bitsarr[i + jmp] << offset;
104 }
105 if (i + jmp + 1 > arr_sz) {
106 temp_arr[i] = 0;
107 }
108 }
109
110 std::memcpy(bitsarr, temp_arr.data(), sizeof(uint64_t) * arr_sz);
111 }
112
113 static inline void RShiftNB(uint64_t* bitsarr, int shift_sz, int arr_sz)
114 {
115 boost::container::small_vector<uint64_t, 10> temp_arr(arr_sz);
116 int jmp = shift_sz / 64;
117 int offset = shift_sz % 64;
118
119 for (int i = arr_sz - 1; i >= 0; --i) {
120 if (i - jmp > 0) {
121 if (offset > 0) {
122 temp_arr[i] =
123 (bitsarr[i - jmp] >> offset) | (bitsarr[i - jmp - 1] << (64 - offset));
124 } else {
125 temp_arr[i] = bitsarr[i - jmp];
126 }
127 }
128 if (i - jmp == 0) {
129 if (offset > 0) {
130 temp_arr[i] = (bitsarr[i - jmp] >> offset);
131 } else {
132 temp_arr[i] = bitsarr[i - jmp];
133 }
134 }
135 if (i - jmp < 0) {
136 temp_arr[i] = 0;
137 }
138 }
139 std::memcpy(bitsarr, temp_arr.data(), sizeof(uint64_t) * arr_sz);
140 }
141
142 // get sub bit array from a bit array.
143 inline void GetSubArray(uint64_t* bitsarr_in, int bitsarr_len, int begin_pos, int sub_sz,
144 uint64_t* bitsarr_out)
145 {
146 if (bitsarr_len < sub_sz) {
147 throw std::runtime_error("Input Kmer too short.");
148 }
149 int rem = bitsarr_len % 32;
150
151 int arr_sz_out = sub_sz / 32 + 1;
152 if (sub_sz % 32 == 0) {
153 arr_sz_out--;
154 }
155
156 boost::container::small_vector<uint64_t, 10> temp_arr(10);
157
158 std::memset(bitsarr_out, 0, sizeof(uint64_t) * arr_sz_out);
159
160 int rem2 = (32 - rem + begin_pos) % 32;
161 int block_beg = (32 - rem + begin_pos) / 32;
162 if (rem == 0) {
163 block_beg--;
164 }
165
166 int rem3 = (32 - rem + begin_pos + sub_sz) % 32;
167 int block_end = (32 - rem + begin_pos + sub_sz) / 32;
168 if (rem3 != 0) {
169 rem3 = 32 - rem3;
170 } else {
171 block_end--;
172 }
173 if (rem == 0) {
174 block_end--;
175 }
176
177 int orig_sz = (block_end - block_beg + 1);
178 if (orig_sz > 10) {
179 throw std::runtime_error("GetSubArray, First: " + std::to_string(orig_sz));
180 }
181 std::memcpy(&temp_arr[0], &bitsarr_in[block_beg], orig_sz * sizeof(uint64_t));
182 LShiftNB(&temp_arr[0], rem2 * 2, orig_sz);
183 RShiftNB(&temp_arr[0], (rem2 + rem3) % 32 * 2, arr_sz_out);
184 if (arr_sz_out > 10) {
185 throw std::runtime_error("GetSubArray, Second: " + std::to_string(orig_sz));
186 }
187 std::memcpy(bitsarr_out, temp_arr.data(), arr_sz_out * sizeof(uint64_t));
188 }
189
190 uint64_t* Str2BitArray(const std::string& str, size_t len, uint64_t* b_str, size_t arr_sz)
191 {
192 for (size_t k = 0; k < arr_sz; ++k) {
193 b_str[k] = 0;
194 }
195 int arr_sz_needed = len / 32 + 1;
196 int rem = len % 32;
197 if (rem == 0) {
198 arr_sz_needed--;
199 }
200
201 int beg_arr_idx = arr_sz - arr_sz_needed;
202 if (rem == 0 && arr_sz_needed > 0) {
203 rem = 32;
204 }
205 for (size_t k = 0; k < len; k++) {
206 if (rem == 0) {
207 beg_arr_idx++;
208 rem = 32;
209 }
210
211 switch (str[k]) {
212 case ('A'):
213 case ('a'):
214 case ('0'):
215 b_str[beg_arr_idx] <<= 2; //LShiftNB(b_str,2,arr_sz);
216 rem--;
217 break;
218
219 case ('C'):
220 case ('c'):
221 case ('1'):
222 b_str[beg_arr_idx] <<= 2; //LShiftNB(b_str,2,arr_sz);
223 ++b_str[beg_arr_idx]; //++b_str[arr_sz-1];
224 rem--;
225 break;
226
227 case 'G':
228 case 'g':
229 case '2':
230 b_str[beg_arr_idx] <<= 1; //LShiftNB(b_str,1,arr_sz);
231 ++b_str[beg_arr_idx]; //++b_str[arr_sz-1];
232 b_str[beg_arr_idx] <<= 1; //LShiftNB(b_str,1,arr_sz);
233 rem--; //(++(b_str<<=1))<<=1;
234 break;
235
236 case 'T':
237 case 't':
238 case '3':
239 b_str[beg_arr_idx] <<= 1; //LShiftNB(b_str,1,arr_sz);
240 ++b_str[beg_arr_idx];
241 b_str[beg_arr_idx] <<= 1; //LShiftNB(b_str,1,arr_sz);
242 ++b_str[beg_arr_idx];
243 rem--;
244 break;
245 default:
246 return b_str;
247 }
248 }
249 return b_str;
250 }
251
252 //convert a std::string of nucleotide bases into bit array.
253 void InitRefRead(const std::string& seq, Read& read)
254 {
255 read.ReadLen = strlen(seq.c_str());
256 size_t Read_arr_sz = read.ReadLen / 32 + 1;
257 int rem = read.ReadLen % 32;
258 if (rem == 0) {
259 Read_arr_sz--;
260 }
261
262 Str2BitArray(seq, seq.size(), read.ReadBits.data(), Read_arr_sz);
263 }
264
265 char* BitsArray2Str(uint64_t* b_seq, int len, char* c_str)
266 {
267 constexpr int32_t maxL = 32;
268 int tot_bits = 64;
269 assert(len < maxL);
270 if (len >= maxL) throw std::runtime_error("BitsArray2Str");
271 for (int i = 0; i < len; ++i) {
272 uint64_t temp;
273 boost::container::small_vector<uint64_t, maxL> temp2(maxL);
274 temp2[0] = b_seq[0];
275 LShiftNB(temp2.data(), tot_bits - (len - i) * 2, 1);
276 RShiftNB(temp2.data(), tot_bits - 2, 1);
277 temp = temp2[0];
278 switch (temp) {
279 case 0:
280 c_str[i] = 'A';
281 break;
282 case 1:
283 c_str[i] = 'C';
284 break;
285 case 2:
286 c_str[i] = 'G';
287 break;
288 case 3:
289 c_str[i] = 'T';
290 break;
291 }
292 }
293 c_str[len] = '\0';
294 return c_str;
295 }
296
297 void ConsensusKmerGraphConstruction(struct Read* read, Backbone* backbone, int k,
298 EdgeBucket& edgeBucket, NodeBucket& nodeBucket)
299 {
300 const int readLen = read->ReadLen;
301 int overlappingKmers = readLen - k + 1;
302
303 uint64_t seq;
304
305 PtrNode previous_node = NULL;
306 PtrNode current_node = NULL;
307 backbone->Nodes.resize(overlappingKmers);
308
309 for (int j = 0; j < overlappingKmers; j++) {
310
311 previous_node = current_node;
312 GetSubArray(read->ReadBits.data(), read->ReadLen, j, k, &seq);
313
314 current_node = new Node();
315 nodeBucket.Add(current_node);
316 backbone->Nodes[j] = current_node;
317 current_node->Kmer = static_cast<uint32_t>(seq);
318 current_node->InBackbone = true;
319 current_node->Cov++;
320 if (j >= 1) {
321 //left edge,right edge
322 previous_node->Right = new EdgeNode();
323 edgeBucket.Add(previous_node->Right);
324 previous_node->Right->NodePtr = current_node;
325
326 current_node->Left = new EdgeNode();
327 edgeBucket.Add(current_node->Left);
328 current_node->Left->NodePtr = previous_node;
329 }
330 }
331 }
332
333 void ConsensusSparseKmerGraphConstruction(struct Read* read, Backbone* backbone, int k,
334 EdgeBucket& edgeBucket, NodeBucket& nodeBucket)
335 {
336 const int gap = backbone->Gap;
337
338 const int readLen = read->ReadLen;
339 const int overlappingKmers = readLen - k + 1;
340
341 uint64_t seq;
342
343 PtrNode previous_node = NULL;
344 PtrNode current_node = NULL;
345 backbone->Nodes.resize(overlappingKmers);
346
347 int last_position = -1;
348 for (int j = 0; j < overlappingKmers; j++) {
349 if (j % gap == 0) {
350
351 previous_node = current_node;
352 GetSubArray(read->ReadBits.data(), read->ReadLen, j, k, &seq);
353
354 current_node = new Node();
355 nodeBucket.Add(current_node);
356 backbone->Nodes[j] = current_node;
357 current_node->Kmer = static_cast<uint32_t>(seq);
358 current_node->InBackbone = true;
359 current_node->Cov++;
360
361 //left edge,right edge
362 uint64_t edge_bits;
363 if (j >= 1) {
364 GetSubArray(read->ReadBits.data(), read->ReadLen, last_position + k, gap,
365 &edge_bits);
366 previous_node->Right = new EdgeNode();
367 edgeBucket.Add(previous_node->Right);
368 previous_node->Right->NodePtr = current_node;
369 previous_node->Right->Edge = edge_bits;
370 previous_node->Right->Len = gap;
371
372 GetSubArray(read->ReadBits.data(), read->ReadLen, last_position, gap, &edge_bits);
373 current_node->Left = new EdgeNode();
374 edgeBucket.Add(current_node->Left);
375 current_node->Left->NodePtr = previous_node;
376 current_node->Left->Len = gap;
377 current_node->Left->Edge = edge_bits;
378 }
379 last_position = j;
380 }
381 }
382 }
383
384 void NormalizeAlignment(Query* query)
385 {
386
387 std::string qAlignedSeq_new, tAlignedSeq_new;
388 size_t seq_sz = query->qAlignedSeq.size();
389 qAlignedSeq_new.resize(2 * seq_sz);
390 tAlignedSeq_new.resize(2 * seq_sz);
391 std::string target_crop, query_crop;
392 int n_char = 0;
393 for (size_t i = 0; i < seq_sz; ++i) {
394 if (query->qAlignedSeq[i] == query->tAlignedSeq[i]) {
395 qAlignedSeq_new[n_char] = query->qAlignedSeq[i];
396 tAlignedSeq_new[n_char] = query->tAlignedSeq[i];
397 n_char++;
398 } else {
399 if (query->qAlignedSeq[i] != '-' && query->tAlignedSeq[i] != '-') {
400 tAlignedSeq_new[n_char] = query->tAlignedSeq[i];
401 n_char++;
402
403 bool replace = 0;
404 for (size_t j = i + 1; j < query->tAlignedSeq.size(); ++j) {
405 if (query->tAlignedSeq[j] != '-') {
406 if (query->tAlignedSeq[j] == query->qAlignedSeq[i]) {
407 replace = 1;
408 query->tAlignedSeq[j] = '-';
409 tAlignedSeq_new[n_char] = query->qAlignedSeq[i];
410 }
411 break;
412 }
413 }
414 if (replace == 0) {
415 tAlignedSeq_new[n_char] = '-';
416 }
417 n_char--;
418
419 qAlignedSeq_new[n_char] = '-';
420 n_char++;
421 qAlignedSeq_new[n_char] = query->qAlignedSeq[i];
422
423 n_char++;
424
425 } else {
426 if (query->qAlignedSeq[i] == '-') {
427
428 for (size_t j = i + 1; j < query->qAlignedSeq.size(); ++j) {
429 if (query->qAlignedSeq[j] != '-') {
430 if (query->qAlignedSeq[j] == query->tAlignedSeq[i]) {
431 query->qAlignedSeq[i] = query->qAlignedSeq[j];
432 query->qAlignedSeq[j] = '-';
433 }
434 break;
435 }
436 }
437
438 } else {
439
440 for (size_t j = i + 1; j < query->qAlignedSeq.size(); ++j) {
441 if (query->tAlignedSeq[j] != '-') {
442 if (query->tAlignedSeq[j] == query->qAlignedSeq[i]) {
443 query->tAlignedSeq[i] = query->tAlignedSeq[j];
444 query->tAlignedSeq[j] = '-';
445 }
446 break;
447 }
448 }
449 }
450
451 qAlignedSeq_new[n_char] = query->qAlignedSeq[i];
452 tAlignedSeq_new[n_char] = query->tAlignedSeq[i];
453 n_char++;
454 }
455 }
456 }
457 qAlignedSeq_new.resize(n_char);
458 tAlignedSeq_new.resize(n_char);
459 query->qAlignedSeq = qAlignedSeq_new;
460 query->tAlignedSeq = tAlignedSeq_new;
461 }
462
463 void AddPathToBackbone(Backbone* backbone, Query* query, int k, EdgeBucket& edgeBucket,
464 NodeBucket& nodeBucket)
465 {
466 NormalizeAlignment(query);
467
468 int target_position = query->tStart;
469 Node* previous_node = NULL;
470 Node* current_node = NULL;
471 int MatchPosition = -100;
472 int32_t backboneLength = backbone->Nodes.size();
473
474 for (size_t i = 0; i + k <= query->qAlignedSeq.size(); ++i) {
475 if (query->qAlignedSeq[i] == '-') {
476 MatchPosition = -1;
477 if (query->tAlignedSeq[i] != '-') {
478 target_position++;
479 }
480 continue;
481 }
482 MatchPosition = target_position;
483 for (int j = 0; j < k; ++j) {
484 if (query->qAlignedSeq[i + j] != query->tAlignedSeq[i + j]) {
485 MatchPosition = -1;
486 break;
487 }
488 }
489
490 std::string KmerStr;
491 KmerStr.resize(k);
492 int KmerSize = 0;
493 for (size_t j = i; j < query->qAlignedSeq.size(); ++j) {
494 if (query->qAlignedSeq[j] != '-') {
495 KmerStr[KmerSize] = query->qAlignedSeq[j];
496 KmerSize++;
497 }
498 if (KmerSize == k) {
499 break;
500 }
501 }
502 if (KmerSize != k) {
503 break;
504 }
505 uint64_t seq = 0;
506 Str2BitArray(KmerStr, k, &seq, 1);
507
508 if (MatchPosition >= backboneLength) {
509 break;
510 }
511 if (MatchPosition >= 0) {
512 current_node = backbone->Nodes[MatchPosition];
513
514 if (previous_node != NULL) {
515 current_node->Cov++;
516 }
517
518 //link previous node to the current one
519
520 if (previous_node != NULL) {
521
522 PtrEdgeNode* edge_p2p = &(previous_node->Right);
523
524 while (*edge_p2p != NULL) {
525
526 if ((*edge_p2p)->NodePtr == current_node) {
527 (*edge_p2p)->EdgeCov++;
528
529 break;
530 }
531
532 edge_p2p = &((*edge_p2p)->NextEdge);
533 }
534
535 if (*edge_p2p == NULL) {
536
537 (*edge_p2p) = new EdgeNode();
538 edgeBucket.Add(*edge_p2p);
539 (*edge_p2p)->NextEdge = NULL;
540 (*edge_p2p)->NodePtr = current_node;
541 (*edge_p2p)->EdgeCov++;
542 }
543
544 edge_p2p = &(current_node->Left);
545 while (*edge_p2p != NULL) {
546 if ((*edge_p2p)->NodePtr == previous_node) {
547 (*edge_p2p)->EdgeCov++;
548
549 break;
550 }
551 edge_p2p = &((*edge_p2p)->NextEdge);
552 }
553 if (*edge_p2p == NULL) {
554 (*edge_p2p) = new EdgeNode();
555 edgeBucket.Add(*edge_p2p);
556 (*edge_p2p)->NextEdge = NULL;
557 (*edge_p2p)->NodePtr = previous_node;
558 (*edge_p2p)->EdgeCov++;
559 }
560 }
561
562 } else {
563
564 //link previous node to the current one
565
566 if (previous_node == NULL) {
567 current_node = new Node();
568 nodeBucket.Add(current_node);
569 current_node->Kmer = static_cast<uint32_t>(seq);
570 current_node->Cov++;
571 previous_node = current_node;
572 } else {
573
574 PtrEdgeNode* edge_p2p = &(previous_node->Right);
575 while (*edge_p2p != NULL) {
576 if ((*edge_p2p)->NodePtr->Kmer == static_cast<uint32_t>(seq) &&
577 (*edge_p2p)->NodePtr->InBackbone == 0) {
578 (*edge_p2p)->EdgeCov++;
579 current_node = (*edge_p2p)->NodePtr;
580 current_node->Cov++;
581
582 break;
583 }
584 edge_p2p = &((*edge_p2p)->NextEdge);
585 }
586
587 if (*edge_p2p == NULL) {
588 (*edge_p2p) = new EdgeNode();
589 edgeBucket.Add(*edge_p2p);
590 (*edge_p2p)->NextEdge = NULL;
591 current_node = new Node();
592 nodeBucket.Add(current_node);
593 current_node->Kmer = static_cast<uint32_t>(seq);
594 current_node->Cov++;
595 (*edge_p2p)->NodePtr = current_node;
596
597 (*edge_p2p)->EdgeCov++;
598 }
599 //link current node to previous
600 edge_p2p = &(current_node->Left);
601 while (*edge_p2p != NULL) {
602 if ((*edge_p2p)->NodePtr->Kmer == previous_node->Kmer) {
603 (*edge_p2p)->EdgeCov++;
604 break;
605 }
606 edge_p2p = &((*edge_p2p)->NextEdge);
607 }
608 if (*edge_p2p == NULL) {
609 (*edge_p2p) = new EdgeNode();
610 edgeBucket.Add(*edge_p2p);
611 (*edge_p2p)->NextEdge = NULL;
612 (*edge_p2p)->NodePtr = previous_node;
613 (*edge_p2p)->EdgeCov++;
614 }
615 }
616 }
617
618 previous_node = current_node;
619
620 if (query->tAlignedSeq[i] != '-') {
621 target_position++;
622 }
623 }
624 }
625
626 void BFSFindBestPath(Backbone* backbone, int node_idx)
627 {
628 PtrNode begin_node = backbone->Nodes[node_idx];
629 std::list<PtrNode> node_list;
630 node_list.push_back(begin_node);
631 int max_cov = backbone->Covs[node_idx];
632 while (node_list.size() > 0) {
633 PtrNode current_node = node_list.front();
634 node_list.pop_front();
635 PtrEdgeNode edge_ptr = current_node->Right;
636 while (edge_ptr != NULL) {
637 bool update = 0;
638 int new_score = 0;
639 if (backbone->Threshold < 0.0) {
640 new_score =
641 (current_node->Score + std::max(edge_ptr->EdgeCov - backbone->MinCov, -2));
642 if (edge_ptr->NodePtr->Score < new_score) {
643 update = 1;
644 }
645 } else {
646 int threshold =
647 std::max(static_cast<int32_t>(std::round((max_cov * backbone->Threshold))),
648 backbone->MinCov);
649 new_score = (current_node->Score + edge_ptr->EdgeCov - threshold);
650 if (edge_ptr->NodePtr->Score < new_score) {
651 update = 1;
652 }
653 }
654
655 if (update) {
656 edge_ptr->NodePtr->Cov = current_node->Cov + 1;
657
658 edge_ptr->NodePtr->Score = new_score;
659
660 edge_ptr->NodePtr->LastNode = current_node;
661 if (!edge_ptr->NodePtr->InBackbone) {
662 node_list.push_back(edge_ptr->NodePtr);
663 }
664 }
665
666 edge_ptr = edge_ptr->NextEdge;
667 }
668 }
669 }
670
671 void BFSFindBestPathSparse(Backbone* backbone, int node_idx)
672 {
673 PtrNode begin_node = backbone->Nodes[node_idx];
674 std::list<PtrNode> node_list;
675 node_list.push_back(begin_node);
676 int max_cov = backbone->Covs[node_idx];
677 while (node_list.size() > 0) {
678 PtrNode current_node = node_list.front();
679 node_list.pop_front();
680 PtrEdgeNode edge_ptr = current_node->Right;
681
682 while (edge_ptr != NULL) {
683 bool update = 0;
684
685 int new_score = 0;
686
687 if (backbone->Threshold < 0.0) {
688 new_score = current_node->Score +
689 edge_ptr->Len * std::max(edge_ptr->EdgeCov - backbone->MinCov, -2);
690 if (edge_ptr->NodePtr->Score < new_score) {
691 update = 1;
692 }
693 } else {
694 int threshold =
695 std::max(static_cast<int32_t>(std::round((max_cov * backbone->Threshold))),
696 backbone->MinCov);
697 new_score = (current_node->Score + edge_ptr->Len * (edge_ptr->EdgeCov - threshold));
698 if (edge_ptr->NodePtr->Score < new_score) {
699 update = 1;
700 }
701 }
702
703 if (update) {
704 edge_ptr->NodePtr->Cov = current_node->Cov + 1;
705 edge_ptr->NodePtr->Score = new_score;
706
707 edge_ptr->NodePtr->LastNode = current_node;
708 if (!edge_ptr->NodePtr->InBackbone) {
709 node_list.push_back(edge_ptr->NodePtr);
710 }
711 }
712
713 edge_ptr = edge_ptr->NextEdge;
714 }
715 }
716 }
717
718 void FindBestPath(Backbone* backbone)
719 {
720 backbone->Nodes[0]->Cov = 1; //depth
721 for (size_t i = 0; i + 1 < backbone->Nodes.size(); ++i) {
722
723 BFSFindBestPath(backbone, i);
724
725 PtrEdgeNode edge_ptr = backbone->Nodes[i]->Right;
726 std::map<uint64_t, PtrNode> node_map;
727 std::map<PtrNode, int> node_cov;
728 while (edge_ptr != NULL) {
729 edge_ptr = edge_ptr->NextEdge;
730 }
731
732 node_map.clear();
733 node_cov.clear();
734
735 edge_ptr = backbone->Nodes[i]->Left;
736 while (edge_ptr != NULL) {
737 edge_ptr = edge_ptr->NextEdge;
738 }
739 }
740 }
741
742 void FindBestPathSparse(Backbone* backbone)
743 {
744 backbone->Nodes[0]->Cov = 1; //depth
745 for (size_t i = 0; i + 1 < backbone->Nodes.size(); ++i) {
746 if (backbone->Nodes[i] == NULL) {
747 continue;
748 }
749
750 BFSFindBestPathSparse(backbone, i);
751
752 PtrEdgeNode edge_ptr = backbone->Nodes[i]->Right;
753 std::map<uint64_t, PtrNode> node_map;
754 std::map<PtrNode, int> node_cov;
755 while (edge_ptr != NULL) {
756 edge_ptr = edge_ptr->NextEdge;
757 }
758
759 node_map.clear();
760 node_cov.clear();
761
762 edge_ptr = backbone->Nodes[i]->Left;
763 while (edge_ptr != NULL) {
764 edge_ptr = edge_ptr->NextEdge;
765 }
766 }
767 }
768 void AddPathToBackboneSparse(Backbone& bb, Query& qq, size_t k, EdgeBucket& edgeBucket,
769 NodeBucket& nodeBucket)
770 {
771 int gap = bb.Gap;
772
773 std::string t1, q1;
774 NormalizeAlignment(&qq);
775 std::string t2, q2;
776
777 PtrNode current_node = NULL;
778 int qStart = -1;
779 std::vector<bool> matched;
780 matched.resize(qq.qAlignedSeq.size());
781 std::vector<int> Align2Backbone, Align2Query, Query2Align;
782
783 Align2Backbone.resize(qq.qAlignedSeq.size());
784 Align2Query.resize(qq.qAlignedSeq.size());
785 Query2Align.resize(qq.qAlignedSeq.size());
786 std::string processed_query, processed_target;
787 processed_query.resize(qq.qAlignedSeq.size());
788 processed_target.resize(qq.qAlignedSeq.size());
789 int n_t = 0, n_q = 0;
790
791 for (size_t i = 0; i < qq.qAlignedSeq.size(); ++i) {
792 if (qq.qAlignedSeq[i] != '-') {
793 processed_query[n_q] = (qq.qAlignedSeq[i]);
794 n_q++;
795 }
796 if (qq.tAlignedSeq[i] != '-') {
797 processed_target[n_t] = (qq.tAlignedSeq[i]);
798 n_t++;
799 }
800 }
801 processed_query.resize(n_q);
802 processed_target.resize(n_t);
803
804 int base_cnt = 0;
805 for (size_t i = 0; i < qq.qAlignedSeq.size(); ++i) {
806 Align2Query[i] = base_cnt;
807 if (qq.qAlignedSeq[i] != '-') {
808 Query2Align[base_cnt] = i;
809 base_cnt++;
810 }
811 }
812
813 base_cnt = qq.tStart;
814 for (size_t i = 0; i + k <= qq.qAlignedSeq.size(); ++i) {
815 Align2Backbone[i] = base_cnt;
816 if (qq.tAlignedSeq[i] != '-') {
817 base_cnt++;
818 }
819 }
820
821 for (size_t i = 0; i < qq.qAlignedSeq.size(); ++i) {
822 matched[i] = 0;
823 }
824
825 for (size_t i = 0; i + k <= qq.tAlignedSeq.size(); ++i) {
826 bool match = 1;
827 size_t match_bases = 0;
828 for (size_t j = 0; j < qq.tAlignedSeq.size(); ++j) {
829 if (qq.qAlignedSeq[i + j] == qq.tAlignedSeq[i + j]) {
830 if (qq.qAlignedSeq[i + j] != '-') {
831 match_bases++;
832 }
833 if (match_bases == k) {
834 break;
835 }
836
837 } else {
838 match = 0;
839 break;
840 }
841 }
842
843 matched[i] = match;
844 if (qStart < 0 && match) {
845 qStart = i;
846 }
847 }
848
849 if (qStart < 0) {
850 return;
851 }
852
853 if (bb.Nodes[Align2Backbone[qStart]] != NULL) {
854 current_node = bb.Nodes[Align2Backbone[qStart]];
855 } else {
856 std::string KmerStr = processed_query.substr(Align2Query[qStart], k);
857
858 if (KmerStr.size() != k) {
859 return;
860 }
861 uint64_t seq = 0;
862 Str2BitArray(KmerStr, k, &seq, 1);
863 current_node = new Node();
864 nodeBucket.Add(current_node);
865 current_node->Kmer = static_cast<uint32_t>(seq);
866 bb.Nodes[Align2Backbone[qStart]] = current_node;
867 current_node->InBackbone = true;
868 }
869
870 for (size_t i = qStart; i < qq.qAlignedSeq.size();) {
871 //explore the edges of the current node
872
873 if (qq.qAlignedSeq[i] == '-') {
874 i++; // must skip to promise the correctness of the algorithm
875 continue;
876 }
877 current_node->Cov++; //increase the coverage
878 std::string EdgeStr;
879 EdgeStr = processed_query.substr(Align2Query[i] + k, gap);
880
881 if (EdgeStr.size() == 0) {
882
883 return;
884 }
885 PtrEdgeNode current_edge = current_node->Right;
886 bool edge_exists = 0;
887 while (current_edge != NULL) {
888 if (EdgeStr.size() < current_edge->Len) {
889 current_edge = current_edge->NextEdge;
890 continue;
891 }
892 uint64_t edge_bits;
893 Str2BitArray(EdgeStr, current_edge->Len, &edge_bits, 1);
894
895 if (edge_bits == current_edge->Edge) {
896
897 bool edge_matched = 0;
898
899 int align_idx = Query2Align[Align2Query[i] + current_edge->Len];
900 if (matched[align_idx] &&
901 bb.Nodes[Align2Backbone[align_idx]] == current_edge->NodePtr) {
902 edge_matched = 1; //backbone matched, so move on
903 }
904 if (!matched[align_idx] && !current_edge->NodePtr->InBackbone) {
905 edge_matched = 1; //off-backbone branch matched, so move on
906 }
907
908 if (edge_matched) {
909 current_edge->EdgeCov++;
910
911 edge_exists = 1;
912 current_node = current_edge->NodePtr;
913
914 std::string LeftEdgeStr =
915 processed_query.substr(Align2Query[i], current_edge->Len);
916
917 Str2BitArray(LeftEdgeStr, current_edge->Len, &edge_bits, 1);
918 PtrEdgeNode left_edge = current_node->Left;
919 while (left_edge != NULL) {
920 if (edge_bits == left_edge->Edge &&
921 LeftEdgeStr.size() == current_edge->Len) {
922 break;
923 }
924
925 left_edge = left_edge->NextEdge;
926 }
927 if (left_edge != NULL) {
928 left_edge->EdgeCov++;
929 } else {
930 throw std::runtime_error("left edge error.");
931 return;
932 }
933
934 i = align_idx;
935 break;
936 }
937 }
938
939 current_edge = current_edge->NextEdge;
940 }
941
942 if (edge_exists) {
943 continue;
944 }
945
946 //There is a backbone match but was not recorded, or there is no match.
947
948 /////non-matching, so pick the best stretch
949 // case 1, within g bases, there is a match with the backbone -- put the node into the backbone nodes
950 // otherwise, skip g bases, and create a new node.
951
952 current_node->Cov++;
953 bool backbone_match = 0;
954
955 int jj; //jj is the position in the processed query read
956 int ii = Align2Query[i]; // these two lines are very tricky,
957 int align_idx = -1;
958 for (jj = ii + 1; jj <= ii + gap; ++jj) {
959 align_idx = Query2Align[jj];
960 if (matched[align_idx]) {
961 backbone_match = 1;
962 break;
963 }
964 if (jj + k >= processed_query.size()) {
965 break;
966 }
967 }
968 jj = std::min(jj, ii + gap);
969
970 std::string temp_str;
971 temp_str = processed_query.substr(ii, jj - ii + k);
972
973 if (temp_str.size() != jj - ii + k) {
974 //std::cout << "bug. skipped" << std::endl;
975 return;
976 }
977
978 PtrNode next_node;
979
980 // Out of bound, bug
981 if (Align2Backbone[align_idx] >= static_cast<int32_t>(bb.Nodes.size())) {
982 return;
983 }
984
985 if (backbone_match && bb.Nodes[Align2Backbone[align_idx]] != NULL) {
986 //add edges to the existing backbone node.
987 next_node = bb.Nodes[Align2Backbone[align_idx]];
988 if (next_node == current_node) {
989 //std::cout << "bug caught, linked to itself." << std::endl;
990 return;
991 }
992
993 } else {
994 //allocate a new node and new edges
995 std::string kmer_str = temp_str.substr(temp_str.size() - k, k);
996 next_node = new Node();
997 nodeBucket.Add(next_node);
998 uint64_t seq;
999 Str2BitArray(kmer_str, k, &seq, 1);
1000 next_node->Kmer = static_cast<uint32_t>(seq);
1001 if (backbone_match) {
1002 bb.Nodes[Align2Backbone[align_idx]] = next_node;
1003 next_node->InBackbone = true;
1004 }
1005 }
1006
1007 //append edges, quite tricky
1008 std::string edge_str;
1009 edge_str = temp_str.substr(k, temp_str.size());
1010
1011 uint64_t edge_bits;
1012 Str2BitArray(edge_str, edge_str.size(), &edge_bits, 1);
1013
1014 PtrEdgeNode* edge_p2p = &(current_node->Right);
1015
1016 while (*edge_p2p != NULL) {
1017 edge_p2p = &((*edge_p2p)->NextEdge);
1018 }
1019
1020 if (*edge_p2p == NULL) {
1021
1022 (*edge_p2p) = new EdgeNode();
1023 edgeBucket.Add(*edge_p2p);
1024 (*edge_p2p)->Edge = static_cast<uint32_t>(edge_bits);
1025 (*edge_p2p)->Len = edge_str.size();
1026 (*edge_p2p)->NextEdge = NULL;
1027 (*edge_p2p)->NodePtr = next_node;
1028 (*edge_p2p)->EdgeCov++;
1029 }
1030
1031 edge_str = temp_str.substr(0, temp_str.size() - k);
1032 Str2BitArray(edge_str, edge_str.size(), &edge_bits, 1);
1033
1034 edge_p2p = &(next_node->Left);
1035
1036 while (*edge_p2p != NULL) {
1037
1038 edge_p2p = &((*edge_p2p)->NextEdge);
1039 }
1040
1041 if (*edge_p2p == NULL) {
1042
1043 (*edge_p2p) = new EdgeNode();
1044 edgeBucket.Add(*edge_p2p);
1045 (*edge_p2p)->Edge = static_cast<uint32_t>(edge_bits);
1046 (*edge_p2p)->Len = edge_str.size();
1047 (*edge_p2p)->NextEdge = NULL;
1048 (*edge_p2p)->NodePtr = current_node;
1049 (*edge_p2p)->EdgeCov++;
1050 }
1051 uint64_t kmer_bits = current_node->Kmer;
1052
1053 char kmer_str[100];
1054 BitsArray2Str(&kmer_bits, k, kmer_str);
1055 if ((*edge_p2p)->Len == k && strcmp(kmer_str, edge_str.c_str()) != 0) {
1056 /*
1057 std::cout << "bug" << std::endl;
1058 std::cout << kmer_str << std::endl;
1059 std::cout << edge_str << std::endl;
1060 std::abort();
1061 */
1062 throw std::runtime_error("Unknown error");
1063 }
1064
1065 current_node = next_node;
1066 i = align_idx;
1067 }
1068 }
1069 } // namespace
1070
1071 std::string SparcConsensus(const std::string& backboneSeq, std::vector<Query>& queries,
1072 const int32_t gap, const size_t k, const int32_t minCov,
1073 const double threshold)
1074 {
1075 const int32_t backboneSeqLen = backboneSeq.size();
1076
1077 Read ref;
1078 ref.ReadBits.resize((backboneSeqLen / 4) + 100);
1079 InitRefRead(backboneSeq, ref);
1080
1081 Backbone backbone;
1082 backbone.Threshold = threshold;
1083 backbone.Gap = gap;
1084 backbone.MinCov = minCov;
1085
1086 EdgeBucket edgeBucket;
1087 NodeBucket nodeBucket;
1088
1089 if (gap == 1) {
1090 ConsensusKmerGraphConstruction(&ref, &backbone, k, edgeBucket, nodeBucket);
1091 } else {
1092 ConsensusSparseKmerGraphConstruction(&ref, &backbone, k, edgeBucket, nodeBucket);
1093 }
1094
1095 for (Query& q : queries) {
1096 if (gap == 1) {
1097 AddPathToBackbone(&backbone, &q, k, edgeBucket, nodeBucket);
1098 } else {
1099 AddPathToBackboneSparse(backbone, q, k, edgeBucket, nodeBucket);
1100 }
1101 }
1102
1103 // hopefully never goes zero
1104 size_t radius = std::min(std::min<size_t>(200, backbone.Nodes.size()),
1105 static_cast<size_t>(backboneSeqLen - 1));
1106 std::map<int, int> cov_cnt;
1107 backbone.Covs.resize(backbone.Nodes.size());
1108
1109 for (size_t i = 0; i < radius; ++i) {
1110 if (backbone.Nodes[i] != NULL) {
1111 cov_cnt[backbone.Nodes[i]->Cov]++;
1112 }
1113 }
1114
1115 for (size_t i = 0; i < backbone.Nodes.size(); ++i) {
1116 if (i >= radius) {
1117 if (backbone.Nodes[i - radius] != NULL) {
1118 cov_cnt[backbone.Nodes[i - radius]->Cov]--;
1119 if (cov_cnt[backbone.Nodes[i - radius]->Cov] <= 0) {
1120 cov_cnt.erase(backbone.Nodes[i - radius]->Cov);
1121 }
1122 }
1123 }
1124 if ((i + radius < backbone.Nodes.size()) && (backbone.Nodes[i + radius] != NULL)) {
1125 cov_cnt[backbone.Nodes[i + radius]->Cov]++;
1126 }
1127
1128 if (cov_cnt.size() > 0) {
1129 backbone.Covs[i] = cov_cnt.rbegin()->first;
1130 } else {
1131 backbone.Covs[i] = 0;
1132 }
1133 }
1134
1135 if (gap == 1) {
1136 FindBestPath(&backbone);
1137 } else {
1138 FindBestPathSparse(&backbone);
1139 }
1140
1141 std::string consensus;
1142 if (gap == 1) {
1143 int64_t max_score = 0;
1144 size_t position = 0;
1145
1146 for (size_t i = 0; i < backbone.Nodes.size(); ++i) {
1147 if (backbone.Nodes[i]->Score > max_score) {
1148 max_score = backbone.Nodes[i]->Score;
1149 position = i;
1150 }
1151 backbone.Nodes[i]->InBackbone = false;
1152 }
1153
1154 if (max_score == 0) {
1155 return "";
1156 }
1157
1158 PtrNode current_node = backbone.Nodes[position];
1159
1160 char KmerStr[5];
1161 if (current_node != NULL) {
1162 uint64_t kmer_uint64 = (current_node->Kmer);
1163 BitsArray2Str(&kmer_uint64, k, KmerStr);
1164 consensus = KmerStr;
1165 std::reverse(consensus.begin(), consensus.end());
1166 current_node = current_node->LastNode;
1167 while (current_node != NULL) {
1168 kmer_uint64 = (current_node->Kmer);
1169 BitsArray2Str(&kmer_uint64, k, KmerStr);
1170
1171 consensus.push_back(KmerStr[0]);
1172 current_node = current_node->LastNode;
1173 }
1174
1175 std::reverse(consensus.begin(), consensus.end());
1176 }
1177
1178 current_node = backbone.Nodes[position];
1179 backbone.Nodes.clear();
1180 backbone.Nodes.push_back(current_node);
1181 if (current_node != NULL) {
1182 current_node = current_node->LastNode;
1183 while (current_node != NULL) {
1184 backbone.Nodes.push_back(current_node);
1185 current_node = current_node->LastNode;
1186 }
1187 }
1188 std::reverse(backbone.Nodes.begin(), backbone.Nodes.end());
1189
1190 for (size_t ii = 0; ii < backbone.Nodes.size(); ++ii) {
1191 backbone.Nodes[ii]->InBackbone = true;
1192 }
1193 } else {
1194 int64_t max_score = 0;
1195 size_t position = 0;
1196 for (size_t i = 0; i < backbone.Nodes.size(); ++i) {
1197 if (backbone.Nodes[i] != NULL && backbone.Nodes[i]->Score > max_score) {
1198 max_score = backbone.Nodes[i]->Score;
1199 position = i;
1200 }
1201 if (backbone.Nodes[i] != NULL) {
1202 backbone.Nodes[i]->InBackbone = false;
1203 }
1204 }
1205
1206 PtrNode current_node = backbone.Nodes[position];
1207 backbone.Nodes.clear();
1208 backbone.Nodes.push_back(current_node);
1209 if (max_score == 0) {
1210 return "";
1211 }
1212 char KmerStr[5];
1213 if (current_node != NULL) {
1214 uint64_t kmer_uint64 = (current_node->Kmer);
1215 BitsArray2Str(&kmer_uint64, k, KmerStr);
1216 consensus = KmerStr;
1217 std::reverse(consensus.begin(), consensus.end());
1218 PtrEdgeNode edge_node = current_node->Left;
1219 PtrEdgeNode best_edge_node = NULL;
1220 int max_edge_cov = 0;
1221 while (edge_node != NULL) {
1222 if (edge_node->NodePtr == current_node->LastNode) {
1223 if (edge_node->EdgeCov >= max_edge_cov) {
1224 max_edge_cov = edge_node->EdgeCov;
1225 best_edge_node = edge_node;
1226 }
1227 }
1228 edge_node = edge_node->NextEdge;
1229 }
1230 uint64_t edge_bits = best_edge_node->Edge;
1231
1232 char edge_str[5];
1233 BitsArray2Str(&edge_bits, best_edge_node->Len, edge_str);
1234 for (int i = best_edge_node->Len - 1; i >= 0; --i) {
1235 consensus.push_back(edge_str[i]);
1236 if (i > 0) {
1237 backbone.Nodes.push_back(NULL);
1238 }
1239 }
1240
1241 current_node = current_node->LastNode;
1242
1243 while (current_node->LastNode != NULL) {
1244 backbone.Nodes.push_back(current_node);
1245 edge_node = current_node->Left;
1246 best_edge_node = NULL;
1247 max_edge_cov = 0;
1248 while (edge_node != NULL) {
1249 if (edge_node->NodePtr == current_node->LastNode) {
1250 if (edge_node->EdgeCov > max_edge_cov || max_edge_cov == 0) {
1251 max_edge_cov = edge_node->EdgeCov;
1252 best_edge_node = edge_node;
1253 }
1254 }
1255 edge_node = edge_node->NextEdge;
1256 }
1257
1258 uint64_t edge_bits_local = best_edge_node->Edge;
1259
1260 char edge_str_local[5];
1261 BitsArray2Str(&edge_bits_local, best_edge_node->Len, edge_str_local);
1262
1263 uint64_t kmer_bits = current_node->LastNode->Kmer;
1264
1265 char kmer_str[5];
1266 BitsArray2Str(&kmer_bits, k, kmer_str);
1267 if (best_edge_node->Len == k && strcmp(kmer_str, edge_str_local) != 0) {
1268 throw std::runtime_error("Unknown error");
1269 }
1270 for (int i = best_edge_node->Len - 1; i >= 0; --i) {
1271 consensus.push_back(edge_str_local[i]);
1272 if (i > 0) {
1273 backbone.Nodes.push_back(NULL);
1274 }
1275 }
1276
1277 current_node = current_node->LastNode;
1278 }
1279
1280 std::reverse(consensus.begin(), consensus.end());
1281 std::reverse(backbone.Nodes.begin(), backbone.Nodes.end());
1282
1283 for (size_t ii = 0; ii < backbone.Nodes.size(); ++ii) {
1284 if (backbone.Nodes[ii] != NULL) {
1285 backbone.Nodes[ii]->InBackbone = true;
1286 }
1287 }
1288 }
1289 }
1290
1291 return consensus;
1292 }
1293 } // namespace Sparc