17 List of examples

List of examples shipped in the distribution of Optimizer API for Java:

Table 17.1 List of distributed examples
File Description
blas_lapack.java Demonstrates the MOSEK interface to BLAS/LAPACK linear algebra routines
callback.java An example of data/progress callback
ceo1.java A simple conic exponential problem
concurrent1.java Implementation of a concurrent optimizer for linear and mixed-integer problems
cqo1.java A simple conic quadratic problem
feasrepairex1.java A simple example of how to repair an infeasible problem
gp1.java A simple geometric program (GP) in conic form
lo1.java A simple linear problem
lo2.java A simple linear problem
logistic.java Implements logistic regression and simple log-sum-exp (CEO)
mico1.java A simple mixed-integer conic problem
milo1.java A simple mixed-integer linear problem
mioinitsol.java A simple mixed-integer linear problem with an initial guess
modelLib.java Library of implementations of basic functions
opt_server_async.java Uses MOSEK OptServer to solve an optimization problem asynchronously
opt_server_sync.java Uses MOSEK OptServer to solve an optimization problem synchronously
parallel.java Demonstrates parallel optimization
parameters.java Shows how to set optimizer parameters and read information items
portfolio_1_basic.java Portfolio optimization - basic Markowitz model
portfolio_2_frontier.java Portfolio optimization - efficient frontier
portfolio_3_impact.java Portfolio optimization - market impact costs
portfolio_4_transcost.java Portfolio optimization - transaction costs
portfolio_5_card.java Portfolio optimization - cardinality constraints
pow1.java A simple power cone problem
qcqo1.java A simple quadratically constrained quadratic problem
qo1.java A simple quadratic problem
reoptimization.java Demonstrate how to modify and re-optimize a linear problem
response.java Demonstrates proper response handling
sdo1.java A simple semidefinite problem with one matrix variable and a quadratic cone
sdo2.java A simple semidefinite problem with two matrix variables
sensitivity.java Sensitivity analysis performed on a small linear problem
simple.java A simple I/O example: read problem from a file, solve and write solutions
solutionquality.java Demonstrates how to examine the quality of a solution
solvebasis.java Demonstrates solving a linear system with the basis matrix
solvelinear.java Demonstrates solving a general linear system

Additional examples can be found on the MOSEK website and in other MOSEK publications.

blas_lapack.java

Listing 17.1 blas_lapack.java Click here to download.
/*
   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

Listing 17.2 callback.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {

      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

Listing 17.3 ceo1.java Click here to download.
/*
   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];
    double[] xx  = new double[numvar];

    // create a new environment object
    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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 */
      csub[0] = 0;
      csub[1] = 1;
      csub[2] = 2;
      task.appendcone(mosek.conetype.pexp,
                      0.0, /* For future use only, can be set to 0.0 */
                      csub);

      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);

      mosek.solsta solsta[] = new mosek.solsta[1];

      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itr, solsta);

      task.getxx(mosek.soltype.itr, // Interior solution.
                 xx);

      switch (solsta[0]) {
        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

Listing 17.4 concurrent1.java Click here to download.
/*
   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

Listing 17.5 cqo1.java Click here to download.
/*
   Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File :      cqo1.java

   Purpose :   Demonstrates how to solve a small conic qaudratic
               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];
    double[] xx  = new double[numvar];
    // create a new environment object
    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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]);

      csub[0] = 3;
      csub[1] = 0;
      csub[2] = 1;
      task.appendcone(mosek.conetype.quad,
                      0.0, /* For future use only, can be set to 0.0 */
                      csub);

      csub[0] = 4;
      csub[1] = 5;
      csub[2] = 2;
      task.appendcone(mosek.conetype.rquad, 0.0, csub);

      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);

      mosek.solsta solsta[] = new mosek.solsta[1];

      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itr, solsta);

      task.getxx(mosek.soltype.itr, // Interior solution.
                 xx);

      switch (solsta[0]) {
        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;
    }
  }
}

feasrepairex1.java

