From 7c336cecfbff5799c161d828300c38d29b497066 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 17:03:11 +0100 Subject: [PATCH 01/14] Rename meta-search roles to hub and spoke Gecode 7 replaces the master() and slave() Space hooks with hub() and spoke() for both restart-based and portfolio-based search. Internal PBS runnables become spokes, their back-pointer the portfolio, and the wrapped engine the engine. --- examples/crossword.cpp | 2 +- examples/job-shop.cpp | 30 +++--- examples/photo.cpp | 4 +- examples/qcp.cpp | 4 +- gecode/flatzinc.hh | 4 +- gecode/flatzinc/flatzinc.cpp | 2 +- gecode/kernel/core.cpp | 4 +- gecode/kernel/core.hpp | 32 +++--- gecode/search.hh | 32 +++--- gecode/search/par/bab.hpp | 2 +- gecode/search/par/pbs.hh | 80 +++++++------- gecode/search/par/pbs.hpp | 138 ++++++++++++------------ gecode/search/pbs.cpp | 12 +-- gecode/search/pbs.hpp | 200 +++++++++++++++++------------------ gecode/search/rbs.cpp | 8 +- gecode/search/rbs.hpp | 24 ++--- gecode/search/seq/pbs.hh | 54 +++++----- gecode/search/seq/pbs.hpp | 94 ++++++++-------- gecode/search/seq/rbs.cpp | 60 +++++------ gecode/search/seq/rbs.hh | 14 +-- gecode/search/seq/rbs.hpp | 2 +- test/search.cpp | 122 ++++++++++----------- 22 files changed, 462 insertions(+), 462 deletions(-) diff --git a/examples/crossword.cpp b/examples/crossword.cpp index d3c6075047..729d3bb116 100755 --- a/examples/crossword.cpp +++ b/examples/crossword.cpp @@ -282,7 +282,7 @@ class Crossword : public Script { << n; } /// Do not perform a restart when a solution is found - bool master(const MetaInfo& mi) { + bool hub(const MetaInfo& mi) { if (mi.type() == MetaInfo::RESTART) // Post no-goods mi.nogoods().post(*this); diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index fcfe95f182..589f7067ab 100755 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -700,16 +700,16 @@ solve(const JobShopOptions& opt) { { Support::Timer t; t.start(); Search::Statistics stat; - JobShopProbe* master = new JobShopProbe(opt); + JobShopProbe* hub = new JobShopProbe(opt); - if (master->status() != SS_SOLVED) { - delete master; + if (hub->status() != SS_SOLVED) { + delete hub; std::cerr << "Error: has no solution..." << std::endl; return; } - l = master->cost().min(); - u = master->cost().max(); + l = hub->cost().min(); + u = hub->cost().max(); FailTimeStop fts(opt.fail_probe(),opt.time_probe()); CommonOptions so(opt); @@ -722,7 +722,7 @@ solve(const JobShopOptions& opt) { << std::endl; for (unsigned int p=0; p(master->clone()); + JobShopProbe* jsp = static_cast(hub->clone()); jsp->branch(p,rnd); DFS dfs(jsp,so); JobShopProbe* s = dfs.next(); @@ -740,7 +740,7 @@ solve(const JobShopOptions& opt) { } stat += statj; } - delete master; + delete hub; print(stat,false); std::cout << "\t\t\truntime: "; @@ -756,11 +756,11 @@ solve(const JobShopOptions& opt) { // Dichotomic search { - JobShopSolve* master = new JobShopSolve(opt); + JobShopSolve* hub = new JobShopSolve(opt); - if (master->status() == SS_FAILED) { - delete master; + if (hub->status() == SS_FAILED) { + delete hub; std::cerr << "Error: has no solution..." << std::endl; return; } @@ -775,7 +775,7 @@ solve(const JobShopOptions& opt) { while (l < u) { std::cout << "\t\tBounds: [" << l << "," << u << "]" << std::endl; - JobShopSolve* jss = static_cast(master->clone()); + JobShopSolve* jss = static_cast(hub->clone()); int m = (l + u) / 2; rel(*jss, jss->cost() >= l); rel(*jss, jss->cost() <= m); @@ -810,7 +810,7 @@ solve(const JobShopOptions& opt) { } if (l == u) { - delete master; + delete hub; std::cout << std::endl << "\tFound best solution and proved optimality." << std::endl; @@ -822,15 +822,15 @@ solve(const JobShopOptions& opt) { Support::Timer t; t.start(); std::cout << std::endl << "\tSolving..." << std::endl; - rel(*master, master->cost() >= l); - rel(*master, master->cost() < u); + rel(*hub, hub->cost() >= l); + rel(*hub, hub->cost() < u); CommonOptions so(opt); if (opt.time_solve() > 0U) so.stop = Search::Stop::time(opt.time_solve()); so.cutoff = Search::Cutoff::geometric(JobShopConfig::restart_scale, JobShopConfig::restart_base); - RBS rbs(master,so); + RBS rbs(hub,so); while (JobShopSolve* s = rbs.next()) { s->print(std::cout); u = s->cost().val(); diff --git a/examples/photo.cpp b/examples/photo.cpp index ed264158c5..15a19e3dd1 100644 --- a/examples/photo.cpp +++ b/examples/photo.cpp @@ -128,8 +128,8 @@ class Photo : public IntMinimizeScript { break; } } - /// Slave function for restarts - bool slave(const MetaInfo& mi) { + /// 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()); diff --git a/examples/qcp.cpp b/examples/qcp.cpp index 49a75d5f92..b74d144b3f 100644 --- a/examples/qcp.cpp +++ b/examples/qcp.cpp @@ -211,8 +211,8 @@ class QCP : public Script { } } } - /// Slave function for portfolio search - virtual bool slave(const MetaInfo& mi) { + /// Spoke function for portfolio search + virtual bool spoke(const MetaInfo& mi) { if (mi.type() == MetaInfo::PORTFOLIO) { double tbf = opt.tbf(); Rnd r(seeds[mi.asset() % n_seeds]); diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index 1d46712726..78b2039c63 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); - /// Slave function for restarts - virtual bool slave(const MetaInfo& mi); + /// Spoke function for restarts + virtual bool spoke(const MetaInfo& mi); /// \name AST to variable and value conversion //@{ diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index cbe0a360a8..c7cffdb5c7 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -2127,7 +2127,7 @@ namespace Gecode { namespace FlatZinc { } bool - FlatZincSpace::slave(const MetaInfo& mi) { + FlatZincSpace::spoke(const MetaInfo& mi) { if (mi.type() == MetaInfo::RESTART) { if (restart_data.initialized() && restart_data().mark_complete) { // Fail the space diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index 21b8584bfb..e5407336c0 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -902,7 +902,7 @@ namespace Gecode { } bool - Space::master(const MetaInfo& mi) { + Space::hub(const MetaInfo& mi) { switch (mi.type()) { case MetaInfo::RESTART: if (mi.last() != nullptr) @@ -920,7 +920,7 @@ namespace Gecode { } bool - Space::slave(const MetaInfo&) { + Space::spoke(const MetaInfo&) { return true; } diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 00ceb07ec1..73c5b63b68 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1730,8 +1730,8 @@ namespace Gecode { /** * \brief Return no-goods recorded from restart * - * The no-goods are empty if the search on the slave space was - * incomplete, as they only hold in the slave's search space. + * The no-goods are empty if the search on the spoke space was + * incomplete, as they only hold in the spoke's search space. */ const NoGoods& nogoods(void) const; //@} @@ -2192,13 +2192,13 @@ namespace Gecode { GECODE_KERNEL_EXPORT virtual SpaceComparison compare(const Space& other) const; /** - * \brief Master configuration function for meta search engines + * \brief Hub configuration function for meta search engines * * This configuration function is used by both restart and * portfolio meta search engines. * * \li A restart meta search engine calls this function on its - * master space whenever it finds a solution or exploration + * hub space whenever it finds a solution or exploration * restarts. \a mi contains information about the current restart. * * If a solution has been found, then search will continue with @@ -2208,38 +2208,38 @@ namespace Gecode { * The default function posts no-goods obtained from \a mi. * * \li A portfolio meta engine calls this function once on - * the master space. The return value is ignored. + * the hub space. The return value is ignored. * - * The default function does nothing. + * The default function removes all common branchers. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool master(const MetaInfo& mi); + virtual bool hub(const MetaInfo& mi); /** - * \brief Slave configuration function for meta search engines + * \brief Spoke configuration function for meta search engines * * This configuration function is used by both restart and * portfolio meta search engines. * * \li A restart meta search engine calls this function on its - * slave space when search starts and whenever it finds a solution or + * spoke space when search starts and whenever it finds a solution or * exploration restarts. \a mi contains information about the * current restart. * - * If the function returns true, the search on the slave space is + * If the function returns true, the search on the spoke space is * considered complete, i.e., if it fails or exhaustively explores the * entire search space, the meta search engine finishes. If the - * function returns false, the search on the slave space is considered + * function returns false, the search on the spoke space is considered * incomplete, and the meta engine will restart the search regardless - * of whether the search on the slave space finishes or times out. + * of whether the search on the spoke space finishes or times out. * The no-goods recorded by an incomplete search only hold in the - * slave's search space, so the meta engine does not pass them to the - * master configuration function. This also holds for the first + * spoke's search space, so the meta engine does not pass them to the + * hub configuration function. This also holds for the first * search when search starts. * * \li A portfolio meta engine calls this function once on each asset - * (that is, on each slave) and passes the number of the asset, + * (that is, on each spoke) and passes the number of the asset, * starting from zero. * * The default function does nothing and returns true. @@ -2247,7 +2247,7 @@ namespace Gecode { * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool slave(const MetaInfo& mi); + virtual bool spoke(const MetaInfo& mi); /* * Member functions for search engines diff --git a/gecode/search.hh b/gecode/search.hh index f4467897ab..78c5865182 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1456,13 +1456,13 @@ namespace Gecode { * periodically restart the search of engine \a E. * * The class \a T can implement member functions - * \code virtual bool master(const MetaInfo& mi) \endcode + * \code virtual bool hub(const MetaInfo& mi) \endcode * and - * \code virtual bool slave(const MetaInfo& mi) \endcode + * \code virtual bool spoke(const MetaInfo& mi) \endcode * * Whenever exploration restarts or a solution is found, the - * engine executes the functions on the master and slave - * space. For more details, consult "Modeling and Programming + * engine executes the functions on the hub and spoke + * spaces. For more details, consult "Modeling and Programming * with Gecode". * * \ingroup TaskModelSearch @@ -1484,13 +1484,13 @@ namespace Gecode { * periodically restart the search of engine \a E. * * The class \a T can implement member functions - * \code virtual bool master(const MetaInfo& mi) \endcode + * \code virtual bool hub(const MetaInfo& mi) \endcode * and - * \code virtual bool slave(const MetaInfo& mi) \endcode + * \code virtual bool spoke(const MetaInfo& mi) \endcode * * Whenever exploration restarts or a solution is found, the - * engine executes the functions on the master and slave - * space. For more details, consult "Modeling and Programming + * engine executes the functions on the hub and spoke + * spaces. For more details, consult "Modeling and Programming * with Gecode". * * \ingroup TaskModelSearch @@ -1510,22 +1510,22 @@ namespace Gecode { namespace Search { namespace Meta { /// Build a sequential engine template class E> - Engine* sequential(T* master, const Search::Statistics& stat, Options& opt); + Engine* sequential(T* hub, const Search::Statistics& stat, Options& opt); /// Build a sequential engine template class E> - Engine* sequential(T* master, SEBs& sebs, + Engine* sequential(T* hub, SEBs& sebs, const Search::Statistics& stat, Options& opt, bool best); #ifdef GECODE_HAS_THREADS /// Build a parallel engine template class E> - Engine* parallel(T* master, const Search::Statistics& stat, Options& opt); + Engine* parallel(T* hub, const Search::Statistics& stat, Options& opt); /// Build a parallel engine template class E> - Engine* parallel(T* master, SEBs& sebs, + Engine* parallel(T* hub, SEBs& sebs, const Search::Statistics& stat, Options& opt, bool best); #endif @@ -1552,9 +1552,9 @@ namespace Gecode { * each restart of an asset takes the next value of the sequence. * * The class \a T can implement member functions - * \code virtual bool master(const MetaInfo& mi) \endcode + * \code virtual bool hub(const MetaInfo& mi) \endcode * and - * \code virtual bool slave(const MetaInfo& mi) \endcode + * \code virtual bool spoke(const MetaInfo& mi) \endcode * * When the assets are created, these functions are executed. * For more details, consult "Modeling and Programming with Gecode". @@ -1601,9 +1601,9 @@ namespace Gecode { * asset. PBS does not implement worker-allocation policy. * * The class \a T can implement member functions - * \code virtual bool master(const MetaInfo& mi) \endcode + * \code virtual bool hub(const MetaInfo& mi) \endcode * and - * \code virtual bool slave(const MetaInfo& mi) \endcode + * \code virtual bool spoke(const MetaInfo& mi) \endcode * * When the assets are created, these functions are executed. * For more details, consult "Modeling and Programming with Gecode". diff --git a/gecode/search/par/bab.hpp b/gecode/search/par/bab.hpp index 0f658098b1..e048391bf0 100755 --- a/gecode/search/par/bab.hpp +++ b/gecode/search/par/bab.hpp @@ -488,7 +488,7 @@ namespace Gecode { namespace Search { namespace Par { // Wait for reset cycle stopped e_reset_ack_stop.wait(); // A worker can fail after next() returns. Report that failure before - // a restart engine invokes its master callback and resets this engine. + // a restart engine invokes its hub callback and resets this engine. Support::Lock lock(m_search); if (failure != nullptr) std::rethrow_exception(failure); diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index cf73f5c839..7ea7f4b4d6 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -44,10 +44,10 @@ namespace Gecode { namespace Search { namespace Par { - /// Stop object used for controlling slaves in a portfolio + /// Stop object used for controlling spokes in a portfolio class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: - /// The stop object for the slaves + /// The stop object for the spokes Stop* so; /// The stop object for the portfolio (possibly nullptr) Stop* po; @@ -56,7 +56,7 @@ namespace Gecode { namespace Search { namespace Par { /// Whether search must be stopped std::atomic* tostop; public: - /// Initialize with slave stop \a so, portfolio stop \a po, and \a control + /// Initialize with spoke 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); @@ -74,9 +74,9 @@ namespace Gecode { namespace Search { namespace Par { template class PBS; - /// Runnable slave of a portfolio master + /// Runnable spoke in a portfolio template - class GECODE_SEARCH_EXPORT Slave : public Support::Runnable { + class GECODE_SEARCH_EXPORT Spoke : public Support::Runnable { protected: /// Completion event for the current run class Completion : public Support::Terminator { @@ -91,33 +91,33 @@ namespace Gecode { namespace Search { namespace Par { /// Wait for completion and consume the signal void wait(void); } completion; - /// The master engine - PBS* master; - /// The slave engine - Engine* slave; + /// The portfolio engine + PBS* portfolio; + /// The wrapped search engine + Engine* engine; /// Stop object Stop* stop; public: - /// Initialize with master \a m, slave \a s, and its stop object \a so - Slave(PBS* m, Engine* s, Stop* so); - /// Return statistics of slave + /// Initialize with portfolio \a p, engine \a e, and its stop object \a so + Spoke(PBS* p, Engine* e, Stop* so); + /// Return statistics of spoke Statistics statistics(void) const; - /// Check whether slave has been stopped + /// Check whether spoke has been stopped bool stopped(void) const; - /// Check whether slave stopped at a local limit + /// Check whether spoke stopped at a local limit bool limited(void) const; /// Return the completion terminator virtual Support::Terminator* terminator(void) const; - /// Wait for the slave to complete its current run + /// Wait for the spoke to complete its current run void wait(void); - /// Wake a paused slave so that it can observe the portfolio stop + /// Wake a paused spoke so that it can observe the portfolio stop void wake(void); /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run virtual void run(void); - /// Delete slave - virtual ~Slave(void); + /// Delete spoke + virtual ~Spoke(void); }; /// Collect all solutions @@ -131,13 +131,13 @@ namespace Gecode { namespace Search { namespace Par { /// Initialize CollectAll(void); /// Add a solution \a a reported by \a r and always return true - bool add(Space* s, Slave* r); + bool add(Space* s, Spoke* r); /// Dummy function bool constrain(const Space& b); /// Check whether there is any solution left bool empty(void) const; /// Return solution reported by \a r - Space* get(Slave*& r); + Space* get(Spoke*& r); /// Destructor ~CollectAll(void); }; @@ -148,20 +148,20 @@ namespace Gecode { namespace Search { namespace Par { /// Currently best solution Space* b; /// Who has reported the best solution (nullptr if solution has already been reported) - Slave* reporter; + Spoke* reporter; public: /// Whether it collects best solutions static const bool best = true; /// Initialize CollectBest(void); /// Add a solution \a s by \a r and return whether is was better - bool add(Space* s, Slave* r); + bool add(Space* s, Spoke* r); /// Check whether \a b better and update accordingly bool constrain(const Space& b); /// Check whether there is any solution left bool empty(void) const; /// Return solution reported by \a r (only if a better one was found) - Space* get(Slave*& r); + Space* get(Spoke*& r); /// Destructor ~CollectBest(void); }; @@ -169,19 +169,19 @@ namespace Gecode { namespace Search { namespace Par { /// Parallel portfolio engine implementation template class GECODE_SEARCH_EXPORT PBS : public Engine { - friend class Slave; + friend class Spoke; protected: - /// Master statistics + /// Portfolio statistics Statistics stat; - /// Slave engines - Slave** slaves; - /// Number of slave engines - unsigned int n_slaves; - /// Number of active slave engines + /// Spoke engines + Spoke** spokes; + /// Number of spoke engines + unsigned int n_spokes; + /// Number of active spoke engines unsigned int n_active; - /// Whether a slave has been stopped - std::atomic slave_stop; - /// Whether a slave stopped at a local limit + /// Whether a spoke has been stopped + std::atomic spoke_stop; + /// Whether a spoke stopped at a local limit bool incomplete; /// Shared stop flag std::atomic tostop; @@ -189,23 +189,23 @@ namespace Gecode { namespace Search { namespace Par { Collect solutions; /// Mutex for synchronization Support::Mutex m; - /// Number of busy slaves + /// Number of busy spokes unsigned int n_busy; - /// Signal that number of busy slaves becomes zero + /// Signal that number of busy spokes becomes zero Support::Event idle; /// Failure raised while running or updating a portfolio asset std::exception_ptr failure; - /// Process report from slave, return false if solution was ignored - bool report(Slave* slave, Space* s); - /// Process failure from slave + /// Process report from spoke, return false if solution was ignored + bool report(Spoke* spoke, Space* s); + /// Process failure from spoke void fail(void); /** * The key invariant of the engine is as follows: * - n_busy is always zero outside the next() function. * - that entails, that locking is only needed inside next(). - * - the slaves 0..n_active-1 still might not have exhausted their + * - the spokes 0..n_active-1 still might not have exhausted their * search space. - * - the slaves n_active..n_slaves-1 have exhausted their search space. + * - the spokes n_active..n_spokes-1 have exhausted their search space. */ public: /// Initialize diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index c9d97fc779..0ce92dd32e 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -41,8 +41,8 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Slave::Completion::Completion(void) { - // A slave has not been submitted yet. This initial signal lets the + Spoke::Completion::Completion(void) { + // A spoke has not been submitted yet. This initial signal lets the // first submission use the same consume-before-reuse handshake as all // subsequent submissions. done.signal(); @@ -50,13 +50,13 @@ namespace Gecode { namespace Search { namespace Par { template forceinline void - Slave::Completion::terminated(void) { + Spoke::Completion::terminated(void) { done.signal(); } template forceinline void - Slave::Completion::wait(void) { + Spoke::Completion::wait(void) { done.wait(); } @@ -65,7 +65,7 @@ namespace Gecode { namespace Search { namespace Par { CollectAll::CollectAll(void) : solutions(heap) {} forceinline bool - CollectAll::add(Space* s, Slave*) { + CollectAll::add(Space* s, Spoke*) { solutions.push(s); return true; } @@ -79,7 +79,7 @@ namespace Gecode { namespace Search { namespace Par { return solutions.empty(); } forceinline Space* - CollectAll::get(Slave*&) { + CollectAll::get(Spoke*&) { return solutions.pop(); } forceinline @@ -93,7 +93,7 @@ namespace Gecode { namespace Search { namespace Par { CollectBest::CollectBest(void) : b(nullptr), reporter(nullptr) {} forceinline bool - CollectBest::add(Space* s, Slave* r) { + CollectBest::add(Space* s, Spoke* r) { if ((b != nullptr) && !Search::better(*s,*b,"PBS::CollectBest::add")) { delete s; @@ -119,7 +119,7 @@ namespace Gecode { namespace Search { namespace Par { return reporter == nullptr; } forceinline Space* - CollectBest::get(Slave*& r) { + CollectBest::get(Spoke*& r) { assert(!empty()); r = reporter; reporter = nullptr; @@ -144,50 +144,50 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Slave::Slave(PBS* m, Engine* s, Stop* so) - : Support::Runnable(false), master(m), slave(s), stop(so) {} + Spoke::Spoke(PBS* p, Engine* e, Stop* so) + : Support::Runnable(false), portfolio(p), engine(e), stop(so) {} template forceinline Statistics - Slave::statistics(void) const { - return slave->statistics(); + Spoke::statistics(void) const { + return engine->statistics(); } template forceinline bool - Slave::stopped(void) const { - return slave->stopped(); + Spoke::stopped(void) const { + return engine->stopped(); } template forceinline bool - Slave::limited(void) const { + Spoke::limited(void) const { #ifdef GECODE_HAS_EXPERIMENTAL - return slave->limited(); + return engine->limited(); #else return false; #endif } template forceinline Support::Terminator* - Slave::terminator(void) const { + Spoke::terminator(void) const { return const_cast(&completion); } template forceinline void - Slave::wait(void) { + Spoke::wait(void) { completion.wait(); } template forceinline void - Slave::wake(void) { + Spoke::wake(void) { static_cast(stop)->wake(); } template forceinline void - Slave::constrain(const Space& b) { - slave->constrain(b); + Spoke::constrain(const Space& b) { + engine->constrain(b); } template - Slave::~Slave(void) { - delete slave; + Spoke::~Spoke(void) { + delete engine; delete stop; } @@ -197,12 +197,12 @@ namespace Gecode { namespace Search { namespace Par { forceinline PBS::PBS(Engine** engines, Stop** stops, unsigned int n, const Statistics& stat0) - : stat(stat0), slaves(heap.alloc*>(n)), - n_slaves(n), n_active(n), - slave_stop(false), incomplete(false), tostop(false), n_busy(0) { - // Initialize slaves - for (unsigned int i=0U; i(this,engines[i],stops[i]); + : stat(stat0), spokes(heap.alloc*>(n)), + n_spokes(n), n_active(n), + spoke_stop(false), incomplete(false), tostop(false), n_busy(0) { + // Initialize spokes + for (unsigned int i=0U; i(this,engines[i],stops[i]); static_cast(stops[i])->share(&tostop); } } @@ -210,14 +210,14 @@ namespace Gecode { namespace Search { namespace Par { template forceinline bool - PBS::report(Slave* slave, Space* s) { + PBS::report(Spoke* spoke, Space* s) { // If b is false the report should be repeated (solution was worse) bool b = true; bool wake = false; m.acquire(); if (s != nullptr) { try { - b = solutions.add(s,slave); + b = solutions.add(s,spoke); if (b) { tostop.store(true, std::memory_order_release); wake = true; @@ -229,29 +229,29 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } - } else if (slave->stopped() && !slave->limited()) { + } else if (spoke->stopped() && !spoke->limited()) { if (!tostop.load(std::memory_order_acquire)) { - slave_stop.store(true, std::memory_order_release); + spoke_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; } } else { - // The slave is done or stopped at a local limit (then search is incomplete) - if (slave->limited()) + // The spoke is done or stopped at a local limit (then search is incomplete) + if (spoke->limited()) incomplete = true; - // Move slave to inactive + // Move spoke to inactive unsigned int i=0; - while (slaves[i] != slave) + while (spokes[i] != spoke) i++; assert(i < n_active); assert(n_active > 0); - std::swap(slaves[i],slaves[--n_active]); + std::swap(spokes[i],spokes[--n_active]); tostop.store(true, std::memory_order_release); wake = true; } if (wake) for (unsigned int i=0U; iwake(); + spokes[i]->wake(); if (b) { if (--n_busy == 0) idle.signal(); @@ -268,7 +268,7 @@ namespace Gecode { namespace Search { namespace Par { failure = std::current_exception(); tostop.store(true, std::memory_order_release); for (unsigned int i=0U; iwake(); + spokes[i]->wake(); if (--n_busy == 0) idle.signal(); m.release(); @@ -276,14 +276,14 @@ namespace Gecode { namespace Search { namespace Par { template void - Slave::run(void) { + Spoke::run(void) { try { Space* s; do { - s = slave->next(); - } while (!master->report(this,s)); + s = engine->next(); + } while (!portfolio->report(this,s)); } catch (...) { - master->fail(); + portfolio->fail(); } } @@ -297,35 +297,35 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(f); } if (solutions.empty()) - slave_stop.store(false, std::memory_order_release); + spoke_stop.store(false, std::memory_order_release); while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !slave_stop.load(std::memory_order_acquire)) { - // Clear the internal stop used to interrupt sibling slaves + !spoke_stop.load(std::memory_order_acquire)) { + // Clear the internal stop used to interrupt sibling spokes tostop.store(false, std::memory_order_release); - // Invariant: all slaves are idle! + // Invariant: all spokes are idle! assert(n_busy == 0); assert(!tostop.load(std::memory_order_acquire)); - // Run all active slaves + // Run all active spokes n_busy = n_active; for (unsigned int i=0U; iwait(); - Support::Thread::run(slaves[i]); + spokes[i]->wait(); + Support::Thread::run(spokes[i]); } m.release(); - // Wait for all slaves to become idle + // Wait for all spokes to become idle idle.wait(); m.acquire(); } - // Invariant all slaves are idle! + // Invariant all spokes are idle! assert(n_busy == 0); if (solutions.empty() && (n_active == 0) && incomplete) - slave_stop.store(true, std::memory_order_release); + spoke_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. @@ -341,13 +341,13 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.empty()) { s = nullptr; } else { - Slave* r; + Spoke* r; s = solutions.get(r); if (Collect::best) { try { for (unsigned int i=0U; iconstrain(*s); + if (spokes[i] != r) + spokes[i]->constrain(*s); } catch (...) { delete s; failure = std::current_exception(); @@ -365,7 +365,7 @@ namespace Gecode { namespace Search { namespace Par { template bool PBS::stopped(void) const { - return slave_stop.load(std::memory_order_acquire); + return spoke_stop.load(std::memory_order_acquire); } template @@ -373,8 +373,8 @@ namespace Gecode { namespace Search { namespace Par { PBS::statistics(void) const { assert(n_busy == 0); Statistics s(stat); - for (unsigned int i=0U; istatistics(); + for (unsigned int i=0U; istatistics(); return s; } @@ -388,7 +388,7 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.constrain(b)) { // The solution is better for (unsigned int i=0U; iconstrain(b); + spokes[i]->constrain(b); } } catch (...) { failure = std::current_exception(); @@ -398,15 +398,15 @@ namespace Gecode { namespace Search { namespace Par { template PBS::~PBS(void) { - // A report can make n_busy zero before Slave::run and Thread::Run::exec + // A report can make n_busy zero before Spoke::run and Thread::Run::exec // have returned. Wait for the completion handshake before deleting the - // PBS-owned slaves. - for (unsigned int i=0U; iwait(); + // PBS-owned spokes. + for (unsigned int i=0U; iwait(); assert(n_busy == 0); - for (unsigned int i=0U; i*>(slaves,n_slaves); + for (unsigned int i=0U; i*>(spokes,n_spokes); } }}} diff --git a/gecode/search/pbs.cpp b/gecode/search/pbs.cpp index b52ce8e269..517f40c59c 100644 --- a/gecode/search/pbs.cpp +++ b/gecode/search/pbs.cpp @@ -46,12 +46,12 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - pbsengine(Engine** slaves, Stop** stops, unsigned int n_slaves, + pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, const Statistics& stat, const Search::Options& opt, bool best) { if (best) - return new PBS(slaves,stops,n_slaves,stat,opt); + return new PBS(spokes,stops,n_spokes,stat,opt); else - return new PBS(slaves,stops,n_slaves,stat,opt); + return new PBS(spokes,stops,n_spokes,stat,opt); } }}} @@ -73,12 +73,12 @@ namespace Gecode { namespace Search { namespace Par { } Engine* - pbsengine(Engine** slaves, Stop** stops, unsigned int n_slaves, + pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, const Statistics& stat, bool best) { if (best) - return new PBS(slaves,stops,n_slaves,stat); + return new PBS(spokes,stops,n_spokes,stat); else - return new PBS(slaves,stops,n_slaves,stat); + return new PBS(spokes,stops,n_spokes,stat); } }}} diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 720787eac0..59694f30ba 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -40,13 +40,13 @@ namespace Gecode { namespace Search { /// Dispose partially constructed portfolio assets forceinline void - pbscleanup(Engine** slaves, Stop** stops, unsigned int n_slaves, - Space* master) { - for (unsigned int i=0U; i forceinline PbsCutoffs* - make_pbs_cutoffs(const Options& opt, unsigned int n_slaves) { + make_pbs_cutoffs(const Options& opt, unsigned int n_spokes) { if (!PbsOwnsCutoff::value || (opt.cutoff == nullptr) || - (n_slaves < 2U)) + (n_spokes < 2U)) return nullptr; return new PbsCutoffs(opt.cutoff); } @@ -272,7 +272,7 @@ namespace Gecode { namespace Search { namespace Seq { /// Create sequential portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** slaves, Stop** stops, unsigned int n_slaves, + pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, const Statistics& stat, const Search::Options& opt, bool best); }}} @@ -289,7 +289,7 @@ namespace Gecode { namespace Search { namespace Par { /// Create parallel portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** slaves, Stop** stops, unsigned int n_slaves, + pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, const Statistics& stat, bool best); }}} @@ -298,7 +298,7 @@ namespace Gecode { namespace Search { template class E> Engine* - pbsseq(T* master, const Search::Statistics& stat, Options& opt) { + pbsseq(T* hub, const Search::Statistics& stat, Options& opt) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -308,42 +308,42 @@ namespace Gecode { namespace Search { opt.threads = std::max(floor(opt.threads / static_cast(opt.assets)),1.0); - unsigned int n_slaves = opt.assets; - Engine** slaves = r.alloc(n_slaves); - Stop** stops = r.alloc(n_slaves); - for (unsigned int i=0U; i(n_spokes); + Stop** stops = r.alloc(n_spokes); + for (unsigned int i=0U; i >(opt,n_slaves); + Space* unowned_hub = hub; + PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_spokes); try { - for (unsigned int i=0U; i slave((i == n_slaves-1) ? - master : master->clone()); - if (slave.get() == master) - unowned_master = nullptr; - (void) slave->slave(i); + std::unique_ptr spoke((i == n_spokes-1) ? + hub : hub->clone()); + if (spoke.get() == hub) + unowned_hub = nullptr; + (void) spoke->spoke(i); std::unique_ptr cutoff; if (cutoffs != nullptr) { cutoff.reset(new PbsCutoff(cutoffs)); opt.cutoff = cutoff.get(); } - slaves[i] = build(slave.get(),opt); + spokes[i] = build(spoke.get(),opt); // The asset owns its cutoff (void) cutoff.release(); } Engine* e = Seq::pbsengine( - slaves,stops,n_slaves,stat,opt,E::best); + spokes,stops,n_spokes,stat,opt,E::best); release_pbs_cutoffs(cutoffs,true); return e; } catch (...) { - pbscleanup(slaves,stops,n_slaves,unowned_master); + pbscleanup(spokes,stops,n_spokes,unowned_hub); release_pbs_cutoffs(cutoffs,false); throw; } @@ -351,46 +351,46 @@ namespace Gecode { namespace Search { template class E> Engine* - pbsseq(T* master, SEBs& sebs, + pbsseq(T* hub, SEBs& sebs, const Search::Statistics& stat, Options& opt, bool best) { Region r; - int n_slaves = sebs.size(); - Engine** slaves = r.alloc(n_slaves); - Stop** stops = r.alloc(n_slaves); - for (int i=0; i(n_spokes); + Stop** stops = r.alloc(n_spokes); + for (int i=0; i(n_slaves)); + static_cast(n_spokes)); - Space* unowned_master = master; + Space* unowned_hub = hub; bool builders_owned = true; try { - for (int i=0; ioptions().stop,opt.stop); sebs[i]->options().stop = stops[i]; sebs[i]->options().clone = true; - std::unique_ptr slave((i == n_slaves-1) ? - master : master->clone()); - if (slave.get() == master) - unowned_master = nullptr; - (void) slave->slave(static_cast(i)); - slaves[i] = (*sebs[i])(slave.get()); + std::unique_ptr spoke((i == n_spokes-1) ? + hub : hub->clone()); + if (spoke.get() == hub) + unowned_hub = nullptr; + (void) spoke->spoke(static_cast(i)); + spokes[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Seq::pbsengine( - slaves,stops,static_cast(n_slaves),stat,opt,best); + spokes,stops,static_cast(n_spokes),stat,opt,best); } catch (...) { if (builders_owned) pbscleanup(sebs); - pbscleanup(slaves,stops,static_cast(n_slaves), - unowned_master); + pbscleanup(spokes,stops,static_cast(n_spokes), + unowned_hub); throw; } } @@ -399,52 +399,52 @@ namespace Gecode { namespace Search { template class E> Engine* - pbspar(T* master, const Search::Statistics& stat, Options& opt) { + pbspar(T* hub, const Search::Statistics& stat, Options& opt) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; Region r; - // Limit the number of slaves to the number of threads - unsigned int n_slaves = std::min(static_cast(opt.threads), + // Limit the number of spokes to the number of threads + unsigned int n_spokes = std::min(static_cast(opt.threads), opt.assets); - // Redistribute additional threads to slaves - opt.threads = floor(opt.threads / static_cast(n_slaves)); + // Redistribute additional threads to spokes + opt.threads = floor(opt.threads / static_cast(n_spokes)); WrapTraceRecorder::engine(opt.tracer, - SearchTracer::EngineType::PBS, n_slaves); + SearchTracer::EngineType::PBS, n_spokes); - Engine** slaves = r.alloc(n_slaves); - Stop** stops = r.alloc(n_slaves); - for (unsigned int i=0U; i(n_spokes); + Stop** stops = r.alloc(n_spokes); + for (unsigned int i=0U; i >(opt,n_slaves); + Space* unowned_hub = hub; + PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_spokes); try { - for (unsigned int i=0U; i slave((i == n_slaves-1) ? - master : master->clone()); - if (slave.get() == master) - unowned_master = nullptr; - (void) slave->slave(static_cast(i)); + std::unique_ptr spoke((i == n_spokes-1) ? + hub : hub->clone()); + if (spoke.get() == hub) + unowned_hub = nullptr; + (void) spoke->spoke(static_cast(i)); std::unique_ptr cutoff; if (cutoffs != nullptr) { cutoff.reset(new PbsCutoff(cutoffs)); opt.cutoff = cutoff.get(); } - slaves[i] = build(slave.get(),opt); + spokes[i] = build(spoke.get(),opt); // The asset owns its cutoff (void) cutoff.release(); } - Engine* e = Par::pbsengine(slaves,stops,n_slaves,stat,E::best); + Engine* e = Par::pbsengine(spokes,stops,n_spokes,stat,E::best); release_pbs_cutoffs(cutoffs,true); return e; } catch (...) { - pbscleanup(slaves,stops,n_slaves,unowned_master); + pbscleanup(spokes,stops,n_spokes,unowned_hub); release_pbs_cutoffs(cutoffs,false); throw; } @@ -452,50 +452,50 @@ namespace Gecode { namespace Search { template class E> Engine* - pbspar(T* master, SEBs& sebs, + pbspar(T* hub, SEBs& sebs, const Search::Statistics& stat, Options& opt, bool best) { Region r; - // Limit the number of slaves to the number of threads - int n_slaves = std::min(static_cast(opt.threads), + // Limit the number of spokes to the number of threads + int n_spokes = std::min(static_cast(opt.threads), sebs.size()); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, - static_cast(n_slaves)); + static_cast(n_spokes)); - Engine** slaves = r.alloc(n_slaves); - Stop** stops = r.alloc(n_slaves); - for (int i=0; i(n_spokes); + Stop** stops = r.alloc(n_spokes); + for (int i=0; ioptions().stop,opt.stop, sebs[i]->options().worker_control); sebs[i]->options().stop = stops[i]; sebs[i]->options().clone = true; - std::unique_ptr slave((i == n_slaves-1) ? - master : master->clone()); - if (slave.get() == master) - unowned_master = nullptr; - (void) slave->slave(static_cast(i)); - slaves[i] = (*sebs[i])(slave.get()); + std::unique_ptr spoke((i == n_spokes-1) ? + hub : hub->clone()); + if (spoke.get() == hub) + unowned_hub = nullptr; + (void) spoke->spoke(static_cast(i)); + spokes[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Par::pbsengine( - slaves,stops,static_cast(n_slaves),stat,best); + spokes,stops,static_cast(n_spokes),stat,best); } catch (...) { if (builders_owned) pbscleanup(sebs); - pbscleanup(slaves,stops,static_cast(n_slaves), - unowned_master); + pbscleanup(spokes,stops,static_cast(n_spokes), + unowned_hub); throw; } } @@ -532,17 +532,17 @@ namespace Gecode { } // Check whether a clone must be used - T* master = opt.clone ? + T* hub = opt.clone ? dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute master function - (void) master->master(0); + // Always execute hub function + (void) hub->hub(0); - // No need to create a portfolio engine but must run slave function + // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { - std::unique_ptr seed(master); - (void) master->slave(0); + std::unique_ptr seed(hub); + (void) hub->spoke(0); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; e = Search::build(seed.get(),opt); @@ -551,10 +551,10 @@ namespace Gecode { #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(master,stat,opt); + e = Search::pbspar(hub,stat,opt); else #endif - e = Search::pbsseq(master,stat,opt); + e = Search::pbsseq(hub,stat,opt); } template class E> @@ -586,19 +586,19 @@ namespace Gecode { } // Check whether a clone must be used - T* master = opt.clone ? + T* hub = opt.clone ? dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute master function - (void) master->master(0); + // Always execute hub function + (void) hub->hub(0); #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(master,sebs,stat,opt,best); + e = Search::pbspar(hub,sebs,stat,opt,best); else #endif - e = Search::pbsseq(master,sebs,stat,opt,best); + e = Search::pbsseq(hub,sebs,stat,opt,best); } template class E> diff --git a/gecode/search/rbs.cpp b/gecode/search/rbs.cpp index 2069e577d0..3a09b23969 100644 --- a/gecode/search/rbs.cpp +++ b/gecode/search/rbs.cpp @@ -41,16 +41,16 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - rbsengine(Space* master, Stop* stop, Engine* slave, + rbsengine(Space* hub, Stop* stop, Engine* spoke, const Search::Statistics& stat, const Options& opt, bool best) { - return rbsengine(master,stop,slave,stat,opt,best,true); + return rbsengine(hub,stop,spoke,stat,opt,best,true); } Engine* - rbsengine(Space* master, Stop* stop, Engine* slave, + rbsengine(Space* hub, Stop* stop, Engine* spoke, const Search::Statistics& stat, const Options& opt, bool best, bool complete) { - return new RBS(master,static_cast(stop), slave, + return new RBS(hub,static_cast(stop), spoke, stat,opt,best,complete); } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index a992a3feb7..320ea723c6 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -43,21 +43,21 @@ namespace Gecode { namespace Search { namespace Seq { GECODE_SEARCH_EXPORT Stop* rbsstop(Stop* so); - /// Create restart engine whose first slave search yields valid no-goods + /// Create restart engine whose first spoke search yields valid no-goods GECODE_SEARCH_EXPORT Engine* - rbsengine(Space* master, Stop* stop, Engine* slave, + rbsengine(Space* hub, Stop* stop, Engine* spoke, const Search::Statistics& stat, const Options& opt, bool best); /** * \brief Create restart engine * - * The value \a complete is the result of the slave configuration of the - * space explored by the first engine \a slave. It only determines whether - * the no-goods of that search hold in the master. + * The value \a complete is the result of the spoke configuration of the + * space explored by the first engine \a spoke. It only determines whether + * the no-goods of that search hold in the hub. */ GECODE_SEARCH_EXPORT Engine* - rbsengine(Space* master, Stop* stop, Engine* slave, + rbsengine(Space* hub, Stop* stop, Engine* spoke, const Search::Statistics& stat, const Options& opt, bool best, bool complete); @@ -112,15 +112,15 @@ namespace Gecode { // The engine owns the cutoff, but a dead engine does not take it delete m_opt.cutoff; } else { - std::unique_ptr master(m_opt.clone ? s->clone() : s); - std::unique_ptr slave(master->clone()); + 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 = slave->slave(mi); + bool complete = spoke->spoke(mi); std::unique_ptr leaf( - Search::build(slave.get(),e_opt)); - e = Search::Seq::rbsengine(master.get(),stop.get(),leaf.get(), + Search::build(spoke.get(),e_opt)); + e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), stat,m_opt,E::best,complete); - master.release(); + hub.release(); stop.release(); leaf.release(); } diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index e755548421..7d67d3e9b4 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -47,17 +47,17 @@ namespace Gecode { namespace Search { namespace Seq { unsigned long long int l; }; - /// Stop object used for controlling slaves in a portfolio + /// Stop object used for controlling spokes in a portfolio class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: - /// The stop object for the slaves + /// The stop object for the spokes Stop* so; /// The stop object for the portfolio (possibly nullptr) Stop* po; /// Pointer to shared stop information SharedStopInfo* ssi; public: - /// Initialize with slave stop \a so and portfolio stop \a po + /// Initialize with spoke stop \a so and portfolio stop \a po PortfolioStop(Stop* so, Stop* po=nullptr); /// Initialize shared stop information void share(SharedStopInfo* ssi); @@ -65,61 +65,61 @@ namespace Gecode { namespace Search { namespace Seq { virtual bool stop(const Statistics& s, const Options& o); }; - /// Runnable slave of a portfolio master - class Slave { + /// Spoke engine in a sequential portfolio + class Spoke { protected: - /// The slave engine - Engine* slave; + /// The wrapped search engine + Engine* engine; /// Stop object Stop* stop; public: /// Default constructor - Slave(void); + Spoke(void); /// Copy constructor - Slave(const Slave& s) = default; + Spoke(const Spoke& s) = default; /// Assignment operator - Slave& operator =(const Slave& s) = default; - /// Initialize with slave \a s and its stop object \a so + Spoke& operator =(const Spoke& s) = default; + /// Initialize with engine \a s and its stop object \a so void init(Engine* s, Stop* so); /// Return next solution Space* next(void); - /// Return statistics of slave + /// Return statistics of spoke Statistics statistics(void) const; - /// Check whether slave has been stopped + /// Check whether spoke has been stopped bool stopped(void) const; - /// Check whether slave stopped at a local limit + /// Check whether spoke stopped at a local limit bool limited(void) const; /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run void run(void); - /// Delete slave - ~Slave(void); + /// Delete spoke + ~Spoke(void); }; /// Sequential portfolio engine implementation template class GECODE_SEARCH_EXPORT PBS : public Engine { protected: - /// Master statistics + /// Initial statistics Statistics stat; - /// Shared slave information + /// Shared spoke information SharedStopInfo ssi; /// Size of a slice unsigned int slice; - /// Slaves - Slave* slaves; - /// Number of slave engines - unsigned int n_slaves; - /// Current slave to run + /// Spokes + Spoke* spokes; + /// Number of spoke engines + unsigned int n_spokes; + /// Current spoke to run unsigned int cur; - /// Whether a slave has been stopped - bool slave_stop; - /// Whether a slave stopped at a local limit + /// Whether a spoke has been stopped + bool spoke_stop; + /// Whether a spoke stopped at a local limit bool incomplete; public: /// Initialize - PBS(Engine** slaves, Stop** stops, unsigned int n, + PBS(Engine** spokes, Stop** stops, 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); diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index e126eb2577..47319b2301 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -46,39 +46,39 @@ namespace Gecode { namespace Search { namespace Seq { forceinline - Slave::Slave(void) - : slave(nullptr), stop(nullptr) {} + Spoke::Spoke(void) + : engine(nullptr), stop(nullptr) {} forceinline void - Slave::init(Engine* e, Stop* s) { - slave = e; stop = s; + Spoke::init(Engine* e, Stop* s) { + engine = e; stop = s; } forceinline Space* - Slave::next(void) { - return slave->next(); + Spoke::next(void) { + return engine->next(); } forceinline Statistics - Slave::statistics(void) const { - return slave->statistics(); + Spoke::statistics(void) const { + return engine->statistics(); } forceinline bool - Slave::stopped(void) const { - return slave->stopped(); + Spoke::stopped(void) const { + return engine->stopped(); } forceinline bool - Slave::limited(void) const { + Spoke::limited(void) const { #ifdef GECODE_HAS_EXPERIMENTAL - return slave->limited(); + return engine->limited(); #else return false; #endif } forceinline void - Slave::constrain(const Space& b) { - slave->constrain(b); + Spoke::constrain(const Space& b) { + engine->constrain(b); } forceinline - Slave::~Slave(void) { - delete slave; + Spoke::~Spoke(void) { + delete engine; delete stop; } @@ -89,13 +89,13 @@ namespace Gecode { namespace Search { namespace Seq { const Statistics& stat0, const Search::Options& opt) : stat(stat0), slice(opt.slice), - slaves(heap.alloc(n)), n_slaves(n), cur(0), - slave_stop(false), incomplete(false) { + spokes(heap.alloc(n)), n_spokes(n), cur(0), + spoke_stop(false), incomplete(false) { ssi.done = false; ssi.l = opt.slice; for (unsigned int i=0U; i(s[i])); + spokes[i].init(e[i],static_cast(s[i])); static_cast(s[i])->share(&ssi); } } @@ -103,18 +103,18 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { - slave_stop = false; + spoke_stop = false; unsigned int n_exhausted = 0; - while (n_slaves > 0) { + while (n_spokes > 0) { ssi.done = false; - if (Space* s = slaves[cur].next()) { - // Constrain other slaves + if (Space* s = spokes[cur].next()) { + // Constrain other spokes if (best) { try { for (unsigned int i=0U; i bool PBS::stopped(void) const { - return slave_stop; + return spoke_stop; } template Statistics PBS::statistics(void) const { Statistics s(stat); - for (unsigned int i=0U; i::constrain(const Space& b) { if (!best) throw NoBest("PBS::constrain"); - for (unsigned int i=0U; i PBS::~PBS(void) { - for (unsigned int i=0U; inogoods(); @@ -78,30 +78,30 @@ namespace Gecode { namespace Search { namespace Seq { Space* RBS::next(void) { - // A failed master proves that no further solution exists - if (master == nullptr) + // A failed hub proves that no further solution exists + if (hub == nullptr) return nullptr; m_stopped = false; if (restart) { restart = false; sslr++; - NoGoods& ng = master_nogoods(); + NoGoods& ng = hub_nogoods(); MetaInfo mi(stop->restarts(),MetaInfo::RR_SOL,sslr,e->statistics().fail,last,ng); - bool r = master->master(mi); + bool r = hub->hub(mi); stop->nogood(ng.ng()); - if (stop->status(master) == SS_FAILED) { + if (stop->status(hub) == SS_FAILED) { stop->update(e->statistics()); - delete master; - master = nullptr; + delete hub; + hub = nullptr; e->reset(nullptr); return nullptr; } else if (r) { stop->update(e->statistics()); - Space* slave = master; - master = master->clone(); - complete = slave->slave(mi); + Space* spoke = hub; + hub = hub->clone(); + complete = spoke->spoke(mi); nogoods_valid = complete; - e->reset(slave); + e->reset(spoke); sslr = 0; stop->restart(); } @@ -121,7 +121,7 @@ namespace Gecode { namespace Search { namespace Seq { if (!complete && !e->stopped()) { /* * The engine might not have checked its stop object, for example - * when the slave failed at the root or a parallel engine had no + * 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)) { @@ -131,24 +131,24 @@ namespace Gecode { namespace Search { namespace Seq { stop->restart(); } sslr = 0; - NoGoods& ng = master_nogoods(); + NoGoods& ng = hub_nogoods(); MetaInfo mi(stop->restarts(),e->stopped() ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); - (void) master->master(mi); + (void) hub->hub(mi); stop->nogood(ng.ng()); unsigned long long int nl = ++(*co); stop->limit(e->statistics(),nl); - if (stop->status(master) == SS_FAILED) { + if (stop->status(hub) == SS_FAILED) { // The statistics of the engine have been added by limit() - delete master; - master = nullptr; + delete hub; + hub = nullptr; e->reset(nullptr); return nullptr; } - Space* slave = master; - master = master->clone(); - complete = slave->slave(mi); + Space* spoke = hub; + hub = hub->clone(); + complete = spoke->spoke(mi); nogoods_valid = complete; - e->reset(slave); + e->reset(spoke); } else { return nullptr; } @@ -166,13 +166,13 @@ namespace Gecode { namespace Search { namespace Seq { RBS::constrain(const Space& b) { if (!best) throw NoBest("RBS::constrain"); - if (master == nullptr) + if (hub == nullptr) return; if ((last != nullptr) && !Search::better(b,*last,"RBS::constrain")) return; delete last; last = b.clone(); - master->constrain(b); + hub->constrain(b); e->constrain(b); } @@ -185,15 +185,15 @@ namespace Gecode { namespace Search { namespace Seq { * invocation of next will do so and no restart will be * missed. * - * The engine may still report a stop when the master failed during a - * restart after a limit. A failed master is a proof, not a stop. + * 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. */ - return (master != nullptr) && (m_stopped || e->stopped()); + return (hub != nullptr) && (m_stopped || e->stopped()); } RBS::~RBS(void) { delete e; - delete master; + delete hub; delete last; delete co; delete stop; diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 10627f45b1..2c57744a59 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -72,7 +72,7 @@ namespace Gecode { namespace Search { namespace Seq { void restart(void); /// Add no-goods to meta statistics void nogood(unsigned long int n); - /// Test master status with meta statistics + /// Test hub status with meta statistics SpaceStatus status(Space* s); /// Set current limit for the engine to \a l fails void limit(const Statistics& s, unsigned long long int l); @@ -89,8 +89,8 @@ namespace Gecode { namespace Search { namespace Seq { protected: /// The actual engine Engine* e; - /// The master space to restart from - Space* master; + /// The hub space to restart from + Space* hub; /// The last solution space (possibly nullptr) Space* last; /// The cutoff object @@ -103,7 +103,7 @@ namespace Gecode { namespace Search { namespace Seq { unsigned long int sslr; /// Whether search for the next solution will be complete bool complete; - /// Whether the no-goods of the current slave search hold in the master + /// 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; @@ -111,13 +111,13 @@ namespace Gecode { namespace Search { namespace Seq { bool best; /// Whether the stop object for the meta engine stopped a restart bool m_stopped; - /// Return the no-goods of the last slave search, valid in the master - NoGoods& master_nogoods(void); + /// Return the no-goods of the last spoke search, valid in the hub + NoGoods& hub_nogoods(void); public: /** * \brief Constructor * - * The value \a complete is the result of the slave configuration of the + * 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. */ diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index ff022f47de..a4bacb56e5 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -97,7 +97,7 @@ namespace Gecode { namespace Search { namespace Seq { RBS::RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& opt, bool best0, bool complete0) - : e(e0), master(s), last(nullptr), co(opt.cutoff), stop(stop0), + : 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) { diff --git a/test/search.cpp b/test/search.cpp index fea6cf8d8c..7fa058331f 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -150,7 +150,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 master(const MetaInfo&) override { return true; } + bool hub(const MetaInfo&) override { return true; } const Node& node(void) const { return (*graph)[vertex]; } void constrain(const Space& s) override { ceiling = static_cast(s).node().cost; @@ -403,8 +403,8 @@ namespace Test { virtual int solutions(void) const = 0; /// Verify that this is best solution virtual bool best(void) const = 0; - /// Master configuration function that does not restart - virtual bool master(const MetaInfo& mi) { + /// 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()); @@ -649,12 +649,12 @@ namespace Test { return "Sol"; } /// Rule out that solution is found more than once during restarts - virtual bool master(const MetaInfo& mi) { + 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::master(mi); + return Space::hub(mi); if (mi.last() != nullptr) { const HasSolutions* s = static_cast(mi.last()); @@ -1255,10 +1255,10 @@ namespace Test { } virtual Space* copy(void) { return new ParallelObjective(*this); } virtual IntVar cost(void) const { return x; } - virtual bool master(const MetaInfo& mi) { + virtual bool hub(const MetaInfo& mi) { if (mi.type() == MetaInfo::PORTFOLIO) return false; - return Space::master(mi); + return Space::hub(mi); } }; @@ -1298,10 +1298,10 @@ namespace Test { throw ComparisonError(); return SpaceComparison::Incomparable; } - virtual bool master(const MetaInfo& mi) { + virtual bool hub(const MetaInfo& mi) { if (mi.type() == MetaInfo::PORTFOLIO) return false; - return Space::master(mi); + return Space::hub(mi); } }; @@ -2142,26 +2142,26 @@ namespace Test { } }; - /// Space whose first slave search is restricted to x2, x3 in {0,1} - class RestrictedFirstSlave : public Gecode::IntMinimizeSpace { + /// Space whose first spoke search is restricted to x2, x3 in {0,1} + class RestrictedFirstSpoke : public Gecode::IntMinimizeSpace { public: /// Distinct variables, the cost is x0 Gecode::IntVarArray x; - RestrictedFirstSlave(void) : x(*this,4,0,3) { + RestrictedFirstSpoke(void) : x(*this,4,0,3) { Gecode::distinct(*this,x); Gecode::branch(*this,x,Gecode::INT_VAR_NONE(),Gecode::INT_VAL_MIN()); } - RestrictedFirstSlave(RestrictedFirstSlave& s) + RestrictedFirstSpoke(RestrictedFirstSpoke& s) : Gecode::IntMinimizeSpace(s) { x.update(*this,s.x); } Gecode::Space* copy(void) override { - return new RestrictedFirstSlave(*this); + return new RestrictedFirstSpoke(*this); } Gecode::IntVar cost(void) const override { return x[0]; } - bool slave(const Gecode::MetaInfo& mi) override { + bool spoke(const Gecode::MetaInfo& mi) override { if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.reason() == Gecode::MetaInfo::RR_INIT)) { Gecode::dom(*this,x[2],0,1); @@ -2172,20 +2172,20 @@ namespace Test { } }; - /// No-goods from an incomplete slave search are not posted in the master + /// No-goods from an incomplete spoke search are not posted in the hub class RBSIncompleteNoGoods : public Base { public: RBSIncompleteNoGoods(void) : Base("Search::RBS::IncompleteNoGoods") {} bool run(void) override { - RestrictedFirstSlave* m = new RestrictedFirstSlave; + RestrictedFirstSpoke* m = new RestrictedFirstSpoke; Gecode::Search::Options o; o.nogoods_limit = 128U; o.cutoff = Gecode::Search::Cutoff::constant(100); - Gecode::RBS rbs(m,o); + Gecode::RBS rbs(m,o); delete m; // The restricted search finds x0 = 2 and rules out x0 in {0,1} int best = -1; - while (RestrictedFirstSlave* s = rbs.next()) { + while (RestrictedFirstSpoke* s = rbs.next()) { best = s->x[0].val(); delete s; } @@ -2215,23 +2215,23 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool master(const Gecode::MetaInfo& mi) override { + bool hub(const Gecode::MetaInfo& mi) override { // Keep the branchers for the assets of a portfolio if (mi.type() == Gecode::MetaInfo::PORTFOLIO) return true; - return Gecode::IntMinimizeSpace::master(mi); + return Gecode::IntMinimizeSpace::hub(mi); } }; - /// Space without solutions whose master fails at a restart after a limit - class FailingMaster : public NoSolution { + /// Space without solutions whose hub fails at a restart after a limit + class FailingHub : public NoSolution { public: - FailingMaster(void) = default; - FailingMaster(FailingMaster& s) : NoSolution(s) {} + FailingHub(void) = default; + FailingHub(FailingHub& s) : NoSolution(s) {} Gecode::Space* copy(void) override { - return new FailingMaster(*this); + return new FailingHub(*this); } - bool master(const Gecode::MetaInfo& mi) override { + bool hub(const Gecode::MetaInfo& mi) override { if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.reason() == Gecode::MetaInfo::RR_LIM)) fail(); @@ -2239,24 +2239,24 @@ namespace Test { } }; - /// A master failing at a restart after a limit proves exhaustion - class RBSFailedMaster : public Base { + /// A hub failing at a restart after a limit proves exhaustion + class RBSFailedHub : public Base { public: - RBSFailedMaster(void) : Base("Search::RBS::FailedMaster") {} + RBSFailedHub(void) : Base("Search::RBS::FailedHub") {} bool run(void) override { for (unsigned int t : {1U,2U}) { - FailingMaster* m = new FailingMaster; + FailingHub* m = new FailingHub; Gecode::Search::Options o; o.threads = t; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS rbs(m,o); + Gecode::RBS rbs(m,o); delete m; - if (FailingMaster* s = rbs.next()) { + if (FailingHub* s = rbs.next()) { delete s; return false; } Gecode::Search::Statistics s = rbs.statistics(); - // The failures of the last slave search are counted once + // The failures of the last spoke search are counted once if (rbs.stopped() || (s.restart != 1U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; @@ -2269,17 +2269,17 @@ namespace Test { } }; - RBSFailedMaster rbs_failed_master; + RBSFailedHub rbs_failed_hub; - /// Space without solutions whose restricted slaves fail at the root - class FailingSlave : public NoSolution { + /// Space without solutions whose restricted spokes fail at the root + class FailingSpoke : public NoSolution { public: - FailingSlave(void) = default; - FailingSlave(FailingSlave& s) : NoSolution(s) {} + FailingSpoke(void) = default; + FailingSpoke(FailingSpoke& s) : NoSolution(s) {} Gecode::Space* copy(void) override { - return new FailingSlave(*this); + return new FailingSpoke(*this); } - bool slave(const Gecode::MetaInfo& mi) override { + bool spoke(const Gecode::MetaInfo& mi) override { if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.restart() > 0)) { fail(); return false; @@ -2299,19 +2299,19 @@ namespace Test { } }; - /// Slave searches failing at the root count as failures + /// Spoke searches failing at the root count as failures class RBSRootFailure : public Base { template class Engine> static bool test(unsigned int threads) { - FailingSlave* m = new FailingSlave; + FailingSpoke* m = new FailingSpoke; FiveFailures f; Gecode::Search::Options o; o.threads = threads; o.stop = &f; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS rbs(m,o); + Gecode::RBS rbs(m,o); delete m; - if (FailingSlave* s = rbs.next()) { + if (FailingSpoke* s = rbs.next()) { delete s; return false; } @@ -2329,15 +2329,15 @@ namespace Test { RBSRootFailure rbs_root_failure; - /// Space with solutions whose first, incomplete slave fails at the root - class FailingFirstSlave : public RestrictedFirstSlave { + /// Space with solutions whose first, incomplete spoke fails at the root + class FailingFirstSpoke : public RestrictedFirstSpoke { public: - FailingFirstSlave(void) = default; - FailingFirstSlave(FailingFirstSlave& s) : RestrictedFirstSlave(s) {} + FailingFirstSpoke(void) = default; + FailingFirstSpoke(FailingFirstSpoke& s) : RestrictedFirstSpoke(s) {} Gecode::Space* copy(void) override { - return new FailingFirstSlave(*this); + return new FailingFirstSpoke(*this); } - bool slave(const Gecode::MetaInfo& mi) override { + bool spoke(const Gecode::MetaInfo& mi) override { if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.reason() == Gecode::MetaInfo::RR_INIT)) { fail(); @@ -2347,24 +2347,24 @@ namespace Test { } }; - /// A failed first slave search that is incomplete is not a proof - class RBSFailedFirstSlave : public Base { + /// A failed first spoke search that is incomplete is not a proof + class RBSFailedFirstSpoke : public Base { template class Engine> static bool test(unsigned int threads) { - FailingFirstSlave* m = new FailingFirstSlave; + FailingFirstSpoke* m = new FailingFirstSpoke; Gecode::Search::Options o; o.threads = threads; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS rbs(m,o); + Gecode::RBS rbs(m,o); delete m; - FailingFirstSlave* s = rbs.next(); + FailingFirstSpoke* s = rbs.next(); if (s == nullptr) return false; delete s; return rbs.statistics().restart >= 1U; } public: - RBSFailedFirstSlave(void) : Base("Search::RBS::FailedFirstSlave") {} + RBSFailedFirstSpoke(void) : Base("Search::RBS::FailedFirstSpoke") {} bool run(void) override { return test(1U) && test(2U) && test(1U) && test(2U) && @@ -2372,7 +2372,7 @@ namespace Test { } }; - RBSFailedFirstSlave rbs_failed_first_slave; + RBSFailedFirstSpoke rbs_failed_first_spoke; /// Stop after a number of failures, or after many checks as a safeguard class FailureLimit : public Gecode::Search::Stop { @@ -2525,9 +2525,9 @@ namespace Test { private: /// Whether best solution search is used bool best; - /// Number of master threads + /// Number of portfolio threads unsigned int mt; - /// Number of slave threads + /// Number of spoke threads unsigned int st; public: /// Initialize test @@ -2674,7 +2674,7 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingAsset(*this); } - bool slave(const Gecode::MetaInfo& mi) override { + bool spoke(const Gecode::MetaInfo& mi) override { if ((mi.type() == Gecode::MetaInfo::PORTFOLIO) && (mi.asset() == 0U)) fail(); return true; From cf48e228b4b74d65a093ac30008a5524b367243f Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 17:29:48 +0100 Subject: [PATCH 02/14] Test Hub and Spoke hook dispatch The MetaDispatch tests check which hook RBS and PBS call, how often, and for which restart reason or asset, with each hook overridden alone and together. They also check that RBS honours the hub() restart decision and the spoke() completeness result, that no-goods reach the hub, that stopped engines delete every clone, and that BAB incumbents reach the hub and spoke spaces through RBS, PBS, and PBS over RBS. The Sol model gains a spoke() override. --- test/search.cpp | 527 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 527 insertions(+) diff --git a/test/search.cpp b/test/search.cpp index 7fa058331f..61e7ecd811 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -672,6 +672,512 @@ namespace Test { } return false; } + /// Use the default completeness contract for each derived exploration + bool + spoke(const MetaInfo&) override { + return true; + } + }; + + /// Return a bit for restart reason \a r + static unsigned int + reason_bit(MetaInfo::RestartReason r) { + return 1U << static_cast(r); + } + + /// 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 assets{0}; + std::atomic live_spaces{0}; + std::atomic copies{0}; + std::atomic constrain_calls{0}; + std::atomic constrain_hub_calls{0}; + std::atomic constrain_spoke_calls{0}; + std::atomic constrain_asset_mask{0}; + 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; + bool fail_solution_spoke = false; + bool nogood_model = false; + }; + + /// Common implementation for meta-search dispatch test spaces + class MetaDispatchSpace : public Space { + protected: + /// RBS role of a space + enum class RestartRole { HUB, SPOKE }; + /// Variable used to provide two solutions + IntVar x; + /// Optional queens model used to force restart no-good extraction + IntVarArray q; + /// Shared hook observations and configuration + MetaDispatchState* state; + /// RBS role retained across cloning + RestartRole restart_role; + /// PBS asset identity, or -1 before portfolio dispatch + int portfolio_asset; + + /// Record and implement a Hub callback + bool + observe_hub(const MetaInfo& mi) { + state->hub_calls.fetch_add(1, std::memory_order_relaxed); + if (mi.type() == MetaInfo::PORTFOLIO) + // PBS must ignore the callback result. + return false; + 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->nogood_handoffs.fetch_add(1, std::memory_order_relaxed); + return (mi.reason() == MetaInfo::RR_SOL) ? state->restart_after_solution : default_result; + } + /// Record and implement a Spoke callback + bool + observe_spoke(const MetaInfo& mi) { + 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); + // PBS must ignore the callback result. + return false; + } + state->spoke_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); + restart_role = RestartRole::SPOKE; + if ((mi.reason() == MetaInfo::RR_SOL) && state->fail_solution_spoke) + fail(); + return (mi.reason() == MetaInfo::RR_SOL) ? state->solution_spoke_complete : true; + } + + public: + /// Initialize with shared observations \a s + MetaDispatchSpace(MetaDispatchState& s) + : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), state(&s), restart_role(RestartRole::HUB), + portfolio_asset(-1) { + state->live_spaces.fetch_add(1, std::memory_order_relaxed); + if (state->nogood_model) { + distinct(*this, IntArgs::create(q.size(), 0, 1), q, IPL_VAL); + distinct(*this, IntArgs::create(q.size(), 0, -1), q, IPL_VAL); + distinct(*this, q, IPL_VAL); + Gecode::branch(*this, q, INT_VAR_NONE(), INT_VAL_MIN()); + } + Gecode::branch(*this, x, INT_VAL_MIN()); + } + /// Clone \a s + MetaDispatchSpace(MetaDispatchSpace& s) + : Space(s), state(s.state), restart_role(s.restart_role), portfolio_asset(s.portfolio_asset) { + state->live_spaces.fetch_add(1, std::memory_order_relaxed); + state->copies.fetch_add(1, std::memory_order_relaxed); + x.update(*this, s.x); + q.update(*this, s.q); + } + /// Record destruction for clone-ownership checks + ~MetaDispatchSpace(void) override { + state->live_spaces.fetch_sub(1, std::memory_order_relaxed); + } + /// Require a larger value than solution \a s + void + constrain(const Space& s) override { + state->constrain_calls.fetch_add(1, std::memory_order_relaxed); + if (restart_role == RestartRole::HUB) + state->constrain_hub_calls.fetch_add(1, std::memory_order_relaxed); + else + state->constrain_spoke_calls.fetch_add(1, std::memory_order_relaxed); + if (portfolio_asset >= 0) { + const unsigned int asset = 1U << static_cast(portfolio_asset); + state->constrain_asset_mask.fetch_or(asset, std::memory_order_relaxed); + if (restart_role == RestartRole::HUB) + state->constrain_hub_asset_mask.fetch_or(asset, std::memory_order_relaxed); + else + state->constrain_spoke_asset_mask.fetch_or(asset, std::memory_order_relaxed); + } + rel(*this, x, IRT_GR, static_cast(s).x.val()); + } + /// Compare with solution \a s, larger values are better + SpaceComparison + compare(const Space& s) const override { + return compare_int(x.val(), static_cast(s).x.val(), Sense::Maximize); + } + /// Return the solution value + int + value(void) const { + return x.val(); + } + }; + + /// Dispatch test space overriding only Hub + class HubDispatchSpace : public MetaDispatchSpace { + public: + /// Initialize with shared observations \a s + HubDispatchSpace(MetaDispatchState& s) : MetaDispatchSpace(s) {} + /// Clone \a s + HubDispatchSpace(HubDispatchSpace& s) : MetaDispatchSpace(s) {} + /// Copy during cloning + Space* + copy(void) override { + return new HubDispatchSpace(*this); + } + /// Observe Hub dispatch + bool + hub(const MetaInfo& mi) override { + return observe_hub(mi); + } + }; + + /// Dispatch test space overriding only Spoke + class SpokeDispatchSpace : public MetaDispatchSpace { + public: + /// Initialize with shared observations \a s + SpokeDispatchSpace(MetaDispatchState& s) : MetaDispatchSpace(s) {} + /// Clone \a s + SpokeDispatchSpace(SpokeDispatchSpace& s) : MetaDispatchSpace(s) {} + /// Copy during cloning + Space* + copy(void) override { + return new SpokeDispatchSpace(*this); + } + /// Observe Spoke dispatch + bool + spoke(const MetaInfo& mi) override { + return observe_spoke(mi); + } + }; + + /// Dispatch test space overriding both Hub and Spoke + class HubSpokeDispatchSpace : public MetaDispatchSpace { + public: + /// Initialize with shared observations \a s + HubSpokeDispatchSpace(MetaDispatchState& s) : MetaDispatchSpace(s) {} + /// Clone \a s + HubSpokeDispatchSpace(HubSpokeDispatchSpace& s) : MetaDispatchSpace(s) {} + /// Copy during cloning + Space* + copy(void) override { + return new HubSpokeDispatchSpace(*this); + } + /// Observe Hub dispatch + bool + hub(const MetaInfo& mi) override { + return observe_hub(mi); + } + /// Observe Spoke dispatch + bool + spoke(const MetaInfo& mi) override { + return observe_spoke(mi); + } + }; + + /// Hub and Spoke hook dispatch through RBS and PBS + class MetaDispatch : public Base { + public: + /// Dispatch scenario + enum class Scenario { + RBS_HUB_ONLY, + RBS_SPOKE_ONLY, + RBS_HUB_CONTINUE, + RBS_HUB_RESTART, + RBS_SPOKE_COMPLETE, + RBS_SPOKE_INCOMPLETE, + PBS_HUB_ONLY, + PBS_SPOKE_ONLY, + PBS_SINGLE, + PBS_SEQUENTIAL_HUB_ONLY, + PBS_SEQUENTIAL_SPOKE_ONLY, + PBS_SEQUENTIAL, + PBS_PARALLEL_HUB_ONLY, + PBS_PARALLEL_SPOKE_ONLY, + PBS_PARALLEL, + RBS_NOGOODS_RESET_OWNERSHIP, + META_STOP_OWNERSHIP, + BAB_INCUMBENT + }; + + protected: + /// Scenario under test + Scenario scenario; + + /// Return whether \a counter holds \a expected + static bool + holds(const std::atomic& counter, unsigned int expected) { + return counter.load(std::memory_order_relaxed) == expected; + } + /// Check independent callback dispatch for one RBS model + template + static bool + rbs_dispatch(unsigned int hub_calls, unsigned int spoke_calls) { + MetaDispatchState state; + Model* m = new Model(state); + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(100); + Gecode::RBS search(m, o); + delete m; + + Model* first = search.next(); + Model* second = search.next(); + bool ok = (first != nullptr) && (second != nullptr) && holds(state.hub_calls, hub_calls) && + holds(state.spoke_calls, spoke_calls); + delete first; + delete second; + return ok; + } + /// Run one RBS dispatch scenario + static bool + rbs(bool restart_after_solution, bool fail_solution_spoke, bool solution_spoke_complete) { + MetaDispatchState state; + state.restart_after_solution = restart_after_solution; + state.fail_solution_spoke = fail_solution_spoke; + state.solution_spoke_complete = solution_spoke_complete; + + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(100); + Gecode::RBS search(m, o); + delete m; + + HubSpokeDispatchSpace* first = search.next(); + bool ok = first != nullptr; + delete first; + + HubSpokeDispatchSpace* second = search.next(); + if (!fail_solution_spoke) { + 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)); + } 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)); + } + delete second; + return ok; + } + /// Run one PBS dispatch scenario + template + static bool + pbs(unsigned int assets, double threads, unsigned int hub_calls, unsigned int spoke_calls, + unsigned int asset_mask) { + MetaDispatchState state; + Model* m = new Model(state); + Gecode::Search::Options o; + o.assets = assets; + o.threads = threads; + Gecode::PBS search(m, o); + delete m; + + Model* solution = search.next(); + bool ok = (solution != nullptr) && holds(state.hub_calls, hub_calls) && + holds(state.spoke_calls, spoke_calls) && holds(state.assets, asset_mask); + delete solution; + return ok; + } + /// Exercise RBS no-good posting, reset, and clone ownership + static bool + rbs_nogoods_reset_ownership(void) { + MetaDispatchState state; + state.nogood_model = true; + bool ok = true; + { + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); + Gecode::Search::Options o; + o.threads = 1; + o.nogoods_limit = 16; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS search(m, o); + delete m; + + unsigned int solutions = 0; + while (HubSpokeDispatchSpace* solution = search.next()) { + solutions++; + delete solution; + } + ok = (solutions == 2U) && (state.spoke_calls.load(std::memory_order_relaxed) >= 2U) && + (state.constrain_calls.load(std::memory_order_relaxed) >= 1U) && + (state.nogood_handoffs.load(std::memory_order_relaxed) >= 1U); + } + return ok && holds(state.live_spaces, 0U) && (state.copies.load(std::memory_order_relaxed) > 0U); + } + /// Stop RBS and PBS, then verify orderly clone destruction + static bool + 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; + bool ok = true; + { + Gecode::Search::NodeStop stop(0); + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(rbs_state); + Gecode::Search::Options o; + o.threads = 1; + o.stop = &stop; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS search(m, o); + delete m; + HubSpokeDispatchSpace* solution = search.next(); + ok = (solution == nullptr) && search.stopped(); + delete solution; + } + ok = ok && holds(rbs_state.live_spaces, 0U); + + MetaDispatchState pbs_state; + { + Gecode::Search::NodeStop stop(0); + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(pbs_state); + Gecode::Search::Options o; + o.assets = 3; +#ifdef GECODE_HAS_THREADS + o.threads = 3; +#else + o.threads = 1; +#endif + o.stop = &stop; + Gecode::PBS search(m, o); + delete m; + HubSpokeDispatchSpace* solution = search.next(); + ok = ok && (solution == nullptr) && search.stopped(); + delete solution; + } + return ok && holds(pbs_state.live_spaces, 0U); + } + /// Exercise incumbent propagation through RBS and PBS wrappers + static bool + bab_incumbent(void) { + MetaDispatchState rbs_state; + // Continue after a solution, so that the spoke engine prunes with it + rbs_state.restart_after_solution = false; + bool ok = true; + { + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(rbs_state); + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(100); + SEB builder = Gecode::rbs(o); + Gecode::Search::Engine* search = (*builder)(m); + delete builder; + delete m; + HubSpokeDispatchSpace* best = nullptr; + while (HubSpokeDispatchSpace* solution = static_cast(search->next())) { + search->constrain(*solution); + delete best; + best = solution; + } + ok = (best != nullptr) && (best->value() == 1) && + (rbs_state.constrain_hub_calls.load(std::memory_order_relaxed) > 0U) && + (rbs_state.constrain_spoke_calls.load(std::memory_order_relaxed) > 0U); + delete best; + delete search; + } + ok = ok && holds(rbs_state.live_spaces, 0U); + + MetaDispatchState pbs_state; + { + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(pbs_state); + Gecode::Search::Options o; + o.assets = 3; + o.threads = 1; + Gecode::PBS search(m, o); + delete m; + HubSpokeDispatchSpace* best = nullptr; + while (HubSpokeDispatchSpace* solution = search.next()) { + delete best; + best = solution; + } + ok = ok && (best != nullptr) && (best->value() == 1) && holds(pbs_state.constrain_asset_mask, 7U); + delete best; + } + ok = ok && holds(pbs_state.live_spaces, 0U); + + MetaDispatchState nested_state; + nested_state.restart_after_solution = false; + { + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(nested_state); + Gecode::Search::Options outer; + outer.assets = 3; + outer.threads = 1; + Gecode::Search::Options inner[3]; + SEBs spokes(3); + for (int i = 0; i < 3; i++) { + inner[i].threads = 1; + // Each RBS engine owns and deletes its cutoff. + inner[i].cutoff = Gecode::Search::Cutoff::constant(100); + spokes[i] = Gecode::rbs(inner[i]); + } + Gecode::PBS search(m, spokes, outer); + delete m; + HubSpokeDispatchSpace* best = nullptr; + while (HubSpokeDispatchSpace* solution = search.next()) { + delete best; + best = solution; + } + ok = ok && (best != nullptr) && (best->value() == 1) && + holds(nested_state.constrain_hub_asset_mask, 7U) && + holds(nested_state.constrain_spoke_asset_mask, 7U); + delete best; + } + return ok && holds(nested_state.live_spaces, 0U); + } + + public: + /// Initialize scenario \a s with name \a n + MetaDispatch(const std::string& n, Scenario s) : Base("Search::MetaDispatch::" + n), scenario(s) {} + /// Run test + bool + run(void) override { + switch (scenario) { + case Scenario::RBS_HUB_ONLY: + return rbs_dispatch(1, 0); + case Scenario::RBS_SPOKE_ONLY: + return rbs_dispatch(0, 2); + case Scenario::RBS_HUB_CONTINUE: + return rbs(false, false, true); + case Scenario::RBS_HUB_RESTART: + return rbs(true, false, true); + case Scenario::RBS_SPOKE_COMPLETE: + return rbs(true, true, true); + case Scenario::RBS_SPOKE_INCOMPLETE: + return rbs(true, true, false); + case Scenario::PBS_HUB_ONLY: + return pbs(1, 1, 1, 0, 0); + case Scenario::PBS_SPOKE_ONLY: + return pbs(1, 1, 0, 1, 1); + case Scenario::PBS_SINGLE: + return pbs(1, 1, 1, 1, 1); + case Scenario::PBS_SEQUENTIAL_HUB_ONLY: + return pbs(3, 1, 1, 0, 0); + case Scenario::PBS_SEQUENTIAL_SPOKE_ONLY: + return pbs(3, 1, 0, 3, 7); + case Scenario::PBS_SEQUENTIAL: + return pbs(3, 1, 1, 3, 7); + case Scenario::PBS_PARALLEL_HUB_ONLY: + return pbs(3, 3, 1, 0, 0); + case Scenario::PBS_PARALLEL_SPOKE_ONLY: + return pbs(3, 3, 0, 3, 7); + case Scenario::PBS_PARALLEL: + return pbs(3, 3, 1, 3, 7); + case Scenario::RBS_NOGOODS_RESET_OWNERSHIP: + return rbs_nogoods_reset_ownership(); + case Scenario::META_STOP_OWNERSHIP: + return meta_stop_ownership(); + case Scenario::BAB_INCUMBENT: + return bab_incumbent(); + default: + GECODE_NEVER; + } + return false; + } }; /// %Base class for search tests @@ -2849,6 +3355,16 @@ namespace Test { c_d,a_d,t); } // Restart-based search + (void)new MetaDispatch("RBS::HubOnly", MetaDispatch::Scenario::RBS_HUB_ONLY); + (void)new MetaDispatch("RBS::SpokeOnly", MetaDispatch::Scenario::RBS_SPOKE_ONLY); + (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RBS_HUB_CONTINUE); + (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RBS_HUB_RESTART); + (void)new MetaDispatch("RBS::SpokeComplete", MetaDispatch::Scenario::RBS_SPOKE_COMPLETE); + (void)new MetaDispatch("RBS::SpokeIncomplete", MetaDispatch::Scenario::RBS_SPOKE_INCOMPLETE); + (void)new MetaDispatch("RBS::NoGoodsResetOwnership", + MetaDispatch::Scenario::RBS_NOGOODS_RESET_OWNERSHIP); + (void)new MetaDispatch("Lifecycle::StopOwnership", MetaDispatch::Scenario::META_STOP_OWNERSHIP); + (void)new MetaDispatch("BAB::Incumbent", MetaDispatch::Scenario::BAB_INCUMBENT); for (unsigned int t=1; t<=4; t++) { (void) new RBS("DFS",t); (void) new RBS("LDS",t); @@ -2861,6 +3377,17 @@ namespace Test { (void) new RBS("BAB",t); } // Portfolio-based search + (void)new MetaDispatch("PBS::HubOnly", MetaDispatch::Scenario::PBS_HUB_ONLY); + (void)new MetaDispatch("PBS::SpokeOnly", MetaDispatch::Scenario::PBS_SPOKE_ONLY); + (void)new MetaDispatch("PBS::Single", MetaDispatch::Scenario::PBS_SINGLE); + (void)new MetaDispatch("PBS::SequentialHubOnly", MetaDispatch::Scenario::PBS_SEQUENTIAL_HUB_ONLY); + (void)new MetaDispatch("PBS::SequentialSpokeOnly", MetaDispatch::Scenario::PBS_SEQUENTIAL_SPOKE_ONLY); + (void)new MetaDispatch("PBS::Sequential", MetaDispatch::Scenario::PBS_SEQUENTIAL); +#ifdef GECODE_HAS_THREADS + (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PBS_PARALLEL_HUB_ONLY); + (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PBS_PARALLEL_SPOKE_ONLY); + (void)new MetaDispatch("PBS::Parallel", MetaDispatch::Scenario::PBS_PARALLEL); +#endif for (unsigned int a=1; a<=4; a++) for (unsigned int t=1; t<=2*a; t++) { (void) new PBS("DFS",false,a,t); From 121e5b7ce85bdf2cf250305feb27ebc0d0a28fe4 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 17:29:53 +0100 Subject: [PATCH 03/14] Check that removed meta-search hooks no longer compile Configuring with tests compiles a space overriding hub() and spoke(), and then requires spaces overriding master() or slave() to fail, one hook at a time. The pass fixture is also built into the test library. The new hub-spoke example shows both overrides and the Gecode 6 names they replace. --- CMakeLists.txt | 35 ++++++++++ Makefile.in | 4 +- cmake/GecodeSources.cmake | 1 + examples/CMakeLists.txt | 1 + examples/hub-spoke.cpp | 105 +++++++++++++++++++++++++++++ test/search/hub-spoke-api-fail.cpp | 62 +++++++++++++++++ test/search/hub-spoke-api-pass.cpp | 58 ++++++++++++++++ 7 files changed, 264 insertions(+), 2 deletions(-) create mode 100644 examples/hub-spoke.cpp create mode 100644 test/search/hub-spoke-api-fail.cpp create mode 100644 test/search/hub-spoke-api-pass.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d293267aec..24fe0df3e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1417,7 +1417,42 @@ if(GECODE_ENABLE_INSTANCE) list(APPEND GECODE_INSTALL_TARGETS gecode-instance) endif() +# Try to compile test/search/hub-spoke-api-.cpp as a static +# library with the further compile definitions given, storing the result in +# . +function(gecode_try_meta_search_hooks result source) + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + unset(${result} CACHE) + try_compile(${result} + "${CMAKE_CURRENT_BINARY_DIR}/hub-spoke-api-${source}" + SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/test/search/hub-spoke-api-${source}.cpp" + COMPILE_DEFINITIONS ${ARGN} + CMAKE_FLAGS + "-DINCLUDE_DIRECTORIES=${CMAKE_CURRENT_SOURCE_DIR};${CMAKE_CURRENT_BINARY_DIR}" + "-DCMAKE_CXX_STANDARD=17" + "-DCMAKE_CXX_STANDARD_REQUIRED=ON" + "-DCMAKE_CXX_EXTENSIONS=OFF") + set(${result} ${${result}} PARENT_SCOPE) +endfunction() + +# The current hub()/spoke() Space hooks must compile, and each removed +# master()/slave() override must fail on its own. +function(gecode_check_meta_search_hooks) + gecode_try_meta_search_hooks(GECODE_CURRENT_META_HOOKS_COMPILE pass) + if(NOT GECODE_CURRENT_META_HOOKS_COMPILE) + message(FATAL_ERROR "Current hub/spoke Space hooks do not compile") + endif() + foreach(hook MASTER SLAVE) + gecode_try_meta_search_hooks(GECODE_REMOVED_${hook}_HOOK_COMPILES fail -DGECODE_TEST_REMOVED_${hook}) + if(GECODE_REMOVED_${hook}_HOOK_COMPILES) + message(FATAL_ERROR "A removed meta-search Space hook (${hook}) unexpectedly compiles") + endif() + endforeach() +endfunction() + if(BUILD_TESTING) + gecode_check_meta_search_hooks() + set(GECODE_CAN_BUILD_TEST_HARNESS TRUE) foreach(required search int) if(NOT TARGET gecode${required}) diff --git a/Makefile.in b/Makefile.in index bfa8c75286..abe4ab7fb3 100755 --- a/Makefile.in +++ b/Makefile.in @@ -973,7 +973,7 @@ INTEXAMPLESRC0 = \ bin-packing knights tsp perfect-square schurs-lemma \ dominating-queens colored-matrix multi-bin-packing \ qcp job-shop open-route common-pattern fifteen-puzzle \ - tsptw + tsptw hub-spoke INTEXAMPLEHDR = $(INTEXAMPLEHDR0:%=examples/%.hpp) \ @@ -1347,7 +1347,7 @@ BRANCHTESTSRC0 = \ test/assign/set.cpp test/assign/float.cpp SEARCHTESTSRC0 = \ - test/search.cpp test/nogoods.cpp + test/search.cpp test/nogoods.cpp test/search/hub-spoke-api-pass.cpp ARRAYTESTSRC0 = \ test/array.cpp diff --git a/cmake/GecodeSources.cmake b/cmake/GecodeSources.cmake index efde7a61c2..2a80ff0746 100644 --- a/cmake/GecodeSources.cmake +++ b/cmake/GecodeSources.cmake @@ -461,6 +461,7 @@ set(GECODE_TEST_SOURCES test/nogoods.cpp test/region.cpp test/search.cpp + test/search/hub-spoke-api-pass.cpp test/set.cpp test/set/channel.cpp test/set/construct.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index f5c12bdcb9..b5144deb83 100755 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -44,6 +44,7 @@ set(GECODE_EXAMPLE_SOURCES nonogram.cpp open-route.cpp open-shop.cpp + hub-spoke.cpp ortho-latin.cpp partition.cpp pentominoes.cpp diff --git a/examples/hub-spoke.cpp b/examples/hub-spoke.cpp new file mode 100644 index 0000000000..5a01e05fc8 --- /dev/null +++ b/examples/hub-spoke.cpp @@ -0,0 +1,105 @@ +/* + * 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. + * + */ + +#include +#include + +using namespace Gecode; + +/** + * \brief %Example: meta-search hooks after the Gecode 7 rename + * + * Gecode 7 renames the two meta-search configuration hooks of a space: + * \code + * // Gecode 6 // Gecode 7 + * bool master(const MetaInfo&) override; bool hub(const MetaInfo&) override; + * bool slave(const MetaInfo&) override; bool spoke(const MetaInfo&) override; + * \endcode + * The removed declarations have no compatibility aliases. With `override`, + * the compiler reports every model that still uses them. Run with + * `-restart` to have restart-based search call both hooks. + * + * \ingroup Example + */ +class HubSpoke : public Script { +protected: + /// Variable with two solutions + IntVar x; + +public: + /// Post the model + HubSpoke(const Options& opt) : Script(opt), x(*this, 0, 1) { + branch(*this, x, INT_VAL_MIN()); + } + /// Constructor for cloning \a s + HubSpoke(HubSpoke& s) : Script(s) { + x.update(*this, s.x); + } + /// Copy during cloning + Space* + copy(void) override { + return new HubSpoke(*this); + } + /// Exclude solution \a s, as the default hub() does after a solution + void + constrain(const Space& s) override { + rel(*this, x, IRT_NQ, static_cast(s).x.val()); + } + /// Configure the hub space; formerly master() + bool + hub(const MetaInfo& mi) override { + return Space::hub(mi); + } + /// Configure a derived spoke space; formerly slave() + bool + spoke(const MetaInfo& mi) override { + return Space::spoke(mi); + } + /// Print solution + void + print(std::ostream& os) const override { + os << "x = " << x << '\n'; + } +}; + +/** \brief Main-function + * \relates HubSpoke + */ +int +main(int argc, char* argv[]) { + Options opt("HubSpoke"); + opt.parse(argc, argv); + Script::run(opt); + return 0; +} + +// STATISTICS: example-any diff --git a/test/search/hub-spoke-api-fail.cpp b/test/search/hub-spoke-api-fail.cpp new file mode 100644 index 0000000000..e8eeebcc31 --- /dev/null +++ b/test/search/hub-spoke-api-fail.cpp @@ -0,0 +1,62 @@ +/* + * 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. Each configuration declares one of the + * meta-search hooks removed in Gecode 7. A successful compilation means + * that a compatibility hook has returned. + * + */ + +#include + +class HubSpokeApiFail : public Gecode::Space { +public: + HubSpokeApiFail(void) {} + HubSpokeApiFail(HubSpokeApiFail& s) : Gecode::Space(s) {} + Gecode::Space* + copy(void) override { + return new HubSpokeApiFail(*this); + } +#if defined(GECODE_TEST_REMOVED_MASTER) + bool + master(const Gecode::MetaInfo&) override { + return true; + } +#elif defined(GECODE_TEST_REMOVED_SLAVE) + bool + slave(const Gecode::MetaInfo&) override { + return true; + } +#else +#error Select one removed meta-search hook +#endif +}; + +// STATISTICS: test-search diff --git a/test/search/hub-spoke-api-pass.cpp b/test/search/hub-spoke-api-pass.cpp new file mode 100644 index 0000000000..772f81819a --- /dev/null +++ b/test/search/hub-spoke-api-pass.cpp @@ -0,0 +1,58 @@ +/* + * 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. + * + */ + +#include + +namespace Test { namespace Search { + + /// Compile-pass fixture for the Gecode 7 meta-search hooks + class HubSpokeApiPass : public Gecode::Space { + public: + HubSpokeApiPass(void) {} + HubSpokeApiPass(HubSpokeApiPass& s) : Gecode::Space(s) {} + Gecode::Space* + copy(void) override { + return new HubSpokeApiPass(*this); + } + bool + hub(const Gecode::MetaInfo&) override { + return true; + } + bool + spoke(const Gecode::MetaInfo&) override { + return true; + } + }; + +}} // namespace Test::Search + +// STATISTICS: test-search From 7ea6f46d29aae71b3db0dcee1cb21e4cbd922ad4 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 17:30:00 +0100 Subject: [PATCH 04/14] Document the Hub and Spoke migration The Gecode 7 migration notes give the hook rename, its unchanged timing and defaults, and the risk of a renamed hook declared without override. The terminology contract records the role definitions, both engine lifecycles, and the names considered and rejected. The README links the migration notes, and the changelog records the breaking change. --- README.md | 3 + changelog.in | 11 ++++ docs/gecode-7-migration.md | 58 +++++++++++++++++ docs/hub-spoke-terminology.md | 114 ++++++++++++++++++++++++++++++++++ 4 files changed, 186 insertions(+) create mode 100644 docs/gecode-7-migration.md create mode 100644 docs/hub-spoke-terminology.md diff --git a/README.md b/README.md index 3fb11c2e01..6e76ddbf62 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,9 @@ The tutorial *Modeling and Programming with Gecode* explains how to model and solve problems with Gecode, and the reference documentation describes the complete API. +For source-level breaking changes, see the +[Gecode 7 migration notes](docs/gecode-7-migration.md). + ## Download Gecode Gecode 6.5.0 is distributed as source code. Source archives can be downloaded from diff --git a/changelog.in b/changelog.in index 0823b65937..02d5a62e8e 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] +Rename the meta-search Space hooks master() and slave() to hub() and spoke(). +[MORE] +There are no compatibility aliases. An override of a removed hook declared +with override fails to compile, one declared without it is never called. 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 new file mode 100644 index 0000000000..7a86ad187a --- /dev/null +++ b/docs/gecode-7-migration.md @@ -0,0 +1,58 @@ +# Gecode 7 migration notes + +## Meta-search Space roles + +Gecode 7 names the two `Space` roles used by restart-based search (RBS) and +portfolio-based search (PBS) **Hub** and **Spoke**. +The [Hub and Spoke terminology contract](hub-spoke-terminology.md) +records the lifecycle and naming rationale behind these roles. + +A Hub is the persistent or common Space from which an exploration Space +is derived. A Spoke is the derived Space configured for one RBS restart +episode or one PBS portfolio asset. These are logical roles. In RBS, the +prepared object becomes the explored Spoke while its clone becomes the next +Hub. + +The same terms apply to both engines because both use the same derivation: +prepare common state, derive an exploration Space, and specialize that Space. +The callback contracts remain engine-specific. RBS uses the return values to +control restart and completeness behavior, while PBS ignores them during +one-time Hub and per-asset Spoke configuration. + +Gecode 7 makes the following breaking override rename: + +```cpp +// Gecode 6 +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; +``` + +There are no compatibility aliases. Keeping `override` on model hooks makes +the compiler identify every model that still uses a Gecode 6 signature. A +`master` or `slave` member declared without `override` still compiles, but +no search engine calls it. + +The build-checked +[Hub and Spoke migration example](../examples/hub-spoke.cpp) +contains both current override declarations. + +The rename does not change callback timing or behavior: + +- RBS calls `hub` when persistent restart state is updated and calls + `spoke` for each derived restart exploration. +- PBS calls `hub` once before constructing assets and calls `spoke` once + per asset, including the single-asset path. +- The default RBS Hub behavior still constrains against the last solution, + posts no-goods, and requests a restart. +- The default PBS Hub behavior still removes common branchers before + asset-specific branching is installed. +- The default Spoke behavior still performs no additional configuration and + returns `true`. + +Hub and Spoke describe Spaces. They do not replace runtime terms such as +portfolio coordinator, wrapped engine, or worker thread where those terms +describe different objects. diff --git a/docs/hub-spoke-terminology.md b/docs/hub-spoke-terminology.md new file mode 100644 index 0000000000..17d630d00c --- /dev/null +++ b/docs/hub-spoke-terminology.md @@ -0,0 +1,114 @@ +# Hub and Spoke terminology contract + +## Decision + +Gecode 7 uses **Hub** and **Spoke** for the two `Space` roles shared by +restart-based search (RBS) and portfolio-based search (PBS). + +The names come from one picture, a wheel. The hub stays at the centre and +holds what persists, and each spoke goes out from it to explore. A Hub is the +persistent or common `Space` from which an exploration space is derived. A +Spoke is the derived `Space` configured for one RBS restart episode or one +PBS portfolio asset. + +These are logical roles. An RBS Hub can itself be a clone of the state used +by the preceding episode while remaining the Hub of the next exploration. + +## Lifecycles + +```text +RBS +hub[n] -- hub(restart_info) --> prepared state + |-- clone --> hub[n+1] + `-- spoke(restart_info) --> explored spoke[n] + +PBS +input -- optional clone --> hub -- hub(portfolio_info) + |-- derive/configure --> spoke[0] + |-- derive/configure --> spoke[1] + `-- derive/configure --> spoke[n] +``` + +The RBS allocation identity changes across an episode: the prepared object +becomes the explored Spoke and its clone becomes the next Hub. Hub therefore +names the centre that the next Spoke leaves from, not the oldest object in the +solve. In single-asset PBS, one object passes through the Hub stage and then +the Spoke stage; the names do not require separate allocations. + +## Behavior matrix + +| Engine | Role | Invocation and relationship | Information and result | Default behavior | +| --- | --- | --- | --- | --- | +| RBS | Hub | Repeated after solutions and at restart boundaries; prepares state before the next Hub clone is retained | Restart reason, counts, last solution, and no-goods. The Boolean can decide whether a solution triggers a restart | Constrain against the last solution when present, post no-goods, and request restart | +| RBS | Spoke | Once for each derived restart exploration | Restart information. The Boolean declares the exploration complete or incomplete | No additional configuration; complete | +| PBS | Hub | Once on the common space before asset construction | Portfolio metadata; result ignored | Remove common branchers so assets can install their own branching | +| PBS | Spoke | Once per asset, including the single-asset path | Asset number starting at zero; result ignored | No additional configuration | + +The common nouns do not require one callback contract. PBS and RBS have +different invocation frequencies and result semantics. Gecode 7 can later +represent those differences with engine-specific metadata, result types, or +overloads while retaining Hub and Spoke. The rename itself preserves current +behavior. + +## Why Hub and Spoke + +- **One metaphor.** Each word names a part of the same wheel, so either word + suggests the other and the relationship between them. +- **Both engines.** A portfolio is a hub with several spokes at once. Restart + search sends out one spoke at a time from a hub that keeps learning between + them through the last solution and no-goods. +- **Short and memorable.** Both are one-syllable nouns that read well as hook + names, `hub()` and `spoke()`, and in prose. +- **Not used for other things.** Before this change, neither word occurred in + the Gecode sources or in MPG outside word-list data, and neither names + anything in the C++ standard library. Searching for them finds only these + roles. + +The picture does not say that a spoke is a clone of its hub. The +documentation states that relationship explicitly. + +Hub and spoke describes positions, not agency. The hub does not schedule or +run its spokes: the engine does. Topology names that describe the runtime, +such as `Controller/Worker`, `Driver/Executor`, and `Scheduler/Worker`, were +not chosen because the PBS coordinator is an engine object rather than the +`Space` passed to the first hook, and because `worker` already names threads. + +Internal names follow the actual objects. The retained RBS `Space*` is the +`hub`, and each per-asset PBS runnable is a `Spoke`. A spoke's pointer to the +enclosing PBS engine is its `portfolio`, and the search engine it wraps is its +`engine`. + +## Alternatives considered but not selected + +| Pair | Strength | Reason not selected | +| --- | --- | --- | +| Origin / Variant | Clear derivation relationship; close to the "variants" of a model in MPG | `variant` already has many unrelated uses, such as model variants in the examples and `std::variant`; `origin` suggests the oldest object, but the RBS Hub is replaced every episode | +| Theme / Variation | One familiar metaphor that fits both engines | Less immediate as a hook name, and a musical theme stays fixed while the Hub gains constraints | +| Anchor / Link; Hyperspace / Subspace | Explicit connection between the two words | `link` and `anchor` occur elsewhere in the sources; a Spoke for a portfolio asset is often not a smaller space | +| Archetype / Variant | Exact common-form relationship | `Archetype` is less immediate in a low-level API | +| Basis / Variant | Handles an evolving RBS source | `Basis` carries linear-algebra associations | +| Coordinator / Explorer | Good engine-topology terminology | The first public hook is on a `Space` that does not coordinate execution | +| Principal / Agent | Clear noun pair | Suggests delegation and autonomy rather than cloning | +| Archetype / Instance | Clear type-to-realization relation | `Instance` already commonly means a problem instance | +| Control / Asset | `Asset` fits PBS | `Control` can be a verb and the pair fits RBS poorly | +| Portfolio / Asset; Hub / Episode | Locally expressive for each engine | Four role names hide the shared derivation and complicate models supporting both engines | + +These alternatives were considered but not rejected outright. + +## Explicitly rejected names and designs + +- **Master / Slave** is the terminology being removed. It describes authority + and subordination rather than common state and a derived exploration. +- **Run / Search** was rejected because both words are verbs and already occur + frequently in this API. As member names, they do not clearly denote roles. +- **Different public role vocabularies for PBS and RBS** were rejected. Contract + differences should be represented by contracts, not by replacing one shared + derivation vocabulary with four unrelated nouns. + +## Migration boundary + +The Gecode 7 migration renames the public virtual functions, overrides, calls, +documentation, tests, and role-bearing internal identifiers. It does not add +deprecated aliases, change restart decisions, change completeness reporting, +change PBS asset numbering, or mechanically rename unrelated historical and +third-party occurrences. From 9f80c89af97174c1dbe8dc31525b6403e7589c4f Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 11:21:26 +0100 Subject: [PATCH 05/14] Reject Gecode 6 meta-search overrides at compile time Space now declares master() and slave() as deleted virtual functions. A non-deleted function cannot override a deleted one, so a Gecode 6 override fails to compile even without override, where it used to compile and never be called. The configure-time try_compile checks become two CTest cases that build EXCLUDE_FROM_ALL object libraries: one overrides hub() and spoke() and must build, the other overrides slave() without override and master() with it, and must fail. The failing case requires the passing one, so a broken setup cannot make it pass. The pass fixture leaves the test library. --- CMakeLists.txt | 54 +++++++++++------------------- Makefile.in | 2 +- changelog.in | 5 +-- cmake/GecodeSources.cmake | 1 - docs/gecode-7-migration.md | 7 ++-- gecode/kernel/core.hpp | 15 +++++++++ test/search/hub-spoke-api-fail.cpp | 18 ++++------ 7 files changed, 48 insertions(+), 54 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 24fe0df3e5..412af949e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1417,42 +1417,7 @@ if(GECODE_ENABLE_INSTANCE) list(APPEND GECODE_INSTALL_TARGETS gecode-instance) endif() -# Try to compile test/search/hub-spoke-api-.cpp as a static -# library with the further compile definitions given, storing the result in -# . -function(gecode_try_meta_search_hooks result source) - set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) - unset(${result} CACHE) - try_compile(${result} - "${CMAKE_CURRENT_BINARY_DIR}/hub-spoke-api-${source}" - SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/test/search/hub-spoke-api-${source}.cpp" - COMPILE_DEFINITIONS ${ARGN} - CMAKE_FLAGS - "-DINCLUDE_DIRECTORIES=${CMAKE_CURRENT_SOURCE_DIR};${CMAKE_CURRENT_BINARY_DIR}" - "-DCMAKE_CXX_STANDARD=17" - "-DCMAKE_CXX_STANDARD_REQUIRED=ON" - "-DCMAKE_CXX_EXTENSIONS=OFF") - set(${result} ${${result}} PARENT_SCOPE) -endfunction() - -# The current hub()/spoke() Space hooks must compile, and each removed -# master()/slave() override must fail on its own. -function(gecode_check_meta_search_hooks) - gecode_try_meta_search_hooks(GECODE_CURRENT_META_HOOKS_COMPILE pass) - if(NOT GECODE_CURRENT_META_HOOKS_COMPILE) - message(FATAL_ERROR "Current hub/spoke Space hooks do not compile") - endif() - foreach(hook MASTER SLAVE) - gecode_try_meta_search_hooks(GECODE_REMOVED_${hook}_HOOK_COMPILES fail -DGECODE_TEST_REMOVED_${hook}) - if(GECODE_REMOVED_${hook}_HOOK_COMPILES) - message(FATAL_ERROR "A removed meta-search Space hook (${hook}) unexpectedly compiles") - endif() - endforeach() -endfunction() - if(BUILD_TESTING) - gecode_check_meta_search_hooks() - set(GECODE_CAN_BUILD_TEST_HARNESS TRUE) foreach(required search int) if(NOT TARGET gecode${required}) @@ -1511,6 +1476,25 @@ 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 Gecode 6 + # master()/slave() overrides must not. + foreach(api pass fail) + 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) + # The failing fixture stays out of the compilation database used for lint. + set_target_properties(hub-spoke-api-fail PROPERTIES EXPORT_COMPILE_COMMANDS OFF) + set_tests_properties(hub-spoke-api-fail PROPERTIES + WILL_FAIL TRUE + FIXTURES_REQUIRED hub-spoke-api + RESOURCE_LOCK gecode-test-build) + set(GECODE_CAN_BUILD_TESTS ${GECODE_CAN_BUILD_TEST_HARNESS}) foreach(required minimodel driver) if(NOT TARGET gecode${required}) diff --git a/Makefile.in b/Makefile.in index abe4ab7fb3..46f6ae6d14 100755 --- a/Makefile.in +++ b/Makefile.in @@ -1347,7 +1347,7 @@ BRANCHTESTSRC0 = \ test/assign/set.cpp test/assign/float.cpp SEARCHTESTSRC0 = \ - test/search.cpp test/nogoods.cpp test/search/hub-spoke-api-pass.cpp + test/search.cpp test/nogoods.cpp ARRAYTESTSRC0 = \ test/array.cpp diff --git a/changelog.in b/changelog.in index 02d5a62e8e..99dea0fe2f 100755 --- a/changelog.in +++ b/changelog.in @@ -82,8 +82,9 @@ Rank: major [DESCRIPTION] Rename the meta-search Space hooks master() and slave() to hub() and spoke(). [MORE] -There are no compatibility aliases. An override of a removed hook declared -with override fails to compile, one declared without it is never called. See +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. [ENTRY] diff --git a/cmake/GecodeSources.cmake b/cmake/GecodeSources.cmake index 2a80ff0746..efde7a61c2 100644 --- a/cmake/GecodeSources.cmake +++ b/cmake/GecodeSources.cmake @@ -461,7 +461,6 @@ set(GECODE_TEST_SOURCES test/nogoods.cpp test/region.cpp test/search.cpp - test/search/hub-spoke-api-pass.cpp test/set.cpp test/set/channel.cpp test/set/construct.cpp diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 7a86ad187a..272ec9477a 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -31,10 +31,9 @@ bool hub(const Gecode::MetaInfo& mi) override; bool spoke(const Gecode::MetaInfo& mi) override; ``` -There are no compatibility aliases. Keeping `override` on model hooks makes -the compiler identify every model that still uses a Gecode 6 signature. A -`master` or `slave` member declared without `override` still compiles, but -no search engine calls it. +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`. The build-checked [Hub and Spoke migration example](../examples/hub-spoke.cpp) diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 73c5b63b68..9694bf3ee3 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2249,6 +2249,21 @@ namespace Gecode { 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; + /* * Member functions for search engines * diff --git a/test/search/hub-spoke-api-fail.cpp b/test/search/hub-spoke-api-fail.cpp index e8eeebcc31..3b4e10ba6c 100644 --- a/test/search/hub-spoke-api-fail.cpp +++ b/test/search/hub-spoke-api-fail.cpp @@ -28,9 +28,10 @@ * 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. Each configuration declares one of the - * meta-search hooks removed in Gecode 7. A successful compilation means - * that a compatibility hook has returned. + * This file must not compile: it overrides the Gecode 6 meta-search + * hooks that Gecode 7 renamed to hub() and spoke() and deletes in + * Space. Successful compilation means that an old override would + * again compile and silently never be called. * */ @@ -44,19 +45,14 @@ class HubSpokeApiFail : public Gecode::Space { copy(void) override { return new HubSpokeApiFail(*this); } -#if defined(GECODE_TEST_REMOVED_MASTER) - bool - master(const Gecode::MetaInfo&) override { + virtual bool + slave(const Gecode::MetaInfo&) { return true; } -#elif defined(GECODE_TEST_REMOVED_SLAVE) bool - slave(const Gecode::MetaInfo&) override { + master(const Gecode::MetaInfo&) override { return true; } -#else -#error Select one removed meta-search hook -#endif }; // STATISTICS: test-search From 5f7a73cb14886e8e95f66fd481944400ef5e3bb7 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 11:21:43 +0100 Subject: [PATCH 06/14] Rewrite the hub and spoke migration notes The notes now start with what a port needs: rename the overrides, keep their signatures, and rely on the compiler to find old ones. Short semantics follow, including that a spoke is a disposable clone rather than a long-lived peer, and pointers to the crossword, photo, and qcp examples. The terminology contract shrinks to the wheel picture in the notes. The hub-spoke example goes: its overrides only called the defaults, and with several assets it printed unassigned solutions. --- Makefile.in | 2 +- docs/gecode-7-migration.md | 70 +++++++++------------ docs/hub-spoke-terminology.md | 114 ---------------------------------- examples/CMakeLists.txt | 1 - examples/hub-spoke.cpp | 105 ------------------------------- 5 files changed, 30 insertions(+), 262 deletions(-) delete mode 100644 docs/hub-spoke-terminology.md delete mode 100644 examples/hub-spoke.cpp diff --git a/Makefile.in b/Makefile.in index 46f6ae6d14..bfa8c75286 100755 --- a/Makefile.in +++ b/Makefile.in @@ -973,7 +973,7 @@ INTEXAMPLESRC0 = \ bin-packing knights tsp perfect-square schurs-lemma \ dominating-queens colored-matrix multi-bin-packing \ qcp job-shop open-route common-pattern fifteen-puzzle \ - tsptw hub-spoke + tsptw INTEXAMPLEHDR = $(INTEXAMPLEHDR0:%=examples/%.hpp) \ diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 272ec9477a..a008778374 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -1,25 +1,8 @@ # Gecode 7 migration notes -## Meta-search Space roles +## Meta-search hooks: master() and slave() are now hub() and spoke() -Gecode 7 names the two `Space` roles used by restart-based search (RBS) and -portfolio-based search (PBS) **Hub** and **Spoke**. -The [Hub and Spoke terminology contract](hub-spoke-terminology.md) -records the lifecycle and naming rationale behind these roles. - -A Hub is the persistent or common Space from which an exploration Space -is derived. A Spoke is the derived Space configured for one RBS restart -episode or one PBS portfolio asset. These are logical roles. In RBS, the -prepared object becomes the explored Spoke while its clone becomes the next -Hub. - -The same terms apply to both engines because both use the same derivation: -prepare common state, derive an exploration Space, and specialize that Space. -The callback contracts remain engine-specific. RBS uses the return values to -control restart and completeness behavior, while PBS ignores them during -one-time Hub and per-asset Spoke configuration. - -Gecode 7 makes the following breaking override rename: +Rename the overrides. Their signatures and return values are unchanged: ```cpp // Gecode 6 @@ -33,25 +16,30 @@ bool spoke(const Gecode::MetaInfo& mi) 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`. - -The build-checked -[Hub and Spoke migration example](../examples/hub-spoke.cpp) -contains both current override declarations. - -The rename does not change callback timing or behavior: - -- RBS calls `hub` when persistent restart state is updated and calls - `spoke` for each derived restart exploration. -- PBS calls `hub` once before constructing assets and calls `spoke` once - per asset, including the single-asset path. -- The default RBS Hub behavior still constrains against the last solution, - posts no-goods, and requests a restart. -- The default PBS Hub behavior still removes common branchers before - asset-specific branching is installed. -- The default Spoke behavior still performs no additional configuration and - returns `true`. - -Hub and Spoke describe Spaces. They do not replace runtime terms such as -portfolio coordinator, wrapped engine, or worker thread where those terms -describe different objects. +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 names come from a wheel. The hub is the persistent centre: in RBS it +carries the last solution and the no-goods from one restart to the next, +and in PBS it is the common model. Each spoke is a disposable clone of the +hub: RBS searches one spoke per restart, and PBS searches one spoke per +asset. A spoke is not a long-lived peer that exchanges information with the +hub, which is what hub and spoke means in some other solvers, such as +mpi-sppy. + +- RBS calls `hub()` after each solution and at each restart, and `spoke()` + on each new spoke, 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 clones one spoke per asset and calls + `spoke()` on it with the asset number. The default `hub()` removes all + branchers, so `spoke()` must post the branching of each asset. + +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. +- `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for + each asset. diff --git a/docs/hub-spoke-terminology.md b/docs/hub-spoke-terminology.md deleted file mode 100644 index 17d630d00c..0000000000 --- a/docs/hub-spoke-terminology.md +++ /dev/null @@ -1,114 +0,0 @@ -# Hub and Spoke terminology contract - -## Decision - -Gecode 7 uses **Hub** and **Spoke** for the two `Space` roles shared by -restart-based search (RBS) and portfolio-based search (PBS). - -The names come from one picture, a wheel. The hub stays at the centre and -holds what persists, and each spoke goes out from it to explore. A Hub is the -persistent or common `Space` from which an exploration space is derived. A -Spoke is the derived `Space` configured for one RBS restart episode or one -PBS portfolio asset. - -These are logical roles. An RBS Hub can itself be a clone of the state used -by the preceding episode while remaining the Hub of the next exploration. - -## Lifecycles - -```text -RBS -hub[n] -- hub(restart_info) --> prepared state - |-- clone --> hub[n+1] - `-- spoke(restart_info) --> explored spoke[n] - -PBS -input -- optional clone --> hub -- hub(portfolio_info) - |-- derive/configure --> spoke[0] - |-- derive/configure --> spoke[1] - `-- derive/configure --> spoke[n] -``` - -The RBS allocation identity changes across an episode: the prepared object -becomes the explored Spoke and its clone becomes the next Hub. Hub therefore -names the centre that the next Spoke leaves from, not the oldest object in the -solve. In single-asset PBS, one object passes through the Hub stage and then -the Spoke stage; the names do not require separate allocations. - -## Behavior matrix - -| Engine | Role | Invocation and relationship | Information and result | Default behavior | -| --- | --- | --- | --- | --- | -| RBS | Hub | Repeated after solutions and at restart boundaries; prepares state before the next Hub clone is retained | Restart reason, counts, last solution, and no-goods. The Boolean can decide whether a solution triggers a restart | Constrain against the last solution when present, post no-goods, and request restart | -| RBS | Spoke | Once for each derived restart exploration | Restart information. The Boolean declares the exploration complete or incomplete | No additional configuration; complete | -| PBS | Hub | Once on the common space before asset construction | Portfolio metadata; result ignored | Remove common branchers so assets can install their own branching | -| PBS | Spoke | Once per asset, including the single-asset path | Asset number starting at zero; result ignored | No additional configuration | - -The common nouns do not require one callback contract. PBS and RBS have -different invocation frequencies and result semantics. Gecode 7 can later -represent those differences with engine-specific metadata, result types, or -overloads while retaining Hub and Spoke. The rename itself preserves current -behavior. - -## Why Hub and Spoke - -- **One metaphor.** Each word names a part of the same wheel, so either word - suggests the other and the relationship between them. -- **Both engines.** A portfolio is a hub with several spokes at once. Restart - search sends out one spoke at a time from a hub that keeps learning between - them through the last solution and no-goods. -- **Short and memorable.** Both are one-syllable nouns that read well as hook - names, `hub()` and `spoke()`, and in prose. -- **Not used for other things.** Before this change, neither word occurred in - the Gecode sources or in MPG outside word-list data, and neither names - anything in the C++ standard library. Searching for them finds only these - roles. - -The picture does not say that a spoke is a clone of its hub. The -documentation states that relationship explicitly. - -Hub and spoke describes positions, not agency. The hub does not schedule or -run its spokes: the engine does. Topology names that describe the runtime, -such as `Controller/Worker`, `Driver/Executor`, and `Scheduler/Worker`, were -not chosen because the PBS coordinator is an engine object rather than the -`Space` passed to the first hook, and because `worker` already names threads. - -Internal names follow the actual objects. The retained RBS `Space*` is the -`hub`, and each per-asset PBS runnable is a `Spoke`. A spoke's pointer to the -enclosing PBS engine is its `portfolio`, and the search engine it wraps is its -`engine`. - -## Alternatives considered but not selected - -| Pair | Strength | Reason not selected | -| --- | --- | --- | -| Origin / Variant | Clear derivation relationship; close to the "variants" of a model in MPG | `variant` already has many unrelated uses, such as model variants in the examples and `std::variant`; `origin` suggests the oldest object, but the RBS Hub is replaced every episode | -| Theme / Variation | One familiar metaphor that fits both engines | Less immediate as a hook name, and a musical theme stays fixed while the Hub gains constraints | -| Anchor / Link; Hyperspace / Subspace | Explicit connection between the two words | `link` and `anchor` occur elsewhere in the sources; a Spoke for a portfolio asset is often not a smaller space | -| Archetype / Variant | Exact common-form relationship | `Archetype` is less immediate in a low-level API | -| Basis / Variant | Handles an evolving RBS source | `Basis` carries linear-algebra associations | -| Coordinator / Explorer | Good engine-topology terminology | The first public hook is on a `Space` that does not coordinate execution | -| Principal / Agent | Clear noun pair | Suggests delegation and autonomy rather than cloning | -| Archetype / Instance | Clear type-to-realization relation | `Instance` already commonly means a problem instance | -| Control / Asset | `Asset` fits PBS | `Control` can be a verb and the pair fits RBS poorly | -| Portfolio / Asset; Hub / Episode | Locally expressive for each engine | Four role names hide the shared derivation and complicate models supporting both engines | - -These alternatives were considered but not rejected outright. - -## Explicitly rejected names and designs - -- **Master / Slave** is the terminology being removed. It describes authority - and subordination rather than common state and a derived exploration. -- **Run / Search** was rejected because both words are verbs and already occur - frequently in this API. As member names, they do not clearly denote roles. -- **Different public role vocabularies for PBS and RBS** were rejected. Contract - differences should be represented by contracts, not by replacing one shared - derivation vocabulary with four unrelated nouns. - -## Migration boundary - -The Gecode 7 migration renames the public virtual functions, overrides, calls, -documentation, tests, and role-bearing internal identifiers. It does not add -deprecated aliases, change restart decisions, change completeness reporting, -change PBS asset numbering, or mechanically rename unrelated historical and -third-party occurrences. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b5144deb83..f5c12bdcb9 100755 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -44,7 +44,6 @@ set(GECODE_EXAMPLE_SOURCES nonogram.cpp open-route.cpp open-shop.cpp - hub-spoke.cpp ortho-latin.cpp partition.cpp pentominoes.cpp diff --git a/examples/hub-spoke.cpp b/examples/hub-spoke.cpp deleted file mode 100644 index 5a01e05fc8..0000000000 --- a/examples/hub-spoke.cpp +++ /dev/null @@ -1,105 +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. - * - */ - -#include -#include - -using namespace Gecode; - -/** - * \brief %Example: meta-search hooks after the Gecode 7 rename - * - * Gecode 7 renames the two meta-search configuration hooks of a space: - * \code - * // Gecode 6 // Gecode 7 - * bool master(const MetaInfo&) override; bool hub(const MetaInfo&) override; - * bool slave(const MetaInfo&) override; bool spoke(const MetaInfo&) override; - * \endcode - * The removed declarations have no compatibility aliases. With `override`, - * the compiler reports every model that still uses them. Run with - * `-restart` to have restart-based search call both hooks. - * - * \ingroup Example - */ -class HubSpoke : public Script { -protected: - /// Variable with two solutions - IntVar x; - -public: - /// Post the model - HubSpoke(const Options& opt) : Script(opt), x(*this, 0, 1) { - branch(*this, x, INT_VAL_MIN()); - } - /// Constructor for cloning \a s - HubSpoke(HubSpoke& s) : Script(s) { - x.update(*this, s.x); - } - /// Copy during cloning - Space* - copy(void) override { - return new HubSpoke(*this); - } - /// Exclude solution \a s, as the default hub() does after a solution - void - constrain(const Space& s) override { - rel(*this, x, IRT_NQ, static_cast(s).x.val()); - } - /// Configure the hub space; formerly master() - bool - hub(const MetaInfo& mi) override { - return Space::hub(mi); - } - /// Configure a derived spoke space; formerly slave() - bool - spoke(const MetaInfo& mi) override { - return Space::spoke(mi); - } - /// Print solution - void - print(std::ostream& os) const override { - os << "x = " << x << '\n'; - } -}; - -/** \brief Main-function - * \relates HubSpoke - */ -int -main(int argc, char* argv[]) { - Options opt("HubSpoke"); - opt.parse(argc, argv); - Script::run(opt); - return 0; -} - -// STATISTICS: example-any From f782d08bb712f43f533cbd38ed5b209b3eaa89fb Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 11:21:56 +0100 Subject: [PATCH 07/14] Name job-shop's cloned spaces root and model The probing phase clones its root space for each DFS probe, and the dichotomic phase clones the model for each bounded search before giving it to RBS. Neither space plays a meta-search role, so the rename to hub misdescribed them. --- examples/job-shop.cpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index 589f7067ab..d497ded4c3 100755 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -700,16 +700,16 @@ solve(const JobShopOptions& opt) { { Support::Timer t; t.start(); Search::Statistics stat; - JobShopProbe* hub = new JobShopProbe(opt); + JobShopProbe* root = new JobShopProbe(opt); - if (hub->status() != SS_SOLVED) { - delete hub; + if (root->status() != SS_SOLVED) { + delete root; std::cerr << "Error: has no solution..." << std::endl; return; } - l = hub->cost().min(); - u = hub->cost().max(); + l = root->cost().min(); + u = root->cost().max(); FailTimeStop fts(opt.fail_probe(),opt.time_probe()); CommonOptions so(opt); @@ -722,7 +722,7 @@ solve(const JobShopOptions& opt) { << std::endl; for (unsigned int p=0; p(hub->clone()); + JobShopProbe* jsp = static_cast(root->clone()); jsp->branch(p,rnd); DFS dfs(jsp,so); JobShopProbe* s = dfs.next(); @@ -740,7 +740,7 @@ solve(const JobShopOptions& opt) { } stat += statj; } - delete hub; + delete root; print(stat,false); std::cout << "\t\t\truntime: "; @@ -756,11 +756,11 @@ solve(const JobShopOptions& opt) { // Dichotomic search { - JobShopSolve* hub = new JobShopSolve(opt); + JobShopSolve* model = new JobShopSolve(opt); - if (hub->status() == SS_FAILED) { - delete hub; + if (model->status() == SS_FAILED) { + delete model; std::cerr << "Error: has no solution..." << std::endl; return; } @@ -775,7 +775,7 @@ solve(const JobShopOptions& opt) { while (l < u) { std::cout << "\t\tBounds: [" << l << "," << u << "]" << std::endl; - JobShopSolve* jss = static_cast(hub->clone()); + JobShopSolve* jss = static_cast(model->clone()); int m = (l + u) / 2; rel(*jss, jss->cost() >= l); rel(*jss, jss->cost() <= m); @@ -810,7 +810,7 @@ solve(const JobShopOptions& opt) { } if (l == u) { - delete hub; + delete model; std::cout << std::endl << "\tFound best solution and proved optimality." << std::endl; @@ -822,15 +822,15 @@ solve(const JobShopOptions& opt) { Support::Timer t; t.start(); std::cout << std::endl << "\tSolving..." << std::endl; - rel(*hub, hub->cost() >= l); - rel(*hub, hub->cost() < u); + rel(*model, model->cost() >= l); + rel(*model, model->cost() < u); CommonOptions so(opt); if (opt.time_solve() > 0U) so.stop = Search::Stop::time(opt.time_solve()); so.cutoff = Search::Cutoff::geometric(JobShopConfig::restart_scale, JobShopConfig::restart_base); - RBS rbs(hub,so); + RBS rbs(model,so); while (JobShopSolve* s = rbs.next()) { s->print(std::cout); u = s->cost().val(); From 4aa4db1979c969e8df6156d97a3fd01872870e74 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 11:21:58 +0100 Subject: [PATCH 08/14] Call PBS engine wrappers assets, not spokes Hub and spoke name Spaces, but the rename also called the per-asset engine wrappers in sequential and parallel PBS spokes. They now use the existing public PBS word: Asset, assets, n_assets, and asset_stop, and make_rbs_engine takes its leaf engine as engine. Space variables keep the names hub and spoke. The sequential Asset::init declaration and definition use the same parameter names, and the stat members describe what they hold. --- gecode/search/par/pbs.hh | 70 +++++++++++----------- gecode/search/par/pbs.hpp | 120 +++++++++++++++++++------------------- gecode/search/pbs.cpp | 12 ++-- gecode/search/pbs.hpp | 118 ++++++++++++++++++------------------- gecode/search/rbs.cpp | 8 +-- gecode/search/rbs.hpp | 6 +- gecode/search/seq/pbs.hh | 52 ++++++++--------- gecode/search/seq/pbs.hpp | 80 ++++++++++++------------- 8 files changed, 233 insertions(+), 233 deletions(-) diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 7ea7f4b4d6..fb180a69f0 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -44,10 +44,10 @@ namespace Gecode { namespace Search { namespace Par { - /// Stop object used for controlling spokes in a portfolio + /// Stop object used for controlling assets in a portfolio class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: - /// The stop object for the spokes + /// The stop object for the assets Stop* so; /// The stop object for the portfolio (possibly nullptr) Stop* po; @@ -56,7 +56,7 @@ namespace Gecode { namespace Search { namespace Par { /// Whether search must be stopped std::atomic* tostop; public: - /// Initialize with spoke stop \a so, portfolio stop \a po, and \a control + /// 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); @@ -74,9 +74,9 @@ namespace Gecode { namespace Search { namespace Par { template class PBS; - /// Runnable spoke in a portfolio + /// Runnable asset in a portfolio template - class GECODE_SEARCH_EXPORT Spoke : public Support::Runnable { + class GECODE_SEARCH_EXPORT Asset : public Support::Runnable { protected: /// Completion event for the current run class Completion : public Support::Terminator { @@ -99,25 +99,25 @@ namespace Gecode { namespace Search { namespace Par { Stop* stop; public: /// Initialize with portfolio \a p, engine \a e, and its stop object \a so - Spoke(PBS* p, Engine* e, Stop* so); - /// Return statistics of spoke + Asset(PBS* p, Engine* e, Stop* so); + /// Return statistics of asset Statistics statistics(void) const; - /// Check whether spoke has been stopped + /// Check whether asset has been stopped bool stopped(void) const; - /// Check whether spoke stopped at a local limit + /// Check whether asset stopped at a local limit bool limited(void) const; /// Return the completion terminator virtual Support::Terminator* terminator(void) const; - /// Wait for the spoke to complete its current run + /// Wait for the asset to complete its current run void wait(void); - /// Wake a paused spoke so that it can observe the portfolio stop + /// Wake a paused asset so that it can observe the portfolio stop void wake(void); /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run virtual void run(void); - /// Delete spoke - virtual ~Spoke(void); + /// Delete asset + virtual ~Asset(void); }; /// Collect all solutions @@ -131,13 +131,13 @@ namespace Gecode { namespace Search { namespace Par { /// Initialize CollectAll(void); /// Add a solution \a a reported by \a r and always return true - bool add(Space* s, Spoke* r); + bool add(Space* s, Asset* r); /// Dummy function bool constrain(const Space& b); /// Check whether there is any solution left bool empty(void) const; /// Return solution reported by \a r - Space* get(Spoke*& r); + Space* get(Asset*& r); /// Destructor ~CollectAll(void); }; @@ -148,20 +148,20 @@ namespace Gecode { namespace Search { namespace Par { /// Currently best solution Space* b; /// Who has reported the best solution (nullptr if solution has already been reported) - Spoke* reporter; + Asset* reporter; public: /// Whether it collects best solutions static const bool best = true; /// Initialize CollectBest(void); /// Add a solution \a s by \a r and return whether is was better - bool add(Space* s, Spoke* r); + bool add(Space* s, Asset* r); /// Check whether \a b better and update accordingly bool constrain(const Space& b); /// Check whether there is any solution left bool empty(void) const; /// Return solution reported by \a r (only if a better one was found) - Space* get(Spoke*& r); + Space* get(Asset*& r); /// Destructor ~CollectBest(void); }; @@ -169,19 +169,19 @@ namespace Gecode { namespace Search { namespace Par { /// Parallel portfolio engine implementation template class GECODE_SEARCH_EXPORT PBS : public Engine { - friend class Spoke; + friend class Asset; protected: - /// Portfolio statistics + /// Statistics of propagating the model Statistics stat; - /// Spoke engines - Spoke** spokes; - /// Number of spoke engines - unsigned int n_spokes; - /// Number of active spoke engines + /// Asset engines + Asset** assets; + /// Number of asset engines + unsigned int n_assets; + /// Number of active asset engines unsigned int n_active; - /// Whether a spoke has been stopped - std::atomic spoke_stop; - /// Whether a spoke stopped at a local limit + /// Whether an asset has been stopped + std::atomic asset_stop; + /// Whether an asset stopped at a local limit bool incomplete; /// Shared stop flag std::atomic tostop; @@ -189,23 +189,23 @@ namespace Gecode { namespace Search { namespace Par { Collect solutions; /// Mutex for synchronization Support::Mutex m; - /// Number of busy spokes + /// Number of busy assets unsigned int n_busy; - /// Signal that number of busy spokes becomes zero + /// Signal that number of busy assets becomes zero Support::Event idle; /// Failure raised while running or updating a portfolio asset std::exception_ptr failure; - /// Process report from spoke, return false if solution was ignored - bool report(Spoke* spoke, Space* s); - /// Process failure from spoke + /// Process report from asset, return false if solution was ignored + bool report(Asset* asset, Space* s); + /// Process failure from asset void fail(void); /** * The key invariant of the engine is as follows: * - n_busy is always zero outside the next() function. * - that entails, that locking is only needed inside next(). - * - the spokes 0..n_active-1 still might not have exhausted their + * - the assets 0..n_active-1 still might not have exhausted their * search space. - * - the spokes n_active..n_spokes-1 have exhausted their search space. + * - the assets n_active..n_assets-1 have exhausted their search space. */ public: /// Initialize diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 0ce92dd32e..fde4156058 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -41,8 +41,8 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Spoke::Completion::Completion(void) { - // A spoke has not been submitted yet. This initial signal lets the + Asset::Completion::Completion(void) { + // An asset has not been submitted yet. This initial signal lets the // first submission use the same consume-before-reuse handshake as all // subsequent submissions. done.signal(); @@ -50,13 +50,13 @@ namespace Gecode { namespace Search { namespace Par { template forceinline void - Spoke::Completion::terminated(void) { + Asset::Completion::terminated(void) { done.signal(); } template forceinline void - Spoke::Completion::wait(void) { + Asset::Completion::wait(void) { done.wait(); } @@ -65,7 +65,7 @@ namespace Gecode { namespace Search { namespace Par { CollectAll::CollectAll(void) : solutions(heap) {} forceinline bool - CollectAll::add(Space* s, Spoke*) { + CollectAll::add(Space* s, Asset*) { solutions.push(s); return true; } @@ -79,7 +79,7 @@ namespace Gecode { namespace Search { namespace Par { return solutions.empty(); } forceinline Space* - CollectAll::get(Spoke*&) { + CollectAll::get(Asset*&) { return solutions.pop(); } forceinline @@ -93,7 +93,7 @@ namespace Gecode { namespace Search { namespace Par { CollectBest::CollectBest(void) : b(nullptr), reporter(nullptr) {} forceinline bool - CollectBest::add(Space* s, Spoke* r) { + CollectBest::add(Space* s, Asset* r) { if ((b != nullptr) && !Search::better(*s,*b,"PBS::CollectBest::add")) { delete s; @@ -119,7 +119,7 @@ namespace Gecode { namespace Search { namespace Par { return reporter == nullptr; } forceinline Space* - CollectBest::get(Spoke*& r) { + CollectBest::get(Asset*& r) { assert(!empty()); r = reporter; reporter = nullptr; @@ -144,21 +144,21 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Spoke::Spoke(PBS* p, Engine* e, Stop* so) + Asset::Asset(PBS* p, Engine* e, Stop* so) : Support::Runnable(false), portfolio(p), engine(e), stop(so) {} template forceinline Statistics - Spoke::statistics(void) const { + Asset::statistics(void) const { return engine->statistics(); } template forceinline bool - Spoke::stopped(void) const { + Asset::stopped(void) const { return engine->stopped(); } template forceinline bool - Spoke::limited(void) const { + Asset::limited(void) const { #ifdef GECODE_HAS_EXPERIMENTAL return engine->limited(); #else @@ -167,26 +167,26 @@ namespace Gecode { namespace Search { namespace Par { } template forceinline Support::Terminator* - Spoke::terminator(void) const { + Asset::terminator(void) const { return const_cast(&completion); } template forceinline void - Spoke::wait(void) { + Asset::wait(void) { completion.wait(); } template forceinline void - Spoke::wake(void) { + Asset::wake(void) { static_cast(stop)->wake(); } template forceinline void - Spoke::constrain(const Space& b) { + Asset::constrain(const Space& b) { engine->constrain(b); } template - Spoke::~Spoke(void) { + Asset::~Asset(void) { delete engine; delete stop; } @@ -197,12 +197,12 @@ namespace Gecode { namespace Search { namespace Par { forceinline PBS::PBS(Engine** engines, Stop** stops, unsigned int n, const Statistics& stat0) - : stat(stat0), spokes(heap.alloc*>(n)), - n_spokes(n), n_active(n), - spoke_stop(false), incomplete(false), tostop(false), n_busy(0) { - // Initialize spokes - for (unsigned int i=0U; i(this,engines[i],stops[i]); + : stat(stat0), assets(heap.alloc*>(n)), + n_assets(n), n_active(n), + asset_stop(false), incomplete(false), tostop(false), n_busy(0) { + // Initialize assets + for (unsigned int i=0U; i(this,engines[i],stops[i]); static_cast(stops[i])->share(&tostop); } } @@ -210,14 +210,14 @@ namespace Gecode { namespace Search { namespace Par { template forceinline bool - PBS::report(Spoke* spoke, Space* s) { + PBS::report(Asset* asset, Space* s) { // If b is false the report should be repeated (solution was worse) bool b = true; bool wake = false; m.acquire(); if (s != nullptr) { try { - b = solutions.add(s,spoke); + b = solutions.add(s,asset); if (b) { tostop.store(true, std::memory_order_release); wake = true; @@ -229,29 +229,29 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } - } else if (spoke->stopped() && !spoke->limited()) { + } else if (asset->stopped() && !asset->limited()) { if (!tostop.load(std::memory_order_acquire)) { - spoke_stop.store(true, std::memory_order_release); + asset_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; } } else { - // The spoke is done or stopped at a local limit (then search is incomplete) - if (spoke->limited()) + // The asset is done or stopped at a local limit (then search is incomplete) + if (asset->limited()) incomplete = true; - // Move spoke to inactive + // Move asset to inactive unsigned int i=0; - while (spokes[i] != spoke) + while (assets[i] != asset) i++; assert(i < n_active); assert(n_active > 0); - std::swap(spokes[i],spokes[--n_active]); + std::swap(assets[i],assets[--n_active]); tostop.store(true, std::memory_order_release); wake = true; } if (wake) for (unsigned int i=0U; iwake(); + assets[i]->wake(); if (b) { if (--n_busy == 0) idle.signal(); @@ -268,7 +268,7 @@ namespace Gecode { namespace Search { namespace Par { failure = std::current_exception(); tostop.store(true, std::memory_order_release); for (unsigned int i=0U; iwake(); + assets[i]->wake(); if (--n_busy == 0) idle.signal(); m.release(); @@ -276,7 +276,7 @@ namespace Gecode { namespace Search { namespace Par { template void - Spoke::run(void) { + Asset::run(void) { try { Space* s; do { @@ -297,35 +297,35 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(f); } if (solutions.empty()) - spoke_stop.store(false, std::memory_order_release); + asset_stop.store(false, std::memory_order_release); while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !spoke_stop.load(std::memory_order_acquire)) { - // Clear the internal stop used to interrupt sibling spokes + !asset_stop.load(std::memory_order_acquire)) { + // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); - // Invariant: all spokes are idle! + // Invariant: all assets are idle! assert(n_busy == 0); assert(!tostop.load(std::memory_order_acquire)); - // Run all active spokes + // Run all active assets n_busy = n_active; for (unsigned int i=0U; iwait(); - Support::Thread::run(spokes[i]); + assets[i]->wait(); + Support::Thread::run(assets[i]); } m.release(); - // Wait for all spokes to become idle + // Wait for all assets to become idle idle.wait(); m.acquire(); } - // Invariant all spokes are idle! + // Invariant all assets are idle! assert(n_busy == 0); if (solutions.empty() && (n_active == 0) && incomplete) - spoke_stop.store(true, std::memory_order_release); + 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. @@ -341,13 +341,13 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.empty()) { s = nullptr; } else { - Spoke* r; + Asset* r; s = solutions.get(r); if (Collect::best) { try { for (unsigned int i=0U; iconstrain(*s); + if (assets[i] != r) + assets[i]->constrain(*s); } catch (...) { delete s; failure = std::current_exception(); @@ -365,7 +365,7 @@ namespace Gecode { namespace Search { namespace Par { template bool PBS::stopped(void) const { - return spoke_stop.load(std::memory_order_acquire); + return asset_stop.load(std::memory_order_acquire); } template @@ -373,8 +373,8 @@ namespace Gecode { namespace Search { namespace Par { PBS::statistics(void) const { assert(n_busy == 0); Statistics s(stat); - for (unsigned int i=0U; istatistics(); + for (unsigned int i=0U; istatistics(); return s; } @@ -388,7 +388,7 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.constrain(b)) { // The solution is better for (unsigned int i=0U; iconstrain(b); + assets[i]->constrain(b); } } catch (...) { failure = std::current_exception(); @@ -398,15 +398,15 @@ namespace Gecode { namespace Search { namespace Par { template PBS::~PBS(void) { - // A report can make n_busy zero before Spoke::run and Thread::Run::exec + // A report can make n_busy zero before Asset::run and Thread::Run::exec // have returned. Wait for the completion handshake before deleting the - // PBS-owned spokes. - for (unsigned int i=0U; iwait(); + // PBS-owned assets. + for (unsigned int i=0U; iwait(); assert(n_busy == 0); - for (unsigned int i=0U; i*>(spokes,n_spokes); + for (unsigned int i=0U; i*>(assets,n_assets); } }}} diff --git a/gecode/search/pbs.cpp b/gecode/search/pbs.cpp index 517f40c59c..70116536ac 100644 --- a/gecode/search/pbs.cpp +++ b/gecode/search/pbs.cpp @@ -46,12 +46,12 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, + pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, const Statistics& stat, const Search::Options& opt, bool best) { if (best) - return new PBS(spokes,stops,n_spokes,stat,opt); + return new PBS(assets,stops,n_assets,stat,opt); else - return new PBS(spokes,stops,n_spokes,stat,opt); + return new PBS(assets,stops,n_assets,stat,opt); } }}} @@ -73,12 +73,12 @@ namespace Gecode { namespace Search { namespace Par { } Engine* - pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, + pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, const Statistics& stat, bool best) { if (best) - return new PBS(spokes,stops,n_spokes,stat); + return new PBS(assets,stops,n_assets,stat); else - return new PBS(spokes,stops,n_spokes,stat); + return new PBS(assets,stops,n_assets,stat); } }}} diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 59694f30ba..b5d2a67c9e 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -40,10 +40,10 @@ namespace Gecode { namespace Search { /// Dispose partially constructed portfolio assets forceinline void - pbscleanup(Engine** spokes, Stop** stops, unsigned int n_spokes, + pbscleanup(Engine** assets, Stop** stops, unsigned int n_assets, Space* hub) { - for (unsigned int i=0U; i forceinline PbsCutoffs* - make_pbs_cutoffs(const Options& opt, unsigned int n_spokes) { + make_pbs_cutoffs(const Options& opt, unsigned int n_assets) { if (!PbsOwnsCutoff::value || (opt.cutoff == nullptr) || - (n_spokes < 2U)) + (n_assets < 2U)) return nullptr; return new PbsCutoffs(opt.cutoff); } @@ -272,7 +272,7 @@ namespace Gecode { namespace Search { namespace Seq { /// Create sequential portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, + pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, const Statistics& stat, const Search::Options& opt, bool best); }}} @@ -289,7 +289,7 @@ namespace Gecode { namespace Search { namespace Par { /// Create parallel portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** spokes, Stop** stops, unsigned int n_spokes, + pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, const Statistics& stat, bool best); }}} @@ -308,23 +308,23 @@ namespace Gecode { namespace Search { opt.threads = std::max(floor(opt.threads / static_cast(opt.assets)),1.0); - unsigned int n_spokes = opt.assets; - Engine** spokes = r.alloc(n_spokes); - Stop** stops = r.alloc(n_spokes); - for (unsigned int i=0U; i(n_assets); + Stop** stops = r.alloc(n_assets); + for (unsigned int i=0U; i >(opt,n_spokes); + PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { - for (unsigned int i=0U; i spoke((i == n_spokes-1) ? + std::unique_ptr spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; @@ -334,16 +334,16 @@ namespace Gecode { namespace Search { cutoff.reset(new PbsCutoff(cutoffs)); opt.cutoff = cutoff.get(); } - spokes[i] = build(spoke.get(),opt); + assets[i] = build(spoke.get(),opt); // The asset owns its cutoff (void) cutoff.release(); } Engine* e = Seq::pbsengine( - spokes,stops,n_spokes,stat,opt,E::best); + assets,stops,n_assets,stat,opt,E::best); release_pbs_cutoffs(cutoffs,true); return e; } catch (...) { - pbscleanup(spokes,stops,n_spokes,unowned_hub); + pbscleanup(assets,stops,n_assets,unowned_hub); release_pbs_cutoffs(cutoffs,false); throw; } @@ -355,41 +355,41 @@ namespace Gecode { namespace Search { const Search::Statistics& stat, Options& opt, bool best) { Region r; - int n_spokes = sebs.size(); - Engine** spokes = r.alloc(n_spokes); - Stop** stops = r.alloc(n_spokes); - for (int i=0; i(n_assets); + Stop** stops = r.alloc(n_assets); + for (int i=0; i(n_spokes)); + static_cast(n_assets)); Space* unowned_hub = hub; bool builders_owned = true; try { - for (int i=0; ioptions().stop,opt.stop); sebs[i]->options().stop = stops[i]; sebs[i]->options().clone = true; - std::unique_ptr spoke((i == n_spokes-1) ? + std::unique_ptr spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; (void) spoke->spoke(static_cast(i)); - spokes[i] = (*sebs[i])(spoke.get()); + assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Seq::pbsengine( - spokes,stops,static_cast(n_spokes),stat,opt,best); + assets,stops,static_cast(n_assets),stat,opt,best); } catch (...) { if (builders_owned) pbscleanup(sebs); - pbscleanup(spokes,stops,static_cast(n_spokes), + pbscleanup(assets,stops,static_cast(n_assets), unowned_hub); throw; } @@ -405,28 +405,28 @@ namespace Gecode { namespace Search { opt.clone = true; Region r; - // Limit the number of spokes to the number of threads - unsigned int n_spokes = std::min(static_cast(opt.threads), + // Limit the number of assets to the number of threads + unsigned int n_assets = std::min(static_cast(opt.threads), opt.assets); - // Redistribute additional threads to spokes - opt.threads = floor(opt.threads / static_cast(n_spokes)); + // Redistribute additional threads to assets + opt.threads = floor(opt.threads / static_cast(n_assets)); WrapTraceRecorder::engine(opt.tracer, - SearchTracer::EngineType::PBS, n_spokes); + SearchTracer::EngineType::PBS, n_assets); - Engine** spokes = r.alloc(n_spokes); - Stop** stops = r.alloc(n_spokes); - for (unsigned int i=0U; i(n_assets); + Stop** stops = r.alloc(n_assets); + for (unsigned int i=0U; i >(opt,n_spokes); + PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { - for (unsigned int i=0U; i spoke((i == n_spokes-1) ? + std::unique_ptr spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; @@ -436,15 +436,15 @@ namespace Gecode { namespace Search { cutoff.reset(new PbsCutoff(cutoffs)); opt.cutoff = cutoff.get(); } - spokes[i] = build(spoke.get(),opt); + assets[i] = build(spoke.get(),opt); // The asset owns its cutoff (void) cutoff.release(); } - Engine* e = Par::pbsengine(spokes,stops,n_spokes,stat,E::best); + Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); release_pbs_cutoffs(cutoffs,true); return e; } catch (...) { - pbscleanup(spokes,stops,n_spokes,unowned_hub); + pbscleanup(assets,stops,n_assets,unowned_hub); release_pbs_cutoffs(cutoffs,false); throw; } @@ -456,45 +456,45 @@ namespace Gecode { namespace Search { const Search::Statistics& stat, Options& opt, bool best) { Region r; - // Limit the number of spokes to the number of threads - int n_spokes = std::min(static_cast(opt.threads), + // Limit the number of assets to the number of threads + int n_assets = std::min(static_cast(opt.threads), sebs.size()); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, - static_cast(n_spokes)); + static_cast(n_assets)); - Engine** spokes = r.alloc(n_spokes); - Stop** stops = r.alloc(n_spokes); - for (int i=0; i(n_assets); + Stop** stops = r.alloc(n_assets); + for (int i=0; ioptions().stop,opt.stop, sebs[i]->options().worker_control); sebs[i]->options().stop = stops[i]; sebs[i]->options().clone = true; - std::unique_ptr spoke((i == n_spokes-1) ? + std::unique_ptr spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; (void) spoke->spoke(static_cast(i)); - spokes[i] = (*sebs[i])(spoke.get()); + assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Par::pbsengine( - spokes,stops,static_cast(n_spokes),stat,best); + assets,stops,static_cast(n_assets),stat,best); } catch (...) { if (builders_owned) pbscleanup(sebs); - pbscleanup(spokes,stops,static_cast(n_spokes), + pbscleanup(assets,stops,static_cast(n_assets), unowned_hub); throw; } diff --git a/gecode/search/rbs.cpp b/gecode/search/rbs.cpp index 3a09b23969..1b78157317 100644 --- a/gecode/search/rbs.cpp +++ b/gecode/search/rbs.cpp @@ -41,16 +41,16 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - rbsengine(Space* hub, Stop* stop, Engine* spoke, + rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best) { - return rbsengine(hub,stop,spoke,stat,opt,best,true); + return rbsengine(hub,stop,engine,stat,opt,best,true); } Engine* - rbsengine(Space* hub, Stop* stop, Engine* spoke, + rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best, bool complete) { - return new RBS(hub,static_cast(stop), spoke, + return new RBS(hub,static_cast(stop), engine, stat,opt,best,complete); } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 320ea723c6..89ffef358a 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -45,7 +45,7 @@ namespace Gecode { namespace Search { namespace Seq { /// Create restart engine whose first spoke search yields valid no-goods GECODE_SEARCH_EXPORT Engine* - rbsengine(Space* hub, Stop* stop, Engine* spoke, + rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best); @@ -53,11 +53,11 @@ 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 engine \a spoke. It only determines whether + * space explored by the first \a engine. It only determines whether * the no-goods of that search hold in the hub. */ GECODE_SEARCH_EXPORT Engine* - rbsengine(Space* hub, Stop* stop, Engine* spoke, + rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best, bool complete); diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 7d67d3e9b4..ef6cf4537b 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -47,17 +47,17 @@ namespace Gecode { namespace Search { namespace Seq { unsigned long long int l; }; - /// Stop object used for controlling spokes in a portfolio + /// Stop object used for controlling assets in a portfolio class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: - /// The stop object for the spokes + /// The stop object for the assets Stop* so; /// The stop object for the portfolio (possibly nullptr) Stop* po; /// Pointer to shared stop information SharedStopInfo* ssi; public: - /// Initialize with spoke stop \a so and portfolio stop \a po + /// Initialize with asset stop \a so and portfolio stop \a po PortfolioStop(Stop* so, Stop* po=nullptr); /// Initialize shared stop information void share(SharedStopInfo* ssi); @@ -65,8 +65,8 @@ namespace Gecode { namespace Search { namespace Seq { virtual bool stop(const Statistics& s, const Options& o); }; - /// Spoke engine in a sequential portfolio - class Spoke { + /// Asset engine in a sequential portfolio + class Asset { protected: /// The wrapped search engine Engine* engine; @@ -74,52 +74,52 @@ namespace Gecode { namespace Search { namespace Seq { Stop* stop; public: /// Default constructor - Spoke(void); + Asset(void); /// Copy constructor - Spoke(const Spoke& s) = default; + Asset(const Asset& s) = default; /// Assignment operator - Spoke& operator =(const Spoke& s) = default; - /// Initialize with engine \a s and its stop object \a so - void init(Engine* s, Stop* so); + Asset& operator =(const Asset& s) = default; + /// Initialize with engine \a e and its stop object \a so + void init(Engine* e, Stop* so); /// Return next solution Space* next(void); - /// Return statistics of spoke + /// Return statistics of asset Statistics statistics(void) const; - /// Check whether spoke has been stopped + /// Check whether asset has been stopped bool stopped(void) const; - /// Check whether spoke stopped at a local limit + /// Check whether asset stopped at a local limit bool limited(void) const; /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run void run(void); - /// Delete spoke - ~Spoke(void); + /// Delete asset + ~Asset(void); }; /// Sequential portfolio engine implementation template class GECODE_SEARCH_EXPORT PBS : public Engine { protected: - /// Initial statistics + /// Statistics of propagating the model and of removed assets Statistics stat; - /// Shared spoke information + /// Stop information shared by the assets SharedStopInfo ssi; /// Size of a slice unsigned int slice; - /// Spokes - Spoke* spokes; - /// Number of spoke engines - unsigned int n_spokes; - /// Current spoke to run + /// Assets + Asset* assets; + /// Number of asset engines + unsigned int n_assets; + /// Current asset to run unsigned int cur; - /// Whether a spoke has been stopped - bool spoke_stop; - /// Whether a spoke stopped at a local limit + /// Whether an asset has been stopped + bool asset_stop; + /// Whether an asset stopped at a local limit bool incomplete; public: /// Initialize - PBS(Engine** spokes, Stop** stops, unsigned int n, + PBS(Engine** assets, Stop** stops, 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); diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 47319b2301..4164993c59 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -46,26 +46,26 @@ namespace Gecode { namespace Search { namespace Seq { forceinline - Spoke::Spoke(void) + Asset::Asset(void) : engine(nullptr), stop(nullptr) {} forceinline void - Spoke::init(Engine* e, Stop* s) { - engine = e; stop = s; + Asset::init(Engine* e, Stop* so) { + engine = e; stop = so; } forceinline Space* - Spoke::next(void) { + Asset::next(void) { return engine->next(); } forceinline Statistics - Spoke::statistics(void) const { + Asset::statistics(void) const { return engine->statistics(); } forceinline bool - Spoke::stopped(void) const { + Asset::stopped(void) const { return engine->stopped(); } forceinline bool - Spoke::limited(void) const { + Asset::limited(void) const { #ifdef GECODE_HAS_EXPERIMENTAL return engine->limited(); #else @@ -73,11 +73,11 @@ namespace Gecode { namespace Search { namespace Seq { #endif } forceinline void - Spoke::constrain(const Space& b) { + Asset::constrain(const Space& b) { engine->constrain(b); } forceinline - Spoke::~Spoke(void) { + Asset::~Asset(void) { delete engine; delete stop; } @@ -89,13 +89,13 @@ namespace Gecode { namespace Search { namespace Seq { const Statistics& stat0, const Search::Options& opt) : stat(stat0), slice(opt.slice), - spokes(heap.alloc(n)), n_spokes(n), cur(0), - spoke_stop(false), incomplete(false) { + assets(heap.alloc(n)), n_assets(n), cur(0), + asset_stop(false), incomplete(false) { ssi.done = false; ssi.l = opt.slice; for (unsigned int i=0U; i(s[i])); + assets[i].init(e[i],static_cast(s[i])); static_cast(s[i])->share(&ssi); } } @@ -103,18 +103,18 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { - spoke_stop = false; + asset_stop = false; unsigned int n_exhausted = 0; - while (n_spokes > 0) { + while (n_assets > 0) { ssi.done = false; - if (Space* s = spokes[cur].next()) { - // Constrain other spokes + if (Space* s = assets[cur].next()) { + // Constrain other assets if (best) { try { for (unsigned int i=0U; i bool PBS::stopped(void) const { - return spoke_stop; + return asset_stop; } template Statistics PBS::statistics(void) const { Statistics s(stat); - for (unsigned int i=0U; i::constrain(const Space& b) { if (!best) throw NoBest("PBS::constrain"); - for (unsigned int i=0U; i PBS::~PBS(void) { - for (unsigned int i=0U; i Date: Sat, 14 Nov 2026 11:22:09 +0100 Subject: [PATCH 09/14] Describe when RBS and PBS call hub() and spoke() The hub() and spoke() documentation now matches the engines. RBS also calls spoke() when search starts and ignores that result. The default RBS hub() constrains with the last solution, if any, posts the no-goods, and returns true. The hub's result counts only after a solution, and returning false then skips spoke(). The default PBS hub() removes all branchers, so spoke() must post each asset's branching. The RBS and PBS class comments point to these functions. --- gecode/kernel/core.hpp | 63 ++++++++++++++++++------------------------ gecode/search.hh | 24 ++++++++-------- 2 files changed, 39 insertions(+), 48 deletions(-) diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 9694bf3ee3..a9ef08cbd5 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2194,23 +2194,23 @@ namespace Gecode { /** * \brief Hub configuration function for meta search engines * - * This configuration function is used by both restart and - * portfolio 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. * - * \li A restart meta search engine calls this function on its - * hub space whenever it finds a solution or exploration - * restarts. \a mi contains information about the current restart. + * The default function constrains the hub with the last + * solution, if any, posts the no-goods from \a mi, and + * returns true. * - * If a solution has been found, then search will continue with - * a restart id the function returns true, otherwise search - * will continue. + * \li Portfolio-based search (PBS) calls this function once on + * its hub before creating the assets. The result is ignored. * - * The default function posts no-goods obtained from \a mi. - * - * \li A portfolio meta engine calls this function once on - * the hub space. The return value is ignored. - * - * The default function removes all common branchers. + * The default function removes all branchers, so the spoke() + * function must post the branching for each asset. * * \ingroup TaskModelScript */ @@ -2219,28 +2219,19 @@ namespace Gecode { /** * \brief Spoke configuration function for meta search engines * - * This configuration function is used by both restart and - * portfolio meta search engines. - * - * \li A restart meta search engine calls this function on its - * spoke space when search starts and whenever it finds a solution or - * exploration restarts. \a mi contains information about the - * current restart. - * - * If the function returns true, the search on the spoke space is - * considered complete, i.e., if it fails or exhaustively explores the - * entire search space, the meta search engine finishes. If the - * function returns false, the search on the spoke space is considered - * incomplete, and the meta engine will restart the search regardless - * of whether the search on the spoke space finishes or times out. - * The no-goods recorded by an incomplete search only hold in the - * spoke's search space, so the meta engine does not pass them to the - * hub configuration function. This also holds for the first - * search when search starts. - * - * \li A portfolio meta engine calls this function once on each asset - * (that is, on each spoke) and passes the number of the asset, - * starting from zero. + * \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. + * + * \li PBS calls this function once on the spoke of each asset, + * a clone of the hub, and passes the asset number, starting + * from zero. The result is ignored. * * The default function does nothing and returns true. * diff --git a/gecode/search.hh b/gecode/search.hh index 78c5865182..05d2a8057c 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1460,10 +1460,9 @@ namespace Gecode { * and * \code virtual bool spoke(const MetaInfo& mi) \endcode * - * Whenever exploration restarts or a solution is found, the - * engine executes the functions on the hub and spoke - * spaces. For more details, consult "Modeling and Programming - * with Gecode". + * 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. * * \ingroup TaskModelSearch */ @@ -1488,10 +1487,9 @@ namespace Gecode { * and * \code virtual bool spoke(const MetaInfo& mi) \endcode * - * Whenever exploration restarts or a solution is found, the - * engine executes the functions on the hub and spoke - * spaces. For more details, consult "Modeling and Programming - * with Gecode". + * 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. * * \ingroup TaskModelSearch */ @@ -1556,8 +1554,9 @@ namespace Gecode { * and * \code virtual bool spoke(const MetaInfo& mi) \endcode * - * When the assets are created, these functions are executed. - * For more details, consult "Modeling and Programming with Gecode". + * 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. * * \ingroup TaskModelSearch */ @@ -1605,8 +1604,9 @@ namespace Gecode { * and * \code virtual bool spoke(const MetaInfo& mi) \endcode * - * When the assets are created, these functions are executed. - * For more details, consult "Modeling and Programming with Gecode". + * 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. * * \ingroup TaskModelSearch */ From f2e127738c6cec33e1585a46b20f7f16cb606623 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 11:26:54 +0100 Subject: [PATCH 10/14] Tighten the hub and spoke dispatch tests PBS spoke-only models now post their branching in spoke(), as the default hub() requires, and every PBS dispatch case checks that its solution is assigned. A new case keeps that branching out and expects an unassigned solution, showing that the default hub() removes the model's branchers. Another case makes the first RBS spoke reach the cutoff and checks the exact hub() and spoke() calls of a limit restart. A parallel case records that PBS runs only as many assets as it has threads. The rename had added a no-op spoke() override to an existing test space; it is gone. The new enums use PascalCase constants, and the SEB portfolio test names its thread counts and options for the portfolio and the assets. --- test/search.cpp | 270 ++++++++++++++++++++++++++++++------------------ 1 file changed, 170 insertions(+), 100 deletions(-) diff --git a/test/search.cpp b/test/search.cpp index 61e7ecd811..e1cddede19 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -672,11 +672,6 @@ namespace Test { } return false; } - /// Use the default completeness contract for each derived exploration - bool - spoke(const MetaInfo&) override { - return true; - } }; /// Return a bit for restart reason \a r @@ -705,17 +700,23 @@ namespace Test { bool solution_spoke_complete = true; bool fail_solution_spoke = false; bool nogood_model = false; + /// 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 + bool limit_first_spoke = false; }; /// Common implementation for meta-search dispatch test spaces class MetaDispatchSpace : public Space { protected: /// RBS role of a space - enum class RestartRole { HUB, SPOKE }; + enum class RestartRole { Hub, Spoke }; /// Variable used to provide two solutions IntVar x; /// Optional queens model used to force restart no-good extraction IntVarArray q; + /// Optional variables without a solution, used to reach the cutoff + IntVarArray y; /// Shared hook observations and configuration MetaDispatchState* state; /// RBS role retained across cloning @@ -730,7 +731,7 @@ namespace Test { if (mi.type() == MetaInfo::PORTFOLIO) // PBS must ignore the callback result. return false; - restart_role = RestartRole::HUB; + 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)) @@ -744,11 +745,20 @@ namespace Test { if (mi.type() == MetaInfo::PORTFOLIO) { portfolio_asset = static_cast(mi.asset()); state->assets.fetch_or(1U << mi.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; } state->spoke_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); - restart_role = RestartRole::SPOKE; + restart_role = RestartRole::Spoke; + if ((mi.reason() == MetaInfo::RR_INIT) && 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; @@ -757,8 +767,8 @@ namespace Test { public: /// Initialize with shared observations \a s MetaDispatchSpace(MetaDispatchState& s) - : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), state(&s), restart_role(RestartRole::HUB), - portfolio_asset(-1) { + : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), y(*this, s.limit_first_spoke ? 4 : 0, 0, 2), + state(&s), restart_role(RestartRole::Hub), portfolio_asset(-1) { state->live_spaces.fetch_add(1, std::memory_order_relaxed); if (state->nogood_model) { distinct(*this, IntArgs::create(q.size(), 0, 1), q, IPL_VAL); @@ -775,6 +785,7 @@ namespace Test { state->copies.fetch_add(1, std::memory_order_relaxed); x.update(*this, s.x); q.update(*this, s.q); + y.update(*this, s.y); } /// Record destruction for clone-ownership checks ~MetaDispatchSpace(void) override { @@ -784,14 +795,14 @@ namespace Test { void constrain(const Space& s) override { state->constrain_calls.fetch_add(1, std::memory_order_relaxed); - if (restart_role == RestartRole::HUB) + if (restart_role == RestartRole::Hub) state->constrain_hub_calls.fetch_add(1, std::memory_order_relaxed); else state->constrain_spoke_calls.fetch_add(1, std::memory_order_relaxed); if (portfolio_asset >= 0) { const unsigned int asset = 1U << static_cast(portfolio_asset); state->constrain_asset_mask.fetch_or(asset, std::memory_order_relaxed); - if (restart_role == RestartRole::HUB) + if (restart_role == RestartRole::Hub) state->constrain_hub_asset_mask.fetch_or(asset, std::memory_order_relaxed); else state->constrain_spoke_asset_mask.fetch_or(asset, std::memory_order_relaxed); @@ -808,6 +819,11 @@ namespace Test { value(void) const { return x.val(); } + /// Return whether the solution variable is assigned + bool + assigned(void) const { + return x.assigned(); + } }; /// Dispatch test space overriding only Hub @@ -877,24 +893,27 @@ namespace Test { public: /// Dispatch scenario enum class Scenario { - RBS_HUB_ONLY, - RBS_SPOKE_ONLY, - RBS_HUB_CONTINUE, - RBS_HUB_RESTART, - RBS_SPOKE_COMPLETE, - RBS_SPOKE_INCOMPLETE, - PBS_HUB_ONLY, - PBS_SPOKE_ONLY, - PBS_SINGLE, - PBS_SEQUENTIAL_HUB_ONLY, - PBS_SEQUENTIAL_SPOKE_ONLY, - PBS_SEQUENTIAL, - PBS_PARALLEL_HUB_ONLY, - PBS_PARALLEL_SPOKE_ONLY, - PBS_PARALLEL, - RBS_NOGOODS_RESET_OWNERSHIP, - META_STOP_OWNERSHIP, - BAB_INCUMBENT + RbsHubOnly, + RbsSpokeOnly, + RbsHubContinue, + RbsHubRestart, + RbsSpokeComplete, + RbsSpokeIncomplete, + RbsLimit, + PbsHubOnly, + PbsSpokeOnly, + PbsSingle, + PbsSequentialHubOnly, + PbsSequentialSpokeOnly, + PbsSequential, + PbsParallelHubOnly, + PbsParallelSpokeOnly, + PbsParallel, + PbsParallelThreadLimit, + PbsDefaultHubRemovesBranchers, + RbsNoGoodsResetOwnership, + MetaStopOwnership, + BabIncumbent }; protected: @@ -979,11 +998,50 @@ namespace Test { delete m; Model* solution = search.next(); - bool ok = (solution != nullptr) && holds(state.hub_calls, hub_calls) && + bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, hub_calls) && holds(state.spoke_calls, spoke_calls) && holds(state.assets, asset_mask); delete solution; return ok; } + /// Check that the default PBS hub() removes the model's branching + static bool + pbs_default_hub_removes_branchers(void) { + MetaDispatchState state; + state.spoke_branching = false; + 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; + } + /// Check RBS dispatch when the first spoke reaches the cutoff + static bool + rbs_limit(void) { + MetaDispatchState state; + state.limit_first_spoke = true; + HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); + Gecode::Search::Options o; + o.threads = 1; + // No-goods from the first spoke would refer to its own brancher. + o.nogoods_limit = 0; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS search(m, o); + 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_reasons, reason_bit(MetaInfo::RR_LIM)) && + holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_LIM)); + delete solution; + return ok; + } /// Exercise RBS no-good posting, reset, and clone ownership static bool rbs_nogoods_reset_ownership(void) { @@ -1108,14 +1166,14 @@ namespace Test { outer.assets = 3; outer.threads = 1; Gecode::Search::Options inner[3]; - SEBs spokes(3); + SEBs assets(3); for (int i = 0; i < 3; i++) { inner[i].threads = 1; // Each RBS engine owns and deletes its cutoff. inner[i].cutoff = Gecode::Search::Cutoff::constant(100); - spokes[i] = Gecode::rbs(inner[i]); + assets[i] = Gecode::rbs(inner[i]); } - Gecode::PBS search(m, spokes, outer); + Gecode::PBS search(m, assets, outer); delete m; HubSpokeDispatchSpace* best = nullptr; while (HubSpokeDispatchSpace* solution = search.next()) { @@ -1137,41 +1195,48 @@ namespace Test { bool run(void) override { switch (scenario) { - case Scenario::RBS_HUB_ONLY: + case Scenario::RbsHubOnly: return rbs_dispatch(1, 0); - case Scenario::RBS_SPOKE_ONLY: + case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); - case Scenario::RBS_HUB_CONTINUE: + case Scenario::RbsHubContinue: return rbs(false, false, true); - case Scenario::RBS_HUB_RESTART: + case Scenario::RbsHubRestart: return rbs(true, false, true); - case Scenario::RBS_SPOKE_COMPLETE: + case Scenario::RbsSpokeComplete: return rbs(true, true, true); - case Scenario::RBS_SPOKE_INCOMPLETE: + case Scenario::RbsSpokeIncomplete: return rbs(true, true, false); - case Scenario::PBS_HUB_ONLY: + case Scenario::RbsLimit: + return rbs_limit(); + case Scenario::PbsHubOnly: return pbs(1, 1, 1, 0, 0); - case Scenario::PBS_SPOKE_ONLY: + case Scenario::PbsSpokeOnly: return pbs(1, 1, 0, 1, 1); - case Scenario::PBS_SINGLE: + case Scenario::PbsSingle: return pbs(1, 1, 1, 1, 1); - case Scenario::PBS_SEQUENTIAL_HUB_ONLY: + case Scenario::PbsSequentialHubOnly: return pbs(3, 1, 1, 0, 0); - case Scenario::PBS_SEQUENTIAL_SPOKE_ONLY: + case Scenario::PbsSequentialSpokeOnly: return pbs(3, 1, 0, 3, 7); - case Scenario::PBS_SEQUENTIAL: + case Scenario::PbsSequential: return pbs(3, 1, 1, 3, 7); - case Scenario::PBS_PARALLEL_HUB_ONLY: + case Scenario::PbsParallelHubOnly: return pbs(3, 3, 1, 0, 0); - case Scenario::PBS_PARALLEL_SPOKE_ONLY: + case Scenario::PbsParallelSpokeOnly: return pbs(3, 3, 0, 3, 7); - case Scenario::PBS_PARALLEL: + case Scenario::PbsParallel: return pbs(3, 3, 1, 3, 7); - case Scenario::RBS_NOGOODS_RESET_OWNERSHIP: + case Scenario::PbsParallelThreadLimit: + // Parallel PBS runs only as many assets as it has threads. + return pbs(3, 2, 1, 2, 3); + case Scenario::PbsDefaultHubRemovesBranchers: + return pbs_default_hub_removes_branchers(); + case Scenario::RbsNoGoodsResetOwnership: return rbs_nogoods_reset_ownership(); - case Scenario::META_STOP_OWNERSHIP: + case Scenario::MetaStopOwnership: return meta_stop_ownership(); - case Scenario::BAB_INCUMBENT: + case Scenario::BabIncumbent: return bab_incumbent(); default: GECODE_NEVER; @@ -3032,35 +3097,36 @@ namespace Test { /// Whether best solution search is used bool best; /// Number of portfolio threads - unsigned int mt; - /// Number of spoke threads - unsigned int st; + unsigned int portfolio_threads; + /// Number of threads of each asset + unsigned int asset_threads; public: /// Initialize test - SEBPBS(const std::string& e, bool b, unsigned int mt0, unsigned int st0) - : Test("PBS::SEB::"+e+"::"+Model::name()+"::"+str(mt0)+"::"+str(st0), - HTB_BINARY,HTB_BINARY,HTB_BINARY), best(b), mt(mt0), st(st0) {} + SEBPBS(const std::string& e, bool b, unsigned int portfolio_threads0, unsigned int asset_threads0) + : Test("PBS::SEB::"+e+"::"+Model::name()+"::"+str(portfolio_threads0)+"::"+str(asset_threads0), + HTB_BINARY,HTB_BINARY,HTB_BINARY), best(b), + portfolio_threads(portfolio_threads0), asset_threads(asset_threads0) {} /// Run test virtual bool run(void) { using namespace Gecode; Model* m = new Model(htb1,htb2,htb3); Gecode::Search::FailStop f(2); - Gecode::Search::Options mo; - mo.threads = mt; - mo.d_l = 100; - mo.stop = &f; + Gecode::Search::Options portfolio_options; + portfolio_options.threads = portfolio_threads; + portfolio_options.d_l = 100; + portfolio_options.stop = &f; - Gecode::Search::Options so; - so.threads = st; - so.d_l = 100; - so.cutoff = Gecode::Search::Cutoff::constant(1000000); + Gecode::Search::Options asset_options; + asset_options.threads = asset_threads; + asset_options.d_l = 100; + asset_options.cutoff = Gecode::Search::Cutoff::constant(1000000); if (best) { SEBs sebs(3); - sebs[0] = bab(so); - sebs[1] = bab(so); - sebs[2] = rbs(so); - Gecode::PBS pbs(m, sebs, mo); + sebs[0] = bab(asset_options); + sebs[1] = bab(asset_options); + sebs[2] = rbs(asset_options); + Gecode::PBS pbs(m, sebs, portfolio_options); delete m; Model* b = nullptr; @@ -3078,10 +3144,10 @@ namespace Test { return ok; } else { SEBs sebs(3); - sebs[0] = dfs(so); - sebs[1] = lds(so); - sebs[2] = rbs(so); - Gecode::PBS pbs(m, sebs, mo); + sebs[0] = dfs(asset_options); + sebs[1] = lds(asset_options); + sebs[2] = rbs(asset_options); + Gecode::PBS pbs(m, sebs, portfolio_options); int n = 3 * m->solutions(); delete m; @@ -3355,16 +3421,17 @@ namespace Test { c_d,a_d,t); } // Restart-based search - (void)new MetaDispatch("RBS::HubOnly", MetaDispatch::Scenario::RBS_HUB_ONLY); - (void)new MetaDispatch("RBS::SpokeOnly", MetaDispatch::Scenario::RBS_SPOKE_ONLY); - (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RBS_HUB_CONTINUE); - (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RBS_HUB_RESTART); - (void)new MetaDispatch("RBS::SpokeComplete", MetaDispatch::Scenario::RBS_SPOKE_COMPLETE); - (void)new MetaDispatch("RBS::SpokeIncomplete", MetaDispatch::Scenario::RBS_SPOKE_INCOMPLETE); + (void)new MetaDispatch("RBS::HubOnly", MetaDispatch::Scenario::RbsHubOnly); + (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::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", - MetaDispatch::Scenario::RBS_NOGOODS_RESET_OWNERSHIP); - (void)new MetaDispatch("Lifecycle::StopOwnership", MetaDispatch::Scenario::META_STOP_OWNERSHIP); - (void)new MetaDispatch("BAB::Incumbent", MetaDispatch::Scenario::BAB_INCUMBENT); + MetaDispatch::Scenario::RbsNoGoodsResetOwnership); + (void)new MetaDispatch("Lifecycle::StopOwnership", MetaDispatch::Scenario::MetaStopOwnership); + (void)new MetaDispatch("BAB::Incumbent", MetaDispatch::Scenario::BabIncumbent); for (unsigned int t=1; t<=4; t++) { (void) new RBS("DFS",t); (void) new RBS("LDS",t); @@ -3377,16 +3444,19 @@ namespace Test { (void) new RBS("BAB",t); } // Portfolio-based search - (void)new MetaDispatch("PBS::HubOnly", MetaDispatch::Scenario::PBS_HUB_ONLY); - (void)new MetaDispatch("PBS::SpokeOnly", MetaDispatch::Scenario::PBS_SPOKE_ONLY); - (void)new MetaDispatch("PBS::Single", MetaDispatch::Scenario::PBS_SINGLE); - (void)new MetaDispatch("PBS::SequentialHubOnly", MetaDispatch::Scenario::PBS_SEQUENTIAL_HUB_ONLY); - (void)new MetaDispatch("PBS::SequentialSpokeOnly", MetaDispatch::Scenario::PBS_SEQUENTIAL_SPOKE_ONLY); - (void)new MetaDispatch("PBS::Sequential", MetaDispatch::Scenario::PBS_SEQUENTIAL); + (void)new MetaDispatch("PBS::HubOnly", MetaDispatch::Scenario::PbsHubOnly); + (void)new MetaDispatch("PBS::SpokeOnly", MetaDispatch::Scenario::PbsSpokeOnly); + (void)new MetaDispatch("PBS::Single", MetaDispatch::Scenario::PbsSingle); + (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); #ifdef GECODE_HAS_THREADS - (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PBS_PARALLEL_HUB_ONLY); - (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PBS_PARALLEL_SPOKE_ONLY); - (void)new MetaDispatch("PBS::Parallel", MetaDispatch::Scenario::PBS_PARALLEL); + (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PbsParallelHubOnly); + (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PbsParallelSpokeOnly); + (void)new MetaDispatch("PBS::Parallel", MetaDispatch::Scenario::PbsParallel); + (void)new MetaDispatch("PBS::ParallelThreadLimit", MetaDispatch::Scenario::PbsParallelThreadLimit); #endif for (unsigned int a=1; a<=4; a++) for (unsigned int t=1; t<=2*a; t++) { @@ -3401,14 +3471,14 @@ namespace Test { (void) new PBS("BAB",true,a,t); } // Portfolio-based search using SEBs - for (unsigned int mt=1; mt<=3; mt += 2) - for (unsigned int st=1; st<=8; st++) { - (void) new SEBPBS("BAB",true,mt,st); - (void) new SEBPBS("BAB",true,mt,st); - (void) new SEBPBS("BAB",true,mt,st); - (void) new SEBPBS("DFS+LDS",false,mt,st); - (void) new SEBPBS("DFS+LDS",false,mt,st); - (void) new SEBPBS("DFS+LDS",false,mt,st); + for (unsigned int pt=1; pt<=3; pt += 2) + for (unsigned int at=1; at<=8; at++) { + (void) new SEBPBS("BAB",true,pt,at); + (void) new SEBPBS("BAB",true,pt,at); + (void) new SEBPBS("BAB",true,pt,at); + (void) new SEBPBS("DFS+LDS",false,pt,at); + (void) new SEBPBS("DFS+LDS",false,pt,at); + (void) new SEBPBS("DFS+LDS",false,pt,at); } } }; From 48152430219f5472a775118cb8015185cacdcddd Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 18:55:29 +0100 Subject: [PATCH 11/14] Make the hook compile-fail tests fail for the deleted hooks only The single fail fixture overrode slave() without override and master() with it. The master() override fails even if Space no longer deletes the old hooks, since override then names no virtual function, so the test could never catch a lost deletion. Split it into hub-spoke-api-fail-master and hub-spoke-api-fail-slave. Each is the pass fixture with one hook replaced by an old override without override. The tests now require the deleted-function diagnostic of Clang or GCC instead of any failure; MSVC words it differently, so there they only require the build to fail. Both still require the pass test. --- CMakeLists.txt | 28 +++++--- test/search/hub-spoke-api-fail-master.cpp | 64 +++++++++++++++++++ ...-fail.cpp => hub-spoke-api-fail-slave.cpp} | 48 ++++++++------ test/search/hub-spoke-api-pass.cpp | 15 +++-- 4 files changed, 120 insertions(+), 35 deletions(-) create mode 100644 test/search/hub-spoke-api-fail-master.cpp rename test/search/{hub-spoke-api-fail.cpp => hub-spoke-api-fail-slave.cpp} (63%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 412af949e3..1a66c12d92 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1476,9 +1476,12 @@ 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 Gecode 6 - # master()/slave() overrides must not. - foreach(api pass fail) + # 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} @@ -1488,12 +1491,19 @@ if(BUILD_TESTING) set_tests_properties(hub-spoke-api-pass PROPERTIES FIXTURES_SETUP hub-spoke-api RESOURCE_LOCK gecode-test-build) - # The failing fixture stays out of the compilation database used for lint. - set_target_properties(hub-spoke-api-fail PROPERTIES EXPORT_COMPILE_COMMANDS OFF) - set_tests_properties(hub-spoke-api-fail PROPERTIES - WILL_FAIL TRUE - FIXTURES_REQUIRED 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) diff --git a/test/search/hub-spoke-api-fail-master.cpp b/test/search/hub-spoke-api-fail-master.cpp new file mode 100644 index 0000000000..f1e08c09d8 --- /dev/null +++ b/test/search/hub-spoke-api-fail-master.cpp @@ -0,0 +1,64 @@ +/* + * 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.cpp b/test/search/hub-spoke-api-fail-slave.cpp similarity index 63% rename from test/search/hub-spoke-api-fail.cpp rename to test/search/hub-spoke-api-fail-slave.cpp index 3b4e10ba6c..f8b3070fb2 100644 --- a/test/search/hub-spoke-api-fail.cpp +++ b/test/search/hub-spoke-api-fail-slave.cpp @@ -28,31 +28,37 @@ * 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 overrides the Gecode 6 meta-search - * hooks that Gecode 7 renamed to hub() and spoke() and deletes in - * Space. Successful compilation means that an old override would - * again compile and silently never be called. + * 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 -class HubSpokeApiFail : public Gecode::Space { -public: - HubSpokeApiFail(void) {} - HubSpokeApiFail(HubSpokeApiFail& s) : Gecode::Space(s) {} - Gecode::Space* - copy(void) override { - return new HubSpokeApiFail(*this); - } - virtual bool - slave(const Gecode::MetaInfo&) { - return true; - } - bool - master(const Gecode::MetaInfo&) override { - return true; - } -}; +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 index 772f81819a..9c684f6ac8 100644 --- a/test/search/hub-spoke-api-pass.cpp +++ b/test/search/hub-spoke-api-pass.cpp @@ -28,20 +28,25 @@ * 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 { - /// Compile-pass fixture for the Gecode 7 meta-search hooks - class HubSpokeApiPass : public Gecode::Space { + /// Space overriding the meta-search hooks + class HookSpace : public Gecode::Space { public: - HubSpokeApiPass(void) {} - HubSpokeApiPass(HubSpokeApiPass& s) : Gecode::Space(s) {} + HookSpace(void) {} + HookSpace(HookSpace& s) : Gecode::Space(s) {} Gecode::Space* copy(void) override { - return new HubSpokeApiPass(*this); + return new HookSpace(*this); } bool hub(const Gecode::MetaInfo&) override { From 54d83389fad0a828127fcdba5de3588431d6ae70 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 18:55:40 +0100 Subject: [PATCH 12/14] Run the hub and spoke compile tests in the Ninja CI check The Ninja job's Check step selected only build-gecode-test and test, so the compile tests for the meta-search hooks never ran in CI. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e136eefe47..92ed3278c0 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)$' + --output-on-failure -R '^(build-gecode-test|test|hub-spoke-api-.*)$' - name: Configure CMake Debug audit smoke shell: bash From e814cfd731f56e5435571bf5b601d5b442863298 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 19:01:31 +0100 Subject: [PATCH 13/14] Say when RBS ends after hub() and which space a PBS spoke is If the hub fails after hub(), RBS ends. The last PBS asset searches the hub itself, so its spoke is the hub or a clone of it, not always a clone. --- gecode/kernel/core.hpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index a9ef08cbd5..548efb571c 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2201,6 +2201,8 @@ namespace Gecode { * 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 @@ -2230,8 +2232,8 @@ namespace Gecode { * holds for the first search when search starts. * * \li PBS calls this function once on the spoke of each asset, - * a clone of the hub, and passes the asset number, starting - * from zero. The result is ignored. + * the hub or a clone of it, and passes the asset number, + * starting from zero. The result is ignored. * * The default function does nothing and returns true. * From 42b7e8a961f2e24ecbb756fb37c663d295943f73 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 19:01:32 +0100 Subject: [PATCH 14/14] Trim the hub and spoke migration notes to what porting needs Drop the origin of the names and the comparison with other solvers, and say which space each hook runs on. --- docs/gecode-7-migration.md | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index a008778374..26156e5728 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -20,20 +20,17 @@ 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 names come from a wheel. The hub is the persistent centre: in RBS it -carries the last solution and the no-goods from one restart to the next, -and in PBS it is the common model. Each spoke is a disposable clone of the -hub: RBS searches one spoke per restart, and PBS searches one spoke per -asset. A spoke is not a long-lived peer that exchanges information with the -hub, which is what hub and spoke means in some other solvers, such as -mpi-sppy. - -- RBS calls `hub()` after each solution and at each restart, and `spoke()` - on each new spoke, 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 clones one spoke per asset and calls - `spoke()` on it with the asset number. The default `hub()` removes all - branchers, so `spoke()` must post the branching of each asset. +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. The examples show typical overrides: