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
use std::f64;

use BitMap;
use line;
use Axis;

const W_ARROW: usize = 4;      //width of arrow
const W_NUMBER: usize = 4;     //number width in pixel
const H_NUMBER: usize = 5;     //number height in pixels
const W_BORDER: usize = 1;     //space around graph width
const H_ARROW_HALF: usize = 3;

const LEFT_SHIFT: usize = W_BORDER + W_NUMBER + H_NUMBER;
const RIGHT_SHIFT: usize = W_ARROW;


quick_error! {
    #[derive(Debug)]
    pub enum GraphError {
        NotEnoughPoints {
            description("There are not enough points to display on graph.")
        }
        NotEnoughSpace {
            description("There are not enough width and height to form graph with axis.")
        }
        NonUniquePoints {
            description("There are only one unique point. Can't construct line.")
        }
    }
}

pub type GraphResult = Result<Vec<u8>, GraphError>;


pub trait InPoint: Into<Point> + PartialEq {}
impl<T: Into<Point> + PartialEq> InPoint for T {}

pub trait IterInPoint<P: InPoint>: Iterator<Item = P> + Clone {}
impl<T, P> IterInPoint<P> for T
    where T: Iterator<Item = P> + Clone,
          P: InPoint
{
}

#[derive(Clone, Copy)]
pub struct Point {
    pub x: f64,
    pub y: f64,
}

impl<'a> From<&'a (f64, f64)> for Point {
    fn from(t: &'a (f64, f64)) -> Point {
        Point { x: t.0, y: t.1 }
    }
}

impl From<(f64, f64)> for Point {
    fn from(t: (f64, f64)) -> Point {
        Point { x: t.0, y: t.1 }
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub struct DisplayPoint {
    pub x: usize,
    pub y: usize,
}


#[derive(Debug, Clone)]
pub struct Serie<T: IterInPoint<P, Item = P>, P: InPoint> {
    pub iter: T,
    color: String,
    max_x: f64,
    max_y: f64,
    min_x: f64,
    min_y: f64,
}

impl<P: InPoint, T: IterInPoint<P>> Serie<T, P> {
    pub fn new<S: Into<String>>(iter: T, color: S) -> Result<Self, GraphError> {

        let color = color.into();

        if iter.clone().nth(1).is_none() {
            return Err(GraphError::NotEnoughPoints);
        }

        let first = iter.clone().nth(0).unwrap();
        if !iter.clone().skip(1).any(move |p| p != first) {
            return Err(GraphError::NonUniquePoints);
        }

        let (max_x, min_x, max_y, min_y) = Self::calculate_max_min(iter.clone());

        Ok(Serie {
            iter: iter,
            color: color,
            max_x: max_x,
            max_y: max_y,
            min_x: min_x,
            min_y: min_y,
        })
    }

    fn calculate_max_min(iter: T) -> (f64, f64, f64, f64) {
        let (mut min_x, mut max_x) = (f64::INFINITY, f64::NEG_INFINITY);
        let (mut min_y, mut max_y) = (f64::INFINITY, f64::NEG_INFINITY);

        for p in iter {
            let p = p.into();
            if p.x > max_x {
                max_x = p.x;
            }
            if p.x < min_x {
                min_x = p.x;
            }
            if p.y > max_y {
                max_y = p.y;
            }
            if p.y < min_y {
                min_y = p.y;
            }
        }
        (max_x, min_x, max_y, min_y)
    }
}


#[derive(Debug)]
pub struct Chart {
    width: usize,
    height: usize,
    background_color: u8,
    axis_color: u8,
    pixs: Vec<u8>,
    picture: BitMap,
    axis_x: Option<Axis>,
    axis_y: Option<Axis>,
}

impl Chart {
    pub fn new(width: usize,
               height: usize,
               background_color: &str,
               axis_color: &str)
               -> Result<Self, GraphError> {

        if width < (2 * H_NUMBER + 2 * W_NUMBER + W_ARROW + 2 * W_BORDER) ||
           height < (2 * H_NUMBER + 2 * W_NUMBER + W_ARROW + 2 * W_BORDER) {
            return Err(GraphError::NotEnoughSpace);
        };

        let mut picture = BitMap::new(width, height);

        let background_color_number = picture.add_color(background_color);

        let axis_color_number = picture.add_color(axis_color);

        let size = width * height;

        let pixs = vec![background_color_number;  size];

        Ok(Chart {
            width: width,
            height: height,
            background_color: background_color_number,
            axis_color: axis_color_number,
            pixs: pixs,
            picture: picture,
            axis_x: None,
            axis_y: None,
        })
    }

    pub fn add_axis_x(self, axis_x: Axis) -> Chart {
        let new_axis_x = Some(Axis::set_axis_manual(axis_x.min_value,
                                                    axis_x.max_value,
                                                    axis_x.interval_count,
                                                    axis_x.decimal_places,
                                                    self.width));
        Chart { axis_x: new_axis_x, ..self }
    }


    pub fn add_axis_y(self, axis_y: Axis) -> Chart {
        let new_axis_y = Some(Axis::set_axis_manual(axis_y.min_value,
                                                    axis_y.max_value,
                                                    axis_y.interval_count,
                                                    axis_y.decimal_places,
                                                    self.height)
            .rotate());
        Chart { axis_y: new_axis_y, ..self }
    }

    fn draw_serie<P: InPoint, T: IterInPoint<P>>(&mut self, serie: Serie<T, P>) {

        let func_points = {

            let max_width = self.width - RIGHT_SHIFT;

            let max_height = self.height - RIGHT_SHIFT;

            let function = self.serie_to_points(&serie);

            line::extrapolate(function)
                .filter(|p| {
                    p.x >= LEFT_SHIFT && p.x <= max_width && p.y >= LEFT_SHIFT && p.y <= max_height
                })
                .collect::<Vec<DisplayPoint>>()

        };

        let points_color_number = self.picture.add_color(&*serie.color);

        self.draw_pixels(func_points, points_color_number);
    }


    fn calc_axis<S, T, P>(&mut self, series: S)
        where S: Iterator<Item = Serie<T, P>>,
              T: IterInPoint<P>,
              P: InPoint
    {
        let (mut min_x, mut max_x) = (f64::INFINITY, f64::NEG_INFINITY);
        let (mut min_y, mut max_y) = (f64::INFINITY, f64::NEG_INFINITY);

        for s in series {
            if s.max_x > max_x {
                max_x = s.max_x;
            }
            if s.min_x < min_x {
                min_x = s.min_x;
            }

            if s.max_y > max_y {
                max_y = s.max_y;
            }
            if s.min_y < min_y {
                min_y = s.min_y;
            }
        }

        if self.axis_x.is_none() {
            self.axis_x = Some(Axis::set_axis_auto(max_x, min_x, self.width));
        }

        if self.axis_y.is_none() {
            self.axis_y = Some(Axis::set_axis_auto(max_y, min_y, self.height).rotate());
        }
    }

    pub fn draw<S, T, P>(&mut self, series: S) -> Vec<u8>
        where S: Iterator<Item = Serie<T, P>> + Clone,
              T: IterInPoint<P>,
              P: InPoint
    {

        if self.axis_x.is_none() || self.axis_y.is_none() {
            self.calc_axis(series.clone());
        }

        self.draw_axis();

        for serie in series {
            self.draw_serie(serie);
        }

        self.picture.add_pixels(&self.pixs);

        self.picture.as_vec()
    }

    fn draw_axis(&mut self) {

        let axis_x = self.axis_x.clone().unwrap();

        let axis_y = self.axis_y.clone().unwrap();

        let minor_net = self.get_minor_net(&axis_x, &axis_y);

        let axis_color = self.axis_color;

        self.draw_pixels(axis_x.create_points(), axis_color);

        self.draw_pixels(axis_y.create_points(), axis_color);

        self.draw_pixels(minor_net, axis_color);
    }

    fn get_minor_net(&self, axis_x: &Axis, axis_y: &Axis) -> Vec<DisplayPoint> {
        let mut v: Vec<DisplayPoint> = vec![];
        for i in 0..axis_x.interval_count {
            let shift = LEFT_SHIFT + ((axis_x.scale_interval_pix * (i as f64)).round() as usize);
            for j in LEFT_SHIFT..(self.height - H_ARROW_HALF) {
                if j % 2 != 0 {
                    v.push(DisplayPoint { x: shift, y: j });
                }
            }
        }

        for i in 0..axis_y.interval_count {
            let shift = LEFT_SHIFT + ((axis_y.scale_interval_pix * (i as f64)).round() as usize);
            for j in LEFT_SHIFT..(self.width - H_ARROW_HALF) {
                if j % 2 != 0 {
                    v.push(DisplayPoint { x: j, y: shift });
                }
            }
        }
        v
    }

    fn serie_to_points<'b, P: InPoint, T: IterInPoint<P>>
        (&'b mut self,
         serie: &'b Serie<T, P>)
         -> Box<Iterator<Item = DisplayPoint> + 'b> {

        let width_available = self.width - LEFT_SHIFT - RIGHT_SHIFT;

        let height_available = self.height - LEFT_SHIFT - RIGHT_SHIFT;

        let axis_x = self.axis_x.clone().unwrap();

        let axis_y = self.axis_y.clone().unwrap();

        let resolution_x: f64 = (axis_x.max_value - axis_x.min_value) / (width_available as f64);
        let resolution_y: f64 = (axis_y.max_value - axis_y.min_value) / (height_available as f64);

        let serie_iter = serie.iter.clone();

        Box::new(serie_iter.map(move |p| {
            let p = p.into();
            let id_x = ((p.x - axis_x.min_value) / resolution_x).round();
            let id_y = ((p.y - axis_y.min_value) / resolution_y).round();

            let id_x = if id_x < 0f64 {
                LEFT_SHIFT - 1
            } else if id_x > (width_available as f64) {
                width_available + LEFT_SHIFT + 1
            } else {
                (id_x as usize) + LEFT_SHIFT
            };

            let id_y = if id_y < 0f64 {
                LEFT_SHIFT - 1
            } else if id_y > (height_available as f64) {
                height_available + LEFT_SHIFT + 1
            } else {
                (id_y as usize) + LEFT_SHIFT
            };

            DisplayPoint { x: id_x, y: id_y }
        }))

    }


    fn draw_pixels(&mut self, points: Vec<DisplayPoint>, color: u8) {
        for p in points {
            let i = p.y * self.width + p.x;
            self.pixs[i] = color;
        }
    }
}



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

    #[test]
    fn not_enough_space_test() {
        let result = Chart::new(10, 15, "#ffffff", "#000000");
        assert_eq!(result.err().unwrap().to_string(),
                   "There are not enough width and height to form graph with axis.");
    }

    #[test]
    fn not_enough_points_test() {
        let v: Vec<(f64, f64)> = vec![];
        let result = Serie::new(v.into_iter(), "#0000ff".to_string());
        assert_eq!(result.err().unwrap().to_string(),
                   "There are not enough points to display on graph.");
    }

    #[test]
    fn one_point_test() {
        let p = vec![(1f64, 1f64)];
        let result = Serie::new(p.into_iter(), "#0000ff".to_string());
        assert_eq!(result.err().unwrap().to_string(),
                   "There are not enough points to display on graph.");
    }

    #[test]
    fn two_identical_point_test() {
        let p = vec![(1f64, 1f64), (1f64, 1f64)];
        let result = Serie::new(p.into_iter(), "#0000ff".to_string());
        assert_eq!(result.err().unwrap().to_string(),
                   "There are only one unique point. Can't construct line.");
    }

    #[test]
    fn can_draw_array() {
        let p = vec![(1f64, 1f64), (2f64, 2f64), (3f64, 3f64)];
        let serie = Serie::new(p.into_iter(), "#0000ff".to_string()).unwrap();
        let mut chart = Chart::new(100, 100, "#ffffff", "#000000").unwrap();
        let series = vec![serie];
        let bmp = chart.draw(series.into_iter());
        for p in bmp {
            println!("{}", p);
        }
    }

    #[test]
    fn can_draw_axis_manual() {
        let p = vec![(1f64, 1f64), (2f64, 2f64), (3f64, 3f64)];
        let serie = Serie::new(p.into_iter(), "#0000ff".to_string()).unwrap();
        let axis_x = Axis::new(0f64, 2f64, 7, 2);
        let mut chart = Chart::new(100, 100, "#ffffff", "#000000")
            .unwrap()
            .add_axis_x(axis_x);
        let series = vec![serie];
        let _ = chart.draw(series.into_iter());
    }
}

#[cfg(all(feature = "dev", test))]
mod bench {
    extern crate test;
    use super::*;

