Search This Blog

Saturday, September 15, 2012

Quadratic programming solver using a null-space active-set method in matlab

% Quadratic programming solver using a null-space active-set method.
%
% [x, obj, lambda, info] = qpng (H, q, A, b, ctype, lb, ub, x0)
%
% Solve the general quadratic program
%
%      min 0.5 x'*H*x + q'*x
%       x
%
% subject to
%      A*x [ "=" | "<=" | ">=" ] b
%      lb <= x <= ub
%
% and given x0 as initial guess.
%
% ctype = An array of characters containing the sense of each constraint in the
%         constraint matrix.  Each element of the array may be one of the
%         following values
%           'U' Variable with upper bound ( A(i,:)*x <= b(i) ).
%           'E' Fixed Variable ( A(i,:)*x = b(i) ).
%           'L' Variable with lower bound ( A(i,:)*x >= b(i) ).
%
% status = an integer indicating the status of the solution, as follows:
%        0 The problem is infeasible.
%        1 The problem is feasible and convex.  Global solution found.
%        2 Max number of iterations reached no feasible solution found.
%        3 Max number of iterations reached but a feasible solution found.
%
% If only 4 arguments are provided the following QP problem is solved:
%
% min_x .5 x'*H*x+x'*q   s.t. A*x <= b
%
% Any bound (ctype, lb, ub, x0) may be set to the empty matrix []
% if not present.  If the initial guess is feasible the algorithm is faster.
%
% See also: glpk.
%
% Copyright 2006-2007 Nicolo Giorgetti.

% This file is part of GLPKMEX.
%
% GLPKMEX is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2, or (at your option)
% any later version.
%
% GLPKMEX is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GLPKMEX; see the file COPYING.  If not, write to the Free
% Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA.

function varargout = qpng (varargin)

% Inputs
H=[];
q=[];
A=[];
b=[];
lb=[];
ub=[];
x0=[];
ctype=[];

% Outputs
x=[];
obj=[];
lambda=[];
info=[];

if nargin < 1
   disp('Quadratic programming solver using null-space active set method.');
   disp('(C) 2006-2007, Nicolo Giorgetti. Version 1.0');
   disp(' ');
   disp('Syntax: [x, obj, lambda, info] = qpng (H, q, A, b, ctype, lb, ub, x0)');
   return;
end
if nargin<4 br="br">   error('At least 4 argument are necessary');
else
   H=varargin{1};
   q=varargin{2};
   A=varargin{3};
   b=varargin{4};
end
if nargin>=5
   ctype=varargin{5};
end
if nargin>=7
   lb=varargin{6};
   ub=varargin{7};
end
if nargin>=8
   x0=varargin{8};  
end
if nargin>8
   warning('qpng: Arguments more the 8th are omitted');
end
  
% Checking the quadratic penalty
[n,m] = size(H);
if n ~= m
   error('qpng: Quadratic penalty matrix not square');
end

