I’m having issues removing type instabilities from the function below, and would appreciate some tips.
A = rand(36,36);
out = [2]; sysdims = [2,9,2];
@code_warntype ptrace2(A,out,sysdims)
function ptrace2{T<:Number}(A::Matrix{T},out,sysdims)
nsys = length(sysdims)
keep = setdiff(1:nsys,out)
keepdims = sysdims[keep]
outdims = sysdims[out]::Vector{Int}
N = prod(keepdims)
R = Base.product(range.(1,keepdims)...)
S = Base.product(range.(1,outdims)...)
B = zeros(T,N,N)
inds_ii = Vector{Int}(nsys)
inds_jj = Vector{Int}(nsys)
for r in R, q in R
i, j = tindex(q,keepdims), tindex(r,keepdims)
for l=1:length(keep)
inds_ii[keep[l]] = q[l]
inds_jj[keep[l]] = r[l]
end
for s in S
for l=1:length(out)
inds_ii[out[l]] = s[l]
inds_jj[out[l]] = s[l]
end
ii = tindex(inds_ii,sysdims)
jj = tindex(inds_jj,sysdims)
B[i,j] += A[ii,jj]
end
end
return B
end
function tindex(inds,sysdims)
N = length(inds)
i = inds[N]
d = 1
for n = N-1:-1:1
d *= sysdims[n+1]
i += d * (inds[n]-1)
end
return i
end