-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathndarray.hpp
More file actions
2690 lines (2093 loc) · 79.8 KB
/
ndarray.hpp
File metadata and controls
2690 lines (2093 loc) · 79.8 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
/**
==============================================================================
Copyright 2019, Jonathan Zrake
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
*/
#pragma once
#include <algorithm> // std::all_of
#include <functional> // std::ref
#include <initializer_list> // std::initializer_list
#include <iterator> // std::distance
#include <memory> // std::shared_ptr
#include <numeric> // std::accumulate
#include <string> // std::to_string
#include <utility> // std::index_sequence
//=============================================================================
namespace nd
{
// array support structs
//=========================================================================
template<std::size_t Rank, typename ValueType, typename DerivedType> class short_sequence_t;
template<std::size_t Rank> class shape_t;
template<std::size_t Rank> class index_t;
template<std::size_t Rank> class jumps_t;
template<std::size_t Rank> class memory_strides_t;
template<std::size_t Rank> class access_pattern_t;
template<typename ValueType, std::size_t Rank> class basic_sequence_t;
template<typename ValueType> class buffer_t;
template<typename Provider> class array_t;
// array and access pattern factory functions
//=========================================================================
template<typename... Args> auto make_shape(Args... args);
template<typename... Args> auto make_index(Args... args);
template<typename... Args> auto make_jumps(Args... args);
template<std::size_t Rank, typename Arg> auto make_uniform_shape(Arg arg);
template<std::size_t Rank, typename Arg> auto make_uniform_index(Arg arg);
template<std::size_t Rank, typename Arg> auto make_uniform_jumps(Arg arg);
template<std::size_t Rank> auto make_strides_row_major(shape_t<Rank> shape);
template<std::size_t Rank> auto make_access_pattern(shape_t<Rank> shape);
template<typename... Args> auto make_access_pattern(Args... args);
template<std::size_t NumPartitions, std::size_t Rank> auto partition_shape(shape_t<Rank> shape);
// provider types
//=========================================================================
template<typename Function, std::size_t Rank> class basic_provider_t;
template<typename ValueType, std::size_t Rank> class shared_provider_t;
template<typename ValueType, std::size_t Rank> class unique_provider_t;
// provider factory functions
//=========================================================================
template<typename ValueType, std::size_t Rank> auto make_shared_provider(shape_t<Rank> shape);
template<typename ValueType, typename... Args> auto make_shared_provider(Args... args);
template<typename ValueType, std::size_t Rank> auto make_unique_provider(shape_t<Rank> shape);
template<typename ValueType, typename... Args> auto make_unique_provider(Args... args);
template<typename Provider> auto evaluate_as_shared(Provider&&);
template<typename Provider> auto evaluate_as_unique(Provider&&);
// array factory functions
//=========================================================================
inline auto arange(int count);
inline auto arange(int start, int final, int step=1);
inline auto linspace(double x0, double x1, std::size_t count);
inline auto divvy(std::size_t num_groups);
template<typename Provider> auto make_array(Provider&&);
template<typename Mapping, std::size_t Rank> auto make_array(Mapping mapping, shape_t<Rank> shape);
template<typename ContainerType> auto make_array_from(const ContainerType& container);
template<typename ValueType, std::size_t Rank> auto make_shared_array(shape_t<Rank> shape);
template<typename ValueType, typename... Args> auto make_shared_array(Args... args);
template<typename ValueType, std::size_t Rank> auto make_unique_array(shape_t<Rank> shape);
template<typename ValueType, typename... Args> auto make_unique_array(Args... args);
template<std::size_t Index, typename ArrayType> auto get(ArrayType array);
template<std::size_t Rank> auto index_array(shape_t<Rank> shape);
template<typename... Args> auto index_array(Args... args);
template<typename... ArrayTypes> auto zip(ArrayTypes... arrays);
template<typename ArrayType> auto unzip(ArrayType array);
template<typename... ArrayTypes> auto cartesian_product(ArrayTypes... arrays);
template<typename... ArrayTypes> auto meshgrid(ArrayTypes... arrays);
template<typename ValueType=int, typename... Args> auto zeros(Args... args);
template<typename ValueType=int, typename... Args> auto ones(Args... args);
template<typename ValueType, std::size_t Rank> auto promote(ValueType, shape_t<Rank>);
// basic array operators
//=========================================================================
inline auto to_shared();
inline auto to_unique();
inline auto bounds_check();
inline auto sum();
inline auto all();
inline auto any();
inline auto min();
inline auto max();
template<typename ArrayType> auto min(ArrayType&& array);
template<typename ArrayType> auto max(ArrayType&& array);
template<typename Function> auto map(Function function);
template<typename Function> auto apply(Function function);
template<typename ArrayType> auto where(ArrayType array);
template<typename Function> auto binary_op(Function function);
// extended operator support structs
//=========================================================================
/**/ class axis_selector_t;
/**/ class axis_shifter_t;
template<std::size_t RankDifference> class axis_freezer_t;
template<typename ArrayType> class axis_reducer_t;
template<typename ArrayType> class concatenator_t;
template<std::size_t Rank, typename ArrayType> class replacer_t;
template<std::size_t Rank> class selector_t;
// extended operators
//=========================================================================
inline auto shift_by(int delta);
inline auto freeze_axis(std::size_t axis_to_freeze);
inline auto select_axis(std::size_t axis_to_select);
template<std::size_t Rank> auto select_from(index_t<Rank> starting_index);
template<typename... Args> auto select_from(Args... args);
template<std::size_t Rank> auto select(access_pattern_t<Rank>);
template<typename OperatorType> auto collect(OperatorType reduction);
template<typename ArrayType> auto concat(ArrayType array_to_concat);
template<std::size_t Rank, typename ArrayType> auto replace(access_pattern_t<Rank>, ArrayType);
template<std::size_t Rank> auto replace_from(index_t<Rank> starting_index);
template<typename... Args> auto replace_from(Args... args);
template<std::size_t Rank> auto reshape(shape_t<Rank> shape);
template<typename... Args> auto reshape(Args... args);
template<std::size_t Rank> auto read_index(index_t<Rank>);
template<typename... Args> auto read_index(Args... args);
template<typename ArrayType> auto read_indexes(ArrayType array_of_indexes);
// to_string overloads
//=========================================================================
template<std::size_t Rank> auto to_string(const index_t<Rank>& index);
template<std::size_t Rank> auto to_string(const shape_t<Rank>& index);
template<std::size_t Rank> auto to_string(const access_pattern_t<Rank>& region);
// convenience typedef's
//=========================================================================
template<typename ValueType, std::size_t Rank> using shared_array = array_t<shared_provider_t<ValueType, Rank>>;
template<typename ValueType, std::size_t Rank> using unique_array = array_t<unique_provider_t<ValueType, Rank>>;
template<typename ArrayType> using value_type_of = typename std::remove_reference_t<ArrayType>::value_type;
// helper functions
//=========================================================================
namespace detail
{
template<std::size_t Index, typename ArrayType>
auto get_through(const ArrayType& array);
template<typename Function, typename Tuple, std::size_t... Is>
auto transform_tuple_impl(Function&& fn, const Tuple& t, std::index_sequence<Is...>);
template<typename Function, typename Tuple>
auto transform_tuple(Function&& fn, const Tuple& t);
template<typename FunctionTuple, typename ArgumentTuple, std::size_t... Is>
auto zip_apply_tuple_impl(FunctionTuple&& fn, ArgumentTuple&& args, std::index_sequence<Is...>);
template<typename FunctionTuple, typename ArgumentTuple>
auto zip_apply_tuple(FunctionTuple&& fn, ArgumentTuple&& args);
template<typename ArrayType, std::size_t... Is>
auto unzip_array_impl(ArrayType array, std::index_sequence<Is...>);
template<typename ResultSequence, typename SourceSequence, typename IndexContainer, typename Sequence>
auto insert_elements(const SourceSequence& source, IndexContainer indexes, Sequence values);
template<typename ResultSequence, typename SourceSequence, typename IndexContainer>
auto remove_elements(const SourceSequence& source, IndexContainer indexes);
template <typename... Ts> using void_t = void;
template <typename T, typename = void>
struct has_typedef_is_ndarray : std::false_type {};
template <typename T>
struct has_typedef_is_ndarray<T, void_t<typename T::is_ndarray>> : std::true_type {};
}
}
//=============================================================================
template<std::size_t Rank, typename ValueType, typename DerivedType>
class nd::short_sequence_t
{
public:
using value_type = ValueType;
//=========================================================================
static DerivedType uniform(ValueType arg)
{
DerivedType result;
for (std::size_t n = 0; n < Rank; ++n)
result.memory[n] = arg;
return result;
}
template<typename Range>
static DerivedType from_range(Range&& rng)
{
if (rng.size() != Rank)
throw std::logic_error("sequence constructed from initializer list of wrong size");
DerivedType result;
std::size_t n = 0;
for (auto a : rng)
result[n++] = a;
return result;
}
static DerivedType range()
{
auto result = DerivedType();
for (std::size_t n = 0; n < Rank; ++n)
result[n] = n;
return result;
};
short_sequence_t()
{
for (std::size_t n = 0; n < Rank; ++n)
memory[n] = ValueType();
}
short_sequence_t(std::initializer_list<ValueType> args)
{
if (args.size() != Rank)
throw std::logic_error("sequence constructed from initializer list of wrong size");
std::size_t n = 0;
for (auto a : args)
memory[n++] = a;
}
bool operator==(const DerivedType& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (memory[i] != b[i]) return false; } return true; }
bool operator!=(const DerivedType& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (memory[i] != b[i]) return true; } return false; }
constexpr std::size_t size() const { return Rank; }
const ValueType* data() const { return memory; }
const ValueType* begin() const { return memory; }
const ValueType* end() const { return memory + Rank; }
const ValueType& operator[](std::size_t n) const { return memory[n]; }
ValueType* data() { return memory; }
ValueType* begin() { return memory; }
ValueType* end() { return memory + Rank; }
ValueType& operator[](std::size_t n) { return memory[n]; }
template<typename Function>
auto transform(Function&& fn) const
{
DerivedType result;
for (std::size_t i = 0; i < Rank; ++i)
result[i] = fn(memory[i]);
return result;
}
private:
//=========================================================================
ValueType memory[Rank];
};
//=============================================================================
template<typename ValueType, std::size_t Size>
class nd::basic_sequence_t : public nd::short_sequence_t<Size, ValueType, basic_sequence_t<ValueType, Size>>
{
};
//=============================================================================
template<std::size_t Rank>
class nd::shape_t : public nd::short_sequence_t<Rank, std::size_t, shape_t<Rank>>
{
public:
using short_sequence_t<Rank, std::size_t, shape_t<Rank>>::short_sequence_t;
std::size_t volume() const
{
return std::accumulate(this->begin(), this->end(), 1, std::multiplies<>());
}
bool contains(const index_t<Rank>& index) const
{
for (std::size_t i = 0; i < Rank; ++i)
if (this->operator[](i) <= index[i])
return false;
return true;
}
template<typename... Args>
bool contains(Args... args) const
{
return contains(make_index(args...));
}
template<typename IndexContainer, typename Sequence>
auto insert_elements(IndexContainer indexes, Sequence values) const
{
return detail::insert_elements<shape_t<Rank + indexes.size()>>(*this, indexes, values);
}
template<typename IndexContainer>
auto remove_elements(IndexContainer indexes) const
{
return detail::remove_elements<shape_t<Rank - indexes.size()>>(*this, indexes);
}
index_t<Rank> last_index() const
{
auto result = index_t<Rank>();
for (std::size_t n = 0; n < Rank; ++n)
{
result[n] = this->operator[](n);
}
return result;
}
};
//=============================================================================
template<std::size_t Rank>
class nd::index_t : public nd::short_sequence_t<Rank, std::size_t, index_t<Rank>>
{
public:
using short_sequence_t<Rank, std::size_t, index_t<Rank>>::short_sequence_t;
template<typename IndexContainer, typename Sequence>
auto insert_elements(IndexContainer indexes, Sequence values) const
{
return detail::insert_elements<index_t<Rank + indexes.size()>>(*this, indexes, values);
}
template<typename IndexContainer>
auto remove_elements(IndexContainer indexes) const
{
return detail::remove_elements<index_t<Rank - indexes.size()>>(*this, indexes);
}
template <size_t... Is>
auto as_tuple(std::index_sequence<Is...>) const { return std::make_tuple(this->operator[](Is)...); }
auto as_tuple() const { return as_tuple(std::make_index_sequence<Rank>()); }
bool operator< (const index_t<Rank>& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (! (this->operator[](i) < b[i])) return false; } return true; }
bool operator> (const index_t<Rank>& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (! (this->operator[](i) > b[i])) return false; } return true; }
bool operator<=(const index_t<Rank>& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (! (this->operator[](i) <= b[i])) return false; } return true; }
bool operator>=(const index_t<Rank>& b) const { for (std::size_t i = 0; i < Rank; ++i) { if (! (this->operator[](i) >= b[i])) return false; } return true; }
};
//=============================================================================
template<std::size_t Rank>
class nd::jumps_t : public nd::short_sequence_t<Rank, long, jumps_t<Rank>>
{
public:
using short_sequence_t<Rank, long, jumps_t<Rank>>::short_sequence_t;
};
//=============================================================================
template<std::size_t Rank>
class nd::memory_strides_t : public nd::short_sequence_t<Rank, std::size_t, memory_strides_t<Rank>>
{
public:
using short_sequence_t<Rank, std::size_t, memory_strides_t<Rank>>::short_sequence_t;
std::size_t compute_offset(const index_t<Rank>& index) const
{
std::size_t result = 0;
for (std::size_t i = 0; i < Rank; ++i)
{
result += index[i] * this->operator[](i);
}
return result;
}
template<typename... Args>
std::size_t compute_offset(Args... args) const
{
return compute_offset(make_index(args...));
}
};
//=============================================================================
template<std::size_t Rank>
class nd::access_pattern_t
{
public:
//=========================================================================
struct iterator
{
using iterator_category = std::input_iterator_tag;
using value_type = index_t<Rank>;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
iterator& operator++() { accessor.advance(current); return *this; }
bool operator==(const iterator& other) const { return current == other.current; }
bool operator!=(const iterator& other) const { return current != other.current; }
const index_t<Rank>& operator*() const { return current; }
access_pattern_t accessor;
index_t<Rank> current;
};
constexpr std::size_t rank() const { return Rank; }
//=========================================================================
bool operator==(const access_pattern_t& other) const
{
return
start == other.start &&
final == other.final &&
jumps == other.jumps;
}
bool operator!=(const access_pattern_t& other) const
{
return
start != other.start ||
final != other.final ||
jumps != other.jumps;
}
//=========================================================================
template<typename... Args> access_pattern_t with_start(Args... args) const { return { make_index(args...), final, jumps }; }
template<typename... Args> access_pattern_t with_final(Args... args) const { return { start, make_index(args...), jumps }; }
template<typename... Args> access_pattern_t with_jumps(Args... args) const { return { start, final, make_jumps(args...) }; }
access_pattern_t with_start(index_t<Rank> arg) const { return { arg, final, jumps }; }
access_pattern_t with_final(index_t<Rank> arg) const { return { start, arg, jumps }; }
access_pattern_t with_jumps(jumps_t<Rank> arg) const { return { start, final, arg }; }
/**
* @brief Return the number of elements hit by an iteration over this
* access pattern.
*
* @return The number of elements
*/
std::size_t size() const
{
return shape().volume();
}
/**
* @brief Return the shape of the mapped-to index space.
*
* @return A shape
*/
auto shape() const
{
auto s = shape_t<Rank>();
for (std::size_t n = 0; n < Rank; ++n)
{
s[n] = (final[n] - start[n] - 1) / jumps[n] + 1;
}
return s;
}
/**
* @brief Determine whether this accessor has any elements.
*
* @return A boolean
*/
bool empty() const
{
return size() == 0;
}
/**
* @brief Move an index forward, and return true if the new index is
* before the end.
*
* @param index The index to advance
*
* @return A boolean
* @note The last index advances fastest.
*/
bool advance(index_t<Rank>& index) const
{
int n = Rank - 1;
index[n] += jumps[n];
while (index[n] >= final[n])
{
if (n == 0)
{
index = final;
return false;
}
index[n] = start[n];
--n;
index[n] += jumps[n];
}
return true;
}
/**
* @brief Map the given index through this accessor.
*
* @param[in] index The index to map
*
* @return The mapped index
*/
index_t<Rank> map_index(const index_t<Rank>& index) const
{
auto result = index_t<Rank>();
for (std::size_t n = 0; n < Rank; ++n)
result[n] = start[n] + jumps[n] * index[n];
return result;
}
/**
* @brief Return the index that generates the given mapped index.
*
* @param[in] mapped_index The mapped index
*
* @return A boolean
*/
index_t<Rank> inverse_map_index(const index_t<Rank>& mapped_index) const
{
auto result = index_t<Rank>();
for (std::size_t n = 0; n < Rank; ++n)
result[n] = (mapped_index[n] - start[n]) / jumps[n];
return result;
}
/**
* @brief Return true if this is a valid mapped-from index.
*
* @param[in] index The index possibly mapped from by this access pattern
*
* @return A boolean
*/
bool contains(const index_t<Rank>& index) const
{
return shape().contains(index);
}
template<typename... Args> bool contains(Args... args) const { return contains(make_index(args...)); }
/**
* @brief Return true if an iteration over this accessor would generate
* the given index, that is, if the index is included in the set
* of mapped-to indexes.
*
* @param[in] mapped_index The index possibly mapped to by this access
* pattern
*
* @return A boolean
*/
bool generates(const index_t<Rank>& mapped_index) const
{
for (std::size_t n = 0; n < Rank; ++n)
{
if ((mapped_index[n] < start[n]) ||
(mapped_index[n] >= final[n]) ||
(mapped_index[n] - start[n]) % jumps[n] != 0)
{
return false;
}
}
return true;
}
template<typename... Args>
bool generates(Args... args) const { return generates(make_index(args...)); }
/**
* @brief Return false if this access pattern would generate any
* indexes not contained in the given shape.
*
* @param[in] parent_shape The shape possibly containing an index in this
* access pattern
*
* @return A boolean
*/
bool within(const shape_t<Rank>& parent_shape) const
{
auto zero = make_uniform_index<Rank>(0);
auto t1 = map_index(zero);
auto t2 = map_index(shape().last_index());
return (t1 >= zero && t1 <= parent_shape.last_index() &&
t2 >= zero && t2 <= parent_shape.last_index());
}
//=========================================================================
iterator begin() const { return { *this, start }; }
iterator end() const { return { *this, final }; }
//=========================================================================
index_t<Rank> start = make_uniform_index<Rank>(0);
index_t<Rank> final = make_uniform_index<Rank>(0);
jumps_t<Rank> jumps = make_uniform_jumps<Rank>(1);
};
//=============================================================================
// Shape, index, and access pattern factories
//=============================================================================
template<typename... Args>
auto nd::make_shape(Args... args)
{
return shape_t<sizeof...(Args)>({std::size_t(args)...});
}
template<typename... Args>
auto nd::make_index(Args... args)
{
return index_t<sizeof...(Args)>({std::size_t(args)...});
}
template<typename... Args>
auto nd::make_jumps(Args... args)
{
return jumps_t<sizeof...(Args)>({long(args)...});
}
template<std::size_t Rank, typename Arg>
auto nd::make_uniform_shape(Arg arg)
{
return shape_t<Rank>::uniform(arg);
}
template<std::size_t Rank, typename Arg>
auto nd::make_uniform_index(Arg arg)
{
return index_t<Rank>::uniform(arg);
}
template<std::size_t Rank, typename Arg>
auto nd::make_uniform_jumps(Arg arg)
{
return jumps_t<Rank>::uniform(arg);
}
template<std::size_t Rank>
auto nd::make_strides_row_major(shape_t<Rank> shape)
{
auto result = memory_strides_t<Rank>();
result[Rank - 1] = 1;
if constexpr (Rank > 1)
{
for (int n = Rank - 2; n >= 0; --n)
{
result[n] = result[n + 1] * shape[n + 1];
}
}
return result;
}
template<std::size_t Rank>
auto nd::make_access_pattern(shape_t<Rank> shape)
{
return access_pattern_t<Rank>().with_final(index_t<Rank>::from_range(shape));
}
template<typename... Args>
auto nd::make_access_pattern(Args... args)
{
return access_pattern_t<sizeof...(Args)>().with_final(args...);
}
/**
* @brief Return a sequence of access patterns that cover a shape by
* partitioning it on its first axis.
*
* @param[in] shape The shape to partition
*
* @tparam NumPartitions The number of partitions
* @tparam Rank The shape rank
*
* @return A sequence of access patterns
*/
template<std::size_t NumPartitions, std::size_t Rank>
auto nd::partition_shape(shape_t<Rank> shape)
{
constexpr std::size_t distributed_axis = 0;
auto result = basic_sequence_t<access_pattern_t<Rank>, NumPartitions>();
for (std::size_t n = 0; n < NumPartitions; ++n)
{
auto p = make_access_pattern(shape);
p.start[distributed_axis] = (n + 0) * shape[distributed_axis] / NumPartitions;
p.final[distributed_axis] = (n + 1) * shape[distributed_axis] / NumPartitions;
result[n] = p;
}
return result;
}
//=============================================================================
class nd::axis_selector_t
{
public:
//=========================================================================
axis_selector_t(std::size_t axis_to_select, std::size_t start, std::size_t final, std::size_t jumps, bool is_final_from_the_end)
: axis_to_select(axis_to_select)
, start(start)
, final(final)
, jumps(jumps)
, is_final_from_the_end(is_final_from_the_end) {}
template<typename ArrayType>
auto operator()(ArrayType&& array) const
{
if (axis_to_select >= array.rank())
{
throw std::logic_error("cannot select axis greater than or equal to array rank");
}
auto accessor = make_access_pattern(array.shape());
accessor.start[axis_to_select] = start;
accessor.final[axis_to_select] = is_final_from_the_end ? array.shape(axis_to_select) - final : final;
accessor.jumps[axis_to_select] = jumps;
auto mapping = [accessor, array] (auto index)
{
return array(accessor.map_index(index));
};
return make_array(mapping, accessor.shape());
}
auto from(std::size_t new_start) const
{
return axis_selector_t(axis_to_select, new_start, final, jumps, is_final_from_the_end);
}
auto to(std::size_t new_final) const
{
return axis_selector_t(axis_to_select, start, new_final, jumps, is_final_from_the_end);
}
auto jumping(std::size_t new_jumps) const
{
return axis_selector_t(axis_to_select, start, final, new_jumps, is_final_from_the_end);
}
auto from_the_end() const
{
return axis_selector_t(axis_to_select, start, final, jumps, true);
}
private:
//=========================================================================
std::size_t axis_to_select;
std::size_t start;
std::size_t final;
std::size_t jumps;
bool is_final_from_the_end;
};
//=============================================================================
class nd::axis_shifter_t
{
public:
//=========================================================================
axis_shifter_t(std::size_t axis_to_shift, int delta) : axis_to_shift(axis_to_shift), delta(delta) {}
template<typename ArrayType>
auto operator()(ArrayType&& array) const
{
if (axis_to_shift >= array.rank())
{
throw std::logic_error("cannot shift axis greater than or equal to array rank");
}
if (std::size_t(std::abs(delta)) >= array.shape(axis_to_shift))
{
throw std::logic_error("cannot shift an array by more than its length on that axis");
}
auto mapping = [axis_to_shift=axis_to_shift, delta=delta, array] (auto index)
{
index[axis_to_shift] -= delta;
return array(index);
};
auto shape = array.shape();
shape[axis_to_shift] -= std::abs(delta);
return make_array(mapping, shape);
}
auto along_axis(std::size_t new_axis_to_shift) const
{
return axis_shifter_t(new_axis_to_shift, delta);
}
private:
//=========================================================================
std::size_t axis_to_shift;
int delta;
};
//=============================================================================
template<std::size_t RankDifference>
class nd::axis_freezer_t
{
public:
//=========================================================================
axis_freezer_t(
index_t<RankDifference> axes_to_freeze,
index_t<RankDifference> index_to_freeze_at=make_uniform_index<RankDifference>(0))
: axes_to_freeze(axes_to_freeze)
, index_to_freeze_at(index_to_freeze_at) {}
template<typename PatchArrayType>
auto operator()(PatchArrayType array) const
{
for (auto a : axes_to_freeze)
if (a >= array.rank())
throw std::logic_error("cannot freeze axis greater than or equal to array rank");
auto mapping = [axes_to_freeze=axes_to_freeze, index_to_freeze_at=index_to_freeze_at, array] (auto&& index)
{
return array(index.insert_elements(axes_to_freeze, index_to_freeze_at));
};
auto shape = array.shape().remove_elements(axes_to_freeze);
return make_array(mapping, shape);
}
auto at_index(index_t<RankDifference> new_index_to_freeze_at) const
{
return axis_freezer_t(axes_to_freeze, new_index_to_freeze_at);
}
template<typename... Args>
auto at_index(Args... new_index_to_freeze_at) const
{
static_assert(sizeof...(Args) == RankDifference);
return at_index(make_index(new_index_to_freeze_at...));
}
private:
//=========================================================================
index_t<RankDifference> axes_to_freeze;
index_t<RankDifference> index_to_freeze_at;
};
//=============================================================================
template<typename OperatorType>
class nd::axis_reducer_t
{
public:
//=========================================================================
axis_reducer_t(std::size_t axis_to_reduce, OperatorType the_operator)
: axis_to_reduce(axis_to_reduce)
, the_operator(the_operator) {}
template<typename ArrayType>
auto operator()(ArrayType array) const
{
if (axis_to_reduce >= array.rank())
{
throw std::logic_error("cannot reduce axis greater than or equal to array rank");
}
constexpr std::size_t R = ArrayType::array_rank;
auto mapping = [the_operator=the_operator, axis_to_reduce=axis_to_reduce, array] (auto&& index)
{
auto axes_to_freeze = index_t<R>::range().remove_elements(make_index(axis_to_reduce));
auto freezer = axis_freezer_t<R - 1>(axes_to_freeze).at_index(index);
return the_operator(freezer(array));
};
auto shape = array.shape().remove_elements(make_index(axis_to_reduce));