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
use crate::gfa::{Link, OptionalField, OptionalFieldValue, Path, Segment, GFA};
use std::fmt::Write;

macro_rules! write_optional {
    ($stream:expr, $path:path, $tag:literal, $val:expr) => {
        if let Some(v) = $val {
            let field = OptionalField {
                tag: $tag.to_string(),
                content: $path(v),
            };
            write!($stream, "\t{}", field).unwrap_or_else(|err| {
                panic!(
                    "Error writing optional field '{:?}' to stream, {:?}",
                    field, err
                )
            })
        }
    };
}

pub fn write_optional_fields<T: Write>(
    fields: &Vec<OptionalField>,
    stream: &mut T,
) {
    for field in fields.iter() {
        write!(stream, "\t{}", field).unwrap_or_else(|err| {
            panic!(
                "Error writing optional field '{:?}' to stream, {:?}",
                field, err
            )
        })
    }
}

pub fn write_header<T: Write>(version: &Option<String>, stream: &mut T) {
    if let Some(v) = version {
        write!(stream, "H\tVN:Z:{}", v).unwrap();
    } else {
        write!(stream, "H").unwrap();
    }
}

// Write segment
pub fn write_segment<T: Write>(seg: &Segment, stream: &mut T) {
    use OptionalFieldValue::*;
    write!(stream, "S\t{}\t{}", seg.name, seg.sequence)
        .expect("Error writing segment to stream");

    let seg = seg.clone();
    write_optional!(stream, SignedInt, "LN", seg.segment_length);
    write_optional!(stream, SignedInt, "RC", seg.read_count);
    write_optional!(stream, SignedInt, "FC", seg.fragment_count);
    write_optional!(stream, SignedInt, "KC", seg.kmer_count);
    write_optional!(stream, ByteArray, "SH", seg.sha256);
    write_optional!(stream, PrintableString, "UR", seg.uri);
    write_optional_fields(&seg.optional_fields, stream);
}

pub fn segment_string(seg: &Segment) -> String {
    let mut result = String::new();
    write_segment(seg, &mut result);
    result
}

// Write link
pub fn write_link<T: Write>(link: &Link, stream: &mut T) {
    use OptionalFieldValue::*;

    write!(
        stream,
        "L\t{}\t{}\t{}\t{}\t{}",
        link.from_segment,
        link.from_orient,
        link.to_segment,
        link.to_orient,
        link.overlap
    )
    .expect("Error writing link to stream");

    let link = link.clone();
    write_optional!(stream, SignedInt, "LN", link.map_quality);
    write_optional!(stream, SignedInt, "RC", link.num_mismatches);
    write_optional!(stream, SignedInt, "RC", link.read_count);
    write_optional!(stream, SignedInt, "FC", link.fragment_count);
    write_optional!(stream, SignedInt, "KC", link.kmer_count);
    write_optional!(stream, PrintableString, "SH", link.edge_id);
    write_optional_fields(&link.optional_fields, stream);
}

pub fn link_string(link: &Link) -> String {
    let mut result = String::new();
    write_link(link, &mut result);
    result
}

// Write path
pub fn write_path<T: Write>(path: &Path, stream: &mut T) {
    write!(stream, "P\t{}\t", path.path_name)
        .expect("Error writing path to stream");
    path.segment_names
        .iter()
        .enumerate()
        .for_each(|(i, (n, o))| {
            if i != 0 {
                write!(stream, ",").unwrap();
            }
            write!(stream, "{}{}", n, o).unwrap();
        });
    write!(stream, "\t").unwrap();
    path.overlaps.iter().enumerate().for_each(|(i, o)| {
        if i != 0 {
            write!(stream, ",").unwrap();
        }
        write!(stream, "{}", o).unwrap();
    });

    write_optional_fields(&path.optional_fields, stream);
}

pub fn path_string(path: &Path) -> String {
    let mut result = String::new();
    write_path(path, &mut result);
    result
}

// Write GFA
pub fn write_gfa<T: Write>(gfa: &GFA, stream: &mut T) {
    write_header(&gfa.version, stream);
    writeln!(stream).unwrap();
    gfa.segments.iter().for_each(|s| {
        write_segment(s, stream);
        writeln!(stream).unwrap();
    });

    gfa.paths.iter().for_each(|p| {
        write_path(p, stream);
        writeln!(stream).unwrap();
    });

    gfa.links.iter().for_each(|l| {
        write_link(l, stream);
        writeln!(stream).unwrap();
    });
}

pub fn gfa_string(gfa: &GFA) -> String {
    let mut result = String::new();
    write_gfa(gfa, &mut result);
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gfa::Orientation;

    #[test]
    fn print_segment() {
        let mut segment = Segment::new("seg1", "GCCCTA");
        segment.read_count = Some(123);
        segment.uri = Some("http://test.com/".to_string());
        let opt1 = OptionalField {
            tag: "IJ".to_string(),
            content: OptionalFieldValue::PrintableChar('x'),
        };
        let opt2 = OptionalField {
            tag: "AB".to_string(),
            content: OptionalFieldValue::IntArray(vec![1, 2, 3, 52124]),
        };
        segment.optional_fields = vec![opt1, opt2];
        let expected = "S\tseg1\tGCCCTA\tRC:i:123\tUR:Z:http://test.com/\tIJ:A:x\tAB:B:I1,2,3,52124";
        let string = segment_string(&segment);
        assert_eq!(string, expected);
    }

    #[test]
    fn print_link() {
        let link = Link::new(
            "13",
            Orientation::Forward,
            "552",
            Orientation::Backward,
            "0M",
        );
        let string = link_string(&link);
        assert_eq!(string, "L\t13\t+\t552\t-\t0M");
    }

    #[test]
    fn print_path() {
        let path = Path::new(
            "path1",
            vec!["13+", "51-", "241+"],
            vec!["8M", "1M", "3M"]
                .into_iter()
                .map(String::from)
                .collect(),
        );

        let string = path_string(&path);
        assert_eq!(string, "P\tpath1\t13+,51-,241+\t8M,1M,3M");
    }

    use std::io::Read;
    use std::path::PathBuf;

    #[test]
    fn print_gfa() {
        let in_gfa =
            crate::parser::parse_gfa(&PathBuf::from("./lil.gfa")).unwrap();
        let mut file =
            std::fs::File::open(&PathBuf::from("./lil.gfa")).unwrap();
        let mut file_string = String::new();
        file.read_to_string(&mut file_string).unwrap();

        let string = gfa_string(&in_gfa);

        assert_eq!(string, file_string);
    }
}