Listing 17.6 feasrepairex1.java Click here to download.
/*
   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

Listing 17.7 gp1.java Click here to download.
//
//   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 numLinCon = 3;  // Linear constraints in original problem
    int numExp    = 2;  // Number of exp-terms in the log-sum-exp constraint

    // Linear part of the problem
    double[] cval  = {1, 1, 1};
    int[]    asubi = {0, 0, 1, 1, 2, 2};
    int[]    asubj = {1, 2, 0, 1, 2, 1};
    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)};

    // Linear part setting up slack variables
    // for the linear expressions appearing inside exps
    // x_5 - x - y = log(2/Awall)
    // x_8 - x - z = log(2/Awall)
    // The slack indexes are convenient for defining exponential cones, see later
    int[]    a2subi = {3, 3, 3, 4, 4, 4};
    int[]    a2subj = {5, 0, 1, 8, 0, 2};
    double[] a2val  = {1.0, -1.0, -1.0, 1.0, -1.0, -1.0};
    boundkey[] b2kc = {boundkey.fx, boundkey.fx};
    double[] b2luc  = {Math.log(2/Aw), Math.log(2/Aw)};

    try (Env  env = new Env();
         Task task = new Task(env, 0, 0)) 
    {
      // 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 + 3*numExp);
      task.appendcons(numLinCon + numExp + 1);

      // 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 three linear constraints
      task.putaijlist(asubi, asubj, aval);
      task.putconboundslice(0, numvar, bkc, blc, buc);

      // Add linear constraints for the expressions appearing in exp(...)
      task.putaijlist(a2subi, a2subj, a2val);
      task.putconboundslice(numLinCon, numLinCon+numExp, b2kc, b2luc, b2luc);

      int c = numLinCon + numExp;
      int expStart = numvar;
      // Add a single log-sum-exp constraint sum(log(exp(z_i))) <= 0
      // Assume numExp variable triples are ordered as (u0,t0,z0,u1,t1,z1...)
      // starting from variable with index expStart
      double[]  val = new double[numExp];
      int[]     sub = new int[numExp];

      // sum(u_i) = 1 as constraint number c, u_i unbounded
      for(int i = 0; i < numExp; i++)
        { sub[i] = expStart + 3*i; val[i] = 1.0; }
      task.putarow(c, sub, val);
      task.putconbound(c, boundkey.fx, 1.0, 1.0);
      task.putvarboundlistconst(sub, boundkey.fr, -inf, inf);

      // z_i unbounded
      for(int i = 0; i < numExp; i++) sub[i] = expStart + 3*i + 2;
      task.putvarboundlistconst(sub, boundkey.fr, -inf, inf);

      // t_i = 1
      for(int i = 0; i < numExp; i++) sub[i] = expStart + 3*i + 1;
      task.putvarboundlistconst(sub, boundkey.fx, 1, 1);

      // Every triple is in an exponential cone
      conetype[] ct = new conetype[numExp];
      int[]     len = new int[numExp];
      for(int i = 0; i < numExp; i++) 
        { ct[i] = conetype.pexp; val[i] = 0.0; len[i] = 3; }
      task.appendconesseq(ct, val, len, expStart);

      // Solve and map to original h, w, d
      task.optimize();
      double[] xyz = new double[numvar];
      double[] hwd = new double[numvar];
      task.getxxslice(soltype.itr, 0, numvar, xyz);
      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]);
  }
}

lo1.java

Listing 17.8 lo1.java Click here to download.
/*
   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
                     };
    double[] xx  = new double[numvar];

    try (mosek.Env  env = new Env();
         mosek.Task task = new Task(env, 0, 0)) {
      // 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[] = new mosek.solsta[1];
      task.getsolsta(mosek.soltype.bas, solsta);

      switch (solsta[0]) {
        case optimal:
          task.getxx(mosek.soltype.bas, // Request the basic solution.
                     xx);

          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

Listing 17.9 lo2.java Click here to download.
/*
   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
                     };
    double[] xx  = new double[numvar];

    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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);

      mosek.solsta solsta[] = new mosek.solsta[1];
      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.bas, solsta);

      task.getxx(mosek.soltype.bas, // Basic solution.
                 xx);
      switch (solsta[0]) {
        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

Listing 17.10 logistic.java Click here to download.
////
//  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;

  // t >= log( 1 + exp(u) )
  // t_i >= log( 1 + exp(u_i) ), i = 0..n-1
  // Adds auxiliary variables and constraints
  public static void softplus(Task task, int t, int u, int n)
  {
    int nvar = task.getnumvar();
    int ncon = task.getnumcon();
    task.appendvars(6*n);
    task.appendcons(3*n);
    int z1 = nvar, z2 = nvar+n, v1 = nvar+2*n, v2 = nvar+3*n, q1 = nvar+4*n, q2 = nvar+5*n;
    int zcon = ncon, v1con = ncon+n, v2con=ncon+2*n;
    int[]    subi = new int[7*n];
    int[]    subj = new int[7*n];
    double[] aval = new double[7*n];
    int         k = 0;

    // Linear constraints
    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++;
      // u - t - v1 = 0
      subi[k] = v1con+i; subj[k] = u+i;   aval[k] = 1;  k++;
      subi[k] = v1con+i; subj[k] = t+i;   aval[k] = -1; k++;
      subi[k] = v1con+i; subj[k] = v1+i;  aval[k] = -1; k++;
      // - t - v2 = 0
      subi[k] = v2con+i; subj[k] = t+i;   aval[k] = -1; k++;
      subi[k] = v2con+i; subj[k] = v2+i;  aval[k] = -1; k++;
    }
    task.putaijlist(subi, subj, aval);
    task.putconboundsliceconst(ncon, ncon+n, boundkey.fx, 1, 1);
    task.putconboundsliceconst(ncon+n, ncon+3*n, boundkey.fx, 0, 0);

    // Bounds for variables
    task.putvarboundsliceconst(nvar, nvar+4*n, boundkey.fr, -inf, inf);
    task.putvarboundsliceconst(nvar+4*n, nvar+6*n, boundkey.fx, 1, 1);

    // Cones
    for(int i = 0; i < n; i++)
    {
      task.appendcone(conetype.pexp, 0.0, new int[]{z1+i, q1+i, v1+i});
      task.appendcone(conetype.pexp, 0.0, new int[]{z2+i, q2+i, v2+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(Env        env,
                                            double[][] X, 
                                            boolean[]  y,
                                            double     lamb)
  {
    int n = X.length;
    int d = X[0].length;       // num samples, dimension

    try (Task task = new Task(env, 0, 0))
    {    
      // Variables [r; theta; t; u]
      int nvar = 1+d+2*n;
      task.appendvars(nvar);
      task.putvarboundsliceconst(0, nvar, boundkey.fr, -inf, inf);
      int r = 0, theta = 1, t = 1+d, u = 1+d+n;
      
      // Constraints: theta'*X +/- u = 0
      task.appendcons(n);
      task.putconboundsliceconst(0, n, boundkey.fx, 0, 0);      
      
      // Objective lambda*r + sum(t)
      task.putcj(r, lamb);
      for(int i = 0; i < n; i++) 
        task.putcj(t+i, 1.0);

      // The X block in theta'*X +/- u = 0
      int[]    subi   = new int[d*n+n];
      int[]    subj   = new int[d*n+n];
      double[] aval   = new double[d*n+n];
      int         k   = 0;
      for(int i = 0; i < n; i++)
      {
        for(int j = 0; j < d; j++)
        {
          subi[k] = i; subj[k] = theta+j; aval[k] = X[i][j]; k++;
        }
        subi[d*n+i] = i; subj[d*n+i] = u+i;
        if (y[i]) aval[d*n+i] = 1; else aval[d*n+i] = -1;
      }
      task.putaijlist(subi, subj, aval);

      // Softplus function constraints
      softplus(task, t, u, n);

      // Regularization
      task.appendconeseq(conetype.quad, 0.0, 1+d, r);

      // Solution
      task.optimize();
      double[] xx = new double[d];
      task.getxxslice(soltype.itr, theta, theta+d, xx);

      return xx;
    }
  }

  public static void main(String[] args)
  {
    Env env = new Env();

    // 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(env, X, Y, 0.1);

    for(int i=0;i<6;i++)
      System.out.println(theta[i]);
  }
}

mico1.java

Listing 17.11 mico1.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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(6);
      task.appendcons(3);
      task.putvarboundsliceconst(0, 6, mosek.boundkey.fr, -0.0, 0.0);

      // Integrality constraints
      task.putvartypelist(new int[]{1,2}, 
                          new mosek.variabletype[]{mosek.variabletype.type_int, mosek.variabletype.type_int});

      // Set up the three auxiliary linear constraints
      task.putaijlist(new int[]{0,0,1,2,2},
                      new int[]{1,3,4,2,5},
                      new double[]{-1,1,1,1,-1});
      task.putconboundslice(0, 3, 
                            new mosek.boundkey[]{mosek.boundkey.fx, mosek.boundkey.fx, mosek.boundkey.fx},
                            new double[]{-3.8, 1, 0}, new double[]{-3.8, 1, 0});

      // Objective
      task.putobjsense(mosek.objsense.minimize);
      task.putcj(0, 1);

      // Conic part of the problem
      task.appendconeseq(mosek.conetype.quad, 0, 3, 0);
      task.appendconeseq(mosek.conetype.pexp, 0, 3, 3);

      // Optimize the task
      task.optimize();
      task.solutionsummary(mosek.streamtype.msg);

      double[] xx = {0, 0};
      task.getxxslice(mosek.soltype.itg, 1, 3, xx);
      System.out.println("x = " + xx[0] + "  y = " + xx[1]);
    }
  }
}

milo1.java

Listing 17.12 milo1.java Click here to download.
/*
   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 };

    double[] xx  = new double[numvar];

    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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);
      task.getxx(mosek.soltype.itg, // Integer solution.
                 xx);
      mosek.solsta solsta[] = new mosek.solsta[1];
      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itg, solsta);

      switch (solsta[0]) {
        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[] = new mosek.prosta[1];
          task.getprosta(mosek.soltype.itg, prosta);
          switch (prosta[0]) {
            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

Listing 17.13 mioinitsol.java Click here to download.
/*
   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
                                   };
    double[] xx = new double[4];

    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) 
    {
      // 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});
      
      // solve
      task.optimize();
      task.solutionsummary(mosek.streamtype.log);

      // Read and print solution
      task.getxx(mosek.soltype.itg, xx);
      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("Initial solution utilization: " + constr);
      System.out.println("Initial 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;
    }
  }
}

modelLib.java

Listing 17.14 modelLib.java Click here to download.
/*
  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File :      modelLib.java

  Purpose: Library of simple building blocks in Mosek Optimizer API.
*/
package com.mosek.example;
import mosek.*;
import java.util.Arrays;

public class modelLib {

  public static double inf = 0.0;

  // Add new constraints and return the index of the first one
  public static int msk_newcon(Task task, int num) {
    int c = task.getnumcon();
    task.appendcons(num);
    return c;
  }

  // Add new variables and return the index of the first one
  public static int msk_newvar(Task task, int num) {  // free
    int v = task.getnumvar();
    task.appendvars(num);
    for(int i=0; i<num; i++)
      task.putvarbound(v+i, boundkey.fr, -inf, inf);
    return v;
  }
  public static int msk_newvar_fx(Task task, int num, double val) {  // fixed
    int v = task.getnumvar();
    task.appendvars(num);
    for(int i=0; i<num; i++)
      task.putvarbound(v+i, boundkey.fx, val, val);
    return v;
  }
  public static int msk_newvar_bin(Task task, int num) {  // binary
    int v = task.getnumvar();
    task.appendvars(num);
    for(int i=0; i<num; i++) {
      task.putvarbound(v+i, boundkey.ra, 0.0, 1.0);
      task.putvartype(v+i, variabletype.type_int);
    }
    return v;
  }

  // Declare variables are duplicates or duplicate a variable and return index of duplicate
  // x = y
  public static void msk_equal(Task task, int x, int y) {
    int c = msk_newcon(task, 1);
    task.putaij(c, x, 1.0);
    task.putaij(c, y, -1.0);
    task.putconbound(c, boundkey.fx, 0.0, 0.0);
  }
  public static int msk_dup(Task task, int x) {
    int y = msk_newvar(task, 1);
    msk_equal(task, x, y);
    return y;
  }

  // Absolute value
  // t >= |x|
  public static void msk_abs(Task task, int t, int x) {
    int c = msk_newcon(task, 2);
    task.putaij(c, t, 1.0);
    task.putaij(c, x, 1.0);
    task.putconbound(c, boundkey.lo, 0.0, inf);
    task.putaij(c+1, t, 1.0);
    task.putaij(c+1, x, -1.0);
    task.putconbound(c+1, boundkey.lo, 0.0, inf);
  }

  // 1-norm
  // t >= sum( |x_i| ), x is a list of variables
  public static void msk_norm1(Task task, int t, int[] x) {
    int n = x.length;
    int u = msk_newvar(task, n);
    for(int i=0; i<n; i++) msk_abs(task, u+i, x[i]);
    int c = msk_newcon(task, 1);
    for(int i=0; i<n; i++) task.putaij(c, u+i, -1.0);
    task.putaij(c, t, 1.0);
    task.putconbound(c, boundkey.lo, 0.0, inf);
  }

  // Square
  // t >= x^2
  public static void msk_sq(Task task, int t, int x) {
    task.appendcone(conetype.rquad, 0.0, new int[]{msk_newvar_fx(task, 1, 0.5), t, x});
  }

  // 2-norm
  // t >= sqrt(x_1^2 + ... + x_n^2) where x is a list of variables
  public static void msk_norm2(Task task, int t, int[] x) {
    int[] submem = new int[x.length+1];
    submem[0] = t;
    for(int i=0; i<x.length; i++) submem[i+1] = x[i];
    task.appendcone(conetype.quad, 0.0, submem);
  }

  // Power with exponent > 1
  // t >= |x|^p (where p>1)
  public static void msk_pow(Task task, int t, int x, double p) {
    task.appendcone(conetype.ppow, 1.0/p, new int[]{t, msk_newvar_fx(task, 1, 1.0), x});
  }

  // Inverse of power 
  // t >= 1/x^p, x>0 (where p>0)
  public static void msk_pow_inv(Task task, int t, int x, double p) {
    task.appendcone(conetype.ppow, 1.0/(1.0+p), new int[]{t, x, msk_newvar_fx(task, 1, 1.0)});
  }

  // p-norm, p>1
  // t >= \|x\|_p (where p>1), x is a list of variables
  public static void msk_pnorm(Task task, int t, int[] x, double p) {
    int n = x.length;
    int r = msk_newvar(task, n);
    for(int i=0; i<n; i++)
      task.appendcone(conetype.ppow, 1.0-1.0/p, new int[]{t, r+i, x[i]});
    int c = msk_newcon(task, 1);
    for(int i=0; i<n; i++)
      task.putaij(c, r+i, -1.0);
    task.putaij(c, t, 1.0);
    task.putconbound(c, boundkey.fx, 0.0, 0.0);
  }

  // Geometric mean
  // |t| <= (x_1...x_n)^(1/n), x_i>=0, x is a list of variables of length >= 1
  public static void msk_geo_mean(Task task, int t, int[] x) {
    int n = x.length;
    if (n==1) msk_abs(task, x[0], t);
    else {
      int t2 = msk_newvar(task, 1);
      task.appendcone(conetype.ppow, 1.0-1.0/n, new int[]{t2, x[n-1], t});
      msk_geo_mean(task, msk_dup(task, t2), Arrays.copyOfRange(x, 0, n-1));
    }
  }

  // Logarithm
  // t <= log(x), x>=0
  public static void msk_log(Task task, int t, int x) {
    task.appendcone(conetype.pexp, 0.0, new int[]{x, msk_newvar_fx(task, 1, 1.0), t});
  }

  // Exponential
  // t >= exp(x)
  public static void msk_exp(Task task, int t, int x) {
    task.appendcone(conetype.pexp, 0.0, new int[]{t, msk_newvar_fx(task, 1, 1.0), x});
  }

  // Entropy
  // t >= x * log(x), x>=0
  public static void msk_ent(Task task, int t, int x) {
    int v = msk_newvar(task, 1);
    int c = msk_newcon(task, 1);
    task.putaij(c, v, 1.0);
    task.putaij(c, t, 1.0);
    task.putconbound(c, boundkey.fx, 0.0, 0.0);
    task.appendcone(conetype.pexp, 0.0, new int[]{msk_newvar_fx(task, 1, 1.0), x, v});
  }

  // Relative entropy
  // t >= x * log(x/y), x,y>=0
  public static void msk_relent(Task task, int t, int x, int y) {
    int v = msk_newvar(task, 1);
    int c = msk_newcon(task, 1);
    task.putaij(c, v, 1.0);
    task.putaij(c, t, 1.0);
    task.putconbound(c, boundkey.fx, 0.0, 0.0);
    task.appendcone(conetype.pexp, 0.0, new int[]{y, x, v});
  }

  // Log-sum-exp
  // log( sum_i(exp(x_i)) ) <= t, where x is a list of variables
  public static void msk_logsumexp(Task task, int t, int[] x) {
    int n = x.length;
    int u = msk_newvar(task, n);
    int z = msk_newvar(task, n);
    for(int i=0; i<n; i++) msk_exp(task, u+i, z+i);
    int c = msk_newcon(task, n);
    for(int i=0; i<n; i++) {
      task.putarow(c+i, new int[]{x[i], t, z+i}, new double[]{1.0, -1.0, -1.0});
      task.putconbound(c+i, boundkey.fx, 0.0, 0.0);
    }
    int s = msk_newcon(task, 1);
    for(int i=0; i<n; i++) task.putaij(s, u+i, 1.0);
    task.putconbound(s, boundkey.up, -inf, 1.0);
  }

  // Semicontinuous variable
  // x = 0 or a <= x <= b
  public static void msk_semicontinuous(Task task, int x, double a, double b) {
    int u = msk_newvar_bin(task, 1);
    int c = msk_newcon(task, 2);
    task.putarow(c, new int[]{x, u}, new double[]{1.0, -a});
    task.putconbound(c, boundkey.lo, 0.0, inf);
    task.putarow(c+1, new int[]{x, u}, new double[]{1.0, -b});
    task.putconbound(c+1, boundkey.up, -inf, 0.0);
  }

