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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use super::{matrix_to_array, vector_to_array, vector_to_strings, AsMatrix, GraphMaker};
use std::fmt::Write;

/// Generates a contour plot
///
/// # Example
///
/// ```
/// use plotpy::{Contour, Plot, generate3d};
///
/// fn main() -> Result<(), &'static str> {
///     // generate (x,y,z) matrices
///     let n = 21;
///     let (x, y, z) = generate3d(-2.0, 2.0, -2.0, 2.0, n, n, |x, y| x * x - y * y);
///
///     // configure contour
///     let mut contour = Contour::new();
///     contour
///         .set_colorbar_label("temperature")
///         .set_colormap_name("terrain")
///         .set_selected_line_color("#f1eb67")
///         .set_selected_line_width(12.0)
///         .set_selected_level(0.0, true);
///
///     // draw contour
///     contour.draw(&x, &y, &z);
///
///     // add contour to plot
///     let mut plot = Plot::new();
///     plot.add(&contour)
///         .set_labels("x", "y");
///
///     // save figure
///     plot.save("/tmp/plotpy/doc_tests/doc_contour.svg")?;
///     Ok(())
/// }
/// ```
///
/// ![doc_contour.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_contour.svg)
///
/// See also integration tests in the [tests directory](https://github.com/cpmech/plotpy/tree/main/tests)
///
/// Output from some integration tests:
///
/// ![integ_contour.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/integ_contour.svg)
pub struct Contour {
    colors: Vec<String>,         // Colors to be used instead of colormap
    levels: Vec<f64>,            // Pre-defined levels
    colormap_name: String,       // Colormap name
    no_lines: bool,              // Skip drawing a lines contour
    no_labels: bool,             // Skip adding labels to the lines contour
    no_inline_labels: bool,      // Do not draw labels inline
    no_colorbar: bool,           // Skip drawing a colorbar
    colorbar_label: String,      // Colorbar label
    number_format_cb: String,    // Number format for the labels in lines contour
    line_color: String,          // Line color for the lines contour
    line_style: String,          // Line style for the lines contour
    line_width: f64,             // Line width for the lines contour
    fontsize_labels: f64,        // Font size for labels
    with_selected: bool,         // Draw a line contour with a selected level
    selected_level: f64,         // Selected level (e.g., 0.0)
    selected_line_color: String, // Color to mark the selected level
    selected_line_style: String, // Line style for the selected level
    selected_line_width: f64,    // Line width for the selected level
    buffer: String,              // buffer
}

impl Contour {
    /// Creates a new Contour object
    pub fn new() -> Self {
        Contour {
            colors: Vec::new(),
            levels: Vec::new(),
            colormap_name: "bwr".to_string(),
            no_lines: false,
            no_labels: false,
            no_inline_labels: false,
            no_colorbar: false,
            colorbar_label: String::new(),
            number_format_cb: String::new(),
            line_color: "black".to_string(),
            line_style: String::new(),
            line_width: 0.0,
            fontsize_labels: 0.0,
            with_selected: false,
            selected_level: 0.0,
            selected_line_color: "yellow".to_string(),
            selected_line_style: "-".to_string(),
            selected_line_width: 2.0,
            buffer: String::new(),
        }
    }

