Search code examples
pythonpython-2.7scipy

Cannot cast array data from dtype('O') to dtype('float64')


I am using scipy's curve_fit to fit a function to some data, and receive the following error;

Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

which points me to this line in my code;

popt_r, pcov = curve_fit(
                    self.rightFunc, np.array(wavelength)[beg:end][edgeIndex+30:], 
                    np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0],
                    p0=[self.m_right, self.a_right])

rightFunc is defined as follows;

def rightFunc(self, x, m, const):

    return np.exp(-(m*x + const))

As I understand it, the 'O' type refers to a python object, but I can't see what is causing this error.

Complete Error:

Image detailing the error received

Any ideas for what I should investigate to get to the bottom of this?


Solution

  • Typically these scipy functions require parameters like:

    curvefit( function, initial_values, (aux_values,), ...)
    

    where the tuple of aux_values is passed through to your function along with the current value of the main variable.

    Is the dstack expression this aux_values? Or a concatenation of several. It may need to be wrapped in a tuple.

    (np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0],)
    

    We may need to know exactly where this error arises, not just which line of your code does it. We need to know what value is being converted. Where is there an array with dtype object?