Search code examples
scipyscipy-optimize-minimize

How to set x of a function given a target and a constraint?


I am trying to replicate somehow what excel solver would do in python. I have a set of functions like this: P1 = f1(x), P2= f2(x), Q1= g1(x) and Q2= g2(x)

I am trying to find the value of x such as P1+P2 = some target and Q1+Q2 is minimum. can it be done with scipy? I already know how to set the P1+P2 part using fsolve, just dont know if the Q1+Q2 restriction can be added. any idea?


Solution

  • As suggested by joni, this is doable by using the scipy.optimize.minimize library. You could define a function residual as follows:

    def residual(x):
        # calculate/define Q1 = g1(x)
        # calculate/define Q2 = g2(x)
    
        res = Q1 + Q2
    
        return res
    

    This function then can easily be minimized using a constrained algorithm from scipy.optimize.minimize:

    import numpy as np
    from scipy.optimize import minimize
    
    x0 = 1 # just for example
    res = minimize(residual, x0, method='trust-constr', constraints=your_constraints)
    

    The constraint P1+P2 = target must be defined and passed to the constraints argument as described here. You have to look for linear or non-linear constraint depending upon your constraint.