0

I have some data that I am trying to fit with a model that includes and definite integral equation. My strategy was to use the optimize.leastsq and integrate.quad, I keep getting a type error: "only length-1 arrays can be converted to Python scalars"

Any help would be greatly appreciated.

Here's the relevant part of my code (keep in mind that self.vvals and self.bvals are 1-D arrays, self.L is a float):

def NLFit(self):
    '''fits data to the NL formula'''
    L=self.L

    def model(m0,m1,m2,B): #m0=So, m1=D, m2=NLtau
        return scipy.integrate.quad(lambda t: -m0/(math.sqrt(4*math.pi*m1*t))*math.exp(-   L**2/(4*m1*t))*math.exp(-t/m2)*math.cos(g*muB*B*t/h) , 0, 1e-9)

    def residuals(p,y,x): 
        m0,m1,m2=p
        err=y-model(m0,m1,m2,x)
        return err

    def peval(x,p):
        return model(p[0],p[1],p[2],x)

    #initial conditions
    p0=[1,1,1]

    #find fit
    B=self.bvals
    V=self.vvals
    plsq=scipy.optimize.leastsq(residuals,p0,args=(V,B))

    print plsq[0]
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

1 Answers1

0

Using numpy may help.

Numpy permet de “vectoriser”, i.e. appliquer une fonction à un vecteur/matrice et éviter les boucles. Comme nous avons choisi d’utiliser Numpy à travers import numpy as np, il faut choisir les fonctions usuelles définies dans Numpy

>>> from math import cos
>>> a=np.arange(4, dtype=float)
>>> a array([ 0.,  1.,  2.,  3.])
>>> cos(a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: only length-1 arrays can be converted to Python scalars
>>> np.cos(a) array([ 1.        ,  0.54030231, -0.41614684, -0.9899925 ])

This is fom help files.

kiriloff
  • 25,609
  • 37
  • 148
  • 229