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
extern crate tempfile;

use std::fs::File;
use std::fs;
use std::io::{Write, Read, Seek, SeekFrom};
use std::process::Command;
use tempfile::NamedTempFile;
use std::fmt;

pub enum Markers {
    Point,
    Pixel,
    Circle,
    Triangle_Down,
    Triangle_Up,
    Triangle_Left,
    Triangle_Right,
    Tri_Down,
    Tri_Up,
    Tri_Left,
    Tri_Right,
    Square,
    Pentagon,
    Star,
    Hexagon1,
    Hexagon2,
    Plus,
    X ,
    Diamond,
    Thin_Diamond,
    VLine,
    HLine,
}

trait AsString {
    fn as_str(&self) -> &str;
}

impl Markers {
    pub fn as_str(&self) -> &str {
        match self {
            &Markers::Point => ".", 	// point marker
            &Markers::Pixel => ",", 	// pixel marker
            &Markers::Circle => "o", 	// circle marker
            &Markers::Triangle_Down => "v",  // triangle_down marker
            &Markers::Triangle_Up => "^", 	// triangle_up marker
            &Markers::Triangle_Left => "<",  //triangle_left marker
            &Markers::Triangle_Right => ">", // triangle_right marker
            &Markers::Tri_Down => "1",  // tri_down marker
            &Markers::Tri_Up => "2", // tri_up marker
            &Markers::Tri_Left => "3", // tri_left marker
            &Markers::Tri_Right => "4", // tri_right marker
            &Markers::Square => "s", // square marker
            &Markers::Pentagon => "p", // pentagon marker
            &Markers::Star => "*", // star marker
            &Markers::Hexagon1 => "h", // hexagon1 marker
            &Markers::Hexagon2 => "H", // hexagon2 marker
            &Markers::Plus => "+", // plus marker
            &Markers::X => "x", // x marker
            &Markers::Diamond => "D", // diamond marker
            &Markers::Thin_Diamond => "d", // thin_diamond marker
            &Markers::VLine => "|", // vline marker
            &Markers::HLine => "_", // hline marker
        }
    }
}

pub enum LineStyle {
    Dot,
    DashDot,
    Dash,
    Fill,
}

impl LineStyle {
    pub fn as_str(&self) -> &str {
        match self {
            &LineStyle::Dot => ":",
            &LineStyle::DashDot => "-.",
            &LineStyle::Dash => "--",
            &LineStyle::Fill => "-",
        }
    }
}

pub struct Figure {
    script: String
}

impl Figure {

    pub fn new() -> Figure {
        return Figure {
            script: "import matplotlib\nimport matplotlib.pyplot as plt\n\n".to_string()
        }   
    }

    pub fn add_plot(&mut self, p: String) {
        self.script += &p;
    }

    pub fn save(&mut self, output: &str) {
        self.script += &format!("plt.savefig('{}')\n", output);
        // create a temporary file
        let mut tmpfile: NamedTempFile = tempfile::NamedTempFile::new().unwrap();
        tmpfile.write_all(self.script.as_bytes());
        print!("{:?}", self.script);

        let mut echo_hello = Command::new("/usr/local/bin/python3");
        echo_hello.arg(tmpfile.path());
        echo_hello.output().expect("failed to execute process");

    }
}

pub struct LinePlotOptions {
    pub marker: Option<Markers>,
    pub lineStyle: Option<LineStyle>,
}

impl LinePlotOptions {
    pub fn new() -> LinePlotOptions {
        return LinePlotOptions {
            marker: None,
            lineStyle: None,
        }
    }
}

pub struct ScatterPlotOptions {
    pub marker: Option<Markers>,
    pub alpha: Option<f64>,
}

impl ScatterPlotOptions {
    pub fn new() -> ScatterPlotOptions {
        return ScatterPlotOptions {
            marker: None,
            alpha: None,
        }
    }
}

impl fmt::Display for LinePlotOptions {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut options : Vec<String> = Vec::new();
        match self.marker {
            Some(ref m) => {options.push(format!("marker='{}'", m.as_str()));}
            None => {}
        }
        match self.lineStyle {
            Some(ref v) => {options.push(format!("linestyle='{}'", v.as_str()));}
            None => {}
        }
        fmt.write_str(&options.join(", "));
        Ok(())
    }
}

impl fmt::Display for ScatterPlotOptions {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut options : Vec<String> = Vec::new();
        match self.marker {
            Some(ref m) => {options.push(format!("marker='{}'", m.as_str()));}
            None => {}
        }
        match self.alpha {
            Some(ref m) => {options.push(format!("alpha={}", m.to_string()));}
            None => {}
        }
        fmt.write_str(&options.join(", "));
        Ok(())
    }
}

fn convert_list_str<T>(x: Vec<T>) -> String where T: ToString {
    let mut result:Vec<String> = Vec::new();
    for _x in x { result.push(_x.to_string()); }
    return "[".to_string() + &result.join(", ") + &"]".to_string();
}

pub fn line_plot<U, T>(x: Vec<U>, y: Vec<T>, options: Option<LinePlotOptions>) -> String where U: ToString, T: ToString {
    let xs = convert_list_str::<U>(x);
    let ys = convert_list_str::<T>(y);
    match options {
        Some(opt) => {
            return format!("plt.plot({},{},{})\n", xs, ys, opt);
        },
        None => {
            return format!("plt.plot({},{})\n", xs, ys);
        }
    }
}

pub fn scatter_plot<U, T>(x: Vec<U>, y: Vec<T>, options: Option<ScatterPlotOptions>) -> String where U: ToString, T: ToString {
    let xs = convert_list_str::<U>(x);
    let ys = convert_list_str::<T>(y);
        match options {
        Some(opt) => {
            return format!("plt.scatter({},{},{})\n", xs, ys, opt);
        },
        None => {
            return format!("plt.scatter({},{})\n", xs, ys);
        }
    }
    
}

#[cfg(test)]
mod lineplot {
    use super::*;

    #[test]
    fn create_lineplot_basic() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let lp = line_plot::<i32, f64>(x, y, None);
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/lineplot_basic.png"));
    }

     #[test]
    fn create_lineplot_basic_markers() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let mut options = LinePlotOptions::new();
        options.marker = Some(Markers::Diamond);
        let lp = line_plot::<i32, f64>(x, y, Some(options));
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/lineplot_basic_markers.png"));
    }

     #[test]
    fn create_lineplot_basic_linestyle() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let mut options = LinePlotOptions::new();
        options.marker = Some(Markers::Diamond);
        options.lineStyle = Some(LineStyle::DashDot);
        let lp = line_plot::<i32, f64>(x, y, Some(options));
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/lineplot_basic_linestyle.png"));
    }

    #[test]
    fn create_scatterplot_basic() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let lp = scatter_plot::<i32, f64>(x, y, None);
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/scatterplot_basic.png"));
    }

    #[test]
    fn create_scatterplot_marker() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let mut options = ScatterPlotOptions::new();
        options.marker = Some(Markers::Diamond);
        let lp = scatter_plot::<i32, f64>(x, y, Some(options));
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/scatterplot_marker.png"));
    }
    #[test]
    fn create_scatterplot_marker_alpha() {
        let x = vec![1, 2, 3, 4];
        let y = vec![0.1, 0.2, 0.5, 0.3];
        let mut options = ScatterPlotOptions::new();
        options.marker = Some(Markers::Diamond);
        options.alpha = Some(0.1);
        let lp = scatter_plot::<i32, f64>(x, y, Some(options));
        let mut figure = Figure::new();
        figure.add_plot(lp.clone());
        print!("{:?}", figure.save("./examples/scatterplot_marker_alpha.png"));
    }


}

fn main() {
    println!("Hello, world!");
}