-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.go
490 lines (433 loc) · 9.86 KB
/
utils.go
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
package shapes
import (
"reflect"
"unsafe"
"github.com/pkg/errors"
)
type exprtup struct {
a, b Expr
}
func (t exprtup) freevars() varset {
retVal := t.a.freevars()
retVal = append(retVal, t.b.freevars()...)
return unique(retVal)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func prodInts(a []int) int {
retVal := 1
if len(a) == 0 {
return retVal
}
for i := 0; i < len(a); i++ {
retVal *= a[i]
}
return retVal
}
func sumInts(a []int) (retVal int) {
if len(a) == 0 {
return
}
for i := 0; i < len(a); i++ {
retVal += a[i]
}
return
}
func allEq(a []int, e int) bool {
for _, v := range a {
if v != e {
return false
}
}
return true
}
func intsEq(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func substToInt(a substitutable) (int, bool) {
switch at := a.(type) {
case Size:
return int(at), true
case Axis:
return int(at), true
}
return -1, false
}
func axesToInts(a Axes) []int {
return *(*[]int)(unsafe.Pointer(&a))
}
func sizesToInts(a Sizes) []int {
return *(*[]int)(unsafe.Pointer(&a))
}
func arrowToTup(a *Arrow) *exprtup {
return (*exprtup)(unsafe.Pointer(a))
}
func sizelikeToSize(a Sizelike) (Size, error) {
switch at := a.(type) {
case sizeOp:
return at.resolveSize()
case Size:
return at, nil
default:
return 0, errors.Errorf("Cannot resolve size of %v of %T", a, a)
}
}
func extractForAll(a Expr) (UnaryOp, bool) {
if uo, ok := a.(UnaryOp); ok && uo.Op == ForAll {
return uo, true
}
return UnaryOp{}, false
}
func reverse(ts []tok) {
for i, j := 0, len(ts)-1; i < j; i, j = i+1, j-1 {
ts[i], ts[j] = ts[j], ts[i]
}
}
func reverseAxes(a Axes) {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
}
// IsMonotonicInts returns true if the slice of ints is monotonically increasing. It also returns true for incr1 if every succession is a succession of 1
func IsMonotonicInts(a []int) (monotonic bool, incr1 bool) {
var prev int
incr1 = true
for i, v := range a {
if i == 0 {
prev = v
continue
}
if v < prev {
return false, false
}
if v != prev+1 {
incr1 = false
}
prev = v
}
monotonic = true
return
}
// UnsafePermute permutes the xs according to the pattern. Each x in xs must have the same length as the pattern's length.
func UnsafePermute(pattern []int, xs ...[]int) (err error) {
if len(xs) == 0 {
err = errors.New("Permute requres something to permute")
return
}
dims := -1
patLen := len(pattern)
for _, x := range xs {
d := len(x)
if dims == -1 {
dims = len(x)
}
if d != dims || d != patLen {
err = errors.Errorf(dimsMismatch, len(x), len(pattern))
return
}
}
if err = patternCheck(pattern, dims); err != nil {
return
}
unsafePermuteInts(pattern, xs...)
return nil
}
// unsafePermuteInts is a fast path.
func unsafePermuteInts(pattern []int, xs ...[]int) {
dims := len(pattern)
switch dims {
case 0, 1:
case 2:
for _, x := range xs {
x[0], x[1] = x[1], x[0]
}
default:
for i := 0; i < dims; i++ {
to := pattern[i]
for to < i {
to = pattern[to]
}
for _, x := range xs {
x[i], x[to] = x[to], x[i]
}
}
}
}
// strided slice is a very lightweight "tensor"
type stridedSlice struct {
data []byte
stride int
}
// genericUnsafePermute will permute slices according to the given pattern
//
// FUTURE:go2generics - genericUnsafePermute[T](pattern []int, xs ...[]T) error
func genericUnsafePermute(pattern []int, xs ...interface{}) (err error) {
if len(xs) == 0 {
return errors.New("Permute requires something to permute")
}
dims := -1
patLen := len(pattern)
xs2 := make([]stridedSlice, 0, len(xs))
allIntSlices := true
for i, x := range xs {
// check all are slices
T := reflect.TypeOf(x)
if T.Kind() != reflect.Slice {
return errors.Errorf("Cannot permute %v (%dth of xs). Expected a slice. Got %T instead", x, i, x)
}
// check all are ints
if T.Elem().Kind() != reflect.Int {
allIntSlices = false
}
v := reflect.ValueOf(x)
// check the dims
var d int
if dims == -1 {
dims = v.Len()
}
d = v.Len()
if d != dims || d != patLen {
return errors.Errorf(dimsMismatch, d, len(pattern))
}
// all good? now we cast the data into a byte slice.
stride := int(T.Elem().Size())
data := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{Data: v.Pointer(), Len: v.Len() * stride, Cap: v.Cap() * stride}))
xs2 = append(xs2, stridedSlice{data: data, stride: stride})
}
// we redirect to a fast path
// FUTURE:go2generics - when there is generics, genericUnsafePermute will be the exported function UnsafePermute.
if allIntSlices {
intses := make([][]int, 0, len(xs2))
for _, x := range xs2 {
hdr := reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(&x.data[0])),
Len: len(x.data) / x.stride,
Cap: len(x.data) / x.stride,
}
intses = append(intses, *(*[]int)(unsafe.Pointer(&hdr)))
}
unsafePermuteInts(pattern, intses...)
return nil
}
// check that patterns are valid, non monotonic and increasing
if err = patternCheck(pattern, dims); err != nil {
return err
}
// perform permutation
switch dims {
case 0, 1:
case 2:
var tmp []byte
for _, x := range xs2 {
if tmp == nil {
tmp = make([]byte, x.stride)
}
swap2(x, 0, 1, tmp)
}
default:
for i := 0; i < dims; i++ {
to := pattern[i]
for to < i {
to = pattern[to]
}
var tmp []byte
for _, x := range xs2 {
if tmp == nil {
tmp = make([]byte, x.stride)
}
if len(tmp) != x.stride {
tmp = make([]byte, x.stride)
}
swap2(x, i, to, tmp)
}
}
}
return nil
}
// patternCheck checks patterns
func patternCheck(pattern []int, dims int) (err error) {
// check that all the axes are < nDims
// and that there are no axis repeated
seen := make(map[int]struct{})
for _, a := range pattern {
if a >= dims {
err = errors.Errorf(invalidAxis, a, dims)
return
}
if _, ok := seen[a]; ok {
err = errors.Errorf(repeatedAxis, a)
return
}
seen[a] = struct{}{}
}
// no op really... we did the checks for no reason too. Maybe move this up?
if monotonic, incr1 := IsMonotonicInts(pattern); monotonic && incr1 {
err = noopError{}
return
}
return nil
}
func swap2(x stridedSlice, i, j int, tmp []byte) {
if i == j {
// nothing to swap
return
}
bs := x.data
stride := x.stride
switch stride {
case 1:
bs[i], bs[j] = bs[j], bs[i]
default:
a := bs[i*stride : i*stride+stride]
b := bs[j*stride : j*stride+stride]
copy(tmp, a)
copy(a, b)
copy(b, tmp)
}
}
// CheckSlice checks a slice to see if it's sane
func CheckSlice(s Slice, size int) error {
start := s.Start()
end := s.End()
step := s.Step()
if start > end {
return errors.Errorf(invalidSliceIndex, start, end)
}
if start < 0 {
return errors.Errorf(invalidSliceIndex, start, 0)
}
if step == 0 && end-start > 1 {
return errors.Errorf("Slice has 0 steps. Start is %d and end is %d", start, end)
}
if start >= size {
return errors.Errorf("Start %d is greater than size %d", start, size)
}
return nil
}
// SliceDetails is a function that takes a slice and spits out its details. The whole reason for this is to handle the nil Slice, which is this: a[:]
func SliceDetails(s Slice, size int) (start, end, step int, err error) {
if s == nil {
start = 0
end = size
step = 1
} else {
if err = CheckSlice(s, size); err != nil {
return
}
start = s.Start()
end = s.End()
step = s.Step()
if end > size {
end = size
}
}
return
}
// ShapeOf returns the shape of a given datum.
func ShapeOf(a interface{}) Expr {
switch at := a.(type) {
case Shaper:
return at.Shape()
case Exprer:
return at.Shape()
}
t := reflect.TypeOf(a)
switch t.Kind() {
case reflect.Func:
in := t.NumIn()
out := t.NumOut()
if out != 1 {
panic("Cannot handle functions with multiple outputs. Please feel free to file a Pull Request")
}
outExpr := ShapeOf(t.Out(0))
inExpr := make([]Expr, 0, in)
for i := 0; i < in; i++ {
it := t.In(i)
inExpr = append(inExpr, ShapeOf(it))
}
B := Arrow{A: inExpr[len(inExpr)-1], B: outExpr}
for i := in - 2; i >= 0; i-- {
A := inExpr[i]
B = Arrow{A: A, B: B}
}
return B
case reflect.Array:
return Shape{t.Len()}
case reflect.Slice, reflect.Chan:
v := reflect.ValueOf(a)
return Shape{v.Len()}
case reflect.Interface:
panic("Cannot turn Interface type into shape. Please feel free to file a Pull Request")
case reflect.Map:
panic("Cannot turn Map type into shape.")
default:
return Shape{}
}
panic("Unreachable")
}
// ShapesToShapelikes is a utility function that retuns a []Shapelike given a []Shape.
func ShapesToShapelikes(ss []Shape) []Shapelike {
retVal := make([]Shapelike, 0, len(ss))
for _, v := range ss {
retVal = append(retVal, v)
}
return retVal
}
// AreBroadcastable checks that two shapes are mutually broadcastable.
func AreBroadcastable(a, b Shape) (err error) {
if a.Eq(b) {
return noopError{}
}
if a.Dims() != b.Dims() {
return errors.Errorf(dimMismatch, a.Dims(), b.Dims())
}
maxDim := a.Dims()
// now, we check the shapes for broadcastability
// if the shapes are not broadcastable, we return an error
for i := maxDim - 1; i >= 0; i-- {
bDim := a[i]
aDim := b[i]
if bDim != aDim && bDim != 1 && aDim != 1 {
return errors.Errorf(broadcastErr, a, b, i)
}
}
return
}
// CalcBroadcastShape computes the final shape of two mutually broadcastable shapes.
// This function does not check that the shapes are mutually broadcastable.
// Use `AreBroadcastable` for that functionality.
func CalcBroadcastShape(a, b Shape) Shape {
if a.IsScalarEquiv() {
return b
}
if b.IsScalarEquiv() {
return a
}
retVal := make(Shape, 0, a.Dims())
for i, u := range a {
v := b[i]
switch {
case u > v:
// assumes v == 1
retVal = append(retVal, u)
case v > u:
// assumes u == 1
retVal = append(retVal, v)
case u == v:
retVal = append(retVal, u)
}
}
return retVal
}