diff --git a/changelog.in b/changelog.in index 1c416a0cc8..a351ba0842 100755 --- a/changelog.in +++ b/changelog.in @@ -166,6 +166,24 @@ fnmul above. The opaque negation prevents that, and the float examples run two to four times faster with MSVC. With GCC and clang on x86-64 the opaque negation is an empty asm barrier instead of a volatile round trip. +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Add Space::compare(), which ranks two solutions without modifying them. +Best-solution search uses it to choose between solutions, for example in +parallel BAB, portfolios, external incumbents, and the experimental A* and +CABS engines. constrain() still prunes the search. Optimization models with a +custom constrain() must now also override compare(). compare() returns the +scoped enum SpaceComparison (Better, Equivalent, Worse, Incomparable), and the +optimization direction is the scoped enum Sense (Minimize, Maximize). +compare_int(), compare_float(), and compare_lex() compare integer, float, and +lexicographic objective values for a given Sense. Comparing solutions whose +objectives differ in direction, float step, or size throws +SpaceIncompatibleObjectives. Search engines throw Search::Incomparable when +compare() reports incomparable solutions. + [RELEASE] Version: 6.5.0 Date: 2026-10-31 diff --git a/examples/car-sequencing.cpp b/examples/car-sequencing.cpp index de6cc757cb..f785eadd58 100644 --- a/examples/car-sequencing.cpp +++ b/examples/car-sequencing.cpp @@ -369,6 +369,13 @@ class CarSequencing : public Script { rel(*this, nstall, IRT_LE, best.nstall.val()); } + using Script::compare; + /// Compare objective values + virtual SpaceComparison compare(const Space& _other) const { + const CarSequencing& other = static_cast(_other); + return compare_int(nstall.val(), other.nstall.val(), Sense::Minimize); + } + /// Print solution virtual void print(std::ostream& os) const { @@ -634,4 +641,3 @@ namespace { }; // STATISTICS: example-any - diff --git a/examples/cartesian-heart.cpp b/examples/cartesian-heart.cpp index f941497470..e2d8aaf61c 100644 --- a/examples/cartesian-heart.cpp +++ b/examples/cartesian-heart.cpp @@ -94,6 +94,22 @@ class CartesianHeart : public Script { (f[1] >= (b.f[1].max()+step)) || (f[1] <= (b.f[1].min()-step))); } + using Script::compare; + /** + * \brief Compare with solution \a other + * + * This model has no objective: constrain only keeps later solutions apart + * from earlier ones. A solution counts as better than \a other when it + * is far enough from \a other to satisfy constrain, so parallel search keeps + * the same kind of solutions as sequential search. This is not an order. + */ + virtual SpaceComparison compare(const Space& _other) const { + const CartesianHeart& b = static_cast(_other); + bool apart = (f[0].min() >= (b.f[0].max()+step)) || + (f[1].min() >= (b.f[1].max()+step)) || + (f[1].max() <= (b.f[1].min()-step)); + return apart ? SpaceComparison::Better : SpaceComparison::Worse; + } /// Print solution coordinates virtual void print(std::ostream& os) const { os << "XY " << f[0].med() << " " << f[1].med() diff --git a/examples/fifteen-puzzle.cpp b/examples/fifteen-puzzle.cpp index 93b35cf91b..5dc638a271 100644 --- a/examples/fifteen-puzzle.cpp +++ b/examples/fifteen-puzzle.cpp @@ -418,7 +418,7 @@ run(PuzzleOptions& opt) { case PuzzleOptions::SEARCH_ASTAR: case PuzzleOptions::SEARCH_CABS: { - Search::HeuristicGuidance guidance(Search::HeuristicGuidance::MINIMIZE, + Search::HeuristicGuidance guidance(Sense::Minimize, [](const Space& home) -> std::int64_t { return static_cast(home).bound(); }); diff --git a/examples/tsptw.cpp b/examples/tsptw.cpp index 2b83ad474b..b7a35dc921 100644 --- a/examples/tsptw.cpp +++ b/examples/tsptw.cpp @@ -381,7 +381,7 @@ main(int argc, char* argv[]) { case TSPTW::SEARCH_ASTAR: case TSPTW::SEARCH_CABS: { - Search::HeuristicGuidance g(Search::HeuristicGuidance::MINIMIZE, + Search::HeuristicGuidance g(Sense::Minimize, [](const Space& s) -> std::int64_t { return static_cast(s).cost().min(); }); diff --git a/gecode/driver.hh b/gecode/driver.hh index 981fc353a1..313b74af5b 100755 --- a/gecode/driver.hh +++ b/gecode/driver.hh @@ -901,6 +901,7 @@ namespace Gecode { namespace Driver { template class ScriptBase : public BaseSpace { public: + using BaseSpace::compare; /// Constructor ScriptBase(const Options& opt); /// Constructor used for cloning diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index d4b29dc5da..1d46712726 100755 --- a/gecode/flatzinc.hh +++ b/gecode/flatzinc.hh @@ -576,7 +576,7 @@ namespace Gecode { namespace FlatZinc { Gecode::FloatVarArray fv_aux; /// Indicates whether a float variable is introduced by mzn2fzn std::vector fv_introduced; - /// Step by which a next solution has to have lower cost + /// Step used by float optimization cuts and comparison compatibility Gecode::FloatNum step; #endif /// Whether the introduced variables still need to be copied @@ -626,6 +626,16 @@ namespace Gecode { namespace FlatZinc { /// Compare this space with space \a s and print the differences on /// \a out void compare(const Space& s, std::ostream& out) const; + /** + * \brief Compare compatible optimization objectives + * + * Integer objectives compare assigned values. Float objectives require + * the same direction and step, and assigned intervals, which may span + * adjacent float values. Float minimization ranks lower endpoints and + * maximization ranks upper endpoints, independently of the step used by + * constrain(). + */ + virtual SpaceComparison compare(const Space& s) const; /// Compare this space with space \a s and print the differences on /// \a out using \a p void compare(const FlatZincSpace& s, std::ostream& out, diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 8f1a11a87c..b50d3fb112 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -2098,6 +2098,33 @@ namespace Gecode { namespace FlatZinc { } } + SpaceComparison + FlatZincSpace::compare(const Space& s) const { + const FlatZincSpace* other = dynamic_cast(&s); + if (other == nullptr) + throw DynamicCastFailed("FlatZincSpace::compare"); + if ((_method != MIN) && (_method != MAX)) + throw SpaceNoComparison("FlatZincSpace::compare"); + if ((_optVarIsInt != other->_optVarIsInt) || + (_method != other->_method)) + throw SpaceIncompatibleObjectives("FlatZincSpace::compare"); + Sense sense = (_method == MIN) ? Sense::Minimize : Sense::Maximize; + if (_optVarIsInt) + return compare_int(iv[_optVar].val(),other->iv[other->_optVar].val(), + sense); +#ifdef GECODE_HAS_FLOAT_VARS + if (step != other->step) + throw SpaceIncompatibleObjectives("FlatZincSpace::compare"); + FloatVal a=fv[_optVar].val(); + FloatVal b=other->fv[other->_optVar].val(); + FloatNum ak=(_method == MIN) ? a.min() : a.max(); + FloatNum bk=(_method == MIN) ? b.min() : b.max(); + return compare_float(ak,bk,sense); +#else + throw DynamicCastFailed("FlatZincSpace::compare"); +#endif + } + bool FlatZincSpace::slave(const MetaInfo& mi) { if (mi.type() == MetaInfo::RESTART) { diff --git a/gecode/float.hh b/gecode/float.hh index 1fe8ace09a..2580443b02 100755 --- a/gecode/float.hh +++ b/gecode/float.hh @@ -105,6 +105,15 @@ namespace Gecode { */ typedef double FloatNum; + /// Compare objective value \a x with \a y for direction \a s + forceinline SpaceComparison + compare_float(FloatNum x, FloatNum y, Sense s) { + if (x == y) + return SpaceComparison::Equivalent; + return ((x < y) == (s == Sense::Minimize)) ? + SpaceComparison::Better : SpaceComparison::Worse; + } + /// Return lower bound of \f$\pi/2\f$ FloatNum pi_half_lower(void); /// Return upper bound of \f$\pi/2\f$ diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index 54ab989695..21b8584bfb 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -896,6 +896,11 @@ namespace Gecode { Space::constrain(const Space&) { } + SpaceComparison + Space::compare(const Space&) const { + throw SpaceNoComparison("Space::compare"); + } + bool Space::master(const MetaInfo& mi) { switch (mi.type()) { diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index e365b91d10..07b85f3083 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -53,6 +53,29 @@ namespace Gecode { + /// Result of comparing two solutions according to their objectives + enum class SpaceComparison { + Better, ///< The receiver has a better objective + Equivalent, ///< Both objectives are equivalent + Worse, ///< The receiver has a worse objective + Incomparable ///< Neither objective dominates the other + }; + + /// Optimization direction + enum class Sense { + Minimize, ///< Smaller objective values are better + Maximize ///< Larger objective values are better + }; + + /// Compare objective value \a x with \a y for direction \a s + forceinline SpaceComparison + compare_int(int x, int y, Sense s) { + if (x == y) + return SpaceComparison::Equivalent; + return ((x < y) == (s == Sense::Minimize)) ? + SpaceComparison::Better : SpaceComparison::Worse; + } + class Space; /** @@ -2153,6 +2176,21 @@ namespace Gecode { * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT virtual void constrain(const Space& best); + /** + * \brief Compare function for best solution search + * + * Must return whether this solution is better than, equivalent to, + * worse than, or incomparable with solution \a other, without modifying + * either. The result must agree with constrain: solutions admitted by + * constrain(b) are better than b, and a better b admits no more solutions. + * + * The default function throws SpaceNoComparison, so a space overriding + * constrain must also override compare. + * + * \ingroup TaskModelScript + */ + GECODE_KERNEL_EXPORT virtual SpaceComparison + compare(const Space& other) const; /** * \brief Master configuration function for meta search engines * diff --git a/gecode/kernel/exception.cpp b/gecode/kernel/exception.cpp index e16c6cd61a..a273a04699 100644 --- a/gecode/kernel/exception.cpp +++ b/gecode/kernel/exception.cpp @@ -47,6 +47,12 @@ namespace Gecode { SpaceNoBrancher::SpaceNoBrancher(const char* l) : Exception(l,"Attempt to commit with no brancher") {} + SpaceNoComparison::SpaceNoComparison(const char* l) + : Exception(l,"Space does not support comparison") {} + + SpaceIncompatibleObjectives::SpaceIncompatibleObjectives(const char* l) + : Exception(l,"Spaces with incompatible objectives cannot be compared") {} + SpaceIllegalAlternative::SpaceIllegalAlternative(const char* l) : Exception(l,"Attempt to commit with illegal alternative") {} diff --git a/gecode/kernel/exception.hpp b/gecode/kernel/exception.hpp index 792f4975e6..3c174d33bc 100644 --- a/gecode/kernel/exception.hpp +++ b/gecode/kernel/exception.hpp @@ -68,6 +68,20 @@ namespace Gecode { SpaceNoBrancher(const char* l); }; + /// %Exception: Comparison not implemented by space + class GECODE_KERNEL_EXPORT SpaceNoComparison : public Exception { + public: + /// Initialize with location \a l + SpaceNoComparison(const char* l); + }; + + /// %Exception: Comparison of spaces with incompatible objectives + class GECODE_KERNEL_EXPORT SpaceIncompatibleObjectives : public Exception { + public: + /// Initialize with location \a l + SpaceIncompatibleObjectives(const char* l); + }; + /// %Exception: Commit with illegal alternative class GECODE_KERNEL_EXPORT SpaceIllegalAlternative : public Exception { public: diff --git a/gecode/minimodel.hh b/gecode/minimodel.hh index 59c7869e61..ad60222438 100755 --- a/gecode/minimodel.hh +++ b/gecode/minimodel.hh @@ -2429,6 +2429,16 @@ namespace Gecode { * \ingroup TaskModelMiniModel */ + /** + * \brief Compare assigned \a x with \a y lexicographically for \a s + * + * The first position where the values differ decides the result. Throws + * SpaceIncompatibleObjectives if the sizes differ. + * \ingroup TaskModelMiniModelOptimize + */ + GECODE_MINIMODEL_EXPORT SpaceComparison + compare_lex(const IntVarArgs& x, const IntVarArgs& y, Sense s); + /** * \brief Class for minimizing integer cost * \ingroup TaskModelMiniModelOptimize @@ -2442,6 +2452,9 @@ namespace Gecode { /// Member function constraining according to decreasing cost GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare integer costs (both costs must be assigned) + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variable with current cost virtual IntVar cost(void) const = 0; }; @@ -2459,6 +2472,9 @@ namespace Gecode { /// Member function constraining according to increasing cost GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare integer costs (both costs must be assigned) + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variable with current cost virtual IntVar cost(void) const = 0; }; @@ -2476,6 +2492,9 @@ namespace Gecode { /// Member function constraining according to decreasing costs GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare integer costs lexicographically + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variables with current costs virtual IntVarArgs cost(void) const = 0; }; @@ -2493,6 +2512,9 @@ namespace Gecode { /// Member function constraining according to increasing costs GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare integer costs lexicographically + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variables with current costs virtual IntVarArgs cost(void) const = 0; }; @@ -2505,6 +2527,9 @@ namespace Gecode { * The class supports using a step value \a step that will make sure * that better solutions must be better by at least the value of * \a step. + * Comparison ranks the upper endpoint of assigned costs independently of + * the step. Both operands must use this base class and the same step. + * Assigned costs may be tight intervals between adjacent float values. * * \ingroup TaskModelMiniModelOptimize */ @@ -2520,6 +2545,9 @@ namespace Gecode { /// Member function constraining according to cost GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare upper endpoints of assigned costs with a common step policy + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variable with current cost virtual FloatVar cost(void) const = 0; }; @@ -2530,6 +2558,9 @@ namespace Gecode { * The class supports using a step value \a step that will make sure * that better solutions must be better by at least the value of * \a step. + * Comparison ranks the lower endpoint of assigned costs independently of + * the step. Both operands must use this base class and the same step. + * Assigned costs may be tight intervals between adjacent float values. * * \ingroup TaskModelMiniModelOptimize */ @@ -2545,6 +2576,9 @@ namespace Gecode { /// Member function constraining according to cost GECODE_MINIMODEL_EXPORT virtual void constrain(const Space& best); + /// Compare lower endpoints of assigned costs with a common step policy + GECODE_MINIMODEL_EXPORT + virtual SpaceComparison compare(const Space& other) const; /// Return variable with current cost virtual FloatVar cost(void) const = 0; }; diff --git a/gecode/minimodel/optimize.cpp b/gecode/minimodel/optimize.cpp index 9e0afca3b8..5a64c7d286 100755 --- a/gecode/minimodel/optimize.cpp +++ b/gecode/minimodel/optimize.cpp @@ -37,6 +37,16 @@ namespace Gecode { + SpaceComparison + compare_lex(const IntVarArgs& x, const IntVarArgs& y, Sense s) { + if (x.size() != y.size()) + throw SpaceIncompatibleObjectives("compare_lex"); + for (int i=0; icost().val()); } + SpaceComparison + IntMinimizeSpace::compare(const Space& other) const { + const IntMinimizeSpace* s = dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("IntMinimizeSpace::compare"); + return compare_int(cost().val(),s->cost().val(),Sense::Minimize); + } + void IntMaximizeSpace::constrain(const Space& _best) { @@ -56,6 +74,14 @@ namespace Gecode { rel(*this, cost(), IRT_GR, best->cost().val()); } + SpaceComparison + IntMaximizeSpace::compare(const Space& other) const { + const IntMaximizeSpace* s = dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("IntMaximizeSpace::compare"); + return compare_int(cost().val(),s->cost().val(),Sense::Maximize); + } + void IntLexMinimizeSpace::constrain(const Space& _best) { @@ -70,6 +96,15 @@ namespace Gecode { rel(*this, cx, IRT_LE, bn); } + SpaceComparison + IntLexMinimizeSpace::compare(const Space& other) const { + const IntLexMinimizeSpace* s = + dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("IntLexMinimizeSpace::compare"); + return compare_lex(cost(),s->cost(),Sense::Minimize); + } + void IntLexMaximizeSpace::constrain(const Space& _best) { const IntLexMaximizeSpace* best = @@ -83,6 +118,15 @@ namespace Gecode { rel(*this, cx, IRT_GR, bn); } + SpaceComparison + IntLexMaximizeSpace::compare(const Space& other) const { + const IntLexMaximizeSpace* s = + dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("IntLexMaximizeSpace::compare"); + return compare_lex(cost(),s->cost(),Sense::Maximize); + } + #ifdef GECODE_HAS_FLOAT_VARS void @@ -102,6 +146,18 @@ namespace Gecode { rel(*this, cost(), FRT_LQ, std::nextafter(n, Float::Limits::min)); } + SpaceComparison + FloatMinimizeSpace::compare(const Space& other) const { + const FloatMinimizeSpace* s = + dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("FloatMinimizeSpace::compare"); + if (step != s->step) + throw SpaceIncompatibleObjectives("FloatMinimizeSpace::compare"); + return compare_float(cost().val().max(),s->cost().val().max(), + Sense::Minimize); + } + void FloatMaximizeSpace::constrain(const Space& _best) { @@ -116,9 +172,20 @@ namespace Gecode { rel(*this, cost(), FRT_GQ, std::nextafter(n, Float::Limits::max)); } + SpaceComparison + FloatMaximizeSpace::compare(const Space& other) const { + const FloatMaximizeSpace* s = + dynamic_cast(&other); + if (s == nullptr) + throw DynamicCastFailed("FloatMaximizeSpace::compare"); + if (step != s->step) + throw SpaceIncompatibleObjectives("FloatMaximizeSpace::compare"); + return compare_float(cost().val().min(),s->cost().val().min(), + Sense::Maximize); + } + #endif } // STATISTICS: minimodel-search - diff --git a/gecode/search.hh b/gecode/search.hh index 11b40fc458..4f35c2f74c 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1236,9 +1236,11 @@ namespace Gecode { namespace Search { * * The bound is an optimistic objective value for a stable space: a lower * bound when minimizing, an upper bound when maximizing, and the exact - * objective for a solution. It must agree with the model's constrain - * function. The optional rank orders nodes (lower first) but is never - * used for pruning. + * objective for a solution. It must agree with the model's constrain and + * compare functions. The bound orders and prunes open nodes, while + * solutions replace the incumbent only when Space::compare reports + * SpaceComparison::Better. The optional rank orders nodes (lower first) + * but is never used for pruning. * * The optional dominance predicate returns whether every completion of * the second space is matched by a completion of the first that is not @@ -1258,8 +1260,6 @@ namespace Gecode { namespace Search { */ class HeuristicGuidance { public: - /// Objective direction - enum Sense { MINIMIZE, MAXIMIZE }; /// Function evaluating a stable space typedef std::function Evaluate; /// Objective direction @@ -1287,7 +1287,8 @@ namespace Gecode { * Expands nodes in order of their bound, then their rank, using the * guidance from Search::Options::guidance. Like BAB, next() returns * improving solutions and exhausting the search proves the last - * solution optimal. + * solution optimal. Additionally, \a T must implement Space::constrain + * and Space::compare. * * All open nodes are stored as clones, so c_d and a_d are ignored. * Tracing is not supported. @@ -1325,7 +1326,8 @@ namespace Gecode { * improve the incumbent, the search restarts with twice the width. * The guidance is taken from Search::Options::guidance. Like BAB, * next() returns improving solutions and exhausting the search proves - * the last solution optimal. + * the last solution optimal. Additionally, \a T must implement + * Space::constrain and Space::compare. * * Search stops when the width would exceed Search::Options::max_width or * the stored nodes would exceed Search::Options::frontier_limit. Nodes are @@ -1361,8 +1363,7 @@ namespace Gecode { /** * \brief Depth-first branch-and-bound search engine * - * Additionally, \a s must implement a member function - * \code virtual void constrain(const T& t) \endcode + * Additionally, \a s must implement Space::constrain and Space::compare. * Whenever exploration requires to add a constraint * to the space \a c currently being explored, the engine * executes \c c.constrain(t) where \a t is the so-far @@ -1381,8 +1382,7 @@ namespace Gecode { /** * \brief Perform depth-first branch-and-bound search for subclass \a T of space \a s and options \a o * - * Additionally, \a s must implement a member function - * \code virtual void constrain(const T& t) \endcode + * Additionally, \a s must implement Space::constrain and Space::compare. * Whenever exploration requires to add a constraint * to the space \a c currently being explored, the engine * executes \c c.constrain(t) where \a t is the so-far @@ -1524,6 +1524,8 @@ namespace Gecode { * The engine will run a portfolio with a number of assets as defined * by the options \a o. The engine supports parallel execution of * assets by using the number of threads as defined by the options. + * For best-solution assets, a solution replaces the incumbent only if + * Space::compare reports SpaceComparison::Better. * An external worker control in \a o is supported only for a single * homogeneous asset. Multiple controlled assets require explicit engine * builders, each with its own control and immutable worker capacity. diff --git a/gecode/search/astar.cpp b/gecode/search/astar.cpp index 9ed5eeab81..3931e17fc1 100644 --- a/gecode/search/astar.cpp +++ b/gecode/search/astar.cpp @@ -142,9 +142,9 @@ namespace Gecode { namespace Search { namespace Seq { AStar::publish(std::unique_ptr s) { // Delete exhausted branchers before cloning the solution (void) s->choice(); - std::int64_t b = guidance.bound(*s); - if (!best.improves(b)) + if (!best.replaced_by(*s,"AStar::next")) return nullptr; + std::int64_t b = guidance.bound(*s); Space* copy = s->clone(); best.update(s.release(),b); return copy; @@ -214,9 +214,8 @@ namespace Gecode { namespace Search { namespace Seq { void AStar::constrain(const Space& s) { - std::int64_t b = guidance.bound(s); - if (best.improves(b)) - best.update(s.clone(),b); + if (best.replaced_by(s,"AStar::constrain")) + best.update(s.clone(),guidance.bound(s)); } void diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index 5616a2e202..233cd489b7 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -210,9 +210,9 @@ namespace Gecode { namespace Search { namespace Seq { CABS::publish(std::unique_ptr s) { // Delete exhausted branchers before cloning the solution (void) s->choice(); - std::int64_t b = guidance.bound(*s); - if (!best.improves(b)) + if (!best.replaced_by(*s,"CABS::next")) return nullptr; + std::int64_t b = guidance.bound(*s); Space* copy = s->clone(); best.update(s.release(),b); return copy; @@ -316,9 +316,8 @@ namespace Gecode { namespace Search { namespace Seq { void CABS::constrain(const Space& s) { - std::int64_t b = guidance.bound(s); - if (best.improves(b)) - best.update(s.clone(),b); + if (best.replaced_by(s,"CABS::constrain")) + best.update(s.clone(),guidance.bound(s)); } void diff --git a/gecode/search/exception.cpp b/gecode/search/exception.cpp index 8d99738996..8e3bcb8974 100644 --- a/gecode/search/exception.cpp +++ b/gecode/search/exception.cpp @@ -64,6 +64,9 @@ namespace Gecode { namespace Search { WorkerControlInUse::WorkerControlInUse(const char* l) : Exception(l,"Worker control is already bound or has unsupported engine placement") {} + Incomparable::Incomparable(const char* l) + : Exception(l,"Incomparable objectives are not supported by best solution search") {} + }} // STATISTICS: search-other diff --git a/gecode/search/exception.hpp b/gecode/search/exception.hpp index e28c3fd9ce..16b65661f1 100644 --- a/gecode/search/exception.hpp +++ b/gecode/search/exception.hpp @@ -80,6 +80,12 @@ namespace Gecode { namespace Search { /// Initialize with location \a l WorkerControlInUse(const char* l); }; + /// %Exception: Incomparable objectives are unsupported by best search + class GECODE_SEARCH_EXPORT Incomparable : public Exception { + public: + /// Initialize with location \a l + Incomparable(const char* l); + }; #ifdef GECODE_HAS_EXPERIMENTAL /// %Exception: Missing guidance for heuristic search class GECODE_SEARCH_EXPORT UninitializedGuidance : public Exception { diff --git a/gecode/search/heuristic.hh b/gecode/search/heuristic.hh index 87fde7c609..7cb24b7e02 100644 --- a/gecode/search/heuristic.hh +++ b/gecode/search/heuristic.hh @@ -35,6 +35,7 @@ #define GECODE_SEARCH_HEURISTIC_HH #include +#include #include #include #include @@ -45,8 +46,8 @@ namespace Gecode { namespace Search { /// Whether bound \a a is better than bound \a b for objective direction \a s forceinline bool - better(HeuristicGuidance::Sense s, std::int64_t a, std::int64_t b) { - return (s == HeuristicGuidance::MINIMIZE) ? (a < b) : (a > b); + better(Sense s, std::int64_t a, std::int64_t b) { + return (s == Sense::Minimize) ? (a < b) : (a > b); } /// Open node of a heuristic search engine @@ -70,7 +71,7 @@ namespace Gecode { namespace Search { class Priority { public: /// Objective direction - HeuristicGuidance::Sense sense; + Sense sense; /// Whether to order by rank only (CABS with rank) bool rank_only; /// Test whether \a a is preferred to \a b @@ -83,11 +84,16 @@ namespace Gecode { namespace Search { } }; - /// Best solution found so far + /** + * \brief Best solution found so far + * + * Solutions are ranked with Space::compare, like in the other best-solution + * engines. The bound of the incumbent prunes open nodes. + */ class Incumbent { public: /// Objective direction - HeuristicGuidance::Sense sense; + Sense sense; /// The solution (if any) std::unique_ptr space; /// Its objective value @@ -95,12 +101,16 @@ namespace Gecode { namespace Search { /// Incremented for every new incumbent unsigned long long int revision; /// Initialize without incumbent - Incumbent(HeuristicGuidance::Sense s) + Incumbent(Sense s) : sense(s), bound(0), revision(0) {} /// Whether a node with bound \a b can improve the incumbent bool improves(std::int64_t b) const { return !space || better(sense,b,bound); } + /// Whether solution \a s should replace the incumbent (location \a l) + bool replaced_by(const Space& s, const char* l) const { + return !space || Search::better(s,*space,l); + } /// Make \a s with objective value \a b the incumbent void update(Space* s, std::int64_t b) { space.reset(s); bound = b; revision++; diff --git a/gecode/search/nogoods.hh b/gecode/search/nogoods.hh index d9b729d25d..6e317803fe 100644 --- a/gecode/search/nogoods.hh +++ b/gecode/search/nogoods.hh @@ -39,7 +39,7 @@ namespace Gecode { namespace Search { /// Class for a sentinel no-good literal - class GECODE_VTABLE_EXPORT NoNGL : public NGL { + class GECODE_SEARCH_EXPORT NoNGL : public NGL { public: /// Constructor for creation NoNGL(void); diff --git a/gecode/search/par/bab.hh b/gecode/search/par/bab.hh index 4a1911b208..cf5a3d7fb9 100644 --- a/gecode/search/par/bab.hh +++ b/gecode/search/par/bab.hh @@ -35,6 +35,7 @@ #define GECODE_SEARCH_PAR_BAB_HH #include +#include namespace Gecode { namespace Search { namespace Par { @@ -46,6 +47,7 @@ namespace Gecode { namespace Search { namespace Par { using Engine::busy; using Engine::stop; using Engine::block; + using Engine::cmd; using Engine::e_search; using Engine::e_reset_ack_start; using Engine::e_reset_ack_stop; @@ -104,6 +106,8 @@ namespace Gecode { namespace Search { namespace Par { Worker** _worker; /// Best solution so far Space* best; + /// Failure raised while accepting a solution in a worker thread + std::exception_ptr failure; public: /// Provide access to worker \a i Worker* worker(unsigned int i) const; @@ -118,6 +122,8 @@ namespace Gecode { namespace Search { namespace Par { //@{ /// Initialize for space \a s with options \a o BAB(Space* s, const Options& o); + /// Return next solution + virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; /// Reset engine to restart at space \a s diff --git a/gecode/search/par/bab.hpp b/gecode/search/par/bab.hpp index deb0ae5f9b..1ba2da0536 100755 --- a/gecode/search/par/bab.hpp +++ b/gecode/search/par/bab.hpp @@ -89,7 +89,7 @@ namespace Gecode { namespace Search { namespace Par { template forceinline BAB::BAB(Space* s, const Options& o) - : Engine(o), best(nullptr) { + : Engine(o), best(nullptr), failure(nullptr) { WrapTraceRecorder::engine(o.tracer, SearchTracer::EngineType::DFS, workers()); // Create workers @@ -126,17 +126,33 @@ namespace Gecode { namespace Search { namespace Par { template forceinline void BAB::solution(Space* s) { - m_search.acquire(); - if (best != nullptr) { - s->constrain(*best); - if (s->status() == SS_FAILED) { + Support::Lock lock(m_search); + if (failure != nullptr) { + delete s; + return; + } + try { + if ((best != nullptr) && + !Search::better(*s,*best,"BAB::solution")) { delete s; - m_search.release(); return; - } else { - delete best; - best = s->clone(); } + } catch (...) { + delete s; + while (!solutions.empty()) + delete solutions.pop(); + failure = std::current_exception(); + // A null entry is private to BAB and only wakes Engine::next. That + // call blocks the workers before BAB::next rethrows the failure. + bool bs = signal(); + solutions.push(nullptr); + if (bs) + e_search.signal(); + return; + } + if (best != nullptr) { + delete best; + best = s->clone(); } else { best = s->clone(); } @@ -147,7 +163,6 @@ namespace Gecode { namespace Search { namespace Par { solutions.push(s); if (bs) e_search.signal(); - m_search.release(); } @@ -198,20 +213,53 @@ namespace Gecode { namespace Search { namespace Par { template void BAB::constrain(const Space& b) { - m_search.acquire(); + Support::Lock lock(m_search); + // Report a worker failure before comparing, so that the original + // exception is not replaced by one from the comparison below. + if (failure != nullptr) + std::rethrow_exception(failure); + // Solutions are queued from worst to best. Even a bound weaker than + // best can exclude the oldest pending solutions. + while (!solutions.empty() && + !Search::better(*solutions.front(),b,"BAB::constrain")) + delete solutions.pop(); + if ((best != nullptr) && + !Search::better(b,*best,"BAB::constrain")) + return; if (best != nullptr) { - best->constrain(b); - if (best->status() != SS_FAILED) { - m_search.release(); - return; - } delete best; } best = b.clone(); // Announce better solutions for (unsigned int i=0U; ibetter(best); - m_search.release(); + } + + template + Space* + BAB::next(void) { + std::exception_ptr f; + { + Support::Lock lock(m_search); + f = failure; + } + if (f != nullptr) + std::rethrow_exception(f); + Space* s = Engine::next(); + { + Support::Lock lock(m_search); + f = failure; + } + if (f != nullptr) { + // Engine::next can consume the failure marker through its initial + // nonempty-queue path. Unlike its event-wait path, that path does not + // block workers, so finish the normal lifecycle before reporting. + if (cmd() != C_WAIT) + block(); + delete s; + std::rethrow_exception(f); + } + return s; } /* @@ -392,9 +440,15 @@ namespace Gecode { namespace Search { namespace Par { // Wait for reset cycle started e_reset_ack_start.wait(); // All workers are marked as busy again - delete best; - best = nullptr; - n_busy = workers(); + { + Support::Lock lock(m_search); + while (!solutions.empty()) + delete solutions.pop(); + failure = nullptr; + delete best; + best = nullptr; + n_busy = workers(); + } for (unsigned int i=1U; ireset(nullptr,0); worker(0)->reset(s,opt().nogoods_limit); @@ -429,6 +483,11 @@ namespace Gecode { namespace Search { namespace Par { m_wait_reset.release(); // Wait for reset cycle stopped e_reset_ack_stop.wait(); + // A worker can fail after next() returns. Report that failure before + // a restart engine invokes its master callback and resets this engine. + Support::Lock lock(m_search); + if (failure != nullptr) + std::rethrow_exception(failure); return *ng; } diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index dacb958871..5977f8827f 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -155,12 +155,10 @@ namespace Gecode { namespace Search { namespace Par { void Frontier::publish(Space* s, std::int64_t b) { - if (!best.improves(b)) { - delete s; - return; - } std::unique_ptr incumbent(s); - solution.reset(s->clone()); + if (!best.replaced_by(*incumbent,"Frontier::publish")) + return; + solution.reset(incumbent->clone()); best.update(incumbent.release(),b); running = false; } @@ -281,7 +279,8 @@ namespace Gecode { namespace Search { namespace Par { (void) step.space->choice(); std::int64_t b = guidance.bound(*step.space); if (step.status == SS_SOLVED) { - if (!cutoff || better(guidance.sense,b,*cutoff)) { + // Comparison decides solutions that tie with the incumbent bound + if (!cutoff || !better(guidance.sense,*cutoff,b)) { solved = std::move(step.space); solved_bound = b; break; @@ -375,7 +374,7 @@ namespace Gecode { namespace Search { namespace Par { Frontier::constrain(const Space& s) { std::int64_t b = guidance.bound(s); Support::Lock lock(mutex); - if (best.improves(b)) { + if (best.replaced_by(s,"Frontier::constrain")) { best.update(s.clone(),b); solution.reset(); } diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index a3825097c9..23a5075a5a 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -143,7 +143,7 @@ namespace Gecode { namespace Search { namespace Par { void push(Task* t); /// Stop all workers (must be called by subclass destructors) void terminate(void); - /// Make \a s with bound \a b the incumbent, if it improves + /// Make \a s with bound \a b the incumbent, if it compares better void publish(Space* s, std::int64_t b); /// Start the threads void launch(void); diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 40d93e7252..7aabfa9558 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -40,6 +40,7 @@ #include #include +#include namespace Gecode { namespace Search { namespace Par { @@ -190,8 +191,12 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_busy; /// Signal that number of busy slaves becomes zero Support::Event idle; + /// Failure raised while running or updating a portfolio asset + std::exception_ptr failure; /// Process report from slave, return false if solution was ignored bool report(Slave* slave, Space* s); + /// Process failure from slave + void fail(void); /** * The key invariant of the engine is as follows: * - n_busy is always zero outside the next() function. diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 0f7f03e769..fa858036f2 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -94,29 +94,22 @@ namespace Gecode { namespace Search { namespace Par { : b(nullptr), reporter(nullptr) {} forceinline bool CollectBest::add(Space* s, Slave* r) { - if (b != nullptr) { - b->constrain(*s); - if (b->status() == SS_FAILED) { - delete b; - } else { - delete s; - return false; - } + if ((b != nullptr) && + !Search::better(*s,*b,"PBS::CollectBest::add")) { + delete s; + return false; } + delete b; b = s; reporter = r; return true; } forceinline bool CollectBest::constrain(const Space& s) { - if (b != nullptr) { - b->constrain(s); - if (b->status() == SS_FAILED) { - delete b; - } else { - return false; - } - } + if ((b != nullptr) && + !Search::better(s,*b,"PBS::CollectBest::constrain")) + return false; + delete b; b = s.clone(); reporter = nullptr; return true; @@ -222,8 +215,16 @@ namespace Gecode { namespace Search { namespace Par { bool wake = false; m.acquire(); if (s != nullptr) { - b = solutions.add(s,slave); - if (b) { + try { + b = solutions.add(s,slave); + if (b) { + tostop.store(true, std::memory_order_release); + wake = true; + } + } catch (...) { + delete s; + if (failure == nullptr) + failure = std::current_exception(); tostop.store(true, std::memory_order_release); wake = true; } @@ -258,22 +259,45 @@ namespace Gecode { namespace Search { namespace Par { return b; } + template + forceinline void + PBS::fail(void) { + m.acquire(); + if (failure == nullptr) + failure = std::current_exception(); + tostop.store(true, std::memory_order_release); + for (unsigned int i=0U; iwake(); + if (--n_busy == 0) + idle.signal(); + m.release(); + } + template void Slave::run(void) { - Space* s; - do { - s = slave->next(); - } while (!master->report(this,s)); + try { + Space* s; + do { + s = slave->next(); + } while (!master->report(this,s)); + } catch (...) { + master->fail(); + } } template Space* PBS::next(void) { m.acquire(); + if (failure != nullptr) { + std::exception_ptr f = failure; + m.release(); + std::rethrow_exception(f); + } if (solutions.empty()) slave_stop.store(false, std::memory_order_release); - while (solutions.empty() && (n_active > 0) && + while (solutions.empty() && (n_active > 0) && (failure == nullptr) && !slave_stop.load(std::memory_order_acquire)) { // Clear the internal stop used to interrupt sibling slaves tostop.store(false, std::memory_order_release); @@ -302,6 +326,14 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.empty() && (n_active == 0) && incomplete) slave_stop.store(true, std::memory_order_release); + // Report a stored failure before broadcasting a solution, which could + // call into the failed asset and replace the original exception. + if (failure != nullptr) { + std::exception_ptr f = failure; + m.release(); + std::rethrow_exception(f); + } + Space* s; // Process solutions @@ -310,10 +342,19 @@ namespace Gecode { namespace Search { namespace Par { } else { Slave* r; s = solutions.get(r); - if (Collect::best) - for (unsigned int i=0U; iconstrain(*s); + if (Collect::best) { + try { + for (unsigned int i=0U; iconstrain(*s); + } catch (...) { + delete s; + failure = std::current_exception(); + std::exception_ptr f = failure; + m.release(); + std::rethrow_exception(f); + } + } } m.release(); @@ -342,10 +383,15 @@ namespace Gecode { namespace Search { namespace Par { assert(n_busy == 0); if (!Collect::best) throw NoBest("PBS::constrain"); - if (solutions.constrain(b)) { - // The solution is better - for (unsigned int i=0U; iconstrain(b); + try { + if (solutions.constrain(b)) { + // The solution is better + for (unsigned int i=0U; iconstrain(b); + } + } catch (...) { + failure = std::current_exception(); + std::rethrow_exception(failure); } } diff --git a/gecode/search/seq/bab.hpp b/gecode/search/seq/bab.hpp index dade2cb075..fed0129c6a 100644 --- a/gecode/search/seq/bab.hpp +++ b/gecode/search/seq/bab.hpp @@ -161,14 +161,9 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline void BAB::constrain(const Space& b) { - if (best != nullptr) { - // Check whether b is in fact better than best - best->constrain(b); - if (best->status(*this) != SS_FAILED) - return; - else - delete best; - } + if ((best != nullptr) && !Search::better(b,*best,"BAB::constrain")) + return; + delete best; best = b.clone(); if (cur != nullptr) cur->constrain(b); diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 4dc77efef1..7dc63372b6 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -110,10 +110,15 @@ namespace Gecode { namespace Search { namespace Seq { if (Space* s = slaves[cur].next()) { // Constrain other slaves if (best) { - for (unsigned int i=0U; iconstrain(b); - if (last->status() == SS_FAILED) { - delete last; - } else { - return; - } - } + if ((last != nullptr) && !Search::better(b,*last,"RBS::constrain")) + return; + delete last; last = b.clone(); master->constrain(b); e->constrain(b); diff --git a/gecode/search/support.hh b/gecode/search/support.hh index fe25d487b2..6cdc0b2be4 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -38,6 +38,23 @@ namespace Gecode { namespace Search { + /// Whether incoming solution \a s should replace incumbent \a b + forceinline bool + better(const Space& s, const Space& b, const char* l) { + switch (s.compare(b)) { + case SpaceComparison::Better: + return true; + case SpaceComparison::Equivalent: + case SpaceComparison::Worse: + return false; + case SpaceComparison::Incomparable: + throw Incomparable(l); + default: + GECODE_NEVER; + } + return false; + } + /// Clone space \a s depending on options \a o forceinline Space* snapshot(Space* s, const Options& o); diff --git a/gecode/support/dynamic-queue.hpp b/gecode/support/dynamic-queue.hpp index a122b809cf..c4e5507b89 100644 --- a/gecode/support/dynamic-queue.hpp +++ b/gecode/support/dynamic-queue.hpp @@ -69,6 +69,8 @@ namespace Gecode { namespace Support { /// Pop element added first from queue and return it T pop(void); + /// Return element added first (queue must be nonempty) + T front(void) const; /// Push element \a x to queue void push(const T& x); @@ -138,6 +140,13 @@ namespace Gecode { namespace Support { return t; } + template + forceinline T + DynamicQueue::front(void) const { + assert(!empty()); + return q[fst]; + } + template forceinline void DynamicQueue::push(const T& x) { diff --git a/test/flatzinc.cpp b/test/flatzinc.cpp index 3430570d6c..9967d3bf8e 100755 --- a/test/flatzinc.cpp +++ b/test/flatzinc.cpp @@ -34,6 +34,9 @@ #include "test/flatzinc.hh" #include +#include +#include +#include namespace Test { namespace FlatZinc { @@ -113,6 +116,165 @@ namespace Test { namespace FlatZinc { FloatCutExcludesIncumbent float_cut_excludes_incumbent; #endif + /// Verify integer objective comparison for FlatZinc spaces. + class IntegerObjectiveComparison : public Base { + private: + static std::unique_ptr + model(const char* source) { + Gecode::FlatZinc::Printer p; + std::stringstream ss(source); + return std::unique_ptr + (Gecode::FlatZinc::parse(ss,p,olog)); + } + public: + IntegerObjectiveComparison(void) + : Base("FlatZinc::IntegerObjectiveComparison") {} + + virtual bool run(void) { + using namespace Gecode; + std::unique_ptr one = + model("var 1..1: x; solve minimize x;\n"); + std::unique_ptr two = + model("var 2..2: x; solve minimize x;\n"); + std::unique_ptr high = + model("var 2..2: x; solve maximize x;\n"); + std::unique_ptr low = + model("var 1..1: x; solve maximize x;\n"); + if (!one || !two || !high || !low || + (one->compare(*two) != SpaceComparison::Better) || + (two->compare(*one) != SpaceComparison::Worse) || + (one->compare(*one) != SpaceComparison::Equivalent) || + (high->compare(*low) != SpaceComparison::Better)) + return false; + try { + (void) one->compare(*high); + return false; + } catch (const SpaceIncompatibleObjectives&) {} + std::unique_ptr sat = + model("var 1..1: x; solve satisfy;\n"); + if (!sat) + return false; + try { + (void) sat->compare(*sat); + return false; + } catch (const SpaceNoComparison&) {} + return true; + } + }; + + IntegerObjectiveComparison integer_objective_comparison; + +#ifdef GECODE_HAS_FLOAT_VARS + /// Verify float objective comparison and its interval-valued cuts. + class FloatObjectiveComparison : public Base { + private: + static std::unique_ptr + model(Gecode::FloatVal v, bool minimize, Gecode::FloatNum step=0.0) { + std::stringstream source; + source << std::showpoint + << std::setprecision(std::numeric_limits::max_digits10) + << "var float: x = " << v.min() << "; solve " + << (minimize ? "minimize" : "maximize") + << " x;\n"; + Gecode::FlatZinc::Printer p; + std::unique_ptr result + (Gecode::FlatZinc::parse(source,p,olog)); + if (result) { + result->fv[result->optVar()] = + Gecode::FloatVar(*result,v.min(),v.max()); + result->step = step; + } + return result; + } + + static bool admitted(Gecode::FloatVal candidate, + const Gecode::FlatZinc::FlatZincSpace& incumbent, + bool minimize, Gecode::FloatNum step) { + std::unique_ptr c = + model(candidate,minimize,step); + c->constrain(incumbent); + return c->status() != Gecode::SS_FAILED; + } + public: + FloatObjectiveComparison(void) + : Base("FlatZinc::FloatObjectiveComparison") {} + + virtual bool run(void) { + using namespace Gecode; + using Gecode::FlatZinc::FlatZincSpace; + const FloatNum next = std::nextafter(1.0,2.0); + std::unique_ptr m9=model(9.5,true,1.0); + std::unique_ptr m10=model(10.0,true,1.0); + std::unique_ptr m10b=model(10.0,true,1.0); + std::unique_ptr x11=model(10.5,false,1.0); + std::unique_ptr x10=model(10.0,false,1.0); + std::unique_ptr x10b=model(10.0,false,1.0); + std::unique_ptr adjacent=model(FloatVal(1.0,next),true); + std::unique_ptr adjacent_key=model(1.0,true); + std::unique_ptr adjacent_max= + model(FloatVal(1.0,next),false); + std::unique_ptr adjacent_max_key=model(next,false); + if (!m9 || !m10 || !m10b || !x11 || !x10 || !x10b || !adjacent || + !adjacent_key || + !adjacent_max || !adjacent_max_key || + (m9->compare(*m10) != SpaceComparison::Better) || + (m10->compare(*m9) != SpaceComparison::Worse) || + (m10->compare(*m10b) != SpaceComparison::Equivalent) || + (x11->compare(*x10) != SpaceComparison::Better) || + (x10->compare(*x11) != SpaceComparison::Worse) || + (x10->compare(*x10b) != SpaceComparison::Equivalent) || + (adjacent->compare(*adjacent_key) != SpaceComparison::Equivalent) || + (adjacent_max->compare(*adjacent_max_key) != SpaceComparison::Equivalent)) + return false; + + const FloatVal probes[] = {FloatVal(8.4), FloatVal(8.5), + FloatVal(8.9), FloatVal(9.0)}; + for (unsigned int i=0; i zero=model(10.0,true); + if (admitted(FloatVal(10.0),*zero,true,0.0) || + !admitted(FloatVal(9.0),*zero,true,0.0) || + admitted(FloatVal(11.0),*x10,false,1.0) || + !admitted(FloatVal(11.1),*x10,false,1.0)) + return false; + + FloatVal before=m9->fv[m9->optVar()].val(); + FloatVal before_other=m10->fv[m10->optVar()].val(); + (void) m9->compare(*m10); + if ((m9->fv[m9->optVar()].val().min() != before.min()) || + (m9->fv[m9->optVar()].val().max() != before.max()) || + (m10->fv[m10->optVar()].val().min() != before_other.min()) || + (m10->fv[m10->optVar()].val().max() != before_other.max())) + return false; + std::unique_ptr different_step=model(10.0,true,0.0); + try { (void) m10->compare(*different_step); return false; } + catch (const SpaceIncompatibleObjectives&) {} + try { (void) m10->compare(*x10); return false; } + catch (const SpaceIncompatibleObjectives&) {} + return true; + } + }; + + FloatObjectiveComparison float_objective_comparison; +#endif + /// Verify that statistics do not override an explicit Gist mode. class GistStatisticsMode : public Base { private: diff --git a/test/search.cpp b/test/search.cpp index 411b5a6dfa..7fc63560f1 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -38,11 +38,15 @@ #include #include #include +#ifdef GECODE_HAS_THREADS +#include +#endif #include "test/test.hh" #include #include +#include #include #include #include @@ -152,12 +156,16 @@ namespace Test { ceiling = static_cast(s).node().cost; if (node().cost >= ceiling) fail(); } + SpaceComparison compare(const Space& s) const override { + int a = node().cost; + int b = static_cast(s).node().cost; + return (a < b) ? SpaceComparison::Better : ((a > b) ? SpaceComparison::Worse : SpaceComparison::Equivalent); + } /// Guidance minimizing cost, or maximizing negated cost static Gecode::Search::HeuristicGuidance guidance(bool max, bool ranked, bool dominance, bool keyed) { using Gecode::Search::HeuristicGuidance; - HeuristicGuidance g(max ? HeuristicGuidance::MAXIMIZE : - HeuristicGuidance::MINIMIZE, + HeuristicGuidance g(max ? Sense::Maximize : Sense::Minimize, [](const Space& s) -> std::int64_t { const TreeSpace& t = static_cast(s); return t.maximize ? -t.node().bound : t.node().bound; @@ -464,6 +472,10 @@ namespace Test { virtual void constrain(const Space&) { fail(); } + /// Treat the single solution as equivalent across best-search assets + virtual SpaceComparison compare(const Space&) const { + return SpaceComparison::Equivalent; + } /// Return number of solutions virtual int solutions(void) const { return 1; @@ -557,6 +569,41 @@ namespace Test { } } } + /// Compare objectives used by best solution search + virtual SpaceComparison compare(const Space& _s) const { + const HasSolutions& s = dynamic_cast(_s); + if (htc != s.htc) + throw DynamicCastFailed("HasSolutions::compare"); + int c=0; + int sc=0; + switch (htc) { + case HTC_LEX_LE: + case HTC_LEX_GR: + for (int i=0; i s.x[i].val()); + return better ? SpaceComparison::Better : SpaceComparison::Worse; + } + return SpaceComparison::Equivalent; + case HTC_BAL_LE: + case HTC_BAL_GR: + c = std::abs(x[0].val()+x[1].val()+x[2].val()- + x[3].val()-x[4].val()-x[5].val()); + sc = std::abs(s.x[0].val()+s.x[1].val()+s.x[2].val()- + s.x[3].val()-s.x[4].val()-s.x[5].val()); + if (c == sc) + return SpaceComparison::Equivalent; + return ((htc == HTC_BAL_LE) ? (c < sc) : (c > sc)) ? + SpaceComparison::Better : SpaceComparison::Worse; + case HTC_NONE: + return SpaceComparison::Equivalent; + default: + GECODE_NEVER; + } + return SpaceComparison::Incomparable; + } /// Return number of solutions virtual int solutions(void) const { if (htb1 == HTB_NONE) { @@ -605,6 +652,9 @@ namespace Test { virtual bool master(const MetaInfo& mi) { switch (mi.type()) { case MetaInfo::RESTART: + // With an objective, restart from a bound improving on the last solution + if (htc != HTC_NONE) + return Space::master(mi); if (mi.last() != nullptr) { const HasSolutions* s = static_cast(mi.last()); @@ -813,7 +863,9 @@ namespace Test { o.threads = threads; o.worker_control = control; o.stop = &pause; - HasSolutions root(HTB_BINARY,HTB_BINARY,HTB_BINARY); + // Best-solution search needs an objective; it then ends with the best + HasSolutions root(HTB_BINARY,HTB_BINARY,HTB_BINARY, + E::best ? HTC_LEX_LE : HTC_NONE); E engine(&root,o); auto result = std::async(std::launch::async,[&] { return engine.next(); }); auto reached = pause.reached.get_future(); @@ -822,21 +874,22 @@ namespace Test { std::future_status::timeout; control.request(1U); int solutions = 0; - if (HasSolutions* solution = result.get()) { + std::unique_ptr last(result.get()); + if (last) ++solutions; - delete solution; - } // Alternate expansion and shrinking at solution boundaries. This - // exercises each request while preserving complete enumeration. + // exercises each request while preserving complete search. while (true) { control.request((solutions % 2) ? threads : 1U); HasSolutions* solution = engine.next(); if (!solution) break; ++solutions; - delete solution; + last.reset(solution); } - return ok && !engine.stopped() && (solutions == root.solutions()); + bool complete = E::best ? + (last && last->best()) : (solutions == root.solutions()); + return ok && !engine.stopped() && complete; } #ifdef GECODE_HAS_EXPERIMENTAL template class E> @@ -1142,6 +1195,776 @@ namespace Test { WorkerControlPBSPause worker_control_pbs_pause; + /// Scalar integer objective used for comparison tests + class MinObjective : public IntMinimizeSpace { + public: + IntVar x; + MinObjective(int l, int u) : x(*this,l,u) {} + MinObjective(MinObjective& s) : IntMinimizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new MinObjective(*this); } + virtual IntVar cost(void) const { return x; } + }; + + /// Scalar maximization objective used to check objective families + class MaxObjective : public IntMaximizeSpace { + public: + IntVar x; + MaxObjective(int v) : x(*this,v,v) {} + MaxObjective(MaxObjective& s) : IntMaximizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new MaxObjective(*this); } + virtual IntVar cost(void) const { return x; } + }; + + /// Objective used to test external incumbent updates + class ExternalObjective : public IntMinimizeSpace { + public: + /// Per-test count of posted improvement constraints (optional) + std::atomic* constraints; + IntVar x; + ExternalObjective(std::atomic* c) : constraints(c), x(*this,0,10) { + Gecode::branch(*this,x,INT_VAL_MIN()); + } + ExternalObjective(int v) : constraints(nullptr), x(*this,v,v) {} + ExternalObjective(ExternalObjective& s) + : IntMinimizeSpace(s), constraints(s.constraints) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new ExternalObjective(*this); } + virtual IntVar cost(void) const { return x; } + virtual void constrain(const Space& s) { + if (constraints != nullptr) + constraints->fetch_add(1); + IntMinimizeSpace::constrain(s); + } + }; + + /// Small objective whose solutions arrive from worst to best + class ParallelObjective : public IntMinimizeSpace { + public: + IntVar x; + ParallelObjective(void) : x(*this,0,10) { + Gecode::branch(*this,x,INT_VAL_MAX()); + } + ParallelObjective(int v) : x(*this,v,v) {} + ParallelObjective(ParallelObjective& s) : IntMinimizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new ParallelObjective(*this); } + virtual IntVar cost(void) const { return x; } + virtual bool master(const MetaInfo& mi) { + if (mi.type() == MetaInfo::PORTFOLIO) + return false; + return Space::master(mi); + } + }; + + /// Comparison error raised by a model + class ComparisonError : public Exception { + public: + ComparisonError(void) : Exception("ParallelObjective::compare", + "model comparison failed") {} + }; + + /// Objective used to exercise asynchronous comparison failures + class FailingParallelObjective : public Space { + public: + enum Failure { MISSING, THROWN, INCOMPARABLE }; + /// Per-test count of live spaces + std::atomic& live; + IntVar x; + Failure failure; + FailingParallelObjective(Failure f, std::atomic& l) + : live(l), x(*this,0,10), failure(f) { + live++; + Gecode::branch(*this,x,INT_VAL_MAX()); + } + FailingParallelObjective(FailingParallelObjective& s) + : Space(s), live(s.live), failure(s.failure) { + live++; + x.update(*this,s.x); + } + virtual ~FailingParallelObjective(void) { live--; } + virtual Space* copy(void) { + return new FailingParallelObjective(*this); + } + virtual SpaceComparison compare(const Space& s) const { + if (failure == MISSING) + return Space::compare(s); + if (failure == THROWN) + throw ComparisonError(); + return SpaceComparison::Incomparable; + } + virtual bool master(const MetaInfo& mi) { + if (mi.type() == MetaInfo::PORTFOLIO) + return false; + return Space::master(mi); + } + }; + + + /// Objective with a genuine partial-order result + class IncomparableObjective : public ExternalObjective { + public: + IncomparableObjective(int v) : ExternalObjective(v) {} + IncomparableObjective(IncomparableObjective& s) : ExternalObjective(s) {} + virtual Space* copy(void) { return new IncomparableObjective(*this); } + virtual SpaceComparison compare(const Space&) const { + return SpaceComparison::Incomparable; + } + }; + + /// Search model without objective comparison support + class UnsupportedObjective : public Space { + public: + UnsupportedObjective(void) {} + UnsupportedObjective(UnsupportedObjective& s) : Space(s) {} + virtual Space* copy(void) { return new UnsupportedObjective(*this); } + }; + + /// Test sequential BAB and RBS external incumbent arbitration + class ExternalIncumbent : public Base { + private: + template + static bool updates(Engine& e, const std::atomic& constraints) { + ExternalObjective five(5), equal(5), worse(7), better(3); + int n = constraints; + e.constrain(five); + int installed = constraints; + e.constrain(equal); + e.constrain(worse); + if ((installed <= n) || (constraints != installed)) + return false; + e.constrain(better); + return constraints > installed; + } + /// Whether engine \a e reports an incomparable incumbent (deletes \a e) + static bool rejects_incomparable(Gecode::Search::Engine* e) { + std::unique_ptr engine(e); + IncomparableObjective incomparable(4), incumbent(5); + engine->constrain(incumbent); + try { + engine->constrain(incomparable); + } catch (const Gecode::Search::Incomparable&) { + return true; + } + return false; + } + public: + ExternalIncumbent(void) : Base("Search::ExternalIncumbent") {} + virtual bool run(void) { + Gecode::Search::Options o; + std::atomic constraints(0); + ExternalObjective* bm = new ExternalObjective(&constraints); + Gecode::Search::Engine* bab = Gecode::Search::babengine(bm,o); + delete bm; + if (!updates(*bab,constraints)) { + delete bab; + return false; + } + delete bab; + + o.cutoff = Gecode::Search::Cutoff::constant(10); + ExternalObjective* rm = new ExternalObjective(&constraints); + Gecode::Search::Engine* rbs = + Gecode::Search::build >(rm,o); + delete rm; + if (!updates(*rbs,constraints)) { + delete rbs; + return false; + } + delete rbs; + + ExternalObjective im(nullptr); + if (!rejects_incomparable(Gecode::Search::babengine(&im,Gecode::Search::Options()))) + return false; +#ifdef GECODE_HAS_EXPERIMENTAL + Gecode::Search::HeuristicGuidance g(Gecode::Sense::Minimize, + [](const Space& s) -> std::int64_t { + return static_cast(s).x.min(); + }); + for (double threads : {1.0,2.0}) { + Gecode::Search::Options ho; + ho.threads = threads; + ho.guidance = &g; + if (!rejects_incomparable(Gecode::Search::build(&im,ho)) || + !rejects_incomparable(Gecode::Search::build(&im,ho))) + return false; + } +#endif + + UnsupportedObjective unsupported; + UnsupportedObjective* um = + static_cast(unsupported.clone()); + Gecode::Search::Engine* missing = Gecode::Search::babengine( + um,Gecode::Search::Options()); + delete um; + missing->constrain(unsupported); + try { + missing->constrain(unsupported); + delete missing; + return false; + } catch (const SpaceNoComparison&) {} + delete missing; + return true; + } + }; + + ExternalIncumbent external_incumbent; + +#ifdef GECODE_HAS_THREADS + /// Test parallel BAB solution arbitration and failure delivery + class ParallelBABComparison : public Base { + private: + static Gecode::Search::Options options(void) { + Gecode::Search::Options o; + o.threads = 2; + return o; + } + static bool resetSearch(Gecode::Search::Engine* e) { + e->reset(new ParallelObjective); + int previous = 11; + ParallelObjective* s; + while ((s = static_cast(e->next())) != nullptr) { + int value = s->x.val(); + delete s; + if (value >= previous) + return false; + previous = value; + } + return previous == 0; + } + static bool pending_bound(int bound) { + Gecode::Search::Par::BAB + bab(nullptr,options()); + for (int v=10; v>=8; v--) + bab.solution(new ParallelObjective(v)); + ParallelObjective incumbent(bound); + bab.constrain(incumbent); + for (int v=10; v>=8; v--) { + if (v >= bound) + continue; + ParallelObjective* s = + static_cast(bab.next()); + bool correct = (s != nullptr) && (s->x.val() == v); + delete s; + if (!correct) { + olog << "Pending solution violates bound " << bound + << "; expected " << v << std::endl; + return false; + } + } + Space* s = bab.next(); + bool exhausted = (s == nullptr); + delete s; + if (!exhausted) + olog << "Unexpected pending solution after bound " << bound + << std::endl; + return exhausted; + } + static bool pending_failure(void) { + std::atomic live(0); + bool reported = false; + bool preserved = false; + { + Gecode::Search::Par::BAB + bab(nullptr,options()); + bab.solution(new FailingParallelObjective( + FailingParallelObjective::THROWN,live)); + delete bab.next(); + bab.solution(new FailingParallelObjective( + FailingParallelObjective::THROWN,live)); + try { (void) bab.nogoods(); } + catch (const ComparisonError&) { reported = true; } + // An external update must report the original worker failure + // before invoking this incompatible incumbent's comparison. + UnsupportedObjective incumbent; + try { bab.constrain(incumbent); } + catch (const ComparisonError&) { preserved = true; } + catch (const SpaceNoComparison&) {} + } + if (!reported || !preserved) + olog << "Pending failure: nogoods reported=" << reported + << ", constrain preserved=" << preserved << std::endl; + return reported && preserved && (live == 0); + } + static bool missingFailure(void) { + std::atomic live(0); + Gecode::Search::TimeStop stop(5000); + Gecode::Search::Options o = options(); + o.stop = &stop; + FailingParallelObjective* m = + new FailingParallelObjective(FailingParallelObjective::MISSING,live); + Gecode::Search::Engine* e = Gecode::Search::babengine(m,o); + delete m; + bool repeated = false; + try { + while (Space* s = e->next()) delete s; + } catch (const SpaceNoComparison&) { + try { (void) e->next(); } + catch (const SpaceNoComparison&) { repeated = true; } + } + if (!repeated) { + delete e; + return false; + } + bool recovered = resetSearch(e); + delete e; + return recovered && (live == 0); + } + static bool thrownFailure(void) { + std::atomic live(0); + Gecode::Search::TimeStop stop(5000); + Gecode::Search::Options o = options(); + o.stop = &stop; + FailingParallelObjective* m = + new FailingParallelObjective(FailingParallelObjective::THROWN,live); + Gecode::Search::Engine* e = Gecode::Search::babengine(m,o); + delete m; + try { + while (Space* s = e->next()) delete s; + } catch (const ComparisonError&) { + bool recovered = resetSearch(e); + delete e; + return recovered && (live == 0); + } + delete e; + return false; + } + static bool incomparableFailure(void) { + std::atomic live(0); + Gecode::Search::TimeStop stop(5000); + Gecode::Search::Options o = options(); + o.stop = &stop; + FailingParallelObjective* m = new FailingParallelObjective( + FailingParallelObjective::INCOMPARABLE,live); + Gecode::Search::Engine* e = Gecode::Search::babengine(m,o); + delete m; + try { + while (Space* s = e->next()) delete s; + } catch (const Gecode::Search::Incomparable&) { + bool recovered = resetSearch(e); + delete e; + return recovered && (live == 0); + } + delete e; + return false; + } + public: + ParallelBABComparison(void) : Base("Search::ParallelBABComparison") {} + virtual bool run(void) { + bool pending = true; + for (int bound=11; bound>=7; bound--) + if (!pending_bound(bound)) + pending = false; + if (!pending_failure() || !pending) + return false; + Gecode::Search::TimeStop stop(5000); + Gecode::Search::Options o = options(); + o.stop = &stop; + ParallelObjective* m = new ParallelObjective; + Gecode::BAB bab(m,o); + delete m; + int previous = 11; + ParallelObjective* s; + while ((s = bab.next()) != nullptr) { + int value = s->x.val(); + delete s; + if (value >= previous) + return false; + previous = value; + } + if (previous != 0) + return false; + + m = new ParallelObjective; + Gecode::Search::Engine* bounded = Gecode::Search::babengine(m,o); + delete m; + if (Space* first = bounded->next()) + delete first; + // This is stronger than every solution in the model, so it also + // supersedes any results queued while the first result was returned. + ParallelObjective bound(-1); + bounded->constrain(bound); + while ((s = static_cast(bounded->next())) != + nullptr) { + int value = s->x.val(); + delete s; + if (value >= -1) { + delete bounded; + return false; + } + } + delete bounded; + return missingFailure() && thrownFailure() && incomparableFailure(); + } + }; + + ParallelBABComparison parallel_bab_comparison; +#endif + + /// Test portfolio comparison, external bounds, and nested failures + class PortfolioComparison : public Base { + private: + static Gecode::Search::Options options(void) { + Gecode::Search::Options o; + o.assets = 2; + o.threads = 2; + return o; + } + static bool failure(FailingParallelObjective::Failure f, + double threads=2.0) { + std::atomic live(0); + bool caught = false; + { + FailingParallelObjective* m = new FailingParallelObjective(f,live); + Gecode::Search::Options o = options(); + o.threads = threads; + Gecode::PBS pbs(m,o); + delete m; + try { + while (Space* s = pbs.next()) delete s; + } catch (const SpaceNoComparison&) { + if (f != FailingParallelObjective::MISSING) + return false; + caught = true; + } catch (const ComparisonError&) { + caught = (f == FailingParallelObjective::THROWN); + } catch (const Gecode::Search::Incomparable&) { + caught = (f == FailingParallelObjective::INCOMPARABLE); + } + } + return caught && (live == 0); + } + public: + PortfolioComparison(void) : Base("Search::PortfolioComparison") {} + virtual bool run(void) { + Gecode::Search::Options o = options(); + ParallelObjective* m = new ParallelObjective; + Gecode::PBS pbs(m,o); + delete m; + int previous = 11; + ParallelObjective* s; + while ((s = pbs.next()) != nullptr) { + int value = s->x.val(); + delete s; + if (value >= previous) + return false; + previous = value; + } + if (previous != 0) + return false; + + std::atomic constraints(0); + ExternalObjective* em = new ExternalObjective(&constraints); + Gecode::Search::Engine* external = + Gecode::Search::build >(em,o); + delete em; + ExternalObjective five(5), equal(5), worse(7), better(3); + int n = constraints; + external->constrain(five); + int installed = constraints; + external->constrain(equal); + external->constrain(worse); + if ((installed <= n) || + (constraints != installed)) { + delete external; + return false; + } + external->constrain(better); + if (constraints <= installed) { + delete external; + return false; + } + delete external; + + using namespace Gecode; + Gecode::Search::Options so; + so.threads = 1; + so.cutoff = Gecode::Search::Cutoff::constant(1000000); + SEBs sebs(2); + sebs[0] = bab(so); + sebs[1] = rbs(so); + m = new ParallelObjective; + Gecode::PBS mixed(m,sebs,o); + delete m; + previous = 11; + while ((s = mixed.next()) != nullptr) { + int value = s->x.val(); + delete s; + if (value >= previous) + return false; + previous = value; + } + return (previous == 0) && + failure(FailingParallelObjective::MISSING,1) && + failure(FailingParallelObjective::MISSING) && + failure(FailingParallelObjective::THROWN) && + failure(FailingParallelObjective::INCOMPARABLE); + } + }; + + PortfolioComparison portfolio_comparison; + +#ifdef GECODE_HAS_FLOAT_VARS + /// Stepped float objective for parallel BAB admission + class ParallelFloatObjective : public FloatMinimizeSpace { + public: + FloatVar x; + ParallelFloatObjective(void) + : FloatMinimizeSpace(1.0), x(*this,8.0,10.0) { + Gecode::branch(*this,x,FLOAT_VAL_SPLIT_MAX()); + } + ParallelFloatObjective(FloatNum v) + : FloatMinimizeSpace(1.0), x(*this,v,v) {} + ParallelFloatObjective(ParallelFloatObjective& s) + : FloatMinimizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new ParallelFloatObjective(*this); } + virtual FloatVar cost(void) const { return x; } + }; + + /// Scalar float minimization objective used for comparison and cut tests + class FloatMinObjective : public FloatMinimizeSpace { + public: + FloatVar x; + FloatMinObjective(FloatVal v, FloatNum s=0.0) + : FloatMinimizeSpace(s), x(*this,v.min(),v.max()) {} + FloatMinObjective(FloatMinObjective& s) : FloatMinimizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new FloatMinObjective(*this); } + virtual FloatVar cost(void) const { return x; } + }; + + /// Scalar float maximization objective used for comparison and cut tests + class FloatMaxObjective : public FloatMaximizeSpace { + public: + FloatVar x; + FloatMaxObjective(FloatVal v, FloatNum s=0.0) + : FloatMaximizeSpace(s), x(*this,v.min(),v.max()) {} + FloatMaxObjective(FloatMaxObjective& s) : FloatMaximizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new FloatMaxObjective(*this); } + virtual FloatVar cost(void) const { return x; } + }; +#endif + + /// Lexicographic integer objective used for comparison tests + class LexObjective : public IntLexMinimizeSpace { + public: + IntVarArray x; + LexObjective(int a, int l, int u, int n=2) : x(*this,n,l,u) { + rel(*this,x[0],IRT_EQ,a); + (void) status(); + } + LexObjective(LexObjective& s) : IntLexMinimizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new LexObjective(*this); } + virtual IntVarArgs cost(void) const { return x; } + }; + +#ifdef GECODE_HAS_FLOAT_VARS + /// Test float objective ranking and compatibility with stepped cuts + class FloatObjectiveComparison : public Base { + private: + template + static bool admitted(FloatVal candidate, FloatNum step, + const Objective& incumbent) { + Objective c(candidate,step); + c.constrain(incumbent); + return c.status() != SS_FAILED; + } + public: + FloatObjectiveComparison(void) + : Base("Search::FloatObjectiveComparison") {} + virtual bool run(void) { + const FloatNum next = std::nextafter(1.0,2.0); + FloatMinObjective m9(9.5,1.0), m10(10.0,1.0), + m10b(10.0,1.0), mzero(10.0), madj(FloatVal(1.0,next)); + FloatMaxObjective x11(10.5,1.0), x10(10.0,1.0), + x10b(10.0,1.0), xadj(FloatVal(1.0,next)); + if ((m9.compare(m10) != SpaceComparison::Better) || + (m10.compare(m9) != SpaceComparison::Worse) || + (m10.compare(m10b) != SpaceComparison::Equivalent) || + (x11.compare(x10) != SpaceComparison::Better) || + (x10.compare(x11) != SpaceComparison::Worse) || + (x10.compare(x10b) != SpaceComparison::Equivalent) || + (madj.compare(FloatMinObjective(next)) != SpaceComparison::Equivalent) || + (xadj.compare(FloatMaxObjective(1.0)) != SpaceComparison::Equivalent)) + return false; + + // Equal keys give identical cuts; better keys only tighten them. + const FloatVal probes[] = {FloatVal(8.4), FloatVal(8.5), + FloatVal(8.9), FloatVal(9.0)}; + for (unsigned int i=0; i(probes[i],1.0,m10) != + admitted(probes[i],1.0,m10b)) + return false; + if (admitted(probes[i],1.0,m9) && + !admitted(probes[i],1.0,m10)) + return false; + } + if (admitted(FloatVal(10.0),0.0,mzero) || + !admitted(FloatVal(9.0),0.0,mzero) || + admitted(FloatVal(11.0),1.0,x10) || + !admitted(FloatVal(11.1),1.0,x10)) + return false; + + FloatVal before_m=m9.cost().val(); + FloatVal before_m_other=m10.cost().val(); + FloatVal before_x=x11.cost().val(); + FloatVal before_x_other=x10.cost().val(); + (void) m9.compare(m10); (void) x11.compare(x10); + if ((m9.cost().val().min() != before_m.min()) || + (m9.cost().val().max() != before_m.max()) || + (m10.cost().val().min() != before_m_other.min()) || + (m10.cost().val().max() != before_m_other.max()) || + (x11.cost().val().min() != before_x.min()) || + (x11.cost().val().max() != before_x.max()) || + (x10.cost().val().min() != before_x_other.min()) || + (x10.cost().val().max() != before_x_other.max())) + return false; + try { (void) mzero.compare(m10); return false; } + catch (const SpaceIncompatibleObjectives&) {} + try { (void) m10.compare(x10); return false; } + catch (const DynamicCastFailed&) {} + +#ifdef GECODE_HAS_THREADS + // A bound better by less than the step still replaces the incumbent. + Gecode::Search::TimeStop stop(5000); + Gecode::Search::Options o; + o.threads = 2; + o.stop = &stop; + ParallelFloatObjective* root = new ParallelFloatObjective; + std::unique_ptr + bab(Gecode::Search::babengine(root,o)); + delete root; + bab->constrain(ParallelFloatObjective(10.0)); + bab->constrain(ParallelFloatObjective(9.5)); + int found = 0; + bool substep = true; + while (Space* s = bab->next()) { + found++; + substep = substep && + (static_cast(s)->x.val().max() < 8.5); + delete s; + } + substep = substep && (found == 1) && !bab->stopped(); + if (!substep) + return false; +#endif + return true; + } + }; + + FloatObjectiveComparison float_objective_comparison; +#endif + + /// Lexicographic maximization objective used for comparison tests + class LexMaxObjective : public IntLexMaximizeSpace { + public: + IntVarArray x; + LexMaxObjective(int a) : x(*this,2,0,2) { + rel(*this,x[0],IRT_EQ,a); + (void) status(); + } + LexMaxObjective(LexMaxObjective& s) : IntLexMaximizeSpace(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { return new LexMaxObjective(*this); } + virtual IntVarArgs cost(void) const { return x; } + }; + + /// Space without objective comparison support + class PlainSpace : public Space { + public: + PlainSpace(void) {} + PlainSpace(PlainSpace& s) : Space(s) {} + virtual Space* copy(void) { return new PlainSpace(*this); } + }; + + /// Test objective comparison independently of search arbitration + class Comparison : public Base { + public: + Comparison(void) : Base("Search::Comparison") {} + virtual bool run(void) { + MinObjective one(1,1), two(2,2), one_again(1,1), open(0,2); + if ((one.compare(two) != SpaceComparison::Better) || + (two.compare(one) != SpaceComparison::Worse) || + (one.compare(one_again) != SpaceComparison::Equivalent)) + return false; + MaxObjective high(2), low(1); + if ((high.compare(low) != SpaceComparison::Better) || + (low.compare(high) != SpaceComparison::Worse)) + return false; + if ((compare_int(1,2,Sense::Minimize) != SpaceComparison::Better) || + (compare_int(2,1,Sense::Minimize) != SpaceComparison::Worse) || + (compare_int(1,1,Sense::Minimize) != SpaceComparison::Equivalent) || + (compare_int(2,1,Sense::Maximize) != SpaceComparison::Better) || + (compare_int(1,2,Sense::Maximize) != SpaceComparison::Worse) || + (compare_int(1,1,Sense::Maximize) != SpaceComparison::Equivalent)) + return false; +#ifdef GECODE_HAS_FLOAT_VARS + if ((compare_float(0.5,1.0,Sense::Minimize) != + SpaceComparison::Better) || + (compare_float(1.0,0.5,Sense::Minimize) != + SpaceComparison::Worse) || + (compare_float(1.0,0.5,Sense::Maximize) != + SpaceComparison::Better) || + (compare_float(0.5,0.5,Sense::Maximize) != + SpaceComparison::Equivalent)) + return false; +#endif + LexObjective lp(1,0,2), lq(2,0,2); + if ((lp.compare(lq) != SpaceComparison::Better) || + (lq.compare(lp) != SpaceComparison::Worse)) + return false; + LexMaxObjective lmp(2), lmq(1); + if ((lmp.compare(lmq) != SpaceComparison::Better) || + (lmq.compare(lmp) != SpaceComparison::Worse)) + return false; + try { + (void) open.compare(one); + return false; + } catch (const Int::ValOfUnassignedVar&) {} + try { + (void) one.compare(high); + return false; + } catch (const DynamicCastFailed&) {} + LexObjective short_cost(1,0,2,1); + try { + (void) lp.compare(short_cost); + return false; + } catch (const SpaceIncompatibleObjectives&) {} + { + IntVarArgs a; + IntVarArgs b; + a << IntVar(lp,1,1) << IntVar(lp,3,3); + b << IntVar(lp,1,1) << IntVar(lp,2,2); + if ((compare_lex(a,b,Sense::Minimize) != SpaceComparison::Worse) || + (compare_lex(a,b,Sense::Maximize) != SpaceComparison::Better) || + (compare_lex(a,a,Sense::Minimize) != + SpaceComparison::Equivalent)) + return false; + } + PlainSpace plain; + try { + (void) plain.compare(plain); + return false; + } catch (const SpaceNoComparison&) {} + return true; + } + }; + /// %Test for depth-first search template class DFS : public Test { @@ -1276,13 +2099,13 @@ namespace Test { /// Number of threads unsigned int t; public: - /// Initialize test - RBS(const std::string& e, unsigned int t0) + /// Initialize test, enumerating all solutions without an objective + RBS(const std::string& e, unsigned int t0, HowToConstrain htc0=HTC_NONE) : Test("RBS::"+e+"::"+Model::name()+"::"+str(t0), - HTB_BINARY,HTB_BINARY,HTB_BINARY), t(t0) {} + HTB_BINARY,HTB_BINARY,HTB_BINARY,htc0), t(t0) {} /// Run test virtual bool run(void) { - Model* m = new Model(htb1,htb2,htb3); + Model* m = new Model(htb1,htb2,htb3,htc); Gecode::Search::FailStop f(2); Gecode::Search::Options o; o.threads = t; @@ -1292,16 +2115,30 @@ namespace Test { Gecode::RBS rbs(m,o); int n = m->solutions(); delete m; + // With an objective, every solution must improve on the previous one + Model* b = nullptr; + bool improving = true; while (true) { Model* s = rbs.next(); if (s != nullptr) { - n--; delete s; + n--; + if (htc == HTC_NONE) { + delete s; + } else { + if ((b != nullptr) && (s->compare(*b) != SpaceComparison::Better)) + improving = false; + delete b; b = s; + } } if ((s == nullptr) && !rbs.stopped()) break; f.limit(f.limit()+2); } - return n == 0; + if (htc == HTC_NONE) + return n == 0; + bool ok = improving && (b != nullptr) && b->best(); + delete b; + return ok; } }; @@ -1576,6 +2413,7 @@ namespace Test { public: /// Perform creation and registration Create(void) { + (void) new Comparison; // Depth-first search for (unsigned int t = 1; t<=4; t++) for (unsigned int c_d = 1; c_d<10; c_d++) @@ -1646,7 +2484,7 @@ namespace Test { for (unsigned int t=1; t<=4; t++) { (void) new RBS("DFS",t); (void) new RBS("LDS",t); - (void) new RBS("BAB",t); + (void) new RBS("BAB",t,HTC_LEX_LE); (void) new RBS("DFS",t); (void) new RBS("LDS",t); (void) new RBS("BAB",t);