SymbolicUtils.jl
SymbolicUtils.jl copied to clipboard
Q: SymbolicUtils.PolyForm() -> StaticPolynomials.Polynomial(). Variable order at evaluation?
The MWE code below converts a Symbolics polynomial expression to a StaticPolynomials one for fast and accurate evaluation [the actual polynomial expression has many more terms and will evaluated repeatedly].
At the point where the StaticPolynomial expression is evaluated, what is the order of the variables; in the case of the example q1, p1, q2, p2, t? Currently I'm testing the MWE using a random vector.
# Test array
x = @SVector rand(5)
StaticPolynomials.evaluate(p_static, x)
excerpted from
# test_symbolics_to_staticpolynomials.jl
using StaticArrays
using StaticPolynomials
using Symbolics
function main()
# Indexed array variables
@variables q[1:2], p[1:2]
# Time variable
@variables t
# Generate the numbered variables {qi, pi | i = 1, 2, . . .}
variables_cv_str = "variables_array = @variables"
for i = 1:2
variables_cv_str = string(variables_cv_str, " ", "q", string(i), " ", "p", string(i))
end
variables_cv_str = string(variables_cv_str, " t")
eval(Meta.parse(variables_cv_str))
@show typeof(variables_array)
# Test expression
expr =
p[1] - q[1]*t - (1//2)*p[1]*(t^2) - (2//1)*q[1]*q[2]*t -
p[1]*q[2]*(t^2) - p[2]*q[1]*(t^2) + (1//6)*q[1]*(t^3) -
(2//3)*p[1]*p[2]*(t^3)
# Substitute {q[i] => qi | i = 1, 2, . . .}
expr =
substitute(
expr,
Dict(
[q[i] => Num(eval(Symbol("q$(i)"))) for i = 1:2]
)
)
# Substitute {p[i] => pi | i = 1, 2, . . .}
expr =
substitute(
expr,
Dict(
[p[i] => Num(eval(Symbol("p$(i)"))) for i = 1:2]
)
)
# Convert Symbolics polynomial to DynamicPolynomials form
@show pf_expr = PolyForm(Symbolics.unwrap(expr))
# Convert the DynamicPolynomials form to StaticPolynomials
@show p_static = StaticPolynomials.Polynomial(pf_expr.p)
# Test array
x = @SVector rand(5)
# Evaluate
@show @time StaticPolynomials.evaluate(p_static, x)
end
begin
main()
end