Initializing help system before first use

Folio - Examples from 'Getting Started'


Type: Portfolio optimization
Rating: 3 (intermediate)
Description: Different versions of a portfolio optimization problem.
Basic modelling and solving tasks:
  • modeling and solving a small LP problem (foliolp)
  • performing explicit initialization (folioinit)
  • data input from file, index sets (foliodata, requires foliocpplp.dat)
  • modeling and solving a small MIP problem with binary variables (foliomip1)
  • modeling and solving a small MIP problem with semi-continuous variables (foliomip2)
  • modeling and solving QP and MIQP problems (folioqp, requires foliocppqp.dat)
  • heuristic solution of a MIP problem (folioheur)
Advanced modeling and solving tasks:
  • enlarged version of the basic MIP model (foliomip3, to be used with data set folio10.cdat)
  • defining an integer solution callback (foliocb)
  • using the MIP solution pool (foliosolpool)
  • using the solution enumerator (folioenumsol)
  • handling infeasibility through deviation variables (folioinfeas)
  • retrieving IIS (folioiis, foliomiis)
  • using the built-in infeasibility repair functionality (foliorep)
File(s): foliolp.cs, folioinit.cs, foliodata.cs, foliomip1.cs, foliomip2.cs, folioqp.cs, folioheur.cs, foliomip3.cs, folioiis.cs
Data file(s): foliocpplp.dat, folio10.cdat

