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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// Copyright (c) 2013-2014 by SiegeLord
//
// All rights reserved. Distributed under LGPL 3.0. For full terms see the file LICENSE.

use axes_common::*;
use coordinates::*;
use datatype::*;
use options::*;
use writer::Writer;

/// 2D axes that is used for drawing 2D plots
pub struct Axes2D<'l>
{
	common: AxesCommonData<'l>,
}

impl<'m> Axes2D<'m>
{
	pub(crate) fn new() -> Axes2D<'m>
	{
		Axes2D { common: AxesCommonData::new() }
	}

	/// Sets the properties of the plot border
	///
	/// # Arguments
	///
	/// * `front` - Whether or not to draw the border above or below the plot contents
	/// * `locations` - Which locations of the border to draw
	/// * `options` - Array of PlotOption controlling the appearance of the border. Relevant options are:
	///      * `Color` - Specifies the color of the border
	///      * `LineStyle` - Specifies the style of the border
	///      * `LineWidth` - Specifies the width of the border
	pub fn set_border<'l>(&'l mut self, front: bool, locations: &[BorderLocation2D], options: &[PlotOption<'m>]) -> &'l mut Self
	{
		{
			let c = &mut self.common.commands as &mut Writer;
			c.write_str("set border ");
			let mut f: i32 = 0;
			for &l in locations.iter()
			{
				f |= l as i32;
			}
			write!(c, "{}", f);
			c.write_str(if front
			{
				" front "
			}
			else
			{
				" back "
			});

			AxesCommonData::write_color_options(c, options, Some("black"));
			AxesCommonData::write_line_options(c, options);

			c.write_str("\n");
		}
		self
	}

	fn set_axis_common<'l>(&'l mut self, axis: &str, show: bool, options: &[PlotOption<'m>]) -> &'l mut Self
	{
		{
			let c = &mut self.common.commands as &mut Writer;
			if show
			{
				c.write_str("set ");
				c.write_str(axis);
				c.write_str("zeroaxis ");
				AxesCommonData::write_color_options(c, options, Some("black"));
				AxesCommonData::write_line_options(c, options);
			}
			else
			{
				c.write_str("unset ");
				c.write_str(axis);
				c.write_str("zeroaxis ");
			}

			c.write_str("\n");
		}
		self
	}

	/// Sets the properties of x axis.
	///
	/// # Arguments
	///
	/// * `show` - Whether or not draw the axis
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the axis. Relevant options are:
	///      * `Color` - Specifies the color of the border
	///      * `LineStyle` - Specifies the style of the border
	///      * `LineWidth` - Specifies the width of the border
	pub fn set_x_axis<'l>(&'l mut self, show: bool, options: &[PlotOption<'m>]) -> &'l mut Self
	{
		self.set_axis_common("x", show, options)
	}

	/// Like `set_x_axis` but for the y axis.
	pub fn set_y_axis<'l>(&'l mut self, show: bool, options: &[PlotOption<'m>]) -> &'l mut Self
	{
		self.set_axis_common("y", show, options)
	}

	/// Adds an arrow to the plot. The arrow is drawn from `(x1, y1)` to `(x2, y2)` with the arrow point towards `(x2, y2)`.
	/// # Arguments
	/// * `x1` - X coordinate of the arrow start
	/// * `y1` - Y coordinate of the arrow start
	/// * `x2` - X coordinate of the arrow end
	/// * `y2` - Y coordinate of the arrow end
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the arrowhead and arrow shaft. Relevant options are:
	///      * `ArrowType` - Specifies the style of the arrow head (or an option to omit it)
	///      * `ArrowSize` - Sets the size of the arrow head (in graph units)
	///      * `Color` - Specifies the color of the arrow
	///      * `LineStyle` - Specifies the style of the arrow shaft
	///      * `LineWidth` - Specifies the width of the arrow shaft
	pub fn arrow<'l>(&'l mut self, x1: Coordinate, y1: Coordinate, x2: Coordinate, y2: Coordinate, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		{
			let c = &mut self.common.commands as &mut Writer;
			write!(c, "set arrow from {},{} to {},{}", x1, y1, x2, y2);

			first_opt!{options,
				ArrowType(s) =>
				{
					c.write_str(match s
					{
						Open => "",
						Closed => " empty",
						Filled => " filled",
						NoArrow => " nohead",
					});
				}
			}

			c.write_str(" size graph ");
			first_opt_default!{options,
				ArrowSize(z) =>
				{
					write!(c, "{:.12e}", z);
				},
				_ =>
				{
					c.write_str("0.05");
				}
			}
			c.write_str(",12");

			AxesCommonData::write_color_options(c, options, Some("black"));
			AxesCommonData::write_line_options(c, options);

			c.write_str("\n");
		}
		self
	}

	/// Specifies the location and other properties of the legend
	/// # Arguments
	/// * `x` - X coordinate of the legend
	/// * `y` - Y coordinate of the legend
	/// * `label_options` - Array of LegendOption options
	/// * `text_options` - Array of LabelOption options specifying the appearance of the plot titles. Valid options are:
	///     * `Font`
	///     * `TextColor`
	///     * `TextAlign(AlignLeft)`
	///     * `TextAlign(AlignRight)`
	pub fn set_legend<'l>(&'l mut self, x: Coordinate, y: Coordinate, legend_options: &[LegendOption], text_options: &[LabelOption])
		-> &'l mut Self
	{
		{
			let c = &mut self.common.commands as &mut Writer;

			write!(c, "set key at {},{}", x, y);

			first_opt_default!{legend_options,
				Placement(h, v) =>
				{
					c.write_str(match h
					{
						AlignLeft => " left",
						AlignRight => " right",
						_ => " center"
					});
					c.write_str(match v
					{
						AlignTop => " top",
						AlignBottom => " bottom",
						_ => " center"
					});
				},
				_ =>
				{
					c.write_str(" right top");
				}
			}

			first_opt_default!{legend_options,
				Horizontal =>
				{
					c.write_str(" horizontal");
				},
				_ =>
				{
					c.write_str(" vertical");
				}
			}

			first_opt_default!{legend_options,
				Reverse =>
				{
					c.write_str(" reverse");
				},
				_ =>
				{
					c.write_str(" noreverse");
				}
			}

			first_opt_default!{legend_options,
				Invert =>
				{
					c.write_str(" invert");
				},
				_ =>
				{
					c.write_str(" noinvert");
				}
			}

			first_opt!{legend_options,
				Title(s) =>
				{
					c.write_str(" title \"");
					c.write_str(s);
					c.write_str("\"");
				}
			}

			first_opt!{text_options,
				Font(f, s) =>
				{
					c.write_str(" font \"");
					c.write_str(f);
					c.write_str(",");
					c.write_str(&s.to_string()[..]);
					c.write_str("\"");
				}
			}
			first_opt!{text_options,
				TextColor(s) =>
				{
					c.write_str(" textcolor rgb \"");
					c.write_str(s);
					c.write_str("\"");
				}
			}
			first_opt!{text_options,
				TextAlign(a) =>
				{
					c.write_str(match a
					{
						AlignLeft => " Left",
						AlignRight => " Right",
						_ => ""
					});
				}
			}

			first_opt!{legend_options,
				MaxRows(r) =>
				{
					write!(c, " maxrows {}", r as i32);
				}
			}

			first_opt!{legend_options,
				MaxCols(l) =>
				{
					write!(c, " maxcols {}", l as i32);
				}
			}

			c.write_str("\n");
		}
		self
	}

	/// Plot a 2D scatter-plot with lines connecting each data point
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `LineWidth` - Sets the width of the line
	///     * `LineStyle` - Sets the style of the line
	///     * `Color` - Sets the color
	pub fn lines<'l, Tx: DataType, X: IntoIterator<Item = Tx>, Ty: DataType, Y: IntoIterator<Item = Ty>>(&'l mut self, x: X, y: Y, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot2(Lines, x, y, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot with a point standing in for each data point
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `PointSymbol` - Sets symbol for each point
	///     * `PointSize` - Sets the size of each point
	///     * `Color` - Sets the color
	pub fn points<'l, Tx: DataType, X: IntoIterator<Item = Tx>, Ty: DataType, Y: IntoIterator<Item = Ty>>(&'l mut self, x: X, y: Y, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot2(Points, x, y, options.to_vec()));
		self
	}

	/// A combination of lines and points methods (drawn in that order).
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element
	pub fn lines_points<'l, Tx: DataType, X: IntoIterator<Item = Tx>, Ty: DataType, Y: IntoIterator<Item = Ty>>(&'l mut self, x: X, y: Y, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot2(LinesPoints, x, y, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot with a point standing in for each data point.
	/// Additionally, error bars are attached to each data point in the X direction.
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y valuess
	/// * `x_error` - Errors associated with the x value
	/// * `options` - Array of PlotOption controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `PointSymbol` - Sets symbol for each point
	///     * `PointSize` - Sets the size of each point
	///     * `Color` - Sets the color
	pub fn x_error_bars<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Ty: DataType,
		Y: IntoIterator<Item = Ty>,
		Txe: DataType,
		XE: IntoIterator<Item = Txe>,
	>(
		&'l mut self, x: X, y: Y, x_error: XE, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(XErrorBars, x, y, x_error, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot with a point standing in for each data point.
	/// Additionally, error bars are attached to each data point in the Y direction.
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y values
	/// * `y_error` - Errors associated with the y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `PointSymbol` - Sets symbol for each point
	///     * `PointSize` - Sets the size of each point
	///     * `Color` - Sets the color
	pub fn y_error_bars<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Ty: DataType,
		Y: IntoIterator<Item = Ty>,
		Tye: DataType,
		YE: IntoIterator<Item = Tye>,
	>(
		&'l mut self, x: X, y: Y, y_error: YE, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(YErrorBars, x, y, y_error, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot with a point standing in for each data point and lines connecting each data point.
	/// Additionally, error bars are attached to each data point in the X direction.
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y valuess
	/// * `x_error` - Errors associated with the x value
	/// * `options` - Array of PlotOption controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `PointSymbol` - Sets symbol for each point
	///     * `PointSize` - Sets the size of each point
	///     * `LineWidth` - Sets the width of the line
	///     * `LineStyle` - Sets the style of the line
	///     * `Color` - Sets the color
	pub fn x_error_lines<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Ty: DataType,
		Y: IntoIterator<Item = Ty>,
		Txe: DataType,
		XE: IntoIterator<Item = Txe>,
	>(
		&'l mut self, x: X, y: Y, x_error: XE, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(XErrorLines, x, y, x_error, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot with a point standing in for each data point and lines connecting each data point.
	/// Additionally, error bars are attached to each data point in the Y direction.
	/// # Arguments
	/// * `x` - x values
	/// * `y` - y values
	/// * `y_error` - Errors associated with the y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `PointSymbol` - Sets symbol for each point
	///     * `PointSize` - Sets the size of each point
	///     * `LineWidth` - Sets the width of the line
	///     * `LineStyle` - Sets the style of the line
	///     * `Color` - Sets the color
	pub fn y_error_lines<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Ty: DataType,
		Y: IntoIterator<Item = Ty>,
		Tye: DataType,
		YE: IntoIterator<Item = Tye>,
	>(
		&'l mut self, x: X, y: Y, y_error: YE, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(YErrorLines, x, y, y_error, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot of two curves (bound by `y_lo` and `y_hi`) with a filled region between them.
	/// `FillRegion` plot option can be used to control what happens when the curves intersect. If set to Above, then the `y_lo < y_hi` region is filled.
	/// If set to Below, then the `y_lo > y_hi` region is filled. Otherwise both regions are filled.
	/// # Arguments
	/// * `x` - x values
	/// * `y_lo` - Bottom y values
	/// * `y_hi` - Top y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `FillRegion` - Specifies the region between the two curves to fill
	///     * `Color` - Sets the color of the filled region
	///     * `FillAlpha` - Sets the transparency of the filled region
	pub fn fill_between<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Tyl: DataType,
		YL: IntoIterator<Item = Tyl>,
		Tyh: DataType,
		YH: IntoIterator<Item = Tyh>,
	>(
		&'l mut self, x: X, y_lo: YL, y_hi: YH, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(FillBetween, x, y_lo, y_hi, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot using boxes of automatic width. Box widths are set so that there are no gaps between successive boxes (i.e. each box may have a different width).
	/// Boxes start at the x-axis and go towards the y value of the datapoint.
	/// # Arguments
	/// * `x` - x values (center of the box)
	/// * `y` - y values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `LineWidth` - Sets the width of the border
	///     * `LineStyle` - Sets the style of the border
	///     * `BorderColor` - Sets the color of the border
	///     * `Color` - Sets the color of the box fill
	///     * `FillAlpha` - Sets the transparency of the box fill
	pub fn boxes<'l, Tx: DataType, X: IntoIterator<Item = Tx>, Ty: DataType, Y: IntoIterator<Item = Ty>>(&'l mut self, x: X, y: Y, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot2(Boxes, x, y, options.to_vec()));
		self
	}

	/// Plot a 2D scatter-plot using boxes of set (per box) width.
	/// Boxes start at the x-axis and go towards the y value of the datapoint.
	/// # Arguments
	/// * `x` - x values (center of the box)
	/// * `y` - y values
	/// * `w` - Box width values
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the plot element. The relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	///     * `LineWidth` - Sets the width of the border
	///     * `LineStyle` - Sets the style of the border
	///     * `BorderColor` - Sets the color of the border
	///     * `Color` - Sets the color of the box fill
	///     * `FillAlpha` - Sets the transparency of the box fill
	pub fn boxes_set_width<
		'l,
		Tx: DataType,
		X: IntoIterator<Item = Tx>,
		Ty: DataType,
		Y: IntoIterator<Item = Ty>,
		Tw: DataType,
		W: IntoIterator<Item = Tw>,
	>(
		&'l mut self, x: X, y: Y, w: W, options: &[PlotOption<'m>]
	) -> &'l mut Self
	{
		self.common.elems.push(PlotElement::new_plot3(Boxes, x, y, w, options.to_vec()));
		self
	}

	/// Draws an image from a rectangular array of data by connecting the individual datapoints with polygons.
	///
	/// #Arguments:
	/// * `mat` - Row-major 2D array signifying the value of the datapoints. The X and Y coordinates of the datapoints are determined automatically,
	///           and optionally scaled using the `dimensions` argument.
	/// * `num_rows` - Number of rows in the data array
	/// * `num_cols` - Number of columns in the data array
	/// * `dimensions` - Optional X and Y coordinates of the first and last data points (with the rest of the coordinates spaced evenly between).
	///                  By default this will be `(0, 0)` and `(num_rows - 1, num_cols - 1)`.
	/// * `options` - Array of PlotOption<'m> controlling the appearance of the surface. Relevant options are:
	///     * `Caption` - Specifies the caption for this dataset. Use an empty string to hide it (default).
	pub fn image<'l, T: DataType, X: IntoIterator<Item = T>>(&'l mut self, mat: X, num_rows: usize, num_cols: usize, dimensions: Option<(f64, f64, f64, f64)>, options: &[PlotOption<'m>])
		-> &'l mut Self
	{
		self.common
			.elems
			.push(PlotElement::new_plot_matrix(Image, false, mat, num_rows, num_cols, dimensions, options.to_vec()));
		self
	}
}

impl<'l> AxesCommonPrivate<'l> for Axes2D<'l>
{
	fn get_common_data_mut(&mut self) -> &mut AxesCommonData<'l>
	{
		&mut self.common
	}

	fn get_common_data(&self) -> &AxesCommonData<'l>
	{
		&self.common
	}
}

impl<'l> AxesCommon<'l> for Axes2D<'l> {}

pub(crate) trait Axes2DPrivate
{
	fn write_out(&self, writer: &mut Writer);
}

impl<'l> Axes2DPrivate for Axes2D<'l>
{
	fn write_out(&self, writer: &mut Writer)
	{
		if self.common.elems.len() == 0
		{
			return;
		}

		self.common.write_out_commands(writer);
		let mut grid_axes = vec![];
		if self.common.x_axis.grid
		{
			grid_axes.push(self.common.x_axis.axis);
		}
		if self.common.y_axis.grid
		{
			grid_axes.push(self.common.y_axis.axis);
		}
		if self.common.cb_axis.grid
		{
			grid_axes.push(self.common.cb_axis.axis);
		}
		self.common.write_grid_options(writer, &grid_axes);
		self.common.write_out_elements("plot", writer);
	}
}