forked from SciSharp/NumSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShape.Unmanaged.cs
More file actions
334 lines (297 loc) · 13.8 KB
/
Shape.Unmanaged.cs
File metadata and controls
334 lines (297 loc) · 13.8 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace NumSharp
{
public partial struct Shape
{
/// <summary>
/// Get offset index out of coordinate indices.
/// </summary>
/// <param name="indices">A pointer to the coordinates to turn into linear offset</param>
/// <param name="ndims">The number of dimensions</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
public readonly unsafe int GetOffset(int* indices, int ndims)
{
int offset;
if (!IsSliced)
{
if (dimensions.Length == 0 && ndims == 1)
return indices[0];
offset = 0;
unchecked
{
for (int i = 0; i < ndims; i++)
offset += strides[i] * indices[i];
}
if (IsBroadcasted)
return offset % BroadcastInfo.OriginalShape.size;
return offset;
}
//if both sliced and broadcasted
if (IsBroadcasted)
return GetOffset_broadcasted(indices, ndims);
// we are dealing with a slice
var vi = ViewInfo;
if (IsRecursive && vi.Slices == null)
{
// we are dealing with an unsliced recursively reshaped slice
offset = GetOffset_IgnoreViewInfo(indices, ndims);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(ndims + 10);
for (int i = 0; i < ndims; i++)
coords.Add(indices[i]);
if (vi.UnreducedShape.IsScalar && ndims == 1 && indices[0] == 0 && !IsRecursive)
return 0;
if (ndims > 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 > ndims)
{
// fill in reduced dimensions in the provided coordinates
for (int i = 0; i < vi.OriginalShape.NDim; i++)
{
var slice = ViewInfo.Slices[i];
if (slice.IsIndex)
coords.Insert(i, 0);
if (coords.Count == orig_ndim)
break;
}
}
var orig_strides = vi.OriginalShape.strides;
//var orig_dims = vi.OriginalShape.dimensions;
offset = 0;
unchecked
{
for (int i = 0; i < coords.Count; i++)
{
// note: we can refrain from bounds checking here, because we should not allow negative indices at all, this should be checked higher up though.
//var coord = coords[i];
//var dim = orig_dims[i];
//if (coord < -dim || coord >= dim)
// throw new ArgumentException($"index {coord} is out of bounds for axis {i} with a size of {dim}");
//if (coord < 0)
// coord = dim + coord;
if (vi.Slices.Length <= i)
{
offset += orig_strides[i] * coords[i];
continue;
}
var slice = vi.Slices[i];
var start = slice.Start;
if (slice.IsIndex)
offset += orig_strides[i] * start; // the coord is irrelevant for index-slices (they are reduced dimensions)
else
offset += orig_strides[i] * (start + coords[i] * slice.Step);
}
}
if (!IsRecursive)
return offset;
// we are dealing with a sliced recursively reshaped slice
var parent_coords1 = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Gets the shape based on given <see cref="indicies"/> and the index offset (C-Contiguous) inside the current storage.
/// </summary>
/// <param name="indicies">The selection of indexes 0 based.</param>
/// <returns></returns>
/// <remarks>Used for slicing, returned shape is the new shape of the slice and offset is the offset from current address.</remarks>
[MethodImpl((MethodImplOptions)768)]
public readonly unsafe (Shape Shape, int Offset) GetSubshape(int* dims, int ndims)
{
if (ndims == 0)
return (this, 0);
int offset;
var dim = ndims;
var newNDim = dimensions.Length - dim;
if (IsBroadcasted)
{
var dimsClone = stackalloc int[ndims];
for (int j = 0; j < ndims; j++)
{
dimsClone[j] = dims[j];
}
Shape unreducedBroadcasted;
if (!BroadcastInfo.UnreducedBroadcastedShape.HasValue)
{
unreducedBroadcasted = this.Clone(true, false, false);
for (int i = 0; i < unreducedBroadcasted.NDim; i++)
{
if (unreducedBroadcasted.strides[i] == 0)
unreducedBroadcasted.dimensions[i] = 1;
}
BroadcastInfo.UnreducedBroadcastedShape = unreducedBroadcasted;
}
else
unreducedBroadcasted = BroadcastInfo.UnreducedBroadcastedShape.Value;
//unbroadcast indices
for (int i = 0; i < dim; i++)
dimsClone[i] = dimsClone[i] % unreducedBroadcasted[i];
offset = unreducedBroadcasted.GetOffset(dimsClone, ndims);
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(dims, ndims);
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 (ndims == 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>
/// Translates coordinates with negative indices, e.g:<br></br>
/// np.arange(9)[-1] == np.arange(9)[8]<br></br>
/// np.arange(9)[-2] == np.arange(9)[7]<br></br>
/// </summary>
/// <param name="dimensions">The dimensions these coordinates are targeting</param>
/// <param name="coords">The coordinates.</param>
/// <returns>Coordinates without negative indices.</returns>
[SuppressMessage("ReSharper", "ParameterHidesMember"), MethodImpl((MethodImplOptions)512)]
public static unsafe void InferNegativeCoordinates(int[] dimensions, int* coords, int coordsCount)
{
for (int i = 0; i < coordsCount; i++)
{
var curr = coords[i];
if (curr < 0)
coords[i] = dimensions[i] + curr;
}
}
/// <summary>
/// Get offset index out of coordinate indices.
/// </summary>
/// <param name="indices">The coordinates to turn into linear offset</param>
/// <returns>The index in the memory block that refers to a specific value.</returns>
/// <remarks>Handles sliced indices and broadcasting</remarks>
[MethodImpl((MethodImplOptions)768)]
private readonly unsafe int GetOffset_broadcasted(int* indices, int ndims)
{
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, ndims);
var parent_coords = vi.ParentShape.GetCoordinates(offset);
return vi.ParentShape.GetOffset(parent_coords);
}
var coords = new List<int>(ndims + 10);
for (int i = 0; i < ndims; i++)
coords.Add(indices[i]);
if (vi.UnreducedShape.IsScalar && ndims == 1 && indices[0] == 0 && !IsRecursive)
return 0;
if (ndims > 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 > ndims)
{
// 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.UnreducedBroadcastedShape.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.UnreducedBroadcastedShape = unreducedBroadcasted;
}
else
unreducedBroadcasted = bi.UnreducedBroadcastedShape.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);
return vi.ParentShape.GetOffset(parent_coords1);
}
/// <summary>
/// Calculate the offset in an unsliced shape. If the shape is sliced, ignore the ViewInfo
/// Note: to be used only inside of GetOffset()
/// </summary>
[MethodImpl((MethodImplOptions)768)]
private readonly unsafe int GetOffset_IgnoreViewInfo(int* indices, int ndims)
{
if (dimensions.Length == 0 && ndims == 1)
return indices[0];
int offset = 0;
unchecked
{
for (int i = 0; i < ndims; i++)
offset += strides[i] * indices[i];
}
if (IsBroadcasted)
return offset % BroadcastInfo.OriginalShape.size;
return offset;
}
}
}