Vector valued callback function jacobian

105 views
Skip to first unread message

Filippo Tamagnini

unread,
Jun 9, 2020, 3:35:37 AM6/9/20
to CasADi
Hi!

I'm trying to code a callback function that takes one vector as input and produces two vectors as output, the first output vector being the first half of the input vector, the second being the second half.

The code I produced is the following:
import pdb
from casadi import *

class MyCallback(Callback):
   
   
def __init__(self,name,N,opts = {}):
       
Callback.__init__(self)
       
self.N = N
       
self.construct(name,opts)
       
   
def get_n_in(self):
       
return 1
   
   
def get_n_out(self):
       
return 2
   
   
def get_sparsity_in(self,n):
       
return Sparsity.dense((self.N,1))
   
   
def get_sparsity_out(self,n):
       
return Sparsity.dense((self.N//2,1))
   
   
def has_jacobian(self):
       
return True
   
   
def eval(self,arg):
        x
= arg[0];
        y
= x[0:self.N//2]
        z
= x[self.N//2:self.N]
       
return y,z
   
   
def get_jacobian(self,*args):
        x
= SX.sym('x',self.N)
        y
= SX.sym('y',self.N//2)
        z
= SX.sym('z',self.N//2)
        I
= SX.eye(self.N//2)
        Z
= SX((self.N//2,self.N//2))
        jac
= Function("jac_y",[x,y,z],[horzcat(I,Z),horzcat(Z,I)])
       
#pdb.set_trace()
       
return jac
   
x
= DM([1,2,3,4])
print("x = ",x)
F
= MyCallback("F",4)
print(F)
y
,z = F(x)
print("y = ",y,"; z = ",z)
Fjac = F.jacobian()
print(Fjac)


When i create the function, everything is fine until i call the jacobian, where i get this error:
Traceback (most recent call last):

 
File "C:\Users\TamagniniF\Desktop\callback_test.py", line 55, in <module>
   
Fjac = F.jacobian()

 
File "C:\Users\TamagniniF\casadi-windows-py37-b4435a5\casadi\casadi.py", line 12121, in jacobian
   
return _casadi.Function_jacobian(self, *args)

RuntimeError: Error in Function::jacobian for 'F' [CallbackInternal] at .../casadi/core/function.cpp:824:
.../casadi/core/function_internal.cpp:2074: Assertion "ret.n_out()==1" failed:
Notify the CasADi developers.

Is there something in my code causing this error?
What if the jacobian can't be expressed as nicely as a casadi function, should i implement it as a second callback or is there something analogous to the eval method?


Thanks for the answers! Ciao!
Reply all
Reply to author
Forward
0 new messages