Call the default constructor of the ObserverBase.
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 Research Group on Combinatorial Optimization, 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.
33 ///\ingroup gen_opt_group
36 ///Internal data structure to convert floating id's to fix one's
38 ///\todo This might be implemented to be also usable in other places.
41 std::vector<int> index;
42 std::vector<int> cross;
45 _FixId() : first_free(-1) {};
46 ///Convert a floating id to a fix one
48 ///\param n is a floating id
49 ///\return the corresponding fix id
50 int fixId(int n) {return cross[n];}
51 ///Convert a fix id to a floating one
53 ///\param n is a fix id
54 ///\return the corresponding floating id
55 int floatingId(int n) { return index[n];}
56 ///Add a new floating id.
58 ///\param n is a floating id
59 ///\return the fix id of the new value
60 ///\todo Multiple additions should also be handled.
63 if(n>=int(cross.size())) {
66 cross[n]=index.size();
71 int next=index[first_free];
77 ///\todo Create an own exception type.
78 else throw LogicError(); //floatingId-s must form a continuous range;
82 ///\param n is a fix id
89 for(int i=fl+1;i<int(cross.size());++i) {
95 ///An upper bound on the largest fix id.
97 ///\todo Do we need this?
99 std::size_t maxFixId() { return cross.size()-1; }
103 ///Common base class for LP solvers
105 ///\todo Much more docs
106 ///\ingroup gen_opt_group
112 enum SolveExitStatus {
120 enum SolutionStatus {
121 ///Feasible solution has'n been found (but may exist).
123 ///\todo NOTFOUND might be a better name.
126 ///The problem has no feasible solution
128 ///Feasible solution found
130 ///Optimal solution exists and found
132 ///The cost function is unbounded
134 ///\todo Give a feasible solution and an infinite ray (and the
135 ///corresponding bases)
139 ///The floating point type used by the solver
140 typedef double Value;
141 ///The infinity constant
142 static const Value INF;
143 ///The not a number constant
144 static const Value NaN;
146 ///Refer to a column of the LP.
148 ///This type is used to refer to a column of the LP.
150 ///Its value remains valid and correct even after the addition or erase of
153 ///\todo Document what can one do with a Col (INVALID, comparing,
154 ///it is similar to Node/Edge)
158 friend class LpSolverBase;
160 typedef Value ExprValue;
161 typedef True LpSolverCol;
163 Col(const Invalid&) : id(-1) {}
164 bool operator<(Col c) const {return id<c.id;}
165 bool operator==(Col c) const {return id==c.id;}
166 bool operator!=(Col c) const {return id==c.id;}
169 ///Refer to a row of the LP.
171 ///This type is used to refer to a row of the LP.
173 ///Its value remains valid and correct even after the addition or erase of
176 ///\todo Document what can one do with a Row (INVALID, comparing,
177 ///it is similar to Node/Edge)
181 friend class LpSolverBase;
183 typedef Value ExprValue;
184 typedef True LpSolverRow;
186 Row(const Invalid&) : id(-1) {}
187 typedef True LpSolverRow;
188 bool operator<(Row c) const {return id<c.id;}
189 bool operator==(Row c) const {return id==c.id;}
190 bool operator!=(Row c) const {return id==c.id;}
193 ///Linear expression of variables and a constant component
195 ///This data structure strores a linear expression of the variables
196 ///(\ref Col "Col"s) and also has a constant component.
198 ///There are several ways to access and modify the contents of this
200 ///- Its it fully compatible with \c std::map<Col,double>, so for expamle
201 ///if \c e is an Expr and \c v and \c w are of type \ref Col, then you can
202 ///read and modify the coefficients like
209 ///or you can also iterate through its elements.
212 ///for(LpSolverBase::Expr::iterator i=e.begin();i!=e.end();++i)
215 ///(This code computes the sum of all coefficients).
216 ///- Numbers (<tt>double</tt>'s)
217 ///and variables (\ref Col "Col"s) directly convert to an
218 ///\ref Expr and the usual linear operations are defined so
221 ///2*v-3.12*(v-w/2)+2
222 ///v*2.1+(3*v+(v*12+w+6)*3)/2
224 ///are valid \ref Expr "Expr"essions.
225 ///The usual assignment operations are also defined.
228 ///e+=2*v-3.12*(v-w/2)+2;
232 ///- The constant member can be set and read by \ref constComp()
235 ///double c=e.constComp();
238 ///\note \ref clear() not only sets all coefficients to 0 but also
239 ///clears the constant components.
243 class Expr : public std::map<Col,Value>
246 typedef LpSolverBase::Col Key;
247 typedef LpSolverBase::Value Value;
250 typedef std::map<Col,Value> Base;
254 typedef True IsLinExpression;
256 Expr() : Base(), const_comp(0) { }
258 Expr(const Key &v) : const_comp(0) {
259 Base::insert(std::make_pair(v, 1));
262 Expr(const Value &v) : const_comp(v) {}
264 void set(const Key &v,const Value &c) {
265 Base::insert(std::make_pair(v, c));
268 Value &constComp() { return const_comp; }
270 const Value &constComp() const { return const_comp; }
272 ///Removes the components with zero coefficient.
274 for (Base::iterator i=Base::begin(); i!=Base::end();) {
277 if ((*i).second==0) Base::erase(i);
282 ///Sets all coefficients and the constant component to 0.
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 ///\todo it might be speeded up using "hints"
293 const_comp+=e.const_comp;
297 Expr &operator-=(const Expr &e) {
298 for (Base::const_iterator j=e.begin(); j!=e.end(); ++j)
299 (*this)[j->first]-=j->second;
300 const_comp-=e.const_comp;
304 Expr &operator*=(const Value &c) {
305 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
311 Expr &operator/=(const Value &c) {
312 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
321 ///This data stucture represents a linear constraint in the LP.
322 ///Basically it is a linear expression with a lower or an upper bound
323 ///(or both). These parts of the constraint can be obtained by the member
324 ///functions \ref expr(), \ref lowerBound() and \ref upperBound(),
326 ///There are two ways to construct a constraint.
327 ///- You can set the linear expression and the bounds directly
328 /// by the functions above.
329 ///- The operators <tt>\<=</tt>, <tt>==</tt> and <tt>\>=</tt>
330 /// are defined between expressions, or even between constraints whenever
331 /// it makes sense. Therefore if \c e and \c f are linear expressions and
332 /// \c s and \c t are numbers, then the followings are valid expressions
333 /// and thus they can be used directly e.g. in \ref addRow() whenever
341 ///\warning The validity of a constraint is checked only at run time, so
342 ///e.g. \ref addRow(<tt>x[1]\<=x[2]<=5</tt>) will compile, but will throw a
343 ///\ref LogicError exception.
347 typedef LpSolverBase::Expr Expr;
348 typedef Expr::Key Key;
349 typedef Expr::Value Value;
351 // static const Value INF;
352 // static const Value NaN;
359 Constr() : _expr(), _lb(NaN), _ub(NaN) {}
361 Constr(Value lb,const Expr &e,Value ub) :
362 _expr(e), _lb(lb), _ub(ub) {}
364 Constr(const Expr &e,Value ub) :
365 _expr(e), _lb(NaN), _ub(ub) {}
367 Constr(Value lb,const Expr &e) :
368 _expr(e), _lb(lb), _ub(NaN) {}
370 Constr(const Expr &e) :
371 _expr(e), _lb(NaN), _ub(NaN) {}
379 ///Reference to the linear expression
380 Expr &expr() { return _expr; }
381 ///Cont reference to the linear expression
382 const Expr &expr() const { return _expr; }
383 ///Reference to the lower bound.
386 ///- -\ref INF: the constraint is lower unbounded.
387 ///- -\ref NaN: lower bound has not been set.
388 ///- finite number: the lower bound
389 Value &lowerBound() { return _lb; }
390 ///The const version of \ref lowerBound()
391 const Value &lowerBound() const { return _lb; }
392 ///Reference to the upper bound.
395 ///- -\ref INF: the constraint is upper unbounded.
396 ///- -\ref NaN: upper bound has not been set.
397 ///- finite number: the upper bound
398 Value &upperBound() { return _ub; }
399 ///The const version of \ref upperBound()
400 const Value &upperBound() const { return _ub; }
401 ///Is the constraint lower bounded?
402 bool lowerBounded() const {
404 return isfinite(_lb);
406 ///Is the constraint upper bounded?
407 bool upperBounded() const {
409 return isfinite(_ub);
418 //Abstract virtual functions
419 virtual LpSolverBase &_newLp() = 0;
420 virtual LpSolverBase &_copyLp() = 0;
422 virtual int _addCol() = 0;
423 virtual int _addRow() = 0;
424 virtual void _setRowCoeffs(int i,
427 Value const * values ) = 0;
428 virtual void _setColCoeffs(int i,
431 Value const * values ) = 0;
432 virtual void _setColLowerBound(int i, Value value) = 0;
433 virtual void _setColUpperBound(int i, Value value) = 0;
434 virtual void _setRowLowerBound(int i, Value value) = 0;
435 virtual void _setRowUpperBound(int i, Value value) = 0;
436 virtual void _setObjCoeff(int i, Value obj_coef) = 0;
437 virtual SolveExitStatus _solve() = 0;
438 virtual Value _getPrimal(int i) = 0;
439 virtual Value _getPrimalValue() = 0;
440 virtual SolutionStatus _getPrimalStatus() = 0;
441 virtual void _setMax() = 0;
442 virtual void _setMin() = 0;
444 //Own protected stuff
446 //Constant component of the objective function
447 Value obj_const_comp;
451 ///\bug Unimplemented
457 LpSolverBase() : obj_const_comp(0) {}
460 virtual ~LpSolverBase() {}
462 ///Creates a new LP problem
463 LpSolverBase &newLp() {return _newLp();}
464 ///Make a copy of the LP problem
465 LpSolverBase ©Lp() {return _copyLp();}
467 ///\name Build up and modify of the LP
471 ///Add a new empty column (i.e a new variable) to the LP
472 Col addCol() { Col c; c.id=cols.insert(_addCol()); return c;}
474 ///\brief Adds several new columns
475 ///(i.e a variables) at once
477 ///This magic function takes a container as its argument
478 ///and fills its elements
479 ///with new columns (i.e. variables)
481 ///- a standard STL compatible iterable container with
482 ///\ref Col as its \c values_type
485 ///std::vector<LpSolverBase::Col>
486 ///std::list<LpSolverBase::Col>
488 ///- a standard STL compatible iterable container with
489 ///\ref Col as its \c mapped_type
492 ///std::map<AnyType,LpSolverBase::Col>
494 ///- an iterable lemon \ref concept::WriteMap "write map" like
496 ///ListGraph::NodeMap<LpSolverBase::Col>
497 ///ListGraph::EdgeMap<LpSolverBase::Col>
499 ///\return The number of the created column.
502 int addColSet(T &t) { return 0;}
505 typename enable_if<typename T::value_type::LpSolverCol,int>::type
506 addColSet(T &t,dummy<0> = 0) {
508 for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addCol();s++;}
512 typename enable_if<typename T::value_type::second_type::LpSolverCol,
514 addColSet(T &t,dummy<1> = 1) {
516 for(typename T::iterator i=t.begin();i!=t.end();++i) {
523 typename enable_if<typename T::ValueSet::value_type::LpSolverCol,
525 addColSet(T &t,dummy<2> = 2) {
526 ///\bug <tt>return addColSet(t.valueSet());</tt> should also work.
528 for(typename T::ValueSet::iterator i=t.valueSet().begin();
529 i!=t.valueSet().end();
539 ///Add a new empty row (i.e a new constaint) to the LP
541 ///This function adds a new empty row (i.e a new constaint) to the LP.
542 ///\return The created row
543 Row addRow() { Row r; r.id=rows.insert(_addRow()); return r;}
545 ///Set a row (i.e a constaint) of the LP
547 ///\param r is the row to be modified
548 ///\param l is lower bound (-\ref INF means no bound)
549 ///\param e is a linear expression (see \ref Expr)
550 ///\param u is the upper bound (\ref INF means no bound)
551 ///\bug This is a temportary function. The interface will change to
553 ///\todo Option to control whether a constraint with a single variable is
555 void setRow(Row r, Value l,const Expr &e, Value u) {
556 std::vector<int> indices;
557 std::vector<Value> values;
558 indices.push_back(0);
560 for(Expr::const_iterator i=e.begin(); i!=e.end(); ++i)
561 if((*i).second!=0) { ///\bug EPSILON would be necessary here!!!
562 indices.push_back(cols.floatingId((*i).first.id));
563 values.push_back((*i).second);
565 _setRowCoeffs(rows.floatingId(r.id),indices.size()-1,
566 &indices[0],&values[0]);
567 _setRowLowerBound(rows.floatingId(r.id),l-e.constComp());
568 _setRowUpperBound(rows.floatingId(r.id),u-e.constComp());
571 ///Set a row (i.e a constaint) of the LP
573 ///\param r is the row to be modified
574 ///\param c is a linear expression (see \ref Constr)
575 void setRow(Row r, const Constr &c) {
577 c.lowerBounded()?c.lowerBound():-INF,
579 c.upperBounded()?c.upperBound():INF);
582 ///Add a new row (i.e a new constaint) to the LP
584 ///\param l is the lower bound (-\ref INF means no bound)
585 ///\param e is a linear expression (see \ref Expr)
586 ///\param u is the upper bound (\ref INF means no bound)
587 ///\return The created row.
588 ///\bug This is a temportary function. The interface will change to
590 Row addRow(Value l,const Expr &e, Value u) {
596 ///Add a new row (i.e a new constaint) to the LP
598 ///\param c is a linear expression (see \ref Constr)
599 ///\return The created row.
600 Row addRow(const Constr &c) {
606 /// Set the lower bound of a column (i.e a variable)
608 /// The upper bound of a variable (column) has to be given by an
609 /// extended number of type Value, i.e. a finite number of type
610 /// Value or -\ref INF.
611 void colLowerBound(Col c, Value value) {
612 _setColLowerBound(cols.floatingId(c.id),value);
614 /// Set the upper bound of a column (i.e a variable)
616 /// The upper bound of a variable (column) has to be given by an
617 /// extended number of type Value, i.e. a finite number of type
618 /// Value or \ref INF.
619 void colUpperBound(Col c, Value value) {
620 _setColUpperBound(cols.floatingId(c.id),value);
622 /// Set the lower and the upper bounds of a column (i.e a variable)
624 /// The lower and the upper bounds of
625 /// a variable (column) have to be given by an
626 /// extended number of type Value, i.e. a finite number of type
627 /// Value, -\ref INF or \ref INF.
628 void colBounds(Col c, Value lower, Value upper) {
629 _setColLowerBound(cols.floatingId(c.id),lower);
630 _setColUpperBound(cols.floatingId(c.id),upper);
633 /// Set the lower bound of a row (i.e a constraint)
635 /// The lower bound of a linear expression (row) has to be given by an
636 /// extended number of type Value, i.e. a finite number of type
637 /// Value or -\ref INF.
638 void rowLowerBound(Row r, Value value) {
639 _setRowLowerBound(rows.floatingId(r.id),value);
641 /// Set the upper bound of a row (i.e a constraint)
643 /// The upper bound of a linear expression (row) has to be given by an
644 /// extended number of type Value, i.e. a finite number of type
645 /// Value or \ref INF.
646 void rowUpperBound(Row r, Value value) {
647 _setRowUpperBound(rows.floatingId(r.id),value);
649 /// Set the lower and the upper bounds of a row (i.e a variable)
651 /// The lower and the upper bounds of
652 /// a constraint (row) have to be given by an
653 /// extended number of type Value, i.e. a finite number of type
654 /// Value, -\ref INF or \ref INF.
655 void rowBounds(Row c, Value lower, Value upper) {
656 _setRowLowerBound(rows.floatingId(c.id),lower);
657 _setRowUpperBound(rows.floatingId(c.id),upper);
660 ///Set an element of the objective function
661 void objCoeff(Col c, Value v) {_setObjCoeff(cols.floatingId(c.id),v); };
662 ///Set the objective function
664 ///\param e is a linear expression of type \ref Expr.
665 ///\bug The previous objective function is not cleared!
666 void setObj(Expr e) {
668 for (Expr::iterator i=e.begin(); i!=e.end(); ++i)
669 objCoeff((*i).first,(*i).second);
670 obj_const_comp=e.constComp();
674 void max() { _setMax(); }
676 void min() { _setMin(); }
682 ///\name Solve the LP
687 SolveExitStatus solve() { return _solve(); }
691 ///\name Obtain the solution
696 SolutionStatus primalStatus() {
697 return _getPrimalStatus();
701 Value primal(Col c) { return _getPrimal(cols.floatingId(c.id)); }
706 ///- \ref INF or -\ref INF means either infeasibility or unboundedness
707 /// of the primal problem, depending on whether we minimize or maximize.
708 ///- \ref NaN if no primal solution is found.
709 ///- The (finite) objective value if an optimal solution is found.
710 Value primalValue() { return _getPrimalValue()+obj_const_comp;}
717 ///\relates LpSolverBase::Expr
719 inline LpSolverBase::Expr operator+(const LpSolverBase::Expr &a,
720 const LpSolverBase::Expr &b)
722 LpSolverBase::Expr tmp(a);
723 tmp+=b; ///\todo Doesn't STL have some special 'merge' algorithm?
728 ///\relates LpSolverBase::Expr
730 inline LpSolverBase::Expr operator-(const LpSolverBase::Expr &a,
731 const LpSolverBase::Expr &b)
733 LpSolverBase::Expr tmp(a);
734 tmp-=b; ///\todo Doesn't STL have some special 'merge' algorithm?
739 ///\relates LpSolverBase::Expr
741 inline LpSolverBase::Expr operator*(const LpSolverBase::Expr &a,
742 const LpSolverBase::Value &b)
744 LpSolverBase::Expr tmp(a);
745 tmp*=b; ///\todo Doesn't STL have some special 'merge' algorithm?
751 ///\relates LpSolverBase::Expr
753 inline LpSolverBase::Expr operator*(const LpSolverBase::Value &a,
754 const LpSolverBase::Expr &b)
756 LpSolverBase::Expr tmp(b);
757 tmp*=a; ///\todo Doesn't STL have some special 'merge' algorithm?
762 ///\relates LpSolverBase::Expr
764 inline LpSolverBase::Expr operator/(const LpSolverBase::Expr &a,
765 const LpSolverBase::Value &b)
767 LpSolverBase::Expr tmp(a);
768 tmp/=b; ///\todo Doesn't STL have some special 'merge' algorithm?
774 ///\relates LpSolverBase::Constr
776 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
777 const LpSolverBase::Expr &f)
779 return LpSolverBase::Constr(-LpSolverBase::INF,e-f,0);
784 ///\relates LpSolverBase::Constr
786 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &e,
787 const LpSolverBase::Expr &f)
789 return LpSolverBase::Constr(e,f);
794 ///\relates LpSolverBase::Constr
796 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
797 const LpSolverBase::Value &f)
799 return LpSolverBase::Constr(e,f);
804 ///\relates LpSolverBase::Constr
806 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
807 const LpSolverBase::Expr &f)
809 return LpSolverBase::Constr(-LpSolverBase::INF,f-e,0);
815 ///\relates LpSolverBase::Constr
817 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &e,
818 const LpSolverBase::Expr &f)
820 return LpSolverBase::Constr(f,e);
826 ///\relates LpSolverBase::Constr
828 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
829 const LpSolverBase::Value &f)
831 return LpSolverBase::Constr(f,e);
836 ///\relates LpSolverBase::Constr
838 inline LpSolverBase::Constr operator==(const LpSolverBase::Expr &e,
839 const LpSolverBase::Expr &f)
841 return LpSolverBase::Constr(0,e-f,0);
846 ///\relates LpSolverBase::Constr
848 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &n,
849 const LpSolverBase::Constr&c)
851 LpSolverBase::Constr tmp(c);
852 ///\todo Create an own exception type.
853 if(!isnan(tmp.lowerBound())) throw LogicError();
854 else tmp.lowerBound()=n;
859 ///\relates LpSolverBase::Constr
861 inline LpSolverBase::Constr operator<=(const LpSolverBase::Constr& c,
862 const LpSolverBase::Value &n)
864 LpSolverBase::Constr tmp(c);
865 ///\todo Create an own exception type.
866 if(!isnan(tmp.upperBound())) throw LogicError();
867 else tmp.upperBound()=n;
873 ///\relates LpSolverBase::Constr
875 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &n,
876 const LpSolverBase::Constr&c)
878 LpSolverBase::Constr tmp(c);
879 ///\todo Create an own exception type.
880 if(!isnan(tmp.upperBound())) throw LogicError();
881 else tmp.upperBound()=n;
886 ///\relates LpSolverBase::Constr
888 inline LpSolverBase::Constr operator>=(const LpSolverBase::Constr& c,
889 const LpSolverBase::Value &n)
891 LpSolverBase::Constr tmp(c);
892 ///\todo Create an own exception type.
893 if(!isnan(tmp.lowerBound())) throw LogicError();
894 else tmp.lowerBound()=n;
901 #endif //LEMON_LP_BASE_H