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
use anyhow::{bail, Context, Result};
use atty::Stream;
use gfa::optfields::{OptField, OptFieldVal::*};
use petgraph::graph::NodeIndex;
use std::collections::HashMap;
use std::fmt;

/// Format a sequence length (`usize`) to kilobases.
pub fn format_usize_to_kb(num: usize) -> String {
    let div = num as f32 / 1000f32;
    format!("{:.2}Kb", div)
}

/// Check if there is anything coming from STDIN.
pub fn is_stdin() -> bool {
    !atty::is(Stream::Stdin)
}

/// Get the coverage associated with an edge (`ec` tag in the GFA).
pub fn get_edge_coverage(options: &[OptField]) -> Result<i64> {
    if let Some(op) = options.iter().next() {
        match op.tag {
            // ec
            [101, 99] => match op.value {
                Int(i) => return Ok(i),
                _ => bail!("Could not find integer ec:i:<i64> tag."),
            },
            _ => bail!("Could not find ec (edge coverage) tag."),
        };
    }
    bail!("Edge coverage not found.")
}

/// Format a GFA option field into a string.
pub fn get_option_string(options: Vec<OptField>) -> Result<String> {
    let mut tag_val = String::new();
    for op in options {
        let tag = std::str::from_utf8(&op.tag)
            .with_context(|| format!("Malformed UTF8: {:?}", op.tag))?;
        let value = match op.value {
            Float(f) => format!(":f:{:.3}", f),
            A(a) => format!(":A:{}", a),
            Int(i) => format!(":i:{}", i),
            Z(z) => format!(
                ":Z:{}",
                std::str::from_utf8(&z).with_context(|| format!("Malformed UTF8: {:?}", z))?
            ),
            // J(j) => ???,
            // a hexadecimal array
            H(h) => format!(":H:{}", h.iter().map(|x| x.to_string()).collect::<String>()),
            // B is a general array
            // is it capital B?
            BInt(bi) => format!(
                ":B:{}",
                bi.iter().map(|x| x.to_string()).collect::<String>()
            ),
            BFloat(bf) => format!(
                ":B:{}",
                bf.iter().map(|x| format!("{:.3}", x)).collect::<String>()
            ),
            _ => "".to_string(),
        };
        tag_val += &format!("{}{}\t", tag, value);
    }
    // should always end in \t ^
    let tag_val_op_un = tag_val
        .strip_suffix('\t')
        .context("Could not strip a tab from the suffix of the tag.")?;
    Ok(tag_val_op_un.to_string())
}

/// Parse a CIGAR string slice into an overlap length.
pub fn parse_cigar(cigar: &[u8]) -> Result<usize> {
    // check it ends with an M
    if !cigar.ends_with(&[77]) {
        bail!(
            "CIGAR string did not end with M: {}",
            std::str::from_utf8(cigar).with_context(|| format!("Malformed UTF8: {:?}", cigar))?
        );
    }
    let stripped = cigar.strip_suffix(&[77]);
    match stripped {
        Some(s) => {
            let string_rep =
                std::str::from_utf8(s).with_context(|| format!("Malformed UTF8: {:?}", s))?;
            Ok(string_rep
                .parse::<usize>()
                .with_context(|| format!("{} could not be parsed to <usize>", string_rep))?)
        }
        None => bail!("Could not strip suffix (M) of the CIGAR string."),
    }
}

/// Reverse complement a string slice.
pub fn reverse_complement(dna: &[u8]) -> Vec<u8> {
    let dna_vec = dna.to_vec();
    let mut revcomp = Vec::new();

    for base in dna_vec.iter() {
        revcomp.push(switch_base(*base))
    }
    revcomp.as_mut_slice().reverse();
    revcomp
}

/// Used in `reverse_complement` to switch to a complementary base.
fn switch_base(c: u8) -> u8 {
    match c {
        b'A' => b'T',
        b'a' => b't',
        b'C' => b'G',
        b'c' => b'g',
        b'T' => b'A',
        b't' => b'a',
        b'G' => b'C',
        b'g' => b'c',
        b'N' => b'N',
        b'n' => b'n',
        _ => b'N',
    }
}

// pinched from past Max
// https://github.com/tolkit/fasta_windows/blob/master/src/seq_statsu8.rs

