1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
extern crate needletail;
extern crate num;
extern crate quickersort;
extern crate rust_htslib;
extern crate sce;
extern crate scroll;
use crate as libradicl;
use self::libradicl::rad_types::{CorrectedCbChunk, RadIntId, ReadRecord};
use self::libradicl::schema::TempCellInfo;
#[allow(unused_imports)]
use ahash::{AHasher, RandomState};
use bio_types::strand::*;
use dashmap::DashMap;
use scroll::Pread;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use std::io::{BufWriter, Write};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::vec::Vec;
pub mod exit_codes;
pub mod rad_types;
pub mod schema;
pub mod utils;
static LIB_NAME: &str = "libradicl";
pub fn lib_name() -> &'static str {
LIB_NAME
}
#[derive(Serialize, Deserialize, Debug)]
#[allow(dead_code)]
pub struct BarcodeLookupMap {
pub barcodes: Vec<u64>,
offsets: Vec<usize>,
bclen: u32,
prefix_len: u32,
suffix_len: u32,
}
impl BarcodeLookupMap {
pub fn new(mut kv: Vec<u64>, bclen: u32) -> BarcodeLookupMap {
let prefix_len = ((bclen + 1) / 2) as u64;
let suffix_len = bclen - prefix_len as u32;
let _prefix_bits = 2 * prefix_len;
let suffix_bits = 2 * suffix_len;
kv.sort_unstable();
let pref_mask = ((4usize.pow(prefix_len as u32) - 1) as u64) << (suffix_bits);
let mut offsets = vec![0; 4usize.pow(prefix_len as u32) + 1];
let mut prev_ind = 0xFFFF;
for (n, &v) in kv.iter().enumerate() {
let ind = ((v & pref_mask) >> (suffix_bits)) as usize;
if ind != prev_ind {
for item in offsets.iter_mut().take(ind).skip(prev_ind + 1) {
*item = n;
}
offsets[ind] = n;
prev_ind = ind;
}
}
for item in offsets.iter_mut().skip(prev_ind + 1) {
*item = kv.len();
}
BarcodeLookupMap {
barcodes: kv,
offsets,
bclen,
prefix_len: prefix_len as u32,
suffix_len,
}
}
#[allow(dead_code)]
pub fn barcode_for_idx(&self, idx: usize) -> u64 {
self.barcodes[idx]
}
pub fn find_exact(&self, query: u64) -> Option<usize> {
let mut ret: Option<usize> = None;
let suffix_bits = 2 * self.suffix_len;
let query_pref = query >> suffix_bits;
let qrange = std::ops::Range {
start: self.offsets[query_pref as usize],
end: self.offsets[(query_pref + 1) as usize],
};
let qs = qrange.start as usize;
if let Ok(res) = self.barcodes[qrange].binary_search(&query) {
ret = Some(qs + res);
}
ret
}
pub fn find_neighbors(&self, query: u64, try_exact: bool) -> (Option<usize>, usize) {
let mut ret: Option<usize> = None;
let pref_bits = 2 * self.prefix_len;
let suffix_bits = 2 * self.suffix_len;
let mut query_pref = query >> suffix_bits;
let mut num_neighbors = 0usize;
let qrange = std::ops::Range {
start: self.offsets[query_pref as usize],
end: self.offsets[(query_pref + 1) as usize],
};
let qs = qrange.start as usize;
if try_exact {
if let Ok(res) = self.barcodes[qrange.clone()].binary_search(&query) {
ret = Some(qs + res);
num_neighbors += 1;
return (ret, num_neighbors);
}
}
if !(std::ops::Range::<usize>::is_empty(&qrange)) {
let qs = qrange.start as usize;
for i in (0..suffix_bits).step_by(2) {
let bit_mask = 3 << (i);
for nmod in 1..4 {
let nucl = 0x3 & ((query >> i) + nmod);
let nquery = (query & (!bit_mask)) | (nucl << i);
if let Ok(res) = self.barcodes[qrange.clone()].binary_search(&nquery) {
ret = Some(qs + res);
num_neighbors += 1;
if num_neighbors >= 2 {
return (ret, num_neighbors);
}
}
}
}
}
{
for i in (suffix_bits..(suffix_bits + pref_bits)).step_by(2) {
let bit_mask = 3 << i;
for nmod in 1..4 {
let nucl = 0x3 & ((query >> i) + nmod);
let nquery = (query & (!bit_mask)) | (nucl << i);
query_pref = nquery >> suffix_bits;
let qrange = std::ops::Range {
start: self.offsets[query_pref as usize],
end: self.offsets[(query_pref + 1) as usize],
};
let qs = qrange.start as usize;
if let Ok(res) = self.barcodes[qrange].binary_search(&nquery) {
ret = Some(qs + res);
num_neighbors += 1;
if num_neighbors >= 2 {
return (ret, num_neighbors);
}
}
}
}
}
(ret, num_neighbors)
}
}
impl CorrectedCbChunk {
pub fn from_label_and_counter(corrected_bc_in: u64, num_remain: u32) -> CorrectedCbChunk {
let mut cc = CorrectedCbChunk {
remaining_records: num_remain,
corrected_bc: corrected_bc_in,
nrec: 0u32,
data: Cursor::new(Vec::<u8>::with_capacity((num_remain * 24) as usize))
};
let dummy = 0u32;
cc.data.write_all(&dummy.to_le_bytes()).unwrap();
cc.data.write_all(&dummy.to_le_bytes()).unwrap();
cc
}
}
#[derive(Debug, Clone)]
pub struct GlobalEqCellList {
cell_ids: Vec<usize>,
count: u32,
}
impl GlobalEqCellList {
pub fn from_umi_and_count(bc_mer: usize, count: u32) -> GlobalEqCellList {
let mut cc = GlobalEqCellList {
cell_ids: Vec::new(),
count: 0,
};
cc.cell_ids.push(bc_mer);
cc.count += count;
cc
}
pub fn add_element(&mut self, bc_mer: usize, count: u32) {
self.cell_ids.push(bc_mer);
self.count += count;
}
}
#[inline]
pub fn dump_chunk(v: &mut CorrectedCbChunk, owriter: &Mutex<BufWriter<File>>) {
v.data.set_position(0);
let nbytes = (v.data.get_ref().len()) as u32;
let nrec = v.nrec;
v.data.write_all(&nbytes.to_le_bytes()).unwrap();
v.data.write_all(&nrec.to_le_bytes()).unwrap();
owriter.lock().unwrap().write_all(v.data.get_ref()).unwrap();
}
pub fn collate_temporary_bucket_twopass<T: Read + Seek, U: Write>(
reader: &mut BufReader<T>,
bct: &RadIntId,
umit: &RadIntId,
nrec: u32,
owriter: &Mutex<U>,
compress: bool,
cb_byte_map: &mut HashMap<u64, TempCellInfo, ahash::RandomState>,
) -> usize {
let mut tbuf = vec![0u8; 65536];
let mut total_bytes = 0usize;
let header_size = 2 * std::mem::size_of::<u32>() as u64;
let size_of_u32 = std::mem::size_of::<u32>();
let size_of_bc = bct.bytes_for_type();
let size_of_umi = umit.bytes_for_type();
let calc_record_bytes = |num_aln: usize| -> usize {
size_of_u32 + size_of_bc + size_of_umi + (size_of_u32 * num_aln)
};
for _ in 0..(nrec as usize) {
let tup = ReadRecord::from_bytes_record_header(reader, bct, umit);
let v = cb_byte_map.entry(tup.0).or_insert(TempCellInfo {
offset: header_size,
nbytes: header_size as u32,
nrec: 0_u32,
});
let na = tup.2 as usize;
let req_size = size_of_u32 * na;
if tbuf.len() < req_size {
tbuf.resize(req_size, 0);
}
reader.read_exact(&mut tbuf[0..(size_of_u32 * na)]).unwrap();
let nbytes = calc_record_bytes(na);
(*v).offset += nbytes as u64;
(*v).nbytes += nbytes as u32;
(*v).nrec += 1;
total_bytes += nbytes as usize;
}
total_bytes += cb_byte_map.len() * header_size as usize;
let mut output_buffer = Cursor::new(vec![0u8; total_bytes]);
let mut next_offset = 0u64;
for (_, v) in cb_byte_map.iter_mut() {
output_buffer.set_position(next_offset);
let cell_bytes = (*v).nbytes as u32;
let cell_rec = (*v).nrec as u32;
output_buffer.write_all(&cell_bytes.to_le_bytes()).unwrap();
output_buffer.write_all(&cell_rec.to_le_bytes()).unwrap();
(*v).offset = output_buffer.position();
let nbytes = (*v).nbytes as u64;
next_offset += nbytes;
}
reader
.get_mut()
.seek(SeekFrom::Start(0))
.expect("could not get read pointer.");
for _ in 0..(nrec as usize) {
let tup = ReadRecord::from_bytes_record_header(reader, bct, umit);
if let Some(v) = cb_byte_map.get_mut(&tup.0) {
output_buffer.set_position(v.offset);
let na = tup.2 as usize;
let nau32 = na as u32;
output_buffer.write_all(&nau32.to_le_bytes()).unwrap();
bct.write_to(tup.0, &mut output_buffer).unwrap();
umit.write_to(tup.1, &mut output_buffer).unwrap();
reader
.read_exact(&mut tbuf[0..(size_of_u32 as usize * na)])
.unwrap();
output_buffer
.write_all(&tbuf[..(size_of_u32 as usize * na)])
.unwrap();
(*v).offset = output_buffer.position();
} else {
panic!("should not have any barcodes we can't find");
}
}
output_buffer.set_position(0);
if compress {
let mut compressed_output =
snap::write::FrameEncoder::new(Cursor::new(Vec::<u8>::with_capacity(total_bytes)));
compressed_output
.write_all(output_buffer.get_ref())
.expect("could not compress the output chunk.");
output_buffer = compressed_output
.into_inner()
.expect("couldn't unwrap the FrameEncoder.");
output_buffer.set_position(0);
}
owriter
.lock()
.unwrap()
.write_all(output_buffer.get_ref())
.unwrap();
cb_byte_map.len()
}
pub fn collate_temporary_bucket<T: Read>(
reader: &mut T,
bct: &RadIntId,
umit: &RadIntId,
_nchunks: u32,
nrec: u32,
output_cache: &mut HashMap<u64, CorrectedCbChunk, ahash::RandomState>,
) {
let mut tbuf = [0u8; 65536];
let est_num_rec = 1;
for _ in 0..(nrec as usize) {
let tup = ReadRecord::from_bytes_record_header(reader, bct, umit);
let v = output_cache
.entry(tup.0)
.or_insert_with(|| CorrectedCbChunk::from_label_and_counter(tup.0, est_num_rec));
(*v).nrec += 1;
let na = tup.2;
(*v).data.write_all(&na.to_le_bytes()).unwrap();
bct.write_to(tup.0, &mut (*v).data).unwrap();
umit.write_to(tup.1, &mut (*v).data).unwrap();
reader.read_exact(&mut tbuf[0..(4 * na as usize)]).unwrap();
(*v).data.write_all(&tbuf[..(4 * na as usize)]).unwrap();
}
}
pub fn process_corrected_cb_chunk<T: Read>(
reader: &mut T,
bct: &RadIntId,
umit: &RadIntId,
correct_map: &HashMap<u64, u64>,
expected_ori: &Strand,
output_cache: &DashMap<u64, CorrectedCbChunk>,
owriter: &Mutex<BufWriter<File>>,
) {
let mut buf = [0u8; 8];
let mut tbuf = [0u8; 65536];
reader.read_exact(&mut buf).unwrap();
let _nbytes = buf.pread::<u32>(0).unwrap();
let nrec = buf.pread::<u32>(4).unwrap();
for _ in 0..(nrec as usize) {
let tup = ReadRecord::from_bytes_record_header(reader, bct, umit);
if let Some(corrected_id) = correct_map.get(&tup.0) {
let rr = ReadRecord::from_bytes_with_header_keep_ori(
reader,
tup.0,
tup.1,
tup.2,
expected_ori,
);
if let Some(mut v) = output_cache.get_mut(corrected_id) {
v.remaining_records -= 1;
let last_record = v.remaining_records == 0;
if rr.is_empty() {
if last_record {
dump_chunk(&mut v, owriter);
}
continue;
}
v.nrec += 1;
let na = rr.refs.len() as u32;
v.data.write_all(&na.to_le_bytes()).unwrap();
bct.write_to(*corrected_id, &mut v.data).unwrap();
umit.write_to(rr.umi, &mut v.data).unwrap();
v.data.write_all(as_u8_slice(&rr.refs[..])).unwrap();
if last_record {
dump_chunk(&mut v, owriter);
}
}
} else {
reader
.read_exact(&mut tbuf[0..(4 * (tup.2 as usize))])
.unwrap();
}
}
}
pub struct TempBucket {
pub bucket_id: u32,
pub bucket_writer: Arc<Mutex<BufWriter<File>>>,
pub num_chunks: u32,
pub num_records: u32,
pub num_records_written: AtomicU32,
pub num_bytes_written: AtomicU64,
}
impl TempBucket {
pub fn from_id_and_parent(bucket_id: u32, parent: &std::path::Path) -> Self {
TempBucket {
bucket_id,
bucket_writer: Arc::new(Mutex::new(BufWriter::with_capacity(
4096_usize,
File::create(parent.join(&format!("bucket_{}.tmp", bucket_id))).unwrap(),
))),
num_chunks: 0u32,
num_records: 0u32,
num_records_written: AtomicU32::new(0u32),
num_bytes_written: AtomicU64::new(0u64),
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn dump_corrected_cb_chunk_to_temp_file<T: Read>(
reader: &mut BufReader<T>,
bct: &RadIntId,
umit: &RadIntId,
correct_map: &HashMap<u64, u64>,
expected_ori: &Strand,
output_cache: &HashMap<u64, Arc<TempBucket>>,
local_buffers: &mut [Cursor<&mut [u8]>],
flush_limit: usize,
) {
let mut buf = [0u8; 8];
let mut tbuf = vec![0u8; 4096];
reader.read_exact(&mut buf).unwrap();
let _nbytes = buf.pread::<u32>(0).unwrap();
let nrec = buf.pread::<u32>(4).unwrap();
let bc_bytes = bct.bytes_for_type();
let umi_bytes = umit.bytes_for_type();
let na_bytes = std::mem::size_of::<u32>();
let target_id_bytes = std::mem::size_of::<u32>();
for _ in 0..(nrec as usize) {
let tup = ReadRecord::from_bytes_record_header(reader, bct, umit);
if let Some(corrected_id) = correct_map.get(&tup.0) {
let rr = ReadRecord::from_bytes_with_header_keep_ori(
reader,
tup.0,
tup.1,
tup.2,
expected_ori,
);
if rr.is_empty() {
continue;
}
if let Some(v) = output_cache.get(corrected_id) {
let nb = (rr.refs.len() * target_id_bytes + na_bytes + bc_bytes + umi_bytes) as u64;
let buffidx = v.bucket_id as usize;
let bcursor = &mut local_buffers[buffidx];
let len = bcursor.position() as usize;
if len + nb as usize >= flush_limit {
let mut filebuf = v.bucket_writer.lock().unwrap();
filebuf
.write_all(&bcursor.get_ref()[0..len as usize])
.unwrap();
bcursor.set_position(0);
}
let na = rr.refs.len() as u32;
bcursor.write_all(&na.to_le_bytes()).unwrap();
bct.write_to(*corrected_id, bcursor).unwrap();
umit.write_to(rr.umi, bcursor).unwrap();
bcursor.write_all(as_u8_slice(&rr.refs[..])).unwrap();
v.num_records_written.fetch_add(1, Ordering::SeqCst);
v.num_bytes_written.fetch_add(nb, Ordering::SeqCst);
}
} else {
let req_len = target_id_bytes * (tup.2 as usize);
let do_resize = req_len > tbuf.len();
if do_resize {
tbuf.resize(req_len, 0);
}
reader
.read_exact(&mut tbuf[0..(target_id_bytes * (tup.2 as usize))])
.unwrap();
if do_resize {
tbuf.resize(4096, 0);
tbuf.shrink_to_fit();
}
}
}
}
pub fn as_u8_slice(v: &[u32]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<u32>(),
)
}
}
#[cfg(test)]
mod tests {
use crate::BarcodeLookupMap;
#[test]
fn test_barcode_lookup_map() {
let barcode_sv_even = vec![
b"AACC", b"AAGG", b"CAGT", b"CATT", b"GACC", b"GATA", b"TCAG", b"TCGT",
];
let barcode_sv_odd = vec![
b"AACCA", b"AAGGC", b"CAGTA", b"CATTG", b"GACCG", b"GATAC", b"TCAGA", b"TCGTG",
];
let mut barcode_even = Vec::with_capacity(barcode_sv_even.len());
for b in barcode_sv_even.clone() {
if let Some((_, km, _)) =
needletail::bitkmer::BitNuclKmer::new(&b[..], b.len() as u8, false).next()
{
barcode_even.push(km.0);
}
}
let mut barcode_odd = Vec::with_capacity(barcode_sv_odd.len());
for b in barcode_sv_odd.clone() {
if let Some((_, km, _)) =
needletail::bitkmer::BitNuclKmer::new(&b[..], b.len() as u8, false).next()
{
barcode_odd.push(km.0);
}
}
let me = BarcodeLookupMap::new(barcode_even, 4);
let mo = BarcodeLookupMap::new(barcode_odd, 5);
let x = b"CAGA";
if let Some((_, et, _)) =
needletail::bitkmer::BitNuclKmer::new(&x[..], x.len() as u8, false).next()
{
assert_eq!((Some(2), 1), me.find_neighbors(et.0, false));
}
let x = b"CAATG";
if let Some((_, et, _)) =
needletail::bitkmer::BitNuclKmer::new(&x[..], x.len() as u8, false).next()
{
assert_eq!((Some(3), 1), mo.find_neighbors(et.0, false));
}
}
}