0

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?

  • 1
    The answer is already in your used tags. This can easily be done by means of `scipy.optimize.minimize` since it is a simply equality constrained optimization problem. Have a look at the [tutorials](https://docs.scipy.org/doc/scipy/tutorial/optimize.html). – joni Jan 05 '22 at 08:47

1 Answers1

0

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.

Muhammad Mohsin Khan
  • 1,444
  • 7
  • 16
  • 23
  • Since you are using `minimize` anyway, why don't you just solve `min g1(x) + g2(x) s.t. f1(x)+f2(x) = target` instead of reformulating it as an unconstrained problem? The latter approach has several disadvantages. – joni Jan 07 '22 at 10:31
  • @joni Did you mean to say that I should minimize a function that returns `target = g1(x) + g2(x) + f1(x) + f2(x)` or did I understand you wrong? – Muhammad Mohsin Khan Jan 07 '22 at 11:03
  • 1
    No, the OP wants to minimize g1(x) + g2(x) subject to f1(x)+f2(x) = target. This is an [equality constrained optimization problem](https://en.wikipedia.org/wiki/Constrained_optimization) and can directly be solved by means of `scipy.optimize.minimize`. One disadvantage of your approach is that you will even get a solution when the problem is infeasible, i.e. when there's no x such that f1(x)+f2(x) = target. – joni Jan 07 '22 at 11:41
  • Thanks for the clarification. I understand your point now. – Muhammad Mohsin Khan Jan 07 '22 at 13:08
  • 1
    @joni I have incorporated your suggestion in my answer. – Muhammad Mohsin Khan Jan 07 '22 at 14:50
  • Thanks @joni and Muhammad.. I have tried with the solution you proposed, but it seems that the x is not the same for all functions. I get message: 'Singular matrix C in LSQ subproblem'... The problem is more like minimize g1(x1)+g2(x2) given f1(x1)+f2(x2) = the_target, so I am looking for 2 "x"... any idea how can this set with scipy? – Ubaldo Gonzalez Feb 10 '22 at 23:01