-
Notifications
You must be signed in to change notification settings - Fork 12
/
batchgetindex.jl
216 lines (199 loc) · 6.88 KB
/
batchgetindex.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
struct ReIndexer{I}
inds::Val{I}
end
struct Colon_From{N} end
getind(_, i, j) = last(i)[j]
getind(data, i, ::Colon_From{N}) where {N} = shrinkaxis(first(i)[N], axes(data, N))
function getrangeinsert(i1)
lastcol = 0
lasticol = 0
allcols = ()
while (nextcol = findnext(i -> !isa(i, Integer), i1, lastcol + 1)) !== nothing
if nextcol == lastcol + 1
lasticol = lasticol + 1
else
lasticol = lasticol + 2
end
lastcol = nextcol
allcols = (allcols..., nextcol => lasticol)
end
return allcols
end
carttotuple(i::CartesianIndex) = i.I
carttotuple(i::Tuple) = i
carttotuple(i::Integer) = (Int(i),)
getnd(::Type{<:Tuple{Vararg{Any,N}}}) where {N} = N
function create_indexvector(a, i)
inds = ()
idim = 1
ibcdim = 1
for ind in i
if isa(ind, AbstractArray) && !isa(ind, AbstractUnitRange)
if eltype(ind) <: Bool
o = carttotuple.(findall(ind))
outshape = (ones(Int, ibcdim - 1)..., length(o))
inds = (inds..., reshape(o, outshape))
idim = idim + ndims(ind)
ibcdim = ibcdim + 1
elseif eltype(ind) <: Union{CartesianIndex,Tuple,Integer}
o = carttotuple.(ind)
N = getnd(eltype(o))
outshape = (ones(Int, ibcdim - 1)..., size(ind)...)
inds = (inds..., reshape(o, outshape))
idim = idim + N
ibcdim = ibcdim + ndims(ind)
else
error("")
end
elseif isa(ind, Colon)
inds = (inds..., Ref((1:size(a, idim),)))
idim = idim + 1
else
inds = (inds..., Ref((ind,)))
idim = idim + 1
end
end
broadcast(inds...) do i...
tuple(Iterators.flatten(i)...)
end
end
function batchgetindex(a, i::AbstractVector{Int})
ci = CartesianIndices(size(a))
return batchgetindex(a, ci[i])
end
function batchgetindex(a, i...)
indvec = create_indexvector(a, i)
return disk_getindex_batch(a, indvec)
end
function prepare_disk_getindex_batch(ar, indstoread)
i1 = first(indstoread)
inserts = getrangeinsert(i1)
inds = collect(Any, 1:ndims(indstoread))
offsets = zeros(Int, ndims(indstoread))
for i in inserts
insert!(inds, last(i), Colon_From{first(i)}())
insert!(offsets, last(i), first(i1[first(i)]) - 1)
end
outindexer = ReIndexer(Val((inds...,)))
it = eltype(indstoread)
affected_chunk_dict = Dict{
ChunkIndex{ndims(ar),OffsetChunks},Vector{Tuple{it,NTuple{ndims(indstoread),Int}}}
}()
for ii in CartesianIndices(indstoread)
for ci in
ChunkIndices(findchunk.(eachchunk(ar).chunks, indstoread[ii]), OffsetChunks())
v = get!(affected_chunk_dict, ci) do
it[]
end
push!(v, (indstoread[ii], ii.I))
end
end
outsize = collect(size(indstoread))
for (iax, iins) in inserts
insert!(outsize, iins, length(i1[iax]))
end
return (; outsize, offsets, affected_chunk_dict, indexer=outindexer)
end
function disk_getindex_batch!(outar, ar, indstoread; prep=nothing)
if prep === nothing
prep = prepare_disk_getindex_batch(ar, indstoread)
end
size(outar) == (prep.outsize...,) || throw(
DimensionMismatch("Output size $(prep.outsize) expected but got $(size(outar))")
)
for (chunk, inds) in prep.affected_chunk_dict
data = ar[chunk]
filldata!(outar, data, inds, prep.indexer)
end
return parent(outar)
end
function disk_getindex_batch(ar, indstoread)
prep = prepare_disk_getindex_batch(ar, indstoread)
outar = OffsetArray(Array{eltype(ar)}(undef, prep.outsize...), prep.offsets...)
return disk_getindex_batch!(outar, ar, indstoread; prep=prep)
end
function filldata!(outar, data, inds, ::ReIndexer{M}) where {M}
for i in inds
inew = map(j -> getind(data, i, j), M)
tofill = data[shrinkaxis.(i[1], axes(data))...]
outar[inew...] = tofill
end
end
function batchsetindex!(a, v, i::AbstractVector{Int})
ci = CartesianIndices(size(a))
return batchsetindex!(a, v, ci[i])
end
function batchsetindex!(a, v, i...)
indvec = create_indexvector(a, i)
return disk_setindex_batch!(a, v, indvec)
end
function disk_setindex_batch!(ar, v, indstoread)
prep = prepare_disk_getindex_batch(ar, indstoread)
size(v) == (prep.outsize...,) ||
throw(DimensionMismatch("Output size $(prep.outsize) expected but got $(size(v))"))
for (chunk, inds) in prep.affected_chunk_dict
data = ar[chunk]
writedata!(v, data, inds, prep.indexer)
ar[chunk] = data
end
return v
end
function writedata!(v, data, inds, ::ReIndexer{M}) where {M}
for i in inds
inew = map(j -> getind(data, i, j), M)
data[shrinkaxis.(i[1], axes(data))...] = v[inew...]
end
end
function shrinkaxis(a, b)
return max(first(a), first(b)):min(last(a), last(b))
end
shrinkaxis(a::Int, _) = a
# Define fallbacks for reading and writing sparse data
function _readblock!(A::AbstractArray, A_ret, r::AbstractVector...)
#Check how sparse the vectors are, we look at the largest stride in the inputs
need_batch = map(approx_chunksize(eachchunk(A)), r) do cs, ids
length(ids) == 1 && return false
largest_jump = maximum(diff(ids))
mi, ma = extrema(ids)
return largest_jump > cs && length(ids) / (ma - mi) < 0.5
end
if any(need_batch)
A_ret .= batchgetindex(A, r...)
else
mi, ma = map(minimum, r), map(maximum, r)
A_temp = similar(A_ret, map((a, b) -> b - a + 1, mi, ma))
readblock!(A, A_temp, map(:, mi, ma)...)
A_ret .= view(A_temp, map(ir -> ir .- (minimum(ir) .- 1), r)...)
end
return nothing
end
function _writeblock!(A::AbstractArray, A_ret, r::AbstractVector...)
#Check how sparse the vectors are, we look at the largest stride in the inputs
need_batch = map(approx_chunksize(eachchunk(A)), r) do cs, ids
length(ids) == 1 && return false
largest_jump = maximum(diff(ids))
mi, ma = extrema(ids)
return largest_jump > cs && length(ids) / (ma - mi) < 0.5
end
if any(need_batch)
batchsetindex!(A, A_ret, r...)
else
mi, ma = map(minimum, r), map(maximum, r)
A_temp = similar(A_ret, map((a, b) -> b - a + 1, mi, ma))
A_temp[map(ir -> ir .- (minimum(ir) .- 1), r)...] = A_ret
writeblock!(A, A_temp, map(:, mi, ma)...)
end
return nothing
end
macro implement_batchgetindex(t)
t = esc(t)
quote
# Define fallbacks for reading and writing sparse data
function DiskArrays.readblock!(A::$t, A_ret, r::AbstractVector...)
return _readblock!(A, A_ret, r...)
end
function DiskArrays.writeblock!(A::$t, A_ret, r::AbstractVector...)
return _writeblock!(A, A_ret, r...)
end
end
end