Debian Codegraph @

kmc_core/kb_sorter.h

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 This file is a part of KMC software distributed under GNU GPL 3 licence.
3 The homepage of the KMC project is http://sun.aei.polsl.pl/kmc
4
5 Authors: Sebastian Deorowicz, Agnieszka Debudaj-Grabysz, Marek Kokot
6
7 Version: 3.2.4
8 Date : 2024-02-09
9 */
10
11 #ifndef _KB_SORTER_H
12 #define _KB_SORTER_H
13
14 #define DEBUGG_INFO
15
16 #include "defs.h"
17 #include "params.h"
18 #include "kmer.h"
19 #include "raduls.h"
20 #include "radix.h"
21 #include "s_mapper.h"
22 #include <string>
23 #include <algorithm>
24 #include <numeric>
25 #include <array>
26 #include <vector>
27 #include <stdio.h>
28 #include <functional>
29 #include <cstddef>
30 #include <set>
31
32
33 #include "kxmer_set.h"
34 #include "rev_byte.h"
35
36
37 template<unsigned SIZE> class CExpandThread;
38
39 //************************************************************************************************************
40 // CKmerBinSorter - sorting of k-mers in a bin
41 //************************************************************************************************************
42 template <unsigned SIZE> class CKmerBinSorter
43 {
44 private:
45
46 mutable mutex expander_mtx;
47 uint64 input_pos;
48
49 CBinDesc *bd;
50 CExpanderPackDesc *epd;
51 CBinQueue *bq;
52 CKmerQueue *kq;
53 CMemoryPool *pmm_radix_buf;
54 CMemoryBins *memory_bins;
55 CSortersManager* sorters_manager;
56
57 CKXmerSet<SIZE> kxmer_set;
58 SortFunction<CKmer<SIZE>> sort_func;
59
60 int32 n_bins;
61 int32 bin_id;
62
63 uchar *data;
64 uint64 size;
65 uint64 n_rec;
66
67 uint64 n_plus_x_recs;
68 string desc;
69 uint32 kmer_len;
70 uint32 max_x;
71
72 uint64 sum_n_rec, sum_n_plus_x_rec;
73
74 int n_sorting_threads;
75
76 bool both_strands;
77 bool without_output;
78
79 CSignatureMapper* s_mapper;
80
81 uint64 n_unique, n_cutoff_min, n_cutoff_max, n_total;
82 uint32 cutoff_min, cutoff_max;
83 int32 lut_prefix_len;
84 uint32 counter_max;
85
86 OutputType output_type;
87
88 CKmer<SIZE> *buffer_input, *buffer_tmp, *buffer;
89 uint32 *kxmer_counters;
90
91 void Sort();
92
93 friend class CExpandThread<SIZE>;
94
95 uint64 FindFirstSymbOccur(uint64 start_pos, uint64 end_pos, uint32 offset, uchar symb);
96 void InitKXMerSet(uint64 start_pos, uint64 end_pos, uint32 offset, uint32 depth);
97 void InitKXMerSetMultithreaded(CKXmerSetMultiThreaded<SIZE>& kxmer_set_multithreaded, uint64 start_pos, uint64 end_pos, uint32 offset, uint32 depth);
98 void CompactKxmers();
99 void PreCompactKxmers(uint64& compacted_count);
100 void CompactKmers();
101 void ExpandKxmersAll(uint64 tmp_size);
102 void ExpandKxmersBoth(uint64 tmp_size);
103 void ExpandKmersAll(uint64 tmp_size);
104 void ExpandKmersBoth(uint64 tmp_size);
105 void GetNextSymb(uchar& symb, uchar& byte_shift, uint64& pos, uchar* data_p);
106 void FromChildThread(CKmer<SIZE>* thread_buffer, uint64 size);
107 uint64 ExpandKxmerBothParallel(uint64 start_pos, uint64 end_pos, uint64 output_start, uint64 output_end);
108
109 void Compact();
110 void Expand(uint64 tmp_size);
111
112
113 public:
114 static uint32 PROB_BUF_SIZE;
115 CKmerBinSorter(CKMCParams &Params, CKMCQueues &Queues, SortFunction<CKmer<SIZE>> sort_func);
116 ~CKmerBinSorter();
117
118 void GetDebugStats(uint64& _sum_n_recs, uint64& _sum_n_plus_x_recs)
119 {
120 _sum_n_recs = sum_n_rec;
121 _sum_n_plus_x_recs = sum_n_plus_x_rec;
122 }
123
124 void ProcessBins();
125 };
126
127 template <unsigned SIZE> uint32 CKmerBinSorter<SIZE>::PROB_BUF_SIZE = 1 << 14;
128
129 // Queue for expander
130 class CExpanderPackQueue
131 {
132 uint64 _start = 0;
133 uint64 _output_start = 0;
134 list<pair<uint64, uint64>> l;
135 mutex mtx;
136 public:
137 CExpanderPackQueue(list<pair<uint64, uint64>>& expander_pack)
138 {
139 l = std::move(expander_pack);
140 }
141 bool Pop(uint64& start, uint64& end, uint64& output_start, uint64& output_end)
142 {
143 lock_guard<mutex> lck(mtx);
144 if (l.empty())
145 return false;
146 start = _start;
147 _start += l.front().first;
148 end = _start;
149 output_start = _output_start;
150 _output_start += l.front().second;
151 output_end = _output_start;
152
153 l.pop_front();
154 return true;
155 }
156 };
157
158
159 //************************************************************************************************************
160 // CKmerBinSorter
161 //************************************************************************************************************
162
163 //----------------------------------------------------------------------------------
164 // Assign queues and monitors
165 template <unsigned SIZE> CKmerBinSorter<SIZE>::CKmerBinSorter(CKMCParams &Params, CKMCQueues &Queues, SortFunction<CKmer<SIZE>> sort_func)
166 :
167 kxmer_set(Params.kmer_len),
168 sort_func(sort_func)
169 {
170 both_strands = Params.both_strands;
171 n_bins = Params.n_bins;
172 bd = Queues.bd.get();
173 epd = Queues.epd.get();
174 bq = Queues.bq.get();
175 kq = Queues.kq.get();
176
177 sorters_manager = Queues.sorters_manager.get();
178
179 s_mapper = Queues.s_mapper.get();
180
181 pmm_radix_buf = Queues.pmm_radix_buf.get();
182
183 memory_bins = Queues.memory_bins.get();
184
185 cutoff_min = Params.cutoff_min;
186 cutoff_max = (uint32)Params.cutoff_max;
187 counter_max = (uint32)Params.counter_max;
188 max_x = Params.max_x;
189 without_output = Params.without_output;
190
191 lut_prefix_len = Params.lut_prefix_len;
192
193 output_type = Params.output_type;
194
195 n_sorting_threads = 0;
196
197 sum_n_rec = sum_n_plus_x_rec = 0;
198
199 kmer_len = Params.kmer_len;
200 }
201
202 //----------------------------------------------------------------------------------
203 template <unsigned SIZE> CKmerBinSorter<SIZE>::~CKmerBinSorter()
204 {
205
206 }
207
208 //----------------------------------------------------------------------------------
209 // Process the bins
210 template <unsigned SIZE> void CKmerBinSorter<SIZE>::ProcessBins()
211 {
212 uint64 tmp_size;
213 uint64 tmp_n_rec;
214 CMemDiskFile *file;
215
216 while (sorters_manager->GetNext(bin_id, data, size, n_rec, n_sorting_threads))
217 {
218 // Get bin data
219 bd->read(bin_id, file, desc, tmp_size, tmp_n_rec, n_plus_x_recs);
220
221 // Uncompact the kmers - append truncate prefixes
222
223 Expand(tmp_size);
224
225 memory_bins->free(bin_id, CMemoryBins::mba_input_file);
226
227 // Perform sorting of kmers in a bin
228 Sort();
229
230 // Compact the same kmers (occurring at neighbour positions now)
231 Compact();
232
233 sorters_manager->ReturnThreads(n_sorting_threads, bin_id);
234 }
235
236 kq->mark_completed();
237 }
238
239 template <unsigned SIZE> inline void CKmerBinSorter<SIZE>::GetNextSymb(uchar& symb, uchar& byte_shift, uint64& pos, uchar* data_p)
240 {
241 symb = (data_p[pos] >> byte_shift) & 3;
242 if (byte_shift == 0)
243 {
244 ++pos;
245 byte_shift = 6;
246 }
247 else
248 byte_shift -= 2;
249 }
250
251 template <unsigned SIZE> void CKmerBinSorter<SIZE>::ExpandKmersAll(uint64 tmp_size)
252 {
253 uint64 pos = 0;
254 input_pos = 0;
255 CKmer<SIZE> kmer;
256 uint32 kmer_bytes = (kmer_len + 3) / 4;
257
258 CKmer<SIZE> kmer_mask;
259 kmer_mask.set_n_1(kmer_len * 2);
260 uchar *data_p = data;
261 uchar additional_symbols;
262 uint32 kmer_shr = SIZE * 32 - kmer_len;
263 while (pos < tmp_size)
264 {
265 kmer.clear();
266 additional_symbols = data_p[pos++];
267 for (uint32 i = 0, kmer_pos = 8 * SIZE - 1; i < kmer_bytes; ++i, --kmer_pos)
268 {
269 kmer.set_byte(kmer_pos, data_p[pos + i]);
270 }
271 pos += kmer_bytes;
272 uchar byte_shift = 6 - (kmer_len % 4) * 2;
273 if (byte_shift != 6)
274 --pos;
275
276 if (kmer_shr)
277 kmer.SHR(kmer_shr);
278
279 kmer.mask(kmer_mask);
280 buffer_input[input_pos++].set(kmer);
281 for (int i = 0; i < additional_symbols; ++i)
282 {
283 uchar symb = (data_p[pos] >> byte_shift) & 3;
284 if (byte_shift == 0)
285 {
286 ++pos;
287 byte_shift = 6;
288 }
289 else
290 byte_shift -= 2;
291 kmer.SHL_insert_2bits(symb);
292 kmer.mask(kmer_mask);
293 buffer_input[input_pos++].set(kmer);
294 }
295 if (byte_shift != 6)
296 ++pos;
297 }
298 }
299 template <unsigned SIZE> void CKmerBinSorter<SIZE>::ExpandKmersBoth(uint64 tmp_size)
300 {
301 uint64 pos = 0;
302 CKmer<SIZE> kmer;
303 CKmer<SIZE> rev_kmer;
304 CKmer<SIZE> kmer_can;
305
306 uint32 kmer_bytes = (kmer_len + 3) / 4;
307 uint32 kmer_len_shift = (kmer_len - 1) * 2;
308 CKmer<SIZE> kmer_mask;
309 kmer_mask.set_n_1(kmer_len * 2);
310 uchar *data_p = data;
311 input_pos = 0;
312 uint32 kmer_shr = SIZE * 32 - kmer_len;
313
314 uchar additional_symbols;
315
316 uchar symb;
317 while (pos < tmp_size)
318 {
319 kmer.clear();
320 rev_kmer.clear();
321 additional_symbols = data_p[pos++];
322
323 //building kmer
324 for (uint32 i = 0, kmer_pos = 8 * SIZE - 1, kmer_rev_pos = 0; i < kmer_bytes; ++i, --kmer_pos, ++kmer_rev_pos)
325 {
326 kmer.set_byte(kmer_pos, data_p[pos + i]);
327 rev_kmer.set_byte(kmer_rev_pos, CRev_byte::lut[data_p[pos + i]]);
328 }
329 pos += kmer_bytes;
330 uchar byte_shift = 6 - (kmer_len % 4) * 2;
331 if (byte_shift != 6)
332 --pos;
333
334 if (kmer_shr)
335 kmer.SHR(kmer_shr);
336
337 kmer.mask(kmer_mask);
338 rev_kmer.mask(kmer_mask);
339
340 kmer_can = kmer < rev_kmer ? kmer : rev_kmer;
341 buffer_input[input_pos++].set(kmer_can);
342
343 for (int i = 0; i < additional_symbols; ++i)
344 {
345 symb = (data_p[pos] >> byte_shift) & 3;
346 if (byte_shift == 0)
347 {
348 ++pos;
349 byte_shift = 6;
350 }
351 else
352 byte_shift -= 2;
353 kmer.SHL_insert_2bits(symb);
354 kmer.mask(kmer_mask);
355 rev_kmer.SHR_insert_2bits(3 - symb, kmer_len_shift);
356 kmer_can = kmer < rev_kmer ? kmer : rev_kmer;
357 buffer_input[input_pos++].set(kmer_can);
358 }
359 if (byte_shift != 6)
360 ++pos;
361 }
362 }
363
364 template <unsigned SIZE> void CKmerBinSorter<SIZE>::FromChildThread(CKmer<SIZE>* thread_buffer, uint64 size)
365 {
366 lock_guard<mutex> lcx(expander_mtx);
367 memcpy(buffer_input + input_pos, thread_buffer, size * sizeof(CKmer<SIZE>));
368 input_pos += size;
369 }
370
371 template<unsigned SIZE> uint64 CKmerBinSorter<SIZE>::ExpandKxmerBothParallel(uint64 start_pos, uint64 end_pos, uint64 output_start, uint64 output_end)
372 {
373 CKmer<SIZE> kmer, rev_kmer, kmer_mask;
374 CKmer<SIZE> kxmer_mask;
375 bool kmer_lower; //true if kmer is lower than its rev. comp
376 uint32 x, additional_symbols;
377 uchar symb;
378 uint32 kmer_bytes = (kmer_len + 3) / 4;
379 uint32 rev_shift = kmer_len * 2 - 2;
380 uchar *data_p = data;
381 kmer_mask.set_n_1(kmer_len * 2);
382 uint32 kmer_shr = SIZE * 32 - kmer_len;
383
384 kxmer_mask.set_n_1((kmer_len + max_x + 1) * 2);
385
386 uint64 pos = start_pos;
387
388 while (pos < end_pos)
389 {
390 kmer.clear();
391 rev_kmer.clear();
392 additional_symbols = data_p[pos++];
393
394 //building kmer
395 for (uint32 i = 0, kmer_pos = 8 * SIZE - 1, kmer_rev_pos = 0; i < kmer_bytes; ++i, --kmer_pos, ++kmer_rev_pos)
396 {
397 kmer.set_byte(kmer_pos, data_p[pos + i]);
398 rev_kmer.set_byte(kmer_rev_pos, CRev_byte::lut[data_p[pos + i]]);
399 }
400 pos += kmer_bytes;
401 uchar byte_shift = 6 - (kmer_len % 4) * 2;
402 if (byte_shift != 6)
403 --pos;
404
405 if (kmer_shr)
406 kmer.SHR(kmer_shr);
407
408 kmer.mask(kmer_mask);
409 rev_kmer.mask(kmer_mask);
410
411 kmer_lower = kmer < rev_kmer;
412 x = 0;
413 if (kmer_lower)
414 buffer_input[output_start].set(kmer);
415 else
416 buffer_input[output_start].set(rev_kmer);
417
418 uint32 symbols_left = additional_symbols;
419 while (symbols_left)
420 {
421 GetNextSymb(symb, byte_shift, pos, data_p);
422 kmer.SHL_insert_2bits(symb);
423 kmer.mask(kmer_mask);
424 rev_kmer.SHR_insert_2bits(3 - symb, rev_shift);
425 --symbols_left;
426
427 if (kmer_lower)
428 {
429 if (kmer < rev_kmer)
430 {
431 buffer_input[output_start].SHL_insert_2bits(symb);
432 ++x;
433 if (x == max_x)
434 {
435 if (!symbols_left)
436 break;
437
438 buffer_input[output_start++].set_2bits(x, kmer_len * 2 + max_x * 2);
439
440 x = 0;
441
442 GetNextSymb(symb, byte_shift, pos, data_p);
443 kmer.SHL_insert_2bits(symb);
444 kmer.mask(kmer_mask);
445 rev_kmer.SHR_insert_2bits(3 - symb, rev_shift);
446 --symbols_left;
447
448 kmer_lower = kmer < rev_kmer;
449
450 if (kmer_lower)
451 buffer_input[output_start].set(kmer);
452 else
453 buffer_input[output_start].set(rev_kmer);
454 }
455 }
456 else
457 {
458 buffer_input[output_start++].set_2bits(x, kmer_len * 2 + max_x * 2);
459
460 x = 0;
461
462 kmer_lower = false;
463 buffer_input[output_start].set(rev_kmer);
464
465 }
466 }
467 else
468 {
469 if (!(kmer < rev_kmer))
470 {
471 buffer_input[output_start].set_2bits(3 - symb, kmer_len * 2 + x * 2);
472 ++x;
473 if (x == max_x)
474 {
475 if (!symbols_left)
476 break;
477
478 buffer_input[output_start++].set_2bits(x, kmer_len * 2 + max_x * 2);
479
480 x = 0;
481
482 GetNextSymb(symb, byte_shift, pos, data_p);
483 kmer.SHL_insert_2bits(symb);
484 kmer.mask(kmer_mask);
485 rev_kmer.SHR_insert_2bits(3 - symb, rev_shift);
486 --symbols_left;
487
488 kmer_lower = kmer < rev_kmer;
489
490 if (kmer_lower)
491 buffer_input[output_start].set(kmer);
492 else
493 buffer_input[output_start].set(rev_kmer);
494 }
495 }
496 else
497 {
498 buffer_input[output_start++].set_2bits(x, kmer_len * 2 + max_x * 2);
499
500 x = 0;
501
502 buffer_input[output_start].set(kmer);
503 kmer_lower = true;
504 }
505 }
506
507 }
508 buffer_input[output_start++].set_2bits(x, kmer_len * 2 + max_x * 2);
509
510 if (byte_shift != 6)
511 ++pos;
512 }
513
514 uint64 ret = output_end - output_start;
515 /*for (; output_start < output_end; ++output_start)
516 buffer_input[output_start].fill_T();*/
517 return ret;
518 }
519
520
521 template<unsigned SIZE>
522 class CExpandThread
523 {
524 CKmerBinSorter<SIZE>& ptr;
525 CExpanderPackQueue& q;
526
527 list<pair<uint64, uint64>> filled_regions;
528
529 uint64 fake_recs = 0;
530
531 public:
532 CExpandThread(CKmerBinSorter<SIZE>& ptr, CExpanderPackQueue& q)
533 :
534 ptr(ptr),
535 q(q)
536 {
537 }
538 void operator()()
539 {
540 uint64 start, end, out_start, out_end;
541 while (q.Pop(start, end, out_start, out_end))
542 {
543
544 auto res = ptr.ExpandKxmerBothParallel(start, end, out_start, out_end);
545 fake_recs += res;
546 filled_regions.push_back(make_pair(out_start, out_end - res));
547 }
548 }
549
550
551 uint64 GetNFakeRecs()
552 {
553 return fake_recs;
554 }
555 list<pair<uint64, uint64>>& GetFilledRegions()
556 {
557 return filled_regions;
558 }
559
560 };
561
562 template <unsigned SIZE> void CKmerBinSorter<SIZE>::ExpandKxmersBoth(uint64 tmp_size)
563 {
564 if (!tmp_size)
565 {
566 return;
567 }
568 input_pos = 0;
569 uint32 threads = n_sorting_threads;
570
571 list<pair<uint64, uint64>> l;
572 epd->pop(bin_id, l);
573
574 if (n_sorting_threads > 1)
575 {
576 CExpanderPackQueue q(l);
577
578 std::vector<thread> ths;
579 std::vector<std::unique_ptr<CExpandThread<SIZE>>> exp;
580 for (uint32 i = 0; i < threads; ++i)
581 {
582 exp.emplace_back(std::make_unique<CExpandThread<SIZE>>(*this, q));
583 ths.push_back(thread(std::ref(*exp.back().get())));
584 }
585
586 for (auto& t : ths)
587 t.join();
588
589 uint64 n_fake_recs_after_expand = 0;
590 vector<pair<uint64, uint64>> filled_regions;
591 uint64 filled_regions_size = 0;
592 for (auto& _ptr : exp)
593 {
594 filled_regions_size += _ptr->GetFilledRegions().size();
595 }
596 filled_regions.reserve(filled_regions_size);
597
598 for (auto& _ptr : exp)
599 {
600 n_fake_recs_after_expand += _ptr->GetNFakeRecs();
601 filled_regions.insert(filled_regions.end(), _ptr->GetFilledRegions().begin(), _ptr->GetFilledRegions().end());
602 }
603 exp.clear();
604
605 //remove fakes
606 sort(filled_regions.begin(), filled_regions.end(), [](const pair<uint64, uint64>& e1, const pair<uint64, uint64>& e2) {return e1.first < e2.first; });
607
608 uint64 first_gap_pos = filled_regions.front().second;
609 uint64 next_reg_desc_pos = 1;
610 uint64 last_elem_pos = filled_regions.back().second - 1;
611 int64 back_reg_desc_pos = filled_regions.size() - 1;
612
613 while (true)
614 {
615 while (next_reg_desc_pos < filled_regions.size() && first_gap_pos >= filled_regions[next_reg_desc_pos].first)
616 first_gap_pos = filled_regions[next_reg_desc_pos++].second;
617
618 while (back_reg_desc_pos >= 0 && last_elem_pos < filled_regions[back_reg_desc_pos].first)
619 last_elem_pos = filled_regions[--back_reg_desc_pos].second - 1;
620
621 if (first_gap_pos >= last_elem_pos)
622 break;
623
624 buffer_input[first_gap_pos++] = buffer_input[last_elem_pos--];
625 }
626
627 n_plus_x_recs -= n_fake_recs_after_expand;
628 }
629 else
630 {
631 l.clear();
632 auto n_fake_recs = ExpandKxmerBothParallel(0, tmp_size, 0, n_plus_x_recs);
633 n_plus_x_recs -= n_fake_recs;
634
635 }
636
637 input_pos = n_plus_x_recs;
638 }
639
640 template<unsigned SIZE> void CKmerBinSorter<SIZE>::ExpandKxmersAll(uint64 tmp_size)
641 {
642 input_pos = 0;
643 uint64 pos = 0;
644 CKmer<SIZE> kmer_mask;
645
646 CKmer<SIZE> kxmer;
647 CKmer<SIZE> kxmer_mask;
648 kxmer_mask.set_n_1((kmer_len + max_x) * 2);
649 uchar *data_p = data;
650
651 kmer_mask.set_n_1(kmer_len * 2);
652 while (pos < tmp_size)
653 {
654 kxmer.clear();
655 uint32 additional_symbols = data_p[pos++];
656
657 uchar symb;
658
659 uint32 kmer_bytes = (kmer_len + 3) / 4;
660 //building kmer
661 for (uint32 i = 0, kmer_pos = 8 * SIZE - 1; i < kmer_bytes; ++i, --kmer_pos)
662 {
663 kxmer.set_byte(kmer_pos, data_p[pos + i]);
664 }
665
666 pos += kmer_bytes;
667 uchar byte_shift = 6 - (kmer_len % 4) * 2;
668 if (byte_shift != 6)
669 --pos;
670 uint32 kmer_shr = SIZE * 32 - kmer_len;
671
672 if (kmer_shr)
673 kxmer.SHR(kmer_shr);
674
675 kxmer.mask(kmer_mask);
676 uint32 tmp = MIN(max_x, additional_symbols);
677
678 for (uint32 i = 0; i < tmp; ++i)
679 {
680 GetNextSymb(symb, byte_shift, pos, data_p);
681 kxmer.SHL_insert_2bits(symb);
682 }
683 kxmer.set_2bits(tmp, (kmer_len + max_x) * 2);
684
685 buffer_input[input_pos++].set(kxmer);
686 additional_symbols -= tmp;
687
688 uint32 kxmers_count = additional_symbols / (max_x + 1);
689 uint32 kxmer_rest = additional_symbols % (max_x + 1);
690
691 for (uint32 j = 0; j < kxmers_count; ++j)
692 {
693 for (uint32 i = 0; i < max_x + 1; ++i)
694 {
695 GetNextSymb(symb, byte_shift, pos, data_p);
696 kxmer.SHL_insert_2bits(symb);
697 }
698
699 kxmer.mask(kxmer_mask);
700
701 kxmer.set_2bits(max_x, (kmer_len + max_x) * 2);
702
703 buffer_input[input_pos++].set(kxmer);
704 }
705 if (kxmer_rest)
706 {
707 uint32 i = 0;
708 GetNextSymb(symb, byte_shift, pos, data_p);
709 kxmer.SHL_insert_2bits(symb);
710 kxmer.mask(kmer_mask);
711 --kxmer_rest;
712 for (; i < kxmer_rest; ++i)
713 {
714 GetNextSymb(symb, byte_shift, pos, data_p);
715 kxmer.SHL_insert_2bits(symb);
716 }
717
718 kxmer.set_2bits(kxmer_rest, (kmer_len + max_x) * 2);
719 buffer_input[input_pos++].set(kxmer);
720 }
721 if (byte_shift != 6)
722 ++pos;
723 }
724 }
725
726 //----------------------------------------------------------------------------------
727 // Uncompact the kmers
728 template <unsigned SIZE> void CKmerBinSorter<SIZE>::Expand(uint64 tmp_size)
729 {
730 uchar *raw_buffer_input, *raw_buffer_tmp;
731
732 memory_bins->reserve(bin_id, raw_buffer_input, CMemoryBins::mba_input_array);
733 memory_bins->reserve(bin_id, raw_buffer_tmp, CMemoryBins::mba_tmp_array);
734
735 buffer_input = (CKmer<SIZE> *) raw_buffer_input;
736 buffer_tmp = (CKmer<SIZE> *) raw_buffer_tmp;
737
738 if (max_x)
739 {
740 if (both_strands)
741 ExpandKxmersBoth(tmp_size);
742 else
743 ExpandKxmersAll(tmp_size);
744 }
745 else
746 {
747 if (both_strands)
748 ExpandKmersBoth(tmp_size);
749 else
750 ExpandKmersAll(tmp_size);
751 }
752 }
753
754
755 //----------------------------------------------------------------------------------
756 // Sort the kmers
757 template <unsigned SIZE> void CKmerBinSorter<SIZE>::Sort()
758 {
759 uint32 rec_len;
760 uint64 sort_rec;
761 if (max_x)
762 {
763 sort_rec = n_plus_x_recs;
764 rec_len = (kmer_len + max_x + 1 + 3) / 4;
765 }
766 else
767 {
768 sort_rec = n_rec;
769 rec_len = (kmer_len + 3) / 4;
770 }
771
772 sum_n_plus_x_rec += n_plus_x_recs;
773 sum_n_rec += n_rec;
774
775 sort_func(buffer_input, buffer_tmp, sort_rec, rec_len - 1, n_sorting_threads, pmm_radix_buf);
776 if (rec_len % 2)
777 buffer = buffer_tmp;
778 else
779 buffer = buffer_input;
780 }
781
782 //----------------------------------------------------------------------------------
783 //Binary search position of first occurrence of symbol 'symb' in [start_pos,end_pos). Offset defines which symbol in k+x-mer is taken.
784 template <unsigned SIZE> uint64 CKmerBinSorter<SIZE>::FindFirstSymbOccur(uint64 start_pos, uint64 end_pos, uint32 offset, uchar symb)
785 {
786 uint32 kxmer_offset = (kmer_len + max_x - offset) * 2;
787 uint64 middle_pos;
788 uchar middle_symb;
789 while (start_pos < end_pos)
790 {
791 middle_pos = (start_pos + end_pos) / 2;
792 middle_symb = buffer[middle_pos].get_2bits(kxmer_offset);
793 if (middle_symb < symb)
794 start_pos = middle_pos + 1;
795 else
796 end_pos = middle_pos;
797 }
798 return end_pos;
799 }
800
801 //----------------------------------------------------------------------------------
802 template<unsigned SIZE> void CKmerBinSorter<SIZE>::InitKXMerSet(uint64 start_pos, uint64 end_pos, uint32 offset, uint32 depth)
803 {
804 if (start_pos == end_pos)
805 return;
806 uint32 shr = max_x + 1 - offset;
807 kxmer_set.init_add(start_pos, end_pos, shr);
808
809 --depth;
810 if (depth > 0)
811 {
812 uint64 pos[5];
813 pos[0] = start_pos;
814 pos[4] = end_pos;
815 for (uint32 i = 1; i < 4; ++i)
816 pos[i] = FindFirstSymbOccur(pos[i - 1], end_pos, offset, i);
817 for (uint32 i = 1; i < 5; ++i)
818 InitKXMerSet(pos[i - 1], pos[i], offset + 1, depth);
819 }
820 }
821
822 //----------------------------------------------------------------------------------
823 template<unsigned SIZE> void CKmerBinSorter<SIZE>::InitKXMerSetMultithreaded(CKXmerSetMultiThreaded<SIZE>& kxmer_set_multithreaded, uint64 start_pos, uint64 end_pos, uint32 offset, uint32 depth)
824 {
825 if (start_pos == end_pos)
826 return;
827 uint32 shr = max_x + 1 - offset;
828 kxmer_set_multithreaded.InitAdd(start_pos, end_pos, shr);
829
830 --depth;
831 if (depth > 0)
832 {
833 uint64 pos[5];
834 pos[0] = start_pos;
835 pos[4] = end_pos;
836 for (uint32 i = 1; i < 4; ++i)
837 pos[i] = FindFirstSymbOccur(pos[i - 1], end_pos, offset, i);
838 for (uint32 i = 1; i < 5; ++i)
839 InitKXMerSetMultithreaded(kxmer_set_multithreaded, pos[i - 1], pos[i], offset + 1, depth);
840 }
841 }
842
843 //----------------------------------------------------------------------------------
844 template<unsigned SIZE> void CKmerBinSorter<SIZE>::PreCompactKxmers(uint64& compacted_count)
845 {
846 uint32 n_threads = n_sorting_threads;
847 vector<thread> threads;
848 vector<pair<uint64, uint64>> start_end(n_threads);
849 uint64 total_recs = n_plus_x_recs;
850 for (uint32 idx = 0; idx < n_threads; ++idx)
851 {
852 threads.push_back(thread([idx, n_threads, total_recs, &start_end, this]
853 {
854 uint64 per_thread = total_recs / n_threads;
855 uint64 start = idx * per_thread;
856 uint64 end = (idx + 1) * per_thread;
857 start_end[idx].first = start;
858 if (idx == n_threads - 1)
859 end = total_recs;
860
861 if (start == end)
862 {
863 start_end[idx].second = end;
864 return;
865 }
866
867 uint64 compacted_pos = start;
868 CKmer<SIZE>* act_kmer = &buffer[compacted_pos];
869 kxmer_counters[compacted_pos] = 1;
870
871 for (uint64 i = start + 1; i < end; ++i)
872 {
873 if (*act_kmer == buffer[i])
874 ++kxmer_counters[compacted_pos];
875 else
876 {
877 buffer[compacted_pos++] = *act_kmer;
878 kxmer_counters[compacted_pos] = 1;
879 act_kmer = &buffer[i];
880 }
881 }
882 buffer[compacted_pos++] = *act_kmer;
883 start_end[idx].second = compacted_pos;
884 }));
885 }
886
887 for (auto& t : threads)
888 t.join();
889
890 compacted_count = start_end[0].second;
891 for (uint32 i = 1; i < n_threads; ++i)
892 {
893 if (start_end[i].second > start_end[i].first)
894 {
895 if (buffer[compacted_count - 1] == buffer[start_end[i].first])
896 {
897 kxmer_counters[compacted_count - 1] += kxmer_counters[start_end[i].first++];
898 }
899 uint64 n_elems = start_end[i].second - start_end[i].first;
900 if (!n_elems)
901 continue;
902 auto kmers_dest = buffer + compacted_count;
903 auto kmers_src = buffer + start_end[i].first;
904 auto counters_dest = kxmer_counters + compacted_count;
905 auto counters_src = kxmer_counters + start_end[i].first;
906
907 if (n_threads < 2 || n_elems < 4096) //size limit achieved experimentally
908 {
909 memmove(kmers_dest, kmers_src, n_elems * sizeof(CKmer<SIZE>));
910 memmove(counters_dest, counters_src, n_elems * sizeof(uint32));
911 }
912 else
913 {
914 std::thread th1([kmers_dest, kmers_src, n_elems]
915 {
916 auto _kmers_dest = kmers_dest;
917 auto _kmers_src = kmers_src;
918 memmove(_kmers_dest, _kmers_src, n_elems * sizeof(CKmer<SIZE>));
919 });
920
921 std::thread th2([counters_dest, counters_src, n_elems]
922 {
923 auto _counters_dest = counters_dest;
924 auto _counters_src = counters_src;
925 memmove(_counters_dest, _counters_src, n_elems * sizeof(uint32));
926 });
927 th1.join();
928 th2.join();
929 }
930
931 compacted_count += n_elems;
932 }
933 }
934 }
935
936 //----------------------------------------------------------------------------------
937 template <unsigned SIZE> void CKmerBinSorter<SIZE>::CompactKxmers()
938 {
939 kxmer_set.clear();
940 kxmer_set.set_buffer(buffer);
941 n_unique = 0;
942 n_cutoff_min = 0;
943 n_cutoff_max = 0;
944 n_total = 0;
945
946 uint32 kmer_symbols = kmer_len - lut_prefix_len;
947 uint64 kmer_bytes = kmer_symbols / 4;
948
949 if (lut_prefix_len == 0) //do not split data to prefix and sufix (for example when storying result in KFF)
950 kmer_bytes = (kmer_symbols + 3) / 4;
951
952 uint64 lut_recs = 1ull << (2 * lut_prefix_len);
953 if (lut_prefix_len == 0)
954 lut_recs = 0;
955 uint64 lut_size = lut_recs * sizeof(uint64);
956
957
958 uchar *out_buffer = nullptr;
959 uchar *raw_lut = nullptr;
960
961 memory_bins->reserve(bin_id, out_buffer, CMemoryBins::mba_suffix);
962 memory_bins->reserve(bin_id, raw_lut, CMemoryBins::mba_lut);
963
964 uint64 *lut = (uint64*)raw_lut;
965 fill_n(lut, lut_recs, 0);
966
967 list<pair<uint64, uint64>> output_packs_desc;
968 if (n_plus_x_recs)
969 {
970 uchar* raw_kxmer_counters = nullptr;
971 memory_bins->reserve(bin_id, raw_kxmer_counters, CMemoryBins::mba_kxmer_counters);
972 kxmer_counters = (uint32*)raw_kxmer_counters;
973 uint64 compacted_count;
974 PreCompactKxmers(compacted_count);
975
976 uint64 pos[5];//pos[symb] is first position where symb occur (at first position of k+x-mer) and pos[symb+1] is first position where symb is not starting symbol of k+x-mer
977 pos[0] = 0;
978 pos[4] = compacted_count;
979 for (uint32 i = 1; i < 4; ++i)
980 pos[i] = FindFirstSymbOccur(pos[i - 1], compacted_count, 0, i);
981
982 if (n_sorting_threads > 1)
983 {
984 CKXmerSetMultiThreaded<SIZE> kxmer_set_multithreaded(buffer, kxmer_counters, compacted_count,
985 cutoff_min, cutoff_max, counter_max, kmer_len, lut_prefix_len, lut, out_buffer, n_sorting_threads);
986
987 for (uint32 i = 1; i < 5; ++i)
988 InitKXMerSetMultithreaded(kxmer_set_multithreaded, pos[i - 1], pos[i], max_x + 2 - i, i);
989
990 kxmer_set_multithreaded.Process(without_output, output_type);
991
992 kxmer_set_multithreaded.GetStats(n_unique, n_cutoff_min, n_cutoff_max, n_total);
993 output_packs_desc = std::move(kxmer_set_multithreaded.GetOutputPacksDesc());
994 }
995 else
996 {
997 uint64 out_pos = 0;
998 for (uint32 i = 1; i < 5; ++i)
999 InitKXMerSet(pos[i - 1], pos[i], max_x + 2 - i, i);
1000
1001 uint64 counter_pos = 0;
1002 uint64 counter_size = calc_counter_size(cutoff_max, counter_max);
1003
1004 CKmer<SIZE> kmer, next_kmer;
1005 kmer.clear();
1006 next_kmer.clear();
1007 CKmer<SIZE> kmer_mask;
1008 kmer_mask.set_n_1(kmer_len * 2);
1009 uint32 count;
1010 //first
1011 kxmer_set.get_min(counter_pos, kmer);
1012 count = kxmer_counters[counter_pos];
1013 //rest
1014 while (kxmer_set.get_min(counter_pos, next_kmer))
1015 {
1016 if (kmer == next_kmer)
1017 count += kxmer_counters[counter_pos];
1018 else
1019 {
1020 n_total += count;
1021 ++n_unique;
1022 if (count < cutoff_min)
1023 n_cutoff_min++;
1024 else if (count >cutoff_max)
1025 n_cutoff_max++;
1026 else
1027 {
1028 if (count > counter_max)
1029 count = counter_max;
1030
1031 if (!without_output)
1032 {
1033 if(output_type == OutputType::KMC)
1034 {
1035 lut[kmer.remove_suffix(2 * kmer_symbols)]++;
1036 // Store compacted kmer
1037
1038 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1039 out_buffer[out_pos++] = kmer.get_byte(j);
1040 for (int32 j = 0; j < (int32)counter_size; ++j)
1041 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1042 }
1043 else if (output_type == OutputType::KFF)
1044 {
1045 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1046 out_buffer[out_pos++] = kmer.get_byte(j);
1047
1048 for (int32 j = (int32)counter_size - 1; j >= 0; --j)
1049 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1050 }
1051 else
1052 {
1053 std::ostringstream ostr;
•1054 ostr << "Error: not implemented, please contact authors showing this message" << __FILE__ << "\t" << __LINE__;
1055 CCriticalErrorHandler::Inst().HandleCriticalError(ostr.str());
1056 }
1057 }
1058 }
1059 count = kxmer_counters[counter_pos];
1060 kmer = next_kmer;
1061 }
1062 }
1063
1064 //last one
1065 ++n_unique;
1066 n_total += count;
1067 if (count < cutoff_min)
1068 n_cutoff_min++;
1069 else if (count >cutoff_max)
1070 n_cutoff_max++;
1071 else
1072 {
1073
1074 if (count > counter_max)
1075 count = counter_max;
1076
1077 if (!without_output)
1078 {
1079 if (output_type == OutputType::KMC)
1080 {
1081 lut[kmer.remove_suffix(2 * kmer_symbols)]++;
1082 // Store compacted kmer
1083
1084 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1085 out_buffer[out_pos++] = kmer.get_byte(j);
1086 for (int32 j = 0; j < (int32)counter_size; ++j)
1087 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1088 }
1089 else if (output_type == OutputType::KFF)
1090 {
1091 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1092 out_buffer[out_pos++] = kmer.get_byte(j);
1093 for (int32 j = (int32)counter_size - 1; j >= 0; --j)
1094 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1095 }
1096 else
1097 {
1098 std::ostringstream ostr;
•1099 ostr << "Error: not implemented, please contact authors showing this message" << __FILE__ << "\t" << __LINE__;
1100 CCriticalErrorHandler::Inst().HandleCriticalError(ostr.str());
1101 }
1102 }
1103 }
1104
1105 if(!without_output)
1106 output_packs_desc.emplace_back(0, out_pos);
1107 }
1108
1109 memory_bins->free(bin_id, CMemoryBins::mba_kxmer_counters);
1110 }
1111
1112
1113 // Push the sorted and compacted kmer bin to a queue in a form ready to be stored to HDD
1114 kq->push(bin_id, out_buffer, output_packs_desc, raw_lut, lut_size, n_unique, n_cutoff_min, n_cutoff_max, n_total);
1115
1116 if (buffer_input)
1117 {
1118 memory_bins->free(bin_id, CMemoryBins::mba_input_array);
1119 memory_bins->free(bin_id, CMemoryBins::mba_tmp_array);
1120 }
1121 buffer = nullptr;
1122 }
1123
1124
1125
1126
1127 //----------------------------------------------------------------------------------
1128 template <unsigned SIZE> void CKmerBinSorter<SIZE>::CompactKmers()
1129 {
1130 uint64 i;
1131
1132 uint32 kmer_symbols = kmer_len - lut_prefix_len;
1133 uint64 kmer_bytes = kmer_symbols / 4;
1134 if (lut_prefix_len == 0) //do not split data to prefix and sufix (for example when storying result in KFF)
1135 kmer_bytes = (kmer_symbols + 3) / 4;
1136
1137 uint64 lut_recs = 1ull << (2 * (lut_prefix_len));
1138 if (lut_prefix_len == 0)
1139 lut_recs = 0;
1140 uint64 lut_size = lut_recs * sizeof(uint64);
1141
1142 uint64 counter_size = calc_counter_size(cutoff_max, counter_max);
1143
1144 uchar *out_buffer;
1145 uchar *raw_lut;
1146
1147 memory_bins->reserve(bin_id, out_buffer, CMemoryBins::mba_suffix);
1148 memory_bins->reserve(bin_id, raw_lut, CMemoryBins::mba_lut);
1149 uint64 *lut = (uint64*)raw_lut;
1150 fill_n(lut, lut_recs, 0);
1151
1152 uint64 out_pos = 0;
1153 uint32 count;
1154 CKmer<SIZE> *act_kmer;
1155
1156 n_unique = 0;
1157 n_cutoff_min = 0;
1158 n_cutoff_max = 0;
1159 n_total = 0;
1160
1161 if (n_rec) // non-empty bin
1162 {
1163 act_kmer = &buffer[0];
1164 count = 1;
1165
1166 n_total = n_rec;
1167
1168 for (i = 1; i < n_rec; ++i)
1169 {
1170 if (*act_kmer == buffer[i])
1171 count++;
1172 else
1173 {
1174 if (count < cutoff_min)
1175 {
1176 act_kmer = &buffer[i];
1177 n_cutoff_min++;
1178 n_unique++;
1179 count = 1;
1180 }
1181 else if (count > cutoff_max)
1182 {
1183 act_kmer = &buffer[i];
1184 n_cutoff_max++;
1185 n_unique++;
1186 count = 1;
1187 }
1188 else
1189 {
1190 if (count > counter_max)
1191 count = counter_max;
1192
1193 if (!without_output)
1194 {
1195 if (output_type == OutputType::KMC)
1196 {
1197 // Store compacted kmer
1198 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1199 out_buffer[out_pos++] = act_kmer->get_byte(j);
1200 for (int32 j = 0; j < (int32)counter_size; ++j)
1201 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1202
1203 lut[act_kmer->remove_suffix(2 * kmer_symbols)]++;
1204 }
1205 else if (output_type == OutputType::KFF)
1206 {
1207 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1208 out_buffer[out_pos++] = act_kmer->get_byte(j);
1209
1210 for (int32 j = (int32)counter_size - 1; j >= 0; --j)
1211 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1212 }
1213 else
1214 {
1215 std::ostringstream ostr;
•1216 ostr << "Error: not implemented, please contact authors showing this message" << __FILE__ << "\t" << __LINE__;
1217 CCriticalErrorHandler::Inst().HandleCriticalError(ostr.str());
1218 }
1219 }
1220 act_kmer = &buffer[i];
1221 count = 1;
1222 n_unique++;
1223 }
1224 }
1225 }
1226
1227 if (count < cutoff_min)
1228 {
1229 n_cutoff_min++;
1230 }
1231 else if (count > cutoff_max)
1232 {
1233 n_cutoff_max++;
1234 }
1235 else
1236 {
1237 if (count > counter_max)
1238 count = counter_max;
1239
1240 if (!without_output)
1241 {
1242 if (output_type == OutputType::KMC)
1243 {
1244 // Store compacted kmer
1245 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1246 out_buffer[out_pos++] = act_kmer->get_byte(j);
1247 for (int32 j = 0; j < (int32)counter_size; ++j)
1248 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1249
1250 lut[act_kmer->remove_suffix(2 * kmer_symbols)]++;
1251 }
1252 else if (output_type == OutputType::KFF)
1253 {
1254 for (int32 j = (int32)kmer_bytes - 1; j >= 0; --j)
1255 out_buffer[out_pos++] = act_kmer->get_byte(j);
1256 for (int32 j = (int32)counter_size - 1; j >= 0; --j)
1257 out_buffer[out_pos++] = (count >> (j * 8)) & 0xFF;
1258 }
1259 else
1260 {
1261 std::ostringstream ostr;
•1262 ostr << "Error: not implemented, please contact authors showing this message" << __FILE__ << "\t" << __LINE__;
1263 CCriticalErrorHandler::Inst().HandleCriticalError(ostr.str());
1264 }
1265 }
1266 }
1267 n_unique++;
1268 }
1269 list<pair<uint64, uint64>> data_packs;
1270 if(!without_output)
1271 data_packs.emplace_back(0, out_pos);
1272 // Push the sorted and compacted kmer bin to a priority queue in a form ready to be stored to HDD
1273 kq->push(bin_id, out_buffer, data_packs, raw_lut, lut_size, n_unique, n_cutoff_min, n_cutoff_max, n_total);
1274
1275 if (buffer_input)
1276 {
1277 memory_bins->free(bin_id, CMemoryBins::mba_input_array);
1278 memory_bins->free(bin_id, CMemoryBins::mba_tmp_array);
1279 }
1280 buffer = nullptr;
1281 }
1282
1283
1284
1285
1286 //----------------------------------------------------------------------------------
1287 template <unsigned SIZE> void CKmerBinSorter<SIZE>::Compact()
1288 {
1289 if (max_x)
1290 CompactKxmers();
1291 else
1292 CompactKmers();
1293 }
1294
1295 //************************************************************************************************************
1296 // CWKmerBinSorter - wrapper for multithreading purposes
1297 //************************************************************************************************************
1298 template <unsigned SIZE> class CWKmerBinSorter {
1299 std::unique_ptr<CKmerBinSorter<SIZE>> kbs;
1300
1301 public:
1302 CWKmerBinSorter(CKMCParams &Params, CKMCQueues &Queues, SortFunction<CKmer<SIZE>> sort_func);
1303 void GetDebugStats(uint64& _sum_n_recs, uint64& _sum_n_plus_x_recs)
1304 {
1305 kbs->GetDebugStats(_sum_n_recs, _sum_n_plus_x_recs);
1306 }
1307 void operator()();
1308 };
1309
1310 //----------------------------------------------------------------------------------
1311 // Constructor
1312 template <unsigned SIZE> CWKmerBinSorter<SIZE>::CWKmerBinSorter(CKMCParams &Params, CKMCQueues &Queues, SortFunction<CKmer<SIZE>> sort_func)
1313 {
1314 kbs = std::make_unique<CKmerBinSorter<SIZE>>(Params, Queues, sort_func);
1315 }
1316
1317 //----------------------------------------------------------------------------------
1318 // Execution
1319 template <unsigned SIZE> void CWKmerBinSorter<SIZE>::operator()()
1320 {
1321 kbs->ProcessBins();
1322 }
1323
1324
1325 #endif
1326 // ***** EOF