pub struct Sampling { /* private fields */ }
Expand description

A 2D sampling. This can be thought as a path, with possible “cuts” because of discontinuities or leaving the domain of the (parametric) function describing the path.

Implementations§

source§

impl Sampling

source

pub fn is_empty(&self) -> bool

Return true if the sampling contains no point.

Examples found in repository?
examples/speed.rs (line 39)
34
35
36
37
38
39
40
41
42
fn main() {
    let mut b = false;
    for n in 10 .. 5_000 {
        let s = Sampling::fun(|x| x.sin(), 0., 10.)
            .n(n).build();
        b &= s.is_empty();
    }
    println!("{b}")
}
source

pub fn iter(&self) -> impl Iterator<Item = [f64; 2]> + '_

Iterate on the points (and cuts) of the path. More precisely, a path is made of continuous segments whose points are given by contiguous values [x,y] with both x and y not NaN, interspaced by “cuts” [f64::NAN; 2]. Two cuts never follow each other. Isolated points p are given by … [f64::NAN; 2], p, None,…

source

pub fn x(&self) -> Vec<f64>

Iterator on the x-coordinates of the sampling. See Self::iter for more information.

source

pub fn y(&self) -> Vec<f64>

Iterator on the y-coordinates of the sampling. See Self::iter for more information.

source§

impl Sampling

source

pub fn bounding_box(&self) -> BoundingBox

Return the smallest rectangle enclosing all the points of the sampling self. If the path is empty, the “min” fields of the bounding box are set to +∞ and “max” fields to -∞.

source

pub fn transpose(&mut self) -> &mut Self

Transpose in place the x and y coordinates of the sampling.

source

pub fn clip(&self, bb: BoundingBox) -> Self

Returns the sampling self but clipped to the 2D box bb. A path that crosses the boundary will get additional nodes at the points of crossing and the part outside the bounding box will be dropped. (Thus a path entirely out of the bounding box will be removed.)

Examples found in repository?
examples/clip.rs (lines 12-13)
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() -> Result<(), Box<dyn Error>> {
    let s = cs::Sampling::from_iter(
        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
    s.write(&mut File::create("/tmp/clip0.dat")?)?;
    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
                                      ymin: 0., ymax: 1. });
    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;

    Ok(())
}
source§

impl Sampling

source

pub fn uniform<F>(f: F, a: f64, b: f64) -> Uniform<F>where F: FnMut(f64) -> f64,

Create a sampling for the graph of f on the interval [ab] with evenly spaced values of the argument.

Panics if a or b is not finite.

