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
#![allow(dead_code)]
mod bwt;
use bwt::Bwt;
use libdivsufsort_rs::{divsufsort64, bw_transform64};
pub struct Config {
kmer_size: Option<usize>,
sa_sampling_ratio: u64,
}
impl Config {
pub fn new() -> Self {
Self {
kmer_size: None,
sa_sampling_ratio: 1,
}
}
#[inline]
pub fn set_kmer_lookup_table(mut self, kmer_size: usize) -> Self {
#[cfg(target_pointer_width = "32")]
let pointer_width: usize = 32;
#[cfg(target_pointer_width = "64")]
let pointer_width: usize = 64;
let max_kmer = pointer_width/2;
if kmer_size < 2 {
panic!("The size of the kmer cannot be less than 2");
} else if kmer_size > max_kmer {
panic!("The size of the kmer cannot be greater than {} which is limited to half of pointer width({} bits) of target system", max_kmer, pointer_width);
} else {
self.kmer_size = Some(kmer_size);
self
}
}
#[inline]
pub fn disable_kmer_lookup_table(mut self) -> Self {
self.kmer_size = None;
self
}
#[inline]
pub fn set_suffix_array_sampling_ratio(mut self, sa_sampling_ratio: u64) -> Self {
if sa_sampling_ratio < 1 {
panic!("The sampling ratio allows only positive integer");
} else {
self.sa_sampling_ratio = sa_sampling_ratio;
self
}
}
}
pub struct FmIndex {
count_array: CountArray,
sampling_ratio: u64,
text_len: u64,
suffix_array: SuffixArray,
kmer_lookup_table: Option<KmerLookupTable>,
bwt: Bwt,
}
impl FmIndex {
#[inline]
pub fn new(config: &Config, text: Vec<u8>) -> Self {
let text_len = text.len() as u64;
let suffix_array = divsufsort64(&text).unwrap();
let (bwt_string, pidx) = {
let mut bwt = text.clone();
let mut sa = suffix_array.clone();
let pidx = bw_transform64(&mut bwt, &mut sa).unwrap();
(bwt, pidx)
};
let suffix_array = compress_suffix_array(suffix_array, config.sa_sampling_ratio);
let bwt = Bwt::new(bwt_string, pidx);
let (count_array, kmer_lookup_table): (CountArray, Option<KmerLookupTable>) = match config.kmer_size {
Some(kmer) => {
let mut count_array: CountArray = [0; 5];
let mut kmer_lookup_table: Vec<u64> = vec![0; 4usize.pow(kmer as u32)];
let mut kmer_iter = text[..].windows(kmer);
while let Some(v) = kmer_iter.next() {
let table_index = kmer_table_index(v);
kmer_lookup_table[table_index] += 1;
match v[0] {
A_UTF8 => count_array[1] += 1,
C_UTF8 => count_array[2] += 1,
G_UTF8 => count_array[3] += 1,
_ => count_array[4] += 1,
}
};
let mut table_index: usize = 0;
let pow = 4_usize.pow(kmer as u32 - 1);
for c in text[text_len as usize-kmer+1..].iter().rev() {
match *c {
A_UTF8 => {
table_index /= 4;
count_array[1] += 1;
},
C_UTF8 => {
table_index /= 4;
table_index += pow;
count_array[2] += 1;
},
G_UTF8 => {
table_index /= 4;
table_index += 2*pow;
count_array[3] += 1;
},
_ => {
table_index /= 4;
table_index += 3*pow;
count_array[4] += 1;
},
}
kmer_lookup_table[table_index] += 1;
}
accumulate_count_array(&mut count_array);
accumulate_count_array(&mut kmer_lookup_table);
(count_array, Some((kmer, kmer_lookup_table)))
},
None => {
let mut count_array: CountArray = [0; 5];
for c in &text {
match *c {
A_UTF8 => count_array[1] += 1,
C_UTF8 => count_array[2] += 1,
G_UTF8 => count_array[3] += 1,
_ => count_array[4] += 1,
}
}
accumulate_count_array(&mut count_array);
(count_array, None)
}
};
Self {
count_array: count_array,
sampling_ratio: config.sa_sampling_ratio,
suffix_array: suffix_array,
text_len: text_len,
kmer_lookup_table: kmer_lookup_table,
bwt: bwt,
}
}
#[inline]
pub fn count(&self, pattern: &[u8]) -> u64 {
let pos_range = self.lf_map(pattern);
pos_range.1 - pos_range.0
}
#[inline]
pub fn locate(&self, pattern: &[u8]) -> Vec<u64> {
let pos_range = self.lf_map(pattern);
let mut locations: Vec<u64> = Vec::with_capacity((pos_range.1 - pos_range.0) as usize);
for mut position in pos_range.0..pos_range.1 {
let mut offset: u64 = 0;
while position % self.sampling_ratio != 0 {
position = self.bwt.lf_map_with_pos(position, &self.count_array);
offset += 1;
}
let location = self.suffix_array[(position / self.sampling_ratio) as usize] + offset;
locations.push(location);
}
locations
}
#[inline]
fn lf_map(&self, pattern: &[u8]) -> (u64, u64) {
let mut idx = pattern.len();
let c = pattern[idx-1];
let mut pos_range = self.pos_range_init(c);
idx -= 1;
while pos_range.0 < pos_range.1 && idx > 0 {
let c = pattern[idx-1];
pos_range = self.bwt.lf_map_with_range(pos_range, c, &self.count_array);
idx -= 1;
}
pos_range
}
#[inline]
fn pos_range_init(&self, c: u8) -> (u64, u64) {
let idx = nc_to_idx(&c);
(self.count_array[idx], self.count_array[idx+1])
}
#[inline]
pub fn locate_with_klt(&self, pattern: &[u8]) -> Vec<u64> {
let (kmer_size, klt) = self.kmer_lookup_table.as_ref().unwrap();
let mut idx = pattern.len();
let pattern_len = idx.clone() as u64;
let mut pos_range: (u64, u64) = {
if *kmer_size >= idx {
let (start_klt_idx, end_kit_idx) = kmer_table_index_from_smaller_string(pattern, kmer_size);
idx -= idx;
if start_klt_idx == 0 {
(0, klt[end_kit_idx])
} else {
(klt[start_klt_idx-1], klt[end_kit_idx])
}
} else {
let kmer_window = &pattern[idx-kmer_size..];
let klt_idx = kmer_table_index(kmer_window);
idx -= kmer_size;
if klt_idx == 0 {
(0, klt[klt_idx])
} else {
(klt[klt_idx-1], klt[klt_idx])
}
}
};
while pos_range.0 < pos_range.1 && idx > 0 {
let c = pattern[idx-1];
pos_range = self.bwt.lf_map_with_range(pos_range, c, &self.count_array);
idx -= 1;
}
let mut locations: Vec<u64> = Vec::with_capacity((pos_range.1 - pos_range.0) as usize);
for mut position in pos_range.0..pos_range.1 {
let mut offset: u64 = 0;
while position % self.sampling_ratio != 0 {
position = self.bwt.lf_map_with_pos(position, &self.count_array);
offset += 1;
}
let location = self.suffix_array[(position / self.sampling_ratio) as usize] + offset;
if location + pattern_len <= self.text_len {
locations.push(location);
}
}
locations
}
}
type CountArray = [u64; 5];
#[inline]
fn accumulate_count_array(count_array: &mut [u64]) {
let mut accumed_count: u64 = 0;
count_array.iter_mut().for_each(|count| {
accumed_count += *count;
*count = accumed_count;
});
}
const A_UTF8: u8 = 65;
const C_UTF8: u8 = 67;
const G_UTF8: u8 = 71;
const T_UTF8: u8 = 84;
const A_U8_IDX: u8 = 0b00;
const C_U8_IDX: u8 = 0b01;
const G_U8_IDX: u8 = 0b10;
const T_U8_IDX: u8 = 0b11;
#[inline]
fn nc_to_idx(c: &u8) -> usize {
match *c {
A_UTF8 => 0,
C_UTF8 => 1,
G_UTF8 => 2,
_ => 3,
}
}
type KmerLookupTable = (usize, Vec<u64>);
#[inline]
fn kmer_table_index(window: &[u8]) -> usize {
window.iter().rev().enumerate().map(|(idx, c)|
4usize.pow(idx as u32) * match *c {
A_UTF8 => 0,
C_UTF8 => 1,
G_UTF8 => 2,
_ => 3,
}
).sum()
}
#[inline]
fn kmer_table_index_from_smaller_string(window: &[u8], kmer: &usize) -> (usize, usize) {
let mut table_index: usize = 0;
let pow = 4_usize.pow(*kmer as u32 - 1);
window.iter().rev().for_each(|c| {
match *c {
A_UTF8 => {
table_index /= 4;
},
C_UTF8 => {
table_index /= 4;
table_index += pow;
},
G_UTF8 => {
table_index /= 4;
table_index += 2*pow;
},
_ => {
table_index /= 4;
table_index += 3*pow;
},
}
});
let offset = 4_usize.pow((*kmer - window.len()) as u32);
(table_index, table_index + offset - 1)
}
type SuffixArray = Vec<u64>;
#[inline]
fn compress_suffix_array(suffix_array: Vec<i64>, sampling_ratio: u64) -> SuffixArray {
if sampling_ratio == 1 {
suffix_array.into_iter().map(|x| x as u64).collect()
} else {
suffix_array.into_iter().step_by(sampling_ratio as usize).map(|x| x as u64).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use fm_index::converter::RangeConverter;
use fm_index::suffix_array::SuffixOrderSampler;
use fm_index::{BackwardSearchIndex, FMIndex};
fn get_locations_using_other_crate(text: &Vec<u8>, pattern: &Vec<u8>) -> Vec<u64> {
let converter = RangeConverter::new(b' ', b'~');
let sampler = SuffixOrderSampler::new().level(2);
let index = FMIndex::new(text.clone(), converter, sampler);
let search = index.search_backward(pattern);
search.locate()
}
#[test]
fn test_compress_suffix_array() {
let raw_suffix_array: Vec<i64> = (0..30).collect();
let sampling_ratio: u64 = 5;
let sa = compress_suffix_array(raw_suffix_array, sampling_ratio);
assert_eq!(sa, vec![0, 5, 10, 15, 20, 25]);
}
#[test]
fn test_fm_index_locate() {
let text = "CTCCGTACACCTGTTTCGTATCGGAACCGGTAAGTGAAATTTCCACATCGCCGGAAACCGTATATTGTCCATCCGCTGCCGGTGGATCCGGCTCCTGCGTGGAAAACCAGTCATCCTGATTTACATATGGTTCAATGGCACCGGATGCATAGATTTCCCCATTTTGCGTACCGGAAACGTGCGCAAGCACGATCTGTGTCTTACC".as_bytes().to_vec();
let config = Config {
sa_sampling_ratio: 4,
kmer_size: None,
};
let fm_index = FmIndex::new(&config, text.clone());
for pattern in vec!["TA", "T", "AAGTGAAATTTCCACATCGCCGGAAAC", "AA", "GGC"] {
let pattern = pattern.as_bytes().to_vec();
let mut locations_res = fm_index.locate(&pattern);
locations_res.sort();
let mut locations_ans = get_locations_using_other_crate(&text, &pattern.to_vec());
locations_ans.sort();
assert_eq!(locations_res, locations_ans);
}
}
#[test]
fn test_fm_index_locate_with_klt() {
let text = "CTCCGTACACCTGTTTCGTATCGGAACCGGTAAGTGAAATTTCCACATCGCCGGAAACCGTATATTGTCCATCCGCTGCCGGTGGATCCGGCTCCTGCGTGGAAAACCAGTCATCCTGATTTACATATGGTTCAATGGCACCGGATGCATAGATTTCCCCATTTTGCGTACCGGAAACGTGCGCAAGCACGATCTGTGTCTTACC".as_bytes().to_vec();
let config = Config {
sa_sampling_ratio: 4,
kmer_size: Some(7),
};
let fm_index = FmIndex::new(&config, text.clone());
for pattern in vec!["TA", "T", "AAGTGAAATTTCCACATCGCCGGAAAC", "AA", "GGC"] {
let pattern = pattern.as_bytes().to_vec();
let mut locations_res = fm_index.locate_with_klt(&pattern);
locations_res.sort();
let mut locations_ans = get_locations_using_other_crate(&text, &pattern.to_vec());
locations_ans.sort();
assert_eq!(locations_res, locations_ans);
}
}
#[test]
fn test_fmindex_with_config() {
let text = b"CTCCGTACACCTGTTTCGTATCGGA".to_vec();
let config = Config::new()
.set_kmer_lookup_table(8)
.set_suffix_array_sampling_ratio(4);
let fm_index = FmIndex::new(&config, text);
let pattern = b"TA".to_vec();
let count = fm_index.count(&pattern);
assert_eq!(count, 2);
let locations = fm_index.locate(&pattern);
assert_eq!(locations, vec![5,18]);
let locations = fm_index.locate_with_klt(&pattern);
assert_eq!(locations, vec![5,18]);
}
#[test]
fn mem_size_check() {
println!("size of FmIndex: {}", std::mem::size_of::<FmIndex>());
println!("size of CountArray: {}", std::mem::size_of::<CountArray>());
println!("size of SuffixArray: {}", std::mem::size_of::<SuffixArray>());
println!("size of KmerLookupTable: {}", std::mem::size_of::<KmerLookupTable>());
println!("size of klt option: {}", std::mem::size_of::<Option<KmerLookupTable>>());
println!("size of Bwt: {}", std::mem::size_of::<Bwt>());
}
}