forked from hayguen/pocketfft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pocketfft_hdronly.h
3578 lines (3275 loc) · 108 KB
/
pocketfft_hdronly.h
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
/*
This file is part of pocketfft.
Copyright (C) 2010-2021 Max-Planck-Society
Copyright (C) 2019-2020 Peter Bell
For the odd-sized DCT-IV transforms:
Copyright (C) 2003, 2007-14 Matteo Frigo
Copyright (C) 2003, 2007-14 Massachusetts Institute of Technology
Authors: Martin Reinecke, Peter Bell
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef POCKETFFT_HDRONLY_H
#define POCKETFFT_HDRONLY_H
#ifndef __cplusplus
#error This file is C++ and requires a C++ compiler.
#endif
#if !(__cplusplus >= 201103L || _MSVC_LANG+0L >= 201103L)
#error This file requires at least C++11 support.
#endif
#ifndef POCKETFFT_CACHE_SIZE
#define POCKETFFT_CACHE_SIZE 0
#endif
#include <cmath>
#include <cstdlib>
#include <stdexcept>
#include <memory>
#include <vector>
#include <complex>
#include <algorithm>
#if POCKETFFT_CACHE_SIZE!=0
#include <array>
#include <mutex>
#endif
#ifndef POCKETFFT_NO_MULTITHREADING
#include <mutex>
#include <condition_variable>
#include <thread>
#include <queue>
#include <atomic>
#include <functional>
#include <new>
#ifdef POCKETFFT_PTHREADS
# include <pthread.h>
#endif
#endif
#if defined(__GNUC__)
#define POCKETFFT_NOINLINE __attribute__((noinline))
#define POCKETFFT_RESTRICT __restrict__
#elif defined(_MSC_VER)
#define POCKETFFT_NOINLINE __declspec(noinline)
#define POCKETFFT_RESTRICT __restrict
#else
#define POCKETFFT_NOINLINE
#define POCKETFFT_RESTRICT
#endif
namespace pocketfft {
namespace detail {
using std::size_t;
using std::ptrdiff_t;
// Always use std:: for <cmath> functions
template <typename T> T cos(T) = delete;
template <typename T> T sin(T) = delete;
template <typename T> T sqrt(T) = delete;
using shape_t = std::vector<size_t>;
using stride_t = std::vector<ptrdiff_t>;
constexpr bool FORWARD = true,
BACKWARD = false;
// only enable vector support for gcc>=5.0 and clang>=5.0
#ifndef POCKETFFT_NO_VECTORS
#define POCKETFFT_NO_VECTORS
#if defined(__INTEL_COMPILER)
// do nothing. This is necessary because this compiler also sets __GNUC__.
#elif defined(__clang__)
// AppleClang has their own version numbering
#ifdef __apple_build_version__
# if (__clang_major__ > 9) || (__clang_major__ == 9 && __clang_minor__ >= 1)
# undef POCKETFFT_NO_VECTORS
# endif
#elif __clang_major__ >= 5
# undef POCKETFFT_NO_VECTORS
#endif
#elif defined(__GNUC__)
#if __GNUC__>=5
#undef POCKETFFT_NO_VECTORS
#endif
#endif
#endif
template<typename T> struct VLEN { static constexpr size_t val=1; };
#ifndef POCKETFFT_NO_VECTORS
#if (defined(__AVX512F__))
template<> struct VLEN<float> { static constexpr size_t val=16; };
template<> struct VLEN<double> { static constexpr size_t val=8; };
#elif (defined(__AVX__))
template<> struct VLEN<float> { static constexpr size_t val=8; };
template<> struct VLEN<double> { static constexpr size_t val=4; };
#elif (defined(__SSE2__))
template<> struct VLEN<float> { static constexpr size_t val=4; };
template<> struct VLEN<double> { static constexpr size_t val=2; };
#elif (defined(__VSX__))
template<> struct VLEN<float> { static constexpr size_t val=4; };
template<> struct VLEN<double> { static constexpr size_t val=2; };
#elif (defined(__ARM_NEON__) || defined(__ARM_NEON))
template<> struct VLEN<float> { static constexpr size_t val=4; };
template<> struct VLEN<double> { static constexpr size_t val=2; };
#else
#define POCKETFFT_NO_VECTORS
#endif
#endif
#if __cplusplus >= 201703L
inline void *aligned_alloc(size_t align, size_t size)
{
// aligned_alloc() requires that the requested size is a multiple of "align"
void *ptr = ::aligned_alloc(align,(size+align-1)&(~(align-1)));
if (!ptr) throw std::bad_alloc();
return ptr;
}
inline void aligned_dealloc(void *ptr)
{ free(ptr); }
#else // portable emulation
inline void *aligned_alloc(size_t align, size_t size)
{
align = std::max(align, alignof(max_align_t));
void *ptr = malloc(size+align);
if (!ptr) throw std::bad_alloc();
void *res = reinterpret_cast<void *>
((reinterpret_cast<uintptr_t>(ptr) & ~(uintptr_t(align-1))) + uintptr_t(align));
(reinterpret_cast<void**>(res))[-1] = ptr;
return res;
}
inline void aligned_dealloc(void *ptr)
{ if (ptr) free((reinterpret_cast<void**>(ptr))[-1]); }
#endif
template<typename T> class arr
{
private:
T *p;
size_t sz;
#if defined(POCKETFFT_NO_VECTORS)
static T *ralloc(size_t num)
{
if (num==0) return nullptr;
void *res = malloc(num*sizeof(T));
if (!res) throw std::bad_alloc();
return reinterpret_cast<T *>(res);
}
static void dealloc(T *ptr)
{ free(ptr); }
#else
static T *ralloc(size_t num)
{
if (num==0) return nullptr;
void *ptr = aligned_alloc(64, num*sizeof(T));
return static_cast<T*>(ptr);
}
static void dealloc(T *ptr)
{ aligned_dealloc(ptr); }
#endif
public:
arr() : p(0), sz(0) {}
arr(size_t n) : p(ralloc(n)), sz(n) {}
arr(arr &&other)
: p(other.p), sz(other.sz)
{ other.p=nullptr; other.sz=0; }
~arr() { dealloc(p); }
void resize(size_t n)
{
if (n==sz) return;
dealloc(p);
p = ralloc(n);
sz = n;
}
T &operator[](size_t idx) { return p[idx]; }
const T &operator[](size_t idx) const { return p[idx]; }
T *data() { return p; }
const T *data() const { return p; }
size_t size() const { return sz; }
};
template<typename T> struct cmplx {
T r, i;
cmplx() {}
cmplx(T r_, T i_) : r(r_), i(i_) {}
void Set(T r_, T i_) { r=r_; i=i_; }
void Set(T r_) { r=r_; i=T(0); }
cmplx &operator+= (const cmplx &other)
{ r+=other.r; i+=other.i; return *this; }
template<typename T2>cmplx &operator*= (T2 other)
{ r*=other; i*=other; return *this; }
template<typename T2>cmplx &operator*= (const cmplx<T2> &other)
{
T tmp = r*other.r - i*other.i;
i = r*other.i + i*other.r;
r = tmp;
return *this;
}
template<typename T2>cmplx &operator+= (const cmplx<T2> &other)
{ r+=other.r; i+=other.i; return *this; }
template<typename T2>cmplx &operator-= (const cmplx<T2> &other)
{ r-=other.r; i-=other.i; return *this; }
template<typename T2> auto operator* (const T2 &other) const
-> cmplx<decltype(r*other)>
{ return {r*other, i*other}; }
template<typename T2> auto operator+ (const cmplx<T2> &other) const
-> cmplx<decltype(r+other.r)>
{ return {r+other.r, i+other.i}; }
template<typename T2> auto operator- (const cmplx<T2> &other) const
-> cmplx<decltype(r+other.r)>
{ return {r-other.r, i-other.i}; }
template<typename T2> auto operator* (const cmplx<T2> &other) const
-> cmplx<decltype(r+other.r)>
{ return {r*other.r-i*other.i, r*other.i + i*other.r}; }
template<bool fwd, typename T2> auto special_mul (const cmplx<T2> &other) const
-> cmplx<decltype(r+other.r)>
{
using Tres = cmplx<decltype(r+other.r)>;
return fwd ? Tres(r*other.r+i*other.i, i*other.r-r*other.i)
: Tres(r*other.r-i*other.i, r*other.i+i*other.r);
}
};
template<typename T> inline void PM(T &a, T &b, T c, T d)
{ a=c+d; b=c-d; }
template<typename T> inline void PMINPLACE(T &a, T &b)
{ T t = a; a+=b; b=t-b; }
template<typename T> inline void MPINPLACE(T &a, T &b)
{ T t = a; a-=b; b=t+b; }
template<typename T> cmplx<T> conj(const cmplx<T> &a)
{ return {a.r, -a.i}; }
template<bool fwd, typename T, typename T2> void special_mul (const cmplx<T> &v1, const cmplx<T2> &v2, cmplx<T> &res)
{
res = fwd ? cmplx<T>(v1.r*v2.r+v1.i*v2.i, v1.i*v2.r-v1.r*v2.i)
: cmplx<T>(v1.r*v2.r-v1.i*v2.i, v1.r*v2.i+v1.i*v2.r);
}
template<typename T> void ROT90(cmplx<T> &a)
{ auto tmp_=a.r; a.r=-a.i; a.i=tmp_; }
template<bool fwd, typename T> void ROTX90(cmplx<T> &a)
{ auto tmp_= fwd ? -a.r : a.r; a.r = fwd ? a.i : -a.i; a.i=tmp_; }
//
// twiddle factor section
//
template<typename T> class sincos_2pibyn
{
private:
using Thigh = typename std::conditional<(sizeof(T)>sizeof(double)), T, double>::type;
size_t N, mask, shift;
arr<cmplx<Thigh>> v1, v2;
static cmplx<Thigh> calc(size_t x, size_t n, Thigh ang)
{
x<<=3;
if (x<4*n) // first half
{
if (x<2*n) // first quadrant
{
if (x<n) return cmplx<Thigh>(std::cos(Thigh(x)*ang), std::sin(Thigh(x)*ang));
return cmplx<Thigh>(std::sin(Thigh(2*n-x)*ang), std::cos(Thigh(2*n-x)*ang));
}
else // second quadrant
{
x-=2*n;
if (x<n) return cmplx<Thigh>(-std::sin(Thigh(x)*ang), std::cos(Thigh(x)*ang));
return cmplx<Thigh>(-std::cos(Thigh(2*n-x)*ang), std::sin(Thigh(2*n-x)*ang));
}
}
else
{
x=8*n-x;
if (x<2*n) // third quadrant
{
if (x<n) return cmplx<Thigh>(std::cos(Thigh(x)*ang), -std::sin(Thigh(x)*ang));
return cmplx<Thigh>(std::sin(Thigh(2*n-x)*ang), -std::cos(Thigh(2*n-x)*ang));
}
else // fourth quadrant
{
x-=2*n;
if (x<n) return cmplx<Thigh>(-std::sin(Thigh(x)*ang), -std::cos(Thigh(x)*ang));
return cmplx<Thigh>(-std::cos(Thigh(2*n-x)*ang), -std::sin(Thigh(2*n-x)*ang));
}
}
}
public:
POCKETFFT_NOINLINE sincos_2pibyn(size_t n)
: N(n)
{
constexpr auto pi = 3.141592653589793238462643383279502884197L;
Thigh ang = Thigh(0.25L*pi/n);
size_t nval = (n+2)/2;
shift = 1;
while((size_t(1)<<shift)*(size_t(1)<<shift) < nval) ++shift;
mask = (size_t(1)<<shift)-1;
v1.resize(mask+1);
v1[0].Set(Thigh(1), Thigh(0));
for (size_t i=1; i<v1.size(); ++i)
v1[i]=calc(i,n,ang);
v2.resize((nval+mask)/(mask+1));
v2[0].Set(Thigh(1), Thigh(0));
for (size_t i=1; i<v2.size(); ++i)
v2[i]=calc(i*(mask+1),n,ang);
}
cmplx<T> operator[](size_t idx) const
{
if (2*idx<=N)
{
auto x1=v1[idx&mask], x2=v2[idx>>shift];
return cmplx<T>(T(x1.r*x2.r-x1.i*x2.i), T(x1.r*x2.i+x1.i*x2.r));
}
idx = N-idx;
auto x1=v1[idx&mask], x2=v2[idx>>shift];
return cmplx<T>(T(x1.r*x2.r-x1.i*x2.i), -T(x1.r*x2.i+x1.i*x2.r));
}
};
struct util // hack to avoid duplicate symbols
{
static POCKETFFT_NOINLINE size_t largest_prime_factor (size_t n)
{
size_t res=1;
while ((n&1)==0)
{ res=2; n>>=1; }
for (size_t x=3; x*x<=n; x+=2)
while ((n%x)==0)
{ res=x; n/=x; }
if (n>1) res=n;
return res;
}
static POCKETFFT_NOINLINE double cost_guess (size_t n)
{
constexpr double lfp=1.1; // penalty for non-hardcoded larger factors
size_t ni=n;
double result=0.;
while ((n&1)==0)
{ result+=2; n>>=1; }
for (size_t x=3; x*x<=n; x+=2)
while ((n%x)==0)
{
result+= (x<=5) ? double(x) : lfp*double(x); // penalize larger prime factors
n/=x;
}
if (n>1) result+=(n<=5) ? double(n) : lfp*double(n);
return result*double(ni);
}
/* returns the smallest composite of 2, 3, 5, 7 and 11 which is >= n */
static POCKETFFT_NOINLINE size_t good_size_cmplx(size_t n)
{
if (n<=12) return n;
size_t bestfac=2*n;
for (size_t f11=1; f11<bestfac; f11*=11)
for (size_t f117=f11; f117<bestfac; f117*=7)
for (size_t f1175=f117; f1175<bestfac; f1175*=5)
{
size_t x=f1175;
while (x<n) x*=2;
for (;;)
{
if (x<n)
x*=3;
else if (x>n)
{
if (x<bestfac) bestfac=x;
if (x&1) break;
x>>=1;
}
else
return n;
}
}
return bestfac;
}
/* returns the smallest composite of 2, 3, 5 which is >= n */
static POCKETFFT_NOINLINE size_t good_size_real(size_t n)
{
if (n<=6) return n;
size_t bestfac=2*n;
for (size_t f5=1; f5<bestfac; f5*=5)
{
size_t x = f5;
while (x<n) x *= 2;
for (;;)
{
if (x<n)
x*=3;
else if (x>n)
{
if (x<bestfac) bestfac=x;
if (x&1) break;
x>>=1;
}
else
return n;
}
}
return bestfac;
}
static size_t prod(const shape_t &shape)
{
size_t res=1;
for (auto sz: shape)
res*=sz;
return res;
}
static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape,
const stride_t &stride_in, const stride_t &stride_out, bool inplace)
{
auto ndim = shape.size();
if (ndim<1) throw std::runtime_error("ndim must be >= 1");
if ((stride_in.size()!=ndim) || (stride_out.size()!=ndim))
throw std::runtime_error("stride dimension mismatch");
if (inplace && (stride_in!=stride_out))
throw std::runtime_error("stride mismatch");
}
static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape,
const stride_t &stride_in, const stride_t &stride_out, bool inplace,
const shape_t &axes)
{
sanity_check(shape, stride_in, stride_out, inplace);
auto ndim = shape.size();
shape_t tmp(ndim,0);
for (auto ax : axes)
{
if (ax>=ndim) throw std::invalid_argument("bad axis number");
if (++tmp[ax]>1) throw std::invalid_argument("axis specified repeatedly");
}
}
static POCKETFFT_NOINLINE void sanity_check(const shape_t &shape,
const stride_t &stride_in, const stride_t &stride_out, bool inplace,
size_t axis)
{
sanity_check(shape, stride_in, stride_out, inplace);
if (axis>=shape.size()) throw std::invalid_argument("bad axis number");
}
#ifdef POCKETFFT_NO_MULTITHREADING
static size_t thread_count (size_t /*nthreads*/, const shape_t &/*shape*/,
size_t /*axis*/, size_t /*vlen*/)
{ return 1; }
#else
static size_t thread_count (size_t nthreads, const shape_t &shape,
size_t axis, size_t vlen)
{
if (nthreads==1) return 1;
size_t size = prod(shape);
size_t parallel = size / (shape[axis] * vlen);
if (shape[axis] < 1000)
parallel /= 4;
size_t max_threads = nthreads == 0 ?
std::thread::hardware_concurrency() : nthreads;
return std::max(size_t(1), std::min(parallel, max_threads));
}
#endif
};
namespace threading {
#ifdef POCKETFFT_NO_MULTITHREADING
constexpr inline size_t thread_id() { return 0; }
constexpr inline size_t num_threads() { return 1; }
template <typename Func>
void thread_map(size_t /* nthreads */, Func f)
{ f(); }
#else
inline size_t &thread_id()
{
static thread_local size_t thread_id_=0;
return thread_id_;
}
inline size_t &num_threads()
{
static thread_local size_t num_threads_=1;
return num_threads_;
}
static const size_t max_threads = std::max(1u, std::thread::hardware_concurrency());
class latch
{
std::atomic<size_t> num_left_;
std::mutex mut_;
std::condition_variable completed_;
using lock_t = std::unique_lock<std::mutex>;
public:
latch(size_t n): num_left_(n) {}
void count_down()
{
lock_t lock(mut_);
if (--num_left_)
return;
completed_.notify_all();
}
void wait()
{
lock_t lock(mut_);
completed_.wait(lock, [this]{ return is_ready(); });
}
bool is_ready() { return num_left_ == 0; }
};
template <typename T> class concurrent_queue
{
std::queue<T> q_;
std::mutex mut_;
std::atomic<size_t> size_;
using lock_t = std::lock_guard<std::mutex>;
public:
void push(T val)
{
lock_t lock(mut_);
++size_;
q_.push(std::move(val));
}
bool try_pop(T &val)
{
if (size_ == 0) return false;
lock_t lock(mut_);
// Queue might have been emptied while we acquired the lock
if (q_.empty()) return false;
val = std::move(q_.front());
--size_;
q_.pop();
return true;
}
bool empty() const { return size_==0; }
};
// C++ allocator with support for over-aligned types
template <typename T> struct aligned_allocator
{
using value_type = T;
template <class U>
aligned_allocator(const aligned_allocator<U>&) {}
aligned_allocator() = default;
T *allocate(size_t n)
{
void* mem = aligned_alloc(alignof(T), n*sizeof(T));
return static_cast<T*>(mem);
}
void deallocate(T *p, size_t /*n*/)
{ aligned_dealloc(p); }
};
class thread_pool
{
// A reasonable guess, probably close enough for most hardware
static constexpr size_t cache_line_size = 64;
struct alignas(cache_line_size) worker
{
std::thread thread;
std::condition_variable work_ready;
std::mutex mut;
std::atomic_flag busy_flag = ATOMIC_FLAG_INIT;
std::function<void()> work;
void worker_main(
std::atomic<bool> &shutdown_flag,
std::atomic<size_t> &unscheduled_tasks,
concurrent_queue<std::function<void()>> &overflow_work)
{
using lock_t = std::unique_lock<std::mutex>;
bool expect_work = true;
while (!shutdown_flag || expect_work)
{
std::function<void()> local_work;
if (expect_work || unscheduled_tasks == 0)
{
lock_t lock(mut);
// Wait until there is work to be executed
work_ready.wait(lock, [&]{ return (work || shutdown_flag); });
local_work.swap(work);
expect_work = false;
}
bool marked_busy = false;
if (local_work)
{
marked_busy = true;
local_work();
}
if (!overflow_work.empty())
{
if (!marked_busy && busy_flag.test_and_set())
{
expect_work = true;
continue;
}
marked_busy = true;
while (overflow_work.try_pop(local_work))
{
--unscheduled_tasks;
local_work();
}
}
if (marked_busy) busy_flag.clear();
}
}
};
concurrent_queue<std::function<void()>> overflow_work_;
std::mutex mut_;
std::vector<worker, aligned_allocator<worker>> workers_;
std::atomic<bool> shutdown_;
std::atomic<size_t> unscheduled_tasks_;
using lock_t = std::lock_guard<std::mutex>;
void create_threads()
{
lock_t lock(mut_);
size_t nthreads=workers_.size();
for (size_t i=0; i<nthreads; ++i)
{
try
{
auto *worker = &workers_[i];
worker->busy_flag.clear();
worker->work = nullptr;
worker->thread = std::thread([worker, this]
{
worker->worker_main(shutdown_, unscheduled_tasks_, overflow_work_);
});
}
catch (...)
{
shutdown_locked();
throw;
}
}
}
void shutdown_locked()
{
shutdown_ = true;
for (auto &worker : workers_)
worker.work_ready.notify_all();
for (auto &worker : workers_)
if (worker.thread.joinable())
worker.thread.join();
}
public:
explicit thread_pool(size_t nthreads):
workers_(nthreads)
{ create_threads(); }
thread_pool(): thread_pool(max_threads) {}
~thread_pool() { shutdown(); }
void submit(std::function<void()> work)
{
lock_t lock(mut_);
if (shutdown_)
throw std::runtime_error("Work item submitted after shutdown");
++unscheduled_tasks_;
// First check for any idle workers and wake those
for (auto &worker : workers_)
if (!worker.busy_flag.test_and_set())
{
--unscheduled_tasks_;
{
lock_t lock(worker.mut);
worker.work = std::move(work);
}
worker.work_ready.notify_one();
return;
}
// If no workers were idle, push onto the overflow queue for later
overflow_work_.push(std::move(work));
}
void shutdown()
{
lock_t lock(mut_);
shutdown_locked();
}
void restart()
{
shutdown_ = false;
create_threads();
}
};
inline thread_pool & get_pool()
{
static thread_pool pool;
#ifdef POCKETFFT_PTHREADS
static std::once_flag f;
std::call_once(f,
[]{
pthread_atfork(
+[]{ get_pool().shutdown(); }, // prepare
+[]{ get_pool().restart(); }, // parent
+[]{ get_pool().restart(); } // child
);
});
#endif
return pool;
}
/** Map a function f over nthreads */
template <typename Func>
void thread_map(size_t nthreads, Func f)
{
if (nthreads == 0)
nthreads = max_threads;
if (nthreads == 1)
{ f(); return; }
auto & pool = get_pool();
latch counter(nthreads);
std::exception_ptr ex;
std::mutex ex_mut;
for (size_t i=0; i<nthreads; ++i)
{
pool.submit(
[&f, &counter, &ex, &ex_mut, i, nthreads] {
thread_id() = i;
num_threads() = nthreads;
try { f(); }
catch (...)
{
std::lock_guard<std::mutex> lock(ex_mut);
ex = std::current_exception();
}
counter.count_down();
});
}
counter.wait();
if (ex)
std::rethrow_exception(ex);
}
#endif
}
//
// complex FFTPACK transforms
//
template<typename T0> class cfftp
{
private:
struct fctdata
{
size_t fct;
cmplx<T0> *tw, *tws;
};
size_t length;
arr<cmplx<T0>> mem;
std::vector<fctdata> fact;
void add_factor(size_t factor)
{ fact.push_back({factor, nullptr, nullptr}); }
template<bool fwd, typename T> void pass2 (size_t ido, size_t l1,
const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch,
const cmplx<T0> * POCKETFFT_RESTRICT wa) const
{
auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T&
{ return ch[a+ido*(b+l1*c)]; };
auto CC = [cc,ido](size_t a, size_t b, size_t c) -> const T&
{ return cc[a+ido*(b+2*c)]; };
auto WA = [wa, ido](size_t x, size_t i)
{ return wa[i-1+x*(ido-1)]; };
if (ido==1)
for (size_t k=0; k<l1; ++k)
{
CH(0,k,0) = CC(0,0,k)+CC(0,1,k);
CH(0,k,1) = CC(0,0,k)-CC(0,1,k);
}
else
for (size_t k=0; k<l1; ++k)
{
CH(0,k,0) = CC(0,0,k)+CC(0,1,k);
CH(0,k,1) = CC(0,0,k)-CC(0,1,k);
for (size_t i=1; i<ido; ++i)
{
CH(i,k,0) = CC(i,0,k)+CC(i,1,k);
special_mul<fwd>(CC(i,0,k)-CC(i,1,k),WA(0,i),CH(i,k,1));
}
}
}
#define POCKETFFT_PREP3(idx) \
T t0 = CC(idx,0,k), t1, t2; \
PM (t1,t2,CC(idx,1,k),CC(idx,2,k)); \
CH(idx,k,0)=t0+t1;
#define POCKETFFT_PARTSTEP3a(u1,u2,twr,twi) \
{ \
T ca=t0+t1*twr; \
T cb{-t2.i*twi, t2.r*twi}; \
PM(CH(0,k,u1),CH(0,k,u2),ca,cb) ;\
}
#define POCKETFFT_PARTSTEP3b(u1,u2,twr,twi) \
{ \
T ca=t0+t1*twr; \
T cb{-t2.i*twi, t2.r*twi}; \
special_mul<fwd>(ca+cb,WA(u1-1,i),CH(i,k,u1)); \
special_mul<fwd>(ca-cb,WA(u2-1,i),CH(i,k,u2)); \
}
template<bool fwd, typename T> void pass3 (size_t ido, size_t l1,
const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch,
const cmplx<T0> * POCKETFFT_RESTRICT wa) const
{
constexpr T0 tw1r=-0.5,
tw1i= (fwd ? -1: 1) * T0(0.8660254037844386467637231707529362L);
auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T&
{ return ch[a+ido*(b+l1*c)]; };
auto CC = [cc,ido](size_t a, size_t b, size_t c) -> const T&
{ return cc[a+ido*(b+3*c)]; };
auto WA = [wa, ido](size_t x, size_t i)
{ return wa[i-1+x*(ido-1)]; };
if (ido==1)
for (size_t k=0; k<l1; ++k)
{
POCKETFFT_PREP3(0)
POCKETFFT_PARTSTEP3a(1,2,tw1r,tw1i)
}
else
for (size_t k=0; k<l1; ++k)
{
{
POCKETFFT_PREP3(0)
POCKETFFT_PARTSTEP3a(1,2,tw1r,tw1i)
}
for (size_t i=1; i<ido; ++i)
{
POCKETFFT_PREP3(i)
POCKETFFT_PARTSTEP3b(1,2,tw1r,tw1i)
}
}
}
#undef POCKETFFT_PARTSTEP3b
#undef POCKETFFT_PARTSTEP3a
#undef POCKETFFT_PREP3
template<bool fwd, typename T> void pass4 (size_t ido, size_t l1,
const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch,
const cmplx<T0> * POCKETFFT_RESTRICT wa) const
{
auto CH = [ch,ido,l1](size_t a, size_t b, size_t c) -> T&
{ return ch[a+ido*(b+l1*c)]; };
auto CC = [cc,ido](size_t a, size_t b, size_t c) -> const T&
{ return cc[a+ido*(b+4*c)]; };
auto WA = [wa, ido](size_t x, size_t i)
{ return wa[i-1+x*(ido-1)]; };
if (ido==1)
for (size_t k=0; k<l1; ++k)
{
T t1, t2, t3, t4;
PM(t2,t1,CC(0,0,k),CC(0,2,k));
PM(t3,t4,CC(0,1,k),CC(0,3,k));
ROTX90<fwd>(t4);
PM(CH(0,k,0),CH(0,k,2),t2,t3);
PM(CH(0,k,1),CH(0,k,3),t1,t4);
}
else
for (size_t k=0; k<l1; ++k)
{
{
T t1, t2, t3, t4;
PM(t2,t1,CC(0,0,k),CC(0,2,k));
PM(t3,t4,CC(0,1,k),CC(0,3,k));
ROTX90<fwd>(t4);
PM(CH(0,k,0),CH(0,k,2),t2,t3);
PM(CH(0,k,1),CH(0,k,3),t1,t4);
}
for (size_t i=1; i<ido; ++i)
{
T t1, t2, t3, t4;
T cc0=CC(i,0,k), cc1=CC(i,1,k),cc2=CC(i,2,k),cc3=CC(i,3,k);
PM(t2,t1,cc0,cc2);
PM(t3,t4,cc1,cc3);
ROTX90<fwd>(t4);
CH(i,k,0) = t2+t3;
special_mul<fwd>(t1+t4,WA(0,i),CH(i,k,1));
special_mul<fwd>(t2-t3,WA(1,i),CH(i,k,2));
special_mul<fwd>(t1-t4,WA(2,i),CH(i,k,3));
}
}
}
#define POCKETFFT_PREP5(idx) \
T t0 = CC(idx,0,k), t1, t2, t3, t4; \
PM (t1,t4,CC(idx,1,k),CC(idx,4,k)); \
PM (t2,t3,CC(idx,2,k),CC(idx,3,k)); \
CH(idx,k,0).r=t0.r+t1.r+t2.r; \
CH(idx,k,0).i=t0.i+t1.i+t2.i;
#define POCKETFFT_PARTSTEP5a(u1,u2,twar,twbr,twai,twbi) \
{ \
T ca,cb; \
ca.r=t0.r+twar*t1.r+twbr*t2.r; \
ca.i=t0.i+twar*t1.i+twbr*t2.i; \
cb.i=twai*t4.r twbi*t3.r; \
cb.r=-(twai*t4.i twbi*t3.i); \
PM(CH(0,k,u1),CH(0,k,u2),ca,cb); \
}
#define POCKETFFT_PARTSTEP5b(u1,u2,twar,twbr,twai,twbi) \
{ \
T ca,cb,da,db; \
ca.r=t0.r+twar*t1.r+twbr*t2.r; \
ca.i=t0.i+twar*t1.i+twbr*t2.i; \
cb.i=twai*t4.r twbi*t3.r; \
cb.r=-(twai*t4.i twbi*t3.i); \
special_mul<fwd>(ca+cb,WA(u1-1,i),CH(i,k,u1)); \
special_mul<fwd>(ca-cb,WA(u2-1,i),CH(i,k,u2)); \
}
template<bool fwd, typename T> void pass5 (size_t ido, size_t l1,
const T * POCKETFFT_RESTRICT cc, T * POCKETFFT_RESTRICT ch,