0

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?

Minsik Seo
  • 15
  • 2

1 Answers1

0

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).

ev-br
  • 24,968
  • 9
  • 65
  • 78
  • Thanks! I think a solving system of linear equations is the most time-consuming task. So re-using is necessary. By the way, because I'm not an Eng. speaker, I wonder: What do you mean by 'brittle?' I mean, I know the meaning of 'brittle' as an Eng. word. But, What does a code is brittle mean? – Minsik Seo Aug 11 '20 at 00:54
  • What I wrote, if implemented literally, depends on the order fun and jac are called. Call jac before fun and you get a jacobian from the previous fun call. – ev-br Aug 11 '20 at 10:12