  // Indicator variable
  // x!=0 implies t=1. Assumes that |x|<=1 in advance.
  public static int msk_indicator(Task task, int x) {
    int t = msk_newvar_bin(task, 1);
    msk_abs(task, t, x);
    return t;
  }

  // Logical OR
  // x OR y, where x, y are binary
  public static void msk_logic_or(Task task, int x, int y) {
    int c = msk_newcon(task, 1);
    task.putarow(c, new int[]{x, y}, new double[]{1.0, 1.0});
    task.putconbound(c, boundkey.lo, 1.0, inf);
  }
  // x_1 OR ... OR x_n, where x is sequence of variables
  public static void msk_logic_or_vect(Task task, int[] x) {
    int c = msk_newcon(task, 1);
    for(int i=0; i<x.length; i++) task.putaij(c, x[i], 1.0);
    task.putconbound(c, boundkey.lo, 1.0, inf);
  }

  // SOS1 (NAND)
  // at most one of x_1,...,x_n, where x is a binary vector (SOS1 constraint)
  public static void msk_logic_sos1(Task task, int[] x) {
    int c = msk_newcon(task, 1);
    for(int i=0; i<x.length; i++) task.putaij(c, x[i], 1.0);
    task.putconbound(c, boundkey.up, -inf, 1.0);
  }
  // NOT(x AND y), where x, y are binary
  public static void msk_logic_nand(Task task, int x, int y) {
    int c = msk_newcon(task, 1);
    task.putarow(c, new int[]{x, y}, new double[]{1.0, 1.0});
    task.putconbound(c, mosek.boundkey.up, -inf, 1.0);
  }

  // Cardinality bound
  // At most k of entries in x are nonzero, assuming in advance that |x_i|<=1.
  public static void msk_card(Task task, int[] x, int k) {
    int n = x.length;
    int t = msk_newvar_bin(task, n);
    for(int i=0; i<n; i++) msk_abs(task, t+i, x[i]);
    int c = msk_newcon(task, 1);
    for(int i=0; i<n; i++) task.putaij(c, t+i, 1.0);
    task.putconbound(c,boundkey.up, -inf, k);
  }

  // This is just a syntactic test without much sense
  public static void testModels() {
    Env env = new Env();
    Task task = new Task(env);
    int x = msk_newvar(task, 1);
    int y = msk_newvar(task, 1);
    int t = msk_newvar(task, 1);
    int p = msk_newvar(task, 5);
    int a = msk_newvar(task, 15);
    int b = msk_newvar(task, 15);
    int e = msk_newvar_bin(task, 1);
    int f = msk_newvar_bin(task, 1);

    msk_log(task, t, x);
    msk_exp(task, msk_dup(task, t), msk_dup(task, x));
    msk_ent(task, msk_dup(task, t), msk_dup(task, x));
    msk_relent(task, msk_dup(task, t), msk_dup(task, x), msk_dup(task, y));
    msk_logsumexp(task, t, new int[]{p, p+1, p+2, p+3, p+4});
    msk_abs(task, msk_dup(task, x), b+3);
    msk_norm1(task, msk_newvar_fx(task, 1, 0.74), new int[]{a, a+9, a+13, a+4});
    msk_sq(task, msk_dup(task, t), msk_dup(task, x));
    msk_norm2(task, msk_dup(task, t), new int[]{b+1, b+3, b+4, b+5, b+6});
    msk_pow(task, msk_dup(task, t), msk_dup(task, x), 1.5);
    msk_pow_inv(task, msk_dup(task, t), msk_dup(task, x), 3.3);
    msk_geo_mean(task, msk_dup(task, t), new int[]{p, p+1, p+2, p+3, p+4});
    msk_semicontinuous(task, y, 1.1, 2.2);
    int i = msk_indicator(task, y);
    msk_logic_or(task, e, f);
    msk_logic_nand(task, e, f);
    msk_card(task, new int[]{b+1, b+3, b+4, b+5, b+6}, 2);
  }

  // A sample problem using functions from the library
  //
  // max -sqrt(x^2 + y^2) + log(y) - x^1.5
  //  st x >= y + 3
  //
  public static void testExample() {
    Env env = new Env();
    Task task = new Task(env);
    int x = msk_newvar(task, 1);
    int y = msk_newvar(task, 1);
    int t = msk_newvar(task, 3);

    int c = msk_newcon(task, 1);
    task.putarow(c, new int[]{x, y}, new double[]{1.0, -1.0});
    task.putconbound(c, boundkey.lo, 3.0, inf);

    msk_norm2(task, t+0, new int[]{x,y});
    msk_log  (task, t+1, msk_dup(task, y));
    msk_pow  (task, t+2, msk_dup(task, x), 1.5);

    task.putclist(new int[]{t, t+1, t+2}, new double[]{-1.0, 1.0, -1.0});
    task.putobjsense(objsense.maximize);

    task.set_Stream(
      mosek.streamtype.log,
      new mosek.Stream() { public void stream(String msg) { System.out.print(msg); }});

    task.optimize();
    task.solutionsummary(streamtype.log);

    double[] xx = new double[task.getnumvar()];
    task.getxx(soltype.itr, xx);
    System.out.format("x=%f y=%f obj=%f\n", xx[x], xx[y], task.getprimalobj(soltype.itr));
  }

  public static void main(String[] args) {
    testModels();
    testExample();
  }
}

opt_server_async.java

Listing 17.15 opt_server_async.java Click here to download.
/*
   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 host      = args[1];
      String port      = args[2];
      int numpolls     = Integer.parseInt(args[3]);

      try (Env env = new Env()) {
        String token;

        try(Task task = new Task(env, 0, 0)) {
          task.readdata (inputfile);
          token = task.asyncoptimize (host, port);
        }

        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);

          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( host,
                                                    port,
                                                    token,
                                                    resp,
                                                    trm);


            System.out.println("polling done");

            if (respavailable) {
              System.out.println("solution available!");

              task.asyncgetresult(host,
                                  port,
                                  token,
                                  resp,
                                  trm);

              task.solutionsummary (mosek.streamtype.log);
              break;
            }

            i++;

            if (i == numpolls) {
              System.out.println("max num polls reached, stopping host.");
              task.asyncstop (host, port, token);
              break;
            }

          }
        } catch (java.lang.Exception e) {
          System.out.println("Something unexpected happend...");
          throw e;
        }
      }
    }
  }
}

opt_server_sync.java

Listing 17.16 opt_server_sync.java Click here to download.
/*
   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 < 2) {
      System.out.println ("Missing argument, syntax is:");
      System.out.println ("  opt_server_sync inputfile serveraddr");
    } else {

      String inputfile = args[0];
      String addr      = args[1];

      rescode trm[]  = new rescode[1];

      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 (inputfile);

        // Set OptServer URL
        task.putoptserverhost(addr);

        // Optimize
        task.optimize (trm);

        task.solutionsummary (mosek.streamtype.log);
      }
    }
  }
}

parallel.java

Listing 17.17 parallel.java Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      parallel.java

   Purpose: Demonstrates parallel optimization
*/
package com.mosek.example;