foliolp.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file foliolp.cs
  ```````````````
  Modeling a small LP problem 
  to perform portfolio optimization.

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{
    public class TestUGFolioLP
    {

        const int NSHARES = 10;                   // Number of shares
        const int NRISK = 5;                      // Number of high-risk shares
        const int NNA = 4;                        // Number of North-American shares

        double[] RET = {5,17,26,12,8,9,7,6,31,21};  // Estimated return in investment
        int[] RISK = {1,2,3,8,9};            // High-risk values among shares
        int[] NA = {0,1,2,3};                // Shares issued in N.-America

        public static void Main()
        {
            XPRB.init();
            int s;
            XPRBprob p = new XPRBprob("FolioLP");              // Initialize a new problem in BCL
            XPRBexpr Risk,Na,Return,Cap;
            XPRBvar[] frac = new XPRBvar[NSHARES];              // Fraction of capital used per share
            TestUGFolioLP TestInstance = new TestUGFolioLP();

            // Create the decision variables
            for(s=0;s<NSHARES;s++) frac[s] = p.newVar("frac");  //, XPRB_PL, 0, 0.3);

            // Objective: total return
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; 
            p.setObj(p.newCtr("Objective", Return));                   // Set the objective function

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; 
            p.newCtr("Risk", Risk <= 1.0/3);

            /* Equivalent:
            XPRBctr CRisk;
            CRisk = p.newCtr("Risk");
            for(s=0;s<NRISK;s++) CRisk.addTerm(frac[RISK[s]], 1);
            CRisk.setType(XPRB_L);
            CRisk.addTerm(1.0/3);
            */

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; 
            p.newCtr("NA", Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s]; 
            p.newCtr("Cap", Cap == 1);

            // Upper bounds on the investment per share
            for(s=0;s<NSHARES;s++) frac[s].setUB(0.3);

            // Export matrix to a file
            /* p.exportProb(XPRB_MPS, "Folio");
            p.setSense(XPRB_MAXIM);
            p.exportProb(XPRB_LP, "Folio");
            */

            // Disable all BCL and Optimizer message printing, except error messages
            // p.setMsgLevel(1);

            // Solve the problem
            p.setSense(BCLconstant.XPRB_MAXIM);
            p.lpOptimize();              /* Solve the LP-problem */

            string[] LPSTATUS = {"not loaded", "optimal", "infeasible", 
            "worse than cutoff", "unfinished", "unbounded", "cutoff in dual"};

            System.Console.WriteLine("Problem status: " + LPSTATUS[p.getLPStat()]);

            // Solution printing
            System.Console.WriteLine("Total return: " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
            System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%");  

            return;
        } 

    }

}

folioinit.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file folioinit.cs
  `````````````````
  Modeling a small LP problem 
  to perform portfolio optimization.
  Explicit initialization.

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{

    public class TestUGFolioInit
    {

        const int NSHARES = 10;                   // Number of shares
        const int NRISK = 5;                      // Number of high-risk shares
        const int NNA = 4;                        // Number of North-American shares

        double[] RET = {5,17,26,12,8,9,7,6,31,21};  // Estimated return in investment
        int[] RISK = {1,2,3,8,9};            // High-risk values among shares
        int[] NA = {0,1,2,3};                // Shares issued in N.-America

        public void solveProb()
        {
            XPRB.init();
            int s;
            XPRBprob p = new XPRBprob("FolioLP");              // Initialize a new problem in BCL
            XPRBexpr Risk,Na,Return,Cap;
            XPRBvar[] frac = new XPRBvar[NSHARES];              // Fraction of capital used per share

            // Create the decision variables
            for(s=0;s<NSHARES;s++) frac[s] = p.newVar("frac");

            // Objective: total return
            Return = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Return += RET[s]*frac[s]; 
            p.setObj(p.newCtr("Objective", Return));                   // Set the objective function

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for(s=0;s<NRISK;s++) Risk += frac[RISK[s]]; 
            p.newCtr("Risk", Risk <= 1.0/3);

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for(s=0;s<NNA;s++) Na += frac[NA[s]]; 
            p.newCtr("NA", Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s]; 
            p.newCtr("Cap", Cap == 1);

            // Upper bounds on the investment per share
            for(s=0;s<NSHARES;s++) frac[s].setUB(0.3);

            // Solve the problem
            p.setSense(BCLconstant.XPRB_MAXIM);
            p.lpOptimize();              /* Solve the LP-problem */

            string[] LPSTATUS = {"not loaded", "optimal", "infeasible", 
            "worse than cutoff", "unfinished", "unbounded", "cutoff in dual"};

            System.Console.WriteLine("Problem status: " + LPSTATUS[p.getLPStat()]);

            // Solution printing
            System.Console.WriteLine("Total return: " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
                System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%");  
        }

        public static void Main()
        {
            TestUGFolioInit TestInstance = new TestUGFolioInit();

            if(XPRB.init() != 0)
            {
                System.Console.WriteLine("Initialization failed.");
                return;
            }
            TestInstance.solveProb();
            return;
        }


    }


}

foliodata.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file foliodata.cs
  `````````````````
  Modeling a small LP problem 
  to perform portfolio optimization.
  -- Data input from file --

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{

    public class TestUGFolioData
    {

        //Define XPRBDATAPATH to wherever you have placed the data folder.
        const string XPRBDATAPATH = "../../data";
        const string DATAFILE = XPRBDATAPATH + "/GS/foliocpplp.dat";

        const int NSHARES = 10;          // Number of shares
        const int NRISK = 5;             // Number of high-risk shares
        const int NNA = 4;               // Number of North-American shares

        // Estimated return in investment
        double[] RET = new double[NSHARES];                 
        
        // High-risk values among shares
        string[] RISK = {"hardware", "theater", "telecom", "software", 
        		 "electronics"};  
        
        // Shares issued in N.-America
        string[] NA = {"treasury", "hardware", "theater", "telecom"};   

	// Set of shares 
        XPRBindexSet SHARES;                 
        
        // Initialize a new problem in BCL
        XPRBprob p = new XPRBprob("FolioLP");               

        public void readData()
        {
            double value;
            int s;
            string name;
            FileStream file;
            StreamReader fileStreamIn;

	    // Create the `SHARES' index set
            SHARES=p.newIndexSet("Shares",NSHARES);  

            // Read `RET' data from file
            file = new FileStream(DATAFILE, FileMode.Open, FileAccess.Read);
            fileStreamIn = new StreamReader(file);
            object[] outdata = new object[2];
            for (s = 0; s < NSHARES; s++)
            {
                p.XPRBreadline(fileStreamIn, 200, "{S} {g}", out outdata);
                name = (string)outdata[0];
                value = (double)outdata[1];
                RET[SHARES + name] = value;
            }
            fileStreamIn.Close();
            file.Close();

            SHARES.print();                     // Print out the set contents 
        }

        public static void Main()
        {
            XPRB.init();
            int s;
            XPRBexpr Risk,Na,Return,Cap;

            // Fraction of capital used per share
            XPRBvar[] frac = new XPRBvar[NSHARES];              

            TestUGFolioData TestInstance = new TestUGFolioData();

            // Read data from file
            TestInstance.readData();

            // Create the decision variables
            for (s = 0; s < NSHARES; s++) 
            	frac[s] = TestInstance.p.newVar("frac");

            // Objective: total return
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) 
            	Return += TestInstance.RET[s] * frac[s];
                   
            // Set the objective function            
            TestInstance.p.setObj(TestInstance.p.newCtr("Objective", Return));

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for (s = 0; s < NRISK; s++) 
            	Risk+=frac[TestInstance.SHARES.getIndex(TestInstance.RISK[s])];
            TestInstance.p.newCtr("Risk", Risk <= 1.0 / 3);

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) 
            	Na += frac[TestInstance.SHARES.getIndex(TestInstance.NA[s])];
            TestInstance.p.newCtr("NA", Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s];
            TestInstance.p.newCtr("Cap", Cap == 1);

            // Upper bounds on the investment per share
            for(s=0;s<NSHARES;s++) frac[s].setUB(0.3);

            // Solve the problem
            TestInstance.p.setSense(BCLconstant.XPRB_MAXIM);
            TestInstance.p.lpOptimize();              /* Solve the LP-problem */

            // Solution printing
            System.Console.WriteLine("Total return: " + 
            			      TestInstance.p.getObjVal());
            for(s=0;s<NSHARES;s++)
                System.Console.WriteLine(TestInstance.SHARES.getIndexName(s) +
                			 ": " + frac[s].getSol() * 100 + "%");  

            return;
        } 

    }

}

