enterpolation 0.3.0

A library for creating and computing interpolations, extrapolations and smoothing of generic data points.
Documentation
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
//! Basis spline curves.
//!
//! BSpline support all flavours or B-Splines, such as uniform (equidistant) and non-uniform B-Splines
//! as well as the most generalized version: NURBS (Non-Uniform Rational B-SPlines).
//! The easist way to create a bspline is by using the builder pattern of [`BSplineBuilder`].
//!
//! ```rust
//! # use std::error::Error;
//! # use enterpolation::{bspline::{BSpline, BSplineError}, Signal, Curve};
//! # use assert_float_eq::{afe_is_f64_near, afe_near_error_msg, assert_f64_near};
//! #
//! # fn main() -> Result<(), BSplineError> {
//! let bspline = BSpline::builder()
//!                 .clamped()
//!                 .elements([0.0,5.0,3.0,10.0,7.0])
//!                 .equidistant::<f64>()
//!                 .degree(3)
//!                 .normalized()
//!                 .constant::<4>()
//!                 .build()?;
//! let results = [0.0,2.346,3.648,4.302,4.704,5.25,6.2,7.27,8.04,8.09,7.0];
//! for (value,result) in bspline.take(results.len()).zip(results.iter().copied()){
//!     assert_f64_near!(value, result);
//! }
//! #
//! #     Ok(())
//! # }
//! ```
//!
//! BSplines can be seen as many bezier curves put together. They have most properties of bezier curves
//! but changing an element in a bspline only affects a local area of the curve,
//! not the whole curve, like it is in bezier curves.
//! BSplines allow you to define curves with a lot of control points without increasing the degree of the curve.
//!
//! [`BSplineBuilder`]: BSplineBuilder
mod adaptors;
mod builder;
mod error;

pub use adaptors::{BorderBuffer, BorderDeletion};
pub use builder::{BSplineBuilder, BSplineDirector};
pub use error::{
    BSplineError, IncongruousElementsDegree, IncongruousElementsKnots, InvalidDegree, NotSorted,
    TooFewElements, TooSmallWorkspace,
};

use crate::builder::Unknown;
use crate::{Chain, Curve, Signal, SortedChain, Space};
use builder::Open;
use num_traits::real::Real;
use topology_traits::Merge;

use core::fmt::Debug;

/// BSpline curve.
///
/// See [bspline module] for more information.
///
/// [bspline module]: self
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct BSpline<K, E, S> {
    elements: E,
    knots: K,
    space: S,
    degree: usize,
}

impl BSpline<Unknown, Unknown, Unknown> {
    /// Get a builder for bsplines.
    ///
    /// The builder takes:
    /// - a mode, either [`open()`], which is default, [`clamped()`] or [`legacy()`]
    /// - elements with [`elements()`] or [`elements_with_weights()`]
    /// - knots with [`knots()`] or [`equidistant()`]
    /// - the kind of workspace to use with [`dynamic()`], [`constant()`] or [`workspace()`]
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::error::Error;
    /// # use enterpolation::{bspline::{BSpline, BSplineError}, Signal, Curve};
    /// # use assert_float_eq::{afe_is_f64_near, afe_near_error_msg, assert_f64_near};
    /// #
    /// # fn main() -> Result<(), BSplineError> {
    /// let bez = BSpline::builder()
    ///     .clamped()
    ///     .elements([20.0,100.0,0.0,200.0])
    ///     .equidistant::<f64>()
    ///     .degree(3)
    ///     .normalized()
    ///     .constant::<4>()    // degree + 1
    ///     .build()?;
    /// let mut iter = bez.take(5);
    /// let expected = [20.0,53.75,65.0,98.75,200.0];
    /// for i in 0..=4 {
    ///     let val = iter.next().unwrap();
    ///     assert_f64_near!(val, expected[i]);
    /// }
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`open()`]: BSplineBuilder::open()
    /// [`clamped()`]: BSplineBuilder::clamped()
    /// [`legacy()`]: BSplineBuilder::legacy()
    /// [`elements()`]: BSplineBuilder::elements()
    /// [`elements_with_weights()`]: BSplineBuilder::elements_with_weights()
    /// [`knots()`]: BSplineBuilder::knots()
    /// [`equidistant()`]: BSplineBuilder::equidistant()
    /// [`dynamic()`]: BSplineBuilder::dynamic()
    /// [`constant()`]: BSplineBuilder::constant()
    /// [`workspace()`]: BSplineBuilder::workspace()
    pub fn builder() -> BSplineBuilder<Unknown, Unknown, Unknown, Unknown, Open> {
        BSplineBuilder::new()
    }
}