public class parallel
{
  /** Takes a list of tasks and optimizes them in parallel threads. The
      response code and termination code from each optimization is
      stored in ``res`` and ``trm``.
   */
  public static void paropt(mosek.Task[]    tasks,
                            mosek.rescode[] res,
                            mosek.rescode[] trm)
  {
    int n = tasks.length;
    Thread[] jobs = new Thread[n];
    
    // 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;
        }
      }};
      jobs[i].start();
    }

    // Join all threads
    try {
      for (Thread j: jobs)
        j.join();
    }
    catch (InterruptedException e) {}
  }


  /** Example of how to use ``paropt``. 
      Optimizes tasks whose names were read from command line.
   */
  public static void main(String[] argv)
  {
    int n = argv.length;
    mosek.Task[]  t      = new mosek.Task[n];
    mosek.rescode[] res  = new mosek.rescode[n];
    mosek.rescode[] trm  = new mosek.rescode[n];

    mosek.Env env = new mosek.Env();

    for(int i = 0; i < n; i++) 
    {
      t[i] = new mosek.Task(env);
      t[i].readdata(argv[i]);
      // Each task will be single-threaded
      t[i].putintparam(mosek.iparam.intpnt_multi_thread, mosek.onoffkey.off.value);      
    }

    paropt(t, res, trm);

    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],  
        t[i].getdouinf(mosek.dinfitem.intpnt_primal_obj),
        t[i].getdouinf(mosek.dinfitem.optimizer_time));
  }
}

parameters.java

Listing 17.18 parameters.java Click here to download.
/*
   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.Env  env = new Env();
      mosek.Task task = new Task(env, 0, 0);

      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;
    }
  }
}

portfolio_1_basic.java

Listing 17.19 portfolio_1_basic.java Click here to download.
/*
   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;

public class portfolio_1_basic {
  static final int n = 3;

  public static void main (String[] args) {
    // Since the value infinity is never used, we define
    // 'infinity' for symbolic purposes only
    double infinity = 0;
    double gamma = 0.05;
    double[]   mu = {0.1073,  0.0737,  0.0627};
    double[][] GT = {
      {0.1667,  0.0232,  0.0013},
      {0.0000,  0.1033, -0.0022},
      {0.0000,  0.0000,  0.0338}
    };
    double[] x0 = {0.0, 0.0, 0.0};
    double   w = 1.0;
    double   totalBudget;

    int numvar = 2 * n + 1;
    int numcon = n + 1;


    //Offset of variables into the API variable.
    int offsetx = 0;
    int offsets = n;
    int offsett = n + 1;

    try ( mosek.Env env   = new mosek.Env ();
          mosek.Task task = new mosek.Task (env, 0, 0) ) {
      // 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); }});

      // Constraints.
      task.appendcons(numcon);

      // Constraint bounds. Compute total budget.
      totalBudget = w;
      for (int i = 0; i < n; ++i)
      {
        totalBudget += x0[i];
        /* Constraint bounds c^l = c^u = 0 */
        task.putconbound(i + 1, mosek.boundkey.fx, 0.0, 0.0);
        task.putconname(i + 1, "GT[" + (i + 1) + "]");
      }
      /* The total budget constraint c^l = c^u = totalBudget in first row of A. */
      task.putconbound(0, mosek.boundkey.fx, totalBudget, totalBudget);
      task.putconname(0, "budget");

      // Variables.
      task.appendvars(numvar);

      /* x variables. */
      for (int j = 0; j < n; ++j)
      {
        /* Return of asset j in the objective */
        task.putcj(offsetx + j, mu[j]);
        /* Coefficients in the first row of A */
        task.putaij(0, offsetx + j, 1.0);
        /* No short-selling - x^l = 0, x^u = inf */
        task.putvarbound(offsetx + j, mosek.boundkey.lo, 0.0, infinity);
        task.putvarname(offsetx + j, "x[" + (j + 1) + "]");            
      }

      /* s variable is a constant equal to gamma. */
      task.putvarbound(offsets, mosek.boundkey.fx, gamma, gamma);
      task.putvarname(offsets, "s");

      /* t variables (t = GT*x). */
      for (int j = 0; j < n; ++j)
      {
        /* Copying the GT matrix in the appropriate block of A */
        for (int k = 0; k < n; ++k)
          if ( GT[k][j] != 0.0 )
            task.putaij(1 + k, offsetx + j, GT[k][j]);
        /* Diagonal -1 entries in a block of A */
        task.putaij(1 + j, offsett + j, -1.0);
        /* Free - no bounds */
        task.putvarbound(offsett + j, mosek.boundkey.fr, -infinity, infinity);
        task.putvarname(offsett + j, "t[" + (j + 1) + "]");
      }

      /* Define the cone spanned by (s, t), i.e. of dimension n + 1 */
      int[] csub = new int[n + 1];
      csub[0] = offsets;
      for(int j = 0; j< n; j++) csub[j + 1] = offsett + j;
      task.appendcone( mosek.conetype.quad,
                       0.0, /* For future use only, can be set to 0.0 */
                       csub );
      task.putconename(0, "stddev");

      /* A maximization problem */
      task.putobjsense(mosek.objsense.maximize);

      task.optimize();

      /* Display solution summary for quick inspection of results */
      task.solutionsummary(mosek.streamtype.log);

      task.writedata("dump.opf");

      /* Read the results */
      double expret = 0.0;
      double[] xx = new double[n + 1];

      task.getxxslice(mosek.soltype.itr, 0, offsets + 1, xx);
      for (int j = 0; j < n; ++j)
        expret += mu[j] * xx[j + offsetx];

      System.out.printf("\nExpected return %e for gamma %e\n", expret, xx[offsets]);
    }
  }
}

portfolio_2_frontier.java

