Problem with Symbolic package: computation of symbolic gradient

Dear all,

I’m trying to use Symbolics package in order to implement the symbolic computation of the gradient of a function. For instance given sin(8.0*x1*x2), I want to compute the partial derivative w.r.t. x1. I implemented the following code:

using Symbolics
@variables x1, x2
f = sin(8.0 * x1 * x2)
D = Differential(x1)
println(eval(build_function(expand_derivatives(D(f)),x1,x2)))(pi,1/8.0)

However I obtain the error

ERROR: LoadError: MethodError: no method matching (::var"#15#16")(::Vector{Float64})
Closest candidates are:
  (::var"#15#16")(::Any, ::Any) at /Users/mencarelli/.julia/packages/SymbolicUtils/qulQp/src/code.jl:349 (method too new to be called from this world context.)

Secondly, I need to implement a loop to compute all the partial derivatives for a function with 20 variables and store them in a variable gradient. How can I do? Thanks for all the suggestions.

@variables x1 x2
f = sin(8.0 * x1 * x2)
D = Differential(x1)

your_function = expand_derivatives(D(f))
# y_f = Symbolics.derivative(f, x1) # alternative

# evaluate the expression at x1=π, x2=1/8
substitute(your_function, Dict(x1=>π, x2=>1/8))

# if you want a callable julia function try this
callable_your_function = eval(build_function(your_function, x1, x2))
callable_your_function(π, 1/8)

# last question
your_gradient = Symbolics.gradient(f, Symbolics.get_variables(f))
1 Like