-
Notifications
You must be signed in to change notification settings - Fork 391
FAQ: How to store a casadi.Function in a file? (save, load)
András Retzler edited this page Oct 10, 2022
·
3 revisions
What is saving a loading good for? For example if you have a CasADi expression graph that you created in a python script, you can use it in another python script, or in a MATLAB script, or even your C++ code.
>>> import casadi
>>> x=casadi.MX.sym('x')
>>> f=casadi.Function('f',(x,),(x**2,))
>>> type(f) #this function is basically an expression graph inside the CasADi shared object's memory space:
<class 'casadi.casadi.Function'>
>>> f(3) #we can evaluate it for x=3 and then we get correctly 3^2=9
DM(9)
>>> f.save('f.casadi') #we save it to this file called 'f.casadi'
>>> g=casadi.Function.load('f.casadi') #now that it's saved we can load it from the file.
>>> type(g) #the type is again the same as for f.
<class 'casadi.casadi.Function'>
>>> g(3)
The saved functions will only contain ASCII small letters from a
to z
, it's basically a plain text file and can be transmitted accordingly (you can even send it to a colleague in a chat window 😊).
The encoding used is defined here: https://github.com/casadi/casadi/blob/402fe583f0d3cf1fc77d1e1ac933f75d86083124/casadi/core/serializing_stream.cpp#L178
Tip: you can also save an nlpsol
or a rootfinder
object (FAQTODO double check this)
FAQTODO add a MATLAB example