Repository navigation
Expand file tree
/
Copy pathShape.cs
More file actions
1916 lines (1679 loc) · 83.7 KB
/
Copy pathShape.cs
File metadata and controls
1916 lines (1679 loc) · 83.7 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.Globalization;
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;
/// <summary>
/// The element count (the product of <see cref="dimensions"/>; 1 for a 0-d shape), read without a property call -
/// the same value as <see cref="Size"/>.
/// </summary>
public readonly long size;
/// <summary>
/// The extent of every axis: the shape's OWN array, shared with every shape and array built on it - no copy, unlike
/// <see cref="Dimensions"/>.
/// </summary>
/// <remarks>
/// For hot reads (an interop bridge, a kernel's setup) that cannot afford <see cref="Dimensions"/>' allocation per
/// read. Footgun: writing into it changes this shape, and every array sharing the array, without updating the cached
/// size, flags or hash - a later read goes past the buffer with no check. Treat it as read-only; build a new shape
/// to change one.
/// </remarks>
public readonly long[] dimensions;
/// <summary>
/// The stride of every axis in ELEMENTS (0 on a broadcast axis, negative on a reversed one): the shape's OWN array,
/// shared like <see cref="dimensions"/> - no copy, unlike <see cref="Strides"/>.
/// </summary>
/// <remarks>Footgun, as for <see cref="dimensions"/>: writing into it retargets every array sharing it with stale
/// flags and no bounds check. Read-only by contract.</remarks>
public 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>
/// <remarks>The same value as <see cref="BufferSize"/>, read without a property call.</remarks>
public 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>
/// <remarks>The same value as <see cref="Offset"/>, counted in elements, read without a property call.</remarks>
public 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: <c>IsSliced && !IsBroadcasted</c>
/// 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>(), copy: false);
/// <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;
}
/// <summary>
/// The extent of every axis (NumPy's <c>ndarray.shape</c>), as a NEW array on every read: NumPy hands out an
/// immutable tuple, so writing into the returned array never changes this shape or any array built on it.
/// </summary>
/// <value>A copy of the dimensions, the caller's to keep or change. A 0-d shape returns its empty array (there is
/// no element to write into) and an uninitialized <c>default(Shape)</c> returns <c>null</c>.</value>
/// <remarks>
/// <para>
/// <b>Why a copy.</b> Shapes and arrays SHARE dimension arrays (an allocation keeps its caller's shape, an
/// elementwise result keeps its input's), so returning the shared array let <c>x.Shape.Dimensions[0] = 100</c>
/// change <c>x</c>, and every array sharing it, to <c>(100, 4)</c> over 12 elements: the cached size, flags and
/// buffer stayed, so the new rows read past the buffer. Plan <c>docs/plans/view-shape-open-bugs.md</c>, bug 2c.
/// </para>
/// <para>
/// The copy costs one small allocation per read. Code inside NumSharp reads the internal <c>dimensions</c> field
/// instead; a caller that needs one extent should use <see cref="this[int]"/> or <see cref="NDim"/>, which do not
/// allocate, and a caller that reads the whole array in a hot loop should hoist it.
/// </para>
/// </remarks>
public readonly long[] Dimensions
{
[MethodImpl(Inline)]
get
{
// An empty array (0-d) has no element to write into and a default Shape has no array at all, so both are
// handed out as they are; anything else is cloned so the shared array never leaves the struct.
var dims = dimensions;
return dims is null || dims.Length == 0 ? dims : (long[])dims.Clone();
}
}
/// <summary>
/// The stride of every axis in ELEMENTS, as a NEW array on every read: writing into the returned array never
/// changes this shape or any array built on it. NumPy's <c>ndarray.strides</c> counts BYTES; that is
/// <see cref="NDArray.strides"/>, which scales these by the item size.
/// </summary>
/// <value>A copy of the element strides (0 on a broadcast axis, negative on a reversed one), the caller's to keep or
/// change. A 0-d shape returns its empty array and an uninitialized <c>default(Shape)</c> returns
/// <c>null</c>.</value>
/// <remarks>
/// <para>
/// <b>Why a copy.</b> Shapes and arrays SHARE stride arrays, and the cached flags (C/F-contiguity, broadcast,
/// writeable) and every kernel's addressing come from them. Returning the shared array let
/// <c>x.Shape.Strides[0] = 1000</c> retarget <c>x</c>'s reads past its buffer with no check and with stale flags.
/// NumPy has no unchecked route: its <c>strides</c> setter validates the request (<c>PyArray_CheckStrides</c>).
/// Plan <c>docs/plans/view-shape-open-bugs.md</c>, bug 2c.
/// </para>
/// <para>
/// The copy costs one small allocation per read. Code inside NumSharp reads the internal <c>strides</c> field
/// instead; a caller that reads the whole array in a hot loop should hoist it.
/// </para>
/// </remarks>
public readonly long[] Strides
{
[MethodImpl(Inline)]
get
{
// Same rule as Dimensions: the empty and the missing array are handed out as they are, anything else is
// cloned so the shared array never leaves the struct.
var st = strides;
return st is null || st.Length == 0 ? st : (long[])st.Clone();
}
}
/// <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>
/// <remarks>
/// The constructor a bridge package lays a strided, offset view over a foreign buffer with. Footguns: it ADOPTS both
/// arrays (the caller must never write into them afterwards, see <see cref="dimensions"/>), and it checks nothing -
/// an element reached through <paramref name="offset"/> and <paramref name="strides"/> outside
/// <paramref name="bufferSize"/> is read or written outside the buffer. <see cref="Shape(long[], long[])"/> copies
/// and validates; use it when the input is not already known to be valid.
/// </remarks>
public 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;
}
/// <summary>
/// A shape with explicit element <paramref name="strides"/>, at offset 0 over a buffer of exactly <c>size</c>
/// elements. By default it keeps COPIES of both arrays, so changing either array afterwards never changes this
/// shape or an array built on it (NumPy copies every shape or strides sequence it is given; plan
/// <c>docs/plans/view-shape-open-bugs.md</c>, bug 2d).
/// </summary>
/// <param name="dims">The extent of every axis. Copied unless <paramref name="copy"/> is <c>false</c>.</param>
/// <param name="strides">The stride of every axis, in ELEMENTS (0 for a broadcast axis, negative for a reversed
/// one). Copied unless <paramref name="copy"/> is <c>false</c>. Not validated against a buffer: an array that
/// installs this shape must own enough memory.</param>
/// <param name="copy"><c>true</c> (the default, NumPy's behaviour): the shape keeps copies of both arrays.
/// <c>false</c>: the shape keeps the two arrays themselves and saves two small allocations; the caller must never
/// write into either of them again (see remarks).</param>
/// <exception cref="ArgumentNullException"><paramref name="dims"/> or <paramref name="strides"/> is
/// <c>null</c>.</exception>
/// <exception cref="ArgumentException">The two arrays differ in length.</exception>
/// <remarks>
/// <c>copy: false</c> is for arrays nothing will write into: ones the caller just built, or another shape's own
/// (a shape never writes into its arrays). The shape caches its size and flags when it is built, and every array
/// built on it shares the two arrays, so a later write into one passed with <c>copy: false</c> changes those
/// arrays' layout but not their size or buffer: indexing then reads and writes past the buffer. NumPy has no
/// such mode; its arrays always own their dimensions and strides.
/// </remarks>
public Shape(long[] dims, long[] strides, bool copy = true)
{
// The checks run before anything is copied, so a bad argument costs no allocation, and they run for
// copy: false too, because the adopting core trusts both arrays as they are.
ValidateDimsAndStrides(dims, strides);
this = copy
? new Shape(CopyOf(dims), CopyOf(strides), AdoptTag.Owned)
: new Shape(dims, strides, AdoptTag.Owned);
}
/// <summary>
/// A shape with explicit element <paramref name="strides"/> over COPIES of the caller's arrays, at offset 0, whose
/// buffer is <paramref name="originalShape"/>'s (its buffer size, or its size when the buffer size is unset): the
/// form a broadcast of <paramref name="originalShape"/> takes. Changing either array afterwards never changes this
/// shape (bug 2d).
/// </summary>
/// <param name="dims">The extent of every axis. Copied.</param>
/// <param name="strides">The stride of every axis, in elements. Copied.</param>
/// <param name="originalShape">The shape whose buffer this one addresses; only its buffer size is read.</param>
/// <exception cref="ArgumentNullException"><paramref name="dims"/> or <paramref name="strides"/> is
/// <c>null</c>.</exception>
/// <exception cref="ArgumentException">The two arrays differ in length.</exception>
public Shape(long[] dims, long[] strides, Shape originalShape)
{
ValidateDimsAndStrides(dims, strides);
// For broadcast shapes, bufferSize is the original (pre-broadcast) size. The adopting view constructor
// computes the size, hash and flags from the two copies exactly as this constructor did.
this = new Shape(CopyOf(dims), CopyOf(strides), 0,
originalShape.bufferSize > 0 ? originalShape.bufferSize : originalShape.size);
}
/// <summary>
/// A C-contiguous shape over a COPY of the caller's dimensions (NumPy's <c>np.empty(shape)</c> layout). Changing
/// <paramref name="dims"/> afterwards never changes this shape or an array built on it: NumPy copies the sequence
/// (<c>PyArray_IntpConverter</c>) and an array owns its dimensions (<c>PyArray_NewFromDescr_int</c>).
/// </summary>
/// <param name="dims">The extent of every axis; <c>null</c> or empty is the 0-d shape. Copied.</param>
/// <remarks>
/// <para>
/// <b>Why a copy.</b> Shapes and arrays SHARE dimension arrays, so keeping the caller's array let
/// <c>long[] s = {3, 4}; var a = np.zeros(s); s[0] = 100;</c> turn <c>a</c> into <c>(100, 4)</c> over 12
/// elements: the cached size and the buffer stayed, so the new rows read past the buffer (plan
/// <c>docs/plans/view-shape-open-bugs.md</c>, bug 2d).
/// </para>
/// <para>
/// Inline values (<c>new Shape(3, 4)</c>) bind the <see cref="Shape(ReadOnlySpan{long})"/> overload, which
/// allocates the one array this shape keeps; a C# 12 caller, which has no span <c>params</c>, binds this one. An
/// array argument costs one copy. A caller that built the array itself and will never write into it again
/// skips the copy with <see cref="Shape(long[], char, bool)"/>: <c>new Shape(dims, copy: false)</c>.
/// </para>
/// </remarks>
[MethodImpl(Optimize)]
public Shape(params long[] dims) : this(CopyOf(dims), AdoptTag.Owned)
{
}
/// <summary>
/// A C-contiguous shape over the given dimensions, copied into the one array the shape keeps. This is the
/// overload inline values bind (<c>new Shape(3, 4)</c>, <c>new Shape(n)</c>): the values arrive on the caller's
/// stack, so building the shape allocates its dimension array once, as the array form did before it copied.
/// </summary>
/// <param name="dims">The extent of every axis; empty is the 0-d shape.</param>
[MethodImpl(Optimize)]
public Shape(params ReadOnlySpan<long> dims) : this(dims.IsEmpty ? Array.Empty<long>() : dims.ToArray(), AdoptTag.Owned)
{
}
/// <summary>
/// Marks the private constructors that take OWNERSHIP of the arrays they are given (no copy), so their
/// signatures cannot collide with the public constructors, which take the same arrays and copy them unless told
/// <c>copy: false</c>.
/// </summary>
private enum AdoptTag : byte
{
/// <summary>The arrays are the new shape's own: nothing else holds them, or nothing writes into them.</summary>
Owned
}
/// <summary>
/// The adopting core of the C-contiguous constructors: <paramref name="ownedDims"/> becomes this shape's
/// dimension array as it is.
/// </summary>
/// <param name="ownedDims">The dimensions, owned from now on by this shape (never <c>null</c>).</param>
/// <param name="tag">Disambiguates the overload; always <see cref="AdoptTag.Owned"/>.</param>
[MethodImpl(Optimize)]
private Shape(long[] ownedDims, AdoptTag tag)
{
this.dimensions = ownedDims;
this.strides = ComputeContiguousStrides(ownedDims);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(ownedDims);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(ownedDims, strides);
}
/// <summary>
/// The adopting core of the explicit-strides constructor: both arrays become this shape's as they are, at offset
/// 0 over a buffer of exactly <c>size</c> elements.
/// </summary>
/// <param name="ownedDims">The dimensions, owned from now on by this shape (already validated).</param>
/// <param name="ownedStrides">The element strides, owned from now on by this shape (same length).</param>
/// <param name="tag">Disambiguates the overload; always <see cref="AdoptTag.Owned"/>.</param>
private Shape(long[] ownedDims, long[] ownedStrides, AdoptTag tag)
{
this.dimensions = ownedDims;
this.strides = ownedStrides;
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(ownedDims);
this.bufferSize = size;
this.IsScalar = size == 1 && ownedDims.Length == 0;
this._flags = ComputeFlagsStatic(ownedDims, ownedStrides);
}
/// <summary>
/// The adopting core of the ordered constructor: <paramref name="ownedDims"/> becomes this shape's dimension
/// array as it is, with C or F strides.
/// </summary>
/// <param name="order">'C' or 'F', already validated.</param>
/// <param name="ownedDims">The dimensions, owned from now on by this shape (never <c>null</c>).</param>
/// <param name="tag">Disambiguates the overload; always <see cref="AdoptTag.Owned"/>.</param>
[MethodImpl(Optimize)]
private Shape(char order, long[] ownedDims, AdoptTag tag)
{
this.dimensions = ownedDims;
this.strides = order == 'F'
? ComputeFContiguousStrides(ownedDims)
: ComputeContiguousStrides(ownedDims);
this.offset = 0;
(this.size, this._hashCode) = ComputeSizeAndHash(ownedDims);
this.bufferSize = size;
this.IsScalar = _hashCode == int.MinValue;
this._flags = ComputeFlagsStatic(ownedDims, strides);
}
/// <summary>
/// The caller's dimensions as an array the new shape may own: a clone, or the shared empty array for
/// <c>null</c> and empty input (a 0-d shape has nothing to write into).
/// </summary>
/// <param name="source">The caller's array, or <c>null</c>.</param>
/// <returns>An array nothing but the new shape holds.</returns>
[MethodImpl(Inline)]
private static long[] CopyOf(long[] source) =>
source is null || source.Length == 0 ? Array.Empty<long>() : (long[])source.Clone();
/// <summary>
/// The argument checks of the explicit-strides constructors, run before anything is copied.
/// </summary>
/// <param name="dims">The dimensions to check.</param>
/// <param name="strides">The strides to check.</param>
/// <exception cref="ArgumentNullException">Either array is <c>null</c>.</exception>
/// <exception cref="ArgumentException">The two arrays differ in length.</exception>
private static void ValidateDimsAndStrides(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(string.Create(CultureInfo.InvariantCulture, $"While trying to construct a shape, given dimensions and strides does not match size ({dims.Length} != {strides.Length})"));
}
/// <summary>
/// The physical-order check of the ordered constructors: only 'C' and 'F' name a layout here.
/// </summary>
/// <param name="order">The requested order.</param>
/// <returns><paramref name="order"/>, unchanged.</returns>
/// <exception cref="ArgumentException"><paramref name="order"/> is not 'C' or 'F' (a logical order such as 'A' or
/// 'K' must be resolved first, through <c>OrderResolver</c>).</exception>
private static char ValidPhysicalOrder(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));
return order;
}
/// <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>
/// A C- or F-contiguous shape (NumPy's <c>np.empty(shape, order=order)</c> layout). By default it keeps a COPY of
/// <paramref name="dims"/>, so changing the array afterwards never changes this shape or an array built on it
/// (NumPy copies every shape sequence it is given; bug 2d). <c>copy: false</c> keeps the array itself, for one
/// nothing will write into.
/// </summary>
/// <param name="dims">The extent of every axis; <c>null</c> or empty is the 0-d shape. Copied unless
/// <paramref name="copy"/> is <c>false</c>.</param>
/// <param name="order">Physical memory order: 'C' (row-major, the default) or 'F' (column-major). A logical order
/// ('A', 'K') must be resolved to a physical one first, through <c>OrderResolver</c>.</param>
/// <param name="copy"><c>true</c> (the default, NumPy's behaviour): the shape keeps a copy of