ripple 0.2.1

General-purpose DSP data structures and algorithms
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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use nalgebra::*;
use nalgebra::storage::*;
use std::ops::{Index, Mul, Add, AddAssign, MulAssign, Div, SubAssign};
use simba::scalar::SubsetOf;
use simba::scalar::SupersetOf;
use std::fmt::Debug;
use std::fmt::{self, Display};
use serde::Deserialize;
use std::convert::TryFrom;
use serde::Deserializer;
use std::iter::{FromIterator, Extend, IntoIterator};
use std::cmp::PartialEq;
use std::ops::Range;

pub mod sampling;

/// Owned time Signal data structure.
#[derive(Debug, Clone)]
pub struct Signal<N>
where
    N : Scalar
{
    pub(crate) buf : DVector<N>
}

impl<'de, N> Deserialize<'de> for Signal<N>
where
    N : Scalar + Deserialize<'de>
{

    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>
    {
        let v : Vec<N> = Deserialize::deserialize(deserializer)?;
        Ok(Signal { buf : DVector::from_vec(v) })
    }

}

pub enum Direction {
    Advance,
    Delay
}

impl<'a, N> Signal<N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd + From<f32>,
    f64 : SubsetOf<N>
{

    pub fn as_slice(&self) -> &[N] {
        self.as_ref()
    }

    pub fn len(&self) -> usize {
        self.buf.nrows()
    }

    pub fn delay(mut self, n : usize) -> Self {
        self.circ_shift(n, Direction::Delay)
    }


    pub fn advance(mut self, n : usize) -> Self {
        self.circ_shift(n, Direction::Advance)
    }

    /// Advance : Push Signal to origin; Delay : pulls Signal away from origin.
    fn circ_shift(mut self, n : usize, dir : Direction) -> Self {
        let mut tmp = Vec::new();
        let sz = self.buf.nrows();
        let sz_compl = sz - n;
        let tmp_sz = match dir {
            Direction::Advance => n,
            Direction::Delay => sz - n
        };
        tmp.extend((0..tmp_sz).map(|_| N::from(0. as f32) ));

        match dir {
            Direction::Advance => {

                // Saves the beginning part that will be written over
                tmp.copy_from_slice(&self.buf.as_slice()[0..n]);

                // Resolve the actual shift
                self.buf.as_mut_slice().copy_within(n..sz, 0);

                // Copied the saved beginning to the end
                self.buf.as_mut_slice()[sz-n..].copy_from_slice(&tmp[..]);
            },
            Direction::Delay => {
                unimplemented!()
            }
        }
        self
    }

    pub fn new_constant(n : usize, value : N) -> Self {
        Self{ buf : DVector::from_element(n, value) }
    }

    pub fn full_epoch(&'a self) -> Epoch<'a, N> {
        Epoch{ slice : self.buf.rows(0, self.buf.nrows()), offset : 0 }
    }

    pub fn full_epoch_mut(&'a mut self) -> EpochMut<'a, N> {
        EpochMut{ slice : self.buf.rows_mut(0, self.buf.nrows()), offset : 0 }
    }

    pub fn epoch(&'a self, start : usize, len : usize) -> Epoch<'a, N> {
        assert!(start + len <= self.buf.nrows());
        Epoch{ slice : self.buf.rows(start, len), offset : start }
    }

    pub fn epoch_mut(&'a mut self, start : usize, len : usize) -> EpochMut<'a, N> {
        assert!(start + len <= self.buf.nrows());
        EpochMut{ slice : self.buf.rows_mut(start, len), offset : start }
    }

    pub fn iter(&self) -> impl Iterator<Item=&N> {
        self.buf.iter()
    }

    pub fn iter_mut(&'a mut self) -> impl Iterator<Item=&'a mut N> {
        self.buf.iter_mut()
    }

    pub fn mean(&mut self) -> N {
        self.full_epoch_mut().mean()
    }

    pub fn offset_by(&mut self, scalar : N) {
        self.full_epoch_mut().offset_by(scalar)
    }

    pub fn downsample_aliased(&mut self, src : &Epoch<'_, N>) {
        let step = src.slice.len() / self.buf.nrows();
        if step == 1 {
            sampling::slices::convert_slice(
                &src.slice.as_slice(),
                self.buf.as_mut_slice()
            );
        } else {
            let ncols = src.slice.ncols();
            assert!(src.slice.len() / step == self.buf.nrows(), "Dimension mismatch");
            sampling::slices::subsample_convert(
                src.slice.as_slice(),
                self.buf.as_mut_slice(),
                ncols,
                step,
                false
            );
        }
    }

    // Iterate over epochs of same size.
    // pub fn epochs(&self, size : usize) -> impl Iterator<Item=Epoch<'_, N>> {
    //    unimplemented!()
    // }

    /*pub fn downsample_from(&mut self, other : &Self) {
        unimplemented!()
    }

    pub fn downsample_into(&self, other : &mut Self) {
        unimplemented!()
    }

    pub fn upsample_from(&mut self, other : &Self) {
        unimplemented!()
    }

    pub fn upsample_into(&self, other : &mut Self) {
        unimplemented!()
    }

    // Move this to method of Pyramid.
    pub fn threshold(&self, thr : &Threshold) -> SparseSignal<'_, N> {
        unimplemented!()
    }*/
}

impl<'a, N> From<&'a [N]> for Epoch<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{

    fn from(slice : &'a [N]) -> Self {
        Self { slice : DVectorSlice::from(slice), offset : 0 }
    }

}

impl<'a, N> From<DVectorSlice<'a, N>> for Epoch<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{

    fn from(slice : DVectorSlice<'a, N>) -> Self {
        Self { slice, offset : 0 }
    }

}

impl<N> AsRef<[N]> for Epoch<'_, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{
    fn as_ref(&self) -> &[N] {
        self.slice.as_slice()
    }
}

impl<N> FromIterator<N> for Signal<N>
where
    N : Scalar
{

    fn from_iter<I : IntoIterator<Item=N>>(iter: I) -> Self {
        let buf = DVector::from(Vec::from_iter(iter));
        Self { buf }
    }

}

impl<N> Extend<N> for Signal<N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd + From<f32>,
    f64 : SubsetOf<N>
{

    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = N>
    {
        let mut v = self.buf.data.as_vec().clone();
        v.extend(iter);
        self.buf = DVector::from_vec(v);
    }

}


impl<N> IntoIterator for Signal<N>
where
    N : Scalar
{
    type Item = N;

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(mut self) -> Self::IntoIter {
        let data : Vec<_> = self.buf.data.into();
        data.into_iter()
    }

}

/*impl<N> Index<(usize, usize)> for Image<N>
where
    N : Scalar
{

    type Output = N;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        &self.buf[index]
    }
}

impl<N> IndexMut<(usize, usize)> for Image<N>
where
    N : Scalar
{

    fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
        &mut self.buf[index]
    }

}*/

/// Borrowed subset of a Signal.
#[derive(Debug, Clone)]
pub struct Epoch<'a, N>
where
    N : Scalar
{
    offset : usize,
    slice : DVectorSlice<'a, N>
}



#[derive(Debug)]
pub struct EpochMut<'a, N>
where
    N : Scalar
{
    offset : usize,
    slice : DVectorSliceMut<'a, N>
}

impl<'a, N> EpochMut<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{

    pub fn sum(&self) -> N {
        self.slice.sum()
    }

    pub fn mean(&self) -> N {
        self.slice.mean()
    }

    pub fn max(&self) -> N {
        self.slice.max()
    }

    pub fn min(&self) -> N {
        self.slice.min()
    }

    pub fn len(&self) -> usize {
        self.slice.len()
    }

    pub fn component_add(&mut self, other : &Epoch<N>) {
        self.slice.add_assign(&other.slice);
    }

    pub fn component_sub(&mut self, other : &Epoch<N>) {
        self.slice.sub_assign(&other.slice);
        //unimplemented!()
    }

    pub fn component_scale(&mut self, other : &Epoch<N>) {
        self.slice.component_mul_assign(&other.slice);
    }

    pub fn offset_by(&mut self, scalar : N) {
        self.slice.add_scalar_mut(scalar);
    }

    pub fn scale_by(&mut self, scalar : N) {
        // self.slice.scale_mut(scalar); // Only available for owned versions
        self.slice.iter_mut().for_each(|n| *n *= scalar );
    }

    pub fn iter_mut(&'a mut self) -> impl Iterator<Item=&'a mut N> {
        self.slice.iter_mut()
    }

    pub fn offset(&self) -> usize {
        self.offset
    }

}

impl<'a, N> Epoch<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{

    pub fn max(&self) -> N {
        self.slice.max()
    }

    pub fn min(&self) -> N {
        self.slice.min()
    }

    pub fn sum(&self) -> N {
        self.slice.sum()
    }

    pub fn mean(&self) -> N {
        self.slice.mean()
    }

    pub fn variance(&self) -> N {
        self.slice.variance()
    }

    pub fn len(&'a self) -> usize {
        self.slice.len()
    }

    pub fn iter(&self) -> impl Iterator<Item=&N> {
        self.slice.iter()
    }

    pub fn sub_epoch(&'a self, pos : usize, len : usize) -> Epoch<'a, N> {
        Self { slice : DVectorSlice::from(&self.slice.as_slice()[pos..pos+len]), offset : self.offset + pos }
    }

    pub fn offset(&self) -> usize {
        self.offset
    }

}

/*impl<'a, M, N> Downsample<Signal<N>> for Epoch<'a, M>
where
    M : Scalar + Copy,
    N : Scalar + Copy + From<M>
{

    fn downsample_aliased(&self, dst : &mut Signal<N>) {
        let step = self.slice.len() / dst.buf.nrows();
        if step == 1 {
            sampling::slices::convert_slice(
                &self.slice.as_slice()[self.offset..],
                dst.buf.as_mut_slice()
            );
        } else {
            let ncols = dst.buf.ncols();
            assert!(self.slice.len() / step == dst.buf.nrows(), "Dimension mismatch");
            sampling::slices::subsample_convert(
                self.slice.as_slice(),
                dst.buf.as_mut_slice(),
                ncols,
                step,
                false
            );
        }
    }
}*/

impl<N> Index<usize> for Signal<N>
where
    N : Scalar
{

    type Output = N;

    fn index(&self, ix: usize) -> &N {
        &self.buf[ix]
    }
}

impl<'a, N> Index<usize> for Epoch<'a, N>
where
    N : Scalar
{

    type Output = N;

    fn index(&self, ix: usize) -> &N {
        &self.slice[ix]
    }
}

/*impl<'a, N> Index<Range<usize>> for Epoch<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{

    type Output = Epoch<'a, N>;

    fn index(&self, ix: Range<usize>) -> Epoch<'a, N> {
        self.sub_epoch(ix.start, ix.end - ix.start)
    }
}*/

impl<N> From<DVector<N>> for Signal<N>
where
    N : Scalar
{
    fn from(s : DVector<N>) -> Self {
        Self{ buf : s }
    }
}

impl<N> From<Vec<N>> for Signal<N>
where
    N : Scalar
{
    fn from(s : Vec<N>) -> Self {
        Self{ buf : DVector::from_vec(s) }
    }
}

impl<N> Into<Vec<N>> for Signal<N>
where
    N : Scalar
{
    fn into(self) -> Vec<N> {
        let n = self.buf.nrows();
        unsafe{ self.buf.data.resize(n) }
    }
}

impl<N> AsRef<[N]> for Signal<N>
where
    N : Scalar
{
    fn as_ref(&self) -> &[N] {
        self.buf.data.as_slice()
    }
}

impl<N> AsMut<[N]> for Signal<N>
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut [N] {
        self.buf.data.as_mut_slice()
    }
}

impl<N> AsRef<Vec<N>> for Signal<N>
where
    N : Scalar
{
    fn as_ref(&self) -> &Vec<N> {
        self.buf.data.as_vec()
    }
}

impl<N> AsMut<Vec<N>> for Signal<N>
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut Vec<N> {
        unsafe{ self.buf.data.as_vec_mut() }
    }
}

impl<N> AsRef<DVector<N>> for Signal<N>
where
    N : Scalar
{
    fn as_ref(&self) -> &DVector<N> {
        &self.buf
    }
}

impl<N> AsMut<DVector<N>> for Signal<N>
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut DVector<N> {
        &mut self.buf
    }
}

pub struct Threshold {

    /// Minimum distance of neighboring values (in number of samples
    /// or symmetrical pixel area). If None, all values satisfying value
    /// will be accepted.
    pub min_dist : Option<usize>,

    /// Threshold value.
    pub value : f64,

    /// All neighboring pixels over the area should be smaller by the
    /// specified ratio. If none, no slope restrictions are imposed.
    pub slope : Option<f64>
}

/*/// Result of thresholding a Signal. This structure carries a (row, col) index and
/// a scalar value for this index.
pub struct SparseSignal<'a, N>
where
    N : Scalar
{
    src : &'a Signal<N>
}

/// Subset of a SparseSignal
pub struct SparseEpoch<'a, N>
where
    N : Scalar
{

    /// Source sparse Signal
    source : &'a SparseSignal<'a, N>,

    /// Which indices we will use from the source
    ixs : Vec<usize>
}*/

/// Auto-generated Signals
pub mod gen {

    use super::*;

    pub fn pulse<T>(n : usize) -> Signal<T>
    where
        T : From<f32> + Scalar + Div<Output=T> + Copy + Debug
    {
        let mut s = flat::<T>(n);
        let s_slice : &mut [T] = s.as_mut();
        s_slice[0] = T::from(1.0);
        s
    }

    pub fn flat<T>(n : usize) -> Signal<T>
    where
        T : From<f32> + Scalar + Div<Output=T> + Copy + Debug
    {
        let max = T::from(n as f32);
        Signal { buf : DVector::from_iterator(n, (0..n).map(|_| T::from(0.) )) }
    }

    pub fn ramp<T>(n : usize) -> Signal<T>
    where
        T : From<f32> + Scalar + Div<Output=T> + Copy + Debug
    {
        let max = T::from(n as f32);
        Signal { buf : DVector::from_iterator(n, (0..n).map(|s| T::from(s as f32) / max )) }
    }

    pub fn step<T>(n : usize) -> Signal<T>
    where
        T : From<f32> + Scalar  + Div<Output=T> + Copy + Debug
    {
        let half_max = n / 2;
        let step_vec = DVector::from_iterator(
            n,
            (0..n).map(|ix| if ix < half_max { T::from(0 as f32) } else { T::from(1.) })
        );
        Signal {
            buf : step_vec
        }
    }

    pub fn step2d<T>(side : usize) -> Signal<T>
    where
        T : Scalar + Copy + MulAssign + AddAssign + Add<Output=T> + Mul<Output=T> + SubAssign + Field + SimdPartialOrd + From<f32>,
        f64 : SubsetOf<T>
    {
        let half_len = side / 2;
        let mut img = flat::<T>(side);
        for i in 0..(side-1) {
            if i <= (half_len-1) {
                img.extend(flat(side));
            } else {
                img.extend(step(side));
            }
        }
        img
    }

}

impl<T> Add for Signal<T>
where
    T : Scalar + AddAssign + Copy
{
    type Output = Self;

    fn add(mut self, other: Self) -> Self {
        self.buf.iter_mut().zip(other.buf.iter()).for_each(|(s, o)| *s += *o );
        self
    }
}

impl<T> fmt::Display for Signal<T>
where
    T : Debug + Display + Copy + Debug + PartialEq + 'static
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.buf)
    }
}