What is optimize.root in SciPy?

Overview

SciPy is an open-source library provided by Python dedicated to scientific computation. The optimize package in SciPy provides several common optimization algorithms such as least squares, minimization, curve fitting, etc. The optimize.root function is used to calculate the root of a vector function with the help of various solver methods.

Syntax

scipy.optimize.root(fun, x0, args=(), method='hybr',
jac=None, tol=None, callback=None, options={'func': None,
'col_deriv': 0, 'xtol': 1.49012e-08, 'maxfev': 0,
'band': None, 'eps': None, 'factor': 100, 'diag': None})

Parameters

  • fun: This is a vector function for which we find the root.

  • x0: This is an n-dimensional array representing the initial guess.

  • args: This is an optional argument passed to the objective function and its Jacobian.

  • method: This is an optional argument to provide the type of solver method, which can be hybr, lm, broyden1, and many more.

  • jac: This can be a boolean or callable function. If jac is a callable function, it returns the Jacobian of fun. If it is a boolean value set to false, then the Jacobian will be estimated numerically. Otherwise, fun is assumed to return the value of the Jacobian along with the objective function.

  • tol: This is an optional argument representing the tolerance of function termination.

  • callback: This is an optional function argument. It is invoked on every iteration as callback(x,f) where x is the current iteration’s solution, and f is the corresponding residual function.

  • options: This is a dictionary of solver options.

Return value

This function returns a solution represented by the OptimizeResult object. As part of the object, there are three main components returned:

  • x: This contains the solution array.
  • success: This tells that the algorithm exited successfully.
  • message: This displays the message produced on the algorithm’s termination.

Example

The following code shows how we can use the optimize.root function on a system of non-linear equations.

from scipy import optimize
import numpy as np
def base_fun(x):
return [
x[1] + 1.5 * (x[1] + x[0])**2 - 3.0,
0.5 * (x[0] - x[1])**3 + x[0]]
def jacobian(a):
return np.array([[1 + 1.5 * (a[0])**2,
-2.5 * (a[0] - a[1])**2],
[-1.5 * (a[1] - a[0])**3,
1 + 1.5 * (a[0] + a[1])**2]]
)
res = optimize.root(base_fun, [0, 0], jac=jacobian, method='anderson')
print(res.x)

Explanation

  • Line 3: We create a vector function.
  • Line 8: We create a function to calculate the Jacobian.
  • Line 15: We use the optimize.root function to find the root of the vector function using the anderson helper method.
  • Line 16: We print the solution array x of the OptimizeResult object to the console.