1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ignore-android: FIXME(#10393)
12 // ignore-pretty very bad with line comments
14 // multi tasking k-nucleotide
16 extern crate collections;
18 use collections::HashMap;
19 use std::mem::replace;
22 use std::string::String;
24 fn f64_cmp(x: f64, y: f64) -> Ordering {
25 // arbitrarily decide that NaNs are larger than everything.
28 } else if x.is_nan() {
39 // given a map, print a sorted version of it
40 fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String {
41 fn pct(xx: uint, yy: uint) -> f64 {
42 return (xx as f64) * 100.0 / (yy as f64);
45 // sort by key, then by value
46 fn sortKV(mut orig: Vec<(Vec<u8> ,f64)> ) -> Vec<(Vec<u8> ,f64)> {
47 orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
48 orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
52 let mut pairs = Vec::new();
55 for (key, &val) in mm.iter() {
56 pairs.push(((*key).clone(), pct(val, total)));
59 let pairs_sorted = sortKV(pairs);
61 let mut buffer = String::new();
62 for &(ref k, v) in pairs_sorted.iter() {
63 buffer.push_str(format!("{} {:0.3f}\n",
67 .into_str(), v).as_slice());
73 // given a map, search for the frequency of a pattern
74 fn find(mm: &HashMap<Vec<u8> , uint>, key: String) -> uint {
75 let key = key.to_owned().into_ascii().as_slice().to_lower().into_str();
76 match mm.find_equiv(&key.as_bytes()) {
77 option::None => { return 0u; }
78 option::Some(&num) => { return num; }
82 // given a map, increment the counter for a key
83 fn update_freq(mm: &mut HashMap<Vec<u8> , uint>, key: &[u8]) {
84 let key = Vec::from_slice(key);
85 let newval = match mm.pop(&key) {
89 mm.insert(key, newval);
92 // given a Vec<u8>, for each window call a function
93 // i.e., for "hello" and windows of size four,
94 // run it("hell") and it("ello"), then return "llo"
95 fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec<u8> {
99 while ii < len - (nn - 1u) {
100 it(bb.slice(ii, ii+nn));
104 return Vec::from_slice(bb.slice(len - (nn - 1u), len));
107 fn make_sequence_processor(sz: uint,
108 from_parent: &Receiver<Vec<u8>>,
109 to_parent: &Sender<String>) {
110 let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
111 let mut carry = Vec::new();
112 let mut total: uint = 0u;
114 let mut line: Vec<u8>;
118 line = from_parent.recv();
119 if line == Vec::new() { break; }
121 carry = windows_with_carry(carry.append(line.as_slice()).as_slice(),
124 update_freq(&mut freqs, window);
129 let buffer = match sz {
130 1u => { sort_and_fmt(&freqs, total) }
131 2u => { sort_and_fmt(&freqs, total) }
132 3u => { format_strbuf!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
133 4u => { format_strbuf!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
134 6u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
135 12u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
136 18u => { format_strbuf!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
137 "GGTATTTTAATTTATAGT") }
138 _ => { "".to_string() }
141 to_parent.send(buffer);
144 // given a FASTA file on stdin, process sequence THREE
146 use std::io::{stdio, MemReader, BufferedReader};
148 let rdr = if os::getenv("RUST_BENCH").is_some() {
149 let foo = include_bin!("shootout-k-nucleotide.data");
150 box MemReader::new(Vec::from_slice(foo)) as Box<Reader>
152 box stdio::stdin() as Box<Reader>
154 let mut rdr = BufferedReader::new(rdr);
156 // initialize each sequence sorter
157 let sizes = vec!(1u,2,3,4,6,12,18);
158 let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
159 let mut from_child = Vec::new();
160 let to_child = sizes.iter().zip(streams.mut_iter()).map(|(sz, stream_ref)| {
162 let stream = replace(stream_ref, None);
163 let (to_parent_, from_child_) = stream.unwrap();
165 from_child.push(from_child_);
167 let (to_child, from_parent) = channel();
170 make_sequence_processor(sz, &from_parent, &to_parent_);
174 }).collect::<Vec<Sender<Vec<u8> >> >();
177 // latch stores true after we've started
178 // reading the sequence of interest
179 let mut proc_mode = false;
181 for line in rdr.lines() {
182 let line = line.unwrap().as_slice().trim().to_owned();
184 if line.len() == 0u { continue; }
186 match (line.as_slice()[0] as char, proc_mode) {
188 // start processing if this is the one
190 match line.as_slice().slice_from(1).find_str("THREE") {
191 option::Some(_) => { proc_mode = true; }
196 // break our processing
197 ('>', true) => { break; }
199 // process the sequence for k-mers
201 let line_bytes = line.as_bytes();
203 for (ii, _sz) in sizes.iter().enumerate() {
204 let lb = Vec::from_slice(line_bytes);
205 to_child.get(ii).send(lb);
215 for (ii, _sz) in sizes.iter().enumerate() {
216 to_child.get(ii).send(Vec::new());
219 // now fetch and print result messages
220 for (ii, _sz) in sizes.iter().enumerate() {
221 println!("{}", from_child.get(ii).recv());