-
Notifications
You must be signed in to change notification settings - Fork 156
/
array-lib.jl
372 lines (306 loc) · 10.7 KB
/
array-lib.jl
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
import Base: getindex
##### getindex #####
struct GetindexPosthookCtx end
@wrapped function getindex_posthook(f, x::AbstractArray)
if hasmetadata(x, GetindexPosthookCtx)
g = getmetadata(x, GetindexPosthookCtx)
setmetadata(x,
GetindexPosthookCtx,
(res, args...) -> f(g(res, args...), args...))
else
setmetadata(x, GetindexPosthookCtx, f)
end
end
function Base.getindex(x::SymArray, idx::CartesianIndex)
return x[Tuple(idx)...]
end
function Base.getindex(x::SymArray, idx...)
idx = unwrap.(idx)
meta = metadata(unwrap(x))
if shape(x) !== Unknown() && all(i -> i isa Integer, idx)
II = CartesianIndices(axes(x))
ii = CartesianIndex(idx)
@boundscheck begin
if !in(ii, II)
throw(BoundsError(x, idx))
end
end
res = Term{eltype(symtype(x))}(getindex, [x, Tuple(ii)...]; metadata = meta)
elseif all(i -> symtype(i) <: Integer, idx)
shape(x) !== Unknown() && @boundscheck begin
if length(idx) > 1
for (a, i) in zip(axes(x), idx)
if i isa Integer && !(i in a)
throw(BoundsError(x, idx))
end
end
end
end
res = Term{eltype(symtype(x))}(getindex, [x, idx...]; metadata = meta)
elseif length(idx) == 1 && symtype(first(idx)) <: CartesianIndex
i = first(idx)
ii = i isa CartesianIndex ? Tuple(i) : arguments(i)
return getindex(x, ii...)
else
input_idx = []
output_idx = []
ranges = Dict{BasicSymbolic,AbstractRange}()
subscripts = makesubscripts(length(idx))
for (j, i) in enumerate(idx)
if symtype(i) <: Integer
push!(input_idx, i)
elseif i isa Colon
push!(output_idx, subscripts[j])
push!(input_idx, subscripts[j])
elseif i isa AbstractVector
isym = subscripts[j]
push!(output_idx, isym)
push!(input_idx, isym)
ranges[isym] = i
else
error("Don't know how to index by $i")
end
end
term = Term{Any}(getindex, [x, idx...]; metadata = meta)
T = eltype(symtype(x))
N = ndims(x) - count(i -> symtype(i) <: Integer, idx)
res = ArrayOp(atype(symtype(x)){T,N},
(output_idx...,),
x[input_idx...],
+,
term,
ranges)
end
if hasmetadata(x, GetindexPosthookCtx)
f = getmetadata(x, GetindexPosthookCtx, identity)
f(res, x, idx...)
else
res
end
end
# Wrapped array should wrap the elements too
function Base.getindex(x::Arr, idx...)
wrap(unwrap(x)[idx...])
end
function Base.getindex(x::Arr, idx::Symbolic{<:Integer}...)
wrap(unwrap(x)[idx...])
end
function Base.getindex(x::Arr, I::Symbolic{CartesianIndex})
wrap(unwrap(x)[tup(I)...])
end
Base.getindex(I::Symbolic{CartesianIndex}, i::Integer) = tup(I)[i]
function Base.getindex(A::AbstractArray{T}, I::Symbolic{CartesianIndex}) where {T}
term(getindex, A, tup(I)..., type=T)
end
function Base.CartesianIndex(x::Symbolic{<:Integer}, xs::Symbolic{<:Integer}...)
term(CartesianIndex, x, xs..., type=CartesianIndex)
end
import Base: +, -, *
tup(c::CartesianIndex) = Tuple(c)
tup(c::Symbolic{CartesianIndex}) = istree(c) ? arguments(c) : error("Cartesian index not found")
@wrapped function -(x::CartesianIndex, y::CartesianIndex)
CartesianIndex((tup(x) .- tup(y))...)
end
@wrapped function +(x::CartesianIndex, y::CartesianIndex)
CartesianIndex((tup(x) .+ tup(y))...)
end
@wrapped function *(x::CartesianIndex, y::CartesianIndex)
CartesianIndex((tup(x) .* tup(y))...)
end
@wrapped function *(a::Integer, x::CartesianIndex)
CartesianIndex((a * tup(x))...)
end
@wrapped function *(x::CartesianIndex, b::Integer)
CartesianIndex((tup(x) * b)...)
end
function propagate_ndims(::typeof(getindex), x, idx...)
ndims(x) - count(x -> symtype(x) <: Integer, idx)
end
function propagate_shape(::typeof(getindex), x, idx...)
@oops axes = shape(x)
idx1 = to_indices(CartesianIndices(axes), axes, idx)
([1:length(x) for x in idx1 if !(symtype(x) <: Number)]...,)
end
propagate_eltype(::typeof(getindex), x, idx...) = geteltype(x)
function SymbolicUtils.promote_symtype(::typeof(getindex), X, ii...)
@assert all(i -> i <: Integer, ii) "user arrterm to create arr term."
eltype(X)
end
#### Broadcast ####
#
using Base.Broadcast
Base.broadcastable(s::SymArray) = s
struct SymBroadcast <: Broadcast.BroadcastStyle end
Broadcast.BroadcastStyle(::Type{<:SymArray}) = SymBroadcast()
Broadcast.result_style(::SymBroadcast) = SymBroadcast()
Broadcast.BroadcastStyle(::SymBroadcast, ::Broadcast.BroadcastStyle) = SymBroadcast()
isonedim(x, i) = shape(x) == Unknown() ? false : isone(size(x, i))
function Broadcast.copy(bc::Broadcast.Broadcasted{SymBroadcast})
# Do the thing here
ndim = mapfoldl(ndims, max, bc.args, init=0)
subscripts = makesubscripts(ndim)
onedim_count = mapreduce(+, bc.args) do x
if ndims(x) != 0
map(i -> isonedim(x, i) ? 1 : 0, 1:ndim)
else
map(i -> 1, 1:ndim)
end
end
extruded = map(x -> x < length(bc.args), onedim_count)
expr_args′ = map(bc.args) do x
if ndims(x) != 0
subs = map(i -> extruded[i] && isonedim(x, i) ?
1 : subscripts[i], 1:ndims(x))
x[subs...]
elseif x isa Base.RefValue
x[]
else
x
end
end
expr = term(bc.f, expr_args′...) # Imagine x .=> y -- if you don't have a term
# then you get pairs, and index matcher cannot
# recurse into pairs
Atype = propagate_atype(broadcast, bc.f, bc.args...)
args = map(x -> x isa Base.RefValue ? Term{Any}(Ref, [x[]]) : x, bc.args)
ArrayOp(Atype{symtype(expr),ndim},
(subscripts...,),
expr,
+,
Term{Any}(broadcast, [bc.f, args...]))
end
# On wrapper:
struct SymWrapBroadcast <: Broadcast.BroadcastStyle end
Base.broadcastable(s::Arr) = s
Broadcast.BroadcastStyle(::Type{<:Arr}) = SymWrapBroadcast()
Broadcast.result_style(::SymWrapBroadcast) = SymWrapBroadcast()
Broadcast.BroadcastStyle(::SymWrapBroadcast,
::Broadcast.BroadcastStyle) = SymWrapBroadcast()
Broadcast.BroadcastStyle(::SymBroadcast,
::SymWrapBroadcast) = Broadcast.Unknown()
function Broadcast.copy(bc::Broadcast.Broadcasted{SymWrapBroadcast})
args = map(bc.args) do arg
if arg isa Broadcast.Broadcasted
return Broadcast.copy(arg)
else
return arg
end
end
wrap(broadcast(bc.f, map(unwrap, args)...))
end
#################### TRANSPOSE ################
#
@wrapped function Base.adjoint(A::AbstractMatrix)
@syms i::Int j::Int
@arrayop (i, j) A[j, i] term = A'
end
@wrapped function Base.adjoint(b::AbstractVector)
@syms i::Int
@arrayop (1, i) b[i] term = b'
end
import Base: *, \
using LinearAlgebra
isdot(A, b) = isadjointvec(A) && ndims(b) == 1
isadjointvec(A::Adjoint) = ndims(parent(A)) == 1
isadjointvec(A::Transpose) = ndims(parent(A)) == 1
function isadjointvec(A)
if istree(A)
(operation(A) === (adjoint) ||
operation(A) == (transpose)) && ndims(arguments(A)[1]) == 1
else
false
end
end
isadjointvec(A::ArrayOp) = isadjointvec(A.term)
# TODO: add more such methods
function getindex(A::AbstractArray, i::Symbolic{<:Integer}, ii::Symbolic{<:Integer}...)
Term{eltype(A)}(getindex, [A, i, ii...])
end
function getindex(A::AbstractArray, i::Int, j::Symbolic{<:Integer})
Term{eltype(A)}(getindex, [A, i, j])
end
function getindex(A::AbstractArray, j::Symbolic{<:Integer}, i::Int)
Term{eltype(A)}(getindex, [A, j, i])
end
function getindex(A::Arr, i::Int, j::Symbolic{<:Integer})
wrap(unwrap(A)[i, j])
end
function getindex(A::Arr, j::Symbolic{<:Integer}, i::Int)
wrap(unwrap(A)[j, i])
end
function _matmul(A, B)
@syms i::Int j::Int k::Int
if isadjointvec(A)
op = operation(A.term)
return op(op(B) * first(arguments(A.term)))
end
return @arrayop (i, j) A[i, k] * B[k, j] term = (A * B)
end
@wrapped (*)(A::AbstractMatrix, B::AbstractMatrix) = _matmul(A, B)
@wrapped (*)(A::AbstractVector, B::AbstractMatrix) = _matmul(A, B)
function _matvec(A, b)
@syms i::Int k::Int
sym_res = @arrayop (i,) A[i, k] * b[k] term=(A*b)
if isdot(A, b)
return sym_res[1]
else
return sym_res
end
end
@wrapped (*)(A::AbstractMatrix, b::AbstractVector) = _matvec(A, b)
# specialize `dot` to dispatch on `Symbolic{<:Number}` to eventually work for
# arrays of (possibly unwrapped) Symbolic types, see issue #831
@wrapped LinearAlgebra.dot(x::Number, y::Number) = conj(x) * y
#################### MAP-REDUCE ################
#
@wrapped Base.map(f, x::AbstractArray) = _map(f, x)
@wrapped Base.map(f, x::AbstractArray, xs...) = _map(f, x, xs...)
@wrapped Base.map(f, x, y::AbstractArray, z...) = _map(f, x, y, z...)
@wrapped Base.map(f, x, y, z::AbstractArray, w...) = _map(f, x, y, z, w...)
function _map(f, x, xs...)
N = ndims(x)
idx = makesubscripts(N)
expr = f(map(a -> a[idx...], [x, xs...])...)
Atype = propagate_atype(map, f, x, xs...)
ArrayOp(Atype{symtype(expr),N},
(idx...,),
expr,
+,
Term{Any}(map, [f, x, xs...]))
end
@inline _mapreduce(f, g, x, dims, kw) = mapreduce(f, g, x; dims=dims, kw...)
function scalarize_op(::typeof(_mapreduce), t)
f, g, x, dims, kw = arguments(t)
# we wrap and unwrap to make things work smoothly.
# we need the result unwrapped to allow recursive scalarize to work.
unwrap(_mapreduce(f, g, collect(wrap(x)), dims, kw))
end
@wrapped function Base.mapreduce(f, g, x::AbstractArray; dims=:, kw...)
idx = makesubscripts(ndims(x))
out_idx = [dims == (:) || i in dims ? 1 : idx[i] for i = 1:ndims(x)]
expr = f(x[idx...])
T = symtype(g(expr, expr))
if dims === (:)
return Term{T}(_mapreduce, [f, g, x, dims, (kw...,)])
end
Atype = propagate_atype(_mapreduce, f, g, x, dims, (kw...,))
ArrayOp(Atype{T,ndims(x)},
(out_idx...,),
expr,
g,
Term{Any}(_mapreduce, [f, g, x, dims, (kw...,)]))
end
for (ff, opts) in [sum => (identity, +, false),
prod => (identity, *, true),
any => (identity, (|), false),
all => (identity, (&), true)]
f, g, init = opts
@eval @wrapped function (::$(typeof(ff)))(x::AbstractArray;
dims=:, init=$init)
mapreduce($f, $g, x, dims=dims, init=init)
end
@eval @wrapped function (::$(typeof(ff)))(f::Function, x::AbstractArray;
dims=:, init=$init)
mapreduce(f, $g, x, dims=dims, init=init)
end
end