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
1157 lines (995 loc) · 41.6 KB
/
Shape.cs
File metadata and controls
1157 lines (995 loc) · 41.6 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 struct Shape : ICloneable, IEquatable<Shape>
{
internal ViewInfo ViewInfo;
internal BroadcastInfo BroadcastInfo;
/// <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 bool IsSliced
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ViewInfo != null;
}
/// <summary>
/// Is this Shape a recusive view? (deeper than 1 view)
/// </summary>
public 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 char layout;
internal int _hashCode;
internal int size;
internal int[] dimensions;
internal int[] strides;
/// <summary>
/// Is this shape a broadcast and/or has modified strides?
/// </summary>
internal 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 bool IsEmpty => _hashCode == 0;
public char Order => layout;
/// <summary>
/// Singleton instance of a <see cref="Shape"/> that represents a scalar.
/// </summary>
public static readonly Shape Scalar = new Shape(Array.Empty<int>());
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar() => new Shape(Array.Empty<int>());
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar(ViewInfo viewInfo) => new Shape(Array.Empty<int>()) {ViewInfo = viewInfo};
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Shape NewScalar(ViewInfo viewInfo, BroadcastInfo broadcastInfo) => new Shape(Array.Empty<int>()) {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}, layout = 'C', size = length};
shape._hashCode = (shape.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 * 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}, layout = 'C', size = rows * cols};
unchecked
{
int hash = (shape.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 int NDim
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => dimensions.Length;
}
public int[] Dimensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => dimensions;
}
public int[] Strides
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => strides;
}
/// <summary>
/// The linear size of this shape.
/// </summary>
public 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;
}
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;
}
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};
}
[MethodImpl((MethodImplOptions)512)]
public Shape(params int[] dims)
{
if (dims == null)
{
strides = dims = dimensions = Array.Empty<int>();
}
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)
if (layout == 'C')
{
strides[strides.Length - 1] = 1;
for (int i = strides.Length - 1; i >= 1; i--)
strides[i - 1] = strides[i] * dims[i];
}
else
{
strides[0] = 1;
for (int idx = 1; idx < strides.Length; idx++)
strides[idx] = strides[idx - 1] * dims[idx - 1];
}
}
IsScalar = _hashCode == int.MinValue;
ViewInfo = null;
BroadcastInfo = null;
}
/// <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 void _computeStrides()
{
if (dimensions.Length == 0)
return;
unchecked
{
if (layout == 'C')
{
strides[strides.Length - 1] = 1;
for (int idx = strides.Length - 1; idx >= 1; idx--)
strides[idx - 1] = strides[idx] * dimensions[idx];
}
else
{
strides[0] = 1;
for (int idx = 1; idx < strides.Length; idx++)
strides[idx] = strides[idx - 1] * dimensions[idx - 1];
}
}
}
public 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 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.
/// </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 int GetOffset(params int[] indices)
{
if (!IsSliced)
return GetOffset_IgnoreViewInfo(indices);
//if both sliced and broadcasted
if (IsBroadcasted)
return GetOffset_broadcasted(indices);
// we are dealing with a slice
int offset;
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, ignore_view_info: true);
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, ignore_view_info: true);
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 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 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, ignore_view_info: true);
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;
if (!bi.UnbroadcastShape.HasValue)
{
if (bi.OriginalShape.IsScalar)
{
unreducedBroadcasted = vi.OriginalShape.Clone(true, false, false);
for (int i = 0; i < unreducedBroadcasted.NDim; i++)
{
unreducedBroadcasted.dimensions[i] = 1;
unreducedBroadcasted.strides[i] = 0;
}
}
else
{
unreducedBroadcasted = vi.OriginalShape.Clone(true, false, false);
for (int i = Math.Abs(vi.OriginalShape.NDim - NDim), j = 0; i < unreducedBroadcasted.NDim; i++, j++)
{
if (strides[j] == 0)
{
unreducedBroadcasted.dimensions[i] = 1;
unreducedBroadcasted.strides[i] = 0;
}
}
}
bi.UnbroadcastShape = unreducedBroadcasted;
}
else
unreducedBroadcasted = bi.UnbroadcastShape.Value;
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, ignore_view_info: true);
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 (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.UnbroadcastShape.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.UnbroadcastShape = unreducedBroadcasted;
}
else
unreducedBroadcasted = BroadcastInfo.UnbroadcastShape.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>
/// Transforms offset index into coordinates that matches this shape.
/// </summary>
/// <param name="offset"></param>
/// <returns></returns>
[MethodImpl((MethodImplOptions)768)]
public int[] GetCoordinates(int offset, bool ignore_view_info = false)
{
int[] coords = null;
if (strides.Length == 1)
coords = new int[] {offset};
else if (layout == 'C')
{
int counter = offset;
coords = new int[strides.Length];
int stride;
for (int i = 0; i < strides.Length; i++)
{
stride = strides[i];
if (stride == 0)
{
coords[i] = 0;
}
else
{
coords[i] = counter / stride;
counter -= coords[i] * stride;
}
}
}
else
{
int counter = offset;
coords = new int[strides.Length];
int stride;
for (int i = strides.Length - 1; i >= 0; i--)
{
stride = strides[i];
if (stride == 0)
{
coords[i] = 0;
}
else
{
coords[i] = counter / stride;
counter -= coords[i] * stride;
}
}
}
if (IsSliced && !ignore_view_info)
{
// TODO! undo dimensionality reduction
for (int i = 0; i < coords.Length; i++)
{
var slice = ViewInfo.Slices[i];
coords[i] = (coords[i] / slice.Step) - slice.Start;
}
}
return coords;
}
[MethodImpl((MethodImplOptions)768)]
public void ChangeTensorLayout(char order = 'C')
{
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 Array.Empty<int>();
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>
/// <remarks>Supports both jagged and multi-dim.</remarks>
[MethodImpl((MethodImplOptions)512)]
public static int[] ExtractShape(Array array)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
bool isJagged = false;
{
var type = array.GetType();
isJagged = array.Rank == 1 && type.IsArray && type.GetElementType().IsArray;
}
var l = new List<int>(16);
if (isJagged)
{
// ReSharper disable once PossibleNullReferenceException
Array arr = array;
do
{
l.Add(arr.Length);
arr = arr.GetValue(0) as Array;
} while (arr != null && arr.GetType().IsArray);
}
else
{
//jagged or regular
for (int dim = 0; dim < array.Rank; dim++)
{
l.Add(array.GetLength(dim));
}
}
return l.ToArray();
}
/// <summary>
/// Recalculate hashcode from current dimension and layout.
/// </summary>
[MethodImpl((MethodImplOptions)768)]
internal void ComputeHashcode()
{
if (dimensions.Length > 0)
{
unchecked
{
size = 1;
int hash = (layout * 397);
foreach (var v in dimensions)
{
size *= v;
hash ^= (size * 397) * (v * 397);
}
_hashCode = hash;
}
}
}
#region Slicing support
[MethodImpl((MethodImplOptions)768)]
public Shape Slice(string slicing_notation) => this.Slice(NumSharp.Slice.ParseSlices(slicing_notation));
[MethodImpl((MethodImplOptions)768)]
public Shape Slice(params Slice[] input_slices)
{
if (IsEmpty)
throw new InvalidOperationException("Unable to slice an empty shape.");
//if (IsBroadcasted)
// throw new NotSupportedException("Unable to slice a shape that is broadcasted.");
var slices = new List<SliceDef>(16);
var sliced_axes_unreduced = new List<int>();
for (int i = 0; i < NDim; i++)
{
var dim = Dimensions[i];
var slice = input_slices.Length > i ? input_slices[i] : NumSharp.Slice.All; //fill missing selectors
var slice_def = slice.ToSliceDef(dim);
slices.Add(slice_def);
var count = Math.Abs(slices[i].Count); // for index-slices count would be -1 but we need 1.
sliced_axes_unreduced.Add(count);
}
if (IsSliced && ViewInfo.Slices != null)
{
// merge new slices with existing ones and insert the indices of the parent shape that were previously reduced
for (int i = 0; i < ViewInfo.OriginalShape.NDim; i++)
{
var orig_slice = ViewInfo.Slices[i];
if (orig_slice.IsIndex)
{
slices.Insert(i, orig_slice);
sliced_axes_unreduced.Insert(i, 1);
continue;
}
slices[i] = ViewInfo.Slices[i].Merge(slices[i]);
sliced_axes_unreduced[i] = Math.Abs(slices[i].Count);
}
}
var sliced_axes = sliced_axes_unreduced.Where((dim, i) => !slices[i].IsIndex).ToArray();
var origin = (this.IsSliced && ViewInfo.Slices != null) ? this.ViewInfo.OriginalShape : this;
var viewInfo = new ViewInfo() {OriginalShape = origin, Slices = slices.ToArray(), UnreducedShape = new Shape(sliced_axes_unreduced.ToArray()),};
if (IsRecursive)
viewInfo.ParentShape = ViewInfo.ParentShape;
if (sliced_axes.Length == 0) //is it a scalar
return NewScalar(viewInfo);
return new Shape(sliced_axes) {ViewInfo = viewInfo};
}
#endregion
#region Implicit Operators
public static explicit operator int[](Shape shape) => (int[])shape.dimensions.Clone(); //we clone to avoid any changes
public static implicit operator Shape(int[] dims) => new Shape(dims);
public static explicit operator int(Shape shape) => shape.Size;
public static explicit operator Shape(int dim) => Shape.Vector(dim);
public static explicit operator (int, int)(Shape shape) => shape.dimensions.Length == 2 ? (shape.dimensions[0], shape.dimensions[1]) : (0, 0); //TODO! this should return (0,0) but rather (dim[0], dim[1]) regardless of size.
public static implicit operator Shape((int, int) dims) => Shape.Matrix(dims.Item1, dims.Item2);
public static explicit operator (int, int, int)(Shape shape) => shape.dimensions.Length == 3 ? (shape.dimensions[0], shape.dimensions[1], shape.dimensions[2]) : (0, 0, 0);
public static implicit operator Shape((int, int, int) dims) => new Shape(dims.Item1, dims.Item2, dims.Item3);
public static explicit operator (int, int, int, int)(Shape shape) => shape.dimensions.Length == 4 ? (shape.dimensions[0], shape.dimensions[1], shape.dimensions[2], shape.dimensions[3]) : (0, 0, 0, 0);
public static implicit operator Shape((int, int, int, int) dims) => new Shape(dims.Item1, dims.Item2, dims.Item3, dims.Item4);
public static explicit operator (int, int, int, int, int)(Shape shape) => shape.dimensions.Length == 5 ? (shape.dimensions[0], shape.dimensions[1], shape.dimensions[2], shape.dimensions[3], shape.dimensions[4]) : (0, 0, 0, 0, 0);
public static implicit operator Shape((int, int, int, int, int) dims) => new Shape(dims.Item1, dims.Item2, dims.Item3, dims.Item4, dims.Item5);
public static explicit operator (int, int, int, int, int, int)(Shape shape) => shape.dimensions.Length == 6 ? (shape.dimensions[0], shape.dimensions[1], shape.dimensions[2], shape.dimensions[3], shape.dimensions[4], shape.dimensions[5]) : (0, 0, 0, 0, 0, 0);
public static implicit operator Shape((int, int, int, int, int, int) dims) => new Shape(dims.Item1, dims.Item2, dims.Item3, dims.Item4, dims.Item5, dims.Item6);
#endregion
#region Deconstructor
public void Deconstruct(out int dim1, out int dim2)
{
var dims = this.dimensions;
dim1 = dims[0];
dim2 = dims[1];
}
public void Deconstruct(out int dim1, out int dim2, out int dim3)
{
var dims = this.dimensions;
dim1 = dims[0];
dim2 = dims[1];
dim3 = dims[2];
}
public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4)
{
var dims = this.dimensions;
dim1 = dims[0];
dim2 = dims[1];
dim3 = dims[2];
dim4 = dims[3];
}
public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5)
{
var dims = this.dimensions;
dim1 = dims[0];
dim2 = dims[1];
dim3 = dims[2];
dim4 = dims[3];
dim5 = dims[4];
}
public void Deconstruct(out int dim1, out int dim2, out int dim3, out int dim4, out int dim5, out int dim6)
{
var dims = this.dimensions;
dim1 = dims[0];
dim2 = dims[1];
dim3 = dims[2];
dim4 = dims[3];
dim5 = dims[4];
dim6 = dims[5];
}
#endregion
#region Equality
public static bool operator ==(Shape a, Shape b)
{
if (a.IsEmpty && b.IsEmpty)
return true;
if (a.IsEmpty || b.IsEmpty)
return false;
if (a.size != b.size || a.NDim != b.NDim)
return false;
var dim = a.NDim;
for (int i = 0; i < dim; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
public static bool operator !=(Shape a, Shape b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (obj.GetType() != this.GetType())
{