Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# CPLEX interface to solve QP problems
import numpy as np
import quadprog.problem as qp
from quadprog.results import quadprogResults
import cplex as cpx
import ipdb
class CPLEX(object):
"""
An interface for the CPLEX QP solver.
"""
# Map of CPLEX status to CVXPY status. #TODO: add more!
STATUS_MAP = {1: qp.OPTIMAL,
3: qp.INFEASIBLE,
2: qp.UNBOUNDED,
6: qp.OPTIMAL_INACCURATE}
def __init__(self, **kwargs):
self.options = kwargs
def solve(self, p):
# Convert Matrices in CSR format
p.A = p.A.tocsr()
p.P = p.P.tocsr()
# Get problem dimensions
n = p.P.shape[0]
m = p.A.shape[0]
# Solve problem
try:
# Solve
m.optimize()
except: # Error in the solution
print "Error in Gurobi solution\n"
return quadprogResults(qp.SOLVER_ERROR, None, None, None,
None, None, None,
np.inf, None)
# Return results
# Get status
status = self.STATUS_MAP.get(m.Status, qp.SOLVER_ERROR)
if (status != qp.SOLVER_ERROR) & (status != qp.INFEASIBLE):
# Get objective value
objval = m.objVal
# Get solution
sol = np.array([x[i].X for i in range(nx)])
# Get dual variables (Gurobi uses swapped signs (-1))
constrs = m.getConstrs()
sol_dual_eq = -np.array([constrs[i].Pi for i in range(neq)])
sol_dual_ineq = -np.array([constrs[i+neq].Pi for i in range(nineq)])
# Bounds
sol_dual_ub = np.zeros(nx)
sol_dual_lb = np.zeros(nx)
RCx = [x[i].RC for i in range(nx)] # Get reduced costs