I have two variables who are related to each other and I want to find an optimal solution, which in this case is the minimum of their sum. For now, let's call them X and Y, and along with pre-defined constants, they add up to a set of "variables" s1 and s2 (that later feed the constraints):
105896649.59 + X = s1
-6738.82 + Y = s2
While searching the SciPy docs, I have come across the linear programming solution, where I have the minimizing function (in this case, X + Y) and a set of inequality and equality constraints to which my variables are bound. In my case, they are as follow:
X >= 0, Y >= 0s1 >= 1, s2 >= 1s2 / (s1 + s2) = 0.0001%
For this specific case, the code was easily implementable:
from scipy.optimize import linprog
lstConst = [105896649.59, -6738.82]
# function to minimise: X + Y
c= [1, 1]
# left-hand side of the equation for s2 / (s1 + s2) = 0.0001%
# i.e., -0.000001 * X + 0.999999 * Y
Aeq = [[-0.000001, 0.999999]]
# right-hand side of the equation
beq = [0.000001 * (lstConst[0] + lstConst[1]) - lstConst[1]]
# ensures minimum can't be a negative number
minX = max(1, max(1 -lstConst[0], 0))
minY = max(1, max(1 -lstConst[1], 0))
X_bounds = (minX, None)
Y_bounds = (minY, None)
res = linprog(c, A_eq=Aeq, b_eq=beq, bounds=[X_bounds, Y_bounds])
So we have the values for X and Y to minimize the function on the x parameter:
In [1]: res.x
Out[1]: array([1.00000000e+00, 6.84471676e+03])
I would like to build upon this approach:
- In fact, there is another set of restrictions:
s1ands2must also be integers (note thatXandYhave no problem with being floats). - Instead of defining a single value for the ratio between
s1ands2, I would supply a list of different possible ratios.
In essence, I would like to find the minimum values for the X + Y function given several different ratios between s1 and s2. This could be achievable by either iterating over a list to define Aeq and beq on each iteration or defining additional restrictions (if possible).
However, I'm clueless as to the integer restriction and how to make the linear programming algorithm take it into account.
If anyone has an alternative suggestion that uses a library/optimizer other than SciPy and linprog, that's also welcome.
max(1, max(1 -lstConst[0], 0))which is equivalent to justmax(1 -lstConst[0], 1)but the comments say this is suppose to only ensure the number is non negative.lstConstwould affect the boundary if I didn't set it that way, thanksminX = max(1 -lstConst[0], 0)notmax(1, max(1 -lstConst[0], 0))AFAICT. I used linprog inequality constraints for these.