Example
use std::{fs::File, io::BufWriter};
use curve_sampling::Sampling;
let s = Sampling::uniform(|x| x.sin(), 0., 4.).build();
s.write(&mut BufWriter::new(File::create("target/uniform.dat")?))?;
Examples found in repository?
examples/latex_speed.rs (line 16)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() -> Result<(), Box<dyn Error>> {
    let path = "/tmp/latex_speed.tex";
    let mut fh = File::create(path)?;
    write!(fh, "\\documentclass[12pt,a4paper]{{article}}\n\
                \\usepackage{{tikz}}\n\
                \\begin{{document}}\n\
                \\begin{{tikzpicture}}\n")?;
    let n = 40_000;
    println!("Run \"latex {}\" measure LaTeX speed with {} points.\n",
             path, n);
    let s = Sampling::uniform(f64::sin, -6., 6.).n(n).build();
    s.latex().write(&mut fh)?;
    write!(fh, "\\end{{tikzpicture}}\n\
                \\end{{document}}")?;
    Ok(())
}
More examples
Hide additional examples
examples/arrows.rs (line 13)
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
fn main() -> Result<(), Box<dyn Error>> {
    let s = Sampling::from_iter([[0., 0.], [1., 1.], [NAN, NAN],
                                 [1., 1.], [3., -1.]]);
    s.latex().arrow_pos(0.3).write(&mut File::create("/tmp/arrow0.tex")?)?;

    let s = Sampling::uniform(|x| -0.7 * (x - 1.).powi(2), 0., 2.5).build();
    s.latex().arrow_pos(0.6).write(&mut File::create("/tmp/arrow1.tex")?)?;


    File::create("/tmp/arrows.tex")?.write_all(
        r"\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[x=3cm, y=3cm]
  \draw[->] (-1.2, 0) -- (3.2, 0);
  \draw[->] (0, -1.2) -- (0, 1.7);
  \foreach \x in {-1, -0.5, 0.5, 1, 1.5,..., 3}{
    \draw (\x, 3pt) -- (\x, -3pt) node[below]{$\scriptstyle \x$};
  }
  \foreach \y in {-1, -0.5, 0.5, 1, 1.5}{
    \draw (3pt, \y) -- (-3pt, \y) node[left]{$\scriptstyle \y$};
  }
  \begin{scope}[color=blue, line width=1pt]
    \input{arrow0.tex}
  \end{scope}
  \begin{scope}[color=orange, line width=1pt]
    \input{arrow1.tex}
  \end{scope}
\end{tikzpicture}
\end{document}".as_bytes())?;

    std::env::set_current_dir("/tmp")?;
    Command::new("pdflatex")
        .args(["-interaction=batchmode", "arrows.tex"]).output()?;
    Ok(())
}
source§

impl Sampling

source

pub fn fun<F>(f: F, a: f64, b: f64) -> Fun<F>where F: FnMut(f64) -> f64,

Create a sampling of the graph of f on the interval [ab] by evaluating f at n points.

Panics if a or b is not finite.

Example
use std::{fs::File, io::BufWriter};
use curve_sampling::Sampling;
let s = Sampling::fun(|x| x.sin(), 0., 4.).build();
s.write(&mut BufWriter::new(File::create("target/fun.dat")?))?;
Examples found in repository?
examples/speed.rs (line 37)
34
35
36
37
38
39
40
41
42
fn main() {
    let mut b = false;
    for n in 10 .. 5_000 {
        let s = Sampling::fun(|x| x.sin(), 0., 10.)
            .n(n).build();
        b &= s.is_empty();
    }
    println!("{b}")
}
More examples
Hide additional examples
examples/nice.rs (line 13)
7
8
9
10
11
12
13
14
15
16
fn main() -> Result<(), Box<dyn Error>> {
    let f = |t: f64| [t.cos(), (2. * t).sin()];
    let s = Sampling::param(f, 0., 2. * PI).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;

    let f = |x: f64| (- x.powi(2)).exp();
    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
    Ok(())
}
examples/sin_inv_x.rs (line 29)
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
fn main() -> R {
    let mut fh = File::create("/tmp/sin_inv_x.gp")?;
    write!(fh, "set terminal pngcairo\n\
                set grid\n")?;
    let mut d = 0;
    let mut save = |s: &Sampling, n, title| -> R {
        d += 1;
        let fname = format!("/tmp/sin_inv_x{}.dat", d);
        s.write(&mut File::create(&fname)?)?;
        write!(fh, "set output \"sin_inv_x{}.png\"\n\
                    plot '{}' with l lt 1 lw 2 title \"{} ({} pts)\"\n",
               d, &fname, title, n)?;
        write!(fh, "set output \"sin_inv_x{}_p.png\"\n\
                    plot '{}' with l lt 5 lw 2 title \"{}\", \
                    '{}' with p lt 3 pt 5 ps 0.2 title \"points ({})\"\n",
               d, &fname, title, &fname, n)?;
        Ok(())
    };

    let f = |x: f64| x * (1. / x).sin();
    let s = Sampling::fun(f, -0.4, 0.4).n(227).build();
    save(&s, 227, "x sin(1/x)")?;
    let s = Sampling::fun(f, -0.4, 0.4).n(389).build();
    save(&s, 389, "x sin(1/x)")?;

    let s = Sampling::fun(|x: f64| (1. / x).sin(), -0.4, 0.4).n(391).build();
    save(&s, 391, "sin(1/x)")?;

    Ok(())
}
source§

impl Sampling

source

pub fn param<F>(f: F, a: f64, b: f64) -> Param<F>where F: FnMut(f64) -> [f64; 2],

Create a sampling of the image of f on the interval [ab] by evaluating f at n points.

Panics if a or b is not finite.

Example
use std::{fs::File, io::BufWriter};
use curve_sampling::Sampling;
let s = Sampling::param(|t| [t.sin(), t.cos()], 0., 4.).build();
s.write(&mut BufWriter::new(File::create("target/param.dat")?))?;
Examples found in repository?
examples/nice.rs (line 9)
7
8
9
10
11
12
13
14
15
16
fn main() -> Result<(), Box<dyn Error>> {
    let f = |t: f64| [t.cos(), (2. * t).sin()];
    let s = Sampling::param(f, 0., 2. * PI).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;

    let f = |x: f64| (- x.powi(2)).exp();
    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
    Ok(())
}
source§

impl Sampling

source

pub fn latex(&self) -> LaTeX<'_>

Write the sampling self using PGF/TikZ commands.

Examples found in repository?
examples/clip.rs (line 11)
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() -> Result<(), Box<dyn Error>> {
    let s = cs::Sampling::from_iter(
        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
    s.write(&mut File::create("/tmp/clip0.dat")?)?;
    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
                                      ymin: 0., ymax: 1. });
    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;

    Ok(())
}
More examples
Hide additional examples
examples/latex_speed.rs (line 17)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() -> Result<(), Box<dyn Error>> {
    let path = "/tmp/latex_speed.tex";
    let mut fh = File::create(path)?;
    write!(fh, "\\documentclass[12pt,a4paper]{{article}}\n\
                \\usepackage{{tikz}}\n\
                \\begin{{document}}\n\
                \\begin{{tikzpicture}}\n")?;
    let n = 40_000;
    println!("Run \"latex {}\" measure LaTeX speed with {} points.\n",
             path, n);
    let s = Sampling::uniform(f64::sin, -6., 6.).n(n).build();
    s.latex().write(&mut fh)?;
    write!(fh, "\\end{{tikzpicture}}\n\
                \\end{{document}}")?;
    Ok(())
}
examples/arrows.rs (line 11)
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
fn main() -> Result<(), Box<dyn Error>> {
    let s = Sampling::from_iter([[0., 0.], [1., 1.], [NAN, NAN],
                                 [1., 1.], [3., -1.]]);
    s.latex().arrow_pos(0.3).write(&mut File::create("/tmp/arrow0.tex")?)?;

    let s = Sampling::uniform(|x| -0.7 * (x - 1.).powi(2), 0., 2.5).build();
    s.latex().arrow_pos(0.6).write(&mut File::create("/tmp/arrow1.tex")?)?;


    File::create("/tmp/arrows.tex")?.write_all(
        r"\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[x=3cm, y=3cm]
  \draw[->] (-1.2, 0) -- (3.2, 0);
  \draw[->] (0, -1.2) -- (0, 1.7);
  \foreach \x in {-1, -0.5, 0.5, 1, 1.5,..., 3}{
    \draw (\x, 3pt) -- (\x, -3pt) node[below]{$\scriptstyle \x$};
  }
  \foreach \y in {-1, -0.5, 0.5, 1, 1.5}{
    \draw (3pt, \y) -- (-3pt, \y) node[left]{$\scriptstyle \y$};
  }
  \begin{scope}[color=blue, line width=1pt]
    \input{arrow0.tex}
  \end{scope}
  \begin{scope}[color=orange, line width=1pt]
    \input{arrow1.tex}
  \end{scope}
\end{tikzpicture}
\end{document}".as_bytes())?;

    std::env::set_current_dir("/tmp")?;
    Command::new("pdflatex")
        .args(["-interaction=batchmode", "arrows.tex"]).output()?;
    Ok(())
}
source

pub fn write(&self, f: &mut impl Write) -> Result<(), Error>

Write the sampling to f in a tabular form: each point is written as “x y” on a single line (in scientific notation). If the path is interrupted, a blank line is printed. This format is compatible with Gnuplot.

Examples found in repository?
examples/nice.rs (line 10)
7
8
9
10
11
12
13
14
15
16
fn main() -> Result<(), Box<dyn Error>> {
    let f = |t: f64| [t.cos(), (2. * t).sin()];
    let s = Sampling::param(f, 0., 2. * PI).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;

    let f = |x: f64| (- x.powi(2)).exp();
    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
    Ok(())
}
More examples
Hide additional examples
examples/clip.rs (line 10)
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() -> Result<(), Box<dyn Error>> {
    let s = cs::Sampling::from_iter(
        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
    s.write(&mut File::create("/tmp/clip0.dat")?)?;
    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
                                      ymin: 0., ymax: 1. });
    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;

    Ok(())
}
examples/sin_inv_x.rs (line 17)
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
fn main() -> R {
    let mut fh = File::create("/tmp/sin_inv_x.gp")?;
    write!(fh, "set terminal pngcairo\n\
                set grid\n")?;
    let mut d = 0;
    let mut save = |s: &Sampling, n, title| -> R {
        d += 1;
        let fname = format!("/tmp/sin_inv_x{}.dat", d);
        s.write(&mut File::create(&fname)?)?;
        write!(fh, "set output \"sin_inv_x{}.png\"\n\
                    plot '{}' with l lt 1 lw 2 title \"{} ({} pts)\"\n",
               d, &fname, title, n)?;
        write!(fh, "set output \"sin_inv_x{}_p.png\"\n\
                    plot '{}' with l lt 5 lw 2 title \"{}\", \
                    '{}' with p lt 3 pt 5 ps 0.2 title \"points ({})\"\n",
               d, &fname, title, &fname, n)?;
        Ok(())
    };

    let f = |x: f64| x * (1. / x).sin();
    let s = Sampling::fun(f, -0.4, 0.4).n(227).build();
    save(&s, 227, "x sin(1/x)")?;
    let s = Sampling::fun(f, -0.4, 0.4).n(389).build();
    save(&s, 389, "x sin(1/x)")?;

    let s = Sampling::fun(|x: f64| (1. / x).sin(), -0.4, 0.4).n(391).build();
    save(&s, 391, "sin(1/x)")?;

    Ok(())
}

Trait Implementations§

source§

impl Clone for Sampling

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Display for Sampling

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Display the sampling in a tabular form: each point is written as “x y” on a single line (in scientific notation). If the path is interrupted, a blank line is printed. This format is compatible with Gnuplot.

source§

impl FromIterator<[f64; 2]> for Sampling

source§

fn from_iter<T>(points: T) -> Selfwhere T: IntoIterator<Item = [f64; 2]>,

Return an sampling from the points. Points with non-finite coordinates are interpreted as cuts.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.