2

I want to fit a set of data with a simple sin^2 function and want to determine its minima based on the fitted parameters.

Here's my code:

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize

data = np.loadtxt('data.txt', usecols=(0,1))
x = data[:,0]*np.pi/180
y = data[:,1]

plt.scatter(x, y, c='red')

def sine(t,a,b,c):
    return a*(np.sin(b*(t-c)))**2

params, cov = optimize.curve_fit(sine, x, y, p0=[9500, 0.5, 0])
print(params)

t = np.linspace(0, 2*np.pi/3, 120) 
plt.plot(t, sine(t, *params), 'black')

plt.show()

optimize.minimize(sine(t, *params), x0=0)

Everything is fine except for the minimize call as I get the following error (with a full traceback):

TypeError                                 Traceback (most recent call last)
~\Documents\CNR\Calibrazione_lamine_20181112\Fit.py in <module>()
     23 plt.show()
     24 
---> 25 optimize.minimize(sine(t, *params), x0=0)

~\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    442         return _minimize_cg(fun, x0, args, jac, callback, **options)
    443     elif meth == 'bfgs':
--> 444         return _minimize_bfgs(fun, x0, args, jac, callback, **options)
    445     elif meth == 'newton-cg':
    446         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in _minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, maxiter, disp, return_all, **unknown_options)
    911     else:
    912         grad_calls, myfprime = wrap_function(fprime, args)
--> 913     gfk = myfprime(x0)
    914     k = 0
    915     N = len(x0)

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in function_wrapper(*wrapper_args)
    290     def function_wrapper(*wrapper_args):
    291         ncalls[0] += 1
--> 292         return function(*(wrapper_args + args))
    293 
    294     return ncalls, function_wrapper

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in approx_fprime(xk, f, epsilon, *args)
    686 
    687     """
--> 688     return _approx_fprime_helper(xk, f, epsilon, args=args)
    689 
    690 

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in _approx_fprime_helper(xk, f, epsilon, args, f0)
    620     """
    621     if f0 is None:
--> 622         f0 = f(*((xk,) + args))
    623     grad = numpy.zeros((len(xk),), float)
    624     ei = numpy.zeros((len(xk),), float)

~\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in function_wrapper(*wrapper_args)
    290     def function_wrapper(*wrapper_args):
    291         ncalls[0] += 1
--> 292         return function(*(wrapper_args + args))
    293 
    294     return ncalls, function_wrapper

TypeError: 'numpy.ndarray' object is not callable.

I'm missing something but I don't know what.


I'm adding the data file to make this program run, as suggested

0   405
5   20
10  350
15  1380
20  2900
25  4750
30  6450
35  8100
40  9100
45  9800
50  10100
55  10250
60  9400
65  8400
70  6430
75  4900
80  3030
85  1500
90  400
95  17
100 410
105 1550
110 3100
115 4850
120 6780
6
  • I guess you just need x0=[0] or something like this (depending on how many variables you use). Just make sure to provide a list of same length as the number of variables. Commented Nov 23, 2018 at 11:06
  • I already tried to use x0=[0] but i get the same error. Commented Nov 23, 2018 at 11:32
  • Ok, could you provide some data then which reproduce the error?! That makes it easier to help. Commented Nov 23, 2018 at 11:52
  • Could you explain what exactly you would like to achieve by this minimize call? You already fitted the parameters using curve_fit. Commented Nov 23, 2018 at 12:39
  • 1
    I want to find the values of the angles which minimize my function and optimize.minimize(sine, x0=[0], args=(params[0], params[1], params[2])) is apparently working fine. Thank you! Commented Nov 23, 2018 at 12:56

2 Answers 2

1

minimize expects a function as first argument, however, you currently pass

sine(t, *params)

which is a numpy array.

You can fix this and do:

print(optimize.minimize(sine, x0=[0], args=tuple(params)))

This will print

      fun: 2.4080485986582715e-12
 hess_inv: array([[1.15258817e-05]])
      jac: array([8.19961349e-09])
  message: 'Optimization terminated successfully.'
     nfev: 18
      nit: 4
     njev: 6
   status: 0
  success: True
        x: array([0.09203053])
Sign up to request clarification or add additional context in comments.

Comments

0

In the documentation of scipy, optimize.minimize function takes ndarray or shape(n) as an input for x, not an integer. I think the error is raised from there because in their error trace

--> 913     gfk = myfprime(x0)

the error is raised form this function.

Documentation link.

1 Comment

I verified that the input for x, is indeed an ndarray of shape(n,), so the problem is probably something else

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.