Repository navigation
Expand file tree
/
Copy pathindexing.v
More file actions
512 lines (486 loc) · 13.5 KB
/
Copy pathindexing.v
File metadata and controls
512 lines (486 loc) · 13.5 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
module vtl
// IndexKind describes one axis operation used by mixed_index.
pub enum IndexKind {
full
slice
integer
array
ellipsis
newaxis
}
struct AxisRange {
start int
length int
step int
}
// TensorIndex describes one axis of a mixed basic and advanced indexing
// operation. Use the constructors below to create valid values.
pub struct TensorIndex {
pub:
kind IndexKind
integer int
start int
stop int
has_start bool
has_stop bool
step int
indices &Tensor[int]
}
// full_index selects every position on one axis.
pub fn full_index() TensorIndex {
return TensorIndex{
kind: .full
step: 1
indices: unsafe { nil }
}
}
// slice_index selects an explicit Python-style [start:stop:step] range.
// Negative boundaries count from the end; a zero step is rejected.
pub fn slice_index(start int, stop int, step int) !TensorIndex {
if step == 0 {
return error('slice_index: step cannot be zero')
}
return TensorIndex{
kind: .slice
start: start
stop: stop
has_start: true
has_stop: true
step: step
indices: unsafe { nil }
}
}
// slice_all selects the whole axis, optionally traversing it in reverse.
pub fn slice_all(step int) !TensorIndex {
if step == 0 {
return error('slice_index: step cannot be zero')
}
return TensorIndex{
kind: .slice
step: step
indices: unsafe { nil }
}
}
// slice_from selects from start through the end of the axis in step
// increments. A negative step traverses toward the beginning.
pub fn slice_from(start int, step int) !TensorIndex {
if step == 0 {
return error('slice_index: step cannot be zero')
}
return TensorIndex{
kind: .slice
start: start
has_start: true
step: step
indices: unsafe { nil }
}
}
// slice_to selects from the beginning of the axis through stop in step
// increments.
pub fn slice_to(stop int, step int) !TensorIndex {
if step == 0 {
return error('slice_index: step cannot be zero')
}
return TensorIndex{
kind: .slice
stop: stop
has_stop: true
step: step
indices: unsafe { nil }
}
}
// integer_index selects one position and removes its axis from the result.
pub fn integer_index(index int) TensorIndex {
return TensorIndex{
kind: .integer
integer: index
indices: unsafe { nil }
}
}
// array_index selects positions using an integer coordinate tensor. All
// coordinate tensors in a mixed_index call are broadcast together.
pub fn array_index(indices &Tensor[int]) TensorIndex {
return TensorIndex{
kind: .array
indices: indices
}
}
// boolean_index selects values where mask is true. The mask shape must match
// the leading tensor dimensions; any remaining tensor dimensions are retained
// after the selected-element axis. The result is an independent row-major
// copy, matching NumPy's a[mask] behavior.
pub fn boolean_index[T](t &Tensor[T], mask &Tensor[bool]) !&Tensor[T] {
if mask.rank() == 0 || mask.rank() > t.rank() {
return error('boolean_index: mask rank must be between 1 and tensor rank')
}
for axis, dimension in mask.shape {
if dimension != t.shape[axis] {
return error('boolean_index: mask shape ${mask.shape} must match the first ${mask.rank()} tensor dimensions ${t.shape[..mask.rank()]}')
}
}
coordinates := nonzero[bool](mask)!
mut indices := []TensorIndex{cap: t.rank()}
for coordinate in coordinates {
indices << array_index(coordinate)
}
for _ in mask.rank() .. t.rank() {
indices << full_index()
}
return mixed_index[T](t, indices)
}
// ellipsis_index expands to enough full axes to cover the unindexed dimensions.
// At most one ellipsis is allowed in a mixed_index call.
pub fn ellipsis_index() TensorIndex {
return TensorIndex{
kind: .ellipsis
indices: unsafe { nil }
}
}
// newaxis_index inserts a size-one axis at this position without consuming an
// input axis. Basic indexing with a new axis remains a view.
pub fn newaxis_index() TensorIndex {
return TensorIndex{
kind: .newaxis
indices: unsafe { nil }
}
}
// mixed_index combines full slices, ranges, scalar integers, broadcasted
// coordinate tensors, ellipsis, and inserted size-one axes. Omitted trailing
// axes select the full axis. If every index is basic, the result is a view; if
// any coordinate tensor is used, the result is an independent row-major copy.
pub fn mixed_index[T](t &Tensor[T], indices []TensorIndex) !&Tensor[T] {
indexed_tensor, expanded_indices := expand_mixed_index[T](t, indices)!
rank := indexed_tensor.rank()
mut axis_indices := []TensorIndex{len: rank, init: full_index()}
for axis, index in expanded_indices {
axis_indices[axis] = index
}
mut ranges := []AxisRange{len: rank}
mut slice_axes := []int{cap: rank}
mut coordinate_axes := []int{cap: rank}
mut first_advanced_axis := rank
mut last_advanced_axis := -1
for axis, index in axis_indices {
match index.kind {
.full {
ranges[axis] = axis_range(indexed_tensor.shape[axis])
slice_axes << axis
}
.slice {
ranges[axis] = normalized_slice_range(indexed_tensor.shape[axis], index) or {
return error('mixed_index: axis ${axis}: ${err}')
}
slice_axes << axis
}
.integer {
normalized := normalize_scalar_index(index.integer, indexed_tensor.shape[axis], axis) or {
return err
}
axis_indices[axis].integer = normalized
first_advanced_axis = if axis < first_advanced_axis {
axis
} else {
first_advanced_axis
}
last_advanced_axis = axis
}
.array {
if isnil(index.indices) {
return error('mixed_index: coordinate tensor for axis ${axis} is nil')
}
coordinate_axes << axis
first_advanced_axis = if axis < first_advanced_axis {
axis
} else {
first_advanced_axis
}
last_advanced_axis = axis
}
}
}
if coordinate_axes.len == 0 {
return mixed_basic_index[T](indexed_tensor, axis_indices, ranges, slice_axes)
}
mut coordinate_tensors := []&Tensor[int]{cap: coordinate_axes.len}
for axis in coordinate_axes {
coordinate_tensors << axis_indices[axis].indices
}
broadcast_coordinates := broadcast_n[int](coordinate_tensors) or {
return error('mixed_index: coordinate tensors cannot be broadcast: ${err}')
}
advanced_shape := broadcast_coordinates[0].shape
advanced_rank := advanced_shape.len
mut advanced_contiguous := true
for axis in first_advanced_axis .. last_advanced_axis + 1 {
if axis_indices[axis].kind == .full || axis_indices[axis].kind == .slice {
advanced_contiguous = false
break
}
}
mut output_shape := []int{cap: rank + advanced_rank}
if advanced_contiguous {
for axis in slice_axes {
if axis < first_advanced_axis {
output_shape << ranges[axis].length
}
}
output_shape << advanced_shape
for axis in slice_axes {
if axis > last_advanced_axis {
output_shape << ranges[axis].length
}
}
} else {
output_shape << advanced_shape
for axis in slice_axes {
output_shape << ranges[axis].length
}
}
mut result := empty[T](output_shape, memory: .row_major)
mut output_index := []int{len: output_shape.len}
mut advanced_index := []int{len: advanced_rank}
mut input_index := []int{len: rank}
mut slice_cursor := 0
mut coordinate_cursor := 0
for flat_index in 0 .. result.size {
decode_flat_coordinate(flat_index, output_shape, mut output_index)
slice_cursor = 0
if advanced_contiguous {
for axis in slice_axes {
if axis < first_advanced_axis {
input_index[axis] = ranges[axis].start + output_index[slice_cursor] * ranges[axis].step
slice_cursor++
}
}
for i in 0 .. advanced_rank {
advanced_index[i] = output_index[slice_cursor + i]
}
slice_cursor += advanced_rank
for axis in slice_axes {
if axis > last_advanced_axis {
input_index[axis] = ranges[axis].start + output_index[slice_cursor] * ranges[axis].step
slice_cursor++
}
}
} else {
for i in 0 .. advanced_rank {
advanced_index[i] = output_index[i]
}
slice_cursor = advanced_rank
for axis in slice_axes {
input_index[axis] = ranges[axis].start + output_index[slice_cursor] * ranges[axis].step
slice_cursor++
}
}
coordinate_cursor = 0
for axis, index in axis_indices {
match index.kind {
.full, .slice {
continue
}
.integer {
input_index[axis] = index.integer
}
.array {
selected := broadcast_coordinates[coordinate_cursor].get(advanced_index)
input_index[axis] = normalize_scalar_index(selected, indexed_tensor.shape[axis], axis) or {
return err
}
coordinate_cursor++
}
}
}
result.data.data[flat_index] = indexed_tensor.get(input_index)
}
return result
}
fn expand_mixed_index[T](t &Tensor[T], indices []TensorIndex) !(&Tensor[T], []TensorIndex) {
rank := t.rank()
mut ellipsis_position := -1
mut consuming_count := 0
mut newaxis_count := 0
for position, index in indices {
match index.kind {
.ellipsis {
if ellipsis_position >= 0 {
return error('mixed_index: only one ellipsis is allowed')
}
ellipsis_position = position
}
.newaxis {
newaxis_count++
}
else {
consuming_count++
}
}
}
if consuming_count > rank {
return error('mixed_index: got ${consuming_count} input-axis indices for rank ${rank}')
}
ellipsis_axes := if ellipsis_position >= 0 { rank - consuming_count } else { 0 }
mut expanded_tensor := t
mut expanded_indices := []TensorIndex{cap: rank + newaxis_count}
mut original_axis := 0
mut expanded_axis := 0
for index in indices {
if index.kind == .ellipsis {
for _ in 0 .. ellipsis_axes {
expanded_indices << full_index()
original_axis++
expanded_axis++
}
continue
}
if index.kind == .newaxis {
mut shape := expanded_tensor.shape.clone()
mut strides := expanded_tensor.strides.clone()
shape.insert(expanded_axis, 1)
strides.insert(expanded_axis, 0)
expanded_tensor = expanded_tensor.as_strided[T](shape, strides)!
expanded_indices << full_index()
expanded_axis++
continue
}
expanded_indices << index
original_axis++
expanded_axis++
}
for _ in original_axis .. rank {
expanded_indices << full_index()
}
return expanded_tensor, expanded_indices
}
fn mixed_basic_index[T](t &Tensor[T], indices []TensorIndex, ranges []AxisRange, slice_axes []int) !&Tensor[T] {
mut shape := []int{cap: slice_axes.len}
mut strides := []int{cap: slice_axes.len}
mut offset := 0
mut has_negative_step := false
for axis, index in indices {
match index.kind {
.full, .slice {
range := ranges[axis]
shape << range.length
strides << t.strides[axis] * range.step
if range.step < 0 {
has_negative_step = true
}
if range.length > 0 {
offset += t.strides[axis] * range.start
}
}
.integer {
offset += t.strides[axis] * index.integer
}
.array {
return error('mixed_index: internal error: coordinate index in basic path')
}
}
}
if has_negative_step {
mut result := empty[T](shape, memory: .row_major)
mut output_index := []int{len: shape.len}
mut input_index := []int{len: t.rank()}
for flat_index in 0 .. result.size {
decode_flat_coordinate(flat_index, shape, mut output_index)
mut output_axis := 0
for axis, index in indices {
match index.kind {
.full, .slice {
range := ranges[axis]
input_index[axis] = range.start + output_index[output_axis] * range.step
output_axis++
}
.integer {
input_index[axis] = index.integer
}
.array {
return error('mixed_index: internal error: coordinate index in basic path')
}
}
}
result.data.data[flat_index] = t.get(input_index)
}
return result
}
mut result := &Tensor[T]{
shape: shape
strides: strides
size: size_from_shape(shape)
data: t.data.offset[T](offset)
memory: .row_major
}
result.ensure_memory()
return result
}
fn axis_range(length int) AxisRange {
return AxisRange{
length: length
step: 1
}
}
fn normalize_scalar_index(index int, length int, axis int) !int {
if index < -length || index >= length {
return error('index ${index} is out of range for axis ${axis} with size ${length}')
}
normalized := if index < 0 { index + length } else { index }
return normalized
}
fn normalized_slice_range(length int, index TensorIndex) !AxisRange {
if index.step == 0 {
return error('slice step cannot be zero')
}
if index.step > 0 {
mut first := if index.has_start { index.start } else { 0 }
mut limit := if index.has_stop { index.stop } else { length }
if index.has_start && first < 0 {
first = if first < -length { 0 } else { first + length }
}
if index.has_stop && limit < 0 {
limit = if limit < -length { 0 } else { limit + length }
}
first = clamp_index(first, 0, length)
limit = clamp_index(limit, 0, length)
distance := limit - first
count := distance / index.step + if distance % index.step == 0 { 0 } else { 1 }
return AxisRange{
start: first
length: count
step: index.step
}
} else {
mut first := if index.has_start { index.start } else { length - 1 }
mut limit := if index.has_stop { index.stop } else { -1 }
if index.has_start && first < 0 {
first = if first < -length { -1 } else { first + length }
}
if index.has_stop && limit < 0 {
limit = if limit < -length { -1 } else { limit + length }
}
first = clamp_index(first, -1, length - 1)
limit = clamp_index(limit, -1, length - 1)
distance := first - limit
count := if distance == 0 {
0
} else if index.step == min_int {
1
} else {
stride := -index.step
distance / stride + if distance % stride == 0 { 0 } else { 1 }
}
return AxisRange{
start: first
length: count
step: index.step
}
}
}
fn clamp_index(value int, min int, max int) int {
return if value < min {
min
} else if value > max {
max
} else {
value
}
}