Giuseppe P.
Giuseppe P.

Reputation: 21

passing the Jacobian to newton_krylov nonlinear solver in python

I want to solve a nonlinear system of algebraic equations by using newton_krylov solver in python.

The function defining the system of equations looks like:

def sys(x, param1, param2, param3, param4):
    
    ...
    
    return f

It gets a vector x at the input, together with three vectors param1, param2, param3 and one number param4, that serve as parameters, and it returns another vector f at the output. I have also a function that gives the Jacobian of the system; it looks like

def jac(x, param1, param2, param3):
    
    dim, =x.shape  # this is the first line of this function that appears to be problematic
    ...
    
    return jacob

This function takes at input a vector x, together with the same parameters as sys a part from param4, and it returns another vector jacob.

Finally the solver is called as following

sol=newton_krylov(lambda x:sys(x, param1, param2, param3, param4),guess,method=jac(x, param1, param2, param3))

At this point I get an error message at the line dim, =x.shape in the jac function that reads: ValueError: too many values to unpack (expected 1).

I believe that the solver does not understand that x in method=jac(x, param1, param2, param3) is the vector of unknowns variables, but I do not know how to solve this problem.

A big thanks to anyone who might have the answer.

Upvotes: 1

Views: 194

Answers (1)

Lisa
Lisa

Reputation: 204

The vector x has shape (n,1) where n is the number of values in the vector. Because of this, x.shape returns (n,1), but you are expecting it to return (n,). A solution is to capture the 1, but not store it. i.e.

dim,_ = x.shape

Upvotes: 1

Related Questions