Advertisement
SVXX

ORTools Linear Program

Dec 19th, 2022
915
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. from ortools.linear_solver import pywraplp
  2. import numpy as np
  3.  
  4. A = np.random.rand(5, 5)
  5. S = [0, 1]
  6. S_bar = [2, 3, 4]
  7. nu = 0.55
  8.  
  9. diff = np.linalg.inv(A[S_bar,:][:,S_bar] - nu * np.eye(3))
  10. prod = np.matmul(diff, A[S_bar,:][:,S])
  11.  
  12. # The above is $prod = (A_{\bar{S}, \bar{S}} - \nu I_{|S|})^{-1} A_{\bar{S}, S}$
  13.  
  14. solver = pywraplp.Solver.CreateSolver('GLOP')
  15. u_S_prog = np.array([solver.NumVar(0, solver.infinity(), "u_S_" + str(i)) for i in range(len(S))])
  16. z = np.array([solver.NumVar(0, solver.infinity(), 'z_' + str(i)) for i in range(len(S_bar))])
  17.  
  18. rhs = -prod.dot(u_S_prog) # rhs of our to-be-formed minimum linear constraint
  19. for index, z_i in enumerate(z):
  20.     solver.Add(z_i <= rhs[index]) # Each component of z must be ≤ each component of rhs
  21.  
  22. objective = solver.Objective()
  23. for z_i in z:
  24.     objective.SetCoefficient(z_i, 1)
  25.    
  26. objective.SetMaximization()
  27. status = solver.Solve()
  28.  
  29. if status == pywraplp.Solver.OPTIMAL:
  30.     print('Objective value =', solver.Objective().Value())
  31.     print()
  32.     print('Problem solved in %f milliseconds' % solver.wall_time())
  33.     print('Problem solved in %d iterations' % solver.iterations())
  34.     print('Problem solved in %d branch-and-bound nodes' % solver.nodes())
  35. else:
  36.     print(f'The problem with status {status} does not have an optimal solution.')
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement