Makefile has changed.
2 * src/lemon/lp_base.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef LEMON_LP_BASE_H
18 #define LEMON_LP_BASE_H
25 #include<lemon/utility.h>
26 #include<lemon/error.h>
27 #include<lemon/invalid.h>
29 //#include"lin_expr.h"
32 ///\brief The interface of the LP solver interface.
35 ///Internal data structure to convert floating id's to fix one's
37 ///\todo This might be implemented to be also usable in other places.
40 std::vector<int> index;
41 std::vector<int> cross;
44 _FixId() : first_free(-1) {};
45 ///Convert a floating id to a fix one
47 ///\param n is a floating id
48 ///\return the corresponding fix id
49 int fixId(int n) {return cross[n];}
50 ///Convert a fix id to a floating one
52 ///\param n is a fix id
53 ///\return the corresponding floating id
54 int floatingId(int n) { return index[n];}
55 ///Add a new floating id.
57 ///\param n is a floating id
58 ///\return the fix id of the new value
59 ///\todo Multiple additions should also be handled.
62 if(n>=int(cross.size())) {
65 cross[n]=index.size();
70 int next=index[first_free];
76 ///\todo Create an own exception type.
77 else throw LogicError(); //floatingId-s must form a continuous range;
81 ///\param n is a fix id
88 for(int i=fl+1;i<int(cross.size());++i) {
94 ///An upper bound on the largest fix id.
96 ///\todo Do we need this?
98 std::size_t maxFixId() { return cross.size()-1; }
102 ///Common base class for LP solvers
108 enum SolveExitStatus {
116 enum SolutionStatus {
117 ///Feasible solution has'n been found (but may exist).
119 ///\todo NOTFOUND might be a better name.
122 ///The problem has no feasible solution
124 ///Feasible solution found
126 ///Optimal solution exists and found
128 ///The cost function is unbounded
130 ///\todo Give a feasible solution and an infinite ray (and the
131 ///corresponding bases)
135 ///The floating point type used by the solver
136 typedef double Value;
137 ///The infinity constant
138 static const Value INF;
139 ///The not a number constant
140 static const Value NaN;
142 ///Refer to a column of the LP.
144 ///This type is used to refer to a column of the LP.
146 ///Its value remains valid and correct even after the addition or erase of
149 ///\todo Document what can one do with a Col (INVALID, comparing,
150 ///it is similar to Node/Edge)
154 friend class LpSolverBase;
156 typedef Value ExprValue;
157 typedef True LpSolverCol;
159 Col(const Invalid&) : id(-1) {}
160 bool operator<(Col c) const {return id<c.id;}
161 bool operator==(Col c) const {return id==c.id;}
162 bool operator!=(Col c) const {return id==c.id;}
165 ///Refer to a row of the LP.
167 ///This type is used to refer to a row of the LP.
169 ///Its value remains valid and correct even after the addition or erase of
172 ///\todo Document what can one do with a Row (INVALID, comparing,
173 ///it is similar to Node/Edge)
177 friend class LpSolverBase;
179 typedef Value ExprValue;
180 typedef True LpSolverRow;
182 Row(const Invalid&) : id(-1) {}
183 typedef True LpSolverRow;
184 bool operator<(Row c) const {return id<c.id;}
185 bool operator==(Row c) const {return id==c.id;}
186 bool operator!=(Row c) const {return id==c.id;}
189 ///Linear expression of variables and a constant component
191 ///This data structure strores a linear expression of the variables
192 ///(\ref Col "Col"s) and also has a constant component.
194 ///There are several ways to access and modify the contents of this
196 ///- Its it fully compatible with \c std::map<Col,double>, so for expamle
197 ///if \c e is an Expr and \c v and \c w are of type \ref Col then you can
198 ///read and modify the coefficients like
205 ///or you can also iterate through its elements.
208 ///for(LpSolverBase::Expr::iterator i=e.begin();i!=e.end();++i)
211 ///(This code computes the sum of all coefficients).
212 ///- Numbers (<tt>double</tt>'s)
213 ///and variables (\ref Col "Col"s) directly convert to an
214 ///\ref Expr and the usual linear operations are defined so
217 ///2*v-3.12*(v-w/2)+2
218 ///v*2.1+(3*v+(v*12+w+6)*3)/2
220 ///are valid expressions. The usual assignment operations are also defined.
223 ///e+=2*v-3.12*(v-w/2)+2;
227 ///- The constant member can be set and read by \ref constComp()
230 ///double c=e.constComp();
233 ///\note that \ref clear() not only sets all coefficients to 0 but also
234 ///clears the constant components.
235 class Expr : public std::map<Col,Value>
238 typedef LpSolverBase::Col Key;
239 typedef LpSolverBase::Value Value;
242 typedef std::map<Col,Value> Base;
246 typedef True IsLinExpression;
248 Expr() : Base(), const_comp(0) { }
250 Expr(const Key &v) : const_comp(0) {
251 Base::insert(std::make_pair(v, 1));
254 Expr(const Value &v) : const_comp(v) {}
256 void set(const Key &v,const Value &c) {
257 Base::insert(std::make_pair(v, c));
260 Value &constComp() { return const_comp; }
262 const Value &constComp() const { return const_comp; }
264 ///Removes the components with zero coefficient.
266 for (Base::iterator i=Base::begin(); i!=Base::end();) {
269 if ((*i).second==0) Base::erase(i);
274 ///Sets all coefficients and the constant component to 0.
281 Expr &operator+=(const Expr &e) {
282 for (Base::const_iterator j=e.begin(); j!=e.end(); ++j)
283 (*this)[j->first]+=j->second;
284 ///\todo it might be speeded up using "hints"
285 const_comp+=e.const_comp;
289 Expr &operator-=(const Expr &e) {
290 for (Base::const_iterator j=e.begin(); j!=e.end(); ++j)
291 (*this)[j->first]-=j->second;
292 const_comp-=e.const_comp;
296 Expr &operator*=(const Value &c) {
297 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
303 Expr &operator/=(const Value &c) {
304 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
312 //typedef LinConstr<Expr> Constr;
316 typedef LpSolverBase::Expr Expr;
317 typedef Expr::Key Key;
318 typedef Expr::Value Value;
320 static const Value INF;
321 static const Value NaN;
322 // static const Value INF=0;
323 // static const Value NaN=1;
330 Constr() : _expr(), _lb(NaN), _ub(NaN) {}
332 Constr(Value lb,const Expr &e,Value ub) :
333 _expr(e), _lb(lb), _ub(ub) {}
335 Constr(const Expr &e,Value ub) :
336 _expr(e), _lb(NaN), _ub(ub) {}
338 Constr(Value lb,const Expr &e) :
339 _expr(e), _lb(lb), _ub(NaN) {}
341 Constr(const Expr &e) :
342 _expr(e), _lb(NaN), _ub(NaN) {}
350 Expr &expr() { return _expr; }
352 const Expr &expr() const { return _expr; }
354 Value &lowerBound() { return _lb; }
356 const Value &lowerBound() const { return _lb; }
358 Value &upperBound() { return _ub; }
360 const Value &upperBound() const { return _ub; }
362 bool lowerBounded() const {
364 return isfinite(_lb);
367 bool upperBounded() const {
369 return isfinite(_ub);
378 virtual int _addCol() = 0;
379 virtual int _addRow() = 0;
380 virtual void _setRowCoeffs(int i,
383 Value const * values ) = 0;
384 virtual void _setColCoeffs(int i,
387 Value const * values ) = 0;
388 virtual void _setColLowerBound(int i, Value value) = 0;
389 virtual void _setColUpperBound(int i, Value value) = 0;
390 virtual void _setRowLowerBound(int i, Value value) = 0;
391 virtual void _setRowUpperBound(int i, Value value) = 0;
392 virtual void _setObjCoeff(int i, Value obj_coef) = 0;
393 virtual SolveExitStatus _solve() = 0;
394 virtual Value _getPrimal(int i) = 0;
395 virtual Value _getPrimalValue() = 0;
396 virtual SolutionStatus _getPrimalStatus() = 0;
397 virtual void _setMax() = 0;
398 virtual void _setMin() = 0;
406 virtual ~LpSolverBase() {}
408 ///\name Build up and modify of the LP
412 ///Add a new empty column (i.e a new variable) to the LP
413 Col addCol() { Col c; c.id=cols.insert(_addCol()); return c;}
415 ///\brief Adds several new columns
416 ///(i.e a variables) at once
418 ///This magic function takes a container as its argument
419 ///and fills its elements
420 ///with new columns (i.e. variables)
422 ///- a standard STL compatible iterable container with
423 ///\ref Col as its \c values_type
426 ///std::vector<LpSolverBase::Col>
427 ///std::list<LpSolverBase::Col>
429 ///- a standard STL compatible iterable container with
430 ///\ref Col as its \c mapped_type
433 ///std::map<AnyStatus,LpSolverBase::Col>
435 ///- an iterable lemon \ref concept::WriteMap "write map" like
437 ///ListGraph::NodeMap<LpSolverBase::Col>
438 ///ListGraph::EdgeMap<LpSolverBase::Col>
440 ///\return The number of the created column.
441 ///\bug Iterable nodemap hasn't been implemented yet.
444 int addColSet(T &t) { return 0;}
447 typename enable_if<typename T::value_type::LpSolverCol,int>::type
448 addColSet(T &t,dummy<0> = 0) {
450 for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addCol();s++;}
454 typename enable_if<typename T::value_type::second_type::LpSolverCol,
456 addColSet(T &t,dummy<1> = 1) {
458 for(typename T::iterator i=t.begin();i!=t.end();++i) {
465 typename enable_if<typename T::ValueSet::value_type::LpSolverCol,
467 addColSet(T &t,dummy<2> = 2) {
468 ///\bug <tt>return addColSet(t.valueSet());</tt> should also work.
470 for(typename T::ValueSet::iterator i=t.valueSet().begin();
471 i!=t.valueSet().end();
481 ///Add a new empty row (i.e a new constaint) to the LP
483 ///This function adds a new empty row (i.e a new constaint) to the LP.
484 ///\return The created row
485 Row addRow() { Row r; r.id=rows.insert(_addRow()); return r;}
487 ///Set a row (i.e a constaint) of the LP
489 ///\param r is the row to be modified
490 ///\param l is lower bound (-\ref INF means no bound)
491 ///\param e is a linear expression (see \ref Expr)
492 ///\param u is the upper bound (\ref INF means no bound)
493 ///\bug This is a temportary function. The interface will change to
495 void setRow(Row r, Value l,const Expr &e, Value u) {
496 std::vector<int> indices;
497 std::vector<Value> values;
498 indices.push_back(0);
500 for(Expr::const_iterator i=e.begin(); i!=e.end(); ++i)
501 if((*i).second!=0) { ///\bug EPSILON would be necessary here!!!
502 indices.push_back(cols.floatingId((*i).first.id));
503 values.push_back((*i).second);
505 _setRowCoeffs(rows.floatingId(r.id),indices.size()-1,
506 &indices[0],&values[0]);
507 _setRowLowerBound(rows.floatingId(r.id),l-e.constComp());
508 _setRowUpperBound(rows.floatingId(r.id),u-e.constComp());
511 ///Set a row (i.e a constaint) of the LP
513 ///\param r is the row to be modified
514 ///\param c is a linear expression (see \ref Constr)
515 void setRow(Row r, const Constr &c) {
517 c.lowerBounded()?c.lowerBound():-INF,
519 c.upperBounded()?c.upperBound():INF);
522 ///Add a new row (i.e a new constaint) to the LP
524 ///\param l is the lower bound (-\ref INF means no bound)
525 ///\param e is a linear expression (see \ref Expr)
526 ///\param u is the upper bound (\ref INF means no bound)
527 ///\return The created row.
528 ///\bug This is a temportary function. The interface will change to
530 Row addRow(Value l,const Expr &e, Value u) {
536 ///Add a new row (i.e a new constaint) to the LP
538 ///\param c is a linear expression (see \ref Constr)
539 ///\return The created row.
540 Row addRow(const Constr &c) {
546 /// Set the lower bound of a column (i.e a variable)
548 /// The upper bound of a variable (column) has to be given by an
549 /// extended number of type Value, i.e. a finite number of type
550 /// Value or -\ref INF.
551 void colLowerBound(Col c, Value value) {
552 _setColLowerBound(cols.floatingId(c.id),value);
554 /// Set the upper bound of a column (i.e a variable)
556 /// The upper bound of a variable (column) has to be given by an
557 /// extended number of type Value, i.e. a finite number of type
558 /// Value or \ref INF.
559 void colUpperBound(Col c, Value value) {
560 _setColUpperBound(cols.floatingId(c.id),value);
562 /// Set the lower and the upper bounds of a column (i.e a variable)
564 /// The lower and the upper bounds of
565 /// a variable (column) have to be given by an
566 /// extended number of type Value, i.e. a finite number of type
567 /// Value, -\ref INF or \ref INF.
568 void colBounds(Col c, Value lower, Value upper) {
569 _setColLowerBound(cols.floatingId(c.id),lower);
570 _setColUpperBound(cols.floatingId(c.id),upper);
573 /// Set the lower bound of a row (i.e a constraint)
575 /// The lower bound of a linear expression (row) has to be given by an
576 /// extended number of type Value, i.e. a finite number of type
577 /// Value or -\ref INF.
578 void rowLowerBound(Row r, Value value) {
579 _setRowLowerBound(rows.floatingId(r.id),value);
581 /// Set the upper bound of a row (i.e a constraint)
583 /// The upper bound of a linear expression (row) has to be given by an
584 /// extended number of type Value, i.e. a finite number of type
585 /// Value or \ref INF.
586 void rowUpperBound(Row r, Value value) {
587 _setRowUpperBound(rows.floatingId(r.id),value);
589 /// Set the lower and the upper bounds of a row (i.e a variable)
591 /// The lower and the upper bounds of
592 /// a constraint (row) have to be given by an
593 /// extended number of type Value, i.e. a finite number of type
594 /// Value, -\ref INF or \ref INF.
595 void rowBounds(Row c, Value lower, Value upper) {
596 _setRowLowerBound(rows.floatingId(c.id),lower);
597 _setRowUpperBound(rows.floatingId(c.id),upper);
600 ///Set an element of the objective function
601 void objCoeff(Col c, Value v) {_setObjCoeff(cols.floatingId(c.id),v); };
602 ///Set the objective function
604 ///\param e is a linear expression of type \ref Expr.
605 ///\todo What to do with the constant component?
606 void setObj(Expr e) {
608 for (Expr::iterator i=e.begin(); i!=e.end(); ++i)
609 objCoeff((*i).first,(*i).second);
613 void max() { _setMax(); }
615 void min() { _setMin(); }
621 ///\name Solve the LP
626 SolveExitStatus solve() { return _solve(); }
630 ///\name Obtain the solution
635 SolutionStatus primalStatus() {
636 return _getPrimalStatus();
640 Value primal(Col c) { return _getPrimal(cols.floatingId(c.id)); }
645 ///- \ref INF or -\ref INF means either infeasibility or unboundedness
646 /// of the primal problem, depending on whether we minimize or maximize.
647 ///- \ref NAN if no primal solution is found.
648 ///- The (finite) objective value if an optimal solution is found.
649 Value primalValue() { return _getPrimalValue();}
656 ///\relates LpSolverBase::Expr
658 inline LpSolverBase::Expr operator+(const LpSolverBase::Expr &a,
659 const LpSolverBase::Expr &b)
661 LpSolverBase::Expr tmp(a);
662 tmp+=b; ///\todo Don't STL have some special 'merge' algorithm?
667 ///\relates LpSolverBase::Expr
669 inline LpSolverBase::Expr operator-(const LpSolverBase::Expr &a,
670 const LpSolverBase::Expr &b)
672 LpSolverBase::Expr tmp(a);
673 tmp-=b; ///\todo Don't STL have some special 'merge' algorithm?
678 ///\relates LpSolverBase::Expr
680 inline LpSolverBase::Expr operator*(const LpSolverBase::Expr &a,
681 const LpSolverBase::Value &b)
683 LpSolverBase::Expr tmp(a);
684 tmp*=b; ///\todo Don't STL have some special 'merge' algorithm?
690 ///\relates LpSolverBase::Expr
692 inline LpSolverBase::Expr operator*(const LpSolverBase::Value &a,
693 const LpSolverBase::Expr &b)
695 LpSolverBase::Expr tmp(b);
696 tmp*=a; ///\todo Don't STL have some special 'merge' algorithm?
701 ///\relates LpSolverBase::Expr
703 inline LpSolverBase::Expr operator/(const LpSolverBase::Expr &a,
704 const LpSolverBase::Value &b)
706 LpSolverBase::Expr tmp(a);
707 tmp/=b; ///\todo Don't STL have some special 'merge' algorithm?
713 ///\relates LpSolverBase::Constr
715 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
716 const LpSolverBase::Expr &f)
718 return LpSolverBase::Constr(-LpSolverBase::INF,e-f,0);
723 ///\relates LpSolverBase::Constr
725 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &e,
726 const LpSolverBase::Expr &f)
728 return LpSolverBase::Constr(e,f);
733 ///\relates LpSolverBase::Constr
735 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
736 const LpSolverBase::Value &f)
738 return LpSolverBase::Constr(e,f);
743 ///\relates LpSolverBase::Constr
745 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
746 const LpSolverBase::Expr &f)
748 return LpSolverBase::Constr(-LpSolverBase::INF,f-e,0);
754 ///\relates LpSolverBase::Constr
756 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &e,
757 const LpSolverBase::Expr &f)
759 return LpSolverBase::Constr(f,e);
765 ///\relates LpSolverBase::Constr
767 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
768 const LpSolverBase::Value &f)
770 return LpSolverBase::Constr(f,e);
775 ///\relates LpSolverBase::Constr
777 inline LpSolverBase::Constr operator==(const LpSolverBase::Expr &e,
778 const LpSolverBase::Expr &f)
780 return LpSolverBase::Constr(0,e-f,0);
785 ///\relates LpSolverBase::Constr
787 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &n,
788 const LpSolverBase::Constr&c)
790 LpSolverBase::Constr tmp(c);
791 ///\todo Create an own exception type.
792 if(!isnan(tmp.lowerBound())) throw LogicError();
793 else tmp.lowerBound()=n;
798 ///\relates LpSolverBase::Constr
800 inline LpSolverBase::Constr operator<=(const LpSolverBase::Constr& c,
801 const LpSolverBase::Value &n)
803 LpSolverBase::Constr tmp(c);
804 ///\todo Create an own exception type.
805 if(!isnan(tmp.upperBound())) throw LogicError();
806 else tmp.upperBound()=n;
812 ///\relates LpSolverBase::Constr
814 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &n,
815 const LpSolverBase::Constr&c)
817 LpSolverBase::Constr tmp(c);
818 ///\todo Create an own exception type.
819 if(!isnan(tmp.upperBound())) throw LogicError();
820 else tmp.upperBound()=n;
825 ///\relates LpSolverBase::Constr
827 inline LpSolverBase::Constr operator>=(const LpSolverBase::Constr& c,
828 const LpSolverBase::Value &n)
830 LpSolverBase::Constr tmp(c);
831 ///\todo Create an own exception type.
832 if(!isnan(tmp.lowerBound())) throw LogicError();
833 else tmp.lowerBound()=n;
840 #endif //LEMON_LP_BASE_H