if H ~= H'
   warning('qpng: Quadratic penalty matrix not symmetric');
   H = (H + H')/2;
end

% Linear penalty.
if isempty(q)
   q=zeros(n,1);
else
   if length(q) ~= n
      error('qpng: The linear term has incorrect length');
   end
end

% Constraint matrices
if (isempty(A) || isempty(b))
   error('qpng: Constraint matrices cannot be empty');
end
[nn, n1] = size(A);
if n1 ~= n
   error('qpng: Constraint matrix has incorrect column dimension');
end
if length (b) ~= nn
   error ('qpng: Equality constraint matrix and vector have inconsistent dimension');
end

Aeq=[];
beq=[];
Ain=[];
bin=[];

if nargin <= 4
   Ain=A;
   bin=b;
end

if ~isempty(ctype)
   if length(ctype) ~= nn
       tmp=sprintf('qpng: ctype must be a char valued vector of length %d', nn);
       error(tmp);
   end
   indE=find(ctype=='E');
   Aeq=A(indE,:);
   beq=b(indE,:);  
  
   indU=find(ctype=='U');
   Ain=A(indU,:);
   bin=b(indU,:);
   indL=find(ctype=='L');
   Ain=[Ain; -A(indL,:)];
   bin=[bin; -b(indL,:)];    
end

if ~isempty(lb)
   if length(lb) ~= n
      error('qpng: Lower bound has incorrect length');
    else
      Ain = [Ain; -eye(n)];
      bin = [bin; -lb];
   end
end

if ~isempty(ub)
   if length(ub) ~= n
      error('qpng: Upper bound has incorrect length');
    else
      Ain = [Ain; eye(n)];
      bin = [bin; ub];
   end
end

% Discard inequality constraints that have -Inf bounds since those
% will never be active.
idx = isinf(bin) &  (bin > 0);
bin(idx) = [];
Ain(idx,:) = [];

% Now we should have the following QP:
%
%   min_x  0.5*x'*H*x + q'*x
%   s.t.   A*x = b
%          Ain*x <= bin

% Checking the initial guess (if empty it is resized to the
% right dimension and filled with 0)
if isempty(x0)
   x0 = zeros(n, 1);
elseif length(x0) ~= n
   error('qpng: The initial guess has incorrect length');
end

% Check if the initial guess is feasible.
rtol = sqrt (eps);

n_eq=size(Aeq,1);
n_in=size(Ain,1);

eq_infeasible=0;
in_infeasible=0;

if n_eq>0
   eq_infeasible = (norm(Aeq*x0-beq) > rtol*(1+norm(beq)));
end
if n_in>0
   in_infeasible = any(Ain*x0-bin > 0);
end

status = 1;

% if (eq_infeasible | in_infeasible)
%    % The initial guess is not feasible. Find one by solving an LP problem.
%    % This function has to be improved by moving in the null space.
%    Atmp=[Aeq; Ain];
%    btmp=[beq; bin];
%    ctmp=zeros(size(Atmp,2),1);
%    ctype=char(['S'*ones(1,n_eq), 'U'*ones(1,n_in)]');
%    [P, dummy, stat] = glpk (ctmp, Atmp, btmp, [], [], ctype);
%
%    if  (stat == 180 | stat == 181 | stat == 151)
%       x0=P;
%    else
%       % The problem is infeasible
%       status = 0;
%    end
%  
% end

if (eq_infeasible | in_infeasible)
   % The initial guess is not feasible.
   % First define xbar that is feasible with respect to the equality
   % constraints.
   if (eq_infeasible)
      if (rank(Aeq) < n_eq)
         error('qpng: Equality constraint matrix must be full row rank')
      end
      xbar = pinv(Aeq) * beq;
   else
      xbar = x0;
   end

   % Check if xbar is feasible with respect to the inequality
   % constraints also.
   if (n_in > 0)
      res = Ain * xbar - bin;
      if any(res > 0)
         % xbar is not feasible with respect to the inequality
         % constraints.  Compute a step in the null space of the
         % equality constraints, by solving a QP.  If the slack is
         % small, we have a feasible initial guess.  Otherwise, the
         % problem is infeasible.
         if (n_eq > 0)
            Z = null(Aeq);
            if (isempty(Z))
               % The problem is infeasible because A is square and full
               % rank, but xbar is not feasible.
               info = 0;
            end
         end

         if info
            % Solve an LP with additional slack variables to find
            % a feasible starting point.
            gamma = eye(n_in);
            if (n_eq > 0)
               Atmp = [Ain*Z, gamma];
               btmp = -res;
            else
               Atmp = [Ain, gamma];
               btmp = bin;
            end
            ctmp = [zeros(n-n_eq, 1); ones(n_in, 1)];
            lb = [-Inf*ones(n-n_eq,1); zeros(n_in,1)];
            ub = [];
            ctype = repmat ('L', n_in, 1);
            [P, dummy, status] = glpk (ctmp, Atmp, btmp, lb, ub, ctype);

            if ((status == 180 | status == 181 | status == 151) & all (abs (P(n-n_eq+1:end)) < rtol * (1 + norm (btmp))))
               % We found a feasible starting point
               if (n_eq > 0)
                  x0 = xbar + Z*P(1:n-n_eq);
               else
                  x0 = P(1:n);
               end
            else
               % The problem is infeasible
               info = 0;
            end
         end
      else
         % xbar is feasible.  We use it a starting point.
         x0 = xbar;
      end
   else
      % xbar is feasible.  We use it a starting point.
      x0 = xbar;
   end
end


if status
   % The initial (or computed) guess is feasible.
   % We call the solver.
   t=cputime;
   [x, lambda, iter, status]=qpsolng(H, q, Aeq, beq, Ain, bin, x0);
   time=cputime-t;
else
   iter = 0;
   x = x0;
   lambda = [];
   time=0;
end

varargout{1}= x;
varargout{2}= 0.5 * x' * H * x + q' * x; %obj
varargout{3}= lambda;

info=struct('status', status, 'solveiter', iter, 'time', time);
varargout{4}=info;




GLPKMEX - Matlab MEX interface: Contents

% GLPKMEX - Matlab MEX interface contents
%
% Files
%   glpk        - Matlab MEX interface for the GLPK library
%   glpksparse  - A LP example which defines A as a sparse matrix
%   glpktest1   - A LP example which shows all the potentials of GLPKMEX
%   glpktest2   - Two examples to show how to solve an MILP and an LP with interior method
%   makeglpkmex - Use this function to build your own MEX interface
%   qpng        - Quadratic programming solver using a null-space active-set method.
%   qpsolng     - Core QP Solver. Use qpng.m instead.
%   qptest      - QP test problem. Demo file
%   INSTALL     - directions to install glpk
%   mps2mat.py  - python script for converting mps files to mat
%   INSTALL_mps2mat - installation instructions for installing mps2mat.py
%   glpkcc.cpp  - source file for glpkmex
%   glpkcc.mex### - precompiled version og glpkcc

GLPKMEX MEX Interface for the GLPK Callable Library

% GLPKMEX MEX Interface for the GLPK Callable Library
%
% Copyright (C) 2004-2007, Nicolo' Giorgetti, All right reserved.
% E-mail: .
%
% This file is part of GLPKMEX.
%
% GLPKMEX is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2, or (at your option)
% any later version.
%
% This part of code is distributed with the FURTHER condition that it is
% possible to link it to the Matlab libraries and/or use it inside the Matlab
% environment.
%
% GLPKMEX is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
% License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GLPKMEX; see the file COPYING. If not, write to the Free
% Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA.

Quadratic programming solver using a null-space active-set method

% Quadratic programming solver using a null-space active-set method.
%
% [x, obj, lambda, info] = qpng (H, q, A, b, ctype, lb, ub, x0)
%
% Solve the general quadratic program
%
%      min 0.5 x'*H*x + q'*x
%       x
%
% subject to
%      A*x [ "=" | "<=" | ">=" ] b
%      lb <= x <= ub
%
% and given x0 as initial guess.
%
% ctype = An array of characters containing the sense of each constraint in the
%         constraint matrix.  Each element of the array may be one of the
%         following values
%           'U' Variable with upper bound ( A(i,:)*x <= b(i) ).
%           'E' Fixed Variable ( A(i,:)*x = b(i) ).
%           'L' Variable with lower bound ( A(i,:)*x >= b(i) ).
%
% status = an integer indicating the status of the solution, as follows:
%        0 The problem is infeasible.
%        1 The problem is feasible and convex.  Global solution found.
%        2 Max number of iterations reached no feasible solution found.
%        3 Max number of iterations reached but a feasible solution found.
%
% If only 4 arguments are provided the following QP problem is solved:
%
% min_x .5 x'*H*x+x'*q   s.t. A*x <= b
%
% Any bound (ctype, lb, ub, x0) may be set to the empty matrix []
% if not present.  If the initial guess is feasible the algorithm is faster.
%
% See also: glpk.
%
% Copyright 2006-2007 Nicolo Giorgetti.

% This file is part of GLPKMEX.
%
% GLPKMEX is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2, or (at your option)
% any later version.
%
% GLPKMEX is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GLPKMEX; see the file COPYING.  If not, write to the Free
% Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA.

Calling GLPK From Matlab Example

Make sure you have downloaded glpkmex and you matlab current working directory is glpkmex

Example:
   c = [10, 6, 4]';
  a = [ 1, 1, 1;
      10, 4, 5;
       2, 2, 6];
  b = [100, 600, 300]';
  lb = [0, 0, 0]';
  ub = [];
  ctype = "UUU";
  vartype = "CCC";
  s = -1;
 param.msglev = 1;
param.itlim = 100;
 [xmin, fmin, status, extra] = ...
   glpk (c, a, b, lb, ub, ctype, vartype, s, param);

Matlab MEX interface for the GLPK library

 % Matlab MEX interface for the GLPK library
%
% [xopt, fmin, status, extra] = glpk (c, a, b, lb, ub, ctype, vartype,
% sense, param)
%
% Solve an LP/MILP problem using the GNU GLPK library. Given three
% arguments, glpk solves the following standard LP:
%
% min C'*x subject to A*x  <= b
%
% but may also solve problems of the form
%
% [ min | max ] C'*x
% subject to
%   A*x [ "=" | "<=" | ">=" ] b
%   x >= LB
%   x <= UB
%
% Input arguments:
% c = A column array containing the objective function coefficients.
%
% A = A matrix containing the constraints coefficients.
%
% b = A column array containing the right-hand side value for each constraint
%     in the constraint matrix.
%
% lb = An array containing the lower bound on each of the variables.  If
%      lb is not supplied (or an empty array) the default lower bound for the variables is
%      minus infinite.
%
% ub = An array containing the upper bound on each of the variables.  If
%      ub is not supplied (or an empty array) the default upper bound is assumed to be
%      infinite.
%
% ctype = An array of characters containing the sense of each constraint in the
%         constraint matrix.  Each element of the array may be one of the
%         following values
%           'F' Free (unbounded) variable (the constraint is ignored).
%           'U' Variable with upper bound ( A(i,:)*x <= b(i)).
%           'S' Fixed Variable (A(i,:)*x = b(i)).
%           'L' Variable with lower bound (A(i,:)*x >= b(i)).
%           'D' Double-bounded variable (A(i,:)*x >= -b(i) and A(i,:)*x <= b(i)).

% vartype = A column array containing the types of the variables.
%               'C' Continuous variable.
%               'I' Integer variable
%               'B' Binary variable
%
% sense = If sense is 1, the problem is a minimization.  If sense is
%         -1, the problem is a maximization.  The default value is 1.
%
% param = A structure containing the following parameters used to define the
%         behavior of solver.  Missing elements in the structure take on default
%         values, so you only need to set the elements that you wish to change
%         from the default.
%
%         Integer parameters:
%           msglev (default: 1)
%                  Level of messages output by solver routines:
%                   0 - No output.
%                   1 - Error messages only.
%                   2 - Normal output.
%                   3 - Full output (includes informational messages).
%
%           scale (default: 1). Scaling option:
%                   0 - No scaling.
%                   1 - Equilibration scaling.
%                   2 - Geometric mean scaling, then equilibration scaling.
%                   3 - Geometric then Equilibrium scaling
%                   4 - Round to nearest power of 2 scaling
%
%           dual (default: 0). Dual simplex option:
%                   0 - Do not use the dual simplex.
%                   1 - If initial basic solution is dual feasible, use
%                       the dual simplex.
%                   2- Use two phase dual simplex, or if primal simplex
%                       if dual fails
%
%           price (default: 1). Pricing option (for both primal and dual simplex):
%                   0 - Textbook pricing.
%                   1 - Steepest edge pricing.
%  
%           r_test (default: 1). Ratio test Technique:
%                   0 - stardard (textbook)
%                   1 - Harris's two-pass ratio test
%  
%           round (default: 0). Solution rounding option:
%
%                   0 - Report all primal and dual values "as is".
%                   1 - Replace tiny primal and dual values by exact zero.
%
%           itlim (default: -1). Simplex iterations limit. 
%                 If this value is positive, it is decreased by one each
%                 time when one simplex iteration has been performed, and
%                 reaching zero value signals the solver to stop the search.
%                 Negative value means no iterations limit.
%
%           itcnt (default: 200). Output frequency, in iterations. 
%                 This parameter specifies how frequently the solver sends
%                 information about the solution to the standard output.
%
%           presol (default: 1). If this flag is set, the routine
%                  lpx_simplex solves the problem using the built-in LP presolver.
%                  Otherwise the LP presolver is not used.
%
%           lpsolver (default: 1) Select which solver to use.
%                  If the problem is a MIP problem this flag will be ignored.
%                   1 - Revised simplex method.
%                   2 - Interior point method.
%                   3 - Simplex method with exact arithmatic.                      
%
%           branch (default: 2). Branching heuristic option (for MIP only):
%                   0 - Branch on the first variable.
%                   1 - Branch on the last variable.
%                   2 - Branch on the most fractional variable.
%                   3 - Branch using a heuristic by Driebeck and Tomlin.
%
%           btrack (default: 2). Backtracking heuristic option (for MIP only):
%                   0 - Depth first search.
%                   1 - Breadth first search.
%                   2 - best local bound
%                   3 - Backtrack using the best projection heuristic.
%
%           pprocess (default: 2) Pre-processing technique option ( for MIP only ):
%                   0 - disable preprocessing
%                   1 - perform preprocessing for root only
%                   2 - perform preprocessing for all levels
%       
%           usecuts (default: 1). ( for MIP only ):
%                  glp_intopt generates and adds cutting planes to
%                  the MIP problem in order to improve its LP relaxation
%                  before applying the branch&bound method
%                   0 -> all cuts off
%                   1 -> Gomoy's mixed integer cuts
%                   2 -> Mixed integer rounding cuts
%                   3 -> Mixed cover cuts
%                   4 -> Clique cuts
%                   5 -> all cuts
%
%           binarize (default: 0 ) Binarizeation option ( for mip only ):
%               ( used only if presolver is enabled )
%                   0 -> do not use binarization
%                   1 -> replace general integer variables by binary ones
%
%           save (default: 0). If this parameter is nonzero save a copy of
%                the original problem to file. You can specify the
%                file name and format by using the 'savefilename' and
%                'savefiletype' parameters (see in String Parameters Section
%                here below).
%                If previous parameters are not defined, the original problem
%                is saved with CPLEX LP format in the default file "outpb.lp".
%
%           mpsinfo (default: 1) If this is set,
%                   the interface writes to file several comment cards,
%                   which contains some information about the problem.
%                   Otherwise the routine writes no comment cards.
%
%           mpsobj ( default: 2) This parameter tells the
%                  routine how to output the objective function row:
%                    0 - never output objective function row
%                    1 - always output objective function row
%                    2 - output objective function row if the problem has
%                        no free rows
%
%           mpsorig (default: 0) If this is set, the
%                   routine uses the original symbolic names of rows and
%                   columns. Otherwise the routine generates plain names
%                   using ordinal numbers of rows and columns.
%
%           mpswide (default: 1) If this is set, the
%                   routine uses all data fields. Otherwise the routine
%                   keeps fields 5 and 6 empty.
%
%           mpsfree (default: 0) If this is set, the routine
%                   omits column and vector names every time when possible
%                   (free style). Otherwise the routine never omits these
%                   names (pedantic style).
%
%
%         Real parameters:
%           relax (default: 0.07). Relaxation parameter used
%                 in the ratio test. If it is zero, the textbook ratio test
%                 is used. If it is non-zero (should be positive), Harris'
%                 two-pass ratio test is used. In the latter case on the
%                 first pass of the ratio test basic variables (in the case
%                 of primal simplex) or reduced costs of non-basic variables
%                 (in the case of dual simplex) are allowed to slightly violate
%                 their bounds, but not more than relax*tolbnd or relax*toldj
%                 (thus, relax is a percentage of tolbnd or toldj).
%
%           tolbnd (default: 10e-7). Relative tolerance used
%                  to check ifthe current basic solution is primal feasible.
%                  It is not recommended that you change this parameter
%                  unless you have a detailed understanding of its purpose.
%
%           toldj (default: 10e-7). Absolute tolerance used to
%                 check if the current basic solution is dual feasible.  It
%                 is not recommended that you change this parameter unless
%                 you have a detailed understanding of its purpose.
%
%           tolpiv (default: 10e-9). Relative tolerance used
%                  to choose eligible pivotal elements of the simplex table.
%                  It is not recommended that you change this parameter
%                  unless you have a detailed understanding of its purpose.
%
%           objll ( default: -DBL_MAX). Lower limit of the
%                 objective function. If on the phase II the objective
%                 function reaches this limit and continues decreasing, the
%                 solver stops the search. This parameter is used in the
%                 dual simplex method only.
%
%           objul (default: +DBL_MAX). Upper limit of the
%                 objective function. If on the phase II the objective
%                 function reaches this limit and continues increasing,
%                 the solver stops the search. This parameter is used in
%                 the dual simplex only.
%
%           tmlim (default: -1.0). Searching time limit, in
%                 seconds. If this value is positive, it is decreased each
%                 time when one simplex iteration has been performed by the
%                 amount of time spent for the iteration, and reaching zero
%                 value signals the solver to stop the search. Negative
%                 value means no time limit.
%
%           outdly (default: 0.0). Output delay, in seconds.
%                  This parameter specifies how long the solver should
%                  delay sending information about the solution to the standard
%                  output. Non-positive value means no delay.
%
%           tolint (default: 10e-5). Relative tolerance used
%                  to check if the current basic solution is integer
%                  feasible. It is not recommended that you change this
%                  parameter unless you have a detailed understanding of
%                  its purpose.
%
%           tolobj (default: 10e-7). Relative tolerance used
%                  to check if the value of the objective function is not
%                  better than in the best known integer feasible solution. 
%                  It is not recommended that you change this parameter
%                  unless you have a detailed understanding of its purpose.
%
%           mipgap (default: 0.0) The relative mip gap tolerance.  If the
%                  relative mip gap for currently known best integer feasible
%                  solution falls below this tolerance, the solver terminates
%                  the search.  This allows obtaining suboptimal interger
%                  feasible solutions if solving the problem to optimality
%                  takes too long.
%
%         String Parameters:
%           savefilename (default: "outpb"). Specify the name to use to
%                        save the original problem. MEX interface looks for
%                        this parameter if 'save' parameter is set to 1. If
%                        no name is provided "outpb" will be used.
%           savefiletype (default: CPLEX format). Specify the format type
%                        used to save the file. Only the following options
%                        are allowed:
%                          'fixedmps' - fixed MPS format (.mps).
%                          'freemps'  - free MPS format (.mps).
%                          'cplex'    - CPLEX LP format (.lp).
%                          'plain'    - plain text (.txt).
%
% Output values:
% xopt = The optimizer (the value of the decision variables at the optimum).
%
% fopt = The optimum value of the objective function.
%
% status = Status of the optimization.
%               1 solution is undefined
%               2 solution is feasible
%               3 solution is infeasible
%               4 no feasible solution exists
%               5 solution is optimal
%               6 solution is unbounded
%
%          If an error occurs, status will contain one of the following
%          codes.
%          Simplex method:
%               101 invalid basis
%               102 singular matrix
%               103 ill-conditioned matrix
%               104 invalid bounds
%               105 solver failed
%               106 objective lower limit reached
%               107 objective upper limit reached
%               108 iteration limit exceeded
%               109 time limit exceeded
%               110 no primal feasible solution
%               111 no dual feasible solution
%
%          Mixed integer problem, interior point method:
%               204 incorrect bounds
%               205 solver failure
%               209 time limit exceeded
%               210 no primal feasible solution
%               212 missing basis
%               214 MIP gap tolerance reached
%               305 problem with no rows/columsn
%               308 iteration limit exceeded
%               316 very slow convergence/divergence
%               317 numerical instability in solving Newtonian system
%
% extra = A data structure containing the following fields:
%           lambda - Dual variables.
%           redcosts - Reduced Costs.
%           time - Time (in seconds) used for solving LP/MIP problem.
%           mem - Memory (in Kbytes) used for solving LP/MIP problem.
%
% Example:
%
% c = [10, 6, 4]';
% a = [ 1, 1, 1;
%      10, 4, 5;
%       2, 2, 6];
% b = [100, 600, 300]';
% lb = [0, 0, 0]';
% ub = [];
% ctype = "UUU";
% vartype = "CCC";
% s = -1;
%
% param.msglev = 1;
% param.itlim = 100;
%
% [xmin, fmin, status, extra] = ...
%     glpk (c, a, b, lb, ub, ctype, vartype, s, param);
%
% See also: qpng.
%
% Copyright 2005-2007 Nicolo' Giorgetti
% Email: Nicolo' Giorgetti
% updated by Niels Klitgord March 2009
% Email: Niels Klitgord

% This file is part of GLPKMEX.
%
% GLPKMEX is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2, or (at your option)
% any later version.
%
% This part of code is distributed with the FURTHER condition that it
% can be linked to the Matlab libraries and/or use it inside the Matlab
% environment.
%
% GLPKMEX is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GLPKMEX; see the file COPYING.  If not, write to the Free
% Software Foundation, 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA.

Calling GLPK From MATLAB

Before writing this post, my original aim was to find a roboust MIP solver that can be used through Matlab on the Win32 platform. However, I found several interfaces to the popular CPLEX (such as Claude Tadonki's solution) but these solutions have not been updated for several years. Fortunately, I hit on Nicolo' Giorgetti's glpkmex project that is more active and there is no restriction on the problem size in glpk comparing to CPLEX.

In the following, I write down my experiences and a workaround of the integration of Matlab and glpkmex including GLPK.

GLPK

The GLPK (GNU Linear Programming Kit) package is intended for solving large-scale linear programming (LP), mixed integer programming (MIP), and other related problems. It is a set of routines written in ANSI C and organized in the form of a callable library.

GLPK supports the GNU MathProg modeling language, which is a subset of the AMPL language.

The GLPK package includes the following main components:
  • primal and dual simplex methods
  • primal-dual interior-point method
  • branch-and-cut method
  • translator for GNU MathProg
  • application program interface (API)
  • stand-alone LP/MIP solver
glpkmex

In order to use GLPK, Matlab needs an interface for the GLPK library. glpkmex is a Matlab MEX interface for the GLPK library which offers:
  • to use GLPK through a simple matlab command, namely glpk
  • to solve LP/MILP problems by defining all data and parameters in the Matlab workspace
  • to save the original model on a file specified by the user with one of the formats supported by GLPK: CPLEX LP, fixed MPS, free MPS, plain text (see GLPK's reference manual for further details
Integration

In the glpkmex site, precompiled version can be found for easy usage. This 'official' version is updated on 2007/08/22 and it is compilant with GLPK v4.20. Fortunately, Niels Klitgord updated this version to the v4.37 (2009/03/29) glpk but it requires some manual work (compilation) before usage.

Installation GLPK on Win32

After downloading the GLPK, one can compile-it with batches within the 'glpk-4.xx\w32' directory. If 'Optimal solution found' message appears in command line, then everything is OK.

If any problem occures, a very good instruction is available how to compile the source source on Win32.

It is important to use the compatible versions, because glpkmex is very sensitive to the GLPK interface.

Compiling glpkmex

Inthe glpkmex package the makeglpkmex.m file supports to compile the glpkcc.cpp file, but it has several bugs (e.g. sensitive to spaces in directory names, and uses slash in some cases instead of backslash) so it is recommended to use it cautiously.

Some Experiences

After integration I compared it with Matlab's built-in 'bintprog' function on my sample datasets (100 decision variables) and the results were fascinating: it solved them faster than 2 magnitudes (200-600 times faster).

how to install glpk on matlab in windows xp

followed the steps:

   1. Download the precompiled version of glpkmex from sourceforge
      <http://glpkmex.sourceforge.net/>:
         1. At the time of writing, you need to download two files
            from the glpkmex page
            <http://sourceforge.net/projects/glpkmex/>:
            glpkmex-2.8-src.zip
            
<http://sourceforge.net/projects/glpkmex/files/glpkmex/2.8/glpkmex-2.8-src.zip/download>
            and glpkcc.mex32
            
<http://sourceforge.net/projects/glpkmex/files/glpkmex/2.8/glpkcc.mexw32/download>.

   2. Unzip the glpkmex-2.8-src.zip file, copy glpkcc.mex32 into the
      resulting glpkmex folder, and then copy the glpkmex folder to
      the toolboxes folder of your Matlab installation (for example,
      C:\Program Files\MATLAB\R2008b\toolbox).
   3. Add the glpkmex folder to your Matlab path:
   4. In Matlab, go to "Set Path" from the "File" drop menu.
   5. In the "Set Path" dialog box that pops up, choose "Add with
      Subfolders"
   6. Navigate to the glpkmex folder you added to your toolbox folder
      and click "ok"
   7. Click "Save" in the "Set Path" diaglog box, then "Close"
   8. Test the glpk installation by typing "glpktest1" and then
      "glpktest2" at the Matlab command prompt. You shouldn't get any
      errors.

how to install glpk on matlab in windows

  1. Download the precompiled version of glpkmex from sourceforge:
    1. At the time of writing, you need to download two files from the glpkmex page: glpkmex-2.8-src.zip and glpkcc.mex32.
  2. Unzip the glpkmex-2.8-src.zip file, copy glpkcc.mex32 into the resulting glpkmex folder, and then copy the glpkmex folder to the toolboxes folder of your Matlab installation (for example, C:\Program Files\MATLAB\R2008b\toolbox).
  3. Add the glpkmex folder to your Matlab path:
  4. In Matlab, go to "Set Path" from the "File" drop menu.
  5. In the "Set Path" dialog box that pops up, choose "Add with Subfolders"
  6. Navigate to the glpkmex folder you added to your toolbox folder and click "ok"
  7. Click "Save" in the "Set Path" diaglog box, then "Close"
  8. Test the glpk installation by typing "glpktest1" and then "glpktest2" at the Matlab command prompt. You shouldn't get any errors. 

Note: Also put glpkmex directory to your current working directory, and please take care of  glpkcc.mexa32 , glpkcc.mexa64 and glpkcc.mexw.32, glpkcc.mexw64, these should not be duplicated.

Say if you get error like glpkcc.mexw64 not found, then search this file in google by typing glpkcc.mexw64 and download the relevant one. Once download finished replace existing glpkcc.mexw64 be new downloaded one.

If this still do not fix the problem, Please contact me.

Thanx!!!  

GLPK

Introduction

The GLPK package supplies a solver for large scale linear programming (LP) and mixed integer programming (MIP). The GLPK project is hosted at http://www.gnu.org/software/glpk.
It has two mailing lists: help-glpk@gnu.org and bug-glpk@gnu.org. To subscribe to one of these lists, please, send an empty mail with a Subject: header line of just "subscribe" to the list.
Project GLPK for Windows delivers executables for Windows.

Download

The latest source release of GLPK is available at ftp://ftp.gnu.org/gnu/glpk/.
The executables supplied by GLPK for Windows are available at http://sourceforge.net/projects/winglpk/

Installation

Download and unzip the distribution zip file. The executables and dynamic link libraries for 32 bit Windows can be found in directory w32, those for 64 bit Windows can be found in directory w64.
The libraries have to be in the search path for binaries when executing the standalone solver glpsol.exe. Therefore it is suggested to copy the DLLs to %SystemRoot%nsystem32 (e.g. c:\windows\system32).
The documentation can be found in directory doc. If you want to use the GNU Math Programming Language (GMPL), please read gmpl.pdf. If you want to use the library in your own coding, please, refer to glpk.pdf.

Quick Guide

Glpsol is a console application. To use it you have to open a console window. Under Windows this is done by starting the program cmd.exe.
Glpsol has a lot of command line parameters. You can enumerate them with
glpsol.exe --help
The problem data is specified in a model file and optional data files. You can find examples in the examples directory of the distribution tar ball.
To solve a model (e.g. examples/tsp.mod) pass the model file name as a parameter to glpsol:
glpsol -m examples/tsp.mod

References

You may find the following links helpful:

Licence

GLPK is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
GLPK is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Legal

Windows is a registered trademark of Microsoft Corporation in the United States and other countries.

GLPKMEX A Matlab MEX Interface for the GLPK library

GLPKMEX
A Matlab MEX Interface for the GLPK library
GLPK (GNU Linear Programming Kit) is a set of routines written in the ANSI C programming language and organized in the form of a callable library. It is intended for solving linear programming (LP), mixed integer programming (MIP), and other related problems.

GLPKMEX
is a Matlab MEX interface for the GLPK library which offers the following potentials:
  • Possibility to use GLPK through a simple matlab command, namely glpk.
  • Possibility to solve LP/MILP problems by defining all data and parameters in the Matlab workspace.
  • Easy definition of all GLPK parameters from which you can specify, for instance, which solver to use (simplex or interior point), activate/deactivate presolver, etc...
  • Possibility to save the original model on a file specified by the user with one of the formats supported by GLPK: CPLEX LP, fixed MPS, free MPS, plain text (see GLPK's reference manual for further details).
  • A few Matlab examples to show how simple is to define and solve LP/MILP problems.
  • An automatic script to compile your own mex interface.
  • And more... GLPKMEX includes now a simple Matlab-coded QP solver (still in beta version) developed by the author of GLPKMEX which uses GLPK to solve QP problems. A few examples are included in the distribution.

GLPKMEX is available both as source code and precompiled package at SourceForge.net

DOWNLOAD HERE