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
use std::cmp;
use std::collections::HashMap;

use minhashes::KmerCount;
use statistics::hist;


/// Used to pass around filter options for sketching
pub struct FilterParams {
    pub filter_on: Option<bool>,
    pub abun_filter: (Option<u16>, Option<u16>),
    pub err_filter: f32,
    pub strand_filter: f32,
}

/// Applies filter options to a sketch
pub fn filter_sketch(hashes: &[KmerCount], filters: &FilterParams) -> (Vec<KmerCount>, HashMap<String, String>) {
    let filter_on = filters.filter_on.expect("Sorry! Filter should have either been passed or set during detection");
    let mut filter_stats: HashMap<String, String> = HashMap::new();

    let mut low_abun_filter = filters.abun_filter.0;

    if filter_on && filters.err_filter > 0f32 {
        let cutoff = guess_filter_threshold(&hashes, filters.err_filter);
        if let None = low_abun_filter {
            low_abun_filter = Some(cutoff);
            filter_stats.insert(String::from("errFilter"), filters.err_filter.to_string());
        }
    }

    let mut filtered_hashes = hashes.to_vec();
    if filter_on && (low_abun_filter != None || filters.abun_filter.1 != None) {
        filtered_hashes = filter_abundance(&filtered_hashes, low_abun_filter, filters.abun_filter.1);
        if let Some(v) = low_abun_filter {
            filter_stats.insert(String::from("minCopies"), v.to_string());
        }
        if let Some(v) = filters.abun_filter.1 {
            filter_stats.insert(String::from("maxCopies"), v.to_string());
        }
    }

    if filter_on && filters.strand_filter > 0f32 {
        filtered_hashes = filter_strands(&filtered_hashes, filters.strand_filter);
        filter_stats.insert(String::from("strandFilter"), filters.strand_filter.to_string());
    }

    (filtered_hashes, filter_stats)
}


/// Determines a dynamic filtering threshold for low abundance kmers
///
/// Useful for removing, e.g. kmers containing sequencing errors
///
pub fn guess_filter_threshold(sketch: &[KmerCount], filter_level: f32) -> u16 {
    let hist_data = hist(sketch);
    let total_counts = hist_data.iter().enumerate().map(|t| (t.0 as u64 + 1) * t.1).sum::<u64>() as f32;
    let cutoff_amt = filter_level * total_counts;

    // calculate the coverage that N% of the weighted data is above
    let mut wgt_cutoff: usize = 1;
    let mut cum_count: u64 = 0;
    for count in &hist_data {
        cum_count += wgt_cutoff as u64 * *count as u64;
        if cum_count as f32 > cutoff_amt {
            break;
        }
        wgt_cutoff += 1;
    }

    if wgt_cutoff <= 2 {
        return wgt_cutoff as u16;
    }

    // now find the right-most global maxima
    let win_size = cmp::max(1, wgt_cutoff / 20);
    let mut sum: u64 = hist_data[..win_size].iter().sum();
    let mut lowest_val = sum;
    let mut lowest_idx = win_size;
    for (i, j) in (0..wgt_cutoff - win_size).zip(win_size..wgt_cutoff) {
        if sum <= lowest_val {
            lowest_val = sum;
            lowest_idx = j;
        }
        sum -= hist_data[i];
        sum += hist_data[j];
    }

    lowest_idx as u16
}

#[test]
fn test_guess_filter_threshold() {
    let sketch = vec![];
    let cutoff = guess_filter_threshold(&sketch, 0.2);
    assert_eq!(cutoff, 1);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
    ];
    let cutoff = guess_filter_threshold(&sketch, 0.2);
    assert_eq!(cutoff, 1);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 1, extra_count: 0},
    ];
    let cutoff = guess_filter_threshold(&sketch, 0.2);
    assert_eq!(cutoff, 1);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 9, extra_count: 0},
    ];
    let cutoff = guess_filter_threshold(&sketch, 0.2);
    assert_eq!(cutoff, 8);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 10, extra_count: 0},
        KmerCount {hash: 3, kmer: vec![], count: 10, extra_count: 0},
        KmerCount {hash: 4, kmer: vec![], count: 9, extra_count: 0},
    ];
    let cutoff = guess_filter_threshold(&sketch, 0.1);
    assert_eq!(cutoff, 8);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 3, kmer: vec![], count: 2, extra_count: 0},
        KmerCount {hash: 4, kmer: vec![], count: 4, extra_count: 0},
    ];
    let cutoff = guess_filter_threshold(&sketch, 0.1);
    assert_eq!(cutoff, 1);
}


