0

I am trying to impose bounds and constraints in my quadratic curve fitting process. Objective is to find coefficients a,b and c. Imposing constraint on b: delta-2*a*x is my doubt. How can I add a variable, x in my constraints. Workable code:

from lmfit import Model, Parameters

#create x and y data to be used for curve fitting
xip=[ 0.02237461, 0.0983837 , 0.25707382, 0.56959641, 1.33419197, 4.95835927]
yip=[0.20085822, 0.23583258, 0.28996988, 0.36350284, 0.47981232, 0.67602165] 

#function to fit data: a,b,c needs to be found
def f(xx, a, b, c):
    # constraints: c <=0,  a>0  and 2*a*x+b >= 0
    return a*xx**2 + b*xx + c

fmodel = Model(f)
params = Parameters()

params.add('a', value=-1e-2, vary=True, min = -1e10, max = 0)
params.add('c', value=-4e-2, vary=True, min = -1e10, max =0)
params.add('delta', value=5e-2, vary=True, min=0, max=1e10)
params.add('xpara', value=5, vary=True)
params.add('b', expr = 'delta-2*a*xpara')

result = fmodel.fit(yip, params, xx=xip)
print(result.fit_report())


import  matplotlib.pyplot as plt
op = plt.subplot(1,1,1)
op.scatter(xip,yip)
plt.plot(xip, result.init_fit, 'k--')
#plt.plot(xip, result.best_fit, 'r-')

Thanks !

Edit: I have changed variables, to make this program work. But not sure if it is the right way to apply constraints.

Edit 2: necessary constrains added: c <=0, a>0 and 2*a*x+b >= 0 ;

learnerADV
  • 13
  • 4

1 Answers1

0

What error do you get?

It looks to me like the code should work. But, in your message you said you wanted to constraint c to be delta+b+2*a*x while in your code you have delta-b-2*a*xpara. Is there a sign problem?

You also initialize delta to 5e-2, but set it's maximum value to 0. That seems like a mistake, possibly related to confusing signs.

M Newville
  • 7,486
  • 2
  • 16
  • 29
  • @M Newville, Sorry ! I have modified my code with my actual data. I am here to check: Is it possible to add variable `xx` in constraints ? How `xpara` representing `xx` in this curve fitting process. where xx is nothing but `xip`, the data to be used in the curve fitting process.Thanks ! – learnerADV Nov 25 '16 at 20:08
  • I am not sure I fully understand your question. Parameters have scalars not arrays. When you say "2*a*x+b > 0", x is probably meant to be an array. But since this is not changing, you might be able to assert that "2*a*x_max + b > 0", and know the value for x_max before the fit. Stackoverflow comments aren't a great place for such discussion. Please consider appropriate mailing lists. – M Newville Nov 27 '16 at 04:08
  • Okay Newville. I could use minimize function. The residue `((y-a*x**2-b*x-c)**2).sum()` is used as an objective function. – learnerADV Dec 01 '16 at 12:39
  • OK, glad you got it working. But, I'm not sure what we can learn from your experience. It might be helpful to other SO readers with similar questions if you could clarify what you are doing that solves the problem you were having. – M Newville Dec 03 '16 at 21:41