-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFCWSIMD.hpp
More file actions
1754 lines (1730 loc) · 72.5 KB
/
FCWSIMD.hpp
File metadata and controls
1754 lines (1730 loc) · 72.5 KB
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* *
* * Filename: FCWSIMD.hpp
* *
* * Description:
* * Fast C++ SIMD-optimized (AVX2) implementations of:
* * - MDCT/IMDCT (Modified Discrete Cosine Transform) via DCT-IV
* * - DCT-I, DCT-II, DCT-III
* * - FFT/IFFT
* * - STFT/ISTFT (Short-Time Fourier Transform)
* * - Wavelet transforms (DWT/IDWT/CWT/ICWT)
* * - PSD (Periodogram, Welch)
* *
* * Author:
* * JEP, J. Enrique Peraza
* *
* * Organizations:
* * Trivium Solutions, LLC, 9175 Guilford Rd, Suite 220, Columbia, MD 21046
*/
#pragma once
#include <vector>
#include <complex>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cassert>
#include <functional>
#include <string>
#include <type_traits>
#include <algorithm>
#if defined(__x86_64__)||defined(_M_X64)||defined(__i386__)
#include <immintrin.h>
#endif
#include "FCWTransforms.h"
#include "DSPWindows.h"
#include "../SDRTypes.hpp"
namespace sig::spectral::simd{
using std::vector;using std::complex;using sdr::Status;
using ::sig::spectral::WaveletOps;using ::sig::spectral::Window;
// ================================
// Tiny SIMD helpers (x86 AVX2)
// ================================
namespace detail
{
inline bool HasAVX2 (void) noexcept
{
#if defined(__AVX2__)
return true;
#else
return false;
#endif
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
inline float Dot8f (
const float* a, // Input signal
const float* b, // Input signal 2
size_t n) noexcept // Length of vectors
{ // ~~~~~~~~~~~ Dot8 ~~~~~~~~~~~~~ //
float acc=0.0f; // Accumulator
size_t i=0; // Loop index
#if defined(__AVX2__) // SIMD enabled?
__m256 vacc=_mm256_setzero_ps();// Zero accumulator
for(;i+8<=n;i+=8) // Process 8 at a time
{
__m256 va=_mm256_loadu_ps(a+i);// Load 8 floats
__m256 vb=_mm256_loadu_ps(b+i);// Load 8 floats
vacc=_mm256_fmadd_ps(va,vb,vacc);// Fused multiply-add
}
alignas(32) // Align for storage in 32-byte boundary
float tmp[8]; // Temp storage
_mm256_storeu_ps(tmp,vacc); // Store accumulator (unaligned for safety)
// Horizontal add
acc=tmp[0]+tmp[1]+tmp[2]+tmp[3]+tmp[4]+tmp[5]+tmp[6]+tmp[7];
#endif
for(;i<n;++i) // Remainder
acc+=a[i]*b[i]; // Scalar dot
return acc; // Return result
} // ~~~~~~~~~~~ Dot8 ~~~~~~~~~~~~~ //
inline double Dot4d (
const double* a, // Input signal
const double* b, // Input signal 2
size_t n) noexcept // Length of vectors
{ // ~~~~~~~~~~~ Dot4d ~~~~~~~~~~~~~ //
double acc=0.0; // Accumulator
size_t i=0; // Loop index
#if defined(__AVX2__) // SIMD enabled?
__m256d vacc=_mm256_setzero_pd();// Zero accumulator
for(;i+4<=n;i+=4) // Process 4 at a time
{
__m256d va=_mm256_loadu_pd(a+i);// Load 4 doubles
__m256d vb=_mm256_loadu_pd(b+i);// Load 4 doubles
vacc=_mm256_fmadd_pd(va,vb,vacc);// Fused multiply-add
}
alignas(32) // Align for storage in 32-byte boundary
double tmp[4]; // Temp storage
_mm256_storeu_pd(tmp,vacc); // Store accumulator (unaligned for safety)
acc=tmp[0]+tmp[1]+tmp[2]+tmp[3];// Horizontal add
#endif
for(;i<n;++i) // Remainder
acc+=a[i]*b[i]; // Scalar dot
return acc; // Return result
} // ~~~~~~~~~~~ Dot4d ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Fused AXPY: y=a*x+b (fused when AVX2 FMA is present)
// y[i]=a[i]*c+b[i];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
inline void AxpyMul (
float* y, // Output
const float* a, // Input signal
const float* b, // Input signal 2
float c, // Scalar
size_t n) noexcept // Length of vectors
{ // ~~~~~~~~~~~ AxpyMul ~~~~~~~~~~~~~ //
size_t i=0; // Loop index
#if defined(__AVX2__) // SIMD enabled?
__m256 vc=_mm256_set1_ps(c); // Broadcast scalar
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 va=_mm256_loadu_ps(a+i);// Load 8 floats
__m256 vb=_mm256_loadu_ps(b+i);// Load 8 floats
__m256 vy=_mm256_fmadd_ps(va,vc,vb);// Fused multiply-add
_mm256_storeu_ps(y+i,vy); // Store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
y[i]=a[i]*c+b[i]; // Scalar
} // ~~~~~~~~~~~ AxpyMul ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// y += a*x (fused when AVX2 FMA is present)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
inline void Axpy (
float* y, // Output
const float* x, // Input signal
float a, // Scalar
size_t n) noexcept
{ // ~~~~~~~~~~~ Axpy ~~~~~~~~~~~~~ //
size_t i=0; // Loop index
#if defined(__AVX2__) // SIMD enabled?
__m256 va=_mm256_set1_ps(a); // Broadcast scalar
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 vx=_mm256_loadu_ps(x+i);// Load 8 floats
__m256 vy=_mm256_loadu_ps(y+i);// Load 8 floats
vy=_mm256_fmadd_ps(vx,va,vy); // Fused multiply-add
_mm256_storeu_ps(y+i,vy); // Store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
y[i]+=a*x[i]; // Scalar
} // ~~~~~~~~~~~ Axpy ~~~~~~~~~~~~~ //
inline void Mul (
float* y, // Output
const float* x, // Input signal
const float* w, // Weights
size_t n) noexcept // Length of vectors
{ // ~~~~~~~~~~~ Mul ~~~~~~~~~~~~~ //
size_t i=0; // Loop index
#if defined(__AVX2__)
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 vx=_mm256_loadu_ps(x+i);// Load 8 floats
__m256 vw=_mm256_loadu_ps(w+i);// Load 8 floats
__m256 vy=_mm256_mul_ps(vx,vw);// Element-wise multiply
_mm256_storeu_ps(y+i,vy); // Store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
y[i]=x[i]*w[i]; // Scalar
} // ~~~~~~~~~~~ Mul ~~~~~~~~~~~~~ //
inline void Square (
const float* x, // Input
float* y, // Output
size_t n) noexcept // Length of vectors
{ // ~~~~~~~~~~~ Square ~~~~~~~~~~~~~ //
size_t i=0; // Loop index
#if defined(__AVX2__)
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 vx=_mm256_loadu_ps(x+i);// Load 8 floats
__m256 vy=_mm256_mul_ps(vx,vx);// Element-wise square
_mm256_storeu_ps(y+i,vy); // Store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
y[i]=x[i]*x[i]; // Scalar
} // ~~~~~~~~~~~ Square ~~~~~~~~~~~~~ //
inline void Square (
const double* x,
double* y,
size_t n) noexcept
{
for(size_t i=0;i<n;++i)
y[i]=x[i]*x[i];
}
inline size_t NextPow2(size_t n) noexcept
{
if(n==0)
return 1;
--n;
for(size_t s=1;s<sizeof(size_t)*8;s<<=1)
n|=n>>s;
return n+1;
}
}
// SIMD HELPERS
template<typename T=float>
static inline void SIMDMAG2 (
const T* const iq, // Input complex data (AoS: re,im,re,im,...)
T* const out, // Output magnitude data
const int32_t N) // Number of complex samples
{ // ~~~~~~~~~~ SIMDMAG2 ~~~~~~~~~~ //
#if defined(__AVX2__)
if constexpr(std::is_same<T,float>::value)
{
const float* p = reinterpret_cast<const float*>(iq);
int32_t i=0;
for(;i+8<=N;i+=8)
{
__m256 vr = _mm256_loadu_ps(p + 2*i + 0);
__m256 vi = _mm256_loadu_ps(p + 2*i + 8);
__m256 vr2= _mm256_mul_ps(vr, vr);
__m256 vi2= _mm256_mul_ps(vi, vi);
__m256 vm = _mm256_add_ps(vr2, vi2);
_mm256_storeu_ps(out + i, vm);
}
for(;i<N;++i)
{
float r = p[2*i+0];
float im= p[2*i+1];
out[i]= r*r + im*im;
}
return;
}
#endif
// Scalar fallback (double or no AVX2)
const T* p = reinterpret_cast<const T*>(iq);
for (int32_t i=0;i<N;++i)
{
T r = p[2*i+0];
T im= p[2*i+1];
out[i]= r*r + im*im;
}
} // ~~~~~~~~~~ SIMDMAG2 ~~~~~~~~~~ //
// =====================================================================
// WaveletOps SIMD (focus on hot inner loops: thresholding & Haar steps)
// =====================================================================
template<typename T=double>
class WaveletOpsSIMD
{
public:
using WT=typename WaveletOps<T>::WaveletType;
using TT=typename WaveletOps<T>::ThresholdType;
// Vector hard-threshold detail coefficients (SIMD where possible)
static Status HardThreshold (
const vector<T>& det, // Detail coeffs
T thr, // Threshold
vector<T>& out) noexcept // Output coeffs
{ // ~~~~~~~~~~~ HardThreshold ~~~~~~~~~~~~~ //
size_t n=det.size(); // Length of vector
out.resize(n); // Resize output vector
if constexpr(std::is_same<T,float>::value)
{ // Is it a float?
const float t=static_cast<float>(thr);// cast threshold to float
size_t i=0; // Loop index
#if defined(__AVX2__) // AVX2 path
__m256 vt=_mm256_set1_ps(t);// Broadcast threshold
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 vx=_mm256_loadu_ps(det.data()+i);// Load 8 floats
__m256 av=_mm256_andnot_ps(_mm256_set1_ps(-0.0f),vx);// abs(x)
__m256 m=_mm256_cmp_ps(av,vt,_CMP_LT_OQ);// mask abs(x)<t
__m256 zr=_mm256_setzero_ps();// zero
__m256 vy=_mm256_blendv_ps(vx,zr,m);// blend
_mm256_storeu_ps(out.data()+i,vy);// store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
{ // Loop body
float v=static_cast<float>(det[i]);// Load value
out[i]=(std::fabs(v)<t)?0.0f:v;// Threshold
} // Loop body
return Status::Ok; // Success
} // Done with float samples
else // Else it is a double
{ // Double path (no SIMD)
for(size_t i=0;i<n;++i) // For the # of samples in the signal
{ // threshold.....
T v=det[i]; // Load value
out[i]=(std::fabs(v)<thr)?T(0):v;// Threshold
} // Done thresholding
return Status::Ok; // Success
} // Done with double samples
} // ~~~~~~~~~~~ HardThreshold ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Vector soft-threshold detail coefficients (SIMD where possible)
// y=sign(x)*max(|x|-thr,0)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static Status SoftThreshold (
const vector<T>& det, // Detail coeffs
T thr, // Threshold
vector<T>& out) noexcept // Output coeffs
{ // ~~~~~~~~~~~ SoftThreshold ~~~~~~~~~~~~~ //
size_t n=det.size(); // Length of vector
out.resize(n); // Resize output vector
if constexpr(std::is_same<T,float>::value)// Is it a float?
{ // Float path
const float t=static_cast<float>(thr);// cast threshold to float
size_t i=0; // Loop index
#if defined(__AVX2__) // AVX2 path
__m256 vt=_mm256_set1_ps(t);// Broadcast threshold
__m256 vz=_mm256_setzero_ps();// Zero
for(;i+8<=n;i+=8) // Process 8 at a time
{ // Loop body
__m256 vx=_mm256_loadu_ps(det.data()+i);// Load 8 floats
__m256 s=_mm256_and_ps(_mm256_set1_ps(-0.0f),vx);// sign(x)
__m256 av=_mm256_andnot_ps(_mm256_set1_ps(-0.0f),vx);// abs(x)
__m256 sh=_mm256_sub_ps(av,vt);// |x|-t
sh=_mm256_max_ps(sh,vz); // max(|x|-t,0)
__m256 vy=_mm256_or_ps(sh,s);// sign(x)*max(|x|-t,0)
_mm256_storeu_ps(out.data()+i,vy);// store result
} // Loop body
#endif
for(;i<n;++i) // Remainder
{ // Loop body
float v=static_cast<float>(det[i]);// Load value
float a=std::fabs(v)-t; // |x|-t
out[i]=(a>0.0f)?std::copysign(a,v):0.0f;// Threshold
} // Done with remainder thresholding
return Status::Ok; // Success
} // Done with float samples
else // Else it is a double
{ // Double path (no SIMD)
for(size_t i=0;i<n;++i) // For the # of samples in the signal
{ // threshold.....
T v=det[i]; // Load detail coefficient
T a=std::fabs(v)-thr; // |x|-t
out[i]=(a>0)?std::copysign(a,v):T(0);// Threshold
} // Done with thresholding
return Status::Ok; // Success
} // Done with double samples
} // ~~~~~~~~~~~ SoftThreshold ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// One-level Haar DWT (approx,detail) using averaging and differencing
// sig length must be even
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static Status HaarLevel (
const vector<T>& sig, // Input signal
vector<T>& app, // Approximation coefficients
vector<T>& det) noexcept // Detail coefficients
{ // ~~~~~~~~~~~ HaarLevel ~~~~~~~~~~~~~ //
size_t n=sig.size(); // Length of signal
if(n<2) // Must be at least 2 samples
return Status::Arg; // Invalid argument
if(n%2!=0) // Must be even length
return Status::Arg; // Invalid argument
size_t h=n/2; // Half-length
app.resize(h); // Resize output
det.resize(h); // Resize output
for(size_t i=0;i<h;++i) // For each output coeff
{ // Haar step
T s0=sig[2*i]; // Even index: approx coeffs
T s1=sig[2*i+1]; // Odd index: detail coeffs
app[i]=T(1/std::sqrt(2.0))*(s0+s1);// 1/sqrt(2)
det[i]=T(1/std::sqrt(2.0))*(s0-s1);// 1/sqrt(2)
} // Done Haar steps
return Status::Ok; // Success
} // ~~~~~~~~~~~ HaarLevel ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// One-level inverse Haar (reconstruct signal from approx,detail)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static Status HaarInverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
size_t h=app.size();
if(h==0||h!=det.size())
return Status::Arg;
sig.resize(h*2);
if constexpr(std::is_same<T,float>::value)
{
for(size_t i=0;i<h;++i)
{
float a=static_cast<float>(app[i]);
float d=static_cast<float>(det[i]);
sig[2*i]=static_cast<T>(0.7071067811865475f*(a+d));
sig[2*i+1]=static_cast<T>(0.7071067811865475f*(a-d));
}
return Status::Ok;
}
else
{
for(size_t i=0;i<h;++i)
{
T a=app[i];
T d=det[i];
sig[2*i]=T(0.70710678118654752440)*(a+d);
sig[2*i+1]=T(0.70710678118654752440)*(a-d);
}
return Status::Ok;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Additional filter banks (wrap)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Helper: convert vector<T> -> vector<double>
static inline vector<double> ToD (
const vector<T>& x) noexcept
{
vector<double> y(x.size());
for(size_t i=0;i<x.size();++i)
y[i]=static_cast<double>(x[i]);
return y;
}
static inline vector<T> FromD (
const vector<double>& x) noexcept
{
vector<T> y(x.size());
for(size_t i=0;i<x.size();++i)
y[i]=static_cast<T>(x[i]);
return y;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Db1 (alias Haar)
static Status Db1Level (
const vector<T>& sig,
vector<T>& app,
vector<T>& det) noexcept
{
return HaarLevel(sig, app, det);
}
static Status Db1Inverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
return HaarInverse(app, det, sig);
}
// Db6 via legacy WaveletOps<double> forward/backward (scalar correctness path)
static Status Db6Level (
const vector<T>& sig, // Input signal
vector<T>& app, // Approximation coefficients
vector<T>& det) noexcept // Detail coefficients
{
vector<double> sd=ToD(sig);
WaveletOps<double> w;
auto pr=w.db6(sd);
app=FromD(pr.first);
det=FromD(pr.second);
return Status::Ok;
}
static Status Db6Inverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
vector<double> ad=ToD(app),dd=ToD(det);
WaveletOps<double> w;
vector<double> rd=w.inverse_db6(ad,dd);
sig=FromD(rd);
return Status::Ok;
}
// Sym5
static Status Sym5Level (
const vector<T>& sig,
vector<T>& app,
vector<T>& det) noexcept
{
vector<double> sd=ToD(sig);
WaveletOps<double> w;
auto pr=w.sym5(sd);
app=FromD(pr.first);
det=FromD(pr.second);
return Status::Ok;
}
static Status Sym5Inverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
vector<double> ad=ToD(app),dd=ToD(det);
WaveletOps<double> w;
vector<double> rd=w.inverse_sym5(ad,dd);
sig=FromD(rd);
return Status::Ok;
}
// Sym8
static Status Sym8Level (
const vector<T>& sig,
vector<T>& app,
vector<T>& det) noexcept
{
vector<double> sd=ToD(sig);
WaveletOps<double> w;
auto pr=w.sym8(sd);
app=FromD(pr.first);
det=FromD(pr.second);
return Status::Ok;
}
static Status Sym8Inverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
vector<double> ad=ToD(app),dd=ToD(det);
WaveletOps<double> w;
vector<double> rd=w.inverse_sym8(ad,dd);
sig=FromD(rd);
return Status::Ok;
}
// Coif5
static Status Coif5Level (
const vector<T>& sig,
vector<T>& app,
vector<T>& det) noexcept
{
vector<double> sd=ToD(sig);
WaveletOps<double> w;
auto pr=w.coif5(sd);
app=FromD(pr.first);
det=FromD(pr.second);
return Status::Ok;
}
static Status Coif5Inverse (
const vector<T>& app,
const vector<T>& det,
vector<T>& sig) noexcept
{
vector<double> ad=ToD(app),dd=ToD(det);
WaveletOps<double> w;
vector<double> rd=w.inverse_coif5(ad,dd);
sig=FromD(rd);
return Status::Ok;
}
// DWT multilevel
static Status DWTMultilevel (
const vector<T>& sig, // Input signal
WT wtype, // Wavelet type
size_t levels, // Decomposition levels
TT ttype, // Threshold type
T thr, // Threshold
vector<vector<T>>& app, // Approx coeffs per level
vector<vector<T>>& det) noexcept// Detail coeffs per level
{ // ~~~~~~~~~~~ DWTMultilevel ~~~~~~~~~~~~~ //
vector<T> s=sig; // Copy input signal
size_t n=s.size(); // Length of signal
size_t np=detail::NextPow2(n); // Next power of 2
if(np!=n) // Is the signal length a power of 2?
s.resize(np,T(0)); // No, pad with zeros
app.clear(); // Clear output approx coeffs
det.clear(); // Clear output detail coeffs
app.reserve(levels); // Reserve space for approx coeffs
det.reserve(levels); // Reserve space for detail coeffs
for(size_t l=0;l<levels;++l) // For each level
{ // Decompose the signal
vector<T> a,d; // Approx and detail coeffs
Status st; // Status
switch (wtype) // Dispatch on wavelet type
{
case WT::Haar:st=HaarLevel(s,a,d);break;
case WT::Db6:st=Db6Level(s,a,d);break;
case WT::Sym5:st=Sym5Level(s,a,d);break;
case WT::Sym8:st=Sym8Level(s,a,d);break;
case WT::Coif5:st=Coif5Level(s,a,d);break;
default:return Status::Err;
}
if (st!=Status::Ok) // Check status
return st; // Return on error
if (ttype!=TT::None) // Thresholding requested?
{ // Yes
vector<T> dt; // Temp storage
switch (ttype) // Dispatch on threshold type
{
case TT::Hard:st=HardThreshold(d,thr,dt);break;
case TT::Soft:st=SoftThreshold(d,thr,dt);break;
default:return Status::Err;
}
if (st!=Status::Ok) // Check status
return st; // Return on error
d=std::move(dt); // Move thresholded detail coeffs
} // Done thresholding
app.push_back(std::move(a)); // Store approx coeffs
det.push_back(std::move(d)); // Next input is current approx coeffs
s=app.back(); // for next level
} // Done levels
return Status::Ok; // Success
} // ~~~~~~~~~~~ DWTMultilevel ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Inverse DWT multilevel (reconstruct signal from app,det coeffs)
// Assumes app and det are vectors of vectors, each inner vector is
// the coeffs for that level, with the last element of app being
// the coarsest approximation.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static Status IDWTMultilevel (
const vector<vector<T>>& app, // Approx coeffs per level
const vector<vector<T>>& det, // Detail coeffs per level
WT wtype, // Wavelet type
vector<T>& sig) noexcept // Output signal
{ // ~~~~~~~~~~~ IDWTMultilevel ~~~~~~~~~~~~~ //
if(app.empty()||app.size()!=det.size())// Bad args?
return Status::Arg; // Invalid argument
size_t n=app.back().size(); // Length of coarsest approx coeffs
sig=app.back(); // Start with coarsest approx coeffs
// Iterate from coarsest to finest level
for(std::ptrdiff_t l=static_cast<std::ptrdiff_t>(app.size())-1;l>=0;--l)
{
vector<T> s; // Temp storage
Status st; // Status variable
switch (wtype) // Dispatch on wavelet type
{ // to reconstruct signal
case WT::Haar:st=HaarInverse(sig,det[l],s);break;
case WT::Db6:st=Db6Inverse(sig,det[l],s);break;
case WT::Sym5:st=Sym5Inverse(sig,det[l],s);break;
case WT::Sym8:st=Sym8Inverse(sig,det[l],s);break;
case WT::Coif5:st=Coif5Inverse(sig,det[l],s);break;
default:return Status::Err;
} // Check status
if (st!=Status::Ok) // Error?
return st; // Yes, return error status
sig=std::move(s); // Move reconstructed signal
} // Done levels
sig.resize(n); // Trim to original length
return Status::Ok; // Success
} // ~~~~~~~~~~~ IDWTMultilevel ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Continuous Wavelet Transforms (CWT)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static Status CWTMultilevel (
const vector<T>& sig, // Input signal
const vector<T>& sca, // Scales
std::function<vector<T>(const vector<T>&,T)> wfunc,// Wavelet function
T thr, // Threshold
const std::string& ttype, // Threshold type: "soft" or "hard"
vector<vector<T>>& coeffs)noexcept
{
size_t n=sig.size(); // Length of signal
size_t np=detail::NextPow2(n); // Next power of 2
vector<T> pad=sig; // Copy input signal
if(np!=n) // Is the signal length a power of 2?
pad.resize(np,T(0)); // No, pad with zeros
coeffs.clear(); // Clear output coeffs
coeffs.reserve(sca.size()); // Reserve space for coeffs
for (const auto& s:sca) // For each scale
{ // Compute CWT at this scale
vector<T> cw=wfunc(pad,s); // CWT coeffs at this scale
if (ttype=="soft") // Soft thresholding?
{ // Yes
vector<T> out; // Temp storage
SoftThreshold(cw,thr,out); // Soft threshold
coeffs.push_back(std::move(out));// Move to output
} // Done soft thresholding
else // Else hard thresholding
{ // Yes
vector<T> out; // Temp storage
HardThreshold(cw,thr,out); // Hard threshold
coeffs.push_back(std::move(out));// Move to output
} // Done hard thresholding
} // Done scales
return Status::Ok; // Success
} // ~~~~~~~~~~~ CWTMultilevel ~~~~~~~~~~~~~ //
static Status ICWTMultilevel (
const vector<vector<T>>& coeffs,// CWT coeffs per scale
std::function<vector<T>(const vector<T>&,T)> wfunc,// Wavelet function
const vector<T>& sca,vector<T>& sig) noexcept // Inverse CWT
{ // ~~~~~~~~~~~ ICWTMultilevel ~~~~~~~~~~~~~ //
if(coeffs.empty()||coeffs.size()!=sca.size())// Bad args?
return Status::Arg; // Invalid argument
size_t n=coeffs[0].size(); // Length of coeffs
sig.assign(n,T(0)); // Start with zero signal
for(size_t i=0;i<coeffs.size();++i)// For each scale
{ // Reconstruct contribution at this scale
vector<T> rec=wfunc(coeffs[i],sca[i]);// Reconstructed signal at this scale
if(rec.size()!=n) // Bad size?
return Status::Arg; // Invalid argument
for(size_t k=0;k<n;++k) // Accumulate
sig[k]+=rec[k]; // into output signal
} // Done scales
return Status::Ok; // Success
} // ~~~~~~~~~~~ ICWTMultilevel ~~~~~~~~~~~~~ //
static Status ScalogramReal (
const vector<vector<T>>& cwt, // CWT coeffs per scale
vector<vector<T>>& out) noexcept // Scalogram (squared magnitude)
{ // ~~~~~~~~~~~ ScalogramReal ~~~~~~~~~~~~~ //
out.clear(); // Clear output
out.reserve(cwt.size()); // Reserve space for output
for(const auto& v:cwt) // For each scale
{ // Square coeffs
vector<T> m(v.size()); // Magnitude squared
if constexpr(std::is_same<T,float>::value)// Is it a float?
{ // Yes
// SIMD square
detail::Square(reinterpret_cast<const float*>(v.data()),reinterpret_cast<float*>(m.data()),v.size());
}
else // Else double
{
// No SIMD square
detail::Square(reinterpret_cast<const double*>(v.data()),reinterpret_cast<double*>(m.data()),v.size());
}
out.push_back(std::move(m)); // Move to output
}
return Status::Ok; // Success
} // ~~~~~~~~~~~ ScalogramReal ~~~~~~~~~~~~~ //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// CWT wavelet PSI (Pointwise) functions
// Pointwise wavelets
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Morlet: psi(t)=(exp(-t^2/2))*cos(w0*t), w0=5 (default)
// Mexican Hat: psi(t)=(1-(t^2)/a^2)*exp(-t^2/(2*a^2)), a=1 (default)
// Meyer: see MeyerVx and MeyerPsi below
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
static inline T MorletPsi (
T x, // Input
T w0=T(5)) noexcept // Wavelet parameter
{
return std::exp(-x*x/T(2))*std::cos(w0*x);
}
static inline T MexicanHatPsi (
T x,
T a=T(1)) noexcept
{
T a2=a*a;
return (T(1)-(x*x)/a2)*std::exp(-(x*x)/(T(2)*a2));
}
static inline T MeyerVx(T x) noexcept
{
if(x<0)
return T(0);
else if (x<1)
{
T c1=T(35)/T(32),c2=T(35)/T(16),c3=T(21)/T(16),c4=T(5)/T(8);
return x*x*x*(c1-c2*x+c3*x*x-c4*x*x*x);
}
else return T(1);
}
static inline T MeyerPsi(T x) noexcept
{
T ax=std::fabs(x);
if (ax<T(1)/T(3))
return T(1);
if (ax<=T(2)/T(3))
return std::sin(T(M_PI)/T(2)*MeyerVx(T(3)*ax-T(1)))*std::cos(T(M_PI)*x);
return T(0);
}
template<typename Psi>
static Status CWTForward (
const vector<T>& sig, // Input signal
T sc, // Scale
Psi psi, // Wavelet function
vector<T>& cof) noexcept // Output coeffs
{ // ~~~~~~~~~~~ CWTForward ~~~~~~~~~~~~~ //
size_t n=sig.size(); // Length of signal
if (n==0||sc<=T(0)) // Bad args?
return Status::Arg; // Invalid argument
cof.assign(n,T(0)); // Resize output coeffs
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Build reversed psi kernel for 'same' convolution: h_rev[j]=psi(((n-1)-j)/sc)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
vector<T> href(n); // Reversed wavelet
for (size_t j=0;j<n;++j) // For each tap
{ // Compute reversed wavelet
T x=(T(n-1)-T(j))/sc; // Scaled position
href[j]=psi(x); // Wavelet value
} // Done building reversed wavelet
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Zero-pad signal on both sides (length n-1 on each) to extract 'same' windows
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
vector<T> pad; // Padded signal
pad.resize(2*n-1,T(0)); // Resize and zero
for (size_t i=0;i<n;++i) // Copy signal
pad[n-1+i]=sig[i]; // to center of padded signal
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// Convolve signal with wavelet by sliding dot product over windows of length n
// Slide dot over windows of length n
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
const T inv=T(1)/std::sqrt(sc); // Normalization factor
if constexpr(std::is_same<T,float>::value)// Is it a float?
{ // Yes
const float* k=reinterpret_cast<const float*>(href.data());// Wavelet kernel
const float* p=reinterpret_cast<const float*>(pad.data());// Padded signal
for(size_t i=0;i<n;++i) // For each output coeff
{ // Compute dot product
float v=detail::Dot8f(p+i,k,n);// Dot product
cof[i]=static_cast<T>(v)*inv;// Scale
} // Done output coeff
} // Done float path
else // Else double
{ // Double path
const double* k=reinterpret_cast<const double*>(href.data()); // Wavelet kernel
const double* p=reinterpret_cast<const double*>(pad.data()); // Padded signal
for(size_t i=0;i<n;++i) // For each output coeff
{ // Compute dot product
double v=detail::Dot4d(p+i,k,n);// Dot product
cof[i]=static_cast<T>(v)*inv;// Scale
} // Done output coeff
} // Done double path
return Status::Ok; // Success
} // ~~~~~~~~~~~ CWTForward ~~~~~~~~~~~~~ //
// Specific wavelet wrappers
static Status CWTForwardMorlet (
const vector<T>& sig,
T sc,vector<T>& cof,
T w0=T(5)) noexcept
{
return CWTForward(sig,sc,[&](T x){return MorletPsi(x,w0);},cof);
}
static Status CWTForwardMexicanHat (
const vector<T>& sig,
T sc,vector<T>& cof,
T a=T(1)) noexcept
{
return CWTForward(sig,sc,[&](T x){return MexicanHatPsi(x,a);},cof);
}
static Status CWTForwardMeyer (
const vector<T>& sig,
T sc,vector<T>& cof) noexcept
{
return CWTForward(sig,sc,[&](T x){return MeyerPsi(x);},cof);
}
// Approx/Detail style decompositions
static Status MorletDecompose (
const vector<T>& s,
T w0,
vector<T>& app,
vector<T>& det) noexcept
{
size_t n=s.size();
app.resize(n);
det.resize(n);
T A=T(1)/std::sqrt(T(2)*T(M_PI));
T si=T(1)/w0;
for(size_t i=0;i<n;++i)
{
T t=T(i)-T(n)/T(2);
T mor=A*std::exp(-(t*t)/(T(2)*si*si))*std::cos(w0*t/si);
app[i]=s[i]*mor;
det[i]=s[i]*(T(1)-mor);
}
return Status::Ok;
}
static Status MexicanHatDecompose (
const vector<T>& s,
T a,
vector<T>& app,
vector<T>& det) noexcept
{
size_t n=s.size();
app.resize(n);
det.resize(n);
T A=T(2)/(std::sqrt(T(3)*a)*std::pow(T(M_PI),T(0.25)));
T a2=a*a;
for(size_t i=0;i<n;++i)
{
T t=T(i)-T(n)/T(2);
T t2=t*t;
T mex=A*(T(1)-t2/a2)*std::exp(-t2/(T(2)*a2));
app[i]=s[i]*mex;
det[i]=s[i]*(T(1)-mex);
}
return Status::Ok;
}
static Status MeyerDecompose (
const vector<T>& s,
vector<T>& app,
vector<T>& det) noexcept
{
size_t n=s.size();
app.resize(n);
det.resize(n);
for(size_t i=0;i<n;++i)
{
T t=T(i)-T(n)/T(2);
T mey=T(0);
T at=std::fabs(t);
if (at<T(1)/T(3))
mey=T(1);
else if (at<=T(2)/T(3))
mey=std::sin(T(M_PI)/T(2)*MeyerVx(T(3)*at-T(1)))*std::cos(T(M_PI)*t);
app[i]=s[i]*mey;
det[i]=s[i]*(T(1)-mey);
}
return Status::Ok;
}
// Inverse reconstructions
static Status InverseMorlet (
const vector<T>& app,
const vector<T>& det,
T w0,
vector<T>& rec) noexcept
{
size_t n=app.size();
if(det.size()!=n)
return Status::Arg;
rec.assign(2*n,T(0));
T A=T(1)/std::sqrt(T(2)*T(M_PI));
T si=T(1)/w0;
for(size_t i=0;i<n;++i)
{
T t=T(2)*T(i)-T(n);
T mor=A*std::exp(-(t*t)/(T(2)*si*si))*std::cos(w0*t/si);
rec[2*i]+=app[i]*mor;
rec[2*i+1]+=det[i]*(T(1)-mor);
}
return Status::Ok;
}
static Status InverseMexicanHat (
const vector<T>& app,
const vector<T>& det,
T a,
vector<T>& rec) noexcept
{
size_t n=app.size();
if(det.size()!=n)
return Status::Arg;
rec.assign(2*n,T(0));
T A=T(2)/(std::sqrt(T(3)*a)*std::pow(T(M_PI),T(0.25)));
T a2=a*a;
for(size_t i=0;i<n;++i)
{
T t=T(2)*T(i)-T(n);
T t2=t*t;
T mex=A*(T(1)-t2/a2)*std::exp(-t2/(T(2)*a2));
rec[2*i]+=app[i]*mex;
rec[2*i+1]+=det[i]*(T(1)-mex);
}
return Status::Ok;
}
static Status InverseMeyer (
const vector<T>& app,
const vector<T>& det,
vector<T>& rec) noexcept
{
size_t n=app.size();
if(det.size()!=n)
return Status::Arg;
rec.assign(2*n,T(0));
for(size_t i=0;i<n;++i)
{
T t=T(2)*T(i)-T(n);
T at=std::fabs(t);
T mey=T(0);
if(at<T(1)/T(3))
mey=T(1);
else if(at<=T(2)/T(3))
mey=std::sin(T(M_PI)/T(2)*MeyerVx(T(3)*at-T(1)))*std::cos(T(M_PI)*t);
rec[2*i]+=app[i]*mey;
rec[2*i+1]+=det[i]*(T(1)-mey);
}
return Status::Ok;
}
};
// ======================================================
// DCT SIMD (DCT-II/III/IV via cosine-matrix dot-products)
// ======================================================
template<typename T=float>
class DCTSIMD
{
public:
// Compute DCT-II (orthonormal variant). O(N^2) using SIMD dot-products.
static Status DCTII (
const vector<T>& x,
vector<T>& X) noexcept
{
size_t n=x.size();
if(n==0)
return Status::Arg;
X.assign(n,T(0));
const T s0=std::sqrt(T(1)/T(n));
const T s=std::sqrt(T(2)/T(n));
// Precompute cosines row-wise for cache locality
vector<T> cosv(n*n,T(0));
for(size_t k=0;k<n;++k)
{
for(size_t i=0;i<n;++i)
{
cosv[k*n+i]=std::cos((T(M_PI)/T(n))*(T(i)+T(0.5))*T(k));
}
}
if constexpr(std::is_same<T,float>::value)
{
for(size_t k=0;k<n;++k)
{
float sc=(k==0)?static_cast<float>(s0):static_cast<float>(s);
X[k]=static_cast<T>(sc*detail::Dot8f(reinterpret_cast<const float*>(x.data()),reinterpret_cast<const float*>(&cosv[k*n]),n));
}
}
else
{
for(size_t k=0;k<n;++k)