Debian Codegraph @

Osi/src/OsiGlpk/OsiGlpkSolverInterface.cpp

raw symbols SCIP
1 //-----------------------------------------------------------------------------
2 // name: OSI Interface for GLPK
3 //-----------------------------------------------------------------------------
4 // Copyright (C) 2001, 2002 Vivian De Smedt
5 // Copyright (C) 2002, 2003 Braden Hunsaker
6 // Copyright (C) 2003, 2004 University of Pittsburgh
7 // Copyright (C) 2004 Joseph Young
8 // Copyright (C) 2007 Lou Hafer
9 // University of Pittsburgh coding done by Brady Hunsaker
10 // All Rights Reserved.
11 // This code is licensed under the terms of the Eclipse Public License (EPL).
12 //
13 // Comments:
14 //
15 // Areas that may need work in the code are marked with '???'.
16 //
17 // As of version 4.7, GLPK problems can be of class LPX_LP or LPX_MIP.
18 // The difference is that LPX_MIP problems have a separate MIP data block,
19 // and certain functions are only allowed for LPX_MIP problems.
20 //
21 // In (much) earlier versions of GLPK, if an LPX_MIP problem was
22 // changed back into a LPX_LP problem, then the MIP data was lost,
23 // including which columns are integer. However, LPX_MIP problems
24 // still had access to LP information (like lpx_get_status).
25 //
26 // It appears that this behavior is no longer true in version 4.7.
27 // Therefore it may be worthwhile to adjust the interface to change
28 // the class of the problem as needed. For the time being, however,
29 // all OSI problems are set to type LPX_MIP. The only trick is
30 // differentiating when the user calls status routines like
31 // isProvenOptimal(). For now, we assume that the user is referring
32 // to the most recent solution call. We add an extra variable,
33 // bbWasLast_, to the class to record which solution call was most
34 // recent (lp or mip).
35 //
36 // Possible areas of improvement
37 // -----------------------------
38 //
39 // Methods that are not implemented:
40 //
41 // getPrimalRays, getDualRays
42 //
43 // Methods that are implemented, but do not do what you probably expect:
44 //
45 // setColSolution, setRowPrice
46 //
47 // Many methods have not been attempted to be improved (for speed)
48 // to take advantage of how GLPK works. The emphasis has been on
49 // making things functional and not too messy. There's plenty of room
50 // for more efficient implementations.
51 //
52
53 /*
54 Various bits and pieces of knowledge that are handy when working on
55 OsiGlpk.
56
57 Glpk uses 1-based indexing. Be careful.
58
59 Primal and dual solutions may be set by the user. This means that
60 getColSolution and getRowPrice are obliged to return the cached solution
61 vector whenever it's available. Various other routines which calculate
62 values based on primal and dual solutions must also use the cached
63 vectors. On the other hand, we don't want to be rebuilding the cache with
64 every call to the solver. The approach is that a call to the solver removes
65 the cached values. Subsequent calls to retrieve solution values will
66 repopulate the cache by interrogating glpk.
67 */
68
69 #include <cassert>
70 #include <cstdio>
71 #include <cmath>
72 #include <string>
73 #include <iostream>
74
75 extern "C" {
76 #include "glpk.h"
77 }
78 #ifndef GLP_PROB_DEFINED
79 #define GLP_PROB_DEFINED
80 #endif
81
82 #include "CoinError.hpp"
83 #include "CoinPragma.hpp"
84
85 #include "OsiConfig.h"
86
87 #include "OsiGlpkSolverInterface.hpp"
88 #include "OsiRowCut.hpp"
89 #include "OsiColCut.hpp"
90 #include "CoinPackedMatrix.hpp"
91 #include "CoinWarmStartBasis.hpp"
92
93 /*
94 Grab the COIN standard finite infinity from CoinFinite.hpp. Also set a
95 zero tolerance, so we can set clean zeros in computed reduced costs and
96 row activities. The value 1.0e-9 is lifted from glpk --- this is the value
97 that it uses when the LPX_K_ROUND parameter is active.
98 */
99 #include "CoinFinite.hpp"
100 namespace {
101 const double CoinInfinity = COIN_DBL_MAX;
102 const double GlpkZeroTol = 1.0e-9;
103 }
104
105 /* Cut names down to a reasonable size. */
106
107 #define OGSI OsiGlpkSolverInterface
108
109 /*
110 A few defines to control execution tracing.
111
112 OGSI_TRACK_SOLVERS track creation, copy, deletion of OGSI objects
113 OGSI_TRACK_FRESH track how a solution is made stale/fresh
114 OGSI_VERBOSITY enables warnings when > 0; probably should be converted
115 to honest messages for message handler
116 */
117
118 #define OGSI_TRACK_SOLVERS 0
119 #define OGSI_TRACK_FRESH 0
120 #define OGSI_VERBOSITY 0
121
122 //#############################################################################
123 // File-local methods
124 //#############################################################################
125
126 namespace {
127
128 /*
129 Convenience routine for generating error messages. Who knows, maybe it'll get
130 used eventually :-).
131 */
132 inline void checkGLPKerror(int err, std::string glpkfuncname,
133 std::string osimethod)
134 {
135 if (err != 0) {
136 char s[100];
137 sprintf(s, "%s returned error %d", glpkfuncname.c_str(), err);
138 std::cout
139 << "ERROR: " << s
140 << " (" << osimethod << " in OsiGlpkSolverInterface)" << std::endl;
141 throw CoinError(s, osimethod.c_str(), "OsiGlpkSolverInterface");
142 }
143
144 return;
145 }
146
147 } // end file-local namespace
148
149 //#############################################################################
150 // Solve methods
151 //#############################################################################
152
153 /*
154 Solve an LP from scratch.
155 */
156 void OGSI::initialSolve()
157 {
158 #if OGSI_TRACK_FRESH > 0
159 std::cout
160 << "OGSI(" << std::hex << this << std::dec
161 << ")::initialSolve." << std::endl;
162 #endif
163
164 LPX *model = getMutableModelPtr();
165 /*
166 Prep. Toss any cached solution information.
167 */
168 freeCachedData(OGSI::FREECACHED_RESULTS);
169 /*
170 Solve the lp.
171 */
172 int err = lpx_simplex(model);
173
174 // for Glpk, a solve fails if the initial basis is invalid or singular
175 // thus, we construct a (advanced) basis first and try again
176 #ifdef LPX_E_BADB
177 if (err == LPX_E_BADB) {
178 lpx_adv_basis(model);
179 err = lpx_simplex(model);
180 } else
181 #endif
182 if (err == LPX_E_SING || err == LPX_E_FAULT) {
183 lpx_adv_basis(model);
184 err = lpx_simplex(model);
185 }
186
187 iter_used_ = lpx_get_int_parm(model, LPX_K_ITCNT);
188 /*
189 Sort out the various state indications.
190
191 When the presolver is turned on, lpx_simplex() will not be able to tell
192 whether the objective function has hit it's upper or lower limit, and does
193 not return OBJLL or OBJUL. The code for these cases should be beefed up to
194 check the objective against the limit.
195
196 The codes NOPFS and NODFS are returned only when the presolver is used.
197
198 If we ever reach the default case, we're deeply confused.
199 */
200 isIterationLimitReached_ = false;
201 isTimeLimitReached_ = false;
202 isAbandoned_ = false;
203 isPrimInfeasible_ = false;
204 isDualInfeasible_ = false;
205 isFeasible_ = false;
206 isObjLowerLimitReached_ = false;
207 isObjUpperLimitReached_ = false;
208
209 switch (err) {
210 case LPX_E_OK: {
211 break;
212 }
213 case LPX_E_ITLIM: {
214 isIterationLimitReached_ = true;
215 break;
216 }
217 case LPX_E_OBJLL: {
218 isObjLowerLimitReached_ = true;
219 break;
220 }
221 case LPX_E_OBJUL: {
222 isObjUpperLimitReached_ = true;
223 break;
224 }
225 case LPX_E_TMLIM: {
226 isTimeLimitReached_ = true;
227 } // no break here, so we still report abandoned
228 case LPX_E_FAULT:
229 case LPX_E_SING:
230 #ifdef LPX_E_BADB
231 case LPX_E_BADB:
232 #endif
233 {
234 isAbandoned_ = true;
235 break;
236 }
237 case LPX_E_NOPFS: {
238 isPrimInfeasible_ = true;
239 break;
240 }
241 case LPX_E_NODFS: {
242 isDualInfeasible_ = true;
243 break;
244 }
245 default: {
246 assert(false);
247 }
248 }
249
250 switch (lpx_get_status(model)) {
251 case LPX_OPT:
252 case LPX_FEAS: {
253 isFeasible_ = true;
254 break;
255 }
256 default: {
257 }
258 }
259
260 // Record that simplex was most recent
261 bbWasLast_ = 0;
262
263 return;
264 }
265
266 //-----------------------------------------------------------------------------
267
268 void OGSI::resolve()
269 {
270 #if OGSI_TRACK_FRESH > 0
271 std::cout
272 << "OGSI(" << std::hex << this << std::dec
273 << ")::resolve." << std::endl;
274 #endif
275
276 LPX *model = getMutableModelPtr();
277 freeCachedData(OGSI::FREECACHED_RESULTS);
278
279 // lpx_simplex will use the current basis if possible
280 int err = lpx_simplex(model);
281
282 // for Glpk, a solve fails if the initial basis is invalid or singular
283 // thus, we construct a (advanced) basis first and try again
284 #ifdef LPX_E_BADB
285 if (err == LPX_E_BADB) {
286 lpx_adv_basis(model);
287 err = lpx_simplex(model);
288 } else
289 #endif
290 if (err == LPX_E_SING || err == LPX_E_FAULT) {
291 lpx_adv_basis(model);
292 err = lpx_simplex(model);
293 }
294
295 iter_used_ = lpx_get_int_parm(model, LPX_K_ITCNT);
296
297 isIterationLimitReached_ = false;
298 isTimeLimitReached_ = false;
299 isAbandoned_ = false;
300 isObjLowerLimitReached_ = false;
301 isObjUpperLimitReached_ = false;
302 isPrimInfeasible_ = false;
303 isDualInfeasible_ = false;
304 isFeasible_ = false;
305
306 switch (err) {
307 case LPX_E_OK: {
308 break;
309 }
310 case LPX_E_ITLIM: {
311 isIterationLimitReached_ = true;
312 break;
313 }
314 case LPX_E_OBJLL: {
315 isObjLowerLimitReached_ = true;
316 break;
317 }
318 case LPX_E_OBJUL: {
319 isObjUpperLimitReached_ = true;
320 break;
321 }
322 case LPX_E_TMLIM: {
323 isTimeLimitReached_ = true;
324 } // no break here, so we still report abandoned
325 case LPX_E_FAULT:
326 case LPX_E_SING:
327 #ifdef LPX_E_BADB
328 case LPX_E_BADB:
329 #endif
330 {
331 isAbandoned_ = true;
332 break;
333 }
334 case LPX_E_NOPFS: {
335 isPrimInfeasible_ = true;
336 break;
337 }
338 case LPX_E_NODFS: {
339 isDualInfeasible_ = true;
340 break;
341 }
342 default: {
343 assert(false);
344 }
345 }
346
347 switch (lpx_get_status(model)) {
348 case LPX_OPT:
349 case LPX_FEAS: {
350 isFeasible_ = true;
351 break;
352 }
353 default: {
354 }
355 }
356
357 // Record that simplex was most recent
358 bbWasLast_ = 0;
359
360 return;
361 }
362
363 //-----------------------------------------------------------------------------
364
365 /*
366 Call glpk's built-in MIP solver. Any halfway recent version (from glpk 4.4,
367 at least) will have lpx_intopt, a branch-and-cut solver. The presence of cut
368 generators is more recent.
369 */
370 void OGSI::branchAndBound()
371
372 {
373 LPX *model = getMutableModelPtr();
374 /*
375 Destroy cached data.
376 */
377 freeCachedData(OGSI::FREECACHED_RESULTS);
378 /*
379 Assuming we have integer variables in the model, call the best MIP solver
380 we can manage.
381
382 lpx_intopt does not require an optimal LP solution as a starting point, so
383 we can call it directly.
384
385 lpx_integer needs an initial optimal solution to the relaxation.
386 */
387 if (lpx_get_num_int(model)) {
388 int err = LPX_E_FAULT;
389
390 #ifdef GLPK_HAS_INTOPT
391 err = lpx_intopt(model);
392 #else
393 if (lpx_get_status(model) != LPX_OPT) {
394 initialSolve();
395 }
396 err = lpx_integer(model);
397 #endif
398 /*
399 We have a result. What is it? Start with a positive attitude and revise as
400 needed. The various LPX_E_* and LPX_I_* defines are stable back as far as
401 glpk-4.4.
402
403 When we get LPX_E_OK (MIP terminated normally), we need to look more
404 closely. LPX_I_OPT indicates a proven optimal integer solution.
405 LPX_I_NOFEAS indicates that there is no integer feasible solution.
406 LPX_I_UNDEF says the MIP solution is undefined. LPX_I_FEAS says that in
407 integer feasible solution was found but not proven optimal (termination of
408 search due to some limit is the common cause). It's not clear what to do
409 with LPX_I_UNDEF; currently, it is not really reflected in
410 termination status. LPX_I_FEAS is reflected by the OsiGlpk specific method
411 isFeasible().
412
413 Various other codes are returned by lpx_intopt (lpx_integer returns a
414 subset of these). LPX_E_NOPFS (LPX_E_NODFS) indicate no primal (dual)
415 feasible solution; detected at the root, either by presolve or when
416 attempting the root relaxation. LPX_E_ITLIM (LPX_E_TMLIM) indicate
417 iteration (time) limit reached. Osi doesn't provide for time limit, so lump
418 it in with iteration limit (an arguable choice, but seems better than the
419 alternatives) and have extra method isTimeLimitReached().
420 LPX_E_SING (lp solver failed due to singular basis) is
421 legimately characterised as abandoned. LPX_E_FAULT indicates a structural
422 problem (problem not of class MIP, or an integer variable has a non-integer
423 bound), which really translates into internal confusion in OsiGlpk.
424
425 Previous comments expressed uncertainty about the iteration count. This
426 should be checked at some point. -- lh, 070709 --
427 */
428 iter_used_ = lpx_get_int_parm(model, LPX_K_ITCNT);
429 isIterationLimitReached_ = false;
430 isTimeLimitReached_ = false;
431 isAbandoned_ = false;
432 isPrimInfeasible_ = false;
433 isDualInfeasible_ = false;
434 isFeasible_ = false;
435 isObjLowerLimitReached_ = false;
436 isObjUpperLimitReached_ = false;
437
438 switch (err) {
439 case LPX_E_OK:
440 #ifdef LPX_E_MIPGAP
441 case LPX_E_MIPGAP:
442 #endif
443 {
444 break;
445 }
446 case LPX_E_NOPFS: {
447 isPrimInfeasible_ = true;
448 break;
449 }
450 case LPX_E_NODFS: {
451 isDualInfeasible_ = true;
452 break;
453 }
454 case LPX_E_TMLIM: {
455 isTimeLimitReached_ = true;
456 } // no break
457 case LPX_E_ITLIM: {
458 isIterationLimitReached_ = true;
459 break;
460 }
461 case LPX_E_SING: {
462 isAbandoned_ = true;
463 break;
464 }
465 case LPX_E_FAULT: {
466 assert(false);
467 break;
468 }
469 default: {
470 assert(false);
471 break;
472 }
473 }
474
475 //check this also if err!=LPX_E_OPT, so we know about feasibility in case time/resource limit is reached
476 int mip_status = lpx_mip_status(model);
477 switch (mip_status) {
478 case LPX_I_OPT: {
479 isFeasible_ = true;
480 break;
481 }
482 case LPX_I_NOFEAS: {
483 isPrimInfeasible_ = true;
484 break;
485 }
486 case LPX_I_UNDEF: {
487 break;
488 }
489 case LPX_I_FEAS: {
490 isFeasible_ = true;
491 break;
492 }
493 default: {
494 assert(false);
495 break;
496 }
497 }
498 /*
499 The final action is to note that our last call to glpk was the MIP solver.
500 */
501 bbWasLast_ = 1;
502 }
503 /*
504 Not a MIP (no integer variables). Call the LP solver. Since we can call
505 branchAndBound with no initial LP solution, initialSolve is appropriate here.
506 (But for glpk, it actually makes no difference --- lpx_simplex makes the
507 decision on how to proceed.)
508 */
509 else {
510 initialSolve();
511 }
512
513 return;
514 }
515
516 //#############################################################################
517 // Parameter related methods
518 //#############################################################################
519
520 /*
521 When we set parameters, we have to stash them locally as well as pushing
522 them into the LPX object. The trouble comes when loading a new problem. If
523 the LPX object is already loaded with a problem, the easiest approach is to
524 simply delete it and start fresh. But then we lose all the parameters that
525 are held in the LPX object. By keeping a copy, we have a way to recover.
526
527 Really, we should be keeping these values in the OSI base class arrays, but
528 the amount of storage involved is too small to provide motivation to change
529 from the present setup.
530 */
531
532 bool OGSI::setIntParam(OsiIntParam key, int value)
533
534 {
535 bool retval = false;
536
537 switch (key) {
538 case OsiMaxNumIteration: {
539 if (value >= 0) {
540 maxIteration_ = value;
541 lpx_set_int_parm(lp_, LPX_K_ITLIM, value);
542 retval = true;
543 } else {
544 retval = false;
545 }
546 break;
547 }
548 case OsiMaxNumIterationHotStart: {
549 if (value >= 0) {
550 hotStartMaxIteration_ = value;
551 retval = true;
552 } else {
553 retval = false;
554 }
555 break;
556 }
557 case OsiNameDiscipline: {
558 if (value < 0 || value > 3) {
559 retval = false;
560 } else {
561 nameDisc_ = value;
562 retval = true;
563 }
564 break;
565 }
566 case OsiLastIntParam: {
567 retval = false;
568 break;
569 }
570 }
571
572 return (retval);
573 }
574
575 //-----------------------------------------------------------------------------
576
577 /*
578 Self-protection is required here --- glpk will fault if handed a value
579 it doesn't like.
580 */
581
582 bool OGSI::setDblParam(OsiDblParam key, double value)
583
584 {
585 bool retval = false;
586
587 switch (key) {
588 case OsiDualObjectiveLimit:
589 // as of 4.7, GLPK only uses this if it does dual simplex
590 {
591 dualObjectiveLimit_ = value;
592 if (getObjSense() == 1) // minimization
593 {
594 lpx_set_real_parm(lp_, LPX_K_OBJUL, value);
595 } else // maximization
596 {
597 lpx_set_real_parm(lp_, LPX_K_OBJLL, value);
598 }
599 retval = true;
600 break;
601 }
602 case OsiPrimalObjectiveLimit:
603 // as of 4.7, GLPK only uses this if it does dual simplex
604 {
605 primalObjectiveLimit_ = value;
606 if (getObjSense() == 1) {
607 lpx_set_real_parm(lp_, LPX_K_OBJLL, value);
608 } else {
609 lpx_set_real_parm(lp_, LPX_K_OBJUL, value);
610 }
611 retval = true;
612 break;
613 }
614 case OsiDualTolerance: {
615 if (value >= 0 && value <= .001) {
616 dualTolerance_ = value;
617 lpx_set_real_parm(lp_, LPX_K_TOLDJ, value);
618 retval = true;
619 } else {
620 retval = false;
621 }
622 break;
623 }
624 case OsiPrimalTolerance: {
625 if (value >= 0 && value <= .001) {
626 primalTolerance_ = value;
627 lpx_set_real_parm(lp_, LPX_K_TOLBND, value);
628 retval = true;
629 } else {
630 retval = false;
631 }
632 break;
633 }
634 case OsiObjOffset: {
635 objOffset_ = value;
636 lpx_set_obj_coef(lp_, 0, value);
637 retval = true;
638 break;
639 }
640 case OsiLastDblParam: {
641 retval = false;
642 break;
643 }
644 }
645
646 return (retval);
647 }
648
649 //-----------------------------------------------------------------------------
650
651 bool OGSI::setStrParam(OsiStrParam key,
652 const std::string &value)
653 {
654 bool retval = false;
655
656 switch (key) {
657 case OsiProbName: {
658 probName_ = value;
659 if (probName_.length() == 0)
660 probName_ = "Pb";
661 lpx_set_prob_name(lp_, const_cast< char * >(value.c_str()));
662 retval = true;
663 break;
664 }
665 case OsiSolverName: {
666 retval = true;
667 break;
668 }
669 case OsiLastStrParam: {
670 break;
671 }
672 }
673
674 return (retval);
675 }
676
677 //-----------------------------------------------------------------------------
678
679 namespace {
680 /*!
681 A helper routine to deal with hints where glpk lacks any flexibility ---
682 the facility is unimplemented, or always on. Failure is defined as
683 OsiForceDo in the wrong direction; in this case an error is thrown. If the
684 routine returns, then either the hint is compatible with glpk's capabilities,
685 or it can be ignored.
686 */
687
688 void unimp_hint(CoinMessageHandler *hdl, bool glpkSense, bool hintSense,
689 OsiHintStrength hintStrength, const char *msgString)
690
691 {
692 if (glpkSense != hintSense) {
693 std::string message = "glpk ";
694 if (glpkSense == true) {
695 message += "cannot disable ";
696 } else {
697 message += "does not support ";
698 }
699 message += msgString;
700 *hdl << message << CoinMessageEol;
701 if (hintStrength == OsiForceDo) {
702 throw CoinError(message, "setHintParam", "OsiDylpSolverInterface");
703 }
704 }
705
706 return;
707 }
708
709 } // end file-local namespace
710
711 bool OGSI::setHintParam(OsiHintParam key, bool sense,
712 OsiHintStrength strength, void *info)
713 /*
714 OSI provides arrays for the sense and strength. OGSI provides the array for
715 info.
716 */
717
718 {
719 bool retval = false;
720 CoinMessageHandler *msgHdl = messageHandler();
721 /*
722 Check for out of range.
723 */
724 if (key >= OsiLastHintParam)
725 return (false);
726 /*
727 Set the hint in the OSI structures. Unlike the other set*Param routines,
728 setHintParam will return false for key == OsiLastHintParam. Unfortunately,
729 it'll also throw for strength = OsiForceDo, without setting a return value.
730 We need to catch that throw.
731 */
732 try {
733 retval = OsiSolverInterface::setHintParam(key, sense, strength);
734 } catch (CoinError &) {
735 retval = (strength == OsiForceDo);
736 }
737
738 if (retval == false)
739 return (false);
740 info_[key] = info;
741 /*
742 Did the client say `ignore this'? Who are we to argue.
743 */
744 if (strength == OsiHintIgnore)
745 return (true);
746 /*
747 We have a valid hint which would be impolite to simply ignore. Deal with
748 it as best we can. But say something if we're ignoring the hint.
749
750 This is under construction. For the present, we don't distinguish between
751 initial solve and resolve.
752 */
753 switch (key) {
754 case OsiDoPresolveInInitial:
755 case OsiDoPresolveInResolve: {
756 if (sense == false) {
757 if (strength >= OsiHintTry)
758 lpx_set_int_parm(lp_, LPX_K_PRESOL, 0);
759 } else {
760 lpx_set_int_parm(lp_, LPX_K_PRESOL, 1);
761 }
762 retval = true;
763 break;
764 }
765 case OsiDoDualInInitial:
766 case OsiDoDualInResolve: {
767 unimp_hint(msgHdl, false, sense, strength, "exclusive use of dual simplex");
768 if (sense == false) {
769 if (strength >= OsiHintDo)
770 lpx_set_int_parm(lp_, LPX_K_DUAL, 0);
771 } else {
772 lpx_set_int_parm(lp_, LPX_K_DUAL, 1);
773 }
774 retval = true;
775 break;
776 }
777 case OsiDoCrash: {
778 unimp_hint(msgHdl, false, sense, strength, "basis crash");
779 retval = true;
780 break;
781 }
782 case OsiDoInBranchAndCut: {
783 unimp_hint(msgHdl, false, sense, strength, "do in branch and cut");
784 retval = true;
785 break;
786 }
787 /*
788 0 is no scaling, 3 is geometric mean followed by equilibration.
789 */
790 case OsiDoScale: {
791 if (sense == false) {
792 if (strength >= OsiHintTry)
793 lpx_set_int_parm(lp_, LPX_K_SCALE, 0);
794 } else {
795 lpx_set_int_parm(lp_, LPX_K_SCALE, 3);
796 }
797 retval = true;
798 break;
799 }
800 /*
801 Glpk supports four levels, 0 (no output), 1 (errors only), 2 (normal), and
802 3 (normal plus informational).
803 */
804 case OsiDoReducePrint: {
805 if (sense == true) {
806 if (strength <= OsiHintTry) {
807 lpx_set_int_parm(lp_, LPX_K_MSGLEV, 1);
808 } else {
809 lpx_set_int_parm(lp_, LPX_K_MSGLEV, 0);
810 }
811 } else {
812 if (strength <= OsiHintTry) {
813 lpx_set_int_parm(lp_, LPX_K_MSGLEV, 2);
814 } else {
815 lpx_set_int_parm(lp_, LPX_K_MSGLEV, 3);
816 }
817 }
818 int logLevel = lpx_get_int_parm(lp_, LPX_K_MSGLEV);
819 messageHandler()->setLogLevel(logLevel);
820 retval = true;
821 break;
822 }
823 /*
824 The OSI spec says that unimplemented options (and, by implication, hints)
825 should return false. In the case of a hint, however, we can ignore anything
826 except OsiForceDo, so usability says we should anticipate new hints and set
827 this up so the solver doesn't break. So return true.
828 */
829 default: {
830 unimp_hint(msgHdl, !sense, sense, strength, "unrecognized hint");
831 retval = true;
832 break;
833 }
834 }
835
836 return (retval);
837 }
838 //-----------------------------------------------------------------------------
839
840 bool OGSI::getIntParam(OsiIntParam key, int &value) const
841 {
842 bool retval = false;
843 switch (key) {
844 case OsiMaxNumIteration:
845 value = maxIteration_;
846 retval = true;
847 break;
848
849 case OsiMaxNumIterationHotStart:
850 value = hotStartMaxIteration_;
851 retval = true;
852 break;
853
854 case OsiNameDiscipline:
855 value = nameDisc_;
856 retval = true;
857 break;
858
859 case OsiLastIntParam:
860 retval = false;
861 break;
862 }
863 return retval;
864 }
865
866 //-----------------------------------------------------------------------------
867
868 bool OGSI::getDblParam(OsiDblParam key, double &value) const
869 {
870 bool retval = false;
871 switch (key) {
872 case OsiDualObjectiveLimit:
873 value = dualObjectiveLimit_;
874 retval = true;
875 break;
876
877 case OsiPrimalObjectiveLimit:
878 value = primalObjectiveLimit_;
879 retval = true;
880 break;
881
882 case OsiDualTolerance:
883 value = dualTolerance_;
884 retval = true;
885 break;
886
887 case OsiPrimalTolerance:
888 value = primalTolerance_;
889 retval = true;
890 break;
891
892 case OsiObjOffset:
893 value = lpx_get_obj_coef(getMutableModelPtr(), 0);
894 retval = true;
895 break;
896
897 case OsiLastDblParam:
898 retval = false;
899 break;
900 }
901 return retval;
902 }
903
904 bool OGSI::getStrParam(OsiStrParam key, std::string &value) const
905 {
906 // bool retval = false;
907 switch (key) {
908 case OsiProbName:
909 value = lpx_get_prob_name(getMutableModelPtr());
910 break;
911 case OsiSolverName:
912 value = "glpk";
913 break;
914 case OsiLastStrParam:
915 return false;
916 }
917 return true;
918 }
919 //#############################################################################
920 // Methods returning info on how the solution process terminated
921 //#############################################################################
922
923 bool OGSI::isAbandoned() const
924 {
925 return isAbandoned_;
926 }
927
928 bool OGSI::isProvenOptimal() const
929 {
930 LPX *model = getMutableModelPtr();
931
932 if (bbWasLast_ == 0) {
933 int stat = lpx_get_status(model);
934 return stat == LPX_OPT;
935 } else {
936 int stat = lpx_mip_status(model);
937 return stat == LPX_I_OPT;
938 }
939 }
940
941 bool OGSI::isProvenPrimalInfeasible() const
942 {
943 LPX *model = getMutableModelPtr();
944
945 if (isPrimInfeasible_ == true)
946 return true;
947
948 if (bbWasLast_ == 0)
949 return lpx_get_prim_stat(model) == LPX_P_NOFEAS;
950 else
951 return lpx_mip_status(model) == LPX_I_NOFEAS;
952 }
953
954 bool OGSI::isProvenDualInfeasible() const
955 {
956 LPX *model = getMutableModelPtr();
957
958 if (isDualInfeasible_ == true)
959 return true;
960
961 if (bbWasLast_ == 0)
962 return lpx_get_dual_stat(model) == LPX_D_NOFEAS;
963 else
964 // Not sure what to do for MIPs; does it just mean unbounded?
965 // ??? for now, return false
966 return false;
967 }
968
969 /*
970 This should return true if the solver stopped on the primal limit, or if the
971 current objective is better than the primal limit. getObjSense == 1 is
972 minimisation, -1 is maximisation.
973 */
974 bool OGSI::isPrimalObjectiveLimitReached() const
975 {
976 bool retval = false;
977 double obj = getObjValue();
978 double objlim;
979
980 getDblParam(OsiPrimalObjectiveLimit, objlim);
981
982 if (getObjSense() == 1) {
983 if (isObjLowerLimitReached_ || obj < objlim) {
984 retval = true;
985 }
986 } else {
987 if (isObjUpperLimitReached_ || obj > objlim) {
988 retval = true;
989 }
990 }
991
992 return (retval);
993 }
994
995 /*
996 This should return true if the solver stopped on the dual limit, or if the
997 current objective is worse than the dual limit.
998 */
999 bool OGSI::isDualObjectiveLimitReached() const
1000 {
1001 bool retval = false;
1002 double obj = getObjValue();
1003 double objlim;
1004
1005 getDblParam(OsiDualObjectiveLimit, objlim);
1006
1007 if (getObjSense() == 1) {
1008 if (isObjUpperLimitReached_ || obj > objlim) {
1009 retval = true;
1010 }
1011 } else {
1012 if (isObjLowerLimitReached_ || obj < objlim) {
1013 retval = true;
1014 }
1015 }
1016
1017 return (retval);
1018 }
1019
1020 bool OGSI::isIterationLimitReached() const
1021 {
1022 return isIterationLimitReached_;
1023 }
1024
1025 bool OGSI::isTimeLimitReached() const
1026 {
1027 return isTimeLimitReached_;
1028 }
1029
1030 bool OGSI::isFeasible() const
1031 {
1032 return isFeasible_;
1033 }
1034
1035 //#############################################################################
1036 // WarmStart related methods
1037 //#############################################################################
1038
1039 /*
1040 Return a warm start object matching the current state of the solver.
1041
1042 Nonbasic fixed variables (LPX_NS) are translated to CWSB::atLowerBound.
1043 */
1044 CoinWarmStart *OGSI::getWarmStart() const
1045
1046 {
1047 /*
1048 Create an empty basis and size it to the correct dimensions.
1049 */
1050 CoinWarmStartBasis *ws = new CoinWarmStartBasis();
1051 int numcols = getNumCols();
1052 int numrows = getNumRows();
1053 ws->setSize(numcols, numrows);
1054 /*
1055 Walk the rows. Retrieve the status information from the glpk model and
1056 store it in the CWSB object.
1057 The convention in Osi regarding the status of a row when on bounds is different from Glpk.
1058 Thus, Glpk's at-lower-bound will be mapped to Osi's at-upper-bound
1059 and Glpk's at-upper-bound will be mapped to Osi's at-lower-bound.
1060 */
1061 for (int i = 0; i < numrows; i++) {
1062 int stati = lpx_get_row_stat(lp_, i + 1);
1063 switch (stati) {
1064 case LPX_BS: {
1065 ws->setArtifStatus(i, CoinWarmStartBasis::basic);
1066 break;
1067 }
1068 case LPX_NS:
1069 case LPX_NL: {
1070 ws->setArtifStatus(i, CoinWarmStartBasis::atUpperBound);
1071 break;
1072 }
1073 case LPX_NU: {
1074 ws->setArtifStatus(i, CoinWarmStartBasis::atLowerBound);
1075 break;
1076 }
1077 case LPX_NF: {
1078 ws->setArtifStatus(i, CoinWarmStartBasis::isFree);
1079 break;
1080 }
1081 default: {
1082 assert(false);
1083 break;
1084 }
1085 }
1086 }
1087 /*
1088 And repeat for the columns.
1089 */
1090 for (int j = 0; j < numcols; j++) {
1091 int statj = lpx_get_col_stat(lp_, j + 1);
1092 switch (statj) {
1093 case LPX_BS: {
1094 ws->setStructStatus(j, CoinWarmStartBasis::basic);
1095 break;
1096 }
1097 case LPX_NS:
1098 case LPX_NL: {
1099 ws->setStructStatus(j, CoinWarmStartBasis::atLowerBound);
1100 break;
1101 }
1102 case LPX_NU: {
1103 ws->setStructStatus(j, CoinWarmStartBasis::atUpperBound);
1104 break;
1105 }
1106 case LPX_NF: {
1107 ws->setStructStatus(j, CoinWarmStartBasis::isFree);
1108 break;
1109 }
1110 default: {
1111 assert(false);
1112 break;
1113 }
1114 }
1115 }
1116
1117 return (ws);
1118 }
1119
1120 //-----------------------------------------------------------------------------
1121
1122 /*
1123 Set the given warm start information in the solver.
1124
1125 By definition, a null warmstart parameter is interpreted as `refresh warm
1126 start information from the solver.' Since OGSI does not cache warm start
1127 information, no action is required.
1128 The convention in Osi regarding the status of a row when on bounds is different from Glpk.
1129 Thus, Osi's at-upper-bound will be mapped to Glpk's at-lower-bound
1130 and Osi's at-lower-bound will be mapped to Glpk's at-upper-bound.
1131 */
1132
1133 bool OGSI::setWarmStart(const CoinWarmStart *warmstart)
1134
1135 {
1136 /*
1137 If this is a simple refresh request, we're done.
1138 */
1139 if (warmstart == 0) {
1140 return (true);
1141 }
1142 /*
1143 Check that the parameter is a CWSB of the appropriate size.
1144 */
1145 const CoinWarmStartBasis *ws = dynamic_cast< const CoinWarmStartBasis * >(warmstart);
1146 if (ws == 0) {
1147 return false;
1148 }
1149
1150 int numcols = ws->getNumStructural();
1151 int numrows = ws->getNumArtificial();
1152
1153 if (numcols != getNumCols() || numrows != getNumRows()) {
1154 return (false);
1155 }
1156 /*
1157 Looks like a basis. Translate to the appropriate codes for glpk and install.
1158 Row status first (logical/artificial variables), then column status
1159 (architectural variables).
1160 */
1161 for (int i = 0; i < numrows; i++) {
1162 int stati;
1163
1164 switch (ws->getArtifStatus(i)) {
1165 case CoinWarmStartBasis::basic: {
1166 stati = LPX_BS;
1167 break;
1168 }
1169 case CoinWarmStartBasis::atLowerBound: {
1170 stati = LPX_NU;
1171 break;
1172 }
1173 case CoinWarmStartBasis::atUpperBound: {
1174 stati = LPX_NL;
1175 break;
1176 }
1177 case CoinWarmStartBasis::isFree: {
1178 stati = LPX_NF;
1179 break;
1180 }
1181 default: {
1182 assert(false);
1183 return (false);
1184 }
1185 }
1186
1187 lpx_set_row_stat(lp_, i + 1, stati);
1188 }
1189
1190 for (int j = 0; j < numcols; j++) {
1191 int statj;
1192
1193 switch (ws->getStructStatus(j)) {
1194 case CoinWarmStartBasis::basic: {
1195 statj = LPX_BS;
1196 break;
1197 }
1198 case CoinWarmStartBasis::atLowerBound: {
1199 statj = LPX_NL;
1200 break;
1201 }
1202 case CoinWarmStartBasis::atUpperBound: {
1203 statj = LPX_NU;
1204 break;
1205 }
1206 case CoinWarmStartBasis::isFree: {
1207 statj = LPX_NF;
1208 break;
1209 }
1210 default: {
1211 assert(false);
1212 return (false);
1213 }
1214 }
1215
1216 lpx_set_col_stat(lp_, j + 1, statj);
1217 }
1218
1219 return (true);
1220 }
1221
1222 //#############################################################################
1223 // Hotstart related methods (primarily used in strong branching)
1224 //#############################################################################
1225
1226 void OGSI::markHotStart()
1227 {
1228 LPX *model = getMutableModelPtr();
1229 int numcols, numrows;
1230
1231 numcols = getNumCols();
1232 numrows = getNumRows();
1233 if (numcols > hotStartCStatSize_) {
1234 delete[] hotStartCStat_;
1235 delete[] hotStartCVal_;
1236 delete[] hotStartCDualVal_;
1237 hotStartCStatSize_ = static_cast< int >(1.2 * static_cast< double >(numcols)); // get some extra space for future hot starts
1238 hotStartCStat_ = new int[hotStartCStatSize_];
1239 hotStartCVal_ = new double[hotStartCStatSize_];
1240 hotStartCDualVal_ = new double[hotStartCStatSize_];
1241 }
1242 int j;
1243 for (j = 0; j < numcols; j++) {
1244 int stat;
1245 double val;
1246 double dualVal;
1247 stat = lpx_get_col_stat(model, j);
1248 val = lpx_get_col_prim(model, j);
1249 dualVal = lpx_get_col_dual(model, j);
1250 hotStartCStat_[j] = stat;
1251 hotStartCVal_[j] = val;
1252 hotStartCDualVal_[j] = dualVal;
1253 }
1254
1255 if (numrows > hotStartRStatSize_) {
1256 delete[] hotStartRStat_;
1257 delete[] hotStartRVal_;
1258 delete[] hotStartRDualVal_;
1259 hotStartRStatSize_ = static_cast< int >(1.2 * static_cast< double >(numrows)); // get some extra space for future hot starts
1260 hotStartRStat_ = new int[hotStartRStatSize_];
1261 hotStartRVal_ = new double[hotStartRStatSize_];
1262 hotStartRDualVal_ = new double[hotStartRStatSize_];
1263 }
1264 int i;
1265 for (i = 0; i < numrows; i++) {
1266 int stat;
1267 double val;
1268 double dualVal;
1269 stat = lpx_get_row_stat(model, i + 1);
1270 val = lpx_get_row_prim(model, i + 1);
1271 dualVal = lpx_get_row_dual(model, i + 1);
1272 hotStartRStat_[i] = stat;
1273 hotStartRVal_[i] = val;
1274 hotStartRDualVal_[i] = dualVal;
1275 }
1276 }
1277
1278 //-----------------------------------------------------------------------------
1279
1280 void OGSI::solveFromHotStart()
1281 {
1282 #if OGSI_TRACK_FRESH > 0
1283 std::cout
1284 << "OGSI(" << std::hex << this << std::dec
1285 << ")::solveFromHotStart." << std::endl;
1286 #endif
1287 LPX *model = getMutableModelPtr();
1288 int numcols, numrows;
1289
1290 numcols = getNumCols();
1291 numrows = getNumRows();
1292
1293 assert(numcols <= hotStartCStatSize_);
1294 assert(numrows <= hotStartRStatSize_);
1295
1296 int j;
1297 for (j = 0; j < numcols; j++) {
1298 lpx_set_col_stat(model, j + 1, hotStartCStat_[j]);
1299 }
1300 int i;
1301 for (i = 0; i < numrows; i++) {
1302 lpx_set_row_stat(model, i + 1, hotStartRStat_[i]);
1303 }
1304
1305 freeCachedData(OGSI::FREECACHED_RESULTS);
1306
1307 int maxIteration = maxIteration_;
1308 maxIteration_ = hotStartMaxIteration_;
1309 resolve();
1310 maxIteration_ = maxIteration;
1311 }
1312
1313 //-----------------------------------------------------------------------------
1314
1315 void OGSI::unmarkHotStart()
1316 {
1317 // ??? be lazy with deallocating memory and do nothing here, deallocate memory in the destructor.
1318 }
1319
1320 //#############################################################################
1321 // Problem information methods (original data)
1322 //#############################################################################
1323
1324 //-----------------------------------------------------------------------------
1325 // Get number of rows, columns, elements, ...
1326 //-----------------------------------------------------------------------------
1327 int OGSI::getNumCols() const
1328 {
1329 return lpx_get_num_cols(getMutableModelPtr());
1330 }
1331
1332 int OGSI::getNumRows() const
1333 {
1334 return lpx_get_num_rows(getMutableModelPtr());
1335 }
1336
1337 CoinBigIndex OGSI::getNumElements() const
1338 {
1339 return lpx_get_num_nz(getMutableModelPtr());
1340 }
1341
1342 //-----------------------------------------------------------------------------
1343 // Get pointer to rim vectors
1344 //------------------------------------------------------------------
1345
1346 const double *OGSI::getColLower() const
1347 {
1348 LPX *model = getMutableModelPtr();
1349
1350 if (collower_ == NULL) {
1351 assert(colupper_ == NULL);
1352 int numcols = getNumCols();
1353 if (numcols > 0) {
1354 collower_ = new double[numcols];
1355 colupper_ = new double[numcols];
1356 }
1357
1358 double inf = getInfinity();
1359
1360 int i;
1361 for (i = 0; i < numcols; i++) {
1362 int type;
1363 double lb;
1364 double ub;
1365 type = lpx_get_col_type(model, i + 1);
1366 lb = lpx_get_col_lb(model, i + 1);
1367 ub = lpx_get_col_ub(model, i + 1);
1368 switch (type) {
1369 case LPX_FR:
1370 lb = -inf;
1371 ub = inf;
1372 break;
1373
1374 case LPX_LO:
1375 ub = inf;
1376 break;
1377
1378 case LPX_UP:
1379 lb = -inf;
1380 break;
1381
1382 case LPX_FX:
1383 case LPX_DB:
1384 break;
1385
1386 default:
1387 assert(false);
1388 break;
1389 }
1390 collower_[i] = lb;
1391 colupper_[i] = ub;
1392 }
1393 }
1394 return collower_;
1395 }
1396
1397 //-----------------------------------------------------------------------------
1398
1399 const double *OGSI::getColUpper() const
1400 {
1401 if (colupper_ == NULL) {
1402 getColLower();
1403 //assert( colupper_ != NULL ); // Could be null if no columns.
1404 }
1405 return colupper_;
1406 }
1407
1408 //-----------------------------------------------------------------------------
1409
1410 const char *OGSI::getRowSense() const
1411 {
1412 // Could be in OsiSolverInterfaceImpl.
1413 if (rowsense_ == NULL) {
1414 assert(rhs_ == NULL && rowrange_ == NULL);
1415
1416 int numrows = getNumRows();
1417 if (numrows > 0) {
1418 rowsense_ = new char[numrows];
1419 rhs_ = new double[numrows];
1420 rowrange_ = new double[numrows];
1421 }
1422
1423 const double *rowlower = getRowLower();
1424 const double *rowupper = getRowUpper();
1425 int i;
1426 for (i = 0; i < numrows; i++) {
1427 char sense;
1428 double right;
1429 double range;
1430 convertBoundToSense(rowlower[i], rowupper[i], sense, right, range);
1431 rowsense_[i] = sense;
1432 rhs_[i] = right;
1433 rowrange_[i] = range;
1434 }
1435 }
1436 return rowsense_;
1437 }
1438
1439 //-----------------------------------------------------------------------------
1440
1441 const double *OGSI::getRightHandSide() const
1442 {
1443 if (rhs_ == NULL) {
1444 getRowSense();
1445 //assert( rhs_ != NULL ); // Could be null if no rows.
1446 }
1447 return rhs_;
1448 }
1449
1450 //-----------------------------------------------------------------------------
1451
1452 const double *OGSI::getRowRange() const
1453 {
1454 if (rowrange_ == NULL) {
1455 getRowSense();
1456 //assert( rowrange_ != NULL ); // Could be null if no rows.
1457 }
1458 return rowrange_;
1459 }
1460
1461 //-----------------------------------------------------------------------------
1462
1463 const double *OGSI::getRowLower() const
1464 {
1465 LPX *model = getMutableModelPtr();
1466
1467 if (rowlower_ == NULL) {
1468 assert(rowupper_ == NULL);
1469 int numrows = getNumRows();
1470 if (numrows > 0) {
1471 rowlower_ = new double[numrows];
1472 rowupper_ = new double[numrows];
1473 }
1474 int i;
1475 for (i = 0; i < numrows; i++) {
1476 double inf = getInfinity();
1477 int type;
1478 double lb;
1479 double ub;
1480 type = lpx_get_row_type(model, i + 1);
1481 lb = lpx_get_row_lb(model, i + 1);
1482 ub = lpx_get_row_ub(model, i + 1);
1483 switch (type) {
1484 case LPX_FR:
1485 lb = -inf;
1486 ub = inf;
1487 break;
1488
1489 case LPX_LO:
1490 ub = inf;
1491 break;
1492
1493 case LPX_UP:
1494 lb = -inf;
1495 break;
1496
1497 case LPX_DB:
1498 case LPX_FX:
1499 break;
1500
1501 default:
1502 assert(false);
1503 break;
1504 }
1505 rowlower_[i] = lb;
1506 rowupper_[i] = ub;
1507 }
1508 }
1509 return rowlower_;
1510 }
1511
1512 //-----------------------------------------------------------------------------
1513
1514 const double *OGSI::getRowUpper() const
1515 {
1516 if (rowupper_ == NULL) {
1517 getRowLower();
1518 //assert( rowupper_ != NULL ); // Could be null if no rows.
1519 }
1520 return rowupper_;
1521 }
1522
1523 //-----------------------------------------------------------------------------
1524
1525 const double *OGSI::getObjCoefficients() const
1526 {
1527 if (obj_ == NULL) {
1528 LPX *model = getMutableModelPtr();
1529
1530 int numcols = getNumCols();
1531 if (numcols > 0) {
1532 obj_ = new double[numcols];
1533 }
1534 int i;
1535 for (i = 0; i < numcols; i++) {
1536 obj_[i] = lpx_get_obj_coef(model, i + 1);
1537 }
1538 }
1539 return obj_;
1540 }
1541
1542 //-----------------------------------------------------------------------------
1543
1544 double OGSI::getObjSense() const
1545
1546 {
1547 if (lpx_get_obj_dir(lp_) == LPX_MIN) {
1548 return (+1.0);
1549 } else if (lpx_get_obj_dir(lp_) == LPX_MAX) {
1550 return (-1.0);
1551 } else // internal confusion
1552 {
1553 assert(false);
1554 return (0);
1555 }
1556 }
1557
1558 //-----------------------------------------------------------------------------
1559 // Return information on integrality
1560 //-----------------------------------------------------------------------------
1561
1562 bool OGSI::isContinuous(int colNumber) const
1563 {
1564 return lpx_get_col_kind(getMutableModelPtr(), colNumber + 1) == LPX_CV;
1565 }
1566
1567 //-----------------------------------------------------------------------------
1568 // Row and column copies of the matrix ...
1569 //-----------------------------------------------------------------------------
1570
1571 const CoinPackedMatrix *OGSI::getMatrixByRow() const
1572 {
1573 if (matrixByRow_ == NULL) {
1574 LPX *model = getMutableModelPtr();
1575
1576 matrixByRow_ = new CoinPackedMatrix();
1577 matrixByRow_->transpose(); // converts to row-order
1578 matrixByRow_->setDimensions(0, getNumCols());
1579
1580 int numcols = getNumCols();
1581 int *colind = new int[numcols + 1];
1582 double *colelem = new double[numcols + 1];
1583 int i;
1584 for (i = 0; i < getNumRows(); i++) {
1585 int colsize = lpx_get_mat_row(model, i + 1, colind, colelem);
1586 int j;
1587 for (j = 1; j <= colsize; j++) {
1588 --colind[j];
1589 }
1590
1591 // Note: lpx_get_mat_row apparently may return the
1592 // elements in decreasing order. This differs from
1593 // people's standard expectations but is not an error.
1594
1595 matrixByRow_->appendRow(colsize, colind + 1, colelem + 1);
1596 }
1597 delete[] colind;
1598 delete[] colelem;
1599 if (numcols)
1600 matrixByRow_->removeGaps();
1601 }
1602 return matrixByRow_;
1603 }
1604
1605 //-----------------------------------------------------------------------------
1606
1607 const CoinPackedMatrix *OGSI::getMatrixByCol() const
1608 {
1609 if (matrixByCol_ == NULL) {
1610 LPX *model = getMutableModelPtr();
1611
1612 matrixByCol_ = new CoinPackedMatrix();
1613 matrixByCol_->setDimensions(getNumRows(), 0);
1614
1615 int numrows = getNumRows();
1616 int *rowind = new int[numrows + 1];
1617 double *rowelem = new double[numrows + 1];
1618 int j;
1619 for (j = 0; j < getNumCols(); j++) {
1620 int rowsize = lpx_get_mat_col(model, j + 1, rowind, rowelem);
1621 int i;
1622 for (i = 1; i <= rowsize; i++) {
1623 --rowind[i];
1624 }
1625 matrixByCol_->appendCol(rowsize, rowind + 1, rowelem + 1);
1626 }
1627 delete[] rowind;
1628 delete[] rowelem;
1629 if (numrows)
1630 matrixByCol_->removeGaps();
1631 }
1632 return matrixByCol_;
1633 }
1634
1635 //-----------------------------------------------------------------------------
1636 // Get solver's value for infinity
1637 //-----------------------------------------------------------------------------
1638 double OGSI::getInfinity() const
1639 {
1640 return (CoinInfinity);
1641 }
1642
1643 //#############################################################################
1644 // Problem information methods (results)
1645 //#############################################################################
1646
1647 /*
1648 Retrieve column solution, querying solver if we don't have a cached solution.
1649 Refresh reduced costs while we're here.
1650
1651 Reduced costs may or may not already exist (user can create a reduced cost
1652 vector by supplying duals (row price) and asking for reduced costs).
1653
1654 Appropriate calls depend on whether last call to solver was simplex or
1655 branch-and-bound.
1656 */
1657
1658 const double *OGSI::getColSolution() const
1659
1660 {
1661 /*
1662 Use the cached solution vector, if present. If we have no constraint system,
1663 return 0.
1664 */
1665 if (colsol_ != 0) {
1666 return (colsol_);
1667 }
1668
1669 int numcols = getNumCols();
1670 if (numcols == 0) {
1671 return (0);
1672 }
1673
1674 colsol_ = new double[numcols];
1675 if (redcost_ != 0)
1676 delete[] redcost_;
1677 {
1678 redcost_ = new double[numcols];
1679 }
1680 /*
1681 Grab the problem status.
1682 */
1683 int probStatus;
1684 if (bbWasLast_) {
1685 probStatus = lpx_mip_status(lp_);
1686 } else {
1687 probStatus = lpx_get_status(lp_);
1688 }
1689 /*
1690 If the problem hasn't been solved, glpk returns zeros, but OSI requires that
1691 the solution be within bound. getColLower() will ensure both upper and lower
1692 bounds are present. There's an implicit assumption that we're feasible (i.e.,
1693 collower[j] < colupper[j]). Solution values will be 0.0 unless that's outside
1694 the bounds.
1695 */
1696 if (probStatus == LPX_UNDEF || probStatus == LPX_I_UNDEF) {
1697 getColLower();
1698 int j;
1699 for (j = 0; j < numcols; j++) {
1700 colsol_[j] = 0.0;
1701 if (collower_[j] > 0.0) {
1702 colsol_[j] = collower_[j];
1703 } else if (colupper_[j] < 0.0) {
1704 colsol_[j] = colupper_[j];
1705 }
1706 }
1707 }
1708 /*
1709 We should have a defined solution. For simplex, refresh the reduced costs
1710 as well as the primal solution. Remove infinitesimals from the results.
1711 */
1712 else if (bbWasLast_ == 0) {
1713 int j;
1714 for (j = 0; j < numcols; j++) {
1715 colsol_[j] = lpx_get_col_prim(lp_, j + 1);
1716 if (fabs(colsol_[j]) < GlpkZeroTol) {
1717 colsol_[j] = 0.0;
1718 }
1719 redcost_[j] = lpx_get_col_dual(lp_, j + 1);
1720 if (fabs(redcost_[j]) < GlpkZeroTol) {
1721 redcost_[j] = 0.0;
1722 }
1723 }
1724 }
1725 /*
1726 Last solve was branch-and-bound. Set the reduced costs to 0. Remove
1727 infinitesimals from the results.
1728 */
1729 else {
1730 int j;
1731 for (j = 0; j < numcols; j++) {
1732 colsol_[j] = lpx_mip_col_val(lp_, j + 1);
1733 if (fabs(colsol_[j]) < GlpkZeroTol) {
1734 colsol_[j] = 0.0;
1735 }
1736 redcost_[j] = 0.0;
1737 }
1738 }
1739
1740 return (colsol_);
1741 }
1742
1743 //-----------------------------------------------------------------------------
1744
1745 /*
1746 Acquire the row solution (dual variables).
1747
1748 The user can set this independently, so use the cached copy if it's present.
1749 */
1750
1751 const double *OGSI::getRowPrice() const
1752
1753 {
1754 /*
1755 If we have a cached solution, use it. If the constraint system is empty,
1756 return 0. Otherwise, allocate a new vector.
1757 */
1758 if (rowsol_ != 0) {
1759 return (rowsol_);
1760 }
1761
1762 int numrows = getNumRows();
1763 if (numrows == 0) {
1764 return (0);
1765 }
1766
1767 rowsol_ = new double[numrows];
1768 /*
1769 For simplex, we have dual variables. For MIP, just set them to zero. Remove
1770 infinitesimals from the results.
1771 */
1772 if (bbWasLast_ == 0) {
1773 int i;
1774 for (i = 0; i < numrows; i++) {
1775 rowsol_[i] = lpx_get_row_dual(lp_, i + 1);
1776 if (fabs(rowsol_[i]) < GlpkZeroTol) {
1777 rowsol_[i] = 0.0;
1778 }
1779 }
1780 } else {
1781 int i;
1782 for (i = 0; i < numrows; i++) {
1783 rowsol_[i] = 0;
1784 }
1785 }
1786
1787 return (rowsol_);
1788 }
1789
1790 //-----------------------------------------------------------------------------
1791
1792 /*
1793 It's tempting to dive into glpk for this, but ... the client may have used
1794 setRowPrice(), and it'd be nice to return reduced costs that agree with the
1795 duals.
1796
1797 To use glpk's routine (lpx_get_col_dual), the interface needs to track the
1798 origin of the dual (row price) values.
1799 */
1800 const double *OGSI::getReducedCost() const
1801 {
1802 /*
1803 Return the cached copy, if it exists.
1804 */
1805 if (redcost_ != 0) {
1806 return (redcost_);
1807 }
1808 /*
1809 We need to calculate. Make sure we have a constraint system, then allocate
1810 a vector and initialise it with the objective coefficients.
1811 */
1812 int n = getNumCols();
1813 if (n == 0) {
1814 return (0);
1815 }
1816
1817 redcost_ = new double[n];
1818 CoinDisjointCopyN(getObjCoefficients(), n, redcost_);
1819 /*
1820 Try and acquire dual variables.
1821 */
1822 const double *y = getRowPrice();
1823 if (!y) {
1824 return (redcost_);
1825 }
1826 /*
1827 Acquire the constraint matrix and calculate y*A.
1828 */
1829 const CoinPackedMatrix *mtx = getMatrixByCol();
1830 double *yA = new double[n];
1831 mtx->transposeTimes(y, yA);
1832 /*
1833 Calculate c-yA and remove infinitesimals from the result.
1834 */
1835 for (int j = 0; j < n; j++) {
1836 redcost_[j] -= yA[j];
1837 if (fabs(redcost_[j]) < GlpkZeroTol) {
1838 redcost_[j] = 0;
1839 }
1840 }
1841
1842 delete[] yA;
1843
1844 return (redcost_);
1845 }
1846
1847 //-----------------------------------------------------------------------------
1848
1849 /*
1850 As with getReducedCost, we need to be mindful that the primal solution may
1851 have been set by the client. As it happens, however, glpk has no equivalent
1852 routine, so there's no temptation to resist.
1853 */
1854
1855 const double *OGSI::getRowActivity() const
1856
1857 {
1858 /*
1859 Return the cached copy, if it exists.
1860 */
1861 if (rowact_) {
1862 return (rowact_);
1863 }
1864 /*
1865 We need to calculate. Make sure we have a constraint system, then allocate
1866 a vector and initialise it with the objective coefficients.
1867 */
1868 int m = getNumRows();
1869 if (m == 0) {
1870 return (0);
1871 }
1872
1873 rowact_ = new double[m];
1874 /*
1875 Acquire primal variables.
1876 */
1877 const double *x = getColSolution();
1878 if (!x) {
1879 CoinZeroN(rowact_, m);
1880 return (rowact_);
1881 }
1882 /*
1883 Acquire the constraint matrix and calculate A*x.
1884 */
1885 const CoinPackedMatrix *mtx = getMatrixByRow();
1886 mtx->times(x, rowact_);
1887 /*
1888 Remove infinitesimals from the result.
1889 */
1890 for (int i = 0; i < m; i++) {
1891 if (fabs(rowact_[i]) < GlpkZeroTol) {
1892 rowact_[i] = 0;
1893 }
1894 }
1895
1896 return (rowact_);
1897 }
1898
1899 //-----------------------------------------------------------------------------
1900
1901 double OGSI::getObjValue() const
1902 {
1903 return OsiSolverInterface::getObjValue();
1904 }
1905
1906 //-----------------------------------------------------------------------------
1907
1908 int OGSI::getIterationCount() const
1909 {
1910 return iter_used_;
1911 }
1912
1913 //-----------------------------------------------------------------------------
1914
1915 std::vector< double * > OGSI::getDualRays(int /*maxNumRays*/, bool /*fullRay*/) const
1916 {
1917 // ??? not yet implemented.
1918 throw CoinError("method is not yet implemented", "getDualRays", "OsiGlpkSolverInterface");
1919 return std::vector< double * >();
1920 }
1921
1922 //-----------------------------------------------------------------------------
1923
1924 std::vector< double * > OGSI::getPrimalRays(int /*maxNumRays*/) const
1925 {
1926 // ??? not yet implemented.
1927 throw CoinError("method is not yet implemented", "getPrimalRays", "OsiGlpkSolverInterface");
1928 return std::vector< double * >();
1929 }
1930
1931 //#############################################################################
1932 // Problem modifying methods (rim vectors)
1933 //#############################################################################
1934
1935 /*
1936 Yes, I know the OSI spec says that pointers returned by get*() routines are
1937 valid only as long as the data is unchanged. But in practice, client code
1938 (in particular, portions of Cgl and Cbc) expects that simple changes to rim
1939 vector values will not invalidate pointers returned by the various get*()
1940 routines. So, for example, modifying an objective coefficient should not
1941 free the cached copies of the objective and column bounds. They should be
1942 updated on-the-fly. This is exactly the opposite of the original OsiGlpk
1943 design, hence this warning.
1944
1945 Beyond that, it's helpful for an OSI to hold on to the current solution as
1946 long as possible. So, for example, a bounds change that does not make the
1947 current solution infeasible should not trash the cached solution.
1948
1949 -- lh, 070326
1950 */
1951
1952 void OGSI::setObjCoeff(int j, double cj)
1953
1954 {
1955 assert(j >= 0 && j < getNumCols());
1956
1957 /*
1958 Remove the solution. Arguably the only thing that we should remove here is
1959 the cached reduced cost.
1960 */
1961 freeCachedData(OGSI::KEEPCACHED_PROBLEM);
1962 /*
1963 Push the changed objective down to glpk.
1964 */
1965 lpx_set_obj_coef(lp_, j + 1, cj);
1966
1967 if (obj_) {
1968 obj_[j] = cj;
1969 }
1970
1971 return;
1972 }
1973
1974 //-----------------------------------------------------------------------------
1975
1976 void OGSI::setColLower(int j, double lbj)
1977
1978 {
1979 /*
1980 Get the upper bound, so we can call setColBounds. glpk reports 0 for an
1981 infinite bound, so we need to check the status and possibly correct.
1982 */
1983 double inf = getInfinity();
1984 int type = lpx_get_col_type(lp_, j + 1);
1985 double ubj = lpx_get_col_ub(lp_, j + 1);
1986 switch (type) {
1987 case LPX_UP:
1988 case LPX_DB:
1989 case LPX_FX: {
1990 break;
1991 }
1992 case LPX_FR:
1993 case LPX_LO: {
1994 ubj = inf;
1995 break;
1996 }
1997 default: {
1998 assert(false);
1999 }
2000 }
2001
2002 #if OGSI_TRACK_FRESH > 0
2003 /*
2004 Check if this bound really invalidates the current solution. This check will
2005 give false positives because OsiGlpk needs a notion of `valid solution from
2006 solver'. getColSolution will always return something, even if it has to make
2007 it up on the spot.
2008 */
2009 {
2010 const double *x = getColSolution();
2011 if (x) {
2012 if (x[j] < lbj - GlpkZeroTol) {
2013 std::cout
2014 << "OGSI(" << std::hex << this << std::dec
2015 << ")::setColLower: new bound "
2016 << lbj << " exceeds current value " << x[j]
2017 << " by " << (lbj - x[j]) << "." << std::endl;
2018 }
2019 }
2020 }
2021 #endif
2022
2023 setColBounds(j, lbj, ubj);
2024
2025 return;
2026 }
2027
2028 //-----------------------------------------------------------------------------
2029
2030 void OGSI::setColUpper(int j, double ubj)
2031
2032 {
2033 /*
2034 Get the lower bound, so we can call setColBounds. glpk reports 0 for an
2035 infinite bound, so we need to check the status and possibly correct.
2036 */
2037 double inf = getInfinity();
2038 int type = lpx_get_col_type(lp_, j + 1);
2039 double lbj = lpx_get_col_lb(lp_, j + 1);
2040 switch (type) {
2041 case LPX_LO:
2042 case LPX_DB:
2043 case LPX_FX: {
2044 break;
2045 }
2046 case LPX_FR:
2047 case LPX_UP: {
2048 lbj = inf;
2049 break;
2050 }
2051 default: {
2052 assert(false);
2053 }
2054 }
2055
2056 #if OGSI_TRACK_FRESH > 0
2057 /*
2058 Check if this bound really invalidates the current solution. This check will
2059 give false positives because OsiGlpk needs a notion of `valid solution from
2060 solver'. getColSolution will always return something, even if it has to make
2061 it up on the spot.
2062 */
2063 {
2064 const double *x = getColSolution();
2065 if (x) {
2066 if (x[j] > ubj + GlpkZeroTol) {
2067 std::cout
2068 << "OGSI(" << std::hex << this << std::dec
2069 << ")::setColUpper: new bound "
2070 << ubj << " exceeds current value " << x[j]
2071 << " by " << (x[j] - ubj) << "." << std::endl;
2072 }
2073 }
2074 }
2075 #endif
2076
2077 setColBounds(j, lbj, ubj);
2078
2079 return;
2080 }
2081
2082 //-----------------------------------------------------------------------------
2083
2084 /*
2085 Yes, in theory, we shouldn't need to worry about maintaining those cached
2086 column bounds over changes to the problem. See the note at the top of this
2087 section.
2088 */
2089
2090 void OGSI::setColBounds(int j, double lower, double upper)
2091
2092 {
2093 assert(j >= 0 && j < getNumCols());
2094 /*
2095 Free only the cached solution. Keep the cached structural variables.
2096 */
2097 freeCachedData(OGSI::KEEPCACHED_PROBLEM);
2098 /*
2099 Figure out what type we should use for glpk.
2100 */
2101 double inf = getInfinity();
2102 int type;
2103
2104 if (lower == upper) {
2105 type = LPX_FX;
2106 } else if (lower > -inf && upper < inf) {
2107 type = LPX_DB;
2108 } else if (lower > -inf) {
2109 type = LPX_LO;
2110 } else if (upper < inf) {
2111 type = LPX_UP;
2112 } else {
2113 type = LPX_FR;
2114 }
2115 /*
2116 Push the bound change down into the solver. 1-based addressing.
2117 */
2118 int statj = lpx_get_col_stat(lp_, j + 1);
2119 lpx_set_col_bnds(lp_, j + 1, type, lower, upper);
2120 lpx_set_col_stat(lp_, j + 1, statj);
2121 statj = lpx_get_col_stat(lp_, j + 1);
2122 /*
2123 Correct the cached upper and lower bound vectors, if present.
2124 */
2125 if (collower_) {
2126 collower_[j] = lower;
2127 }
2128 if (colupper_) {
2129 colupper_[j] = upper;
2130 }
2131
2132 return;
2133 }
2134
2135 //-----------------------------------------------------------------------------
2136
2137 void OGSI::setColSetBounds(const int *indexFirst,
2138 const int *indexLast,
2139 const double *boundList)
2140 {
2141 OsiSolverInterface::setColSetBounds(indexFirst, indexLast, boundList);
2142 }
2143
2144 //-----------------------------------------------------------------------------
2145
2146 void OGSI::setRowLower(int elementIndex, double elementValue)
2147 {
2148 // Could be in OsiSolverInterfaceImpl.
2149 double inf = getInfinity();
2150
2151 int type;
2152 double lb;
2153 double ub;
2154
2155 type = lpx_get_row_type(getMutableModelPtr(), elementIndex + 1);
2156 ub = lpx_get_row_ub(getMutableModelPtr(), elementIndex + 1);
2157 lb = elementValue;
2158 switch (type) {
2159 case LPX_UP:
2160 case LPX_DB:
2161 case LPX_FX:
2162 break;
2163
2164 case LPX_FR:
2165 case LPX_LO:
2166 ub = inf;
2167 break;
2168
2169 default:
2170 assert(false);
2171 }
2172 setRowBounds(elementIndex, lb, ub);
2173 }
2174
2175 //-----------------------------------------------------------------------------
2176 void OGSI::setRowUpper(int elementIndex, double elementValue)
2177 {
2178 // Could be in OsiSolverInterfaceImpl.
2179 double inf = getInfinity();
2180
2181 int type;
2182 double lb;
2183 double ub;
2184
2185 type = lpx_get_row_type(getMutableModelPtr(), elementIndex + 1);
2186 lb = lpx_get_row_lb(getMutableModelPtr(), elementIndex + 1);
2187 ub = elementValue;
2188 switch (type) {
2189 case LPX_LO:
2190 case LPX_DB:
2191 case LPX_FX:
2192 break;
2193
2194 case LPX_FR:
2195 case LPX_UP:
2196 lb = -inf;
2197 break;
2198
2199 default:
2200 assert(false);
2201 }
2202 setRowBounds(elementIndex, lb, ub);
2203 }
2204
2205 //-----------------------------------------------------------------------------
2206
2207 /*
2208 As with setColBounds, just changing the bounds should not invalidate the
2209 current rim vectors.
2210 */
2211
2212 void OGSI::setRowBounds(int i, double lower, double upper)
2213 {
2214 /*
2215 Free only the row and column solution, keep the cached structural vectors.
2216 */
2217 freeCachedData(OGSI::KEEPCACHED_PROBLEM);
2218 /*
2219 Figure out the correct row type for glpk and push the change down into the
2220 solver. 1-based addressing.
2221 */
2222 double inf = getInfinity();
2223 int type;
2224
2225 if (lower == upper) {
2226 type = LPX_FX;
2227 } else if (lower > -inf && upper < inf) {
2228 type = LPX_DB;
2229 } else if (lower > -inf) {
2230 type = LPX_LO;
2231 } else if (upper < inf) {
2232 type = LPX_UP;
2233 } else {
2234 type = LPX_FR;
2235 }
2236
2237 lpx_set_row_bnds(lp_, i + 1, type, lower, upper);
2238 /*
2239 Update cached vectors, if they exist.
2240 */
2241 if (rowlower_) {
2242 rowlower_[i] = lower;
2243 }
2244 if (rowupper_) {
2245 rowupper_[i] = upper;
2246 }
2247
2248 return;
2249 }
2250
2251 //-----------------------------------------------------------------------------
2252
2253 void OGSI::setRowType(int elementIndex, char sense, double rightHandSide,
2254 double range)
2255 {
2256 // Could be in OsiSolverInterfaceImpl.
2257 double lower = 0.0;
2258 double upper = 0.0;
2259 convertSenseToBound(sense, rightHandSide, range, lower, upper);
2260 setRowBounds(elementIndex, lower, upper);
2261 }
2262
2263 //-----------------------------------------------------------------------------
2264
2265 void OGSI::setRowSetBounds(const int *indexFirst,
2266 const int *indexLast,
2267 const double *boundList)
2268 {
2269 // Could be in OsiSolverInterface (should'nt be implemeted at here).
2270 OsiSolverInterface::setRowSetBounds(indexFirst, indexLast, boundList);
2271 }
2272
2273 //-----------------------------------------------------------------------------
2274
2275 void OGSI::setRowSetTypes(const int *indexFirst,
2276 const int *indexLast,
2277 const char *senseList,
2278 const double *rhsList,
2279 const double *rangeList)
2280 {
2281 // Could be in OsiSolverInterface (should'nt be implemeted at here).
2282 OsiSolverInterface::setRowSetTypes(indexFirst, indexLast, senseList, rhsList, rangeList);
2283 }
2284
2285 //#############################################################################
2286
2287 void OGSI::setContinuous(int index)
2288 {
2289 LPX *model = getMutableModelPtr();
2290 freeCachedData(OGSI::FREECACHED_COLUMN);
2291 lpx_set_col_kind(model, index + 1, LPX_CV);
2292 }
2293
2294 //-----------------------------------------------------------------------------
2295
2296 void OGSI::setInteger(int index)
2297
2298 {
2299 LPX *model = getMutableModelPtr();
2300 freeCachedData(OGSI::FREECACHED_COLUMN);
2301 lpx_set_col_kind(model, index + 1, LPX_IV);
2302 /*
2303 Temporary hack to correct upper bounds on general integer variables.
2304 CoinMpsIO insists on forcing a bound of 1e30 for general integer variables
2305 with no upper bound. This causes several cut generators (MIR, MIR2) to fail.
2306 Put the bound back to infinity.
2307
2308 -- lh, 070530 --
2309
2310 double uj = getColUpper()[index] ;
2311 if (uj >= 1e30)
2312 { setColUpper(index,getInfinity()) ; }
2313 */
2314 return;
2315 }
2316
2317 //-----------------------------------------------------------------------------
2318
2319 void OGSI::setContinuous(const int *indices, int len)
2320 {
2321 // Could be in OsiSolverInterfaceImpl.
2322 int i;
2323 for (i = 0; i < len; i++) {
2324 setContinuous(indices[i]);
2325 }
2326 }
2327
2328 //-----------------------------------------------------------------------------
2329
2330 void OGSI::setInteger(const int *indices, int len)
2331 {
2332 // Could be in OsiSolverInterfaceImpl.
2333 int i;
2334 for (i = 0; i < len; i++) {
2335 setInteger(indices[i]);
2336 }
2337 }
2338
2339 //#############################################################################
2340
2341 /*
2342 Opt for the natural sense (minimisation) unless the user is clear that
2343 maximisation is what's desired.
2344 */
2345 void OGSI::setObjSense(double s)
2346
2347 {
2348 freeCachedData(OGSI::FREECACHED_RESULTS);
2349
2350 if (s <= -1.0) {
2351 lpx_set_obj_dir(lp_, LPX_MAX);
2352 } else {
2353 lpx_set_obj_dir(lp_, LPX_MIN);
2354 }
2355
2356 return;
2357 }
2358
2359 //-----------------------------------------------------------------------------
2360
2361 void OGSI::setColSolution(const double *cs)
2362 {
2363 // You probably don't want to use this function. You probably want
2364 // setWarmStart instead.
2365 // This implementation changes the cached information,
2366 // BUT DOES NOT TELL GLPK about the changes. In that sense, it's not
2367 // really useful. It is added to conform to current OSI expectations.
2368
2369 // Other results (such as row prices) might not make sense with this
2370 // new solution, but we can't free all the results we have, since the
2371 // row prices may have already been set with setRowPrice.
2372 if (cs == 0)
2373 delete[] colsol_;
2374 else {
2375 int nc = getNumCols();
2376
2377 if (colsol_ == 0)
2378 colsol_ = new double[nc];
2379
2380 // Copy in new col solution.
2381 CoinDisjointCopyN(cs, nc, colsol_);
2382 }
2383 }
2384
2385 //-----------------------------------------------------------------------------
2386
2387 void OGSI::setRowPrice(const double *rs)
2388 {
2389 // You probably don't want to use this function. You probably want
2390 // setWarmStart instead.
2391 // This implementation changes the cached information,
2392 // BUT DOES NOT TELL GLPK about the changes. In that sense, it's not
2393 // really useful. It is added to conform to current OSI expectations.
2394
2395 // Other results (such as column solutions) might not make sense with this
2396 // new solution, but we can't free all the results we have, since the
2397 // column solutions may have already been set with setColSolution.
2398 if (rs == 0)
2399 delete[] rowsol_;
2400 else {
2401 int nr = getNumRows();
2402
2403 if (rowsol_ == 0)
2404 rowsol_ = new double[nr];
2405
2406 // Copy in new col solution.
2407 CoinDisjointCopyN(rs, nr, rowsol_);
2408 }
2409 }
2410
2411 //#############################################################################
2412 // Problem modifying methods (matrix)
2413 //#############################################################################
2414
2415 void OGSI::addCol(const CoinPackedVectorBase &vec,
2416 const double collb, const double colub, const double obj)
2417 {
2418 // Note: GLPK expects only non-zero coefficients will be given in
2419 // lpx_set_mat_col and will abort if there are any zeros. So any
2420 // zeros must be removed prior to calling lpx_set_mat_col.
2421 LPX *model = getMutableModelPtr();
2422 freeCachedData(OGSI::KEEPCACHED_ROW);
2423
2424 lpx_add_cols(model, 1);
2425 int numcols = getNumCols();
2426 setColBounds(numcols - 1, collb, colub);
2427 setObjCoeff(numcols - 1, obj);
2428 int i;
2429 // For GLPK, we don't want the arrays to start at 0
2430 // We also need to weed out any 0.0 coefficients
2431 const int *indices = vec.getIndices();
2432 const double *elements = vec.getElements();
2433 int numrows = getNumRows();
2434
2435 int *indices_adj = new int[1 + vec.getNumElements()];
2436 double *elements_adj = new double[1 + vec.getNumElements()];
2437
2438 int count = 0;
2439 for (i = 0; i < vec.getNumElements(); i++) {
2440 if (elements[i] != 0.0) {
2441 if (indices[i] + 1 > numrows) {
2442 lpx_add_rows(model, indices[i] + 1 - numrows);
2443 numrows = indices[i] + 1;
2444 // ??? could do this more efficiently with a single call based on the max
2445 }
2446 count++;
2447 // GLPK arrays start at 1
2448 indices_adj[count] = indices[i] + 1;
2449 elements_adj[count] = elements[i];
2450 }
2451 }
2452 lpx_set_mat_col(model, numcols, count, indices_adj, elements_adj);
2453 delete[] indices_adj;
2454 delete[] elements_adj;
2455
2456 #if OGSI_TRACK_FRESH > 2
2457 std::cout
2458 << "OGSI(" << std::hex << this << std::dec
2459 << ")::addCol: new column." << std::endl;
2460 #endif
2461 }
2462
2463 //-----------------------------------------------------------------------------
2464
2465 void OGSI::addCols(const int numcols,
2466 const CoinPackedVectorBase *const *cols,
2467 const double *collb, const double *colub,
2468 const double *obj)
2469 {
2470 // ??? We could do this more efficiently now
2471 // Could be in OsiSolverInterfaceImpl.
2472 int i;
2473 for (i = 0; i < numcols; ++i)
2474 addCol(*(cols[i]), collb[i], colub[i], obj[i]);
2475 }
2476
2477 //-----------------------------------------------------------------------------
2478
2479 void OGSI::deleteCols(const int num, const int *columnIndices)
2480 {
2481 int *columnIndicesPlus1 = new int[num + 1];
2482 LPX *model = getMutableModelPtr();
2483 freeCachedData(OGSI::KEEPCACHED_ROW);
2484
2485 for (int i = 0; i < num; i++) {
2486 columnIndicesPlus1[i + 1] = columnIndices[i] + 1;
2487 deleteColNames(columnIndices[i], 1);
2488 }
2489 lpx_del_cols(model, num, columnIndicesPlus1);
2490 delete[] columnIndicesPlus1;
2491
2492 #if OGSI_TRACK_FRESH > 0
2493 std::cout
2494 << "OGSI(" << std::hex << this << std::dec
2495 << ")::deleteCols: deleted " << num << "columns." << std::endl;
2496 #endif
2497 }
2498
2499 //-----------------------------------------------------------------------------
2500
2501 void OGSI::addRow(const CoinPackedVectorBase &vec,
2502 const double rowlb, const double rowub)
2503 {
2504 // Note: GLPK expects only non-zero coefficients will be given in
2505 // lpx_set_mat_row and will abort if there are any zeros. So any
2506 // zeros must be removed prior to calling lpx_set_mat_row.
2507
2508 LPX *model = getMutableModelPtr();
2509 freeCachedData(OGSI::KEEPCACHED_COLUMN);
2510
2511 lpx_add_rows(model, 1);
2512 int numrows = getNumRows();
2513 setRowBounds(numrows - 1, rowlb, rowub);
2514 int i;
2515 const int *indices = vec.getIndices();
2516 const double *elements = vec.getElements();
2517 int numcols = getNumCols();
2518
2519 // For GLPK, we don't want the arrays to start at 0
2520 // Also, we need to weed out any 0.0 elements
2521 int *indices_adj = new int[1 + vec.getNumElements()];
2522 double *elements_adj = new double[1 + vec.getNumElements()];
2523
2524 int count = 0;
2525 for (i = 0; i < vec.getNumElements(); i++) {
2526 if (elements[i] != 0.0) {
2527 if (indices[i] + 1 > numcols) {
2528 // ??? Could do this more efficiently with a single call
2529 lpx_add_cols(model, indices[i] + 1 - numcols);
2530 numcols = indices[i] + 1;
2531 }
2532 count++;
2533 elements_adj[count] = elements[i];
2534 indices_adj[count] = indices[i] + 1;
2535 }
2536 }
2537 lpx_set_mat_row(model, numrows, count, indices_adj, elements_adj);
2538 delete[] indices_adj;
2539 delete[] elements_adj;
2540
2541 #if OGSI_TRACK_FRESH > 0
2542 std::cout
2543 << "OGSI(" << std::hex << this << std::dec
2544 << ")::addRow: new row." << std::endl;
2545 #endif
2546 }
2547
2548 //-----------------------------------------------------------------------------
2549
2550 void OGSI::addRow(const CoinPackedVectorBase &vec,
2551 const char rowsen, const double rowrhs,
2552 const double rowrng)
2553 {
2554 // Could be in OsiSolverInterfaceImpl.
2555 double lb = 0.0;
2556 double ub = 0.0;
2557 convertSenseToBound(rowsen, rowrhs, rowrng, lb, ub);
2558 addRow(vec, lb, ub);
2559 }
2560
2561 //-----------------------------------------------------------------------------
2562
2563 void OGSI::addRows(const int numrows,
2564 const CoinPackedVectorBase *const *rows,
2565 const double *rowlb, const double *rowub)
2566 {
2567 // ??? Could do this more efficiently now
2568 // Could be in OsiSolverInterfaceImpl.
2569 int i;
2570 for (i = 0; i < numrows; ++i)
2571 addRow(*(rows[i]), rowlb[i], rowub[i]);
2572 }
2573
2574 //-----------------------------------------------------------------------------
2575
2576 void OGSI::addRows(const int numrows,
2577 const CoinPackedVectorBase *const *rows,
2578 const char *rowsen, const double *rowrhs,
2579 const double *rowrng)
2580 {
2581 // Could be in OsiSolverInterfaceImpl.
2582 int i;
2583 for (i = 0; i < numrows; ++i)
2584 addRow(*(rows[i]), rowsen[i], rowrhs[i], rowrng[i]);
2585 }
2586
2587 //-----------------------------------------------------------------------------
2588
2589 /*
2590 There's an expectation that a valid basis will be maintained across row
2591 deletions. Fortunately, glpk will do this automagically as long as we play
2592 by the rules and delete only slack constraints. If we delete a constraint
2593 with a nonbasic slack, we're in trouble.
2594 */
2595 void OGSI::deleteRows(const int num, const int *osiIndices)
2596
2597 {
2598 int *glpkIndices = new int[num + 1];
2599 int i, ndx;
2600 /*
2601 Arguably, column results remain valid across row deletion.
2602 */
2603 freeCachedData(OGSI::KEEPCACHED_COLUMN);
2604 /*
2605 Glpk uses 1-based indexing, so convert the array of indices. While we're
2606 doing that, delete the row names.
2607 */
2608 for (ndx = 0; ndx < num; ndx++) {
2609 glpkIndices[ndx + 1] = osiIndices[ndx] + 1;
2610 deleteRowNames(osiIndices[ndx], 1);
2611 }
2612 /*
2613 See if we're about to do damage. If we delete a row with a nonbasic slack,
2614 we'll have an excess of basic variables.
2615 */
2616 int notBasic = 0;
2617 for (ndx = 1; ndx <= num; ndx++) {
2618 i = glpkIndices[ndx];
2619 int stati = lpx_get_row_stat(lp_, i);
2620 if (stati != LPX_BS) {
2621 notBasic++;
2622 }
2623 }
2624 if (notBasic) {
2625 #if OGSI_VERBOSITY > 1
2626 std::cout
2627 << "OGSI(" << std::hex << this << std::dec
2628 << ")::deleteRows: deleting " << notBasic << " tight constraints; "
2629 << "basis is no longer valid." << std::endl;
2630 #endif
2631 }
2632 /*
2633 Tell glpk to delete the rows.
2634 */
2635 lpx_del_rows(lp_, num, glpkIndices);
2636
2637 delete[] glpkIndices;
2638
2639 #if OGSI_TRACK_FRESH > 0
2640 std::cout
2641 << "OGSI(" << std::hex << this << std::dec
2642 << ")::deleteRows: deleted " << num << " rows." << std::endl;
2643 #endif
2644
2645 return;
2646 }
2647
2648 //#############################################################################
2649 // Methods to input a problem
2650 //#############################################################################
2651
2652 void OGSI::loadProblem(const CoinPackedMatrix &matrix,
2653 const double *collb_parm, const double *colub_parm,
2654 const double *obj_parm,
2655 const double *rowlb_parm, const double *rowub_parm)
2656
2657 {
2658 #if OGSI_TRACK_FRESH > 0
2659 std::cout
2660 << "OGSI(" << std::hex << this << std::dec << ")::loadProblem."
2661 << std::endl;
2662 #endif
2663 /*
2664 There's always an existing LPX object. If it's empty, we can simply load in
2665 the new data. If it's non-empty, easiest to delete it and start afresh. When
2666 we do this, we need to reload parameters. For hints, it's easiest to grab
2667 from the existing LPX structure.
2668
2669 In any event, get rid of cached data in the OsiGlpk object.
2670 */
2671 if (lpx_get_num_cols(lp_) != 0 || lpx_get_num_rows(lp_) != 0) {
2672 int presolVal = lpx_get_int_parm(lp_, LPX_K_PRESOL);
2673 int usedualVal = lpx_get_int_parm(lp_, LPX_K_DUAL);
2674 int scaleVal = lpx_get_int_parm(lp_, LPX_K_SCALE);
2675 int logVal = lpx_get_int_parm(lp_, LPX_K_MSGLEV);
2676 #if OGSI_TRACK_FRESH > 0
2677 std::cout
2678 << " emptying LPX(" << std::hex << lp_ << std::dec << "), "
2679 #endif
2680 lpx_delete_prob(lp_);
2681 lp_ = lpx_create_prob();
2682 assert(lp_);
2683 #if OGSI_TRACK_FRESH > 0
2684 std::cout
2685 << "loading LPX(" << std::hex << lp_ << std::dec << ")."
2686 << std::endl;
2687 #endif
2688 lpx_set_class(lp_, LPX_MIP);
2689 lpx_set_int_parm(lp_, LPX_K_ITLIM, maxIteration_);
2690 if (getObjSense() == 1) // minimization
2691 {
2692 lpx_set_real_parm(lp_, LPX_K_OBJUL, dualObjectiveLimit_);
2693 lpx_set_real_parm(lp_, LPX_K_OBJLL, primalObjectiveLimit_);
2694 } else // maximization
2695 {
2696 lpx_set_real_parm(lp_, LPX_K_OBJLL, dualObjectiveLimit_);
2697 lpx_set_real_parm(lp_, LPX_K_OBJUL, primalObjectiveLimit_);
2698 }
2699 lpx_set_real_parm(lp_, LPX_K_TOLDJ, dualTolerance_);
2700 lpx_set_real_parm(lp_, LPX_K_TOLBND, primalTolerance_);
2701 lpx_set_obj_coef(lp_, 0, objOffset_);
2702 lpx_set_prob_name(lp_, const_cast< char * >(probName_.c_str()));
2703 lpx_set_int_parm(lp_, LPX_K_PRESOL, presolVal);
2704 lpx_set_int_parm(lp_, LPX_K_DUAL, usedualVal);
2705 lpx_set_int_parm(lp_, LPX_K_SCALE, scaleVal);
2706 lpx_set_int_parm(lp_, LPX_K_MSGLEV, logVal);
2707 messageHandler()->setLogLevel(logVal);
2708 }
2709
2710 freeCachedData(OGSI::KEEPCACHED_NONE);
2711
2712 double inf = getInfinity();
2713 int m = matrix.getNumRows();
2714 int n = matrix.getNumCols();
2715 int i, j;
2716 double *zeroVec, *infVec, *negInfVec;
2717 const double *collb, *colub, *obj, *rowlb, *rowub;
2718 /*
2719 Check if we need default values for any of the vectors, and set up
2720 accordingly.
2721 */
2722 if (collb_parm == 0 || obj_parm == 0) {
2723 zeroVec = new double[n];
2724 CoinZeroN(zeroVec, n);
2725 } else {
2726 zeroVec = 0;
2727 }
2728
2729 if (colub_parm == 0 || rowub_parm == 0) {
2730 if (colub_parm == 0 && rowub_parm == 0) {
2731 j = CoinMax(m, n);
2732 } else if (colub_parm == 0) {
2733 j = n;
2734 } else {
2735 j = m;
2736 }
2737 infVec = new double[j];
2738 CoinFillN(infVec, j, inf);
2739 } else {
2740 infVec = 0;
2741 }
2742
2743 if (rowlb_parm == 0) {
2744 negInfVec = new double[m];
2745 CoinFillN(negInfVec, m, -inf);
2746 } else {
2747 negInfVec = 0;
2748 }
2749
2750 if (collb_parm == 0) {
2751 collb = zeroVec;
2752 } else {
2753 collb = collb_parm;
2754 }
2755
2756 if (colub_parm == 0) {
2757 colub = infVec;
2758 } else {
2759 colub = colub_parm;
2760 }
2761
2762 if (obj_parm == 0) {
2763 obj = zeroVec;
2764 } else {
2765 obj = obj_parm;
2766 }
2767
2768 if (rowlb_parm == 0) {
2769 rowlb = negInfVec;
2770 } else {
2771 rowlb = rowlb_parm;
2772 }
2773
2774 if (rowub_parm == 0) {
2775 rowub = infVec;
2776 } else {
2777 rowub = rowub_parm;
2778 }
2779 /*
2780 The actual load.
2781 */
2782 if (matrix.isColOrdered()) {
2783 for (j = 0; j < n; j++) {
2784 const CoinShallowPackedVector reqdBySunCC = matrix.getVector(j);
2785 addCol(reqdBySunCC, collb[j], colub[j], obj[j]);
2786 }
2787 // Make sure there are enough rows
2788 if (m > getNumRows()) {
2789 lpx_add_rows(lp_, m - getNumRows());
2790 }
2791 for (i = 0; i < m; i++) {
2792 setRowBounds(i, rowlb[i], rowub[i]);
2793 }
2794 } else {
2795 for (i = 0; i < m; i++) {
2796 const CoinShallowPackedVector reqdBySunCC = matrix.getVector(i);
2797 addRow(reqdBySunCC, rowlb[i], rowub[i]);
2798 }
2799 // Make sure there are enough columns
2800 if (n > getNumCols()) {
2801 lpx_add_cols(lp_, n - getNumCols());
2802 }
2803 for (j = 0; j < n; j++) {
2804 setColBounds(j, collb[j], colub[j]);
2805 setObjCoeff(j, obj[j]);
2806 }
2807 }
2808 /*
2809 Cleanup.
2810 */
2811 if (zeroVec)
2812 delete[] zeroVec;
2813 if (infVec)
2814 delete[] infVec;
2815 if (negInfVec)
2816 delete[] negInfVec;
2817
2818 return;
2819 }
2820
2821 //-----------------------------------------------------------------------------
2822
2823 void OGSI::assignProblem(CoinPackedMatrix *&matrix,
2824 double *&collb, double *&colub,
2825 double *&obj,
2826 double *&rowlb, double *&rowub)
2827 {
2828 // Could be in OsiSolverInterfaceImpl.
2829 loadProblem(*matrix, collb, colub, obj, rowlb, rowub);
2830 delete matrix;
2831 matrix = NULL;
2832 delete[] collb;
2833 collb = NULL;
2834 delete[] colub;
2835 colub = NULL;
2836 delete[] obj;
2837 obj = NULL;
2838 delete[] rowlb;
2839 rowlb = NULL;
2840 delete[] rowub;
2841 rowub = NULL;
2842 }
2843
2844 //-----------------------------------------------------------------------------
2845
2846 void OGSI::loadProblem(const CoinPackedMatrix &matrix,
2847 const double *collb, const double *colub,
2848 const double *obj,
2849 const char *rowsen, const double *rowrhs,
2850 const double *rowrng)
2851 {
2852 // Could be in OsiSolverInterfaceImpl.
2853 int numrows = matrix.getNumRows();
2854 double *rowlb = new double[numrows];
2855 double *rowub = new double[numrows];
2856
2857 int i;
2858 for (i = numrows - 1; i >= 0; --i) {
2859 convertSenseToBound(rowsen ? rowsen[i] : 'G',
2860 rowrhs ? rowrhs[i] : 0.0,
2861 rowrng ? rowrng[i] : 0.0,
2862 rowlb[i], rowub[i]);
2863 }
2864
2865 loadProblem(matrix, collb, colub, obj, rowlb, rowub);
2866 delete[] rowlb;
2867 delete[] rowub;
2868 }
2869
2870 //-----------------------------------------------------------------------------
2871
2872 void OGSI::assignProblem(CoinPackedMatrix *&matrix,
2873 double *&collb, double *&colub,
2874 double *&obj,
2875 char *&rowsen, double *&rowrhs,
2876 double *&rowrng)
2877 {
2878 // Could be in OsiSolverInterfaceImpl.
2879 loadProblem(*matrix, collb, colub, obj, rowsen, rowrhs, rowrng);
2880 delete matrix;
2881 matrix = NULL;
2882 delete[] collb;
2883 collb = NULL;
2884 delete[] colub;
2885 colub = NULL;
2886 delete[] obj;
2887 obj = NULL;
2888 delete[] rowsen;
2889 rowsen = NULL;
2890 delete[] rowrhs;
2891 rowrhs = NULL;
2892 delete[] rowrng;
2893 rowrng = NULL;
2894 }
2895 //-----------------------------------------------------------------------------
2896
2897 void OGSI::loadProblem(const int numcols, const int numrows,
2898 const CoinBigIndex *start, const int *index,
2899 const double *value,
2900 const double *collb, const double *colub,
2901 const double *obj,
2902 const double *rowlb, const double *rowub)
2903 {
2904 freeCachedData(OGSI::KEEPCACHED_NONE);
2905 LPX *model = getMutableModelPtr();
2906 double inf = getInfinity();
2907
2908 // Can't send 0 to lpx_add_xxx
2909 if (numcols > 0)
2910 lpx_add_cols(model, numcols);
2911 if (numrows > 0)
2912 lpx_add_rows(model, numrows);
2913
2914 // How many elements? Column-major, so indices of start are columns
2915 CoinBigIndex numelem = start[numcols];
2916 // int numelem = 0;
2917 // while ( index[numelem] != 0 )
2918 // numelem++;
2919 int *index_adj = new int[1 + numelem];
2920 double *value_adj = new double[1 + numelem];
2921
2922 int i;
2923 for (i = 1; i <= numelem; i++) {
2924 index_adj[i] = index[i - 1] + 1;
2925 value_adj[i] = value[i - 1];
2926 }
2927
2928 for (i = 0; i < numcols; i++) {
2929 setColBounds(i, collb ? collb[i] : 0.0,
2930 colub ? colub[i] : inf);
2931 lpx_set_mat_col(model, i + 1, static_cast< int >(start[i + 1] - start[i]),
2932 &(index_adj[start[i]]), &(value_adj[start[i]]));
2933 setObjCoeff(i, obj ? obj[i] : 0.0);
2934 }
2935 int j;
2936 for (j = 0; j < numrows; j++) {
2937 setRowBounds(j, rowlb ? rowlb[j] : -inf, rowub ? rowub[j] : inf);
2938 }
2939
2940 delete[] index_adj;
2941 delete[] value_adj;
2942 }
2943 //-----------------------------------------------------------------------------
2944
2945 void OGSI::loadProblem(const int numcols, const int numrows,
2946 const CoinBigIndex *start, const int *index,
2947 const double *value,
2948 const double *collb, const double *colub,
2949 const double *obj,
2950 const char *rowsen, const double *rowrhs,
2951 const double *rowrng)
2952 {
2953 double *rowlb = new double[numrows];
2954 double *rowub = new double[numrows];
2955 for (int i = numrows - 1; i >= 0; --i) {
2956 convertSenseToBound(rowsen != NULL ? rowsen[i] : 'G', rowrhs != NULL ? rowrhs[i] : 0.0, rowrng != NULL ? rowrng[i] : 0.0, rowlb[i], rowub[i]);
2957 }
2958
2959 loadProblem(numcols, numrows, start, index, value, collb, colub, obj,
2960 rowlb, rowub);
2961
2962 delete[] rowlb;
2963 delete[] rowub;
2964 }
2965
2966 //-----------------------------------------------------------------------------
2967 // Read mps files
2968 //-----------------------------------------------------------------------------
2969
2970 /*
2971 Call OSI::readMps, which will parse the mps file and call
2972 OsiGlpk::loadProblem.
2973 */
2974 int OGSI::readMps(const char *filename,
2975 const char *extension)
2976 {
2977
2978 int retval = OsiSolverInterface::readMps(filename, extension);
2979
2980 return (retval);
2981 }
2982
2983 //-----------------------------------------------------------------------------
2984 // Write mps files
2985 //-----------------------------------------------------------------------------
2986
2987 void OGSI::writeMps(const char *filename,
2988 const char *extension,
2989 double /*objSense*/) const
2990 {
2991 // Could be in OsiSolverInterfaceImpl.
2992 #if 1
2993 std::string f(filename);
2994 std::string e(extension);
2995 std::string fullname = f + "." + e;
2996 lpx_write_mps(getMutableModelPtr(), const_cast< char * >(fullname.c_str()));
2997 #else
2998 // Fall back on native MPS writer.
2999 // These few lines of code haven't been tested. 2004/10/15
3000 std::string f(filename);
3001 std::string e(extension);
3002 std::string fullname = f + "." + e;
3003
3004 OsiSolverInterface::writeMpsNative(fullname.c_str(),
3005 NULL, NULL, 0, 2, objSense);
3006 #endif
3007 }
3008
3009 //############################################################################
3010 // GLPK-specific methods
3011 //############################################################################
3012
3013 // Get a pointer to the instance
3014 LPX *OGSI::getModelPtr()
3015 {
3016 freeCachedResults();
3017 return lp_;
3018 }
3019
3020 //#############################################################################
3021 // Constructors, destructors clone and assignment
3022 //#############################################################################
3023
3024 //-----------------------------------------------------------------------------
3025 // Default Constructor
3026 //-----------------------------------------------------------------------------
3027
3028 OGSI::OsiGlpkSolverInterface()
3029 : OsiSolverInterface()
3030 {
3031 gutsOfConstructor();
3032 incrementInstanceCounter();
3033
3034 #if OGSI_TRACK_SOLVERS > 0
3035 std::cout
3036 << "OGSI(" << std::hex << this << std::dec
3037 << "): default constructor." << std::endl;
3038 #endif
3039 }
3040
3041 //-----------------------------------------------------------------------------
3042 // Clone
3043 //-----------------------------------------------------------------------------
3044
3045 OsiSolverInterface *OGSI::clone(bool copyData) const
3046 {
3047 #if OGSI_TRACK_SOLVERS > 0
3048 std::cout
3049 << "OGSI(" << std::hex << this << std::dec << "): cloning." << std::endl;
3050 #endif
3051 if (copyData)
3052 return (new OsiGlpkSolverInterface(*this));
3053 else
3054 return (new OsiGlpkSolverInterface());
3055 }
3056
3057 //-----------------------------------------------------------------------------
3058 // Copy constructor
3059 //-----------------------------------------------------------------------------
3060
3061 OGSI::OsiGlpkSolverInterface(const OsiGlpkSolverInterface &source)
3062 : OsiSolverInterface(source)
3063 {
3064 gutsOfConstructor();
3065 gutsOfCopy(source);
3066 incrementInstanceCounter();
3067
3068 #if OGSI_TRACK_SOLVERS > 0
3069 std::cout
3070 << "OGSI(" << std::hex << this << "): copy from "
3071 << &source << std::dec << "." << std::endl;
3072 #endif
3073 }
3074
3075 //-----------------------------------------------------------------------------
3076 // Destructor
3077 //-----------------------------------------------------------------------------
3078
3079 OGSI::~OsiGlpkSolverInterface()
3080 {
3081 gutsOfDestructor();
3082 decrementInstanceCounter();
3083
3084 #if OGSI_TRACK_SOLVERS > 0
3085 std::cout
3086 << "OGSI(" << std::hex << this << std::dec
3087 << "): destructor." << std::endl;
3088 #endif
3089 }
3090
3091 // Resets
3092 // ??? look over this carefully to be sure it is correct
3093 void OGSI::reset()
3094 {
3095 setInitialData(); // this is from the base class OsiSolverInterface
3096 gutsOfDestructor();
3097 gutsOfConstructor();
3098
3099 #if OGSI_TRACK_SOLVERS > 0
3100 std::cout
3101 << "OGSI(" << std::hex << this << std::dec
3102 << "): reset." << std::endl;
3103 #endif
3104
3105 return;
3106 }
3107
3108 //-----------------------------------------------------------------------------
3109 // Assignment operator
3110 //-----------------------------------------------------------------------------
3111
3112 OsiGlpkSolverInterface &OGSI::operator=(const OsiGlpkSolverInterface &rhs)
3113 {
3114 if (this != &rhs) {
3115 OsiSolverInterface::operator=(rhs);
3116 gutsOfDestructor();
3117 gutsOfConstructor();
3118 if (rhs.lp_ != NULL)
3119 gutsOfCopy(rhs);
3120 }
3121
3122 #if OGSI_TRACK_SOLVERS > 0
3123 std::cout
3124 << "OGSI(" << std::hex << this << "): assign from "
3125 << &rhs << std::dec << "." << std::endl;
3126 #endif
3127
3128 return *this;
3129 }
3130
3131 //#############################################################################
3132 // Applying cuts
3133 //#############################################################################
3134
3135 void OGSI::applyColCut(const OsiColCut &cc)
3136 {
3137 // Could be in OsiSolverInterfaceImpl.
3138 const double *colLb = getColLower();
3139 const double *colUb = getColUpper();
3140 const CoinPackedVector &lbs = cc.lbs();
3141 const CoinPackedVector &ubs = cc.ubs();
3142 int i;
3143 #if 0
3144 // replaced (JJF) because colLb and colUb are invalidated by sets
3145 for( i = 0; i < lbs.getNumElements(); ++i )
3146 if( lbs.getElements()[i] > colLb[lbs.getIndices()[i]] )
3147 setColLower( lbs.getIndices()[i], lbs.getElements()[i] );
3148 for( i = 0; i < ubs.getNumElements(); ++i )
3149 if( ubs.getElements()[i] < colUb[ubs.getIndices()[i]] )
3150 setColUpper( ubs.getIndices()[i], ubs.getElements()[i] );
3151 #else
3152 double inf = getInfinity();
3153
3154 int type;
3155 // lower bounds
3156 for (i = 0; i < lbs.getNumElements(); ++i) {
3157 int column = lbs.getIndices()[i];
3158 double lower = lbs.getElements()[i];
3159 double upper = colUb[column];
3160 if (lower > colLb[column]) {
3161 // update cached version as well
3162 collower_[column] = lower;
3163 if (lower == upper)
3164 type = LPX_FX;
3165 else if (lower > -inf && upper < inf)
3166 type = LPX_DB;
3167 else if (lower > -inf)
3168 type = LPX_LO;
3169 else if (upper < inf)
3170 type = LPX_UP;
3171 else
3172 type = LPX_FR;
3173
3174 lpx_set_col_bnds(getMutableModelPtr(), column + 1, type, lower, upper);
3175 }
3176 }
3177 // lower bounds
3178 for (i = 0; i < ubs.getNumElements(); ++i) {
3179 int column = ubs.getIndices()[i];
3180 double upper = ubs.getElements()[i];
3181 double lower = colLb[column];
3182 if (upper < colUb[column]) {
3183 // update cached version as well
3184 colupper_[column] = upper;
3185 if (lower == upper)
3186 type = LPX_FX;
3187 else if (lower > -inf && upper < inf)
3188 type = LPX_DB;
3189 else if (lower > -inf)
3190 type = LPX_LO;
3191 else if (upper < inf)
3192 type = LPX_UP;
3193 else
3194 type = LPX_FR;
3195
3196 lpx_set_col_bnds(getMutableModelPtr(), column + 1, type, lower, upper);
3197 }
3198 }
3199 #endif
3200 }
3201
3202 //-----------------------------------------------------------------------------
3203
3204 void OGSI::applyRowCut(const OsiRowCut &rowCut)
3205 {
3206 // Could be in OsiSolverInterfaceImpl.
3207 addRow(rowCut.row(), rowCut.lb(), rowCut.ub());
3208 }
3209
3210 //#############################################################################
3211 // Private methods (non-static and static) and static data
3212 //#############################################################################
3213
3214 LPX *OGSI::getMutableModelPtr(void) const
3215 {
3216 return lp_;
3217 }
3218
3219 /*
3220 This routine must work even if there's no problem loaded in the solver.
3221 */
3222
3223 void OGSI::gutsOfCopy(const OsiGlpkSolverInterface &source)
3224
3225 {
3226 LPX *srclpx = source.lp_;
3227 LPX *lpx = lp_;
3228 double dblParam;
3229 int intParam;
3230 std::string strParam;
3231 /*
3232 Copy information from the source OSI that a user might change before
3233 loading a problem: objective sense and offset, other OSI parameters. Use
3234 the get/set parameter calls here to hide pushing information into the LPX
3235 object.
3236 */
3237 setObjSense(source.getObjSense());
3238 source.getDblParam(OsiObjOffset, dblParam);
3239 setDblParam(OsiObjOffset, dblParam);
3240
3241 source.getIntParam(OsiNameDiscipline, intParam);
3242 setIntParam(OsiNameDiscipline, intParam);
3243
3244 source.getIntParam(OsiMaxNumIteration, intParam);
3245 setIntParam(OsiMaxNumIteration, intParam);
3246 source.getIntParam(OsiMaxNumIterationHotStart, intParam);
3247 setIntParam(OsiMaxNumIterationHotStart, intParam);
3248
3249 source.getDblParam(OsiPrimalObjectiveLimit, dblParam);
3250 setDblParam(OsiPrimalObjectiveLimit, dblParam);
3251 source.getDblParam(OsiDualObjectiveLimit, dblParam);
3252 setDblParam(OsiDualObjectiveLimit, dblParam);
3253 source.getDblParam(OsiPrimalTolerance, dblParam);
3254 setDblParam(OsiPrimalTolerance, dblParam);
3255 source.getDblParam(OsiDualTolerance, dblParam);
3256 setDblParam(OsiDualTolerance, dblParam);
3257 /*
3258 For hints, we need to be a little more circumspect, so as not to pump out a
3259 bunch of warnings. Pull parameters from the source LPX object and load into
3260 the copy. The actual values of the hint parameters (sense & strength) are
3261 held up on the parent OSI object, so we don't need to worry about copying
3262 them.
3263 */
3264 intParam = lpx_get_int_parm(srclpx, LPX_K_PRESOL);
3265 lpx_set_int_parm(lpx, LPX_K_PRESOL, intParam);
3266 intParam = lpx_get_int_parm(srclpx, LPX_K_DUAL);
3267 lpx_set_int_parm(lpx, LPX_K_DUAL, intParam);
3268 intParam = lpx_get_int_parm(srclpx, LPX_K_SCALE);
3269 lpx_set_int_parm(lpx, LPX_K_SCALE, intParam);
3270 /*
3271 Printing is a bit more complicated. Pull the parameter and set the log
3272 level in the message handler and set the print parameter in glpk.
3273 */
3274 intParam = lpx_get_int_parm(srclpx, LPX_K_MSGLEV);
3275 lpx_set_int_parm(lpx, LPX_K_MSGLEV, intParam);
3276 messageHandler()->setLogLevel(intParam);
3277
3278 #ifdef LPX_K_USECUTS
3279 intParam = lpx_get_int_parm(lp_, LPX_K_USECUTS);
3280 lpx_set_int_parm(lp_, LPX_K_USECUTS, intParam);
3281 #endif
3282
3283 /*
3284 Now --- do we have a problem loaded? If not, we're done.
3285 */
3286 int n = source.getNumCols();
3287 int m = source.getNumRows();
3288 assert(m >= 0 && n >= 0);
3289 if (m == 0 && n == 0) {
3290 #if OGSI_TRACK_SOLVERS > 0
3291 std::cout
3292 << " no problem loaded." << std::endl;
3293 #endif
3294 return;
3295 }
3296 /*
3297 We have rows and/or columns, so we need to transfer the problem. Do a few
3298 parameters and status fields that may have changed if a problem is loaded.
3299 Then pull the problem information and load it into the lpx object for this
3300 OSI. Information on integrality must be copied over separately.
3301 */
3302 source.getStrParam(OsiProbName, strParam);
3303 setStrParam(OsiProbName, strParam);
3304 bbWasLast_ = source.bbWasLast_;
3305 iter_used_ = source.iter_used_;
3306
3307 const double *obj = source.getObjCoefficients();
3308 const CoinPackedMatrix *cols = source.getMatrixByCol();
3309 const double *lb = source.getColLower();
3310 const double *ub = source.getColUpper();
3311 const double *rlb = source.getRowLower();
3312 const double *rub = source.getRowUpper();
3313 loadProblem(*cols, lb, ub, obj, rlb, rub);
3314
3315 int i, j;
3316 for (j = 0; j < n; j++) {
3317 if (source.isInteger(j)) {
3318 setInteger(j);
3319 }
3320 }
3321 /*
3322 Copy the solution information. We need to be a bit careful here. Even though
3323 the source has something loaded as a problem, there's no guarantee that we've
3324 even called glpk, so we can't consult glpk directly for solution values.
3325 */
3326 setColSolution(source.getColSolution());
3327 setRowPrice(source.getRowPrice());
3328 /*
3329 We can, however, consult it directly for variable status: glpk initialises
3330 this information as soon as columns and/or rows are created. Of course, that
3331 applies to the problem we've just created, too. If we're just copying
3332 nonsense, then don't bother. Once we've copied the status into the new lpx
3333 object, do the warm-up.
3334 */
3335 if (lpx_get_status(srclpx) != LPX_UNDEF) {
3336 for (j = 1; j <= n; j++) {
3337 int statj = lpx_get_col_stat(srclpx, j);
3338 lpx_set_col_stat(lpx, j, statj);
3339 }
3340 for (i = 1; i <= m; i++) {
3341 int stati = lpx_get_row_stat(srclpx, i);
3342 lpx_set_row_stat(lpx, i, stati);
3343 }
3344
3345 #ifndef NDEBUG
3346 int retval = lpx_warm_up(lpx);
3347 #endif
3348 #if OGSI_TRACK_SOLVERS > 1
3349 std::cout
3350 << " lpx_warm_up returns " << retval << "." << std::endl;
3351 #endif
3352 assert(retval == LPX_E_OK);
3353 }
3354
3355 return;
3356 }
3357
3358 //-----------------------------------------------------------------------------
3359
3360 void OGSI::gutsOfConstructor()
3361 {
3362 bbWasLast_ = 0;
3363 iter_used_ = 0;
3364 obj_ = NULL;
3365 collower_ = NULL;
3366 colupper_ = NULL;
3367 ctype_ = NULL;
3368 rowsense_ = NULL;
3369 rhs_ = NULL;
3370 rowrange_ = NULL;
3371 rowlower_ = NULL;
3372 rowupper_ = NULL;
3373 colsol_ = NULL;
3374 rowsol_ = NULL;
3375 redcost_ = NULL;
3376 rowact_ = NULL;
3377 matrixByRow_ = NULL;
3378 matrixByCol_ = NULL;
3379
3380 maxIteration_ = COIN_INT_MAX;
3381 hotStartMaxIteration_ = 0;
3382 nameDisc_ = 0;
3383
3384 dualObjectiveLimit_ = getInfinity();
3385 primalObjectiveLimit_ = -getInfinity();
3386 dualTolerance_ = 1.0e-6;
3387 primalTolerance_ = 1.0e-6;
3388 objOffset_ = 0.0;
3389
3390 probName_ = "<none loaded>";
3391
3392 hotStartCStat_ = NULL;
3393 hotStartCStatSize_ = 0;
3394 hotStartRStat_ = NULL;
3395 hotStartRStatSize_ = 0;
3396
3397 isIterationLimitReached_ = false;
3398 isTimeLimitReached_ = false;
3399 isAbandoned_ = false;
3400 isPrimInfeasible_ = false;
3401 isDualInfeasible_ = false;
3402 isObjLowerLimitReached_ = false;
3403 isObjUpperLimitReached_ = false;
3404 isFeasible_ = false;
3405
3406 lp_ = lpx_create_prob();
3407 assert(lp_ != NULL);
3408 // Make all problems MIPs. See note at top of file.
3409 lpx_set_class(lp_, LPX_MIP);
3410
3411 // Push OSI parameters down into LPX object.
3412 lpx_set_int_parm(lp_, LPX_K_ITLIM, maxIteration_);
3413
3414 if (getObjSense() == 1.0) // minimization
3415 {
3416 lpx_set_real_parm(lp_, LPX_K_OBJUL, dualObjectiveLimit_);
3417 lpx_set_real_parm(lp_, LPX_K_OBJLL, primalObjectiveLimit_);
3418 } else // maximization
3419 {
3420 lpx_set_real_parm(lp_, LPX_K_OBJLL, dualObjectiveLimit_);
3421 lpx_set_real_parm(lp_, LPX_K_OBJUL, -primalObjectiveLimit_);
3422 }
3423 lpx_set_real_parm(lp_, LPX_K_TOLDJ, dualTolerance_);
3424 lpx_set_real_parm(lp_, LPX_K_TOLBND, primalTolerance_);
3425
3426 lpx_set_obj_coef(lp_, 0, objOffset_);
3427
3428 lpx_set_prob_name(lp_, const_cast< char * >(probName_.c_str()));
3429
3430 /* Stefan: with the new simplex algorithm in Glpk 4.31, some netlib instances (e.g., dfl001)
3431 take very long or get into a cycle.
3432 Thus, let's try to leave parameters onto their defaults.
3433 */
3434 // lpx_set_int_parm(lp_,LPX_K_PRESOL,0) ;
3435 // lpx_set_int_parm(lp_,LPX_K_DUAL,1) ;
3436 // lpx_set_int_parm(lp_,LPX_K_SCALE,3) ;
3437 /*
3438 Printing is a bit more complicated. Set the log level in the handler and set
3439 the print parameter in glpk.
3440 */
3441 lpx_set_int_parm(lp_, LPX_K_MSGLEV, 1);
3442 messageHandler()->setLogLevel(1);
3443
3444 /*
3445 Enable cuts if they're available. This is a bit of a pain,
3446 as the interface has changed since it was first introduced in 4.9.
3447 LPX_K_USECUTS appears in 4.9; the parameter value
3448 appears to be unused in this version. LPX_C_ALL appears in 4.10.
3449 */
3450 #ifdef LPX_K_USECUTS
3451 #ifdef LPX_C_ALL
3452 lpx_set_int_parm(lp_, LPX_K_USECUTS, LPX_C_ALL);
3453 #else
3454 lpx_set_int_parm(lp_, LPX_K_USECUTS, 0);
3455 #endif
3456 #endif
3457 }
3458
3459 //-----------------------------------------------------------------------------
3460
3461 void OGSI::gutsOfDestructor()
3462 {
3463 if (lp_ != NULL) {
3464 lpx_delete_prob(lp_);
3465 lp_ = NULL;
3466 freeAllMemory();
3467 }
3468 assert(lp_ == NULL);
3469 assert(obj_ == NULL);
3470 assert(collower_ == NULL);
3471 assert(colupper_ == NULL);
3472 assert(ctype_ == NULL);
3473 assert(rowsense_ == NULL);
3474 assert(rhs_ == NULL);
3475 assert(rowrange_ == NULL);
3476 assert(rowlower_ == NULL);
3477 assert(rowupper_ == NULL);
3478 assert(colsol_ == NULL);
3479 assert(rowsol_ == NULL);
3480 assert(redcost_ == NULL);
3481 assert(rowact_ == NULL);
3482 assert(matrixByRow_ == NULL);
3483 assert(matrixByCol_ == NULL);
3484 }
3485
3486 //-----------------------------------------------------------------------------
3487 // free cached vectors
3488 //-----------------------------------------------------------------------------
3489
3490 void OGSI::freeCachedColRim()
3491 {
3492 delete[] ctype_;
3493 delete[] obj_;
3494 delete[] collower_;
3495 delete[] colupper_;
3496 ctype_ = NULL;
3497 obj_ = NULL;
3498 collower_ = NULL;
3499 colupper_ = NULL;
3500 }
3501
3502 //-----------------------------------------------------------------------------
3503
3504 void OGSI::freeCachedRowRim()
3505 {
3506 delete[] rowsense_;
3507 delete[] rhs_;
3508 delete[] rowrange_;
3509 delete[] rowlower_;
3510 delete[] rowupper_;
3511 rowsense_ = NULL;
3512 rhs_ = NULL;
3513 rowrange_ = NULL;
3514 rowlower_ = NULL;
3515 rowupper_ = NULL;
3516 }
3517
3518 //-----------------------------------------------------------------------------
3519
3520 void OGSI::freeCachedMatrix()
3521 {
3522 delete matrixByRow_;
3523 delete matrixByCol_;
3524 matrixByRow_ = NULL;
3525 matrixByCol_ = NULL;
3526 }
3527
3528 //-----------------------------------------------------------------------------
3529
3530 void OGSI::freeCachedResults()
3531 {
3532 iter_used_ = 0;
3533 isAbandoned_ = false;
3534 isIterationLimitReached_ = false;
3535 isTimeLimitReached_ = false;
3536 isPrimInfeasible_ = false;
3537 isDualInfeasible_ = false;
3538 isFeasible_ = false;
3539 delete[] colsol_;
3540 delete[] rowsol_;
3541 delete[] redcost_;
3542 delete[] rowact_;
3543 colsol_ = NULL;
3544 rowsol_ = NULL;
3545 redcost_ = NULL;
3546 rowact_ = NULL;
3547 }
3548
3549 //-----------------------------------------------------------------------------
3550
3551 void OGSI::freeCachedData(int keepCached)
3552 {
3553 if (!(keepCached & OGSI::KEEPCACHED_COLUMN))
3554 freeCachedColRim();
3555 if (!(keepCached & OGSI::KEEPCACHED_ROW))
3556 freeCachedRowRim();
3557 if (!(keepCached & OGSI::KEEPCACHED_MATRIX))
3558 freeCachedMatrix();
3559 if (!(keepCached & OGSI::KEEPCACHED_RESULTS))
3560 freeCachedResults();
3561 }
3562
3563 //-----------------------------------------------------------------------------
3564
3565 void OGSI::freeAllMemory()
3566 {
3567 freeCachedData(OGSI::KEEPCACHED_NONE);
3568 delete[] hotStartCStat_;
3569 delete[] hotStartRStat_;
3570 hotStartCStat_ = NULL;
3571 hotStartCStatSize_ = 0;
3572 hotStartRStat_ = NULL;
3573 hotStartRStatSize_ = 0;
3574 }
3575
3576 //-----------------------------------------------------------------------------
3577
3578 /*!
3579 Set the objective function name.
3580 */
3581 void OGSI::setObjName(std::string name)
3582
3583 {
3584 OsiSolverInterface::setObjName(name);
3585 lpx_set_obj_name(lp_, const_cast< char * >(name.c_str()));
3586 }
3587
3588 /*!
3589 Set a row name. Make sure both glpk and OSI see the same name.
3590 */
3591 void OGSI::setRowName(int ndx, std::string name)
3592
3593 {
3594 int nameDiscipline;
3595 /*
3596 Quietly do nothing if the index is out of bounds.
3597 */
3598 if (ndx < 0 || ndx >= getNumRows()) {
3599 return;
3600 }
3601 /*
3602 Get the name discipline. Quietly do nothing if it's auto.
3603 */
3604 (void)getIntParam(OsiNameDiscipline, nameDiscipline);
3605 if (nameDiscipline == 0) {
3606 return;
3607 }
3608 /*
3609 Set the name in the OSI base, then in the consys structure.
3610 */
3611 OsiSolverInterface::setRowName(ndx, name);
3612 lpx_set_row_name(lp_, ndx + 1, const_cast< char * >(name.c_str()));
3613
3614 return;
3615 }
3616
3617 /*!
3618 Set a column name. Make sure both glpk and OSI see the same name.
3619 */
3620 void OGSI::setColName(int ndx, std::string name)
3621
3622 {
3623 int nameDiscipline;
3624 /*
3625 Quietly do nothing if the index is out of bounds.
3626 */
3627 if (ndx < 0 || ndx >= getNumCols()) {
3628 return;
3629 }
3630 /*
3631 Get the name discipline. Quietly do nothing if it's auto.
3632 */
3633 (void)getIntParam(OsiNameDiscipline, nameDiscipline);
3634 if (nameDiscipline == 0) {
3635 return;
3636 }
3637 /*
3638 Set the name in the OSI base, then in the consys structure.
3639 */
3640 OsiSolverInterface::setColName(ndx, name);
3641 lpx_set_col_name(lp_, ndx + 1, const_cast< char * >(name.c_str()));
3642
3643 return;
3644 }
3645
3646 //-----------------------------------------------------------------------------
3647
3648 unsigned int OsiGlpkSolverInterface::numInstances_ = 0;
3649
3650 void OsiGlpkSolverInterface::decrementInstanceCounter()
3651 {
3652 assert(numInstances_ != 0);
3653 if (--numInstances_ == 0)
3654 glp_free_env();
3655 }
3656
3657 /* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
3658 */