Skip to content

Commit

Permalink
Fix linear indexing for middle-dimension slices; add more tests
Browse files Browse the repository at this point in the history
This also boosts the speed of linear indexing by about 2-3 fold in my
tests (10^6 elements)
  • Loading branch information
timholy committed Jul 21, 2013
1 parent daa5750 commit e392ec1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
30 changes: 25 additions & 5 deletions base/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,34 @@ end
function translate_linear_indexes(s, n, I, pdims)
idx = Array(Int, length(I))
ssztail = size(s)[n:]
psztail = size(s.parent)[pdims[n:]]
indexestail = s.indexes[pdims[n:]]
# The next gets the strides of dimensions listed in pdims[n:end], relative to the stride of pdims[n]
pstrd = [1]
j = n+1
strd = 1
for i = pdims[n]+1:ndims(s.parent)
strd *= size(s.parent, i-1)
if j <= length(pdims) && i == pdims[j]
push!(pstrd, strd)
j += 1
end
end
# Compute the offset from any omitted dimensions
taildimsoffset = 0
for i = pdims[end]+1:ndims(s.parent)
taildimsoffset += (s.indexes[i]-1)*stride(s.parent, i)
for i = pdims[n]+1:ndims(s.parent)
thisI = s.indexes[i]
if isa(thisI, Integer)
taildimsoffset += (thisI-1)*stride(s.parent, i)
end
end
nd = length(pstrd)
for j=1:length(I)
su = ind2sub(ssztail,I[j])
idx[j] = sub2ind(psztail, [ s.indexes[pdims[n+k-1]][su[k]] for k=1:length(su) ]...) + taildimsoffset
su = ind2sub(ssztail,I[j]) # convert to particular location within indexes
K = taildimsoffset + 1
for k = 1:nd
K += pstrd[k]*(indexestail[k][su[k]]-1) # convert to particular location in parent
end
idx[j] = K
end
idx
end
Expand Down
9 changes: 8 additions & 1 deletion test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,15 @@ sA[1:3,1:5] = -2
sA[:] = -3
@test all(A[:,:,5] .== -3)
@test strides(sA) == (1,3)
sA = sub(A, 1:3, 3, 2:5)
@test Base.parentdims(sA) == 1:3
@test size(sA) == (3,1,4)
@test sA == A[1:3,3,2:5]
@test sA[:] == A[1:3,3,2:5][:]
sA = sub(A, 1:2:3, 1:3:5, 1:2:8)
@test Base.parentdims(sA) == 1:3
@test strides(sA) == (2,9,30)
@test sA[:] == A[1:2:3, 1:3:5, 1:2:8][:]

# slice
A = reshape(1:120, 3, 5, 8)
Expand All @@ -120,7 +126,7 @@ sA = slice(A, 2, 1:5, 1:8)
@test strides(sA) == (3,15)
@test sA[2, 1:8][:] == 5:15:120
@test sA[:,1] == 2:3:14
@test sA[2:5:end] == 5:15:120
@test sA[2:5:end] == 5:15:110
sA[2:5:end] = -1
@test all(sA[2:5:end] .== -1)
@test all(A[5:15:120] .== -1)
Expand All @@ -132,6 +138,7 @@ sA = slice(A, 1:2:3, 3, 1:2:8)
@test Base.parentdims(sA) == [1,3]
@test size(sA) == (2,4)
@test strides(sA) == (2,30)
@test sA[:] == A[sA.indexes...][:]

# get
let
Expand Down

0 comments on commit e392ec1

Please sign in to comment.