Repository navigation
Expand file tree
/
Copy pathiteration.d
More file actions
4519 lines (3991 loc) · 111 KB
/
Copy pathiteration.d
File metadata and controls
4519 lines (3991 loc) · 111 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
// Written in the D programming language.
/**
This module contains generic _iteration algorithms.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE $(H2 Function),
$(TR $(TH Function Name) $(TH Description))
$(T2 all, Checks if all elements satisfy to a predicate.)
$(T2 any, Checks if at least one element satisfy to a predicate.)
$(T2 cmp, Compares two slices.)
$(T2 count, Counts elements in a slices according to a predicate.)
$(T2 each, Iterates elements.)
$(T2 eachLower, Iterates lower triangle of matrix.)
$(T2 eachOnBorder, Iterates elementes on tensors borders and corners.)
$(T2 eachUploPair, Iterates upper and lower pairs of elements in square matrix.)
$(T2 eachUpper, Iterates upper triangle of matrix.)
$(T2 equal, Compares two slices for equality.)
$(T2 filter, Filters elements in a range or an ndslice.)
$(T2 find, Finds backward index.)
$(T2 findIndex, Finds index.)
$(T2 fold, Accumulates all elements (different parameter order than `reduce`).)
$(T2 isSymmetric, Checks if the matrix is symmetric.)
$(T2 maxElement, Returns the maximum.)
$(T2 maxIndex, Finds index of the maximum.)
$(T2 maxPos, Finds backward index of the maximum.)
$(T2 minElement, Returns the minimum.)
$(T2 minIndex, Finds index of the minimum.)
$(T2 minmaxIndex, Finds indices of the minimum and the maximum.)
$(T2 minmaxPos, Finds backward indices of the minimum and the maximum.)
$(T2 minPos, Finds backward index of the minimum.)
$(T2 nBitsToCount, Сount bits until set bit count is reached.)
$(T2 reduce, Accumulates all elements.)
$(T2 Chequer, Chequer color selector to work with $(LREF each) .)
$(T2 uniq, Iterates over the unique elements in a range or an ndslice, which is assumed sorted.)
)
Transform function is represented by $(NDSLICEREF topology, map).
All operators are suitable to change slices using `ref` argument qualification in a function declaration.
Note, that string lambdas in Mir are `auto ref` functions.
License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Copyright: 2020 Ilia Ki, Kaleidic Associates Advisory Limited, Symmetry Investments
Authors: Ilia Ki, John Michael Hall, Andrei Alexandrescu (original Phobos code)
License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Copyright: 2020 Ilia Ki, Kaleidic Associates Advisory Limited, Symmetry Investments
Authors: , Ilia Ki (Mir & BetterC rework).
Source: $(PHOBOSSRC std/algorithm/_iteration.d)
Macros:
NDSLICEREF = $(REF_ALTTEXT $(TT $2), $2, mir, ndslice, $1)$(NBSP)
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
*/
module mir.algorithm.iteration;
import mir.functional: naryFun;
import mir.internal.utility;
import mir.math.common: fmamath;
import mir.ndslice.field: BitField;
import mir.ndslice.internal;
import mir.ndslice.iterator: FieldIterator, RetroIterator;
import mir.ndslice.slice;
import mir.primitives;
import mir.qualifier;
import std.meta;
import std.traits;
/++
Chequer color selector to work with $(LREF each)
+/
enum Chequer : bool
{
/// Main diagonal color
black,
/// First sub-diagonal color
red,
}
///
version(mir_test) unittest
{
import mir.ndslice.allocation: slice;
auto s = [5, 4].slice!int;
Chequer.black.each!"a = 1"(s);
assert(s == [
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
]);
Chequer.red.each!((ref b) => b = 2)(s);
assert(s == [
[1, 2, 1, 2],
[2, 1, 2, 1],
[1, 2, 1, 2],
[2, 1, 2, 1],
[1, 2, 1, 2],
]);
}
@fmamath:
/+
Bitslice representation for accelerated bitwise algorithm.
1-dimensional contiguousitslice can be split into three chunks: head bits, body chunks, and tail bits.
Bitslice can have head bits because it has slicing and the zero bit may not be aligned to the zero of a body chunk.
+/
private struct BitSliceAccelerator(Field, I = typeof(Field.init[size_t.init]))
if (__traits(isUnsigned, I))
{
import mir.bitop;
import mir.qualifier: lightConst;
import mir.ndslice.traits: isIterator;
import mir.ndslice.iterator: FieldIterator;
import mir.ndslice.field: BitField;
///
alias U = typeof(I.init + 1u);
/// body bits chunks
static if (isIterator!Field)
Slice!Field bodyChunks;
else
Slice!(FieldIterator!Field) bodyChunks;
/// head length
int headLength;
/// tail length
int tailLength;
@fmamath:
this(Slice!(FieldIterator!(BitField!(Field, I))) slice)
{
enum mask = bitShiftMask!I;
enum shift = bitElemShift!I;
size_t length = slice.length;
size_t index = slice._iterator._index;
if (auto hlen = index & mask)
{
auto l = I.sizeof * 8 - hlen;
if (l > length)
{
// central problem
headLength = -cast(int) length;
tailLength = cast(int) hlen;
goto F;
}
else
{
headLength = cast(uint) l;
length -= l;
index += l;
}
}
tailLength = cast(int) (length & mask);
F:
length >>= shift;
index >>= shift;
bodyChunks._lengths[0] = length;
static if (isIterator!Field)
{
bodyChunks._iterator = slice._iterator._field._field;
bodyChunks._iterator += index;
}
else
{
bodyChunks._iterator._index = index;
bodyChunks._iterator._field = slice._iterator._field._field;
}
}
scope const:
bool isCentralProblem()
{
return headLength < 0;
}
U centralBits()
{
assert(isCentralProblem);
return *bodyChunks._iterator.lightConst >>> tailLength;
}
uint centralLength()
{
assert(isCentralProblem);
return -headLength;
}
/// head bits (last `headLength` bits are valid).
U headBits()
{
assert(!isCentralProblem);
if (headLength == 0)
return U.init;
static if (isIterator!Field)
return bodyChunks._iterator.lightConst[-1];
else
return bodyChunks._iterator._field.lightConst[bodyChunks._iterator._index - 1];
}
/// tail bits (first `tailLength` bits are valid).
U tailBits()
{
assert(!isCentralProblem);
if (tailLength == 0)
return U.init;
static if (isIterator!Field)
return bodyChunks._iterator.lightConst[bodyChunks.length];
else
return bodyChunks._iterator._field.lightConst[bodyChunks._iterator._index + bodyChunks.length];
}
U negCentralMask()
{
return U.max << centralLength;
}
U negHeadMask()
{
return U.max << headLength;
}
U negTailMask()
{
return U.max << tailLength;
}
U negCentralMaskS()
{
return U.max >> centralLength;
}
U negHeadMaskS()
{
return U.max >> headLength;
}
U negTailMaskS()
{
return U.max >> tailLength;
}
U centralBitsWithRemainingZeros()
{
return centralBits & ~negCentralMask;
}
U centralBitsWithRemainingZerosS()
{
return centralBits << (U.sizeof * 8 - centralLength);
}
U headBitsWithRemainingZeros()
{
return headBits >>> (I.sizeof * 8 - headLength);
}
U headBitsWithRemainingZerosS()
{
static if (U.sizeof > I.sizeof)
return (headBits << (U.sizeof - I.sizeof) * 8) & ~negTailMaskS;
else
return headBits & ~negTailMaskS;
}
U tailBitsWithRemainingZeros()
{
return tailBits & ~negTailMask;
}
U tailBitsWithRemainingZerosS()
{
return tailBits << (U.sizeof * 8 - tailLength);
}
U centralBitsWithRemainingOnes()
{
return centralBits | negCentralMask;
}
U centralBitsWithRemainingOnesS()
{
return centralBitsWithRemainingZerosS | negCentralMaskS;
}
U headBitsWithRemainingOnes()
{
return headBitsWithRemainingZeros | negHeadMask;
}
U headBitsWithRemainingOnesS()
{
return headBitsWithRemainingZerosS | negHeadMaskS;
}
U tailBitsWithRemainingOnes()
{
return tailBits | negTailMask;
}
U tailBitsWithRemainingOnesS()
{
return tailBitsWithRemainingZerosS | negTailMaskS;
}
size_t ctpop()
{
import mir.bitop: ctpop;
if (isCentralProblem)
return centralBitsWithRemainingZeros.ctpop;
size_t ret;
if (headLength)
ret = cast(size_t) headBitsWithRemainingZeros.ctpop;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
ret += cast(size_t) bc.front.ctpop;
bc.popFront;
}
while(bc.length);
}
if (tailBits)
ret += cast(size_t) tailBitsWithRemainingZeros.ctpop;
return ret;
}
bool any()
{
if (isCentralProblem)
return centralBitsWithRemainingZeros != 0;
if (headBitsWithRemainingZeros != 0)
return true;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
if (bc.front != 0)
return true;
bc.popFront;
}
while(bc.length);
}
if (tailBitsWithRemainingZeros != 0)
return true;
return false;
}
bool all()
{
if (isCentralProblem)
return centralBitsWithRemainingOnes != U.max;
size_t ret;
if (headBitsWithRemainingOnes != U.max)
return false;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
if (bc.front != I.max)
return false;
bc.popFront;
}
while(bc.length);
}
if (tailBitsWithRemainingOnes != U.max)
return false;
return true;
}
size_t cttz()
{
U v;
size_t ret;
if (isCentralProblem)
{
v = centralBitsWithRemainingOnes;
if (v)
goto R;
ret = centralLength;
goto L;
}
v = headBitsWithRemainingOnes;
if (v)
goto R;
ret = headLength;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
v = bc.front;
if (v)
goto R;
ret += I.sizeof * 8;
bc.popFront;
}
while(bc.length);
}
v = tailBitsWithRemainingOnes;
if (v)
goto R;
ret += tailLength;
goto L;
R:
ret += v.cttz;
L:
return ret;
}
size_t ctlz()
{
U v;
size_t ret;
if (isCentralProblem)
{
v = centralBitsWithRemainingOnes;
if (v)
goto R;
ret = centralLength;
goto L;
}
v = tailBitsWithRemainingOnesS;
if (v)
goto R;
ret = tailLength;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
v = bc.back;
if (v)
goto R;
ret += I.sizeof * 8;
bc.popBack;
}
while(bc.length);
}
v = headBitsWithRemainingOnesS;
if (v)
goto R;
ret += headLength;
goto L;
R:
ret += v.ctlz;
L:
return ret;
}
sizediff_t nBitsToCount(size_t count)
{
pragma(inline, false);
size_t ret;
if (count == 0)
return count;
U v, cnt;
if (isCentralProblem)
{
v = centralBitsWithRemainingZeros;
goto E;
}
v = headBitsWithRemainingZeros;
cnt = v.ctpop;
if (cnt >= count)
goto R;
ret += headLength;
count -= cast(size_t) cnt;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
v = bc.front;
cnt = v.ctpop;
if (cnt >= count)
goto R;
ret += I.sizeof * 8;
count -= cast(size_t) cnt;
bc.popFront;
}
while(bc.length);
}
v = tailBitsWithRemainingZeros;
E:
cnt = v.ctpop;
if (cnt >= count)
goto R;
return -1;
R:
return ret + v.nTrailingBitsToCount(count);
}
sizediff_t retroNBitsToCount(size_t count)
{
if (count == 0)
return count;
size_t ret;
U v, cnt;
if (isCentralProblem)
{
v = centralBitsWithRemainingZerosS;
goto E;
}
v = tailBitsWithRemainingZerosS;
cnt = v.ctpop;
if (cnt >= count)
goto R;
ret += tailLength;
count -= cast(size_t) cnt;
if (bodyChunks.length)
{
auto bc = bodyChunks.lightConst;
do
{
v = bc.back;
cnt = v.ctpop;
if (cnt >= count)
goto R;
ret += I.sizeof * 8;
count -= cast(size_t) cnt;
bc.popBack;
}
while(bc.length);
}
v = headBitsWithRemainingZerosS;
E:
cnt = v.ctpop;
if (cnt >= count)
goto R;
return -1;
R:
return ret + v.nLeadingBitsToCount(count);
}
}
/++
Сount bits until set bit count is reached. Works with ndslices created with $(REF bitwise, mir,ndslice,topology), $(REF bitSlice, mir,ndslice,allocation).
Returns: bit count if set bit count is reached or `-1` otherwise.
+/
sizediff_t nBitsToCount(Field, I)(Slice!(FieldIterator!(BitField!(Field, I))) bitSlice, size_t count)
{
return BitSliceAccelerator!(Field, I)(bitSlice).nBitsToCount(count);
}
///ditto
sizediff_t nBitsToCount(Field, I)(Slice!(RetroIterator!(FieldIterator!(BitField!(Field, I)))) bitSlice, size_t count)
{
import mir.ndslice.topology: retro;
return BitSliceAccelerator!(Field, I)(bitSlice.retro).retroNBitsToCount(count);
}
/++
Сount bits starting from the end until set bit count is reached. Works with ndslices created with $(REF bitwise, mir,ndslice,topology), $(REF bitSlice, mir,ndslice,allocation).
Returns: bit count if set bit count is reached or `-1` otherwise.
+/
sizediff_t retroNBitsToCount(Field, I)(Slice!(FieldIterator!(BitField!(Field, I))) bitSlice, size_t count)
{
return BitSliceAccelerator!(Field, I)(bitSlice).retroNBitsToCount(count);
}
///ditto
sizediff_t retroNBitsToCount(Field, I)(Slice!(RetroIterator!(FieldIterator!(BitField!(Field, I)))) bitSlice, size_t count)
{
import mir.ndslice.topology: retro;
return BitSliceAccelerator!(Field, I)(bitSlice.retro).nBitsToCount(count);
}
///
version(mir_test)
pure unittest
{
import mir.ndslice.allocation: bitSlice;
import mir.ndslice.topology: retro;
auto s = bitSlice(1000);
s[50] = true;
s[100] = true;
s[200] = true;
s[300] = true;
s[400] = true;
assert(s.nBitsToCount(4) == 301);
assert(s.retro.nBitsToCount(4) == 900);
}
private void checkShapesMatch(
string fun = __FUNCTION__,
string pfun = __PRETTY_FUNCTION__,
Slices...)
(Slices slices)
if (Slices.length > 1)
{
enum msgShape = "all slices must have the same shape" ~ tailErrorMessage!(fun, pfun);
enum N = slices[0].shape.length;
foreach (i, Slice; Slices)
{
static if (i == 0)
continue;
else
static if (slices[i].shape.length == N)
assert(slices[i].shape == slices[0].shape, msgShape);
else
{
import mir.ndslice.fuse: fuseShape;
static assert(slices[i].fuseShape.length >= N);
assert(cast(size_t[N])slices[i].fuseShape[0 .. N] == slices[0].shape, msgShape);
}
}
}
package(mir) template allFlattened(args...)
{
static if (args.length)
{
alias arg = args[0];
@fmamath @property allFlattenedMod()()
{
import mir.ndslice.topology: flattened;
return flattened(arg);
}
alias allFlattened = AliasSeq!(allFlattenedMod, allFlattened!(args[1..$]));
}
else
alias allFlattened = AliasSeq!();
}
private template areAllContiguousSlices(Slices...)
{
import mir.ndslice.traits: isContiguousSlice;
static if (allSatisfy!(isContiguousSlice, Slices))
enum areAllContiguousSlices = Slices[0].N > 1 && areAllContiguousSlicesImpl!(Slices[0].N, Slices[1 .. $]);
else
enum areAllContiguousSlices = false;
}
private template areAllContiguousSlicesImpl(size_t N, Slices...)
{
static if (Slices.length == 0)
enum areAllContiguousSlicesImpl = true;
else
enum areAllContiguousSlicesImpl = Slices[0].N == N && areAllContiguousSlicesImpl!(N, Slices[1 .. $]);
}
version(LDC) {}
else version(GNU) {}
else version (Windows) {}
else version (X86_64)
{
//Compiling with DMD for x86-64 for Linux & OS X with optimizations enabled,
//"Tensor mutation on-the-fly" unittest was failing. Disabling inlining
//caused it to succeed.
//TODO: Rework so this is unnecessary!
version = Mir_disable_inlining_in_reduce;
}
version(Mir_disable_inlining_in_reduce)
{
private enum Mir_disable_inlining_in_reduce = true;
private template _naryAliases(size_t n)
{
static if (n == 0)
enum _naryAliases = "";
else
{
enum i = n - 1;
enum _naryAliases = _naryAliases!i ~ "alias " ~ cast(char)('a' + i) ~ " = args[" ~ i.stringof ~ "];\n";
}
}
private template nonInlinedNaryFun(alias fun)
{
import mir.math.common : fmamath;
static if (is(typeof(fun) : string))
{
/// Specialization for string lambdas
@fmamath auto ref nonInlinedNaryFun(Args...)(auto ref Args args)
if (args.length <= 26)
{
pragma(inline,false);
mixin(_naryAliases!(Args.length));
return mixin(fun);
}
}
else static if (is(typeof(fun.opCall) == function))
{
@fmamath auto ref nonInlinedNaryFun(Args...)(auto ref Args args)
if (is(typeof(fun.opCall(args))))
{
pragma(inline,false);
return fun.opCall(args);
}
}
else
{
@fmamath auto ref nonInlinedNaryFun(Args...)(auto ref Args args)
if (is(typeof(fun(args))))
{
pragma(inline,false);
return fun(args);
}
}
}
}
else
{
private enum Mir_disable_inlining_in_reduce = false;
}
S reduceImpl(alias fun, S, Slices...)(S seed, Slices slices)
{
do
{
static if (DimensionCount!(Slices[0]) == 1)
mixin(`seed = fun(seed,` ~ frontOf!(Slices.length) ~ `);`);
else
mixin(`seed = .reduceImpl!fun(seed,` ~ frontOf!(Slices.length) ~ `);`);
foreach_reverse(ref slice; slices)
slice.popFront;
}
while(!slices[0].empty);
return seed;
}
/++
Implements the homonym function (also known as `accumulate`,
`compress`, `inject`, or `fold`) present in various programming
languages of functional flavor. The call `reduce!(fun)(seed, slice1, ..., sliceN)`
first assigns `seed` to an internal variable `result`,
also called the accumulator. Then, for each set of element `x1, ..., xN` in
`slice1, ..., sliceN`, `result = fun(result, x1, ..., xN)` gets evaluated. Finally,
`result` is returned.
`reduce` allows to iterate multiple slices in the lockstep.
Note:
$(NDSLICEREF topology, pack) can be used to specify dimensions.
Params:
fun = A function.
See_Also:
$(HTTP llvm.org/docs/LangRef.html#fast-math-flags, LLVM IR: Fast Math Flags)
$(HTTP en.wikipedia.org/wiki/Fold_(higher-order_function), Fold (higher-order function))
+/
template reduce(alias fun)
{
import mir.functional: naryFun;
static if (__traits(isSame, naryFun!fun, fun)
&& !Mir_disable_inlining_in_reduce)
/++
Params:
seed = An initial accumulation value.
slices = One or more slices, range, and arrays.
Returns:
the accumulated `result`
+/
@fmamath auto reduce(S, Slices...)(S seed, Slices slices)
if (Slices.length)
{
static if (Slices.length > 1)
slices.checkShapesMatch;
static if (areAllContiguousSlices!Slices)
{
import mir.ndslice.topology: flattened;
return .reduce!fun(seed, allFlattened!(allLightScope!slices));
}
else
{
if (slices[0].anyEmpty)
return cast(Unqual!S) seed;
static if (is(S : Unqual!S))
alias UT = Unqual!S;
else
alias UT = S;
return reduceImpl!(fun, UT, Slices)(seed, allLightScope!slices);
}
}
else version(Mir_disable_inlining_in_reduce)
//As above, but with inlining disabled.
@fmamath auto reduce(S, Slices...)(S seed, Slices slices)
if (Slices.length)
{
static if (Slices.length > 1)
slices.checkShapesMatch;
static if (areAllContiguousSlices!Slices)
{
import mir.ndslice.topology: flattened;
return .reduce!fun(seed, allFlattened!(allLightScope!slices));
}
else
{
if (slices[0].anyEmpty)
return cast(Unqual!S) seed;
static if (is(S : Unqual!S))
alias UT = Unqual!S;
else
alias UT = S;
return reduceImpl!(nonInlinedNaryFun!fun, UT, Slices)(seed, allLightScope!slices);
}
}
else
alias reduce = .reduce!(naryFun!fun);
}
/// Ranges and arrays
version(mir_test)
unittest
{
auto ar = [1, 2, 3];
auto s = 0.reduce!"a + b"(ar);
assert (s == 6);
}
/// Single slice
version(mir_test)
unittest
{
import mir.ndslice.topology : iota;
//| 0 1 2 | => 3 |
//| 3 4 5 | => 12 | => 15
auto sl = iota(2, 3);
// sum of all element in the slice
auto res = size_t(0).reduce!"a + b"(sl);
assert(res == 15);
}
/// Multiple slices, dot product
version(mir_test)
unittest
{
import mir.ndslice.allocation : slice;
import mir.ndslice.topology : as, iota;
//| 0 1 2 |
//| 3 4 5 |
auto a = iota([2, 3], 0).as!double.slice;
//| 1 2 3 |
//| 4 5 6 |
auto b = iota([2, 3], 1).as!double.slice;
alias dot = reduce!"a + b * c";
auto res = dot(0.0, a, b);
// check the result:
import mir.ndslice.topology : flattened;
import std.numeric : dotProduct;
assert(res == dotProduct(a.flattened, b.flattened));
}
/// Zipped slices, dot product
pure
version(mir_test) unittest
{
import std.typecons : Yes;
import std.numeric : dotProduct;
import mir.ndslice.allocation : slice;
import mir.ndslice.topology : as, iota, zip, universal;
import mir.math.common : fmamath;
static @fmamath T fmuladd(T, Z)(const T a, Z z)
{
return a + z.a * z.b;
}
// 0 1 2
// 3 4 5
auto sl1 = iota(2, 3).as!double.slice.universal;
// 1 2 3
// 4 5 6
auto sl2 = iota([2, 3], 1).as!double.slice;
// slices must have the same strides for `zip!true`.
assert(sl1.strides == sl2.strides);
auto z = zip!true(sl1, sl2);
auto dot = reduce!fmuladd(0.0, z);
assert(dot == dotProduct(iota(6), iota([6], 1)));
}
/// Tensor mutation on-the-fly
version(mir_test)
unittest
{
import mir.ndslice.allocation : slice;
import mir.ndslice.topology : as, iota;
import mir.math.common : fmamath;
static @fmamath T fun(T)(const T a, ref T b)
{
return a + b++;
}
//| 0 1 2 |
//| 3 4 5 |
auto sl = iota(2, 3).as!double.slice;
auto res = reduce!fun(double(0), sl);
assert(res == 15);
//| 1 2 3 |
//| 4 5 6 |
assert(sl == iota([2, 3], 1));
}
/++
Packed slices.
Computes minimum value of maximum values for each row.
+/
version(mir_test)
unittest
{
import mir.math.common;
import mir.ndslice.allocation : slice;
import mir.ndslice.dynamic : transposed;
import mir.ndslice.topology : as, iota, pack, map, universal;
alias maxVal = (a) => reduce!fmax(-double.infinity, a);
alias minVal = (a) => reduce!fmin(double.infinity, a);
alias minimaxVal = (a) => minVal(a.pack!1.map!maxVal);
auto sl = iota(2, 3).as!double.slice;
// Vectorized computation: row stride equals 1.
//| 0 1 2 | => | 2 |
//| 3 4 5 | => | 5 | => 2
auto res = minimaxVal(sl);
assert(res == 2);
// Common computation: row stride does not equal 1.
//| 0 1 2 | | 0 3 | => | 3 |
//| 3 4 5 | => | 1 4 | => | 4 |
// | 2 5 | => | 5 | => 3
auto resT = minimaxVal(sl.universal.transposed);
assert(resT == 3);
}
/// Dlang Range API support.
version(mir_test)
unittest
{
import mir.algorithm.iteration: each;
import std.range: phobos_iota = iota;
int s;
// 0 1 2 3
4.phobos_iota.each!(i => s += i);
assert(s == 6);
}
@safe pure nothrow @nogc
version(mir_test) unittest
{
import mir.ndslice.topology : iota;
auto a = reduce!"a + b"(size_t(7), iota([0, 1], 1));
assert(a == 7);
}
void eachImpl(alias fun, Slices...)(Slices slices)
{
foreach(ref slice; slices)
assert(!slice.empty);
do
{
static if (DimensionCount!(Slices[0]) == 1)
mixin(`fun(`~ frontOf!(Slices.length) ~ `);`);
else
.eachImpl!fun(frontOf2!slices);
foreach_reverse(i; Iota!(Slices.length))
slices[i].popFront;
}
while(!slices[0].empty);
}
void chequerEachImpl(alias fun, Slices...)(Chequer color, Slices slices)
{
foreach(ref slice; slices)
assert(!slice.empty);
static if (DimensionCount!(Slices[0]) == 1)
{
if (color)
{
foreach_reverse(i; Iota!(Slices.length))
slices[i].popFront;