pub fn filter_abundance(sketch: &[KmerCount], low: Option<u16>, high: Option<u16>) -> Vec<KmerCount> {
    let mut filtered = Vec::new();
    let lo_threshold = low.unwrap_or(0u16);
    let hi_threshold = high.unwrap_or(u16::max_value());
    for kmer in sketch {
        if lo_threshold <= kmer.count && kmer.count <= hi_threshold {
            filtered.push(kmer.clone());
        }
    }
    filtered
}

#[test]
fn test_filter_abundance() {
    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 1, extra_count: 0},
    ];
    let filtered = filter_abundance(&sketch, Some(1), None);
    assert_eq!(filtered.len(), 2);
    assert_eq!(filtered[0].hash, 1);
    assert_eq!(filtered[1].hash, 2);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 1, extra_count: 0},
        KmerCount {hash: 2, kmer: vec![], count: 10, extra_count: 0},
        KmerCount {hash: 3, kmer: vec![], count: 10, extra_count: 0},
        KmerCount {hash: 4, kmer: vec![], count: 9, extra_count: 0},
    ];
    let filtered = filter_abundance(&sketch, Some(9), None);
    assert_eq!(filtered.len(), 3);
    assert_eq!(filtered[0].hash, 2);
    assert_eq!(filtered[1].hash, 3);
    assert_eq!(filtered[2].hash, 4);

    let filtered = filter_abundance(&sketch, Some(2), Some(9));
    assert_eq!(filtered.len(), 1);
    assert_eq!(filtered[0].hash, 4);
}


/// Filter out kmers that have a large abundance difference between being seen in the
/// "forward" and "reverse" orientations (picked arbitrarily which is which).
///
/// These tend to be sequencing adapters.
pub fn filter_strands(sketch: &[KmerCount], ratio_cutoff: f32) -> Vec<KmerCount> {
    let mut filtered = Vec::new();
    for kmer in sketch {
        // "special-case" anything with fewer than 16 kmers -> these are too stochastic to accurately
        // determine if something is an adapter or not. The odds of randomly picking less than 10%
        // (0 or 1 reversed kmers) in 16 should be ~ 17 / 2 ** 16 or 1/4000 so we're avoiding
        // removing "good" kmers
        if kmer.count < 16u16 {
            filtered.push(kmer.clone());
            continue;
        }

        // check the forward/reverse ratio and only add if it's within bounds
        let lowest_strand_count: u16 = cmp::min(kmer.extra_count, kmer.count - kmer.extra_count);
        if (lowest_strand_count as f32 / kmer.count as f32) >= ratio_cutoff {
            filtered.push(kmer.clone());
        }
    }
    filtered
}


#[test]
fn test_filter_strands() {
    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 10, extra_count: 1},
        KmerCount {hash: 2, kmer: vec![], count: 10, extra_count: 2},
        KmerCount {hash: 3, kmer: vec![], count: 10, extra_count: 8},
        KmerCount {hash: 4, kmer: vec![], count: 10, extra_count: 9},
    ];
    let filtered = filter_strands(&sketch, 0.15);
    assert_eq!(filtered.len(), 4);
    assert_eq!(filtered[0].hash, 1);
    assert_eq!(filtered[3].hash, 4);

    let sketch = vec![
        KmerCount {hash: 1, kmer: vec![], count: 16, extra_count: 1},
        KmerCount {hash: 2, kmer: vec![], count: 16, extra_count: 2},
        KmerCount {hash: 3, kmer: vec![], count: 16, extra_count: 8},
        KmerCount {hash: 4, kmer: vec![], count: 16, extra_count: 9},
    ];
    let filtered = filter_strands(&sketch, 0.15);
    assert_eq!(filtered.len(), 2);
    assert_eq!(filtered[0].hash, 3);
    assert_eq!(filtered[1].hash, 4);
}