Struct Sampling

Source
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)
34fn main() {
35    let mut b = false;
36    for n in 10 .. 5_000 {
37        let s = Sampling::fun(|x| x.sin(), 0., 10.)
38            .n(n).build();
39        b &= s.is_empty();
40    }
41    println!("{b}")
42}
Source

pub fn iter(&self) -> SamplingIter<'_>

Returns an iterator 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 iter_mut(&mut self) -> SamplingIterMut<'_>

Returns an iterator that allows to modify the points and cuts of the path. Unlike [iter], this iterates on all the nodes even if several cuts (i.e., node with a non finite coordinate) follow each other.

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)
6fn main() -> Result<(), Box<dyn Error>> {
7    let s = cs::Sampling::from_iter(
8        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
9         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
10    s.write(&mut File::create("/tmp/clip0.dat")?)?;
11    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
12    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
13                                      ymin: 0., ymax: 1. });
14    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
15    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;
16
17    Ok(())
18}
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)
6fn main() -> Result<(), Box<dyn Error>> {
7    let path = "/tmp/latex_speed.tex";
8    let mut fh = File::create(path)?;
9    write!(fh, "\\documentclass[12pt,a4paper]{{article}}\n\
10                \\usepackage{{tikz}}\n\
11                \\begin{{document}}\n\
12                \\begin{{tikzpicture}}\n")?;
13    let n = 40_000;
14    println!("Run \"latex {}\" measure LaTeX speed with {} points.\n",
15             path, n);
16    let s = Sampling::uniform(f64::sin, -6., 6.).n(n).build();
17    s.latex().write(&mut fh)?;
18    write!(fh, "\\end{{tikzpicture}}\n\
19                \\end{{document}}")?;
20    Ok(())
21}
More examples
Hide additional examples
examples/arrows.rs (line 13)
8fn main() -> Result<(), Box<dyn Error>> {
9    let s = Sampling::from_iter([[0., 0.], [1., 1.], [NAN, NAN],
10                                 [1., 1.], [3., -1.]]);
11    s.latex().arrow_pos(0.3).write(&mut File::create("/tmp/arrow0.tex")?)?;
12
13    let s = Sampling::uniform(|x| -0.7 * (x - 1.).powi(2), 0., 2.5).build();
14    s.latex().arrow_pos(0.6).write(&mut File::create("/tmp/arrow1.tex")?)?;
15
16
17    File::create("/tmp/arrows.tex")?.write_all(
18        r"\documentclass{article}
19\usepackage{tikz}
20\begin{document}
21\begin{tikzpicture}[x=3cm, y=3cm]
22  \draw[->] (-1.2, 0) -- (3.2, 0);
23  \draw[->] (0, -1.2) -- (0, 1.7);
24  \foreach \x in {-1, -0.5, 0.5, 1, 1.5,..., 3}{
25    \draw (\x, 3pt) -- (\x, -3pt) node[below]{$\scriptstyle \x$};
26  }
27  \foreach \y in {-1, -0.5, 0.5, 1, 1.5}{
28    \draw (3pt, \y) -- (-3pt, \y) node[left]{$\scriptstyle \y$};
29  }
30  \begin{scope}[color=blue, line width=1pt]
31    \input{arrow0.tex}
32  \end{scope}
33  \begin{scope}[color=orange, line width=1pt]
34    \input{arrow1.tex}
35  \end{scope}
36\end{tikzpicture}
37\end{document}".as_bytes())?;
38
39    std::env::set_current_dir("/tmp")?;
40    Command::new("pdflatex")
41        .args(["-interaction=batchmode", "arrows.tex"]).output()?;
42    Ok(())
43}
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)
34fn main() {
35    let mut b = false;
36    for n in 10 .. 5_000 {
37        let s = Sampling::fun(|x| x.sin(), 0., 10.)
38            .n(n).build();
39        b &= s.is_empty();
40    }
41    println!("{b}")
42}
More examples
Hide additional examples
examples/nice.rs (line 13)
7fn main() -> Result<(), Box<dyn Error>> {
8    let f = |t: f64| [t.cos(), (2. * t).sin()];
9    let s = Sampling::param(f, 0., 2. * PI).build();
10    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;
11
12    let f = |x: f64| (- x.powi(2)).exp();
13    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
14    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
15    Ok(())
16}
examples/sin_inv_x.rs (line 29)
9fn main() -> R {
10    let mut fh = File::create("/tmp/sin_inv_x.gp")?;
11    write!(fh, "set terminal pngcairo\n\
12                set grid\n")?;
13    let mut d = 0;
14    let mut save = |s: &Sampling, n, title| -> R {
15        d += 1;
16        let fname = format!("/tmp/sin_inv_x{}.dat", d);
17        s.write(&mut File::create(&fname)?)?;
18        write!(fh, "set output \"sin_inv_x{}.png\"\n\
19                    plot '{}' with l lt 1 lw 2 title \"{} ({} pts)\"\n",
20               d, &fname, title, n)?;
21        write!(fh, "set output \"sin_inv_x{}_p.png\"\n\
22                    plot '{}' with l lt 5 lw 2 title \"{}\", \
23                    '{}' with p lt 3 pt 5 ps 0.2 title \"points ({})\"\n",
24               d, &fname, title, &fname, n)?;
25        Ok(())
26    };
27
28    let f = |x: f64| x * (1. / x).sin();
29    let s = Sampling::fun(f, -0.4, 0.4).n(227).build();
30    save(&s, 227, "x sin(1/x)")?;
31    let s = Sampling::fun(f, -0.4, 0.4).n(389).build();
32    save(&s, 389, "x sin(1/x)")?;
33
34    let s = Sampling::fun(|x: f64| (1. / x).sin(), -0.4, 0.4).n(391).build();
35    save(&s, 391, "sin(1/x)")?;
36
37    Ok(())
38}
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)
7fn main() -> Result<(), Box<dyn Error>> {
8    let f = |t: f64| [t.cos(), (2. * t).sin()];
9    let s = Sampling::param(f, 0., 2. * PI).build();
10    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;
11
12    let f = |x: f64| (- x.powi(2)).exp();
13    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
14    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
15    Ok(())
16}
Source§

