5
$\begingroup$

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.).

$\endgroup$
4
  • 2
    $\begingroup$ Could you provide some context - are you using google spreadsheets or a programming language? $\endgroup$
    – CMichael
    Jan 12, 2022 at 8:32
  • 2
    $\begingroup$ There's an example in their repo: github.com/google/or-tools/blob/stable/examples/python/… $\endgroup$ Jan 12, 2022 at 18:14
  • $\begingroup$ @CMichael: Thank you. I am using or-tools as a framework with GLOP solver in python. $\endgroup$ Jan 15, 2022 at 7:00
  • $\begingroup$ @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. $\endgroup$ Jan 15, 2022 at 7:03

1 Answer 1

4
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$ Jan 27 at 1:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.