-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathndarray.hpp
More file actions
1335 lines (1146 loc) · 48.3 KB
/
Copy pathndarray.hpp
File metadata and controls
1335 lines (1146 loc) · 48.3 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
#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <array>
#include <cassert>
#include <cmath>
#include <type_traits>
#include <initializer_list>
#include "cxxabi.h"
#define is_slicing_pack(Expr, Slices) (contains_slice<Slices...>::value || (sizeof...(Slices) < Expr::ndim && all_integral<Slices...>::value))
#define is_non_slicing_pack(Expr, Slices) (sizeof...(Slices) == Expr::ndim && all_integral<Slices...>::value)
#define make_trait_tester(trait) constexpr bool _is_ ## trait(...) { return false; } \
template <typename T> \
constexpr auto _is_ ## trait(T* t) -> decltype(T::_is_ ## trait) \
{ return T::_is_ ## trait; } \
template <typename T> \
struct is_ ## trait { \
static constexpr bool value = _is_ ## trait((typename std::decay<T>::type*)0); \
}
/*
* Macros for expression and scalar type traits.
*/
#define enable_if_array(type) typename = std::enable_if_t<is_array<type>::value>
#define enable_if_expression(type) typename = std::enable_if_t<is_expression<type>::value>
#define enable_if_scalar(type) typename = std::enable_if_t<std::is_arithmetic<type>::value>
#define shape_compatible(type1, type2) elementwise_compatible<type1, type2>::value
#define requires(condition) typename std::enable_if<condition, void*>::type __ = 0
namespace nda {
make_trait_tester(expression);
make_trait_tester(constant);
make_trait_tester(array);
make_trait_tester(slice);
template <typename T, typename... Ts>
struct contains_slice {
static constexpr bool value = is_slice<T>::value || contains_slice<Ts...>::value;
};
template <typename T>
struct contains_slice<T> {
static constexpr bool value = is_slice<T>::value;
};
}
/*
* Template metaprogramming tools for manipulating variadic non-type template
* parameters (possibly encapsulated in a struct called a shape pack).
*/
constexpr size_t DYNAMIC_SHAPE = 0;
template <typename T, typename... Ts>
struct count_integral {
static constexpr size_t value = count_integral<Ts...>::value + (std::is_integral<typename std::decay<T>::type>::value ? 1 : 0);
};
template <typename T>
struct count_integral<T> {
static constexpr size_t value = std::is_integral<typename std::decay<T>::type>::value ? 1 : 0;
};
template <size_t N, size_t I, size_t... Is>
struct nth_in_size_pack {
static constexpr size_t value = nth_in_size_pack<N-1, Is...>::value;
};
template <size_t I, size_t... Is>
struct nth_in_size_pack<0, I, Is...> {
static constexpr size_t value = I;
};
template <size_t N, typename T, typename... Ts>
struct nth_in_type_pack {
static_assert((N-1) < sizeof...(Ts), "Invalid pack index.");
using type = typename nth_in_type_pack<N-1, Ts...>::type;
};
template <typename T, typename... Ts>
struct nth_in_type_pack<0, T, Ts...> {
using type = T;
};
template <size_t N, size_t... Is>
inline constexpr size_t _at() {
static_assert((N >= 0) && (N < sizeof...(Is)), "Invalid pack index.");
return nth_in_size_pack<N, Is...>::value;
}
template <typename T, typename... Ts>
struct all_integral {
static constexpr bool value = std::is_integral<typename std::decay<T>::type>::value && all_integral<Ts...>::value;
};
template <typename T>
struct all_integral<T> {
static constexpr bool value = std::is_integral<typename std::decay<T>::type>::value;
};
template <size_t Q, typename ShapePack, size_t I = ShapePack::len-1>
struct count_in {
static constexpr size_t value = count_in<Q, ShapePack, I-1>::value + ( (Q==ShapePack::template at<I>) ? 1 : 0 );
};
template <size_t Q, typename ShapePack>
struct count_in<Q, ShapePack, 0> {
static constexpr size_t value = ( (Q==ShapePack::template at<0>) ? 1 : 0 );
};
/*
* Find the index of the Nth occurrence of Q in ShapePack. Requires that
* ShapePack actually contain at least N Qs.
*/
template <size_t N, size_t Q, typename ShapePack, size_t match_count = 0, size_t cur_ind = 0>
struct nth_match_index_in_pack {
static_assert(N < count_in<Q, ShapePack>::value, "Pack does not contain sufficient matches.");
static_assert((N >= 0) && (N < ShapePack::len), "Invalid pack index.");
static constexpr size_t value =
std::conditional<cur_ind == ShapePack::len-1,
std::integral_constant<size_t, cur_ind>,
typename std::conditional<ShapePack::template at<cur_ind> == Q,
typename std::conditional<match_count == N,
std::integral_constant<size_t, cur_ind>,
nth_match_index_in_pack<N, Q, ShapePack, match_count+1, cur_ind+1>
>::type,
nth_match_index_in_pack<N, Q, ShapePack, match_count, cur_ind+1>
>::type>::type::value;
};
/*
* Find the index of the Nth non-integral type in a type pack. Requires that
* the pack actually contain at least N non-integral types.
*/
template <size_t N, size_t match_count, size_t cur_ind, typename... Types>
struct _nth_non_integral_index {
static_assert(N < sizeof...(Types) - count_integral<Types...>::value, "Pack does not contain sufficient non-integral types.");
static_assert((N >= 0) && (N < sizeof...(Types)), "Invalid pack index.");
static constexpr size_t value =
std::conditional<cur_ind == sizeof...(Types)-1,
std::integral_constant<size_t, cur_ind>,
typename std::conditional<!std::is_integral<typename nth_in_type_pack<cur_ind, Types...>::type>::value,
typename std::conditional<match_count == N,
std::integral_constant<size_t, cur_ind>,
_nth_non_integral_index<N, match_count+1, cur_ind+1, Types...>
>::type,
_nth_non_integral_index<N, match_count, cur_ind+1, Types...>
>::type>::type::value;
};
template <size_t N, typename... Types>
struct nth_non_integral_index {
static constexpr size_t value = _nth_non_integral_index<N, 0, 0, Types...>::value;
};
template <size_t A, size_t B>
constexpr size_t tmax() { return ((A>B) ? A : B); }
template <size_t A, size_t B>
constexpr size_t tmin() { return ((A<B) ? A : B); }
/*
* Checks each dimension in a pair of shape packs to make sure they match for
* elementwise operations (including copy construction and assignment).
*
* Dynamic dimensions match with any other dimension, they are checked at
* runtime.
*/
template <typename Pack1, typename Pack2, size_t I = tmin<Pack1::len, Pack2::len>()-1>
struct elementwise_compatible {
static constexpr bool value = std::conditional<Pack1::len == Pack2::len,
std::integral_constant<bool,
((Pack1::template at<I> == Pack2::template at<I>) ||
(Pack1::template at<I> == DYNAMIC_SHAPE) ||
(Pack2::template at<I> == DYNAMIC_SHAPE)) &&
elementwise_compatible<Pack1, Pack2, I-1>::value>,
std::false_type>::type::value;
};
template <typename Pack1, typename Pack2>
struct elementwise_compatible<Pack1, Pack2, 0> {
static constexpr bool value = std::conditional<Pack1::len == Pack2::len,
std::integral_constant<bool,
((Pack1::template at<0> == Pack2::template at<0>) ||
(Pack1::template at<0> == DYNAMIC_SHAPE) ||
(Pack2::template at<0> == DYNAMIC_SHAPE))>,
std::false_type>::type::value;
};
/*
* A basic shape pack.
*/
template <size_t... Shape>
struct shape_pack {
static constexpr size_t len = sizeof...(Shape);
template <size_t I>
static constexpr size_t at = _at<I, Shape...>();
};
template<size_t Ndim>
struct universal_shape_pack {
static constexpr size_t len = Ndim;
template <size_t I>
static constexpr size_t at = 0;
};
/*
* A shape pack representing the elementwise maximum between two shape packs.
* This is the shape that results from an elementwise operation.
*/
template <typename Pack1, typename Pack2>
struct max_shape_pack {
static_assert(Pack1::len == Pack2::len, "Cannot take max of packs of different length.");
static constexpr size_t len = Pack1::len;
template <size_t I>
static constexpr size_t at = tmax<Pack1::template at<I>, Pack2::template at<I>>();
};
// Placeholder for a full axis as a slice.
struct all { static constexpr bool _is_slice = true; };
template <typename T>
static constexpr bool is_all(const T& t) { return std::is_same<typename std::decay<T>::type, all>::value; }
template <typename Pack, typename... Slices>
struct sliced_shape_pack {
static constexpr size_t len = Pack::len - count_integral<Slices...>::value;
template <size_t I>
static constexpr size_t ___at(requires(I < sizeof...(Slices))) {
static_assert(I < Pack::len, "Invalid pack index.");
return std::conditional<std::is_integral<typename nth_in_type_pack<I, Slices...>::type>::value,
std::integral_constant<size_t, 1>,
typename std::conditional<
std::is_same<typename std::decay<typename nth_in_type_pack<I, Slices...>::type>::type, all>::value,
std::integral_constant<size_t, Pack::template at<I>>,
std::integral_constant<size_t, 0>
>::type
>::type::value;
}
template <size_t I>
static constexpr size_t ___at(requires(I >= sizeof...(Slices))) {
static_assert(I < Pack::len, "Invalid pack index.");
return Pack::template at<I>;
}
template <size_t I>
static constexpr size_t __at() {
static_assert(I < len, "Invalid pack index.");
return ___at<std::conditional<I < (sizeof...(Slices) - count_integral<Slices...>::value),
nth_non_integral_index<I, Slices...>,
std::integral_constant<size_t, I>
>::type::value>();
}
template <size_t I>
static constexpr size_t at = __at<I>();
};
template <typename Pack, size_t Axis>
struct sum_shape_pack {
static constexpr size_t len = Pack::len - 1;
template <size_t I>
static constexpr size_t at = std::conditional<I < Axis,
std::integral_constant<size_t, Pack::template at<I>>,
std::integral_constant<size_t, Pack::template at<I+1>>
>::type::value;
};
/*
* Fill an std::array with values from a shape pack.
*/
template <typename ShapePack, size_t I>
struct _array_filler {
static void fill(std::array<size_t, ShapePack::len>& arr) {
arr[I] = ShapePack::template at<I>;
_array_filler<ShapePack, I-1>::fill(arr);
}
};
template <typename ShapePack>
struct _array_filler<ShapePack, 0> {
static void fill(std::array<size_t, ShapePack::len>& arr) {
arr[0] = ShapePack::template at<0>;
}
};
template <typename ShapePack>
void fill_array(std::array<size_t, ShapePack::len>& arr) {
_array_filler<ShapePack, ShapePack::len-1>::fill(arr);
}
/*
* Demangle the name of a type. Useful for debugging.
*/
std::string demangle(const char* name) {
char* buf = new char[1024];
size_t len = 1024;
int status;
abi::__cxa_demangle(name, buf, &len, &status);
std::string s(buf);
delete[] buf;
return s;
}
namespace nda {
/*
* A constant expression template containing a constant value and a matching
* expression (to define the shape of the constant).
*/
template <typename T, typename Expr>
struct constant {
static_assert(!is_constant<Expr>::value,
"Cannot create a constant expression attached to another constant.");
using value_type = T;
using shape_type = typename Expr::shape_type;
T value;
const Expr& expr;
static constexpr size_t ndim = Expr::ndim;
size_t size() const { return expr.size(); }
std::array<size_t, ndim> shape() const { return expr.shape(); }
explicit constant(const T& t, const Expr& e) : value(t), expr(e)
{}
struct const_iterator {
T ivalue;
typename Expr::const_iterator iter;
const_iterator(const constant& p, bool end = false) : ivalue(p.value),
iter(end ? p.expr.end() : p.expr.begin()) {}
const value_type& operator*() const { return ivalue; }
bool operator==(const const_iterator& other) const { return (ivalue == other.ivalue) && (iter == other.iter); }
bool operator!=(const const_iterator& other) const { return !(this->operator==(other)); }
const_iterator& operator++() { ++iter; return *this; }
const_iterator& operator--() { --iter; return *this; }
const_iterator operator++(int) { const_iterator copy(*this); ++iter; return *this; }
const_iterator operator--(int) { const_iterator copy(*this); --iter; return *this; }
};
const_iterator begin() const { return const_iterator(*this); }
const_iterator end() const { return const_iterator(*this, true); }
};
/*
* Expression template class for binary expressions operating on individual
* matching elements from a pair of arrays (elementwise operators).
*/
template <typename Expr1, typename Expr2, template<typename, typename> class BinaryOp>
struct elemwise_binary_expr {
using Op = BinaryOp<Expr1, Expr2>;
using value_type = typename Op::value_type;
using shape_type = typename Op::shape_type;
static constexpr bool _is_expression = true;
using expr1_type = typename std::conditional<is_array<Expr1>::value, const Expr1&, const Expr1>::type;
using expr2_type = typename std::conditional<is_array<Expr2>::value, const Expr2&, const Expr2>::type;
expr1_type lhs;
expr2_type rhs;
static constexpr size_t ndim = Op::ndim;
size_t size() const { return lhs.size(); }
std::array<size_t, ndim> shape() const { return lhs.shape(); }
elemwise_binary_expr(const Expr1& l, const Expr2& r) : lhs(l), rhs(r) {
assert(l.size() == r.size());
assert(shape_match(l.shape(), r.shape()));
}
/*
* Iterator access is provided to evaluate the expression for use in array
* construction.
*/
struct const_iterator {
typename Expr1::const_iterator iter1;
typename Expr2::const_iterator iter2;
const_iterator(const elemwise_binary_expr& p, bool end=false) :
iter1(end ? p.lhs.end() : p.lhs.begin()),
iter2(end ? p.rhs.end() : p.rhs.begin()) {}
value_type operator*() const { return Op::eval(*iter1, *iter2); }
bool operator==(const const_iterator& other) const { return (iter1 == other.iter1) && (iter2 == other.iter2); }
bool operator!=(const const_iterator& other) const { return !(this->operator==(other)); }
const_iterator& operator++() { ++iter1; ++iter2; return *this; }
const_iterator& operator--() { --iter1; --iter2; return *this; }
const_iterator operator++(int) { const_iterator copy(*this); ++iter1; ++iter2; return copy; }
const_iterator operator--(int) { const_iterator copy(*this); --iter1; --iter2; return copy; }
};
const_iterator begin() const { return const_iterator(*this); }
const_iterator end() const { return const_iterator(*this, true); }
};
/*
* See above, but for unary operations on individual array elements.
*/
template <typename Expr, template<typename> class UnaryOp>
struct elemwise_unary_expr {
using Op = UnaryOp<Expr>;
using value_type = typename Op::value_type;
using shape_type = typename Expr::shape_type;
using expr_type = typename std::conditional<is_array<Expr>::value, const Expr&, const Expr>::type;
static constexpr bool _is_expression = true;
expr_type expr;
static constexpr size_t ndim = Op::ndim;
size_t size() const { return expr.size(); }
std::array<size_t, ndim> shape() const { return expr.shape(); }
elemwise_unary_expr(const Expr& e) : expr(e) { }
value_type operator()(const std::array<size_t, ndim>& inds) const {
return Op::eval(expr(inds));
}
struct const_iterator {
typename Expr::const_iterator iter;
explicit const_iterator(const elemwise_unary_expr& p, bool end=false) :
iter(end ? p.expr.end() : p.expr.begin()) {}
value_type operator*() const { return Op::eval(*iter); }
bool operator==(const const_iterator& other) const { return iter == other.iter; }
bool operator!=(const const_iterator& other) const { return !(this->operator==(other)); }
const_iterator& operator++() { ++iter; return *this; }
const_iterator& operator--() { --iter; return *this; }
const_iterator operator++(int) { const_iterator copy(*this); ++iter; return copy; }
const_iterator operator--(int) { const_iterator copy(*this); --iter; return copy; }
};
const_iterator begin() const { return const_iterator(*this); }
const_iterator end() const { return const_iterator(*this, true); }
};
/*
* Macros to define the required functions/operators and expression template
* operator classes for basic operators (+,-,*,/), unary, and binary functions.
*
* Each requires 3 overloaded forms: one for a pair of arrays/expressions, and
* one for a single array/expression with a broadcasted scalar on either side.
*/
#define make_basic_elemwise_binary_expr_op(op, name) \
template <typename Expr1, typename Expr2> \
struct name ## _op { \
using value_type = decltype(typename Expr1::value_type() op typename Expr2::value_type()); \
using shape_type = max_shape_pack<typename Expr1::shape_type, typename Expr2::shape_type>; \
static constexpr value_type eval(const value_type& l, const value_type& r) { return l op r; } \
static constexpr size_t ndim = Expr1::ndim; \
}; \
template <typename Expr1, typename Expr2> \
typename std::enable_if<is_expression<Expr1>::value && is_expression<Expr2>::value, \
elemwise_binary_expr<Expr1, Expr2, name ## _op>>::type \
operator op(const Expr1& lhs, const Expr2& rhs) { \
return {lhs, rhs}; \
} \
template <typename Expr, typename T> \
typename std::enable_if<is_expression<Expr>::value && std::is_arithmetic<T>::value, \
elemwise_binary_expr<Expr, constant<T, Expr>, name ## _op>>::type \
operator op(const Expr& lhs, const T& rhs) { \
return {lhs, constant<T, Expr>{rhs, lhs}}; \
} \
template <typename Expr, typename T> \
typename std::enable_if<is_expression<Expr>::value && std::is_arithmetic<T>::value, \
elemwise_binary_expr<constant<T, Expr>, Expr, name ## _op>>::type \
operator op(const T& lhs, const Expr& rhs) { \
return {constant<T, Expr>{lhs, rhs}, rhs}; \
}
#define make_func_elemwise_unary_expr_op(func, name) \
template <typename Expr> \
struct name ## _op { \
using value_type = decltype(func(typename Expr::value_type())); \
using shape_type = typename Expr::shape_type; \
static constexpr value_type eval(const value_type& e) { return func(e); } \
static constexpr size_t ndim = Expr::ndim; \
}; \
template <typename Expr> \
typename std::enable_if<is_expression<Expr>::value, \
elemwise_unary_expr<Expr, name ## _op>>::type \
name(const Expr& expr) { return expr; }
#define make_func_elemwise_binary_expr_op(func, name) \
template <typename Expr1, typename Expr2> \
struct name ## _op { \
using value_type = decltype(func(typename Expr1::value_type(), typename Expr2::value_type())); \
using shape_type = max_shape_pack<typename Expr1::shape_type, typename Expr2::shape_type>; \
static constexpr value_type eval(const value_type& l, const value_type& r) { return func(l, r); } \
static constexpr size_t ndim = Expr1::ndim; \
}; \
template <typename Expr1, typename Expr2> \
typename std::enable_if<is_expression<Expr1>::value && is_expression<Expr2>::value, \
elemwise_binary_expr<Expr1, Expr2, name ## _op>>::type \
func(const Expr1& lhs, const Expr2& rhs) { \
return {lhs, rhs}; \
} \
template <typename Expr, typename T> \
typename std::enable_if<is_expression<Expr>::value && std::is_arithmetic<T>::value, \
elemwise_binary_expr<Expr, constant<T, Expr>, name ## _op>>::type \
func(const Expr& lhs, const T& rhs) { \
return {lhs, constant<T, Expr>{rhs, lhs}}; \
} \
template <typename Expr, typename T> \
typename std::enable_if<is_expression<Expr>::value && std::is_arithmetic<T>::value, \
elemwise_binary_expr<constant<T, Expr>, Expr, name ## _op>>::type \
func(const T& lhs, const Expr& rhs) { \
return {constant<T, Expr>{lhs, rhs}, rhs}; \
}
/*
* Macro-based definitions of expression-template-generating operators for
* basic operations, as well as unary and binary cmath functions.
*/
make_basic_elemwise_binary_expr_op(+, add);
make_basic_elemwise_binary_expr_op(-, sub);
make_basic_elemwise_binary_expr_op(*, mul);
make_basic_elemwise_binary_expr_op(/, div);
make_func_elemwise_binary_expr_op(pow, pow);
make_func_elemwise_binary_expr_op(atan2, atan2);
make_func_elemwise_unary_expr_op(std::exp, exp);
make_func_elemwise_unary_expr_op(std::log, log);
make_func_elemwise_unary_expr_op(std::log2, log2);
make_func_elemwise_unary_expr_op(std::log10, log10);
make_func_elemwise_unary_expr_op(std::sin, sin);
make_func_elemwise_unary_expr_op(std::cos, cos);
make_func_elemwise_unary_expr_op(std::tan, tan);
make_func_elemwise_unary_expr_op(std::asin, asin);
make_func_elemwise_unary_expr_op(std::acos, acos);
make_func_elemwise_unary_expr_op(std::atan, atan);
// The only unary basic operator supported currently is negation, no need for
// another macro type.
template <typename Expr>
struct neg_op {
using value_type = decltype(-(typename Expr::value_type()));
using shape_type = typename Expr::shape_type;
static constexpr value_type eval(const value_type& v) { return -v; }
static constexpr size_t ndim = Expr::ndim;
};
template <typename Expr>
typename std::enable_if<is_expression<Expr>::value,
elemwise_unary_expr<Expr, neg_op>>::type
operator-(const Expr& expr) { return expr; }
struct range {
static constexpr bool _is_slice = true;
int start, stop, step;
range() : start(-1), stop(-1), step(-1) {}
range(const all& a) : start(-1), stop(-1), step(-1) {}
explicit range(int sto) : start(0), stop(sto), step(1) {}
range(int sta, int sto, int ste=1) : start(sta), stop(sto), step(ste) {}
struct rng_iter {
const range& rng;
int cur;
rng_iter(const range& r) : rng(r), cur(r.start) {}
rng_iter(const range& r, int init) : rng(r), cur(init) {}
const int& operator*() const { return cur; }
rng_iter& operator++() { cur += rng.step; return *this; }
rng_iter operator++(int) { rng_iter tmp(*this); cur += rng.step; return tmp; }
rng_iter& operator+=(int x) { cur += x*rng.step; return *this; }
rng_iter operator+(int x) const { return rng_iter(*this) += x; }
rng_iter& operator-=(int x) { cur -= x*rng.step; return *this; }
rng_iter operator-(int x) const { return rng_iter(*this) -= x; }
bool operator==(const rng_iter& other) const { return other.cur == cur && other.rng == rng; }
bool operator!=(const rng_iter& other) const { return !(this->operator==(other)); }
};
rng_iter begin() const { return rng_iter(*this); }
rng_iter end() const { return rng_iter(*this, start + len()*step); }
int len() const { return (stop - start) / step + (((abs(stop-start)%abs(step)) == 0) ? 0 : 1); }
bool operator==(const range& other) const { return other.start == start && other.stop == stop && other.step == step; }
bool operator!=(const range& other) const { return !(this->operator==(other)); }
};
using slice = range;
/*
* Convert a list of parameters, which may be indices or slices, to a
* list of slices.
*/
template<typename I0>
slice _index_to_slice(const I0& i0, requires(std::is_integral<I0>::value)) {
return slice(i0, i0+1);
}
template<typename I0>
slice _index_to_slice(const I0& i0, requires(is_slice<I0>::value)) {
return i0;
}
template <size_t S, typename I0, typename... Indices>
void _convert_indices(std::array<slice, S>& slices, std::array<bool, S>& ind_types, int n, const I0& i0, const Indices&... inds) {
slices[n] = _index_to_slice(i0);
ind_types[n] = is_slice<I0>::value;
_convert_indices(slices, ind_types, n+1, inds...);
}
template <size_t S, typename I0>
void _convert_indices(std::array<slice, S>& slices, std::array<bool, S>& ind_types, int n, const I0& i0) {
slices[n] = _index_to_slice(i0);
ind_types[n] = is_slice<I0>::value;
}
template <typename Expr, bool Mutable>
struct fancy_iterator {
using expr_ref = typename std::conditional<Mutable, Expr&, const Expr&>::type;
using access_type = typename Expr::access_type;
using const_access_type = typename Expr::const_access_type;
static constexpr size_t ndim = Expr::ndim;
expr_ref expr;
// The {} is required to value-initialize the array with zeroes.
std::array<size_t, ndim> cur_pos{};
fancy_iterator(expr_ref e) : expr(e) { }
fancy_iterator(expr_ref e, const std::array<size_t, ndim>& p) : expr(e), cur_pos(p) {}
const_access_type operator*() const { return expr(cur_pos); }
template<bool M = Mutable>
typename std::enable_if<M, access_type>::type
operator*() { return expr(this->cur_pos); }
bool operator==(const fancy_iterator& other) const {
bool equal = true;
for(int i=0; i<ndim; ++i) {
equal = equal && (cur_pos[i] == other.cur_pos[i]);
}
return equal;
}
bool operator!=(const fancy_iterator& other) const { return !(this->operator==(other)); }
fancy_iterator& operator++() {
int carries = 0;
for(int i=ndim-1; i>=0; --i) {
if(cur_pos[i] < expr.shape()[i]-1) {
++cur_pos[i];
break;
} else {
cur_pos[i] = 0;
++carries;
}
}
if (carries == ndim) {
cur_pos = expr.shape();
}
return *this;
}
fancy_iterator& operator--() {
int zeros = 0;
for(int i=ndim-1; i>=0; --i) {
if(cur_pos[i] > 0) {
--cur_pos[i];
break;
} else {
cur_pos[i] = expr.shape()[i]-1;
++zeros;
}
}
if (zeros == ndim) {
cur_pos = expr.shape();
}
return *this;
}
fancy_iterator operator++(int) {
fancy_iterator copy(*this);
++(*this);
return copy;
}
fancy_iterator operator--(int) {
fancy_iterator copy(*this);
--(*this);
return copy;
}
};
template <typename Expr, typename... Slices>
struct slice_expr {
// Sliced arrays are still arrays, other expressions are not.
static constexpr bool _is_array = is_array<Expr>::value;
static constexpr bool _is_expression = true;
using value_type = typename std::decay<typename Expr::value_type>::type;
using access_type = typename std::conditional<is_array<Expr>::value, value_type&, value_type>::type;
using const_access_type = typename std::conditional<is_array<Expr>::value, const value_type&, const value_type>::type;
using shape_type = sliced_shape_pack<typename Expr::shape_type, Slices...>;
using expr_ref = typename std::conditional<std::is_const<Expr>::value, const Expr&, Expr&>::type;
static constexpr size_t ndim = Expr::ndim - count_integral<Slices...>::value;
static constexpr size_t old_ndim = Expr::ndim;
expr_ref expr;
std::array<slice, old_ndim> _slices = {};
std::array<bool, old_ndim> dim_preserved = {};
std::array<size_t, ndim> _shape = {};
size_t _size;
const size_t& size() const { return _size; }
const std::array<size_t, ndim>& shape() const { return _shape; }
template <enable_if_expression(Expr)>
slice_expr(expr_ref e, const Slices&... slices) : expr(e) {
const auto& a_shp = expr.shape();
std::array<slice, old_ndim> converted_slices;
for(int i=0; i<old_ndim; ++i) { dim_preserved[i] = true; }
_convert_indices(converted_slices, dim_preserved, 0, slices...);
_size = 1;
int si = 0;
for(int i=0; i<old_ndim; ++i) {
const auto& sl = converted_slices[i];
if( dim_preserved[i] ) {
_slices[i] = (sl == slice()) ? slice(a_shp[i]) : sl;
_shape[si] = _slices[i].len();
_size *= _shape[si];
++si;
} else {
_slices[i] = sl;
}
}
}
template <typename... Is, typename = std::enable_if_t<is_non_slicing_pack(slice_expr, Is)>>
const_access_type operator()(Is... is) const {
return (*this)({{static_cast<size_t>(is)}...});
}
template <typename... Is, typename = std::enable_if_t<is_non_slicing_pack(slice_expr, Is)>>
access_type operator()(Is... is) {
return (*this)({{static_cast<size_t>(is)}...});
}
const_access_type operator()(const std::array<size_t, ndim>& slice_inds) const {
std::array<size_t, old_ndim> inds;
int si = 0;
for(int i=0; i < old_ndim; ++i) {
if( dim_preserved[i] ) {
assert(slice_inds[si] < _shape[i] && "Invalid index.");
inds[i] = *(_slices[i].begin() + slice_inds[si]);
++si;
} else {
inds[i] = _slices[i].start;
}
}
return expr(inds);
}
access_type operator()(const std::array<size_t, ndim>& slice_inds) {
std::array<size_t, old_ndim> inds;
int si = 0;
for(int i=0; i < old_ndim; ++i) {
if( dim_preserved[i] ) {
assert(slice_inds[si] < _shape[i] && "Invalid index.");
inds[i] = *(_slices[i].begin() + slice_inds[si]);
++si;
} else {
inds[i] = _slices[i].start;
}
}
return expr(inds);
}
/*
* Slice access operator (returns another slice expression).
*/
template <typename... Slices2, typename = std::enable_if_t<is_slicing_pack(slice_expr, Slices2)>>
slice_expr<const slice_expr<Expr, Slices...>, Slices2...> operator()(const Slices2&... slices2) const {
return {*this, slices2...};
}
template <typename... Slices2, typename = std::enable_if_t<is_slicing_pack(slice_expr, Slices2)>>
slice_expr<slice_expr<Expr, Slices...>, Slices2...> operator()(const Slices2&... slices2) {
return {*this, slices2...};
}
template<typename E = Expr>
typename std::enable_if<is_array<E>::value, slice_expr&>::type
operator=(const value_type v) {
for(auto it = begin(); it != end(); ++it) { (*it) = v; }
return *this;
}
using const_iterator = fancy_iterator<const slice_expr, false>;
using mutable_iterator = fancy_iterator<slice_expr, true>;
const_iterator begin() const { return const_iterator(*this); }
const_iterator end() const { return const_iterator(*this, _shape); }
mutable_iterator begin() { return mutable_iterator(*this); }
mutable_iterator end() { return mutable_iterator(*this, _shape); }
};
template <typename Expr, size_t Axis>
struct sum_expr {
static_assert(Axis < Expr::ndim, "Invalid sum axis.");
static constexpr bool _is_expression = true;
using value_type = typename Expr::value_type;
using shape_type = sum_shape_pack<typename Expr::shape_type, Axis>;
using expr_ref = typename std::conditional<std::is_const<Expr>::value, const Expr&, Expr&>::type;
using access_type = value_type;
using const_access_type = value_type;
static constexpr size_t ndim = Expr::ndim - 1;
static constexpr size_t old_ndim = Expr::ndim;
expr_ref expr;
std::array<size_t, ndim> _shape;
size_t _size;
const size_t& size() const { return _size; }
const std::array<size_t, ndim>& shape() const { return _shape; }
sum_expr(expr_ref e, requires(is_expression<Expr>::value)) : expr(e) {
fill_array<shape_type>(_shape);
_size = 1;
for(int i=0; i<ndim; ++i) { _size *= _shape[i]; }
}
template <typename... Is, typename = std::enable_if_t<is_non_slicing_pack(sum_expr, Is)>>
const_access_type operator()(Is... is) const {
return (*this)({{static_cast<size_t>(is)}...});
}
const_access_type operator()(const std::array<size_t, ndim>& inds) const {
std::array<size_t, old_ndim> old_inds = {};
for(size_t i=0; i<old_ndim; ++i) {
if(i < Axis) {
old_inds[i] = inds[i];
} else if(i > Axis) {
old_inds[i] = inds[i-1];
}
}
access_type sum = 0;
for(size_t i=0; i < expr.shape()[Axis]; ++i) {
sum += expr(old_inds);
old_inds[Axis]++;
}
return sum;
}
/*
* Slice access operator (returns a slice expression).
*/
template <typename... Slices, typename = std::enable_if_t<is_slicing_pack(sum_expr, Slices)>>
slice_expr<const sum_expr<Expr, Axis>, Slices...> operator()(const Slices&... slices) const {
return {*this, slices...};
}
using const_iterator = fancy_iterator<const sum_expr, false>;
const_iterator begin() const { return const_iterator(*this); }
const_iterator end() const { return const_iterator(*this, _shape); }
};
/*
* Ensures instances of any two types with shape() methods have matching
* shapes.
*/
template <typename Arr1, typename Arr2>
bool shape_match(const Arr1& s1, const Arr2& s2) {
assert(s1.size() == s2.size());
bool match = true;
for(size_t i=0; i < s1.size(); ++i) {
match = match && (s1[i] == s2[i]);
}
return match;
}
//////////////////////
// NDARRAY
//////////////////////
/*
* Base n-dimensional array class. Shape is defined by a static ShapePack-like
* struct encapsulating the variadic shapes.
*/
template <typename T, typename ShapePack>
class nda_impl {
public:
using value_type = T;
using shape_type = ShapePack;
static constexpr bool _is_array = true;
static constexpr bool _is_expression = true;
static constexpr size_t ndim = ShapePack::len;
size_t _size;
std::array<size_t, ndim> _strides;
std::array<size_t, ndim> _shape;
const std::array<size_t, ndim>& shape() const { return _shape; }
const std::array<size_t, ndim>& strides() const { return _strides; }
const size_t& size() const { return _size; }
T* data = nullptr;
////////////////////////
// Default Constructor
////////////////////////
nda_impl() {
static_assert(n_dynamic_dims == 0, "Must specify all dynamic dimensions for construction.");
fill_array<ShapePack>(_shape);
_compute_size();
_compute_basic_strides();
_alloc_data();
}
//////////////////////////////////
// Initializer-list Constructor
//////////////////////////////////
nda_impl(const std::initializer_list<T>& items) {
static_assert(n_dynamic_dims < 2,
"Cannot construct arrays with multiple dynamic dimensions from an initializer list (yet).");
fill_array<ShapePack>(_shape);
size_t sz = 1;
size_t dyn_dim = 0;
for(size_t i=0; i<ndim; ++i) {
if(_shape[i] == 0) { dyn_dim = i; } else { sz *= _shape[i]; }
}
if (n_dynamic_dims == 1) {
_shape[dyn_dim] = items.size() / sz;
}
_compute_size();
assert(_size == items.size());
_compute_basic_strides();
_alloc_data(items);
}
//////////////////////
// Copy Constructors
//////////////////////
/*
* Two copy constructors are needed, one "true" copy constructor for
* other instances of nda_impl with the same (possibly dynamic) shape,
* and one for instances with other (compatible) shapes. The same holds
* for move constructors and assignment operators.
*/
nda_impl(const nda_impl& other) : _size(other._size), _strides(other._strides), _shape(other._shape)
{
if(!has_fixed_shape) {
assert(shape_match(_shape, other._shape));
}
_alloc_data();
memcpy(data, other.data, _size*sizeof(T));
}
template <typename OShape>
nda_impl(const nda_impl<T, OShape>& other, requires(shape_compatible(ShapePack, OShape))) :
_size(other._size), _strides(other._strides), _shape(other._shape)
{
if(!has_fixed_shape) {
assert(shape_match(_shape, other._shape));
}
_alloc_data();
memcpy(data, other.data, _size*sizeof(T));
}
//////////////////////
// Move Constructors
//////////////////////
nda_impl(nda_impl&& other) : _size(other._size),
_strides(other._strides),
_shape(other._shape),
data(other.data)
{
if(!has_fixed_shape) {
assert(shape_match(_shape, other._shape));
}
other.data = nullptr;
}