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
use super::{generate_list, generate_nested_list, matrix_to_array, AsMatrix, GraphMaker};
use std::fmt::Write;

/// Draw a box and whisker plot
///
/// [See Matplotlib's documentation](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
///
/// # Examples
///
/// ## Data as a nested list
///
/// ```
/// use plotpy::{Boxplot, Plot, StrError};
///
/// fn main() -> Result<(), StrError> {
///     // data (as a nested list)
///     let data = vec![
///         vec![1, 2, 3, 4, 5],              // A
///         vec![2, 3, 4, 5, 6, 7, 8, 9, 10], // B
///         vec![3, 4, 5, 6],                 // C
///         vec![4, 5, 6, 7, 8, 9, 10],       // D
///         vec![5, 6, 7],                    // E
///     ];
///
///     // x ticks and labels
///     let n = data.len();
///     let ticks: Vec<_> = (1..(n + 1)).into_iter().collect();
///     let labels = ["A", "B", "C", "D", "E"];
///
///     // boxplot object and options
///     let mut boxes = Boxplot::new();
///     boxes.draw(&data);
///
///     // save figure
///     let mut plot = Plot::new();
///     plot.add(&boxes)
///         .set_title("boxplot documentation test")
///         .set_ticks_x_labels(&ticks, &labels)
///         .save("/tmp/plotpy/doc_tests/doc_boxplot_2.svg")?;
///     Ok(())
/// }
/// ```
///
/// ![doc_boxplot_2.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_boxplot_2.svg)
///
/// ## Data as a 2D array
///
/// ```
/// use plotpy::{Boxplot, Plot, StrError};
///
/// fn main() -> Result<(), StrError> {
///     // data (as a 2D array/matrix)
///     let data = vec![
///         //   A  B  C  D  E
///         vec![1, 2, 3, 4, 5],
///         vec![2, 3, 4, 5, 6],
///         vec![3, 4, 5, 6, 7],
///         vec![4, 5, 6, 7, 8],
///         vec![5, 6, 7, 8, 9],
///         vec![6, 7, 8, 9, 10],
///         vec![14, 14, 14, 14, 14], // outliers
///     ];
///
///     // x ticks and labels
///     let ncol = data[0].len();
///     let ticks: Vec<_> = (1..(ncol + 1)).into_iter().collect();
///     let labels = ["A", "B", "C", "D", "E"];
///
///     // boxplot object and options
///     let mut boxes = Boxplot::new();
///     boxes.draw_mat(&data);
///
///     // save figure
///     let mut plot = Plot::new();
///     plot.add(&boxes)
///         .set_title("boxplot documentation test")
///         .set_ticks_x_labels(&ticks, &labels)
///         .save("/tmp/plotpy/doc_tests/doc_boxplot_1.svg")?;
///     Ok(())
/// }
/// ```
///
/// ![doc_boxplot_1.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_boxplot_1.svg)
///
/// ## More examples
///
/// See also integration test in the **tests** directory.
pub struct Boxplot {
    symbol: String,       // The default symbol for flier (outlier) points.
    horizontal: bool,     // Horizontal boxplot (default is false)
    whisker: Option<f64>, // The position of the whiskers
    positions: Vec<f64>,  // The positions of the boxes
    width: Option<f64>,   // The width of the boxes
    extra: String,        // Extra commands (comma separated)
    buffer: String,       // Buffer
}

impl Boxplot {
    /// Creates a new Boxplot object
    pub fn new() -> Self {
        Boxplot {
            symbol: String::new(),
            horizontal: false,
            whisker: None,
            positions: Vec::new(),
            width: None,
            extra: String::new(),
            buffer: String::new(),
        }
    }

    /// Draws the box plot given a nested list
    ///
    /// # Input
    ///
    /// * `data` -- Is a sequence of 1D arrays such that a boxplot is drawn for each array in the sequence.
    ///   [From Matplotlib](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    ///
    /// # Notes
    ///
    /// * The type `T` must be a number.
    pub fn draw<T>(&mut self, data: &Vec<Vec<T>>)
    where
        T: std::fmt::Display,
    {
        generate_nested_list(&mut self.buffer, "x", data);
        if self.positions.len() > 0 {
            generate_list(&mut self.buffer, "positions", self.positions.as_slice());
        }
        let opt = self.options();
        write!(&mut self.buffer, "p=plt.boxplot(x{})\n", &opt).unwrap();
    }

    /// Draws the box plot given a 2D array (matrix)
    ///
    /// # Input
    ///
    /// * `data` -- Is a 2D array (matrix) such that a boxplot is drawn for each column in the matrix.
    ///   [From Matplotlib](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    ///
    /// # Notes
    ///
    /// * The type `U` must be a number.
    pub fn draw_mat<'a, T, U>(&mut self, data: &'a T)
    where
        T: AsMatrix<'a, U>,
        U: 'a + std::fmt::Display,
    {
        matrix_to_array(&mut self.buffer, "x", data);
        if self.positions.len() > 0 {
            generate_list(&mut self.buffer, "positions", self.positions.as_slice());
        }
        let opt = self.options();
        write!(&mut self.buffer, "p=plt.boxplot(x{})\n", &opt).unwrap();
    }

    /// Sets the symbol for the outliers
    pub fn set_symbol(&mut self, symbol: &str) -> &mut Self {
        self.symbol = symbol.to_string();
        self
    }

    /// Enables drawing horizontal boxes
    pub fn set_horizontal(&mut self, flag: bool) -> &mut Self {
        self.horizontal = flag;
        self
    }

    /// Sets the position of the whiskers
    ///
    /// The default value of whisker = 1.5 corresponds to Tukey's original definition of boxplots.
    ///
    /// [See Matplotlib's documentation](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    pub fn set_whisker(&mut self, whisker: f64) -> &mut Self {
        self.whisker = Some(whisker);
        self
    }

    /// Sets the positions of the boxes
    pub fn set_positions(&mut self, positions: &[f64]) -> &mut Self {
        self.positions = positions.to_vec();
        self
    }

    /// Sets the width of the boxes
    pub fn set_width(&mut self, width: f64) -> &mut Self {
        self.width = Some(width);
        self
    }

    /// Sets extra matplotlib commands (comma separated)
    ///
    /// **Important:** The extra commands must be comma separated. For example:
    ///
    /// ```text
    /// param1=123,param2='hello'
    /// ```
    ///
    /// [See Matplotlib's documentation for extra parameters](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    pub fn set_extra(&mut self, extra: &str) -> &mut Self {
        self.extra = extra.to_string();
        self
    }

    /// Returns options (optional parameters) for boxplot
    fn options(&self) -> String {
        let mut opt = String::new();
        if self.symbol != "" {
            write!(&mut opt, ",sym=r'{}'", self.symbol).unwrap();
        }
        if self.horizontal {
            write!(&mut opt, ",vert=False").unwrap();
        }
        if self.whisker != None {
            write!(&mut opt, ",whis={}", self.whisker.unwrap()).unwrap();
        }
        if self.positions.len() > 0 {
            write!(&mut opt, ",positions=positions").unwrap();
        }
        if self.width != None {
            write!(&mut opt, ",widths={}", self.width.unwrap()).unwrap();
        }
        if self.extra != "" {
            write!(&mut opt, ",{}", self.extra).unwrap();
        }
        opt
    }
}

impl GraphMaker for Boxplot {
    fn get_buffer<'a>(&'a self) -> &'a String {
        &self.buffer
    }
    fn clear_buffer(&mut self) {
        self.buffer.clear();
    }
}

/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::Boxplot;
    use crate::GraphMaker;

    #[test]
    fn new_works() {
        let boxes = Boxplot::new();
        assert_eq!(boxes.symbol.len(), 0);
        assert_eq!(boxes.horizontal, false);
        assert_eq!(boxes.whisker, None);
        assert_eq!(boxes.positions.len(), 0);
        assert_eq!(boxes.width, None);
        assert_eq!(boxes.extra.len(), 0);
        assert_eq!(boxes.buffer.len(), 0);
    }

    #[test]
    fn draw_works_1() {
        let x = vec![
            vec![1, 2, 3],       // A
            vec![2, 3, 4, 5, 6], // B
            vec![6, 7],          // C
        ];
        let mut boxes = Boxplot::new();
        boxes.draw(&x);
        let b: &str = "x=[[1,2,3,],[2,3,4,5,6,],[6,7,],]\n\
                       p=plt.boxplot(x)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }

    #[test]
    fn draw_mat_works_1() {
        let x = vec![
            //   A  B  C  D  E
            vec![1, 2, 3, 4, 5],
            vec![2, 3, 4, 5, 6],
            vec![3, 4, 5, 6, 7],
            vec![4, 5, 6, 7, 8],
            vec![5, 6, 7, 8, 9],
            vec![6, 7, 8, 9, 10],
        ];
        let mut boxes = Boxplot::new();
        boxes.draw_mat(&x);
        let b: &str = "x=np.array([[1,2,3,4,5,],[2,3,4,5,6,],[3,4,5,6,7,],[4,5,6,7,8,],[5,6,7,8,9,],[6,7,8,9,10,],],dtype=float)\n\
                       p=plt.boxplot(x)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }

    #[test]
    fn draw_mat_works_2() {
        let x = vec![
            //   A  B  C  D  E
            vec![1, 2, 3, 4, 5],
            vec![2, 3, 4, 5, 6],
            vec![3, 4, 5, 6, 7],
            vec![4, 5, 6, 7, 8],
            vec![5, 6, 7, 8, 9],
            vec![6, 7, 8, 9, 10],
        ];
        let mut boxes = Boxplot::new();
        boxes
            .set_symbol("b+")
            .set_horizontal(true)
            .set_whisker(1.5)
            .set_positions(&[1.0, 2.0, 3.0, 4.0, 5.0])
            .set_width(0.5)
            .draw_mat(&x);
        let b: &str = "x=np.array([[1,2,3,4,5,],[2,3,4,5,6,],[3,4,5,6,7,],[4,5,6,7,8,],[5,6,7,8,9,],[6,7,8,9,10,],],dtype=float)\n\
                       positions=[1,2,3,4,5,]\n\
                       p=plt.boxplot(x,sym=r'b+',vert=False,whis=1.5,positions=positions,widths=0.5)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }
}