From 1b660bfef8bffdb024da776a4b25023200d44261 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 19:51:40 +0100 Subject: [PATCH 01/16] Give each restart asset of a portfolio its own cutoff A homogeneous portfolio of restart-based engines, PBS, gave every asset a PbsCutoff that drew its values from one cutoff shared under a mutex. The assets thus advanced a single sequence together, and a random cutoff made all assets restart from the same sequence of values. Cutoff now has a pure virtual copy() that returns a generator in the same state, and each asset that takes ownership of the cutoff gets its own copy. A copy of a random cutoff draws its own sequence. The portfolio deletes the original once it has been built; if building throws, the caller keeps the cutoff, as with RBS. Nested portfolios of restart-based engines are handled the same way, and other engines do not take the cutoff and are left unchanged. This replaces PbsCutoffs, PbsCutoff, make_pbs_cutoffs(), and release_pbs_cutoffs(). --- changelog.in | 11 +++ docs/gecode-7-migration.md | 28 ++++++++ gecode/search.hh | 48 ++++++++++++- gecode/search/cutoff.cpp | 62 +++++++++++++++++ gecode/search/cutoff.hpp | 3 +- gecode/search/pbs.hpp | 135 ++++++++----------------------------- test/search.cpp | 69 ++++++++++++++++++- 7 files changed, 243 insertions(+), 113 deletions(-) diff --git a/changelog.in b/changelog.in index 99dea0fe2f..d92f6eda44 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Give each restart-based asset of a portfolio its own copy of the cutoff. +[MORE] +Cutoff has a new pure virtual function copy(), which custom cutoff generators +must implement. Copies of a random cutoff draw different sequences, so the +assets restart at different times. See docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 26156e5728..5dd81bfe08 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -40,3 +40,31 @@ The examples show typical overrides: large neighbourhood search. - `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for each asset. + +## Cutoff generators implement copy() + +`Search::Cutoff` has a new pure virtual member function: + +```cpp +virtual Gecode::Search::Cutoff* copy(void) const; +``` + +It returns a copy of the generator in its current state that continues the +sequence on its own. A copy of `Cutoff::rnd()` draws its own random +sequence, so that the assets restart at different times. A portfolio of +restart-based engines, `PBS`, gives each asset its own copy of the +cutoff in its options and deletes the original once the portfolio is built. +In Gecode 6.6, the assets drew their values from one shared cutoff sequence. + +A custom cutoff generator must implement `copy()`. For a generator whose +state is plain data, the copy constructor suffices: + +```cpp +Gecode::Search::Cutoff* +MyCutoff::copy(void) const { + return new MyCutoff(*this); +} +``` + +A generator that owns other generators copies them with their own +`copy()`. diff --git a/gecode/search.hh b/gecode/search.hh index 05d2a8057c..070b170ad3 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -487,6 +487,15 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const = 0; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void) = 0; + /** + * \brief Return a copy of this generator in its current state + * + * The copy continues the sequence independently of this generator, + * except that a copy of a random generator draws its own sequence + * (see CutoffRandom::copy()). A portfolio of restart-based engines + * gives each asset its own copy. + */ + virtual Cutoff* copy(void) const = 0; /// Destructor virtual ~Cutoff(void); //@} @@ -542,6 +551,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -561,6 +572,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -588,6 +601,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -609,6 +624,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -627,6 +644,8 @@ namespace Gecode { namespace Search { unsigned long long int step; /// Current value unsigned long long int cur; + /// Number of copies made of this generator + mutable unsigned int copies; public: /// Constructor CutoffRandom(unsigned int seed, @@ -636,6 +655,17 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /** + * \brief Return a copy of this generator with its own random sequence + * + * The copy draws its values, starting with its current one, from a + * seed that depends on the state of this generator and on how many + * copies of it have been made before. Copies made one after the + * other thus have different sequences, so that the assets of a + * portfolio restart at different times, and the same program + * creates the same sequences. + */ + virtual Cutoff* copy(void) const; }; /** @@ -657,6 +687,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffAppend(void); }; @@ -678,6 +710,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffMerge(void); }; @@ -703,6 +737,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffRepeat(void); }; @@ -1470,7 +1506,12 @@ namespace Gecode { class RBS : public Search::Base { using Search::Base::e; public: - /// Initialize engine for space \a s and options \a o + /** + * \brief Initialize engine for space \a s and options \a o + * + * The engine takes ownership of the cutoff in \a o. If the + * constructor throws an exception, the caller keeps the cutoff. + */ RBS(T* s, const Search::Options& o); /// Whether engine does best solution search static const bool best = E::best; @@ -1546,8 +1587,9 @@ namespace Gecode { * PBS does not allocate workers or adjust those controls. * * When the assets are restart-based engines, the portfolio takes - * ownership of the cutoff in \a o and the assets share its sequence: - * each restart of an asset takes the next value of the sequence. + * ownership of the cutoff in \a o and gives each asset its own copy + * (see Cutoff::copy()). If the constructor throws an exception, the + * caller keeps the cutoff. * * The class \a T can implement member functions * \code virtual bool hub(const MetaInfo& mi) \endcode diff --git a/gecode/search/cutoff.cpp b/gecode/search/cutoff.cpp index 54a5483d4b..be173d5943 100755 --- a/gecode/search/cutoff.cpp +++ b/gecode/search/cutoff.cpp @@ -36,6 +36,7 @@ */ #include +#include #include namespace Gecode { namespace Search { @@ -49,6 +50,11 @@ namespace Gecode { namespace Search { return c; } + Cutoff* + CutoffConstant::copy(void) const { + return new CutoffConstant(*this); + } + unsigned long long int CutoffLinear::operator ()(void) const { @@ -60,6 +66,11 @@ namespace Gecode { namespace Search { return n; } + Cutoff* + CutoffLinear::copy(void) const { + return new CutoffLinear(*this); + } + unsigned long int CutoffLuby::start[CutoffLuby::n_start] = { @@ -75,6 +86,11 @@ namespace Gecode { namespace Search { return scale*luby(i++); } + Cutoff* + CutoffLuby::copy(void) const { + return new CutoffLuby(*this); + } + unsigned long long int CutoffGeometric::operator ()(void) const { @@ -86,6 +102,11 @@ namespace Gecode { namespace Search { return static_cast(scale * n); } + Cutoff* + CutoffGeometric::copy(void) const { + return new CutoffGeometric(*this); + } + unsigned long long int CutoffRandom::operator ++(void) { @@ -97,6 +118,17 @@ namespace Gecode { namespace Search { return cur; } + Cutoff* + CutoffRandom::copy(void) const { + CutoffRandom* c = new CutoffRandom(*this); + // Derive a distinct seed for each copy, the golden ratio spreads them + copies++; + c->rnd.seed(rnd.seed() + copies * 0x9e3779b9U); + c->copies = 0U; + (void) ++(*c); + return c; + } + unsigned long long int CutoffAppend::operator ()(void) const { @@ -116,6 +148,16 @@ namespace Gecode { namespace Search { } } + Cutoff* + CutoffAppend::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffAppend(d1.get(),n,d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffMerge::operator ()(void) const { @@ -128,6 +170,16 @@ namespace Gecode { namespace Search { return (*c1)(); } + Cutoff* + CutoffMerge::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffMerge(d1.get(),d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffRepeat::operator ()(void) const { @@ -143,6 +195,16 @@ namespace Gecode { namespace Search { return cutoff; } + Cutoff* + CutoffRepeat::copy(void) const { + std::unique_ptr d1(c->copy()); + CutoffRepeat* d = new CutoffRepeat(d1.get(),n); + (void) d1.release(); + d->cutoff = cutoff; + d->i = i; + return d; + } + Cutoff* Cutoff::constant(unsigned long long int scale) { diff --git a/gecode/search/cutoff.hpp b/gecode/search/cutoff.hpp index 441a286e1f..c52b82d6b5 100755 --- a/gecode/search/cutoff.hpp +++ b/gecode/search/cutoff.hpp @@ -91,7 +91,8 @@ namespace Gecode { namespace Search { unsigned long long int n0) : rnd(seed), min(min0), n(n0), step(std::max(1ULL, - static_cast((max0-min0+1U)/n))) { + static_cast((max0-min0+1U)/n))), + copies(0U) { cur = ++(*this); } diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index b5d2a67c9e..96c6ee48b5 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -129,109 +129,34 @@ namespace Gecode { namespace Search { }; /** - * \brief Cutoff sequence shared by the assets of a portfolio + * \brief Return the cutoff for the next asset of a portfolio * - * A cutoff cannot be copied, so the assets of a portfolio that each take - * ownership of a cutoff get a PbsCutoff each, drawing from one sequence. - * The sequence is disposed with the last PbsCutoff and the reference held - * while the portfolio is built. The original cutoff is disposed as well - * only if building has succeeded, otherwise it stays with the caller. - * - * \internal - */ - class PbsCutoffs : public HeapAllocated { - public: - /// Mutex protecting the sequence, assets can run in parallel - Support::Mutex m; - /// The shared cutoff sequence - Cutoff* c; - /// Number of references - unsigned int n; - /// Whether the cutoff sequence is disposed with the last reference - bool owner; - /// Initialize for cutoff \a c0 with the reference held while building - PbsCutoffs(Cutoff* c0) : c(c0), n(1U), owner(false) {} - /// Release a reference - static void release(PbsCutoffs* s) { - bool last; - { - Support::Lock lock(s->m); - last = (--s->n == 0U); - } - if (last) { - if (s->owner) - delete s->c; - delete s; - } - } - }; - - /** - * \brief Cutoff of a portfolio asset, the assets share the sequence of values - * \internal - */ - class PbsCutoff : public Cutoff { - protected: - /// The shared sequence - PbsCutoffs* s; - /// The current cutoff value of this asset - unsigned long long int v; - public: - /// Initialize as a new reference to \a s0 - PbsCutoff(PbsCutoffs* s0) : s(s0) { - Support::Lock lock(s->m); - v = (*s->c)(); - s->n++; - } - /// Return the current cutoff value - unsigned long long int operator ()(void) const override { - return v; - } - /// Take the next value of the shared sequence and return it - unsigned long long int operator ++(void) override { - Support::Lock lock(s->m); - v = ++(*s->c); - return v; - } - /// Release the reference to the shared sequence - ~PbsCutoff(void) override { - PbsCutoffs::release(s); - } - }; - - /** - * \brief Return the cutoffs shared by the assets of a portfolio - * - * Returns nullptr if the assets of engine \a E do not take ownership of - * the cutoff in \a opt, or if there are fewer than two assets. + * When the assets of engine \a E take ownership of the cutoff \a c, + * each asset gets its own copy of \a c, and the portfolio deletes \a c + * once it has been built. Otherwise the assets share \a c and the caller + * keeps it. * * \internal */ template - forceinline PbsCutoffs* - make_pbs_cutoffs(const Options& opt, unsigned int n_assets) { - if (!PbsOwnsCutoff::value || (opt.cutoff == nullptr) || - (n_assets < 2U)) + forceinline std::unique_ptr + pbs_cutoff(const Cutoff* c) { + if (!PbsOwnsCutoff::value || (c == nullptr)) return nullptr; - return new PbsCutoffs(opt.cutoff); + return std::unique_ptr(c->copy()); } /** - * \brief Release the cutoffs \a cs held while building - * - * The flag \a built tells whether building has succeeded. + * \brief Delete the cutoff \a c of a built portfolio if its assets of + * engine \a E own copies * * \internal */ + template forceinline void - release_pbs_cutoffs(PbsCutoffs* cs, bool built) { - if (cs == nullptr) - return; - { - Support::Lock lock(cs->m); - cs->owner = built; - } - PbsCutoffs::release(cs); + pbs_release_cutoff(Cutoff* c) { + if (PbsOwnsCutoff::value) + delete c; } /// A PBS engine builder @@ -319,8 +244,8 @@ namespace Gecode { namespace Search { WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, n_assets); + Cutoff* cutoff = opt.cutoff; Space* unowned_hub = hub; - PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { for (unsigned int i=0U; ispoke(i); - std::unique_ptr cutoff; - if (cutoffs != nullptr) { - cutoff.reset(new PbsCutoff(cutoffs)); - opt.cutoff = cutoff.get(); - } + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } Engine* e = Seq::pbsengine( assets,stops,n_assets,stat,opt,E::best); - release_pbs_cutoffs(cutoffs,true); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } @@ -421,8 +343,8 @@ namespace Gecode { namespace Search { stops[i] = nullptr; } + Cutoff* cutoff = opt.cutoff; Space* unowned_hub = hub; - PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { for (unsigned int i=0U; ispoke(static_cast(i)); - std::unique_ptr cutoff; - if (cutoffs != nullptr) { - cutoff.reset(new PbsCutoff(cutoffs)); - opt.cutoff = cutoff.get(); - } + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); - release_pbs_cutoffs(cutoffs,true); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } diff --git a/test/search.cpp b/test/search.cpp index e1cddede19..426545450b 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3196,7 +3196,74 @@ namespace Test { PBSBuilderStop pbs_builder_stop; - /// Restart-based assets of a portfolio share the cutoff sequence + /// A copy of a cutoff generator continues its sequence independently + class CutoffCopy : public Base { + /// Check that a copy of \a c continues as \a c, then delete \a c + static bool same(Gecode::Search::Cutoff* c) { + std::unique_ptr o(c); + for (int i=0; i<5; i++) + (void) ++(*o); + std::unique_ptr d(o->copy()); + if ((*d)() != (*o)()) + return false; + for (int i=0; i<20; i++) + if (++(*d) != ++(*o)) + return false; + return true; + } + public: + CutoffCopy(void) : Base("Search::Cutoff::Copy") {} + bool run(void) override { + using Gecode::Search::Cutoff; + return same(Cutoff::constant(3)) && same(Cutoff::linear(2)) && + same(Cutoff::geometric(2,1.5)) && same(Cutoff::luby(2)) && + same(Cutoff::append(Cutoff::linear(1),8,Cutoff::luby(3))) && + same(Cutoff::merge(Cutoff::linear(1),Cutoff::geometric(1,2.0))) && + same(Cutoff::repeat(Cutoff::linear(4),3)); + } + }; + + CutoffCopy cutoff_copy; + + /// Copies of a random cutoff generator draw distinct, reproducible sequences + class CutoffRandomCopy : public Base { + /// Return the first values of \a c, which is deleted + static std::vector + values(Gecode::Search::Cutoff* c) { + std::unique_ptr d(c); + std::vector v{(*d)()}; + for (int i=0; i<20; i++) { + v.push_back(++(*d)); + if ((v.back() < 1U) || (v.back() > 1000U)) + return {}; + } + return v; + } + /// Return the values of two copies of a generator with seed \a seed + static std::vector > + copies(unsigned int seed) { + std::unique_ptr + o(Gecode::Search::Cutoff::rnd(seed,1,1000,1000)); + (void) ++(*o); + std::vector > v; + v.push_back(values(o->copy())); + v.push_back(values(o->copy())); + v.push_back(values(o.release())); + return v; + } + public: + CutoffRandomCopy(void) : Base("Search::Cutoff::RandomCopy") {} + bool run(void) override { + std::vector > v = copies(7); + return !v[0].empty() && !v[1].empty() && !v[2].empty() && + (v[0] != v[1]) && (v[0] != v[2]) && (v[1] != v[2]) && + (copies(7) == v); + } + }; + + CutoffRandomCopy cutoff_random_copy; + + /// Each restart-based asset of a portfolio owns a copy of the cutoff class PBSRestartCutoff : public Base { template class Engine> static bool test(unsigned int threads) { From f100a32c4b5898def9508196083e77ba5c401939 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:02:51 +0100 Subject: [PATCH 02/16] Replace stopped() with end_reason() stopped() could not tell an exhausted search from a search that ended without exhausting its search space, so callers took a search that was not stopped as a proof. Search engines now report why next() returned no solution with end_reason(): Exhausted, Incomplete, or Limit, and NotEnded while next() returns solutions. stopped() and the experimental limited() are removed without a replacement alias. Restart-based search reports Exhausted when its hub fails, Limit only for its own stop object, and the end reason of a complete spoke search otherwise. CABS and the parallel frontier engine report Incomplete at their width or frontier limit. Portfolio search keeps its previous behaviour in terms of the new end reasons. FlatZinc reports optimality and unsatisfiability only for an exhausted search, and the script driver reports an incomplete search. --- changelog.in | 13 +++++++ docs/gecode-7-migration.md | 31 +++++++++++++++ examples/job-shop.cpp | 9 +++-- gecode/driver/script.hpp | 6 ++- gecode/flatzinc/flatzinc.cpp | 7 ++-- gecode/search.hh | 49 ++++++++++++++++++------ gecode/search/base.hpp | 6 +-- gecode/search/cabs.cpp | 19 ++------- gecode/search/engine.cpp | 7 ---- gecode/search/par/engine.hh | 6 ++- gecode/search/par/engine.hpp | 15 +++++--- gecode/search/par/frontier.cpp | 24 +++++++----- gecode/search/par/frontier.hh | 8 ++-- gecode/search/par/pbs.hh | 14 +++---- gecode/search/par/pbs.hpp | 37 ++++++++---------- gecode/search/seq/cabs.hh | 4 +- gecode/search/seq/dead.cpp | 17 ++++++--- gecode/search/seq/lds.hh | 8 ++-- gecode/search/seq/lds.hpp | 21 +++++++--- gecode/search/seq/pbs.hh | 16 ++++---- gecode/search/seq/pbs.hpp | 35 +++++++---------- gecode/search/seq/rbs.cpp | 41 +++++++++++--------- gecode/search/seq/rbs.hh | 8 ++-- gecode/search/seq/rbs.hpp | 2 +- gecode/search/support.hh | 20 ++++++---- gecode/search/worker.hh | 7 ++++ test/int/open-var-list.cpp | 2 +- test/nogoods.cpp | 2 +- test/search.cpp | 70 +++++++++++++++++++--------------- 29 files changed, 298 insertions(+), 206 deletions(-) diff --git a/changelog.in b/changelog.in index d92f6eda44..213471335d 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,19 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Replace stopped() of search engines by end_reason(). +[MORE] +end_reason() tells why next() returned no solution: EndReason::Exhausted is a +proof, EndReason::Incomplete is an end without one, and EndReason::Limit is a +stop. stopped() and the experimental limited() are removed. FlatZinc reports +optimality or unsatisfiability only for an exhausted search. See +docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 5dd81bfe08..389d6fb29e 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -68,3 +68,34 @@ MyCutoff::copy(void) const { A generator that owns other generators copies them with their own `copy()`. + +## stopped() is replaced by end_reason() + +`Search::Engine::stopped()` and `Search::Base::stopped()` are removed, +and so is the experimental `limited()`. After `next()` returns no solution, +`end_reason()` tells why: + +```cpp +enum class Gecode::Search::EndReason : unsigned char { + NotEnded, Exhausted, Incomplete, Limit +}; +``` + +| Gecode 6 | Gecode 7 | +|-----------------------------------------------|-------------------------------------------------| +| `stopped()` is true | `end_reason() == EndReason::Limit` | +| `stopped()` is false after no solution | `end_reason() == EndReason::Exhausted` or `EndReason::Incomplete` | +| `limited()` is true (AStar, CABS) | `end_reason() == EndReason::Incomplete` | +| last `next()` returned a solution | `end_reason() == EndReason::NotEnded` | + +`Exhausted` means that the engine explored everything it was asked to +explore: there is no further solution, and the last solution of a +branch-and-bound search is optimal. `Incomplete` means that the engine ended +on its own without that proof, for example CABS at its width limit. Calling +`next()` again does not continue an incomplete search. `Limit` means that a +stop object stopped the engine, and calling `next()` again continues the +search. + +Code that used `!stopped()` as a proof, such as reporting optimality, should +test for `EndReason::Exhausted`. Code that resumes a search after a limit +should test for `EndReason::Limit`. diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index d497ded4c3..33f5eef2db 100755 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -790,11 +790,12 @@ solve(const JobShopOptions& opt) { s->print(std::cout); u = s->cost().val(); delete s; - } else if (rbs.stopped()) { + } else if (rbs.end_reason() == Search::EndReason::Exhausted) { + l = m+1; + } else { + // Stopped, or ended without proving that no solution exists stopped = true; break; - } else { - l = m+1; } } @@ -842,7 +843,7 @@ solve(const JobShopOptions& opt) { Driver::stop(t,std::cout); std::cout << std::endl; - if (rbs.stopped()) { + if (rbs.end_reason() != Search::EndReason::Exhausted) { std::cout << "\t\t\t\tstopped due to time-out..." << std::endl; std::cout << std::endl << "\tSolution at most "; diff --git a/gecode/driver/script.hpp b/gecode/driver/script.hpp index 1c8f707088..8a83556fd2 100755 --- a/gecode/driver/script.hpp +++ b/gecode/driver/script.hpp @@ -427,7 +427,9 @@ namespace Gecode { namespace Driver { CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); s_out << endl; - if (e.stopped()) { + if (e.end_reason() == Search::EndReason::Incomplete) { + l_out << "Search engine finished without exhausting the search space" << '\n' << '\n'; + } else if (e.end_reason() == Search::EndReason::Limit) { l_out << "Search engine stopped..." << endl << "\treason: "; int r = static_cast(so.stop)->reason(stat,so); @@ -572,7 +574,7 @@ namespace Gecode { namespace Driver { delete ex; s_n++; } while (s_n < s_l); - if (e.stopped()) + if (e.end_reason() == Search::EndReason::Limit) stopped = true; } delete sok.stop; diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index c7cffdb5c7..f63de0766e 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -1937,7 +1937,8 @@ namespace Gecode { namespace FlatZinc { bool printAll = _method == SAT || opt.allSolutions() || noOfSolutions != 0; int findSol = noOfSolutions; bool solution_limit_reached = false; - bool engine_stopped = false; + // Only an exhausted search proves optimality or unsatisfiability + bool proof = false; Gecode::Search::Statistics stat; std::unique_ptr sol; { @@ -1958,7 +1959,7 @@ namespace Gecode { namespace FlatZinc { break; } } - engine_stopped = se.stopped(); + proof = se.end_reason() == Search::EndReason::Exhausted; if (opt.mode() == SM_STAT) { stat = se.statistics(); } @@ -1972,7 +1973,7 @@ namespace Gecode { namespace FlatZinc { out << "----------" << std::endl; } if (!solution_limit_reached) { - if (!engine_stopped) { + if (proof) { if (sol) { out << "==========" << std::endl; } else { diff --git a/gecode/search.hh b/gecode/search.hh index 070b170ad3..0e51e75a38 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1093,6 +1093,36 @@ namespace Gecode { namespace Search { namespace Gecode { namespace Search { + /** + * \brief Why the last call to next() of a search engine returned no solution + * + * A search engine reports the reason with end_reason(). Only + * Exhausted is a proof: the space that the engine was given has no + * further solutions (no better ones for best solution search). Any + * other reason after next() returned nullptr means that the engine + * ended without such a proof. + * + * A meta engine (restart-based or portfolio search) reports Limit + * only for a stop object installed above it, not for its own + * cutoffs, slices, or the stop objects of its assets. + * + * \ingroup TaskModelSearch + */ + enum class EndReason : unsigned char { + /// next() has not been called, or the last call returned a solution + NotEnded, + /// The search space is exhausted, calling next() again finds nothing + Exhausted, + /** + * Search finished without exhausting its search space, for example + * at the width limit of CABS. There may be further solutions, but + * calling next() again finds none. + */ + Incomplete, + /// A stop object stopped search, calling next() again resumes it + Limit, + }; + /** * \brief %Search engine implementation interface */ @@ -1109,12 +1139,8 @@ namespace Gecode { namespace Search { virtual Space* next(void) = 0; /// Return statistics virtual Statistics statistics(void) const = 0; - /// Check whether engine has been stopped - virtual bool stopped(void) const = 0; -#ifdef GECODE_HAS_EXPERIMENTAL - /// Whether the engine stopped at a local limit (such as a CABS width limit) and cannot continue - virtual bool limited(void) const; -#endif + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const = 0; /// Constrain future solutions to be better than \a b (raises exception) virtual void constrain(const Space& b); /// Reset engine to restart at space \a s (does nothing) @@ -1148,8 +1174,8 @@ namespace Gecode { namespace Search { virtual T* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~Base(void); private: @@ -1446,9 +1472,10 @@ namespace Gecode { * Search::Options::d_l discrepancies, allowing more discrepancies in each * iteration, starting from none. * - * When next() returns nullptr and stopped() returns false, either the - * search tree has been explored completely, or the discrepancy limit has - * been reached while parts of the tree are still unexplored. The engine + * When next() returns nullptr and end_reason() returns + * Search::EndReason::Exhausted, either the search tree has been explored + * completely, or the discrepancy limit has been reached while parts of + * the tree are still unexplored. The engine * does not report which: a search that finds no (further) solution only * proves that none exists if no path of the tree has more discrepancies * than the limit. diff --git a/gecode/search/base.hpp b/gecode/search/base.hpp index a00bcb5174..bdb78a1386 100644 --- a/gecode/search/base.hpp +++ b/gecode/search/base.hpp @@ -52,9 +52,9 @@ namespace Gecode { namespace Search { return e->statistics(); } template - forceinline bool - Base::stopped(void) const { - return e->stopped(); + forceinline EndReason + Base::end_reason(void) const { + return e->end_reason(); } template forceinline diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index 233cd489b7..2e8e11da9e 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -123,17 +123,6 @@ namespace Gecode { namespace Search { namespace Par { namespace Gecode { namespace Search { namespace Seq { - /// Sequential CABS engine - class CABSEngine : public WorkerToEngine { - public: - /// Initialize for space \a s with options \a o - CABSEngine(Space* s, const Options& o) : WorkerToEngine(s,o) {} - /// Whether search stopped at the width or frontier limit - bool limited(void) const override { - return w.limited(); - } - }; - }}} namespace Gecode { namespace Search { @@ -149,7 +138,7 @@ namespace Gecode { namespace Search { if (e.threads > 1.0) return new Par::CABS(s,e); #endif - return new Seq::CABSEngine(s,e); + return new WorkerToEngine< Seq::CABS>(s,e); } }} @@ -309,9 +298,9 @@ namespace Gecode { namespace Search { namespace Seq { return *this; } - bool - CABS::limited(void) const { - return _limited; + EndReason + CABS::end_reason(void) const { + return _limited ? EndReason::Incomplete : Worker::end_reason(); } void diff --git a/gecode/search/engine.cpp b/gecode/search/engine.cpp index b2a3d31851..63a71d98ff 100644 --- a/gecode/search/engine.cpp +++ b/gecode/search/engine.cpp @@ -49,13 +49,6 @@ namespace Gecode { namespace Search { (void) b; throw NoBest("Engine::constrain"); } -#ifdef GECODE_HAS_EXPERIMENTAL - bool - Engine::limited(void) const { - return false; - } - -#endif void Engine::reset(Space* s) { (void) s; diff --git a/gecode/search/par/engine.hh b/gecode/search/par/engine.hh index 3cd196e36e..50a1be64a1 100644 --- a/gecode/search/par/engine.hh +++ b/gecode/search/par/engine.hh @@ -242,6 +242,8 @@ namespace Gecode { namespace Search { namespace Par { volatile unsigned int n_busy; /// Whether a worker had been stopped std::atomic has_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Number of calls to next() that have started search std::atomic n_runs; /// Whether search state changed such that signal is needed @@ -265,8 +267,8 @@ namespace Gecode { namespace Search { namespace Par { Engine(const Options& o); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; //@} /// Destructor diff --git a/gecode/search/par/engine.hpp b/gecode/search/par/engine.hpp index 35ed2bf141..00233bc2b6 100644 --- a/gecode/search/par/engine.hpp +++ b/gecode/search/par/engine.hpp @@ -57,9 +57,9 @@ namespace Gecode { namespace Search { namespace Par { return static_cast(opt().threads); } template - forceinline bool - Engine::stopped(void) const { - return has_stopped.load(std::memory_order_acquire); + forceinline EndReason + Engine::end_reason(void) const { + return end; } @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Par { _opt(o), scheduler_enabled(false), scheduler_fast_admit(nullptr), scheduler_worker(nullptr), scheduler_requested(workers()), - scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), - _cmd(C_WAIT), solutions(heap) { + scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), _cmd(C_WAIT), solutions(heap), + end(EndReason::NotEnded) { // Initialize termination information _n_term_not_ack = workers(); _n_not_terminated = workers(); @@ -526,6 +526,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // No search needs to be done, take leftover solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); return s; } @@ -533,6 +534,7 @@ namespace Gecode { namespace Search { namespace Par { has_stopped.store(false, std::memory_order_release); // No more solutions? if (n_busy == 0) { + end = EndReason::Exhausted; m_search.release(); return nullptr; } @@ -553,6 +555,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // Report solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); // Make workers wait again block(); @@ -560,6 +563,8 @@ namespace Gecode { namespace Search { namespace Par { } // No more solutions or stopped? if ((n_busy == 0) || has_stopped.load(std::memory_order_acquire)) { + // Workers that still have work have been stopped + end = (n_busy == 0) ? EndReason::Exhausted : EndReason::Limit; m_search.release(); // Make workers wait again block(); diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index 5977f8827f..38b001ae04 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -60,6 +60,7 @@ namespace Gecode { namespace Search { namespace Par { guidance(*o.guidance), best(guidance.sense), order(0), pending(heap), n_pending(0), runners(nullptr), active(0), running(false), shutdown(false), _stopped(false), _limited(false), + end(EndReason::NotEnded), batch(1), keyed(false) {} void @@ -335,6 +336,7 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(error); if (_limited) { _stopped = true; + end = EndReason::Incomplete; return nullptr; } _stopped = false; @@ -348,7 +350,14 @@ namespace Gecode { namespace Search { namespace Par { continue; if (error) std::rethrow_exception(error); - return solution.release(); + Space* s = solution.release(); + if (s != nullptr) + end = EndReason::NotEnded; + else if (_limited) + end = EndReason::Incomplete; + else + end = _stopped ? EndReason::Limit : EndReason::Exhausted; + return s; } } @@ -358,16 +367,10 @@ namespace Gecode { namespace Search { namespace Par { return stat; } - bool - Frontier::stopped(void) const { - Support::Lock lock(mutex); - return _stopped; - } - - bool - Frontier::limited(void) const { + EndReason + Frontier::end_reason(void) const { Support::Lock lock(mutex); - return _limited; + return end; } void @@ -392,6 +395,7 @@ namespace Gecode { namespace Search { namespace Par { solution.reset(); order = 0; _stopped = _limited = false; + end = EndReason::NotEnded; error = nullptr; stat.reset(); initialize(s,false); diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index 23a5075a5a..63fd89a35f 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -110,6 +110,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int active; /// Whether search is running, being shut down, stopped, or limited bool running, shutdown, _stopped, _limited; + /// Why the last call to next() returned no solution + EndReason end; /// First exception thrown by a worker std::exception_ptr error; @@ -160,10 +162,8 @@ namespace Gecode { namespace Search { namespace Par { Space* next(void) override; /// Return statistics Search::Statistics statistics(void) const override; - /// Whether search has been stopped - bool stopped(void) const override; - /// Whether search stopped at the width or frontier limit - bool limited(void) const override; + /// Return why the last call to next() returned no solution + EndReason end_reason(void) const override; /// Constrain future solutions to be better than \a s void constrain(const Space& s) override; /// Reset engine to restart at space \a s diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index fb180a69f0..e8881e7b75 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -102,10 +102,8 @@ namespace Gecode { namespace Search { namespace Par { Asset(PBS* p, Engine* e, Stop* so); /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; /// Return the completion terminator virtual Support::Terminator* terminator(void) const; /// Wait for the asset to complete its current run @@ -181,8 +179,10 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_active; /// Whether an asset has been stopped std::atomic asset_stop; - /// Whether an asset stopped at a local limit + /// Whether an asset finished without exhausting its search space bool incomplete; + /// Why the last call to next() returned no solution + EndReason end; /// Shared stop flag std::atomic tostop; /// Collect solutions in this @@ -214,8 +214,8 @@ namespace Gecode { namespace Search { namespace Par { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index fde4156058..cf2a9da757 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -152,18 +152,9 @@ namespace Gecode { namespace Search { namespace Par { return engine->statistics(); } template - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); - } - template - forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } template forceinline Support::Terminator* @@ -199,7 +190,7 @@ namespace Gecode { namespace Search { namespace Par { const Statistics& stat0) : stat(stat0), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), incomplete(false), tostop(false), n_busy(0) { + asset_stop(false), incomplete(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -229,15 +220,15 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } - } else if (asset->stopped() && !asset->limited()) { + } else if (asset->end_reason() == EndReason::Limit) { if (!tostop.load(std::memory_order_acquire)) { asset_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; } } else { - // The asset is done or stopped at a local limit (then search is incomplete) - if (asset->limited()) + // The asset is done , without a proof if it is incomplete + if (asset->end_reason() == EndReason::Incomplete) incomplete = true; // Move asset to inactive unsigned int i=0; @@ -324,9 +315,6 @@ namespace Gecode { namespace Search { namespace Par { // Invariant all assets are idle! assert(n_busy == 0); - if (solutions.empty() && (n_active == 0) && incomplete) - asset_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) { @@ -340,7 +328,12 @@ namespace Gecode { namespace Search { namespace Par { // Process solutions if (solutions.empty()) { s = nullptr; + if (asset_stop.load(std::memory_order_acquire)) + end = EndReason::Limit; + else + end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; } else { + end = EndReason::NotEnded; Asset* r; s = solutions.get(r); if (Collect::best) { @@ -363,9 +356,9 @@ namespace Gecode { namespace Search { namespace Par { } template - bool - PBS::stopped(void) const { - return asset_stop.load(std::memory_order_acquire); + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/cabs.hh b/gecode/search/seq/cabs.hh index f75e9ed056..05f41e2842 100644 --- a/gecode/search/seq/cabs.hh +++ b/gecode/search/seq/cabs.hh @@ -88,8 +88,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* next(void); /// Return statistics Statistics statistics(void) const; - /// Whether search stopped at the width or frontier limit - bool limited(void) const; + /// Return why next() returned no solution, Incomplete at the width or frontier limit + EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b void constrain(const Space& b); /// Reset engine to restart at space \a s diff --git a/gecode/search/seq/dead.cpp b/gecode/search/seq/dead.cpp index fa8ac10a07..550b87f350 100644 --- a/gecode/search/seq/dead.cpp +++ b/gecode/search/seq/dead.cpp @@ -43,6 +43,9 @@ namespace Gecode { namespace Search { namespace Seq { Tracer tracer; /// Statistics Statistics stat; + /// Why the last call to next() returned no solution + EndReason end; + public: /// Initialize Dead(const Options& o, const Statistics& stat0); @@ -50,15 +53,15 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Delete virtual ~Dead(void); }; template Dead::Dead(const Options& o, const Statistics& stat0) - : tracer(o.tracer), stat(stat0) { + : tracer(o.tracer), stat(stat0) , end(EndReason::NotEnded) { tracer.engine(SearchTracer::EngineType::AOE, 1U); tracer.worker(); } @@ -66,13 +69,15 @@ namespace Gecode { namespace Search { namespace Seq { template Space* Dead::next(void) { + // The root has failed + end = EndReason::Exhausted; return nullptr; } template - bool - Dead::stopped(void) const { - return false; + EndReason + Dead::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/lds.hh b/gecode/search/seq/lds.hh index d95869b55a..35e42f91c9 100644 --- a/gecode/search/seq/lds.hh +++ b/gecode/search/seq/lds.hh @@ -112,8 +112,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* root; /// Current discrepancy unsigned int d; - /// Solution found for current discrepancy - bool no_solution; + /// Why the last call to next() returned no solution + EndReason end; public: /// Initialize for space \a s with options \a o LDS(Space* s, const Options& o); @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Seq { void constrain(const Space& b); /// Reset engine to restart at space \a s void reset(Space* s); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~LDS(void); }; diff --git a/gecode/search/seq/lds.hpp b/gecode/search/seq/lds.hpp index 6a19404392..81f7331a75 100644 --- a/gecode/search/seq/lds.hpp +++ b/gecode/search/seq/lds.hpp @@ -276,7 +276,7 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline LDS::LDS(Space* s, const Options& o) - : opt(o), e(opt), root(nullptr), d(0) { + : opt(o), e(opt), root(nullptr), d(0) , end(EndReason::NotEnded) { e.node = 1; if (s->status(e) == SS_FAILED) { e.fail++; @@ -295,10 +295,18 @@ namespace Gecode { namespace Search { namespace Seq { LDS::next(void) { while (true) { Space* s = e.next(opt); - if (s != nullptr) + if (s != nullptr) { + end = EndReason::NotEnded; return s; - if (((s == nullptr) && e.stopped()) || (++d > opt.d_l) || e.done()) + } + if (e.stopped()) { + end = EndReason::Limit; + break; + } + if ((++d > opt.d_l) || e.done()) { + end = EndReason::Exhausted; break; + } if (d == opt.d_l) { if (root != nullptr) e.reset(root,d); @@ -311,9 +319,9 @@ namespace Gecode { namespace Search { namespace Seq { } template - bool - LDS::stopped(void) const { - return e.stopped(); + EndReason + LDS::end_reason(void) const { + return end; } template @@ -327,6 +335,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline void LDS::reset(Space* s) { delete root; root=nullptr; d=0; + end = EndReason::NotEnded; // Reset the statistics first, so that a failed root is counted e.reset(nullptr,0); if (s == nullptr) diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index ef6cf4537b..008fdb8831 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -85,10 +85,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* next(void); /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run @@ -113,10 +111,10 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_assets; /// Current asset to run unsigned int cur; - /// Whether an asset has been stopped - bool asset_stop; - /// Whether an asset stopped at a local limit + /// Whether an asset finished without exhausting its search space bool incomplete; + /// Why the last call to next() returned no solution + EndReason end; public: /// Initialize PBS(Engine** assets, Stop** stops, unsigned int n, @@ -125,8 +123,8 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 4164993c59..3a234f7174 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -60,17 +60,9 @@ namespace Gecode { namespace Search { namespace Seq { Asset::statistics(void) const { return engine->statistics(); } - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); - } - forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } forceinline void Asset::constrain(const Space& b) { @@ -90,7 +82,7 @@ namespace Gecode { namespace Search { namespace Seq { const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), - asset_stop(false), incomplete(false) { + incomplete(false), end(EndReason::NotEnded) { ssi.done = false; ssi.l = opt.slice; @@ -103,7 +95,6 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { - asset_stop = false; unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; @@ -120,18 +111,20 @@ namespace Gecode { namespace Search { namespace Seq { throw; } } + end = EndReason::NotEnded; return s; } - if (assets[cur].stopped() && !assets[cur].limited()) { + EndReason asset_end = assets[cur].end_reason(); + if (asset_end == EndReason::Limit) { if (ssi.done) { cur++; n_exhausted++; } else { - asset_stop = true; + end = EndReason::Limit; return nullptr; } } else { - // The asset is done or stopped at a local limit (then search is incomplete) - if (assets[cur].limited()) + // The asset is done, without a proof if it is incomplete + if (asset_end == EndReason::Incomplete) incomplete = true; // Kill the asset after saving the statistics stat += assets[cur].statistics(); @@ -149,14 +142,14 @@ namespace Gecode { namespace Search { namespace Seq { if (cur == n_assets) cur = 0; } - asset_stop = incomplete; + end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; return nullptr; } template - bool - PBS::stopped(void) const { - return asset_stop; + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index de656bee86..25696ea86a 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -79,9 +79,10 @@ namespace Gecode { namespace Search { namespace Seq { Space* RBS::next(void) { // A failed hub proves that no further solution exists - if (hub == nullptr) + if (hub == nullptr) { + end = EndReason::Exhausted; return nullptr; - m_stopped = false; + } if (restart) { restart = false; sslr++; @@ -94,6 +95,7 @@ namespace Gecode { namespace Search { namespace Seq { delete hub; hub = nullptr; e->reset(nullptr); + end = EndReason::Exhausted; return nullptr; } else if (r) { stop->update(e->statistics()); @@ -113,26 +115,29 @@ namespace Gecode { namespace Search { namespace Seq { restart = true; delete last; last = n->clone(); + end = EndReason::NotEnded; return n; - } else if ( (!complete && !e->stopped()) || - (e->stopped() && stop->enginestopped()) ) { + } + EndReason inner = e->end_reason(); + bool limit = inner == EndReason::Limit; + if ((!complete && !limit) || (limit && stop->enginestopped())) { // The engine must perform a true restart // The number of the restart has been incremented in the stop object - if (!complete && !e->stopped()) { + if (!complete && !limit) { /* * The engine might not have checked its stop object, for example * when the spoke failed at the root or a parallel engine had no * work. Without this check, the restarts might never stop. */ if (stop->meta_stop(e->statistics(),m_opt)) { - m_stopped = true; + end = EndReason::Limit; return nullptr; } stop->restart(); } sslr = 0; NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),e->stopped() ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); + MetaInfo mi(stop->restarts(),limit ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); (void) hub->hub(mi); stop->nogood(ng.ng()); unsigned long long int nl = ++(*co); @@ -142,6 +147,7 @@ namespace Gecode { namespace Search { namespace Seq { delete hub; hub = nullptr; e->reset(nullptr); + end = EndReason::Exhausted; return nullptr; } Space* spoke = hub; @@ -150,6 +156,8 @@ namespace Gecode { namespace Search { namespace Seq { nogoods_valid = complete; e->reset(spoke); } else { + // A stop from above, or a complete spoke search has ended + end = inner; return nullptr; } } @@ -176,19 +184,16 @@ namespace Gecode { namespace Search { namespace Seq { e->constrain(b); } - bool - RBS::stopped(void) const { + EndReason + RBS::end_reason(void) const { /* - * What might happen during parallel search is that the - * engine has been stopped but the meta engine has not, so - * the meta engine does not perform a restart. However the - * invocation of next will do so and no restart will be - * missed. - * - * The engine may still report a stop when the hub failed during a - * restart after a limit. A failed hub is a proof, not a stop. + * What might happen during parallel search is that the engine has + * been stopped by the cutoff but the meta engine reports a limit, + * because the stop object of the meta engine also fired. The next + * invocation of next() then performs the restart, and no restart + * will be missed. */ - return (hub != nullptr) && (m_stopped || e->stopped()); + return end; } RBS::~RBS(void) { diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 2c57744a59..4d930f2065 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -109,8 +109,8 @@ namespace Gecode { namespace Search { namespace Seq { bool restart; /// Whether the engine performs best solution search bool best; - /// Whether the stop object for the meta engine stopped a restart - bool m_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Return the no-goods of the last spoke search, valid in the hub NoGoods& hub_nogoods(void); public: @@ -128,8 +128,8 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index a4bacb56e5..ba428fd7ba 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -100,7 +100,7 @@ namespace Gecode { namespace Search { namespace Seq { : e(e0), hub(s), last(nullptr), co(opt.cutoff), stop(stop0), m_opt(opt.expand()), sslr(0), complete(complete0), nogoods_valid(complete0), restart(false), - best(best0), m_stopped(false) { + best(best0), end(EndReason::NotEnded) { stop->limit(stat,(*co)()); } diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 6cdc0b2be4..bce378bc4d 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -65,6 +65,9 @@ namespace Gecode { namespace Search { protected: /// The worker to wrap into an engine Worker w; + /// Why the last call to next() returned no solution + EndReason end; + public: /// Initialization WorkerToEngine(Space* s, const Options& o); @@ -72,8 +75,8 @@ namespace Gecode { namespace Search { virtual Space* next(void); /// Return statistics virtual Search::Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Reset engine to restart at space \a s @@ -92,11 +95,13 @@ namespace Gecode { namespace Search { template WorkerToEngine::WorkerToEngine(Space* s, const Options& o) - : Engine(o,1U), w(s,o) {} + : Engine(o,1U), w(s,o) , end(EndReason::NotEnded) {} template Space* WorkerToEngine::next(void) { - return w.next(); + Space* s = w.next(); + end = (s != nullptr) ? EndReason::NotEnded : w.end_reason(); + return s; } template Search::Statistics @@ -104,14 +109,15 @@ namespace Gecode { namespace Search { return w.statistics(); } template - bool - WorkerToEngine::stopped(void) const { - return w.stopped(); + EndReason + WorkerToEngine::end_reason(void) const { + return end; } template void WorkerToEngine::reset(Space* s) { w.reset(s); + end = EndReason::NotEnded; } template void diff --git a/gecode/search/worker.hh b/gecode/search/worker.hh index 892cd85a59..16118f8717 100644 --- a/gecode/search/worker.hh +++ b/gecode/search/worker.hh @@ -58,6 +58,8 @@ namespace Gecode { namespace Search { bool stop_seq(Options& o); /// Check whether engine has been stopped bool stopped(void) const; + /// Return why next() returned no solution: Limit if stopped, otherwise Exhausted + EndReason end_reason(void) const; /// Reset statistics with root depth \a d void reset(unsigned long int d=0); /// Record stack depth \a d @@ -102,6 +104,11 @@ namespace Gecode { namespace Search { return _stopped; } + forceinline EndReason + Worker::end_reason(void) const { + return _stopped ? EndReason::Limit : EndReason::Exhausted; + } + forceinline void Worker::reset(unsigned long int d) { Statistics::reset(); diff --git a/test/int/open-var-list.cpp b/test/int/open-var-list.cpp index 03a9f5920f..9f959ed039 100644 --- a/test/int/open-var-list.cpp +++ b/test/int/open-var-list.cpp @@ -274,7 +274,7 @@ namespace Test { namespace Int { }; while (Space* solution = engine->next()) record(static_cast(solution)); - if (!engine->stopped()) + if (engine->end_reason() != Search::EndReason::Limit) return false; // Deeper choices refer to positions absent from the restart root. engine->nogoods().post(root); diff --git a/test/nogoods.cpp b/test/nogoods.cpp index 2e819fd5f2..a7964ed174 100644 --- a/test/nogoods.cpp +++ b/test/nogoods.cpp @@ -242,7 +242,7 @@ namespace Test { while (true) { Model* s = static_cast(e->next()); delete s; - if (!e->stopped()) + if (e->end_reason() != Search::EndReason::Limit) break; // Add no-goods e->nogoods().post(*m); diff --git a/test/search.cpp b/test/search.cpp index 426545450b..8dc3bbe229 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -89,6 +89,8 @@ namespace Test { using namespace Gecode; using namespace Gecode::Int; + using Gecode::Search::EndReason; + #ifdef GECODE_HAS_EXPERIMENTAL /// Explicit finite tree with prefix costs, admissible bounds, and ranks class TreeSpace : public Space { @@ -255,7 +257,7 @@ namespace Test { break; } } - return e.stopped() || (last == (*root.graph)[0].best); + return (e.end_reason() != EndReason::Exhausted) || (last == (*root.graph)[0].best); } /// Heuristic search engines on random trees @@ -287,7 +289,7 @@ namespace Test { E e(&root,o); if (!improving(e,root,step > 0U ? &stop : nullptr)) return false; - if ((o.max_width == 0UL) && e.stopped()) + if ((o.max_width == 0UL) && (e.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -362,7 +364,7 @@ namespace Test { last = s->node().cost; delete s; } - return (last == 1) && e.stopped(); + return (last == 1) && (e.end_reason() == EndReason::Incomplete); } } heuristic_portfolio; #endif @@ -1085,7 +1087,7 @@ namespace Test { Gecode::RBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = (solution == nullptr) && search.stopped(); + ok = (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } ok = ok && holds(rbs_state.live_spaces, 0U); @@ -1105,7 +1107,7 @@ namespace Test { Gecode::PBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = ok && (solution == nullptr) && search.stopped(); + ok = ok && (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } return ok && holds(pbs_state.live_spaces, 0U); @@ -1460,7 +1462,7 @@ namespace Test { } bool complete = E::best ? (last && last->best()) : (solutions == root.solutions()); - return ok && !engine.stopped() && complete; + return ok && (engine.end_reason() == EndReason::Exhausted) && complete; } #ifdef GECODE_HAS_EXPERIMENTAL template class E> @@ -1489,7 +1491,7 @@ namespace Test { std::future_status::timeout; control.request(threads); result.get(); - return ok && !engine.stopped() && (last == (*root.graph)[0].best); + return ok && (engine.end_reason() == EndReason::Exhausted) && (last == (*root.graph)[0].best); } #endif @@ -1550,7 +1552,7 @@ namespace Test { resizer.join(); best = (last != nullptr) && last->best(); delete last; - return !engine.stopped(); + return engine.end_reason() == EndReason::Exhausted; } public: WorkerControlConcurrentResize(void) @@ -2429,7 +2431,8 @@ namespace Test { (static_cast(s)->x.val().max() < 8.5); delete s; } - substep = substep && (found == 1) && !bab->stopped(); + substep = substep && (found == 1) && + (bab->end_reason() == EndReason::Exhausted); if (!substep) return false; #endif @@ -2572,11 +2575,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !dfs.stopped()) + if ((s == nullptr) && (dfs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (dfs.end_reason() == EndReason::Exhausted); } }; @@ -2609,11 +2612,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !lds.stopped()) + if ((s == nullptr) && (lds.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (lds.end_reason() == EndReason::Exhausted); } }; @@ -2653,11 +2656,11 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !bab.stopped()) + if ((s == nullptr) && (bab.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - bool ok = (b == nullptr) || b->best(); + bool ok = ((b == nullptr) || b->best()) && (bab.end_reason() == EndReason::Exhausted); delete b; return ok; } @@ -2701,12 +2704,12 @@ namespace Test { delete b; b = s; } } - if ((s == nullptr) && !rbs.stopped()) + if ((s == nullptr) && (rbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } if (htc == HTC_NONE) - return n == 0; + return (n == 0) && (rbs.end_reason() == EndReason::Exhausted); bool ok = improving && (b != nullptr) && b->best(); delete b; return ok; @@ -2760,7 +2763,7 @@ namespace Test { best = s->x[0].val(); delete s; } - return !rbs.stopped() && (best == 0); + return (rbs.end_reason() == EndReason::Exhausted) && (best == 0); } }; @@ -2828,10 +2831,12 @@ namespace Test { } Gecode::Search::Statistics s = rbs.statistics(); // The failures of the last spoke search are counted once - if (rbs.stopped() || (s.restart != 1U) || (s.fail < 2U) || + if ((rbs.end_reason() != EndReason::Exhausted) || + (s.restart != 1U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; - if ((rbs.next() != nullptr) || rbs.stopped() || + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted) || (rbs.statistics().fail != s.fail) || (rbs.statistics().node != s.node)) return false; @@ -2886,7 +2891,7 @@ namespace Test { delete s; return false; } - return rbs.stopped() && (f.checks <= 1000) && + return (rbs.end_reason() == EndReason::Limit) && (f.checks <= 1000) && (rbs.statistics().fail >= 5); } public: @@ -2959,7 +2964,7 @@ namespace Test { } }; - /// A search exhausted when it reaches a failure limit is not stopped + /// A search exhausted when it reaches a failure limit is exhausted class ExhaustedAtLimit : public Base { template class Engine> static bool test(void) { @@ -2981,7 +2986,7 @@ namespace Test { Gecode::Search::Options o; o.stop = &l; Engine e(&root,o); - if ((e.next() != nullptr) || e.stopped()) + if ((e.next() != nullptr) || (e.end_reason() != EndReason::Exhausted)) return false; } // Restarts at that limit post no no-goods and would repeat forever @@ -2992,7 +2997,8 @@ namespace Test { o.nogoods_limit = 128U; o.cutoff = Gecode::Search::Cutoff::constant(f-1); Gecode::RBS rbs(&root,o); - if ((rbs.next() != nullptr) || rbs.stopped()) + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -3066,7 +3072,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3081,7 +3087,7 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3135,7 +3141,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3157,7 +3163,7 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3181,7 +3187,8 @@ namespace Test { sebs[0] = builder(Gecode::Search::Options::def); sebs[1] = builder(Gecode::Search::Options::def); Gecode::PBS pbs(&root,sebs,o); - return (pbs.next() == nullptr) && pbs.stopped() && (l.checks <= 1000); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit) && (l.checks <= 1000); } public: PBSBuilderStop(void) : Base("Search::PBS::SEB::Stop") {} @@ -3273,7 +3280,8 @@ namespace Test { o.threads = threads; o.cutoff = Gecode::Search::Cutoff::geometric(1,2); Gecode::PBS pbs(&root,o); - return (pbs.next() == nullptr) && !pbs.stopped(); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); } public: PBSRestartCutoff(void) : Base("Search::PBS::RBS::Cutoff") {} @@ -3335,7 +3343,7 @@ namespace Test { delete s; return false; } - if (pbs.stopped()) + if (pbs.end_reason() != EndReason::Exhausted) return false; } return deleted == 1U; From 6bc53091a04fa5b2605443da83bdd534276a3446 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 16:45:28 +0100 Subject: [PATCH 03/16] Report LDS at its discrepancy limit as incomplete Limited discrepancy search that reached its discrepancy limit reported the same end as a search that explored the whole tree, so its end could be taken as a proof. It now reports EndReason::Incomplete, and only a search whose last probe explored every alternative reports EndReason::Exhausted. --- changelog.in | 7 +++++++ docs/gecode-7-migration.md | 8 ++++---- gecode/search.hh | 14 +++++--------- gecode/search/seq/lds.hpp | 7 ++++++- test/search.cpp | 24 ++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 14 deletions(-) diff --git a/changelog.in b/changelog.in index 213471335d..6307538f48 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,13 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Report limited discrepancy search at its discrepancy limit as incomplete. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 389d6fb29e..82c1545a6d 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -91,10 +91,10 @@ enum class Gecode::Search::EndReason : unsigned char { `Exhausted` means that the engine explored everything it was asked to explore: there is no further solution, and the last solution of a branch-and-bound search is optimal. `Incomplete` means that the engine ended -on its own without that proof, for example CABS at its width limit. Calling -`next()` again does not continue an incomplete search. `Limit` means that a -stop object stopped the engine, and calling `next()` again continues the -search. +on its own without that proof, for example limited discrepancy search at its +discrepancy limit or CABS at its width limit. Calling `next()` again does not +continue an incomplete search. `Limit` means that a stop object stopped the +engine, and calling `next()` again continues the search. Code that used `!stopped()` as a proof, such as reporting optimality, should test for `EndReason::Exhausted`. Code that resumes a search after a limit diff --git a/gecode/search.hh b/gecode/search.hh index 0e51e75a38..09e70edcbc 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1115,8 +1115,8 @@ namespace Gecode { namespace Search { Exhausted, /** * Search finished without exhausting its search space, for example - * at the width limit of CABS. There may be further solutions, but - * calling next() again finds none. + * at the discrepancy limit of LDS or the width limit of CABS. There + * may be further solutions, but calling next() again finds none. */ Incomplete, /// A stop object stopped search, calling next() again resumes it @@ -1472,13 +1472,9 @@ namespace Gecode { * Search::Options::d_l discrepancies, allowing more discrepancies in each * iteration, starting from none. * - * When next() returns nullptr and end_reason() returns - * Search::EndReason::Exhausted, either the search tree has been explored - * completely, or the discrepancy limit has been reached while parts of - * the tree are still unexplored. The engine - * does not report which: a search that finds no (further) solution only - * proves that none exists if no path of the tree has more discrepancies - * than the limit. + * When the search tree has choices that need more discrepancies than + * the limit in Search::Options::d_l, end_reason() returns + * Search::EndReason::Incomplete once the search ends. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/seq/lds.hpp b/gecode/search/seq/lds.hpp index 81f7331a75..257b63e19e 100644 --- a/gecode/search/seq/lds.hpp +++ b/gecode/search/seq/lds.hpp @@ -303,10 +303,15 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; break; } - if ((++d > opt.d_l) || e.done()) { + if (e.done()) { end = EndReason::Exhausted; break; } + // Choices with more discrepancies than the limit were not explored + if (++d > opt.d_l) { + end = EndReason::Incomplete; + break; + } if (d == opt.d_l) { if (root != nullptr) e.reset(root,d); diff --git a/test/search.cpp b/test/search.cpp index 8dc3bbe229..57657ca471 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3012,6 +3012,30 @@ namespace Test { ExhaustedAtLimit exhausted_at_limit; + /// LDS reports an incomplete search at its discrepancy limit + class LDSIncomplete : public Base { + static EndReason end_reason(unsigned int d_l) { + NoSolution root; + Gecode::Search::Options o; + o.d_l = d_l; + Gecode::LDS lds(&root,o); + if (NoSolution* s = lds.next()) { + delete s; + return EndReason::NotEnded; + } + return lds.end_reason(); + } + public: + LDSIncomplete(void) : Base("Search::LDS::Incomplete") {} + bool run(void) override { + return (end_reason(0) == EndReason::Incomplete) && + (end_reason(1) == EndReason::Incomplete) && + (end_reason(100) == EndReason::Exhausted); + } + }; + + LDSIncomplete lds_incomplete; + /// Space for relaxing class RelaxSpace : public Gecode::Space { public: From 506637fe60d22d3918aff1a6037721c5cabf8961 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:06:24 +0100 Subject: [PATCH 04/16] End a portfolio when an asset exhausts its search space An asset that exhausted its search space was dropped and the remaining assets continued. A portfolio next to an asset that never ends, such as restart-based large neighbourhood search, then ran until a stop object fired, although the exhausted asset had proven that no further solution exists. The portfolio now ends with EndReason::Exhausted. Every spoke is still taken to cover the search space of the hub. The check is kept in pbs_asset_proof() so that a spoke covering only part of the search space can be excluded once spokes declare their coverage. An asset ending without a proof is dropped as before, and a portfolio whose assets all end that way reports EndReason::Incomplete. --- changelog.in | 10 ++++++++++ gecode/search.hh | 7 +++++++ gecode/search/par/pbs.hh | 7 ++++--- gecode/search/par/pbs.hpp | 21 ++++++++++++-------- gecode/search/seq/pbs.hh | 3 +-- gecode/search/seq/pbs.hpp | 16 ++++++++++------ gecode/search/support.hh | 16 ++++++++++++++++ test/search.cpp | 40 ++++++++++++++++++++++++++++++++++++++- 8 files changed, 100 insertions(+), 20 deletions(-) diff --git a/changelog.in b/changelog.in index 6307538f48..5bfdd27962 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,16 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +End a portfolio when an asset exhausts its search space. +[MORE] +The exhausted asset proves that no further solution exists, so the other +assets no longer run until they are stopped. + [ENTRY] Module: search What: change diff --git a/gecode/search.hh b/gecode/search.hh index 09e70edcbc..b9e270797c 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1614,6 +1614,13 @@ namespace Gecode { * (see Cutoff::copy()). If the constructor throws an exception, the * caller keeps the cutoff. * + * The spoke of each asset is taken to cover the search space of the + * hub. When an asset exhausts its search space, the portfolio ends and + * end_reason() returns Search::EndReason::Exhausted. An asset that ends + * without exhausting its search space, such as LDS at its discrepancy + * limit, is dropped while the other assets continue. When every asset + * has been dropped, end_reason() returns Search::EndReason::Incomplete. + * * The class \a T can implement member functions * \code virtual bool hub(const MetaInfo& mi) \endcode * and diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index e8881e7b75..10581d2d23 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -39,6 +39,7 @@ #define GECODE_SEARCH_PAR_PBS_HH #include +#include #include #include @@ -179,8 +180,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_active; /// Whether an asset has been stopped std::atomic asset_stop; - /// Whether an asset finished without exhausting its search space - bool incomplete; + /// Whether an asset has proven that no further solution exists + bool exhausted; /// Why the last call to next() returned no solution EndReason end; /// Shared stop flag @@ -205,7 +206,7 @@ namespace Gecode { namespace Search { namespace Par { * - that entails, that locking is only needed inside next(). * - the assets 0..n_active-1 still might not have exhausted their * search space. - * - the assets n_active..n_assets-1 have exhausted their search space. + * - the assets n_active..n_assets-1 have ended without a proof. */ public: /// Initialize diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index cf2a9da757..bc53415ac4 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -190,7 +190,7 @@ namespace Gecode { namespace Search { namespace Par { const Statistics& stat0) : stat(stat0), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), incomplete(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { + asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -226,11 +226,13 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } + } else if (pbs_asset_proof(asset->end_reason())) { + // Stop the other assets, no further solution exists + exhausted = true; + tostop.store(true, std::memory_order_release); + wake = true; } else { - // The asset is done , without a proof if it is incomplete - if (asset->end_reason() == EndReason::Incomplete) - incomplete = true; - // Move asset to inactive + // The asset ended without a proof, move it to inactive unsigned int i=0; while (assets[i] != asset) i++; @@ -290,7 +292,7 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.empty()) asset_stop.store(false, std::memory_order_release); while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !asset_stop.load(std::memory_order_acquire)) { + !exhausted && !asset_stop.load(std::memory_order_acquire)) { // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); @@ -328,10 +330,13 @@ namespace Gecode { namespace Search { namespace Par { // Process solutions if (solutions.empty()) { s = nullptr; - if (asset_stop.load(std::memory_order_acquire)) + if (exhausted) + end = EndReason::Exhausted; + else if (asset_stop.load(std::memory_order_acquire)) end = EndReason::Limit; else - end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; + // All assets ended without a proof + end = EndReason::Incomplete; } else { end = EndReason::NotEnded; Asset* r; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 008fdb8831..ddcfe2db4f 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -35,6 +35,7 @@ #define GECODE_SEARCH_SEQ_PBS_HH #include +#include namespace Gecode { namespace Search { namespace Seq { @@ -111,8 +112,6 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_assets; /// Current asset to run unsigned int cur; - /// Whether an asset finished without exhausting its search space - bool incomplete; /// Why the last call to next() returned no solution EndReason end; public: diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 3a234f7174..bd32fca5a7 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -82,7 +82,7 @@ namespace Gecode { namespace Search { namespace Seq { const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), - incomplete(false), end(EndReason::NotEnded) { + end(EndReason::NotEnded) { ssi.done = false; ssi.l = opt.slice; @@ -95,6 +95,9 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { + // An asset has proven that no further solution exists + if (end == EndReason::Exhausted) + return nullptr; unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; @@ -122,11 +125,11 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; return nullptr; } + } else if (pbs_asset_proof(asset_end)) { + end = EndReason::Exhausted; + return nullptr; } else { - // The asset is done, without a proof if it is incomplete - if (asset_end == EndReason::Incomplete) - incomplete = true; - // Kill the asset after saving the statistics + // The asset ended without a proof, kill it after saving the statistics stat += assets[cur].statistics(); assets[cur].~Asset(); assets[cur] = assets[--n_assets]; @@ -142,7 +145,8 @@ namespace Gecode { namespace Search { namespace Seq { if (cur == n_assets) cur = 0; } - end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; + // All assets ended without a proof + end = EndReason::Incomplete; return nullptr; } diff --git a/gecode/search/support.hh b/gecode/search/support.hh index bce378bc4d..7e5d7abd4c 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -59,6 +59,22 @@ namespace Gecode { namespace Search { forceinline Space* snapshot(Space* s, const Options& o); + /** + * \brief Whether a portfolio asset that ended for reason \a r proves that + * the hub has no further solution + * + * The spoke of every asset is taken to cover the search space of the + * hub, so an exhausted asset ends the portfolio with a proof. A spoke + * that covers only part of the search space, such as a fragment for + * large neighbourhood search, must not end the portfolio when it is + * exhausted: once spokes can declare their coverage, this is where it is + * taken into account. + */ + forceinline bool + pbs_asset_proof(EndReason r) { + return r == EndReason::Exhausted; + } + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { diff --git a/test/search.cpp b/test/search.cpp index 57657ca471..29d0b78750 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -364,7 +364,7 @@ namespace Test { last = s->node().cost; delete s; } - return (last == 1) && (e.end_reason() == EndReason::Incomplete); + return (last == 1) && (e.end_reason() == EndReason::Exhausted); } } heuristic_portfolio; #endif @@ -3227,6 +3227,44 @@ namespace Test { PBSBuilderStop pbs_builder_stop; + /// An exhausted asset ends a portfolio whose other asset never ends + class PBSExhaustedAsset : public Base { + /// Stop after many checks, in case the portfolio does not end + class ManyChecks : public Gecode::Search::Stop { + public: + /// Number of checks + std::atomic checks{0UL}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return ++checks > 10000000UL; + } + }; + static bool test(unsigned int threads) { + FailingSpoke root; + ManyChecks l; + Gecode::Search::Options a; + a.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::SEBs sebs(2); + sebs[0] = Gecode::rbs(a); + sebs[1] = Gecode::dfs(); + Gecode::Search::Options o; + o.threads = threads; + o.stop = &l; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted) && + (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSExhaustedAsset(void) : Base("Search::PBS::ExhaustedAsset") {} + bool run(void) override { + return test(1U) && test(2U); + } + }; + + PBSExhaustedAsset pbs_exhausted_asset; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From aa8c060e2b76d1020b2038f2ca4b80e2059d830f Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:11:25 +0100 Subject: [PATCH 05/16] Run every asset of a parallel portfolio Parallel portfolio search ran only as many assets, or engine builders, as it had threads and silently dropped the others. A portfolio of three assets with two threads therefore ran two of them. Every asset now runs in its own thread, and the threads are divided among the assets with at least one thread for each asset's engine, as in sequential portfolios. --- changelog.in | 11 +++++++++++ gecode/search.hh | 16 ++++++++++------ gecode/search/pbs.hpp | 25 ++++++------------------- test/search.cpp | 6 +++--- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/changelog.in b/changelog.in index 5bfdd27962..d858d11159 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Run every asset of a parallel portfolio, also when there are more assets +than threads. +[MORE] +Parallel portfolio search ran only as many assets as it had threads and +silently dropped the others. + [ENTRY] Module: search What: bug diff --git a/gecode/search.hh b/gecode/search.hh index b9e270797c..98f16ba38e 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1600,8 +1600,11 @@ namespace Gecode { * \brief Meta engine using a portfolio of search engines * * 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. + * by the options \a o. With more than one thread in \a o, every asset + * runs in its own thread, also when there are more assets than threads, + * and the threads are divided evenly among the assets, with at least + * one thread for each asset. With one thread, the assets take turns in + * slices of failures (see Search::Options::slice). * 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 @@ -1649,8 +1652,9 @@ namespace Gecode { * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. - * In parallel PBS, the outer thread count limits how many builders run, - * in array order; each builder's options set its own engine's thread count. + * In parallel PBS, the engine of every builder runs in its own thread, + * also when there are more builders than outer threads; each builder's + * options set its own engine's thread count. * * With experimental search, AStar and CABS builders can be used * together with BAB builders. @@ -1666,8 +1670,8 @@ namespace Gecode { * \brief Run a portfolio of search engines * * 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. + * by the options \a o. See PBS for how the assets use the threads in + * \a o. * An external worker control is supported only when \a o selects one * asset. PBS does not implement worker-allocation policy. * diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 96c6ee48b5..759158e2d2 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -64,16 +64,6 @@ namespace Gecode { namespace Search { throw WorkerControlInUse("PBS::PBS"); } - /// Return the number of explicit builders admitted by this portfolio - forceinline int - pbsadmitted(const SEBs& sebs, const Options& opt) { -#ifdef GECODE_HAS_THREADS - if (opt.threads > 1.0) - return std::min(static_cast(opt.threads),sebs.size()); -#endif - return sebs.size(); - } - /// Validate worker-control placement for an explicit portfolio forceinline void pbscontrol(const SEBs& sebs, const Options& opt) { @@ -84,8 +74,7 @@ namespace Gecode { namespace Search { #else const bool parallel = false; #endif - int admitted = pbsadmitted(sebs,opt); - for (int i=0; ioptions().worker_control; if (!x.engaged()) continue; @@ -327,11 +316,10 @@ namespace Gecode { namespace Search { opt.clone = true; Region r; - // Limit the number of assets to the number of threads - unsigned int n_assets = std::min(static_cast(opt.threads), - opt.assets); + // Run every asset in its own thread, even with fewer threads than assets + unsigned int n_assets = opt.assets; // Redistribute additional threads to assets - opt.threads = floor(opt.threads / static_cast(n_assets)); + opt.threads = std::max(floor(opt.threads / static_cast(n_assets)), 1.0); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, n_assets); @@ -375,9 +363,8 @@ namespace Gecode { namespace Search { const Search::Statistics& stat, Options& opt, bool best) { Region r; - // Limit the number of assets to the number of threads - int n_assets = std::min(static_cast(opt.threads), - sebs.size()); + // Run every asset in its own thread, even with fewer threads than assets + int n_assets = sebs.size(); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, diff --git a/test/search.cpp b/test/search.cpp index 29d0b78750..6e51ac8f31 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -1230,8 +1230,8 @@ namespace Test { case Scenario::PbsParallel: return pbs(3, 3, 1, 3, 7); case Scenario::PbsParallelThreadLimit: - // Parallel PBS runs only as many assets as it has threads. - return pbs(3, 2, 1, 2, 3); + // Parallel PBS runs all assets, also with fewer threads. + return pbs(3, 2, 1, 3, 7); case Scenario::PbsDefaultHubRemovesBranchers: return pbs_default_hub_removes_branchers(); case Scenario::RbsNoGoodsResetOwnership: @@ -3104,7 +3104,7 @@ namespace Test { delete b; return ok; } else { - int n = ((t > 1) ? std::min(a,t) : a) * m->solutions(); + int n = a * m->solutions(); delete m; while (true) { Model* s = pbs.next(); From 51e4caf78f6333acc6033c51b1e7299e8b857f00 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:29:58 +0100 Subject: [PATCH 06/16] Check the portfolio stop object with portfolio-wide statistics The stop object in the options of a portfolio was checked for each asset with the statistics of that asset. A failure limit of n for a portfolio of k assets therefore allowed up to k * n failures, and with engine builders the portfolio stop object was checked like a builder's. The portfolio stop object is now checked with the sum of the statistics of all assets. A sequential portfolio adds the statistics of the other assets before running an asset. A parallel portfolio records the latest statistics of each asset under a mutex, only when the portfolio has a stop object. The stop objects of engine builders are still checked with the statistics of their engine. --- changelog.in | 11 +++++++++ docs/gecode-7-migration.md | 17 +++++++++++++ gecode/search.hh | 13 ++++++++-- gecode/search/par/pbs.cpp | 12 ++++++++- gecode/search/par/pbs.hh | 44 ++++++++++++++++++++++++++++++--- gecode/search/par/pbs.hpp | 24 +++++++++++++++--- gecode/search/pbs.hpp | 4 +-- gecode/search/seq/pbs.cpp | 2 +- gecode/search/seq/pbs.hh | 10 +++++++- gecode/search/seq/pbs.hpp | 4 +++ test/search.cpp | 50 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 177 insertions(+), 14 deletions(-) diff --git a/changelog.in b/changelog.in index d858d11159..7a8ad4a7e4 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Check the stop object of a portfolio with the statistics of the whole +portfolio. +[MORE] +It was checked for each asset with the statistics of that asset. See +docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 82c1545a6d..370ab709d2 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -99,3 +99,20 @@ engine, and calling `next()` again continues the search. Code that used `!stopped()` as a proof, such as reporting optimality, should test for `EndReason::Exhausted`. Code that resumes a search after a limit should test for `EndReason::Limit`. + +## Portfolio stop objects see the whole portfolio + +The stop object in the options of `PBS` is now checked with the statistics +of the whole portfolio, the sum over all assets. In Gecode 6, it was checked +for each asset with the statistics of that asset, so a failure limit of +`n` for a portfolio of `k` assets allowed up to `k * n` failures. A stop +object that should limit each asset on its own belongs in the options of an +engine builder: + +```cpp +Gecode::Search::Options a, b; +a.stop = &dfs_stop; +b.stop = &lds_stop; +Gecode::SEBs sebs({Gecode::dfs(a), Gecode::lds(b)}); +Gecode::PBS engine(model, sebs, portfolio_options); +``` diff --git a/gecode/search.hh b/gecode/search.hh index 98f16ba38e..92d23324fa 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1605,6 +1605,14 @@ namespace Gecode { * and the threads are divided evenly among the assets, with at least * one thread for each asset. With one thread, the assets take turns in * slices of failures (see Search::Options::slice). + * + * The stop object in \a o is checked with the statistics of the whole + * portfolio, that is, the sum of the statistics of all assets. With + * parallel assets, these are the statistics that the workers pass to + * their stop objects. When the stop object stops search, end_reason() + * returns Search::EndReason::Limit and calling next() again resumes all + * assets. + * * 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 @@ -1647,8 +1655,9 @@ namespace Gecode { /** * Initialize with engine builders \a sebs * - * The stop object of \a o is checked for each builder's engine with the - * statistics of that engine, as is the stop object of the builder. + * The stop object of \a o is checked with the statistics of the whole + * portfolio, the stop object of a builder with the statistics of the + * engine it builds. * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 2c8e06f0a8..072c01568c 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -40,11 +40,21 @@ namespace Gecode { namespace Search { namespace Par { + Statistics + PortfolioStatistics::update(unsigned int i, const Statistics& s) { + Support::Lock lock(m); + stat[i + 1] = s; + Statistics t; + for (unsigned int j = 0U; j < n; j++) + t += stat[j]; + return t; + } + bool PortfolioStop::stop(const Statistics& s, const Options& o) { return tostop->load(std::memory_order_acquire) || ((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o)); + ((po != nullptr) && po->stop(ps->update(asset,s),o)); } void diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 10581d2d23..7fd267c9de 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -45,7 +45,38 @@ namespace Gecode { namespace Search { namespace Par { - /// Stop object used for controlling assets in a portfolio + /** + * \brief Statistics of the assets of a parallel portfolio + * + * Each asset records the statistics that its engine passes to its stop + * object. For an asset with a parallel engine, these are the statistics + * of the worker that checks the stop object. + */ + class GECODE_SEARCH_EXPORT PortfolioStatistics { + private: + /// Mutex for access + Support::Mutex m; + /// Number of entries: propagating the model and one for each asset + unsigned int n; + /// Statistics of propagating the model followed by those of each asset + Statistics* stat; + + public: + /// Initialize with statistics \a s of propagating the model for \a n assets + PortfolioStatistics(const Statistics& s, unsigned int n); + /// Record statistics \a s of asset \a i and return those of the portfolio + Statistics update(unsigned int i, const Statistics& s); + /// Delete + ~PortfolioStatistics(void); + }; + + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets @@ -56,11 +87,16 @@ namespace Gecode { namespace Search { namespace Par { WorkerControl worker_control; /// Whether search must be stopped std::atomic* tostop; + /// Statistics of the portfolio + PortfolioStatistics* ps; + /// Index of the asset + unsigned int asset; public: /// Initialize with asset stop \a so, portfolio stop \a po, and \a control PortfolioStop(Stop* so, Stop* po, const WorkerControl& control); - /// Set pointer to shared \a tostop variable - void share(std::atomic* ts); + /// Share stop flag \a ts and statistics \a ps of the portfolio with asset \a i + void share(std::atomic* ts, PortfolioStatistics* ps, + unsigned int i); /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); /// Wake workers so that a paused asset can observe the portfolio stop @@ -172,6 +208,8 @@ namespace Gecode { namespace Search { namespace Par { protected: /// Statistics of propagating the model Statistics stat; + /// Statistics of the portfolio for its stop object + PortfolioStatistics portfolio_stat; /// Asset engines Asset** assets; /// Number of asset engines diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index bc53415ac4..15dee7aa25 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -131,14 +131,29 @@ namespace Gecode { namespace Search { namespace Par { } + forceinline + PortfolioStatistics::PortfolioStatistics(const Statistics& s, unsigned int n0) + : n(n0 + 1), stat(heap.alloc(n0 + 1)) { + stat[0] = s; + } + + forceinline + PortfolioStatistics::~PortfolioStatistics(void) { + heap.free(stat, n); + } + forceinline PortfolioStop::PortfolioStop(Stop* so0, Stop* po0, const WorkerControl& control) - : so(so0), po(po0), worker_control(control), tostop(nullptr) {} + : so(so0), po(po0), worker_control(control), tostop(nullptr), + ps(nullptr), asset(0U) {} forceinline void - PortfolioStop::share(std::atomic* ts) { + PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, + unsigned int i) { tostop = ts; + ps = ps0; + asset = i; } @@ -188,13 +203,14 @@ namespace Gecode { namespace Search { namespace Par { forceinline PBS::PBS(Engine** engines, Stop** stops, unsigned int n, const Statistics& stat0) - : stat(stat0), assets(heap.alloc*>(n)), + : stat(stat0), portfolio_stat(stat0,n), + assets(heap.alloc*>(n)), n_assets(n), n_active(n), asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); - static_cast(stops[i])->share(&tostop); + static_cast(stops[i])->share(&tostop,&portfolio_stat,i); } } diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 759158e2d2..34990d41a7 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -237,7 +237,7 @@ namespace Gecode { namespace Search { Space* unowned_hub = hub; try { for (unsigned int i=0U; i spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) @@ -335,7 +335,7 @@ namespace Gecode { namespace Search { Space* unowned_hub = hub; try { for (unsigned int i=0U; i spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 1e79557f76..87624239c0 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -38,7 +38,7 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { if (((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o))) { + ((po != nullptr) && po->stop(ssi->others + s,o))) { ssi->done = false; return true; } diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index ddcfe2db4f..43cf6cd13c 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -46,9 +46,17 @@ namespace Gecode { namespace Search { namespace Seq { bool done; /// The current failure limit, incremented for each slice unsigned long long int l; + /// Statistics of the portfolio except for the running asset + Statistics others; }; - /// Stop object used for controlling assets in a portfolio + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index bd32fca5a7..70a0add84b 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -101,6 +101,10 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; + ssi.others = stat; + for (unsigned int i=0U; i(a); + sebs[1] = Gecode::rbs(b); + Gecode::PBS pbs(&root,sebs,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } else { + o.assets = 2; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::PBS pbs(&root,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } + // Checked for each asset, the limit would allow twice the failures + return (s.fail > limit) && (s.fail < limit + limit / 2U); + } + public: + PBSPortfolioStop(void) : Base("Search::PBS::PortfolioStop") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + for (bool builders : {false,true}) + if (!test(t,builders)) + return false; + return true; + } + }; + + PBSPortfolioStop pbs_portfolio_stop; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From f92bb856c562b45817a87a64073a47f225e7e6ca Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 18:00:05 +0100 Subject: [PATCH 07/16] Park a portfolio asset whose own stop object fires When the stop object of an engine builder stopped its engine, the whole portfolio stopped and reported a limit, although the other assets could still have found solutions or exhausted the search space. The portfolio stop objects now record which stop object stopped an asset. An asset stopped by its own stop object is parked and the other assets continue. The portfolio reports EndReason::Limit when only parked assets remain, or when its own stop object fires, and parked assets resume with the next call to next(). --- changelog.in | 11 +++++ gecode/search.hh | 12 ++++-- gecode/search/par/pbs.cpp | 16 +++++-- gecode/search/par/pbs.hh | 21 +++++++-- gecode/search/par/pbs.hpp | 89 ++++++++++++++++++++++++++++++--------- gecode/search/seq/pbs.cpp | 11 +++-- gecode/search/seq/pbs.hh | 14 ++++-- gecode/search/seq/pbs.hpp | 57 +++++++++++++++++++------ gecode/search/support.hh | 9 ++++ test/search.cpp | 60 ++++++++++++++++++++++++++ 10 files changed, 249 insertions(+), 51 deletions(-) diff --git a/changelog.in b/changelog.in index 7a8ad4a7e4..dfed98a0b7 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Keep the other assets of a portfolio running when the stop object of an +engine builder stops its engine. +[MORE] +The whole portfolio stopped instead. The stopped asset is now parked until +the next call to next(). + [ENTRY] Module: search What: change diff --git a/gecode/search.hh b/gecode/search.hh index 92d23324fa..8fdbda55a9 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1103,8 +1103,10 @@ namespace Gecode { namespace Search { * ended without such a proof. * * A meta engine (restart-based or portfolio search) reports Limit - * only for a stop object installed above it, not for its own - * cutoffs, slices, or the stop objects of its assets. + * for a stop object installed above it, not for its own cutoffs or + * slices. A portfolio also reports Limit when the stop objects of + * its assets have parked every asset that remains (see PBS), and + * calling next() again resumes them. * * \ingroup TaskModelSearch */ @@ -1657,7 +1659,11 @@ namespace Gecode { * * The stop object of \a o is checked with the statistics of the whole * portfolio, the stop object of a builder with the statistics of the - * engine it builds. + * engine it builds. When the stop object of a builder stops its + * engine, that asset is parked while the other assets continue. When + * only parked assets remain, end_reason() returns + * Search::EndReason::Limit, and the parked assets resume with the + * next call to next(). * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 072c01568c..94ef331ef0 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -52,9 +52,19 @@ namespace Gecode { namespace Search { namespace Par { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - return tostop->load(std::memory_order_acquire) || - ((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(ps->update(asset,s),o)); + if (tostop->load(std::memory_order_acquire)) { + _cause.store(PortfolioStopCause::Interrupt, std::memory_order_relaxed); + return true; + } + if ((po != nullptr) && po->stop(ps->update(asset,s),o)) { + _cause.store(PortfolioStopCause::Portfolio, std::memory_order_relaxed); + return true; + } + if ((so != nullptr) && so->stop(s,o)) { + _cause.store(PortfolioStopCause::Asset, std::memory_order_relaxed); + return true; + } + return false; } void diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 7fd267c9de..a91559e679 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -91,6 +91,8 @@ namespace Gecode { namespace Search { namespace Par { PortfolioStatistics* ps; /// Index of the asset unsigned int asset; + /// Which stop object stopped the asset + std::atomic _cause; public: /// Initialize with asset stop \a so, portfolio stop \a po, and \a control PortfolioStop(Stop* so, Stop* po, const WorkerControl& control); @@ -101,6 +103,10 @@ namespace Gecode { namespace Search { namespace Par { virtual bool stop(const Statistics& s, const Options& o); /// Wake workers so that a paused asset can observe the portfolio stop void wake(void); + /// Forget which stop object stopped the asset + void reset(void); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; /// Signal whether search must be stopped void stop(bool s); /// Whether search must be stopped @@ -134,6 +140,8 @@ namespace Gecode { namespace Search { namespace Par { Engine* engine; /// Stop object Stop* stop; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: /// Initialize with portfolio \a p, engine \a e, and its stop object \a so Asset(PBS* p, Engine* e, Stop* so); @@ -149,6 +157,12 @@ namespace Gecode { namespace Search { namespace Par { void wake(void); /// Constrain with better solution \a b void constrain(const Space& b); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; + /// Set whether the asset is parked + void parked(bool p); + /// Whether the asset is parked + bool parked(void) const; /// Perform one run virtual void run(void); /// Delete asset @@ -216,8 +230,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_assets; /// Number of active asset engines unsigned int n_active; - /// Whether an asset has been stopped - std::atomic asset_stop; + /// Whether the stop object of the portfolio has stopped an asset + std::atomic portfolio_stop; /// Whether an asset has proven that no further solution exists bool exhausted; /// Why the last call to next() returned no solution @@ -243,7 +257,8 @@ namespace Gecode { namespace Search { namespace Par { * - n_busy is always zero outside the next() function. * - that entails, that locking is only needed inside next(). * - the assets 0..n_active-1 still might not have exhausted their - * search space. + * search space, the parked ones among them are not run until the + * next call to next(). * - the assets n_active..n_assets-1 have ended without a proof. */ public: diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 15dee7aa25..38bcb83161 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -145,12 +145,21 @@ namespace Gecode { namespace Search { namespace Par { forceinline PortfolioStop::PortfolioStop(Stop* so0, Stop* po0, const WorkerControl& control) - : so(so0), po(po0), worker_control(control), tostop(nullptr), - ps(nullptr), asset(0U) {} + : so(so0), po(po0), worker_control(control), tostop(nullptr), ps(nullptr), asset(0U), + _cause(PortfolioStopCause::None) {} forceinline void - PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, - unsigned int i) { + PortfolioStop::reset(void) { + _cause.store(PortfolioStopCause::None, std::memory_order_relaxed); + } + + forceinline PortfolioStopCause + PortfolioStop::cause(void) const { + return _cause.load(std::memory_order_relaxed); + } + + forceinline void + PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, unsigned int i) { tostop = ts; ps = ps0; asset = i; @@ -160,7 +169,7 @@ namespace Gecode { namespace Search { namespace Par { template forceinline Asset::Asset(PBS* p, Engine* e, Stop* so) - : Support::Runnable(false), portfolio(p), engine(e), stop(so) {} + : Support::Runnable(false), portfolio(p), engine(e), stop(so), _parked(false) {} template forceinline Statistics Asset::statistics(void) const { @@ -192,6 +201,21 @@ namespace Gecode { namespace Search { namespace Par { engine->constrain(b); } template + forceinline PortfolioStopCause + Asset::cause(void) const { + return static_cast(stop)->cause(); + } + template + forceinline void + Asset::parked(bool p) { + _parked = p; + } + template + forceinline bool + Asset::parked(void) const { + return _parked; + } + template Asset::~Asset(void) { delete engine; delete stop; @@ -206,7 +230,7 @@ namespace Gecode { namespace Search { namespace Par { : stat(stat0), portfolio_stat(stat0,n), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { + portfolio_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -237,10 +261,19 @@ namespace Gecode { namespace Search { namespace Par { wake = true; } } else if (asset->end_reason() == EndReason::Limit) { - if (!tostop.load(std::memory_order_acquire)) { - asset_stop.store(true, std::memory_order_release); + switch (asset->cause()) { + case PortfolioStopCause::Interrupt: + // The asset runs again with the next round + break; + case PortfolioStopCause::Portfolio: + portfolio_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; + break; + default: + // The stop object of the asset stopped it, the others continue + asset->parked(true); + break; } } else if (pbs_asset_proof(asset->end_reason())) { // Stop the other assets, no further solution exists @@ -289,6 +322,7 @@ namespace Gecode { namespace Search { namespace Par { try { Space* s; do { + static_cast(stop)->reset(); s = engine->next(); } while (!portfolio->report(this,s)); } catch (...) { @@ -305,10 +339,21 @@ namespace Gecode { namespace Search { namespace Par { m.release(); std::rethrow_exception(f); } - if (solutions.empty()) - asset_stop.store(false, std::memory_order_release); - while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !exhausted && !asset_stop.load(std::memory_order_acquire)) { + if (solutions.empty()) { + portfolio_stop.store(false, std::memory_order_release); + // Resume the assets that their own stop objects stopped + for (unsigned int i=0U; iparked(false); + } + while (solutions.empty() && (failure == nullptr) && + !exhausted && !portfolio_stop.load(std::memory_order_acquire)) { + unsigned int n_run = 0; + for (unsigned int i=0U; iparked()) + n_run++; + if (n_run == 0) + break; + // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); @@ -316,14 +361,15 @@ namespace Gecode { namespace Search { namespace Par { assert(n_busy == 0); assert(!tostop.load(std::memory_order_acquire)); - // Run all active assets - n_busy = n_active; - for (unsigned int i=0U; iwait(); - Support::Thread::run(assets[i]); - } + // Run all active assets that are not parked + n_busy = n_run; + for (unsigned int i=0U; iparked()) { + // Consume the previous completion before reusing this asset. The + // initial signal handles the first submission. + assets[i]->wait(); + Support::Thread::run(assets[i]); + } m.release(); // Wait for all assets to become idle idle.wait(); @@ -348,7 +394,8 @@ namespace Gecode { namespace Search { namespace Par { s = nullptr; if (exhausted) end = EndReason::Exhausted; - else if (asset_stop.load(std::memory_order_acquire)) + else if (portfolio_stop.load(std::memory_order_acquire) || (n_active > 0)) + // Stopped by the portfolio stop object, or only parked assets remain end = EndReason::Limit; else // All assets ended without a proof diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 87624239c0..64c7909a35 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -37,13 +37,16 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - if (((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(ssi->others + s,o))) { - ssi->done = false; + if ((po != nullptr) && po->stop(ssi->others + s,o)) { + ssi->cause = PortfolioStopCause::Portfolio; + return true; + } + if ((so != nullptr) && so->stop(s,o)) { + ssi->cause = PortfolioStopCause::Asset; return true; } if (s.fail >= ssi->l) { - ssi->done = true; + ssi->cause = PortfolioStopCause::Slice; return true; } return false; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 43cf6cd13c..87bafc751d 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -42,8 +42,8 @@ namespace Gecode { namespace Search { namespace Seq { /// Shared stop information class SharedStopInfo { public: - /// Whether search stopped because the slice is done - bool done; + /// Which stop object stopped the running asset + PortfolioStopCause cause; /// The current failure limit, incremented for each slice unsigned long long int l; /// Statistics of the portfolio except for the running asset @@ -81,6 +81,8 @@ namespace Gecode { namespace Search { namespace Seq { Engine* engine; /// Stop object Stop* stop; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: /// Default constructor Asset(void); @@ -98,8 +100,12 @@ namespace Gecode { namespace Search { namespace Seq { EndReason end_reason(void) const; /// Constrain with better solution \a b void constrain(const Space& b); - /// Perform one run - void run(void); + /// Park the asset after its stop object stopped it + void park(void); + /// Resume a parked asset + void resume(void); + /// Whether the asset is parked + bool parked(void) const; /// Delete asset ~Asset(void); }; diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 70a0add84b..b7a66a9f35 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -47,7 +47,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline Asset::Asset(void) - : engine(nullptr), stop(nullptr) {} + : engine(nullptr), stop(nullptr), _parked(false) {} forceinline void Asset::init(Engine* e, Stop* so) { engine = e; stop = so; @@ -68,8 +68,19 @@ namespace Gecode { namespace Search { namespace Seq { Asset::constrain(const Space& b) { engine->constrain(b); } - forceinline - Asset::~Asset(void) { + forceinline void + Asset::park(void) { + _parked = true; + } + forceinline void + Asset::resume(void) { + _parked = false; + } + forceinline bool + Asset::parked(void) const { + return _parked; + } + forceinline Asset::~Asset(void) { delete engine; delete stop; } @@ -83,7 +94,7 @@ namespace Gecode { namespace Search { namespace Seq { : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), end(EndReason::NotEnded) { - ssi.done = false; + ssi.cause = PortfolioStopCause::None; ssi.l = opt.slice; for (unsigned int i=0U; i 0) { - ssi.done = false; + if (assets[cur].parked()) { + if (++cur == n_assets) + cur = 0; + continue; + } + ssi.cause = PortfolioStopCause::None; ssi.others = stat; for (unsigned int i=0U; i 0) && (n_parked == n_assets)) { + // Only parked assets remain, they resume with the next call + end = EndReason::Limit; + return nullptr; + } + if (n_sliced + n_parked == n_assets) { + n_sliced = 0; // Increment by one slice ssi.l += slice; } - if (cur == n_assets) - cur = 0; } // All assets ended without a proof end = EndReason::Incomplete; diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 7e5d7abd4c..44042cb16c 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -75,6 +75,15 @@ namespace Gecode { namespace Search { return r == EndReason::Exhausted; } + /// Which stop object stopped an asset of a portfolio + enum class PortfolioStopCause : unsigned char { + None, ///< No stop object has stopped the asset + Slice, ///< The asset used up its slice of a sequential portfolio + Interrupt, ///< Another asset of a parallel portfolio interrupted the asset + Asset, ///< The stop object of the asset + Portfolio, ///< The stop object of the portfolio + }; + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { diff --git a/test/search.cpp b/test/search.cpp index 982b9728a8..a6ab3105f3 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3315,6 +3315,66 @@ namespace Test { PBSPortfolioStop pbs_portfolio_stop; + /// An asset stopped by its own stop object is parked while the others continue + class PBSParkedAsset : public Base { + /// Stop object that always stops + class AlwaysStop : public Gecode::Search::Stop { + public: + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return true; + } + }; + /// Whether the other asset continues and exhausts the search space + static bool others_continue(unsigned int threads) { + NoSolution root; + AlwaysStop always; + Gecode::Search::Options a; + a.stop = &always; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a); + sebs[1] = Gecode::dfs(); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + /// Whether parked assets resume with the next call + static bool resume(unsigned int threads) { + NoSolution root; + Gecode::Search::FailStop f0(0), f1(0); + Gecode::Search::Options a0, a1; + a0.stop = &f0; + a1.stop = &f1; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a0); + sebs[1] = Gecode::lds(a1); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + unsigned int limits = 0; + while ((pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit)) { + if (++limits > 1000) + return false; + f0.limit(f0.limit() + 1); + f1.limit(f1.limit() + 1); + } + return (limits > 0) && (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSParkedAsset(void) : Base("Search::PBS::ParkedAsset") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + if (!others_continue(t) || !resume(t)) + return false; + return true; + } + }; + + PBSParkedAsset pbs_parked_asset; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From 18b8652fddb1a02b8abc369cae9e9ef715a11f1d Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sun, 15 Nov 2026 02:03:28 +0100 Subject: [PATCH 08/16] Replace MetaInfo with hub and spoke contexts The meta search hooks now take contexts and answer through them: void hub(HubContext& hc); void spoke(SpokeContext& sc); Both contexts tell the hook which engine calls it (MetaEngine), why (MetaEvent), the episode, the asset and the number of assets, the last solution, the statistics and the no-goods of the episode that ended. hub() sets a MetaDecision (Restart or Continue), Restart by default. spoke() declares a SpokeCoverage (Full or Partial), Full by default. MetaInfo, the Boolean results and the deleted master() and slave() declarations are removed, and with them the compile tests for the deleted declarations. The engines call the hooks at the same points and with the same semantics as before. Restart-based search calls hub() after a solution, at the cutoff, and when a Partial spoke is exhausted or ends without a proof, honours Continue only after a solution, and ends after a Full spoke is exhausted or ends without a proof. Episodes count from zero and increase for every new spoke. Portfolio search calls hub() once with Start and spoke() for each asset. FlatZinc derives the on_restart status from the event and declares its on_restart and LNS spokes Partial. The examples, tests, documentation and migration notes use the new hooks. --- .github/workflows/build.yml | 2 +- CMakeLists.txt | 29 -- changelog.in | 10 +- docs/gecode-7-migration.md | 81 +++- examples/crossword.cpp | 15 +- examples/photo.cpp | 14 +- examples/qcp.cpp | 9 +- gecode/flatzinc.hh | 4 +- gecode/flatzinc/flatzinc.cpp | 52 +-- gecode/kernel/core.cpp | 28 +- gecode/kernel/core.hpp | 522 +++++++++++++++------- gecode/search.hh | 36 +- gecode/search/pbs.hpp | 36 +- gecode/search/rbs.cpp | 6 +- gecode/search/rbs.hpp | 18 +- gecode/search/seq/rbs.cpp | 151 ++++--- gecode/search/seq/rbs.hh | 27 +- gecode/search/seq/rbs.hpp | 12 +- test/search.cpp | 265 +++++------ test/search/hub-spoke-api-fail-master.cpp | 64 --- test/search/hub-spoke-api-fail-slave.cpp | 64 --- test/search/hub-spoke-api-pass.cpp | 63 --- 22 files changed, 769 insertions(+), 739 deletions(-) delete mode 100644 test/search/hub-spoke-api-fail-master.cpp delete mode 100644 test/search/hub-spoke-api-fail-slave.cpp delete mode 100644 test/search/hub-spoke-api-pass.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 92ed3278c0..e136eefe47 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -260,7 +260,7 @@ jobs: shell: bash run: > ctest --test-dir "$GITHUB_WORKSPACE/build-ninja" - --output-on-failure -R '^(build-gecode-test|test|hub-spoke-api-.*)$' + --output-on-failure -R '^(build-gecode-test|test)$' - name: Configure CMake Debug audit smoke shell: bash diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a66c12d92..d293267aec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1476,35 +1476,6 @@ if(BUILD_TESTING) message(WARNING "Skipping public test harness targets because required modules are disabled") endif() - # Overrides of the hub()/spoke() Space hooks must compile, and a Gecode 6 - # master() or slave() override must not, even without override. Each fail - # case overrides one old hook and must fail with the deleted-function - # diagnostic, not for another reason. MSVC words it differently (C2282), - # so there the test only requires the build to fail. - foreach(api pass fail-master fail-slave) - add_library(hub-spoke-api-${api} OBJECT EXCLUDE_FROM_ALL test/search/hub-spoke-api-${api}.cpp) - target_link_libraries(hub-spoke-api-${api} PRIVATE gecodekernel) - add_test(NAME hub-spoke-api-${api} - COMMAND ${CMAKE_COMMAND} --build "${CMAKE_BINARY_DIR}" - --target hub-spoke-api-${api} --config $) - endforeach() - set_tests_properties(hub-spoke-api-pass PROPERTIES - FIXTURES_SETUP hub-spoke-api - RESOURCE_LOCK gecode-test-build) - foreach(hook master slave) - # The failing fixtures stay out of the compilation database used for lint. - set_target_properties(hub-spoke-api-fail-${hook} PROPERTIES EXPORT_COMPILE_COMMANDS OFF) - set_tests_properties(hub-spoke-api-fail-${hook} PROPERTIES - FIXTURES_REQUIRED hub-spoke-api - RESOURCE_LOCK gecode-test-build) - if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - set_tests_properties(hub-spoke-api-fail-${hook} PROPERTIES WILL_FAIL TRUE) - else() - set_tests_properties(hub-spoke-api-fail-${hook} PROPERTIES - PASS_REGULAR_EXPRESSION "cannot override a deleted function;overriding deleted function") - endif() - endforeach() - set(GECODE_CAN_BUILD_TESTS ${GECODE_CAN_BUILD_TEST_HARNESS}) foreach(required minimodel driver) if(NOT TARGET gecode${required}) diff --git a/changelog.in b/changelog.in index dfed98a0b7..8727c377af 100755 --- a/changelog.in +++ b/changelog.in @@ -154,12 +154,12 @@ Module: search What: change Rank: major [DESCRIPTION] -Rename the meta-search Space hooks master() and slave() to hub() and spoke(). +Replace the meta-search Space hooks master() and slave() and the class +MetaInfo by hub(HubContext&) and spoke(SpokeContext&). [MORE] -There are no compatibility aliases. Space declares master() and slave() as -deleted, so an old override fails to compile with or without override. This -includes the FlatZincSpace override of slave(). See -docs/gecode-7-migration.md. +hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of +returning a Boolean. There are no compatibility aliases, also not for the +FlatZincSpace override of slave(). See docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 370ab709d2..9027192fa6 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -1,8 +1,8 @@ # Gecode 7 migration notes -## Meta-search hooks: master() and slave() are now hub() and spoke() +## Meta-search hooks: hub() and spoke() take contexts -Rename the overrides. Their signatures and return values are unchanged: +The hooks `master()` and `slave()` and the class `MetaInfo` are replaced: ```cpp // Gecode 6 @@ -10,34 +10,71 @@ bool master(const Gecode::MetaInfo& mi) override; bool slave(const Gecode::MetaInfo& mi) override; // Gecode 7 -bool hub(const Gecode::MetaInfo& mi) override; -bool spoke(const Gecode::MetaInfo& mi) override; +void hub(Gecode::HubContext& hc) override; +void spoke(Gecode::SpokeContext& sc) override; ``` -There are no compatibility aliases. `Space` declares `master()` and -`slave()` as deleted, so an old override fails to compile whether or not it -is marked `override`. Restart-based search (RBS) and portfolio-based search -(PBS) call the renamed hooks at the same points and with the same defaults -as before. - -The hooks run on these spaces: - -- RBS calls `hub()` after each solution and at each restart. The hub - carries the last solution and the no-goods from one restart to the next. - RBS calls `spoke()` on each new spoke, a clone of the hub, including the - first. The default `hub()` constrains the hub with the last solution, if - any, and posts the no-goods. -- PBS calls `hub()` once, then calls `spoke()` with the asset number on the - spoke of each asset, the hub or a clone of it. The default `hub()` - removes all branchers, so `spoke()` must post the branching of each - asset. +There are no compatibility aliases. `MetaInfo` no longer exists, so an old +override fails to compile. Restart-based search (RBS) calls `hub()` on its +hub and `spoke()` on each spoke, a clone of the hub that one episode +searches. Portfolio-based search (PBS) calls `hub()` once and `spoke()` on +the spoke of each asset. + +Both contexts provide what `MetaInfo` provided: + +| Gecode 6 | Gecode 7 | +|----------------------------------------|----------------------------------------------------| +| `mi.type()`: `RESTART`, `PORTFOLIO` | `engine()`: `MetaEngine::Restart`, `Portfolio` | +| `mi.reason()`: `RR_INIT` | `event()`: `MetaEvent::Start` | +| `RR_SOL` | `MetaEvent::Solution` | +| `RR_LIM` | `MetaEvent::Limit` | +| `RR_CMPL` | `MetaEvent::Exhausted` | +| (none) | `MetaEvent::Incomplete`, such as LDS at its limit | +| `RR_NO` (portfolio) | `MetaEvent::Start` | +| `mi.restart()` | `episode()` | +| `mi.fail()` | `statistics().fail` | +| `mi.solution()` | none: `event()` tells whether there was a solution | +| `mi.last()` | `last()` | +| `mi.nogoods()` | `nogoods()` | +| `mi.asset()` | `asset()`, and `assets()` for their number | + +`episode()` counts from zero and increases by one for every new spoke, +whatever ended the previous episode. In `hub()` it is the episode that +ended, in `spoke()` the episode that starts. `statistics()` holds the +statistics of the episode that ended. `last()` is only valid while the hook +runs; clone the solution to keep it. + +The return values become explicit decisions: + +| Gecode 6 | Gecode 7 | +|----------------------------------------|--------------------------------------------------------| +| `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | +| `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | +| `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | +| `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | + +RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored +`false` from `master()` after other events. To prove that no further +solution exists, fail the hub. + +The coverage tells the engine what a spoke covers of the hub's search space: + +- `Full`: the spoke adds only branching and constraints that the hub + implies. Exhausting it is a proof. +- `Partial`: the spoke searches part of the hub's search space, such as a + large neighbourhood. Exhausting it is no proof, and the no-goods + recorded while searching it do not reach `hub()`. + +The engine trusts the declared coverage. A spoke that declares more than it +covers, such as `Full` for a spoke that removes solutions, gives undefined +results. The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues after a solution instead of restarting. - `examples/photo.cpp`: an RBS `spoke()` that relaxes the last solution for - large neighbourhood search. + large neighbourhood search and declares `SpokeCoverage::Partial`. - `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for each asset. diff --git a/examples/crossword.cpp b/examples/crossword.cpp index 729d3bb116..dc97dc74a2 100755 --- a/examples/crossword.cpp +++ b/examples/crossword.cpp @@ -281,13 +281,14 @@ class Crossword : public Script { << ((a == 0) ? "<=" : ">") << " " << n; } - /// Do not perform a restart when a solution is found - bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) - // Post no-goods - mi.nogoods().post(*this); - // Do not perform a restart if a solution has been found - return false; + /// Post no-goods, and do not perform a restart when a solution is found + void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + hc.nogoods().post(*this); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); + } + // For portfolio search, keep the branchers } /// Constructor for cloning \a s diff --git a/examples/photo.cpp b/examples/photo.cpp index 15a19e3dd1..bd9e94c8de 100644 --- a/examples/photo.cpp +++ b/examples/photo.cpp @@ -128,15 +128,13 @@ class Photo : public IntMinimizeScript { break; } } - /// Spoke function for restarts - bool spoke(const MetaInfo& mi) { - if ((mi.type() == MetaInfo::RESTART) && - (mi.restart() > 0) && (p > 0.0)) { - const Photo& l = static_cast(*mi.last()); + /// Relax the last solution for large neighbourhood search + void spoke(SpokeContext& sc) { + if ((sc.engine() == MetaEngine::Restart) && + (sc.last() != nullptr) && (p > 0.0)) { + const Photo& l = static_cast(*sc.last()); relax(*this, pos, l.pos, rnd, p); - return false; - } else { - return true; + sc.coverage(SpokeCoverage::Partial); } } /// Constructor for cloning \a s diff --git a/examples/qcp.cpp b/examples/qcp.cpp index b74d144b3f..00f3b57348 100644 --- a/examples/qcp.cpp +++ b/examples/qcp.cpp @@ -211,11 +211,11 @@ class QCP : public Script { } } } - /// Spoke function for portfolio search - virtual bool spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) { + /// Post a different branching for each asset of portfolio search + virtual void spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Portfolio) { double tbf = opt.tbf(); - Rnd r(seeds[mi.asset() % n_seeds]); + Rnd r(seeds[sc.asset() % n_seeds]); switch (opt.branching()) { case BRANCH_SIZE: { @@ -244,7 +244,6 @@ class QCP : public Script { default: ; } } - return true; } /// Constructor for cloning \a s QCP(QCP& s) diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index 78b2039c63..534222f0f2 100755 --- a/gecode/flatzinc.hh +++ b/gecode/flatzinc.hh @@ -682,8 +682,8 @@ namespace Gecode { namespace FlatZinc { virtual void constrain(const Space& s); /// Copy function virtual Gecode::Space* copy(void); - /// Spoke function for restarts - virtual bool spoke(const MetaInfo& mi); + /// Spoke hook for restarts: on_restart and LNS spokes have partial coverage + virtual void spoke(SpokeContext& sc); /// \name AST to variable and value conversion //@{ diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index f63de0766e..054868f97b 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -2127,14 +2127,13 @@ namespace Gecode { namespace FlatZinc { #endif } - bool - FlatZincSpace::spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { + void + FlatZincSpace::spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Restart) { if (restart_data.initialized() && restart_data().mark_complete) { - // Fail the space + // Exhausting the failed spoke of full coverage proves completeness this->fail(); - // Return true to signal we are in the global search space - return true; + return; } bool ret = false; @@ -2142,7 +2141,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_int values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_iv.size() == restart_data().on_restart_iv_sol); for (int i = 0; i < restart_data().on_restart_iv_sol; ++i) { IntVar& outVar = on_restart_iv[base + restart_data().on_restart_iv_sol + i]; @@ -2175,20 +2174,20 @@ namespace Gecode { namespace FlatZinc { if (restart_data().on_restart_status) { assert(base == on_restart_iv.size() - 1); IntVar& restart_status = on_restart_iv[base]; - switch(mi.reason()) { - case MetaInfo::RR_INIT: - assert(!mi.last()); + switch(sc.event()) { + case MetaEvent::Start: + assert(sc.last() == nullptr); rel(*this, restart_status, IRT_EQ, 1); // 1: START break; - case MetaInfo::RR_SOL: - assert(mi.solution() > 0); + case MetaEvent::Solution: + assert(sc.last() != nullptr); rel(*this, restart_status, IRT_EQ, 4); // 4: SAT break; - case MetaInfo::RR_CMPL: + case MetaEvent::Exhausted: rel(*this, restart_status, IRT_EQ, 3); // 3: UNSAT break; default: - assert(mi.reason() == MetaInfo::RR_LIM); + assert((sc.event() == MetaEvent::Limit) || (sc.event() == MetaEvent::Incomplete)); rel(*this, restart_status, IRT_EQ, 2); // 2: UNKNOWN break; } @@ -2209,7 +2208,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_bool values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_bv.size() == restart_data().on_restart_bv_sol); for (int i = 0; i < restart_data().on_restart_bv_sol; ++i) { BoolVar& outVar = on_restart_bv[base + restart_data().on_restart_bv_sol + i]; @@ -2239,7 +2238,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_set values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_sv.size() == restart_data().on_restart_sv_sol); for (int i = 0; i < restart_data().on_restart_sv_sol; ++i) { SetVar& outVar = on_restart_sv[base + restart_data().on_restart_sv_sol + i]; @@ -2271,7 +2270,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_float values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_fv.size() == restart_data().on_restart_fv_sol); for (int i = 0; i < restart_data().on_restart_fv_sol; ++i) { FloatVar& outVar = on_restart_fv[base + restart_data().on_restart_fv_sol + i]; @@ -2310,30 +2309,31 @@ namespace Gecode { namespace FlatZinc { } #endif if (ret) { - return false; + // The on_restart constraints can restrict the spoke in any way + sc.coverage(SpokeCoverage::Partial); + return; } } - if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && (mi.last()==nullptr) && (_lnsInitialSolution.size()>0)) { + if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last()==nullptr) && (_lnsInitialSolution.size()>0)) { for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, _lnsInitialSolution[i]); } } - return false; - } else if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && mi.last()) { + sc.coverage(SpokeCoverage::Partial); + } else if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last() != nullptr)) { const FlatZincSpace& last = - static_cast(*mi.last()); + static_cast(*sc.last()); for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, last.iv_lns[i]); } } - return false; + sc.coverage(SpokeCoverage::Partial); } - return true; } Space* diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index e5407336c0..728aa83c37 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -901,28 +901,24 @@ namespace Gecode { throw SpaceNoComparison("Space::compare"); } - bool - Space::hub(const MetaInfo& mi) { - switch (mi.type()) { - case MetaInfo::RESTART: - if (mi.last() != nullptr) - constrain(*mi.last()); - mi.nogoods().post(*this); - // Perform a restart even if a solution has been found - return true; - case MetaInfo::PORTFOLIO: + void + Space::hub(HubContext& hc) { + switch (hc.engine()) { + case MetaEngine::Restart: + if (hc.last() != nullptr) + constrain(*hc.last()); + hc.nogoods().post(*this); + break; + case MetaEngine::Portfolio: // Kill all branchers BrancherGroup::all.kill(*this); - return true; + break; default: GECODE_NEVER; - return true; } } - bool - Space::spoke(const MetaInfo&) { - return true; - } + void + Space::spoke(SpokeContext&) {} void* diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 548efb571c..8e76dee801 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1651,97 +1651,243 @@ namespace Gecode { static NoGoods eng; }; + namespace Search { + class Statistics; + class MetaContextAccess; + } + /** - * \brief Information passed by meta search engines + * \defgroup TaskModelScriptMeta Meta search hooks + * + * A meta search engine keeps a \e hub space and searches clones of it, + * the \e spokes, with an inner engine. Restart-based search (RBS) runs + * one spoke after the other, each search of a spoke being an + * \e episode. Portfolio-based search (PBS) runs one spoke for each of + * its assets. + * + * The engines call Space::hub() on the hub and Space::spoke() on each + * spoke. A HubContext or SpokeContext tells the hook why it is called, + * and the hook answers through it: hub() with a MetaDecision, spoke() + * with a SpokeCoverage. * + * \ingroup TaskModelScript */ - class GECODE_VTABLE_EXPORT MetaInfo { - public: - /// Which type of information is provided - enum Type { - /// Information is provided by a restart-based engine - RESTART, - /// Information is provided by a portfolio-based engine - PORTFOLIO - }; - /// Reason for restarting - enum RestartReason { - /// No reason - used for PORTFOLIO - RR_NO, - /// Restarting after initialisation - RR_INIT, - /// Restarting after a solution is found - RR_SOL, - /// Restarting after exhausting search space - RR_CMPL, - /// Restarting after reaching restart limit - RR_LIM - }; + //@{ + + /// Meta search engine that calls a hook + enum class MetaEngine : unsigned char { + Restart, ///< Restart-based search (RBS) + Portfolio, ///< Portfolio-based search (PBS) + }; + + /** + * \brief Why a meta search engine calls a hook + * + * In Space::hub(), the event that ended the episode, or \c Start before + * the first one. In Space::spoke(), the event that ended the previous + * episode, or \c Start for the first episode and for the assets of a + * portfolio. + */ + enum class MetaEvent : unsigned char { + Start, ///< Search starts: no episode has run yet + Solution, ///< The episode found a solution + /** + * The episode exhausted its spoke. This is a proof only for a spoke + * of SpokeCoverage::Full, and then the engine has already ended: a + * hook only sees this event after a spoke of SpokeCoverage::Partial. + */ + Exhausted, + /** + * The inner engine ended without a proof (such as LDS). For a spoke + * of SpokeCoverage::Full, the engine has then already ended: a hook + * only sees this event after a spoke of SpokeCoverage::Partial. + */ + Incomplete, + Limit, ///< The episode reached the cutoff + }; + + /** + * \brief What a meta search engine does after Space::hub() returns + * + * The default is \c Restart. RBS honours \c Continue only after + * MetaEvent::Solution and restarts after any other event. PBS calls + * hub() only with MetaEvent::Start and ignores the decision. + */ + enum class MetaDecision : unsigned char { + /// Search a new spoke + Restart, + /// Continue the current episode: search the same spoke for the next solution + Continue, + }; + + /** + * \brief How much of the hub's search space a spoke covers + * + * Space::spoke() declares the coverage of its spoke. It decides whether + * exhausting the spoke proves that the hub has no further solution, and + * whether the no-goods recorded while searching the spoke hold in the + * hub. + * + * The engine trusts the declaration: a spoke that declares more coverage + * than it has, such as a spoke that removes solutions but declares + * \c Full, gives undefined results. + */ + enum class SpokeCoverage : unsigned char { + /** + * The spoke adds only branching and constraints that the hub + * implies: exhaustion is a proof + */ + Full, + /** + * The spoke explores part of the hub's search space, such as a large + * neighbourhood search fragment: exhaustion is no proof + */ + Partial, + }; + + /** + * \brief Information that a meta search engine passes to a hook + * + * Meta search engines create the contexts with + * Search::MetaContextAccess, models only read them. All references and + * pointers are valid only while the hook runs. + */ + class MetaContext { protected: - /// Type of information - const Type t; - /// \name Restart-based information - //@{ - /// Number of restarts - const unsigned long int r; - /// Reason for restarting - const RestartReason rr; - /// Number of solutions since last restart - const unsigned long long int s; - /// Number of failures since last restart - const unsigned long long int f; - /// Last solution found - const Space* l; - /// No-goods from restart - const NoGoods& ng; - //@} - /// \name Portfolio-based information - //@{ - /// Number of asset in portfolio - const unsigned int a; - //@} + /// The engine calling the hook + MetaEngine _engine; + /// Why the hook is called + MetaEvent _event; + /// The episode + unsigned long int _episode; + /// The asset + unsigned int _asset; + /// The number of assets + unsigned int _assets; + /// The most recent solution (possibly nullptr) + const Space* _last; + /// The statistics of the finished episode + const Search::Statistics& _statistics; + /// The no-goods of the finished episode + const NoGoods& _nogoods; + /// Initialize, the arguments correspond to the access functions + MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); public: - /// \name Constructors depending on type of engine - //@{ - /// Constructor for restart-based engine - MetaInfo(unsigned long int r, - RestartReason rr, - unsigned long long int s, - unsigned long long int f, - const Space* l, - NoGoods& ng); - /// Constructor for portfolio-based engine - MetaInfo(unsigned int a); - //@} - /// Return type of information - Type type(void) const; - /// \name Restart-based information - //@{ - /// Return number of restarts - unsigned long int restart(void) const; - /// Return reason for restarting - RestartReason reason(void) const; - /// Return number of solutions since last restart - unsigned long long int solution(void) const; - /// Return number of failures since last restart - unsigned long long int fail(void) const; - /// Return last solution found (possibly nullptr) + /// Contexts are not copied + MetaContext(const MetaContext&) = delete; + /// Contexts are not assigned + MetaContext& operator =(const MetaContext&) = delete; + /// Return the engine calling the hook + MetaEngine engine(void) const; + /// Return why the hook is called + MetaEvent event(void) const; + /** + * \brief Return the episode, counting from zero + * + * Each new spoke of RBS starts a new episode, whatever ended the + * previous one. In hub(), this is the episode that ended (zero for + * \c Start); in spoke(), the episode that starts. PBS always passes + * zero. + */ + unsigned long int episode(void) const; + /// Return the asset of a portfolio, counting from zero (zero for RBS) + unsigned int asset(void) const; + /// Return the number of assets of a portfolio (one for RBS) + unsigned int assets(void) const; + /** + * \brief Return the most recent solution, or nullptr if none + * + * The engine owns the solution, and the pointer is valid only while + * the hook runs: clone the solution to keep it. + */ const Space* last(void) const; /** - * \brief Return no-goods recorded from restart + * \brief Return the statistics of the finished episode + * + * Empty for \c Start. Use the statistics of the engine for totals. + */ + const Search::Statistics& statistics(void) const; + /** + * \brief Return the no-goods of the finished episode * - * The no-goods are empty if the search on the spoke space was - * incomplete, as they only hold in the spoke's search space. + * The no-goods are empty if the spoke of the episode has + * SpokeCoverage::Partial, as they only hold in the spoke's search + * space. */ const NoGoods& nogoods(void) const; - //@} - /// \name Portfolio-based information - //@{ - /// Return number of asset in portfolio - unsigned int asset(void) const; - //@} }; + /// Context passed to Space::hub() + class HubContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The decision + MetaDecision _decision; + private: + /// Initialize with decision MetaDecision::Restart + HubContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the decision + MetaDecision decision(void) const; + /// Set the decision to \a d, the last one set counts + void decision(MetaDecision d); + }; + + /// Context passed to Space::spoke() + class SpokeContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The coverage + SpokeCoverage _coverage; + private: + /// Initialize with coverage SpokeCoverage::Full + SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the coverage + SpokeCoverage coverage(void) const; + /// Set the coverage to \a c, the last one set counts + void coverage(SpokeCoverage c); + }; + + namespace Search { + /** + * \brief Creation of the contexts of meta search hooks + * + * For meta search engines, which create the contexts that they pass + * to Space::hub() and Space::spoke(). The arguments correspond to the + * access functions of MetaContext. + */ + class MetaContextAccess { + public: + /// Return a context for Space::hub() with decision MetaDecision::Restart + static HubContext hub(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + /// Return a context for Space::spoke() with coverage SpokeCoverage::Full + static SpokeContext spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + }; + } + + //@} + /** * \brief %Space status * \ingroup TaskSearch @@ -2192,70 +2338,54 @@ namespace Gecode { GECODE_KERNEL_EXPORT virtual SpaceComparison compare(const Space& other) const; /** - * \brief Hub configuration function for meta search engines - * - * \li Restart-based search (RBS) calls this function on its hub - * after each solution and before each restart. \a mi - * describes the restart. After a solution, returning true - * restarts search from a new spoke, and returning false - * continues the current search without calling spoke(). At a - * restart caused by the cutoff or by an incomplete spoke being - * exhausted, the result is ignored and search restarts. - * Whatever the result, if the hub fails after the call, RBS - * ends. - * - * The default function constrains the hub with the last - * solution, if any, posts the no-goods from \a mi, and - * returns true. - * - * \li Portfolio-based search (PBS) calls this function once on - * its hub before creating the assets. The result is ignored. - * - * The default function removes all branchers, so the spoke() - * function must post the branching for each asset. + * \brief Hub hook for meta search engines + * + * Restart-based search (RBS) calls hub() on its hub whenever an + * episode ends with a solution or at the cutoff, and when an episode + * that searches a spoke of SpokeCoverage::Partial is exhausted or + * ends without a proof (see MetaEvent). Any other episode that ends + * this way ends RBS with Search::EndReason::Exhausted or + * Search::EndReason::Incomplete instead. + * Portfolio-based search (PBS) calls hub() once, with + * MetaEvent::Start, before it creates the assets. + * + * The hook may post constraints in the hub and sets what the engine + * does next with \a hc.decision() (see MetaDecision). If the hub + * fails, RBS ends with Search::EndReason::Exhausted whatever + * the decision: failing the hub is how a hook declares that no + * further solution exists. + * + * The default hook constrains the hub with \a hc.last(), if any, and + * posts \a hc.nogoods() for RBS. For PBS, it removes all branchers, + * so spoke() must post the branching of each asset. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool hub(const MetaInfo& mi); + virtual void hub(HubContext& hc); /** - * \brief Spoke configuration function for meta search engines + * \brief Spoke hook for meta search engines * - * \li RBS calls this function on each spoke, a clone of the hub, - * before searching it: once when search starts and once at - * each restart. \a mi describes the restart. Returning true - * declares the search of the spoke complete: when it is - * exhausted, RBS finishes. Returning false declares it - * incomplete: when it is exhausted, RBS restarts. The no-goods - * recorded by an incomplete search only hold in the spoke's - * search space, so RBS does not pass them to hub(). This also - * holds for the first search when search starts. + * RBS calls spoke() on each new spoke, a clone of the hub, before + * searching it: for the first episode with MetaEvent::Start, and + * for each later episode with the event that ended the previous + * one. PBS calls spoke() once on the spoke of each asset, the hub + * or a clone of it, with MetaEvent::Start and the asset number. * - * \li PBS calls this function once on the spoke of each asset, - * the hub or a clone of it, and passes the asset number, - * starting from zero. The result is ignored. + * The hook may post constraints and branching in the spoke and + * declares with \a sc.coverage() how much of the hub's search space + * the spoke covers (see SpokeCoverage, the default is Full). Large + * neighbourhood search, for example, fixes part of \a sc.last() and + * declares SpokeCoverage::Partial. The no-goods recorded while + * searching a spoke of SpokeCoverage::Partial only hold in its + * search space, so RBS does not pass them to hub(). * - * The default function does nothing and returns true. + * The default hook does nothing. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool spoke(const MetaInfo& mi); - - /** - * \brief Renamed to hub() in Gecode 7 - * - * Deleted so that a Gecode 6 override, with or without - * \c override, fails to compile instead of never being called. - */ - virtual bool master(const MetaInfo& mi) = delete; - /** - * \brief Renamed to spoke() in Gecode 7 - * - * Deleted so that a Gecode 6 override, with or without - * \c override, fails to compile instead of never being called. - */ - virtual bool slave(const MetaInfo& mi) = delete; + virtual void spoke(SpokeContext& sc); /* * Member functions for search engines @@ -3259,58 +3389,106 @@ namespace Gecode { /* - * Information from meta search engines + * Contexts of meta search hooks */ forceinline - MetaInfo::MetaInfo(unsigned long int r0, - RestartReason rr0, - unsigned long long int s0, - unsigned long long int f0, - const Space* l0, - NoGoods& ng0) - : t(RESTART), r(r0), rr(rr0), s(s0), f(f0), l(l0), ng(ng0), a(0) {} - - forceinline - MetaInfo::MetaInfo(unsigned int a0) - : t(PORTFOLIO), r(0), rr(RR_NO), s(0), f(0), l(nullptr), ng(NoGoods::eng), a(a0) {} - - forceinline MetaInfo::Type - MetaInfo::type(void) const { - return t; + MetaContext::MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : _engine(engine), _event(event), _episode(episode), + _asset(asset), _assets(assets), _last(last), + _statistics(statistics), _nogoods(nogoods) {} + forceinline MetaEngine + MetaContext::engine(void) const { + return _engine; + } + forceinline MetaEvent + MetaContext::event(void) const { + return _event; } forceinline unsigned long int - MetaInfo::restart(void) const { - assert(type() == RESTART); - return r; + MetaContext::episode(void) const { + return _episode; } - forceinline MetaInfo::RestartReason - MetaInfo::reason(void) const { - return rr; - } - forceinline unsigned long long int - MetaInfo::solution(void) const { - assert(type() == RESTART); - return s; + forceinline unsigned int + MetaContext::asset(void) const { + return _asset; } - forceinline unsigned long long int - MetaInfo::fail(void) const { - assert(type() == RESTART); - return f; + forceinline unsigned int + MetaContext::assets(void) const { + return _assets; } forceinline const Space* - MetaInfo::last(void) const { - assert(type() == RESTART); - return l; + MetaContext::last(void) const { + return _last; + } + forceinline const Search::Statistics& + MetaContext::statistics(void) const { + return _statistics; } forceinline const NoGoods& - MetaInfo::nogoods(void) const { - assert(type() == RESTART); - return ng; + MetaContext::nogoods(void) const { + return _nogoods; } - forceinline unsigned int - MetaInfo::asset(void) const { - assert(type() == PORTFOLIO); - return a; + + forceinline + HubContext::HubContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _decision(MetaDecision::Restart) {} + forceinline MetaDecision + HubContext::decision(void) const { + return _decision; + } + forceinline void + HubContext::decision(MetaDecision d) { + _decision = d; + } + + forceinline + SpokeContext::SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _coverage(SpokeCoverage::Full) {} + forceinline SpokeCoverage + SpokeContext::coverage(void) const { + return _coverage; + } + forceinline void + SpokeContext::coverage(SpokeCoverage c) { + _coverage = c; + } + + forceinline HubContext + Search::MetaContextAccess::hub(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return HubContext(engine,event,episode,asset,assets,last,statistics, + nogoods); + } + forceinline SpokeContext + Search::MetaContextAccess::spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return SpokeContext(engine,event,episode,asset,assets,last,statistics, + nogoods); } diff --git a/gecode/search.hh b/gecode/search.hh index 8fdbda55a9..b40565fed7 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1516,10 +1516,10 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, * and spoke() on each spoke it clones from the hub. See Space::hub() @@ -1548,10 +1548,10 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, * and spoke() on each spoke it clones from the hub. See Space::hub() @@ -1634,14 +1634,14 @@ namespace Gecode { * limit, is dropped while the other assets continue. When every asset * has been dropped, end_reason() returns Search::EndReason::Incomplete. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start and then + * spoke() on the spoke of each asset. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1690,14 +1690,14 @@ namespace Gecode { * An external worker control is supported only when \a o selects one * asset. PBS does not implement worker-allocation policy. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start and then + * spoke() on the spoke of each asset. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 34990d41a7..7b739b2b62 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -148,6 +148,26 @@ namespace Gecode { namespace Search { delete c; } + /// Run hub() with MetaEvent::Start on the hub \a hub of a portfolio of \a n assets + forceinline void + pbs_hub(Space& hub, unsigned int n) { + Statistics start; + HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, + MetaEvent::Start,0UL,0U,n, + nullptr,start,NoGoods::eng); + hub.hub(hc); + } + + /// Run spoke() on the spoke \a s of asset \a i of \a n + forceinline void + pbs_spoke(Space& s, unsigned int i, unsigned int n) { + Statistics start; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, + MetaEvent::Start,0UL,i,n, + nullptr,start,NoGoods::eng); + s.spoke(sc); + } + /// A PBS engine builder template class E> class PbsBuilder : public Builder { @@ -242,7 +262,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(i); + pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -290,7 +310,8 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -340,7 +361,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -390,7 +411,8 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -443,12 +465,12 @@ namespace Gecode { opt.clone = false; // Always execute hub function - (void) hub->hub(0); + Search::pbs_hub(*hub,opt.assets); // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - (void) hub->spoke(0); + Search::pbs_spoke(*hub,0U,1U); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; e = Search::build(seed.get(),opt); @@ -497,7 +519,7 @@ namespace Gecode { opt.clone = false; // Always execute hub function - (void) hub->hub(0); + Search::pbs_hub(*hub,static_cast(sebs.size())); #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) diff --git a/gecode/search/rbs.cpp b/gecode/search/rbs.cpp index 1b78157317..f54e6ff54d 100644 --- a/gecode/search/rbs.cpp +++ b/gecode/search/rbs.cpp @@ -43,15 +43,15 @@ namespace Gecode { namespace Search { namespace Seq { Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best) { - return rbsengine(hub,stop,engine,stat,opt,best,true); + return rbsengine(hub,stop,engine,stat,opt,best,SpokeCoverage::Full); } Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best, - bool complete) { + SpokeCoverage coverage) { return new RBS(hub,static_cast(stop), engine, - stat,opt,best,complete); + stat,opt,best,coverage); } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 89ffef358a..f9b4f75068 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -43,7 +43,7 @@ namespace Gecode { namespace Search { namespace Seq { GECODE_SEARCH_EXPORT Stop* rbsstop(Stop* so); - /// Create restart engine whose first spoke search yields valid no-goods + /// Create restart engine whose first spoke has SpokeCoverage::Full GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, @@ -52,14 +52,13 @@ namespace Gecode { namespace Search { namespace Seq { /** * \brief Create restart engine * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first \a engine. It only determines whether - * the no-goods of that search hold in the hub. + * The value \a coverage is the coverage that the spoke hook declared for + * the space explored by the first \a engine. */ GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, - bool best, bool complete); + bool best, SpokeCoverage coverage); }}} @@ -114,12 +113,15 @@ namespace Gecode { } else { std::unique_ptr hub(m_opt.clone ? s->clone() : s); std::unique_ptr spoke(hub->clone()); - MetaInfo mi(0,MetaInfo::RR_INIT,0,0,nullptr,NoGoods::eng); - bool complete = spoke->spoke(mi); + Search::Statistics start; + SpokeContext sc = Search::MetaContextAccess::spoke( + MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, + NoGoods::eng); + spoke->spoke(sc); std::unique_ptr leaf( Search::build(spoke.get(),e_opt)); e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), - stat,m_opt,E::best,complete); + stat,m_opt,E::best,sc.coverage()); hub.release(); stop.release(); leaf.release(); diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 25696ea86a..ab80f7ef55 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -66,9 +66,9 @@ namespace Gecode { namespace Search { namespace Seq { NoGoods& RBS::hub_nogoods(void) { - // The no-goods of an incomplete spoke search only hold in its restricted - // search space, not in the hub. - if (!nogoods_valid) + // The no-goods of a partial spoke only hold in its restricted search + // space, not in the hub. + if (coverage == SpokeCoverage::Partial) return NoGoods::eng; NoGoods& ng = e->nogoods(); // Reset number of no-goods found @@ -76,6 +76,48 @@ namespace Gecode { namespace Search { namespace Seq { return ng; } + bool + RBS::hub_event(MetaEvent ev) { + Search::Statistics episode_stat = e->statistics(); + NoGoods& ng = hub_nogoods(); + HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, + 0U,1U,last,episode_stat,ng); + hub->hub(hc); + stop->nogood(ng.ng()); + // Only an episode that found a solution can continue + bool cont = (ev == MetaEvent::Solution) && + (hc.decision() == MetaDecision::Continue); + // Any other episode ends with a restart that takes the next cutoff + if (ev != MetaEvent::Solution) + stop->limit(e->statistics(),++(*co)); + if (stop->status(hub) == SS_FAILED) { + // A failed hub proves that no further solution exists + if (ev == MetaEvent::Solution) + stop->update(e->statistics()); + delete hub; + hub = nullptr; + e->reset(nullptr); + end = EndReason::Exhausted; + return false; + } + if (cont) + return true; + if (ev == MetaEvent::Solution) { + // A restart after a solution keeps the cutoff + stop->update(e->statistics()); + stop->restart(); + } + Space* spoke = hub; + hub = hub->clone(); + episode++; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, + 0U,1U,last,episode_stat,ng); + spoke->spoke(sc); + coverage = sc.coverage(); + e->reset(spoke); + return true; + } + Space* RBS::next(void) { // A failed hub proves that no further solution exists @@ -83,83 +125,66 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Exhausted; return nullptr; } - if (restart) { - restart = false; - sslr++; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),MetaInfo::RR_SOL,sslr,e->statistics().fail,last,ng); - bool r = hub->hub(mi); - stop->nogood(ng.ng()); - if (stop->status(hub) == SS_FAILED) { - stop->update(e->statistics()); - delete hub; - hub = nullptr; - e->reset(nullptr); - end = EndReason::Exhausted; + if (solution) { + solution = false; + if (!hub_event(MetaEvent::Solution)) return nullptr; - } else if (r) { - stop->update(e->statistics()); - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - sslr = 0; - stop->restart(); - } } while (true) { Space* n = e->next(); if (n != nullptr) { // The engine found a solution - restart = true; + solution = true; delete last; last = n->clone(); end = EndReason::NotEnded; return n; } - EndReason inner = e->end_reason(); - bool limit = inner == EndReason::Limit; - if ((!complete && !limit) || (limit && stop->enginestopped())) { - // The engine must perform a true restart - // The number of the restart has been incremented in the stop object - if (!complete && !limit) { - /* - * The engine might not have checked its stop object, for example - * when the spoke failed at the root or a parallel engine had no - * work. Without this check, the restarts might never stop. - */ - if (stop->meta_stop(e->statistics(),m_opt)) { - end = EndReason::Limit; - return nullptr; - } - stop->restart(); + MetaEvent ev; + switch (e->end_reason()) { + case EndReason::Limit: + if (!stop->enginestopped()) { + // A stop from above + end = EndReason::Limit; + return nullptr; } - sslr = 0; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),limit ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); - (void) hub->hub(mi); - stop->nogood(ng.ng()); - unsigned long long int nl = ++(*co); - stop->limit(e->statistics(),nl); - if (stop->status(hub) == SS_FAILED) { - // The statistics of the engine have been added by limit() - delete hub; - hub = nullptr; - e->reset(nullptr); + // The stop object has counted the restart + ev = MetaEvent::Limit; + break; + case EndReason::Exhausted: + if (coverage != SpokeCoverage::Partial) { + // The spoke covers the hub, so this is a proof end = EndReason::Exhausted; return nullptr; } - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - } else { - // A stop from above, or a complete spoke search has ended - end = inner; + ev = MetaEvent::Exhausted; + break; + case EndReason::Incomplete: + if (coverage != SpokeCoverage::Partial) { + // A new spoke would repeat the same incomplete search + end = EndReason::Incomplete; + return nullptr; + } + ev = MetaEvent::Incomplete; + break; + default: + GECODE_NEVER; return nullptr; } + if (ev != MetaEvent::Limit) { + /* + * The engine might not have checked its stop object, for example + * when the spoke failed at the root or a parallel engine had no + * work. Without this check, the restarts might never stop. + */ + if (stop->meta_stop(e->statistics(),m_opt)) { + end = EndReason::Limit; + return nullptr; + } + stop->restart(); + } + if (!hub_event(ev)) + return nullptr; } GECODE_NEVER; return nullptr; diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 4d930f2065..4daa27e18a 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -66,15 +66,13 @@ namespace Gecode { namespace Search { namespace Seq { virtual bool stop(const Statistics& s, const Options& o); /// Return true if the stop object for the meta engine says so bool meta_stop(const Statistics& s, const Options& o); - /// Return current restart count - unsigned long int restarts(void) const; /// Increment current restart count void restart(void); /// Add no-goods to meta statistics void nogood(unsigned long int n); /// Test hub status with meta statistics SpaceStatus status(Space* s); - /// Set current limit for the engine to \a l fails + /// Add statistics \a s and set the limit for the engine to \a l fails void limit(const Statistics& s, unsigned long long int l); /// Update statistics void update(const Search::Statistics& s); @@ -99,31 +97,30 @@ namespace Gecode { namespace Search { namespace Seq { RestartStop* stop; /// The options for the stop object of the meta engine Options m_opt; - /// How many solutions since the last restart - unsigned long int sslr; - /// Whether search for the next solution will be complete - bool complete; - /// Whether the no-goods of the current spoke search hold in the hub - bool nogoods_valid; - /// Whether a restart must be performed when next is called - bool restart; + /// The current episode + unsigned long int episode; + /// The coverage of the spoke of the current episode + SpokeCoverage coverage; + /// Whether the last call to next() returned a solution that hub() has not seen + bool solution; /// Whether the engine performs best solution search bool best; /// Why the last call to next() returned no solution EndReason end; /// Return the no-goods of the last spoke search, valid in the hub NoGoods& hub_nogoods(void); + /// Call hub() for event \a ev and act on its decision, return whether search continues + bool hub_event(MetaEvent ev); public: /** * \brief Constructor * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first engine \a e0, and is used as for the - * searches after later restarts. + * The value \a coverage is the coverage that the spoke hook declared + * for the space explored by the first engine \a e0. */ RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& o, bool best, - bool complete); + SpokeCoverage coverage); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index ba428fd7ba..854d26e9b4 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -42,12 +42,6 @@ namespace Gecode { namespace Search { namespace Seq { RestartStop::RestartStop(Stop* s) : l(0U), m_stop(s), e_stopped(false) {} - forceinline unsigned long int - RestartStop::restarts(void) const { - Support::Lock lock(m); - return m_stat.restart; - } - forceinline void RestartStop::restart(void) { Support::Lock lock(m); @@ -96,10 +90,10 @@ namespace Gecode { namespace Search { namespace Seq { forceinline RBS::RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& opt, - bool best0, bool complete0) + bool best0, SpokeCoverage coverage0) : e(e0), hub(s), last(nullptr), co(opt.cutoff), stop(stop0), - m_opt(opt.expand()), sslr(0), - complete(complete0), nogoods_valid(complete0), restart(false), + m_opt(opt.expand()), episode(0UL), coverage(coverage0), + solution(false), best(best0), end(EndReason::NotEnded) { stop->limit(stat,(*co)()); } diff --git a/test/search.cpp b/test/search.cpp index a6ab3105f3..7bd42eea6e 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -152,7 +152,7 @@ namespace Test { : Space(s), graph(s.graph), maximize(s.maximize), vertex(s.vertex), ceiling(s.ceiling) {} Space* copy(void) override { return new TreeSpace(*this); } - bool hub(const MetaInfo&) override { return true; } + void hub(HubContext&) override {} const Node& node(void) const { return (*graph)[vertex]; } void constrain(const Space& s) override { ceiling = static_cast(s).node().cost; @@ -405,14 +405,13 @@ namespace Test { virtual int solutions(void) const = 0; /// Verify that this is best solution virtual bool best(void) const = 0; - /// Hub configuration function that does not restart - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { - if (mi.last() != nullptr) - constrain(*mi.last()); - return false; - } else { - return false; + /// Hub hook that does not restart after a solution and keeps the branchers of a portfolio + virtual void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + if (hc.last() != nullptr) + constrain(*hc.last()); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } } }; @@ -651,43 +650,40 @@ namespace Test { return "Sol"; } /// Rule out that solution is found more than once during restarts - virtual bool hub(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::hub(mi); - if (mi.last() != nullptr) { - const HasSolutions* s - = static_cast(mi.last()); - BoolVarArgs b; - for (int i=0; ix[i]); - rel(*this, BOT_AND, b, 0); - } - break; - case MetaInfo::PORTFOLIO: - // Do not kill the brancher! - break; - default: - break; + virtual void hub(HubContext& hc) { + // For portfolio search, keep the branchers + if (hc.engine() != MetaEngine::Restart) + return; + // With an objective, restart from a bound improving on the last solution + if (htc != HTC_NONE) { + Space::hub(hc); + return; } - return false; + if (hc.last() != nullptr) { + const HasSolutions* s + = static_cast(hc.last()); + BoolVarArgs b; + for (int i=0; ix[i]); + rel(*this, BOT_AND, b, 0); + } + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } }; - /// Return a bit for restart reason \a r + /// Return a bit for meta event \a e static unsigned int - reason_bit(MetaInfo::RestartReason r) { - return 1U << static_cast(r); + event_bit(MetaEvent e) { + return 1U << static_cast(e); } /// Observations shared by meta-search dispatch test spaces struct MetaDispatchState { std::atomic hub_calls{0}; std::atomic spoke_calls{0}; - std::atomic hub_reasons{0}; - std::atomic spoke_reasons{0}; + std::atomic hub_events{0}; + std::atomic spoke_events{0}; std::atomic assets{0}; std::atomic live_spaces{0}; std::atomic copies{0}; @@ -698,8 +694,10 @@ namespace Test { std::atomic constrain_hub_asset_mask{0}; std::atomic constrain_spoke_asset_mask{0}; std::atomic nogood_handoffs{0}; - bool restart_after_solution = true; - bool solution_spoke_complete = true; + /// Decision of hub() after a solution + MetaDecision solution_decision = MetaDecision::Restart; + /// Coverage that spoke() declares after a solution + SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; bool fail_solution_spoke = false; bool nogood_model = false; /// Whether a PBS spoke() posts the branching for its asset @@ -727,43 +725,45 @@ namespace Test { int portfolio_asset; /// Record and implement a Hub callback - bool - observe_hub(const MetaInfo& mi) { + void + observe_hub(HubContext& hc) { state->hub_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) - // PBS must ignore the callback result. - return false; + // Keep the branchers of a portfolio hub + if (hc.engine() == MetaEngine::Portfolio) + return; restart_role = RestartRole::Hub; - state->hub_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); - bool default_result = Space::hub(mi); - if ((mi.type() == MetaInfo::RESTART) && (mi.nogoods().ng() > 0)) + state->hub_events.fetch_or(event_bit(hc.event()), std::memory_order_relaxed); + Space::hub(hc); + if (hc.nogoods().ng() > 0) state->nogood_handoffs.fetch_add(1, std::memory_order_relaxed); - return (mi.reason() == MetaInfo::RR_SOL) ? state->restart_after_solution : default_result; + if (hc.event() == MetaEvent::Solution) + hc.decision(state->solution_decision); } /// Record and implement a Spoke callback - bool - observe_spoke(const MetaInfo& mi) { + void + observe_spoke(SpokeContext& sc) { state->spoke_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) { - portfolio_asset = static_cast(mi.asset()); - state->assets.fetch_or(1U << mi.asset(), std::memory_order_relaxed); + if (sc.engine() == MetaEngine::Portfolio) { + portfolio_asset = static_cast(sc.asset()); + state->assets.fetch_or(1U << sc.asset(), std::memory_order_relaxed); // The default hub() removes the model's branching. A hub() // override keeps it, and then this branching is redundant. if (state->spoke_branching) Gecode::branch(*this, x, INT_VAL_MIN()); - // PBS must ignore the callback result. - return false; + return; } - state->spoke_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); + state->spoke_events.fetch_or(event_bit(sc.event()), std::memory_order_relaxed); restart_role = RestartRole::Spoke; - if ((mi.reason() == MetaInfo::RR_INIT) && state->limit_first_spoke) { + if ((sc.event() == MetaEvent::Start) && state->limit_first_spoke) { // Four distinct values from three fail only during search. distinct(*this, y, IPL_VAL); Gecode::branch(*this, y, INT_VAR_NONE(), INT_VAL_MIN()); } - if ((mi.reason() == MetaInfo::RR_SOL) && state->fail_solution_spoke) - fail(); - return (mi.reason() == MetaInfo::RR_SOL) ? state->solution_spoke_complete : true; + if (sc.event() == MetaEvent::Solution) { + if (state->fail_solution_spoke) + fail(); + sc.coverage(state->solution_spoke_coverage); + } } public: @@ -841,9 +841,9 @@ namespace Test { return new HubDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } }; @@ -860,9 +860,9 @@ namespace Test { return new SpokeDispatchSpace(*this); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -879,14 +879,14 @@ namespace Test { return new HubSpokeDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -899,8 +899,8 @@ namespace Test { RbsSpokeOnly, RbsHubContinue, RbsHubRestart, - RbsSpokeComplete, - RbsSpokeIncomplete, + RbsSpokeFull, + RbsSpokePartial, RbsLimit, PbsHubOnly, PbsSpokeOnly, @@ -949,11 +949,12 @@ namespace Test { } /// Run one RBS dispatch scenario static bool - rbs(bool restart_after_solution, bool fail_solution_spoke, bool solution_spoke_complete) { + rbs(MetaDecision solution_decision, bool fail_solution_spoke, + SpokeCoverage solution_spoke_coverage) { MetaDispatchState state; - state.restart_after_solution = restart_after_solution; + state.solution_decision = solution_decision; state.fail_solution_spoke = fail_solution_spoke; - state.solution_spoke_complete = solution_spoke_complete; + state.solution_spoke_coverage = solution_spoke_coverage; HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); Gecode::Search::Options o; @@ -966,22 +967,27 @@ namespace Test { bool ok = first != nullptr; delete first; + const unsigned int start = event_bit(MetaEvent::Start); + const unsigned int solution = event_bit(MetaEvent::Solution); + const unsigned int exhausted = event_bit(MetaEvent::Exhausted); HubSpokeDispatchSpace* second = search.next(); if (!fail_solution_spoke) { + const bool restart = solution_decision == MetaDecision::Restart; ok = ok && (second != nullptr) && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, restart_after_solution ? 2U : 1U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | - (restart_after_solution ? reason_bit(MetaInfo::RR_SOL) : 0U)); - } else if (solution_spoke_complete) { - ok = ok && (second == nullptr) && holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_SOL)); + holds(state.spoke_calls, restart ? 2U : 1U) && + holds(state.hub_events, solution) && + holds(state.spoke_events, start | (restart ? solution : 0U)); + } else if (solution_spoke_coverage == SpokeCoverage::Full) { + // Exhausting a spoke of full coverage is a proof + ok = ok && (second == nullptr) && + (search.end_reason() == EndReason::Exhausted) && + holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && + holds(state.hub_events, solution) && + holds(state.spoke_events, start | solution); } else { ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, 3U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL) | reason_bit(MetaInfo::RR_CMPL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_SOL) | - reason_bit(MetaInfo::RR_CMPL)); + holds(state.hub_events, solution | exhausted) && + holds(state.spoke_events, start | solution | exhausted); } delete second; return ok; @@ -1039,8 +1045,8 @@ namespace Test { HubSpokeDispatchSpace* solution = search.next(); bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, 2U) && holds(state.hub_reasons, reason_bit(MetaInfo::RR_LIM)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_LIM)); + holds(state.spoke_calls, 2U) && holds(state.hub_events, event_bit(MetaEvent::Limit)) && + holds(state.spoke_events, event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit)); delete solution; return ok; } @@ -1075,7 +1081,7 @@ namespace Test { meta_stop_ownership(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { Gecode::Search::NodeStop stop(0); @@ -1117,7 +1123,7 @@ namespace Test { bab_incumbent(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(rbs_state); @@ -1161,7 +1167,7 @@ namespace Test { ok = ok && holds(pbs_state.live_spaces, 0U); MetaDispatchState nested_state; - nested_state.restart_after_solution = false; + nested_state.solution_decision = MetaDecision::Continue; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(nested_state); Gecode::Search::Options outer; @@ -1202,13 +1208,13 @@ namespace Test { case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); case Scenario::RbsHubContinue: - return rbs(false, false, true); + return rbs(MetaDecision::Continue, false, SpokeCoverage::Full); case Scenario::RbsHubRestart: - return rbs(true, false, true); - case Scenario::RbsSpokeComplete: - return rbs(true, true, true); - case Scenario::RbsSpokeIncomplete: - return rbs(true, true, false); + return rbs(MetaDecision::Restart, false, SpokeCoverage::Full); + case Scenario::RbsSpokeFull: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Full); + case Scenario::RbsSpokePartial: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Partial); case Scenario::RbsLimit: return rbs_limit(); case Scenario::PbsHubOnly: @@ -1828,10 +1834,10 @@ namespace Test { } virtual Space* copy(void) { return new ParallelObjective(*this); } virtual IntVar cost(void) const { return x; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -1871,10 +1877,10 @@ namespace Test { throw ComparisonError(); return SpaceComparison::Incomparable; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -2735,14 +2741,13 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { Gecode::dom(*this,x[2],0,1); Gecode::dom(*this,x[3],0,1); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -2789,11 +2794,10 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool hub(const Gecode::MetaInfo& mi) override { + void hub(Gecode::HubContext& hc) override { // Keep the branchers for the assets of a portfolio - if (mi.type() == Gecode::MetaInfo::PORTFOLIO) - return true; - return Gecode::IntMinimizeSpace::hub(mi); + if (hc.engine() == Gecode::MetaEngine::Restart) + Gecode::IntMinimizeSpace::hub(hc); } }; @@ -2805,11 +2809,9 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingHub(*this); } - bool hub(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_LIM)) + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Limit) fail(); - return true; } }; @@ -2855,12 +2857,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.restart() > 0)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.episode() > 0)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -2913,13 +2915,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingFirstSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -3493,10 +3494,10 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingAsset(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::PORTFOLIO) && (mi.asset() == 0U)) + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Portfolio) && + (sc.asset() == 0U)) fail(); - return true; } }; @@ -3672,8 +3673,8 @@ namespace Test { (void)new MetaDispatch("RBS::SpokeOnly", MetaDispatch::Scenario::RbsSpokeOnly); (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RbsHubContinue); (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RbsHubRestart); - (void)new MetaDispatch("RBS::SpokeComplete", MetaDispatch::Scenario::RbsSpokeComplete); - (void)new MetaDispatch("RBS::SpokeIncomplete", MetaDispatch::Scenario::RbsSpokeIncomplete); + (void)new MetaDispatch("RBS::SpokeFull", MetaDispatch::Scenario::RbsSpokeFull); + (void)new MetaDispatch("RBS::SpokePartial", MetaDispatch::Scenario::RbsSpokePartial); (void)new MetaDispatch("RBS::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", MetaDispatch::Scenario::RbsNoGoodsResetOwnership); diff --git a/test/search/hub-spoke-api-fail-master.cpp b/test/search/hub-spoke-api-fail-master.cpp deleted file mode 100644 index f1e08c09d8..0000000000 --- a/test/search/hub-spoke-api-fail-master.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Main authors: - * Mikael Zayenz Lagerkvist - * - * Copyright: - * Mikael Zayenz Lagerkvist, 2026 - * - * This file is part of Gecode, the generic constraint - * development environment: - * http://www.gecode.dev - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * This file must not compile: it is hub-spoke-api-pass.cpp with the - * hub() override replaced by a Gecode 6 master() override without - * override. Space deletes master(), and a non-deleted function cannot - * override a deleted one. Successful compilation means that an old - * override would again compile and silently never be called. - * - */ - -#include - -namespace Test { namespace Search { - - /// Space overriding the meta-search hooks - class HookSpace : public Gecode::Space { - public: - HookSpace(void) {} - HookSpace(HookSpace& s) : Gecode::Space(s) {} - Gecode::Space* - copy(void) override { - return new HookSpace(*this); - } - bool - master(const Gecode::MetaInfo&) { - return true; - } - bool - spoke(const Gecode::MetaInfo&) override { - return true; - } - }; - -}} // namespace Test::Search - -// STATISTICS: test-search diff --git a/test/search/hub-spoke-api-fail-slave.cpp b/test/search/hub-spoke-api-fail-slave.cpp deleted file mode 100644 index f8b3070fb2..0000000000 --- a/test/search/hub-spoke-api-fail-slave.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Main authors: - * Mikael Zayenz Lagerkvist - * - * Copyright: - * Mikael Zayenz Lagerkvist, 2026 - * - * This file is part of Gecode, the generic constraint - * development environment: - * http://www.gecode.dev - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * This file must not compile: it is hub-spoke-api-pass.cpp with the - * spoke() override replaced by a Gecode 6 slave() override without - * override. Space deletes slave(), and a non-deleted function cannot - * override a deleted one. Successful compilation means that an old - * override would again compile and silently never be called. - * - */ - -#include - -namespace Test { namespace Search { - - /// Space overriding the meta-search hooks - class HookSpace : public Gecode::Space { - public: - HookSpace(void) {} - HookSpace(HookSpace& s) : Gecode::Space(s) {} - Gecode::Space* - copy(void) override { - return new HookSpace(*this); - } - bool - hub(const Gecode::MetaInfo&) override { - return true; - } - bool - slave(const Gecode::MetaInfo&) { - return true; - } - }; - -}} // namespace Test::Search - -// STATISTICS: test-search diff --git a/test/search/hub-spoke-api-pass.cpp b/test/search/hub-spoke-api-pass.cpp deleted file mode 100644 index 9c684f6ac8..0000000000 --- a/test/search/hub-spoke-api-pass.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Main authors: - * Mikael Zayenz Lagerkvist - * - * Copyright: - * Mikael Zayenz Lagerkvist, 2026 - * - * This file is part of Gecode, the generic constraint - * development environment: - * http://www.gecode.dev - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * This file must compile: it overrides the Gecode 7 meta-search hooks - * hub() and spoke(). The files hub-spoke-api-fail-master.cpp and - * hub-spoke-api-fail-slave.cpp differ from it only in this comment and - * in one hook. - * - */ - -#include - -namespace Test { namespace Search { - - /// Space overriding the meta-search hooks - class HookSpace : public Gecode::Space { - public: - HookSpace(void) {} - HookSpace(HookSpace& s) : Gecode::Space(s) {} - Gecode::Space* - copy(void) override { - return new HookSpace(*this); - } - bool - hub(const Gecode::MetaInfo&) override { - return true; - } - bool - spoke(const Gecode::MetaInfo&) override { - return true; - } - }; - -}} // namespace Test::Search - -// STATISTICS: test-search From 3cf8104d567f60bc74730f21022c58ab40719f23 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:46:56 +0100 Subject: [PATCH 09/16] Honour spoke coverage for no-goods and in portfolio search SpokeCoverage::Reduced declares a spoke that prunes solutions but keeps one, or an optimal one, if any exists, such as a spoke with symmetry breaking or dominance constraints. Exhausting it is a proof, as for Full, but its no-goods do not hold in the hub. Restart-based search posts only the no-goods of a Full spoke in the hub, so the no-goods of a Reduced spoke stay in that spoke, as those of a Partial spoke already did. Portfolio search honours the coverage of every asset: an asset with a Partial spoke that is exhausted is dropped instead of ending the portfolio. This also holds for a portfolio of a single asset, which then runs inside a portfolio engine instead of as the bare asset engine. --- changelog.in | 3 +- docs/gecode-7-migration.md | 15 +++++-- gecode/kernel/core.hpp | 34 +++++++++------ gecode/search.hh | 15 ++++--- gecode/search/par/pbs.hh | 13 ++++-- gecode/search/par/pbs.hpp | 18 +++++--- gecode/search/pbs.cpp | 17 ++++---- gecode/search/pbs.hpp | 63 ++++++++++++++++++++-------- gecode/search/seq/pbs.hh | 14 ++++--- gecode/search/seq/pbs.hpp | 18 +++++--- gecode/search/seq/rbs.cpp | 5 +-- gecode/search/support.hh | 18 ++++---- test/search.cpp | 86 +++++++++++++++++++++++++++++++++++--- 13 files changed, 230 insertions(+), 89 deletions(-) diff --git a/changelog.in b/changelog.in index 8727c377af..0f7c3f7a18 100755 --- a/changelog.in +++ b/changelog.in @@ -116,7 +116,8 @@ Rank: minor End a portfolio when an asset exhausts its search space. [MORE] The exhausted asset proves that no further solution exists, so the other -assets no longer run until they are stopped. +assets no longer run until they are stopped. An asset whose spoke declares +SpokeCoverage::Partial is still dropped. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 9027192fa6..bcebdf7a3d 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -52,6 +52,7 @@ The return values become explicit decisions: | `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | | `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | | `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | +| (none) | `sc.coverage(SpokeCoverage::Reduced)` | RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored `false` from `master()` after other events. To prove that no further @@ -60,15 +61,23 @@ solution exists, fail the hub. The coverage tells the engine what a spoke covers of the hub's search space: - `Full`: the spoke adds only branching and constraints that the hub - implies. Exhausting it is a proof. + implies. Exhausting it is a proof, and its no-goods hold in the hub. +- `Reduced`: the spoke prunes solutions but keeps one, or an optimal one, if + any exists, such as symmetry breaking. Exhausting it is a proof, but its + no-goods do not hold in the hub. Search for all solutions misses the + solutions that the spoke prunes. - `Partial`: the spoke searches part of the hub's search space, such as a - large neighbourhood. Exhausting it is no proof, and the no-goods - recorded while searching it do not reach `hub()`. + large neighbourhood. Exhausting it is no proof, and its no-goods do not + hold in the hub. The engine trusts the declared coverage. A spoke that declares more than it covers, such as `Full` for a spoke that removes solutions, gives undefined results. +`nogoods()` is empty unless the spoke of the episode that ended was `Full`. +PBS honours the coverage of each asset: an asset whose `Partial` spoke +exhausts is dropped instead of ending the portfolio. + The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 8e76dee801..cb837a61b3 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1693,14 +1693,16 @@ namespace Gecode { Solution, ///< The episode found a solution /** * The episode exhausted its spoke. This is a proof only for a spoke - * of SpokeCoverage::Full, and then the engine has already ended: a - * hook only sees this event after a spoke of SpokeCoverage::Partial. + * of SpokeCoverage::Full or SpokeCoverage::Reduced, and then the + * engine has already ended: a hook only sees this event after a + * spoke of SpokeCoverage::Partial. */ Exhausted, /** * The inner engine ended without a proof (such as LDS). For a spoke - * of SpokeCoverage::Full, the engine has then already ended: a hook - * only sees this event after a spoke of SpokeCoverage::Partial. + * of SpokeCoverage::Full or SpokeCoverage::Reduced, the engine has + * then already ended: a hook only sees this event after a spoke of + * SpokeCoverage::Partial. */ Incomplete, Limit, ///< The episode reached the cutoff @@ -1725,8 +1727,7 @@ namespace Gecode { * * Space::spoke() declares the coverage of its spoke. It decides whether * exhausting the spoke proves that the hub has no further solution, and - * whether the no-goods recorded while searching the spoke hold in the - * hub. + * whether the no-goods recorded in the spoke hold in the hub. * * The engine trusts the declaration: a spoke that declares more coverage * than it has, such as a spoke that removes solutions but declares @@ -1735,12 +1736,20 @@ namespace Gecode { enum class SpokeCoverage : unsigned char { /** * The spoke adds only branching and constraints that the hub - * implies: exhaustion is a proof + * implies: exhaustion is a proof, and its no-goods hold in the hub */ Full, + /** + * The spoke prunes solutions but keeps one, or an optimal one, if + * any exists, such as symmetry breaking or dominance: exhaustion is + * a proof, but its no-goods do not hold in the hub. Search for all + * solutions misses the solutions that the spoke prunes. + */ + Reduced, /** * The spoke explores part of the hub's search space, such as a large - * neighbourhood search fragment: exhaustion is no proof + * neighbourhood search fragment: exhaustion is no proof, and its + * no-goods do not hold in the hub */ Partial, }; @@ -1814,9 +1823,8 @@ namespace Gecode { /** * \brief Return the no-goods of the finished episode * - * The no-goods are empty if the spoke of the episode has - * SpokeCoverage::Partial, as they only hold in the spoke's search - * space. + * Empty unless the spoke of that episode has SpokeCoverage::Full, so + * they can always be posted in the hub. */ const NoGoods& nogoods(void) const; }; @@ -2377,8 +2385,8 @@ namespace Gecode { * the spoke covers (see SpokeCoverage, the default is Full). Large * neighbourhood search, for example, fixes part of \a sc.last() and * declares SpokeCoverage::Partial. The no-goods recorded while - * searching a spoke of SpokeCoverage::Partial only hold in its - * search space, so RBS does not pass them to hub(). + * searching a spoke only hold in the hub for SpokeCoverage::Full, so + * RBS passes no no-goods to hub() for any other spoke. * * The default hook does nothing. * diff --git a/gecode/search.hh b/gecode/search.hh index b40565fed7..c1aa785530 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1627,12 +1627,15 @@ namespace Gecode { * (see Cutoff::copy()). If the constructor throws an exception, the * caller keeps the cutoff. * - * The spoke of each asset is taken to cover the search space of the - * hub. When an asset exhausts its search space, the portfolio ends and - * end_reason() returns Search::EndReason::Exhausted. An asset that ends - * without exhausting its search space, such as LDS at its discrepancy - * limit, is dropped while the other assets continue. When every asset - * has been dropped, end_reason() returns Search::EndReason::Incomplete. + * The spoke of each asset declares its coverage in Space::spoke() (see + * SpokeCoverage). When an asset whose spoke has SpokeCoverage::Full or + * SpokeCoverage::Reduced exhausts its search space, the portfolio ends + * and end_reason() returns Search::EndReason::Exhausted. An asset that + * ends without a proof is dropped while the other assets continue: an + * asset whose spoke has SpokeCoverage::Partial and exhausts its search + * space, or an engine such as LDS at its discrepancy limit. When every + * asset has been dropped, end_reason() returns + * Search::EndReason::Incomplete. * * The class \a T can override the member functions * \code virtual void hub(HubContext& hc) \endcode diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index a91559e679..b99626f23d 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -140,11 +140,15 @@ namespace Gecode { namespace Search { namespace Par { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; /// Whether the stop object of the asset stopped it during the current call to next() bool _parked; public: - /// Initialize with portfolio \a p, engine \a e, and its stop object \a so - Asset(PBS* p, Engine* e, Stop* so); + /// Initialize with portfolio \a p, engine \a e, its stop object \a so, and the coverage \a c of its spoke + Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return statistics of asset Statistics statistics(void) const; /// Return why the last call to next() of the asset returned no solution @@ -262,8 +266,9 @@ namespace Gecode { namespace Search { namespace Par { * - the assets n_active..n_assets-1 have ended without a proof. */ public: - /// Initialize - PBS(Engine** s, Stop** so, unsigned int n, const Statistics& stat); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** s, Stop** so, const SpokeCoverage* c, unsigned int n, + const Statistics& stat); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 38bcb83161..c5190b7d87 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -168,8 +168,14 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Asset::Asset(PBS* p, Engine* e, Stop* so) - : Support::Runnable(false), portfolio(p), engine(e), stop(so), _parked(false) {} + Asset::Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c) + : Support::Runnable(false), portfolio(p), engine(e), stop(so), + _coverage(c), _parked(false) {} + template + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; + } template forceinline Statistics Asset::statistics(void) const { @@ -225,15 +231,15 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - PBS::PBS(Engine** engines, Stop** stops, unsigned int n, - const Statistics& stat0) + PBS::PBS(Engine** engines, Stop** stops, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0) : stat(stat0), portfolio_stat(stat0,n), assets(heap.alloc*>(n)), n_assets(n), n_active(n), portfolio_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); + assets[i] = new Asset(this,engines[i],stops[i],c[i]); static_cast(stops[i])->share(&tostop,&portfolio_stat,i); } } @@ -275,7 +281,7 @@ namespace Gecode { namespace Search { namespace Par { asset->parked(true); break; } - } else if (pbs_asset_proof(asset->end_reason())) { + } else if (pbs_asset_proof(asset->end_reason(),asset->coverage())) { // Stop the other assets, no further solution exists exhausted = true; tostop.store(true, std::memory_order_release); diff --git a/gecode/search/pbs.cpp b/gecode/search/pbs.cpp index 70116536ac..6bcaf91b4b 100644 --- a/gecode/search/pbs.cpp +++ b/gecode/search/pbs.cpp @@ -46,12 +46,13 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); else - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); } }}} @@ -73,12 +74,12 @@ namespace Gecode { namespace Search { namespace Par { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); else - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); } }}} diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 7b739b2b62..5c762cf492 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -158,14 +158,15 @@ namespace Gecode { namespace Search { hub.hub(hc); } - /// Run spoke() on the spoke \a s of asset \a i of \a n - forceinline void + /// Run spoke() on the spoke \a s of asset \a i of \a n and return its coverage + forceinline SpokeCoverage pbs_spoke(Space& s, unsigned int i, unsigned int n) { Statistics start; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, MetaEvent::Start,0UL,i,n, nullptr,start,NoGoods::eng); s.spoke(sc); + return sc.coverage(); } /// A PBS engine builder @@ -206,8 +207,9 @@ namespace Gecode { namespace Search { namespace Seq { /// Create sequential portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best); }}} @@ -223,8 +225,8 @@ namespace Gecode { namespace Search { namespace Par { /// Create parallel portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best); }}} @@ -245,6 +247,7 @@ namespace Gecode { namespace Search { unsigned int n_assets = opt.assets; Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -271,7 +274,7 @@ namespace Gecode { namespace Search { (void) c.release(); } Engine* e = Seq::pbsengine( - assets,stops,n_assets,stat,opt,E::best); + assets,stops,coverage,n_assets,stat,opt,E::best); pbs_release_cutoff >(cutoff); return e; } catch (...) { @@ -289,6 +292,7 @@ namespace Gecode { namespace Search { int n_assets = sebs.size(); Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Seq::pbsengine( - assets,stops,static_cast(n_assets),stat,opt,best); + assets,stops,coverage,static_cast(n_assets),stat,opt, + best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -347,6 +352,7 @@ namespace Gecode { namespace Search { Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -369,7 +375,8 @@ namespace Gecode { namespace Search { // The asset owns its cutoff (void) c.release(); } - Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); + Engine* e = Par::pbsengine(assets,stops,coverage,n_assets,stat, + E::best); pbs_release_cutoff >(cutoff); return e; } catch (...) { @@ -393,6 +400,7 @@ namespace Gecode { namespace Search { Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Par::pbsengine( - assets,stops,static_cast(n_assets),stat,best); + assets,stops,coverage,static_cast(n_assets),stat,best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -470,10 +478,29 @@ namespace Gecode { // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - Search::pbs_spoke(*hub,0U,1U); + SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; - e = Search::build(seed.get(),opt); + if (c != SpokeCoverage::Partial) { + e = Search::build(seed.get(),opt); + return; + } + // Only a portfolio engine reports an exhausted partial spoke as incomplete + std::unique_ptr stop(Search::Seq::pbsstop(nullptr,opt.stop)); + opt.stop = stop.get(); + // As for several assets, the asset owns a copy of the cutoff + Search::Cutoff* cutoff = opt.cutoff; + std::unique_ptr cc(Search::pbs_cutoff >(cutoff)); + if (cc != nullptr) + opt.cutoff = cc.get(); + std::unique_ptr asset(Search::build(seed.get(),opt)); + (void) cc.release(); + Search::Engine* a = asset.get(); + Search::Stop* so = stop.get(); + e = Search::Seq::pbsengine(&a,&so,&c,1U,stat,opt,E::best); + (void) asset.release(); + (void) stop.release(); + Search::pbs_release_cutoff >(cutoff); return; } diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 87bafc751d..739fe81eae 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -81,6 +81,8 @@ namespace Gecode { namespace Search { namespace Seq { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; /// Whether the stop object of the asset stopped it during the current call to next() bool _parked; public: @@ -90,8 +92,10 @@ namespace Gecode { namespace Search { namespace Seq { Asset(const Asset& s) = default; /// Assignment operator Asset& operator =(const Asset& s) = default; - /// Initialize with engine \a e and its stop object \a so - void init(Engine* e, Stop* so); + /// Initialize with engine \a e, its stop object \a so, and the coverage \a c of its spoke + void init(Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return next solution Space* next(void); /// Return statistics of asset @@ -129,9 +133,9 @@ namespace Gecode { namespace Search { namespace Seq { /// Why the last call to next() returned no solution EndReason end; public: - /// Initialize - PBS(Engine** assets, Stop** stops, unsigned int n, - const Statistics& stat, const Search::Options& opt); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n, const Statistics& stat, const Search::Options& opt); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index b7a66a9f35..64462dca0a 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -47,10 +47,16 @@ namespace Gecode { namespace Search { namespace Seq { forceinline Asset::Asset(void) - : engine(nullptr), stop(nullptr), _parked(false) {} + : engine(nullptr), stop(nullptr), _coverage(SpokeCoverage::Full), + _parked(false) {} forceinline void - Asset::init(Engine* e, Stop* so) { + Asset::init(Engine* e, Stop* so, SpokeCoverage c) { engine = e; stop = so; + _coverage = c; + } + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; } forceinline Space* Asset::next(void) { @@ -88,8 +94,8 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline - PBS::PBS(Engine** e, Stop** s, unsigned int n, - const Statistics& stat0, + PBS::PBS(Engine** e, Stop** s, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0, const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), @@ -98,7 +104,7 @@ namespace Gecode { namespace Search { namespace Seq { ssi.l = opt.slice; for (unsigned int i=0U; i(s[i])); + assets[i].init(e[i],static_cast(s[i]),c[i]); static_cast(s[i])->share(&ssi); } } @@ -155,7 +161,7 @@ namespace Gecode { namespace Search { namespace Seq { n_parked++; } cur++; - } else if (pbs_asset_proof(asset_end)) { + } else if (pbs_asset_proof(asset_end,assets[cur].coverage())) { end = EndReason::Exhausted; return nullptr; } else { diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index ab80f7ef55..19de19c39d 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -66,9 +66,8 @@ namespace Gecode { namespace Search { namespace Seq { NoGoods& RBS::hub_nogoods(void) { - // The no-goods of a partial spoke only hold in its restricted search - // space, not in the hub. - if (coverage == SpokeCoverage::Partial) + // The no-goods hold in the hub only for a spoke of full coverage + if (coverage != SpokeCoverage::Full) return NoGoods::eng; NoGoods& ng = e->nogoods(); // Reset number of no-goods found diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 44042cb16c..8fe8b72e9b 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -60,19 +60,17 @@ namespace Gecode { namespace Search { snapshot(Space* s, const Options& o); /** - * \brief Whether a portfolio asset that ended for reason \a r proves that - * the hub has no further solution + * \brief Whether a portfolio asset whose spoke has coverage \a c and that + * ended for reason \a r proves that the hub has no further solution * - * The spoke of every asset is taken to cover the search space of the - * hub, so an exhausted asset ends the portfolio with a proof. A spoke - * that covers only part of the search space, such as a fragment for - * large neighbourhood search, must not end the portfolio when it is - * exhausted: once spokes can declare their coverage, this is where it is - * taken into account. + * Only an asset that exhausted a spoke of full or reduced coverage ends + * the portfolio with a proof. An asset that exhausted a spoke of partial + * coverage, such as a fragment for large neighbourhood search, has proven + * nothing about the hub and is dropped. */ forceinline bool - pbs_asset_proof(EndReason r) { - return r == EndReason::Exhausted; + pbs_asset_proof(EndReason r, SpokeCoverage c) { + return (r == EndReason::Exhausted) && (c != SpokeCoverage::Partial); } /// Which stop object stopped an asset of a portfolio diff --git a/test/search.cpp b/test/search.cpp index 7bd42eea6e..c0fd35761c 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -900,6 +900,7 @@ namespace Test { RbsHubContinue, RbsHubRestart, RbsSpokeFull, + RbsSpokeReduced, RbsSpokePartial, RbsLimit, PbsHubOnly, @@ -977,8 +978,8 @@ namespace Test { holds(state.spoke_calls, restart ? 2U : 1U) && holds(state.hub_events, solution) && holds(state.spoke_events, start | (restart ? solution : 0U)); - } else if (solution_spoke_coverage == SpokeCoverage::Full) { - // Exhausting a spoke of full coverage is a proof + } else if (solution_spoke_coverage != SpokeCoverage::Partial) { + // Exhausting a spoke that is not partial is a proof ok = ok && (second == nullptr) && (search.end_reason() == EndReason::Exhausted) && holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && @@ -1213,6 +1214,8 @@ namespace Test { return rbs(MetaDecision::Restart, false, SpokeCoverage::Full); case Scenario::RbsSpokeFull: return rbs(MetaDecision::Restart, true, SpokeCoverage::Full); + case Scenario::RbsSpokeReduced: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Reduced); case Scenario::RbsSpokePartial: return rbs(MetaDecision::Restart, true, SpokeCoverage::Partial); case Scenario::RbsLimit: @@ -2722,6 +2725,76 @@ namespace Test { } }; + /// Space whose spokes add constraints that keep some solution + class SatPreservingSpoke : public Gecode::Space { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Variable with four values + Gecode::IntVar x; + /// Four variables with three values + Gecode::IntVarArray y; + /// Initialize with declared coverage \a c + SatPreservingSpoke(Gecode::SpokeCoverage c) + : coverage(c), x(*this,0,3), y(*this,4,0,2) { + Gecode::branch(*this,x,Gecode::INT_VAL_MIN()); + Gecode::branch(*this,y,Gecode::INT_VAR_NONE(),Gecode::INT_VAL_MIN()); + } + /// Clone \a s + SatPreservingSpoke(SatPreservingSpoke& s) + : Gecode::Space(s), coverage(s.coverage) { + x.update(*this,s.x); + y.update(*this,s.y); + } + Gecode::Space* copy(void) override { + return new SatPreservingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + // The y must be distinct, which is impossible, for x < 3 in the + // first episode and for x > 0 later: either keeps a solution + Gecode::BoolVar b = (sc.episode() == 0) ? + Gecode::expr(*this,x < 3) : Gecode::expr(*this,x > 0); + for (int i=0; i rbs(m,o); + delete m; + SatPreservingSpoke* s = rbs.next(); + r = rbs.end_reason(); + return s; + } + public: + RBSSpokeCoverage(void) : Base("Search::RBS::SpokeCoverage") {} + bool run(void) override { + EndReason r; + // Declared Reduced: no-goods stay in their spoke, x = 0 remains. + // These spokes are not Full, declaring them so is undefined. + SatPreservingSpoke* s = solve(Gecode::SpokeCoverage::Reduced,r); + const bool reduced = (s != nullptr) && (s->x.val() == 0); + delete s; + return reduced; + } + }; + + RBSSpokeCoverage rbs_spoke_coverage; + /// Space whose first spoke search is restricted to x2, x3 in {0,1} class RestrictedFirstSpoke : public Gecode::IntMinimizeSpace { public: @@ -2751,10 +2824,10 @@ namespace Test { } }; - /// No-goods from an incomplete spoke search are not posted in the hub - class RBSIncompleteNoGoods : public Base { + /// No-goods from a partial spoke search are not posted in the hub + class RBSPartialNoGoods : public Base { public: - RBSIncompleteNoGoods(void) : Base("Search::RBS::IncompleteNoGoods") {} + RBSPartialNoGoods(void) : Base("Search::RBS::PartialNoGoods") {} bool run(void) override { RestrictedFirstSpoke* m = new RestrictedFirstSpoke; Gecode::Search::Options o; @@ -2772,7 +2845,7 @@ namespace Test { } }; - RBSIncompleteNoGoods rbs_incomplete_nogoods; + RBSPartialNoGoods rbs_partial_nogoods; /// Space without solutions whose search tree has several failures class NoSolution : public Gecode::IntMinimizeSpace { @@ -3674,6 +3747,7 @@ namespace Test { (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RbsHubContinue); (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RbsHubRestart); (void)new MetaDispatch("RBS::SpokeFull", MetaDispatch::Scenario::RbsSpokeFull); + (void)new MetaDispatch("RBS::SpokeReduced", MetaDispatch::Scenario::RbsSpokeReduced); (void)new MetaDispatch("RBS::SpokePartial", MetaDispatch::Scenario::RbsSpokePartial); (void)new MetaDispatch("RBS::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", From f537319ee13be10e9c80cb2f9424469b3a827fee Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:51:15 +0100 Subject: [PATCH 10/16] Constrain the hub with each solution in the engine For a best solution engine, restart-based search now constrains the hub with each solution before it calls hub(), instead of leaving it to the default hub(). An override that did not call the default lost the bound and found the same solutions again. The default hub() now only posts the no-goods. --- changelog.in | 11 +++ docs/gecode-7-migration.md | 8 +++ gecode/kernel/core.cpp | 2 - gecode/kernel/core.hpp | 10 ++- gecode/search.hh | 12 ++-- gecode/search/seq/rbs.cpp | 3 + test/search.cpp | 133 ++++++++++++++++++++++++++++++++++++- 7 files changed, 169 insertions(+), 10 deletions(-) diff --git a/changelog.in b/changelog.in index 0f7c3f7a18..ff666fa4fc 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Constrain the hub of restart-based branch-and-bound search with each +solution in the engine itself. +[MORE] +The default hub() did it, so an override that did not call the default lost +the bound and found the same solutions again. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index bcebdf7a3d..a5eb1c5037 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -78,6 +78,14 @@ results. PBS honours the coverage of each asset: an asset whose `Partial` spoke exhausts is dropped instead of ending the portfolio. +Other changes to the hooks: + +- For a best solution engine such as `RBS`, the engine constrains + the hub with the last solution before it calls `hub()`. The default + `hub()` no longer calls `constrain()`, and an override that does not call + the default keeps the bound. For other engines, such as `RBS`, + RBS no longer calls `constrain()` at all. + The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index 728aa83c37..2632a32499 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -905,8 +905,6 @@ namespace Gecode { Space::hub(HubContext& hc) { switch (hc.engine()) { case MetaEngine::Restart: - if (hc.last() != nullptr) - constrain(*hc.last()); hc.nogoods().post(*this); break; case MetaEngine::Portfolio: diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index cb837a61b3..31edac311f 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2363,9 +2363,13 @@ namespace Gecode { * the decision: failing the hub is how a hook declares that no * further solution exists. * - * The default hook constrains the hub with \a hc.last(), if any, and - * posts \a hc.nogoods() for RBS. For PBS, it removes all branchers, - * so spoke() must post the branching of each asset. + * In best solution search, RBS constrains the hub with each new + * solution before it calls hub(), so an override cannot lose the + * bound by not calling the default. + * + * The default hook posts \a hc.nogoods() for RBS. For PBS, it + * removes all branchers, so spoke() must post the branching of each + * asset. * * \ingroup TaskModelScript */ diff --git a/gecode/search.hh b/gecode/search.hh index c1aa785530..9c85a6a685 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1522,8 +1522,10 @@ namespace Gecode { * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * and spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ @@ -1554,8 +1556,10 @@ namespace Gecode { * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * and spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 19de19c39d..17fb8d3e16 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -77,6 +77,9 @@ namespace Gecode { namespace Search { namespace Seq { bool RBS::hub_event(MetaEvent ev) { + // Constrain the hub with a new solution, whatever hub() does + if ((ev == MetaEvent::Solution) && best) + hub->constrain(*last); Search::Statistics episode_stat = e->statistics(); NoGoods& ng = hub_nogoods(); HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, diff --git a/test/search.cpp b/test/search.cpp index c0fd35761c..42aef9467c 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include static_assert(std::is_copy_constructible::value, @@ -1063,7 +1064,8 @@ namespace Test { o.threads = 1; o.nogoods_limit = 16; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS search(m, o); + // The engine constrains the hub by each solution + Gecode::RBS search(m, o); delete m; unsigned int solutions = 0; @@ -3541,6 +3543,135 @@ namespace Test { PBSRestartCutoff pbs_restart_cutoff; + /// Hook behaviour of ProtocolSpace + enum class Protocol { + Default, ///< Default hooks + EmptyHub, ///< hub() does nothing + }; + + /// Calls of the hooks of ProtocolSpace + struct ProtocolLog { + /// Event and episode of each hub() call + std::vector > hub; + /// Event and episode of each spoke() call + std::vector > spoke; + /// Number of spaces alive + std::atomic live{0}; + }; + + /// Space whose hooks follow a Protocol + class ProtocolSpace : public IntMinimizeSpace { + public: + /// Hook behaviour + Protocol protocol; + /// Log of hook calls + ProtocolLog* log; + /// Cost + IntVar c; + /// Whether the y must be distinct, which is impossible + BoolVar p; + /// Four variables with three values + IntVarArray y; + /// Initialize with hook behaviour \a pr and log \a l + ProtocolSpace(Protocol pr, ProtocolLog& l) + : protocol(pr), log(&l), c(*this,0,3), p(*this,0,1), y(*this,4,0,2) { + log->live++; + for (int i=0; ilive++; + c.update(*this,s.c); + p.update(*this,s.p); + y.update(*this,s.y); + } + /// Record destruction + ~ProtocolSpace(void) override { + log->live--; + } + Space* copy(void) override { + return new ProtocolSpace(*this); + } + IntVar cost(void) const override { + return c; + } + void hub(HubContext& hc) override { + log->hub.emplace_back(hc.event(),hc.episode()); + switch (protocol) { + case Protocol::EmptyHub: + return; + case Protocol::Default: + break; + } + IntMinimizeSpace::hub(hc); + } + void spoke(SpokeContext& sc) override { + log->spoke.emplace_back(sc.event(),sc.episode()); + } + }; + + /// Decisions, events, and ends of the meta search protocol + class MetaProtocol : public Base { + public: + /// Scenario + enum class Scenario { + EngineConstrainsHub, + }; + protected: + /// Scenario under test + Scenario scenario; + /// Return options for RBS with constant cutoff \a c + static Gecode::Search::Options rbs_options(unsigned long int c) { + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(c); + return o; + } + /// Check that RBS constrains the hub when hub() does nothing + static bool engine_constrains_hub(void) { + ProtocolLog log; + std::vector costs; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::EmptyHub,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + // Without the bound, every spoke finds c = 3 again + while (ProtocolSpace* s = rbs.next()) { + costs.push_back(s->c.val()); + delete s; + if (costs.size() > 10U) + return false; + } + if (rbs.end_reason() != EndReason::Exhausted) + return false; + } + return (costs == std::vector{3,2,1,0}) && (log.live == 0); + } + public: + /// Initialize scenario \a s with name \a n + MetaProtocol(const std::string& n, Scenario s) + : Base("Search::Meta::"+n), scenario(s) {} + bool run(void) override { + switch (scenario) { + case Scenario::EngineConstrainsHub: + return engine_constrains_hub(); + default: + GECODE_NEVER; + } + return false; + } + }; + + MetaProtocol meta_engine_constrains_hub + ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); + /** * \brief Constant cutoff counting its deletions * From d8fadb244c3566921972d2b144d717f090a913eb Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:54:59 +0100 Subject: [PATCH 11/16] Propagate the hub of portfolio search and require spoke branchers Portfolio search now calls status() on the hub after hub() and before it clones the spokes. A hub() that posted a constraint made the portfolio throw SpaceNotStable, and a hub that fails now ends the portfolio as exhausted. After spoke(), a spoke without branchers throws Search::SpokeNoBrancher when the hub had branchers. The default hub() removes all branchers, so a spoke() that forgot to post the branching of its asset returned the unassigned spoke as a solution. --- changelog.in | 21 ++++++++ docs/gecode-7-migration.md | 6 +++ gecode/kernel/core.hpp | 5 +- gecode/search.hh | 16 +++--- gecode/search/exception.cpp | 4 ++ gecode/search/exception.hpp | 6 +++ gecode/search/pbs.hpp | 90 +++++++++++++++++++++++++--------- test/search.cpp | 98 ++++++++++++++++++++++++++++++------- 8 files changed, 198 insertions(+), 48 deletions(-) diff --git a/changelog.in b/changelog.in index ff666fa4fc..032df50272 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,27 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Throw Search::SpokeNoBrancher when a spoke of portfolio search has no +brancher but the hub had branchers. +[MORE] +The default hub() removes all branchers, so a spoke() that forgot to post +the branching of its asset returned the unassigned spoke as a solution. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Propagate the hub of portfolio search after hub() and before cloning the +spokes. +[MORE] +A hub() that posted a constraint made the portfolio throw SpaceNotStable. + [ENTRY] Module: search What: bug diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index a5eb1c5037..ffa0997471 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -85,6 +85,12 @@ Other changes to the hooks: `hub()` no longer calls `constrain()`, and an override that does not call the default keeps the bound. For other engines, such as `RBS`, RBS no longer calls `constrain()` at all. +- PBS calls `status()` on the hub after `hub()`, so `hub()` can post + constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. +- The default PBS `hub()` still removes all branchers, so `spoke()` must post + the branching of each asset. When the hub had branchers but a spoke has + none after `spoke()`, PBS throws `Search::SpokeNoBrancher` instead of + returning the unassigned spoke as a solution. The examples show typical overrides: diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 31edac311f..5165470ddc 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2359,7 +2359,7 @@ namespace Gecode { * * The hook may post constraints in the hub and sets what the engine * does next with \a hc.decision() (see MetaDecision). If the hub - * fails, RBS ends with Search::EndReason::Exhausted whatever + * fails, the engine ends with Search::EndReason::Exhausted whatever * the decision: failing the hub is how a hook declares that no * further solution exists. * @@ -2392,6 +2392,9 @@ namespace Gecode { * searching a spoke only hold in the hub for SpokeCoverage::Full, so * RBS passes no no-goods to hub() for any other spoke. * + * PBS throws Search::SpokeNoBrancher if the hub had branchers before + * hub() and a spoke that has not failed has none after spoke(). + * * The default hook does nothing. * * \ingroup TaskModelScript diff --git a/gecode/search.hh b/gecode/search.hh index 9c85a6a685..0dccb78284 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1646,9 +1646,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub with MetaEvent::Start and then - * spoke() on the spoke of each asset. See Space::hub() and - * Space::spoke() for details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke has none + * after spoke(), the engine throws Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1702,9 +1704,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub with MetaEvent::Start and then - * spoke() on the spoke of each asset. See Space::hub() and - * Space::spoke() for details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke has none + * after spoke(), the engine throws Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/exception.cpp b/gecode/search/exception.cpp index 8e3bcb8974..f1a36df33e 100644 --- a/gecode/search/exception.cpp +++ b/gecode/search/exception.cpp @@ -52,6 +52,10 @@ namespace Gecode { namespace Search { : Exception(l,"Illegal combination of best and non-best solution search") {} + SpokeNoBrancher::SpokeNoBrancher(const char* l) + : Exception(l,"Spoke of a portfolio has no brancher, but the hub had " + "branchers") {} + NoBest::NoBest(const char* l) : Exception(l,"Best solution search is not supported") {} diff --git a/gecode/search/exception.hpp b/gecode/search/exception.hpp index 16b65661f1..dc7ff26dc3 100644 --- a/gecode/search/exception.hpp +++ b/gecode/search/exception.hpp @@ -56,6 +56,12 @@ namespace Gecode { namespace Search { /// Initialize with location \a l MixedBest(const char* l); }; + /// %Exception: Portfolio spoke without brancher although the hub had branchers + class GECODE_SEARCH_EXPORT SpokeNoBrancher : public Exception { + public: + /// Initialize with location \a l + SpokeNoBrancher(const char* l); + }; /// %Exception: Best solution search is not supported class GECODE_SEARCH_EXPORT NoBest : public Exception { public: diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 5c762cf492..7d7426d549 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -148,24 +148,46 @@ namespace Gecode { namespace Search { delete c; } - /// Run hub() with MetaEvent::Start on the hub \a hub of a portfolio of \a n assets - forceinline void - pbs_hub(Space& hub, unsigned int n) { + /** + * \brief Run hub() with MetaEvent::Start on the hub \a hub of a portfolio + * of \a n assets and propagate it + * + * Return whether the portfolio must be built. Otherwise the hub has + * failed and \a hub is deleted. + */ + template + bool + pbs_start(T* hub, unsigned int n, Statistics& stat) { + std::unique_ptr owned(hub); Statistics start; HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, MetaEvent::Start,0UL,0U,n, nullptr,start,NoGoods::eng); - hub.hub(hc); + hub->hub(hc); + if (hub->status(stat) == SS_FAILED) { + stat.fail++; + return false; + } + (void) owned.release(); + return true; } - /// Run spoke() on the spoke \a s of asset \a i of \a n and return its coverage + /** + * \brief Run spoke() on the spoke \a s of asset \a i of \a n and return + * its coverage + * + * Throw SpokeNoBrancher if the hub had branchers (\a hub_branchers) and + * \a s has none, as the spoke would then be taken as a solution. + */ forceinline SpokeCoverage - pbs_spoke(Space& s, unsigned int i, unsigned int n) { + pbs_spoke(Space& s, unsigned int i, unsigned int n, bool hub_branchers) { Statistics start; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, MetaEvent::Start,0UL,i,n, nullptr,start,NoGoods::eng); s.spoke(sc); + if (hub_branchers && !s.failed() && (BrancherGroup::all.size(s) == 0U)) + throw SpokeNoBrancher("PBS::PBS"); return sc.coverage(); } @@ -234,7 +256,8 @@ namespace Gecode { namespace Search { template class E> Engine* - pbsseq(T* hub, const Search::Statistics& stat, Options& opt) { + pbsseq(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -265,7 +288,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - coverage[i] = pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -286,7 +309,8 @@ namespace Gecode { namespace Search { template class E> Engine* pbsseq(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; int n_assets = sebs.size(); @@ -315,7 +339,8 @@ namespace Gecode { namespace Search { if (spoke.get() == hub) unowned_hub = nullptr; coverage[i] = pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -336,7 +361,8 @@ namespace Gecode { namespace Search { template class E> Engine* - pbspar(T* hub, const Search::Statistics& stat, Options& opt) { + pbspar(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -367,7 +393,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - coverage[i] = pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -388,7 +414,8 @@ namespace Gecode { namespace Search { template class E> Engine* pbspar(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; // Run every asset in its own thread, even with fewer threads than assets @@ -420,7 +447,8 @@ namespace Gecode { namespace Search { if (spoke.get() == hub) unowned_hub = nullptr; coverage[i] = pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -472,13 +500,17 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - Search::pbs_hub(*hub,opt.assets); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + if (!Search::pbs_start(hub,opt.assets,stat)) { + e = Search::Seq::dead(opt,stat); + Search::pbs_release_cutoff >(opt.cutoff); + return; + } // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U); + SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U,hub_branchers); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; if (c != SpokeCoverage::Partial) { @@ -506,10 +538,10 @@ namespace Gecode { #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,stat,opt); + e = Search::pbspar(hub,stat,opt,hub_branchers); else #endif - e = Search::pbsseq(hub,stat,opt); + e = Search::pbsseq(hub,stat,opt,hub_branchers); } template class E> @@ -545,15 +577,27 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - Search::pbs_hub(*hub,static_cast(sebs.size())); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + bool started; + try { + started = Search::pbs_start(hub,static_cast(sebs.size()), + stat); + } catch (...) { + Search::pbscleanup(sebs); + throw; + } + if (!started) { + Search::pbscleanup(sebs); + e = Search::Seq::dead(opt,stat); + return; + } #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,sebs,stat,opt,best); + e = Search::pbspar(hub,sebs,stat,opt,best,hub_branchers); else #endif - e = Search::pbsseq(hub,sebs,stat,opt,best); + e = Search::pbsseq(hub,sebs,stat,opt,best,hub_branchers); } template class E> diff --git a/test/search.cpp b/test/search.cpp index 42aef9467c..63dc5eb1b0 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -701,6 +701,8 @@ namespace Test { SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; bool fail_solution_spoke = false; bool nogood_model = false; + /// Whether the model posts a branching on x + bool model_branching = true; /// Whether a PBS spoke() posts the branching for its asset bool spoke_branching = true; /// Whether the first RBS spoke reaches the cutoff without a solution @@ -779,7 +781,8 @@ namespace Test { distinct(*this, q, IPL_VAL); Gecode::branch(*this, q, INT_VAR_NONE(), INT_VAL_MIN()); } - Gecode::branch(*this, x, INT_VAL_MIN()); + if (state->model_branching) + Gecode::branch(*this, x, INT_VAL_MIN()); } /// Clone \a s MetaDispatchSpace(MetaDispatchSpace& s) @@ -914,7 +917,8 @@ namespace Test { PbsParallelSpokeOnly, PbsParallel, PbsParallelThreadLimit, - PbsDefaultHubRemovesBranchers, + PbsSpokeWithoutBrancher, + PbsNoBrancher, RbsNoGoodsResetOwnership, MetaStopOwnership, BabIncumbent @@ -1013,23 +1017,29 @@ namespace Test { delete solution; return ok; } - /// Check that the default PBS hub() removes the model's branching + /// Check that PBS rejects a spoke without branching when the hub had one static bool - pbs_default_hub_removes_branchers(void) { + pbs_spoke_without_brancher(bool model_branching) { MetaDispatchState state; state.spoke_branching = false; + state.model_branching = model_branching; SpokeDispatchSpace* m = new SpokeDispatchSpace(state); Gecode::Search::Options o; o.assets = 3; o.threads = 1; - Gecode::PBS search(m, o); - delete m; - - // A spoke without branching is a solution as soon as it is stable. - SpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && !solution->assigned() && holds(state.spoke_calls, 3U); - delete solution; - return ok; + try { + Gecode::PBS search(m, o); + delete m; + // A spoke without branching is a solution as soon as it is stable. + SpokeDispatchSpace* solution = search.next(); + bool ok = !model_branching && (solution != nullptr) && !solution->assigned() && + holds(state.spoke_calls, 3U); + delete solution; + return ok; + } catch (const Gecode::Search::SpokeNoBrancher&) { + delete m; + return model_branching && holds(state.live_spaces, 0U); + } } /// Check RBS dispatch when the first spoke reaches the cutoff static bool @@ -1243,8 +1253,10 @@ namespace Test { case Scenario::PbsParallelThreadLimit: // Parallel PBS runs all assets, also with fewer threads. return pbs(3, 2, 1, 3, 7); - case Scenario::PbsDefaultHubRemovesBranchers: - return pbs_default_hub_removes_branchers(); + case Scenario::PbsSpokeWithoutBrancher: + return pbs_spoke_without_brancher(true); + case Scenario::PbsNoBrancher: + return pbs_spoke_without_brancher(false); case Scenario::RbsNoGoodsResetOwnership: return rbs_nogoods_reset_ownership(); case Scenario::MetaStopOwnership: @@ -1824,6 +1836,11 @@ namespace Test { constraints->fetch_add(1); IntMinimizeSpace::constrain(s); } + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); + } }; /// Small objective whose solutions arrive from worst to best @@ -3545,8 +3562,9 @@ namespace Test { /// Hook behaviour of ProtocolSpace enum class Protocol { - Default, ///< Default hooks - EmptyHub, ///< hub() does nothing + Default, ///< Default hooks + EmptyHub, ///< hub() does nothing + BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers }; /// Calls of the hooks of ProtocolSpace @@ -3607,6 +3625,12 @@ namespace Test { switch (protocol) { case Protocol::EmptyHub: return; + case Protocol::BoundInHub: + if (hc.event() == MetaEvent::Start) { + rel(*this,c,IRT_LQ,1); + return; + } + break; case Protocol::Default: break; } @@ -3623,6 +3647,7 @@ namespace Test { /// Scenario enum class Scenario { EngineConstrainsHub, + PortfolioHubConstraint, }; protected: /// Scenario under test @@ -3654,6 +3679,39 @@ namespace Test { } return (costs == std::vector{3,2,1,0}) && (log.live == 0); } + /// Check that a constraint posted by hub() under PBS takes effect + static bool portfolio_hub_constraint(void) { + ProtocolLog log; + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + Gecode::PBS pbs(m,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1); + delete s; + if (!ok) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + Gecode::PBS pbs(m,assets,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1); + delete s; + if (!ok) + return false; + } + return log.live == 0; + } public: /// Initialize scenario \a s with name \a n MetaProtocol(const std::string& n, Scenario s) @@ -3662,6 +3720,8 @@ namespace Test { switch (scenario) { case Scenario::EngineConstrainsHub: return engine_constrains_hub(); + case Scenario::PortfolioHubConstraint: + return portfolio_hub_constraint(); default: GECODE_NEVER; } @@ -3671,6 +3731,8 @@ namespace Test { MetaProtocol meta_engine_constrains_hub ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); + MetaProtocol meta_portfolio_hub_constraint + ("PortfolioHubConstraint",MetaProtocol::Scenario::PortfolioHubConstraint); /** * \brief Constant cutoff counting its deletions @@ -3903,8 +3965,8 @@ namespace Test { (void)new MetaDispatch("PBS::SequentialHubOnly", MetaDispatch::Scenario::PbsSequentialHubOnly); (void)new MetaDispatch("PBS::SequentialSpokeOnly", MetaDispatch::Scenario::PbsSequentialSpokeOnly); (void)new MetaDispatch("PBS::Sequential", MetaDispatch::Scenario::PbsSequential); - (void)new MetaDispatch("PBS::DefaultHubRemovesBranchers", - MetaDispatch::Scenario::PbsDefaultHubRemovesBranchers); + (void)new MetaDispatch("PBS::SpokeWithoutBrancher", MetaDispatch::Scenario::PbsSpokeWithoutBrancher); + (void)new MetaDispatch("PBS::NoBrancher", MetaDispatch::Scenario::PbsNoBrancher); #ifdef GECODE_HAS_THREADS (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PbsParallelHubOnly); (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PbsParallelSpokeOnly); From fe6fbb900f1d3c5279857ae0cb23e7d60e2fbc19 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:05:42 +0100 Subject: [PATCH 12/16] Add the Finish decision and per-event defaults for meta search hub() can now set MetaDecision::Finish to end restart-based search as incomplete, and Continue after MetaEvent::Limit to resume the same spoke with the next cutoff as a fresh budget. A decision that is illegal for the event throws IllegalMetaDecision, and HubContext::legal() tells which decisions are legal. Restart-based search calls hub() with Start before the first spoke, and after every episode that does not end with a proof, also when the inner engine of a Full or Reduced spoke ends incomplete. The engine sets a default decision for each event: Restart, except Finish after an Incomplete episode whose spoke is not Partial, since a new spoke would repeat the same search. A restart is counted when the engine restarts, after hub() returns and the hub is not failed. --- changelog.in | 6 +- docs/gecode-7-migration.md | 16 +- gecode/kernel/core.hpp | 95 ++++++---- gecode/kernel/exception.cpp | 3 + gecode/kernel/exception.hpp | 7 + gecode/search.hh | 20 +- gecode/search/pbs.hpp | 34 ++-- gecode/search/rbs.hpp | 19 +- gecode/search/seq/dead.cpp | 22 ++- gecode/search/seq/dead.hh | 3 +- gecode/search/seq/rbs.cpp | 86 +++++---- gecode/search/seq/rbs.hh | 2 + gecode/search/seq/rbs.hpp | 7 + test/search.cpp | 369 ++++++++++++++++++++++++++++++++++-- 14 files changed, 562 insertions(+), 127 deletions(-) diff --git a/changelog.in b/changelog.in index 032df50272..2195c5a464 100755 --- a/changelog.in +++ b/changelog.in @@ -191,8 +191,10 @@ Replace the meta-search Space hooks master() and slave() and the class MetaInfo by hub(HubContext&) and spoke(SpokeContext&). [MORE] hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of -returning a Boolean. There are no compatibility aliases, also not for the -FlatZincSpace override of slave(). See docs/gecode-7-migration.md. +returning a Boolean. Restart-based search also calls hub() when search +starts and after an episode that ends without a proof. There are no +compatibility aliases, also not for the FlatZincSpace override of slave(). +See docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index ffa0997471..131d1b54b1 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -50,13 +50,16 @@ The return values become explicit decisions: |----------------------------------------|--------------------------------------------------------| | `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | | `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | +| (none) | `hc.decision(MetaDecision::Continue)` after a limit | +| (none) | `hc.decision(MetaDecision::Finish)` | | `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | | `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | | (none) | `sc.coverage(SpokeCoverage::Reduced)` | -RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored -`false` from `master()` after other events. To prove that no further -solution exists, fail the hub. +`Continue` is only legal after `MetaEvent::Solution` and `MetaEvent::Limit`; +setting it for another event throws `IllegalMetaDecision`. `Finish` ends the +engine with `EndReason::Incomplete`. To prove that no further solution +exists, fail the hub. The coverage tells the engine what a spoke covers of the hub's search space: @@ -80,11 +83,18 @@ exhausts is dropped instead of ending the portfolio. Other changes to the hooks: +- RBS calls `hub()` with `MetaEvent::Start` before it clones the first + spoke. Gecode 6 did not call `master()` then. - For a best solution engine such as `RBS`, the engine constrains the hub with the last solution before it calls `hub()`. The default `hub()` no longer calls `constrain()`, and an override that does not call the default keeps the bound. For other engines, such as `RBS`, RBS no longer calls `constrain()` at all. +- After an episode that ends without a proof, such as LDS at its + discrepancy limit, RBS calls `hub()` with `MetaEvent::Incomplete`. By + default, it finishes when the spoke was `Full` or `Reduced`, as a new + spoke would repeat the same search, and restarts when it was `Partial`. + Both `Restart` and `Finish` are legal. - PBS calls `status()` on the hub after `hub()`, so `hub()` can post constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. - The default PBS `hub()` still removes all branchers, so `spoke()` must post diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 5165470ddc..3dc0bd1519 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1698,28 +1698,43 @@ namespace Gecode { * spoke of SpokeCoverage::Partial. */ Exhausted, - /** - * The inner engine ended without a proof (such as LDS). For a spoke - * of SpokeCoverage::Full or SpokeCoverage::Reduced, the engine has - * then already ended: a hook only sees this event after a spoke of - * SpokeCoverage::Partial. - */ - Incomplete, - Limit, ///< The episode reached the cutoff + Incomplete, ///< The inner engine ended without a proof (such as LDS) + Limit, ///< The episode reached the cutoff }; /** * \brief What a meta search engine does after Space::hub() returns * - * The default is \c Restart. RBS honours \c Continue only after - * MetaEvent::Solution and restarts after any other event. PBS calls - * hub() only with MetaEvent::Start and ignores the decision. + * The engine sets the default before it calls hub(). Which decisions are + * legal depends on the event: + * + * | Event | Restart | Continue | Finish | + * |---------------|-----------|----------|-----------| + * | \c Start | default | illegal | legal | + * | \c Solution | default | legal | legal | + * | \c Limit | default | legal | legal | + * | \c Exhausted | default | illegal | legal | + * | \c Incomplete | see below | illegal | see below | + * + * After \c Incomplete, the default is \c Finish when the spoke of the + * episode has SpokeCoverage::Full or SpokeCoverage::Reduced, as a new + * spoke would repeat the same search, and \c Restart when it has + * SpokeCoverage::Partial. + * + * Setting an illegal decision throws IllegalMetaDecision. PBS calls + * hub() only with MetaEvent::Start. */ enum class MetaDecision : unsigned char { - /// Search a new spoke + /// Search a new spoke (at \c Start: start search) Restart, - /// Continue the current episode: search the same spoke for the next solution + /** + * Continue the current episode: after \c Solution, search the same + * spoke for the next solution; after \c Limit, resume the same spoke + * with the next cutoff as a fresh budget + */ Continue, + /// End the engine: next() returns nullptr with EndReason::Incomplete + Finish, }; /** @@ -1835,9 +1850,11 @@ namespace Gecode { protected: /// The decision MetaDecision _decision; + /// Whether decision \a d is legal for event \a e (see MetaDecision) + static bool legal(MetaEvent e, MetaDecision d); private: - /// Initialize with decision MetaDecision::Restart - HubContext(MetaEngine engine, MetaEvent event, + /// Initialize with the default decision \a d + HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Search::Statistics& statistics, @@ -1845,7 +1862,12 @@ namespace Gecode { public: /// Return the decision MetaDecision decision(void) const; - /// Set the decision to \a d, the last one set counts + /** + * \brief Set the decision to \a d, the last one set counts + * + * Throws IllegalMetaDecision if \a d is illegal for the event (see + * MetaDecision). + */ void decision(MetaDecision d); }; @@ -1879,9 +1901,9 @@ namespace Gecode { */ class MetaContextAccess { public: - /// Return a context for Space::hub() with decision MetaDecision::Restart + /// Return a context for Space::hub() with the default decision \a d static HubContext hub(MetaEngine engine, MetaEvent event, - unsigned long int episode, + MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Statistics& statistics, const NoGoods& nogoods); @@ -2348,20 +2370,19 @@ namespace Gecode { /** * \brief Hub hook for meta search engines * - * Restart-based search (RBS) calls hub() on its hub whenever an - * episode ends with a solution or at the cutoff, and when an episode - * that searches a spoke of SpokeCoverage::Partial is exhausted or - * ends without a proof (see MetaEvent). Any other episode that ends - * this way ends RBS with Search::EndReason::Exhausted or - * Search::EndReason::Incomplete instead. + * Restart-based search (RBS) calls hub() on its hub when search + * starts and whenever an episode ends with a solution, at the + * cutoff, or without a proof (see MetaEvent). An episode that + * exhausts a spoke of SpokeCoverage::Full or SpokeCoverage::Reduced + * ends RBS with Search::EndReason::Exhausted instead. * Portfolio-based search (PBS) calls hub() once, with * MetaEvent::Start, before it creates the assets. * * The hook may post constraints in the hub and sets what the engine - * does next with \a hc.decision() (see MetaDecision). If the hub - * fails, the engine ends with Search::EndReason::Exhausted whatever - * the decision: failing the hub is how a hook declares that no - * further solution exists. + * does next with \a hc.decision() (see MetaDecision for the legal + * decisions and the default). If the hub fails, the engine ends + * with Search::EndReason::Exhausted whatever the decision: failing + * the hub is how a hook declares that no further solution exists. * * In best solution search, RBS constrains the hub with each new * solution before it calls hub(), so an override cannot lose the @@ -3449,21 +3470,31 @@ namespace Gecode { return _nogoods; } + forceinline bool + HubContext::legal(MetaEvent e, MetaDecision d) { + // Only an episode that found a solution or reached the cutoff continues + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } forceinline - HubContext::HubContext(MetaEngine engine, MetaEvent event, + HubContext::HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Search::Statistics& statistics, const NoGoods& nogoods) : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), - _decision(MetaDecision::Restart) {} + _decision(d) { + assert(legal(event,d)); + } forceinline MetaDecision HubContext::decision(void) const { return _decision; } forceinline void HubContext::decision(MetaDecision d) { + if (!legal(_event,d)) + throw IllegalMetaDecision("HubContext::decision"); _decision = d; } @@ -3487,12 +3518,12 @@ namespace Gecode { forceinline HubContext Search::MetaContextAccess::hub(MetaEngine engine, MetaEvent event, - unsigned long int episode, + MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Statistics& statistics, const NoGoods& nogoods) { - return HubContext(engine,event,episode,asset,assets,last,statistics, + return HubContext(engine,event,d,episode,asset,assets,last,statistics, nogoods); } forceinline SpokeContext diff --git a/gecode/kernel/exception.cpp b/gecode/kernel/exception.cpp index a273a04699..8dc6000879 100644 --- a/gecode/kernel/exception.cpp +++ b/gecode/kernel/exception.cpp @@ -89,6 +89,9 @@ namespace Gecode { MoreThanOneTracer::MoreThanOneTracer(const char* l) : Exception(l,"Attempt create more than one non-variable tracer") {} + IllegalMetaDecision::IllegalMetaDecision(const char* l) + : Exception(l,"Illegal decision for the event of a meta search hook") {} + } // STATISTICS: kernel-other diff --git a/gecode/kernel/exception.hpp b/gecode/kernel/exception.hpp index 3c174d33bc..5d46874730 100644 --- a/gecode/kernel/exception.hpp +++ b/gecode/kernel/exception.hpp @@ -166,6 +166,13 @@ namespace Gecode { MoreThanOneTracer(const char* l); }; + /// %Exception: illegal decision of a meta search hook (see MetaDecision) + class GECODE_KERNEL_EXPORT IllegalMetaDecision : public Exception { + public: + /// Initialize with location \a l + IllegalMetaDecision(const char* l); + }; + //@} } diff --git a/gecode/search.hh b/gecode/search.hh index 0dccb78284..cdf3c4ebfc 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1521,11 +1521,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() on its hub when search starts and after each + * episode, and spoke() on each spoke it clones from the hub. When \a E + * is a best solution engine, the engine constrains the hub by each + * solution before it calls hub(). See Space::hub() and Space::spoke() + * for details. * * \ingroup TaskModelSearch */ @@ -1555,11 +1555,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() on its hub when search starts and after each + * episode, and spoke() on each spoke it clones from the hub. When \a E + * is a best solution engine, the engine constrains the hub by each + * solution before it calls hub(). See Space::hub() and Space::spoke() + * for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 7d7426d549..041bb3225d 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -152,24 +152,28 @@ namespace Gecode { namespace Search { * \brief Run hub() with MetaEvent::Start on the hub \a hub of a portfolio * of \a n assets and propagate it * - * Return whether the portfolio must be built. Otherwise the hub has - * failed and \a hub is deleted. + * Return EndReason::NotEnded if the portfolio must be built. Otherwise + * delete \a hub and return EndReason::Exhausted if the hub failed or + * EndReason::Incomplete if hub() decided to finish. */ template - bool + EndReason pbs_start(T* hub, unsigned int n, Statistics& stat) { std::unique_ptr owned(hub); Statistics start; HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, - MetaEvent::Start,0UL,0U,n, + MetaEvent::Start, + MetaDecision::Restart,0UL,0U,n, nullptr,start,NoGoods::eng); hub->hub(hc); if (hub->status(stat) == SS_FAILED) { stat.fail++; - return false; + return EndReason::Exhausted; } + if (hc.decision() == MetaDecision::Finish) + return EndReason::Incomplete; (void) owned.release(); - return true; + return EndReason::NotEnded; } /** @@ -484,7 +488,7 @@ namespace Gecode { stat.fail++; if (!opt.clone) delete s; - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); /* * The assets would own the cutoff, but a dead engine does not take * it. This includes the cutoff of an outer portfolio when this is @@ -501,8 +505,9 @@ namespace Gecode { opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; - if (!Search::pbs_start(hub,opt.assets,stat)) { - e = Search::Seq::dead(opt,stat); + Search::EndReason r = Search::pbs_start(hub,opt.assets,stat); + if (r != Search::EndReason::NotEnded) { + e = Search::Seq::dead(opt,stat,r); Search::pbs_release_cutoff >(opt.cutoff); return; } @@ -568,7 +573,7 @@ namespace Gecode { if (!opt.clone) delete s; Search::pbscleanup(sebs); - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); return; } @@ -578,17 +583,16 @@ namespace Gecode { opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; - bool started; + Search::EndReason r; try { - started = Search::pbs_start(hub,static_cast(sebs.size()), - stat); + r = Search::pbs_start(hub,static_cast(sebs.size()),stat); } catch (...) { Search::pbscleanup(sebs); throw; } - if (!started) { + if (r != Search::EndReason::NotEnded) { Search::pbscleanup(sebs); - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,r); return; } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index f9b4f75068..2468b8fe7f 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -107,13 +107,28 @@ namespace Gecode { stat.fail++; if (!m_opt.clone) delete s; - e = Search::Seq::dead(e_opt, stat); + e = Search::Seq::dead(e_opt,stat,Search::EndReason::Exhausted); // The engine owns the cutoff, but a dead engine does not take it delete m_opt.cutoff; } else { std::unique_ptr hub(m_opt.clone ? s->clone() : s); - std::unique_ptr spoke(hub->clone()); Search::Statistics start; + HubContext hc = Search::MetaContextAccess::hub( + MetaEngine::Restart,MetaEvent::Start,MetaDecision::Restart,0UL,0U,1U, + nullptr,start,NoGoods::eng); + hub->hub(hc); + if ((hub->status(stat) == SS_FAILED) || + (hc.decision() == MetaDecision::Finish)) { + // A failed hub is a proof, finishing is not + Search::EndReason r = hub->failed() ? + Search::EndReason::Exhausted : Search::EndReason::Incomplete; + if (r == Search::EndReason::Exhausted) + stat.fail++; + e = Search::Seq::dead(e_opt,stat,r); + delete m_opt.cutoff; + return; + } + std::unique_ptr spoke(hub->clone()); SpokeContext sc = Search::MetaContextAccess::spoke( MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, NoGoods::eng); diff --git a/gecode/search/seq/dead.cpp b/gecode/search/seq/dead.cpp index 550b87f350..657af57540 100644 --- a/gecode/search/seq/dead.cpp +++ b/gecode/search/seq/dead.cpp @@ -35,7 +35,7 @@ namespace Gecode { namespace Search { namespace Seq { - /// A dead engine (failed root) + /// A dead engine (failed root, or a meta engine that has finished) template class GECODE_SEARCH_EXPORT Dead : public Engine { protected: @@ -43,12 +43,14 @@ namespace Gecode { namespace Search { namespace Seq { Tracer tracer; /// Statistics Statistics stat; + /// Why next() returns no solution + EndReason reason; /// Why the last call to next() returned no solution EndReason end; public: - /// Initialize - Dead(const Options& o, const Statistics& stat0); + /// Initialize, next() returns no solution for reason \a r + Dead(const Options& o, const Statistics& stat0, EndReason r); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics @@ -60,8 +62,9 @@ namespace Gecode { namespace Search { namespace Seq { }; template - Dead::Dead(const Options& o, const Statistics& stat0) - : tracer(o.tracer), stat(stat0) , end(EndReason::NotEnded) { + Dead::Dead(const Options& o, const Statistics& stat0, + EndReason r) + : tracer(o.tracer), stat(stat0), reason(r), end(EndReason::NotEnded) { tracer.engine(SearchTracer::EngineType::AOE, 1U); tracer.worker(); } @@ -69,8 +72,7 @@ namespace Gecode { namespace Search { namespace Seq { template Space* Dead::next(void) { - // The root has failed - end = EndReason::Exhausted; + end = reason; return nullptr; } @@ -92,11 +94,11 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - dead(const Options& o, const Statistics& stat) { + dead(const Options& o, const Statistics& stat, EndReason r) { if (o.tracer) - return new Dead(o,stat); + return new Dead(o,stat,r); else - return new Dead(o,stat); + return new Dead(o,stat,r); } diff --git a/gecode/search/seq/dead.hh b/gecode/search/seq/dead.hh index 4844a59f30..4355bfbb15 100644 --- a/gecode/search/seq/dead.hh +++ b/gecode/search/seq/dead.hh @@ -38,8 +38,9 @@ namespace Gecode { namespace Search { namespace Seq { + /// Create an engine without solutions whose next() ends for reason \a r GECODE_SEARCH_EXPORT - Engine* dead(const Options& o, const Statistics& stat); + Engine* dead(const Options& o, const Statistics& stat, EndReason r); }}} diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 17fb8d3e16..0f98498cd4 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -40,13 +40,24 @@ namespace Gecode { namespace Search { namespace Seq { + namespace { + + /// Return the default decision of hub() for event \a ev after a spoke of coverage \a c + MetaDecision + default_decision(MetaEvent ev, SpokeCoverage c) { + // A new spoke would repeat an incomplete search of a spoke that is not partial + if ((ev == MetaEvent::Incomplete) && (c != SpokeCoverage::Partial)) + return MetaDecision::Finish; + return MetaDecision::Restart; + } + + } + bool RestartStop::stop(const Statistics& s, const Options& o) { Support::Lock lock(m); // Stop if the fail limit for the engine says so if (s.fail > l) { - if (!e_stopped) - m_stat.restart++; e_stopped = true; return true; } @@ -82,33 +93,42 @@ namespace Gecode { namespace Search { namespace Seq { hub->constrain(*last); Search::Statistics episode_stat = e->statistics(); NoGoods& ng = hub_nogoods(); - HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, - 0U,1U,last,episode_stat,ng); + HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev, + default_decision(ev,coverage), + episode,0U,1U,last,episode_stat, + ng); hub->hub(hc); stop->nogood(ng.ng()); - // Only an episode that found a solution can continue - bool cont = (ev == MetaEvent::Solution) && - (hc.decision() == MetaDecision::Continue); - // Any other episode ends with a restart that takes the next cutoff - if (ev != MetaEvent::Solution) - stop->limit(e->statistics(),++(*co)); + MetaDecision d = hc.decision(); if (stop->status(hub) == SS_FAILED) { // A failed hub proves that no further solution exists - if (ev == MetaEvent::Solution) - stop->update(e->statistics()); + stop->update(e->statistics()); delete hub; hub = nullptr; e->reset(nullptr); end = EndReason::Exhausted; return false; } - if (cont) + switch (d) { + case MetaDecision::Finish: + end = EndReason::Incomplete; + return false; + case MetaDecision::Continue: + // After a limit, the episode continues with the next cutoff as budget + if (ev == MetaEvent::Limit) + stop->extend(e->statistics().fail + ++(*co)); return true; - if (ev == MetaEvent::Solution) { - // A restart after a solution keeps the cutoff - stop->update(e->statistics()); - stop->restart(); + case MetaDecision::Restart: + break; + default: + GECODE_NEVER; } + stop->restart(); + // A restart after a solution keeps the cutoff + if (ev == MetaEvent::Solution) + stop->update(e->statistics()); + else + stop->limit(e->statistics(),++(*co)); Space* spoke = hub; hub = hub->clone(); episode++; @@ -122,11 +142,9 @@ namespace Gecode { namespace Search { namespace Seq { Space* RBS::next(void) { - // A failed hub proves that no further solution exists - if (hub == nullptr) { - end = EndReason::Exhausted; + // A proof or a decision to finish ends the search + if ((end == EndReason::Exhausted) || (end == EndReason::Incomplete)) return nullptr; - } if (solution) { solution = false; if (!hub_event(MetaEvent::Solution)) @@ -150,7 +168,6 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; return nullptr; } - // The stop object has counted the restart ev = MetaEvent::Limit; break; case EndReason::Exhausted: @@ -162,28 +179,21 @@ namespace Gecode { namespace Search { namespace Seq { ev = MetaEvent::Exhausted; break; case EndReason::Incomplete: - if (coverage != SpokeCoverage::Partial) { - // A new spoke would repeat the same incomplete search - end = EndReason::Incomplete; - return nullptr; - } ev = MetaEvent::Incomplete; break; default: GECODE_NEVER; return nullptr; } - if (ev != MetaEvent::Limit) { - /* - * The engine might not have checked its stop object, for example - * when the spoke failed at the root or a parallel engine had no - * work. Without this check, the restarts might never stop. - */ - if (stop->meta_stop(e->statistics(),m_opt)) { - end = EndReason::Limit; - return nullptr; - } - stop->restart(); + /* + * The engine might not have checked its stop object, for example + * when the spoke failed at the root or a parallel engine had no + * work. Without this check, the restarts might never stop. + */ + if ((ev != MetaEvent::Limit) && + stop->meta_stop(e->statistics(),m_opt)) { + end = EndReason::Limit; + return nullptr; } if (!hub_event(ev)) return nullptr; diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 4daa27e18a..4ea474a991 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -74,6 +74,8 @@ namespace Gecode { namespace Search { namespace Seq { SpaceStatus status(Space* s); /// Add statistics \a s and set the limit for the engine to \a l fails void limit(const Statistics& s, unsigned long long int l); + /// Set the limit for the engine, which continues its search, to \a l fails + void extend(unsigned long long int l); /// Update statistics void update(const Search::Statistics& s); /// Return whether the engine has been stopped diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index 854d26e9b4..a6d2464433 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -68,6 +68,13 @@ namespace Gecode { namespace Search { namespace Seq { e_stopped = false; } + forceinline void + RestartStop::extend(unsigned long long int l0) { + Support::Lock lock(m); + l = l0; + e_stopped = false; + } + forceinline void RestartStop::update(const Search::Statistics& s) { Support::Lock lock(m); diff --git a/test/search.cpp b/test/search.cpp index 63dc5eb1b0..5b6f82c1ec 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -979,20 +979,20 @@ namespace Test { HubSpokeDispatchSpace* second = search.next(); if (!fail_solution_spoke) { const bool restart = solution_decision == MetaDecision::Restart; - ok = ok && (second != nullptr) && holds(state.hub_calls, 1U) && + ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, restart ? 2U : 1U) && - holds(state.hub_events, solution) && + holds(state.hub_events, start | solution) && holds(state.spoke_events, start | (restart ? solution : 0U)); } else if (solution_spoke_coverage != SpokeCoverage::Partial) { // Exhausting a spoke that is not partial is a proof ok = ok && (second == nullptr) && (search.end_reason() == EndReason::Exhausted) && - holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && - holds(state.hub_events, solution) && + holds(state.hub_calls, 2U) && holds(state.spoke_calls, 2U) && + holds(state.hub_events, start | solution) && holds(state.spoke_events, start | solution); } else { - ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, 3U) && - holds(state.hub_events, solution | exhausted) && + ok = ok && (second != nullptr) && holds(state.hub_calls, 3U) && holds(state.spoke_calls, 3U) && + holds(state.hub_events, start | solution | exhausted) && holds(state.spoke_events, start | solution | exhausted); } delete second; @@ -1056,9 +1056,10 @@ namespace Test { delete m; HubSpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, 2U) && holds(state.hub_events, event_bit(MetaEvent::Limit)) && - holds(state.spoke_events, event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit)); + const unsigned int events = event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit); + bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 2U) && + holds(state.spoke_calls, 2U) && holds(state.hub_events, events) && + holds(state.spoke_events, events); delete solution; return ok; } @@ -1217,7 +1218,7 @@ namespace Test { run(void) override { switch (scenario) { case Scenario::RbsHubOnly: - return rbs_dispatch(1, 0); + return rbs_dispatch(2, 0); case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); case Scenario::RbsHubContinue: @@ -2926,7 +2927,7 @@ namespace Test { Gecode::Search::Statistics s = rbs.statistics(); // The failures of the last spoke search are counted once if ((rbs.end_reason() != EndReason::Exhausted) || - (s.restart != 1U) || (s.fail < 2U) || + (s.restart != 0U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; if ((rbs.next() != nullptr) || @@ -3129,6 +3130,72 @@ namespace Test { LDSIncomplete lds_incomplete; + /// Space without solutions recording the default decisions after incomplete episodes + class IncompleteEpisodes : public NoSolution { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Default decisions of hub() after an incomplete episode + std::vector* defaults; + IncompleteEpisodes(Gecode::SpokeCoverage c, + std::vector& d) + : coverage(c), defaults(&d) {} + IncompleteEpisodes(IncompleteEpisodes& s) + : NoSolution(s), coverage(s.coverage), defaults(s.defaults) {} + Gecode::Space* copy(void) override { + return new IncompleteEpisodes(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Incomplete) { + defaults->push_back(hc.decision()); + // Finish after the second incomplete episode at the latest + if (defaults->size() == 2U) + hc.decision(Gecode::MetaDecision::Finish); + } + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + sc.coverage(coverage); + } + }; + + /// RBS finishes after an incomplete episode unless its spoke is partial + class RBSIncompleteDefault : public Base { + /// Return the default decisions when spokes of coverage \a c end incomplete + static std::vector + defaults(Gecode::SpokeCoverage c) { + std::vector d; + IncompleteEpisodes root(c,d); + Gecode::Search::Options o; + o.d_l = 1; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::RBS rbs(&root,o); + for (int i=0; i<2; i++) + if (IncompleteEpisodes* s = rbs.next()) { + delete s; + d.clear(); + } else if (rbs.end_reason() != EndReason::Incomplete) { + d.clear(); + } + return d; + } + public: + RBSIncompleteDefault(void) : Base("Search::RBS::IncompleteDefault") {} + bool run(void) override { + using Gecode::MetaDecision; + using Gecode::SpokeCoverage; + using Decisions = std::vector; + return (defaults(SpokeCoverage::Full) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Reduced) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Partial) == + Decisions{MetaDecision::Restart,MetaDecision::Restart}); + } + }; + + RBSIncompleteDefault rbs_incomplete_default; + /// Space for relaxing class RelaxSpace : public Gecode::Space { public: @@ -3562,9 +3629,16 @@ namespace Test { /// Hook behaviour of ProtocolSpace enum class Protocol { - Default, ///< Default hooks - EmptyHub, ///< hub() does nothing - BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers + Default, ///< Default hooks + ContinueAtStart, ///< hub() continues at Start, which is illegal + FinishAtStart, ///< hub() finishes at Start + FinishAtLimit, ///< hub() finishes at Limit + FailAtStart, ///< hub() fails at Start + FailAtSolution, ///< hub() fails at Solution + ContinueAtLimit, ///< hub() continues at Limit + EmptyHub, ///< hub() does nothing + BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers + Alternate, ///< Episodes alternate between a solution and the cutoff }; /// Calls of the hooks of ProtocolSpace @@ -3623,6 +3697,36 @@ namespace Test { void hub(HubContext& hc) override { log->hub.emplace_back(hc.event(),hc.episode()); switch (protocol) { + case Protocol::ContinueAtStart: + if (hc.event() == MetaEvent::Start) + hc.decision(MetaDecision::Continue); + break; + case Protocol::FinishAtStart: + if (hc.event() == MetaEvent::Start) { + hc.decision(MetaDecision::Finish); + return; + } + break; + case Protocol::FinishAtLimit: + if (hc.event() == MetaEvent::Limit) + hc.decision(MetaDecision::Finish); + break; + case Protocol::FailAtStart: + if (hc.event() == MetaEvent::Start) { + fail(); + return; + } + break; + case Protocol::FailAtSolution: + if (hc.event() == MetaEvent::Solution) { + fail(); + return; + } + break; + case Protocol::ContinueAtLimit: + if (hc.event() == MetaEvent::Limit) + hc.decision(MetaDecision::Continue); + break; case Protocol::EmptyHub: return; case Protocol::BoundInHub: @@ -3632,12 +3736,19 @@ namespace Test { } break; case Protocol::Default: + case Protocol::Alternate: break; } IntMinimizeSpace::hub(hc); } void spoke(SpokeContext& sc) override { log->spoke.emplace_back(sc.event(),sc.episode()); + if ((protocol == Protocol::Alternate) && + (sc.engine() == MetaEngine::Restart)) { + // Odd episodes search only the part without solutions + rel(*this,p,IRT_EQ,((sc.episode() % 2U) == 1U) ? 1 : 0); + sc.coverage(SpokeCoverage::Partial); + } } }; @@ -3646,8 +3757,16 @@ namespace Test { public: /// Scenario enum class Scenario { + DecisionLegality, + IllegalDecisionInEngine, + FinishAtStart, + FinishAtLimit, + FailAtStart, + FailAtSolution, + ContinueAtLimit, EngineConstrainsHub, PortfolioHubConstraint, + Episodes, }; protected: /// Scenario under test @@ -3659,6 +3778,167 @@ namespace Test { o.cutoff = Gecode::Search::Cutoff::constant(c); return o; } + /// Return whether engine \a e has no further solution and ends with \a r + template + static bool ends(Engine& e, EndReason r) { + for (int i=0; i<2; i++) { + if (ProtocolSpace* s = e.next()) { + delete s; + return false; + } + if (e.end_reason() != r) + return false; + } + return true; + } + /// Return whether \a d is legal after event \a e + static bool legal(MetaEvent e, MetaDecision d) { + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } + /// Check the legality of each decision for each event + static bool decision_legality(void) { + const Gecode::Search::Statistics stat; + for (MetaEvent e : {MetaEvent::Start,MetaEvent::Solution, + MetaEvent::Exhausted,MetaEvent::Incomplete, + MetaEvent::Limit}) + for (MetaDecision d : {MetaDecision::Restart,MetaDecision::Continue, + MetaDecision::Finish}) { + HubContext hc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,e,MetaDecision::Restart,0,0,1,nullptr, + stat,NoGoods::eng); + if (hc.decision() != MetaDecision::Restart) + return false; + bool thrown = false; + try { + hc.decision(d); + } catch (const IllegalMetaDecision&) { + thrown = true; + } + if ((thrown == legal(e,d)) || + (hc.decision() != (thrown ? MetaDecision::Restart : d))) + return false; + } + // The engine sets the default decision + HubContext fc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,MetaEvent::Incomplete,MetaDecision::Finish, + 0,0,1,nullptr,stat,NoGoods::eng); + if (fc.decision() != MetaDecision::Finish) + return false; + SpokeContext sc = Gecode::Search::MetaContextAccess::spoke + (MetaEngine::Restart,MetaEvent::Start,0,0,1,nullptr,stat, + NoGoods::eng); + if (sc.coverage() != SpokeCoverage::Full) + return false; + sc.coverage(SpokeCoverage::Partial); + sc.coverage(SpokeCoverage::Reduced); + return sc.coverage() == SpokeCoverage::Reduced; + } + /// Check that an illegal decision throws from the engine + static bool illegal_decision_in_engine(void) { + ProtocolLog log; + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtStart,log); + Gecode::Search::Options o = rbs_options(10); + bool thrown = false; + try { + Gecode::RBS rbs(m,o); + } catch (const IllegalMetaDecision&) { + // The engine owns the cutoff only once it is constructed + delete o.cutoff; + thrown = true; + } + delete m; + return thrown && log.spoke.empty() && (log.live == 0); + } + /// Check that RBS and PBS end with \a r when hub() at Start follows \a pr + static bool ends_at_start(Protocol pr, EndReason r) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::RBS rbs(m,rbs_options(10)); + delete m; + if (!ends(rbs,r)) + return false; + } + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + Gecode::PBS pbs(m,o); + delete m; + if (!ends(pbs,r)) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + Gecode::PBS pbs(m,assets,o); + delete m; + if (!ends(pbs,r)) + return false; + } + return log.spoke.empty() && (log.hub.size() == 4U) && (log.live == 0); + } + /// Check that Finish at Limit ends RBS without a proof + static bool finish_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FinishAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + if (!ends(rbs,EndReason::Incomplete) || + (rbs.statistics().restart != 0U)) + return false; + } + using Call = std::pair; + return (log.hub == std::vector{{MetaEvent::Start,0}, + {MetaEvent::Limit,0}}) && + (log.spoke == std::vector{{MetaEvent::Start,0}}) && + (log.live == 0); + } + /// Check that a hub failing after a solution proves exhaustion + static bool fail_at_solution(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FailAtSolution,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + if (!ends(rbs,EndReason::Exhausted)) + return false; + } + return (log.spoke.size() == 1U) && (log.live == 0); + } + /// Check that Continue at Limit resumes the same spoke + static bool continue_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + const bool assigned = s->p.assigned() && (s->p.val() == 0); + delete s; + if (!assigned || (rbs.statistics().restart != 0U)) + return false; + } + if ((log.spoke.size() != 1U) || (log.hub.size() < 3U)) + return false; + for (std::size_t i=1; i constrains the hub when hub() does nothing static bool engine_constrains_hub(void) { ProtocolLog log; @@ -3712,16 +3992,61 @@ namespace Test { } return log.live == 0; } + /// Check episode numbering across solution and limit restarts + static bool episodes(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::Alternate,log); + Gecode::RBS rbs(m,rbs_options(2)); + delete m; + for (int i=0; i<3; i++) { + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + if (rbs.statistics().restart != 4U) + return false; + } + using Call = std::pair; + const std::vector hub{{MetaEvent::Start,0}, + {MetaEvent::Solution,0}, + {MetaEvent::Limit,1}, + {MetaEvent::Solution,2}, + {MetaEvent::Limit,3}}; + const std::vector spoke{{MetaEvent::Start,0}, + {MetaEvent::Solution,1}, + {MetaEvent::Limit,2}, + {MetaEvent::Solution,3}, + {MetaEvent::Limit,4}}; + return (log.hub == hub) && (log.spoke == spoke) && (log.live == 0); + } public: /// Initialize scenario \a s with name \a n MetaProtocol(const std::string& n, Scenario s) : Base("Search::Meta::"+n), scenario(s) {} bool run(void) override { switch (scenario) { + case Scenario::DecisionLegality: + return decision_legality(); + case Scenario::IllegalDecisionInEngine: + return illegal_decision_in_engine(); + case Scenario::FinishAtStart: + return ends_at_start(Protocol::FinishAtStart,EndReason::Incomplete); + case Scenario::FinishAtLimit: + return finish_at_limit(); + case Scenario::FailAtStart: + return ends_at_start(Protocol::FailAtStart,EndReason::Exhausted); + case Scenario::FailAtSolution: + return fail_at_solution(); + case Scenario::ContinueAtLimit: + return continue_at_limit(); case Scenario::EngineConstrainsHub: return engine_constrains_hub(); case Scenario::PortfolioHubConstraint: return portfolio_hub_constraint(); + case Scenario::Episodes: + return episodes(); default: GECODE_NEVER; } @@ -3729,10 +4054,26 @@ namespace Test { } }; + MetaProtocol meta_decision_legality + ("DecisionLegality",MetaProtocol::Scenario::DecisionLegality); + MetaProtocol meta_illegal_decision_in_engine + ("IllegalDecisionInEngine", + MetaProtocol::Scenario::IllegalDecisionInEngine); + MetaProtocol meta_finish_at_start + ("FinishAtStart",MetaProtocol::Scenario::FinishAtStart); + MetaProtocol meta_finish_at_limit + ("FinishAtLimit",MetaProtocol::Scenario::FinishAtLimit); + MetaProtocol meta_fail_at_start + ("FailAtStart",MetaProtocol::Scenario::FailAtStart); + MetaProtocol meta_fail_at_solution + ("FailAtSolution",MetaProtocol::Scenario::FailAtSolution); + MetaProtocol meta_continue_at_limit + ("ContinueAtLimit",MetaProtocol::Scenario::ContinueAtLimit); MetaProtocol meta_engine_constrains_hub ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); MetaProtocol meta_portfolio_hub_constraint ("PortfolioHubConstraint",MetaProtocol::Scenario::PortfolioHubConstraint); + MetaProtocol meta_episodes("Episodes",MetaProtocol::Scenario::Episodes); /** * \brief Constant cutoff counting its deletions From d55cd6de92d5ab4c1cfb602c3f222595ecfe9f3d Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:15:37 +0100 Subject: [PATCH 13/16] Keep hub branchers from taking the ids of spoke branchers A brancher that spoke() posts gets the next brancher id of the spoke. The hub, from which the spoke was cloned, still has the same counter, so a brancher that hub() posts later got the same id. Restart-based search then posted the no-goods of the spoke, which refer to the spoke's brancher by its id, for the hub's brancher: the no-goods could prune the wrong variables and lose solutions, or reach a brancher of another type. The engine now calls Space::reserve_brancher_ids() on the hub after each spoke(), so the hub's later branchers get fresh ids and no-goods for the spoke's branchers find no brancher in the hub. Branchers that other branchers post during the search of a spoke are not covered; the hub() documentation says so. --- changelog.in | 11 +++++++ gecode/kernel/core.hpp | 26 +++++++++++++++ gecode/search/rbs.hpp | 1 + gecode/search/seq/rbs.cpp | 1 + test/search.cpp | 66 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 105 insertions(+) diff --git a/changelog.in b/changelog.in index 2195c5a464..faba8e3812 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Do not let a brancher that hub() posts take the identity of a brancher that +spoke() posted earlier. +[MORE] +Restart-based search then posted the no-goods of that spoke for the wrong +brancher, which could lose solutions. + [ENTRY] Module: search What: change diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 3dc0bd1519..a640a69fc3 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2392,6 +2392,14 @@ namespace Gecode { * removes all branchers, so spoke() must post the branching of each * asset. * + * No-goods refer to the branchers that created their choices. RBS + * keeps a brancher that hub() posts from taking the identity of a + * brancher that spoke() posted, so the no-goods of a spoke are never + * posted for the wrong brancher. This does not cover branchers that + * other branchers post while a spoke is searched: if there are such + * branchers and the spoke has SpokeCoverage::Full, hub() must not + * post branchers. + * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT @@ -2443,6 +2451,17 @@ namespace Gecode { SpaceStatus status(StatusStatistics& stat); /// Query space status without collecting statistics SpaceStatus status(void); + /** + * \brief Reserve in this space the brancher ids that clone \a s uses + * + * A meta search engine calls this on its hub after spoke() has run + * on the clone \a s. A brancher that hub() posts later then never + * gets the id of a brancher that spoke() posted, so a no-good + * recorded in the spoke cannot reach the wrong brancher of the hub. + * + * \ingroup TaskSearch + */ + void reserve_brancher_ids(const Space& s); /** * \brief Create new choice for current brancher @@ -3650,6 +3669,13 @@ namespace Gecode { return status(stat); } + forceinline void + Space::reserve_brancher_ids(const Space& s) { + unsigned int n = s.pc.p.bid_sc >> sc_bits; + if (n > (pc.p.bid_sc >> sc_bits)) + pc.p.bid_sc = (n << sc_bits) | (pc.p.bid_sc & ((1U << sc_bits) - 1U)); + } + forceinline Space* Space::clone(void) const { CloneStatistics stat; diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 2468b8fe7f..6352e9328d 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -133,6 +133,7 @@ namespace Gecode { MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, NoGoods::eng); spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); std::unique_ptr leaf( Search::build(spoke.get(),e_opt)); e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 0f98498cd4..ecae1b136e 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -135,6 +135,7 @@ namespace Gecode { namespace Search { namespace Seq { SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, 0U,1U,last,episode_stat,ng); spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); coverage = sc.coverage(); e->reset(spoke); return true; diff --git a/test/search.cpp b/test/search.cpp index 5b6f82c1ec..a8d9e2d7a5 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -2867,6 +2867,72 @@ namespace Test { RBSPartialNoGoods rbs_partial_nogoods; + /// Space whose hub posts a brancher after a spoke posted one + class LateHubBrancher : public Gecode::Space { + public: + /// Variables branched on by the spokes + Gecode::IntVarArray y; + /// Variables branched on by the hub after the first episode + Gecode::IntVarArray z; + /// Whether the hub branches on z + bool z_branching; + LateHubBrancher(void) + : y(*this,5,0,2), z(*this,2,0,1), z_branching(false) { + // For y0 = 0 the other y must be distinct, which is impossible + Gecode::BoolVar b = Gecode::expr(*this,y[0] == 0); + for (int i=1; i rbs(m,o); + delete m; + // A no-good taken for one on z would rule out z = (0,0) + LateHubBrancher* s = rbs.next(); + const bool ok = (s != nullptr) && + (s->z[0].val() == 0) && (s->z[1].val() == 0); + delete s; + return ok; + } + }; + + RBSLateHubBrancher rbs_late_hub_brancher; + /// Space without solutions whose search tree has several failures class NoSolution : public Gecode::IntMinimizeSpace { public: From 25ca6dec265fc0cdb2557eb88af5c4a1af2a2bf5 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:16:18 +0100 Subject: [PATCH 14/16] Delete the spoke when spoke() throws at a restart Restart-based search took the old hub as the spoke and called spoke() on it before handing it to the engine. An exception from spoke() or from reserving the brancher ids leaked the spoke. Hold it in a unique_ptr until the engine takes it. --- changelog.in | 8 ++++++ gecode/search/seq/rbs.cpp | 10 +++++--- test/search.cpp | 54 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/changelog.in b/changelog.in index faba8e3812..d237ad6495 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,14 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Delete the spoke of restart-based search when spoke() throws an exception at +a restart. + [ENTRY] Module: search What: bug diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index ecae1b136e..cadbb1fecf 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -38,6 +38,8 @@ #include +#include + namespace Gecode { namespace Search { namespace Seq { namespace { @@ -129,15 +131,17 @@ namespace Gecode { namespace Search { namespace Seq { stop->update(e->statistics()); else stop->limit(e->statistics(),++(*co)); - Space* spoke = hub; - hub = hub->clone(); + // The old hub becomes the spoke, which is deleted if spoke() throws + std::unique_ptr next_hub(hub->clone()); + std::unique_ptr spoke(hub); + hub = next_hub.release(); episode++; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, 0U,1U,last,episode_stat,ng); spoke->spoke(sc); hub->reserve_brancher_ids(*spoke); coverage = sc.coverage(); - e->reset(spoke); + e->reset(spoke.release()); return true; } diff --git a/test/search.cpp b/test/search.cpp index a8d9e2d7a5..dd4730a741 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -50,6 +50,7 @@ #include #include #include +#include #include #include #include @@ -3110,6 +3111,59 @@ namespace Test { RBSFailedFirstSpoke rbs_failed_first_spoke; + /// Space without solutions whose spoke() throws after the first episode + class ThrowingSpoke : public NoSolution { + public: + /// Number of spaces alive, shared with the workers of a parallel engine + std::atomic* live; + ThrowingSpoke(std::atomic& l) : live(&l) { + (*live)++; + } + ThrowingSpoke(ThrowingSpoke& s) : NoSolution(s), live(s.live) { + (*live)++; + } + ~ThrowingSpoke(void) override { + (*live)--; + } + Gecode::Space* copy(void) override { + return new ThrowingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.episode() == 1) + throw std::runtime_error("spoke"); + } + }; + + /// RBS deletes the spoke when spoke() throws at a restart + class RBSSpokeException : public Base { + public: + RBSSpokeException(void) : Base("Search::RBS::SpokeException") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { + std::atomic live{0}; + bool thrown = false; + { + ThrowingSpoke root(live); + Gecode::Search::Options o; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS rbs(&root,o); + try { + if (ThrowingSpoke* s = rbs.next()) + delete s; + } catch (const std::runtime_error&) { + thrown = true; + } + } + if (!thrown || (live != 0)) + return false; + } + return true; + } + }; + + RBSSpokeException rbs_spoke_exception; + /// Stop after a number of failures, or after many checks as a safeguard class FailureLimit : public Gecode::Search::Stop { public: From 11081ba695f84640d2657547bd1d1953aa59e63d Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:17:43 +0100 Subject: [PATCH 15/16] Test an exception from an asset of portfolio search An exception that a hook throws in an asset, such as IllegalMetaDecision from the hub of a restart-based asset, must not leave the thread of a parallel asset. Parallel portfolio search already catches it, stops the other assets, and rethrows it from next(). Check this for sequential and parallel portfolios. --- test/search.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/test/search.cpp b/test/search.cpp index dd4730a741..3d9d279c92 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3655,6 +3655,53 @@ namespace Test { PBSParkedAsset pbs_parked_asset; + /// Space without solutions whose hub continues after a partial spoke is exhausted, which is illegal + class IllegalContinue : public NoSolution { + public: + IllegalContinue(void) = default; + IllegalContinue(IllegalContinue& s) : NoSolution(s) {} + Gecode::Space* copy(void) override { + return new IllegalContinue(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Exhausted) + hc.decision(Gecode::MetaDecision::Continue); + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.engine() == Gecode::MetaEngine::Restart) + sc.coverage(Gecode::SpokeCoverage::Partial); + } + }; + + /// An exception thrown in an asset of a portfolio is rethrown by next() + class PBSAssetException : public Base { + public: + PBSAssetException(void) : Base("Search::PBS::AssetException") {} + bool run(void) override { + for (unsigned int t : {1U,2U,4U}) { + IllegalContinue root; + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::PBS pbs(&root,o); + bool thrown = false; + try { + if (IllegalContinue* s = pbs.next()) + delete s; + } catch (const Gecode::IllegalMetaDecision&) { + thrown = true; + } + if (!thrown) + return false; + } + return true; + } + }; + + PBSAssetException pbs_asset_exception; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From 5dd73b30ee3f51f3944a8601cd0f82225566362b Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:18:18 +0100 Subject: [PATCH 16/16] Advance the repeated generator of Cutoff::repeat() CutoffRepeat read the current value of the generator it repeats without advancing it, so after the first value it repeated the same value forever. --- changelog.in | 11 +++++++++++ gecode/search/cutoff.cpp | 2 +- test/search.cpp | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/changelog.in b/changelog.in index d237ad6495..d7624f6f23 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Advance the generator that a cutoff generator from Cutoff::repeat() +repeats. +[MORE] +It read the current value of that generator without advancing it, so after +the first value it repeated the same value forever. + [ENTRY] Module: search What: bug diff --git a/gecode/search/cutoff.cpp b/gecode/search/cutoff.cpp index be173d5943..d85301feab 100755 --- a/gecode/search/cutoff.cpp +++ b/gecode/search/cutoff.cpp @@ -189,7 +189,7 @@ namespace Gecode { namespace Search { CutoffRepeat::operator ++(void) { i++; if (i == n) { - cutoff = (*c)(); + cutoff = ++(*c); i = 0; } return cutoff; diff --git a/test/search.cpp b/test/search.cpp index 3d9d279c92..ad9760f1d6 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3769,6 +3769,22 @@ namespace Test { CutoffRandomCopy cutoff_random_copy; + /// A repeating cutoff generator advances the generator it repeats + class CutoffRepeat : public Base { + public: + CutoffRepeat(void) : Base("Search::Cutoff::Repeat") {} + bool run(void) override { + std::unique_ptr c + (Gecode::Search::Cutoff::repeat(Gecode::Search::Cutoff::linear(4),3)); + std::vector v{(*c)()}; + for (int i=0; i<6; i++) + v.push_back(++(*c)); + return v == std::vector{4,4,4,8,8,8,12}; + } + }; + + CutoffRepeat cutoff_repeat; + /// Each restart-based asset of a portfolio owns a copy of the cutoff class PBSRestartCutoff : public Base { template class Engine>