1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_LP_BASE_H
20 #define LEMON_LP_BASE_H
26 #include<lemon/math.h>
28 #include<lemon/error.h>
29 #include<lemon/assert.h>
31 #include<lemon/core.h>
32 #include<lemon/bits/solver_bits.h>
34 #include<lemon/bits/stl_iterators.h>
37 ///\brief The interface of the LP solver interface.
41 ///Common base class for LP and MIP solvers
43 ///Usually this class is not used directly, please use one of the concrete
44 ///implementations of the solver interface.
50 _solver_bits::VarIndex _rows;
51 _solver_bits::VarIndex _cols;
55 ///Possible outcomes of an LP solving procedure
56 enum SolveExitStatus {
57 /// = 0. It means that the problem has been successfully solved: either
58 ///an optimal solution has been found or infeasibility/unboundedness
61 /// = 1. Any other case (including the case when some user specified
62 ///limit has been exceeded).
66 ///Direction of the optimization
74 ///Enum for \c messageLevel() parameter
76 /// No output (default value).
78 /// Error messages only.
89 ///The floating point type used by the solver
91 ///The infinity constant
92 static const Value INF;
93 ///The not a number constant
94 static const Value NaN;
101 ///Refer to a column of the LP.
103 ///This type is used to refer to a column of the LP.
105 ///Its value remains valid and correct even after the addition or erase of
108 ///\note This class is similar to other Item types in LEMON, like
109 ///Node and Arc types in digraph.
114 explicit Col(int id) : _id(id) {}
116 typedef Value ExprValue;
118 /// Default constructor
120 /// \warning The default constructor sets the Col to an
123 /// Invalid constructor \& conversion.
125 /// This constructor initializes the Col to be invalid.
126 /// \sa Invalid for more details.
127 Col(const Invalid&) : _id(-1) {}
128 /// Equality operator
130 /// Two \ref Col "Col"s are equal if and only if they point to
131 /// the same LP column or both are invalid.
132 bool operator==(Col c) const {return _id == c._id;}
133 /// Inequality operator
135 /// \sa operator==(Col c)
137 bool operator!=(Col c) const {return _id != c._id;}
138 /// Artificial ordering operator.
140 /// To allow the use of this object in std::map or similar
141 /// associative container we require this.
143 /// \note This operator only have to define some strict ordering of
144 /// the items; this order has nothing to do with the iteration
145 /// ordering of the items.
146 bool operator<(Col c) const {return _id < c._id;}
149 ///Iterator for iterate over the columns of an LP problem
151 /// Its usage is quite simple, for example, you can count the number
152 /// of columns in an LP \c lp:
155 /// for (LpBase::ColIt c(lp); c!=INVALID; ++c) ++count;
157 class ColIt : public Col {
158 const LpBase *_solver;
160 /// Default constructor
162 /// \warning The default constructor sets the iterator
163 /// to an undefined value.
165 /// Sets the iterator to the first Col
167 /// Sets the iterator to the first Col.
169 ColIt(const LpBase &solver) : _solver(&solver)
171 _solver->_cols.firstItem(_id);
173 /// Invalid constructor \& conversion
175 /// Initialize the iterator to be invalid.
176 /// \sa Invalid for more details.
177 ColIt(const Invalid&) : Col(INVALID) {}
180 /// Assign the iterator to the next column.
184 _solver->_cols.nextItem(_id);
189 /// \brief Gets the collection of the columns of the LP problem.
191 /// This function can be used for iterating on
192 /// the columns of the LP problem. It returns a wrapped ColIt, which looks
193 /// like an STL container (by having begin() and end())
194 /// which you can use in range-based for loops, STL algorithms, etc.
195 /// For example you can write:
197 /// for(auto c: lp.cols())
200 LemonRangeWrapper1<ColIt, LpBase> cols() {
201 return LemonRangeWrapper1<ColIt, LpBase>(*this);
205 /// \brief Returns the ID of the column.
206 static int id(const Col& col) { return col._id; }
207 /// \brief Returns the column with the given ID.
209 /// \pre The argument should be a valid column ID in the LP problem.
210 static Col colFromId(int id) { return Col(id); }
212 ///Refer to a row of the LP.
214 ///This type is used to refer to a row of the LP.
216 ///Its value remains valid and correct even after the addition or erase of
219 ///\note This class is similar to other Item types in LEMON, like
220 ///Node and Arc types in digraph.
225 explicit Row(int id) : _id(id) {}
227 typedef Value ExprValue;
229 /// Default constructor
231 /// \warning The default constructor sets the Row to an
234 /// Invalid constructor \& conversion.
236 /// This constructor initializes the Row to be invalid.
237 /// \sa Invalid for more details.
238 Row(const Invalid&) : _id(-1) {}
239 /// Equality operator
241 /// Two \ref Row "Row"s are equal if and only if they point to
242 /// the same LP row or both are invalid.
243 bool operator==(Row r) const {return _id == r._id;}
244 /// Inequality operator
246 /// \sa operator==(Row r)
248 bool operator!=(Row r) const {return _id != r._id;}
249 /// Artificial ordering operator.
251 /// To allow the use of this object in std::map or similar
252 /// associative container we require this.
254 /// \note This operator only have to define some strict ordering of
255 /// the items; this order has nothing to do with the iteration
256 /// ordering of the items.
257 bool operator<(Row r) const {return _id < r._id;}
260 ///Iterator for iterate over the rows of an LP problem
262 /// Its usage is quite simple, for example, you can count the number
263 /// of rows in an LP \c lp:
266 /// for (LpBase::RowIt c(lp); c!=INVALID; ++c) ++count;
268 class RowIt : public Row {
269 const LpBase *_solver;
271 /// Default constructor
273 /// \warning The default constructor sets the iterator
274 /// to an undefined value.
276 /// Sets the iterator to the first Row
278 /// Sets the iterator to the first Row.
280 RowIt(const LpBase &solver) : _solver(&solver)
282 _solver->_rows.firstItem(_id);
284 /// Invalid constructor \& conversion
286 /// Initialize the iterator to be invalid.
287 /// \sa Invalid for more details.
288 RowIt(const Invalid&) : Row(INVALID) {}
291 /// Assign the iterator to the next row.
295 _solver->_rows.nextItem(_id);
300 /// \brief Gets the collection of the rows of the LP problem.
302 /// This function can be used for iterating on
303 /// the rows of the LP problem. It returns a wrapped RowIt, which looks
304 /// like an STL container (by having begin() and end())
305 /// which you can use in range-based for loops, STL algorithms, etc.
306 /// For example you can write:
308 /// for(auto c: lp.rows())
311 LemonRangeWrapper1<RowIt, LpBase> rows() {
312 return LemonRangeWrapper1<RowIt, LpBase>(*this);
316 /// \brief Returns the ID of the row.
317 static int id(const Row& row) { return row._id; }
318 /// \brief Returns the row with the given ID.
320 /// \pre The argument should be a valid row ID in the LP problem.
321 static Row rowFromId(int id) { return Row(id); }
325 ///Linear expression of variables and a constant component
327 ///This data structure stores a linear expression of the variables
328 ///(\ref Col "Col"s) and also has a constant component.
330 ///There are several ways to access and modify the contents of this
337 ///or you can also iterate through its elements.
340 ///for(LpBase::Expr::ConstCoeffIt i(e);i!=INVALID;++i)
341 /// s+=*i * primal(i);
343 ///(This code computes the primal value of the expression).
344 ///- Numbers (<tt>double</tt>'s)
345 ///and variables (\ref Col "Col"s) directly convert to an
346 ///\ref Expr and the usual linear operations are defined, so
349 ///2*v-3.12*(v-w/2)+2
350 ///v*2.1+(3*v+(v*12+w+6)*3)/2
352 ///are valid expressions.
353 ///The usual assignment operations are also defined.
356 ///e+=2*v-3.12*(v-w/2)+2;
360 ///- The constant member can be set and read by dereference
361 /// operator (unary *)
372 /// The key type of the expression
373 typedef LpBase::Col Key;
374 /// The value type of the expression
375 typedef LpBase::Value Value;
379 std::map<int, Value> comps;
382 typedef True SolverExpr;
383 /// Default constructor
385 /// Construct an empty expression, the coefficients and
386 /// the constant component are initialized to zero.
387 Expr() : const_comp(0) {}
388 /// Construct an expression from a column
390 /// Construct an expression, which has a term with \c c variable
391 /// and 1.0 coefficient.
392 Expr(const Col &c) : const_comp(0) {
393 typedef std::map<int, Value>::value_type pair_type;
394 comps.insert(pair_type(id(c), 1));
396 /// Construct an expression from a constant
398 /// Construct an expression, which's constant component is \c v.
400 Expr(const Value &v) : const_comp(v) {}
401 /// Returns the coefficient of the column
402 Value operator[](const Col& c) const {
403 std::map<int, Value>::const_iterator it=comps.find(id(c));
404 if (it != comps.end()) {
410 /// Returns the coefficient of the column
411 Value& operator[](const Col& c) {
414 /// Sets the coefficient of the column
415 void set(const Col &c, const Value &v) {
417 typedef std::map<int, Value>::value_type pair_type;
418 comps.insert(pair_type(id(c), v));
423 /// Returns the constant component of the expression
424 Value& operator*() { return const_comp; }
425 /// Returns the constant component of the expression
426 const Value& operator*() const { return const_comp; }
427 /// \brief Removes the coefficients which's absolute value does
428 /// not exceed \c epsilon. It also sets to zero the constant
429 /// component, if it does not exceed epsilon in absolute value.
430 void simplify(Value epsilon = 0.0) {
431 std::map<int, Value>::iterator it=comps.begin();
432 while (it != comps.end()) {
433 std::map<int, Value>::iterator jt=it;
435 if (std::fabs((*it).second) <= epsilon) comps.erase(it);
438 if (std::fabs(const_comp) <= epsilon) const_comp = 0;
441 void simplify(Value epsilon = 0.0) const {
442 const_cast<Expr*>(this)->simplify(epsilon);
445 ///Sets all coefficients and the constant component to 0.
451 ///Compound assignment
452 Expr &operator+=(const Expr &e) {
453 for (std::map<int, Value>::const_iterator it=e.comps.begin();
454 it!=e.comps.end(); ++it)
455 comps[it->first]+=it->second;
456 const_comp+=e.const_comp;
459 ///Compound assignment
460 Expr &operator-=(const Expr &e) {
461 for (std::map<int, Value>::const_iterator it=e.comps.begin();
462 it!=e.comps.end(); ++it)
463 comps[it->first]-=it->second;
464 const_comp-=e.const_comp;
467 ///Multiply with a constant
468 Expr &operator*=(const Value &v) {
469 for (std::map<int, Value>::iterator it=comps.begin();
470 it!=comps.end(); ++it)
475 ///Division with a constant
476 Expr &operator/=(const Value &c) {
477 for (std::map<int, Value>::iterator it=comps.begin();
478 it!=comps.end(); ++it)
484 ///Iterator over the expression
486 ///The iterator iterates over the terms of the expression.
490 ///for(LpBase::Expr::CoeffIt i(e);i!=INVALID;++i)
491 /// s+= *i * primal(i);
496 std::map<int, Value>::iterator _it, _end;
500 /// Sets the iterator to the first term
502 /// Sets the iterator to the first term of the expression.
505 : _it(e.comps.begin()), _end(e.comps.end()){}
507 /// Convert the iterator to the column of the term
508 operator Col() const {
509 return colFromId(_it->first);
512 /// Returns the coefficient of the term
513 Value& operator*() { return _it->second; }
515 /// Returns the coefficient of the term
516 const Value& operator*() const { return _it->second; }
519 /// Assign the iterator to the next term.
521 CoeffIt& operator++() { ++_it; return *this; }
523 /// Equality operator
524 bool operator==(Invalid) const { return _it == _end; }
525 /// Inequality operator
526 bool operator!=(Invalid) const { return _it != _end; }
529 /// Const iterator over the expression
531 ///The iterator iterates over the terms of the expression.
535 ///for(LpBase::Expr::ConstCoeffIt i(e);i!=INVALID;++i)
536 /// s+=*i * primal(i);
541 std::map<int, Value>::const_iterator _it, _end;
545 /// Sets the iterator to the first term
547 /// Sets the iterator to the first term of the expression.
549 ConstCoeffIt(const Expr& e)
550 : _it(e.comps.begin()), _end(e.comps.end()){}
552 /// Convert the iterator to the column of the term
553 operator Col() const {
554 return colFromId(_it->first);
557 /// Returns the coefficient of the term
558 const Value& operator*() const { return _it->second; }
562 /// Assign the iterator to the next term.
564 ConstCoeffIt& operator++() { ++_it; return *this; }
566 /// Equality operator
567 bool operator==(Invalid) const { return _it == _end; }
568 /// Inequality operator
569 bool operator!=(Invalid) const { return _it != _end; }
576 ///This data stucture represents a linear constraint in the LP.
577 ///Basically it is a linear expression with a lower or an upper bound
578 ///(or both). These parts of the constraint can be obtained by the member
579 ///functions \ref expr(), \ref lowerBound() and \ref upperBound(),
581 ///There are two ways to construct a constraint.
582 ///- You can set the linear expression and the bounds directly
583 /// by the functions above.
584 ///- The operators <tt>\<=</tt>, <tt>==</tt> and <tt>\>=</tt>
585 /// are defined between expressions, or even between constraints whenever
586 /// it makes sense. Therefore if \c e and \c f are linear expressions and
587 /// \c s and \c t are numbers, then the followings are valid expressions
588 /// and thus they can be used directly e.g. in \ref addRow() whenever
597 ///\warning The validity of a constraint is checked only at run
598 ///time, so e.g. \ref addRow(<tt>x[1]\<=x[2]<=5</tt>) will
599 ///compile, but will fail an assertion.
603 typedef LpBase::Expr Expr;
604 typedef Expr::Key Key;
605 typedef Expr::Value Value;
612 Constr() : _expr(), _lb(NaN), _ub(NaN) {}
614 Constr(Value lb, const Expr &e, Value ub) :
615 _expr(e), _lb(lb), _ub(ub) {}
616 Constr(const Expr &e) :
617 _expr(e), _lb(NaN), _ub(NaN) {}
625 ///Reference to the linear expression
626 Expr &expr() { return _expr; }
627 ///Cont reference to the linear expression
628 const Expr &expr() const { return _expr; }
629 ///Reference to the lower bound.
632 ///- \ref INF "INF": the constraint is lower unbounded.
633 ///- \ref NaN "NaN": lower bound has not been set.
634 ///- finite number: the lower bound
635 Value &lowerBound() { return _lb; }
636 ///The const version of \ref lowerBound()
637 const Value &lowerBound() const { return _lb; }
638 ///Reference to the upper bound.
641 ///- \ref INF "INF": the constraint is upper unbounded.
642 ///- \ref NaN "NaN": upper bound has not been set.
643 ///- finite number: the upper bound
644 Value &upperBound() { return _ub; }
645 ///The const version of \ref upperBound()
646 const Value &upperBound() const { return _ub; }
647 ///Is the constraint lower bounded?
648 bool lowerBounded() const {
649 return _lb != -INF && !isNaN(_lb);
651 ///Is the constraint upper bounded?
652 bool upperBounded() const {
653 return _ub != INF && !isNaN(_ub);
658 ///Linear expression of rows
660 ///This data structure represents a column of the matrix,
661 ///thas is it strores a linear expression of the dual variables
662 ///(\ref LpBase::Row "Row"s).
664 ///There are several ways to access and modify the contents of this
671 ///or you can also iterate through its elements.
674 ///for(LpBase::DualExpr::ConstCoeffIt i(e);i!=INVALID;++i)
677 ///(This code computes the sum of all coefficients).
678 ///- Numbers (<tt>double</tt>'s)
679 ///and variables (\ref LpBase::Row "Row"s) directly convert to an
680 ///\ref DualExpr and the usual linear operations are defined, so
684 ///v*2.1+(3*v+(v*12+w)*3)/2
686 ///are valid \ref DualExpr dual expressions.
687 ///The usual assignment operations are also defined.
690 ///e+=2*v-3.12*(v-w/2);
699 /// The key type of the expression
700 typedef LpBase::Row Key;
701 /// The value type of the expression
702 typedef LpBase::Value Value;
705 std::map<int, Value> comps;
708 typedef True SolverExpr;
709 /// Default constructor
711 /// Construct an empty expression, the coefficients are
712 /// initialized to zero.
714 /// Construct an expression from a row
716 /// Construct an expression, which has a term with \c r dual
717 /// variable and 1.0 coefficient.
718 DualExpr(const Row &r) {
719 typedef std::map<int, Value>::value_type pair_type;
720 comps.insert(pair_type(id(r), 1));
722 /// Returns the coefficient of the row
723 Value operator[](const Row& r) const {
724 std::map<int, Value>::const_iterator it = comps.find(id(r));
725 if (it != comps.end()) {
731 /// Returns the coefficient of the row
732 Value& operator[](const Row& r) {
735 /// Sets the coefficient of the row
736 void set(const Row &r, const Value &v) {
738 typedef std::map<int, Value>::value_type pair_type;
739 comps.insert(pair_type(id(r), v));
744 /// \brief Removes the coefficients which's absolute value does
745 /// not exceed \c epsilon.
746 void simplify(Value epsilon = 0.0) {
747 std::map<int, Value>::iterator it=comps.begin();
748 while (it != comps.end()) {
749 std::map<int, Value>::iterator jt=it;
751 if (std::fabs((*it).second) <= epsilon) comps.erase(it);
756 void simplify(Value epsilon = 0.0) const {
757 const_cast<DualExpr*>(this)->simplify(epsilon);
760 ///Sets all coefficients to 0.
764 ///Compound assignment
765 DualExpr &operator+=(const DualExpr &e) {
766 for (std::map<int, Value>::const_iterator it=e.comps.begin();
767 it!=e.comps.end(); ++it)
768 comps[it->first]+=it->second;
771 ///Compound assignment
772 DualExpr &operator-=(const DualExpr &e) {
773 for (std::map<int, Value>::const_iterator it=e.comps.begin();
774 it!=e.comps.end(); ++it)
775 comps[it->first]-=it->second;
778 ///Multiply with a constant
779 DualExpr &operator*=(const Value &v) {
780 for (std::map<int, Value>::iterator it=comps.begin();
781 it!=comps.end(); ++it)
785 ///Division with a constant
786 DualExpr &operator/=(const Value &v) {
787 for (std::map<int, Value>::iterator it=comps.begin();
788 it!=comps.end(); ++it)
793 ///Iterator over the expression
795 ///The iterator iterates over the terms of the expression.
799 ///for(LpBase::DualExpr::CoeffIt i(e);i!=INVALID;++i)
800 /// s+= *i * dual(i);
805 std::map<int, Value>::iterator _it, _end;
809 /// Sets the iterator to the first term
811 /// Sets the iterator to the first term of the expression.
814 : _it(e.comps.begin()), _end(e.comps.end()){}
816 /// Convert the iterator to the row of the term
817 operator Row() const {
818 return rowFromId(_it->first);
821 /// Returns the coefficient of the term
822 Value& operator*() { return _it->second; }
824 /// Returns the coefficient of the term
825 const Value& operator*() const { return _it->second; }
829 /// Assign the iterator to the next term.
831 CoeffIt& operator++() { ++_it; return *this; }
833 /// Equality operator
834 bool operator==(Invalid) const { return _it == _end; }
835 /// Inequality operator
836 bool operator!=(Invalid) const { return _it != _end; }
839 ///Iterator over the expression
841 ///The iterator iterates over the terms of the expression.
845 ///for(LpBase::DualExpr::ConstCoeffIt i(e);i!=INVALID;++i)
846 /// s+= *i * dual(i);
851 std::map<int, Value>::const_iterator _it, _end;
855 /// Sets the iterator to the first term
857 /// Sets the iterator to the first term of the expression.
859 ConstCoeffIt(const DualExpr& e)
860 : _it(e.comps.begin()), _end(e.comps.end()){}
862 /// Convert the iterator to the row of the term
863 operator Row() const {
864 return rowFromId(_it->first);
867 /// Returns the coefficient of the term
868 const Value& operator*() const { return _it->second; }
872 /// Assign the iterator to the next term.
874 ConstCoeffIt& operator++() { ++_it; return *this; }
876 /// Equality operator
877 bool operator==(Invalid) const { return _it == _end; }
878 /// Inequality operator
879 bool operator!=(Invalid) const { return _it != _end; }
886 class InsertIterator {
889 std::map<int, Value>& _host;
890 const _solver_bits::VarIndex& _index;
894 typedef std::output_iterator_tag iterator_category;
895 typedef void difference_type;
896 typedef void value_type;
897 typedef void reference;
898 typedef void pointer;
900 InsertIterator(std::map<int, Value>& host,
901 const _solver_bits::VarIndex& index)
902 : _host(host), _index(index) {}
904 InsertIterator& operator=(const std::pair<int, Value>& value) {
905 typedef std::map<int, Value>::value_type pair_type;
906 _host.insert(pair_type(_index[value.first], value.second));
910 InsertIterator& operator*() { return *this; }
911 InsertIterator& operator++() { return *this; }
912 InsertIterator operator++(int) { return *this; }
918 std::map<int, Value>::const_iterator _host_it;
919 const _solver_bits::VarIndex& _index;
922 typedef std::bidirectional_iterator_tag iterator_category;
923 typedef std::ptrdiff_t difference_type;
924 typedef const std::pair<int, Value> value_type;
925 typedef value_type reference;
929 pointer(value_type& _value) : value(_value) {}
930 value_type* operator->() { return &value; }
935 ExprIterator(const std::map<int, Value>::const_iterator& host_it,
936 const _solver_bits::VarIndex& index)
937 : _host_it(host_it), _index(index) {}
939 reference operator*() {
940 return std::make_pair(_index(_host_it->first), _host_it->second);
943 pointer operator->() {
944 return pointer(operator*());
947 ExprIterator& operator++() { ++_host_it; return *this; }
948 ExprIterator operator++(int) {
949 ExprIterator tmp(*this); ++_host_it; return tmp;
952 ExprIterator& operator--() { --_host_it; return *this; }
953 ExprIterator operator--(int) {
954 ExprIterator tmp(*this); --_host_it; return tmp;
957 bool operator==(const ExprIterator& it) const {
958 return _host_it == it._host_it;
961 bool operator!=(const ExprIterator& it) const {
962 return _host_it != it._host_it;
969 //Abstract virtual functions
971 virtual int _addColId(int col) { return _cols.addIndex(col); }
972 virtual int _addRowId(int row) { return _rows.addIndex(row); }
974 virtual void _eraseColId(int col) { _cols.eraseIndex(col); }
975 virtual void _eraseRowId(int row) { _rows.eraseIndex(row); }
977 virtual int _addCol() = 0;
978 virtual int _addRow() = 0;
980 virtual int _addRow(Value l, ExprIterator b, ExprIterator e, Value u) {
982 _setRowCoeffs(row, b, e);
983 _setRowLowerBound(row, l);
984 _setRowUpperBound(row, u);
988 virtual void _eraseCol(int col) = 0;
989 virtual void _eraseRow(int row) = 0;
991 virtual void _getColName(int col, std::string& name) const = 0;
992 virtual void _setColName(int col, const std::string& name) = 0;
993 virtual int _colByName(const std::string& name) const = 0;
995 virtual void _getRowName(int row, std::string& name) const = 0;
996 virtual void _setRowName(int row, const std::string& name) = 0;
997 virtual int _rowByName(const std::string& name) const = 0;
999 virtual void _setRowCoeffs(int i, ExprIterator b, ExprIterator e) = 0;
1000 virtual void _getRowCoeffs(int i, InsertIterator b) const = 0;
1002 virtual void _setColCoeffs(int i, ExprIterator b, ExprIterator e) = 0;
1003 virtual void _getColCoeffs(int i, InsertIterator b) const = 0;
1005 virtual void _setCoeff(int row, int col, Value value) = 0;
1006 virtual Value _getCoeff(int row, int col) const = 0;
1008 virtual void _setColLowerBound(int i, Value value) = 0;
1009 virtual Value _getColLowerBound(int i) const = 0;
1011 virtual void _setColUpperBound(int i, Value value) = 0;
1012 virtual Value _getColUpperBound(int i) const = 0;
1014 virtual void _setRowLowerBound(int i, Value value) = 0;
1015 virtual Value _getRowLowerBound(int i) const = 0;
1017 virtual void _setRowUpperBound(int i, Value value) = 0;
1018 virtual Value _getRowUpperBound(int i) const = 0;
1020 virtual void _setObjCoeffs(ExprIterator b, ExprIterator e) = 0;
1021 virtual void _getObjCoeffs(InsertIterator b) const = 0;
1023 virtual void _setObjCoeff(int i, Value obj_coef) = 0;
1024 virtual Value _getObjCoeff(int i) const = 0;
1026 virtual void _setSense(Sense) = 0;
1027 virtual Sense _getSense() const = 0;
1029 virtual void _clear() = 0;
1031 virtual const char* _solverName() const = 0;
1033 virtual void _messageLevel(MessageLevel level) = 0;
1035 //Own protected stuff
1037 //Constant component of the objective function
1038 Value obj_const_comp;
1040 LpBase() : _rows(), _cols(), obj_const_comp(0) {}
1044 ///Unsupported file format exception
1045 class UnsupportedFormatError : public Exception
1047 std::string _format;
1048 mutable std::string _what;
1050 explicit UnsupportedFormatError(std::string format) throw()
1051 : _format(format) { }
1052 virtual ~UnsupportedFormatError() throw() {}
1053 virtual const char* what() const throw() {
1056 std::ostringstream oss;
1057 oss << "lemon::UnsupportedFormatError: " << _format;
1061 if (!_what.empty()) return _what.c_str();
1062 else return "lemon::UnsupportedFormatError";
1067 virtual void _write(std::string, std::string format) const
1069 throw UnsupportedFormatError(format);
1074 /// Virtual destructor
1075 virtual ~LpBase() {}
1077 ///Gives back the name of the solver.
1078 const char* solverName() const {return _solverName();}
1080 ///\name Build Up and Modify the LP
1084 ///Add a new empty column (i.e a new variable) to the LP
1085 Col addCol() { Col c; c._id = _addColId(_addCol()); return c;}
1087 ///\brief Adds several new columns (i.e variables) at once
1089 ///This magic function takes a container as its argument and fills
1090 ///its elements with new columns (i.e. variables)
1092 ///- a standard STL compatible iterable container with
1093 ///\ref Col as its \c values_type like
1095 ///std::vector<LpBase::Col>
1096 ///std::list<LpBase::Col>
1098 ///- a standard STL compatible iterable container with
1099 ///\ref Col as its \c mapped_type like
1101 ///std::map<AnyType,LpBase::Col>
1103 ///- an iterable lemon \ref concepts::WriteMap "write map" like
1105 ///ListGraph::NodeMap<LpBase::Col>
1106 ///ListGraph::ArcMap<LpBase::Col>
1108 ///\return The number of the created column.
1111 int addColSet(T &t) { return 0;}
1114 typename enable_if<typename T::value_type::LpCol,int>::type
1115 addColSet(T &t,dummy<0> = 0) {
1117 for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addCol();s++;}
1121 typename enable_if<typename T::value_type::second_type::LpCol,
1123 addColSet(T &t,dummy<1> = 1) {
1125 for(typename T::iterator i=t.begin();i!=t.end();++i) {
1132 typename enable_if<typename T::MapIt::Value::LpCol,
1134 addColSet(T &t,dummy<2> = 2) {
1136 for(typename T::MapIt i(t); i!=INVALID; ++i)
1145 ///Set a column (i.e a dual constraint) of the LP
1147 ///\param c is the column to be modified
1148 ///\param e is a dual linear expression (see \ref DualExpr)
1150 void col(Col c, const DualExpr &e) {
1152 _setColCoeffs(_cols(id(c)), ExprIterator(e.comps.begin(), _rows),
1153 ExprIterator(e.comps.end(), _rows));
1156 ///Get a column (i.e a dual constraint) of the LP
1158 ///\param c is the column to get
1159 ///\return the dual expression associated to the column
1160 DualExpr col(Col c) const {
1162 _getColCoeffs(_cols(id(c)), InsertIterator(e.comps, _rows));
1166 ///Add a new column to the LP
1168 ///\param e is a dual linear expression (see \ref DualExpr)
1169 ///\param o is the corresponding component of the objective
1170 ///function. It is 0 by default.
1171 ///\return The created column.
1172 Col addCol(const DualExpr &e, Value o = 0) {
1179 ///Add a new empty row (i.e a new constraint) to the LP
1181 ///This function adds a new empty row (i.e a new constraint) to the LP.
1182 ///\return The created row
1183 Row addRow() { Row r; r._id = _addRowId(_addRow()); return r;}
1185 ///\brief Add several new rows (i.e constraints) at once
1187 ///This magic function takes a container as its argument and fills
1188 ///its elements with new row (i.e. variables)
1190 ///- a standard STL compatible iterable container with
1191 ///\ref LpBase::Row "Row" as its \c values_type like
1193 ///std::vector<LpBase::Row>
1194 ///std::list<LpBase::Row>
1196 ///- a standard STL compatible iterable container with
1197 ///\ref LpBase::Row "Row" as its \c mapped_type like
1199 ///std::map<AnyType,LpBase::Row>
1201 ///- an iterable lemon \ref concepts::WriteMap "write map" like
1203 ///ListGraph::NodeMap<LpBase::Row>
1204 ///ListGraph::ArcMap<LpBase::Row>
1206 ///\return The number of rows created.
1209 int addRowSet(T &t) { return 0;}
1212 typename enable_if<typename T::value_type::LpRow,int>::type
1213 addRowSet(T &t, dummy<0> = 0) {
1215 for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addRow();s++;}
1219 typename enable_if<typename T::value_type::second_type::LpRow, int>::type
1220 addRowSet(T &t, dummy<1> = 1) {
1222 for(typename T::iterator i=t.begin();i!=t.end();++i) {
1229 typename enable_if<typename T::MapIt::Value::LpRow, int>::type
1230 addRowSet(T &t, dummy<2> = 2) {
1232 for(typename T::MapIt i(t); i!=INVALID; ++i)
1241 ///Set a row (i.e a constraint) of the LP
1243 ///\param r is the row to be modified
1244 ///\param l is lower bound (-\ref INF means no bound)
1245 ///\param e is a linear expression (see \ref Expr)
1246 ///\param u is the upper bound (\ref INF means no bound)
1247 void row(Row r, Value l, const Expr &e, Value u) {
1249 _setRowCoeffs(_rows(id(r)), ExprIterator(e.comps.begin(), _cols),
1250 ExprIterator(e.comps.end(), _cols));
1251 _setRowLowerBound(_rows(id(r)),l - *e);
1252 _setRowUpperBound(_rows(id(r)),u - *e);
1255 ///Set a row (i.e a constraint) of the LP
1257 ///\param r is the row to be modified
1258 ///\param c is a linear expression (see \ref Constr)
1259 void row(Row r, const Constr &c) {
1260 row(r, c.lowerBounded()?c.lowerBound():-INF,
1261 c.expr(), c.upperBounded()?c.upperBound():INF);
1265 ///Get a row (i.e a constraint) of the LP
1267 ///\param r is the row to get
1268 ///\return the expression associated to the row
1269 Expr row(Row r) const {
1271 _getRowCoeffs(_rows(id(r)), InsertIterator(e.comps, _cols));
1275 ///Add a new row (i.e a new constraint) to the LP
1277 ///\param l is the lower bound (-\ref INF means no bound)
1278 ///\param e is a linear expression (see \ref Expr)
1279 ///\param u is the upper bound (\ref INF means no bound)
1280 ///\return The created row.
1281 Row addRow(Value l,const Expr &e, Value u) {
1284 r._id = _addRowId(_addRow(l - *e, ExprIterator(e.comps.begin(), _cols),
1285 ExprIterator(e.comps.end(), _cols), u - *e));
1289 ///Add a new row (i.e a new constraint) to the LP
1291 ///\param c is a linear expression (see \ref Constr)
1292 ///\return The created row.
1293 Row addRow(const Constr &c) {
1295 c.expr().simplify();
1296 r._id = _addRowId(_addRow(c.lowerBounded()?c.lowerBound()-*c.expr():-INF,
1297 ExprIterator(c.expr().comps.begin(), _cols),
1298 ExprIterator(c.expr().comps.end(), _cols),
1299 c.upperBounded()?c.upperBound()-*c.expr():INF));
1302 ///Erase a column (i.e a variable) from the LP
1304 ///\param c is the column to be deleted
1306 _eraseCol(_cols(id(c)));
1307 _eraseColId(_cols(id(c)));
1309 ///Erase a row (i.e a constraint) from the LP
1311 ///\param r is the row to be deleted
1313 _eraseRow(_rows(id(r)));
1314 _eraseRowId(_rows(id(r)));
1317 /// Get the name of a column
1319 ///\param c is the coresponding column
1320 ///\return The name of the colunm
1321 std::string colName(Col c) const {
1323 _getColName(_cols(id(c)), name);
1327 /// Set the name of a column
1329 ///\param c is the coresponding column
1330 ///\param name The name to be given
1331 void colName(Col c, const std::string& name) {
1332 _setColName(_cols(id(c)), name);
1335 /// Get the column by its name
1337 ///\param name The name of the column
1338 ///\return the proper column or \c INVALID
1339 Col colByName(const std::string& name) const {
1340 int k = _colByName(name);
1341 return k != -1 ? Col(_cols[k]) : Col(INVALID);
1344 /// Get the name of a row
1346 ///\param r is the coresponding row
1347 ///\return The name of the row
1348 std::string rowName(Row r) const {
1350 _getRowName(_rows(id(r)), name);
1354 /// Set the name of a row
1356 ///\param r is the coresponding row
1357 ///\param name The name to be given
1358 void rowName(Row r, const std::string& name) {
1359 _setRowName(_rows(id(r)), name);
1362 /// Get the row by its name
1364 ///\param name The name of the row
1365 ///\return the proper row or \c INVALID
1366 Row rowByName(const std::string& name) const {
1367 int k = _rowByName(name);
1368 return k != -1 ? Row(_rows[k]) : Row(INVALID);
1371 /// Set an element of the coefficient matrix of the LP
1373 ///\param r is the row of the element to be modified
1374 ///\param c is the column of the element to be modified
1375 ///\param val is the new value of the coefficient
1376 void coeff(Row r, Col c, Value val) {
1377 _setCoeff(_rows(id(r)),_cols(id(c)), val);
1380 /// Get an element of the coefficient matrix of the LP
1382 ///\param r is the row of the element
1383 ///\param c is the column of the element
1384 ///\return the corresponding coefficient
1385 Value coeff(Row r, Col c) const {
1386 return _getCoeff(_rows(id(r)),_cols(id(c)));
1389 /// Set the lower bound of a column (i.e a variable)
1391 /// The lower bound of a variable (column) has to be given by an
1392 /// extended number of type Value, i.e. a finite number of type
1393 /// Value or -\ref INF.
1394 void colLowerBound(Col c, Value value) {
1395 _setColLowerBound(_cols(id(c)),value);
1398 /// Get the lower bound of a column (i.e a variable)
1400 /// This function returns the lower bound for column (variable) \c c
1401 /// (this might be -\ref INF as well).
1402 ///\return The lower bound for column \c c
1403 Value colLowerBound(Col c) const {
1404 return _getColLowerBound(_cols(id(c)));
1407 ///\brief Set the lower bound of several columns
1408 ///(i.e variables) at once
1410 ///This magic function takes a container as its argument
1411 ///and applies the function on all of its elements.
1412 ///The lower bound of a variable (column) has to be given by an
1413 ///extended number of type Value, i.e. a finite number of type
1414 ///Value or -\ref INF.
1417 void colLowerBound(T &t, Value value) { return 0;}
1420 typename enable_if<typename T::value_type::LpCol,void>::type
1421 colLowerBound(T &t, Value value,dummy<0> = 0) {
1422 for(typename T::iterator i=t.begin();i!=t.end();++i) {
1423 colLowerBound(*i, value);
1427 typename enable_if<typename T::value_type::second_type::LpCol,
1429 colLowerBound(T &t, Value value,dummy<1> = 1) {
1430 for(typename T::iterator i=t.begin();i!=t.end();++i) {
1431 colLowerBound(i->second, value);
1435 typename enable_if<typename T::MapIt::Value::LpCol,
1437 colLowerBound(T &t, Value value,dummy<2> = 2) {
1438 for(typename T::MapIt i(t); i!=INVALID; ++i){
1439 colLowerBound(*i, value);
1444 /// Set the upper bound of a column (i.e a variable)
1446 /// The upper bound of a variable (column) has to be given by an
1447 /// extended number of type Value, i.e. a finite number of type
1448 /// Value or \ref INF.
1449 void colUpperBound(Col c, Value value) {
1450 _setColUpperBound(_cols(id(c)),value);
1453 /// Get the upper bound of a column (i.e a variable)
1455 /// This function returns the upper bound for column (variable) \c c
1456 /// (this might be \ref INF as well).
1457 /// \return The upper bound for column \c c
1458 Value colUpperBound(Col c) const {
1459 return _getColUpperBound(_cols(id(c)));
1462 ///\brief Set the upper bound of several columns
1463 ///(i.e variables) at once
1465 ///This magic function takes a container as its argument
1466 ///and applies the function on all of its elements.
1467 ///The upper bound of a variable (column) has to be given by an
1468 ///extended number of type Value, i.e. a finite number of type
1469 ///Value or \ref INF.
1472 void colUpperBound(T &t, Value value) { return 0;}
1475 typename enable_if<typename T1::value_type::LpCol,void>::type
1476 colUpperBound(T1 &t, Value value,dummy<0> = 0) {
1477 for(typename T1::iterator i=t.begin();i!=t.end();++i) {
1478 colUpperBound(*i, value);
1482 typename enable_if<typename T1::value_type::second_type::LpCol,
1484 colUpperBound(T1 &t, Value value,dummy<1> = 1) {
1485 for(typename T1::iterator i=t.begin();i!=t.end();++i) {
1486 colUpperBound(i->second, value);
1490 typename enable_if<typename T1::MapIt::Value::LpCol,
1492 colUpperBound(T1 &t, Value value,dummy<2> = 2) {
1493 for(typename T1::MapIt i(t); i!=INVALID; ++i){
1494 colUpperBound(*i, value);
1499 /// Set the lower and the upper bounds of a column (i.e a variable)
1501 /// The lower and the upper bounds of
1502 /// a variable (column) have to be given by an
1503 /// extended number of type Value, i.e. a finite number of type
1504 /// Value, -\ref INF or \ref INF.
1505 void colBounds(Col c, Value lower, Value upper) {
1506 _setColLowerBound(_cols(id(c)),lower);
1507 _setColUpperBound(_cols(id(c)),upper);
1510 ///\brief Set the lower and the upper bound of several columns
1511 ///(i.e variables) at once
1513 ///This magic function takes a container as its argument
1514 ///and applies the function on all of its elements.
1515 /// The lower and the upper bounds of
1516 /// a variable (column) have to be given by an
1517 /// extended number of type Value, i.e. a finite number of type
1518 /// Value, -\ref INF or \ref INF.
1521 void colBounds(T &t, Value lower, Value upper) { return 0;}
1524 typename enable_if<typename T2::value_type::LpCol,void>::type
1525 colBounds(T2 &t, Value lower, Value upper,dummy<0> = 0) {
1526 for(typename T2::iterator i=t.begin();i!=t.end();++i) {
1527 colBounds(*i, lower, upper);
1531 typename enable_if<typename T2::value_type::second_type::LpCol, void>::type
1532 colBounds(T2 &t, Value lower, Value upper,dummy<1> = 1) {
1533 for(typename T2::iterator i=t.begin();i!=t.end();++i) {
1534 colBounds(i->second, lower, upper);
1538 typename enable_if<typename T2::MapIt::Value::LpCol, void>::type
1539 colBounds(T2 &t, Value lower, Value upper,dummy<2> = 2) {
1540 for(typename T2::MapIt i(t); i!=INVALID; ++i){
1541 colBounds(*i, lower, upper);
1546 /// Set the lower bound of a row (i.e a constraint)
1548 /// The lower bound of a constraint (row) has to be given by an
1549 /// extended number of type Value, i.e. a finite number of type
1550 /// Value or -\ref INF.
1551 void rowLowerBound(Row r, Value value) {
1552 _setRowLowerBound(_rows(id(r)),value);
1555 /// Get the lower bound of a row (i.e a constraint)
1557 /// This function returns the lower bound for row (constraint) \c c
1558 /// (this might be -\ref INF as well).
1559 ///\return The lower bound for row \c r
1560 Value rowLowerBound(Row r) const {
1561 return _getRowLowerBound(_rows(id(r)));
1564 /// Set the upper bound of a row (i.e a constraint)
1566 /// The upper bound of a constraint (row) has to be given by an
1567 /// extended number of type Value, i.e. a finite number of type
1568 /// Value or -\ref INF.
1569 void rowUpperBound(Row r, Value value) {
1570 _setRowUpperBound(_rows(id(r)),value);
1573 /// Get the upper bound of a row (i.e a constraint)
1575 /// This function returns the upper bound for row (constraint) \c c
1576 /// (this might be -\ref INF as well).
1577 ///\return The upper bound for row \c r
1578 Value rowUpperBound(Row r) const {
1579 return _getRowUpperBound(_rows(id(r)));
1582 ///Set an element of the objective function
1583 void objCoeff(Col c, Value v) {_setObjCoeff(_cols(id(c)),v); };
1585 ///Get an element of the objective function
1586 Value objCoeff(Col c) const { return _getObjCoeff(_cols(id(c))); };
1588 ///Set the objective function
1590 ///\param e is a linear expression of type \ref Expr.
1592 void obj(const Expr& e) {
1593 _setObjCoeffs(ExprIterator(e.comps.begin(), _cols),
1594 ExprIterator(e.comps.end(), _cols));
1595 obj_const_comp = *e;
1598 ///Get the objective function
1600 ///\return the objective function as a linear expression of type
1604 _getObjCoeffs(InsertIterator(e.comps, _cols));
1605 *e = obj_const_comp;
1610 ///Set the direction of optimization
1611 void sense(Sense sense) { _setSense(sense); }
1613 ///Query the direction of the optimization
1614 Sense sense() const {return _getSense(); }
1616 ///Set the sense to maximization
1617 void max() { _setSense(MAX); }
1619 ///Set the sense to maximization
1620 void min() { _setSense(MIN); }
1622 ///Clear the problem
1623 void clear() { _clear(); _rows.clear(); _cols.clear(); }
1625 /// Set the message level of the solver
1626 void messageLevel(MessageLevel level) { _messageLevel(level); }
1628 /// Write the problem to a file in the given format
1630 /// This function writes the problem to a file in the given format.
1631 /// Different solver backends may support different formats.
1632 /// Trying to write in an unsupported format will trigger
1633 /// \ref UnsupportedFormatError. For the supported formats,
1634 /// visit the documentation of the base class of the related backends
1635 /// (\ref CplexBase, \ref GlpkBase etc.)
1636 /// \param file The file path
1637 /// \param format The output file format.
1638 void write(std::string file, std::string format = "MPS") const
1640 _write(file.c_str(),format.c_str());
1649 ///\relates LpBase::Expr
1651 inline LpBase::Expr operator+(const LpBase::Expr &a, const LpBase::Expr &b) {
1652 LpBase::Expr tmp(a);
1658 ///\relates LpBase::Expr
1660 inline LpBase::Expr operator-(const LpBase::Expr &a, const LpBase::Expr &b) {
1661 LpBase::Expr tmp(a);
1665 ///Multiply with constant
1667 ///\relates LpBase::Expr
1669 inline LpBase::Expr operator*(const LpBase::Expr &a, const LpBase::Value &b) {
1670 LpBase::Expr tmp(a);
1675 ///Multiply with constant
1677 ///\relates LpBase::Expr
1679 inline LpBase::Expr operator*(const LpBase::Value &a, const LpBase::Expr &b) {
1680 LpBase::Expr tmp(b);
1684 ///Divide with constant
1686 ///\relates LpBase::Expr
1688 inline LpBase::Expr operator/(const LpBase::Expr &a, const LpBase::Value &b) {
1689 LpBase::Expr tmp(a);
1694 ///Create constraint
1696 ///\relates LpBase::Constr
1698 inline LpBase::Constr operator<=(const LpBase::Expr &e,
1699 const LpBase::Expr &f) {
1700 return LpBase::Constr(0, f - e, LpBase::NaN);
1703 ///Create constraint
1705 ///\relates LpBase::Constr
1707 inline LpBase::Constr operator<=(const LpBase::Value &e,
1708 const LpBase::Expr &f) {
1709 return LpBase::Constr(e, f, LpBase::NaN);
1712 ///Create constraint
1714 ///\relates LpBase::Constr
1716 inline LpBase::Constr operator<=(const LpBase::Expr &e,
1717 const LpBase::Value &f) {
1718 return LpBase::Constr(LpBase::NaN, e, f);
1721 ///Create constraint
1723 ///\relates LpBase::Constr
1725 inline LpBase::Constr operator>=(const LpBase::Expr &e,
1726 const LpBase::Expr &f) {
1727 return LpBase::Constr(0, e - f, LpBase::NaN);
1731 ///Create constraint
1733 ///\relates LpBase::Constr
1735 inline LpBase::Constr operator>=(const LpBase::Value &e,
1736 const LpBase::Expr &f) {
1737 return LpBase::Constr(LpBase::NaN, f, e);
1741 ///Create constraint
1743 ///\relates LpBase::Constr
1745 inline LpBase::Constr operator>=(const LpBase::Expr &e,
1746 const LpBase::Value &f) {
1747 return LpBase::Constr(f, e, LpBase::NaN);
1750 ///Create constraint
1752 ///\relates LpBase::Constr
1754 inline LpBase::Constr operator==(const LpBase::Expr &e,
1755 const LpBase::Value &f) {
1756 return LpBase::Constr(f, e, f);
1759 ///Create constraint
1761 ///\relates LpBase::Constr
1763 inline LpBase::Constr operator==(const LpBase::Expr &e,
1764 const LpBase::Expr &f) {
1765 return LpBase::Constr(0, f - e, 0);
1768 ///Create constraint
1770 ///\relates LpBase::Constr
1772 inline LpBase::Constr operator<=(const LpBase::Value &n,
1773 const LpBase::Constr &c) {
1774 LpBase::Constr tmp(c);
1775 LEMON_ASSERT(isNaN(tmp.lowerBound()), "Wrong LP constraint");
1779 ///Create constraint
1781 ///\relates LpBase::Constr
1783 inline LpBase::Constr operator<=(const LpBase::Constr &c,
1784 const LpBase::Value &n)
1786 LpBase::Constr tmp(c);
1787 LEMON_ASSERT(isNaN(tmp.upperBound()), "Wrong LP constraint");
1792 ///Create constraint
1794 ///\relates LpBase::Constr
1796 inline LpBase::Constr operator>=(const LpBase::Value &n,
1797 const LpBase::Constr &c) {
1798 LpBase::Constr tmp(c);
1799 LEMON_ASSERT(isNaN(tmp.upperBound()), "Wrong LP constraint");
1803 ///Create constraint
1805 ///\relates LpBase::Constr
1807 inline LpBase::Constr operator>=(const LpBase::Constr &c,
1808 const LpBase::Value &n)
1810 LpBase::Constr tmp(c);
1811 LEMON_ASSERT(isNaN(tmp.lowerBound()), "Wrong LP constraint");
1818 ///\relates LpBase::DualExpr
1820 inline LpBase::DualExpr operator+(const LpBase::DualExpr &a,
1821 const LpBase::DualExpr &b) {
1822 LpBase::DualExpr tmp(a);
1828 ///\relates LpBase::DualExpr
1830 inline LpBase::DualExpr operator-(const LpBase::DualExpr &a,
1831 const LpBase::DualExpr &b) {
1832 LpBase::DualExpr tmp(a);
1836 ///Multiply with constant
1838 ///\relates LpBase::DualExpr
1840 inline LpBase::DualExpr operator*(const LpBase::DualExpr &a,
1841 const LpBase::Value &b) {
1842 LpBase::DualExpr tmp(a);
1847 ///Multiply with constant
1849 ///\relates LpBase::DualExpr
1851 inline LpBase::DualExpr operator*(const LpBase::Value &a,
1852 const LpBase::DualExpr &b) {
1853 LpBase::DualExpr tmp(b);
1857 ///Divide with constant
1859 ///\relates LpBase::DualExpr
1861 inline LpBase::DualExpr operator/(const LpBase::DualExpr &a,
1862 const LpBase::Value &b) {
1863 LpBase::DualExpr tmp(a);
1868 /// \ingroup lp_group
1870 /// \brief Common base class for LP solvers
1872 /// This class is an abstract base class for LP solvers. This class
1873 /// provides a full interface for set and modify an LP problem,
1874 /// solve it and retrieve the solution. You can use one of the
1875 /// descendants as a concrete implementation, or the \c Lp
1876 /// default LP solver. However, if you would like to handle LP
1877 /// solvers as reference or pointer in a generic way, you can use
1878 /// this class directly.
1879 class LpSolver : virtual public LpBase {
1882 /// The problem types for primal and dual problems
1884 /// = 0. Feasible solution hasn't been found (but may exist).
1886 /// = 1. The problem has no feasible solution.
1888 /// = 2. Feasible solution found.
1890 /// = 3. Optimal solution exists and found.
1892 /// = 4. The cost function is unbounded.
1896 ///The basis status of variables
1898 /// The variable is in the basis
1900 /// The variable is free, but not basic
1902 /// The variable has active lower bound
1904 /// The variable has active upper bound
1906 /// The variable is non-basic and fixed
1912 virtual SolveExitStatus _solve() = 0;
1914 virtual Value _getPrimal(int i) const = 0;
1915 virtual Value _getDual(int i) const = 0;
1917 virtual Value _getPrimalRay(int i) const = 0;
1918 virtual Value _getDualRay(int i) const = 0;
1920 virtual Value _getPrimalValue() const = 0;
1922 virtual VarStatus _getColStatus(int i) const = 0;
1923 virtual VarStatus _getRowStatus(int i) const = 0;
1925 virtual ProblemType _getPrimalType() const = 0;
1926 virtual ProblemType _getDualType() const = 0;
1930 ///Allocate a new LP problem instance
1931 virtual LpSolver* newSolver() const = 0;
1932 ///Make a copy of the LP problem
1933 virtual LpSolver* cloneSolver() const = 0;
1935 ///\name Solve the LP
1939 ///\e Solve the LP problem at hand
1941 ///\return The result of the optimization procedure. Possible
1942 ///values and their meanings can be found in the documentation of
1943 ///\ref SolveExitStatus.
1944 SolveExitStatus solve() { return _solve(); }
1948 ///\name Obtain the Solution
1952 /// The type of the primal problem
1953 ProblemType primalType() const {
1954 return _getPrimalType();
1957 /// The type of the dual problem
1958 ProblemType dualType() const {
1959 return _getDualType();
1962 /// Return the primal value of the column
1964 /// Return the primal value of the column.
1965 /// \pre The problem is solved.
1966 Value primal(Col c) const { return _getPrimal(_cols(id(c))); }
1968 /// Return the primal value of the expression
1970 /// Return the primal value of the expression, i.e. the dot
1971 /// product of the primal solution and the expression.
1972 /// \pre The problem is solved.
1973 Value primal(const Expr& e) const {
1975 for (Expr::ConstCoeffIt c(e); c != INVALID; ++c) {
1976 res += *c * primal(c);
1980 /// Returns a component of the primal ray
1982 /// The primal ray is solution of the modified primal problem,
1983 /// where we change each finite bound to 0, and we looking for a
1984 /// negative objective value in case of minimization, and positive
1985 /// objective value for maximization. If there is such solution,
1986 /// that proofs the unsolvability of the dual problem, and if a
1987 /// feasible primal solution exists, then the unboundness of
1990 /// \pre The problem is solved and the dual problem is infeasible.
1991 /// \note Some solvers does not provide primal ray calculation
1993 Value primalRay(Col c) const { return _getPrimalRay(_cols(id(c))); }
1995 /// Return the dual value of the row
1997 /// Return the dual value of the row.
1998 /// \pre The problem is solved.
1999 Value dual(Row r) const { return _getDual(_rows(id(r))); }
2001 /// Return the dual value of the dual expression
2003 /// Return the dual value of the dual expression, i.e. the dot
2004 /// product of the dual solution and the dual expression.
2005 /// \pre The problem is solved.
2006 Value dual(const DualExpr& e) const {
2008 for (DualExpr::ConstCoeffIt r(e); r != INVALID; ++r) {
2009 res += *r * dual(r);
2014 /// Returns a component of the dual ray
2016 /// The dual ray is solution of the modified primal problem, where
2017 /// we change each finite bound to 0 (i.e. the objective function
2018 /// coefficients in the primal problem), and we looking for a
2019 /// ositive objective value. If there is such solution, that
2020 /// proofs the unsolvability of the primal problem, and if a
2021 /// feasible dual solution exists, then the unboundness of
2024 /// \pre The problem is solved and the primal problem is infeasible.
2025 /// \note Some solvers does not provide dual ray calculation
2027 Value dualRay(Row r) const { return _getDualRay(_rows(id(r))); }
2029 /// Return the basis status of the column
2032 VarStatus colStatus(Col c) const { return _getColStatus(_cols(id(c))); }
2034 /// Return the basis status of the row
2037 VarStatus rowStatus(Row r) const { return _getRowStatus(_rows(id(r))); }
2039 ///The value of the objective function
2042 ///- \ref INF or -\ref INF means either infeasibility or unboundedness
2043 /// of the primal problem, depending on whether we minimize or maximize.
2044 ///- \ref NaN if no primal solution is found.
2045 ///- The (finite) objective value if an optimal solution is found.
2046 Value primal() const { return _getPrimalValue()+obj_const_comp;}
2054 /// \ingroup lp_group
2056 /// \brief Common base class for MIP solvers
2058 /// This class is an abstract base class for MIP solvers. This class
2059 /// provides a full interface for set and modify an MIP problem,
2060 /// solve it and retrieve the solution. You can use one of the
2061 /// descendants as a concrete implementation, or the \c Lp
2062 /// default MIP solver. However, if you would like to handle MIP
2063 /// solvers as reference or pointer in a generic way, you can use
2064 /// this class directly.
2065 class MipSolver : virtual public LpBase {
2068 /// The problem types for MIP problems
2070 /// = 0. Feasible solution hasn't been found (but may exist).
2072 /// = 1. The problem has no feasible solution.
2074 /// = 2. Feasible solution found.
2076 /// = 3. Optimal solution exists and found.
2078 /// = 4. The cost function is unbounded.
2079 ///The Mip or at least the relaxed problem is unbounded.
2083 ///Allocate a new MIP problem instance
2084 virtual MipSolver* newSolver() const = 0;
2085 ///Make a copy of the MIP problem
2086 virtual MipSolver* cloneSolver() const = 0;
2088 ///\name Solve the MIP
2092 /// Solve the MIP problem at hand
2094 ///\return The result of the optimization procedure. Possible
2095 ///values and their meanings can be found in the documentation of
2096 ///\ref SolveExitStatus.
2097 SolveExitStatus solve() { return _solve(); }
2101 ///\name Set Column Type
2104 ///Possible variable (column) types (e.g. real, integer, binary etc.)
2106 /// = 0. Continuous variable (default).
2108 /// = 1. Integer variable.
2112 ///Sets the type of the given column to the given type
2114 ///Sets the type of the given column to the given type.
2116 void colType(Col c, ColTypes col_type) {
2117 _setColType(_cols(id(c)),col_type);
2120 ///Gives back the type of the column.
2122 ///Gives back the type of the column.
2124 ColTypes colType(Col c) const {
2125 return _getColType(_cols(id(c)));
2129 ///\name Obtain the Solution
2133 /// The type of the MIP problem
2134 ProblemType type() const {
2138 /// Return the value of the row in the solution
2140 /// Return the value of the row in the solution.
2141 /// \pre The problem is solved.
2142 Value sol(Col c) const { return _getSol(_cols(id(c))); }
2144 /// Return the value of the expression in the solution
2146 /// Return the value of the expression in the solution, i.e. the
2147 /// dot product of the solution and the expression.
2148 /// \pre The problem is solved.
2149 Value sol(const Expr& e) const {
2151 for (Expr::ConstCoeffIt c(e); c != INVALID; ++c) {
2156 ///The value of the objective function
2159 ///- \ref INF or -\ref INF means either infeasibility or unboundedness
2160 /// of the problem, depending on whether we minimize or maximize.
2161 ///- \ref NaN if no primal solution is found.
2162 ///- The (finite) objective value if an optimal solution is found.
2163 Value solValue() const { return _getSolValue()+obj_const_comp;}
2168 virtual SolveExitStatus _solve() = 0;
2169 virtual ColTypes _getColType(int col) const = 0;
2170 virtual void _setColType(int col, ColTypes col_type) = 0;
2171 virtual ProblemType _getType() const = 0;
2172 virtual Value _getSol(int i) const = 0;
2173 virtual Value _getSolValue() const = 0;
2181 #endif //LEMON_LP_BASE_H