Strange error in computing trace on product of symbolic matrices in Symbolics.jl

Dear All,

I am a new user of Symbolics.jl and using it to compute trace of product of two symbolic matrices. It seems that if I do not perform a simplify. on the product of the matrices, I get a strange error when computing the trace, but running simplify. on the product before computing trace works without any problem. My sample code is as follows. Am I doing anything wrong? I looked into how to use LinearAlgebra functions on symbolic matrices but could not find anything along this line. Any tips on correct usage/best practice will be much appreciated.

using Symbolics, LinearAlgebra

Symbolics.@variables A[1:3, 1:3], B[1:3, 1:3]

AMat = Symbolics.scalarize(A) 
# AMat is 
# Num[A[1, 1] A[1, 2] A[1, 3]; A[2, 1] A[2, 2] A[2, 3]; A[3, 1] A[3, 2] A[3, 3]]

BMat = Symbolics.scalarize(B)
# BMat is 
# Num[B[1, 1] B[1, 2] B[1, 3]; B[2, 1] B[2, 2] B[2, 3]; B[3, 1] B[3, 2] B[3, 3]]

CMat = AMat*BMat
# CMat is
# Any[A[1, 1]*B[1, 1] + A[1, 2]*B[2, 1] + A[1, 3]*B[3, 1] A[1, 1]*B[1, 2] + A[1, 2]*B[2, 2] + A[1, 3]*B[3, 2] A[1, 1]*B[1, 3] + A[1, 2]*B[2, 3] + A[1, 3]*B[3, 3]; A[2, 1]*B[1, 1] + A[2, 2]*B[2, 1] + A[2, 3]*B[3, 1] A[2, 1]*B[1, 2] + A[2, 2]*B[2, 2] + A[2, 3]*B[3, 2] A[2, 1]*B[1, 3] + A[2, 2]*B[2, 3] + A[2, 3]*B[3, 3]; A[3, 1]*B[1, 1] + A[3, 2]*B[2, 1] + A[3, 3]*B[3, 1] A[3, 1]*B[1, 2] + A[3, 2]*B[2, 2] + A[3, 3]*B[3, 2] A[3, 1]*B[1, 3] + A[3, 2]*B[2, 3] + A[3, 3]*B[3, 3]]

At this point running tr(CMat) gives the error:

Error: 
ERROR: MethodError: no method matching zero(::Type{Any})
This error has been manually thrown, explicitly, so the method may exist but be intentionally marked as unimplemented.

Closest candidates are:
  zero(::Type{Union{Missing, T}}) where T
   @ Base missing.jl:105
  zero(::Type{Union{}}, Any...)
   @ Base number.jl:310
  zero(::Type{Dates.Date})
   @ Dates C:\Users\username\.julia\juliaup\julia-1.11.3+0.x64.w64.mingw32\share\julia\stdlib\v1.11\Dates\src\types.jl:459
  ...

Stacktrace:
 [1] zero(::Type{Any})
   @ Base .\missing.jl:106
 [2] tr(A::Matrix{Any})
   @ LinearAlgebra C:\Users\username\.julia\juliaup\julia-1.11.3+0.x64.w64.mingw32\share\julia\stdlib\v1.11\LinearAlgebra\src\dense.jl:374
 [3] top-level scope
   @ c:\test.jl:18

However, if I run tr(simplify.(CMat)) then I get the correct trace as intended:

A[1, 1]*B[1, 1] + A[1, 2]*B[2, 1] + A[1, 3]*B[3, 1] + A[2, 1]*B[1, 2] + A[2, 2]*B[2, 2] + A[2, 3]*B[3, 2] + A[3, 1]*B[1, 3] + A[3, 2]*B[2, 3] + A[3, 3]*B[3, 3]

What is going on here?

Cmat isn’t inferred as having eltype Num so the generic fallback for tr isn’t able to build the accumulator variable. That should get an issue, should be easy to fix by making matmul return the same thing but with a Num eltype. Why it doesn’t do that by default needs an investigation though

1 Like

Okay thanks for your comment @ChrisRackauckas !