forked from SciSharp/NumSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShape.cs
More file actions
1417 lines (1214 loc) · 51.9 KB
/
Shape.cs
File metadata and controls
1417 lines (1214 loc) · 51.9 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using NumSharp.Utilities;
namespace NumSharp
{
/// <summary>
/// Represents a shape of an N-D array.
/// </summary>
/// <remarks>Handles slicing, indexing based on coordinates or linear offset and broadcastted indexing.</remarks>
public partial struct Shape : ICloneable, IEquatable<Shape>
{
internal ViewInfo ViewInfo;
internal BroadcastInfo BroadcastInfo;
/// <summary>
/// Does this Shape have modified strides, usually in scenarios like np.transpose.
/// </summary>
public bool ModifiedStrides;
/// <summary>
/// True if the shape of this array was obtained by a slicing operation that caused the underlying data to be non-contiguous
/// </summary>
public readonly bool IsSliced
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ViewInfo != null;
}
/// <summary>
/// Does this Shape represents a non-sliced and non-broadcasted hence contagious unmanaged memory?
/// </summary>
public readonly bool IsContiguous
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => !IsSliced && !IsBroadcasted;
}
/// <summary>
/// Is this Shape a recusive view? (deeper than 1 view)
/// </summary>
public readonly bool IsRecursive
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ViewInfo != null && ViewInfo.ParentShape.IsEmpty == false;
}
/// <summary>
/// Dense data are stored contiguously in memory, addressed by a single index (the memory address). <br></br>
/// Array memory ordering schemes translate that single index into multiple indices corresponding to the array coordinates.<br></br>
/// 0: Row major<br></br>
/// 1: Column major
/// </summary>
internal const char layout = 'C';
internal int _hashCode;
internal int size;
internal int[] dimensions;
internal int[] strides;
/// <summary>
/// Is this shape a broadcast and/or has modified strides?
/// </summary>
public readonly bool IsBroadcasted => BroadcastInfo != null;
/// <summary>
/// Is this shape a scalar? (<see cref="NDim"/>==0 && <see cref="size"/> == 1)
/// </summary>
public bool IsScalar;
/// <summary>
/// True if the shape is not initialized.
/// Note: A scalar shape is not empty.
/// </summary>
public readonly bool IsEmpty => _hashCode == 0;
public readonly char Order => layout;
/// <summary>
/// Singleton instance of a <see cref="Shape"/> that represents a scalar.
/// </summary>
public static readonly Shape Scalar = new Shape(new int[0]);
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar() =>
new Shape(new int[0]);
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar(ViewInfo viewInfo) =>
new Shape(new int[0]) {ViewInfo = viewInfo};
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar(ViewInfo viewInfo, BroadcastInfo broadcastInfo) =>
new Shape(new int[0]) {ViewInfo = viewInfo, BroadcastInfo = broadcastInfo};
/// <summary>
/// Create a shape that represents a vector.
/// </summary>
/// <remarks>Faster than calling Shape's constructor</remarks>
public static Shape Vector(int length)
{
var shape = new Shape {dimensions = new int[] {length}, strides = new int[] {1}, size = length};
shape._hashCode = ( /*shape.layout*/ layout * 397) ^ (length * 397) * (length * 397);
return shape;
}
/// <summary>
/// Create a shape that represents a vector.
/// </summary>
/// <remarks>Faster than calling Shape's constructor</remarks>
public static Shape Vector(int length, ViewInfo viewInfo)
{
var shape = new Shape
{
dimensions = new[] {length},
strides = new int[] {1},
//layout = 'C',
size = length,
ViewInfo = viewInfo
};
shape._hashCode = ( /*shape.layout*/ layout * 397) ^ (length * 397) * (length * 397);
return shape;
}
/// <summary>
/// Create a shape that represents a matrix.
/// </summary>
/// <remarks>Faster than calling Shape's constructor</remarks>
public static Shape Matrix(int rows, int cols)
{
var shape = new Shape {dimensions = new[] {rows, cols}, strides = new int[] {cols, 1}, size = rows * cols};
unchecked
{
int hash = ( /*shape.layout*/ layout * 397);
int size = 1;
foreach (var v in shape.dimensions)
{
size *= v;
hash ^= (size * 397) * (v * 397);
}
shape._hashCode = hash;
}
shape.IsScalar = false;
return shape;
}
public readonly int NDim
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => dimensions.Length;
}
public readonly int[] Dimensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => dimensions;
}
public readonly int[] Strides
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => strides;
}
/// <summary>
/// The linear size of this shape.
/// </summary>
public readonly int Size
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => size;
}
public Shape(Shape other)
{
if (other.IsEmpty)
{
this = default;
return;
}
//this.layout = other.layout;
this._hashCode = other._hashCode;
this.size = other.size;
this.dimensions = (int[])other.dimensions.Clone();
this.strides = (int[])other.strides.Clone();
this.IsScalar = other.IsScalar;
this.ViewInfo = other.ViewInfo?.Clone();
this.BroadcastInfo = other.BroadcastInfo?.Clone();
this.ModifiedStrides = other.ModifiedStrides;
}
public Shape(int[] dims, int[] strides)
{
if (dims == null)
throw new ArgumentNullException(nameof(dims));
if (strides == null)
throw new ArgumentNullException(nameof(strides));
if (dims.Length != strides.Length)
throw new ArgumentException($"While trying to construct a shape, given dimensions and strides does not match size ({dims.Length} != {strides.Length})");
//layout = 'C';
size = 1;
unchecked
{
//calculate hash and size
if (dims.Length > 0)
{
int hash = (layout * 397);
foreach (var v in dims)
{
size *= v;
hash ^= (size * 397) * (v * 397);
}
_hashCode = hash;
}
else
_hashCode = 0;
}
this.strides = strides;
this.dimensions = dims;
IsScalar = size == 1 && dims.Length == 0;
ViewInfo = null;
BroadcastInfo = null;
ModifiedStrides = false;
}
public Shape(int[] dims, int[] strides, Shape originalShape)
{
if (dims == null)
throw new ArgumentNullException(nameof(dims));
if (strides == null)
throw new ArgumentNullException(nameof(strides));
if (dims.Length != strides.Length)
throw new ArgumentException($"While trying to construct a shape, given dimensions and strides does not match size ({dims.Length} != {strides.Length})");
//layout = 'C';
size = 1;
unchecked
{
//calculate hash and size
if (dims.Length > 0)
{
int hash = (layout * 397);
foreach (var v in dims)
{
size *= v;
hash ^= (size * 397) * (v * 397);
}
_hashCode = hash;
}
else
_hashCode = 0;
}
this.strides = strides;
this.dimensions = dims;
IsScalar = size == 1 && dims.Length == 0;
ViewInfo = null;
BroadcastInfo = new BroadcastInfo() {OriginalShape = originalShape};
ModifiedStrides = false;
}
[MethodImpl((MethodImplOptions)512)]
public Shape(params int[] dims)
{
if (dims == null)
{
strides = dims = dimensions = new int[0];
}
else
{
dimensions = dims;
strides = new int[dims.Length];
}
unchecked
{
size = 1;
//layout = 'C';
if (dims.Length > 0)
{
int hash = (layout * 397);
foreach (var v in dims)
{
size *= v;
hash ^= (size * 397) * (v * 397);
}
_hashCode = hash;
}
else
_hashCode = int.MinValue; //scalar's hashcode is int.minvalue
if (dims.Length != 0)
{
strides[strides.Length - 1] = 1;
for (int i = strides.Length - 1; i >= 1; i--)
strides[i - 1] = strides[i] * dims[i];
}
}
IsScalar = _hashCode == int.MinValue;
ViewInfo = null;
BroadcastInfo = null;
ModifiedStrides = false;
}
/// <summary>
/// An empty shape without any fields set except all are default.
/// </summary>
/// <remarks>Used internally.</remarks>
[MethodImpl((MethodImplOptions)768)]
public static Shape Empty(int ndim)
{
return new Shape {dimensions = new int[ndim], strides = new int[ndim]};
//default vals already sets: ret.layout = 0;
//default vals already sets: ret.size = 0;
//default vals already sets: ret._hashCode = 0;
//default vals already sets: ret.IsScalar = false;
//default vals already sets: ret.ViewInfo = null;
}
[MethodImpl((MethodImplOptions)768)]
private readonly void _computeStrides()
{
if (dimensions.Length == 0)
return;
unchecked
{
strides[strides.Length - 1] = 1;
for (int idx = strides.Length - 1; idx >= 1; idx--)
strides[idx - 1] = strides[idx] * dimensions[idx];
}
}
[MethodImpl((MethodImplOptions)768)]
private readonly void _computeStrides(int axis)
{
if (dimensions.Length == 0)
return;
if (axis == 0)
strides[0] = strides[1] * dimensions[1];
else
unchecked
{
if (axis == strides.Length - 1)
strides[strides.Length - 1] = 1;
else
strides[axis - 1] = strides[axis] * dimensions[axis];
}
}
public readonly int this[int dim]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => dimensions[dim < 0 ? dimensions.Length + dim : dim];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => dimensions[dim < 0 ? dimensions.Length + dim : dim] = value;
}
/// <summary>
/// Retrieve the transformed offset if <see cref="IsSliced"/> is true, otherwise returns <paramref name="offset"/>.
/// </summary>
/// <param name="offset">The offset within the bounds of <see cref="size"/>.</param>
/// <returns>The transformed offset.</returns>
/// <remarks>Avoid using unless it is unclear if shape is sliced or not.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int TransformOffset(int offset)
{
// ReSharper disable once ConvertIfStatementToReturnStatement
if (ViewInfo == null && BroadcastInfo == null)
return offset;
return GetOffset(GetCoordinates(offset));
}
/// <summary>
/// Get offset index out of coordinate indices.
///
/// The offset is the absolute offset in memory for the given coordinates.
/// Even for shapes that were sliced and reshaped after slicing and sliced again (and so forth)
/// this returns the absolute memory offset.
///
/// Note: the inverse operation to this is GetCoordinatesFromAbsoluteIndex
/// </summary>
/// <param name="indices">The coordinates to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
public readonly int GetOffset(params int[] indices)
{
int offset;
if (!IsSliced)
{
if (dimensions.Length == 0 && indices.Length == 1)
return indices[0];
offset = 0;
unchecked
{
for (int i = 0; i < indices.Length; i++)
offset += strides[i] * indices[i];
}
if (IsBroadcasted)
return offset % BroadcastInfo.OriginalShape.size;
return offset;
}
//if both sliced and broadcasted
if (IsBroadcasted)
return GetOffset_broadcasted(indices);
// we are dealing with a slice
var vi = ViewInfo;
if (IsRecursive && vi.Slices == null)
{
// we are dealing with an unsliced recursively reshaped slice
offset = GetOffset_IgnoreViewInfo(indices);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(indices);
if (vi.UnreducedShape.IsScalar && indices.Length == 1 && indices[0] == 0 && !IsRecursive)
return 0;
if (indices.Length > vi.UnreducedShape.dimensions.Length)
throw new ArgumentOutOfRangeException(nameof(indices), $"select has too many coordinates for this shape");
var orig_ndim = vi.OriginalShape.NDim;
if (orig_ndim > NDim && orig_ndim > indices.Length)
{
// fill in reduced dimensions in the provided coordinates
for (int i = 0; i < vi.OriginalShape.NDim; i++)
{
var slice = ViewInfo.Slices[i];
if (slice.IsIndex)
coords.Insert(i, 0);
if (coords.Count == orig_ndim)
break;
}
}
var orig_strides = vi.OriginalShape.strides;
//var orig_dims = vi.OriginalShape.dimensions;
offset = 0;
unchecked
{
for (int i = 0; i < coords.Count; i++)
{
// note: we can refrain from bounds checking here, because we should not allow negative indices at all, this should be checked higher up though.
//var coord = coords[i];
//var dim = orig_dims[i];
//if (coord < -dim || coord >= dim)
// throw new ArgumentException($"index {coord} is out of bounds for axis {i} with a size of {dim}");
//if (coord < 0)
// coord = dim + coord;
if (vi.Slices.Length <= i)
{
offset += orig_strides[i] * coords[i];
continue;
}
var slice = vi.Slices[i];
var start = slice.Start;
if (slice.IsIndex)
offset += orig_strides[i] * start; // the coord is irrelevant for index-slices (they are reduced dimensions)
else
offset += orig_strides[i] * (start + coords[i] * slice.Step);
}
}
if (!IsRecursive)
return offset;
// we are dealing with a sliced recursively reshaped slice
var parent_coords1 = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Get offset index out of coordinate indices.
/// </summary>
/// <param name="index">The coordinates to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
internal readonly int GetOffset_1D(int index)
{
int offset;
if (!IsSliced)
{
if (dimensions.Length == 0)
return index;
offset = 0;
unchecked
{
offset += strides[0] * index;
}
if (IsBroadcasted)
return offset % BroadcastInfo.OriginalShape.size;
return offset;
}
//if both sliced and broadcasted
if (IsBroadcasted)
return GetOffset_broadcasted_1D(index);
// we are dealing with a slice
var vi = ViewInfo;
if (IsRecursive && vi.Slices == null)
{
// we are dealing with an unsliced recursively reshaped slice
offset = GetOffset_IgnoreViewInfo(index);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(1) {index};
if (vi.UnreducedShape.IsScalar && index == 0 && !IsRecursive)
return 0;
if (1 > vi.UnreducedShape.dimensions.Length)
throw new ArgumentOutOfRangeException(nameof(index), $"select has too many coordinates for this shape");
var orig_ndim = vi.OriginalShape.NDim;
if (orig_ndim > NDim && orig_ndim > 1)
{
// fill in reduced dimensions in the provided coordinates
for (int i = 0; i < vi.OriginalShape.NDim; i++)
{
var slice = ViewInfo.Slices[i];
if (slice.IsIndex)
coords.Insert(i, 0);
if (coords.Count == orig_ndim)
break;
}
}
var orig_strides = vi.OriginalShape.strides;
//var orig_dims = vi.OriginalShape.dimensions;
offset = 0;
unchecked
{
for (int i = 0; i < coords.Count; i++)
{
// note: we can refrain from bounds checking here, because we should not allow negative indices at all, this should be checked higher up though.
//var coord = coords[i];
//var dim = orig_dims[i];
//if (coord < -dim || coord >= dim)
// throw new ArgumentException($"index {coord} is out of bounds for axis {i} with a size of {dim}");
//if (coord < 0)
// coord = dim + coord;
if (vi.Slices.Length <= i)
{
offset += orig_strides[i] * coords[i];
continue;
}
var slice = vi.Slices[i];
var start = slice.Start;
if (slice.IsIndex)
offset += orig_strides[i] * start; // the coord is irrelevant for index-slices (they are reduced dimensions)
else
offset += orig_strides[i] * (start + coords[i] * slice.Step);
}
}
if (!IsRecursive)
return offset;
// we are dealing with a sliced recursively reshaped slice
var parent_coords1 = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Calculate the offset in an unsliced shape. If the shape is sliced, ignore the ViewInfo
/// Note: to be used only inside of GetOffset()
/// </summary>
[MethodImpl((MethodImplOptions)768)]
private readonly int GetOffset_IgnoreViewInfo(params int[] indices)
{
if (dimensions.Length == 0 && indices.Length == 1)
return indices[0];
int offset = 0;
unchecked
{
for (int i = 0; i < indices.Length; i++)
offset += strides[i] * indices[i];
}
if (IsBroadcasted)
return offset % BroadcastInfo.OriginalShape.size;
return offset;
}
/// <summary>
/// Get offset index out of coordinate indices.
/// </summary>
/// <param name="indices">The coordinates to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
private readonly int GetOffset_broadcasted(params int[] indices)
{
int offset;
var vi = ViewInfo;
var bi = BroadcastInfo;
if (IsRecursive && vi.Slices == null)
{
// we are dealing with an unsliced recursively reshaped slice
offset = GetOffset_IgnoreViewInfo(indices);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(indices);
if (vi.UnreducedShape.IsScalar && indices.Length == 1 && indices[0] == 0 && !IsRecursive)
return 0;
if (indices.Length > vi.UnreducedShape.dimensions.Length)
throw new ArgumentOutOfRangeException(nameof(indices), $"select has too many coordinates for this shape");
var orig_ndim = vi.OriginalShape.NDim;
if (orig_ndim > NDim && orig_ndim > indices.Length)
{
// fill in reduced dimensions in the provided coordinates
for (int i = 0; i < vi.OriginalShape.NDim; i++)
{
var slice = ViewInfo.Slices[i];
if (slice.IsIndex)
coords.Insert(i, 0);
if (coords.Count == orig_ndim)
break;
}
}
var orig_strides = vi.OriginalShape.strides;
Shape unreducedBroadcasted = resolveUnreducedBroadcastedShape();
orig_strides = unreducedBroadcasted.strides;
offset = 0;
unchecked
{
for (int i = 0; i < coords.Count; i++)
{
if (vi.Slices.Length <= i)
{
offset += orig_strides[i] * coords[i];
continue;
}
var slice = vi.Slices[i];
var start = slice.Start;
if (slice.IsIndex)
offset += orig_strides[i] * start; // the coord is irrelevant for index-slices (they are reduced dimensions)
else
offset += orig_strides[i] * (start + coords[i] * slice.Step);
}
}
if (!IsRecursive)
return offset;
// we are dealing with a sliced recursively reshaped slice
var parent_coords1 = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Get offset index out of coordinate indices.
/// </summary>
/// <param name="index">The coordinates to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
private readonly int GetOffset_broadcasted_1D(int index)
{
int offset;
var vi = ViewInfo;
var bi = BroadcastInfo;
if (IsRecursive && vi.Slices == null)
{
// we are dealing with an unsliced recursively reshaped slice
offset = GetOffset_IgnoreViewInfo(index);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(1) {index};
if (vi.UnreducedShape.IsScalar && index == 0 && !IsRecursive)
return 0;
if (1 > vi.UnreducedShape.dimensions.Length)
throw new ArgumentOutOfRangeException(nameof(index), $"select has too many coordinates for this shape");
var orig_ndim = vi.OriginalShape.NDim;
if (orig_ndim > NDim && orig_ndim > 1)
{
// fill in reduced dimensions in the provided coordinates
for (int i = 0; i < vi.OriginalShape.NDim; i++)
{
var slice = ViewInfo.Slices[i];
if (slice.IsIndex)
coords.Insert(i, 0);
if (coords.Count == orig_ndim)
break;
}
}
var orig_strides = vi.OriginalShape.strides;
Shape unreducedBroadcasted = resolveUnreducedBroadcastedShape();
orig_strides = unreducedBroadcasted.strides;
offset = 0;
unchecked
{
for (int i = 0; i < coords.Count; i++)
{
if (vi.Slices.Length <= i)
{
offset += orig_strides[i] * coords[i];
continue;
}
var slice = vi.Slices[i];
var start = slice.Start;
if (slice.IsIndex)
offset += orig_strides[i] * start; // the coord is irrelevant for index-slices (they are reduced dimensions)
else
offset += orig_strides[i] * (start + coords[i] * slice.Step);
}
}
if (!IsRecursive)
return offset;
// we are dealing with a sliced recursively reshaped slice
var parent_coords1 = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Gets the shape based on given <see cref="indicies"/> and the index offset (C-Contiguous) inside the current storage.
/// </summary>
/// <param name="indicies">The selection of indexes 0 based.</param>
/// <returns></returns>
/// <remarks>Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.</remarks>
[MethodImpl((MethodImplOptions)768)]
public readonly (Shape Shape, int Offset) GetSubshape(params int[] indicies)
{
if (indicies.Length == 0)
return (this, 0);
int offset;
var dim = indicies.Length;
var newNDim = dimensions.Length - dim;
if (IsBroadcasted)
{
indicies = (int[])indicies.Clone(); //we must copy because we make changes to it.
Shape unreducedBroadcasted;
if (!BroadcastInfo.UnreducedBroadcastedShape.HasValue)
{
unreducedBroadcasted = this.Clone(true, false, false);
for (int i = 0; i < unreducedBroadcasted.NDim; i++)
{
if (unreducedBroadcasted.strides[i] == 0)
unreducedBroadcasted.dimensions[i] = 1;
}
BroadcastInfo.UnreducedBroadcastedShape = unreducedBroadcasted;
}
else
unreducedBroadcasted = BroadcastInfo.UnreducedBroadcastedShape.Value;
//unbroadcast indices
for (int i = 0; i < dim; i++)
indicies[i] = indicies[i] % unreducedBroadcasted[i];
offset = unreducedBroadcasted.GetOffset(indicies);
var retShape = new int[newNDim];
var strides = new int[newNDim];
var original = new int[newNDim];
var original_strides = new int[newNDim];
for (int i = 0; i < newNDim; i++)
{
retShape[i] = this.dimensions[dim + i];
strides[i] = this.strides[dim + i];
original[i] = unreducedBroadcasted[dim + i];
original_strides[i] = unreducedBroadcasted.strides[dim + i];
}
return (new Shape(retShape, strides, new Shape(original, original_strides)), offset);
}
//compute offset
offset = GetOffset(indicies);
var orig_shape = IsSliced ? ViewInfo.OriginalShape : this;
if (offset >= orig_shape.Size)
throw new IndexOutOfRangeException($"The offset {offset} is out of range in Shape {orig_shape.Size}");
if (indicies.Length == dimensions.Length)
return (Scalar, offset);
//compute subshape
var innerShape = new int[newNDim];
for (int i = 0; i < innerShape.Length; i++)
innerShape[i] = this.dimensions[dim + i];
//TODO! This is not full support of sliced,
//TODO! when sliced it usually diverts from this function but it would be better if we add support for sliced arrays too.
return (new Shape(innerShape), offset);
}
/// <summary>
/// Gets coordinates in this shape from index in this shape (slicing is ignored).
/// Example: Shape (2,3)
/// 0 => [0, 0]
/// 1 => [0, 1]
/// ...
/// 6 => [1, 2]
/// </summary>
/// <param name="offset">the index if you would iterate from 0 to shape.size in row major order</param>
/// <returns></returns>
[MethodImpl((MethodImplOptions)768)]
public readonly int[] GetCoordinates(int offset)
{
int[] coords = null;
if (strides.Length == 1)
coords = new int[] {offset};
int counter = offset;
coords = new int[strides.Length];
int stride;
for (int i = 0; i < strides.Length; i++)
{
unchecked
{
stride = strides[i];
if (stride == 0)
{
coords[i] = 0;
}
else
{
coords[i] = counter / stride;
counter -= coords[i] * stride;
}
}
}
return coords;
}
/// <summary>
/// Retrievs the coordinates in current shape (potentially sliced and reshaped) from index in original array.<br></br>
/// Note: this is the inverse operation of GetOffset<br></br>
/// Example: Shape a (2,3) => sliced to b (2,2) by a[:, 1:]<br></br>
/// The absolute indices in a are:<br></br>
/// [0, 1, 2,<br></br>
/// 3, 4, 5]<br></br>
/// The absolute indices in b are:<br></br>
/// [1, 2,<br></br>
/// 4, 5]<br></br>
/// <br></br>
/// <br></br>
/// Examples:<br></br>
/// a.GetCoordinatesFromAbsoluteIndex(1) returns [0, 1]<br></br>
/// b.GetCoordinatesFromAbsoluteIndex(0) returns [0, 0]<br></br>
/// b.GetCoordinatesFromAbsoluteIndex(0) returns [] because it is out of shape<br></br>
/// </summary>
/// <param name="offset">Is the index in the original array before it was sliced and/or reshaped</param>
/// <remarks>Note: due to slicing the absolute indices (offset in memory) are different from what GetCoordinates would return, which are relative indices in the shape.</remarks>
[MethodImpl((MethodImplOptions)768)]
public readonly int[] GetCoordinatesFromAbsoluteIndex(int offset)
{
if (!IsSliced)
return GetCoordinates(offset);
// handle sliced shape
int[] parent_coords = null;
if (IsRecursive)
{
var parent = ViewInfo.ParentShape;
var unreshaped_parent_coords = parent.GetCoordinatesFromAbsoluteIndex(offset);
var parent_shape_offset = parent.GetOffset_IgnoreViewInfo(unreshaped_parent_coords);
var orig_shape = ViewInfo.OriginalShape.IsEmpty ? this : ViewInfo.OriginalShape;
parent_coords = orig_shape.GetCoordinates(parent_shape_offset);
}
else
parent_coords = ViewInfo.OriginalShape.GetCoordinates(offset);
if (ViewInfo.Slices == null)
return parent_coords;
return ReplaySlicingOnCoords(parent_coords, ViewInfo.Slices);
}
[MethodImpl((MethodImplOptions)768)]
private int[] ReplaySlicingOnCoords(int[] parentCoords, SliceDef[] slices)
{
var coords = new List<int>();
for (int i = 0; i < parentCoords.Length; i++)
{
var slice = slices[i];
var coord = parentCoords[i];
if (slice.Count == -1) // this is a Slice.Index so we remove this dim from coords
continue;
if (slice.Count == 0) // this is a Slice.None which means there is no set of coordinates that can index anything in this shape
return new int[0];
if (slice.Start > coord && slice.Step > 0 || slice.Start < coord && slice.Step < 0) // outside of the slice, return empty coords
return new int[0];
if (coord % Math.Abs(slice.Step) != 0) // coord is between the steps, so we are "outside" of this shape, return empty coords
return new int[0];
coords.Add((coord - slice.Start) / slice.Step);
}
return coords.ToArray();
}
[MethodImpl((MethodImplOptions)768)]
public void ChangeTensorLayout(char order = 'C')
{
return; //currently this does nothing.
//layout = order;
_computeStrides();
ComputeHashcode();
}
[MethodImpl((MethodImplOptions)768)]
public static int GetSize(int[] dims)
{
int size = 1;
unchecked
{
for (int i = 0; i < dims.Length; i++)
size *= dims[i];
}
return size;
}
public static int[] GetAxis(ref Shape shape, int axis)
{
return GetAxis(shape.dimensions, axis);
}
public static int[] GetAxis(Shape shape, int axis)
{
return GetAxis(shape.dimensions, axis);
}
public static int[] GetAxis(int[] dims, int axis)
{
if (dims == null)
throw new ArgumentNullException(nameof(dims));
if (dims.Length == 0)
return new int[0];
if (axis <= -1) axis = dims.Length - 1;
if (axis >= dims.Length)
throw new AxisOutOfRangeException(dims.Length, axis);
return dims.RemoveAt(axis);
}
/// <summary>
/// Extracts the shape of given <paramref name="array"/>.
/// </summary>