Skip to content

cse fails to do anything when building sparse matrices #743

@baggepinnen

Description

@baggepinnen
using Symbolics: variables
using Symbolics
function cartpole(x, u)
    mc, mp, l, g = 1.0, 0.2, 0.5, 9.81

    q  = x[SA[1, 2]]
    qd = x[SA[3, 4]]

    s = sin(q[2])
    c = cos(q[2])

    H = [mc+mp mp*l*c; mp*l*c mp*l^2]
    C = [0 -mp*qd[2]*l*s; 0 0]
    G = [0, mp * g * l * s]
    B = [1, 0]

    qdd = (-H) \ (C * qd + G - B * u[1])
    return [qd; qdd]
end

x = variables(:x, 1:4)
u = variables(:u, 1:2)
xp = cartpole(x, u)
c = sum(abs2, xp)
vars = [x; u]
hs = Symbolics.sparsehessian(c, vars)
h = build_function(hs, x, u; expression=Val{false}, cse=true)
H = h[1](randn(4), randn(4)) # Show sparsity pattern

produces an in-place function h[2] with code like this

ˍ₋out.nzval[10] = (+)(
    (*)(
        (+)(
            0.8333333333333334,
            (/)(
                (*)(-0.006944444444444446, (^)((cos)(ˍ₋arg1[2]), 2)),
                (+)(-0.05, (*)(0.008333333333333335, (^)((cos)(ˍ₋arg1[2]), 2))),
            ),
        ),
        (+)(
            1.6666666666666667,
            (/)(
                (*)(-0.013888888888888892, (^)((cos)(ˍ₋arg1[2]), 2)),
                (+)(-0.05, (*)(0.008333333333333335, (^)((cos)(ˍ₋arg1[2]), 2))),
            ),
        ),
    ),
    (/)(
        (*)(0.013888888888888892, (^)((cos)(ˍ₋arg1[2]), 2)),
        (^)((+)(-0.05, (*)(0.008333333333333335, (^)((cos)(ˍ₋arg1[2]), 2))), 2),
    ),
)

where the expression (^)((cos)(ˍ₋arg1[2]), 2)) appears 6 times.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions