17 List of examples

List of examples shipped in the distribution of Optimizer API for .NET:

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

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

blas_lapack.cs

Listing 17.1 blas_lapack.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      blas_lapack.cs

   Purpose: To demonstrate how to call BLAS/LAPACK routines for whose MOSEK provides simplified interfaces.
*/
using System;

namespace mosek.example
{
  public class blas_lapack
  {
    public static void Main ()
    {
      const int n = 3, m = 2, k = 2;

      double alpha = 2.0, beta = 0.5;
      double[] x = {1.0, 1.0, 1.0};
      double[] y = {1.0, 2.0, 3.0};
      double[] z = {1.0, 1.0};

      /*A has m=2 rows and k=3 cols*/
      double[] A = {1.0, 1.0, 2.0, 2.0, 3.0, 3.0};
      /*B has k=3 rows and n=3 cols*/
      double[] B = {1.0, 1.0, 1.0,
                    1.0, 1.0, 1.0,
                    1.0, 1.0, 1.0
                   };
      double[] C = {1.0, 2.0, 3.0,
                    4.0, 5.0, 6.0
                   };

      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;


      using (mosek.Env env = new mosek.Env())
      {
        /* BLAS routines */

        try
        {

          env.dot(n, x, y, out 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)
        {
          Console.WriteLine (e.Code);
          Console.WriteLine (e);
        }
        finally
        {
          if (env != null)  env.Dispose ();
        }
      }
    }
  }
}

callback.cs

Listing 17.2 callback.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      callback.cs

   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. 
*/
using mosek;
using System;

namespace mosek.example
{
  class myCallback : mosek.DataCallback
  {
    double maxtime;
    
    public myCallback(double maxtime_)
    {
      maxtime = maxtime_;
    }
    
    public override int callback( callbackcode caller, 
                                  double[]     douinf,
                                  int[]        intinf,
                                  long[]       lintinf )
    {
      double opttime = 0.0;
      int itrn;
      double pobj, dobj, stime;

      switch (caller)
      {
        case callbackcode.begin_intpnt:
          Console.WriteLine("Starting interior-point optimizer");
          break;
        case callbackcode.intpnt:
          itrn    = intinf[(int) iinfitem.intpnt_iter      ];
          pobj    = douinf[(int) dinfitem.intpnt_primal_obj];
          dobj    = douinf[(int) dinfitem.intpnt_dual_obj  ];
          stime   = douinf[(int) dinfitem.intpnt_time      ];
          opttime = douinf[(int) dinfitem.optimizer_time   ];
          
          Console.WriteLine("Iterations: {0,-3}",itrn);
          Console.WriteLine("  Elapsed: Time: {0,6:F2}({1:F2})",opttime,stime);
          Console.WriteLine("  Primal obj.: {0,-18:E6}  Dual obj.: {1,018:E6}e",pobj,dobj);
          break;
        case callbackcode.end_intpnt:
          Console.WriteLine("Interior-point optimizer finished.");
          break;
        case callbackcode.begin_primal_simplex:
          Console.WriteLine("Primal simplex optimizer started.");
          break;
        case callbackcode.update_primal_simplex:
          itrn    = intinf[(int) iinfitem.sim_primal_iter  ];
          pobj    = douinf[(int) dinfitem.sim_obj          ];
          stime   = douinf[(int) dinfitem.sim_time         ];
          opttime = douinf[(int) dinfitem.optimizer_time   ];
          
          Console.WriteLine("Iterations: {0,-3}}", itrn);
          Console.WriteLine("  Elapsed time: {0,6:F2}({1:F2})",opttime,stime);
          Console.WriteLine("  Obj.: {0,-18:E6}", pobj );
          break;
        case callbackcode.end_primal_simplex:
          Console.WriteLine("Primal simplex optimizer finished.");
          break;
        case callbackcode.begin_dual_simplex:
          Console.WriteLine("Dual simplex optimizer started.");
          break;
        case callbackcode.update_dual_simplex:
          itrn    = intinf[(int) iinfitem.sim_dual_iter    ];
          pobj    = douinf[(int) dinfitem.sim_obj          ];
          stime   = douinf[(int) dinfitem.sim_time         ];
          opttime = douinf[(int) dinfitem.optimizer_time   ];
          Console.WriteLine("Iterations: {0,-3}}", itrn);
          Console.WriteLine("  Elapsed time: {0,6:F2}({1:F2})",opttime,stime);
          Console.WriteLine("  Obj.: {0,-18:E6}", pobj );
          break;
        case callbackcode.end_dual_simplex:
          Console.WriteLine("Dual simplex optimizer finished.");
          break;
        case callbackcode.begin_bi:
          Console.WriteLine("Basis identification started.");
          break;
        case  callbackcode.end_bi:
          Console.WriteLine("Basis identification finished.");
          break;
        default:
          break;
      }

      if (opttime >= maxtime)
        // mosek is spending too much time. Terminate it.
        return 1;
                
      return 0;
    }
  }

  class myStream : Stream
  {
    public myStream () : base() { }
    
    public override void streamCB (string msg)
    {
      Console.Write ("{0}",msg);
    }
  }

  public class callback
  {
    public static void Main(string[] args)
    {
      string filename = "../data/25fv47.mps";
      string slvr     = "intpnt";

      if (args.Length < 2)
      {
          Console.WriteLine("Usage: callback ( psim | dsim | intpnt ) filename");
      }

      if (args.Length >= 1) slvr = args[0];
      if (args.Length >= 2) filename = args[1];

      using (Env env = new mosek.Env())
      {
        using (Task task = new Task(env,0,0))
        {
          task.readdata(filename);

          if (slvr == "psim")
            task.putintparam(iparam.optimizer, optimizertype.primal_simplex);
          else if (slvr == "dsim")
            task.putintparam(iparam.optimizer, optimizertype.dual_simplex);
          else if (slvr == "intpnt")
            task.putintparam(iparam.optimizer, optimizertype.intpnt);

          double maxtime = 0.06;
          task.set_InfoCallback(new myCallback(maxtime));
          task.optimize();

          task.solutionsummary(streamtype.msg);
        }
      }
    }
  }
}

ceo1.cs

Listing 17.3 ceo1.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      ceo1.cs

  Purpose:   Demonstrates how to solve a small conic exponential
  optimization problem using the MOSEK API.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class ceo1
  {
    public static void Main ()
    {
      const int numcon = 1;
      const int numvar = 3;

      // 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[3];

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream (mosek.streamtype.log, new msgclass (""));

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

          /* Set up 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);

          /* Define the exponential cone */
          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);
          task.optimize();

          // Print a summary containing information
          // about the solution for debugging purposes
          task.solutionsummary(mosek.streamtype.msg);

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

          double[] xx  = new double[numvar];

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

          switch (solsta)
          {
            case mosek.solsta.optimal:
              Console.WriteLine ("Optimal primal solution\n");
              for (int j = 0; j < numvar; ++j)
                Console.WriteLine ("x[{0}]: {1}", j, xx[j]);
              break;
            case mosek.solsta.dual_infeas_cer:
            case mosek.solsta.prim_infeas_cer:
              Console.WriteLine("Primal or dual infeasibility.\n");
              break;
            case mosek.solsta.unknown:
              Console.WriteLine("Unknown solution status.\n");
              break;
            default:
              Console.WriteLine("Other solution status");
              break;
          }
        }
      }
    }
  }
}

concurrent.cs

Listing 17.4 concurrent.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      concurrent.cs

   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.
*/
using System.Threading.Tasks;
using System;

namespace mosek.example
{
  public class concurrent
  {
    /** 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 true if some optimizer returned without error. In this case
        ``firstOK`` is the index of the first task that returned
        with rescode == ok. Whether or not this is the task firstOK contains the
        most valuable answer, is for the caller to decide.
     */
    public static bool optimize(mosek.Task[]    tasks,
                                mosek.rescode[] res,
                                mosek.rescode[] trm,
                                out int         firstOK)
    {
      var n = tasks.Length;
      var jobs = new System.Threading.Tasks.Task[n];
      int firstStop = -1;

      // Set a callback function 
      var cb = new CallbackProxy();
      for (var i = 0; i < n; ++i)
        tasks[i].set_Progress(cb);
      
      // Initialize
      for (var i = 0; i < n; ++i) 
      {
        res[i] = mosek.rescode.err_unknown;
        trm[i] = mosek.rescode.err_unknown;
      }

      // Start parallel optimizations, one per task
      for (var i = 0; i < n; ++i)
      {
        int num = i;
        jobs[i] = System.Threading.Tasks.Task.Factory.StartNew( () => {
          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) firstStop = num;
              cb.Stop = true;
            }
          }
        } );
      }

      // Join all threads
      foreach (var j in jobs)
        j.Wait();

      // For debugging, print res and trm codes for all optimizers
      for (var i = 0; i < n; ++i)
        Console.WriteLine("Optimizer  {0}  res {1}   trm {2}", i, res[i], trm[i]);

      firstOK = firstStop;
      return cb.Stop;
    }


    /** 
        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, 
                                          int[]                 optimizers,
                                          out mosek.Task        winTask,
                                          out mosek.rescode     winTrm,
                                          out mosek.rescode     winRes)
    {
      var n = optimizers.Length;
      var tasks = new mosek.Task[n];
      var res   = new mosek.rescode[n];
      var trm   = new mosek.rescode[n];

      // Clone tasks and choose various optimizers
      for (var i = 0; i < n; ++i)
      {
        tasks[i] = new mosek.Task(task);
        tasks[i].putintparam(mosek.iparam.optimizer, optimizers[i]);
      }

      // Solve tasks in parallel
      bool success;
      int firstOK;
      success = optimize(tasks, res, trm, out firstOK);

      if (success) 
      {
        winTask  = tasks[firstOK]; 
        winTrm   = trm[firstOK]; 
        winRes   = res[firstOK];
        return firstOK;
      }
      else
      {
        winTask  = null; 
        winTrm   = 0; 
        winRes   = 0;        
        return -1;
      }
    }

    /** 
        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,
                                             out mosek.Task        winTask,
                                             out mosek.rescode     winTrm,
                                             out mosek.rescode     winRes)
    {
      var n = seeds.Length;
      var tasks = new mosek.Task[n];
      var res   = new mosek.rescode[n];
      var trm   = new mosek.rescode[n];

      // Clone tasks and choose various seeds for the optimizer
      for (var i = 0; i < n; ++i)
      {
        tasks[i] = new mosek.Task(task);
        tasks[i].putintparam(mosek.iparam.mio_seed, seeds[i]);
      }

      // Solve tasks in parallel
      bool success;
      int firstOK;
      success = optimize(tasks, res, trm, out firstOK);

      if (success) 
      {
        // 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 (var i = 0; i < n; ++i)
          Console.WriteLine("{0}   {1}   ", i, tasks[i].getprimalobj(mosek.soltype.itg));

        for (var 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  = tasks[bestPos]; 
          winTrm   = trm[bestPos]; 
          winRes   = res[bestPos];
          return bestPos;
        }
      }

      winTask  = null; 
      winTrm   = 0; 
      winRes   = 0;        
      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)
    {
      using (var env = new mosek.Env())
      {
        using (var task = new mosek.Task(env))
        {
          if (argv.Length >= 1) 
          {
            task.readdata(argv[0]);
          }
          else
          {
            task.readdata("../data/25fv47.mps");
          }

          mosek.rescode res, trm;
          mosek.Task    t;
          int           idx;
          int           numint;
          task.getnumintvar(out numint);

          // Optional time limit
          if (argv.Length >= 2) 
          {
            double timeLimit = double.Parse(argv[1]);
            task.putdouparam(mosek.dparam.optimizer_max_time, timeLimit);
          }

          if (numint == 0) 
          {
            /* If the problem is continuous
               optimize it with three continuous optimizers.
              (Simplex will fail for non-linear problems)
            */
            int[] optimizers = { 
              mosek.optimizertype.conic,
              mosek.optimizertype.dual_simplex,
              mosek.optimizertype.primal_simplex
            };

            idx = optimizeconcurrent(task, optimizers, out t, out trm, out res);
          }          
          else
          {
            /* Mixed-integer problem.
               Try various seeds.
            */
            int[] seeds = { 42, 13, 71749373 };

            idx = optimizeconcurrentMIO(task, seeds, out t, out trm, out res);
          }          

          // Check results and print the best answer
          if (idx >= 0) 
          {
            Console.WriteLine("Result from optimizer with index {0}: res {1}  trm {2}", idx, res, trm);
            t.set_Stream(mosek.streamtype.log, new msgclass(""));
            t.optimizersummary(mosek.streamtype.log);
            t.solutionsummary(mosek.streamtype.log);
          }
          else 
          {
            Console.WriteLine("All optimizers failed.");
          }
        }
      }
    }


    /**
       Defines a Mosek callback function whose only function
       is to indicate if the optimizer should be stopped.
     */
    private class CallbackProxy : mosek.Progress
    {
      private bool stop;
      public CallbackProxy()
      {
        stop = false;
      }

      public override int progressCB(mosek.callbackcode caller)
      {
        // Return non-zero implies terminate the optimizer
        return stop ? 1 : 0;
      }

      public bool Stop
      {
        get { return stop; }
        set { stop = value; }
      }
    }

    /**
       A simple stream handler.
     */
    class msgclass : mosek.Stream
    {
      public msgclass (string prfx) { }
      public override void streamCB (string msg)
      {
        Console.Write("{0}", msg);
      }
    }
  }
}

cqo1.cs

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

  File:      cqo1.cs

  Purpose:   Demonstrates how to solve a small conic qaudratic
  optimization problem using the MOSEK API.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class cqo1
  {
    public static void Main ()
    {
      const int numcon = 1;
      const int numvar = 6;

      // 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 = {
              new double[] {1.0},
              new double[] {1.0},
              new double[] {2.0}
      };

      int[][] asub = {
            new int[] {0},
            new int[] {0},
            new int[] {0}
      };

      int[] csub = new int[3];

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream (mosek.streamtype.log, new msgclass (""));

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

          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);
          task.optimize();
          // Print a summary containing information
          //   about the solution for debugging purposes
          task.solutionsummary(mosek.streamtype.msg);

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

          double[] xx  = new double[numvar];

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

          switch (solsta)
          {
            case mosek.solsta.optimal:
              Console.WriteLine ("Optimal primal solution\n");
              for (int j = 0; j < numvar; ++j)
                Console.WriteLine ("x[{0}]: {1}", j, xx[j]);
              break;
            case mosek.solsta.dual_infeas_cer:
            case mosek.solsta.prim_infeas_cer:
              Console.WriteLine("Primal or dual infeasibility.\n");
              break;
            case mosek.solsta.unknown:
              Console.WriteLine("Unknown solution status.\n");
              break;
            default:
              Console.WriteLine("Other solution status");
              break;
          }
        }
      }
    }
  }
}

feasrepairex1.cs

Listing 17.6 feasrepairex1.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      feasrepairex1.cs

  Purpose:    To demonstrate how to use the MSK_relaxprimal function to
              locate the cause of an infeasibility.

  Syntax: On command line
          feasrepairex1 feasrepair.lp
          feasrepair.lp is located in mosek\<version>\tools\examples.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    public msgclass () {}

    public override void streamCB (string msg)
    {
      Console.Write ("{1}", msg);
    }
  }

  public class feasrepairex1
  {
    public static void Main (String[] args)
    {
      string filename = "../data/feasrepair.lp";
      if (args.Length >= 1) filename = args[0];

      using (mosek.Env env = new mosek.Env())
      {
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          task.set_Stream (mosek.streamtype.log, new msgclass());

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

          Console.WriteLine("Minimized sum of violations = %{0}", sum_viol);

          task.optimize();
          task.solutionsummary(mosek.streamtype.msg);
        }
      }
    }
  }
}

gp1.cs

Listing 17.7 gp1.cs Click here to download.
//
//   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
//   File:      gp1.cs
//
//   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
//
using System;
using mosek;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class gp1
  {
    // Since the value of infinity is ignored, we define it solely
    // for symbolic purposes
    static 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)};

      using (Env env = new Env())
      {
        using (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 msgclass (""));

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

      Console.WriteLine("h={0:f4} w={1:f4} d={2:f4}", hwd[0], hwd[1], hwd[2]);
    }
  }
}

lo1.cs

Listing 17.8 lo1.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      lo1.cs

   Purpose:   Demonstrates how to solve small linear
              optimization problem using the MOSEK C# API.
 */

using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class lo1
  {
    public static void Main ()
    {
      const int numcon = 3;
      const int numvar = 4;

      // 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 = { 
            new int[] {0, 1},
            new int[] {0, 1, 2},
            new int[] {0, 1},
            new int[] {1, 2}
      };
      double[][] aval = { 
               new double[] {3.0, 2.0},
               new double[] {1.0, 1.0, 2.0},
               new double[] {2.0, 3.0},
               new double[] {1.0, 3.0}
      };

      mosek.boundkey[] bkc  = {mosek.boundkey.fx,
                               mosek.boundkey.lo,
                               mosek.boundkey.up
                              };

      double[] blc  = {30.0,
                       15.0,
                       -infinity
                      };
      double[] buc  = {30.0,
                       +infinity,
                       25.0
                      };
      mosek.boundkey[]  bkx  = {mosek.boundkey.lo,
                                mosek.boundkey.ra,
                                mosek.boundkey.lo,
                                mosek.boundkey.lo
                               };
      double[]  blx  = {0.0,
                        0.0,
                        0.0,
                        0.0
                       };
      double[]  bux  = { +infinity,
                         10.0,
                         +infinity,
                         +infinity
                       };

      try
      {
        // Make mosek environment.
        using (mosek.Env env = new mosek.Env())
        {
          // Create a task object.
          using (mosek.Task task = new mosek.Task(env, 0, 0))
          {
            // Directs the log task stream to the user specified
            // method msgclass.streamCB
            task.set_Stream (mosek.streamtype.log, new msgclass (""));

            // Append 'numcon' empty constraints.
            // The constraints will initially have no bounds.
            task.appendcons(numcon);

            // Append 'numvar' variables.
            // The variables will initially be fixed at zero (x=0).
            task.appendvars(numvar);

            for (int j = 0; j < numvar; ++j)
            {
              // Set the linear term c_j in the objective.
              task.putcj(j, c[j]);

              // Set the bounds on variable j.
              // blx[j] <= x_j <= bux[j]
              task.putvarbound(j, bkx[j], blx[j], bux[j]);

              // Input column j of A
              task.putacol(j,                     /* Variable (column) index.*/
                           asub[j],               /* Row index of non-zeros in column j.*/
                           aval[j]);              /* Non-zero Values of column j. */
            }

            // Set the bounds on constraints.
            // blc[i] <= constraint_i <= buc[i]
            for (int i = 0; i < numcon; ++i)
              task.putconbound(i, bkc[i], blc[i], buc[i]);

            // Input the objective sense (minimize/maximize)
            task.putobjsense(mosek.objsense.maximize);

            // Solve the problem
            task.optimize();

            // Print a summary containing information
            // about the solution for debugging purposes
            task.solutionsummary(mosek.streamtype.msg);

            // Get status information about the solution
            mosek.solsta solsta;

            task.getsolsta(mosek.soltype.bas, out solsta);

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

                Console.WriteLine ("Optimal primal solution\n");
                for (int j = 0; j < numvar; ++j)
                  Console.WriteLine ("x[{0}]: {1}", j, xx[j]);
                break;
              case mosek.solsta.dual_infeas_cer:
              case mosek.solsta.prim_infeas_cer:
                Console.WriteLine("Primal or dual infeasibility certificate found.\n");
                break;
              case mosek.solsta.unknown:
                Console.WriteLine("Unknown solution status.\n");
                break;
              default:
                Console.WriteLine("Other solution status");
                break;
            }
          }
        }
      }
      catch (mosek.Exception e) {
        mosek.rescode res = e.Code;
        Console.WriteLine("Response code {0}\nMessage       {1}", res, e.Message);
      }
    }
  }
}

lo1.vb

Listing 17.9 lo1.vb Click here to download.
'   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
'
'   File:    lo1.vb
'
'   Purpose: Demonstrates how to solve small linear
'            optimization problem using the MOSEK .net API.
'
Imports System, mosek


Public Class MsgTest
    Inherits mosek.Stream
    Dim name As String

    Public Sub New(ByVal e As mosek.Env, ByVal n As String)
        '        MyBase.New ()
        name = n
    End Sub

    Public Overrides Sub streamCB(ByVal msg As String)
        Console.Write("{0}: {1}", name, msg)
    End Sub
End Class

Module Module1
    Sub Main()
        Dim infinity As Double = 0.0
        Dim numcon As Integer = 3
        Dim numvar As Integer = 4

        Dim bkc As boundkey() = {boundkey.fx, boundkey.lo, boundkey.up}
        Dim bkx As boundkey() = {boundkey.lo, boundkey.ra, boundkey.lo, boundkey.lo}
        Dim asub(numvar)() As Integer
        asub(0) = New Integer() {0, 1}
        asub(1) = New Integer() {0, 1, 2}
        asub(2) = New Integer() {0, 1}
        asub(3) = New Integer() {1, 2}

        Dim blc As Double() = {30.0, 15.0, -infinity}
        Dim buc As Double() = {30.0, infinity, 25.0}
        Dim cj As Double() = {3.0, 1.0, 5.0, 1.0}
        Dim blx As Double() = {0.0, 0.0, 0.0, 0, 0}
        Dim bux As Double() = {infinity, 10, infinity, infinity}

        Dim aval(numvar)() As Double
        aval(0) = New Double() {3.0, 2.0}
        aval(1) = New Double() {1.0, 1.0, 2.0}
        aval(2) = New Double() {2.0, 3.0}
        aval(3) = New Double() {1.0, 3.0}

        Dim xx As Double() = {0, 0, 0, 0, 0}

        Dim msg As MsgTest
        Dim i As Integer
        Dim j As Integer

        Try
            Using env As New mosek.Env()
                Using task As New mosek.task(env, 0, 0)
                    msg = New MsgTest(env, "msg")
                    task.set_Stream(streamtype.log, msg)

                    'Append 'numcon' empty constraints.
                    'The constraints will initially have no bounds. 
                    Call task.appendcons(numcon)

                    'Append 'numvar' variables.
                    ' The variables will initially be fixed at zero (x=0). 

                    Call task.appendvars(numvar)

                    For j = 0 To numvar - 1
                        'Set the linear term c_j in the objective.
                        Call task.putcj(j, cj(j))

                        ' Set the bounds on variable j.
                        'blx[j] <= x_j <= bux[j] 
                        Call task.putvarbound(j, bkx(j), blx(j), bux(j))
                        'Input column j of A 
                        Call task.putacol(j, asub(j), aval(j))
                    Next j

                    ' for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    For i = 0 To numcon - 1
                        Call task.putconbound(i, bkc(i), blc(i), buc(i))
                    Next i

                    Call task.putobjsense(mosek.objsense.maximize)

                    Call task.optimize()
                    ' Print a summary containing information
                    '   about the solution for debugging purposes
                    Call task.solutionsummary(mosek.streamtype.msg)

                    Dim solsta As mosek.solsta
                    ' Get status information about the solution 

                    Call task.getsolsta(mosek.soltype.bas, solsta)

                    task.getxx(soltype.bas, xx)

                    For j = 0 To numvar - 1
                        Console.WriteLine("x[{0}]:{1}", j, xx(j))
                    Next

                    Console.WriteLine("Finished optimization")
                End Using
            End Using
        Catch e As mosek.Exception
            Console.WriteLine("MosekException caught, {0}", e)
            Throw (e)
        End Try
    End Sub
End Module

lo2.cs

Listing 17.10 lo2.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:    lo2.cs

   Purpose: Demonstrates how to solve small linear
            optimization problem using the MOSEK C# API.
 */

using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class lo2
  {
    public static void Main ()
    {
      const int numcon = 3;
      const int numvar = 4;

      // 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 = {
            new int[] {0, 1, 2},
            new int[] {0, 1, 2, 3},
            new int[] {1, 3}
      };
      double[][] aval = {
            new double[] {3.0, 1.0, 2.0},
            new double[] {2.0, 1.0, 3.0, 1.0},
            new double[] {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
                       };

      mosek.Task task = null;
      mosek.Env  env  = null;

      double[] xx  = new double[numvar];

      try
      {
        // Make mosek environment.
        env  = new mosek.Env ();
        // Create a task object linked with the environment env.
        task = new mosek.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 msgclass (""));

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

        task.putobjsense(mosek.objsense.maximize);
        task.optimize();

        // Print a summary containing information
        //   about the solution for debugging purposes
        task.solutionsummary(mosek.streamtype.msg);

        mosek.solsta solsta;
        /* Get status information about the solution */
        task.getsolsta(mosek.soltype.bas, out solsta);
        task.getxx(mosek.soltype.bas, // Basic solution.
                   xx);

        switch (solsta)
        {
          case mosek.solsta.optimal:
            Console.WriteLine ("Optimal primal solution\n");
            for (int j = 0; j < numvar; ++j)
              Console.WriteLine ("x[{0}]: {1}", j, xx[j]);
            break;
          case mosek.solsta.dual_infeas_cer:
          case mosek.solsta.prim_infeas_cer:
            Console.WriteLine("Primal or dual infeasibility.\n");
            break;
          case mosek.solsta.unknown:
            Console.WriteLine("Unknown solution status.\n");
            break;
          default:
            Console.WriteLine("Other solution status");
            break;
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }
      finally
      {
        if (task != null) task.Dispose ();
        if (env  != null)  env.Dispose ();
      }
    }
  }
}

logistic.cs

Listing 17.11 logistic.cs Click here to download.
////
//  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
//
//  File:      logistic.cs
//
// Purpose: Implements logistic regression with regulatization.
//
//          Demonstrates using the exponential cone and log-sum-exp in Optimizer API.

using System;
using mosek;

namespace mosek.example
{
  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, 
                                              bool[]     y,
                                              double     lamb)
    {
      int n = X.GetLength(0);
      int d = X.GetLength(1);       // num samples, dimension

      using (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];
      bool[] Y     = new bool[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++)
        Console.WriteLine(theta[i]);
    }
  }
}

mico1.cs

Listing 17.12 mico1.cs Click here to download.
/*
   Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File :      mico1.cs

   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
*/
using System;

namespace mosek.example
{
  public class MsgClass : mosek.Stream
  {
    public MsgClass () {}
    public override void streamCB (string msg)
    {
      Console.Write ("{0}", msg);
    }
  }

  public class mico1
  {
    public static void Main ()
    {
      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.streamCB
      MsgClass task_msg_obj = new MsgClass ();
      task.set_Stream (mosek.streamtype.log, task_msg_obj);

      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);
      Console.WriteLine ("x = {0}, y = {1}", xx[0], xx[1]);
    }
  }
}

milo1.cs

Listing 17.13 milo1.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:    milo1.cs

   Purpose:  Demonstrates how to solve a small mixed
             integer linear optimization problem using the MOSEK C# API.
 */

using System;

namespace mosek.example
{
  public class MsgClass : mosek.Stream
  {
    public MsgClass ()
    {
      /* Construct the object */
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}", msg);
    }
  }

  public class milo1
  {
    public static void Main ()
    {
      const int numcon = 2;
      const int numvar = 2;

      // 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    = { new int[]  {0,   1},  new int[] {0,    1}   };
      double[][] aval = { new double[] {50.0, 3.0}, new double[] {31.0, -2.0} };

      double[] xx  = new double[numvar];

      mosek.Env env = null;
      mosek.Task task = null;

      try
      {
        // Make mosek environment.
        env  = new mosek.Env ();
        // Create a task object linked with the environment env.
        task = new mosek.Task (env, numcon, numvar);
        // Directs the log task stream to the user specified
        // method task_msg_obj.streamCB
        MsgClass task_msg_obj = new MsgClass ();
        task.set_Stream (mosek.streamtype.log, task_msg_obj);

        /* 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]);
          /* 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);
        task.putobjsense(mosek.objsense.maximize);

        /* Set max solution time */
        task.putdouparam(mosek.dparam.mio_max_time, 60.0);

        task.optimize();


        // Print a summary containing information
        //   about the solution for debugging purposes
        task.solutionsummary(mosek.streamtype.msg);

        mosek.solsta solsta;
        /* Get status information about the solution */
        task.getsolsta(mosek.soltype.itg, out solsta);
        task.getxx(mosek.soltype.itg, // Integer solution.
                   xx);

        switch (solsta)
        {
          case mosek.solsta.optimal:
            Console.WriteLine ("Optimal primal solution\n");
            for (int j = 0; j < numvar; ++j)
              Console.WriteLine ("x[{0}]:", xx[j]);
            break;
          case mosek.solsta.prim_feas:
            Console.WriteLine ("Feasible primal solution\n");
            for (int j = 0; j < numvar; ++j)
              Console.WriteLine ("x[{0}]:", xx[j]);
            break;
          case mosek.solsta.unknown:
            mosek.prosta prosta;
            task.getprosta(mosek.soltype.itg, out prosta);
            switch (prosta)
            {
              case mosek.prosta.prim_infeas_or_unbounded:
                Console.WriteLine("Problem status Infeasible or unbounded");
                break;
              case mosek.prosta.prim_infeas:
                Console.WriteLine("Problem status Infeasible.");
                break;
              case mosek.prosta.unknown:
                Console.WriteLine("Problem status unknown.");
                break;
              default:
                Console.WriteLine("Other problem status.");
                break;
            }
            break;
          default:
            Console.WriteLine("Other solution status");
            break;
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }
      finally
      {
        if (task != null) task.Dispose ();
        if (env  != null)  env.Dispose ();
      }
    }
  }
}

mioinitsol.cs

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

   File:      mioinitsol.cs

   Purpose:   Demonstrates how to solve a MIP with a start guess.

 */
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class mioinitsol
  {
    public static void Main ()
    {
      mosek.Env env = null;
      mosek.Task task = null;
      // Since the value infinity is never used, we define
      // 'infinity' symbolic purposes only
      double infinity = 0;

      int numvar = 4;
      int numcon = 1;
      int NUMINTVAR = 3;

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

      try
      {
        // Make mosek environment.
        env  = new mosek.Env ();
        // Create a task object linked with the environment env.
        task = new mosek.Task (env, numcon, numvar);
        // Directs the log task stream to the user specified
        // method task_msg_obj.streamCB
        task.set_Stream (mosek.streamtype.log, new msgclass ("[task]"));
        task.inputdata(numcon, numvar,
                       c,
                       0.0,
                       ptrb,
                       ptre,
                       asub,
                       aval,
                       bkc,
                       blc,
                       buc,
                       bkx,
                       blx,
                       bux);

        for (int j = 0 ; j < NUMINTVAR ; ++j)
          task.putvartype(intsub[j], mosek.variabletype.type_int);
        task.putobjsense(mosek.objsense.maximize);

        // Assign values to integer variables.
        // We only set a slice of xx
        double[] values = {1.0, 1.0, 0.0};
        task.putxxslice(mosek.soltype.itg, 0, 3, values);

        try
        {
          task.optimize();
          task.solutionsummary(mosek.streamtype.log);
        }
        catch (mosek.Warning w)
        {
          Console.WriteLine("Mosek warning:");
          Console.WriteLine (w.Code);
          Console.WriteLine (w);
        }
        
        task.getxx(mosek.soltype.itg, xx);

        Console.WriteLine("Solution:");
        for (int j = 0; j < numvar; ++j)
          Console.WriteLine ("x[{0}]:{1}", j, xx[j]);

        // Was the initial solution used?
        int constr = task.getintinf(mosek.iinfitem.mio_construct_solution);
        double constrVal = task.getdouinf(mosek.dinfitem.mio_construct_solution_obj);
        Console.WriteLine("Initial solution utilization: " + constr);
        Console.WriteLine("Initial solution objective: " +  constrVal);
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }

      if (task != null) task.Dispose ();
      if (env  != null)  env.Dispose ();
    }
  }
}

modelLib.cs

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

  File :      modelLib.cs

  Purpose: Library of simple building blocks in Mosek Optimizer API.
*/
using System;

namespace mosek.example 
{
  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 n, int[] x) {
      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), n-1, x);
      }
    }

    // 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), 5, new int[]{p, p+1, p+2, p+3, p+4});
      msk_semicontinuous(task, y, 1.1, 2.2);
      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.optimize();

      double[] xx = new double[task.getnumvar()];
      task.getxx(soltype.itr, xx);
      Console.Write("x={0} y={1} obj={2}\n", xx[x], xx[y], task.getprimalobj(soltype.itr));
    }

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

opt_server_async.cs

Listing 17.16 opt_server_async.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:       opt_server_async.cs

   Purpose :   Demonstrates how to use MOSEK OptServer
               to solve optimization problem asynchronously

*/
using System;
using System.Threading;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    public override void streamCB (string msg)
    {
      Console.Write ("{0}", msg);
    }
  }

  public class opt_server_async
  {
    public static void Main (string[] args)
    {
      if (args.Length == 0)
      {
        Console.WriteLine ("Missing argument, syntax is:");
        Console.WriteLine ("  opt_server inputfile host port numpolls");
      }
      else
      {

        string inputfile = args[0];
        string host      = args[1];
        string port      = args[2];
        int numpolls     = Convert.ToInt32(args[3]);

        using (mosek.Env env = new mosek.Env())
        {

          string token;

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

          using (mosek.Task task = new mosek.Task(env))
          {
            task.readdata (inputfile);
            task.set_Stream (mosek.streamtype.log, new msgclass ());
            Console.WriteLine("Starting polling loop...");

            int i = 0;

            while ( true )
            {
              Thread.Sleep(500);
              Console.WriteLine("poll {0}...\n", i);

              mosek.rescode trm;
              mosek.rescode resp;

              int respavailable = task.asyncpoll( host,
                                                  port,
                                                  token,
                                                  out resp,
                                                  out trm);


              Console.WriteLine("polling done");

              if (respavailable != 0)
              {
                Console.WriteLine("solution available!");

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

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

              if (i == numpolls)
              {
                Console.WriteLine("max num polls reached, stopping host.");
                task.asyncstop (host, port, token);
                break;
              }
              i++;
            }

          }
        }
      }
    }
  }
}

opt_server_sync.cs

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

  File:    opt_server_sync.cs

  Purpose :   Demonstrates how to use MOSEK OptServer
              to solve optimization problem synchronously
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    public override void streamCB (string msg)
    {
      Console.Write ("{0}", msg);
    }
  }

  public class simple
  {
    public static void Main (string[] args)
    {
      if (args.Length == 0)
      {
        Console.WriteLine ("Missing arguments, syntax is:");
        Console.WriteLine ("  opt_server_sync inputfile host port");
      }
      else
      {
        String inputfile = args[0];
        String host      = args[1];
        String port      = args[2];

        mosek.rescode trm;

        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            task.set_Stream (mosek.streamtype.log, new msgclass ());

            task.readdata (inputfile);

            task.optimizermt (host, port, out trm);

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

parallel.cs

Listing 17.18 parallel.cs Click here to download.
/*
  File : parallel.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Demonstrates parallel optimization
*/
using System.Threading.Tasks;
using System;

namespace mosek.example
{
  public class Parallel
  {
    /** Takes a list of tasks and optimizes them in parallel threads. The
        response code and termination ocde from each optimization is
        stored in ``res`` and ``trm``.
     */
    public static void paropt(mosek.Task[]    tasks,
                              mosek.rescode[] res,
                              mosek.rescode[] trm)
    {
      var n = tasks.Length;
      var jobs = new System.Threading.Tasks.Task[n];
     
      // Initialize
      for (var i = 0; i < n; ++i) 
      {
        res[i] = mosek.rescode.err_unknown;
        trm[i] = mosek.rescode.err_unknown;
      }

      // Start parallel optimizations, one per task
      for (var i = 0; i < n; ++i)
      {
        int num = i;
        jobs[i] = System.Threading.Tasks.Task.Factory.StartNew( () => {
          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;
          }
        } );
      }

      // Join all threads
      foreach (var j in jobs)
        j.Wait();
    }

    /** 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];
  
      using (var 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);
        }

        paropt(t, res, trm);

        for(int i = 0; i < n; i++) 
          Console.WriteLine("Task  {0}  res {1}   trm {2}   obj_val  {3}  time {4}", 
            i, 
            res[i], 
            trm[i],  
            t[i].getdouinf(mosek.dinfitem.intpnt_primal_obj),
            t[i].getdouinf(mosek.dinfitem.optimizer_time));
      }
    }
  }
}

parameters.cs

Listing 17.19 parameters.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      parameters.cs

 Purpose: Demonstrates a very simple example about how to get/set
 parameters with MOSEK .NET API

*/

using System;

namespace mosek.example
{
  public class parameters
  {
    public static void Main()
    {
      using (mosek.Env env = new mosek.Env())
      {
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          Console.WriteLine("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);
          // ... without basis identification (integer parameter)
          task.putintparam(mosek.iparam.intpnt_basis, mosek.basindtype.never);
          // 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) 
          {
            Console.WriteLine("Wrong parameter value"); 
          }


          double param = task.getdouparam(mosek.dparam.intpnt_co_tol_rel_gap);
          Console.WriteLine("Current value for parameter intpnt_co_tol_rel_gap = " + param);

          /* Define and solve an optimization problem here */
          /* task.optimize() */
          /* After optimization: */

          Console.WriteLine("Get MOSEK information items");

          double tm = task.getdouinf(mosek.dinfitem.optimizer_time);
          int  iter = task.getintinf(mosek.iinfitem.intpnt_iter);     
           
          Console.WriteLine("Time: " + tm);
          Console.WriteLine("Iterations: " + iter);         
        }
      }
    }
  }
}

portfolio_1_basic.cs

Listing 17.20 portfolio_1_basic.cs Click here to download.
/*
  File : portfolio_1_basic.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Implements a basic portfolio optimization model.
*/
using System;

namespace mosek.example
{
  /* Log handler class */
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx) { prefix = prfx; }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class portfolio_1_basic
  {
    public static void Main (String[] args)
    {
      const int n = 3;

      // Since the value infinity is never used, we define
      // 'infinity' for symbolic purposes only
      double infinity = 0.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;

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream
          task.set_Stream(mosek.streamtype.log, new msgclass (""));

          // 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];

          Console.WriteLine("\nExpected return {0:E} for gamma {1:E}", expret, xx[offsets]);
        }
      }
    }
  }
}

portfolio_2_frontier.cs

Listing 17.21 portfolio_2_frontier.cs Click here to download.
/*
  File : portfolio_2_frontier.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Implements a basic portfolio optimization model.
                 Computes points on the efficient frontier.
*/
using System;
namespace mosek.example 
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class portfolio_2_frontier
  {
    public static void Main (String[] args)
    {
      const int n = 3;

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

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream (mosek.streamtype.log, new msgclass (""));

          task.appendvars(numvar);
          task.appendcons(numcon);
          
          //Constraints.
          for (int i = 1; i <= n; ++i)
          {
            w += x0[i - 1];
            task.putconbound(i, mosek.boundkey.fx, 0.0, 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
          for(int i = 0; i < n; i++)
            task.putcj(offsetx + i, mu[i]);

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

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

            // x variable
            task.putvarbound(offsetx + i, mosek.boundkey.lo, 0.0, 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");

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

          Console.WriteLine("{0,-15}{1,-15}{2,-15}", "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;
            double[] xx = new double[numvar];

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

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

            Console.WriteLine("{0:E6}  {1:E}  {2:E}", alphas[k], expret, xx[offsets]);

          }
          Console.WriteLine("\n");
        }
      }
    }
  }
}

portfolio_3_impact.cs

Listing 17.22 portfolio_3_impact.cs Click here to download.
/*
  File : portfolio_3_impact.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Implements a basic portfolio optimization model
                 with transaction costs of type x^(3/2)
*/
using System;

namespace mosek.example {
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }
  
  public class portfolio_3_impact
  {
    public static void Main (String[] args)
    {
      const int n = 3;

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

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream(mosek.streamtype.log, new msgclass(""));

          //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, 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.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");

          // Quaadratic cone
          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);

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

          //task.writedata("dump.opf");
          /* Solve the problem */
          task.optimize();

          task.solutionsummary(mosek.streamtype.log);

          double expret = 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];

          Console.WriteLine("Expected return {0:E6} for gamma {1:E6}\n\n", expret, xx[offsets]);
        }
      }
    }
  }
}

portfolio_4_transcost.cs

Listing 17.23 portfolio_4_transcost.cs Click here to download.
/*
  File : portfolio_4_transcost.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Implements a basic portfolio optimization model
                 with fixed setup costs and transaction costs
                 as a mixed-integer problem.
*/
using System;

namespace mosek.example {
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }
  
  public class portfolio_4_transcost
  {
    public static void Main (String[] args)
    {
      const int n = 3;

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

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream(mosek.streamtype.log, new msgclass(""));

          //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, 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.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");

          // Quaadratic cone
          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);

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

          //task.writedata("dump.opf");
          /* Solve the problem */
          task.optimize();

          task.solutionsummary(mosek.streamtype.log);

          double expret = 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];

          Console.WriteLine("Expected return {0:E6} for gamma {1:E6}\n\n", expret, xx[offsets]);
        }
      }
    }
  }
}

portfolio_5_card.cs

Listing 17.24 portfolio_5_card.cs Click here to download.
/*
  File : portfolio_5_card.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Description :  Implements a basic portfolio optimization model
                 with cardinality constraints on number of assets traded.
*/
using System;

namespace mosek.example {
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }
  
  public class portfolio_5_card
  {
    // Since the value infinity is never used, we define
    // 'infinity' symbolic purposes only
    public static 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;

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream(mosek.streamtype.log, new msgclass(""));

          //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, 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.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");

          // Quaadratic cone
          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);

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

          //task.writedata("dump.opf");
          /* Solve the problem */
          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)
    {
      const 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;
        Console.Write("Bound:  {0:d}  x =  ", k);
        for(int i=0; i<n; i++)
        {
          Console.Write("{0:f5} ", xx[i]);
          expret += xx[i]*mu[i];
        }
        Console.WriteLine("  Return:  {0:f5}", expret);
      }      
    }
  }
}

pow1.cs

Listing 17.25 pow1.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      pow1.cs

  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
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class ceo1
  {
    public static void Main ()
    {
      const int numcon = 1;
      const int numvar = 6;

      // 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];

      // Make mosek environment.
      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream (mosek.streamtype.log, new msgclass (""));

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

          /* Set up 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 */
          task.appendcone(mosek.conetype.ppow, 0.2, new int[3] {0, 1, 3});
          task.appendcone(mosek.conetype.ppow, 0.4, new int[3] {2, 5, 4});
          
          task.putobjsense(mosek.objsense.maximize);
          task.optimize();

          // Print a summary containing information
          // about the solution for debugging purposes
          task.solutionsummary(mosek.streamtype.msg);

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

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

          switch (solsta)
          {
            case mosek.solsta.optimal:
              Console.WriteLine ("Optimal primal solution\n");
              for (int j = 0; j < 3; ++j)
                Console.WriteLine ("x[{0}]: {1}", j, xx[j]);
              break;
            case mosek.solsta.dual_infeas_cer:
            case mosek.solsta.prim_infeas_cer:
              Console.WriteLine("Primal or dual infeasibility.\n");
              break;
            case mosek.solsta.unknown:
              Console.WriteLine("Unknown solution status.\n");
              break;
            default:
              Console.WriteLine("Other solution status");
              break;
          }
        }
      }
    }
  }
}

qcqo1.cs

Listing 17.26 qcqo1.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      qcqo1.cs

   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
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class qcqo1
  {
    public static void Main ()
    {
      const double inf = 0.0; /* We don't actually need any value for infinity */

      const int numcon = 1;   /* Number of constraints.             */
      const int numvar = 3;   /* Number of variables.               */

      mosek.boundkey[]
      bkc = { mosek.boundkey.lo },
      bkx = { mosek.boundkey.lo, mosek.boundkey.lo, mosek.boundkey.lo };
      int[][]  asub  = { new int[] {0}, new int[] {0}, new int[] {0} };
      double[][] aval  = { new double[]{1.0}, new double[]{1.0}, new double[]{1.0} };

      double[]
      blc  = { 1.0 },
      buc  = { inf },
      c    = { 0.0, -1.0, 0.0 },
      blx  = { 0.0, 0.0, 0.0 },
      bux  = { inf, inf, inf },
      xx   = new double[numvar];
      try
      {
        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            task.set_Stream (mosek.streamtype.log, new msgclass (""));

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

            task.optimize();

            // Print a summary containing information
            //   about the solution for debugging purposes
            task.solutionsummary(mosek.streamtype.msg);

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

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

            switch (solsta)
            {
              case mosek.solsta.optimal:
                Console.WriteLine ("Optimal primal solution\n");
                for (int j = 0; j < numvar; ++j)
                  Console.WriteLine ("x[{0}]:", xx[j]);
                break;
              case mosek.solsta.dual_infeas_cer:
              case mosek.solsta.prim_infeas_cer:
                Console.WriteLine("Primal or dual infeasibility.\n");
                break;
              case mosek.solsta.unknown:
                Console.WriteLine("Unknown solution status.\n");
                break;
              default:
                Console.WriteLine("Other solution status");
                break;
            }
          }
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e);
        throw;
      }

    } /* Main */
  }
}

qo1.cs

Listing 17.27 qo1.cs Click here to download.
/*
  File : qo1.cs

  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  Purpose: Demonstrate how to solve a quadratic
           optimization problem using the MOSEK .NET API.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class qo1
  {
    public static void Main ()
    {
      // Since the value infinity is never used, we define
      // 'infinity' symbolic purposes only
      const double infinity = 0;
      const int numcon = 1;   /* Number of constraints.             */
      const int numvar = 3;   /* Number of variables.               */

      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  = { new int[] {0},   new int[] {0},   new int[] {0}};
      double[][] aval  = { new double[] {1.0}, new double[] {1.0}, new double[] {1.0}};

      mosek.Task task = null;
      mosek.Env  env = null;
      double[] xx  = new double[numvar];
      try
      {
        // Make mosek environment.
        env  = new mosek.Env ();
        // Create a task object linked with the environment env.
        task = new mosek.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 msgclass (""));

        /* 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.putobjsense(mosek.objsense.minimize);

        task.putqobj(qsubi, qsubj, qval);

        task.optimize();

        // Print a summary containing information
        //   about the solution for debugging purposes
        task.solutionsummary(mosek.streamtype.msg);

        mosek.solsta solsta;
        /* Get status information about the solution */
        task.getsolsta(mosek.soltype.itr, out solsta);
        switch (solsta)
        {
          case mosek.solsta.optimal:
            task.getxx(mosek.soltype.itr, // Interior point solution.
                       xx);

            Console.WriteLine ("Optimal primal solution\n");
            for (int j = 0; j < numvar; ++j)
              Console.WriteLine ("x[{0}]:", xx[j]);
            break;
          case mosek.solsta.dual_infeas_cer:
          case mosek.solsta.prim_infeas_cer:
            Console.WriteLine("Primal or dual infeasibility.\n");
            break;
          case mosek.solsta.unknown:
            Console.WriteLine("Unknown solution status.\n");
            break;
          default:
            Console.WriteLine("Other solution status");
            break;
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e);
        throw;
      }
      finally
      {
        if (task != null) task.Dispose ();
        if (env  != null)  env.Dispose ();
      }
    } /* Main */
  }
}

reoptimization.cs

Listing 17.28 reoptimization.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      reoptimization.cs

   Purpose:   Demonstrates how to solve a  linear
              optimization problem using the MOSEK API
              and modify and re-optimize the problem.
*/

using System;

namespace mosek.example
{
  public class reoptimization
  {
    public static void Main ()
    {
      // 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 = new int[numvar][];
      asub[0] = new int[] {0, 1, 2};
      asub[1] = new int[] {0, 1, 2};
      asub[2] = new int[] {0, 1, 2};

      double[][] aval   = new double[numvar][];
      aval[0] = new double[] { 2.0, 3.0, 2.0 };
      aval[1] = new double[] { 4.0, 2.0, 3.0 };
      aval[2] = new double[] { 3.0, 3.0, 2.0 };

      double[] xx  = new double[numvar];

      mosek.Task task = null;
      mosek.Env  env  = null;

      try
      {
        // Create mosek environment.
        env  = new mosek.Env ();
        // Create a task object linked with the environment env.
        task = new mosek.Task (env, numcon, numvar);

        /* Append the constraints. */
        task.appendcons(numcon);

        /* Append the variables. */
        task.appendvars(numvar);

        /* Put C. */
        task.putcfix(0.0);
        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]);
        }

        task.putobjsense(mosek.objsense.maximize);

        try
        {
          task.optimize();
        }
        catch (mosek.Warning w)
        {
          Console.WriteLine("Mosek warning:");
          Console.WriteLine (w.Code);
          Console.WriteLine (w);
        }

        task.getxx(mosek.soltype.bas, // Request the basic solution.
                   xx);
        
        for (int j = 0; j < numvar; ++j)
          Console.WriteLine ("x[{0}]:{1}", j, xx[j]);

        /********************** Make a change to the A matrix ********************/
        task.putaij(0, 0, 3.0);
        task.optimize();
        task.getxx(mosek.soltype.bas, // Request the basic solution.
                   xx);

        for (int j = 0; j < numvar; ++j)
          Console.WriteLine ("x[{0}]:{1}", j, xx[j]);

        /********************** Add a new variable ********************/
        /* Get index of new variable. */
        int varidx;
        task.getnumvar(out varidx);

        /* Append a new varaible x_3 to the problem */
        task.appendvars(1);
        numvar++;

        /* Set bounds on new varaible */
        task.putvarbound(varidx,
                         mosek.boundkey.lo,
                         0,
                         +infinity);

        /* Change objective */
        task.putcj(varidx, 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, /* column index */
                     acolsub,
                     acolval);
        /* Change optimizer to simplex free and reoptimize */
        task.putintparam(mosek.iparam.optimizer, mosek.optimizertype.free_simplex);
        task.optimize();

        xx = new double[numvar];
        task.getxx(mosek.soltype.bas, // Request the basic solution.
                   xx);

        for (int j = 0; j < numvar; ++j)
          Console.WriteLine ("x[{0}]:{1}", j, xx[j]);


        /********************** Add a new constraint ********************/
        /* Get index of new constraint */
        int conidx;
        task.getnumcon(out conidx);

        /* Append a new constraint */
        task.appendcons(1);
        numcon++;

        /* Set bounds on new constraint */
        task.putconbound(conidx,
                      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, /* row index */
                     arowsub,
                     arowval);

        task.optimize();

        task.getxx(mosek.soltype.bas, // Request the basic solution.
                   xx);

        for (int j = 0; j < numvar; ++j)
          Console.WriteLine ("x[{0}]:{1}", 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)
          Console.WriteLine ("x[{0}]:{1}", j, xx[j]);
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
      }

      if (task != null) task.Dispose ();
      if (env  != null)  env.Dispose ();
    }
  }
}

response.cs

Listing 17.29 response.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      response.cs

  Purpose:   This example demonstrates proper response handling
             for problems solved with the interior-point optimizers.
*/
using System;
using mosek;
using System.Text;

namespace mosek.example
{
  // A log handler class
  class msgclass : mosek.Stream
  {
    public msgclass () {}
    public override void streamCB (string msg) { Console.Write ("{0}", msg); }
  }

  public class response
  {
    public static void Main(string[] argv)
    {
      StringBuilder symname = new StringBuilder();
      StringBuilder desc = new StringBuilder();

      string filename;
      if (argv.Length >= 1) filename = argv[0];
      else                  filename = "../data/cqo1.mps";

      // Define environment and task
      using (Env env = new Env())
      {
        using (Task task = new Task(env, 0, 0))
        {
          try 
          {
            // (Optionally) set a log handler
            // task.set_Stream (streamtype.log, new msgclass ());

            // (Optionally) uncomment this to get solution status unknown
            // task.putintparam(iparam.intpnt_max_iterations, 1);

            // In this example we read data 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 solsta.optimal:
                // Optimal solution. Print variable values
                Console.WriteLine("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++) 
                  Console.WriteLine("x[" + i + "] = " + xx[i]);
                break;

              case solsta.dual_infeas_cer:
                Console.WriteLine("Dual infeasibility certificate found.");
                break;

              case solsta.prim_infeas_cer:
                Console.WriteLine("Primal infeasibility certificate found.");
                break;

              case solsta.unknown:
                /* The solutions status is unknown. The termination code
                   indicates why the optimizer terminated prematurely. */
                Console.WriteLine("The solution status is unknown.");
                Env.getcodedesc(trm, symname, desc);
                Console.WriteLine("  Termination code: {0} {1}", symname, desc);
                break;

              default:
                Console.WriteLine("An unexpected solution status " + solsta);
                break;
            }
          }
          catch (mosek.Error e)
          {
            Console.WriteLine("Unexpected optimization error ({0}) {1}", e.Code, e.Message);
          }
        }
      }
    }
  }
}

sdo1.cs

Listing 17.30 sdo1.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      sdo1.cs

   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
*/
using System;

namespace mosek.example
{
  public class sdo1
  {
    public static void Main(string[] args)
    {
      int    numcon    = 2;  /* Number of constraints.              */
      int    numvar    = 3;  /* Number of conic quadratic variables */
      int[]  dimbarvar = { 3 };         /* Dimensions of semidefinite cones */
      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    = { new int[] {0},   new int[] {1, 2}}; /* column subscripts of A */
      double[][]   aval    = { new double[] {1.0}, new double[] {1.0, 1.0}};

      int[][]      bara_i  = { new int[] {0,   1,   2},   new int[] {0,   1 ,  2,   1,   2,   2 } },
                   bara_j  = { new int[] {0,   1,   2},   new int[] {0,   0 ,  0,   1,   1,   2 } };
      double[][]   bara_v  = { new double[] {1.0, 1.0, 1.0}, new double[] {1.0, 1.0, 1.0, 1.0, 1.0, 1.0}};
      int[]        conesub = { 0, 1, 2 };



      using (mosek.Env env = new mosek.Env())
      {
        // Create a task object.
        using (mosek.Task task = new mosek.Task(env, 0, 0))
        {
          // Directs the log task stream to the user specified
          // method msgclass.streamCB
          task.set_Stream (mosek.streamtype.log, new msgclass (""));
          /* 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],
                                    out idx[0]);

            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],
                                    out idx[0]);

            task.putbaraij(1, 0, idx, falpha);
          }

          /* Run optimizer */
          task.optimize();

          /* Print a summary containing information
             about the solution for debugging purposes*/
          task.solutionsummary (mosek.streamtype.msg);

          mosek.solsta solsta;
          task.getsolsta (mosek.soltype.itr, out solsta);

          switch (solsta)
          {
            case mosek.solsta.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);
              Console.WriteLine("Optimal primal solution");
              for (int i = 0; i < numvar; ++i)
                Console.WriteLine("x[{0}]   : {1}", i, xx[i]);

              for (int i = 0; i < lenbarvar[0]; ++i)
                Console.WriteLine("barx[{0}]: {1}", i, barx[i]);
              break;
            case mosek.solsta.dual_infeas_cer:
            case mosek.solsta.prim_infeas_cer:
              Console.WriteLine("Primal or dual infeasibility certificate found.");
              break;
            case mosek.solsta.unknown:
              Console.WriteLine("The status of the solution could not be determined.");
              break;
            default:
              Console.WriteLine("Other solution status.");
              break;
          }
        }
      }
    }
  }



  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }
}

sensitivity.cs

Listing 17.31 sensitivity.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:      sensitivity.cs

  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.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class sensitivity
  {
    public static void Main ()
    {
      const double
      infinity = 0;

      mosek.boundkey[] bkc = new mosek.boundkey[] {
        mosek.boundkey.up, mosek.boundkey.up,
        mosek.boundkey.up, mosek.boundkey.fx,
        mosek.boundkey.fx, mosek.boundkey.fx,
        mosek.boundkey.fx
      };

      mosek.boundkey[] bkx = new mosek.boundkey[] {
        mosek.boundkey.lo, mosek.boundkey.lo,
        mosek.boundkey.lo, mosek.boundkey.lo,
        mosek.boundkey.lo, mosek.boundkey.lo,
        mosek.boundkey.lo
      };

      int[] ptrb = new int[] {0, 2, 4, 6, 8, 10, 12};
      int[] ptre = new int[] {2, 4, 6, 8, 10, 12, 14};
      int[] sub = new int[] {0, 3, 0, 4, 1, 5, 1, 6, 2, 3, 2, 5, 2, 6};
      double[] blc = new double[] {
        -infinity, -infinity,
        -infinity, 800, 100, 500, 500
      };

      double[] buc = new double[] {400, 1200, 1000, 800, 100, 500, 500};
      double[] c   = new double[] {1.0, 2.0, 5.0, 2.0, 1.0, 2.0, 1.0};
      double[] blx = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
      double[] bux = new double[] {infinity,
                                   infinity,
                                   infinity,
                                   infinity,
                                   infinity,
                                   infinity,
                                   infinity
                                  };

      double[] val = new double[] {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.               */
      try
      {
        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            // Directs the log task stream to the user specified
            // method task_msg_obj.streamCB
            task.set_Stream(mosek.streamtype.log, new msgclass ("[task]"));

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

            try
            {
              task.optimize();
            }
            catch (mosek.Warning w)
            {
              Console.WriteLine("Mosek warning:");
              Console.WriteLine (w.Code);
              Console.WriteLine (w);
            }


            /* Analyze upper bound on c1 and the equality constraint on c4 */
            int[] subi  = new int [] {0, 3};
            mosek.mark[] marki = new mosek.mark[] {mosek.mark.up,
                                                   mosek.mark.up
                                                  };

            /* Analyze lower bound on the variables x12 and x31 */
            int[] subj  = new int [] {1, 4};
            mosek.mark[] markj = new mosek.mark[] {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);

            Console.Write("Results from sensitivity analysis on bounds:\n");

            Console.Write("For constraints:\n");
            for (int i = 0; i < 2; ++i)
              Console.Write(
                "leftprice = {0}, rightprice = {1},leftrange = {2}, rightrange ={3}\n",
                leftpricei[i], rightpricei[i], leftrangei[i], rightrangei[i]);

            Console.Write("For variables:\n");
            for (int i = 0; i < 2; ++i)
              Console.Write(
                "leftprice = {0}, rightprice = {1},leftrange = {2}, rightrange ={3}\n",
                leftpricej[i], rightpricej[i], leftrangej[i], rightrangej[i]);


            double[] leftprice  = new  double[2];
            double[] rightprice = new  double[2];
            double[] leftrange  = new  double[2];
            double[] rightrange = new  double[2];
            int[] subc = new int[] {2, 5};

            task.dualsensitivity(  subc,
                                   leftprice,
                                   rightprice,
                                   leftrange,
                                   rightrange
                                );

            Console.Write("Results from sensitivity analysis on objective coefficients:");

            for (int i = 0; i < 2; ++i)
              Console.Write(
                "leftprice = {0}, rightprice = {1},leftrange = {2}, rightrange = {3}\n",
                leftprice[i], rightprice[i], leftrange[i], rightrange[i]);
          }
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }
    }
  }
}

simple.cs

Listing 17.32 simple.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:    simple.cs

  Purpose: Demonstrates a very simple example using MOSEK by
  reading a problem file, solving the problem and
  writing the solution to a file.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    public override void streamCB (string msg)
    {
      Console.Write ("{0}", msg);
    }
  }

  public class simple
  {
    public static void Main (string[] args)
    {
      if (args.Length == 0)
      {
        Console.WriteLine ("Missing argument, syntax is:");
        Console.WriteLine ("  simple inputfile [ solutionfile ]");
      }
      else
      {
        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            task.set_Stream (mosek.streamtype.log, new msgclass ());

            // 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 a 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);
              task.putintparam (mosek.iparam.opf_write_problem,    mosek.onoffkey.on);
              task.putintparam (mosek.iparam.opf_write_hints,      mosek.onoffkey.off);
              task.putintparam (mosek.iparam.opf_write_parameters, mosek.onoffkey.off);

              task.writedata(args[1]);
            }
          }
        }
      }
    }
  }
}

solutionquality.cs

Listing 17.33 solutionquality.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File:    solutionquality.cs

  Purpose: To demonstrate how to examine the quality of a solution.
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass(string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB(string msg)
    {
      Console.Write("{0}{1}", prefix, msg);
    }
  }

  public class solutionquality
  {
    public static void Main(String[] args)
    {
      if (args.Length == 0)
      {
        Console.WriteLine("Missing argument, syntax is:");
        Console.WriteLine("  solutionquality inputfile");
      }
      else
      {
        using (mosek.Env env = new mosek.Env())
        {
          // Create a task object.
          using (mosek.Task task = new mosek.Task(env, 0, 0))
          {
            task.set_Stream(mosek.streamtype.log, new msgclass(""));
            try
            {

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

              // Console.WriteLine (a summary of the solution
              task.solutionsummary(mosek.streamtype.log);

              mosek.solsta solsta;
              task.getsolsta(mosek.soltype.bas, out solsta);

              double pobj, pviolcon, pviolvar, pviolbarvar, pviolcones, pviolitg;
              double dobj, dviolcon, dviolvar, dviolbarvar, dviolcones;

              task.getsolutioninfo(mosek.soltype.bas,
                                   out pobj, out pviolcon, out pviolvar, out pviolbarvar, out pviolcones, out pviolitg,
                                   out dobj, out dviolcon, out dviolvar, out dviolbarvar, out dviolcones);

              switch (solsta)
              {
                case mosek.solsta.optimal:

                  double abs_obj_gap = Math.Abs(dobj - pobj);
                  double rel_obj_gap = abs_obj_gap / (1.0 + Math.Min(Math.Abs(pobj), Math.Abs(dobj)));
                  double max_primal_viol = Math.Max(pviolcon, pviolvar);
                  max_primal_viol = Math.Max(max_primal_viol, pviolbarvar);
                  max_primal_viol = Math.Max(max_primal_viol, pviolcones);

                  double max_dual_viol = Math.Max(dviolcon, dviolvar);
                  max_dual_viol = Math.Max(max_dual_viol, dviolbarvar);
                  max_dual_viol = Math.Max(max_dual_viol, dviolcones);

                  // 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

                  Console.WriteLine("Customized solution information.\n");
                  Console.WriteLine("  Absolute objective gap: " + abs_obj_gap);
                  Console.WriteLine("  Relative objective gap: " + rel_obj_gap);
                  Console.WriteLine("  Max primal violation  : " + max_primal_viol);
                  Console.WriteLine("  Max dual violation    : " + max_dual_viol);

                  bool accepted = true;

                  if (rel_obj_gap > 1e-6)
                  {
                    Console.WriteLine("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)
                  {
                    Console.WriteLine("Warning: Primal violation is too LARGE");
                    accepted = false;
                  }

                  if (max_dual_viol > 1e-6)
                  {
                    Console.WriteLine("Warning: Dual violation is too LARGE.");
                    accepted = false;
                  }

                  if (accepted)
                  {
                    int numvar = task.getnumvar();
                    double[] xx = new double[numvar];
                    Console.WriteLine("Optimal primal solution");
                    task.getxx(mosek.soltype.bas, xx);
                    for (int j = 0; j < numvar; j++)
                      Console.WriteLine("x[{0}]: {1}", j, xx[j]);
                  }
                  else
                  {
                    // print etailed information about the solution
                    task.analyzesolution(mosek.streamtype.log, mosek.soltype.bas);
                  }
                  break;

                case mosek.solsta.dual_infeas_cer:
                case mosek.solsta.prim_infeas_cer:
                  Console.WriteLine("Primal or dual infeasibility certificate found.");
                  break;

                case mosek.solsta.unknown:
                  Console.WriteLine("The status of the solution is unknown.");
                  break;

                default:
                  Console.WriteLine("Other solution status");
                  break;
              }
            }
            catch (mosek.Exception e)
            {
              Console.WriteLine("\nAn error occourred: " + e.Code);
              Console.WriteLine(e);
              //throw;
            }
          }
        }
      }
    }
  }
}

solvebasis.cs

Listing 17.34 solvebasis.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File     : solvebasis.cs

  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
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  public class solvebasis
  {
    public static void Main ()
    {
      const int numcon = 2;
      const int numvar = 2;

      // 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, 3};
      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
                       };
      double[] w1 = {2.0, 6.0};
      double[] w2 = {1.0, 0.0};
      try
      {
        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            task.set_Stream (mosek.streamtype.log, new msgclass ("[task]"));
            task.inputdata(numcon, numvar,
                           c,
                           0.0,
                           ptrb,
                           ptre,
                           asub,
                           aval,
                           bkc,
                           blc,
                           buc,
                           bkx,
                           blx,
                           bux);
            task.putobjsense(mosek.objsense.maximize);
            try
            {
              task.optimize();
            }
            catch (mosek.Warning w)
            {
              Console.WriteLine("Mosek warning:");
              Console.WriteLine (w.Code);
              Console.WriteLine (w);
            }

            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++) {
              if (basis[varsub[i]] < numcon)
                Console.WriteLine ("Basis variable no {0} is xc{1}",
                                   i,
                                   basis[i]);
              else
                Console.WriteLine ("Basis variable no {0} is x{1}",
                                   i,
                                   basis[i] - numcon);
            }

            // solve Bx = w1
            // varsub contains index of non-zeros in b.
            //  On return b contains the solution x and
            // varsub the index of the non-zeros in x.
            int nz = 2;

            task.solvewithbasis(0, ref nz, varsub, w1);
            Console.WriteLine ("nz = {0}", nz);
            Console.WriteLine ("Solution to Bx = w1:\n");

            for (int i = 0; i < nz; i++) {
              if (basis[varsub[i]] < numcon)
                Console.WriteLine ("xc {0} = {1}",
                                   basis[varsub[i]],
                                   w1[varsub[i]] );
              else
                Console.WriteLine ("x{0} = {1}",
                                   basis[varsub[i]] - numcon,
                                   w1[varsub[i]]);
            }

            // Solve B^Tx = w2
            nz = 1;
            varsub[0] = 0; // Only w2[0] is nonzero.

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

            Console.WriteLine ("\nSolution to B^Ty = w2:\n");

            for (int i = 0; i < nz; i++)
            {
              Console.WriteLine ("y {0} = {1}",
                                 varsub[i],
                                 w2[varsub[i]]);
            }
          }
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }
    }
  }
}

solvelinear.cs

Listing 17.35 solvelinear.cs Click here to download.
/*
  Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

  File     :  solvelinear.cs

  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)
*/
using System;

namespace mosek.example
{
  class msgclass : mosek.Stream
  {
    string prefix;
    public msgclass (string prfx)
    {
      prefix = prfx;
    }

    public override void streamCB (string msg)
    {
      Console.Write ("{0}{1}", prefix, msg);
    }
  }

  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 ()
    {
      const int numcon = 2;
      const int numvar = 2;

      double[][]
      aval   = new double[numvar][];

      aval[0] = new double[] { -1.0 };
      aval[1] = new double[] {1.0, 1.0};


      int[][]
      asub = new int[numvar][];

      asub[0] = new int[] {1};
      asub[1] = new int[] {0, 1};

      int []      ptrb  = {0, 1};
      int []      ptre  = {1, 3};

      int[]       bsub  = new int[numvar];
      double[]    b     = new double[numvar];
      int[]       basis = new int[numvar];

      try
      {
        using (mosek.Env env = new mosek.Env())
        {
          using (mosek.Task task = new mosek.Task(env))
          {
            // Directs the log task stream to the user specified
            // method task_msg_obj.streamCB
            task.set_Stream(mosek.streamtype.log, new msgclass ("[task]"));
            /* 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, ref nz, bsub, b);
            Console.WriteLine ("\nSolution to Bx = b:\n\n");

            /* Print solution and show correspondents
               to original variables in the problem */
            for (int i = 0; i < nz; ++i)
            {
              if (basis[bsub[i]] < numcon)
                Console.WriteLine ("This should never happen\n");
              else
                Console.WriteLine ("x{0} = {1}\n", basis[bsub[i]] - numcon , b[bsub[i]] );
            }

            b[0] = 7;
            bsub[0] = 0;
            nz = 1;

            task.solvewithbasis(0, ref nz, bsub, b);

            Console.WriteLine ("\nSolution to Bx = b:\n\n");
            /* Print solution and show correspondents
               to original variables in the problem */
            for (int i = 0; i < nz; ++i)
            {
              if (basis[bsub[i]] < numcon)
                Console.WriteLine ("This should never happen\n");
              else
                Console.WriteLine ("x{0} = {1}\n", basis[bsub[i]] - numcon , b[bsub[i]] );
            }
          }
        }
      }
      catch (mosek.Exception e)
      {
        Console.WriteLine (e.Code);
        Console.WriteLine (e);
        throw;
      }
    }
  }
}

sparsecholesky.cs

Listing 17.36 sparsecholesky.cs Click here to download.
/*
   Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.

   File:      sparsecholesky.cs

   Purpose:   Demonstrate the sparse Cholesky factorization.

 */

using System;

namespace mosek.example
{
  public class Sparsecholesky
  {

    public static void printsparse(int      n,
                                   int[]    perm,
                                   double[] diag,
                                   int[]    lnzc,
                                   long[]   lptrc,
                                   long     lensubnval,
                                   int[]    lsubc,
                                   double[] lvalc)
    {
      long i, j;
      Console.Write("P = [ ");
      for (i = 0; i < n; i++) Console.Write("{0} ", perm[i]);
      Console.WriteLine("]");
      Console.Write("diag(D) = [ ");
      for (i = 0; i < n; i++) Console.Write("{0} ", diag[i]);
      Console.WriteLine("]");
      double[] l = new double[n * n];
      for (j = 0; j < n; j++)
        for (i = lptrc[j]; i < lptrc[j] + lnzc[j]; i++)
          l[lsubc[i]*n + j] = lvalc[i];
      Console.WriteLine("L=");
      for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) Console.Write("{0} ", l[i * n + j]);
        Console.WriteLine("");
      }
    }


    public static void Main ()
    {
      /* Create the mosek environment. */
      using (mosek.Env env = new mosek.Env())
      {
        {
          //Example from the manual
          //Observe that anzc, aptrc, asubc and avalc only specify the lower triangular part.
          const int n           = 4;
          int[] anzc            = {4, 1, 1, 1};
          int[] asubc           = {0, 1, 2, 3, 1, 2, 3};
          long[] aptrc          = {0, 4, 5, 6};
          double[] avalc        = {4.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
          double[] b            = {13.0, 3.0, 4.0, 5.0};

          int[] perm, lnzc, lsubc;
          long lensubnval;
          double[] diag, lvalc;
          long[] lptrc;

          env.computesparsecholesky(0,        //Disable multithreading
                                    1,        //Apply reordering heuristic
                                    1.0e-14,  //Singularity tolerance
                                    anzc, aptrc, asubc, avalc,
                                    out perm, out diag,
                                    out lnzc, out lptrc, out lensubnval, out lsubc, out lvalc);

          printsparse(n, perm, diag, lnzc, lptrc, lensubnval, lsubc, lvalc);

          /* Permuted b is stored as x. */
          double[] x = new double[n];
          for (int i = 0; i < n; i++) x[i] = b[perm[i]];

          /*Compute  inv(L)*x.*/
          env.sparsetriangularsolvedense(mosek.transpose.no, lnzc, lptrc, lsubc, lvalc, x);
          /*Compute  inv(L^T)*x.*/
          env.sparsetriangularsolvedense(mosek.transpose.yes, lnzc, lptrc, lsubc, lvalc, x);

          Console.Write("\nSolution A x = b, x = [ ");
          for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) if (perm[j] == i) Console.Write("{0} ", x[j]);
          Console.WriteLine("]\n");
        }
        {
          const int n           = 3;
          int[] anzc            = {3, 2, 1};
          int[] asubc           = {0, 1, 2, 1, 2, 2};
          long[] aptrc          = {0, 3, 5, };
          double[] avalc        = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};

          int[] perm, lnzc, lsubc;
          long lensubnval;
          double[] diag, lvalc;
          long[] lptrc;

          env.computesparsecholesky(0,        //Disable multithreading
                                    1,        //Apply reordering heuristic
                                    1.0e-14,  //Singularity tolerance
                                    anzc, aptrc, asubc, avalc,
                                    out perm, out diag,
                                    out lnzc, out lptrc, out lensubnval, out lsubc, out lvalc);

          printsparse(n, perm, diag, lnzc, lptrc, lensubnval, lsubc, lvalc);
        }
      }
    }
  }
}