impl<K, E, S> BSpline<K, E, S>
where
    E: Chain,
    S: Space<E::Output>,
{
    /// Creates a workspace and copies degree+1 elements into it, starting from given index.
    fn workspace(&self, index: usize) -> impl AsMut<[E::Output]> {
        let mut workspace = self.space.workspace();
        let mut_workspace = workspace.as_mut();
        for (i, val) in mut_workspace.iter_mut().enumerate().take(self.degree + 1) {
            *val = self.elements.eval(index - self.degree + i);
        }
        workspace
    }
}

impl<K, E, S, R> Signal<R> for BSpline<K, E, S>
where
    E: Chain,
    S: Space<E::Output>,
    E::Output: Merge<R> + Copy,
    R: Real + Debug,
    K: SortedChain<Output = R>,
{
    type Output = E::Output;
    fn eval(&self, scalar: R) -> E::Output {
        // we do NOT calculaute a possible multiplicity of the scalar, as we assume
        // the chance of hitting a knot is almost zero.
        let lower_cut = self.degree;
        let upper_cut = self.knots.len() - self.degree;
        // The strict_upper_bound is easier to calculate and behaves nicely on the edges of the array.
        // Such it is more ergonomic than using upper_border.
        let index = self
            .knots
            .strict_upper_bound_clamped(scalar, lower_cut, upper_cut);

        //copy elements into workspace
        let mut workspace = self.workspace(index);
        let elements = workspace.as_mut();

        for r in 1..=self.degree {
            for j in 0..=(self.degree - r) {
                let i = j + r + index - self.degree;
                let factor = (scalar - self.knots.eval(i - 1))
                    / (self.knots.eval(i + self.degree - r) - self.knots.eval(i - 1));
                elements[j] = elements[j].merge(elements[j + 1], factor);
            }
        }
        elements[0]
    }
}

impl<K, E, S, R> Curve<R> for BSpline<K, E, S>
where
    E: Chain,
    S: Space<E::Output>,
    E::Output: Merge<R> + Copy,
    R: Real + Debug,
    K: SortedChain<Output = R>,
{
    fn domain(&self) -> [R; 2] {
        [
            self.knots.eval(self.degree - 1),
            self.knots.eval(self.knots.len() - self.degree),
        ]
    }
}

impl<K, E, S> BSpline<K, E, S>
where
    E: Chain,
    K: SortedChain,
    S: Space<E::Output>,
{
    /// Creates a bspline curve of elements and knots given.
    ///
    /// The resulting degree of the curve is `elements.len() - knots.len() +1`.
    /// The domain for the curve with degree `p` is `knots[p-1]` and `knots[knots.len() - p -2]`.
    ///
    /// The knots have to be sorted.
    ///
    /// # Errors
    ///
    /// [`TooFewElements`] if there are less than two elements.
    /// [`InvalidDegree`] if degree is not at least 1 and at most the number of elements - 1.
    /// [`TooSmallWorkspace`] if the workspace is not bigger than the degree of the curve.
    /// [`IncongruousElementsKnots`] either if the amount of knots is less than the amount of elements
    /// or if the anoumt of knots is more than double the amount of elements.
    ///
    /// [`TooFewElements`]: BSplineError
    /// [`InvalidDegree`]: BSplineError
    /// [`TooSmallWorkspace`]: BSplineError
    pub fn new(elements: E, knots: K, space: S) -> Result<Self, BSplineError> {
        //Test if we have at least two elements
        if elements.len() < 2 {
            return Err(TooFewElements::new(elements.len()).into());
        }
        // Test if degree is strict positive
        if knots.len() < elements.len() {
            return Err(IncongruousElementsKnots::open(elements.len(), knots.len()).into());
        }
        // Test if we have enough elements for the degree
        if elements.len() <= knots.len() - elements.len() + 1 {
            return Err(IncongruousElementsKnots::open(elements.len(), knots.len()).into());
        }
        let degree = knots.len() - elements.len() + 1;
        if space.len() <= degree {
            return Err(TooSmallWorkspace::new(space.len(), degree).into());
        }
        Ok(BSpline {
            elements,
            knots,
            space,
            degree,
        })
    }
}

impl<K, E, S> BSpline<K, E, S>
where
    E: Chain,
    K: SortedChain,
    S: Space<E::Output>,
{
    /// Creates a bspline curve of elements and knots given.
    ///
    /// The resulting degree of the curve is `elements.len() - knots.len() + 1`.
    /// The domain for the curve with degree `p` is `knots[p-1]` and `knots[knots.len() - p -2]`.
    /// The knots have to be sorted.
    ///
    /// # Panics
    ///
    /// The degree has to be at least 1, otherwise the library may panic at any time.
    pub fn new_unchecked(elements: E, knots: K, space: S) -> Self {
        let degree = knots.len() - elements.len() + 1;
        BSpline {
            elements,
            knots,
            space,
            degree,
        }
    }
}

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

    #[test]
    fn linear_bspline() {
        let expect = [
            (-1.0, -1.0),
            (0.0, 0.0),
            (0.2, 0.2),
            (0.4, 0.4),
            (0.6, 0.6),
            (0.8, 0.8),
            (1.0, 1.0),
            (2.0, 2.0),
        ];
        let points = [0.0f32, 1.0];
        let knots = [0.0f32, 1.0];
        let spline = BSpline::builder()
            .elements(points)
            .knots(knots)
            .constant::<2>()
            .build()
            .unwrap();
        for (input, output) in expect {
            assert_f32_near!(spline.eval(input), output);
        }
    }

    #[test]
    fn quadratic_bspline() {
        let expect = [
            (0.0, 0.0),
            (0.5, 0.125),
            (1.0, 0.5),
            (1.4, 0.74),
            (1.5, 0.75),
            (1.6, 0.74),
            (2.0, 0.5),
            (2.5, 0.125),
            (3.0, 0.0),
        ];
        let points = [0.0f32, 0.0, 1.0, 0.0, 0.0];
        let knots = [0.0f32, 0.0, 1.0, 2.0, 3.0, 3.0];
        let spline = BSpline::builder()
            .elements(points)
            .knots(knots)
            .constant::<3>()
            .build()
            .unwrap();
        for (input, output) in expect {
            assert_f32_near!(spline.eval(input), output);
        }
    }

    #[test]
    fn cubic_bspline() {
        let expect = [
            (-2.0, 0.0),
            (-1.5, 0.125),
            (-1.0, 1.0),
            (-0.6, 2.488),
            (0.0, 4.0),
            (0.5, 2.875),
            (1.5, 0.12500001),
            (2.0, 0.0),
        ];
        let points = [0.0f32, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0];
        let knots = [-2.0f32, -2.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.0, 2.0];
        let spline = BSpline::builder()
            .elements(points)
            .knots(knots)
            .constant::<4>()
            .build()
            .unwrap();
        for (input, output) in expect {
            assert_f32_near!(spline.eval(input), output);
        }
    }

    #[test]
    fn quartic_bspline() {
        let expect = [
            (0.0, 0.0),
            (0.4, 0.0010666668),
            (1.0, 0.041666668),
            (1.5, 0.19791667),
            (2.0, 0.4583333),
            (2.5, 0.5989583),
            (3.0, 0.4583333),
            (3.2, 0.35206667),
            (4.1, 0.02733751),
            (4.5, 0.002604167),
            (5.0, 0.0),
        ];
        let points = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0];
        let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0];
        let spline = BSpline::builder()
            .elements(points)
            .knots(knots)
            .constant::<5>()
            .build()
            .unwrap();
        for (input, output) in expect {
            assert_f32_near!(spline.eval(input), output);
        }
    }

    #[test]
    fn quartic_bspline_f64() {
        let expect = [
            (0.0, 0.0),
            (0.4, 0.001066666666666667),
            (1.0, 0.041666666666666664),
            (1.5, 0.19791666666666666),
            (2.0, 0.45833333333333337),
            (2.5, 0.5989583333333334),
            (3.0, 0.4583333333333333),
            (3.2, 0.3520666666666666),
            (4.1, 0.027337500000000046),
            (4.5, 0.002604166666666666),
            (5.0, 0.0),
        ];
        let points = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0];
        let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0];
        let spline = BSpline::builder()
            .elements(points)
            .knots(knots)
            .constant::<5>()
            .build()
            .unwrap();
        for (input, output) in expect {
            assert_f64_near!(spline.eval(input), output);
        }
    }

    #[test]
    fn partial_eq() {
        let spline = BSpline::builder()
            .elements([0.0f32, 1.0])
            .knots([0.0f32, 1.0])
            .constant::<2>()
            .build()
            .unwrap();
        let spline2 = BSpline::builder()
            .elements([0.0f32, 1.0])
            .knots([0.0f32, 1.0])
            .constant::<2>()
            .build()
            .unwrap();
        assert_eq!(spline, spline2);
    }
}