7.3 Errors and exceptions

Exceptions

Almost every function in Optimizer API for Python can throw an exception informing that the requested operation was not performed correctly, and indicating the type of error that occurred. This is the case in situations such as for instance:

  • referencing a nonexisting variable (for example with too large index),

  • defining an invalid value for a parameter,

  • accessing an undefined solution,

  • repeating a variable name, etc.

It is therefore a good idea to catch exceptions of type Error. The one case where it is extremely important to do so is when Task.optimize is invoked. We will say more about this in Sec. 7.2 (Accessing the solution).

The exception contains a response code (element of the enum rescode) and short diagnostic messages. They can be accessed as in the following example.

try:
  task.putdouparam(mosek.dparam.intpnt_co_tol_rel_gap, -1.0e-7)
except mosek.Error as e: 
  print("Response code {0}\nMessage       {1}".format(e.errno, e.msg))

It will produce as output:

Response code rescode.err_param_is_too_small
Message       The parameter value -1e-07 is too small for parameter 'MSK_DPAR_INTPNT_CO_TOL_REL_GAP'.

Another way to obtain a human-readable string corresponding to a response code is the method Env.getcodedesc. A full list of exceptions, as well as response codes, can be found in the API reference.

Optimizer errors and warnings

The optimizer may also produce warning messages. They indicate non-critical but important events, that will not prevent solver execution, but may be an indication that something in the optimization problem might be improved. Warning messages are normally printed to a log stream (see Sec. 7.4 (Input/Output)). A typical warning is, for example:

MOSEK warning 53: A numerically large upper bound value  6.6e+09 is specified for constraint 'C69200' (46020).

Warnings can also be suppressed by setting the iparam.max_num_warnings parameter to zero, if they are well-understood.

Error and solution status handling example

Below is a source code example with a simple framework for handling major errors when assessing and retrieving the solution to a conic optimization problem.

Listing 7.2 Sample framework for checking optimization result. Click here to download.
import mosek
import sys

# A log message
def streamprinter(text):
    sys.stdout.write(text)
    sys.stdout.flush()

def main(args):
  filename = args[0] if len(args) >= 1 else "../data/cqo1.mps"

  try:
    # Create environment and task
    with mosek.Env() as env:
      with env.Task(0, 0) as task:
        # (Optional) set a log stream
        # task.set_Stream(mosek.streamtype.log, streamprinter)

        # (Optional) uncomment to see what happens when solution status is unknown
        # task.putintparam(mosek.iparam.intpnt_max_iterations, 1)

        # In this example we read data from a file
        task.readdata(filename)

        # Optimize
        trmcode = task.optimize()
        task.solutionsummary(mosek.streamtype.log)

        # We expect solution status OPTIMAL
        solsta = task.getsolsta(mosek.soltype.itr)

        if solsta == mosek.solsta.optimal:
          # Optimal solution. Fetch and print it.
          print("An optimal interior-point solution is located.")
          numvar = task.getnumvar()
          xx = task.getxx(mosek.soltype.itr)
          for i in range(numvar): 
            print("x[{0}] = {1}".format(i, xx[i]))

        elif solsta == mosek.solsta.dual_infeas_cer:
          print("Dual infeasibility certificate found.")

        elif solsta == mosek.solsta.prim_infeas_cer:
          print("Primal infeasibility certificate found.")
        
        elif solsta == mosek.solsta.unknown:
          # The solutions status is unknown. The termination code
          # indicates why the optimizer terminated prematurely.
          print("The solution status is unknown.")
          symname, desc = mosek.Env.getcodedesc(trmcode)
          print("   Termination code: {0} {1}".format(symname, desc))

        else:
          print("An unexpected solution status {0} is obtained.".format(str(solsta)))

  except mosek.Error as e:
      print("Unexpected error ({0}) {1}".format(e.errno, e.msg))

if __name__ == '__main__':
    main(sys.argv[1:])