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
119 ///The floating point type used by the solver
120 typedef double Value;
121 ///The infinity constant
122 static const Value INF;
123 ///The not a number constant
124 static const Value NaN;
126 ///Refer to a column of the LP.
128 ///This type is used to refer to a column of the LP.
130 ///Its value remains valid and correct even after the addition or erase of
133 ///\todo Document what can one do with a Col (INVALID, comparing,
134 ///it is similar to Node/Edge)
138 friend class LpSolverBase;
140 typedef Value ExprValue;
141 typedef True LpSolverCol;
143 Col(const Invalid&) : id(-1) {}
144 bool operator<(Col c) const {return id<c.id;}
145 bool operator==(Col c) const {return id==c.id;}
146 bool operator!=(Col c) const {return id==c.id;}
149 ///Refer to a row of the LP.
151 ///This type is used to refer to a row of the LP.
153 ///Its value remains valid and correct even after the addition or erase of
156 ///\todo Document what can one do with a Row (INVALID, comparing,
157 ///it is similar to Node/Edge)
161 friend class LpSolverBase;
163 typedef Value ExprValue;
164 typedef True LpSolverRow;
166 Row(const Invalid&) : id(-1) {}
167 typedef True LpSolverRow;
168 bool operator<(Row c) const {return id<c.id;}
169 bool operator==(Row c) const {return id==c.id;}
170 bool operator!=(Row c) const {return id==c.id;}
173 ///Linear expression of variables and a constant component
175 ///This data structure strores a linear expression of the variables
176 ///(\ref Col "Col"s) and also has a constant component.
178 ///There are several ways to access and modify the contents of this
180 ///- Its it fully compatible with \c std::map<Col,double>, so for expamle
181 ///if \c e is an Expr and \c v and \c w are of type \ref Col then you can
182 ///read and modify the coefficients like
189 ///or you can also iterate through its elements.
192 ///for(LpSolverBase::Expr::iterator i=e.begin();i!=e.end();++i)
195 ///(This code computes the sum of all coefficients).
196 ///- Numbers (<tt>double</tt>'s)
197 ///and variables (\ref Col "Col"s) directly convert to an
198 ///\ref Expr and the usual linear operations are defined so
201 ///2*v-3.12*(v-w/2)+2
202 ///v*2.1+(3*v+(v*12+w+6)*3)/2
204 ///are valid expressions. The usual assignment operations are also defined.
207 ///e+=2*v-3.12*(v-w/2)+2;
211 ///- The constant member can be set and read by \ref constComp()
214 ///double c=e.constComp();
217 ///\note that \ref clear() not only sets all coefficients to 0 but also
218 ///clears the constant components.
219 class Expr : public std::map<Col,Value>
222 typedef LpSolverBase::Col Key;
223 typedef LpSolverBase::Value Value;
226 typedef std::map<Col,Value> Base;
230 typedef True IsLinExpression;
232 Expr() : Base(), const_comp(0) { }
234 Expr(const Key &v) : const_comp(0) {
235 Base::insert(std::make_pair(v, 1));
238 Expr(const Value &v) : const_comp(v) {}
240 void set(const Key &v,const Value &c) {
241 Base::insert(std::make_pair(v, c));
244 Value &constComp() { return const_comp; }
246 const Value &constComp() const { return const_comp; }
248 ///Removes the components with zero coefficient.
250 for (Base::iterator i=Base::begin(); i!=Base::end();) {
253 if ((*i).second==0) Base::erase(i);
258 ///Sets all coefficients and the constant component to 0.
265 Expr &operator+=(const Expr &e) {
266 for (Base::const_iterator j=e.begin(); j!=e.end(); ++j)
267 (*this)[j->first]+=j->second;
268 ///\todo it might be speeded up using "hints"
269 const_comp+=e.const_comp;
273 Expr &operator-=(const Expr &e) {
274 for (Base::const_iterator j=e.begin(); j!=e.end(); ++j)
275 (*this)[j->first]-=j->second;
276 const_comp-=e.const_comp;
280 Expr &operator*=(const Value &c) {
281 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
287 Expr &operator/=(const Value &c) {
288 for (Base::iterator j=Base::begin(); j!=Base::end(); ++j)
296 //typedef LinConstr<Expr> Constr;
300 typedef LpSolverBase::Expr Expr;
301 typedef Expr::Key Key;
302 typedef Expr::Value Value;
304 static const Value INF;
305 static const Value NaN;
306 // static const Value INF=0;
307 // static const Value NaN=1;
314 Constr() : _expr(), _lb(NaN), _ub(NaN) {}
316 Constr(Value lb,const Expr &e,Value ub) :
317 _expr(e), _lb(lb), _ub(ub) {}
319 Constr(const Expr &e,Value ub) :
320 _expr(e), _lb(NaN), _ub(ub) {}
322 Constr(Value lb,const Expr &e) :
323 _expr(e), _lb(lb), _ub(NaN) {}
325 Constr(const Expr &e) :
326 _expr(e), _lb(NaN), _ub(NaN) {}
334 Expr &expr() { return _expr; }
336 const Expr &expr() const { return _expr; }
338 Value &lowerBound() { return _lb; }
340 const Value &lowerBound() const { return _lb; }
342 Value &upperBound() { return _ub; }
344 const Value &upperBound() const { return _ub; }
346 bool lowerBounded() const { return std::isfinite(_lb); }
348 bool upperBounded() const { return std::isfinite(_ub); }
357 virtual int _addCol() = 0;
359 virtual int _addRow() = 0;
362 /// \warning Arrays are indexed from 1 (datum at index 0 is ignored)
364 virtual void _setRowCoeffs(int i,
367 Value const * values ) = 0;
370 /// \warning Arrays are indexed from 1 (datum at index 0 is ignored)
372 virtual void _setColCoeffs(int i,
375 Value const * values ) = 0;
379 /// The lower bound of a variable (column) have to be given by an
380 /// extended number of type Value, i.e. a finite number of type
381 /// Value or -\ref INF.
382 virtual void _setColLowerBound(int i, Value value) = 0;
385 /// The upper bound of a variable (column) have to be given by an
386 /// extended number of type Value, i.e. a finite number of type
387 /// Value or \ref INF.
388 virtual void _setColUpperBound(int i, Value value) = 0;
391 /// The lower bound of a linear expression (row) have to be given by an
392 /// extended number of type Value, i.e. a finite number of type
393 /// Value or -\ref INF.
394 virtual void _setRowLowerBound(int i, Value value) = 0;
397 /// The upper bound of a linear expression (row) have to be given by an
398 /// extended number of type Value, i.e. a finite number of type
399 /// Value or \ref INF.
400 virtual void _setRowUpperBound(int i, Value value) = 0;
403 virtual void _setObjCoeff(int i, Value obj_coef) = 0;
407 ///\bug Wrong interface
409 virtual SolutionType _solve() = 0;
413 ///\bug Wrong interface
415 virtual Value _getSolution(int i) = 0;
418 ///\bug unimplemented!!!!
424 virtual ~LpSolverBase() {}
426 ///\name Building up and modification of the LP
430 ///Add a new empty column (i.e a new variable) to the LP
431 Col addCol() { Col c; c.id=cols.insert(_addCol()); return c;}
433 ///\brief Fill the elements of a container with newly created columns
434 ///(i.e a new variables)
436 ///This magic function takes a container as its argument
437 ///and fills its elements
438 ///with new columns (i.e. variables)
440 ///- a standard STL compatible iterable container with
441 ///\ref Col as its \c values_type
444 ///std::vector<LpSolverBase::Col>
445 ///std::list<LpSolverBase::Col>
447 ///- a standard STL compatible iterable container with
448 ///\ref Col as its \c mapped_type
451 ///std::map<AnyType,LpSolverBase::Col>
453 ///- an iterable lemon \ref concept::WriteMap "write map" like
455 ///ListGraph::NodeMap<LpSolverBase::Col>
456 ///ListGraph::EdgeMap<LpSolverBase::Col>
458 ///\return The number of the created column.
459 ///\bug Iterable nodemap hasn't been implemented yet.
462 int addColSet(T &t) { return 0;}
465 typename enable_if<typename T::value_type::LpSolverCol,int>::type
466 addColSet(T &t,dummy<0> = 0) {
468 for(typename T::iterator i=t.begin();i!=t.end();++i) {*i=addCol();s++;}
472 typename enable_if<typename T::value_type::second_type::LpSolverCol,
474 addColSet(T &t,dummy<1> = 1) {
476 for(typename T::iterator i=t.begin();i!=t.end();++i) {
483 typename enable_if<typename T::ValueSet::value_type::LpSolverCol,
485 addColSet(T &t,dummy<2> = 2) {
486 ///\bug <tt>return addColSet(t.valueSet());</tt> should also work.
488 for(typename T::ValueSet::iterator i=t.valueSet().begin();
489 i!=t.valueSet().end();
499 ///Add a new empty row (i.e a new constaint) to the LP
501 ///This function adds a new empty row (i.e a new constaint) to the LP.
502 ///\return The created row
503 Row addRow() { Row r; r.id=rows.insert(_addRow()); return r;}
505 ///Set a row (i.e a constaint) of the LP
507 ///\param r is the row to be modified
508 ///\param l is lower bound (-\ref INF means no bound)
509 ///\param e is a linear expression (see \ref Expr)
510 ///\param u is the upper bound (\ref INF means no bound)
511 ///\bug This is a temportary function. The interface will change to
513 void setRow(Row r, Value l,const Expr &e, Value u) {
514 std::vector<int> indices;
515 std::vector<Value> values;
516 indices.push_back(0);
518 for(Expr::const_iterator i=e.begin(); i!=e.end(); ++i)
519 if((*i).second!=0) { ///\bug EPSILON would be necessary here!!!
520 indices.push_back(cols.floatingId((*i).first.id));
521 values.push_back((*i).second);
523 _setRowCoeffs(rows.floatingId(r.id),indices.size()-1,
524 &indices[0],&values[0]);
525 _setRowLowerBound(rows.floatingId(r.id),l-e.constComp());
526 _setRowUpperBound(rows.floatingId(r.id),u-e.constComp());
529 ///Set a row (i.e a constaint) of the LP
531 ///\param r is the row to be modified
532 ///\param c is a linear expression (see \ref Constr)
533 void setRow(Row r, const Constr &c) {
535 c.lowerBounded()?c.lowerBound():-INF,
537 c.upperBounded()?c.upperBound():INF);
540 ///Add a new row (i.e a new constaint) to the LP
542 ///\param l is the lower bound (-\ref INF means no bound)
543 ///\param e is a linear expression (see \ref Expr)
544 ///\param u is the upper bound (\ref INF means no bound)
545 ///\return The created row.
546 ///\bug This is a temportary function. The interface will change to
548 Row addRow(Value l,const Expr &e, Value u) {
554 ///Add a new row (i.e a new constaint) to the LP
556 ///\param c is a linear expression (see \ref Constr)
557 ///\return The created row.
558 Row addRow(const Constr &c) {
564 /// Set the lower bound of a column (i.e a variable)
566 /// The upper bound of a variable (column) have to be given by an
567 /// extended number of type Value, i.e. a finite number of type
568 /// Value or -\ref INF.
569 virtual void setColLowerBound(Col c, Value value) {
570 _setColLowerBound(cols.floatingId(c.id),value);
572 /// Set the upper bound of a column (i.e a variable)
574 /// The upper bound of a variable (column) have to be given by an
575 /// extended number of type Value, i.e. a finite number of type
576 /// Value or \ref INF.
577 virtual void setColUpperBound(Col c, Value value) {
578 _setColUpperBound(cols.floatingId(c.id),value);
580 /// Set the lower bound of a row (i.e a constraint)
582 /// The lower bound of a linear expression (row) have to be given by an
583 /// extended number of type Value, i.e. a finite number of type
584 /// Value or -\ref INF.
585 virtual void setRowLowerBound(Row r, Value value) {
586 _setRowLowerBound(rows.floatingId(r.id),value);
588 /// Set the upper bound of a row (i.e a constraint)
590 /// The upper bound of a linear expression (row) have to be given by an
591 /// extended number of type Value, i.e. a finite number of type
592 /// Value or \ref INF.
593 virtual void setRowUpperBound(Row r, Value value) {
594 _setRowUpperBound(rows.floatingId(r.id),value);
596 ///Set an element of the objective function
597 void setObjCoeff(Col c, Value v) {_setObjCoeff(cols.floatingId(c.id),v); };
598 ///Set the objective function
600 ///\param e is a linear expression of type \ref Expr.
601 ///\todo What to do with the constant component?
602 void setObj(Expr e) {
604 for (Expr::iterator i=e.begin(); i!=e.end(); ++i)
605 setObjCoeff((*i).first,(*i).second);
611 ///\name Solving the LP
616 SolutionType solve() { return _solve(); }
620 ///\name Obtaining the solution LP
625 Value solution(Col c) { return _getSolution(cols.floatingId(c.id)); }
633 ///\relates LpSolverBase::Expr
635 inline LpSolverBase::Expr operator+(const LpSolverBase::Expr &a,
636 const LpSolverBase::Expr &b)
638 LpSolverBase::Expr tmp(a);
639 tmp+=b; ///\todo Don't STL have some special 'merge' algorithm?
644 ///\relates LpSolverBase::Expr
646 inline LpSolverBase::Expr operator-(const LpSolverBase::Expr &a,
647 const LpSolverBase::Expr &b)
649 LpSolverBase::Expr tmp(a);
650 tmp-=b; ///\todo Don't STL have some special 'merge' algorithm?
655 ///\relates LpSolverBase::Expr
657 inline LpSolverBase::Expr operator*(const LpSolverBase::Expr &a,
658 const LpSolverBase::Value &b)
660 LpSolverBase::Expr tmp(a);
661 tmp*=b; ///\todo Don't STL have some special 'merge' algorithm?
667 ///\relates LpSolverBase::Expr
669 inline LpSolverBase::Expr operator*(const LpSolverBase::Value &a,
670 const LpSolverBase::Expr &b)
672 LpSolverBase::Expr tmp(b);
673 tmp*=a; ///\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::Constr
692 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
693 const LpSolverBase::Expr &f)
695 return LpSolverBase::Constr(-LpSolverBase::INF,e-f,0);
700 ///\relates LpSolverBase::Constr
702 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &e,
703 const LpSolverBase::Expr &f)
705 return LpSolverBase::Constr(e,f);
710 ///\relates LpSolverBase::Constr
712 inline LpSolverBase::Constr operator<=(const LpSolverBase::Expr &e,
713 const LpSolverBase::Value &f)
715 return LpSolverBase::Constr(e,f);
720 ///\relates LpSolverBase::Constr
722 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
723 const LpSolverBase::Expr &f)
725 return LpSolverBase::Constr(-LpSolverBase::INF,f-e,0);
731 ///\relates LpSolverBase::Constr
733 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &e,
734 const LpSolverBase::Expr &f)
736 return LpSolverBase::Constr(f,e);
742 ///\relates LpSolverBase::Constr
744 inline LpSolverBase::Constr operator>=(const LpSolverBase::Expr &e,
745 const LpSolverBase::Value &f)
747 return LpSolverBase::Constr(f,e);
752 ///\relates LpSolverBase::Constr
754 inline LpSolverBase::Constr operator==(const LpSolverBase::Expr &e,
755 const LpSolverBase::Expr &f)
757 return LpSolverBase::Constr(0,e-f,0);
762 ///\relates LpSolverBase::Constr
764 inline LpSolverBase::Constr operator<=(const LpSolverBase::Value &n,
765 const LpSolverBase::Constr&c)
767 LpSolverBase::Constr tmp(c);
768 ///\todo Create an own exception type.
769 if(!isnan(tmp.lowerBound())) throw LogicError();
770 else tmp.lowerBound()=n;
775 ///\relates LpSolverBase::Constr
777 inline LpSolverBase::Constr operator<=(const LpSolverBase::Constr& c,
778 const LpSolverBase::Value &n)
780 LpSolverBase::Constr tmp(c);
781 ///\todo Create an own exception type.
782 if(!isnan(tmp.upperBound())) throw LogicError();
783 else tmp.upperBound()=n;
789 ///\relates LpSolverBase::Constr
791 inline LpSolverBase::Constr operator>=(const LpSolverBase::Value &n,
792 const LpSolverBase::Constr&c)
794 LpSolverBase::Constr tmp(c);
795 ///\todo Create an own exception type.
796 if(!isnan(tmp.upperBound())) throw LogicError();
797 else tmp.upperBound()=n;
802 ///\relates LpSolverBase::Constr
804 inline LpSolverBase::Constr operator>=(const LpSolverBase::Constr& c,
805 const LpSolverBase::Value &n)
807 LpSolverBase::Constr tmp(c);
808 ///\todo Create an own exception type.
809 if(!isnan(tmp.lowerBound())) throw LogicError();
810 else tmp.lowerBound()=n;
817 #endif //LEMON_LP_BASE_H