/// Collect nucleotide counts into a `HashMap`.
fn nucleotide_counts(dna: &[u8]) -> HashMap<&u8, i32> {
    let mut map = HashMap::new();
    for nucleotide in dna {
        let count = map.entry(nucleotide).or_insert(0);
        *count += 1;
    }
    map
}

/// Calculate the GC content of a string slice.
pub fn gc_content(dna: &[u8]) -> f32 {
    // G/C/A/T counts
    // upper + lower
    let counts = nucleotide_counts(dna);
    let g_counts = counts.get(&71).unwrap_or(&0) + counts.get(&103).unwrap_or(&0);
    let c_counts = counts.get(&67).unwrap_or(&0) + counts.get(&99).unwrap_or(&0);
    let a_counts = counts.get(&65).unwrap_or(&0) + counts.get(&97).unwrap_or(&0);
    let t_counts = counts.get(&84).unwrap_or(&0) + counts.get(&116).unwrap_or(&0);

    (g_counts + c_counts) as f32 / (g_counts + c_counts + a_counts + t_counts) as f32
}

// convert Node Index to segment ID and vice versa
// I rely a lot on this tuple:
// (NodeIndex, usize)
// which stores the node index and it's corresponding segment ID
// I just realise this should 100000% be a hashmap... change that later.

/// A pair consisting of a node index and a segment ID.
#[derive(Clone, Copy, Debug)]
pub struct GFAGraphPair {
    /// The node index (petgraph's `NodeIndex`).
    pub node_index: NodeIndex,
    /// The segment ID.
    pub seg_id: usize,
}
/// A vector of `GFAGraphPair`'s.
///
/// This should 100% have been a map-like structure...
#[derive(Clone, Debug)]
pub struct GFAGraphLookups(pub Vec<GFAGraphPair>);

impl GFAGraphLookups {
    /// Create a new GFAGraphLookups
    pub fn new() -> Self {
        Self(Vec::new())
    }
    /// Push a new `GFAGraphPair` to the end.
    pub fn push(&mut self, other: GFAGraphPair) {
        self.0.push(other);
    }

    /// Return segment ID from a node index.
    pub fn node_index_to_seg_id(&self, node_index: NodeIndex) -> Result<usize> {
        let seg_id = &self
            .0
            .iter()
            .find(|e| e.node_index == node_index)
            .with_context(|| {
                format!(
                    "Node index {:?} could not be converted to segment ID",
                    node_index
                )
            })?
            .seg_id;

        Ok(*seg_id)
    }
    /// Return a node index from a segment ID.
    pub fn seg_id_to_node_index(&self, seg_id: usize) -> Result<NodeIndex> {
        let node_index = &self
            .0
            .iter()
            .find(|e| e.seg_id == seg_id)
            .with_context(|| {
                format!(
                    "Segment ID {:?} could not be converted to NodeIndex",
                    seg_id
                )
            })?
            .node_index;

        Ok(*node_index)
    }
}

impl fmt::Display for GFAGraphLookups {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut output = String::new();
        output += "\n\tSegment ID's:\n\t";

        let mut seg_ids: String = self
            .0
            .iter()
            .map(|pair| pair.seg_id.to_string() + ", ")
            .collect();
        seg_ids.drain(seg_ids.len() - 2..);

        output += &seg_ids;

        writeln!(f, "{}", output)
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_node_seg_id_indexes() {
        let mut gl = GFAGraphLookups::new();
        // just add two pairs
        gl.push(GFAGraphPair {
            node_index: NodeIndex::new(1),
            seg_id: 12,
        });

        gl.push(GFAGraphPair {
            node_index: NodeIndex::new(2),
            seg_id: 10,
        });

        assert_eq!(12, gl.node_index_to_seg_id(NodeIndex::new(1)).unwrap());
        assert_eq!(NodeIndex::new(2), gl.seg_id_to_node_index(10).unwrap());
    }

    #[test]
    fn test_gc_content() {
        let dna_bytes = vec![b'A', b'G', b'G', b'T', b'T', b'C'];

        let gc = gc_content(&dna_bytes);

        assert_eq!(gc, 0.5);
    }

    #[test]
    fn test_cigar_parse() {
        let cigar_ok = "120M".as_bytes();
        let cigar_err = "30M10D20M5I10M".as_bytes();

        let parsed_cigar = parse_cigar(cigar_ok).is_err();
        let parsed_cigar2 = parse_cigar(cigar_err).is_err();

        assert_eq!(parsed_cigar, false);
        assert_eq!(parsed_cigar2, true);
    }
}