I'm trying to fit a function to some data in Python using the LMFIT library for nonlinear functions. It's easy enough, but I want to know if there's a way to restrict some properties of the fitted values.
For example, in the following code I fit my data to optimize values A, B and C. But I also want the ratio of A to B to be pi/4 times some integer. Is there a way to impose this restriction?
from lmfit import Model
import numpy
from numpy import cos, sin, pi, linspace
Upload data:
data = numpy.genfromtxt('data')
axis = numpy.genfromtxt('axis')
Define function:
def func(x, A, B, C):
return (A*cos(x)*cos(x) + B*sin(x)*sin(x) + 2*C*sin(x)*cos(x))**2
I must make an initial guess for my parameters:
a = 0.009
b = 0.3
c = 0.3
Then create a model to fit my function:
func_model = Model(func)
Fit the function to input data, with initial guesses (A = a, B = b, C = c):
result = func_model.fit(data, x=axis, A = a, B = b, C = c)
fitted_vals = result.best_values #dictionary structure
Afit = fitted_vals['A']
Bfit = fitted_vals['B']
Cfit = fitted_vals['C']
How can I make sure that the ratio of Afit to Bfit is pi/4 times some integer?
If it's not possible, is anyone aware of software that has this capability?