forked from SciSharp/NumSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlice.cs
More file actions
377 lines (334 loc) · 13.7 KB
/
Slice.cs
File metadata and controls
377 lines (334 loc) · 13.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
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace NumSharp
{
/// <summary>
/// NDArray can be indexed using slicing
/// A slice is constructed by start:stop:step notation
///
/// Examples:
///
/// a[start:stop] # items start through stop-1
/// a[start:] # items start through the rest of the array
/// a[:stop] # items from the beginning through stop-1
///
/// The key point to remember is that the :stop value represents the first value that is not
/// in the selected slice. So, the difference between stop and start is the number of elements
/// selected (if step is 1, the default).
///
/// There is also the step value, which can be used with any of the above:
/// a[:] # a copy of the whole array
/// a[start:stop:step] # start through not past stop, by step
///
/// The other feature is that start or stop may be a negative number, which means it counts
/// from the end of the array instead of the beginning. So:
/// a[-1] # last item in the array
/// a[-2:] # last two items in the array
/// a[:-2] # everything except the last two items
/// Similarly, step may be a negative number:
///
/// a[::- 1] # all items in the array, reversed
/// a[1::- 1] # the first two items, reversed
/// a[:-3:-1] # the last two items, reversed
/// a[-3::- 1] # everything except the last two items, reversed
///
/// NumSharp is kind to the programmer if there are fewer items than
/// you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an
/// empty list instead of an error.Sometimes you would prefer the error, so you have to be aware
/// that this may happen.
///
/// Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation
///
/// Note: special IsIndex == true
/// It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension.
/// It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix
///
/// Example:
/// a=[[1, 2], [3, 4]]
/// a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector
/// </summary>
[DebuggerStepThrough]
public class Slice
{
public static readonly Slice All = new Slice(null, null);
public static readonly Slice None = new Slice(0, 0, 1);
public int? Start;
public int? Stop;
public int Step;
public bool IsIndex;
/// <summary>
/// Length of the slice.
/// <remarks>
/// The length is not guaranteed to be known for i.e. a slice like ":". Make sure to check Start and Stop
/// for null before using it</remarks>
/// </summary>
public int? Length => Stop - Start;
/// <summary>
/// ndarray can be indexed using slicing
/// slice is constructed by start:stop:step notation
/// </summary>
/// <param name="start">Start index of the slice, null means from the start of the array</param>
/// <param name="stop">Stop index (first index after end of slice), null means to the end of the array</param>
/// <param name="step">Optional step to select every n-th element, defaults to 1</param>
public Slice(int? start = null, int? stop = null, int step = 1)
{
Start = start;
Stop = stop;
Step = step;
}
public Slice(string slice_notation)
{
Parse(slice_notation);
}
/// <summary>
/// Parses Python array slice notation and returns an array of Slice objects
/// </summary>
public static Slice[] ParseSlices(string multi_slice_notation)
{
return Regex.Split(multi_slice_notation, @",\s*").Where(s => !string.IsNullOrWhiteSpace(s)).Select(token => new Slice(token)).ToArray();
}
/// <summary>
/// Creates Python array slice notation out of an array of Slice objects (mainly used for tests)
/// </summary>
public static string FormatSlices(params Slice[] slices)
{
return string.Join(",", slices.Select(s => s.ToString()));
}
private void Parse(string slice_notation)
{
if (string.IsNullOrEmpty(slice_notation))
throw new ArgumentException("Slice notation expected, got empty string or null");
var match = Regex.Match(slice_notation, @"^\s*([+-]?\s*\d+)?\s*:\s*([+-]?\s*\d+)?\s*(:\s*([+-]?\s*\d+)?)?\s*$|^\s*([+-]?\s*\d+)\s*$");
if (!match.Success)
throw new ArgumentException("Invalid slice notation");
var start_string = Regex.Replace(match.Groups[1].Value ?? "", @"\s+", ""); // removing spaces from match to be able to parse what python allows, like: "+ 1" or "- 9";
var stop_string = Regex.Replace(match.Groups[2].Value ?? "", @"\s+", "");
var step_string = Regex.Replace(match.Groups[4].Value ?? "", @"\s+", "");
var single_pick_string = match.Groups[5].Value;
if (!string.IsNullOrWhiteSpace(single_pick_string))
{
if (!int.TryParse(Regex.Replace(single_pick_string ?? "", @"\s+", ""), out var start))
throw new ArgumentException($"Invalid value for start: {start_string}");
Start = start;
Stop = start + 1;
Step = 1; // special case for dimensionality reduction by picking a single element
IsIndex = true;
return;
}
if (string.IsNullOrWhiteSpace(start_string))
Start = null;
else
{
if (!int.TryParse(start_string, out var start))
throw new ArgumentException($"Invalid value for start: {start_string}");
Start = start;
}
if (string.IsNullOrWhiteSpace(stop_string))
Stop = null;
else
{
if (!int.TryParse(stop_string, out var stop))
throw new ArgumentException($"Invalid value for start: {stop_string}");
Stop = stop;
}
if (string.IsNullOrWhiteSpace(step_string))
Step = 1;
else
{
if (!int.TryParse(step_string, out var step))
throw new ArgumentException($"Invalid value for start: {step_string}");
Step = step;
}
}
#region Equality comparison
public static bool operator ==(Slice a, Slice b)
{
if (ReferenceEquals(a, b))
return true;
if (a is null || b is null)
return false;
return a.Start == b.Start && a.Stop == b.Stop && a.Step == b.Step;
}
public static bool operator !=(Slice a, Slice b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != typeof(Slice))
return false;
var b = (Slice)obj;
return Start == b.Start && Stop == b.Stop && Step == b.Step;
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Slice Index(int index) => new Slice(index, index + 1) {IsIndex = true};
public override string ToString()
{
if (IsIndex)
return $"{Start ?? 0}";
var optional_step = Step == 1 ? "" : $":{Step}";
return $"{(Start == 0 ? "" : Start.ToString())}:{(Stop == null ? "" : Stop.ToString())}{optional_step}";
}
// return the size of the slice, given the data dimension on this axis
// note: this works only with sanitized shapes!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetSize()
{
var astep = Math.Abs(Step);
return (Math.Abs(Start.Value - Stop.Value) + (astep - 1)) / astep;
}
/// <summary>
/// Converts the user Slice into an internal SliceDef which is easier to calculate with
/// </summary>
/// <param name="dim"></param>
/// <returns></returns>
[MethodImpl((MethodImplOptions)768)]
public SliceDef ToSliceDef(int dim)
{
if (IsIndex)
{
var index = Start ?? 0;
if (index < 0)
{
if (Math.Abs(index) > dim)
throw new ArgumentException($"Index {index} is out of bounds for the axis with size {dim}");
return new SliceDef(dim + index);
}
if (index > 0 && index >= dim)
throw new ArgumentException($"Index {index} is out of bounds for the axis with size {dim}");
return new SliceDef(index);
}
if (Step == 0)
return new SliceDef() {Count = 0, Start = 0, Step = 0};
var astep = Math.Abs(Step);
if (Step > 0)
{
var start = Start ?? 0;
var stop = Stop ?? dim;
if (start >= dim)
return new SliceDef() {Count = 0, Start = 0, Step = 0};
if (start < 0)
start = Math.Abs(start) <= dim ? dim + start : 0;
if (stop > dim)
stop = dim;
if (stop < 0)
stop = Math.Abs(stop) <= dim ? dim + stop : 0;
if (start >= stop)
return new SliceDef() {Count = 0, Start = 0, Step = 0};
var count = (Math.Abs(start - stop) + (astep - 1)) / astep;
return new SliceDef() {Start = start, Step = Step, Count = count};
}
else
{
// negative step!
var start = Start ?? dim - 1;
var stop = Stop ?? -1;
if (start < 0)
start = Math.Abs(start) <= dim ? dim + start : 0;
if (start >= dim)
start = dim - 1;
if (Stop < 0)
stop = Math.Abs(stop) <= dim ? dim + stop : -1;
if (start <= stop)
return new SliceDef() {Count = 0, Start = 0, Step = 0};
var count = (Math.Abs(start - stop) + (astep - 1)) / astep;
var retval = new SliceDef() {Start = start, Step = Step, Count = count};
return retval;
}
}
#region Operators
public static Slice operator ++(Slice a)
{
if (a.Start.HasValue)
a.Start++;
if (a.Stop.HasValue)
a.Stop++;
return a;
}
public static Slice operator --(Slice a)
{
if (a.Start.HasValue)
a.Start--;
if (a.Stop.HasValue)
a.Stop--;
return a;
}
public static implicit operator Slice(int index) => new Slice(index, index + 1) {IsIndex = true};
#endregion
}
public struct SliceDef
{
public int Start; // start index in array
public int Step; // positive => forward from Start,
public int Count; // number of steps to take from Start (1 means just take Start, 0 means take nothing, -1 means this is an index)
public SliceDef(int start, int step, int count)
{
(Start, Step, Count) = (start, step, count);
}
public SliceDef(int idx)
{
(Start, Step, Count) = (idx, 1, -1);
}
/// <summary>
/// (Start>>Step*Count)
/// </summary>
/// <param name="def"></param>
public SliceDef(string def)
{
if (def == "()")
{
(Start, Step, Count) = (0, 0, 0);
return;
}
var m = Regex.Match(def, @"\((\d+)>>(-?\d+)\*(\d+)\)");
Start = int.Parse(m.Groups[1].Value);
Step = int.Parse(m.Groups[2].Value);
Count = int.Parse(m.Groups[3].Value);
}
public bool IsIndex
{
[MethodImpl((MethodImplOptions)768)] get => Count == -1;
}
/// <summary>
/// reverts the order of the slice sequence
/// </summary>
/// <returns></returns>
[MethodImpl((MethodImplOptions)768)]
public SliceDef Invert()
{
return new SliceDef() {Count = Count, Start = (Start + Step * Count), Step = -Step};
}
public override string ToString()
{
if (IsIndex)
return $"[{Start}]";
if (Count <= 0)
return "()";
return $"({Start}>>{Step}*{Count})";
}
/// <summary>
/// Merge calculates the resulting one-time slice on the original data if it is sliced repeatedly
/// </summary>
[MethodImpl((MethodImplOptions)768)]
public SliceDef Merge(SliceDef other)
{
if (other.Count == 0)
return new SliceDef() {Start = 0, Step = 0, Count = 0};
var self = this;
if (other.IsIndex)
return new SliceDef(self.Start + other.Start * self.Step);
var result = new SliceDef() {Start = self.Start + other.Start * self.Step, Step = Step * other.Step, Count = other.Count,};
return result;
}
}
}