foliomip1.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file foliomip1.cs
  `````````````````
  Modeling a small MIP problem 
  to perform portfolio optimization.
   -- Limiting the total number of assets --

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{
    public class TestUGFolioMip1
    {

        const int MAXNUM = 4;                   // Max. number of different assets

        const int NSHARES = 10;                 // Number of shares
        const int NRISK = 5;                    // Number of high-risk shares
        const int NNA = 4;                      // Number of North-American shares

        double[] RET = {5,17,26,12,8,9,7,6,31,21};  // Estimated return in investment
        int[] RISK = {1,2,3,8,9};          // High-risk values among shares
        int[] NA = {0,1,2,3};              // Shares issued in N.-America

        public static void Main()
        {
            XPRB.init();
            int s;
            XPRBprob p = new XPRBprob("FolioMIP1");          // Initialize a new problem in BCL
            XPRBexpr Risk,Na,Return,Cap,Num;
            XPRBvar[] frac = new XPRBvar[NSHARES];            // Fraction of capital used per share
            XPRBvar[] buy = new XPRBvar[NSHARES];             // 1 if asset is in portfolio, 0 otherwise
            TestUGFolioMip1 TestInstance = new TestUGFolioMip1();

            // Create the decision variables (including upper bounds for `frac')
            for(s=0;s<NSHARES;s++) 
            {
                frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, 0.3);
                buy[s] = p.newVar("buy", BCLconstant.XPRB_BV);
            } 

            // Objective: total return
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; 
            p.setObj(p.newCtr("Objective", Return));                // Set the objective function

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; 
            p.newCtr(Risk <= 1.0/3);

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; 
            p.newCtr(Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s]; 
            p.newCtr(Cap == 1);

            // Limit the total number of assets
            Num = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Num += buy[s];
            p.newCtr(Num <= MAXNUM);

            // Linking the variables
            for(s=0;s<NSHARES;s++) p.newCtr(frac[s] <= buy[s]);

            // Solve the problem
            p.setSense(BCLconstant.XPRB_MAXIM);
            p.mipOptimize();              /* Solve the LP-problem */


            string[] MIPSTATUS = {"not loaded", "not optimized", "LP optimized",  
            "unfinished (no solution)", 
            "unfinished (solution found)", "infeasible", "optimal"};

            System.Console.WriteLine("Problem status: " + MIPSTATUS[p.getMIPStat()]);


            // Solution printing
            System.Console.WriteLine("Total return: " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
                System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "% (" + buy[s].getSol() + ")");  

            return;
        } 

    }

}

foliomip2.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file foliomip2.cs
  `````````````````
  Modeling a small MIP problem 
  to perform portfolio optimization.
   -- Imposing a minimum investment per share --

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{

    public class TestUGFolioMip2
    {
        const int NSHARES = 10;                   // Number of shares
        const int NRISK = 5;                      // Number of high-risk shares
        const int NNA = 4;                        // Number of North-American shares

        double[] RET = {5,17,26,12,8,9,7,6,31,21};  // Estimated return in investment
        int[] RISK = {1,2,3,8,9};            // High-risk values among shares
        int[] NA = {0,1,2,3};                // Shares issued in N.-America

        public static void Main()
        {
            XPRB.init();
            int s;
            XPRBprob p = new XPRBprob("FolioSC");              // Initialize a new problem in BCL
            XPRBexpr Risk,Na,Return,Cap;
            XPRBvar[] frac = new XPRBvar[NSHARES];              // Fraction of capital used per share
            TestUGFolioMip2 TestInstance = new TestUGFolioMip2();

            // Create the decision variables
            for(s=0;s<NSHARES;s++)
            {
                frac[s] = p.newVar("frac", BCLconstant.XPRB_SC, 0, 0.3);
                frac[s].setLim(0.1);
            } 

            // Objective: total return
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; 
            p.setObj(p.newCtr("Objective", Return));                   // Set the objective function

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; 
            p.newCtr(Risk <= 1.0/3);

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; 
            p.newCtr(Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s]; 
            p.newCtr(Cap == 1);

            // Solve the problem
            p.setSense(BCLconstant.XPRB_MAXIM);
            p.mipOptimize();

            // Solution printing
            System.Console.WriteLine("Total return: " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
                System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%");  

            return;
        } 

    }

}

folioqp.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file folioqp.cs
  ```````````````
  Modeling a small QP problem 
  to perform portfolio optimization.
   -- 1. QP: minimize variance
      2. MIQP: limited number of assets ---

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using BCL;


namespace Examples
{

    public class TestUGFolioQp
    {

        //Define XPRBDATAPATH to wherever you have stored the data folder.
        const string XPRBDATAPATH = "../../data";
        const string DATAFILE = XPRBDATAPATH + "/GS/foliocppqp.dat";

        const int TARGET = 9;                   // Target yield
        const int MAXNUM = 4;                   // Max. number of different assets

        const int NSHARES = 10;                 // Number of shares
        const int NNA = 4;                      // Number of North-American shares

        double[] RET = {5,17,26,12,8,9,7,6,31,21};  // Estimated return in investment
        int[] NA = {0,1,2,3};              // Shares issued in N.-America
        double[,] VAR = new double[NSHARES,NSHARES];      // Variance/covariance matrix of
               // estimated returns

        public static void Main()
        {
            XPRB.init();
            int s,t;
            XPRBprob p = new XPRBprob("FolioQP");            // Initialize a new problem in BCL
            XPRBexpr Na,Return,Cap,Num;
            XPRBexpr Variance;
            XPRBvar[] frac = new XPRBvar[NSHARES];            // Fraction of capital used per share
            XPRBvar[] buy = new XPRBvar[NSHARES];             // 1 if asset is in portfolio, 0 otherwise
            FileStream file;
            StreamReader fileStreamIn;
            TestUGFolioQp TestInstance = new TestUGFolioQp();

            // Read `VAR' data from file
            file = new FileStream(DATAFILE, FileMode.Open, FileAccess.Read);
            fileStreamIn = new StreamReader(file);
            object[] outdata = new object[NSHARES];
            for (s = 0; s < NSHARES; s++)
            {
                p.XPRBreadarrline(fileStreamIn, 200, "{g} ", out outdata, NSHARES);
                for(t=0; t<NSHARES; t++)
                    TestInstance.VAR[s, t] = (double)outdata[t];
            }
            fileStreamIn.Close();
            file.Close();

            // **** First problem: unlimited number of assets ****

            // Create the decision variables
            for(s=0;s<NSHARES;s++) 
                frac[s] = p.newVar("frac(" + (s+1) + ")", BCLconstant.XPRB_PL, 0, 0.3);

            // Objective: mean variance
            Variance = new XPRBexpr();
            for(s=0;s<NSHARES;s++)
                for (t = 0; t < NSHARES; t++) Variance += TestInstance.VAR[s,t] * (frac[s] * frac[t]); 
            p.setObj(Variance);                 // Set the objective function

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; 
            p.newCtr(Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Cap += frac[s]; 
            p.newCtr(Cap == 1);

            // Target yield 
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; 
            p.newCtr(Return >= TARGET);

            // Solve the problem
            p.setSense(BCLconstant.XPRB_MINIM);
            p.lpOptimize();              /* Solve the LP-problem */

            // Solution printing
            System.Console.WriteLine("With a target of " + TARGET + " minimum variance is " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
                System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%");  

            // **** Second problem: limit total number of assets ****

            // Create the decision variables
            for(s=0;s<NSHARES;s++)
                buy[s] = p.newVar("buy(" + (s+1) + ")", BCLconstant.XPRB_BV);

            // Limit the total number of assets
            Num = new XPRBexpr();
            for(s=0;s<NSHARES;s++) Num += buy[s];
            p.newCtr(Num <= MAXNUM);

            // Linking the variables
            for(s=0;s<NSHARES;s++) p.newCtr(frac[s] <= buy[s]);

            // Solve the problem
            p.mipOptimize();

            // Solution printing
            System.Console.WriteLine("With a target of " + TARGET + " and at most " + MAXNUM +
                                    " assets, minimum variance is " + p.getObjVal());
            for(s=0;s<NSHARES;s++) 
                System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "% (" + buy[s].getSol() + ")");  

            return;
        } 

    }

}

folioheur.cs
/********************************************************
  Xpress-BCL C# Example Problems
  ==============================

  file folioheur.cs
  `````````````````
  Modeling a small MIP problem 
  to perform portfolio optimization.
   -- Heuristic solution --

  (c) 2008 Fair Isaac Corporation
      authors: S.Heipcke, D.Brett.
********************************************************/

using System;
using System.Text;
using System.IO;
using Optimizer;
using BCL;


namespace Examples
{
    public class TestUGFolioHeur
    {
        const int MAXNUM = 4;          // Max. number of shares to be selected

        const int NSHARES = 10;        // Number of shares
        const int NRISK = 5;           // Number of high-risk shares
        const int NNA = 4;             // Number of North-American shares

	// Estimated return in investment
        double[] RET = {5,17,26,12,8,9,7,6,31,21};  
        
        // High-risk values among shares
        int[] RISK = {1,2,3,8,9};          
        
        // Shares issued in N.-America
        int[] NA = {0,1,2,3};              

        // Initialize a new problem in BCL
        XPRBprob p = new XPRBprob("FolioMIPHeur");        
        
        // Fraction of capital used per share
        XPRBvar[] frac = new XPRBvar[NSHARES];             
        
        // 1 if asset is in portfolio, 0 otherwise
        XPRBvar[] buy = new XPRBvar[NSHARES];              

        public static void Main()
        {
            XPRB.init();
            int s;
            XPRBexpr Risk,Na,Return,Cap,Num;
            TestUGFolioHeur TestInstance = new TestUGFolioHeur();

            // Create decision variables (including upper bounds for `frac')
            for(s=0;s<NSHARES;s++) 
            {
                TestInstance.frac[s] = 
                    TestInstance.p.newVar("frac", BCLconstant.XPRB_PL, 0, 0.3);
                TestInstance.buy[s] = 
                    TestInstance.p.newVar("buy", BCLconstant.XPRB_BV);
            } 

            // Objective: total return
            Return = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) 
            	Return += TestInstance.RET[s] * TestInstance.frac[s];
            
            // Set the objective function
            TestInstance.p.setObj(TestInstance.p.newCtr("Objective", Return));

            // Limit the percentage of high-risk values
            Risk = new XPRBexpr();
            for (s = 0; s < NRISK; s++) 
            	Risk += TestInstance.frac[TestInstance.RISK[s]];
            TestInstance.p.newCtr(Risk <= 1.0 / 3);

            // Minimum amount of North-American values
            Na = new XPRBexpr();
            for (s = 0; s < NNA; s++) 
            	Na += TestInstance.frac[TestInstance.NA[s]];
            TestInstance.p.newCtr(Na >= 0.5);

            // Spend all the capital
            Cap = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) 
            	Cap += TestInstance.frac[s];
            TestInstance.p.newCtr(Cap == 1);

            // Limit the total number of assets
            Num = new XPRBexpr();
            for (s = 0; s < NSHARES; s++) 
            	Num += TestInstance.buy[s];
            TestInstance.p.newCtr(Num <= MAXNUM);

            // Linking the variables
            for (s = 0; s < NSHARES; s++) 
            	TestInstance.p.newCtr(TestInstance.frac[s] <=
            			      TestInstance.buy[s]);

            // Solve problem heuristically
            TestInstance.solveHeur();

            // Solve the problem
            TestInstance.p.setSense(BCLconstant.XPRB_MAXIM);
            TestInstance.p.mipOptimize();              /* Solve the LP-problem */

