Search code examples
pythoncurve-fittinglmfit

Set an optimization using LMFIT and Parameters class with condition to be checked


How to use ExpressionModel in LMFIT to fit a conditional model that can be represented as:

from lmfit.models import ExpressionModel
# read(xdata and ydata) here
if xdata < some_parameter_value:
    model = ExpressionModel('expression1')
else:
    model = ExpressionModel('expression2')

How to write this conditional model as one model (global_model) and pass it to the fit method

results = global_model.fit(y, x = x, parameters_dictionary)

some_parameter_value: is a member of parameters_dictionary which is created using Parameters class


Solution

  • lmfit Models are defined independent of the data and cannot be used for "part of the data".

    Perhaps you can rewrite the expression for the model as:

     expr1 if x < x0 else expr2
    

    Otherwise, I think you'll have to write a custom Model that tests the condition and does a different calculation based on that condition.