雑多な備忘録です。
@tullio ΨXΨ_[i,α,β] := conj(Ψ[pad(i+m),α])*X[m+2,n+2]*Ψ[pad(i+n),β] (i in 1:6, m in -1:1, n in -1:1)
@tullio Z[i,j,α,β] := conj(V[(m-1)*($N)+i,α]) * Λ[m,n] * V[(n-1)*($N)+m,β]
練習問題
using Tullio
using LinearAlgebra
using BenchmarkTools
# 2-Matrix mutltiplication
X = randn(100,100)
Y = randn(100,100)
Z = X * Y
@tullio Z_tu[i,j] := X[i,k] * Y[k,j]
@show Z ≈ Z_tu
display(@benchmark Z = X * Y)
display(@benchmark @tullio Z_tu[i,j] := X[i,k] * Y[k,j])
# 3-Matrix mutltiplication
X = randn(100,100)
Y = randn(100,100)
Z = randn(100,100)
A = X * Y * Z
@tullio A_tu[i,j] := X[i,k] * Y[k,l] * Z[l,j]
@show A ≈ A_tu
display(@benchmark A = X * Y * Z)
display(@benchmark @tullio A_tu[i,j] := X[i,k] * Y[k,l] * Z[l,j])
# Trace of Matrix
X = randn(1000,1000)
tr_X = tr(X)
@tullio tr_X_tu := X[i,i]
@show tr_X ≈ tr_X_tu
display(@benchmark tr_X = tr(X))
display(@benchmark @tullio tr_X_tu := X[i,i])
# for loop -> Tullio
X = randn(10,10)
Y = randn(100)
Z = zeros(10,100-9)
for i in 1:10, j in 1:100-9
for k in 1:10
Z[i,j] += X[i,k] * Y[j+(k-1)]
end
end
@tullio Z_tu[i,j] := X[i,k] * Y[j+(k-1)] (i in 1:10, j in 1:100-9, k in 1:10)
@tullio Z_tu_2[i,j] := X[i,k] * Y[j+(k-1)] # 実は長さを判別してこっちでもうまくやってくれる
@show Z ≈ Z_tu
@show Z ≈ Z_tu_2
display(@benchmark begin
Z = zeros(10,100-9)
for i in 1:10, j in 1:100-9
for k in 1:10
Z[i,j] += X[i,k] * Y[j+(k-1)]
end
end
end)
display(@benchmark @tullio Z_tu_2[i,j] := X[i,k] * Y[j+(k-1)])
# padding for edge evaluation
J = randn(3,3)
Ψ = randn(1000)
JΨ = zeros(3,1000)
for i in 1:3, j in 2:999 # without edge site
for k in 1:3
JΨ[i,j] += J[i,k] * Ψ[j+(k-2)]
end
end
JΨ[:,1] = J[:,2:3]*Ψ[1:2]
JΨ[:,1000] = J[:,1:2]*Ψ[999:1000]
@tullio JΨ_tu[i,j] := J[i,k] * Ψ[pad(j+(k-2))] (j in 1:1000)
@show JΨ ≈ JΨ_tu
display(@benchmark begin
JΨ = zeros(3,1000)
for i in 1:3, j in 2:999 # without edge site
for k in 1:3
JΨ[i,j] += J[i,k] * Ψ[j+(k-2)]
end
end
JΨ[:,1] = J[:,2:3]*Ψ[1:2]
JΨ[:,1000] = J[:,1:2]*Ψ[999:1000]
end)
display(@benchmark @tullio JΨ_tu[i,j] := J[i,k] * Ψ[pad(j+(k-2))] (j in 1:1000))