GNU Octave 7.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
__glpk__.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 2005-2022 The Octave Project Developers
4//
5// See the file COPYRIGHT.md in the top-level directory of this
6// distribution or <https://octave.org/copyright/>.
7//
8// This file is part of Octave.
9//
10// Octave is free software: you can redistribute it and/or modify it
11// under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// Octave is distributed in the hope that it will be useful, but
16// WITHOUT ANY WARRANTY; without even the implied warranty of
17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18// GNU General Public License for more details.
19//
20// You should have received a copy of the GNU General Public License
21// along with Octave; see the file COPYING. If not, see
22// <https://www.gnu.org/licenses/>.
23//
24////////////////////////////////////////////////////////////////////////
25
26#if defined (HAVE_CONFIG_H)
27# include "config.h"
28#endif
29
30#include <ctime>
31
32#include <limits>
33
34#include "Array.h"
35#include "chMatrix.h"
36#include "dColVector.h"
37#include "dMatrix.h"
38#include "dSparse.h"
39#include "lo-ieee.h"
40
41#include "defun-dld.h"
42#include "error.h"
43#include "errwarn.h"
44#include "oct-map.h"
45#include "ov.h"
46#include "ovl.h"
47
48#if defined (HAVE_GLPK)
49
50extern "C"
51{
52#if defined (HAVE_GLPK_GLPK_H)
53# include <glpk/glpk.h>
54#else
55# include <glpk.h>
56#endif
57}
58
60{
61 int msglev;
62 int dual;
63 int price;
64 int itlim;
65 int outfrq;
66 int branch;
67 int btrack;
68 int presol;
69 int rtest;
70 int tmlim;
71 int outdly;
72 double tolbnd;
73 double toldj;
74 double tolpiv;
75 double objll;
76 double objul;
77 double tolint;
78 double tolobj;
79};
80
81static int
82glpk (int sense, int n, int m, double *c, int nz, int *rn, int *cn,
83 double *a, double *b, char *ctype, int *freeLB, double *lb,
84 int *freeUB, double *ub, int *vartype, int isMIP, int lpsolver,
85 int save_pb, int scale, const control_params& par,
86 double *xmin, double& fmin, int& status,
87 double *lambda, double *redcosts, double& time)
88{
89 int typx = 0;
90 int errnum = 0;
91
92 time = 0.0;
93 status = -1; // Initialize status to "bad" value
94
95 clock_t t_start = clock ();
96
97 glp_prob *lp = glp_create_prob ();
98
99 // Set the sense of optimization
100 if (sense == 1)
101 glp_set_obj_dir (lp, GLP_MIN);
102 else
103 glp_set_obj_dir (lp, GLP_MAX);
104
105 glp_add_cols (lp, n);
106 for (int i = 0; i < n; i++)
107 {
108 // Define type of the structural variables
109 if (! freeLB[i] && ! freeUB[i])
110 {
111 if (lb[i] != ub[i])
112 glp_set_col_bnds (lp, i+1, GLP_DB, lb[i], ub[i]);
113 else
114 glp_set_col_bnds (lp, i+1, GLP_FX, lb[i], ub[i]);
115 }
116 else
117 {
118 if (! freeLB[i] && freeUB[i])
119 glp_set_col_bnds (lp, i+1, GLP_LO, lb[i], ub[i]);
120 else
121 {
122 if (freeLB[i] && ! freeUB[i])
123 glp_set_col_bnds (lp, i+1, GLP_UP, lb[i], ub[i]);
124 else
125 glp_set_col_bnds (lp, i+1, GLP_FR, lb[i], ub[i]);
126 }
127 }
128
129 // -- Set the objective coefficient of the corresponding
130 // -- structural variable. No constant term is assumed.
131 glp_set_obj_coef(lp, i+1, c[i]);
132
133 if (isMIP)
134 glp_set_col_kind (lp, i+1, vartype[i]);
135 }
136
137 glp_add_rows (lp, m);
138
139 for (int i = 0; i < m; i++)
140 {
141 // If the i-th row has no lower bound (types F,U), the
142 // corrispondent parameter will be ignored. If the i-th row has
143 // no upper bound (types F,L), the corrispondent parameter will be
144 // ignored. If the i-th row is of S type, the i-th LB is used,
145 // but the i-th UB is ignored.
146
147 switch (ctype[i])
148 {
149 case 'F':
150 typx = GLP_FR;
151 break;
152
153 case 'U':
154 typx = GLP_UP;
155 break;
156
157 case 'L':
158 typx = GLP_LO;
159 break;
160
161 case 'S':
162 typx = GLP_FX;
163 break;
164
165 case 'D':
166 typx = GLP_DB;
167 break;
168 }
169
170 glp_set_row_bnds (lp, i+1, typx, b[i], b[i]);
171
172 }
173
174 glp_load_matrix (lp, nz, rn, cn, a);
175
176 if (save_pb)
177 {
178 static char tmp[] = "outpb.lp";
179 if (glp_write_lp (lp, nullptr, tmp) != 0)
180 error ("__glpk__: unable to write problem");
181 }
182
183 // scale the problem data
184 if (! par.presol || lpsolver != 1)
185 glp_scale_prob (lp, scale);
186
187 // build advanced initial basis (if required)
188 if (lpsolver == 1 && ! par.presol)
189 glp_adv_basis (lp, 0);
190
191 // For MIP problems without a presolver, a first pass with glp_simplex
192 // is required
193 if ((! isMIP && lpsolver == 1)
194 || (isMIP && ! par.presol))
195 {
196 glp_smcp smcp;
197 glp_init_smcp (&smcp);
198 smcp.msg_lev = par.msglev;
199 smcp.meth = par.dual;
200 smcp.pricing = par.price;
201 smcp.r_test = par.rtest;
202 smcp.tol_bnd = par.tolbnd;
203 smcp.tol_dj = par.toldj;
204 smcp.tol_piv = par.tolpiv;
205 smcp.obj_ll = par.objll;
206 smcp.obj_ul = par.objul;
207 smcp.it_lim = par.itlim;
208 smcp.tm_lim = par.tmlim;
209 smcp.out_frq = par.outfrq;
210 smcp.out_dly = par.outdly;
211 smcp.presolve = par.presol;
212 errnum = glp_simplex (lp, &smcp);
213 }
214
215 if (isMIP)
216 {
217 glp_iocp iocp;
218 glp_init_iocp (&iocp);
219 iocp.msg_lev = par.msglev;
220 iocp.br_tech = par.branch;
221 iocp.bt_tech = par.btrack;
222 iocp.tol_int = par.tolint;
223 iocp.tol_obj = par.tolobj;
224 iocp.tm_lim = par.tmlim;
225 iocp.out_frq = par.outfrq;
226 iocp.out_dly = par.outdly;
227 iocp.presolve = par.presol;
228 errnum = glp_intopt (lp, &iocp);
229 }
230
231 if (! isMIP && lpsolver == 2)
232 {
233 glp_iptcp iptcp;
234 glp_init_iptcp (&iptcp);
235 iptcp.msg_lev = par.msglev;
236 errnum = glp_interior (lp, &iptcp);
237 }
238
239 if (errnum == 0)
240 {
241 if (isMIP)
242 {
243 status = glp_mip_status (lp);
244 fmin = glp_mip_obj_val (lp);
245 }
246 else
247 {
248 if (lpsolver == 1)
249 {
250 status = glp_get_status (lp);
251 fmin = glp_get_obj_val (lp);
252 }
253 else
254 {
255 status = glp_ipt_status (lp);
256 fmin = glp_ipt_obj_val (lp);
257 }
258 }
259
260 if (isMIP)
261 {
262 for (int i = 0; i < n; i++)
263 xmin[i] = glp_mip_col_val (lp, i+1);
264 }
265 else
266 {
267 // Primal values
268 for (int i = 0; i < n; i++)
269 {
270 if (lpsolver == 1)
271 xmin[i] = glp_get_col_prim (lp, i+1);
272 else
273 xmin[i] = glp_ipt_col_prim (lp, i+1);
274 }
275
276 // Dual values
277 for (int i = 0; i < m; i++)
278 {
279 if (lpsolver == 1)
280 lambda[i] = glp_get_row_dual (lp, i+1);
281 else
282 lambda[i] = glp_ipt_row_dual (lp, i+1);
283 }
284
285 // Reduced costs
286 for (int i = 0; i < glp_get_num_cols (lp); i++)
287 {
288 if (lpsolver == 1)
289 redcosts[i] = glp_get_col_dual (lp, i+1);
290 else
291 redcosts[i] = glp_ipt_col_dual (lp, i+1);
292 }
293 }
294 }
295
296 time = (clock () - t_start) / CLOCKS_PER_SEC;
297
298 glp_delete_prob (lp);
299 // Request that GLPK free all memory resources.
300 // This prevents reported memory leaks, but isn't strictly necessary.
301 // The memory blocks used are allocated once and don't grow with further
302 // calls to glpk so they would be reclaimed anyways when Octave exits.
303 glp_free_env ();
304
305 return errnum;
306}
307
308#endif
309
310OCTAVE_NAMESPACE_BEGIN
311
312#define OCTAVE_GLPK_GET_REAL_PARAM(NAME, VAL) \
313 do \
314 { \
315 octave_value tmp = PARAM.getfield (NAME); \
316 \
317 if (tmp.is_defined ()) \
318 { \
319 if (! tmp.isempty ()) \
320 VAL = tmp.xscalar_value ("glpk: invalid value in PARAM" NAME); \
321 else \
322 error ("glpk: invalid value in PARAM" NAME); \
323 } \
324 } \
325 while (0)
326
327#define OCTAVE_GLPK_GET_INT_PARAM(NAME, VAL) \
328 do \
329 { \
330 octave_value tmp = PARAM.getfield (NAME); \
331 \
332 if (tmp.is_defined ()) \
333 { \
334 if (! tmp.isempty ()) \
335 VAL = tmp.xint_value ("glpk: invalid value in PARAM" NAME); \
336 else \
337 error ("glpk: invalid value in PARAM" NAME); \
338 } \
339 } \
340 while (0)
341
342DEFUN_DLD (__glpk__, args, ,
343 doc: /* -*- texinfo -*-
344@deftypefn {} {[@var{values}] =} __glpk__ (@var{args})
345Undocumented internal function.
346@end deftypefn */)
347{
348#if defined (HAVE_GLPK)
349
350 // FIXME: Should we even need checking for an internal function?
351 if (args.length () != 9)
352 print_usage ();
353
354 // 1st Input. A column array containing the objective function coefficients.
355 int mrowsc = args(0).rows ();
356
357 Matrix C = args(0).xmatrix_value ("__glpk__: invalid value of C");
358
359 double *c = C.fortran_vec ();
360 Array<int> rn;
361 Array<int> cn;
362 ColumnVector a;
363 int mrowsA;
364 int nz = 0;
365
366 // 2nd Input. A matrix containing the constraints coefficients.
367 // If matrix A is NOT a sparse matrix
368 if (args(1).issparse ())
369 {
370 SparseMatrix A = args(1).xsparse_matrix_value ("__glpk__: invalid value of A");
371
372 mrowsA = A.rows ();
373 octave_idx_type Anc = A.cols ();
374 octave_idx_type Anz = A.nnz ();
375 rn.resize (dim_vector (Anz+1, 1));
376 cn.resize (dim_vector (Anz+1, 1));
377 a.resize (Anz+1, 0.0);
378
379 if (Anc != mrowsc)
380 error ("__glpk__: invalid value of A");
381
382 for (octave_idx_type j = 0; j < Anc; j++)
383 for (octave_idx_type i = A.cidx (j); i < A.cidx (j+1); i++)
384 {
385 nz++;
386 rn(nz) = A.ridx (i) + 1;
387 cn(nz) = j + 1;
388 a(nz) = A.data(i);
389 }
390 }
391 else
392 {
393 Matrix A = args(1).xmatrix_value ("__glpk__: invalid value of A");
394
395 mrowsA = A.rows ();
396 rn.resize (dim_vector (mrowsA*mrowsc+1, 1));
397 cn.resize (dim_vector (mrowsA*mrowsc+1, 1));
398 a.resize (mrowsA*mrowsc+1, 0.0);
399
400 for (int i = 0; i < mrowsA; i++)
401 {
402 for (int j = 0; j < mrowsc; j++)
403 {
404 if (A(i, j) != 0)
405 {
406 nz++;
407 rn(nz) = i + 1;
408 cn(nz) = j + 1;
409 a(nz) = A(i, j);
410 }
411 }
412 }
413
414 }
415
416 // 3rd Input. A column array containing the right-hand side value
417 // for each constraint in the constraint matrix.
418 Matrix B = args(2).xmatrix_value ("__glpk__: invalid value of B");
419
420 double *b = B.fortran_vec ();
421
422 // 4th Input. An array of length mrowsc containing the lower
423 // bound on each of the variables.
424 Matrix LB = args(3).xmatrix_value ("__glpk__: invalid value of LB");
425
426 if (LB.numel () < mrowsc)
427 error ("__glpk__: invalid dimensions for LB");
428
429 double *lb = LB.fortran_vec ();
430
431 // LB argument, default: Free
432 Array<int> freeLB (dim_vector (mrowsc, 1));
433 for (int i = 0; i < mrowsc; i++)
434 {
435 if (math::isinf (lb[i]))
436 {
437 freeLB(i) = 1;
438 lb[i] = -numeric_limits<double>::Inf ();
439 }
440 else
441 freeLB(i) = 0;
442 }
443
444 // 5th Input. An array of at least length numcols containing the upper
445 // bound on each of the variables.
446 Matrix UB = args(4).xmatrix_value ("__glpk__: invalid value of UB");
447
448 if (UB.numel () < mrowsc)
449 error ("__glpk__: invalid dimensions for UB");
450
451 double *ub = UB.fortran_vec ();
452
453 Array<int> freeUB (dim_vector (mrowsc, 1));
454 for (int i = 0; i < mrowsc; i++)
455 {
456 if (math::isinf (ub[i]))
457 {
458 freeUB(i) = 1;
460 }
461 else
462 freeUB(i) = 0;
463 }
464
465 // 6th Input. A column array containing the sense of each constraint
466 // in the constraint matrix.
467 charMatrix CTYPE = args(5).xchar_matrix_value ("__glpk__: invalid value of CTYPE");
468
469 char *ctype = CTYPE.fortran_vec ();
470
471 // 7th Input. A column array containing the types of the variables.
472 charMatrix VTYPE = args(6).xchar_matrix_value ("__glpk__: invalid value of VARTYPE");
473
474 Array<int> vartype (dim_vector (mrowsc, 1));
475 int isMIP = 0;
476 for (int i = 0; i < mrowsc ; i++)
477 {
478 if (VTYPE(i, 0) == 'I')
479 {
480 isMIP = 1;
481 vartype(i) = GLP_IV;
482 }
483 else
484 vartype(i) = GLP_CV;
485 }
486
487 // 8th Input. Sense of optimization.
488 int sense;
489 double SENSE = args(7).xscalar_value ("__glpk__: invalid value of SENSE");
490
491 if (SENSE >= 0)
492 sense = 1;
493 else
494 sense = -1;
495
496 // 9th Input. A structure containing the control parameters.
497 octave_scalar_map PARAM = args(8).xscalar_map_value ("__glpk__: invalid value of PARAM");
498
499 control_params par;
500
501 // Integer parameters
502
503 // Level of messages output by the solver
504 par.msglev = 1;
505 OCTAVE_GLPK_GET_INT_PARAM ("msglev", par.msglev);
506 if (par.msglev < 0 || par.msglev > 3)
507 error ("__glpk__: PARAM.msglev must be 0 (no output) or 1 (error and warning messages only [default]) or 2 (normal output) or 3 (full output)");
508
509 // scaling option
510 int scale = 16;
512 if (scale < 0 || scale > 128)
513 error ("__glpk__: PARAM.scale must either be 128 (automatic selection of scaling options), or a bitwise or of: 1 (geometric mean scaling), 16 (equilibration scaling), 32 (round scale factors to power of two), 64 (skip if problem is well scaled");
514
515 // Dual simplex option
516 par.dual = 1;
517 OCTAVE_GLPK_GET_INT_PARAM ("dual", par.dual);
518 if (par.dual < 1 || par.dual > 3)
519 error ("__glpk__: PARAM.dual must be 1 (use two-phase primal simplex [default]) or 2 (use two-phase dual simplex) or 3 (use two-phase dual simplex, and if it fails, switch to the primal simplex)");
520
521 // Pricing option
522 par.price = 34;
523 OCTAVE_GLPK_GET_INT_PARAM ("price", par.price);
524 if (par.price != 17 && par.price != 34)
525 error ("__glpk__: PARAM.price must be 17 (textbook pricing) or 34 (steepest edge pricing [default])");
526
527 // Simplex iterations limit
529 OCTAVE_GLPK_GET_INT_PARAM ("itlim", par.itlim);
530
531 // Output frequency, in iterations
532 par.outfrq = 200;
533 OCTAVE_GLPK_GET_INT_PARAM ("outfrq", par.outfrq);
534
535 // Branching heuristic option
536 par.branch = 4;
537 OCTAVE_GLPK_GET_INT_PARAM ("branch", par.branch);
538 if (par.branch < 1 || par.branch > 5)
539 error ("__glpk__: PARAM.branch must be 1 (first fractional variable) or 2 (last fractional variable) or 3 (most fractional variable) or 4 (heuristic by Driebeck and Tomlin [default]) or 5 (hybrid pseudocost heuristic)");
540
541 // Backtracking heuristic option
542 par.btrack = 4;
543 OCTAVE_GLPK_GET_INT_PARAM ("btrack", par.btrack);
544 if (par.btrack < 1 || par.btrack > 4)
545 error ("__glpk__: PARAM.btrack must be 1 (depth first search) or 2 (breadth first search) or 3 (best local bound) or 4 (best projection heuristic [default]");
546
547 // Presolver option
548 par.presol = 1;
549 OCTAVE_GLPK_GET_INT_PARAM ("presol", par.presol);
550 if (par.presol < 0 || par.presol > 1)
551 error ("__glpk__: PARAM.presol must be 0 (do NOT use LP presolver) or 1 (use LP presolver [default])");
552
553 // LPsolver option
554 int lpsolver = 1;
555 OCTAVE_GLPK_GET_INT_PARAM ("lpsolver", lpsolver);
556 if (lpsolver < 1 || lpsolver > 2)
557 error ("__glpk__: PARAM.lpsolver must be 1 (simplex method) or 2 (interior point method)");
558
559 // Ratio test option
560 par.rtest = 34;
561 OCTAVE_GLPK_GET_INT_PARAM ("rtest", par.rtest);
562 if (par.rtest != 17 && par.rtest != 34)
563 error ("__glpk__: PARAM.rtest must be 17 (standard ratio test) or 34 (Harris' two-pass ratio test [default])");
564
566 OCTAVE_GLPK_GET_INT_PARAM ("tmlim", par.tmlim);
567
568 par.outdly = 0;
569 OCTAVE_GLPK_GET_INT_PARAM ("outdly", par.outdly);
570
571 // Save option
572 int save_pb = 0;
573 OCTAVE_GLPK_GET_INT_PARAM ("save", save_pb);
574 save_pb = save_pb != 0;
575
576 // Real parameters
577
578 // Relative tolerance used to check if the current basic solution
579 // is primal feasible
580 par.tolbnd = 1e-7;
581 OCTAVE_GLPK_GET_REAL_PARAM ("tolbnd", par.tolbnd);
582
583 // Absolute tolerance used to check if the current basic solution
584 // is dual feasible
585 par.toldj = 1e-7;
586 OCTAVE_GLPK_GET_REAL_PARAM ("toldj", par.toldj);
587
588 // Relative tolerance used to choose eligible pivotal elements of
589 // the simplex table in the ratio test
590 par.tolpiv = 1e-10;
591 OCTAVE_GLPK_GET_REAL_PARAM ("tolpiv", par.tolpiv);
592
594 OCTAVE_GLPK_GET_REAL_PARAM ("objll", par.objll);
595
597 OCTAVE_GLPK_GET_REAL_PARAM ("objul", par.objul);
598
599 par.tolint = 1e-5;
600 OCTAVE_GLPK_GET_REAL_PARAM ("tolint", par.tolint);
601
602 par.tolobj = 1e-7;
603 OCTAVE_GLPK_GET_REAL_PARAM ("tolobj", par.tolobj);
604
605 // Assign pointers to the output parameters
606 ColumnVector xmin (mrowsc, octave_NA);
607 double fmin = octave_NA;
608 ColumnVector lambda (mrowsA, octave_NA);
609 ColumnVector redcosts (mrowsc, octave_NA);
610
611 double time = 0.0;
612 int status = -1;
613
614 int errnum = glpk (sense, mrowsc, mrowsA, c, nz, rn.fortran_vec (),
615 cn.fortran_vec (), a.fortran_vec (), b, ctype,
616 freeLB.fortran_vec (), lb, freeUB.fortran_vec (),
617 ub, vartype.fortran_vec (), isMIP, lpsolver,
618 save_pb, scale, par, xmin.fortran_vec (), fmin,
619 status, lambda.fortran_vec (),
620 redcosts.fortran_vec (), time);
621
622 octave_scalar_map extra;
623
624 if (! isMIP)
625 {
626 extra.assign ("lambda", lambda);
627 extra.assign ("redcosts", redcosts);
628 }
629
630 extra.assign ("time", time);
631 extra.assign ("status", status);
632
633 return ovl (xmin, fmin, errnum, extra);
634
635#else
636
637 octave_unused_parameter (args);
638
639 err_disabled_feature ("glpk", "GNU Linear Programming Kit");
640
641#endif
642}
643
644/*
645## No test needed for internal helper function.
646%!assert (1)
647*/
648
649OCTAVE_NAMESPACE_END
#define Inf
Definition: Faddeeva.cc:260
#define C(a, b)
Definition: Faddeeva.cc:259
#define OCTAVE_GLPK_GET_INT_PARAM(NAME, VAL)
Definition: __glpk__.cc:327
#define OCTAVE_GLPK_GET_REAL_PARAM(NAME, VAL)
Definition: __glpk__.cc:312
static int glpk(int sense, int n, int m, double *c, int nz, int *rn, int *cn, double *a, double *b, char *ctype, int *freeLB, double *lb, int *freeUB, double *ub, int *vartype, int isMIP, int lpsolver, int save_pb, int scale, const control_params &par, double *xmin, double &fmin, int &status, double *lambda, double *redcosts, double &time)
Definition: __glpk__.cc:82
charNDArray max(char d, const charNDArray &m)
Definition: chNDArray.cc:230
octave_idx_type numel(void) const
Number of elements in the array.
Definition: Array.h:411
OCTARRAY_API void resize(const dim_vector &dv, const T &rfv)
Size of the specified dimension.
Definition: Array.cc:1010
OCTARRAY_API T * fortran_vec(void)
Size of the specified dimension.
Definition: Array.cc:1744
void resize(octave_idx_type n, const double &rfv=0)
Definition: dColVector.h:112
Definition: dMatrix.h:42
Vector representing the dimensions (size) of an Array.
Definition: dim-vector.h:94
void assign(const std::string &k, const octave_value &val)
Definition: oct-map.h:238
#define DEFUN_DLD(name, args_name, nargout_name, doc)
Macro to define an at run time dynamically loadable builtin function.
Definition: defun-dld.h:61
OCTINTERP_API void print_usage(void)
Definition: defun-int.h:72
void error(const char *fmt,...)
Definition: error.cc:980
void err_disabled_feature(const std::string &fcn, const std::string &feature, const std::string &pkg)
Definition: errwarn.cc:53
void scale(Matrix &m, double x, double y, double z)
Definition: graphics.cc:5893
#define octave_NA
Definition: lo-ieee.h:41
F77_RET_T const F77_INT F77_CMPLX const F77_INT F77_CMPLX * B
F77_RET_T const F77_INT F77_CMPLX * A
bool isinf(double x)
Definition: lo-mappers.h:203
octave_int< T > xmin(const octave_int< T > &x, const octave_int< T > &y)
octave_value_list ovl(const OV_Args &... args)
Construct an octave_value_list with less typing.
Definition: ovl.h:211
double tolpiv
Definition: __glpk__.cc:74
double objul
Definition: __glpk__.cc:76
double toldj
Definition: __glpk__.cc:73
double objll
Definition: __glpk__.cc:75
double tolbnd
Definition: __glpk__.cc:72
double tolobj
Definition: __glpk__.cc:78
double tolint
Definition: __glpk__.cc:77