Listing 17.20 portfolio_2_frontier.java Click here to download.
/*
   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.*;

public class portfolio_2_frontier {
  static final int n = 3;

  public static void main (String[] args) {
    // Since the value infinity is never used, we define
    // 'infinity' symbolic purposes only
    double infinity = 0;
    double[]   mu = {0.1073,  0.0737,  0.0627};
    double[][] GT = {
      {0.1667,  0.0232,  0.0013},
      {0.0000,  0.1033, -0.0022},
      {0.0000,  0.0000,  0.0338}
    };
    double[] x0 = {0.0, 0.0, 0.0};
    double   w = 1.0;
    double[] alphas = {0.0, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5};
    int numalphas = 12;

    int numvar = 2 * n + 2;
    int numcon = n + 1;


    //Offset of variables into the API variable.
    int offsetx = 0;
    int offsets = n;
    int offsett = n + 1;
    int offsetu = 2 * n + 1;

    try ( Env env  = new mosek.Env ();
          Task task = new mosek.Task (env, 0, 0) ) {

      // 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.appendcons(numcon);
      task.appendvars(numvar);

      //Constraints.
      for ( int i = 1; i <= n; ++i) {
        w += x0[i - 1];
        task.putconbound(i, mosek.boundkey.fx, 0., 0.);
        task.putconname(i, "GT[" + i + "]");
      }
      for (int i = 0; i < n; ++i)
        task.putaij(0, offsetx + i, 1.0);
      task.putconbound(0, mosek.boundkey.fx, w, w);
      task.putconname(0, "budget");

      // Objective coefficients
      for(int i = 0; i < n; i++)
        task.putcj(offsetx + i, mu[i]);

      for ( int i = 0; i < n; ++i) {
        // The constraint t = GT * x
        for ( int j = i; j < n; ++j)
          task.putaij(i + 1, offsetx + j, GT[i][j]);

        task.putaij(i + 1, offsett + i, -1.0);

        // x variables
        task.putvarbound(offsetx + i, mosek.boundkey.lo, 0., 0.);

        task.putvarname(offsetx + i, "x[" + (i + 1) + "]");
        task.putvarname(offsett + i, "t[" + (i + 1) + "]");

        // t variable
        task.putvarbound(offsett + i, mosek.boundkey.fr, -infinity, infinity);
      }

      // s variable
      task.putvarbound(offsets, mosek.boundkey.fr, -infinity, infinity);
      task.putvarname(offsets, "s");

      // u variable
      task.putvarbound(offsetu, mosek.boundkey.fx, 0.5, 0.5);
      task.putvarname(offsetu, "u");

      //Cones.
      int[] csub = new int[n+2];
      csub[0] = offsets; 
      csub[1] = offsetu;
      for(int i = 0; i < n; i++)
        csub[i+2] = offsett + i;

      task.appendcone(mosek.conetype.rquad,
                      0.0, /* For future use only, can be set to 0.0 */
                      csub);
      task.putconename(0, "variance");

      /* A maximization problem */
      task.putobjsense(mosek.objsense.maximize);

      //task.writedata("dump.opf");

      try {
        //Turn all log output off.
        task.putintparam(mosek.iparam.log, 0);

        System.out.printf("%-12s  %-12s  %-12s", "alpha", "exp ret", "variance");
        for (int k = 0; k < numalphas; ++k) {
          task.putcj(offsets, -alphas[k]);

          task.optimize();

          task.solutionsummary(mosek.streamtype.log);

          double expret = 0.0, stddev = 0.0;
          double[] xx = new double[numvar];

          task.getxx(mosek.soltype.itr, xx);

          for (int j = 0; j < n; ++j)
            expret += mu[j] * xx[j + offsetx];

          System.out.printf("%-12.3e  %-12.3e  %-12.3e\n", alphas[k], expret, xx[offsets]);

        }
        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

Listing 17.21 portfolio_3_impact.java Click here to download.
/*
   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;

public class portfolio_3_impact {
  static final int n = 3;

  public static void main (String[] args) {
    // Since the value infinity is never used, we define
    // 'infinity' symbolic purposes only
    double infinity = 0;
    double gamma = 0.05;
    double[]   mu = {0.1073,  0.0737,  0.0627};
    double[][] GT = {
      {0.1667,  0.0232,  0.0013},
      {0.0000,  0.1033, -0.0022},
      {0.0000,  0.0000,  0.0338}
    };
    double[] x0 = {0.0, 0.0, 0.0};
    double   w = 1.0;
    double[] m = {0.01, 0.01, 0.01};

    int offsetx = 0;
    int offsets = offsetx + n;
    int offsett = offsets + 1;
    int offsetc = offsett + n;
    int offsetz = offsetc + n;
    int offsetf = offsetz + n;

    int numvar = 5 * n + 1;

    int offset_con_budget = 0;
    int offset_con_gx_t = offset_con_budget + 1;
    int offset_con_abs1 = offset_con_gx_t + n;
    int offset_con_abs2 = offset_con_abs1 + n;

    int numcon = 3 * n  +1;

    try ( mosek.Env env  = new mosek.Env ();
          mosek.Task task = new mosek.Task (env, 0, 0) ) {

      // 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); }});

      //Set up constraint bounds, names and variable coefficients
      task.appendcons(numcon);
      for (int i = 0; i < n; ++i) {
        w += x0[i];
        task.putconbound(offset_con_gx_t + i, mosek.boundkey.fx, 0., 0.);
        task.putconname(offset_con_gx_t + i, "GT[" + (i + 1) + "]");

        task.putconbound(offset_con_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
        task.putconname(offset_con_abs1 + i, "zabs1[" + (i + 1) + "]");

        task.putconbound(offset_con_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
        task.putconname(offset_con_abs2 + i, "zabs2[" + (i + 1) + "]");
      }
      // e x = w + e x0
      task.putconbound(offset_con_budget, mosek.boundkey.fx, w, w);
      task.putconname(offset_con_budget, "budget");

      //Variables.
      task.appendvars(numvar);

      //the objective function coefficients
      for (int i = 0; i < n; i++) 
      {
        task.putcj(offsetx + i, mu[i]);
      }

      double[] one_m_one = {1.0, -1.0};
      double[] one_one = {1.0, 1.0};

      //set up variable bounds and names
      for (int i = 0; i < n; ++i) {
        task.putvarbound(offsetx + i, mosek.boundkey.lo, 0., infinity);
        task.putvarbound(offsett + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsetc + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsetz + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsetf + i, mosek.boundkey.fx, 1.0, 1.0);

        task.putvarname(offsetx + i, "x[" + (i + 1) + "]");
        task.putvarname(offsett + i, "t[" + (i + 1) + "]");
        task.putvarname(offsetc + i, "c[" + (i + 1) + "]");
        task.putvarname(offsetz + i, "z[" + (i + 1) + "]");
        task.putvarname(offsetf + i, "f[" + (i + 1) + "]");

        for (int j = i; j < n; ++j)
          task.putaij(offset_con_gx_t + i, j, GT[i][j]);

        task.putaij(offset_con_gx_t + i, offsett + i, -1.0);

        task.putaij(offset_con_budget, offsetx + i, 1.0);
        task.putaij(offset_con_budget, offsetc + i, m[i]);

        // z_j - x_j >= -x0_j
        int[] indx1 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs1 + i, indx1, one_m_one);
        // z_j + x_j >= +x0_j
        int[] indx2 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs2 + i, indx2, one_one);
      }
      task.putvarbound(offsets, mosek.boundkey.fx, gamma, gamma);
      task.putvarname(offsets, "s");

      //Cones.
      int[] csub = new int[n+1];
      csub[0] = offsets;
      for(int i = 0; i < n; i++) csub[i + 1] = offsett + i;
      task.appendcone(mosek.conetype.quad, 0.0, csub);
      task.putconename(0, "stddev");

      // Power cones
      for (int j = 0; j < n; ++j)
      {
        int[] coneindx = { offsetc + j, offsetf + j, offsetz + j };
        task.appendcone(mosek.conetype.ppow, 2.0/3.0, coneindx);
        task.putconename(1 + j, "trans[" + (j + 1) + "]");
      }

      /* A maximization problem */
      task.putobjsense(mosek.objsense.maximize);

      /* Solve the problem */
      try {
        //Turn all log output off.
        //task.putintparam(mosek.iparam.log,0);

        //task.writedata("dump.opf");

        task.optimize();

        task.solutionsummary(mosek.streamtype.log);

        double expret = 0.0, stddev = 0.0;
        double[] xx = new double[numvar];

        task.getxx(mosek.soltype.itr, xx);

        for (int j = 0; j < n; ++j)
          expret += mu[j] * xx[j + offsetx];

        System.out.printf("Expected return %e for gamma %e\n\n", expret, xx[offsets]);

      } 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

Listing 17.22 portfolio_4_transcost.java Click here to download.
/*
   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;

public class portfolio_4_transcost {
  static final int n = 3;

  public static void main (String[] args) {
    // Since the value infinity is never used, we define
    // 'infinity' symbolic purposes only
    double infinity = 0;
    double gamma = 0.05;
    double[]   mu = {0.1073,  0.0737,  0.0627};
    double[][] GT = {
      {0.1667,  0.0232,  0.0013},
      {0.0000,  0.1033, -0.0022},
      {0.0000,  0.0000,  0.0338}
    };
    double[] x0 = {0.0, 0.0, 0.0};
    double   w = 1.0;
    double[] f = {0.01, 0.01, 0.01};
    double[] g = {0.001, 0.001, 0.001};

    // Total initial wealth
    double U = w;
    for(int i=0; i< n; i++) U += x0[i];

    int offsetx = 0;
    int offsets = offsetx + n;
    int offsett = offsets + 1;
    int offsetz = offsett + n;
    int offsety = offsetz + n;

    int numvar = 4 * n + 1;

    int offset_con_budget = 0;
    int offset_con_gx_t = offset_con_budget + 1;
    int offset_con_abs1 = offset_con_gx_t + n;
    int offset_con_abs2 = offset_con_abs1 + n;
    int offset_con_ind  = offset_con_abs2 + n;

    int numcon = 4 * n  +1;

    try ( mosek.Env env  = new mosek.Env ();
          mosek.Task task = new mosek.Task (env, 0, 0) ) {

      // 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); }});

      //Set up constraint bounds, names and variable coefficients
      task.appendcons(numcon);
      for (int i = 0; i < n; ++i) {
        task.putconbound(offset_con_gx_t + i, mosek.boundkey.fx, 0., 0.);
        task.putconname(offset_con_gx_t + i, "GT[" + (i + 1) + "]");

        task.putconbound(offset_con_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
        task.putconname(offset_con_abs1 + i, "zabs1[" + (i + 1) + "]");

        task.putconbound(offset_con_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
        task.putconname(offset_con_abs2 + i, "zabs2[" + (i + 1) + "]");

        task.putconbound(offset_con_ind + i, mosek.boundkey.up, -infinity, 0.0);
        task.putconname(offset_con_ind + i, "ind[" + (i + 1) + "]");
      }
      // e x = w + e x0
      task.putconbound(offset_con_budget, mosek.boundkey.fx, U, U);
      task.putconname(offset_con_budget, "budget");

      //Variables.
      task.appendvars(numvar);

      //the objective function coefficients
      for (int i = 0; i < n; i++) 
      {
        task.putcj(offsetx + i, mu[i]);
      }

      double[] one_m_one = {1.0, -1.0};
      double[] one_one = {1.0, 1.0};

      //set up variable bounds and names
      for (int i = 0; i < n; ++i) {
        task.putvarbound(offsetx + i, mosek.boundkey.lo, 0., infinity);
        task.putvarbound(offsett + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsetz + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsety + i, mosek.boundkey.ra, 0.0, 1.0);
        task.putvartype(offsety + i, mosek.variabletype.type_int);

        task.putvarname(offsetx + i, "x[" + (i + 1) + "]");
        task.putvarname(offsett + i, "t[" + (i + 1) + "]");
        task.putvarname(offsetz + i, "z[" + (i + 1) + "]");
        task.putvarname(offsety + i, "y[" + (i + 1) + "]");

        for (int j = i; j < n; ++j)
          task.putaij(offset_con_gx_t + i, j, GT[i][j]);

        task.putaij(offset_con_gx_t + i, offsett + i, -1.0);

        task.putaij(offset_con_budget, offsetx + i, 1.0);
        task.putaij(offset_con_budget, offsetz + i, g[i]);
        task.putaij(offset_con_budget, offsety + i, f[i]);

        // z_j - x_j >= -x0_j
        int[] indx1 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs1 + i, indx1, one_m_one);
        // z_j + x_j >= +x0_j
        int[] indx2 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs2 + i, indx2, one_one);

        // z_j - U*y_j <= 0
        int[] indx3 = {offsetz + i, offsety + i};
        double[] va = {1.0, -U};
        task.putarow(offset_con_ind + i, indx3, va);        
      }
      task.putvarbound(offsets, mosek.boundkey.fx, gamma, gamma);
      task.putvarname(offsets, "s");

      //Cones.
      int[] csub = new int[n+1];
      csub[0] = offsets;
      for(int i = 0; i < n; i++) csub[i + 1] = offsett + i;
      task.appendcone(mosek.conetype.quad, 0.0, csub);
      task.putconename(0, "stddev");

      /* A maximization problem */
      task.putobjsense(mosek.objsense.maximize);

      /* Solve the problem */
      try {
        //Turn all log output off.
        //task.putintparam(mosek.iparam.log,0);

        //task.writedata("dump.opf");

        task.optimize();

        task.solutionsummary(mosek.streamtype.log);

        double expret = 0.0, stddev = 0.0;
        double[] xx = new double[numvar];

        task.getxx(mosek.soltype.itg, xx);

        for (int j = 0; j < n; ++j)
          expret += mu[j] * xx[j + offsetx];

        System.out.printf("Expected return %e for gamma %e\n\n", expret, xx[offsets]);

      } 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

Listing 17.23 portfolio_5_card.java Click here to download.
/*
   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;

public class portfolio_5_card {

  // Since the value infinity is never used, we define
  // 'infinity' symbolic purposes only
  static final double infinity = 0;

  public static double[] markowitz_with_card(int        n,
                                             double[]   x0,
                                             double     w,
                                             double     gamma,
                                             double[]   mu,
                                             double[][] GT,
                                             int        k) 
  {
    // Total initial wealth
    double U = w;
    for(int i=0; i<n; i++) U += x0[i];

    int offsetx = 0;
    int offsets = offsetx + n;
    int offsett = offsets + 1;
    int offsetz = offsett + n;
    int offsety = offsetz + n;

    int numvar = 4 * n + 1;

    int offset_con_budget = 0;
    int offset_con_gx_t = offset_con_budget + 1;
    int offset_con_abs1 = offset_con_gx_t + n;
    int offset_con_abs2 = offset_con_abs1 + n;
    int offset_con_ind  = offset_con_abs2 + n;
    int offset_con_card = offset_con_ind + n;

    int numcon = 4 * n  + 2;

    try ( mosek.Env env  = new mosek.Env ();
          mosek.Task task = new mosek.Task (env, 0, 0) ) {

      // 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); }});

      //Set up constraint bounds, names and variable coefficients
      task.appendcons(numcon);
      for (int i = 0; i < n; ++i) {
        task.putconbound(offset_con_gx_t + i, mosek.boundkey.fx, 0., 0.);
        task.putconname(offset_con_gx_t + i, "GT[" + (i + 1) + "]");

        task.putconbound(offset_con_abs1 + i, mosek.boundkey.lo, -x0[i], infinity);
        task.putconname(offset_con_abs1 + i, "zabs1[" + (i + 1) + "]");

        task.putconbound(offset_con_abs2 + i, mosek.boundkey.lo, x0[i], infinity);
        task.putconname(offset_con_abs2 + i, "zabs2[" + (i + 1) + "]");

        task.putconbound(offset_con_ind + i, mosek.boundkey.up, -infinity, 0.0);
        task.putconname(offset_con_ind + i, "ind[" + (i + 1) + "]");
      }
      // e x = w + e x0
      task.putconbound(offset_con_budget, mosek.boundkey.fx, U, U);
      task.putconname(offset_con_budget, "budget");

      // sum(y) <= k
      task.putconbound(offset_con_card, mosek.boundkey.up, -infinity, k);
      task.putconname(offset_con_card, "cardinality");

      //Variables.
      task.appendvars(numvar);

      //the objective function coefficients
      for (int i = 0; i < n; i++) 
      {
        task.putcj(offsetx + i, mu[i]);
      }

      double[] one_m_one = {1.0, -1.0};
      double[] one_one = {1.0, 1.0};

      //set up variable bounds and names
      for (int i = 0; i < n; ++i) {
        task.putvarbound(offsetx + i, mosek.boundkey.lo, 0., infinity);
        task.putvarbound(offsett + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsetz + i, mosek.boundkey.fr, -infinity, infinity);
        task.putvarbound(offsety + i, mosek.boundkey.ra, 0.0, 1.0);
        task.putvartype(offsety + i, mosek.variabletype.type_int);

        task.putvarname(offsetx + i, "x[" + (i + 1) + "]");
        task.putvarname(offsett + i, "t[" + (i + 1) + "]");
        task.putvarname(offsetz + i, "z[" + (i + 1) + "]");
        task.putvarname(offsety + i, "y[" + (i + 1) + "]");

        for (int j = i; j < n; ++j)
          task.putaij(offset_con_gx_t + i, j, GT[i][j]);

        task.putaij(offset_con_gx_t + i, offsett + i, -1.0);
        task.putaij(offset_con_budget, offsetx + i, 1.0);

        // z_j - x_j >= -x0_j
        int[] indx1 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs1 + i, indx1, one_m_one);
        // z_j + x_j >= +x0_j
        int[] indx2 = {offsetz + i, offsetx + i};
        task.putarow(offset_con_abs2 + i, indx2, one_one);

        // z_j - U*y_j <= 0
        int[] indx3 = {offsetz + i, offsety + i};
        double[] va = {1.0, -U};
        task.putarow(offset_con_ind + i, indx3, va);    

        // sum(y)
        task.putaij(offset_con_card, offsety + i, 1.0);
      }
      task.putvarbound(offsets, mosek.boundkey.fx, gamma, gamma);
      task.putvarname(offsets, "s");

      //Cones.
      int[] csub = new int[n+1];
      csub[0] = offsets;
      for(int i = 0; i < n; i++) csub[i + 1] = offsett + i;
      task.appendcone(mosek.conetype.quad, 0.0, csub);
      task.putconename(0, "stddev");

      /* A maximization problem */
      task.putobjsense(mosek.objsense.maximize);

      /* Solve the problem */
      //Turn all log output off.
      task.putintparam(mosek.iparam.log,0);

      //task.writedata("dump.opf");

      task.optimize();
      task.solutionsummary(mosek.streamtype.log);

      double[] xx = new double[n];
      task.getxxslice(mosek.soltype.itg, offsetx, offsetx + n, xx);
      return xx;
    }
  }

  public static void main (String[] args) 
  {
    int n = 3;
    double gamma = 0.05;
    double[]   mu = {0.1073,  0.0737,  0.0627};
    double[][] GT = {
      {0.1667,  0.0232,  0.0013},
      {0.0000,  0.1033, -0.0022},
      {0.0000,  0.0000,  0.0338}
    };
    double[] x0 = {0.0, 0.0, 0.0};
    double   w = 1.0;

    for(int k=1; k<=3; k++)
    {
      double[] xx = markowitz_with_card(n, 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);
    }
  }
}

