title: Scipy.optimize - curve fitting with fixed parameters
body: <p>I'm performing curve fitting with <code>scipy.optimize.leastsq</code>. E.g. for a gaussian:</p>
  
  <pre><code>def fitGaussian(x, y, init=[1.0,0.0,4.0,0.1]):
      fitfunc = lambda p, x: p[0]*np.exp(-(x-p[1])**2/(2*p[2]**2))+p[3] # Target function
      errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
      final, success = scipy.optimize.leastsq(errfunc, init[:], args=(x, y))
      return fitfunc, final
  </code></pre>
  
  <p>Now, I want to optionally fix the values of some of the parameters in the fit. I found that suggestions are to use a different package <a href="https://lmfit.github.io/lmfit-py/intro.html" rel="nofollow">lmfit</a>, which I want to avoid, or are very general, like <a href="http://scipy-user.10969.n7.nabble.com/curve-fitting-with-fixed-parameters-td3310.html" rel="nofollow">here</a>.
  Since I need a solution which </p>
  
  <ol>
  <li>works with numpy/scipy (no further packages etc.)</li>
  <li>is independent of the parameters themselves,</li>
  <li>is flexible, in which parameters are fixed or not, </li>
  </ol>
  
  <p>I came up with the following, using a condition on each of the parameters:</p>
  
  <pre><code>def fitGaussian2(x, y, init=[1.0,0.0,4.0,0.1], fix = [False, False, False, False]):
      fitfunc = lambda p, x: (p[0] if not fix[0] else init[0])*np.exp(-(x-(p[1] if not fix[1] else init[1]))**2/(2*(p[2] if not fix[2] else init[2])**2))+(p[3] if not fix[3] else init[3]) 
      errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
      final, success = scipy.optimize.leastsq(errfunc, init[:], args=(x, y))
      return fitfunc, final
  </code></pre>
  
  <p>While this works fine, it's neither practical, nor beautiful. 
  So my question is: Are there better ways of performing curve fitting in scipy for fixed parameters? Or are there wrappers, which already include such parameter fixing?</p>