impl Sampling

§Output

Source

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

Write the sampling self using PGF/TikZ commands.

Examples found in repository?
examples/clip.rs (line 11)
6fn main() -> Result<(), Box<dyn Error>> {
7    let s = cs::Sampling::from_iter(
8        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
9         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
10    s.write(&mut File::create("/tmp/clip0.dat")?)?;
11    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
12    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
13                                      ymin: 0., ymax: 1. });
14    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
15    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;
16
17    Ok(())
18}
More examples
Hide additional examples
examples/latex_speed.rs (line 17)
6fn main() -> Result<(), Box<dyn Error>> {
7    let path = "/tmp/latex_speed.tex";
8    let mut fh = File::create(path)?;
9    write!(fh, "\\documentclass[12pt,a4paper]{{article}}\n\
10                \\usepackage{{tikz}}\n\
11                \\begin{{document}}\n\
12                \\begin{{tikzpicture}}\n")?;
13    let n = 40_000;
14    println!("Run \"latex {}\" measure LaTeX speed with {} points.\n",
15             path, n);
16    let s = Sampling::uniform(f64::sin, -6., 6.).n(n).build();
17    s.latex().write(&mut fh)?;
18    write!(fh, "\\end{{tikzpicture}}\n\
19                \\end{{document}}")?;
20    Ok(())
21}
examples/arrows.rs (line 11)
8fn main() -> Result<(), Box<dyn Error>> {
9    let s = Sampling::from_iter([[0., 0.], [1., 1.], [NAN, NAN],
10                                 [1., 1.], [3., -1.]]);
11    s.latex().arrow_pos(0.3).write(&mut File::create("/tmp/arrow0.tex")?)?;
12
13    let s = Sampling::uniform(|x| -0.7 * (x - 1.).powi(2), 0., 2.5).build();
14    s.latex().arrow_pos(0.6).write(&mut File::create("/tmp/arrow1.tex")?)?;
15
16
17    File::create("/tmp/arrows.tex")?.write_all(
18        r"\documentclass{article}
19\usepackage{tikz}
20\begin{document}
21\begin{tikzpicture}[x=3cm, y=3cm]
22  \draw[->] (-1.2, 0) -- (3.2, 0);
23  \draw[->] (0, -1.2) -- (0, 1.7);
24  \foreach \x in {-1, -0.5, 0.5, 1, 1.5,..., 3}{
25    \draw (\x, 3pt) -- (\x, -3pt) node[below]{$\scriptstyle \x$};
26  }
27  \foreach \y in {-1, -0.5, 0.5, 1, 1.5}{
28    \draw (3pt, \y) -- (-3pt, \y) node[left]{$\scriptstyle \y$};
29  }
30  \begin{scope}[color=blue, line width=1pt]
31    \input{arrow0.tex}
32  \end{scope}
33  \begin{scope}[color=orange, line width=1pt]
34    \input{arrow1.tex}
35  \end{scope}
36\end{tikzpicture}
37\end{document}".as_bytes())?;
38
39    std::env::set_current_dir("/tmp")?;
40    Command::new("pdflatex")
41        .args(["-interaction=batchmode", "arrows.tex"]).output()?;
42    Ok(())
43}
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)
7fn main() -> Result<(), Box<dyn Error>> {
8    let f = |t: f64| [t.cos(), (2. * t).sin()];
9    let s = Sampling::param(f, 0., 2. * PI).build();
10    s.write(&mut BufWriter::new(File::create("/tmp/nice1.dat")?))?;
11
12    let f = |x: f64| (- x.powi(2)).exp();
13    let s = Sampling::fun(f, -2.5, 2.5).n(53).build();
14    s.write(&mut BufWriter::new(File::create("/tmp/nice2.dat")?))?;
15    Ok(())
16}
More examples
Hide additional examples
examples/clip.rs (line 10)
6fn main() -> Result<(), Box<dyn Error>> {
7    let s = cs::Sampling::from_iter(
8        [[0., -0.5], [1.5, 1.], [0.2, 0.5], [0.3, 1.5], [1., 0.6],
9         [NAN, NAN], [-0.5, 0.5], [-1., 0.], [0.5, 0.5]]);
10    s.write(&mut File::create("/tmp/clip0.dat")?)?;
11    s.latex().write(&mut File::create("/tmp/clip0.tex")?)?;
12    let s1 = s.clip(cs::BoundingBox { xmin: 0., xmax: 1.,
13                                      ymin: 0., ymax: 1. });
14    s1.write(&mut File::create("/tmp/clip1.dat")?)?;
15    s1.latex().write(&mut File::create("/tmp/clip1.tex")?)?;
16
17    Ok(())
18}
examples/sin_inv_x.rs (line 17)
9fn main() -> R {
10    let mut fh = File::create("/tmp/sin_inv_x.gp")?;
11    write!(fh, "set terminal pngcairo\n\
12                set grid\n")?;
13    let mut d = 0;
14    let mut save = |s: &Sampling, n, title| -> R {
15        d += 1;
16        let fname = format!("/tmp/sin_inv_x{}.dat", d);
17        s.write(&mut File::create(&fname)?)?;
18        write!(fh, "set output \"sin_inv_x{}.png\"\n\
19                    plot '{}' with l lt 1 lw 2 title \"{} ({} pts)\"\n",
20               d, &fname, title, n)?;
21        write!(fh, "set output \"sin_inv_x{}_p.png\"\n\
22                    plot '{}' with l lt 5 lw 2 title \"{}\", \
23                    '{}' with p lt 3 pt 5 ps 0.2 title \"points ({})\"\n",
24               d, &fname, title, &fname, n)?;
25        Ok(())
26    };
27
28    let f = |x: f64| x * (1. / x).sin();
29    let s = Sampling::fun(f, -0.4, 0.4).n(227).build();
30    save(&s, 227, "x sin(1/x)")?;
31    let s = Sampling::fun(f, -0.4, 0.4).n(389).build();
32    save(&s, 389, "x sin(1/x)")?;
33
34    let s = Sampling::fun(|x: f64| (1. / x).sin(), -0.4, 0.4).n(391).build();
35    save(&s, 391, "sin(1/x)")?;
36
37    Ok(())
38}

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) -> Self
where 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 T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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 T
where 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 T
where T: Clone,

Source§

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 T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

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

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.