pow1.java

Listing 17.24 pow1.java Click here to download.
/*
   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 = 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[] bkx = new mosek.boundkey[numvar];
    double[] blx         = new double[numvar];
    double[] bux         = new double[numvar];    

    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;
    double[] xx  = new double[numvar];

    // create a new environment object
    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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);
      for(i=0;i<5;i++) {
        bkx[i] = mosek.boundkey.fr;
        blx[i] = -infinity;
        bux[i] = infinity;
      }
      bkx[5] = mosek.boundkey.fx;
      blx[5] = bux[5] = 1.0;
      task.putvarboundslice(0, numvar, bkx, blx, bux);

      /* Add a conic constraint */
      int[][] csub = { {0, 1, 3}, {2, 5, 4}};
      task.appendcone(mosek.conetype.ppow, 0.2, csub[0]);
      task.appendcone(mosek.conetype.ppow, 0.4, csub[1]);

      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);

      mosek.solsta solsta[] = new mosek.solsta[1];

      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itr, solsta);

      task.getxx(mosek.soltype.itr, // Interior solution.
                 xx);

      switch (solsta[0]) {
        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

Listing 17.25 qcqo1.java Click here to download.
/*
   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} };

    double[] xx   = new double[numvar];


    try (mosek.Env  env  = new mosek.Env();
         mosek.Task task = new mosek.Task(env, 0, 0)) {
      // 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);

      mosek.solsta solsta[] = new mosek.solsta[1];
      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itr, solsta);

      task.getxx(mosek.soltype.itr, // Interior solution.
                 xx);
      switch (solsta[0]) {
        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

Listing 17.26 qo1.java Click here to download.
/*
   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} };
    double[] xx   = new double[numvar];

    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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);

      mosek.solsta solsta[] = new mosek.solsta[1];
      /* Get status information about the solution */
      task.getsolsta(mosek.soltype.itr, solsta);

      /* Get the solution */
      task.getxx(mosek.soltype.itr, // Interior solution.
                 xx);

      switch (solsta[0]) {
        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

Listing 17.27 reoptimization.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      /* 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

Listing 17.28 response.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      
      // (Optionally) attach the log handler to receive log information
      /*
      task.set_Stream(
        streamtype.log,
        new mosek.Stream()
      { public void stream(String msg) { System.out.print(msg); }});
      */

      // (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 = new double[numvar];
          task.getxx(soltype.itr, xx);
          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

Listing 17.29 sdo1.java Click here to download.
/*
   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 conic quadratic 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}};
    int[]        conesub = { 0, 1, 2};


    try (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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 cone */
      task.appendcone(mosek.conetype.quad,
                      0.0,
                      conesub);

      /* 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 = new mosek.solsta[1];
      task.getsolsta (mosek.soltype.itr, solsta);

      switch (solsta[0]) {
        case optimal:
          double[] xx = new double[numvar];
          double[] barx = new double[lenbarvar[0]];

          task.getxx(mosek.soltype.itr, xx);
          task.getbarxj(mosek.soltype.itr,    /* Request the interior solution. */
                        0,
                        barx);
          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

Listing 17.30 sdo2.java Click here to download.
/*
  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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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(6, Cj, Ck, Cl, Cv);

      /* Set the equality constraint (6 nonzeros).*/
      task.putbarablocktriplet(6, Ai, Aj, Ak, Al, Av);

      /* Set the inequality constraint (1 nonzero).*/
      task.putbarablocktriplet(1, 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 = new mosek.solsta[1];
      task.getsolsta (mosek.soltype.itr, solsta);

      switch (solsta[0]) {
        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 = new double[dim];

            task.getbarxj(mosek.soltype.itr, i, barx);

            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;
      }
    }
  }
}

