GNU Octave 10.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
 
Loading...
Searching...
No Matches
__glpk__.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 2005-2025 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
59struct control_params
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 int tout = 0; // to save and restore msglev settings
92
93 time = 0.0;
94 status = -1; // Initialize status to "bad" value
95
96 clock_t t_start = clock ();
97
98 glp_prob *lp = glp_create_prob ();
99
100 // Set the sense of optimization
101 if (sense == 1)
102 glp_set_obj_dir (lp, GLP_MIN);
103 else
104 glp_set_obj_dir (lp, GLP_MAX);
105
106 glp_add_cols (lp, n);
107 for (int i = 0; i < n; i++)
108 {
109 // Define type of the structural variables
110 if (! freeLB[i] && ! freeUB[i])
111 {
112 if (lb[i] != ub[i])
113 glp_set_col_bnds (lp, i+1, GLP_DB, lb[i], ub[i]);
114 else
115 glp_set_col_bnds (lp, i+1, GLP_FX, lb[i], ub[i]);
116 }
117 else
118 {
119 if (! freeLB[i] && freeUB[i])
120 glp_set_col_bnds (lp, i+1, GLP_LO, lb[i], ub[i]);
121 else
122 {
123 if (freeLB[i] && ! freeUB[i])
124 glp_set_col_bnds (lp, i+1, GLP_UP, lb[i], ub[i]);
125 else
126 glp_set_col_bnds (lp, i+1, GLP_FR, lb[i], ub[i]);
127 }
128 }
129
130 // -- Set the objective coefficient of the corresponding
131 // -- structural variable. No constant term is assumed.
132 glp_set_obj_coef(lp, i+1, c[i]);
133
134 if (isMIP)
135 glp_set_col_kind (lp, i+1, vartype[i]);
136 }
137
138 glp_add_rows (lp, m);
139
140 for (int i = 0; i < m; i++)
141 {
142 // If the i-th row has no lower bound (types F,U), the
143 // corrispondent parameter will be ignored. If the i-th row has
144 // no upper bound (types F,L), the corrispondent parameter will be
145 // ignored. If the i-th row is of S type, the i-th LB is used,
146 // but the i-th UB is ignored.
147
148 switch (ctype[i])
149 {
150 case 'F':
151 typx = GLP_FR;
152 break;
153
154 case 'U':
155 typx = GLP_UP;
156 break;
157
158 case 'L':
159 typx = GLP_LO;
160 break;
161
162 case 'S':
163 typx = GLP_FX;
164 break;
165
166 case 'D':
167 typx = GLP_DB;
168 break;
169 }
170
171 glp_set_row_bnds (lp, i+1, typx, typx == GLP_DB ? -b[i] : b[i], b[i]);
172
173 }
174
175 glp_load_matrix (lp, nz, rn, cn, a);
176
177 // sort the constraints for better presolving analogue to the code
178 // sample provided by glpk
179 glp_sort_matrix (lp);
180
181 if (save_pb)
182 {
183 static char tmp[] = "outpb.lp";
184 if (glp_write_lp (lp, nullptr, tmp) != 0)
185 error ("__glpk__: unable to write problem");
186 }
187
188 // direct calling glp_subroutines requires explicit msglev setting
189 if (par.msglev < 3)
190 tout = glp_term_out (GLP_OFF);
191 else
192 tout = glp_term_out (GLP_ON);
193
194 // scale the problem data
195 if (! par.presol || lpsolver != 1)
196 glp_scale_prob (lp, scale);
197
198 // build advanced initial basis (if required)
199 if (lpsolver == 1 && ! par.presol)
200 glp_adv_basis (lp, 0);
201
202 glp_term_out (tout); // restore previous msglev status
203
204 // For MIP problems without a presolver, a first pass with glp_simplex
205 // is required
206 if ((! isMIP && lpsolver == 1)
207 || (isMIP && ! par.presol))
208 {
209 glp_smcp smcp;
210 glp_init_smcp (&smcp);
211 smcp.msg_lev = par.msglev;
212 smcp.meth = par.dual;
213 smcp.pricing = par.price;
214 smcp.r_test = par.rtest;
215 smcp.tol_bnd = par.tolbnd;
216 smcp.tol_dj = par.toldj;
217 smcp.tol_piv = par.tolpiv;
218 smcp.obj_ll = par.objll;
219 smcp.obj_ul = par.objul;
220 smcp.it_lim = par.itlim;
221 smcp.tm_lim = par.tmlim;
222 smcp.out_frq = par.outfrq;
223 smcp.out_dly = par.outdly;
224 smcp.presolve = par.presol;
225 errnum = glp_simplex (lp, &smcp);
226 }
227
228 if (isMIP)
229 {
230 glp_iocp iocp;
231 glp_init_iocp (&iocp);
232 iocp.msg_lev = par.msglev;
233 iocp.br_tech = par.branch;
234 iocp.bt_tech = par.btrack;
235 iocp.tol_int = par.tolint;
236 iocp.tol_obj = par.tolobj;
237 iocp.tm_lim = par.tmlim;
238 iocp.out_frq = par.outfrq;
239 iocp.out_dly = par.outdly;
240 iocp.presolve = par.presol;
241 errnum = glp_intopt (lp, &iocp);
242 }
243
244 if (! isMIP && lpsolver == 2)
245 {
246 glp_iptcp iptcp;
247 glp_init_iptcp (&iptcp);
248 iptcp.msg_lev = par.msglev;
249 errnum = glp_interior (lp, &iptcp);
250 }
251
252 if (errnum == 0)
253 {
254 if (isMIP)
255 {
256 status = glp_mip_status (lp);
257 fmin = glp_mip_obj_val (lp);
258 }
259 else
260 {
261 if (lpsolver == 1)
262 {
263 status = glp_get_status (lp);
264 fmin = glp_get_obj_val (lp);
265 }
266 else
267 {
268 status = glp_ipt_status (lp);
269 fmin = glp_ipt_obj_val (lp);
270 }
271 }
272
273 if (isMIP)
274 {
275 for (int i = 0; i < n; i++)
276 xmin[i] = glp_mip_col_val (lp, i+1);
277 }
278 else
279 {
280 // Primal values
281 for (int i = 0; i < n; i++)
282 {
283 if (lpsolver == 1)
284 xmin[i] = glp_get_col_prim (lp, i+1);
285 else
286 xmin[i] = glp_ipt_col_prim (lp, i+1);
287 }
288
289 // Dual values
290 for (int i = 0; i < m; i++)
291 {
292 if (lpsolver == 1)
293 lambda[i] = glp_get_row_dual (lp, i+1);
294 else
295 lambda[i] = glp_ipt_row_dual (lp, i+1);
296 }
297
298 // Reduced costs
299 for (int i = 0; i < glp_get_num_cols (lp); i++)
300 {
301 if (lpsolver == 1)
302 redcosts[i] = glp_get_col_dual (lp, i+1);
303 else
304 redcosts[i] = glp_ipt_col_dual (lp, i+1);
305 }
306 }
307 }
308
309 time = (clock () - t_start) / CLOCKS_PER_SEC;
310
311 glp_delete_prob (lp);
312 // Request that GLPK free all memory resources.
313 // This prevents reported memory leaks, but isn't strictly necessary.
314 // The memory blocks used are allocated once and don't grow with further
315 // calls to glpk so they would be reclaimed anyways when Octave exits.
316 glp_free_env ();
317
318 return errnum;
319}
320
321#endif
322
324
325#define OCTAVE_GLPK_GET_REAL_PARAM(NAME, VAL) \
326 do \
327 { \
328 octave_value tmp = PARAM.getfield (NAME); \
329 \
330 if (tmp.is_defined ()) \
331 { \
332 if (! tmp.isempty ()) \
333 VAL = tmp.xscalar_value ("glpk: invalid value in PARAM" NAME); \
334 else \
335 error ("glpk: invalid value in PARAM" NAME); \
336 } \
337 } \
338 while (0)
339
340#define OCTAVE_GLPK_GET_INT_PARAM(NAME, VAL) \
341 do \
342 { \
343 octave_value tmp = PARAM.getfield (NAME); \
344 \
345 if (tmp.is_defined ()) \
346 { \
347 if (! tmp.isempty ()) \
348 VAL = tmp.strict_int_value ("glpk: invalid value in PARAM" NAME); \
349 else \
350 error ("glpk: invalid value in PARAM" NAME); \
351 } \
352 } \
353 while (0)
354
355DEFUN_DLD (__glpk__, args, ,
356 doc: /* -*- texinfo -*-
357@deftypefn {} {[@var{values}] =} __glpk__ (@var{args})
358Undocumented internal function.
359@end deftypefn */)
360{
361#if defined (HAVE_GLPK)
362
363 // FIXME: Should we even need checking for an internal function?
364 if (args.length () != 9)
365 print_usage ();
366
367 // 1st Input. A column array containing the objective function coefficients.
368 int mrowsc = args(0).rows ();
369
370 Matrix C = args(0).xmatrix_value ("__glpk__: invalid value of C");
371
372 double *c = C.rwdata ();
373 Array<int> rn;
374 Array<int> cn;
375 ColumnVector a;
376 int mrowsA;
377 int nz = 0;
378
379 // 2nd Input. A matrix containing the constraints coefficients.
380 // If matrix A is NOT a sparse matrix
381 if (args(1).issparse ())
382 {
383 SparseMatrix A = args(1).xsparse_matrix_value ("__glpk__: invalid value of A");
384
385 mrowsA = A.rows ();
386 octave_idx_type Anc = A.cols ();
387 octave_idx_type Anz = A.nnz ();
388 rn.resize (dim_vector (Anz+1, 1));
389 cn.resize (dim_vector (Anz+1, 1));
390 a.resize (Anz+1, 0.0);
391
392 if (Anc != mrowsc)
393 error ("__glpk__: invalid value of A");
394
395 for (octave_idx_type j = 0; j < Anc; j++)
396 for (octave_idx_type i = A.cidx (j); i < A.cidx (j+1); i++)
397 {
398 nz++;
399 rn(nz) = A.ridx (i) + 1;
400 cn(nz) = j + 1;
401 a(nz) = A.data(i);
402 }
403 }
404 else
405 {
406 Matrix A = args(1).xmatrix_value ("__glpk__: invalid value of A");
407
408 mrowsA = A.rows ();
409 rn.resize (dim_vector (mrowsA*mrowsc+1, 1));
410 cn.resize (dim_vector (mrowsA*mrowsc+1, 1));
411 a.resize (mrowsA*mrowsc+1, 0.0);
412
413 for (int i = 0; i < mrowsA; i++)
414 {
415 for (int j = 0; j < mrowsc; j++)
416 {
417 if (A(i, j) != 0)
418 {
419 nz++;
420 rn(nz) = i + 1;
421 cn(nz) = j + 1;
422 a(nz) = A(i, j);
423 }
424 }
425 }
426
427 }
428
429 // 3rd Input. A column array containing the right-hand side value
430 // for each constraint in the constraint matrix.
431 Matrix B = args(2).xmatrix_value ("__glpk__: invalid value of B");
432
433 double *b = B.rwdata ();
434
435 // 4th Input. An array of length mrowsc containing the lower
436 // bound on each of the variables.
437 Matrix LB = args(3).xmatrix_value ("__glpk__: invalid value of LB");
438
439 if (LB.numel () < mrowsc)
440 error ("__glpk__: invalid dimensions for LB");
441
442 double *lb = LB.rwdata ();
443
444 // LB argument, default: Free
445 Array<int> freeLB (dim_vector (mrowsc, 1));
446 for (int i = 0; i < mrowsc; i++)
447 {
448 if (math::isinf (lb[i]))
449 {
450 freeLB(i) = 1;
451 lb[i] = -numeric_limits<double>::Inf ();
452 }
453 else
454 freeLB(i) = 0;
455 }
456
457 // 5th Input. An array of at least length numcols containing the upper
458 // bound on each of the variables.
459 Matrix UB = args(4).xmatrix_value ("__glpk__: invalid value of UB");
460
461 if (UB.numel () < mrowsc)
462 error ("__glpk__: invalid dimensions for UB");
463
464 double *ub = UB.rwdata ();
465
466 Array<int> freeUB (dim_vector (mrowsc, 1));
467 for (int i = 0; i < mrowsc; i++)
468 {
469 if (math::isinf (ub[i]))
470 {
471 freeUB(i) = 1;
472 ub[i] = numeric_limits<double>::Inf ();
473 }
474 else
475 freeUB(i) = 0;
476 }
477
478 // 6th Input. A column array containing the sense of each constraint
479 // in the constraint matrix.
480 charMatrix CTYPE = args(5).xchar_matrix_value ("__glpk__: invalid value of CTYPE");
481
482 char *ctype = CTYPE.rwdata ();
483
484 // 7th Input. A column array containing the types of the variables.
485 charMatrix VTYPE = args(6).xchar_matrix_value ("__glpk__: invalid value of VARTYPE");
486
487 Array<int> vartype (dim_vector (mrowsc, 1));
488 int isMIP = 0;
489 for (int i = 0; i < mrowsc ; i++)
490 {
491 if (VTYPE(i, 0) == 'I')
492 {
493 isMIP = 1;
494 vartype(i) = GLP_IV;
495 }
496 else
497 vartype(i) = GLP_CV;
498 }
499
500 // 8th Input. Sense of optimization.
501 int sense;
502 double SENSE = args(7).xscalar_value ("__glpk__: invalid value of SENSE");
503
504 if (SENSE >= 0)
505 sense = 1;
506 else
507 sense = -1;
508
509 // 9th Input. A structure containing the control parameters.
510 octave_scalar_map PARAM = args(8).xscalar_map_value ("__glpk__: invalid value of PARAM");
511
512 control_params par;
513
514 // Integer parameters
515
516 // Level of messages output by the solver
517 par.msglev = 1;
518 OCTAVE_GLPK_GET_INT_PARAM ("msglev", par.msglev);
519 if (par.msglev < 0 || par.msglev > 3)
520 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)");
521
522 // scaling option
523 int scale = 16;
525 if (scale < 0 || scale > 128)
526 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");
527
528 // Dual simplex option
529 par.dual = 1;
530 OCTAVE_GLPK_GET_INT_PARAM ("dual", par.dual);
531 if (par.dual < 1 || par.dual > 3)
532 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)");
533
534 // Pricing option
535 par.price = 34;
536 OCTAVE_GLPK_GET_INT_PARAM ("price", par.price);
537 if (par.price != 17 && par.price != 34)
538 error ("__glpk__: PARAM.price must be 17 (textbook pricing) or 34 (steepest edge pricing [default])");
539
540 // Simplex iterations limit
541 par.itlim = std::numeric_limits<int>::max ();
542 OCTAVE_GLPK_GET_INT_PARAM ("itlim", par.itlim);
543
544 // Output frequency, in iterations
545 par.outfrq = 200;
546 OCTAVE_GLPK_GET_INT_PARAM ("outfrq", par.outfrq);
547
548 // Branching heuristic option
549 par.branch = 4;
550 OCTAVE_GLPK_GET_INT_PARAM ("branch", par.branch);
551 if (par.branch < 1 || par.branch > 5)
552 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)");
553
554 // Backtracking heuristic option
555 par.btrack = 4;
556 OCTAVE_GLPK_GET_INT_PARAM ("btrack", par.btrack);
557 if (par.btrack < 1 || par.btrack > 4)
558 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]");
559
560 // Presolver option
561 par.presol = 1;
562 OCTAVE_GLPK_GET_INT_PARAM ("presol", par.presol);
563 if (par.presol < 0 || par.presol > 1)
564 error ("__glpk__: PARAM.presol must be 0 (do NOT use LP presolver) or 1 (use LP presolver [default])");
565
566 // LPsolver option
567 int lpsolver = 1;
568 OCTAVE_GLPK_GET_INT_PARAM ("lpsolver", lpsolver);
569 if (lpsolver < 1 || lpsolver > 2)
570 error ("__glpk__: PARAM.lpsolver must be 1 (simplex method) or 2 (interior point method)");
571
572 // Ratio test option
573 par.rtest = 34;
574 OCTAVE_GLPK_GET_INT_PARAM ("rtest", par.rtest);
575 if (par.rtest != 17 && par.rtest != 34)
576 error ("__glpk__: PARAM.rtest must be 17 (standard ratio test) or 34 (Harris' two-pass ratio test [default])");
577
578 par.tmlim = std::numeric_limits<int>::max ();
579 OCTAVE_GLPK_GET_INT_PARAM ("tmlim", par.tmlim);
580
581 par.outdly = 0;
582 OCTAVE_GLPK_GET_INT_PARAM ("outdly", par.outdly);
583
584 // Save option
585 int save_pb = 0;
586 OCTAVE_GLPK_GET_INT_PARAM ("save", save_pb);
587 save_pb = save_pb != 0;
588
589 // Real parameters
590
591 // Relative tolerance used to check if the current basic solution
592 // is primal feasible
593 par.tolbnd = 1e-7;
594 OCTAVE_GLPK_GET_REAL_PARAM ("tolbnd", par.tolbnd);
595
596 // Absolute tolerance used to check if the current basic solution
597 // is dual feasible
598 par.toldj = 1e-7;
599 OCTAVE_GLPK_GET_REAL_PARAM ("toldj", par.toldj);
600
601 // Relative tolerance used to choose eligible pivotal elements of
602 // the simplex table in the ratio test
603 par.tolpiv = 1e-9;
604 OCTAVE_GLPK_GET_REAL_PARAM ("tolpiv", par.tolpiv);
605
606 par.objll = -std::numeric_limits<double>::max ();
607 OCTAVE_GLPK_GET_REAL_PARAM ("objll", par.objll);
608
609 par.objul = std::numeric_limits<double>::max ();
610 OCTAVE_GLPK_GET_REAL_PARAM ("objul", par.objul);
611
612 par.tolint = 1e-5;
613 OCTAVE_GLPK_GET_REAL_PARAM ("tolint", par.tolint);
614
615 par.tolobj = 1e-7;
616 OCTAVE_GLPK_GET_REAL_PARAM ("tolobj", par.tolobj);
617
618 // Assign pointers to the output parameters
619 ColumnVector xmin (mrowsc, octave_NA);
620 double fmin = octave_NA;
621 ColumnVector lambda (mrowsA, octave_NA);
622 ColumnVector redcosts (mrowsc, octave_NA);
623
624 double time = 0.0;
625 int status = -1;
626
627 int errnum = glpk (sense, mrowsc, mrowsA, c, nz, rn.rwdata (),
628 cn.rwdata (), a.rwdata (), b, ctype,
629 freeLB.rwdata (), lb, freeUB.rwdata (),
630 ub, vartype.rwdata (), isMIP, lpsolver,
631 save_pb, scale, par, xmin.rwdata (), fmin,
632 status, lambda.rwdata (),
633 redcosts.rwdata (), time);
634
635 octave_scalar_map extra;
636
637 if (! isMIP)
638 {
639 extra.assign ("lambda", lambda);
640 extra.assign ("redcosts", redcosts);
641 }
642
643 extra.assign ("time", time);
644 extra.assign ("status", status);
645
646 return ovl (xmin, fmin, errnum, extra);
647
648#else
649
650 octave_unused_parameter (args);
651
652 err_disabled_feature ("glpk", "GNU Linear Programming Kit");
653
654#endif
655}
656
657/*
658## No test needed for internal helper function.
659%!assert (1)
660*/
661
662OCTAVE_END_NAMESPACE(octave)
#define C(a, b)
Definition Faddeeva.cc:256
#define OCTAVE_GLPK_GET_INT_PARAM(NAME, VAL)
Definition __glpk__.cc:340
#define OCTAVE_GLPK_GET_REAL_PARAM(NAME, VAL)
Definition __glpk__.cc:325
N Dimensional Array with copy-on-write semantics.
Definition Array.h:130
void resize(const dim_vector &dv, const T &rfv)
Size of the specified dimension.
const T * data() const
Size of the specified dimension.
Definition Array.h:665
T * rwdata()
Size of the specified dimension.
octave_idx_type numel() const
Number of elements in the array.
Definition Array.h:418
void resize(octave_idx_type n, const double &rfv=0)
Definition dColVector.h:112
Vector representing the dimensions (size) of an Array.
Definition dim-vector.h:90
void assign(const std::string &k, const octave_value &val)
Definition oct-map.h:230
OCTAVE_BEGIN_NAMESPACE(octave) static octave_value daspk_fcn
#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
void print_usage()
Definition defun-int.h:72
void error(const char *fmt,...)
Definition error.cc:1003
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:5731
#define octave_NA
Definition lo-ieee.h:43
F77_RET_T const F77_INT F77_CMPLX const F77_INT F77_CMPLX * B
F77_RET_T const F77_INT F77_CMPLX * A
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:217