            // Solution printing
            if (TestInstance.p.getMIPStat() == 4 || 
            	TestInstance.p.getMIPStat() == 6)
            {
                System.Console.WriteLine("Exact solution: Total return: " +
                			  TestInstance.p.getObjVal());
                for(s=0;s<NSHARES;s++)
                    System.Console.WriteLine(s + ": " + 
                    		TestInstance.frac[s].getSol() * 100 + "%");
            }    
            else
                System.Console.WriteLine("Heuristic solution is optimal.");

            return;
        } 

        void solveHeur()
        {
            XPRBbasis basis;
            int s, ifgsol;
            double solval=0, TOL;
            double[] fsol = new double[NSHARES];
            XPRSprob xprsp = p.getXPRSprob();

            xprsp.CutStrategy = 0;
            // Disable automatic cuts

            xprsp.Presolve = 0;
            // Switch presolve off

            TOL = xprsp.FeasTol;
            // Get feasibility tolerance

            p.setSense(BCLconstant.XPRB_MAXIM);
            p.lpOptimize();              /* Solve the LP-problem */
            basis=p.saveBasis();              // Save the current basis

            // Fix all variables `buy' for which `frac' is at 0 or at a
            // relatively large value
            for(s=0;s<NSHARES;s++)
            {
                // Get the solution values of `frac'
                fsol[s]=frac[s].getSol();        
                if(fsol[s] < TOL)  
                    buy[s].setUB(0);
                else if(fsol[s] > 0.2-TOL)  
                    buy[s].setLB(1);
            }

            p.mipOptimize();                     // Solve the MIP-problem
            
            
            // If an integer feas. solution was found...
            ifgsol=0;            
            if(p.getMIPStat()==4 || p.getMIPStat()==6)
            {                                 
                ifgsol=1;
                
                // ...get the value of the best solution
                solval=p.getObjVal();            
                System.Console.WriteLine("Heuristic solution: Total return: " +
                			  p.getObjVal());
                for(s=0;s<NSHARES;s++) 
                    System.Console.WriteLine(s + ": " + frac[s].getSol()*100 +
                    			     "%");  
            }

            xprsp.InitGlobal();// Re-initialize the global search

            // Reset variables to their original bounds
            for(s=0;s<NSHARES;s++)
                if((fsol[s] < TOL) || (fsol[s] > 0.2-TOL))
                {
                    buy[s].setLB(0);
                    buy[s].setUB(1);
                }

            /* Load the saved basis: bound changes are
            immediately passed on from BCL to the
            Optimizer if the problem has not been modified
            in any other way, so that there is no need to 
            reload the matrix */
	        p.loadBasis(basis);        

             // No need to store the saved basis any longer 
            basis.reset();

            // Set the cutoff to the best known solution
            if (ifgsol == 1)
                xprsp.MIPAbsCutoff = solval + TOL;

        } 

    }

}

foliomip3.cs
/********************************************************
Xpress-BCL Java Example Problems
================================

file foliomip3.java
```````````````````
Modeling a MIP problem 
to perform portfolio optimization.
-- Extending the problem with constraints on 
  the geographical and sectorial distributions --
-- Working with a larger data set --

(c) 2009 Fair Isaac Corporation
  author: S.Heipcke, Y.Colombani, rev. Mar. 2011
********************************************************/

using System;
using System.Collections;
using System.Text;
using System.IO;
using BCL;


namespace Examples {
  public class TestUGFolioMip2 {
   const String DATAFILE = "folio10.cdat";

   const int MAXNUM = 7;          /* Max. number of different assets */
   const double MAXRISK = 1.0/3;  /* Max. investment into high-risk values */
   const double MINREG = 0.2;     /* Min. investment per geogr. region */
   const double MAXREG = 0.5;     /* Max. investment per geogr. region */
   const double MAXSEC = 0.25;    /* Max. investment per ind. sector */
   const double MAXVAL = 0.2;     /* Max. investment per share */
   const double MINVAL = 0.1;     /* Min. investment per share */

   static double[] RET;              /* Estimated return in investment  */
   static int[] RISK;                /* High-risk values among shares */
   static bool[][] LOC;           /* Geogr. region of shares */
   static bool[][] SEC;           /* Industry sector of shares */

   static String[] SHARES_n;
   static String[] REGIONS_n;
   static String[] TYPES_n;

   static readonly String[] MIPSTATUS = {"not loaded", "not optimized", 
                        "LP optimized", "unfinished (no solution)", 
                        "unfinished (solution found)", "infeasible", "optimal",
                        "unbounded"};
   
   public static void Main()
   { 
    try {
      readData();                     /* Read data from file */
    } catch (Exception exc){
      Console.Error.WriteLine(exc);
      Console.Error.WriteLine(Environment.StackTrace);
      return;
    }

    XPRB.init();                /* Initialize BCL */
    XPRBprob p = new XPRBprob("FolioMIP3");    /* Create a new problem in BCL */

    /* Create the decision variables */
    XPRBvar[] frac = new XPRBvar[SHARES_n.Length]; /* Fraction of capital used per share */
    XPRBvar[] buy = new XPRBvar[SHARES_n.Length]; /* 1 if asset is in portfolio, 0 otherwise */
    for(int s=0; s<SHARES_n.Length; s++)
    {
     frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, MAXVAL);
     buy[s] = p.newVar("buy", BCLconstant.XPRB_BV);
    }
     
  /* Objective: total return */
    XPRBexpr Return = new XPRBexpr();
    for(int s=0;s<SHARES_n.Length;s++) Return.add(frac[s] * RET[s]); 
    p.setObj(Return);                  /* Set the objective function */

  /* Limit the percentage of high-risk values */
    XPRBexpr Risk = new XPRBexpr();
    for(int s=0;s<RISK.Length;s++) Risk.add(frac[RISK[s]]); 
    p.newCtr(Risk <= MAXRISK);

  /* Limits on geographical distribution */
    XPRBexpr[] MinReg = new XPRBexpr[REGIONS_n.Length];
    XPRBexpr[] MaxReg = new XPRBexpr[REGIONS_n.Length];
    for(int r=0;r<REGIONS_n.Length;r++)
    {
     MinReg[r] = new XPRBexpr();
     MaxReg[r] = new XPRBexpr();
     for(int s=0;s<SHARES_n.Length;s++)
      if(LOC[r][s])
      {
       MinReg[r].add(frac[s]); 
       MaxReg[r].add(frac[s]);
      } 
      p.newCtr(MinReg[r] >= MINREG);
      p.newCtr(MaxReg[r] <= MAXREG);
    } 

  /* Diversification across industry sectors */
    XPRBexpr[] LimSec = new XPRBexpr[TYPES_n.Length];
    for(int t=0;t<TYPES_n.Length;t++)
    {
     LimSec[t] = new XPRBexpr();
     for(int s=0;s<SHARES_n.Length;s++)
      if(SEC[t][s]) LimSec[t].add(frac[s]); 
     p.newCtr(LimSec[t] <= MAXSEC);
    } 
   
  /* Spend all the capital */
    XPRBexpr Cap = new XPRBexpr();
    for(int s=0;s<SHARES_n.Length;s++) Cap.add(frac[s]); 
    p.newCtr(Cap == 1.0);
   
  /* Limit the total number of assets */
    XPRBexpr Num = new XPRBexpr();
    for(int s=0;s<SHARES_n.Length;s++) Num.add(buy[s]);
    p.newCtr(Num <= MAXNUM);

  /* Linking the variables */
    for(int s=0;s<SHARES_n.Length;s++) p.newCtr(frac[s] <= buy[s] * MAXVAL);
    for(int s=0;s<SHARES_n.Length;s++) p.newCtr(frac[s] >= buy[s] * MINVAL);

    p.exportProb(BCLconstant.XPRB_LP, "dnetmat.lp"); 

  /* Solve the problem */
    p.setSense(BCLconstant.XPRB_MAXIM);
    p.mipOptimize();

    Console.WriteLine("Problem status: " + MIPSTATUS[p.getMIPStat()]);
   
  /* Solution printing */
    Console.WriteLine("Total return: " + p.getObjVal());
    for(int s=0;s<SHARES_n.Length;s++) 
     if(buy[s].getSol()>0.5)
      Console.WriteLine("  " + s + ": " + frac[s].getSol()*100 + "% (" +
       buy[s].getSol() + ")");  
   }

  /***********************Data input routines***************************/

  /***************************/
  /* Input a list of strings */
  /***************************/
   private static String[] read_str_list(String data)
   {
    return data.Split();
   }
   
   private static Array read_list(String data, Type ty) {
    ArrayList li = new ArrayList();
    foreach(String s in data.Split()) {
      if (s == null || s == "") { continue; }
      Object value = Convert.ChangeType(s, ty);
      li.Add(value);
    }
    return li.ToArray(ty);
   }

  /************************/
  /* Input a list of ints */
  /************************/
   private static int[] read_int_list(String data) 
   {
    return (int[])read_list(data, typeof(int));
   }

  /****************************/
  /* Input a table of doubles */
  /****************************/
   private static double[] read_dbl_list(String data) 
   {
    return (double[])read_list(data, typeof(double));
   }
   
   private static bool[] read_bool_list(String data, int len) {
    bool[] bools = new bool[len];
    int[] trues = read_int_list(data);
    foreach(int t in trues) {
      bools[t] = true;
    }
    return bools;
   }

  /************************************/
  /* Input a sparse table of bools */
  /************************************/
   private static bool[][] read_bool_table(StreamReader r, int nrows, int ncols)
   {
    bool[][] lists = new bool[nrows][];
    for (int i = 0; i < nrows; i++) { lists[i] = new bool[ncols]; }
    
    for (int i = 0; i < nrows; i++) {
      String line = r.ReadLine();
      if (line == null) { break; }
      LineData ld = new LineData(line);
      if (ld.data == "") { break; }
      
      bool[] row = read_bool_list(ld.data, ncols);
      lists[i] = row;
    }
    return lists;
   }
   
   private class LineData {
    internal String name;
    internal String data;
    
    internal LineData(String line) {
      name = "";
      data = "";
      line = line.Trim();
      String[] split = line.Split(new char[] {'!'}, 2); // the comment char
      if (split.Length == 0) { return; }
      line = split[0].Trim();
      // chop into name:data pair
      split = line.Split(new char[]{':'}, 2);
      if (split.Length == 0) { return; }
      if (split.Length > 1) {
        name = split[0].Trim();
      }
      // lose trailing ';'
      data = split[split.Length - 1].Trim().TrimEnd(';').Trim();
    }
  }
  
   private static void readData() 
   {
    using (StreamReader r = new StreamReader(DATAFILE)) {
      for(;;) {
        String line = r.ReadLine();
        if (line == null) { break; }
        LineData ld = new LineData(line);
        if (ld.name == "SHARES" && SHARES_n == null) {
          SHARES_n = read_str_list(ld.data);
        } else if (ld.name == "REGIONS" && REGIONS_n == null) {
          REGIONS_n = read_str_list(ld.data);
        } else if (ld.name == "TYPES" && TYPES_n == null) {
          TYPES_n = read_str_list(ld.data);
        } else if (ld.name == "RISK" && RISK == null) {
          RISK = read_int_list(ld.data);
        } else if (ld.name == "RET" && RET == null) {
          RET = read_dbl_list(ld.data);
        } else if (ld.name == "LOC" && SHARES_n != null && REGIONS_n != null) {
          LOC = read_bool_table(r, REGIONS_n.Length, SHARES_n.Length);
        } else if (ld.name == "SEC" && SHARES_n != null && REGIONS_n != null) {
          SEC = read_bool_table(r, TYPES_n.Length, SHARES_n.Length);
        }
      }
    }
   }
  } 
}

folioiis.cs
/********************************************************
Xpress-BCL Java Example Problems
================================

file folioiis.cs
```````````````````
Modeling a MIP problem 
to perform portfolio optimization.
Same model as in foliomip3.cs.
-- Infeasible model parameter values --
-- Retrieving IIS --

(c) 2014 Fair Isaac Corporation
  author: L.Bertacco, September 2014
********************************************************/

using System;
using System.Collections;
using System.Text;
using System.IO;
using BCL;

namespace Examples
{
  public class TestUGFolioIIS
  {
    const String DATAFILE = "folio10.cdat";

    const int MAXNUM = 5;          /* Max. number of different assets */
    const double MAXRISK = 1.0/3;  /* Max. investment into high-risk values */
    const double MINREG = 0.1;     /* Min. investment per geogr. region */
    const double MAXREG = 0.2;     /* Max. investment per geogr. region */
    const double MAXSEC = 0.1;     /* Max. investment per ind. sector */
    const double MAXVAL = 0.2;     /* Max. investment per share */
    const double MINVAL = 0.1;     /* Min. investment per share */

    static double[] RET;           /* Estimated return in investment  */
    static int[] RISK;             /* High-risk values among shares */
    static bool[][] LOC;           /* Geogr. region of shares */
    static bool[][] SEC;           /* Industry sector of shares */

    static String[] SHARES_n;
    static String[] REGIONS_n;
    static String[] TYPES_n;

    static readonly String[] MIPSTATUS = {"not loaded", "not optimized", 
                    "LP optimized", "unfinished (no solution)", 
                    "unfinished (solution found)", "infeasible", "optimal",
                    "unbounded"};

    public static void Main()
    {
      try
      {
        readData();                     /* Read data from file */
      }
      catch (Exception exc)
      {
        Console.Error.WriteLine(exc);
        Console.Error.WriteLine(Environment.StackTrace);
        return;
      }

      XPRB.init();                /* Initialize BCL */
      XPRBprob p = new XPRBprob("FolioMIP3inf");  /* Create a new problem in BCL */

      /* Create the decision variables */
      XPRBvar[] frac = new XPRBvar[SHARES_n.Length]; /* Fraction of capital used per share */
      XPRBvar[] buy = new XPRBvar[SHARES_n.Length]; /* 1 if asset is in portfolio, 0 otherwise */
      for (int s = 0; s < SHARES_n.Length; s++)
      {
        frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, MAXVAL);
        buy[s] = p.newVar("buy", BCLconstant.XPRB_BV);
      }

      /* Objective: total return */
      XPRBexpr Return = new XPRBexpr();
      for (int s = 0; s < SHARES_n.Length; s++) Return.add(frac[s] * RET[s]);
      p.setObj(Return);                  /* Set the objective function */

      /* Limit the percentage of high-risk values */
      XPRBexpr Risk = new XPRBexpr();
      for (int s = 0; s < RISK.Length; s++) Risk.add(frac[RISK[s]]);
      p.newCtr(Risk <= MAXRISK);

      /* Limits on geographical distribution */
      XPRBexpr[] MinReg = new XPRBexpr[REGIONS_n.Length];
      XPRBexpr[] MaxReg = new XPRBexpr[REGIONS_n.Length];
      for (int r = 0; r < REGIONS_n.Length; r++)
      {
        MinReg[r] = new XPRBexpr();
        MaxReg[r] = new XPRBexpr();
        for (int s = 0; s < SHARES_n.Length; s++)
          if (LOC[r][s])
          {
            MinReg[r].add(frac[s]);
            MaxReg[r].add(frac[s]);
          }
        p.newCtr(MinReg[r] >= MINREG);
        p.newCtr(MaxReg[r] <= MAXREG);
      }

      /* Diversification across industry sectors */
      XPRBexpr[] LimSec = new XPRBexpr[TYPES_n.Length];
      for (int t = 0; t < TYPES_n.Length; t++)
      {
        LimSec[t] = new XPRBexpr();
        for (int s = 0; s < SHARES_n.Length; s++)
          if (SEC[t][s]) LimSec[t].add(frac[s]);
        p.newCtr(LimSec[t] <= MAXSEC);
      }

      /* Spend all the capital */
      XPRBexpr Cap = new XPRBexpr();
      for (int s = 0; s < SHARES_n.Length; s++) Cap.add(frac[s]);
      p.newCtr(Cap == 1.0);

      /* Limit the total number of assets */
      XPRBexpr Num = new XPRBexpr();
      for (int s = 0; s < SHARES_n.Length; s++) Num.add(buy[s]);
      p.newCtr(Num <= MAXNUM);

      /* Linking the variables */
      for (int s = 0; s < SHARES_n.Length; s++) p.newCtr(frac[s] <= buy[s] * MAXVAL);
      for (int s = 0; s < SHARES_n.Length; s++) p.newCtr(frac[s] >= buy[s] * MINVAL);

      p.exportProb(BCLconstant.XPRB_LP, "dnetmat.lp");

      /* Solve the problem */
      p.setSense(BCLconstant.XPRB_MAXIM);
      p.lpOptimize();

      Console.WriteLine("Problem status: " + p.getLPStat());
      if (p.getLPStat() == BCLconstant.XPRB_LP_INFEAS) 
      {
        Console.WriteLine("LP infeasible. Retrieving IIS.");             

        int numiis = p.getNumIIS();       /* Get the number of independent IIS */
        Console.WriteLine("Number of IIS: " + numiis);

        for(int s=1; s<=numiis; s++) 
        {
          ArrayList iisctr = new ArrayList();
          ArrayList iisvar = new ArrayList();
          p.getIIS(iisvar, iisctr, s);
          Console.WriteLine("IIS {0}: {1} variables, {2} constraints", s, iisvar.Count, iisctr.Count);                    
          if (iisvar.Count > 0)
          {                              /* Print all variables in the IIS */
            Console.Write("        Variables: ");
            foreach(XPRBvar v in iisvar) Console.Write("{0} ", v.getName());
            Console.WriteLine();
          } 
          if (iisctr.Count>0)
          {                              /* Print all constraints in the IIS */
            Console.Write("        Constraints: ");
            foreach (XPRBctr c in iisctr) Console.Write("{0} ", c.getName());
            Console.WriteLine();
          }
        }                
      }
      else 
      {
        /* Solution printing */
        Console.WriteLine("Total return: " + p.getObjVal());
        for (int s = 0; s < SHARES_n.Length; s++)
          if (buy[s].getSol() > 0.5)
            Console.WriteLine("  " + s + ": " + frac[s].getSol() * 100 + "% (" +
              buy[s].getSol() + ")");
      }
    }

    /***********************Data input routines***************************/
  
    /***************************/
    /* Input a list of strings */
    /***************************/
    private static String[] read_str_list(String data)
    {
      return data.Split();
    }
  
    private static Array read_list(String data, Type ty)
    {
      ArrayList li = new ArrayList();
      foreach (String s in data.Split())
      {
        if (s == null || s == "") { continue; }
        Object value = Convert.ChangeType(s, ty);
        li.Add(value);
      }
      return li.ToArray(ty);
    }
  
    /************************/
    /* Input a list of ints */
    /************************/
    private static int[] read_int_list(String data)
    {
      return (int[])read_list(data, typeof(int));
    }
  
    /****************************/
    /* Input a table of doubles */
    /****************************/
    private static double[] read_dbl_list(String data)
    {
      return (double[])read_list(data, typeof(double));
    }
  
    private static bool[] read_bool_list(String data, int len)
    {
      bool[] bools = new bool[len];
      int[] trues = read_int_list(data);
      foreach (int t in trues) bools[t] = true;
      return bools;
    }
  
    /************************************/
    /* Input a sparse table of bools */
    /************************************/
    private static bool[][] read_bool_table(StreamReader r, int nrows, int ncols)
    {
      bool[][] lists = new bool[nrows][];
      for (int i = 0; i < nrows; i++) { lists[i] = new bool[ncols]; }
  
      for (int i = 0; i < nrows; i++)
      {
        String line = r.ReadLine();
        if (line == null) { break; }
        LineData ld = new LineData(line);
        if (ld.data == "") { break; }
  
        bool[] row = read_bool_list(ld.data, ncols);
        lists[i] = row;
      }
      return lists;
    }
  
    private class LineData
    {
      internal String name;
      internal String data;
  
      internal LineData(String line)
      {
        name = "";
        data = "";
        line = line.Trim();
        String[] split = line.Split(new char[] { '!' }, 2); // the comment char
        if (split.Length == 0) { return; }
        line = split[0].Trim();
        // chop into name:data pair
        split = line.Split(new char[] { ':' }, 2);
        if (split.Length == 0) { return; }
        if (split.Length > 1) name = split[0].Trim();
        // lose trailing ';'
        data = split[split.Length - 1].Trim().TrimEnd(';').Trim();
      }
    }
  
    private static void readData()
    {
      using (StreamReader r = new StreamReader(DATAFILE))
      {
        for (; ; )
        {
          String line = r.ReadLine();
          if (line == null) { break; }
          LineData ld = new LineData(line);
          if (ld.name == "SHARES" && SHARES_n == null)        
            SHARES_n = read_str_list(ld.data);
          else if (ld.name == "REGIONS" && REGIONS_n == null) 
            REGIONS_n = read_str_list(ld.data);
          else if (ld.name == "TYPES" && TYPES_n == null)     
            TYPES_n = read_str_list(ld.data);
          else if (ld.name == "RISK" && RISK == null)         
            RISK = read_int_list(ld.data);
          else if (ld.name == "RET" && RET == null)           
            RET = read_dbl_list(ld.data);
          else if (ld.name == "LOC" && SHARES_n != null && REGIONS_n != null)
            LOC = read_bool_table(r, REGIONS_n.Length, SHARES_n.Length);
          else if (ld.name == "SEC" && SHARES_n != null && REGIONS_n != null)
            SEC = read_bool_table(r, TYPES_n.Length, SHARES_n.Length);
        }
      }
    }
  }
}