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
//! This is documentation for the `uniparc_xml_parser` crate.
//!
//!
extern crate flate2;
extern crate quick_xml;

pub mod writer;

mod model;
mod properties;

use std::error::Error;
use std::io::{BufReader, Stdin, Write};
use std::str;

use quick_xml::events::attributes::Attribute;
use quick_xml::events::Event;
use quick_xml::reader::Reader;

use model::{Uniparc, UniparcDomain, UniparcProperty, UniparcXRef};
use properties::Properties;
pub use writer::{initialize_outputs, initialize_outputs_compressed};
use writer::{
    write_uniparc, write_uniparc_domains, write_uniparc_properties, write_uniparc_xrefs,
    OutputBuffers,
};

/// Add new data
fn add_uniparc_xref(
    uniparc_id: String,
    uniparc_xrefs: &mut Vec<UniparcXRef>,
    attributes: Vec<Attribute>,
) -> bool {
    let mut uniparc_xref = UniparcXRef {
        uniparc_id: uniparc_id,
        xref_id: (uniparc_xrefs.len() + 1) as u64,
        db_type: String::new(),
        db_id: String::new(),
        version_i: String::new(),
        active: String::new(),
        version: String::new(),
        created: String::new(),
        last: String::new(),
    };
    for attribute in attributes {
        match attribute.key {
            b"type" => {
                uniparc_xref.db_type = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"id" => {
                uniparc_xref.db_id = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"version_i" => {
                uniparc_xref.version_i = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"active" => {
                uniparc_xref.active = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"version" => {
                uniparc_xref.version = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"created" => {
                uniparc_xref.created = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"last" => {
                uniparc_xref.last = str::from_utf8(attribute.value).unwrap().to_string();
            }
            _ => {
                println!("Skipping attribute '{:?}' for dbReference.", attribute);
            }
        }
    }
    if uniparc_xref.active == "Y" {
        uniparc_xrefs.push(uniparc_xref);
        return true;
    }
    false
}

fn add_property(
    uniparc_id: String,
    uniparc_xrefs: &Vec<UniparcXRef>,
    properties: &mut Properties<Vec<UniparcProperty>>,
    attributes: Vec<Attribute>,
) {
    let attr_type = str::from_utf8(attributes[0].value).unwrap();
    let mut attr_value = str::from_utf8(attributes[1].value).unwrap().to_string();

    let xref_id = uniparc_xrefs.len() as u64;

    if attr_type == "chain" {
        assert!(uniparc_xrefs.last().unwrap().db_type == "PDB");
        attr_value = uniparc_xrefs.last().unwrap().db_id.clone() + &attr_value;
    }

    let (property_vec, attr_type_clean) = match attr_type {
        "NCBI_GI" => (&mut properties.ncbi_gi, String::from("ncbi_gi")),
        "NCBI_taxonomy_id" => (
            &mut properties.ncbi_taxonomy_id,
            String::from("ncbi_taxonomy_id"),
        ),
        "protein_name" => (&mut properties.protein_name, String::from("protein_name")),
        "gene_name" => (&mut properties.gene_name, String::from("gene_name")),
        "chain" => (&mut properties.pdb_chain, String::from("pdb_chain")),
        "UniProtKB_accession" => (
            &mut properties.uniprot_kb_accession,
            String::from("uniprot_kb_accession"),
        ),
        "proteome_id" => (&mut properties.proteome_id, String::from("proteome_id")),
        "component" => (&mut properties.component, String::from("component")),
        _ => panic!("Unmatched value: '{:?}'.", attr_type),
    };

    property_vec.push(UniparcProperty {
        uniparc_id,
        xref_id,
        property: attr_type_clean,
        value: attr_value,
    });
}

fn add_signature_sequence_match(
    uniparc_id: String,
    uniparc_domains: &mut Vec<UniparcDomain>,
    attributes: Vec<Attribute>,
) {
    let mut database = String::new();
    let mut database_id = String::new();
    for attribute in attributes {
        match attribute.key {
            b"database" => {
                database = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"id" => {
                database_id = str::from_utf8(attribute.value).unwrap().to_string();
            }
            _ => panic!("Unmatched value: '{:?}'.", attribute.key),
        }
    }
    let uniparc_domain = UniparcDomain {
        uniparc_id,
        database,
        database_id,
        interpro_name: String::new(),
        interpro_id: String::new(),
        domain_start: 0,
        domain_end: 0,
    };
    uniparc_domains.push(uniparc_domain);
}

fn add_interpro_annotation(uniparc_domains: &mut Vec<UniparcDomain>, attributes: Vec<Attribute>) {
    let mut interpro_name = String::new();
    let mut interpro_id = String::new();
    for attribute in attributes {
        match attribute.key {
            b"name" => {
                interpro_name = str::from_utf8(attribute.value).unwrap().to_string();
            }
            b"id" => {
                interpro_id = str::from_utf8(attribute.value).unwrap().to_string();
            }
            _ => panic!("Unmatched value: '{:?}'.", attribute.key),
        }
    }
    let mut uniparc_domain = uniparc_domains.pop().unwrap();
    assert!(uniparc_domain.interpro_name == "");
    assert!(interpro_name != "");
    assert!(uniparc_domain.interpro_id == "");
    assert!(interpro_name != "");
    uniparc_domain.interpro_name = interpro_name;
    uniparc_domain.interpro_id = interpro_id;
    uniparc_domains.push(uniparc_domain);
}

fn add_domain_definitions(uniparc_domains: &mut Vec<UniparcDomain>, attributes: Vec<Attribute>) {
    let mut domain_start: u32 = 0;
    let mut domain_end: u32 = 0;
    for attribute in attributes {
        match attribute.key {
            b"start" => {
                domain_start = str::from_utf8(attribute.value)
                    .unwrap()
                    .parse::<u32>()
                    .unwrap()
            }
            b"end" => {
                domain_end = str::from_utf8(attribute.value)
                    .unwrap()
                    .parse::<u32>()
                    .unwrap()
            }
            _ => panic!("Unmatched value: '{:?}'.", attribute.key),
        }
    }
    let mut uniparc_domain = uniparc_domains.pop().unwrap();
    assert!(domain_start != 0);
    assert!(domain_end != 0);
    if (uniparc_domain.domain_start == 0) && (uniparc_domain.domain_end == 0) {
        uniparc_domain.domain_start = domain_start;
        uniparc_domain.domain_end = domain_end;
        uniparc_domains.push(uniparc_domain);
    } else {
        let uniparc_domain_bak = uniparc_domain.clone();
        uniparc_domain.domain_start = domain_start;
        uniparc_domain.domain_end = domain_end;
        uniparc_domains.push(uniparc_domain_bak);
        uniparc_domains.push(uniparc_domain);
    }
}

fn add_sequence(uniparc: &mut Uniparc, attributes: Vec<Attribute>) {
    for attribute in attributes {
        match attribute.key {
            b"length" => {
                uniparc.sequence_length = str::from_utf8(attribute.value)
                    .unwrap()
                    .parse::<u32>()
                    .unwrap();
            }
            b"checksum" => {
                uniparc.sequence_checksum = str::from_utf8(attribute.value).unwrap().to_string();
            }
            _ => {
                println!("Skipping attribute '{:?}' for sequence.", attribute);
            }
        }
    }
}

fn attribute_to_string(a: Attribute) -> (String, String) {
    let key = str::from_utf8(a.key).unwrap().to_string();
    let value = str::from_utf8(a.value).unwrap().to_string();
    (key, value)
}

enum TextField {
    Accession,
    Sequence,
}

/// Main loop
pub fn run<T: Write>(
    input_stream: Stdin,
    mut handlers: OutputBuffers<T>,
) -> Result<usize, Box<dyn Error>> {
    let mut reader = Reader::from_reader(BufReader::new(input_stream));
    reader.trim_text(true);

    // Variables created for each UniParc ID
    let mut uniparc: Uniparc = Default::default();
    let mut domains: Vec<UniparcDomain> = Vec::new();
    let mut xrefs: Vec<UniparcXRef> = Vec::new();
    let mut properties: Properties<Vec<UniparcProperty>> = Default::default();

    let mut keep_uniparc_xref = true;
    let mut current_element = Vec::new();

    // Number of UniParc entries that are in the proces of being processed.
    // When we start processing an entry, we *increment* `depth` by 1.
    // When we finish processing an entry, we *decrement* `depth` by 1.
    let mut depth = 0;
    // The number of UniParc sequences that have been processed.
    let mut count = 0;
    let mut buf = Vec::new();

    let mut text_field = TextField::Accession;

    loop {
        match reader.read_event(&mut buf) {
            Ok(Event::Start(ref e)) => {
                match e.name() {
                    b"entry" => {
                        uniparc = Default::default();
                        domains = Vec::new();
                        xrefs = Vec::new();
                        properties = Default::default();
                        count += 1;
                    }
                    b"dbReference" => {
                        keep_uniparc_xref = add_uniparc_xref(
                            uniparc.uniparc_id.clone(),
                            &mut xrefs,
                            e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                        );
                    }
                    b"signatureSequenceMatch" => {
                        add_signature_sequence_match(
                            uniparc.uniparc_id.clone(),
                            &mut domains,
                            e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                        );
                    }
                    b"accession" => {
                        text_field = TextField::Accession;
                    }
                    b"sequence" => {
                        text_field = TextField::Sequence;
                        add_sequence(
                            &mut uniparc,
                            e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                        );
                    }
                    _ => println!(
                        "Skipping StartElement '{}' with attributes {:?}.",
                        str::from_utf8(e.name()).unwrap(),
                        e.attributes()
                            .map(|a| attribute_to_string(a.unwrap()))
                            .collect::<Vec<_>>()
                    ),
                }
                current_element.push(e.name().to_ascii_lowercase());
                depth += 1;
            }
            Ok(Event::Empty(ref e)) => match e.name() {
                b"dbReference" => {
                    add_uniparc_xref(
                        uniparc.uniparc_id.clone(),
                        &mut xrefs,
                        e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                    );
                }
                b"property" => {
                    if keep_uniparc_xref {
                        add_property(
                            uniparc.uniparc_id.clone(),
                            &xrefs,
                            &mut properties,
                            e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                        );
                    }
                }
                b"ipr" => add_interpro_annotation(
                    &mut domains,
                    e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                ),
                b"lcn" => add_domain_definitions(
                    &mut domains,
                    e.attributes().map(|a| a.unwrap()).collect::<Vec<_>>(),
                ),
                _ => println!(
                    "Skipping Empty element '{:?}' with attributes {:?}.",
                    str::from_utf8(e.name()).unwrap(),
                    e.attributes()
                        .map(|a| attribute_to_string(a.unwrap()))
                        .collect::<Vec<_>>()
                ),
            },
            Ok(Event::Text(text)) => match text_field {
                TextField::Accession => {
                    uniparc.uniparc_id =
                        text.unescape_and_decode(&reader).unwrap().replace("\n", "");
                }
                TextField::Sequence => {
                    uniparc.sequence = text.unescape_and_decode(&reader).unwrap().replace("\n", "");
                }
            },
            Ok(Event::End(ref e)) => {
                match e.name() {
                    b"entry" => {
                        write_uniparc(&mut handlers, &uniparc);
                        write_uniparc_domains(&mut handlers, &domains);
                        write_uniparc_xrefs(&mut handlers, &xrefs);
                        write_uniparc_properties(&mut handlers, &properties);
                        if count % 10_000 == 0 {
                            println!("Finished processing UniParc number {}...", count);
                        }
                    }
                    _ => {}
                }
                assert!(current_element.pop().unwrap() == e.name().to_ascii_lowercase());
                depth -= 1;
            }
            Ok(Event::CData(e)) => println!("Skipping CData '{:?}'.", e),
            Ok(Event::Decl(e)) => println!("Skipping Decl '{:?}'.", e),
            Ok(Event::PI(e)) => println!("Skipping PI '{:?}'.", e),
            Ok(Event::Comment(comment)) => println!("Skipping Comment: '{:?}'", comment),
            Ok(Event::DocType(e)) => println!("Skipping DocType: '{:?}'", e),
            Ok(Event::Eof) => break,
            Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
        }
        buf.clear();
    }
    // buf.clear();
    println!("Depth: {}", depth);
    assert!(depth == 0);
    Ok(count)
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}