17 List of examples¶
List of examples shipped in the distribution of Optimizer API for Java:
File |
Description |
---|---|
A simple problem with one affine conic constraint (ACC) |
|
A simple problem with two affine conic constraints (ACC) |
|
Demonstrates the MOSEK interface to BLAS/LAPACK linear algebra routines |
|
An example of data/progress callback |
|
A simple conic exponential problem |
|
Implementation of a concurrent optimizer for linear and mixed-integer problems |
|
A simple conic quadratic problem |
|
A simple problem with disjunctive constraints (DJC) |
|
A simple example of how to repair an infeasible problem |
|
A simple geometric program (GP) in conic form |
|
A Hello World example |
|
A simple linear problem |
|
A simple linear problem |
|
Implements logistic regression and simple log-sum-exp (CEO) |
|
A simple mixed-integer conic problem |
|
A simple mixed-integer linear problem |
|
A simple mixed-integer linear problem with an initial guess |
|
Uses MOSEK OptServer to solve an optimization problem asynchronously |
|
Uses MOSEK OptServer to solve an optimization problem synchronously |
|
Demonstrates parallel optimization using a batch method in MOSEK |
|
Shows how to set optimizer parameters and read information items |
|
Shows how to obtain and analyze a primal infeasibility certificate |
|
Portfolio optimization - basic Markowitz model |
|
Portfolio optimization - efficient frontier |
|
Portfolio optimization - market impact costs |
|
Portfolio optimization - transaction costs |
|
Portfolio optimization - cardinality constraints |
|
Portfolio optimization - factor model |
|
A simple power cone problem |
|
A simple quadratically constrained quadratic problem |
|
A simple quadratic problem |
|
Demonstrate how to modify and re-optimize a linear problem |
|
Demonstrates proper response handling |
|
A simple semidefinite problem with one matrix variable and a quadratic cone |
|
A simple semidefinite problem with two matrix variables |
|
A simple semidefinite problem with an LMI using the SVEC domain. |
|
Sensitivity analysis performed on a small linear problem |
|
A simple I/O example: read problem from a file, solve and write solutions |
|
Demonstrates how to examine the quality of a solution |
|
Demonstrates solving a linear system with the basis matrix |
|
Demonstrates solving a general linear system |
Additional examples can be found on the MOSEK website and in other MOSEK publications.
acc1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : acc1.java
Purpose : Tutorial example for affine conic constraints.
Models the problem:
maximize c^T x
subject to sum(x) = 1
gamma >= |Gx+h|_2
*/
package com.mosek.example;
import mosek.*;
public class acc1 {
/* Data dimensions */
static final int n = 3;
static final int k = 2;
public static void main (String[] args) throws java.lang.Exception {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int i,j;
long quadDom;
// create a task object
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Create n free variables
task.appendvars(n);
task.putvarboundsliceconst(0, n, mosek.boundkey.fr, -infinity, infinity);
// Set up the objective
double[] c = {2, 3, -1};
int[] cind = {0, 1, 2};
task.putobjsense(mosek.objsense.maximize);
task.putclist(cind, c);
// One linear constraint - sum(x) = 1
task.appendcons(1);
task.putconbound(0, mosek.boundkey.fx, 1.0, 1.0);
for(i = 0; i < n; i++) task.putaij(0, i, 1.0);
// Append empty AFE rows for affine expression storage
task.appendafes(k + 1);
// F matix in sparse form
long[] Fsubi = {1, 1, 2, 2}; // The G matrix starts in F from row 1
int[] Fsubj = {0, 1, 0, 2};
double[] Fval = {1.5, 0.1, 0.3, 2.1};
// Other data
double[] h = {0, 0.1};
double gamma = 0.03;
// Fill in F storage
task.putafefentrylist(Fsubi, Fsubj, Fval);
// Fill in g storage;
task.putafeg(0, gamma);
task.putafegslice(1, k+1, h);
// Define a conic quadratic domain
quadDom = task.appendquadraticconedomain(k + 1);
// Create the ACC
long[] afeidx = {0, 1, 2};
task.appendacc(quadDom, // Domain index
afeidx, // Indices of AFE rows [0,...,k]
null); // Ignored
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Termination code: " + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
switch (solsta) {
case optimal:
// Fetch solution
double[] xx = task.getxx(mosek.soltype.itr); // Interior solution.
System.out.println("Optimal primal solution");
for (j = 0; j < n; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
// Fetch doty dual for the ACC
double[] doty = task.getaccdoty(mosek.soltype.itr, // Interior solution.
0); // ACC index
System.out.println("Dual doty value for the ACC");
for (j = 0; j < k + 1; ++j)
System.out.println ("doty[" + j + "]:" + doty[j]);
// Fetch ACC activity
double[] activity = task.evaluateacc(mosek.soltype.itr, // Interior solution.
0); // ACC index
System.out.println("Activity for the ACC");
for (j = 0; j < k + 1; ++j)
System.out.println ("activity[" + j + "]:" + activity[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
acc2.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : acc2.java
Purpose : Tutorial example for affine conic constraints.
Models the problem:
maximize c^T x
subject to sum(x) = 1
gamma >= |Gx+h|_2
This version inputs the linear constraint as an affine conic constraint.
*/
package com.mosek.example;
import mosek.*;
public class acc2 {
/* Data dimensions */
static final int n = 3;
static final int k = 2;
public static void main (String[] args) throws java.lang.Exception {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int i,j;
long quadDom, zeroDom;
// create a task object
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Create n free variables
task.appendvars(n);
task.putvarboundsliceconst(0, n, mosek.boundkey.fr, -infinity, infinity);
// Set up the objective
double[] c = {2, 3, -1};
int[] cind = {0, 1, 2};
task.putobjsense(mosek.objsense.maximize);
task.putclist(cind, c);
// Set AFE rows representing the linear constraint
task.appendafes(1);
task.putafeg(0, -1.0);
for(i = 0; i < n; i++) task.putafefentry(0, i, 1.0);
// Set AFE rows representing the quadratic constraint
// F matix in sparse form
long[] Fsubi = {2, 2, 3, 3}; // The G matrix starts in F from row 2
int[] Fsubj = {0, 1, 0, 2};
double[] Fval = {1.5, 0.1, 0.3, 2.1};
// Other data
double[] h = {0, 0.1};
double gamma = 0.03;
task.appendafes(k + 1);
task.putafefentrylist(Fsubi, Fsubj, Fval);
task.putafeg(1, gamma);
task.putafegslice(2, k+2, h);
// Define domains
zeroDom = task.appendrzerodomain(1);
quadDom = task.appendquadraticconedomain(k + 1);
// Create the linear ACC
long[] afeidxZero = {0};
task.appendacc(zeroDom, // Domain index
afeidxZero, // Indices of AFE rows
null); // Ignored
// Create the quadratic ACC
long[] afeidxQuad = {1, 2, 3};
task.appendacc(quadDom, // Domain index
afeidxQuad, // Indices of AFE rows
null); // Ignored
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Termination code: " + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
switch (solsta) {
case optimal:
// Fetch solution
double[] xx = task.getxx(mosek.soltype.itr); // Interior solution.
System.out.println("Optimal primal solution");
for (j = 0; j < n; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
// Fetch doty dual for the ACC
double[] doty = task.getaccdoty(mosek.soltype.itr, // Interior solution.
1); // ACC index
System.out.println("Dual doty value for the ACC");
for (j = 0; j < k + 1; ++j)
System.out.println ("doty[" + j + "]:" + doty[j]);
// Fetch ACC activity
double[] activity = task.evaluateacc(mosek.soltype.itr, // Interior solution.
1); // ACC index
System.out.println("Activity for the ACC");
for (j = 0; j < k + 1; ++j)
System.out.println ("activity[" + j + "]:" + activity[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
blas_lapack.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : blas_lapack.java
Purpose : To demonstrate how to call BLAS/LAPACK routines for whose MOSEK provides simplified interfaces.
*/
package com.mosek.example;
public class blas_lapack {
static final int n = 3, m = 2, k = 3;
public static void main (String[] args) {
double alpha = 2.0, beta = 0.5;
double[] x = {1., 1., 1.};
double[] y = {1., 2., 3.};
double[] z = {1.0, 1.0};
/*A has m=2 rows and k=3 cols*/
double[] A = {1., 1., 2., 2., 3., 3.};
/*B has k=3 rows and n=3 cols*/
double[] B = {1., 1., 1., 1., 1., 1., 1., 1., 1.};
double[] C = { 1., 2., 3., 4., 5., 6.};
double[] D = {1.0, 1.0, 1.0, 1.0};
double[] Q = {1.0, 0.0, 0.0, 2.0};
double[] v = new double[2];
double[] xy = {0.};
try (mosek.Env env = new mosek.Env()) {
/* routines*/
env.dot(n, x, y, xy);
env.axpy(n, alpha, x, y);
env.gemv(mosek.transpose.no, m, n, alpha, A, x, beta, z);
env.gemm(mosek.transpose.no, mosek.transpose.no, m, n, k, alpha, A, B, beta, C);
env.syrk(mosek.uplo.lo, mosek.transpose.no, m, k, alpha, A, beta, D);
/* LAPACK routines*/
env.potrf(mosek.uplo.lo, m, Q);
env.syeig(mosek.uplo.lo, m, Q, v);
env.syevd(mosek.uplo.lo, m, Q, v);
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
}
}
}
callback.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : callback.java
Purpose : To demonstrate how to use the progress
callback.
Use this script as follows:
callback psim 25fv47.mps
callback dsim 25fv47.mps
callback intpnt 25fv47.mps
The first argument tells which optimizer to use
i.e. psim is primal simplex, dsim is dual simplex
and intpnt is interior-point.
*/
package com.mosek.example;
import mosek.*;
import java.util.Formatter;
public class callback {
private static DataCallback makeUserCallback(final double maxtime) {
return new DataCallback() {
public int callback(callbackcode caller,
double[] douinf,
int[] intinf,
long[] lintinf) {
double opttime = 0.0;
int itrn;
double pobj, dobj, stime;
Formatter f = new Formatter(System.out);
switch (caller) {
case begin_intpnt:
f.format("Starting interior-point optimizer\n");
break;
case intpnt:
itrn = intinf[iinfitem.intpnt_iter.value ];
pobj = douinf[dinfitem.intpnt_primal_obj.value];
dobj = douinf[dinfitem.intpnt_dual_obj.value ];
stime = douinf[dinfitem.intpnt_time.value ];
opttime = douinf[dinfitem.optimizer_time.value ];
f.format("Iterations: %-3d\n", itrn);
f.format(" Time: %6.2f(%.2f) ", opttime, stime);
f.format(" Primal obj.: %-18.6e Dual obj.: %-18.6e\n", pobj, dobj);
break;
case end_intpnt:
f.format("Interior-point optimizer finished.\n");
break;
case begin_primal_simplex:
f.format("Primal simplex optimizer started.\n");
break;
case update_primal_simplex:
itrn = intinf[iinfitem.sim_primal_iter.value ];
pobj = douinf[dinfitem.sim_obj.value ];
stime = douinf[dinfitem.sim_time.value ];
opttime = douinf[dinfitem.optimizer_time.value ];
f.format("Iterations: %-3d\n", itrn);
f.format(" Elapsed time: %6.2f(%.2f\n", opttime, stime);
f.format(" Obj.: %-18.6e", pobj );
break;
case end_primal_simplex:
f.format("Primal simplex optimizer finished.\n");
break;
case begin_dual_simplex:
f.format("Dual simplex optimizer started.\n");
break;
case update_dual_simplex:
itrn = intinf[iinfitem.sim_dual_iter.value ];
pobj = douinf[dinfitem.sim_obj.value ];
stime = douinf[dinfitem.sim_time.value ];
opttime = douinf[dinfitem.optimizer_time.value ];
f.format("Iterations: %-3d\n", itrn);
f.format(" Elapsed time: %6.2f(%.2f)\n", opttime, stime);
f.format(" Obj.: %-18.6e\n", pobj);
break;
case end_dual_simplex:
f.format("Dual simplex optimizer finished.\n");
break;
case begin_bi:
f.format("Basis identification started.\n");
break;
case end_bi:
f.format("Basis identification finished.\n");
break;
default:
}
System.out.flush();
if (opttime >= maxtime)
// mosek is spending too much time. Terminate it.
return 1;
return 0;
}
};
}
public static void main(String[] args) {
String filename = "../data/25fv47.mps";
String slvr = "intpnt";
if (args.length < 2) {
System.out.println("Usage: ( psim | dsim | intpnt ) filename");
}
if (args.length >= 1) slvr = args[0];
if (args.length >= 2) filename = args[1];
System.out.println("filename = " + filename);
try (Task task = new Task()) {
task.readdata(filename);
if (slvr == "psim")
task.putintparam(iparam.optimizer, optimizertype.primal_simplex.value);
else if (slvr == "dsim")
task.putintparam(iparam.optimizer, optimizertype.dual_simplex.value);
else if (slvr == "intpnt")
task.putintparam(iparam.optimizer, optimizertype.intpnt.value);
// Turn all MOSEK logging off (note that errors and other messages
// are still sent through the log stream)
double maxtime = 0.05;
task.set_InfoCallback(makeUserCallback(maxtime));
task.optimize();
task.putintparam(iparam.log, 1);
task.solutionsummary(streamtype.msg);
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
ceo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : ceo1.java
Purpose : Demonstrates how to solve a small conic exponential
optimization problem using the MOSEK API.
*/
package com.mosek.example;
import mosek.*;
public class ceo1 {
static final int numcon = 1;
static final int numvar = 3;
public static void main (String[] args) throws java.lang.Exception {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
mosek.boundkey bkc = mosek.boundkey.fx ;
double blc = 1.0 ;
double buc = 1.0 ;
mosek.boundkey[] bkx = { mosek.boundkey.fr,
mosek.boundkey.fr,
mosek.boundkey.fr
};
double[] blx = { -infinity,
-infinity,
-infinity
};
double[] bux = { +infinity,
+infinity,
+infinity
};
double[] c = { 1.0,
1.0,
0.0
};
double[] a = { 1.0,
1.0,
1.0
};
int[] asub = {0, 1, 2};
int[] csub = new int[numvar];
// create a new task
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
/* Define the linear part of the problem */
task.putcslice(0, numvar, c);
task.putarow(0, asub, a);
task.putconbound(0, bkc, blc, buc);
task.putvarboundslice(0, numvar, bkx, blx, bux);
/* Add a conic constraint */
/* Create a 3x3 identity matrix F */
task.appendafes(3);
task.putafefentrylist(new long[]{0, 1, 2}, /* Rows */
new int[]{0, 1, 2}, /* Columns */
new double[]{1.0, 1.0, 1.0});
/* Exponential cone (x(0),x(1),x(2)) \in EXP */
long expdomain = task.appendprimalexpconedomain();
task.appendacc(expdomain, /* Domain */
new long[]{0, 1, 2}, /* Rows from F */
null); /* Unused */
task.putobjsense(mosek.objsense.minimize);
System.out.println ("optimize");
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Mosek warning:" + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
double[] xx = task.getxx(mosek.soltype.itr); // Interior solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
concurrent1.java
/*
Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File: concurrent1.java
Purpose: Demonstrates a simple implementation of a concurrent optimizer.
The concurrent optimizer starts a few parallel optimizations
of the same problem using different algorithms, and reports
a solution when the first optimizer is ready.
This example also demonstrates how to define a simple callback handler
that stops the optimizer when requested.
*/
package com.mosek.example;
public class concurrent1
{
/** Takes a list of tasks and optimizes then in parallel. The
response code and termination code from each optimization is
stored in ``res`` and ``trm``.
When one task completes with rescode == ok, others are terminated.
Returns the index of the first task that returned
with rescode == ok. Whether or not this task contains the
most valuable answer, is for the caller to decide. If none
completed without error return -1.
*/
public static int optimize(mosek.Task[] tasks,
mosek.rescode[] res,
mosek.rescode[] trm)
{
int n = tasks.length;
Thread[] jobs = new Thread[n];
// Set a callback function
final CallbackProxy cb = new CallbackProxy();
for (int i = 0; i < n; ++i)
tasks[i].set_Progress(cb);
// Initialize
for (int i = 0; i < n; ++i)
{
res[i] = mosek.rescode.err_unknown;
trm[i] = mosek.rescode.err_unknown;
}
// Start parallel optimizations, one per task
for (int i = 0; i < n; ++i)
{
int num = i;
jobs[i] = new Thread() { public void run() {
try
{
trm[num] = tasks[num].optimize();
res[num] = mosek.rescode.ok;
}
catch (mosek.Exception e)
{
trm[num] = mosek.rescode.err_unknown;
res[num] = e.code;
}
finally
{
// If this finished with success, inform other tasks to interrupt
if (res[num] == mosek.rescode.ok)
{
if (!cb.stop) cb.firstStop = num;
cb.stop = true;
}
}
}};
jobs[i].start();
}
// Join all threads
try {
for (Thread j: jobs)
j.join();
}
catch (InterruptedException e) {}
// For debugging, print res and trm codes for all optimizers
for (int i = 0; i < n; ++i)
System.out.println("Optimizer " + i + " res " + res[i] + " trm " + trm[i]);
return cb.firstStop;
}
/**
Given a continuous task, set up jobs to optimize it
with a list of different solvers.
Returns an index, corresponding to the optimization
task that is returned as winTask. This is the task
with the best possible status of those that finished.
If none task is considered successful returns -1.
*/
public static int optimizeconcurrent(mosek.Task task,
mosek.optimizertype[] optimizers,
mosek.Task[] winTask,
mosek.rescode[] winTrm,
mosek.rescode[] winRes)
{
int n = optimizers.length;
mosek.Task[] tasks = new mosek.Task[n];
mosek.rescode[] res = new mosek.rescode[n];
mosek.rescode[] trm = new mosek.rescode[n];
// Clone tasks and choose various optimizers
for (int i = 0; i < n; ++i)
{
tasks[i] = new mosek.Task(task);
tasks[i].putintparam(mosek.iparam.optimizer, optimizers[i].value);
}
// Solve tasks in parallel
int firstOK = optimize(tasks, res, trm);
if (firstOK >= 0)
{
winTask[0] = tasks[firstOK];
winTrm[0] = trm[firstOK];
winRes[0] = res[firstOK];
}
return firstOK;
}
/**
Given a mixed-integer task, set up jobs to optimize it
with different values of seed. That will lead to
different execution paths of the optimizer.
Returns an index, corresponding to the optimization
task that is returned as winTask. This is the task
with the best value of the objective function.
If none task is considered successful returns -1.
Typically, the input task would contain a time limit. The two
major scenarios are:
1. Some clone ends before time limit - then it has optimum.
2. All clones reach time limit - pick the one with best objective.
*/
public static int optimizeconcurrentMIO(mosek.Task task,
int[] seeds,
mosek.Task[] winTask,
mosek.rescode[] winTrm,
mosek.rescode[] winRes)
{
int n = seeds.length;
mosek.Task[] tasks = new mosek.Task[n];
mosek.rescode[] res = new mosek.rescode[n];
mosek.rescode[] trm = new mosek.rescode[n];
// Clone tasks and choose various seeds for the optimizer
for (int i = 0; i < n; ++i)
{
tasks[i] = new mosek.Task(task);
tasks[i].putintparam(mosek.iparam.mio_seed, seeds[i]);
}
// Solve tasks in parallel
int firstOK = optimize(tasks, res, trm);
if (firstOK >= 0)
{
// Pick the task that ended with res = ok
// and contains an integer solution with best objective value
mosek.objsense sense = task.getobjsense();
double bestObj = (sense == mosek.objsense.minimize) ? 1.0e+10 : -1.0e+10;
int bestPos = -1;
for (int i = 0; i < n; ++i)
System.out.println(i + " " + tasks[i].getprimalobj(mosek.soltype.itg));
for (int i = 0; i < n; ++i)
if ((res[i] == mosek.rescode.ok) &&
(tasks[i].getsolsta(mosek.soltype.itg) == mosek.solsta.prim_feas ||
tasks[i].getsolsta(mosek.soltype.itg) == mosek.solsta.integer_optimal) &&
((sense == mosek.objsense.minimize) ?
(tasks[i].getprimalobj(mosek.soltype.itg) < bestObj) :
(tasks[i].getprimalobj(mosek.soltype.itg) > bestObj) ) )
{
bestObj = tasks[i].getprimalobj(mosek.soltype.itg);
bestPos = i;
}
if (bestPos != -1)
{
winTask[0] = tasks[bestPos];
winTrm[0] = trm[bestPos];
winRes[0] = res[bestPos];
return bestPos;
}
}
return -1;
}
/**
This is an example of how one can use the methods
optimizeconcurrent
optimizeconcurrentMIO
argv[0] : name of file with input problem
argv[1]: (optional) time limit
*/
public static void main(String[] argv)
{
try (mosek.Env env = new mosek.Env();
mosek.Task task = new mosek.Task(env, 0, 0)) {
if (argv.length>=1)
{
task.readdata(argv[0]);
}
else
{
task.readdata("../data/25fv47.mps");
}
mosek.rescode[] res = { mosek.rescode.ok }, trm = { mosek.rescode.ok };
mosek.Task[] t = new mosek.Task[1];
int idx;
int[] numint = { 0 };
task.getnumintvar(numint);
// Optional time limit
if (argv.length >= 2) {
double timeLimit = Double.parseDouble(argv[1]);
task.putdouparam(mosek.dparam.optimizer_max_time, timeLimit);
}
if (numint[0] == 0)
{
/* If the problem is continuous
optimize it with three continuous optimizers.
(Simplex will fail for non-linear problems)
*/
mosek.optimizertype[] optimizers = {
mosek.optimizertype.conic,
mosek.optimizertype.dual_simplex,
mosek.optimizertype.primal_simplex
};
idx = optimizeconcurrent(task, optimizers, t, trm, res);
}
else
{
/* Mixed-integer problem.
Try various seeds.
*/
int[] seeds = { 42, 13, 71749373 };
idx = optimizeconcurrentMIO(task, seeds, t, trm, res);
}
// Check results and print the best answer
if (idx >= 0)
{
System.out.println("Result from optimizer with index " + idx + ": res " + res[0] + " trm " + trm[0]);
t[0].set_Stream(mosek.streamtype.log, new mosek.Stream() { public void stream(String s) { System.out.print(s); }});
t[0].optimizersummary(mosek.streamtype.log);
t[0].solutionsummary(mosek.streamtype.log);
}
else
{
System.out.println("All optimizers failed.");
}
}
}
/**
Defines a Mosek callback function whose only function
is to indicate if the optimizer should be stopped.
*/
public static class CallbackProxy extends mosek.Progress
{
public boolean stop;
public int firstStop;
public CallbackProxy()
{
stop = false;
firstStop = -1;
}
public int progress(mosek.callbackcode caller)
{
// Return non-zero implies terminate the optimizer
return stop ? 1 : 0;
}
}
}
cqo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : cqo1.java
Purpose : Demonstrates how to solve a small conic quadratic
optimization problem using the MOSEK API.
*/
package com.mosek.example;
import mosek.*;
public class cqo1 {
static final int numcon = 1;
static final int numvar = 6;
public static void main (String[] args) throws java.lang.Exception {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
mosek.boundkey[] bkc = { mosek.boundkey.fx };
double[] blc = { 1.0 };
double[] buc = { 1.0 };
mosek.boundkey[] bkx
= {mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.fr,
mosek.boundkey.fr,
mosek.boundkey.fr
};
double[] blx = { 0.0,
0.0,
0.0,
-infinity,
-infinity,
-infinity
};
double[] bux = { +infinity,
+infinity,
+infinity,
+infinity,
+infinity,
+infinity
};
double[] c = { 0.0,
0.0,
0.0,
1.0,
1.0,
1.0
};
double[][] aval = {
{1.0},
{1.0},
{2.0}
};
int[][] asub = {
{0},
{0},
{0}
};
int[] csub = new int[3];
// create a new task
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Give MOSEK an estimate of the size of the input data.
This is done to increase the speed of inputting data.
However, it is optional. */
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
/* Optionally add a constant term to the objective. */
task.putcfix(0.0);
for (int j = 0; j < numvar; ++j) {
/* Set the linear term c_j in the objective.*/
task.putcj(j, c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putvarbound(j, bkx[j], blx[j], bux[j]);
}
for (int j = 0; j < aval.length; ++j)
/* Input column j of A */
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
/* Create a matrix F such that F * x = [x(3),x(0),x(1),x(4),x(5),x(2)] */
task.appendafes(6);
task.putafefentrylist(new long[]{0, 1, 2, 3, 4, 5}, /* Rows */
new int[]{3, 0, 1, 4, 5, 2}, /* Columns */
new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0});
/* Quadratic cone (x(3),x(0),x(1)) \in QUAD_3 */
long quadcone = task.appendquadraticconedomain(3);
task.appendacc(quadcone, /* Domain */
new long[]{0, 1, 2}, /* Rows from F */
null); /* Unused */
/* Rotated quadratic cone (x(4),x(5),x(2)) \in RQUAD_3 */
long rquadcone = task.appendrquadraticconedomain(3);
task.appendacc(rquadcone, /* Domain */
new long[]{3, 4, 5}, /* Rows from F */
null); /* Unused */
task.putobjsense(mosek.objsense.minimize);
System.out.println ("optimize");
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Mosek warning:" + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
double[] xx = task.getxx(mosek.soltype.itr); // Interior solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
djc1.java
////
// Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
// File: djc1.java
//
// Purpose: Demonstrates how to solve the problem with two disjunctions:
//
// minimize 2x0 + x1 + 3x2 + x3
// subject to x0 + x1 + x2 + x3 >= -10
// (x0-2x1<=-1 and x2=x3=0) or (x2-3x3<=-2 and x1=x2=0)
// x0=2.5 or x1=2.5 or x2=2.5 or x3=2.5
////
package com.mosek.example;
import mosek.*;
public class djc1 {
static double inf = 0.0; // Infinity for symbolic purposes
public static void main (String[] args) {
// Make a task
try (mosek.Task task = new Task()) {
// Append free variables
int numvar = 4;
task.appendvars(numvar);
task.putvarboundsliceconst(0, numvar, mosek.boundkey.fr, -inf, inf);
// The linear part: the linear constraint
task.appendcons(1);
task.putarow(0, new int[]{0, 1, 2, 3}, new double[]{1, 1, 1, 1});
task.putconbound(0, mosek.boundkey.lo, -10.0, -10.0);
// The linear part: objective
task.putobjsense(mosek.objsense.minimize);
task.putclist(new int[]{0, 1, 2, 3}, new double[]{2, 1, 3, 1});
// Fill in the affine expression storage F, g
long numafe = 10;
task.appendafes(numafe);
long[] fafeidx = new long[]{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] fvaridx = new int[]{0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};
double[] fval = new double[]{1.0, -2.0, 1.0, -3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
double[] g = new double[]{1.0, 2.0, 0.0, 0.0, 0.0, 0.0, -2.5, -2.5, -2.5, -2.5};
task.putafefentrylist(fafeidx, fvaridx, fval);
task.putafegslice(0, numafe, g);
// Create domains
long zero1 = task.appendrzerodomain(1);
long zero2 = task.appendrzerodomain(2);
long rminus1 = task.appendrminusdomain(1);
// Append disjunctive constraints
long numdjc = 2;
task.appenddjcs(numdjc);
// First disjunctive constraint
task.putdjc(0, // DJC index
new long[]{rminus1, zero2, rminus1, zero2}, // Domains (domidxlist)
new long[]{0, 4, 5, 1, 2, 3}, // AFE indices (afeidxlist)
null, // Unused
new long[]{2, 2} ); // Term sizes (termsizelist)
// Second disjunctive constraint
task.putdjc(1, // DJC index
new long[]{zero1, zero1, zero1, zero1}, // Domains (domidxlist)
new long[]{6, 7, 8, 9}, // AFE indices (afeidxlist)
null, // Unused
new long[]{1, 1, 1, 1} ); // Term sizes (termidxlist)
// Useful for debugging
task.writedata("djc.ptf"); // Write file in human-readable format
// Attach a log stream printer to the task
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Solve the problem
task.optimize();
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
// Get status information about the solution
mosek.solsta solsta = task.getsolsta(mosek.soltype.itg);
switch (solsta) {
case integer_optimal:
double[] xx = task.getxx(mosek.soltype.itg);
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
default:
System.out.println("Another solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
feasrepairex1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : feasrepairex1.java
Purpose : To demonstrate how to use the MSK_relaxprimal function to
locate the cause of an infeasibility.
Syntax : On command line
java feasrepairex1.feasrepairex1 feasrepair.lp
feasrepair.lp is located in mosek\<version>\tools\examples.
*/
package com.mosek.example;
import mosek.*;
public class feasrepairex1 {
public static void main (String[] args) {
String filename = "../data/feasrepair.lp";
if (args.length >= 1) filename = args[0];
try (Env env = new Env();
Task task = new Task(env, 0, 0)) {
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
task.readdata(filename);
task.putintparam(mosek.iparam.log_feas_repair, 3);
task.primalrepair(null, null, null, null);
double sum_viol = task.getdouinf(mosek.dinfitem.primal_repair_penalty_obj);
System.out.println("Minimized sum of violations = " + sum_viol);
task.optimize();
task.solutionsummary(mosek.streamtype.msg);
}
}
}
gp1.java
//
// Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
// File: gp1.java
//
// Purpose: Demonstrates how to solve a simple Geometric Program (GP)
// cast into conic form with exponential cones and log-sum-exp.
//
// Example from
// https://gpkit.readthedocs.io/en/latest/examples.html//maximizing-the-volume-of-a-box
//
package com.mosek.example;
import mosek.*;
import java.lang.Math;
public class gp1 {
// Since the value of infinity is ignored, we define it solely
// for symbolic purposes
static final double inf = 0.0;
// maximize h*w*d
// subjecto to 2*(h*w + h*d) <= Awall
// w*d <= Afloor
// alpha <= h/w <= beta
// gamma <= d/w <= delta
//
// Variable substitutions: h = exp(x), w = exp(y), d = exp(z).
//
// maximize x+y+z
// subject log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0
// y+z <= log(Afloor)
// log( alpha ) <= x-y <= log( beta )
// log( gamma ) <= z-y <= log( delta )
public static double[] max_volume_box(double Aw, double Af,
double alpha, double beta, double gamma, double delta)
{
// Basic dimensions of our problem
int numvar = 3; // Variables in original problem
int x=0, y=1, z=2; // Indices of variables
int numcon = 3; // Linear constraints in original problem
// Linear part of the problem involving x, y, z
double[] cval = {1, 1, 1};
int[] asubi = {0, 0, 1, 1, 2, 2};
int[] asubj = {y, z, x, y, z, y};
double[] aval = {1.0, 1.0, 1.0, -1.0, 1.0, -1.0};
boundkey[] bkc = {boundkey.up, boundkey.ra, boundkey.ra};
double[] blc = {-inf, Math.log(alpha), Math.log(gamma)};
double[] buc = {Math.log(Af), Math.log(beta), Math.log(delta)};
try (Task task = new Task())
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
streamtype.log,
new Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Add variables and constraints
task.appendvars(numvar);
task.appendcons(numcon);
// Objective is the sum of three first variables
task.putobjsense(objsense.maximize);
task.putcslice(0, numvar, cval);
task.putvarboundsliceconst(0, numvar, boundkey.fr, -inf, inf);
// Add the linear constraints
task.putaijlist(asubi, asubj, aval);
task.putconboundslice(0, numcon, bkc, blc, buc);
// Affine expressions appearing in affine conic constraints
// in this order:
// u1, u2, x+y+log(2/Awall), x+z+log(2/Awall), 1.0, u1+u2-1.0
long numafe = 6;
int u1 = 3, u2 = 4; // Indices of slack variables
long[] afeidx = {0, 1, 2, 2, 3, 3, 5, 5};
int[] varidx = {u1, u2, x, y, x, z, u1, u2};
double[] fval = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
double[] gfull = {0, 0, Math.log(2/Aw), Math.log(2/Aw), 1.0, -1.0};
// New variables u1, u2
task.appendvars(2);
task.putvarboundsliceconst(u1, u2+1, boundkey.fr, -inf, inf);
// Append affine expressions
task.appendafes(numafe);
task.putafefentrylist(afeidx, varidx, fval);
task.putafegslice(0, numafe, gfull);
// Two affine conic constraints
long expdom = task.appendprimalexpconedomain();
// (u1, 1, x+y+log(2/Awall)) \in EXP
task.appendacc(expdom, new long[]{0, 4, 2}, null);
// (u2, 1, x+z+log(2/Awall)) \in EXP
task.appendacc(expdom, new long[]{1, 4, 3}, null);
// The constraint u1+u2-1 \in \ZERO is added also as an ACC
task.appendacc(task.appendrzerodomain(1), new long[]{5}, null);
// Solve and map to original h, w, d
task.optimize();
double[] xyz = task.getxxslice(soltype.itr, 0, numvar);
double[] hwd = new double[numvar];
for(int i = 0; i < numvar; i++) hwd[i] = Math.exp(xyz[i]);
return hwd;
}
}
public static void main(String[] args)
{
double Aw = 200.0;
double Af = 50.0;
double alpha = 2.0;
double beta = 10.0;
double gamma = 2.0;
double delta = 10.0;
double[] hwd = max_volume_box(Aw, Af, alpha, beta, gamma, delta);
System.out.format("h=%.4f w=%.4f d=%.4f\n", hwd[0], hwd[1], hwd[2]);
}
}
helloworld.java
//
// Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
// File: helloworld.java
//
// The most basic example of how to get started with MOSEK.
package com.mosek.example;
import mosek.*;
public class helloworld {
public static void main(String[] args) {
try (Task task = new Task()) { // Create task
task.appendvars(1); // 1 variable x
task.putcj(0, 1.0); // c_0 = 1.0
task.putvarbound(0, boundkey.ra, 2.0, 3.0); // 2.0 <= x <= 3.0
task.putobjsense(objsense.minimize); // minimize
task.optimize(); // Optimize
double x[] = task.getxx(soltype.itr); // Get solution
System.out.println("Solution x = " + x[0]); // Print solution
}
}
}
lo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : lo1.java
Purpose : Demonstrates how to solve a small linear
optimization problem using the MOSEK Java API.
*/
package com.mosek.example;
import mosek.*;
public class lo1 {
static final int numcon = 3;
static final int numvar = 4;
public static void main (String[] args) {
// Since the value of infinity is ignored, we define it solely
// for symbolic purposes
double infinity = 0;
double c[] = {3.0, 1.0, 5.0, 1.0};
int asub[][] = {
{0, 1},
{0, 1, 2},
{0, 1},
{1, 2}
};
double aval[][] = {
{3.0, 2.0},
{1.0, 1.0, 2.0},
{2.0, 3.0},
{1.0, 3.0}
};
mosek.boundkey[]
bkc = {mosek.boundkey.fx,
mosek.boundkey.lo,
mosek.boundkey.up
};
double blc[] = {30.0,
15.0,
-infinity
};
double buc[] = {30.0,
+infinity,
25.0
};
mosek.boundkey
bkx[] = {mosek.boundkey.lo,
mosek.boundkey.ra,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double blx[] = {0.0,
0.0,
0.0,
0.0
};
double bux[] = { +infinity,
10.0,
+infinity,
+infinity
};
try (mosek.Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Append 'numcon' empty constraints.
// The constraints will initially have no bounds.
task.appendcons(numcon);
// Append 'numvar' variables.
// The variables will initially be fixed at zero (x=0).
task.appendvars(numvar);
for (int j = 0; j < numvar; ++j) {
// Set the linear term c_j in the objective.
task.putcj(j, c[j]);
// Set the bounds on variable j.
// blx[j] <= x_j <= bux[j]
task.putvarbound(j, bkx[j], blx[j], bux[j]);
// Input column j of A
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
}
// Set the bounds on constraints.
// blc[i] <= constraint_i <= buc[i]
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
// Input the objective sense (minimize/maximize)
task.putobjsense(mosek.objsense.maximize);
// Solve the problem
task.optimize();
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
// Get status information about the solution
mosek.solsta solsta = task.getsolsta(mosek.soltype.bas);
switch (solsta) {
case optimal:
double[] xx = task.getxx(mosek.soltype.bas); // Request the basic solution.
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility certificate found.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
lo2.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : lo2.java
Purpose : Demonstrates how to solve a small linear
optimization problem using the MOSEK Java API.
*/
package com.mosek.example;
import mosek.*;
public class lo2 {
static final int numcon = 3;
static final int numvar = 4;
static final int NUMANZ = 9;
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double
infinity = 0;
double c[] = {3.0, 1.0, 5.0, 1.0};
int asub[][] = {
{0, 1, 2},
{0, 1, 2, 3},
{1, 3}
};
double aval[][] = {
{3.0, 1.0, 2.0 },
{2.0, 1.0, 3.0, 1.0},
{2.0, 3.0}
};
mosek.boundkey[]
bkc = {mosek.boundkey.fx,
mosek.boundkey.lo,
mosek.boundkey.up
};
double blc[] = {30.0,
15.0,
-infinity
};
double buc[] = {30.0,
+infinity,
25.0
};
mosek.boundkey
bkx[] = {mosek.boundkey.lo,
mosek.boundkey.ra,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double blx[] = {0.0,
0.0,
0.0,
0.0
};
double bux[] = { +infinity,
10.0,
+infinity,
+infinity
};
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Give MOSEK an estimate of the size of the input data.
This is done to increase the speed of inputting data.
However, it is optional. */
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
for (int j = 0; j < numvar; ++j) {
/* Set the linear term c_j in the objective.*/
task.putcj(j, c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putvarbound(j, bkx[j], blx[j], bux[j]);
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i) {
task.putconbound(i, bkc[i], blc[i], buc[i]);
/* Input row i of A */
task.putarow(i, /* Row index.*/
asub[i], /* Column indexes of non-zeros in row i.*/
aval[i]); /* Non-zero Values of row i. */
}
/* A maximization problem */
task.putobjsense(mosek.objsense.maximize);
/* Solve the problem */
mosek.rescode r = task.optimize();
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.bas);
double xx[] = task.getxx(mosek.soltype.bas); // Basic solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
logistic.java
//
// Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
// File: logistic.java
//
// Purpose: Implements logistic regression with regulatization.
//
// Demonstrates using the exponential cone and log-sum-exp in Optimizer API.
package com.mosek.example;
import mosek.*;
public class logistic {
public static double inf = 0.0;
// Adds ACCs for t_i >= log ( 1 + exp((1-2*y[i]) * theta' * X[i]) )
// Adds auxiliary variables, AFE rows and constraints
public static void softplus(Task task, int d, int n, int theta, int t, double[][] X, boolean[] y)
{
int nvar = task.getnumvar();
int ncon = task.getnumcon();
long nafe = task.getnumafe();
task.appendvars(2*n); // z1, z2
task.appendcons(n); // z1 + z2 = 1
task.appendafes(4*n); //theta * X[i] - t[i], -t[i], z1[i], z2[i]
int z1 = nvar, z2 = nvar+n;
int zcon = ncon;
long thetaafe = nafe, tafe = nafe+n, z1afe = nafe+2*n, z2afe = nafe+3*n;
int k = 0;
// Linear constraints
int[] subi = new int[2*n];
int[] subj = new int[2*n];
double[] aval = new double[2*n];
for(int i = 0; i < n; i++)
{
// z1 + z2 = 1
subi[k] = zcon+i; subj[k] = z1+i; aval[k] = 1; k++;
subi[k] = zcon+i; subj[k] = z2+i; aval[k] = 1; k++;
}
task.putaijlist(subi, subj, aval);
task.putconboundsliceconst(zcon, zcon+n, boundkey.fx, 1, 1);
task.putvarboundsliceconst(nvar, nvar+2*n, boundkey.fr, -inf, inf);
// Affine conic expressions
long[] afeidx = new long[d*n+4*n];
int[] varidx = new int[d*n+4*n];
double[] fval = new double[d*n+4*n];
k = 0;
// Thetas
for(int i = 0; i < n; i++) {
for(int j = 0; j < d; j++) {
afeidx[k] = thetaafe + i; varidx[k] = theta + j;
fval[k] = ((y[i]) ? -1 : 1) * X[i][j];
k++;
}
}
// -t[i]
for(int i = 0; i < n; i++) {
afeidx[k] = thetaafe + i; varidx[k] = t + i; fval[k] = -1; k++;
afeidx[k] = tafe + i; varidx[k] = t + i; fval[k] = -1; k++;
}
// z1, z2
for(int i = 0; i < n; i++) {
afeidx[k] = z1afe + i; varidx[k] = z1 + i; fval[k] = 1; k++;
afeidx[k] = z2afe + i; varidx[k] = z2 + i; fval[k] = 1; k++;
}
// Add the expressions
task.putafefentrylist(afeidx, varidx, fval);
// Add a single row with the constant expression "1.0"
long oneafe = task.getnumafe();
task.appendafes(1);
task.putafeg(oneafe, 1.0);
// Add an exponential cone domain
long expdomain = task.appendprimalexpconedomain();
// Conic constraints
long numacc = task.getnumacc();
for(int i = 0; i < n; i++)
{
task.appendacc(expdomain, new long[]{z1afe+i, oneafe, thetaafe+i}, null);
task.appendacc(expdomain, new long[]{z2afe+i, oneafe, tafe+i}, null);
task.putaccname(numacc+i*2, String.format("z1:theta[%d]",i));
task.putaccname(numacc+i*2+1,String.format("z2:t[%d]",i));
}
}
// Model logistic regression (regularized with full 2-norm of theta)
// X - n x d matrix of data points
// y - length n vector classifying training points
// lamb - regularization parameter
public static double[] logisticRegression(double[][] X,
boolean[] y,
double lamb)
{
int n = X.length;
int d = X[0].length; // num samples, dimension
try (Task task = new Task())
{
// Variables [r; theta; t]
int nvar = 1+d+n;
task.appendvars(nvar);
task.putvarboundsliceconst(0, nvar, boundkey.fr, -inf, inf);
int r = 0, theta = 1, t = 1+d;
task.putvarname(r,"r");
for (int i = 0; i < d; ++i) task.putvarname(theta+i,String.format("theta[%d]",i));
for (int i = 0; i < n; ++i) task.putvarname(t+i,String.format("t[%d]",i));
// Objective lambda*r + sum(t)
task.putobjsense(mosek.objsense.minimize);
task.putcj(r, lamb);
for(int i = 0; i < n; i++)
task.putcj(t+i, 1.0);
// Softplus function constraints
softplus(task, d, n, theta, t, X, y);
// Regularization
// Append a sequence of linear expressions (r, theta) to F
long numafe = task.getnumafe();
task.appendafes(1+d);
task.putafefentry(numafe, r, 1.0);
for(int i = 0; i < d; i++)
task.putafefentry(numafe + i + 1, theta + i, 1.0);
// Add the constraint
task.appendaccseq(task.appendquadraticconedomain(1+d), numafe, null);
// Solution
task.optimize();
return task.getxxslice(soltype.itr, theta, theta+d);
}
}
public static void main(String[] args)
{
// Test: detect and approximate a circle using degree 2 polynomials
int n = 30;
double[][] X = new double[n*n][6];
boolean[] Y = new boolean[n*n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
int k = i*n+j;
double x = -1 + 2.0*i/(n-1);
double y = -1 + 2.0*j/(n-1);
X[k][0] = 1.0; X[k][1] = x; X[k][2] = y; X[k][3] = x*y;
X[k][4] = x*x; X[k][5] = y*y;
Y[k] = (x*x+y*y>=0.69);
}
double[] theta = logisticRegression(X, Y, 0.1);
for(int i=0;i<6;i++)
System.out.println(theta[i]);
}
}
mico1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : mico1.java
Purpose : Demonstrates how to solve a small mixed
integer conic optimization problem.
minimize x^2 + y^2
subject to x >= e^y + 3.8
x, y - integer
*/
package com.mosek.example;
import mosek.*;
public class mico1 {
public static void main (String[] args) {
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
task.appendvars(3); // x, y, t
int x=0, y=1, t=2;
task.putvarboundsliceconst(0, 3, mosek.boundkey.fr, -0.0, 0.0);
// Integrality constraints for x, y
task.putvartypelist(new int[]{x,y},
new mosek.variabletype[]{mosek.variabletype.type_int, mosek.variabletype.type_int});
// Set up the affine expressions
// x, x-3.8, y, t, 1.0
task.appendafes(5);
task.putafefentrylist(new long[]{0,1,2,3},
new int[]{x,x,y,t},
new double[]{1,1,1,1});
task.putafegslice(0, 5, new double[]{0, -3.8, 0, 0, 1.0});
// Add constraint (x-3.8, 1, y) \in \EXP
task.appendacc(task.appendprimalexpconedomain(), new long[]{1, 4, 2}, null);
// Add constraint (t, x, y) \in \QUAD
task.appendacc(task.appendquadraticconedomain(3), new long[]{3, 0, 2}, null);
// Objective
task.putobjsense(mosek.objsense.minimize);
task.putcj(t, 1);
// Optimize the task
task.optimize();
task.solutionsummary(mosek.streamtype.msg);
double[] xx = task.getxxslice(mosek.soltype.itg, 0, 2);
System.out.println("x = " + xx[0] + " y = " + xx[1]);
}
}
}
milo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : milo1.java
Purpose : Demonstrates how to solve a small mixed
integer linear optimization problem using the MOSEK Java API.
*/
package com.mosek.example;
import mosek.*;
public class milo1 {
static final int numcon = 2;
static final int numvar = 2;
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
mosek.boundkey[] bkc
= { mosek.boundkey.up, mosek.boundkey.lo };
double[] blc = { -infinity, -4.0 };
double[] buc = { 250.0, infinity };
mosek.boundkey[] bkx
= { mosek.boundkey.lo, mosek.boundkey.lo };
double[] blx = { 0.0, 0.0 };
double[] bux = { infinity, infinity };
double[] c = {1.0, 0.64 };
int[][] asub = { {0, 1}, {0, 1} };
double[][] aval = { {50.0, 3.0}, {31.0, -2.0} };
int[] ptrb = { 0, 2 };
int[] ptre = { 2, 4 };
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
task.set_ItgSolutionCallback(
new mosek.ItgSolutionCallback() {
public void callback(double[] xx) {
System.out.print("New integer solution: ");
for (double v : xx) System.out.print("" + v + " ");
System.out.println("");
}
});
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
for (int j = 0; j < numvar; ++j) {
/* Set the linear term c_j in the objective.*/
task.putcj(j, c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putvarbound(j, bkx[j], blx[j], bux[j]);
/* Input column j of A */
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
/* Specify integer variables. */
for (int j = 0; j < numvar; ++j)
task.putvartype(j, mosek.variabletype.type_int);
/* Set max solution time */
task.putdouparam(mosek.dparam.mio_max_time, 60.0);
/* A maximization problem */
task.putobjsense(mosek.objsense.maximize);
/* Solve the problem */
try {
task.optimize();
} catch (mosek.Warning e) {
System.out.println (" Mosek warning:");
System.out.println (e.toString ());
}
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
double xx[] = task.getxx(mosek.soltype.itg); // Integer solution.
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itg);
switch (solsta) {
case integer_optimal:
System.out.println("Optimal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case prim_feas:
System.out.println("Feasible solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case unknown:
mosek.prosta prosta = task.getprosta(mosek.soltype.itg);
switch (prosta) {
case prim_infeas_or_unbounded:
System.out.println("Problem status Infeasible or unbounded");
break;
case prim_infeas:
System.out.println("Problem status Infeasible.");
break;
case unknown:
System.out.println("Problem status unknown.");
break;
default:
System.out.println("Other problem status.");
break;
}
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error or warning was encountered");
System.out.println (e.getMessage ());
throw e;
}
}
}
mioinitsol.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : mioinitsol.java
Purpose : Demonstrates how to solve a MIP with a start guess.
*/
package com.mosek.example;
import mosek.*;
class msgclass extends mosek.Stream {
public msgclass () {
super ();
}
public void stream (String msg) {
System.out.print (msg);
}
}
public class mioinitsol {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int numvar = 4;
int numcon = 1;
double[] c = { 7.0, 10.0, 1.0, 5.0 };
mosek.boundkey[] bkc = {mosek.boundkey.up};
double[] blc = { -infinity};
double[] buc = {2.5};
mosek.boundkey[] bkx = {mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double[] blx = {0.0,
0.0,
0.0,
0.0
};
double[] bux = {infinity,
infinity,
infinity,
infinity
};
int[] ptrb = {0, 1, 2, 3};
int[] ptre = {1, 2, 3, 4};
double[] aval = {1.0, 1.0, 1.0, 1.0};
int[] asub = {0, 0, 0, 0 };
int[] intsub = {0, 1, 2};
mosek.variabletype[] inttype = {mosek.variabletype.type_int,
mosek.variabletype.type_int,
mosek.variabletype.type_int
};
try (Task task = new Task())
{
// Directs the log task stream to the user specified
// method task_msg_obj.print
msgclass task_msg_obj = new msgclass ();
task.set_Stream (mosek.streamtype.log, task_msg_obj);
task.inputdata(numcon, numvar,
c, 0.0,
ptrb, ptre,
asub, aval,
bkc, blc, buc,
bkx, blx, bux);
task.putvartypelist(intsub, inttype);
/* A maximization problem */
task.putobjsense(mosek.objsense.maximize);
// Assign values to integer variables
// We only set that slice of xx
task.putxxslice(mosek.soltype.itg, 0, 3, new double[]{1.0, 1.0, 0.0});
// Request constructing the solution from integer variable values
task.putintparam(mosek.iparam.mio_construct_sol, mosek.onoffkey.on.value);
// solve
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Read and print solution
double xx[] = task.getxx(mosek.soltype.itg);
System.out.println("Optimal solution:");
for(int i = 0; i < numvar; i++) {
System.out.println(xx[i]);
}
// Was the initial solution used?
int constr = task.getintinf(mosek.iinfitem.mio_construct_solution);
double constrVal = task.getdouinf(mosek.dinfitem.mio_construct_solution_obj);
System.out.println("Construct solution utilization: " + constr);
System.out.println("Construct solution objective: " + constrVal);
} catch (mosek.Exception e)
/* Catch both Error and Warning */
{
System.out.println ("An error was encountered");
System.out.println (e.getMessage ());
throw e;
}
}
}
opt_server_async.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : opt_server_async.java
Purpose : Demonstrates how to use MOSEK OptServer
to solve optimization problem asynchronously
*/
package com.mosek.example;
import mosek.*;
public class opt_server_async {
public static void main (String[] args) throws java.lang.Exception {
if (args.length == 0) {
System.out.println ("Missing argument, syntax is:");
System.out.println (" opt_server_async inputfile host:port numpolls");
} else {
String inputfile = args[0];
String addr = args[1];
int numpolls = Integer.parseInt(args[2]);
String cert = args.length < 4 ? null : args[3];
try (Env env = new Env()) {
String token;
try(Task task = new Task(env, 0, 0)) {
task.readdata (inputfile);
if (cert != null)
task.putstrparam(sparam.remote_tls_cert_path,cert);
token = task.asyncoptimize (addr,"");
}
System.out.printf("Task token = %s\n", token);
try(Task task = new Task(env, 0, 0)) {
System.out.println("Reading input file...");
task.readdata (inputfile);
if (cert != null)
task.putstrparam(sparam.remote_tls_cert_path,cert);
System.out.println("Setting log stream...");
task.set_Stream (mosek.streamtype.log,
new mosek.Stream() {
public void stream(String msg) { System.out.print(msg); }
});
long start = System.currentTimeMillis();
System.out.println("Starting polling loop...");
int i = 0;
while ( true ) {
Thread.sleep(100);
System.out.printf("poll %d...\n", i);
rescode trm[] = new rescode[1];
rescode resp[] = new rescode[1];
boolean respavailable = task.asyncpoll( addr,
"",
token,
resp,
trm);
System.out.println("polling done");
if (respavailable) {
System.out.println("solution available!");
task.asyncgetresult(addr,
"",
token,
resp,
trm);
task.solutionsummary (mosek.streamtype.log);
break;
}
i++;
if (i == numpolls) {
System.out.println("max num polls reached, stopping host.");
task.asyncstop (addr, "", token);
break;
}
}
} catch (java.lang.Exception e) {
System.out.println("Something unexpected happend...");
throw e;
}
}
}
}
}
opt_server_sync.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : opt_server_sync.java
Purpose : Demonstrates how to use MOSEK OptServer
to solve optimization problem synchronously
*/
package com.mosek.example;
import mosek.*;
public class opt_server_sync {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println ("Missing argument, syntax is:");
System.out.println (" opt_server_sync inputfile addr [certpath]");
} else {
String inputfile = args[0];
String addr = args[1];
String cert = args.length < 3 ? null : args[2];
rescode trm;
try (Env env = new Env();
Task task = new Task(env, 0, 0)) {
task.set_Stream (mosek.streamtype.log,
new mosek.Stream() {
public void stream(String msg) { System.out.print(msg); }
});
// Load some data into the task
task.readdata (inputfile);
// Set OptServer URL
task.putoptserverhost(addr);
// Path to certificate, if any
if (cert != null)
task.putstrparam(sparam.remote_tls_cert_path, cert);
// Optimize remotely, no access token
trm = task.optimize ();
task.solutionsummary (mosek.streamtype.log);
}
}
}
}
parallel.java
/*
Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File: parallel.java
Purpose: Demonstrates parallel optimization using optimizebatch()
*/
package com.mosek.example;
public class parallel
{
/** Example of how to use env.optimizebatch().
Optimizes tasks whose names were read from command line.
*/
public static void main(String[] argv)
{
int n = argv.length;
mosek.Task[] tasks = new mosek.Task[n];
mosek.rescode[] res = new mosek.rescode[n];
mosek.rescode[] trm = new mosek.rescode[n];
mosek.Env env = new mosek.Env();
// Size of thread pool available for all tasks
int threadpoolsize = 6;
// Create an example list of tasks to optimize
for(int i = 0; i < n; i++)
{
tasks[i] = new mosek.Task(env);
tasks[i].readdata(argv[i]);
// We can set the number of threads for each task
tasks[i].putintparam(mosek.iparam.num_threads, 2);
}
// Optimize all the given tasks in parallel
env.optimizebatch(false, // No race
-1.0, // No time limit
threadpoolsize,
tasks, // Array of tasks to optimize
trm,
res);
for(int i = 0; i < n; i++)
System.out.printf("Task %d res %s trm %s obj_val %f time %f\n",
i,
res[i],
trm[i],
tasks[i].getdouinf(mosek.dinfitem.intpnt_primal_obj),
tasks[i].getdouinf(mosek.dinfitem.optimizer_time));
}
}
parameters.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : parameters.java
Purpose : Demonstrates a very simple example about how to get/set
parameters with MOSEK Java API
*/
package com.mosek.example;
import mosek.*;
public class parameters {
public static void main (String[] args) {
try (mosek.Task task = new Task()) {
System.out.println("Test MOSEK parameter get/set functions");
// Set log level (integer parameter)
task.putintparam(mosek.iparam.log, 1);
// Select interior-point optimizer... (integer parameter)
task.putintparam(mosek.iparam.optimizer, mosek.optimizertype.intpnt.value);
// ... without basis identification (integer parameter)
task.putintparam(mosek.iparam.intpnt_basis, mosek.basindtype.never.value);
// Set relative gap tolerance (double parameter)
task.putdouparam(mosek.dparam.intpnt_co_tol_rel_gap, 1.0e-7);
// The same using explicit string names
task.putparam ("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7");
task.putnadouparam("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", 1.0e-7 );
// Incorrect value
try {
task.putdouparam(mosek.dparam.intpnt_co_tol_rel_gap, -1.0);
}
catch (mosek.Error e) {
System.out.println("Wrong parameter value");
}
double param = task.getdouparam(mosek.dparam.intpnt_co_tol_rel_gap);
System.out.println("Current value for parameter intpnt_co_tol_rel_gap = " + param);
/* Define and solve an optimization problem here */
/* task.optimize() */
/* After optimization: */
System.out.println("Get MOSEK information items");
double tm = task.getdouinf(mosek.dinfitem.optimizer_time);
int iter = task.getintinf(mosek.iinfitem.intpnt_iter);
System.out.println("Time: " + tm);
System.out.println("Iterations: " + iter);
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
pinfeas.java
// File : pinfeas.java
//
// Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
// Purpose: Demonstrates how to fetch a primal infeasibility certificate
// for a linear problem
//
package com.mosek.example;
import mosek.*;
public class pinfeas {
static double inf = 0.0; // Infinity for symbolic purposes
// Set up a simple linear problem from the manual for test purposes
public static mosek.Task testProblem() {
mosek.Task task = new mosek.Task();
task.appendvars(7);
task.appendcons(7);
task.putclist(new int[]{0,1,2,3,4,5,6}, new double[]{1,2,5,2,1,2,1});
task.putaijlist(new int[]{0,0,1,1,2,2,2,3,3,4,5,5,6,6},
new int[]{0,1,2,3,4,5,6,0,4,1,2,5,3,6},
new double[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1});
mosek.boundkey up = mosek.boundkey.up,
fx = mosek.boundkey.fx,
lo = mosek.boundkey.lo;
task.putconboundslice(0, 7, new mosek.boundkey[]{up,up,up,fx,fx,fx,fx},
new double[]{-inf, -inf, -inf, 1100, 200, 500, 500},
new double[]{200, 1000, 1000, 1100, 200, 500, 500});
task.putvarboundsliceconst(0, 7, lo, 0, +inf);
return task;
}
// Analyzes and prints infeasibility contributing elements
// sl - dual values for lower bounds
// su - dual values for upper bounds
// eps - tolerance for when a nunzero dual value is significant
public static void analyzeCertificate(double[] sl, double[] su, double eps) {
for(int i = 0; i < sl.length; i++) {
if (Math.abs(sl[i]) > eps)
System.out.printf("#%d, lower, dual = %e\n", i, sl[i]);
if (Math.abs(su[i]) > eps)
System.out.printf("#%d, upper, dual = %e\n", i, su[i]);
}
}
public static void main (String[] args) {
// In this example we set up a simple problem
// One could use any task or a task read from a file
mosek.Task task = testProblem();
// Useful for debugging
task.writedata("pinfeas.ptf"); // Write file in human-readable format
// Attach a log stream printer to the task
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Perform the optimization.
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Check problem status, we use the interior point solution
if (task.getprosta(soltype.itr) == prosta.prim_infeas) {
// Set the tolerance at which we consider a dual value as essential
double eps = 1e-7;
System.out.println("Variable bounds important for infeasibility: ");
analyzeCertificate(task.getslx(soltype.itr), task.getsux(soltype.itr), eps);
System.out.println("Constraint bounds important for infeasibility: ");
analyzeCertificate(task.getslc(soltype.itr), task.getsuc(soltype.itr), eps);
}
else {
System.out.println("The problem is not primal infeasible, no certificate to show");
}
task.dispose();
}
}
portfolio_1_basic.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_1_basic.java
Purpose : Implements a basic portfolio optimization model.
*/
package com.mosek.example;
import mosek.solsta;
import mosek.Exception;
public class portfolio_1_basic {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' for symbolic purposes only
int n = 8;
double infinity = 0;
double gamma = 36.0;
double[] mu = {0.07197349, 0.15518171, 0.17535435, 0.0898094 , 0.42895777, 0.39291844, 0.32170722, 0.18378628};
double[][] GT = {
{0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638},
{0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506},
{0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914},
{0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742},
{0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 },
{0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187},
{0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327},
{0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 }
};
int k = GT.length;
double[] x0 = {8.0, 5.0, 3.0, 5.0, 2.0, 9.0, 3.0, 6.0};
double w = 59;
double totalBudget;
//Offset of variables into the API variable.
int numvar = n;
int voff_x = 0;
// Constraints offsets
int numcon = 1;
int coff_bud = 0;
try (mosek.Task task = new mosek.Task())
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }}
);
// Holding variable x of length n
// No other auxiliary variables are needed in this formulation
task.appendvars(numvar);
// Setting up variable x
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
/* No short-selling - x^l = 0, x^u = inf */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
}
// One linear constraint: total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
}
totalBudget = w;
for (int i = 0; i < n; ++i)
{
totalBudget += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, totalBudget, totalBudget);
// Input (gamma, GTx) in the AFE (affine expression) storage
// We need k+1 rows
task.appendafes(k + 1);
// The first affine expression = gamma
task.putafeg(0, gamma);
// The remaining k expressions comprise GT*x, we add them row by row
// In more realisic scenarios it would be better to extract nonzeros and input in sparse form
int[] vslice_x = new int[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
task.putafefrow(i + 1, vslice_x, GT[i]);
}
// Input the affine conic constraint (gamma, GT*x) \in QCone
// Add the quadratic domain of dimension k+1
long qdom = task.appendquadraticconedomain(k + 1);
// Add the constraint
task.appendaccseq(qdom, 0, null);
task.putaccname(0, "risk");
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
task.optimize();
/* Display solution summary for quick inspection of results */
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itr);
if (solsta != mosek.solsta.optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
task.writedata("dump.ptf");
/* Read the results */
double expret = 0.0;
double[] xx = task.getxxslice(mosek.soltype.itr, voff_x, voff_x + n);
for (int j = 0; j < n; ++j)
expret += mu[j] * xx[voff_x + j];
System.out.printf("\nExpected return %e for gamma %e\n", expret, gamma);
}
}
}
portfolio_2_frontier.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_2_frontier.java
Purpose : Implements a basic portfolio optimization model.
Computes points on the efficient frontier.
*/
package com.mosek.example;
import mosek.solsta;
import mosek.Exception;
import mosek.*;
public class portfolio_2_frontier {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int n = 8;
double[] mu = {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379};
double[][] GT = {
{0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638},
{0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506},
{0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914},
{0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742},
{0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 },
{0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187},
{0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327},
{0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 }
};
int k = GT.length;
double[] x0 = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
double w = 1.0;
double[] alphas = {0.0, 0.01, 0.1, 0.25, 0.30, 0.35, 0.4, 0.45, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 10.0};
int numalphas = 15;
double totalBudget;
//Offset of variables into the API variable.
int numvar = n + 1;
int voff_x = 0;
int voff_s = n;
// Offset of constraints
int coff_bud = 0;
try (Task task = new mosek.Task () )
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
task.appendvars(numvar);
// Setting up variable x
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
/* No short-selling - x^l = 0, x^u = inf */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
}
task.putvarname(voff_s, "s");
task.putvarbound(voff_s, mosek.boundkey.fr, -infinity, infinity);
// One linear constraint: total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
}
totalBudget = w;
for (int i = 0; i < n; ++i)
{
totalBudget += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, totalBudget, totalBudget);
// Input (gamma, GTx) in the AFE (affine expression) storage
// We build the following F and g for variables [x, s]:
// [0, 1] [0 ]
// F = [0, 0], g = [0.5]
// [GT,0] [0 ]
// We need k+2 rows
task.appendafes(k + 2);
// The first affine expression is variable s (last variable, index n)
task.putafefentry(0, n, 1.0);
// The second affine expression is constant 0.5
task.putafeg(1, 0.5);
// The remaining k expressions comprise GT*x, we add them row by row
// In more realisic scenarios it would be better to extract nonzeros and input in sparse form
int[] vslice_x = new int[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
task.putafefrow(i + 2, vslice_x, GT[i]);
}
// Input the affine conic constraint (gamma, GT*x) \in QCone
// Add the quadratic domain of dimension k+1
long rqdom = task.appendrquadraticconedomain(k + 2);
// Add the constraint
task.appendaccseq(rqdom, 0, null);
task.putaccname(0, "risk");
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
task.writedata("dump.ptf");
try {
//Turn all log output off.
task.putintparam(mosek.iparam.log, 0);
System.out.printf("%-12s %-12s %-12s\n", "alpha", "exp ret", "std. dev.");
for (int j = 0; j < numalphas; ++j)
{
task.putcj(voff_s, -alphas[j]);
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itr);
if (solsta != mosek.solsta.optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
double expret = 0.0, stddev = 0.0;
double[] xx = task.getxx(mosek.soltype.itr);
for (int jj = 0; jj < n; ++jj)
expret += mu[jj] * xx[jj + voff_x];
System.out.printf("%-12.3e %-12.3e %-12.3e\n", alphas[j], expret, Math.sqrt(xx[voff_s]));
}
System.out.println("");
} catch (mosek.Warning mw) {
System.out.println (" Mosek warning:");
System.out.println (mw.toString ());
}
} catch ( mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString ());
throw e;
}
}
}
portfolio_3_impact.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_3_impact.java
Purpose : Implements a basic portfolio optimization model
with transaction costs of the form x^(3/2).
*/
package com.mosek.example;
import mosek.solsta;
import mosek.Exception;
public class portfolio_3_impact {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int n = 8;
double[] mu = {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379};
double[][] GT = {
{0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638},
{0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506},
{0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914},
{0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742},
{0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 },
{0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187},
{0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327},
{0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 }
};
int k = GT.length;
double[] x0 = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
double w = 1.0;
double gamma = 0.36;
double totalBudget;
double[] m = new double[n];
for (int i = 0; i < n; ++i)
{
m[i] = 0.01;
}
// Offset of variables into the API variable.
int numvar = 3 * n;
int voff_x = 0;
int voff_c = n;
int voff_z = 2 * n;
// Offset of constraints.
int numcon = 2 * n + 1;
int coff_bud = 0;
int coff_abs1 = 1;
int coff_abs2 = 1 + n;
try (mosek.Task task = new mosek.Task() )
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Variables (vector of x, c, z)
task.appendvars(numvar);
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
task.putvarname(voff_c + j, "c[" + (j + 1) + "]");
task.putvarname(voff_z + j, "z[" + (j + 1) + "]");
/* Apply variable bounds (x >= 0, c and z free) */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
task.putvarbound(voff_c + j, mosek.boundkey.fr, -infinity, infinity);
task.putvarbound(voff_z + j, mosek.boundkey.fr, -infinity, infinity);
}
// Linear constraints
// - Total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
task.putaij(coff_bud, voff_c + j, m[j]);
}
totalBudget = w;
for (int i = 0; i < n; ++i)
{
totalBudget += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, totalBudget, totalBudget);
// - Absolute value
task.appendcons(2 * n);
for (int i = 0; i < n; ++i)
{
task.putconname(coff_abs1 + i, "zabs1[" + (1 + i) + "]");
task.putaij(coff_abs1 + i, voff_x + i, -1.0);
task.putaij(coff_abs1 + i, voff_z + i, 1.0);
task.putconbound(coff_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
task.putconname(coff_abs2 + i, "zabs2[" + (1 + i) + "]");
task.putaij(coff_abs2 + i, voff_x + i, 1.0);
task.putaij(coff_abs2 + i, voff_z + i, 1.0);
task.putconbound(coff_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
}
// ACCs
int aoff_q = 0;
int aoff_pow = k + 1;
// - (gamma, GTx) in Q(k+1)
// The part of F and g for variable x:
// [0, 0, 0] [gamma]
// F = [GT, 0, 0], g = [0 ]
task.appendafes(k + 1);
task.putafeg(aoff_q, gamma);
int[] vslice_x = new int[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
task.putafefrow(aoff_q + i + 1, vslice_x, GT[i]);
}
long qdom = task.appendquadraticconedomain(k + 1);
task.appendaccseq(qdom, aoff_q, null);
task.putaccname(aoff_q, "risk");
// - (c_j, 1, z_j) in P3(2/3, 1/3)
// The part of F and g for variables [c, z]:
// [0, I, 0] [0]
// F = [0, 0, I], g = [0]
// [0, 0, 0] [1]
task.appendafes(2 * n + 1);
for (int i = 0; i < n; ++i)
{
task.putafefentry(aoff_pow + i, voff_c + i, 1.0);
task.putafefentry(aoff_pow + n + i, voff_z + i, 1.0);
}
task.putafeg(aoff_pow + 2 * n, 1.0);
// We use one row from F and g for both c_j and z_j, and the last row of F and g for the constant 1.
// NOTE: Here we reuse the last AFE and the power cone n times, but we store them only once.
double[] exponents = {2, 1};
long powdom = task.appendprimalpowerconedomain(3, exponents);
long[] flat_afe_list = new long[3 * n];
long[] dom_list = new long[n];
for (int i = 0; i < n; ++i)
{
flat_afe_list[3 * i + 0] = aoff_pow + i;
flat_afe_list[3 * i + 1] = aoff_pow + 2 * n;
flat_afe_list[3 * i + 2] = aoff_pow + n + i;
dom_list[i] = powdom;
}
task.appendaccs(dom_list, flat_afe_list, null);
for (int i = 0; i < n; ++i)
{
task.putaccname(i + 1, "market_impact[" + i + "]");
}
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
/* Solve the problem */
try {
//Turn all log output off.
//task.putintparam(mosek.iparam.log,0);
task.writedata("dump.ptf");
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itr);
if (solsta != mosek.solsta.optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
double expret = 0.0, stddev = 0.0;
double[] xx = task.getxx(mosek.soltype.itr);
for (int j = 0; j < n; ++j)
expret += mu[j] * xx[j + voff_x];
System.out.printf("Expected return %e for gamma %e\n\n", expret, gamma);
} catch (mosek.Warning mw) {
System.out.println (" Mosek warning:");
System.out.println (mw.toString ());
}
} catch ( mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString ());
throw e;
}
}
}
portfolio_4_transcost.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_4_transcost.java
Purpose : Implements a basic portfolio optimization model
with fixed setup costs and transaction costs
as a mixed-integer problem.
*/
package com.mosek.example;
import mosek.solsta;
import mosek.Exception;
public class portfolio_4_transcost {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int n = 8;
double[] mu = {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379};
double[][] GT = {
{0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638},
{0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506},
{0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914},
{0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742},
{0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 },
{0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187},
{0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327},
{0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 }
};
int k = GT.length;
double[] x0 = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
double w = 1.0;
double gamma = 0.36;
double totalBudget;
double[] f = new double[n];
double[] g = new double[n];
for (int i = 0; i < n; ++i)
{
f[i] = 0.01;
g[i] = 0.001;
}
// Offset of variables.
int numvar = 3 * n;
int voff_x = 0;
int voff_z = n;
int voff_y = 2 * n;
// Offset of constraints.
int numcon = 3 * n + 1;
int coff_bud = 0;
int coff_abs1 = 1;
int coff_abs2 = 1 + n;
int coff_swi = 1 + 2 * n;
try (mosek.Task task = new mosek.Task() )
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Variables (vector of x, z, y)
task.appendvars(numvar);
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
task.putvarname(voff_z + j, "z[" + (j + 1) + "]");
task.putvarname(voff_y + j, "y[" + (j + 1) + "]");
/* Apply variable bounds (x >= 0, z free, y binary) */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
task.putvarbound(voff_z + j, mosek.boundkey.fr, -infinity, infinity);
task.putvarbound(voff_y + j, mosek.boundkey.ra, 0.0, 1.0);
task.putvartype(voff_y + j, mosek.variabletype.type_int);
}
// Linear constraints
// - Total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
task.putaij(coff_bud, voff_z + j, g[j]);
task.putaij(coff_bud, voff_y + j, f[j]);
}
double U = w;
for (int i = 0; i < n; ++i)
{
U += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, U, U);
// - Absolute value
task.appendcons(2 * n);
for (int i = 0; i < n; ++i)
{
task.putconname(coff_abs1 + i, "zabs1[" + (1 + i) + "]");
task.putaij(coff_abs1 + i, voff_x + i, -1.0);
task.putaij(coff_abs1 + i, voff_z + i, 1.0);
task.putconbound(coff_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
task.putconname(coff_abs2 + i, "zabs2[" + (1 + i) + "]");
task.putaij(coff_abs2 + i, voff_x + i, 1.0);
task.putaij(coff_abs2 + i, voff_z + i, 1.0);
task.putconbound(coff_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
}
// - Switch
task.appendcons(n);
for (int i = 0; i < n; ++i)
{
task.putconname(coff_swi + i, "switch[" + (1 + i) + "]");
task.putaij(coff_swi + i, voff_z + i, 1.0);
task.putaij(coff_swi + i, voff_y + i, -U);
task.putconbound(coff_swi + i, mosek.boundkey.up, -infinity, 0.0);
}
// ACCs
int aoff_q = 0;
// - (gamma, GTx) in Q(k+1)
// The part of F and g for variable x:
// [0, 0, 0] [gamma]
// F = [GT, 0, 0], g = [0 ]
task.appendafes(k + 1);
task.putafeg(aoff_q, gamma);
int[] vslice_x = new int[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
task.putafefrow(aoff_q + i + 1, vslice_x, GT[i]);
}
long qdom = task.appendquadraticconedomain(k + 1);
task.appendaccseq(qdom, aoff_q, null);
task.putaccname(aoff_q, "risk");
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
/* Solve the problem */
try {
//Turn all log output off.
//task.putintparam(mosek.iparam.log,0);
task.writedata("dump.ptf");
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itg);
if (solsta != mosek.solsta.integer_optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
double expret = 0.0, stddev = 0.0;
double[] xx = task.getxx(mosek.soltype.itg);
for (int j = 0; j < n; ++j)
expret += mu[j] * xx[j + voff_x];
System.out.printf("Expected return %e for gamma %e\n\n", expret, gamma);
} catch (mosek.Warning mw) {
System.out.println (" Mosek warning:");
System.out.println (mw.toString ());
}
} catch ( mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString ());
throw e;
}
}
}
portfolio_5_card.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_5_card.java
Description : Implements a basic portfolio optimization model
with cardinality constraints on number of assets traded.
*/
package com.mosek.example;
import mosek.solsta;
import mosek.Exception;
public class portfolio_5_card {
public static double[] markowitz_with_card(int n,
int k,
double[] x0,
double w,
double gamma,
double[] mu,
double[][] GT,
int K)
{
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
// Offset of variables.
int numvar = 3 * n;
int voff_x = 0;
int voff_z = n;
int voff_y = 2 * n;
// Offset of constraints.
int numcon = 3 * n + 2;
int coff_bud = 0;
int coff_abs1 = 1;
int coff_abs2 = 1 + n;
int coff_swi = 1 + 2 * n;
int coff_card = 1 + 3 * n;
try (mosek.Task task = new mosek.Task() )
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
// Variables (vector of x, z, y)
task.appendvars(numvar);
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
task.putvarname(voff_z + j, "z[" + (j + 1) + "]");
task.putvarname(voff_y + j, "y[" + (j + 1) + "]");
/* Apply variable bounds (x >= 0, z free, y binary) */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
task.putvarbound(voff_z + j, mosek.boundkey.fr, -infinity, infinity);
task.putvarbound(voff_y + j, mosek.boundkey.ra, 0.0, 1.0);
task.putvartype(voff_y + j, mosek.variabletype.type_int);
}
// Linear constraints
// - Total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
}
double U = w;
for (int i = 0; i < n; ++i)
{
U += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, U, U);
// - Absolute value
task.appendcons(2 * n);
for (int i = 0; i < n; ++i)
{
task.putconname(coff_abs1 + i, "zabs1[" + (1 + i) + "]");
task.putaij(coff_abs1 + i, voff_x + i, -1.0);
task.putaij(coff_abs1 + i, voff_z + i, 1.0);
task.putconbound(coff_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
task.putconname(coff_abs2 + i, "zabs2[" + (1 + i) + "]");
task.putaij(coff_abs2 + i, voff_x + i, 1.0);
task.putaij(coff_abs2 + i, voff_z + i, 1.0);
task.putconbound(coff_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
}
// - Switch
task.appendcons(n);
for (int i = 0; i < n; ++i)
{
task.putconname(coff_swi + i, "switch[" + (1 + i) + "]");
task.putaij(coff_swi + i, voff_z + i, 1.0);
task.putaij(coff_swi + i, voff_y + i, -U);
task.putconbound(coff_swi + i, mosek.boundkey.up, -infinity, 0.0);
}
// - Cardinality
task.appendcons(1);
task.putconname(coff_card, "cardinality");
for (int i = 0; i < n; ++i)
{
task.putaij(coff_card, voff_y + i, 1.0);
}
task.putconbound(coff_card, mosek.boundkey.up, -infinity, K);
// ACCs
int aoff_q = 0;
// - (gamma, GTx) in Q(k+1)
// The part of F and g for variable x:
// [0, 0, 0] [gamma]
// F = [GT, 0, 0], g = [0 ]
task.appendafes(k + 1);
task.putafeg(aoff_q, gamma);
int[] vslice_x = new int[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
task.putafefrow(aoff_q + i + 1, vslice_x, GT[i]);
}
long qdom = task.appendquadraticconedomain(k + 1);
task.appendaccseq(qdom, aoff_q, null);
task.putaccname(aoff_q, "risk");
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
task.writedata("dump.ptf");
task.optimize();
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itg);
if (solsta != mosek.solsta.integer_optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
double[] xx = task.getxxslice(mosek.soltype.itg, voff_x, voff_x + n);
return xx;
}
}
public static void main (String[] args)
{
int n = 8;
double[] mu = {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379};
double[][] GT = {
{0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638},
{0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506},
{0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914},
{0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742},
{0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 },
{0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187},
{0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327},
{0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 }
};
int k = GT.length;
double[] x0 = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
double w = 1.0;
double gamma = 0.25;
for (int K = 1; K <= n; K++)
{
double[] xx = markowitz_with_card(n, k, x0, w, gamma, mu, GT, K);
double expret = 0;
System.out.printf("Bound %d: x = ", K);
for(int i=0; i<n; i++)
{
System.out.printf("%.5f ", xx[i]);
expret += xx[i]*mu[i];
}
System.out.printf(" Return: %.5f\n", expret);
}
}
}
portfolio_6_factor.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : portfolio_6_factor.java
Purpose : Implements a portfolio optimization model using factor model.
*/
package com.mosek.example;
import mosek.LinAlg;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Arrays;
import mosek.solsta;
import mosek.Exception;
public class portfolio_6_factor
{
public static double sum(double[] x)
{
double r = 0.0;
for (int i = 0; i < x.length; ++i) r += x[i];
return r;
}
public static double dot(double[] x, double[] y)
{
double r = 0.0;
for (int i = 0; i < x.length; ++i) r += x[i] * y[i];
return r;
}
// Vectorize matrix (column-major order)
public static double[] mat_to_vec_c(double[][] m)
{
int ni = m.length;
int nj = m[0].length;
double[] c = new double[nj * ni];
for (int j = 0; j < nj; ++j)
{
for (int i = 0; i < ni; ++i)
{
c[j * ni + i] = m[i][j];
}
}
return c;
}
// Reshape vector to matrix (column-major order)
public static double[][] vec_to_mat_c(double[] c, int ni, int nj)
{
double[][] m = new double[ni][nj];
for (int j = 0; j < nj; ++j)
{
for (int i = 0; i < ni; ++i)
{
m[i][j] = c[j * ni + i];
}
}
return m;
}
public static double[][] cholesky(double[][] m)
{
int n = m.length;
double[] vecs = mat_to_vec_c(m);
LinAlg.potrf(mosek.uplo.lo, n, vecs);
double[][] s = vec_to_mat_c(vecs, n, n);
// Zero out upper triangular part (LinAlg.potrf does not use it, original matrix values remain there)
for (int i = 0; i < n; ++i)
{
for (int j = i+1; j < n; ++j)
{
s[i][j] = 0.0;
}
}
return s;
}
// Matrix multiplication
public static double[][] matrix_mul(double[][] a, double[][] b)
{
int na = a.length;
int nb = b[0].length;
int k = b.length;
double[] vecm = new double[na * nb];
Arrays.fill(vecm, 0.0);
LinAlg.gemm(mosek.transpose.no, mosek.transpose.no, na, nb, k, 1.0, mat_to_vec_c(a), mat_to_vec_c(b), 1.0, vecm);
double[][] m = vec_to_mat_c(vecm, na, nb);
return m;
}
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' for symbolic purposes only
double infinity = 0;
int n = 8;
double w = 1.0;
double[] mu = {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379};
double[] x0 = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
// Factor exposure matrix
double[][] B =
{
{0.4256, 0.1869},
{0.2413, 0.3877},
{0.2235, 0.3697},
{0.1503, 0.4612},
{1.5325, -0.2633},
{1.2741, -0.2613},
{0.6939, 0.2372},
{0.5425, 0.2116}
};
// Factor covariance matrix
double[][] S_F =
{
{0.0620, 0.0577},
{0.0577, 0.0908}
};
// Specific risk components
double[] theta = {0.0720, 0.0508, 0.0377, 0.0394, 0.0663, 0.0224, 0.0417, 0.0459};
double[][] P = cholesky(S_F);
double[][] G_factor = matrix_mul(B, P);
int k = G_factor[0].length;
double[] gammas = {0.24, 0.28, 0.32, 0.36, 0.4, 0.44, 0.48};
double totalBudget;
//Offset of variables into the API variable.
int numvar = n;
int voff_x = 0;
// Constraint offset
int coff_bud = 0;
try (mosek.Task task = new mosek.Task() )
{
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }}
);
// Holding variable x of length n
// No other auxiliary variables are needed in this formulation
task.appendvars(numvar);
// Setting up variable x
for (int j = 0; j < n; ++j)
{
/* Optionally we can give the variables names */
task.putvarname(voff_x + j, "x[" + (j + 1) + "]");
/* No short-selling - x^l = 0, x^u = inf */
task.putvarbound(voff_x + j, mosek.boundkey.lo, 0.0, infinity);
}
// One linear constraint: total budget
task.appendcons(1);
task.putconname(coff_bud, "budget");
for (int j = 0; j < n; ++j)
{
/* Coefficients in the first row of A */
task.putaij(coff_bud, voff_x + j, 1.0);
}
totalBudget = w;
for (int i = 0; i < n; ++i)
{
totalBudget += x0[i];
}
task.putconbound(coff_bud, mosek.boundkey.fx, totalBudget, totalBudget);
// Input (gamma, G_factor_T x, diag(sqrt(theta))*x) in the AFE (affine expression) storage
// We need k+n+1 rows and we fill them in in three parts
task.appendafes(k + n + 1);
// 1. The first affine expression = gamma, will be specified later
// 2. The next k expressions comprise G_factor_T*x, we add them row by row
// transposing the matrix G_factor on the fly
int[] vslice_x = new int[n];
double[] G_factor_T_row = new double[n];
for (int i = 0; i < n; ++i)
{
vslice_x[i] = voff_x + i;
}
for (int i = 0; i < k; ++i)
{
for (int j = 0; j < n; ++j) G_factor_T_row[j] = G_factor[j][i];
task.putafefrow(i + 1, vslice_x, G_factor_T_row);
}
// 3. The remaining n rows contain sqrt(theta) on the diagonal
for (int i = 0; i < n; ++i)
{
task.putafefentry(k + 1 + i, voff_x + i, Math.sqrt(theta[i]));
}
// Input the affine conic constraint (gamma, G_factor_T x, diag(sqrt(theta))*x) \in QCone
// Add the quadratic domain of dimension k+n+1
long qdom = task.appendquadraticconedomain(k + n + 1);
// Add the constraint
task.appendaccseq(qdom, 0, null);
task.putaccname(0, "risk");
// Objective: maximize expected return mu^T x
for (int j = 0; j < n; ++j)
{
task.putcj(voff_x + j, mu[j]);
}
task.putobjsense(mosek.objsense.maximize);
for (int i = 0; i < gammas.length; i++)
{
double gamma = gammas[i];
// Specify gamma in ACC
task.putafeg(0, gamma);
task.optimize();
/* Display solution summary for quick inspection of results */
task.solutionsummary(mosek.streamtype.log);
// Check if the interior point solution is an optimal point
solsta solsta = task.getsolsta(mosek.soltype.itr);
if (solsta != mosek.solsta.optimal)
{
// See https://docs.mosek.com/latest/javaapi/accessing-solution.html about handling solution statuses.
throw new Exception(6010, String.format("Unexpected solution status: %s", solsta));
}
task.writedata("dump.ptf");
/* Read the results */
double expret = 0.0;
double[] xx = task.getxxslice(mosek.soltype.itr, voff_x, voff_x + n);
for (int j = 0; j < n; ++j)
expret += mu[j] * xx[voff_x + j];
System.out.printf("\nExpected return %e for gamma %e\n", expret, gamma);
}
}
}
}
pow1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : pow1.java
Purpose: Demonstrates how to solve the problem
maximize x^0.2*y^0.8 + z^0.4 - x
st x + y + 0.5z = 2
x,y,z >= 0
*/
package com.mosek.example;
import mosek.*;
public class pow1 {
static final int numcon = 1;
static final int numvar = 5; // x,y,z and 2 auxiliary variables for conic constraints
public static void main (String[] args) throws java.lang.Exception {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
double[] val = { 1.0, 1.0, -1.0 };
int[] sub = { 3, 4, 0 };
double[] aval = { 1.0, 1.0, 0.5 };
int[] asub = { 0, 1, 2 };
int i;
// create a new environment object
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
/* Define the linear part of the problem */
task.putclist(sub, val);
task.putarow(0, asub, aval);
task.putconbound(0, mosek.boundkey.fx, 2.0, 2.0);
task.putvarboundsliceconst(0, numvar, mosek.boundkey.fr, -infinity, infinity);
/* Add conic constraints */
/* Append two power cone domains */
long pc1 = task.appendprimalpowerconedomain(3, new double[]{0.2, 0.8});
long pc2 = task.appendprimalpowerconedomain(3, new double[]{4.0, 6.0});
/* Create data structures F,g so that
F * x + g = (x(0), x(1), x(3), x(2), 1.0, x(4))
*/
task.appendafes(6);
task.putafefentrylist(new long[]{0, 1, 2, 3, 5}, /* Rows */
new int[]{0, 1, 3, 2, 4}, /* Columns */
new double[]{1.0, 1.0, 1.0, 1.0, 1.0});
task.putafeg(4, 1.0);
/* Append the two conic constraints */
task.appendacc(pc1, /* Domain */
new long[]{0, 1, 2}, /* Rows from F */
null); /* Unused */
task.appendacc(pc2, /* Domain */
new long[]{3, 4, 5}, /* Rows from F */
null); /* Unused */
task.putobjsense(mosek.objsense.maximize);
System.out.println ("optimize");
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Mosek warning:" + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
double[] xx = task.getxx(mosek.soltype.itr); // Interior solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < 3; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
qcqo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : qcqo1.java
Purpose : Demonstrate how to solve a quadratic
optimization problem using the MOSEK API.
minimize x0^2 + 0.1 x1^2 + x2^2 - x0 x2 - x1
s.t
1 <= x0 + x1 + x2 - x0^2 - x1^2 - 0.1 x2^2 + 0.2 x0 x2
x >= 0
*/
package com.mosek.example;
import mosek.*;
public class qcqo1 {
static final int numcon = 1; /* Number of constraints. */
static final int numvar = 3; /* Number of variables. */
static final int NUMANZ = 3; /* Number of numzeros in A. */
static final int NUMQNZ = 4; /* Number of nonzeros in Q. */
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
double[] c = {0.0, -1.0, 0.0};
mosek.boundkey[] bkc = {mosek.boundkey.lo};
double[] blc = {1.0};
double[] buc = {infinity};
mosek.boundkey[] bkx
= {mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double[] blx = {0.0,
0.0,
0.0
};
double[] bux = {infinity,
infinity,
infinity
};
int[][] asub = { {0}, {0}, {0} };
double[][] aval = { {1.0}, {1.0}, {1.0} };
try (mosek.Task task = new mosek.Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Give MOSEK an estimate of the size of the input data.
This is done to increase the speed of inputting data.
However, it is optional. */
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
for (int j = 0; j < numvar; ++j) {
/* Set the linear term c_j in the objective.*/
task.putcj(j, c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putvarbound(j, bkx[j], blx[j], bux[j]);
/* Input column j of A */
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
/*
* The lower triangular part of the Q
* matrix in the objective is specified.
*/
int[] qosubi = { 0, 1, 2, 2 };
int[] qosubj = { 0, 1, 0, 2 };
double[] qoval = { 2.0, 0.2, -1.0, 2.0 };
/* Input the Q for the objective. */
task.putqobj(qosubi, qosubj, qoval);
/*
* The lower triangular part of the Q^0
* matrix in the first constraint is specified.
* This corresponds to adding the term
* x0^2 - x1^2 - 0.1 x2^2 + 0.2 x0 x2
*/
int[] qsubi = {0, 1, 2, 2 };
int[] qsubj = {0, 1, 2, 0 };
double[] qval = { -2.0, -2.0, -0.2, 0.2};
/* put Q^0 in constraint with index 0. */
task.putqconk (0,
qsubi,
qsubj,
qval);
task.putobjsense(mosek.objsense.minimize);
/* Solve the problem */
try {
mosek.rescode termcode = task.optimize();
} catch (mosek.Warning e) {
System.out.println (" Mosek warning:");
System.out.println (e.toString ());
}
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
double xx[] = task.getxx(mosek.soltype.itr); // Interior solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.msg);
throw e;
}
} /* Main */
}
qo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : qo1.java
Purpose : Demonstrate how to solve a quadratic
optimization problem using the MOSEK Java API.
*/
package com.mosek.example;
import mosek.*;
public class qo1 {
static final int numcon = 1; /* Number of constraints. */
static final int numvar = 3; /* Number of variables. */
static final int NUMANZ = 3; /* Number of numzeros in A. */
static final int NUMQNZ = 4; /* Number of nonzeros in Q. */
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
double[] c = {0.0, -1.0, 0.0};
mosek.boundkey[] bkc = { mosek.boundkey.lo };
double[] blc = {1.0};
double[] buc = {infinity};
mosek.boundkey[] bkx = { mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double[] blx = {0.0,
0.0,
0.0
};
double[] bux = {infinity,
infinity,
infinity
};
int[][] asub = { {0}, {0}, {0} };
double[][] aval = { {1.0}, {1.0}, {1.0} };
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Give MOSEK an estimate of the size of the input data.
This is done to increase the speed of inputting data.
However, it is optional. */
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
for (int j = 0; j < numvar; ++j) {
/* Set the linear term c_j in the objective.*/
task.putcj(j, c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putvarbound(j, bkx[j], blx[j], bux[j]);
/* Input column j of A */
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
/*
The lower triangular part of the Q
matrix in the objective is specified.
*/
int[] qsubi = {0, 1, 2, 2 };
int[] qsubj = {0, 1, 0, 2 };
double[] qval = {2.0, 0.2, -1.0, 2.0};
/* Input the Q for the objective. */
task.putqobj(qsubi, qsubj, qval);
/* Solve the problem */
mosek.rescode r = task.optimize();
System.out.println (" Mosek warning:" + r.toString());
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.streamtype.msg);
/* Get status information about the solution */
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
/* Get the solution */
double xx[] = task.getxx(mosek.soltype.itr); // Interior solution.
switch (solsta) {
case optimal:
System.out.println("Optimal primal solution\n");
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
} /* Main */
}
reoptimization.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : reoptimization.java
Purpose : Demonstrates how to solve a linear
optimization problem using the MOSEK API
and modify and re-optimize the problem.
*/
package com.mosek.example;
import mosek.*;
public class reoptimization {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
int numcon = 3;
int numvar = 3;
double c[] = {1.5, 2.5, 3.0 };
mosek.boundkey bkc[] = { mosek.boundkey.up,
mosek.boundkey.up,
mosek.boundkey.up
};
double blc[] = { -infinity,
-infinity,
-infinity
};
double buc[] = { 100000,
50000,
60000
};
mosek.boundkey bkx[] = { mosek.boundkey.lo,
mosek.boundkey.lo,
mosek.boundkey.lo
};
double blx[] = { 0.0, 0.0, 0.0 };
double bux[] = { +infinity,
+infinity,
+infinity
};
int asub[][] = {
{0, 1, 2},
{0, 1, 2},
{0, 1, 2}
};
double aval[][] = {
{ 2.0, 3.0, 2.0 },
{ 4.0, 2.0, 3.0 },
{ 3.0, 3.0, 2.0 }
};
double[] xx = new double[numvar];
try (Task task = new Task()) {
/* Append the constraints. */
task.appendcons(numcon);
/* Append the variables. */
task.appendvars(numvar);
/* Put C. */
for (int j = 0; j < numvar; ++j)
task.putcj(j, c[j]);
/* Put constraint bounds. */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, bkc[i], blc[i], buc[i]);
/* Put variable bounds. */
for (int j = 0; j < numvar; ++j)
task.putvarbound(j, bkx[j], blx[j], bux[j]);
/* Put A. */
if ( numcon > 0 ) {
for (int j = 0; j < numvar; ++j)
task.putacol(j,
asub[j],
aval[j]);
}
/* A maximization problem */
task.putobjsense(mosek.objsense.maximize);
/* Solve the problem */
mosek.rescode termcode = task.optimize();
task.getxx(mosek.soltype.bas, // Request the basic solution.
xx);
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
/****************** Make a change to the A matrix ******************/
task.putaij(0, 0, 3.0);
termcode = task.optimize();
task.getxx(mosek.soltype.bas, // Request the basic solution.
xx);
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
/***************** Add a new variable ******************************/
/* Get index of new variable. */
int[] varidx = new int[1];
task.getnumvar(varidx);
/* Append a new variable x_3 to the problem */
task.appendvars(1);
numvar++;
/* Set bounds on new varaible */
task.putvarbound(varidx[0],
mosek.boundkey.lo,
0,
+infinity);
/* Change objective */
task.putcj(varidx[0], 1.0);
/* Put new values in the A matrix */
int[] acolsub = new int[] {0, 2};
double[] acolval = new double[] {4.0, 1.0};
task.putacol(varidx[0], /* column index */
acolsub,
acolval);
/* Change optimizer to simplex free and reoptimize */
task.putintparam(mosek.iparam.optimizer, mosek.optimizertype.free_simplex.value);
termcode = task.optimize();
xx = new double[numvar];
task.getxx(mosek.soltype.bas, // Request the basic solution.
xx);
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
/********************** Add a new constraint ***************************/
/* Get index of new constraint. */
int[] conidx = new int[1];
task.getnumcon(conidx);
/* Append a new constraint */
task.appendcons(1);
numcon++;
/* Set bounds on new constraint */
task.putconbound(conidx[0],
mosek.boundkey.up,
-infinity,
30000);
/* Put new values in the A matrix */
int[] arowsub = new int[] {0, 1, 2, 3 };
double[] arowval = new double[] {1.0, 2.0, 1.0, 1.0};
task.putarow(conidx[0], /* row index */
arowsub,
arowval);
termcode = task.optimize();
task.getxx(mosek.soltype.bas, // Request the basic solution.
xx);
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
/********************** Change constraint bounds ********************/
mosek.boundkey[] newbkc = {mosek.boundkey.up,
mosek.boundkey.up,
mosek.boundkey.up,
mosek.boundkey.up
};
double[] newblc = { -infinity,
-infinity,
-infinity,
-infinity
};
double[] newbuc = { 80000, 40000, 50000, 22000 };
task.putconboundslice(0, numcon, newbkc, newblc, newbuc);
task.optimize();
task.getxx(mosek.soltype.bas, // Request the basic solution.
xx);
for (int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
} catch (mosek.Exception e)
/* Catch both Error and Warning */
{
System.out.println ("An error was encountered");
System.out.println (e.getMessage ());
throw e;
}
}
}
response.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : response.java
Purpose : This example demonstrates proper response handling
for problems solved with the interior-point optimizers.
*/
package com.mosek.example;
import mosek.*;
public class response {
public static void main(String[] argv) {
StringBuffer symname = new StringBuffer();
StringBuffer desc = new StringBuffer();
String filename;
if (argv.length >=1) filename = argv[0];
else filename = "../data/cqo1.mps";
// Create the task and environment
try (Task task = new Task()) {
// (Optionally) attach the log handler to receive log information
// (Optionally) uncomment this line to experience solution status Unknown
// task.putintparam(iparam.intpnt_max_iterations, 1);
// On this example we read an optimization problem from a file
task.readdata(filename);
// Perform optimization.
rescode trm = task.optimize();
task.solutionsummary(streamtype.log);
// Handle solution status. We expect Optimal
solsta solsta = task.getsolsta(soltype.itr);
switch ( solsta ) {
case optimal:
// Fetch and print the solution
System.out.println("An optimal interior point solution is located.");
int numvar = task.getnumvar();
double[] xx = task.getxx(soltype.itr);
for(int i = 0; i < numvar; i++)
System.out.println("x[" + i + "] = " + xx[i]);
break;
case dual_infeas_cer:
System.out.println("Dual infeasibility certificate found.");
break;
case prim_infeas_cer:
System.out.println("Primal infeasibility certificate found.");
break;
case unknown:
// The solutions status is unknown. The termination code
// indicates why the optimizer terminated prematurely.
System.out.println("The solution status is unknown.");
Env.getcodedesc(trm, symname, desc);
System.out.printf(" Termination code: %s %s\n", symname, desc);
break;
default:
System.out.println("Unexpected solution status " + solsta + "\n");
break;
}
}
catch (mosek.Error e) {
System.out.println("Unexpected error (" + e.code + ") " + e.msg);
}
}
}
sdo1.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : sdo1.java
Purpose : Solves the following small semidefinite optimization problem
using the MOSEK API.
minimize Tr [2, 1, 0; 1, 2, 1; 0, 1, 2]*X + x0
subject to Tr [1, 0, 0; 0, 1, 0; 0, 0, 1]*X + x0 = 1
Tr [1, 1, 1; 1, 1, 1; 1, 1, 1]*X + x1 + x2 = 0.5
(x0,x1,x2) \in Q, X \in PSD
*/
package com.mosek.example;
import mosek.*;
public class sdo1 {
public static void main(String[] argv) {
int numcon = 2; /* Number of constraints. */
int numvar = 3; /* Number of scalar variables */
int dimbarvar[] = {3}; /* Dimension of semidefinite cone */
int lenbarvar[] = {3 * (3 + 1) / 2}; /* Number of scalar SD variables */
mosek.boundkey bkc[] = { mosek.boundkey.fx,
mosek.boundkey.fx
};
double[] blc = { 1.0, 0.5 };
double[] buc = { 1.0, 0.5 };
int[] barc_i = {0, 1, 1, 2, 2},
barc_j = {0, 0, 1, 1, 2};
double[] barc_v = {2.0, 1.0, 2.0, 1.0, 2.0};
int[][] asub = {{0}, {1, 2}}; /* column subscripts of A */
double[][] aval = {{1.0}, {1.0, 1.0}};
int[][] bara_i = { {0, 1, 2}, {0, 1 , 2, 1, 2, 2 } },
bara_j = { {0, 1, 2}, {0, 0 , 0, 1, 1, 2 } };
double[][] bara_v = { {1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0}};
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Append 'NUMCON' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'NUMVAR' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
/* Append 'NUMBARVAR' semidefinite variables. */
task.appendbarvars(dimbarvar);
/* Optionally add a constant term to the objective. */
task.putcfix(0.0);
/* Set the linear term c_j in the objective.*/
task.putcj(0, 1.0);
for (int j = 0; j < numvar; ++j)
task.putvarbound(j, mosek.boundkey.fr, -0.0, 0.0);
/* Set the linear term barc_j in the objective.*/
{
long[] idx = new long[1];
double[] falpha = { 1.0 };
idx[0] = task.appendsparsesymmat(dimbarvar[0],
barc_i,
barc_j,
barc_v);
task.putbarcj(0, idx, falpha);
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for (int i = 0; i < numcon; ++i)
task.putconbound(i, /* Index of constraint.*/
bkc[i], /* Bound key.*/
blc[i], /* Numerical value of lower bound.*/
buc[i]); /* Numerical value of upper bound.*/
/* Input A row by row */
for (int i = 0; i < numcon; ++i)
task.putarow(i,
asub[i],
aval[i]);
/* Append the conic quadratic constraint */
task.appendafes(3);
// Diagonal F matrix
task.putafefentrylist(new long[]{0,1,2}, new int[]{0,1,2}, new double[]{1.0,1.0,1.0});
task.appendaccseq(task.appendquadraticconedomain(3), 0, null);
/* Add the first row of barA */
{
long[] idx = new long[1];
double[] falpha = {1.0};
task.appendsparsesymmat(dimbarvar[0],
bara_i[0],
bara_j[0],
bara_v[0],
idx);
task.putbaraij(0, 0, idx, falpha);
}
{
long[] idx = new long[1];
double[] falpha = {1.0};
/* Add the second row of barA */
task.appendsparsesymmat(dimbarvar[0],
bara_i[1],
bara_j[1],
bara_v[1],
idx);
task.putbaraij(1, 0, idx, falpha);
}
/* Run optimizer */
task.optimize();
/* Print a summary containing information
about the solution for debugging purposes*/
task.solutionsummary (mosek.streamtype.msg);
mosek.solsta solsta = task.getsolsta (mosek.soltype.itr);
switch (solsta) {
case optimal:
double[] xx = task.getxx(mosek.soltype.itr);
double[] barx = task.getbarxj(mosek.soltype.itr, 0); /* Request the interior solution. */
System.out.println("Optimal primal solution");
for (int i = 0; i < numvar; ++i)
System.out.println("x[" + i + "] : " + xx[i]);
for (int i = 0; i < lenbarvar[0]; ++i)
System.out.println("barx[" + i + "]: " + barx[i]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility certificate found.");
break;
case unknown:
System.out.println("The status of the solution could not be determined.");
break;
default:
System.out.println("Other solution status.");
break;
}
}
}
}
sdo2.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : sdo2.java
Purpose : Solves the semidefinite problem with two symmetric variables:
min <C1,X1> + <C2,X2>
st. <A1,X1> + <A2,X2> = b
(X2)_{1,2} <= k
where X1, X2 are symmetric positive semidefinite,
C1, C2, A1, A2 are assumed to be constant symmetric matrices,
and b, k are constants.
*/
package com.mosek.example;
import mosek.*;
public class sdo2 {
public static void main(String[] argv) {
/* Input data */
int numcon = 2; /* Number of constraints. */
int numbarvar = 2;
int[] dimbarvar = {3, 4}; /* Dimension of semidefinite variables */
/* Objective coefficients concatenated */
int[] Cj = { 0, 0, 1, 1, 1, 1 }; /* Which symmetric variable (j) */
int[] Ck = { 0, 2, 0, 1, 1, 2 }; /* Which entry (k,l)->v */
int[] Cl = { 0, 2, 0, 0, 1, 2 };
double[] Cv = { 1.0, 6.0, 1.0, -3.0, 2.0, 1.0 };
/* Equality constraints coefficients concatenated */
int[] Ai = { 0, 0, 0, 0, 0, 0 }; /* Which constraint (i = 0) */
int[] Aj = { 0, 0, 0, 1, 1, 1 }; /* Which symmetric variable (j) */
int[] Ak = { 0, 2, 2, 1, 1, 3 }; /* Which entry (k,l)->v */
int[] Al = { 0, 0, 2, 0, 1, 3 };
double[] Av = { 1.0, 1.0, 2.0, 1.0, -1.0, -3.0 };
/* The second constraint - one-term inequality */
int[] A2i = { 1 }; /* Which constraint (i = 1) */
int[] A2j = { 1 }; /* Which symmetric variable (j = 1) */
int[] A2k = { 1 }; /* Which entry A(1,0) = A(0,1) = 0.5 */
int[] A2l = { 0 };
double[] A2v = { 0.5 };
mosek.boundkey[] bkc = { mosek.boundkey.fx,
mosek.boundkey.up
};
double[] blc = { 23.0, 0.0 };
double[] buc = { 23.0, -3.0 };
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Append numcon empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append numbarvar semidefinite variables. */
task.appendbarvars(dimbarvar);
/* Set objective (6 nonzeros).*/
task.putbarcblocktriplet(Cj, Ck, Cl, Cv);
/* Set the equality constraint (6 nonzeros).*/
task.putbarablocktriplet(Ai, Aj, Ak, Al, Av);
/* Set the inequality constraint (1 nonzero).*/
task.putbarablocktriplet(A2i, A2j, A2k, A2l, A2v);
/* Set constraint bounds */
task.putconboundslice(0, 2, bkc, blc, buc);
/* Run optimizer */
task.optimize();
task.solutionsummary(mosek.streamtype.msg);
mosek.solsta solsta = task.getsolsta(mosek.soltype.itr);
switch (solsta) {
case optimal:
/* Retrieve the soution for all symmetric variables */
System.out.println("Solution (lower triangular part vectorized):");
for(int i = 0; i < numbarvar; i++) {
int dim = dimbarvar[i] * (dimbarvar[i] + 1) / 2;
double[] barx = task.getbarxj(mosek.soltype.itr, i);
System.out.print("X" + (i+1) + ": ");
for (int j = 0; j < dim; ++j)
System.out.print(barx[j] + " ");
System.out.println();
}
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility certificate found.");
break;
case unknown:
System.out.println("The status of the solution could not be determined.");
break;
default:
System.out.println("Other solution status.");
break;
}
}
}
}
sdo_lmi.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : sdo_lmi.java
Purpose : To solve a problem with an LMI and an affine conic constrained problem with a PSD term
minimize Tr [1, 0; 0, 1]*X + x(1) + x(2) + 1
subject to Tr [0, 1; 1, 0]*X - x(1) - x(2) >= 0
x(1) [0, 1; 1, 3] + x(2) [3, 1; 1, 0] - [1, 0; 0, 1] >> 0
X >> 0
*/
package com.mosek.example;
import mosek.*;
public class sdo_lmi {
public static void main(String[] argv) {
int numafe = 4; /* Number of affine expressions. */
int numvar = 2; /* Number of scalar variables */
int dimbarvar[] = {2}; /* Dimension of semidefinite cone */
int lenbarvar[] = {2 * (2 + 1) / 2}; /* Number of scalar SD variables */
int[] barc_j = {0, 0},
barc_k = {0, 1},
barc_l = {0, 1};
double[] barc_v = {1.0, 1.0};
long[] afeidx = {0, 0, 1, 2, 2, 3};
int[] varidx = {0, 1, 1, 0, 1, 0};
double[] f_val = {-1, -1, 3, Math.sqrt(2), Math.sqrt(2), 3},
g = {0, -1, 0, -1};
long[] barf_i = {0, 0};
int[] barf_j = {0, 0},
barf_k = {0, 1},
barf_l = {0, 0};
double[] barf_v = {0.0, 1.0};
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Append 'NUMAFE' empty affine expressions. */
task.appendafes(numafe);
/* Append 'NUMVAR' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
/* Append 'NUMBARVAR' semidefinite variables. */
task.appendbarvars(dimbarvar);
/* Optionally add a constant term to the objective. */
task.putcfix(1.0);
/* Set the linear term c_j in the objective.*/
task.putcj(0, 1.0);
task.putcj(1, 1.0);
for (int j = 0; j < numvar; ++j)
task.putvarbound(j, mosek.boundkey.fr, -0.0, 0.0);
/* Set the linear term barc_j in the objective.*/
task.putbarcblocktriplet(barc_j, barc_k, barc_l, barc_v);
/* Set up the affine conic constraints */
/* Construct the affine expressions */
/* F matrix */
task.putafefentrylist(afeidx, varidx, f_val);
/* g vector */
task.putafegslice(0, 4, g);
/* barF block triplets */
task.putafebarfblocktriplet(barf_i, barf_j, barf_k, barf_l, barf_v);
/* Append R+ domain and the corresponding ACC */
task.appendacc(task.appendrplusdomain(1), new long[]{0}, null);
/* Append SVEC_PSD domain and the corresponding ACC */
task.appendacc(task.appendsvecpsdconedomain(3), new long[]{1,2,3}, null);
/* Run optimizer */
task.optimize();
/* Print a summary containing information
about the solution for debugging purposes*/
task.solutionsummary (mosek.streamtype.msg);
mosek.solsta solsta = task.getsolsta (mosek.soltype.itr);
switch (solsta) {
case optimal:
double[] xx = task.getxx(mosek.soltype.itr);
double[] barx = task.getbarxj(mosek.soltype.itr, 0); /* Request the interior solution. */
System.out.println("Optimal primal solution");
for (int i = 0; i < numvar; ++i)
System.out.println("x[" + i + "] : " + xx[i]);
for (int i = 0; i < lenbarvar[0]; ++i)
System.out.println("barx[" + i + "]: " + barx[i]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println("Primal or dual infeasibility certificate found.");
break;
case unknown:
System.out.println("The status of the solution could not be determined.");
break;
default:
System.out.println("Other solution status.");
break;
}
}
}
}
sensitivity.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : sensitivity.java
Purpose : To demonstrate how to perform sensitivity
analysis from the API on a small problem:
minimize
obj: +1 x11 + 2 x12 + 5 x23 + 2 x24 + 1 x31 + 2 x33 + 1 x34
st
c1: + x11 + x12 <= 400
c2: + x23 + x24 <= 1200
c3: + x31 + x33 + x34 <= 1000
c4: + x11 + x31 = 800
c5: + x12 = 100
c6: + x23 + x33 = 500
c7: + x24 + x34 = 500
The example uses basis type sensitivity analysis.
*/
package com.mosek.example;
import mosek.*;
public class sensitivity {
public static void main (String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double
infinity = 0;
try (Task task = new Task()) {
mosek.boundkey[] bkc = {
mosek.boundkey.up, mosek.boundkey.up,
mosek.boundkey.up, mosek.boundkey.fx,
mosek.boundkey.fx, mosek.boundkey.fx,
mosek.boundkey.fx
};
mosek.boundkey[] bkx = {
mosek.boundkey.lo, mosek.boundkey.lo,
mosek.boundkey.lo, mosek.boundkey.lo,
mosek.boundkey.lo, mosek.boundkey.lo,
mosek.boundkey.lo
};
int[] ptrb = {0, 2, 4, 6, 8, 10, 12};
int[] ptre = {2, 4, 6, 8, 10, 12, 14};
int[] sub = {0, 3, 0, 4, 1, 5, 1, 6, 2, 3, 2, 5, 2, 6};
double[] blc = { -infinity, -infinity,
-infinity, 800, 100, 500, 500
};
double[] buc = {400, 1200, 1000, 800, 100, 500, 500};
double[] c = {1.0, 2.0, 5.0, 2.0, 1.0, 2.0, 1.0};
double[] blx = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
double[] bux = {infinity, infinity,
infinity, infinity,
infinity, infinity,
infinity
};
double[] val = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
};
int numcon = 7; /* Number of constraints. */
int numvar = 7; /* Number of variables. */
int NUMANZ = 14; /* Number of non-zeros in A. */
// Directs the log task stream to the user specified
// method task_msg_obj.print
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
task.inputdata(numcon, numvar,
c,
0.0,
ptrb,
ptre,
sub,
val,
bkc,
blc,
buc,
bkx,
blx,
bux);
/* A maximization problem */
task.putobjsense(mosek.objsense.minimize);
task.optimize();
/* Analyze upper bound on c1 and the equality constraint on c4 */
int subi[] = {0, 3};
mosek.mark marki[] = {mosek.mark.up, mosek.mark.up};
/* Analyze lower bound on the variables x12 and x31 */
int subj[] = {1, 4};
mosek.mark markj[] = {mosek.mark.lo, mosek.mark.lo};
double[] leftpricei = new double[2];
double[] rightpricei = new double[2];
double[] leftrangei = new double[2];
double[] rightrangei = new double[2];
double[] leftpricej = new double[2];
double[] rightpricej = new double[2];
double[] leftrangej = new double[2];
double[] rightrangej = new double[2];
task.primalsensitivity( subi,
marki,
subj,
markj,
leftpricei,
rightpricei,
leftrangei,
rightrangei,
leftpricej,
rightpricej,
leftrangej,
rightrangej);
System.out.println("Results from sensitivity analysis on bounds:\n");
System.out.println("For constraints:\n");
for (int i = 0; i < 2; ++i)
System.out.print("leftprice = " + leftpricei[i] +
" rightprice = " + rightpricei[i] +
" leftrange = " + leftrangei[i] +
" rightrange = " + rightrangei[i] + "\n");
System.out.print("For variables:\n");
for (int i = 0; i < 2; ++i)
System.out.print("leftprice = " + leftpricej[i] +
" rightprice = " + rightpricej[i] +
" leftrange = " + leftrangej[i] +
" rightrange = " + rightrangej[i] + "\n");
double[] leftprice = new double[2];
double[] rightprice = new double[2];
double[] leftrange = new double[2];
double[] rightrange = new double[2];
int subc[] = {2, 5};
task.dualsensitivity( subc,
leftprice,
rightprice,
leftrange,
rightrange
);
System.out.println(
"Results from sensitivity analysis on objective coefficients:"
);
for (int i = 0; i < 2; ++i)
System.out.print("leftprice = " + leftprice[i] +
" rightprice = " + rightprice[i] +
" leftrange = " + leftrange[i] +
" rightrange = " + rightrange[i] + "\n");
} catch (mosek.Exception e)
/* Catch both mosek.Error and mosek.Warning */
{
System.out.println ("An error or warning was encountered");
System.out.println (e.getMessage ());
throw e;
}
}
}
simple.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : simple.java
Purpose : Demonstrates a very simple example using MOSEK by
reading a problem file, solving the problem and
writing the solution to a file.
*/
package com.mosek.example;
import mosek.*;
public class simple {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println ("Missing argument, syntax is:");
System.out.println (" simple inputfile [ solutionfile ]");
} else {
try (Task task = new Task()) {
task.set_Stream (mosek.streamtype.log,
new mosek.Stream() {
public void stream(String msg) { System.out.print(msg); }
});
// We assume that a problem file was given as the first command
// line argument (received in `args')
task.readdata (args[0]);
// Solve the problem
task.optimize ();
// Print a summary of the solution
task.solutionsummary (mosek.streamtype.log);
// If an output file was specified, save problem to file
if (args.length >= 2) {
// If using OPF format, these parameters will specify what to include in output
task.putintparam (mosek.iparam.opf_write_solutions, mosek.onoffkey.on.value);
task.putintparam (mosek.iparam.opf_write_problem, mosek.onoffkey.on.value);
task.putintparam (mosek.iparam.opf_write_hints, mosek.onoffkey.off.value);
task.putintparam (mosek.iparam.opf_write_parameters, mosek.onoffkey.off.value);
task.writedata (args[1]);
}
}
}
}
}
solutionquality.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : solutionquality.java
Purpose : To demonstrate how to examine the quality of a solution.
*/
package com.mosek.example;
import mosek.*;
public class solutionquality {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println ("Missing argument, syntax is:");
System.out.println (" solutionquality inputfile");
} else {
try (Task task = new Task()) {
task.set_Stream (mosek.streamtype.log,
new mosek.Stream() {
public void stream(String msg) { System.out.print(msg); }
});
// We assume that a problem file was given as the first command
// line argument (received in `args')
task.readdata (args[0]);
// Solve the problem
task.optimize ();
// System.Out.Println (a summary of the solution
task.solutionsummary (mosek.streamtype.log);
mosek.solsta solsta = task.getsolsta(mosek.soltype.bas);
double pobj[] = new double[1];
double pviolcon[] = new double[1];
double pviolvar[] = new double[1];
double pviolbarvar[] = new double[1];
double pviolcones[] = new double[1];
double pviolitg[] = new double[1];
double dobj[] = new double[1];
double dviolcon[] = new double[1];
double dviolvar[] = new double[1];
double dviolbarvar[] = new double[1];
double dviolcones[] = new double[1];
task.getsolutioninfo(mosek.soltype.bas,
pobj, pviolcon, pviolvar, pviolbarvar, pviolcones, pviolitg,
dobj, dviolcon, dviolvar, dviolbarvar, dviolcones);
switch (solsta) {
case optimal:
double abs_obj_gap = Math.abs(dobj[0] - pobj[0]);
double rel_obj_gap = abs_obj_gap / (1.0 + Math.min(Math.abs(pobj[0]), Math.abs(dobj[0])));
double max_primal_viol = Math.max(pviolcon[0], pviolvar[0]);
max_primal_viol = Math.max(max_primal_viol , pviolbarvar[0]);
max_primal_viol = Math.max(max_primal_viol , pviolcones[0]);
double max_dual_viol = Math.max(dviolcon[0], dviolvar[0]);
max_dual_viol = Math.max(max_dual_viol , dviolbarvar[0]);
max_dual_viol = Math.max(max_dual_viol , dviolcones[0]);
// Assume the application needs the solution to be within
// 1e-6 ofoptimality in an absolute sense. Another approach
// would be looking at the relative objective gap
System.out.println ("Customized solution information.\n");
System.out.println (" Absolute objective gap: " + abs_obj_gap);
System.out.println (" Relative objective gap: " + rel_obj_gap);
System.out.println (" Max primal violation : " + max_primal_viol);
System.out.println (" Max dual violation : " + max_dual_viol);
boolean accepted = true;
if ( rel_obj_gap > 1e-6 ) {
System.out.println ("Warning: The relative objective gap is LARGE.");
accepted = false;
}
// We will accept a primal infeasibility of 1e-8 and
// dual infeasibility of 1e-6. These number should chosen problem
// dependent.
if ( max_primal_viol > 1e-8 ) {
System.out.println ("Warning: Primal violation is too LARGE");
accepted = false;
}
if (max_dual_viol > 1e-6 ) {
System.out.println ("Warning: Dual violation is too LARGE.");
accepted = false;
}
if ( accepted ) {
int numvar = task.getnumvar();
System.out.println ("Optimal primal solution");
double xj[] = new double[1];
for (int j = 0; j < numvar; j++) {
task.getxxslice(mosek.soltype.bas, j, j + 1, xj);
System.out.println ("x[" + j + "]: " + xj[0]);
}
} else {
// print etailed information about the solution
task.analyzesolution(mosek.streamtype.log, mosek.soltype.bas);
}
break;
case dual_infeas_cer:
case prim_infeas_cer:
System.out.println ("Primal or dual infeasibility certificate found.");
break;
case unknown:
System.out.println ("The status of the solution is unknown.");
break;
default:
System.out.println ("Other solution status");
}
} catch (mosek.Exception e) {
System.out.println ("An error/warning was encountered");
System.out.println (e.toString());
throw e;
}
}
}
}
solvebasis.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : solvebasis.java
Purpose : To demonstrate the usage of
MSK_solvewithbasis on the problem:
maximize x0 + x1
st.
x0 + 2.0 x1 <= 2
x0 + x1 <= 6
x0 >= 0, x1>= 0
The problem has the slack variables
xc0, xc1 on the constraints
and the variabels x0 and x1.
maximize x0 + x1
st.
x0 + 2.0 x1 -xc1 = 2
x0 + x1 -xc2 = 6
x0 >= 0, x1>= 0,
xc1 <= 0 , xc2 <= 0
*/
package com.mosek.example;
import mosek.*;
public class solvebasis {
public static void main(String[] args) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double
infinity = 0;
double[] c = {1.0, 1.0};
int[] ptrb = {0, 2};
int[] ptre = {2 , 4};
int[] asub = {0, 1,
0, 1
};
double[] aval = {1.0, 1.0,
2.0, 1.0
};
mosek.boundkey[] bkc = {
mosek.boundkey.up,
mosek.boundkey.up
};
double[] blc = { -infinity,
-infinity
};
double[] buc = {2.0,
6.0
};
mosek.boundkey[] bkx = {
mosek.boundkey.lo,
mosek.boundkey.lo
};
double[] blx = {0.0,
0.0
};
double[] bux = { +infinity,
+infinity
};
int numvar = 2;
int numcon = 2;
double[] w1 = {2.0, 6.0};
double[] w2 = {1.0, 0.0};
try (Task task = new Task()) {
task.inputdata(numcon, numvar,
c,
0.0,
ptrb,
ptre,
asub,
aval,
bkc,
blc,
buc,
bkx,
blx,
bux);
task.putobjsense(mosek.objsense.maximize);
System.out.println("optimize");
try {
task.optimize();
} catch (mosek.Warning e) {
System.out.println("Mosek warning:");
System.out.println(e.toString());
}
int[] basis = new int[numcon];
task.initbasissolve(basis);
//List basis variables corresponding to columns of B
int[] varsub = {0, 1};
for (int i = 0; i < numcon; i++) {
System.out.println("Basis i:" + i + " Basis:" + basis[i]);
if (basis[varsub[i]] < numcon) {
System.out.println("Basis variable no " + i + " is xc" +
basis[i]);
} else {
int index = basis[i] - numcon;
System.out.println("Basis variable no " + i + " is x" +
index);
}
}
// solve Bx = w1
// varsub contains index of non-zeros in b.
// On return b contains the solution x and
// varsub the index of the non-zeros in x.
int nz = 2;
nz = task.solvewithbasis(false, nz, varsub, w1);
System.out.println("nz =" + nz);
System.out.println("\nSolution to Bx = w1:\n");
for (int i = 0; i < nz; i++) {
if (basis[varsub[i]] < numcon) {
System.out.println("xc" + basis[varsub[i]] + "=" + w1[varsub[i]]);
} else {
int index = basis[varsub[i]] - numcon;
System.out.println("x" + index + " = " + w1[varsub[i]]);
}
}
// Solve B^Tx = w2
nz = 2;
varsub[0] = 0;
varsub[1] = 1;
nz = task.solvewithbasis(true, nz, varsub, w2);
System.out.println("\nSolution to B^Tx = w2:\n");
for (int i = 0; i < nz; i++) {
if (basis[varsub[i]] < numcon) {
System.out.println("xc" + basis[varsub[i]] + " = " + w2[varsub[i]]);
} else {
int index = basis[varsub[i]] - numcon;
System.out.println("x" + index + " = " + w2[varsub[i]]);
}
}
} catch (mosek.Exception e)
/* Catch both Error and Warning */
{
System.out.println("An error was encountered");
System.out.println(e.getMessage());
throw e;
}
}
}
solvelinear.java
/*
Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File : solvelinear.java
Purpose : To demonstrate the usage of MSK_solvewithbasis
when solving the linear system:
1.0 x1 = b1
-1.0 x0 + 1.0 x1 = b2
with two different right hand sides
b = (1.0, -2.0)
and
b = (7.0, 0.0)
*/
package com.mosek.example;
import mosek.*;
public class solvelinear {
static public void setup(
mosek.Task task,
double[][] aval,
int[][] asub,
int[] ptrb,
int[] ptre,
int numvar,
int[] basis ) {
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double
infinity = 0;
mosek.stakey[] skx = new mosek.stakey [numvar];
mosek.stakey[] skc = new mosek.stakey [numvar];
for (int i = 0; i < numvar ; ++i) {
skx[i] = mosek.stakey.bas;
skc[i] = mosek.stakey.fix;
}
task.appendvars(numvar);
task.appendcons(numvar);
for (int i = 0; i < numvar ; ++i)
task.putacol(i,
asub[i],
aval[i]);
for (int i = 0 ; i < numvar ; ++i)
task.putconbound(
i,
mosek.boundkey.fx,
0.0,
0.0);
for (int i = 0 ; i < numvar ; ++i)
task.putvarbound(
i,
mosek.boundkey.fr,
-infinity,
infinity);
/* Define a basic solution by specifying
status keys for variables & constraints. */
task.deletesolution(mosek.soltype.bas);
task.putskcslice(mosek.soltype.bas, 0, numvar, skc);
task.putskxslice(mosek.soltype.bas, 0, numvar, skx);
task.initbasissolve(basis);
}
public static void main (String[] argv) {
int numcon = 2;
int numvar = 2;
double[][] aval = {
{ -1.0 },
{ 1.0, 1.0 }
};
int[][] asub = {
{ 1 },
{ 0, 1 }
};
int [] ptrb = new int[] {0, 1};
int [] ptre = new int[] {1, 3};
int[] bsub = new int[numvar];
double[] b = new double[numvar];
int[] basis = new int[numvar];
try (Task task = new Task()) {
// Directs the log task stream to the user specified
// method task_msg_obj.streamCB
task.set_Stream(
mosek.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Put A matrix and factor A.
Call this function only once for a given task. */
setup(
task,
aval,
asub,
ptrb,
ptre,
numvar,
basis
);
/* now solve rhs */
b[0] = 1;
b[1] = -2;
bsub[0] = 0;
bsub[1] = 1;
int nz;
nz = task.solvewithbasis(false, 2, bsub, b);
System.out.println("\nSolution to Bx = b:\n");
/* Print solution and show correspondents
to original variables in the problem */
for (int i = 0; i < nz; ++i) {
if (basis[bsub[i]] < numcon)
System.out.println ("This should never happen");
else
System.out.println("x" + (basis[bsub[i]] - numcon) + " = " + b[bsub[i]]);
}
b[0] = 7;
bsub[0] = 0;
nz = task.solvewithbasis(false, 1, bsub, b);
System.out.println ("\nSolution to Bx = b:\n");
/* Print solution and show correspondents
to original variables in the problem */
for (int i = 0; i < nz; ++i) {
if (basis[bsub[i]] < numcon)
System.out.println("This should never happen");
else
System.out.println("x" + (basis[bsub[i]] - numcon) + " = " + b[bsub[i]] );
}
}
}
}