In a project I've been working on I have been using SciPy's optimize.curve_fit() function to fit curve to a graph by varying 3 parameters. One of the parameters (c) needs to be constrained within limits based on another parameter (Mhalo) as you can see in the graph here.
As the next step in the project I want to change this relation so that instead of varying c within limits based on Mhalo, as shown in the graph, the c parameter has a lognormal distribution around the Mhalo-c relation.
When I've tried to do this by taking c out of the variables in the optimize.curve_fit() function and putting a random lognormal calculation inside the function I am fitting instead, the program fails to fit a curve at all (presumably because of the random element).
Is there any way I can accomplish what I've described here either using optimize.curve_fit() or a different function in Python?
This is related to I need a Python function that can fit a curve within a parameter space. It is not quite a duplicate.
Are c
and Mhalo
meant to be fitting parameters?
As also mentioned in the earlier question, you might find lmfit
helpful. It can allow one parameter to be defined as a simple (or maybe not so simple) mathematical expression of other parameters. For example, it might be that what your looking to do is constrain c
to be some function of Mhalo
plus some term that has finite bounds. That might be done in lmfit
with something like
from lmfit import Parameters
params = Parameters()
params.add('mhalo', value=100, vary=True)
params.add('c_offset', value=0, min=-1, max=1, vary=True)
params.add('c', expr='log10(mhalo) + c_offset')
That will allow mhalo
to vary freely, allow c_offset
to vary within bounds, and constrain c
to be a function of these two parameters, meaning that c
can change in the fit but not independently of mhalo
and c_offset
.