sensitivity.java

Listing 17.31 sensitivity.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      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

Listing 17.32 simple.java Click here to download.
/*
   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 (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); }
        });
        // 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

Listing 17.33 solutionquality.java Click here to download.
/*
   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 (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); }
        });
        // 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[] = new mosek.solsta[1];
        task.getsolsta(mosek.soltype.bas, solsta);

        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[0]) {
          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

Listing 17.34 solvebasis.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      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 = new int[1];
      nz[0] = 2;

      task.solvewithbasis(0, nz, varsub, w1);
      System.out.println("nz =" + nz[0]);
      System.out.println("\nSolution to Bx = w1:\n");

      for (int i = 0; i < nz[0]; 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[0] = 2;
      varsub[0] = 0;
      varsub[1] = 1;

      task.solvewithbasis(1, nz, varsub, w2);

      System.out.println("\nSolution to B^Tx = w2:\n");

      for (int i = 0; i < nz[0]; 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

Listing 17.35 solvelinear.java Click here to download.
/*
   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 (Env  env  = new Env();
         Task task = new Task(env, 0, 0)) {
      // 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_ = { 2 };
      task.solvewithbasis(0, nz_, bsub, b);
      int nz = nz_[0];
      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_[0] = 1;
      task.solvewithbasis(0, nz_, bsub, b);
      nz = nz_[0];

      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]] );
      }
    }
  }
}