    #[bench]
    fn create_graph_2_points(b: &mut test::Bencher) {
        b.iter(|| {
            let p = vec![(1f64, 1f64), (2f64, 2f64), (3f64, 3f64)];
            let serie = Serie::new(p.into_iter(), "#0000ff".to_string()).unwrap();
            let mut chart = Chart::new(740, 480, "#ffffff", "#000000").unwrap();
            let series = vec![serie];
            let _ = chart.draw(series.into_iter());
        })
    }

    #[bench]
    fn create_graph_1000_points(b: &mut test::Bencher) {
        b.iter(|| {
            let p: Vec<_> = formula!(y(x) = {x*x}, x = [0, 1000; 1]).collect();
            let serie = Serie::new(p.into_iter(), "#0000ff".to_string()).unwrap();
            let mut chart = Chart::new(740, 480, "#ffffff", "#000000").unwrap();
            let series = vec![serie];
            let _ = chart.draw(series.into_iter());
        })
    }

    #[bench]
    #[ignore]
    fn create_graph_1000000_points(b: &mut test::Bencher) {
        b.iter(|| {
            let p: Vec<_> = formula!(y(x) = {x*x}, x = [0, 1000; 0.001]).collect();
            let serie = Serie::new(p.into_iter(), "#0000ff".to_string()).unwrap();
            let mut chart = Chart::new(740, 480, "#ffffff", "#000000").unwrap();
            let series = vec![serie];
            let _ = chart.draw(series.into_iter());
        })
    }
}