title: Fitting a 2D-function to a 2D dataset with errors in python
body: <p>I have a 2D np.array as experimental data, so something with a shape like (50,50), corresponding to the pixel of my cam. I have a second np.array of the same shape for errors on each point. So my error isn't just sqrt(n). I would like to use those errors for a fit, so using sum( (experimental - function)^2 / (error of the pixel)^2 ).</p>
  
  <p>Up to now, to handle 2D I just flatten my errorfunction as input for leastsq. This works perfectly. So I have fit parameters taking account of the errors. But there is one Problem: How do I tell leastsq it has also to use them to calculate the errors on my fitparameters?
  I looked at curve_fit, but it seems absolutly not designed for my case. It seems to me it needs a function which you can give an x as an input. But with my convolution I can't simply convert a x-value in a y-value.</p>
  
  <p>so is there a way to do this with leastsq, with curve_fit or an other function?</p>
  
  <p>Here is the script without taking care of the error of the fitparameters:</p>
  
  <pre><code>#img is my experimental data, errimg the array with the errors.
  #My fitfunction is a convolution of a bivariate_normal with a circular
  #box-function given by a function i called ellipsenmatrix.
  
  tx = np.arange(-100,100,1.)    
  ty = np.arange(-100,100,1.)
  X, Y = np.meshgrid(tx, ty)
  
  circ= lambda x: ellipsenmatrix([24.,24.,x],shape=img.shape,kreis='on')
  
  def fitfunc(v):
      conv= ndimage.convolve( circ(v[4]), mlab.bivariate_normal(X, Y, v[0], v[1], v[2], v[3], 0) )
      conv/=np.sum(conv)
      return conv
  
  errfunc = lambda v: ( (fitfunc(v) - img) /errimg ).flatten()
  vinit=[2.5,2.5,0,0,27.5]
  vend, kovmtx, einstell, mesg, success = optimize.leastsq(errfunc, vinit, full_output=True)
  
  print vend
  </code></pre>