I'm working with scipy.optimize
library.
In the adjoint variable method, some of the resulted values from the objective function are needed to compute the jacobian.
Is that possible to use them in the jacobian function without using global
variables?
For example,
def fun(x):
'''
something, something...
'''
# solving system equation.
u = spsolve(K,f)
return u.dot(f)
def jac(x):
'''
something, something...
'''
# computing jacobian using the adjoint method
return -(u.T@K@u).flatten()
In the jac
function, u
and K
are necessary...
How can I do this?
Use a class with two callables, fun
and jac
, and store the intermediate results on the instance. I.e. fun
fills in self.u
and self.K
, which jac
uses.
Note however that this is brittle and give it a thought whether you really need this (that is, write it all with recomputing everything, check the profile, and if and only if these computations are a bottleneck, then OK, use a class or a global).