Inconsistent build_function behavior in Symbolics


is there a good way to make sure that the output function from build_function in Symbolics returns output in the same dimensions as the symbolic function used to generate it?

In the simple example below, if N = 5, running myf returns a sparse matrix (as expected). However, if N=100, it returns a sparse vector. If I reshape it, it becomes a dense vector, defeating the purpose of trying to keep everything sparse. Does anybody have a work around?

using Symbolics, SparseArrays

N = 5 # try with N = 5 and N = 100
_S = sprand(N, N, 0.1) 
_Q = Array(sprand(N, N, 0.1))

F(z) = [
    _S * z 
    _Q * z.^2

Symbolics.@variables z[1:N]

sj = Symbolics.sparsejacobian(F(z), z)

f_expr = build_function(sj, z)
myf = eval(first(f_expr))

reshape(myf(rand(N)), size(sj)) # dense!

What if you do sj = Symbolics.sparsejacobian(F(z), collect(z))?

That doesn’t change the inconsistent output behavior. I think the problem is in build_function because sj seem to look good no matter the size of N. However, myf is a sparse matrix for small N, and a sparse vector for large N (ideally they should both be sparse matrices).