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
//! Parser implementation for matrices in UniPROBE format.
//!
//! The [UniPROBE database](http://the_brain.bwh.harvard.edu/uniprobe/index.php)
//! stores DNA-binding sites as Position-Weight Matrices.
//!
//! The UniPROBE files contains a metadata line for each matrix, followed
//! by one line per symbol storing tab-separated scores for the column:
//! ```text
//! Motif XYZ
//! A:	0.179	0.210	0.182	0.25
//! C:	0.268	0.218	0.213	0.25
//! G:	0.383	0.352	0.340	0.25
//! T:	0.383	0.352	0.340	0.25
//! ```

use std::io::BufRead;

use lightmotif::abc::Alphabet;
use lightmotif::dense::DefaultAlignment;
use lightmotif::pwm::FrequencyMatrix;

use crate::error::Error;

mod parse;

// ---

#[derive(Debug, Clone)]
pub struct Record<A: Alphabet> {
    id: String,
    matrix: FrequencyMatrix<A>,
}

impl<A: Alphabet> Record<A> {
    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn matrix(&self) -> &FrequencyMatrix<A> {
        &self.matrix
    }
}

impl<A: Alphabet> AsRef<FrequencyMatrix<A>> for Record<A> {
    fn as_ref(&self) -> &FrequencyMatrix<A> {
        &self.matrix
    }
}

// ---

pub struct Reader<B: BufRead, A: Alphabet> {
    buffer: String,
    bufread: B,
    line: bool,
    _alphabet: std::marker::PhantomData<A>,
}

impl<B: BufRead, A: Alphabet> Reader<B, A> {
    pub fn new(reader: B) -> Self {
        Self {
            bufread: reader,
            buffer: String::new(),
            line: false,
            _alphabet: std::marker::PhantomData,
        }
    }
}

impl<B: BufRead, A: Alphabet> Iterator for Reader<B, A> {
    type Item = Result<Record<A>, Error>;
    fn next(&mut self) -> Option<Self::Item> {
        // advance to first line with content
        while !self.line {
            match self.bufread.read_line(&mut self.buffer) {
                Err(e) => return Some(Err(Error::from(e))),
                Ok(0) => return None,
                Ok(_) => {
                    if !self.buffer.trim().is_empty() {
                        self.line = true;
                    } else {
                        self.buffer.clear();
                    }
                }
            }
        }
        // parse id
        let id = match self::parse::id(&self.buffer) {
            Err(e) => return Some(Err(Error::from(e))),
            Ok((_, x)) => x.to_string(),
        };
        self.line = false;
        self.buffer.clear();

        // parse columns
        let mut columns = Vec::new();
        loop {
            while !self.line {
                match self.bufread.read_line(&mut self.buffer) {
                    Err(e) => return Some(Err(Error::from(e))),
                    Ok(0) => break,
                    Ok(_) => {
                        if !self.buffer.trim().is_empty() {
                            self.line = true;
                        } else {
                            self.buffer.clear();
                        }
                    }
                }
            }
            match self::parse::matrix_column::<A>(&self.buffer) {
                Err(_e) => break,
                Ok((_, column)) => {
                    columns.push(column);
                    self.buffer.clear();
                    self.line = false;
                }
            }
        }

        let matrix = match self::parse::build_matrix::<A, DefaultAlignment>(columns) {
            Err(e) => return Some(Err(Error::from(e))),
            Ok(matrix) => matrix,
        };
        match FrequencyMatrix::<A>::new(matrix) {
            Err(e) => Some(Err(Error::from(e))),
            Ok(matrix) => Some(Ok(Record { id, matrix })),
        }
    }
}

#[cfg(test)]
mod test {

    use lightmotif::Dna;

    #[test]
    fn test_single() {
        let text = concat!(
            "TEST001\n",
            "A:	0.179	0.210	0.182\n",
            "C:	0.268	0.218	0.213\n",
            "G:	0.383	0.352	0.340\n",
            "T:	0.170	0.220	0.265\n",
        );
        let mut reader = super::Reader::<_, Dna>::new(std::io::Cursor::new(text));
        let record = reader.next().unwrap().unwrap();
        assert_eq!(&record.id, "TEST001");
        assert!(reader.next().is_none());
    }

    #[test]
    fn test_multi() {
        let text = concat!(
            "TEST001\n",
            "A:	0.179	0.210	0.182\n",
            "C:	0.268	0.218	0.213\n",
            "G:	0.383	0.352	0.340\n",
            "T:	0.170	0.220	0.265\n",
            "\n",
            "TEST002\n",
            "A:	0.179	0.210	0.182\n",
            "C:	0.268	0.218	0.213\n",
            "G:	0.383	0.352	0.340\n",
            "T:	0.170	0.220	0.265\n",
            "\n",
        );
        let mut reader = super::Reader::<_, Dna>::new(std::io::Cursor::new(text));
        let record = reader.next().unwrap().unwrap();
        assert_eq!(&record.id, "TEST001");
        let record = reader.next().unwrap().unwrap();
        assert_eq!(&record.id, "TEST002");
        assert!(reader.next().is_none());
    }

    #[test]
    fn test_multi_concatenated() {
        let text = concat!(
            "TEST001\n",
            "A:	0.179	0.210	0.182\n",
            "C:	0.268	0.218	0.213\n",
            "G:	0.383	0.352	0.340\n",
            "T:	0.170	0.220	0.265\n",
            "TEST002\n",
            "A:	0.179	0.210	0.182\n",
            "C:	0.268	0.218	0.213\n",
            "G:	0.383	0.352	0.340\n",
            "T:	0.170	0.220	0.265\n",
        );
        let mut reader = super::Reader::<_, Dna>::new(std::io::Cursor::new(text));
        let record = reader.next().unwrap().unwrap();
        assert_eq!(&record.id, "TEST001");
        let record = reader.next().unwrap().unwrap();
        assert_eq!(&record.id, "TEST002");
        assert!(reader.next().is_none());
    }
}