    /// Draws a fancy contour: filled contour with a line contour and a colorbar
    ///
    /// # Input
    ///
    /// * `x` -- matrix with x values
    /// * `y` -- matrix with y values
    /// * `z` -- matrix with z values
    ///
    /// # Flags
    ///
    /// The following flags control what features are not to be drawn:
    ///
    /// * `no_lines` -- skip drawing a lines contour on top of the filled contour
    /// * `no_labels` -- skip adding labels to the lines contour (if enabled)
    /// * `no_colorbar` -- skip drawing a colorbar
    /// * `with_selected` -- draw a line contour with a selected level (e.g., 0.0) on top of everything
    ///
    /// # Notes
    ///
    /// * The type `U` of the input matrices must be a number.
    ///
    pub fn draw<'a, T, U>(&mut self, x: &'a T, y: &'a T, z: &'a T)
    where
        T: AsMatrix<'a, U>,
        U: 'a + std::fmt::Display,
    {
        matrix_to_array(&mut self.buffer, "x", x);
        matrix_to_array(&mut self.buffer, "y", y);
        matrix_to_array(&mut self.buffer, "z", z);
        if self.colors.len() > 0 {
            vector_to_strings(&mut self.buffer, "colors", &self.colors);
        }
        if self.levels.len() > 0 {
            vector_to_array(&mut self.buffer, "levels", &self.levels);
        }
        let opt = self.options_filled();
        write!(&mut self.buffer, "cf=plt.contourf(x,y,z{})\n", &opt).unwrap();
        if !self.no_lines {
            let opt_line = self.options_line();
            write!(&mut self.buffer, "cl=plt.contour(x,y,z{})\n", &opt_line).unwrap();
            if !self.no_labels {
                let opt_label = self.options_label();
                write!(&mut self.buffer, "plt.clabel(cl{})\n", &opt_label).unwrap();
            }
        }
        if !self.no_colorbar {
            let opt_colorbar = self.options_colorbar();
            write!(&mut self.buffer, "cb=plt.colorbar(cf{})\n", &opt_colorbar).unwrap();
            if self.colorbar_label != "" {
                write!(&mut self.buffer, "cb.ax.set_ylabel(r'{}')\n", self.colorbar_label).unwrap();
            }
        }
        if self.with_selected {
            let opt_selected = self.options_selected();
            write!(&mut self.buffer, "plt.contour(x,y,z{})\n", &opt_selected).unwrap();
        }
    }

    /// Sets the colors to be used instead of a pre-defined colormap
    ///
    /// Will use `colormap_index` instead if its empty.
    pub fn set_colors(&mut self, colors: &[&str]) -> &mut Self {
        self.colors = colors.iter().map(|color| color.to_string()).collect();
        self
    }

    /// Sets pre-defined levels, otherwise automatically calculate levels
    pub fn set_levels(&mut self, levels: &[f64]) -> &mut Self {
        self.levels = levels.to_vec();
        self
    }

    /// Sets the colormap index
    ///
    /// Options:
    ///
    /// * 0 -- bwr
    /// * 1 -- RdBu
    /// * 2 -- hsv
    /// * 3 -- jet
    /// * 4 -- terrain
    /// * 5 -- pink
    /// * 6 -- Greys
    /// * `>`6 -- starts over from 0
    pub fn set_colormap_index(&mut self, index: usize) -> &mut Self {
        const CMAP: [&str; 7] = ["bwr", "RdBu", "hsv", "jet", "terrain", "pink", "Greys"];
        self.colormap_name = CMAP[index % 7].to_string();
        self.colors = Vec::new();
        self
    }

    /// Sets the colormap name
    ///
    /// Colormap names:
    ///
    /// * see <https://matplotlib.org/stable/tutorials/colors/colormaps.html>
    ///
    /// Will use `colormap_index` instead if `colormap_name` is empty.
    pub fn set_colormap_name(&mut self, name: &str) -> &mut Self {
        self.colormap_name = String::from(name);
        self.colors = Vec::new();
        self
    }

    /// Sets option to skip drawing a lines contour on top of the filled contour
    pub fn set_no_lines(&mut self, flag: bool) -> &mut Self {
        self.no_lines = flag;
        self
    }

    /// Sets option to skip adding labels to the lines contour (if enabled)
    pub fn set_no_labels(&mut self, flag: bool) -> &mut Self {
        self.no_labels = flag;
        self
    }

    /// Sets option to skip drawing labels inline with the contour lines (if enabled)
    pub fn set_no_inline_labels(&mut self, flag: bool) -> &mut Self {
        self.no_inline_labels = flag;
        self
    }

    /// Sets option to skip drawing a colorbar
    pub fn set_no_colorbar(&mut self, flag: bool) -> &mut Self {
        self.no_colorbar = flag;
        self
    }

    /// Sets the colorbar label
    pub fn set_colorbar_label(&mut self, label: &str) -> &mut Self {
        self.colorbar_label = String::from(label);
        self
    }

    /// Sets the number format for the labels in the colorbar (cb)
    pub fn set_number_format_cb(&mut self, format: &str) -> &mut Self {
        self.number_format_cb = String::from(format);
        self
    }

    /// Sets the line color for the lines contour (default is black)
    pub fn set_line_color(&mut self, color: &str) -> &mut Self {
        self.line_color = String::from(color);
        self
    }

    /// Sets the line style for the lines contour
    ///
    /// Options:
    ///
    /// * "`-`", "`:`", "`--`", "`-.`"
    pub fn set_line_style(&mut self, style: &str) -> &mut Self {
        self.line_style = String::from(style);
        self
    }

    /// Sets the line width for the lines contour
    pub fn set_line_width(&mut self, width: f64) -> &mut Self {
        self.line_width = width;
        self
    }

    /// Sets the font size for labels
    pub fn set_fontsize_labels(&mut self, fontsize: f64) -> &mut Self {
        self.fontsize_labels = fontsize;
        self
    }

    /// Sets option to draw a line contour with a selected level (e.g., 0.0)
    ///
    /// Will draw the selected level (e.g., 0.0) on top of everything
    pub fn set_selected_level(&mut self, level: f64, enabled: bool) -> &mut Self {
        self.selected_level = level;
        self.with_selected = enabled;
        self
    }

    /// Sets the color to mark the selected level
    pub fn set_selected_line_color(&mut self, color: &str) -> &mut Self {
        self.selected_line_color = String::from(color);
        self
    }

    /// Sets the line style for the selected level
    ///
    /// Options:
    ///
    /// * "`-`", "`:`", "`--`", "`-.`"
    pub fn set_selected_line_style(&mut self, style: &str) -> &mut Self {
        self.selected_line_style = String::from(style);
        self
    }

    /// Sets the line width for the selected level
    pub fn set_selected_line_width(&mut self, width: f64) -> &mut Self {
        self.selected_line_width = width;
        self
    }

    /// Returns options for filled contour
    fn options_filled(&self) -> String {
        let mut opt = String::new();
        if self.colors.len() > 0 {
            write!(&mut opt, ",colors=colors",).unwrap();
        } else {
            if self.colormap_name != "" {
                write!(&mut opt, ",cmap=plt.get_cmap('{}')", self.colormap_name).unwrap();
            }
        }
        if self.levels.len() > 0 {
            write!(&mut opt, ",levels=levels").unwrap();
        }
        opt
    }

    /// Returns options for line contour
    fn options_line(&self) -> String {
        let mut opt = String::new();
        if self.line_color != "" {
            write!(&mut opt, ",colors=['{}']", self.line_color).unwrap();
        }
        if self.levels.len() > 0 {
            write!(&mut opt, ",levels=levels").unwrap();
        }
        if self.line_style != "" {
            write!(&mut opt, ",linestyles=['{}']", self.line_style).unwrap();
        }
        if self.line_width > 0.0 {
            write!(&mut opt, ",linewidths=[{}]", self.line_width).unwrap();
        }
        opt
    }

    /// Returns options for labels
    fn options_label(&self) -> String {
        let mut opt = String::new();
        if self.no_inline_labels {
            write!(&mut opt, ",inline=False").unwrap();
        } else {
            write!(&mut opt, ",inline=True").unwrap();
        }
        if self.fontsize_labels > 0.0 {
            write!(&mut opt, ",fontsize={}", self.fontsize_labels).unwrap();
        }
        opt
    }

    /// Returns options for colorbar
    fn options_colorbar(&self) -> String {
        let mut opt = String::new();
        if self.number_format_cb != "" {
            write!(&mut opt, ",format='{}'", self.number_format_cb).unwrap();
        }
        opt
    }

    /// Returns options for selected line contour
    fn options_selected(&self) -> String {
        let mut opt = String::new();
        if self.selected_line_color != "" {
            write!(&mut opt, ",colors=['{}']", self.selected_line_color).unwrap();
        }
        write!(&mut opt, ",levels=[{}]", self.selected_level).unwrap();
        if self.selected_line_style != "" {
            write!(&mut opt, ",linestyles=['{}']", self.selected_line_style).unwrap();
        }
        if self.selected_line_width > 0.0 {
            write!(&mut opt, ",linewidths=[{}]", self.selected_line_width).unwrap();
        }
        opt
    }
}

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

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

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

    #[test]
    fn new_works() {
        let contour = Contour::new();
        assert_eq!(contour.colors.len(), 0);
        assert_eq!(contour.levels.len(), 0);
        assert_eq!(contour.colormap_name, "bwr");
        assert_eq!(contour.no_lines, false);
        assert_eq!(contour.no_labels, false);
        assert_eq!(contour.no_inline_labels, false);
        assert_eq!(contour.no_colorbar, false);
        assert_eq!(contour.colorbar_label.len(), 0);
        assert_eq!(contour.number_format_cb.len(), 0);
        assert_eq!(contour.line_color, "black".to_string());
        assert_eq!(contour.line_style.len(), 0);
        assert_eq!(contour.line_width, 0.0);
        assert_eq!(contour.fontsize_labels, 0.0);
        assert_eq!(contour.with_selected, false);
        assert_eq!(contour.selected_level, 0.0);
        assert_eq!(contour.selected_line_color, "yellow".to_string());
        assert_eq!(contour.selected_line_style, "-".to_string());
        assert_eq!(contour.selected_line_width, 2.0);
        assert_eq!(contour.buffer.len(), 0);
    }

    #[test]
    fn options_filled_works() {
        let mut contour = Contour::new();
        contour
            .set_colors(&vec!["#f00", "#0f0", "#00f"])
            .set_levels(&vec![0.25, 0.5, 1.0]);
        let opt = contour.options_filled();
        assert_eq!(
            opt,
            ",colors=colors\
             ,levels=levels"
        );
        contour.set_colormap_index(4);
        let opt = contour.options_filled();
        assert_eq!(
            opt,
            ",cmap=plt.get_cmap('terrain')\
             ,levels=levels"
        );
    }

    #[test]
    fn options_line_works() {
        let mut contour = Contour::new();
        contour
            .set_levels(&vec![0.25, 0.5, 1.0])
            .set_line_color("red")
            .set_line_style(":")
            .set_line_width(3.0);
        let opt = contour.options_line();
        assert_eq!(
            opt,
            ",colors=['red']\
             ,levels=levels\
             ,linestyles=[':']\
             ,linewidths=[3]"
        );
    }

    #[test]
    fn options_label_works() {
        let mut contour = Contour::new();
        contour.set_no_inline_labels(false).set_fontsize_labels(5.0);
        let opt = contour.options_label();
        assert_eq!(
            opt,
            ",inline=True\
             ,fontsize=5"
        );
        contour.set_no_inline_labels(true);
        let opt = contour.options_label();
        assert_eq!(
            opt,
            ",inline=False\
             ,fontsize=5"
        );
    }

    #[test]
    fn options_colorbar_works() {
        let mut contour = Contour::new();
        contour.set_number_format_cb("%.4f");
        let opt = contour.options_colorbar();
        assert_eq!(opt, ",format='%.4f'");
    }

    #[test]
    fn options_selected_works() {
        let mut contour = Contour::new();
        contour
            .set_selected_level(0.75, true)
            .set_selected_line_color("blue")
            .set_selected_line_style("--")
            .set_selected_line_width(2.5);
        let opt = contour.options_selected();
        assert_eq!(
            opt,
            ",colors=['blue']\
             ,levels=[0.75]\
             ,linestyles=['--']\
             ,linewidths=[2.5]"
        );
    }

    #[test]
    fn draw_works() {
        let mut contour = Contour::new();
        contour
            .set_colors(&vec!["#f00", "#0f0", "#00f"])
            .set_levels(&vec![0.25, 0.5, 1.0])
            .set_colorbar_label("temperature")
            .set_selected_level(0.0, true);
        let x = vec![vec![-0.5, 0.0, 0.5], vec![-0.5, 0.0, 0.5], vec![-0.5, 0.0, 0.5]];
        let y = vec![vec![-0.5, -0.5, -0.5], vec![0.0, 0.0, 0.0], vec![0.5, 0.5, 0.5]];
        let z = vec![vec![0.50, 0.25, 0.50], vec![0.25, 0.00, 0.25], vec![0.50, 0.25, 0.50]];
        contour.draw(&x, &y, &z);
        let b: &str = "x=np.array([[-0.5,0,0.5,],[-0.5,0,0.5,],[-0.5,0,0.5,],],dtype=float)\n\
                       y=np.array([[-0.5,-0.5,-0.5,],[0,0,0,],[0.5,0.5,0.5,],],dtype=float)\n\
                       z=np.array([[0.5,0.25,0.5,],[0.25,0,0.25,],[0.5,0.25,0.5,],],dtype=float)\n\
                       colors=['#f00','#0f0','#00f',]\n\
                       levels=np.array([0.25,0.5,1,],dtype=float)\n\
                       cf=plt.contourf(x,y,z,colors=colors,levels=levels)\n\
                       cl=plt.contour(x,y,z,colors=['black'],levels=levels)\n\
                       plt.clabel(cl,inline=True)\n\
                       cb=plt.colorbar(cf)\n\
                       cb.ax.set_ylabel(r'temperature')\n\
                       plt.contour(x,y,z,colors=['yellow'],levels=[0],linestyles=['-'],linewidths=[2])\n";
        assert_eq!(contour.buffer, b);
        contour.clear_buffer();
        assert_eq!(contour.buffer, "");
    }
}