One can solve the linear programs using google or-tools with GLOP solver. I wonder if there is a way to print the sensitivity report (like shadow prices etc.).
-
2Could you provide some context - are you using google spreadsheets or a programming language? – CMichael Jan 12 '22 at 08:32
-
2There's an example in their repo: https://github.com/google/or-tools/blob/stable/examples/python/linear_programming.py#L92 – David Torres Jan 12 '22 at 18:14
-
@CMichael: Thank you. I am using or-tools as a framework with GLOP solver in python. – Manu K. Gupta Jan 15 '22 at 07:00
-
@DavidTorres: Thank you for the reference. This is what I was looking for. The last part of the code gives me the reduced cost for a Linear Program. – Manu K. Gupta Jan 15 '22 at 07:03
1 Answers
Here is a straightforward conversion of Python PuLP code from https://machinelearninggeek.com/sensitivity-analysis-in-python/ into Google OR Tools:
import pandas as pd
from ortools.linear_solver import pywraplp
from ortools.init import pywrapinit
solver = pywraplp.Solver.CreateSolver('GLOP')
A = solver.NumVar(0.0, solver.infinity(), "A")
B = solver.NumVar(0.0, solver.infinity(), "B")
solver.Add(4 * A + 10 * B <= 100, "c0")
solver.Add(2 * A + 1 * B <= 22, "c1")
solver.Add(3 * A + 3 * B <= 39, "c2")
solver.Maximize(60 * A + 50 * B )
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print('Solution:')
print('Objective value =', solver.Objective().Value())
print('A =', A.solution_value())
print('B =', B.solution_value())
else:
print('The problem does not have an optimal solution.')
activities = solver.ComputeConstraintActivities()
o = [{'Name':c.name(), 'shadow price':c.dual_value(), 'slack': c.ub() - activities[i]} for i, c in enumerate(solver.constraints())]
print(pd.DataFrame(o))
Output is
Solution:
Objective value = 740.0
A = 9.000000000000002
B = 3.9999999999999973
Name shadow price slack
0 c0 -0.000000 24.0
1 c1 10.000000 0.0
2 c2 13.333333 0.0
Shadow prices can be retrieved from constraint.dual_value() and slack by substracting the constraint activities from the upper bound of the constraint.
- 141
- 3
-
How about the slack (range) for the objective function coefficients? (the interval where they can change without changing the solution) Pyomo generates slack intervals for constraints and for the objective function quite easily. I would like to do the same in OR-Tools. – Florin Andrei Jan 27 '24 at 01:26