Advertisement
SVXX

ORTools Linear Prog with Sparsity

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