#![deny(missing_docs)]
#![deny(warnings)]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default))]
#![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))]
extern crate byteorder;
extern crate cast;
#[macro_use]
extern crate itertools;
use std::borrow::Cow;
use std::fs::File;
use std::io;
use std::path::Path;
use std::process::{Child, Command};
use std::str;
use data::Matrix;
use traits::{Configure, Set};
mod data;
mod display;
mod map;
pub mod axis;
pub mod candlestick;
pub mod curve;
pub mod errorbar;
pub mod filledcurve;
pub mod grid;
pub mod key;
pub mod prelude;
pub mod proxy;
pub mod traits;
#[derive(Clone)]
pub struct Figure {
alpha: Option<f64>,
axes: map::axis::Map<axis::Properties>,
box_width: Option<f64>,
font: Option<Cow<'static, str>>,
font_size: Option<f64>,
key: Option<key::Properties>,
output: Cow<'static, Path>,
plots: Vec<Plot>,
size: Option<(usize, usize)>,
terminal: Terminal,
tics: map::axis::Map<String>,
title: Option<Cow<'static, str>>,
}
impl Figure {
pub fn new() -> Figure {
Figure {
alpha: None,
axes: map::axis::Map::new(),
box_width: None,
font: None,
font_size: None,
key: None,
output: Cow::Borrowed(Path::new("output.plot")),
plots: Vec::new(),
size: None,
terminal: Terminal::Svg,
tics: map::axis::Map::new(),
title: None,
}
}
fn script(&self) -> Vec<u8> {
let mut s = String::new();
s.push_str(&format!("set output '{}'\n", self.output.display()));
if let Some(width) = self.box_width {
s.push_str(&format!("set boxwidth {}\n", width))
}
if let Some(ref title) = self.title {
s.push_str(&format!("set title '{}'\n", title))
}
for axis in self.axes.iter() {
s.push_str(&axis.script());
}
for (_, script) in self.tics.iter() {
s.push_str(script);
}
if let Some(ref key) = self.key {
s.push_str(&key.script())
}
if let Some(alpha) = self.alpha {
s.push_str(&format!("set style fill transparent solid {}\n", alpha))
}
s.push_str(&format!("set terminal {} dashed", self.terminal.display()));
if let Some((width, height)) = self.size {
s.push_str(&format!(" size {}, {}", width, height))
}
if let Some(ref name) = self.font {
if let Some(size) = self.font_size {
s.push_str(&format!(" font '{},{}'", name, size))
} else {
s.push_str(&format!(" font '{}'", name))
}
}
s.push_str("\nunset bars\n");
let mut is_first_plot = true;
for plot in &self.plots {
let data = plot.data();
if data.bytes().is_empty() {
continue;
}
if is_first_plot {
s.push_str("plot ");
is_first_plot = false;
} else {
s.push_str(", ");
}
s.push_str(&format!(
"'-' binary endian=little record={} format='%float64' using ",
data.nrows()
));
let mut is_first_col = true;
for col in 0..data.ncols() {
if is_first_col {
is_first_col = false;
} else {
s.push(':');
}
s.push_str(&(col + 1).to_string());
}
s.push(' ');
s.push_str(plot.script());
}
let mut buffer = s.into_bytes();
let mut is_first = true;
for plot in &self.plots {
if is_first {
is_first = false;
buffer.push(b'\n');
}
buffer.extend_from_slice(plot.data().bytes());
}
buffer
}
pub fn draw(&mut self) -> io::Result<Child> {
use std::process::Stdio;
let mut gnuplot = try!{
Command::new("gnuplot").
stderr(Stdio::piped()).
stdin(Stdio::piped()).
stdout(Stdio::piped()).
spawn()
};
try!(self.dump(gnuplot.stdin.as_mut().unwrap()));
Ok(gnuplot)
}
pub fn dump<W>(&mut self, sink: &mut W) -> io::Result<&mut Figure>
where
W: io::Write,
{
try!(sink.write_all(&self.script()));
Ok(self)
}
pub fn save(&self, path: &Path) -> io::Result<&Figure> {
use std::io::Write;
try!((try!(File::create(path))).write_all(&self.script()));
Ok(self)
}
}
impl Configure<Axis> for Figure {
type Properties = axis::Properties;
fn configure<F>(&mut self, axis: Axis, configure: F) -> &mut Figure
where
F: FnOnce(&mut axis::Properties) -> &mut axis::Properties,
{
if self.axes.contains_key(axis) {
configure(self.axes.get_mut(axis).unwrap());
} else {
let mut properties = Default::default();
configure(&mut properties);
self.axes.insert(axis, properties);
}
self
}
}
impl Configure<Key> for Figure {
type Properties = key::Properties;
fn configure<F>(&mut self, _: Key, configure: F) -> &mut Figure
where
F: FnOnce(&mut key::Properties) -> &mut key::Properties,
{
if self.key.is_some() {
configure(self.key.as_mut().unwrap());
} else {
let mut key = Default::default();
configure(&mut key);
self.key = Some(key);
}
self
}
}
impl Set<BoxWidth> for Figure {
fn set(&mut self, width: BoxWidth) -> &mut Figure {
let width = width.0;
assert!(width >= 0.);
self.box_width = Some(width);
self
}
}
impl Set<Font> for Figure {
fn set(&mut self, font: Font) -> &mut Figure {
self.font = Some(font.0);
self
}
}
impl Set<FontSize> for Figure {
fn set(&mut self, size: FontSize) -> &mut Figure {
let size = size.0;
assert!(size >= 0.);
self.font_size = Some(size);
self
}
}
impl Set<Output> for Figure {
fn set(&mut self, output: Output) -> &mut Figure {
self.output = output.0;
self
}
}
impl Set<Size> for Figure {
fn set(&mut self, size: Size) -> &mut Figure {
self.size = Some((size.0, size.1));
self
}
}
impl Set<Terminal> for Figure {
fn set(&mut self, terminal: Terminal) -> &mut Figure {
self.terminal = terminal;
self
}
}
impl Set<Title> for Figure {
fn set(&mut self, title: Title) -> &mut Figure {
self.title = Some(title.0);
self
}
}
impl Default for Figure {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Copy)]
pub struct BoxWidth(pub f64);
pub struct Font(Cow<'static, str>);
#[derive(Clone, Copy)]
pub struct FontSize(pub f64);
#[derive(Clone, Copy)]
pub struct Key;
pub struct Label(Cow<'static, str>);
#[derive(Clone, Copy)]
pub struct LineWidth(pub f64);
#[derive(Clone, Copy)]
pub struct Opacity(pub f64);
pub struct Output(Cow<'static, Path>);
#[derive(Clone, Copy)]
pub struct PointSize(pub f64);
#[derive(Clone, Copy)]
pub enum Range {
Auto,
Limits(f64, f64),
}
#[derive(Clone, Copy)]
pub struct Size(pub usize, pub usize);
pub struct TicLabels<P, L> {
pub labels: L,
pub positions: P,
}
pub struct Title(Cow<'static, str>);
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum Axes {
BottomXLeftY,
BottomXRightY,
TopXLeftY,
TopXRightY,
}
#[derive(Clone, Copy)]
pub enum Axis {
BottomX,
LeftY,
RightY,
TopX,
}
impl Axis {
fn next(&self) -> Option<Axis> {
use Axis::*;
match *self {
BottomX => Some(LeftY),
LeftY => Some(RightY),
RightY => Some(TopX),
TopX => None,
}
}
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum Color {
Black,
Blue,
Cyan,
DarkViolet,
ForestGreen,
Gold,
Gray,
Green,
Magenta,
Red,
Rgb(u8, u8, u8),
White,
Yellow,
}
#[derive(Clone, Copy)]
pub enum Grid {
Major,
Minor,
}
impl Grid {
fn next(&self) -> Option<Grid> {
use Grid::*;
match *self {
Major => Some(Minor),
Minor => None,
}
}
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum LineType {
Dash,
Dot,
DotDash,
DotDotDash,
SmallDot,
Solid,
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum PointType {
Circle,
FilledCircle,
FilledSquare,
FilledTriangle,
Plus,
Square,
Star,
Triangle,
X,
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum Scale {
Linear,
Logarithmic,
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub struct ScaleFactor(pub f64);
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum Terminal {
Svg,
}
trait Default {
fn default() -> Self;
}
trait Display<S> {
fn display(&self) -> S;
}
trait CurveDefault<S> {
fn default(S) -> Self;
}
trait ErrorBarDefault<S> {
fn default(S) -> Self;
}
trait Script {
fn script(&self) -> String;
}
#[derive(Clone)]
struct Plot {
data: Matrix,
script: String,
}
impl Plot {
fn new<S>(data: Matrix, script: &S) -> Plot
where
S: Script,
{
Plot {
data: data,
script: script.script(),
}
}
fn data(&self) -> &Matrix {
&self.data
}
fn script(&self) -> &str {
&self.script
}
}
pub fn version() -> io::Result<(usize, usize, usize)> {
let stdout = try!(Command::new("gnuplot").arg("--version").output()).stdout;
let mut words = str::from_utf8(&stdout).unwrap().split_whitespace().skip(1);
let mut version = words.next().unwrap().split('.');
let major = version.next().unwrap().parse().unwrap();
let minor = version.next().unwrap().parse().unwrap();
let patchlevel = words.nth(1).unwrap().parse().unwrap();
Ok((major, minor, patchlevel))
}
fn scale_factor(map: &map::axis::Map<axis::Properties>, axes: Axes) -> (f64, f64) {
use Axes::*;
use Axis::*;
match axes {
BottomXLeftY => (
map.get(BottomX).map_or(1., |props| props.scale_factor()),
map.get(LeftY).map_or(1., |props| props.scale_factor()),
),
BottomXRightY => (
map.get(BottomX).map_or(1., |props| props.scale_factor()),
map.get(RightY).map_or(1., |props| props.scale_factor()),
),
TopXLeftY => (
map.get(TopX).map_or(1., |props| props.scale_factor()),
map.get(LeftY).map_or(1., |props| props.scale_factor()),
),
TopXRightY => (
map.get(TopX).map_or(1., |props| props.scale_factor()),
map.get(RightY).map_or(1., |props| props.scale_factor()),
),
}
}
trait ScaleFactorTrait {
fn scale_factor(&self) -> f64;
}
#[cfg(test)]
mod test {
#[test]
fn version() {
if let Ok(version) = super::version() {
let (major, _, _) = version;
assert!(major >= 4);
} else {
println!("Gnuplot not installed.");
}
}
}