Repository navigation
Expand file tree
/
Copy pathShape.cs
More file actions
1644 lines (1410 loc) · 63.6 KB
/
Copy pathShape.cs
File metadata and controls
1644 lines (1410 loc) · 63.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>
/// NumPy-aligned array flags. Cached at shape creation for O(1) access.
/// Matches numpy/core/include/numpy/ndarraytypes.h flag definitions.
/// </summary>
[Flags]
public enum ArrayFlags
{
/// <summary>No flags set.</summary>
None = 0,
/// <summary>Data is C-contiguous (row-major, last dimension varies fastest).</summary>
C_CONTIGUOUS = 0x0001,
/// <summary>Data is F-contiguous (column-major).</summary>
F_CONTIGUOUS = 0x0002,
/// <summary>
/// Array owns its data buffer (NumPy's <c>NPY_ARRAY_OWNDATA</c>). Not derivable from
/// dims/strides — maintained by <see cref="NumSharp.Backends.UnmanagedStorage.OnReshaped"/>
/// at the storage funnels: set when the storage allocated its buffer
/// (NumPy <c>ctors.c</c>: <c>fa->flags |= NPY_ARRAY_OWNDATA</c> when <c>data == NULL</c>),
/// cleared for views and foreign-memory wraps (<c>base != NULL ⟹ !OWNDATA</c>).
/// </summary>
OWNDATA = 0x0004,
/// <summary>Data is aligned for the CPU (always true for managed allocations).</summary>
ALIGNED = 0x0100,
/// <summary>Data is writeable (false for broadcast views).</summary>
WRITEABLE = 0x0400,
/// <summary>Shape has a broadcast dimension (stride=0 with dim > 1).</summary>
BROADCASTED = 0x1000, // NumSharp extension for cached IsBroadcasted
}
/// <summary>
/// Represents a shape of an N-D array. Immutable after construction (NumPy-aligned).
/// </summary>
/// <remarks>Handles slicing, indexing based on coordinates or linear offset and broadcastted indexing.</remarks>
public readonly partial struct Shape : ICloneable, IEquatable<Shape>
{
/// <summary>
/// Cached array flags computed at shape creation.
/// Use ArrayFlags enum for bit meanings.
/// </summary>
internal readonly int _flags;
/// <summary>
/// Hash seed constant used in <see cref="ComputeSizeAndHash"/> for stable Shape hash values.
/// NOT the physical memory order — use <see cref="Order"/>, <see cref="IsContiguous"/>,
/// or <see cref="IsFContiguous"/> for actual memory layout information.
/// </summary>
internal const char layout = 'C';
internal readonly int _hashCode;
internal readonly long size;
internal readonly long[] dimensions;
internal readonly long[] strides;
/// <summary>
/// Size of the underlying buffer (NumPy-aligned architecture).
/// For non-view shapes, equals size. For sliced/broadcast shapes,
/// this is the actual buffer size (not the view size), used for
/// bounds checking and InternalArray slicing.
/// </summary>
internal readonly long bufferSize;
/// <summary>
/// Base offset into storage (NumPy-aligned architecture).
/// Computed at slice/broadcast time, enabling simple element access:
/// element[indices] = data[offset + sum(indices * strides)]
/// </summary>
internal readonly long offset;
/// <summary>
/// True if this shape represents a view (sliced) into underlying data.
/// A shape is "sliced" if it doesn't represent the full original buffer.
/// This includes: non-zero offset, different size than buffer, or non-contiguous strides.
/// </summary>
public readonly bool IsSliced
{
[MethodImpl(Inline)]
get => offset != 0 || (bufferSize > 0 && bufferSize != size) || !IsContiguous;
}
/// <summary>
/// Does this Shape represent contiguous unmanaged memory in C-order (row-major)?
/// Cached flag computed at shape creation, matching NumPy's flags['C_CONTIGUOUS'] algorithm.
/// </summary>
/// <remarks>
/// NumPy algorithm (from numpy/_core/src/multiarray/flagsobject.c:116-160):
/// Scan right-to-left. stride[-1] must equal 1 (itemsize in NumPy, but NumSharp uses element strides).
/// stride[i] must equal shape[i+1] * stride[i+1]. Size-1 dimensions are skipped (stride doesn't matter).
/// Empty arrays (any dimension is 0) are considered contiguous by definition.
/// </remarks>
public readonly bool IsContiguous
{
[MethodImpl(Inline)]
get => (_flags & (int)ArrayFlags.C_CONTIGUOUS) != 0;
}
/// <summary>
/// Does this Shape represent contiguous unmanaged memory in F-order (column-major)?
/// Cached flag computed at shape creation, matching NumPy's flags['F_CONTIGUOUS'] algorithm.
/// </summary>
/// <remarks>
/// NumPy algorithm: scan left-to-right. stride[0] must equal 1.
/// stride[i] must equal shape[i-1] * stride[i-1]. Size-1 dimensions are skipped.
/// Empty arrays are considered contiguous by definition.
/// A 1-D array that is C-contiguous is also F-contiguous (same memory layout).
/// </remarks>
public readonly bool IsFContiguous
{
[MethodImpl(Inline)]
get => (_flags & (int)ArrayFlags.F_CONTIGUOUS) != 0;
}
#region Static Flag/Hash Computation (for readonly struct)
/// <summary>
/// Computes array flags from dimensions and strides (static for readonly struct).
/// </summary>
[MethodImpl(Inline)]
private static int ComputeFlagsStatic(long[] dims, long[] strides)
{
// Empty arrays (any dim == 0) short-circuit per NumPy _UpdateContiguousFlags:
// unconditionally both C- and F-contiguous, writeable, and NOT broadcast.
// With no elements, broadcast semantics have no meaning.
if (dims != null)
{
for (int i = 0; i < dims.Length; i++)
{
if (dims[i] == 0)
{
return (int)(ArrayFlags.C_CONTIGUOUS
| ArrayFlags.F_CONTIGUOUS
| ArrayFlags.ALIGNED
| ArrayFlags.WRITEABLE);
}
}
}
int flags = 0;
// Check BROADCASTED first (only meaningful for non-empty arrays).
bool isBroadcasted = ComputeIsBroadcastedStatic(dims, strides);
if (isBroadcasted)
flags |= (int)ArrayFlags.BROADCASTED;
// Compute C- and F-contiguity together in a single pass (NumPy-aligned).
// Broadcast shapes are never flagged as contiguous even if the inner
// stride pattern would otherwise qualify.
if (!isBroadcasted)
{
var (isC, isF) = ComputeContiguousFlagsStatic(dims, strides);
if (isC) flags |= (int)ArrayFlags.C_CONTIGUOUS;
if (isF) flags |= (int)ArrayFlags.F_CONTIGUOUS;
}
// ALIGNED is always true because NumSharp uses unaligned SIMD loads (Vector.Load, not LoadAligned)
flags |= (int)ArrayFlags.ALIGNED;
// WRITEABLE is true unless this is a broadcast shape (NumPy behavior).
// Broadcast arrays have stride=0 dimensions where multiple logical positions
// map to the same physical memory - writing would corrupt shared data.
if (!isBroadcasted)
flags |= (int)ArrayFlags.WRITEABLE;
return flags;
}
/// <summary>
/// Computes whether any dimension is broadcast (stride=0 with dim > 1).
/// Internal so view-producers that pre-derive flags for the no-walk ctor
/// (<see cref="np.split"/>'s <c>DeriveSubFlags</c>) judge broadcastness with the
/// SAME rule the walking ctor uses.
/// </summary>
[MethodImpl(Inline)]
internal static bool ComputeIsBroadcastedStatic(long[] dims, long[] strides)
{
if (strides == null || strides.Length == 0)
return false;
for (int i = 0; i < strides.Length; i++)
if (strides[i] == 0 && dims[i] > 1)
return true;
return false;
}
/// <summary>
/// Computes both C- and F-contiguity in a single call, matching NumPy's
/// <c>_UpdateContiguousFlags</c> in <c>numpy/_core/src/multiarray/flagsobject.c</c>.
/// </summary>
/// <remarks>
/// From NumPy's source comments:
/// <list type="bullet">
/// <item>C-contiguous: <c>strides[-1] == itemsize</c> and <c>strides[i] == shape[i+1] * strides[i+1]</c></item>
/// <item>F-contiguous: <c>strides[0] == itemsize</c> and <c>strides[i] == shape[i-1] * strides[i-1]</c></item>
/// <item>A 0- or 1-dimensional array is either both C- and F-contiguous, or neither.</item>
/// <item>Multi-dim arrays can be C, F, or neither, but not both (unless only one element).</item>
/// <item>Size-1 dimensions don't count (their strides are unused).</item>
/// <item>Any dimension of size 0 makes the array trivially both C- and F-contiguous.</item>
/// </list>
/// NumSharp uses element-indexed strides (sd starts at 1) rather than byte strides.
/// Internal so view-producers that pre-derive flags for the no-walk ctor
/// (<see cref="np.split"/>'s <c>DeriveSubFlags</c>) compute contiguity with the SAME
/// size-1-relaxed walk the walking ctor uses — parent-flag algebra cannot express the
/// relaxation (a <c>(1,4)</c> child of a C-only parent is BOTH C- and F-contiguous).
/// </remarks>
[MethodImpl(Inline)]
internal static (bool isC, bool isF) ComputeContiguousFlagsStatic(long[] dims, long[] strides)
{
if (dims == null || dims.Length == 0)
return (true, true); // scalar is both
// Empty arrays (any dim == 0) are trivially both C- and F-contiguous (NumPy convention).
for (int i = 0; i < dims.Length; i++)
{
if (dims[i] == 0)
return (true, true);
}
// C-contiguity: scan right-to-left, stride[-1] must be 1, stride[i] = shape[i+1] * stride[i+1]
bool isC = true;
{
long sd = 1;
for (int i = dims.Length - 1; i >= 0; i--)
{
long dim = dims[i];
if (dim != 1)
{
if (strides[i] != sd) { isC = false; break; }
sd *= dim;
}
}
}
// F-contiguity: scan left-to-right, stride[0] must be 1, stride[i] = shape[i-1] * stride[i-1]
bool isF = true;
{
long sd = 1;
for (int i = 0; i < dims.Length; i++)
{
long dim = dims[i];
if (dim != 1)
{
if (strides[i] != sd) { isF = false; break; }
sd *= dim;
}
}
}
return (isC, isF);
}
/// <summary>
/// Computes size and hash from dimensions.
/// </summary>
[MethodImpl(Inline)]
private static (long size, int hash) ComputeSizeAndHash(long[] dims)
{
if (dims == null || dims.Length == 0)
return (1, int.MinValue); // scalar
long size = 1;
int hash = layout * 397;
unchecked
{
foreach (var v in dims)
{
size *= v;
hash ^= ((int)(size & 0x7FFFFFFF) * 397) * ((int)(v & 0x7FFFFFFF) * 397);
}
}
return (size, hash);
}
/// <summary>
/// Computes C-contiguous strides for given dimensions.
/// </summary>
[MethodImpl(Inline)]
private static long[] ComputeContiguousStrides(long[] dims)
{
if (dims == null || dims.Length == 0)
return Array.Empty<long>();
var strides = new long[dims.Length];
strides[dims.Length - 1] = 1;
for (int i = dims.Length - 2; i >= 0; i--)
strides[i] = strides[i + 1] * dims[i + 1];
return strides;
}
/// <summary>
/// Computes F-contiguous (column-major) strides for given dimensions.
/// strides[0] = 1, strides[i] = dims[i-1] * strides[i-1].
/// </summary>
[MethodImpl(Inline)]
private static long[] ComputeFContiguousStrides(long[] dims)
{
if (dims == null || dims.Length == 0)
return Array.Empty<long>();
var strides = new long[dims.Length];
strides[0] = 1;
for (int i = 1; i < dims.Length; i++)
strides[i] = strides[i - 1] * dims[i - 1];
return strides;
}
/// <summary>
/// Converts int[] dimensions to long[] for backwards compatibility.
/// </summary>
[MethodImpl(Inline)]
public static long[] ComputeLongShape(int[] dimensions)
{
if (dimensions == null) return null;
var result = new long[dimensions.Length];
for (int i = 0; i < dimensions.Length; i++)
result[i] = dimensions[i];
return result;
}
#endregion
/// <summary>
/// Is this a simple sliced shape that uses the fast GetOffsetSimple path?
/// True when: IsSliced && !IsBroadcasted
/// For simple slices, element access is: offset + sum(indices * strides)
/// </summary>
public readonly bool IsSimpleSlice
{
[MethodImpl(Inline)]
get => IsSliced && !IsBroadcasted;
}
/// <summary>
/// Is this shape a broadcast (has any stride=0 with dimension > 1)?
/// Cached flag computed at shape creation for O(1) access.
/// </summary>
public readonly bool IsBroadcasted
{
[MethodImpl(Inline)]
get => (_flags & (int)ArrayFlags.BROADCASTED) != 0;
}
/// <summary>
/// Is this array writeable? False for broadcast views (NumPy behavior).
/// Cached flag computed at shape creation for O(1) access.
/// </summary>
public readonly bool IsWriteable
{
[MethodImpl(Inline)]
get => (_flags & (int)ArrayFlags.WRITEABLE) != 0;
}
/// <summary>
/// Does this array own its data buffer (NumPy's <c>flags.owndata</c>)?
/// True for freshly allocated arrays (<c>np.arange</c>, <c>np.zeros</c>, <c>.copy()</c>);
/// false for views (slices, transposes, broadcasts) and foreign-memory wraps (memmaps).
/// Maintained at the <see cref="NumSharp.Backends.UnmanagedStorage"/> funnels
/// (<see cref="NumSharp.Backends.UnmanagedStorage.OnReshaped"/>), mirroring
/// <c>UnmanagedStorage.OwnsData</c> — meaningful only on a shape read off a storage
/// (<c>nd.Shape</c>); a hand-built <see cref="Shape"/> carries no ownership claim.
/// </summary>
public readonly bool OwnsData
{
[MethodImpl(Inline)]
get => (_flags & (int)ArrayFlags.OWNDATA) != 0;
}
/// <summary>
/// Get all array flags as a single integer.
/// Use ArrayFlags enum for bit meanings.
/// </summary>
public readonly ArrayFlags Flags
{
[MethodImpl(Inline)]
get => (ArrayFlags)_flags;
}
/// <summary>
/// Is this shape a scalar that was broadcast to a larger shape?
/// True when all strides are 0, meaning all dimensions are broadcast from a scalar.
/// Used for optimization: when iterating, we can use a single value instead of indexing.
/// </summary>
public readonly bool IsScalarBroadcast
{
[MethodImpl(Inline)]
get
{
if (strides == null || strides.Length == 0)
return false;
for (int i = 0; i < strides.Length; i++)
{
if (strides[i] != 0)
return false;
}
return true;
}
}
/// <summary>
/// Computes the size of the original (non-broadcast) data.
/// This is the product of all dimensions where stride != 0.
/// For a non-broadcast shape, this equals size.
/// For a broadcast shape, this is the actual data size before broadcast.
/// </summary>
public readonly long OriginalSize
{
[MethodImpl(Inline)]
get
{
if (strides == null || strides.Length == 0)
return IsScalar ? 1 : size;
long originalSize = 1;
for (int i = 0; i < strides.Length; i++)
{
if (strides[i] != 0)
originalSize *= dimensions[i];
}
return originalSize == 0 ? 1 : originalSize; // At least 1 for scalar broadcasts
}
}
/// <summary>
/// Is this shape a scalar? (<see cref="NDim"/>==0 && <see cref="size"/> == 1)
/// </summary>
public readonly bool IsScalar;
/// <summary>
/// True if the shape is not initialized.
/// Note: A scalar shape is not empty.
/// </summary>
public readonly bool IsEmpty => _hashCode == 0;
/// <summary>
/// Physical memory layout: 'F' if strictly F-contiguous, otherwise 'C'.
/// 1-D and scalar shapes (both C- and F-contig) report 'C' by convention.
/// Non-contiguous shapes also report 'C' as the default reference order.
/// </summary>
public readonly char Order => (IsFContiguous && !IsContiguous) ? 'F' : 'C';
/// <summary>
/// Singleton instance of a <see cref="Shape"/> that represents a scalar.
/// </summary>
public static readonly Shape Scalar = new Shape(Array.Empty<long>());
/// <summary>
/// Create a new scalar shape
/// </summary>
[MethodImpl(Inline)]
internal static Shape NewScalar()
{
return new Shape();
}
/// <summary>
/// Create a shape that represents a vector.
/// </summary>
/// <remarks>Faster than calling Shape's constructor</remarks>
public static Shape Vector(long length)
{
return new Shape(new long[] { length }, new long[] { 1 }, 0, length);
}
/// <summary>
/// Create a shape that represents a matrix.
/// </summary>
/// <remarks>Faster than calling Shape's constructor</remarks>
public static Shape Matrix(long rows, long cols)
{
long sz = rows * cols;
return new Shape(new[] { rows, cols }, new long[] { cols, 1 }, 0, sz);
}
public readonly int NDim
{
[MethodImpl(Inline)]
get => dimensions.Length;
}
public readonly long[] Dimensions
{
[MethodImpl(Inline)]
get => dimensions;
}
public readonly long[] Strides
{
[MethodImpl(Inline)]
get => strides;
}
/// <summary>
/// The linear size of this shape.
/// </summary>
public readonly long Size
{
[MethodImpl(Inline)]
get => size;
}
/// <summary>
/// Base offset into storage (like NumPy's adjusted data pointer).
/// For non-view shapes this is 0. For sliced/broadcast shapes,
/// this will be computed at slice/broadcast time in future phases.
/// </summary>
public readonly long Offset
{
[MethodImpl(Inline)]
get => offset;
}
/// <summary>
/// Size of the underlying buffer (NumPy-aligned architecture).
/// For non-view shapes, equals Size. For sliced/broadcast shapes,
/// this is the actual buffer size (not the view size).
/// </summary>
public readonly long BufferSize
{
[MethodImpl(Inline)]
get => bufferSize > 0 ? bufferSize : size;
}
#region Constructors
/// <summary>
/// Creates a scalar shape (ndim=0, size=1).
/// Equivalent to NumPy's empty tuple shape ().
/// </summary>
/// <remarks>
/// In NumPy: np.array(42).shape == ()
/// In NumSharp: new Shape() creates a scalar shape.
/// </remarks>
public Shape()
{
this.dimensions = Array.Empty<long>();
this.strides = Array.Empty<long>();
this.offset = 0;
this.bufferSize = 1;
this.size = 1;
this._hashCode = int.MinValue; // Scalar hash
this.IsScalar = true;
// Scalars are trivially both C- and F-contiguous
this._flags = (int)(ArrayFlags.C_CONTIGUOUS | ArrayFlags.F_CONTIGUOUS | ArrayFlags.ALIGNED | ArrayFlags.WRITEABLE);
}
/// <summary>
/// Complete constructor for views/broadcasts (NumPy-aligned).
/// All parameters are set explicitly, flags computed from dims/strides.
/// </summary>
/// <param name="dims">Dimension sizes (not cloned - caller must provide fresh array)</param>
/// <param name="strides">Stride values (not cloned - caller must provide fresh array)</param>
/// <param name="offset">Offset into underlying buffer</param>
/// <param name="bufferSize">Size of underlying buffer</param>
internal Shape(long[] dims, long[] strides, long offset, long bufferSize)
{
this.dimensions = dims ?? Array.Empty<long>();
this.strides = strides ?? Array.Empty<long>();
this.offset = offset;
this.bufferSize = bufferSize;
(this.size, this._hashCode) = ComputeSizeAndHash(dims);
this.IsScalar = size == 1 && (dims == null || dims.Length == 0);
this._flags = ComputeFlagsStatic(dims, strides);
}
/// <summary>
/// Creates a shape with modified flags (for clearing WRITEABLE on broadcasts, or
/// setting/clearing OWNDATA at the <see cref="NumSharp.Backends.UnmanagedStorage"/> funnels).
/// </summary>
/// <remarks>
/// Dimensions and strides are unchanged, so <see cref="size"/> and <see cref="_hashCode"/>
/// are carried over verbatim through the no-walk constructor instead of being recomputed.
/// </remarks>
public Shape WithFlags(ArrayFlags flagsToSet = ArrayFlags.None, ArrayFlags flagsToClear = ArrayFlags.None)
{
int newFlags = (_flags | (int)flagsToSet) & ~(int)flagsToClear;
return new Shape(dimensions, strides, offset, bufferSize, newFlags, size, _hashCode);
}
/// <summary>
/// Internal constructor with explicit flags (for WithFlags).
/// </summary>
private Shape(long[] dims, long[] strides, long offset, long bufferSize, int flags)
{
this.dimensions = dims;
this.strides = strides;
this.offset = offset;
this.bufferSize = bufferSize;
this._flags = flags;
(this.size, this._hashCode) = ComputeSizeAndHash(dims);
this.IsScalar = size == 1 && (dims == null || dims.Length == 0);
}
/// <summary>
/// Hot-path constructor for view kernels that already know the final
/// <paramref name="flags"/>, <paramref name="size"/>, and
/// <paramref name="hashCode"/>. Skips both <c>ComputeFlagsStatic</c>
/// (3 walks of dims/strides) and <c>ComputeSizeAndHash</c> (1 walk).
/// Caller must guarantee values are consistent with
/// <paramref name="dims"/> / <paramref name="strides"/>; this ctor
/// does no validation.
/// </summary>
/// <remarks>
/// Used by <c>np.split</c> / <c>np.array_split</c> where every
/// sub-array shares the parent strides and only <c>dims[axis]</c>
/// changes, so the parent's flags and size scale by an O(1) ratio.
/// </remarks>
internal Shape(long[] dims, long[] strides, long offset, long bufferSize, int flags, long size, int hashCode)
{
this.dimensions = dims;
this.strides = strides;
this.offset = offset;
this.bufferSize = bufferSize;
this._flags = flags;
this.size = size;
this._hashCode = hashCode;
this.IsScalar = size == 1 && (dims == null || dims.Length == 0);
}
public Shape(Shape other)
{
if (other.IsEmpty)
{
this = default;
return;
}
//this.layout = other.layout;
this._hashCode = other._hashCode;
this.size = other.size;
this.bufferSize = other.bufferSize;
this.dimensions = (long[])other.dimensions.Clone();
this.strides = (long[])other.strides.Clone();
this.offset = other.offset;
this.IsScalar = other.IsScalar;
this._flags = other._flags;
}
public Shape(long[] dims, long[] 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})");
this.dimensions = dims;
this.strides = strides;
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(dims);
this.bufferSize = size;
this.IsScalar = size == 1 && dims.Length == 0;
this._flags = ComputeFlagsStatic(dims, strides);
}
public Shape(long[] dims, long[] 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})");
this.dimensions = dims;
this.strides = strides;
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(dims);
// For broadcast shapes, bufferSize is the original (pre-broadcast) size
this.bufferSize = originalShape.bufferSize > 0 ? originalShape.bufferSize : originalShape.size;
this.IsScalar = size == 1 && dims.Length == 0;
this._flags = ComputeFlagsStatic(dims, strides);
}
/// <summary>
/// Primary constructor with long dimensions.
/// </summary>
[MethodImpl(Optimize)]
public Shape(params long[] dims)
{
if (dims == null)
dims = Array.Empty<long>();
this.dimensions = dims;
this.strides = ComputeContiguousStrides(dims);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(dims);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(dims, strides);
}
/// <summary>
/// Primary constructor with long dimensions.
/// </summary>
[MethodImpl(Optimize)]
public Shape(IEnumerable<long> dims)
{
var dimsArray = dims?.ToArray() ?? Array.Empty<long>();
this.dimensions = dimsArray;
this.strides = ComputeContiguousStrides(dimsArray);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(dimsArray);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(dimsArray, strides);
}
/// <summary>
/// Backward-compatible constructor with int dimensions.
/// </summary>
[MethodImpl(Optimize)]
public Shape(int[] dims)
{
if (dims == null)
{
this.dimensions = Array.Empty<long>();
}
else
{
this.dimensions = new long[dims.Length];
for (int i = 0; i < dims.Length; i++)
this.dimensions[i] = dims[i];
}
this.strides = ComputeContiguousStrides(this.dimensions);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(this.dimensions);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(this.dimensions, this.strides);
}
/// <summary>
/// Constructs a Shape with a specified physical memory order.
/// Only 'C' (row-major) and 'F' (column-major) are valid — logical orders
/// ('A', 'K') must be resolved to a physical order first via OrderResolver.
/// </summary>
/// <param name="dims">Dimension sizes.</param>
/// <param name="order">Physical memory order: 'C' or 'F'.</param>
/// <exception cref="ArgumentException">Thrown if order is not 'C' or 'F'.</exception>
[MethodImpl(Optimize)]
public Shape(long[] dims, char order)
{
if (order != 'C' && order != 'F')
throw new ArgumentException(
$"Physical order must be 'C' or 'F' (got '{order}'). Use OrderResolver to resolve 'A' or 'K'.",
nameof(order));
this.dimensions = dims ?? Array.Empty<long>();
this.strides = order == 'F'
? ComputeFContiguousStrides(this.dimensions)
: ComputeContiguousStrides(this.dimensions);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(this.dimensions);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(this.dimensions, this.strides);
}
#endregion
/// <summary>
/// An empty shape without any fields set (all dimensions are 0).
/// </summary>
/// <remarks>Used internally for building shapes that will be filled in.</remarks>
[MethodImpl(OptimizeAndInline)]
public static Shape Empty(int ndim)
{
// Create shape with zero dimensions and zero strides
return new Shape(new long[ndim], new long[ndim], 0, 0);
}
public readonly long this[int dim]
{
[MethodImpl(Inline)]
get => dimensions[dim < 0 ? dimensions.Length + dim : dim];
[MethodImpl(Inline)]
set => dimensions[dim < 0 ? dimensions.Length + dim : dim] = value;
}
/// <summary>
/// Retrieve the transformed offset if the shape is non-contiguous,
/// 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>For contiguous shapes, returns offset directly. For non-contiguous, translates through coordinates.</remarks>
[MethodImpl(Inline)]
public readonly long TransformOffset(long offset)
{
// For contiguous shapes, direct return
if (IsContiguous)
return this.offset + offset;
// Non-contiguous: translate through coordinates
return GetOffset(GetCoordinates(offset));
}
/// <summary>
/// Get offset index out of coordinate indices.
/// NumPy-aligned: offset + sum(indices * strides)
/// </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>
[MethodImpl(OptimizeAndInline)]
public readonly long GetOffset(params long[] indices)
{
// Scalar with single index: direct offset access
if (dimensions.Length == 0)
return offset + (indices.Length > 0 ? indices[0] : 0);
// NumPy formula: data_ptr + sum(indices * strides)
return GetOffsetSimple(indices);
}
/// <summary>
/// Backward-compatible GetOffset with int indices.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public readonly long GetOffset(int[] indices)
{
// Scalar with single index: direct offset access
if (dimensions.Length == 0)
return offset + (indices.Length > 0 ? indices[0] : 0);
// NumPy formula: data_ptr + sum(indices * strides)
long off = offset;
unchecked
{
for (int i = 0; i < indices.Length; i++)
off += indices[i] * strides[i];
}
return off;
}
/// <summary>
/// Get offset index out of a single coordinate index (1D fast path).
/// NumPy-aligned: offset + stride[0] * index
/// </summary>
/// <param name="index">The 1D coordinate to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
[MethodImpl(OptimizeAndInline)]
internal readonly long GetOffset_1D(long index)
{
// Scalar case: direct offset access
if (dimensions.Length == 0)
return offset + index;
return offset + index * strides[0];
}
/// <summary>
/// NumPy-aligned offset calculation: offset + sum(indices * strides).
/// This is the core formula - offset is computed at slice/broadcast time,
/// strides include step factors, and stride=0 handles broadcasting.
/// </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>
[MethodImpl(Inline)]
internal readonly long GetOffsetSimple(params long[] indices)
{
long off = offset;
unchecked
{
for (int i = 0; i < indices.Length; i++)
off += indices[i] * strides[i];
}
return off;
}
/// <summary>
/// Simplified offset calculation for 1D access.
/// </summary>
[MethodImpl(Inline)]
internal readonly long GetOffsetSimple(long index)
{
// Scalar case: direct offset access
if (strides.Length == 0)
return offset + index;
return offset + index * strides[0];
}
/// <summary>
/// Simplified offset calculation for 2D access.
/// </summary>
[MethodImpl(Inline)]
internal readonly long GetOffsetSimple(long i, long j)
{
return offset + i * strides[0] + j * strides[1];
}
/// <summary>
/// Simplified offset calculation for 3D access.
/// </summary>
[MethodImpl(Inline)]
internal readonly long GetOffsetSimple(long i, long j, long k)
{
return offset + i * strides[0] + j * strides[1] + k * strides[2];
}
/// <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(OptimizeAndInline)]
public readonly (Shape Shape, long Offset) GetSubshape(params long[] indicies)
{
if (indicies.Length == 0)
return (this, 0);
long offset;
var dim = indicies.Length;
var newNDim = dimensions.Length - dim;
if (IsBroadcasted)
{
indicies = (long[])indicies.Clone(); //we must copy because we make changes to it.
// NumPy-aligned: compute unreduced shape on the fly
// Unreduced shape has 1 for broadcast dimensions (stride=0)
var unreducedDims = new long[NDim];
for (int i = 0; i < NDim; i++)
unreducedDims[i] = strides[i] == 0 ? 1 : dimensions[i];
// Unbroadcast indices (wrap around for broadcast dimensions)
for (int i = 0; i < dim; i++)
indicies[i] = indicies[i] % unreducedDims[i];
// Compute offset using strides (stride=0 means index doesn't affect offset)
offset = this.offset;
for (int i = 0; i < dim; i++)
offset += strides[i] * indicies[i];
var retShape = new long[newNDim];
var retStrides = new long[newNDim];
for (int i = 0; i < newNDim; i++)
{
retShape[i] = this.dimensions[dim + i];
retStrides[i] = this.strides[dim + i];
}
// Create result with bufferSize preserved (immutable constructor)
long bufSize = this.bufferSize > 0 ? this.bufferSize : this.size;
var result = new Shape(retShape, retStrides, offset, bufSize);
return (result, offset);
}
//compute offset
offset = GetOffset(indicies);
// Use bufferSize for bounds checking (NumPy-aligned: no ViewInfo dependency)
long boundSize = bufferSize > 0 ? bufferSize : size;
if (offset >= boundSize && AddressesAnElement(dim))
throw new IndexOutOfRangeException($"The offset {offset} is out of range in Shape {boundSize}");
if (indicies.Length == dimensions.Length)
return (Scalar, offset);
//compute subshape
var innerShape = new long[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);