Search code examples
cvxpymosek

Capture timeout exception with Mosek + Cvxpy


We are solving our large scale MI optimization problems with Cvxpy and Mosek.

Often times it happens that Mosek consumes higher runtime then our stipulated timeout of two hours.

Is there a way to systematically capture those timeout exception?

Minimum reproducible example:

import cvxpy as cp
import numpy as np
import mosek

m = 15
n = 10
np.random.seed(1)
s0 = np.random.randn(m)
lamb0 = np.maximum(-s0, 0)
s0 = np.maximum(s0, 0)
x0 = np.random.randn(n)
A = np.random.randn(m, n)
b = A @ x0 + s0
c = -A.T @ lamb0

# Define and solve the CVXPY problem.
x = cp.Variable(n)
prob = cp.Problem(cp.Minimize(c.T@x),
                 [A @ x <= b])
# try:
prob.solve(cp.MOSEK, mosek_params={mosek.dparam.optimizer_max_time: 0.01})   # set verbose=True (to see actual error in solver logs)
# except Timeout exception
#     print('Timeout occured')

print(prob.value)

def execute_other_important_stuff():
    print("Hello world")

execute_other_important_stuff()  # Not executed currently

Solution

  • When MOSEK terminates because of a timeout there will never be any exception - you set a timeout, so terminating at that point is a normal, not an abnormal, situation. I am not sure what "Error" you are referring to.

    If you mean something like

    Cannot unpack invalid solution: Solution(status=UNKNOWN
    

    then it is not related to the timeout itself, but to the fact that there is no solution available (yet, so the only available "solution" has UNKNOWN status), and CVXPY handles this by throwing an exception. So the question is, has any solution at all to your problem been found after those 2 hours? If yes, it should be returned without problem. If not, you might see the above and I would guess the only way is to catch the ValueError CVXPY happens to throw.

    If you were using the native Mosek interface then you could find out why it terminated from various response codes, but I CVXPY does not propagate them.