Skip to content

Instantly share code, notes, and snippets.

@jaeandersson
Created June 28, 2017 16:25
Show Gist options
  • Save jaeandersson/ffab8ba5a0e3bba8a1024ab447b40562 to your computer and use it in GitHub Desktop.
Save jaeandersson/ffab8ba5a0e3bba8a1024ab447b40562 to your computer and use it in GitHub Desktop.
codegen with derivatives
from casadi import *
# Simple function:
x = SX.sym('x',2)
y = SX.sym('f',2)
F = Function('F', [x,y],[sin(x)*cos(y), dot(x,y)], ['x','y'], ['f','g'])
# Generate code, including derivatives
CG = CodeGenerator('F')
CG.add(F)
CG.add(F.forward(1))
CG.add(F.forward(2))
CG.add(F.forward(4))
CG.add(F.forward(8))
CG.add(F.reverse(1))
CG.add(F.reverse(2))
CG.add(F.reverse(4))
CG.add(F.reverse(8))
CG.add(F.jacobian())
print(CG.generate()) # F.c
# Compile
from os import system
system('gcc -fPIC -shared -O3 F.c -o F.so')
# Load as external function
Fex = external('F')
# Embed in an algorithm
a = MX.sym('a', 2)
f,g = Fex(a, a)
J = jacobian(f, a)
Jfun = Function('Jfun', [a], [J, f, g], ['a'], ['J', 'f', 'g'])
print(Jfun.generate()) # Jfun.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment