I have a complicated model function that is composed by 12 other functions. I have about 10 parameters. I use the model function both to fit data and to generate contour plots. Sometimes I am only interested in estimating only a few parameters, and fixing the rest, setting them as global variables. Other times I want to estimate most parameters, and fix only a few. Every time I change the set of which parameters to estimate and which to fit, I go through my 13 functions, changing all the calls to only include those parameters I want to estimate. Can this be done more dynamically? Perhaps also avoiding global variables?
-
2Would you mind providing a minimal reproducible example?joni– joni2022-10-16 10:22:00 +00:00Commented Oct 16, 2022 at 10:22
-
Please provide enough code so others can better understand or reproduce the problem.Community– Community Bot2022-10-16 13:55:30 +00:00Commented Oct 16, 2022 at 13:55
1 Answer
The partial function from the functools library can help you (here is the documentation).
For instance, one of your functions has the following form:
def f(x, a, b, c, d):
# a very complex expression
return ...
where a, b, c and d are the parameters to be optimized using curve_fit by SciPy.
Suppose that you need to optimize the parameters a and b and you want to keep c and d fixed. You can write:
# constant value
c0 = ...
# constant value
d0 = ...
f_partial = partial(f, c=c0, d=d0)
now you get a new function with a simplified signature and you can pass f_partial to curve_fit and only a and b will be optimized.
You can now leverage the partial function to choose which parameters to optimize.
This tutorial can also help you to understand better how the partial function works.