Jutho / TensorOperations.jl

Julia package for tensor contractions and related operations
https://jutho.github.io/TensorOperations.jl/stable/
Other
443 stars 56 forks source link

Uncontracted indices error when summing two contracted objects #121

Closed tomkimpson closed 1 year ago

tomkimpson commented 1 year ago

MWE:

g_inverse = zeros(Float64,4,4)     # 2 indices
g_∂ = zeros(Float64,4,4,4)         # 3 indicies

@tensor begin
Riemann[ρ,σ,μ,ν] := 
g_inverse[ρ,f]*(g_∂[f,μ,λ] + g_∂[f,λ,μ] - g_∂[μ,λ,f])*g_inverse[λ,h]*(g_∂[h,ν,σ] + g_∂[h,σ,ν] - g_∂[ν,σ,h])
-g_inverse[ρ,i]*(g_∂[i,ν,λ] + g_∂[i,λ,ν] - g_∂[ν,λ,i])*g_inverse[λ,k]*(g_∂[k,μ,σ] + g_∂[k,σ,μ] - g_∂[μ,σ,k])

end

throws an error that it cannot be evaluated to a scalar due to uncontracted indices.

Analytically, the indices contract correctly. Additionally each of the two lines within the @tensor constructor work separately, i.e.


@tensor begin
Riemann[ρ,σ,μ,ν] := 
g_inverse[ρ,f]*(g_∂[f,μ,λ] + g_∂[f,λ,μ] - g_∂[μ,λ,f])*g_inverse[λ,h]*(g_∂[h,ν,σ] + g_∂[h,σ,ν] - g_∂[ν,σ,h])                                
end

is ok ✅ , as is


@tensor begin
Riemann[ρ,σ,μ,ν] := 
-g_inverse[ρ,i]*(g_∂[i,ν,λ] + g_∂[i,λ,ν] - g_∂[ν,λ,i])*g_inverse[λ,k]*(g_∂[k,μ,σ] + g_∂[k,σ,μ] - g_∂[μ,σ,k])                              
end

The summation of these two scalar quantities then seems to throw the error?

Any guidance appreciated 🙏

Jutho commented 1 year ago

I think this is mostly a problem of misunderstanding how expressions are parsed in Julia. A line break typically indicates the end of an expression, unless the parser detects that the expression does not make sense, in which case it will try to add the second line and ignore the line break.

So if you had written

@tensor begin
Riemann[ρ,σ,μ,ν] := 
g_inverse[ρ,f]*(g_∂[f,μ,λ] + g_∂[f,λ,μ] - g_∂[μ,λ,f])*g_inverse[λ,h]*(g_∂[h,ν,σ] + g_∂[h,σ,ν] - g_∂[ν,σ,h]) -
g_inverse[ρ,i]*(g_∂[i,ν,λ] + g_∂[i,λ,ν] - g_∂[ν,λ,i])*g_inverse[λ,k]*(g_∂[k,μ,σ] + g_∂[k,σ,μ] - g_∂[μ,σ,k])                                
end

This works fine. But your input is equivalent to

@tensor begin
Riemann[ρ,σ,μ,ν] :=  g_inverse[ρ,f]*(g_∂[f,μ,λ] + g_∂[f,λ,μ] - g_∂[μ,λ,f])*g_inverse[λ,h]*(g_∂[h,ν,σ] + g_∂[h,σ,ν] - g_∂[ν,σ,h])
end

and

@tensor begin
-g_inverse[ρ,i]*(g_∂[i,ν,λ] + g_∂[i,λ,ν] - g_∂[ν,λ,i])*g_inverse[λ,k]*(g_∂[k,μ,σ] + g_∂[k,σ,μ] - g_∂[μ,σ,k])                              
end

For this second case, TensorOperations will try to evaluate to a scalar (but of course fails), which would then be the return value of this block.

tomkimpson commented 1 year ago

Yes you are right! Sorry I am a new Julia-er so didn't realise this is how it worked. Thanks for your help and apologies for the spam issue!

Jutho commented 1 year ago

No problem, glad I could help out. You've got me worried for a second too, before I noticed the problem.

Also, the error messages of the @tensor macro need to be much improved, they are often very cryptic.