JuliaSymbolics / Symbolics.jl

Symbolic programming for the next generation of numerical software

Home Page:https://docs.sciml.ai/Symbolics/stable/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot sum an array of symbolics because of conversion error

akriegman opened this issue · comments

When I try to sum an array of Symbolics I get a conversion error.

MWE:

@syms a b
l = [a, b]
sum(l, dims=1)

Output:

MethodError: Cannot `convert` an object of type SymbolicUtils.BasicSymbolic{Number} to an object of type Int64

Closest candidates are:

convert(::Type{T}, !Matched::DualNumbers.Dual) where T<:Union{Real, Complex}

@ DualNumbers ~/.julia/packages/DualNumbers/5knFX/src/dual.jl:24

convert(::Type{T}, !Matched::MultivariatePolynomials.AbstractPolynomialLike) where T<:Number

@ MultivariatePolynomials ~/.julia/packages/MultivariatePolynomials/TpRhf/src/conversion.jl:96

convert(::Type{T}, !Matched::T) where T

@ Base Base.jl:84

...

    setindex!(::Vector{Int64}, ::SymbolicUtils.BasicSymbolic{Number}, ::Int64)@array.jl:1021
    setindex!@multidimensional.jl:698[inlined]
    _mapreducedim!(::typeof(identity), ::typeof(Base.add_sum), ::Vector{Int64}, ::Vector{SymbolicUtils.BasicSymbolic{Number}})@reducedim.jl:311
    mapreducedim!(::Function, ::Function, ::Vector{Int64}, ::Vector{SymbolicUtils.BasicSymbolic{Number}})@reducedim.jl:324
    _mapreduce_dim(::Function, ::Function, ::Base._InitialValue, ::Vector{SymbolicUtils.BasicSymbolic{Number}}, ::Int64)@reducedim.jl:371
    mapreduce@reducedim.jl:357[inlined]
    _sum@reducedim.jl:1039[inlined]
    _sum@reducedim.jl:1038[inlined]
    sum@reducedim.jl:1010[inlined]
    top-level scope@[Local: 4](http://localhost:1234/edit?id=f65195a4-d00d-11ee-25e9-41c812cd54ea#)[inlined]

I think what's happening is roughly this: it creates an array to put the results of the summation into, and for some reason it thinks the appropriate type to use is Array{Int64, ...}. So then when it goes to place a BasicSymbolic{Number} in there we get an error. So I guess the problem is with the type prediction infrastructure.

I looked into this more, and I think the deeper problem is that when you call sum with dims it needs an init value, and there is no zero(Any) or zero(BasicSymbolic{Number}), so instead it uses zero(Int64). It would be fine if we had and Any[] full of zero(Int64)s, but instead we have an Int64[], so when we finally do the addition we promote the type correctly but can't store it in the result array.

Anyways, I found a workaround:

@syms a b c d
l = [
    a b
    c d
]
sum(eachslice(l, dims=1))

The documentation doesn't use @syms for a reason. Please use @variables as documented.

using Symbolics
@variables a b
l = [a, b]
sum(l, dims=1)

this works fine.