Skip to content

Instantly share code, notes, and snippets.

@cossio
Last active August 4, 2018 14:20
Show Gist options
  • Save cossio/2c47f2f4e5264afd4a3ac9a8ae66de1b to your computer and use it in GitHub Desktop.
Save cossio/2c47f2f4e5264afd4a3ac9a8ae66de1b to your computer and use it in GitHub Desktop.
for i = 1:L, a = 1:A
@assert sub2ind((A,L),a,i) == (i-1)*A + a
end
for j=1:L, i=1:L, b=1:A, a=1:A
@assert sub2ind((A,A,L,L),a,b,i,j) == a + (b-1)*A + (i-1)*A*A + (j-1)*A*A*L
end
srand(2);
L = rand(2:10); A = rand(2:10,L);
J = Dict((a,b,i,j) => randn() for i=1:L-1 for j=i+1:L for a=1:A[i] for b=1:A[j]);
h = Dict((a,i) => randn() for i=1:L for a=1:A[i]);
@assert length(J) == sum(A[i]*A[j] for i = 2:L for j=1:i-1)
@assert length(h) == sum(A[i] for i = 1:L)
subJ2inddict = Dict{NTuple{4,Int},Int}()
k = 0
for j=2:L, i=1:j-1, b=1:A[j], a=1:A[i]
k += 1
subJ2inddict[(a,b,i,j)] = k
end
@assert length(subJ2inddict) == length(J)
subh2inddict = Dict{NTuple{2,Int},Int}()
k = 0
for i=1:L, a=1:A[i]
k += 1
subh2inddict[(a,i)] = k
end
@assert length(subh2inddict) == length(h)
function indmap(a,b,i,j,A,L)
off1 = 0
for k = 1 : i-1
off1 += A[k]
end
off2 = 0
for l=1:j-1, k = 1:l-1
off2 += A[k]*A[l]
end
a + (b-1)*A[i] + off1 * A[j] + off2
end
function indmap(a,i,A,L)
off1 = 0
for k=1:L, l=k+1:L
off1 += A[k]*A[l]
end
off2 = 0
for k = 1:i-1
off2 += A[k]
end
off1 + off2 + a
end
f = fill(NaN, length(J) + length(h));
@assert all(isnan.(f))
for i=1:L,j=(i+1):L,a=1:A[i],b=1:A[j]
@assert indmap(a,b,i,j,A,L) == subJ2inddict[(a,b,i,j)]
@assert isnan(f[indmap(a,b,i,j,A,L)])
f[indmap(a,b,i,j,A,L)] = J[(a,b,i,j)]
end
for i=1:L,a=1:A[i]
@assert indmap(a,i,A,L) == sum(A[k]*A[l] for k=1:L-1 for l=k+1:L) + subh2inddict[(a,i)]
@assert isnan(f[indmap(a,i,A,L)])
f[indmap(a,i,A,L)] = h[(a,i)]
end
@assert all(isfinite.(f))
for i=1:L,j=(i+1):L,a=1:A[i],b=1:A[j]
@assert f[indmap(a,b,i,j,A,L)] == J[(a,b,i,j)]
end
for i=1:L,a=1:A[i]
@assert f[indmap(a,i,A,L)] == h[(a,i)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment