Search code examples
pythonnumpyscipy

Use of fsolve and numpy


I have an issue when I'm trying to minimize my (complex matrix) function using fsolve or scipy.optimize.newton but neither of them worked. Indeed, my function is 2*2 matrix with complex values. First, I defined my function in a class I called real and it is called by my main program Main.py:

import sys,os
import numpy as np
import random, math 
from scipy.optimize import fsolve
from scipy import optimize

class real :
    def __init__(self):
        self.w = 2

    def func1(self,eps):
        self.k_ch=2.5*np.exp(eps)
        f=np.array([[0,eps*3*self.k_ch+0.032],[0,self.w]])
        return f  

And my Main.py program is:

import sys, os
import numpy as np
import random, math, cmath
from scipy.optimize import fsolve
from Carlo import *

A=real()
eps=0.003+0.0042j
C=A.func1(eps)

Cp=0
track=1e-03
variable=np.arange(track,0.1,1)
for track in variable:
    Cp=Cp+1
    
    if Cp==1:
         eps_real=0
    elif Cp==1:
         fray=np.array([Cp-1,2])
         eps_real=fray/2*3.14*track

    R_0= fsolve(C,eps.real)
    print R_0
    if xtol<=1e-04:
        value_stock= np.array([Cp-1,2])
    print 'R_0 value is', R_0

But I got this error:

Traceback (most recent call last):
  File "Main.py", line 29, in <module>
    R_0= fsolve(C,eps.real)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 127, in fsolve
    res = _root_hybr(func, x0, args, jac=fprime, **options)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 183, in _root_hybr
    _check_func('fsolve', 'func', func, x0, args, n, (n,))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 14, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: 'numpy.ndarray' object is not callable

Since I'm a beginner with python, I don't know how to deal with it. Can you help me please if you have any idea. It seems like maybe fsolve does not like complex values but I got the same error using scipy.optimize.newton.

Thank you.


Solution

  • I wonder why you use fsolve while you state you want to minimize a function? In case minimization is what you want, this example straight from the scipy.optimize tutorial might set you on track:

    import numpy as np
    from scipy.optimize import minimize
    
    def rosen(x):
        """The Rosenbrock function"""
        return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
    
    x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
    res = minimize(rosen, x0, method='nelder-mead',
                    options={'xtol': 1e-8, 'disp': True})
    
    print(res.x)
    [ 1.  1.  1.  1.  1.]