plotting/
lib.rs

1//Needed to serialize data for Python
2extern crate serde;
3extern crate serde_pickle;
4
5//Needed to write stuff to files, and to delete temporary files
6use std::fs::File;
7use std::io::prelude::*;
8use std::env;
9
10//Needed to call a Python script from Rust
11use std::process::Command;
12
13//Needed for unit tests
14extern crate rand;
15
16pub fn plot(basic_vectors: &(Vec<f64>, Vec<f64>)) {
17    //Serialize the data and write it to a pickle file.
18    let global_path = env::current_dir().unwrap();
19    let ser_path: &str = &format!("{}/output.tmp.pkl", global_path.to_str().unwrap());
20    let serialized = serde_pickle::to_vec(basic_vectors, true).unwrap();
21    let mut buffer = File::create(ser_path).unwrap();
22    match buffer.write(&serialized) {
23        Err(_x) => panic!(
24            "Failed to write serialized data to file at path = \"{}\"",
25            ser_path
26        ),
27        _ => {}
28    };
29
30    //Now we send python the path to the serialized file and let matplotlib create a graph of it for us.
31    //let py_path = "src/plotter.py";
32
33    let py_path = &format!("{}/plotter.py", global_path.to_str().unwrap());
34
35    let _new_command = Command::new("pythonw")
36        .arg(py_path)
37        .arg(ser_path)
38        .status()
39        .expect("Failed to start plotter.");
40
41    //Now we want to delete the file, we don't want tons of loose ends around.
42    match std::fs::remove_file(ser_path) {
43        Err(_x) => panic!("Failed to remove temporary file at path = \"{}\"", ser_path),
44        _ => {}
45    };
46}
47
48#[cfg(test)]
49mod tests {
50    use rand::{thread_rng, Rng};
51    #[test]
52    fn test_serialize() {
53        //Can we serialize and deserialize something?
54        let mut a: Vec<f64> = vec![];
55        let mut b: Vec<f64> = vec![];
56
57        let mut rng = thread_rng();
58
59        for i in 0..100000 {
60            let x: f64 = rng.gen();
61            let y: f64 = rng.gen();
62
63            a.push(x);
64            b.push(y);
65        }
66
67        let serialized = serde_pickle::to_vec(&(&a, &b), true).unwrap();
68        let deserialized = serde_pickle::from_slice(&serialized).unwrap();
69        assert_eq!((a, b), deserialized);
70    }
71
72    #[test]
73    fn test_fs() {}
74}