Search code examples
pythonscipyscipy-optimize

supply extra parameter as function argument for scipy optimize curve_fit


I am defining a piecewise function for some data,

def fit_jt(x, e1, e2, n1, E1, E2, N1, N2):
  a = 1.3
  return np.piecewise(x, [x <= a, x > a], [
      lambda x: 1 / e1 +
      (1 - np.float128(np.exp(-e2 * x / n1))) / e2, lambda x: 1 / E1 +
      (1 - np.float128(np.exp(-E2 * x / N1))) / E2 + x / N2
  ])

which is called in main as:

 popt_jt, pcov_jt = optimize.curve_fit(fit_jt,
                                          time.values,
                                          jt.values,
                                          method='trf')

Now, the problem here is the a is hardcoded in the function fit_jt. Is it possible to supply the value of a from the main (without making a lot of changes)?


Solution

  • Use a factory function that returns a fit_it function with the desired value of a "baked in" via a closure:

    def make_fit_it(a):
        def fit_jt(x, e1, e2, n1, E1, E2, N1, N2):
          return np.piecewise(x, [x <= a, x > a], [
              lambda x: 1 / e1 +
              (1 - np.float128(np.exp(-e2 * x / n1))) / e2, lambda x: 1 / E1 +
              (1 - np.float128(np.exp(-E2 * x / N1))) / E2 + x / N2
          ])
        return fit_it
    

    To use it:

    popt_jt, pcov_jt = optimize.curve_fit(make_fit_jt(1.3),
                                          time.values,
                                          jt.values,
                                          method='trf')