Skip to content

FAQ: How to use a purely numerical function inside CasADi? a.k.a how to convert a symbol to a number, a.k.a custom functions, a.k.a Callback

Joris Gillis edited this page Jan 24, 2024 · 2 revisions

It is very common for one to have a piece of numerical code lying around in Python/Matlab/C++ that needs to end up inside a CasADi optimization problem. An inexperienced user will typically proceed to ask how we can convert symbols to floats/numbers/values. This is an ill-posed question. A symbol has no numerical value attached to it, so conversion to numbers is meaningless.

The proper question is, how can I represent numerical evaluation in a symbolic way?

There is a whole chapter in the Users Guide devoted to this topic: https://web.casadi.org/docs/#document-custom

The easiest way to start is with Callbacks:

Example in Python: https://github.com/casadi/casadi/blob/main/docs/examples/python/callback.py

Example in Matlab: https://github.com/casadi/casadi/blob/main/docs/examples/matlab/callback.m https://github.com/casadi/casadi/blob/main/docs/examples/matlab/MyCallback.m

You may encounter an error like 'eval_sx' not defined for CallbackInternal in the process. Check here for a solution: https://github.com/casadi/casadi/wiki/FAQ:-how-to-resolve-'eval_sx'-not-defined%3F

The purpose of Callback is to make custom Functions accessible to Python/Matlab users. If you are using CasADi in C++ or if you are a library developer, the solution using external is superior (maintainability, efficiency).

Clone this wiki locally