Search code examples
pythonpython-2.7numpylmfit

Is this numpy error attributable to a difference in Python 2.7 and 3.5?


The following code comes from an example on http://cars9.uchicago.edu/software/python/lmfit/parameters.html.

from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit
import numpy as np
# create data to be fitted
x = np.linspace(0, 15, 301) 
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
np.random.normal(size=len(x), scale=0.2) )
# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
    """ model decaying sine wave, subtract data"""
    amp = params['amp']
    shift = params['shift']
    omega = params['omega']
    decay = params['decay']
    model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
    return model - data
# create a set of Parameters
params = Parameters()
params.add('amp', value= 10, min=0)
params.add('decay', value= 0.1)
params.add('shift', value= 0.0, min=-np.pi/2., max=np.pi/2)
params.add('omega', value= 3.0)
# do fit, here with leastsq model
minner = Minimizer(fcn2min, params, fcn_args=(x, data))
result = minner.minimize()
# calculate final result
final = data + result.residual
# write error report
report_fit(result)
# try to plot results
try:
    import pylab
    pylab.plot(x, data, 'k+')
    pylab.plot(x, final, 'r')
    pylab.show()
except:
    pass

I tried to run this code in Canopy. When using Canopy 64 bit for Python 3.5 it ran fine. I need to use it in Canopy 32 using Python 2.7. When I changed to use the other editor, it no longer worked. Here is the issue it gives me:

     13     omega = params['omega']
     14     decay = params['decay']
---> 15     model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
     16     return model - data
     17 # create a set of Parameters
AttributeError: 'numpy.float64' object has no attribute 'sin' 

I am confused because the only thing I changed is the version of Python and the version of Canopy. Could this be caused by difference between Python 2.7 and Python 3.5?


Solution

  • Please verify the version of lmfit being used for each version of Python. Prior to lmfit version 0.9.4, you would need to use amp = params['amp'].value (and so on: param.value for all parameters).

    That is, params['amp'] is an instance of an lmfit.Parameter -- it has several attributes, including .value holding it's floating point valuepy. It was only with version 0.9.4 that automatic coercion to numpy arrays became possible.