In this chapter the reader will learn how to build a simple application that uses MOSEK.
A number of examples is provided to demonstrate the functionality required for solving linear, quadratic, and conic problems as well as mixed integer problems.
Please note that the section on linear optimization also describes most of the basic functionality that is not specific to linear problems. Hence, it is recommended to read Section 5.2 before reading the rest of this chapter.
A typical program using the MOSEK Java interface can be described shortly:
The first MOSEK related step in any program that employs MOSEK is to create an environment (mosek.Env) object. The environment contains environment specific data such as information about the license file, streams for environment messages etc. Before creating any task objects, the environment must be initialized using Env.initenv. When this is done one or more task (mosek.Task) objects can be created. Each task is associated with a single environment and defines a complete optimization problem as well as task message streams and optimization parameters.
When done, all task and environments created must be explicitly disposed of using the dispose method. As tasks depend on their environment, a task must be disposed of before its environment; not doing so will cause memory leaks or fatal errors.
In Java creation of an environment and a task would look something like this:
... mosek.Env env = new mosek.Env (); // input environment data here env.initenv (); mosek.Task task = new mosek.Task (env, num_con, num_var); ... // input some task data, optimize etc. ... task.Dispose () env.Dispose ()
Please note that an environment should, if possible, be shared between multiple tasks.
The following simple example shows a working Java program which
It is frequently beneficial to write a problem to a file that can be stored for later use or inspected visually. The Task.writedata function is used write a problem to a file as follows
By default the extension of the filename is the format written. I.e. the filename somename.opf implies the file is written in the OPF format.
Similarly, the function Task.readdata reads a problem from a file:
An optimization problem consists of several components; objective, objective sense, constraints, variable bounds etc. Therefore, the task (mosek.Task) provides a number of methods to operate on the task specific data, all of which are listed in Section 14.9.
Apart from the problem data, the task contains a number of parameters defining the behavior of MOSEK. For example the Env.iparam.optimizer parameter defines which optimizer to use. A complete list of all parameters are listed in Chapter 15.
All examples presented in this chapter are distributed with MOSEK and are available in the directory
mosek/6/tools/examples/
in the MOSEK installation. Chapter 4 describes how to compile and run the examples.
It is recommended to copy examples to a different directory before modifying and compiling them.
The simplest optimization problem is a purely linear problem. A linear optimization problem is a problem of the following form:
Minimize or maximize the objective function
![]() |
(5.2.1) |
subject to the linear constraints
![]() |
(5.2.2) |
and the bounds
![]() |
(5.2.3) |
where we have used the problem elements
m and n, which are the number of constraints and variables respectively,
c, which is a coefficient vector of size n
![]() |
, which is a constant,
A, which is a matrix of coefficients is given by
![]() |
and
, which specify the lower and upper bounds on constraints respectively, and
and
, which specifies the lower and upper bounds on variables respectively.
Please note the unconventional notation using 0 as the first index rather than 1. Hence, is the first element in variable vector x. This convention has been adapted from Java arrays which are indexed from 0.
The following is an example of a linear optimization problem:
![]() |
(5.2.4) |
having the bounds
![]() |
(5.2.5) |
To solve the problem above we go through the following steps:
Below we explain each of these steps. For the complete source code see section 5.2.1.2. The code can also be found in:
mosek\6\tools\examples\java\lo1.java
Before setting up the optimization problem, a MOSEK environment must be created and initialized. This is done in the lines:
We connect a call-back function to the environment log stream. In this case the call-back function simply prints messages to the standard output stream.
Next, an empty task object is created:
We also connect a call-back function to the task log stream. Messages related to the task are passed to the call-back function. In this case the stream call-back function writes its messages to the standard output stream.
First an estimate of the size of the input data is set. This is done to increase the speed of inputting data and is optional.
Before any problem data can be set, variables and constraints must be added to the problem via calls to the function Task.append.
New variables can now be referenced from other functions with indexes in and new constraints can be referenced with indexes in
. More variables / constraints can be appended later as needed, these will be assigned indexes from
/
and up.
Next step is to set the problem data. We loop over each variable index calling functions to set problem data. We first set the objective coefficient
by calling the function Task.putcj.
The bounds on variables are stored in the arrays
and are set with calls to Task.putbound.
The Bound key stored in bkx specify the type of the bound according to Table 5.1.
|
For instance bkx[0]= Env.boundkey.lo means that . Finally, the numerical values of the bounds on variables are given by
![]() |
(5.2.6) |
and
![]() |
(5.2.7) |
Recall that in our example the A matrix is given by
![]() |
This matrix is stored in sparse format in the arrays:
The array aval[j] contains the non-zero values of column j and asub[j] contains the row index of these non-zeros.
Using the function Task.putavec we set column j of A
Alternatively, the same A matrix can be set one row at a time; please see section 5.2.2 for an example.
Finally, the bounds on each constraint are set by looping over each constraint index
After the problem is set-up the task can be optimized by calling the function Task.optimizetrm.
After optimizing the status of the solution is examined with a call to Task.getsolutionstatus. If the solution status is reported as Env.solsta.optimal or Env.solsta.near_optimal the solution is extracted in the lines below:
The Task.getsolutionslice function obtains a “slice” of the solution. MOSEK may compute several solutions depending on the optimizer employed. In this example the basic solution is requested by setting the first argument to Env.soltype.bas. The second argument Env.solitem.xx specifies that we want the variable values of the solution. The two following arguments 0 and NUMVAR specifies the range of variable values we want.
The range specified is the first index (here “0”) up to but not including the second index (here “NUMVAR”).
We cache any exceptions thrown by mosek in the lines:
The types of exceptions that MOSEK can throw can be seen in 14.5 and 14.10.
In the previous example the A matrix is set one column at a time. Alternatively the same matrix can be set one row at a time or the two methods can be mixed as in the example in section 5.6. The following example show how to set the A matrix by rows.
The source code for this example can be found in:
mosek\6\tools\examples\java\lo2.java
MOSEK can solve quadratic and quadratically constrained convex problems. This class of problems can be formulated as follows:
![]() |
(5.3.1) |
Without loss of generality it is assumed that and
are all symmetric because
![]() |
This implies that a non-symmetric Q can be replaced by the symmetric matrix .
The problem is required to be convex. More precisely, the matrix must be positive semi-definite and the kth constraint must be of the form
![]() |
(5.3.2) |
with a negative semi-definite or of the form
![]() |
(5.3.3) |
with a positive semi-definite . This implies that quadratic equalities are not allowed. Specifying a non-convex problem will result in an error when the optimizer is called.
The following is an example if a quadratic, linearly constrained problem:
![]() |
(5.3.4) |
This can be written equivalently as
![]() |
(5.3.5) |
where
![]() |
(5.3.6) |
Please note that MOSEK always assumes that there is a 1/2 in front of the term in the objective. Therefore, the 1 in front of
becomes 2 in Q, i.e.
.
Most of the functionality in this example has already been explained for the linear optimization example in Section 5.2 and it will not be repeated here.
This example introduces one new function, Task.putqobj, which is used to input the quadratic terms of the objective function.
Since is symmetric only the lower triangular part of
is inputted. The upper part of
is computed by MOSEK using the relation
![]() |
Entries from the upper part may not appear in the input.
The lower triangular part of the matrix is specified using an unordered sparse triplet format (for details, see Section 5.8.3):
Please note that
Finally, the matrix is loaded into the task:
In this section describes how to solve a problem with quadratic constraints. Please note that quadratic constraints are subject to the convexity requirement (5.3.2).
Consider the problem:
![]() |
(5.3.7) |
This is equivalent to
![]() |
(5.3.8) |
where
![]() |
(5.3.9) |
![]() |
(5.3.10) |
The only new function introduced in this example is Task.putqconk, which is used to add quadratic terms to the constraints. While Task.putqconk add quadratic terms to a specific constraint, it is also possible to input all quadratic terms in all constraints in one chunk using the Task.putqcon function.
Conic problems are a generalization of linear problems, allowing constraints of the type
![]() |
where is a convex cone.
MOSEK can solve conic optimization problems of the following form
![]() |
(5.4.1) |
where is a cone.
can be a product of cones, i.e.
![]() |
in which case means
. Please note that the set of real numbers
is itself a cone, so linear variables are still allowed.
MOSEK supports two specific cones apart from the real numbers:
The quadratic cone:
![]() |
The rotated quadratic cone:
![]() |
When creating a conic problem in MOSEK, each cone is defined by a cone type (quadratic or rotated quadratic cone) and a list of variable indexes. To summarize:
The problem
![]() |
(5.4.2) |
is an example of a conic quadratic optimization problem. The problem includes a set of linear constraints and two quadratic cones.
The only new function introduced in the example is Task.appendcone, which is called here:
Here Env.conetype.quad defines the cone type, in this case it is a quadratic cone. The cone parameter 0.0 is currently not used by MOSEK — simply passing 0.0 will work.
The last argument is a list of indexes of the variables in the cone.
An optimization problem where one or more of the variables are constrained to integer values is denoted an integer optimization problem.
In this section the example
![]() |
(5.5.1) |
is used to demonstrate how to solve a problem with integer variables.
The example (5.5.1) is almost identical to a linear optimization problem except for some variables being integer constrained. Therefore, only the specification of the integer constraints requires something new compared to the linear optimization problem discussed previously. In MOSEK these constraints are specified using the function Task.putvartype as shown in the code:
The complete source for the example is listed below.
Please note that when Task.getsolutionslice is called, the integer solution is requested by using Env.soltype.itg. No dual solution is defined for integer optimization problems.
Integer optimization problems are generally hard to solve, but the solution time can often be reduced by providing an initial solution for the solver. Solution values can be set using Task.putsolution (for inputting a whole solution) or Task.putsolutioni (for inputting solution values related to a single variable or constraint).
It is not necessary to specify the whole solution. By setting the Env.iparam.mio_construct_sol parameter to Env.onoffkey.on and inputting values for the integer variables only, will force MOSEK to compute the remaining continuous variable values.
If the specified integer solution is infeasible or incomplete, MOSEK will simply ignore it.
Consider the problem
![]() |
(5.5.2) |
The following example demonstrates how to optimize the problem using a feasible starting solution generated by selecting the integer values as .
Often one might want to solve not just a single optimization problem, but a sequence of problem, each differing only slightly from the previous one. This section demonstrates how to modify and reoptimize an existing problem. The example we study is a simple production planning model.
A company manufactures three types of products. Suppose the stages of manufacturing can be split into three parts, namely Assembly, Polishing and Packing. In the table below we show the time required for each stage as well as the profit associated with each product.
Product no. | Assembly (minutes) | Polishing (minutes) | Packing (minutes) | Profit ($) |
0 | 2 | 3 | 2 | 1.50 |
1 | 4 | 2 | 3 | 2.50 |
2 | 3 | 3 | 2 | 3.00 |
With the current resources available, the company has 100,000 minutes of assembly time, 50,000 minutes of polishing time and 60,000 minutes of packing time available per year.
Now the question is how many items of each product the company should produce each year in order to maximize profit?
Denoting the number of items of each type by and
, this problem can be formulated as the linear optimization problem:
![]() |
(5.6.1) |
and
![]() |
(5.6.2) |
The following code loads this problem into the optimization task.
Suppose we want to change the time required for assembly of product 0 to 3 minutes. This corresponds to setting , which is done by calling the function Task.putaij as shown below.
The problem now has the form:
![]() |
(5.6.3) |
and
![]() |
(5.6.4) |
After changing the A matrix we can find the new optimal solution by calling
again
We now want to add a new product with the following data:
Product no. | Assembly (minutes) | Polishing (minutes) | Packing (minutes) | Profit ($) |
3 | 4 | 0 | 1 | 1.00 |
This corresponds to creating a new variable , appending a new column to the A matrix and setting a new value in the objective. We do this in the following code.
After this operation the problem looks this way:
![]() |
(5.6.5) |
and
![]() |
(5.6.6) |
When
is called MOSEK will store the optimal solution internally. After a task has been modified and
is called again the solution will automatically be used to reduce solution time of the new problem, if possible.
In this case an optimal solution to problem (5.6.3) was found and then added a column was added to get (5.6.5). The simplex optimizer is well suited for exploiting an existing primal or dual feasible solution. Hence, the subsequent code instructs MOSEK to choose the simplex optimizer freely when optimizing.
Now suppose we want to add a new stage to the production called “Quality control” for which 30000 minutes are available. The time requirement for this stage is shown below:
Product no. | Quality control (minutes) |
0 | 1 |
1 | 2 |
2 | 1 |
3 | 1 |
This corresponds to adding the constraint
![]() |
(5.6.7) |
to the problem which is done in the following code:
Although MOSEK is implemented to handle memory efficiently, the user may have valuable knowledge about a problem, which could be used to improve the performance of MOSEK. This section discusses some tricks and general advice that hopefully make MOSEK process your problem faster.
MOSEK stores the optimization problem in internal data structures in the memory. Initially MOSEK will allocate structures of a certain size, and as more items are added to the problem the structures are reallocated. For large problems the same structures may be reallocated many times causing memory fragmentation. One way to avoid this is to give MOSEK an estimated size of your problem using the functions:
None of these functions change the problem, they only give hints to the eventual dimension of the problem. If the problem ends up growing larger than this, the estimates are automatically increased.
It is possible to obtain information about how often MOSEK reallocates storage for the A matrix by inspecting Env.iinfitem.sto_num_a_realloc. A large value indicates that maxnumanz has been reestimated many times and that the initial estimate should be increased.
For instance, the functions Task.putavec and Task.getavec. MOSEK will queue put- commands internally until a get- function is called. If every put- function call is followed by a get- function call, the queue will have to be flushed often, decreasing efficiency.
In general get- commands should not be called often during problem setup.
MOSEK can more efficiently remove constraints and variables with a high index than a small index.
An alternative to removing a constraint or a variable is to fix it at 0, and set all relevant coefficients to 0. Generally this will not have any impact on the optimization speed.
The cost of adding one constraint or one variable is about the same as adding many of them. Therefore, it may be worthwhile to add many variables instead of one. Initially fix the unused variable at zero, and then later unfix them as needed. Similarly, you can add multiple free constraints and then use them as needed.
If possible share the environment (env) between several tasks. For most applications you need to create only a single env.
When doing reoptimizations, instead of removing a basic variable it may be more efficient to fix the variable at zero and then remove it when the problem is reoptimized and it has left the basis. This makes it easier for MOSEK to restart the simplex optimizer.
The Java interface is a thin wrapper around a native MOSEK library. The layer between the Java application and the native MOSEK library is made as thin as possible to minimize the overhead from function calls.
The methods in mosek.Env and mosek.Task are all written in C and resides in the library mosekjava. Each method converts the call parameter data structures (i.e. creates a complete copy of the data), calls a native MOSEK function and converts the returned values back into Java structures.
All data are copied at least once. For larger problems this may mean, that fetching or inputting large chunks of data is less expensive than fetching/inputting the same data as single values.
In the definition of the MOSEK Java API a consistent naming convention has been used. This implies that whenever for example numcon is an argument in a function definition it indicates the number of constraints.
In Table 5.2 the variable names used to specify the problem parameters are listed.
The relation between the variable names and the problem parameters is as follows:
The quadratic terms in the objective:
![]() |
(5.8.1) |
The linear terms in the objective:
![]() |
(5.8.2) |
The fixed term in the objective:
![]() |
(5.8.3) |
The quadratic terms in the constraints:
![]() |
(5.8.4) |
The linear terms in the constraints:
![]() |
(5.8.5) |
The bounds on the constraints are specified using the variables bkc, blc, and buc. The components of the integer array bkc specify the bound type according to Table 5.3.
|
For instance bkc[2]=Env.boundkey.lo means that and
. Finally, the numerical values of the bounds are given by
![]() |
(5.8.6) |
and
![]() |
(5.8.7) |
The bounds on the variables are specified using the variables bkx, blx, and bux. The components in the integer array bkx specify the bound type according to Table 5.3. The numerical values for the lower bounds on the variables are given by
![]() |
(5.8.8) |
The numerical values for the upper bounds on the variables are given by
![]() |
(5.8.9) |
A bound on a variable or on a constraint in MOSEK consists of a bound key, as defined in Table 5.3, a lower bound value and an upper bound value. Even if a variable or constraint is bounded only from below, e.g. x≥0, both bounds are inputted or extracted; the value inputted as upper bound for (x≥0) is ignored.
Three different vector formats are used in the MOSEK API:
This is simply an array where the first element corresponds to the first item, the second element to the second item etc. For example to get the linear coefficients of the objective in task, one would write
where numvar is the number of variables in the problem.
A vector slice is a range of values. For example, to get the bounds associated constraint 3 through 10 (both inclusive) one would write
Please note that items in MOSEK are numbered from 0, so that the index of the first item is 0, and the index of the n'th item is n-1.
A sparse vector is given as an array of indexes and an array of values. For example, to input a set of bounds associated with constraints number 1, 6, 3, and 9, one might write
Note that the list of indexes need not be ordered.
The coefficient matrices in a problem are inputted and extracted in a sparse format, either as complete or a partial matrices. Basically there are two different formats for this.
In unordered triplet format each entry is defined as a row index, a column index and a coefficient. For example, to input the A matrix coefficients for ,
, and
, one would write as follows:
Please note that in some cases (like Task.putaijlist) only the specified indexes remain modified — all other are unchanged. In other cases (such as Task.putqconk) the triplet format is used to modify all entries — entries that are not specified are set to 0.
In a sparse matrix format only the non-zero entries of the matrix are stored. MOSEK uses a sparse matrix format ordered either by rows or columns. In the column-wise format the position of the non-zeros are given as a list of row indexes. In the row-wise format the position of the non-zeros are given as a list of column indexes. Values of the non-zero entries are given in column or row order.
A sparse matrix in column ordered format consists of:
List of row indexes.
List of non-zero entries of A ordered by columns.
Where ptrb[j] is the position of the first value/index in aval / asub for column j.
Where ptre[j] is the position of the last value/index plus one in aval / asub for column j.
The values of a matrix A with numcol columns are assigned so that for
![]() |
We define
![]() |
(5.8.10) |
|
As an example consider the matrix
![]() |
(5.8.11) |
which can be represented in the column ordered sparse matrix format as
![]() |
Fig. 5.1 illustrates how the matrix A (5.8.11) is represented in column ordered sparse matrix format.
The matrix A (5.8.11) can also be represented in the row ordered sparse matrix format as:
![]() |
By default a license token is checked out when Task.optimizetrm is first called and is returned when the MOSEK environment is deleted. Calling Task.optimizetrm from different threads using the same MOSEK environment only consumes one license token.
To change the license systems behavior to returning the license token after each call to Task.optimizetrm set the parameter Env.iparam.cache_license to Env.onoffkey.off. Please note that there is a small overhead associated with setting this parameter, since checking out a license token from the license server can take a small amount of time.
Additionally license checkout and checkin can be controlled manually with the functions Env.checkinlicense and Env.checkoutlicense.
By default an error will be returned if no license token is available. By setting the parameter Env.iparam.license_wait MOSEK can be instructed to wait until a license token is available.