diff --git a/changelog.in b/changelog.in index 5da2d434d0..6fc63ee08e 100755 --- a/changelog.in +++ b/changelog.in @@ -75,15 +75,158 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Advance the generator that a cutoff generator from Cutoff::repeat() +repeats. +[MORE] +It read the current value of that generator without advancing it, so after +the first value it repeated the same value forever. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Delete the spoke of restart-based search when spoke() throws an exception at +a restart. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Do not let a brancher that hub() posts take the identity of a brancher that +spoke() posted earlier. +[MORE] +Restart-based search then posted the no-goods of that spoke for the wrong +brancher, which could lose solutions. + +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Throw Search::SpokeNoBrancher when a spoke of portfolio search has no +brancher but the hub had branchers, unless the spoke failed. +[MORE] +The default hub() removes all branchers, so a spoke() that forgot to post +the branching of its asset returned the unassigned spoke as a solution. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Propagate the hub of portfolio search after hub() and before cloning the +spokes. +[MORE] +A hub() that posted a constraint made the portfolio throw SpaceNotStable. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Constrain the hub of restart-based branch-and-bound search with each +solution in the engine itself. +[MORE] +The default hub() did it, so an override that did not call the default lost +the bound and found the same solutions again. + +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Keep the other assets of a portfolio running when the stop object of an +engine builder stops its engine. +[MORE] +The whole portfolio stopped instead. The stopped asset is now parked until +the next call to next(). + +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Check the stop object of a portfolio with the statistics of the whole +portfolio. +[MORE] +It was checked for each asset with the statistics of that asset. See +docs/gecode-7-migration.md. + +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Run every asset of a parallel portfolio, also when there are more assets +than threads. +[MORE] +Parallel portfolio search ran only as many assets as it had threads and +silently dropped the others. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +End a portfolio when an asset exhausts its search space. +[MORE] +The exhausted asset proves that no further solution exists, so the other +assets no longer run until they are stopped. An asset whose spoke declares +SpokeCoverage::Partial is still dropped. + +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Report limited discrepancy search at its discrepancy limit as incomplete. + +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Replace stopped() of search engines by end_reason(). +[MORE] +end_reason() tells why next() returned no solution: EndReason::Exhausted is a +proof, EndReason::Incomplete is an end without one, and EndReason::Limit is a +stop. stopped() and the experimental limited() are removed. FlatZinc reports +optimality or unsatisfiability only for an exhausted search. See +docs/gecode-7-migration.md. + +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Give each restart-based asset of a portfolio its own copy of the cutoff. +[MORE] +Cutoff has a new pure virtual function copy(), which custom cutoff generators +must implement. Copies of a random cutoff use different seeds, so the assets +can restart at different times. A portfolio with a single asset that does not +declare SpokeCoverage::Partial uses the cutoff itself. See +docs/gecode-7-migration.md. + [ENTRY] Module: search What: change Rank: major [DESCRIPTION] -Rename the meta-search Space hooks master() and slave() to hub() and spoke(). +Replace the meta-search Space hooks master() and slave() and the class +MetaInfo by hub(HubContext&) and spoke(SpokeContext&). [MORE] -There are no compatibility aliases. An old override marked override fails to -compile; one without it is never called. See docs/gecode-7-migration.md. +hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of +returning a Boolean. Restart-based search also calls hub() when search +starts and after an episode that ends without a proof. There are no +compatibility aliases, also not for the FlatZincSpace override of slave(). +See docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 0e20ce7921..8053b8cc5a 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -1,8 +1,8 @@ # Gecode 7 migration notes -## Meta-search hooks: master() and slave() are now hub() and spoke() +## Meta-search hooks: hub() and spoke() take contexts -Rename the overrides. Their signatures and return values are unchanged: +The hooks `master()` and `slave()` and the class `MetaInfo` are replaced: ```cpp // Gecode 6 @@ -10,32 +10,185 @@ bool master(const Gecode::MetaInfo& mi) override; bool slave(const Gecode::MetaInfo& mi) override; // Gecode 7 -bool hub(const Gecode::MetaInfo& mi) override; -bool spoke(const Gecode::MetaInfo& mi) override; +void hub(Gecode::HubContext& hc) override; +void spoke(Gecode::SpokeContext& sc) override; ``` -There are no compatibility aliases. An old override marked `override` fails -to compile; one without it compiles but is never called. Restart-based search (RBS) and portfolio-based search -(PBS) call the renamed hooks at the same points and with the same defaults -as before. +There are no compatibility aliases. `MetaInfo` no longer exists, so an old +override fails to compile. Restart-based search (RBS) calls `hub()` on its +hub and `spoke()` on each spoke, a clone of the hub that one episode +searches. Portfolio-based search (PBS) calls `hub()` once and `spoke()` on +the spoke of each asset. -The hooks run on these spaces: +Both contexts provide what `MetaInfo` provided: -- 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. +| Gecode 6 | Gecode 7 | +|----------------------------------------|----------------------------------------------------| +| `mi.type()`: `RESTART`, `PORTFOLIO` | `engine()`: `MetaEngine::Restart`, `Portfolio` | +| `mi.reason()`: `RR_INIT` | `event()`: `MetaEvent::Start` | +| `RR_SOL` | `MetaEvent::Solution` | +| `RR_LIM` | `MetaEvent::Limit` | +| `RR_CMPL` | `MetaEvent::Exhausted` | +| (none) | `MetaEvent::Incomplete`, such as LDS at its limit | +| `RR_NO` (portfolio) | `MetaEvent::Start` | +| `mi.restart()` | `episode()` | +| `mi.fail()` | `statistics().fail` | +| `mi.solution()` | none: `event()` tells whether there was a solution | +| `mi.last()` | `last()` | +| `mi.nogoods()` | `nogoods()` | +| `mi.asset()` | `asset()`, and `assets()` for their number | + +`episode()` counts from zero and increases by one for every new spoke, +whatever ended the previous episode. In `hub()` it is the episode that +ended, in `spoke()` the episode that starts. `statistics()` holds the +statistics of the episode that ended. `last()` is only valid while the hook +runs; clone the solution to keep it. + +The return values become explicit decisions: + +| Gecode 6 | Gecode 7 | +|----------------------------------------|--------------------------------------------------------| +| `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | +| `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | +| (none) | `hc.decision(MetaDecision::Continue)` after a limit | +| (none) | `hc.decision(MetaDecision::Finish)` | +| `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | +| `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | +| (none) | `sc.coverage(SpokeCoverage::Reduced)` | + +`Continue` is only legal after `MetaEvent::Solution` and `MetaEvent::Limit`; +setting it for another event throws `IllegalMetaDecision`. `Finish` ends the +engine with `EndReason::Incomplete`. To prove that no further solution +exists, fail the hub. + +The coverage tells the engine what a spoke covers of the hub's search space: + +- `Full`: the spoke adds only branching and constraints that the hub + implies. Exhausting it is a proof, and its no-goods hold in the hub. +- `Reduced`: the spoke prunes solutions but keeps one, or an optimal one, if + any exists, such as symmetry breaking. Exhausting it is a proof, but its + no-goods do not hold in the hub. Search for all solutions misses the + solutions that the spoke prunes. +- `Partial`: the spoke searches part of the hub's search space, such as a + large neighbourhood. Exhausting it is no proof, and its no-goods do not + hold in the hub. + +The engine trusts the declared coverage. A spoke that declares more than it +covers, such as `Full` for a spoke that removes solutions, gives undefined +results. + +`nogoods()` is empty unless the spoke of the episode that ended was `Full`. +PBS honours the coverage of each asset: an asset whose `Partial` spoke +exhausts is dropped instead of ending the portfolio. + +Other changes to the hooks: + +- RBS calls `hub()` with `MetaEvent::Start` before it clones the first + spoke. Gecode 6 did not call `master()` then. +- For a best solution engine such as `RBS`, the engine constrains + the hub with the last solution before it calls `hub()`. The default + `hub()` no longer calls `constrain()`, and an override that does not call + the default keeps the bound. For other engines, such as `RBS`, + RBS no longer calls `constrain()` at all. +- After an episode that ends without a proof, such as LDS at its + discrepancy limit, RBS calls `hub()` with `MetaEvent::Incomplete`. By + default, it finishes when the spoke was `Full` or `Reduced`, as a new + spoke would repeat the same search, and restarts when it was `Partial`. + Both `Restart` and `Finish` are legal. +- PBS calls `status()` on the hub after `hub()`, so `hub()` can post + constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. +- The default PBS `hub()` still removes all branchers, so `spoke()` must post + the branching of each asset. When the hub had branchers but a spoke has + none after `spoke()`, PBS throws `Search::SpokeNoBrancher` instead of + returning the unassigned spoke as a solution. The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues after a solution instead of restarting. - `examples/photo.cpp`: an RBS `spoke()` that relaxes the last solution for - large neighbourhood search. + large neighbourhood search and declares `SpokeCoverage::Partial`. - `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for each asset. + +## Cutoff generators implement copy() + +`Search::Cutoff` has a new pure virtual member function: + +```cpp +virtual Gecode::Search::Cutoff* copy(void) const; +``` + +It returns a copy of the generator in its current state that continues the +sequence on its own. A copy of `Cutoff::rnd()` uses a different seed, so +the assets can restart at different times (unless every value of the range +is the same). A portfolio of restart-based engines, `PBS`, gives +each asset its own copy of the cutoff in its options and deletes the +original once the portfolio is built. A portfolio of a single asset whose +spoke does not declare `SpokeCoverage::Partial` needs no portfolio engine +and passes the cutoff itself to that asset. +In Gecode 6.6, the assets drew their values from one shared cutoff sequence. + +A custom cutoff generator must implement `copy()`. For a generator whose +state is plain data, the copy constructor suffices: + +```cpp +Gecode::Search::Cutoff* +MyCutoff::copy(void) const { + return new MyCutoff(*this); +} +``` + +A generator that owns other generators copies them with their own +`copy()`. + +## stopped() is replaced by end_reason() + +`Search::Engine::stopped()` and `Search::Base::stopped()` are removed, +and so is the experimental `limited()`. After `next()` returns no solution, +`end_reason()` tells why: + +```cpp +enum class Gecode::Search::EndReason : unsigned char { + NotEnded, Exhausted, Incomplete, Limit +}; +``` + +| Gecode 6 | Gecode 7 | +|-----------------------------------------------|-------------------------------------------------| +| `stopped()` is true | `end_reason() == EndReason::Limit` | +| `stopped()` is false after no solution | `end_reason() == EndReason::Exhausted` or `EndReason::Incomplete` | +| `limited()` is true (AStar, CABS) | `end_reason() == EndReason::Incomplete` | +| last `next()` returned a solution | `end_reason() == EndReason::NotEnded` | + +`Exhausted` means that the engine explored everything it was asked to +explore: there is no further solution, and the last solution of a +branch-and-bound search is optimal. `Incomplete` means that the engine ended +on its own without that proof, for example limited discrepancy search at its +discrepancy limit or CABS at its width limit. Calling `next()` again does not +continue an incomplete search. `Limit` means that a stop object stopped the +engine, and calling `next()` again continues the search. + +Code that used `!stopped()` as a proof, such as reporting optimality, should +test for `EndReason::Exhausted`. Code that resumes a search after a limit +should test for `EndReason::Limit`, and first lift the limit: a stop object +that still fires, such as an expired `TimeStop`, stops the search again +right away. Reset the `TimeStop` or raise the limit of a `NodeStop` or +`FailStop` before calling `next()` again. + +## Portfolio stop objects see the whole portfolio + +The stop object in the options of `PBS` is now checked with the statistics +of the whole portfolio, the sum over all assets. In Gecode 6, it was checked +for each asset with the statistics of that asset, so a failure limit of +`n` for a portfolio of `k` assets allowed up to `k * n` failures. A stop +object that should limit each asset on its own belongs in the options of an +engine builder: + +```cpp +Gecode::Search::Options a, b; +a.stop = &dfs_stop; +b.stop = &lds_stop; +Gecode::SEBs sebs({Gecode::dfs(a), Gecode::lds(b)}); +Gecode::PBS engine(model, sebs, portfolio_options); +``` diff --git a/examples/crossword.cpp b/examples/crossword.cpp index 729d3bb116..dc97dc74a2 100755 --- a/examples/crossword.cpp +++ b/examples/crossword.cpp @@ -281,13 +281,14 @@ class Crossword : public Script { << ((a == 0) ? "<=" : ">") << " " << n; } - /// Do not perform a restart when a solution is found - bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) - // Post no-goods - mi.nogoods().post(*this); - // Do not perform a restart if a solution has been found - return false; + /// Post no-goods, and do not perform a restart when a solution is found + void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + hc.nogoods().post(*this); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); + } + // For portfolio search, keep the branchers } /// Constructor for cloning \a s diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index d497ded4c3..33f5eef2db 100755 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -790,11 +790,12 @@ solve(const JobShopOptions& opt) { s->print(std::cout); u = s->cost().val(); delete s; - } else if (rbs.stopped()) { + } else if (rbs.end_reason() == Search::EndReason::Exhausted) { + l = m+1; + } else { + // Stopped, or ended without proving that no solution exists stopped = true; break; - } else { - l = m+1; } } @@ -842,7 +843,7 @@ solve(const JobShopOptions& opt) { Driver::stop(t,std::cout); std::cout << std::endl; - if (rbs.stopped()) { + if (rbs.end_reason() != Search::EndReason::Exhausted) { std::cout << "\t\t\t\tstopped due to time-out..." << std::endl; std::cout << std::endl << "\tSolution at most "; diff --git a/examples/photo.cpp b/examples/photo.cpp index 15a19e3dd1..bd9e94c8de 100644 --- a/examples/photo.cpp +++ b/examples/photo.cpp @@ -128,15 +128,13 @@ class Photo : public IntMinimizeScript { break; } } - /// Spoke function for restarts - bool spoke(const MetaInfo& mi) { - if ((mi.type() == MetaInfo::RESTART) && - (mi.restart() > 0) && (p > 0.0)) { - const Photo& l = static_cast(*mi.last()); + /// Relax the last solution for large neighbourhood search + void spoke(SpokeContext& sc) { + if ((sc.engine() == MetaEngine::Restart) && + (sc.last() != nullptr) && (p > 0.0)) { + const Photo& l = static_cast(*sc.last()); relax(*this, pos, l.pos, rnd, p); - return false; - } else { - return true; + sc.coverage(SpokeCoverage::Partial); } } /// Constructor for cloning \a s diff --git a/examples/qcp.cpp b/examples/qcp.cpp index b74d144b3f..00f3b57348 100644 --- a/examples/qcp.cpp +++ b/examples/qcp.cpp @@ -211,11 +211,11 @@ class QCP : public Script { } } } - /// Spoke function for portfolio search - virtual bool spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) { + /// Post a different branching for each asset of portfolio search + virtual void spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Portfolio) { double tbf = opt.tbf(); - Rnd r(seeds[mi.asset() % n_seeds]); + Rnd r(seeds[sc.asset() % n_seeds]); switch (opt.branching()) { case BRANCH_SIZE: { @@ -244,7 +244,6 @@ class QCP : public Script { default: ; } } - return true; } /// Constructor for cloning \a s QCP(QCP& s) diff --git a/gecode/driver/script.hpp b/gecode/driver/script.hpp index 1c8f707088..204f767ba4 100755 --- a/gecode/driver/script.hpp +++ b/gecode/driver/script.hpp @@ -427,7 +427,9 @@ namespace Gecode { namespace Driver { CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); s_out << endl; - if (e.stopped()) { + if (e.end_reason() == Search::EndReason::Incomplete) { + l_out << "Search engine finished without exhausting the search space" << '\n' << '\n'; + } else if (e.end_reason() == Search::EndReason::Limit) { l_out << "Search engine stopped..." << endl << "\treason: "; int r = static_cast(so.stop)->reason(stat,so); @@ -541,6 +543,7 @@ namespace Gecode { namespace Driver { Support::Timer t; double* ts = new double[o.samples()]; bool stopped = false; + bool incomplete = false; for (unsigned int ns = o.samples(); !stopped && ns--; ) { unsigned long long int s_l = (o.solutions() == 0) ? ULLONG_MAX : o.solutions(); @@ -572,8 +575,10 @@ namespace Gecode { namespace Driver { delete ex; s_n++; } while (s_n < s_l); - if (e.stopped()) + if (e.end_reason() == Search::EndReason::Limit) stopped = true; + else if (e.end_reason() == Search::EndReason::Incomplete) + incomplete = true; } delete sok.stop; } @@ -590,6 +595,8 @@ namespace Gecode { namespace Driver { << setprecision(6) << m << "ms" << setprecision(2) << " (" << d << "% deviation)" << endl; + if (incomplete) + l_out << "\tsearch finished without exhausting the search space" << endl; } delete [] ts; } diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index 78b2039c63..534222f0f2 100755 --- a/gecode/flatzinc.hh +++ b/gecode/flatzinc.hh @@ -682,8 +682,8 @@ namespace Gecode { namespace FlatZinc { virtual void constrain(const Space& s); /// Copy function virtual Gecode::Space* copy(void); - /// Spoke function for restarts - virtual bool spoke(const MetaInfo& mi); + /// Spoke hook for restarts: on_restart and LNS spokes have partial coverage + virtual void spoke(SpokeContext& sc); /// \name AST to variable and value conversion //@{ diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 52b9b0fdc2..d326496c4d 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -1941,7 +1941,8 @@ namespace Gecode { namespace FlatZinc { bool printAll = _method == SAT || opt.allSolutions() || noOfSolutions != 0; int findSol = noOfSolutions; bool solution_limit_reached = false; - bool engine_stopped = false; + // Only an exhausted search proves optimality or unsatisfiability + bool proof = false; Gecode::Search::Statistics stat; std::unique_ptr sol; { @@ -1962,7 +1963,7 @@ namespace Gecode { namespace FlatZinc { break; } } - engine_stopped = se.stopped(); + proof = se.end_reason() == Search::EndReason::Exhausted; if (opt.mode() == SM_STAT) { stat = se.statistics(); } @@ -1976,7 +1977,7 @@ namespace Gecode { namespace FlatZinc { out << "----------" << std::endl; } if (!solution_limit_reached) { - if (!engine_stopped) { + if (proof) { if (sol) { out << "==========" << std::endl; } else { @@ -2130,14 +2131,13 @@ namespace Gecode { namespace FlatZinc { #endif } - bool - FlatZincSpace::spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { + void + FlatZincSpace::spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Restart) { if (restart_data.initialized() && restart_data().mark_complete) { - // Fail the space + // Exhausting the failed spoke of full coverage proves completeness this->fail(); - // Return true to signal we are in the global search space - return true; + return; } bool ret = false; @@ -2145,7 +2145,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_int values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_iv.size() == restart_data().on_restart_iv_sol); for (int i = 0; i < restart_data().on_restart_iv_sol; ++i) { IntVar& outVar = on_restart_iv[base + restart_data().on_restart_iv_sol + i]; @@ -2178,20 +2178,20 @@ namespace Gecode { namespace FlatZinc { if (restart_data().on_restart_status) { assert(base == on_restart_iv.size() - 1); IntVar& restart_status = on_restart_iv[base]; - switch(mi.reason()) { - case MetaInfo::RR_INIT: - assert(!mi.last()); + switch(sc.event()) { + case MetaEvent::Start: + assert(sc.last() == nullptr); rel(*this, restart_status, IRT_EQ, 1); // 1: START break; - case MetaInfo::RR_SOL: - assert(mi.solution() > 0); + case MetaEvent::Solution: + assert(sc.last() != nullptr); rel(*this, restart_status, IRT_EQ, 4); // 4: SAT break; - case MetaInfo::RR_CMPL: + case MetaEvent::Exhausted: rel(*this, restart_status, IRT_EQ, 3); // 3: UNSAT break; default: - assert(mi.reason() == MetaInfo::RR_LIM); + assert((sc.event() == MetaEvent::Limit) || (sc.event() == MetaEvent::Incomplete)); rel(*this, restart_status, IRT_EQ, 2); // 2: UNKNOWN break; } @@ -2212,7 +2212,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_bool values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_bv.size() == restart_data().on_restart_bv_sol); for (int i = 0; i < restart_data().on_restart_bv_sol; ++i) { BoolVar& outVar = on_restart_bv[base + restart_data().on_restart_bv_sol + i]; @@ -2242,7 +2242,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_set values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_sv.size() == restart_data().on_restart_sv_sol); for (int i = 0; i < restart_data().on_restart_sv_sol; ++i) { SetVar& outVar = on_restart_sv[base + restart_data().on_restart_sv_sol + i]; @@ -2274,7 +2274,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_float values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_fv.size() == restart_data().on_restart_fv_sol); for (int i = 0; i < restart_data().on_restart_fv_sol; ++i) { FloatVar& outVar = on_restart_fv[base + restart_data().on_restart_fv_sol + i]; @@ -2313,30 +2313,31 @@ namespace Gecode { namespace FlatZinc { } #endif if (ret) { - return false; + // The on_restart constraints can restrict the spoke in any way + sc.coverage(SpokeCoverage::Partial); + return; } } - if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && (mi.last()==nullptr) && (_lnsInitialSolution.size()>0)) { + if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last()==nullptr) && (_lnsInitialSolution.size()>0)) { for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, _lnsInitialSolution[i]); } } - return false; - } else if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && mi.last()) { + sc.coverage(SpokeCoverage::Partial); + } else if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last() != nullptr)) { const FlatZincSpace& last = - static_cast(*mi.last()); + static_cast(*sc.last()); for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, last.iv_lns[i]); } } - return false; + sc.coverage(SpokeCoverage::Partial); } - return true; } Space* diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index e5407336c0..2632a32499 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -901,28 +901,22 @@ namespace Gecode { throw SpaceNoComparison("Space::compare"); } - bool - Space::hub(const MetaInfo& mi) { - switch (mi.type()) { - case MetaInfo::RESTART: - if (mi.last() != nullptr) - constrain(*mi.last()); - mi.nogoods().post(*this); - // Perform a restart even if a solution has been found - return true; - case MetaInfo::PORTFOLIO: + void + Space::hub(HubContext& hc) { + switch (hc.engine()) { + case MetaEngine::Restart: + hc.nogoods().post(*this); + break; + case MetaEngine::Portfolio: // Kill all branchers BrancherGroup::all.kill(*this); - return true; + break; default: GECODE_NEVER; - return true; } } - bool - Space::spoke(const MetaInfo&) { - return true; - } + void + Space::spoke(SpokeContext&) {} void* diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 0e3c0cfcfb..c8a0fdc1b9 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1651,97 +1651,282 @@ namespace Gecode { static NoGoods eng; }; + namespace Search { + class Statistics; + class MetaContextAccess; + } + /** - * \brief Information passed by meta search engines + * \defgroup TaskModelScriptMeta Meta search hooks + * + * A meta search engine keeps a \e hub space and searches clones of it, + * the \e spokes, with an inner engine. Restart-based search (RBS) runs + * one spoke after the other, each search of a spoke being an + * \e episode. Portfolio-based search (PBS) runs one spoke for each of + * its assets. + * + * The engines call Space::hub() on the hub and Space::spoke() on each + * spoke. A HubContext or SpokeContext tells the hook why it is called, + * and the hook answers through it: hub() with a MetaDecision, spoke() + * with a SpokeCoverage. * + * \ingroup TaskModelScript */ - class GECODE_VTABLE_EXPORT MetaInfo { - public: - /// Which type of information is provided - enum Type { - /// Information is provided by a restart-based engine - RESTART, - /// Information is provided by a portfolio-based engine - PORTFOLIO - }; - /// Reason for restarting - enum RestartReason { - /// No reason - used for PORTFOLIO - RR_NO, - /// Restarting after initialisation - RR_INIT, - /// Restarting after a solution is found - RR_SOL, - /// Restarting after exhausting search space - RR_CMPL, - /// Restarting after reaching restart limit - RR_LIM - }; + //@{ + + /// Meta search engine that calls a hook + enum class MetaEngine : unsigned char { + Restart, ///< Restart-based search (RBS) + Portfolio, ///< Portfolio-based search (PBS) + }; + + /** + * \brief Why a meta search engine calls a hook + * + * In Space::hub(), the event that ended the episode, or \c Start before + * the first one. In Space::spoke(), the event that ended the previous + * episode, or \c Start for the first episode and for the assets of a + * portfolio. + */ + enum class MetaEvent : unsigned char { + Start, ///< Search starts: no episode has run yet + Solution, ///< The episode found a solution + /** + * The episode exhausted its spoke. This is a proof only for a spoke + * of SpokeCoverage::Full or SpokeCoverage::Reduced, and then the + * engine has already ended: a hook only sees this event after a + * spoke of SpokeCoverage::Partial. + */ + Exhausted, + Incomplete, ///< The inner engine ended without a proof (such as LDS) + Limit, ///< The episode reached the cutoff + }; + + /** + * \brief What a meta search engine does after Space::hub() returns + * + * The engine sets the default before it calls hub(). Which decisions are + * legal depends on the event: + * + * | Event | Restart | Continue | Finish | + * |---------------|-----------|----------|-----------| + * | \c Start | default | illegal | legal | + * | \c Solution | default | legal | legal | + * | \c Limit | default | legal | legal | + * | \c Exhausted | default | illegal | legal | + * | \c Incomplete | see below | illegal | see below | + * + * After \c Incomplete, the default is \c Finish when the spoke of the + * episode has SpokeCoverage::Full or SpokeCoverage::Reduced, as a new + * spoke would repeat the same search, and \c Restart when it has + * SpokeCoverage::Partial. + * + * Setting an illegal decision throws IllegalMetaDecision. PBS calls + * hub() only with MetaEvent::Start. + */ + enum class MetaDecision : unsigned char { + /// Search a new spoke (at \c Start: start search) + Restart, + /** + * Continue the current episode: after \c Solution, search the same + * spoke for the next solution; after \c Limit, resume the same spoke + * with the next cutoff as a fresh budget. + * + * The spoke is not rebuilt, so constraints that hub() posts reach only + * the spokes of later episodes, and exhausting the spoke proves that + * the hub had no further solution when the spoke was created. In best + * solution search the engine still constrains the spoke with each new + * solution. A hook that restricts the hub in a way that the current + * spoke must respect selects \c Restart instead. + */ + Continue, + /// End the engine: next() returns nullptr with EndReason::Incomplete + Finish, + }; + + /** + * \brief How much of the hub's search space a spoke covers + * + * Space::spoke() declares the coverage of its spoke. It decides whether + * exhausting the spoke proves that the hub has no further solution, and + * whether the no-goods recorded in the spoke hold in the hub. + * + * The engine trusts the declaration: a spoke that declares more coverage + * than it has, such as a spoke that removes solutions but declares + * \c Full, gives undefined results. + */ + enum class SpokeCoverage : unsigned char { + /** + * The spoke adds only branching and constraints that the hub + * implies: exhaustion is a proof, and its no-goods hold in the hub + */ + Full, + /** + * The spoke prunes solutions but keeps one, or an optimal one, if + * any exists, such as symmetry breaking or dominance: exhaustion is + * a proof, but its no-goods do not hold in the hub. Search for all + * solutions misses the solutions that the spoke prunes. + */ + Reduced, + /** + * The spoke explores part of the hub's search space, such as a large + * neighbourhood search fragment: exhaustion is no proof, and its + * no-goods do not hold in the hub + */ + Partial, + }; + + /** + * \brief Information that a meta search engine passes to a hook + * + * Meta search engines create the contexts with + * Search::MetaContextAccess, models only read them. All references and + * pointers are valid only while the hook runs. + */ + class MetaContext { protected: - /// Type of information - const Type t; - /// \name Restart-based information - //@{ - /// Number of restarts - const unsigned long int r; - /// Reason for restarting - const RestartReason rr; - /// Number of solutions since last restart - const unsigned long long int s; - /// Number of failures since last restart - const unsigned long long int f; - /// Last solution found - const Space* l; - /// No-goods from restart - const NoGoods& ng; - //@} - /// \name Portfolio-based information - //@{ - /// Number of asset in portfolio - const unsigned int a; - //@} + /// The engine calling the hook + MetaEngine _engine; + /// Why the hook is called + MetaEvent _event; + /// The episode + unsigned long int _episode; + /// The asset + unsigned int _asset; + /// The number of assets + unsigned int _assets; + /// The most recent solution (possibly nullptr) + const Space* _last; + /// The statistics of the finished episode + const Search::Statistics& _statistics; + /// The no-goods of the finished episode + const NoGoods& _nogoods; + /// Initialize, the arguments correspond to the access functions + MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); public: - /// \name Constructors depending on type of engine - //@{ - /// Constructor for restart-based engine - MetaInfo(unsigned long int r, - RestartReason rr, - unsigned long long int s, - unsigned long long int f, - const Space* l, - NoGoods& ng); - /// Constructor for portfolio-based engine - MetaInfo(unsigned int a); - //@} - /// Return type of information - Type type(void) const; - /// \name Restart-based information - //@{ - /// Return number of restarts - unsigned long int restart(void) const; - /// Return reason for restarting - RestartReason reason(void) const; - /// Return number of solutions since last restart - unsigned long long int solution(void) const; - /// Return number of failures since last restart - unsigned long long int fail(void) const; - /// Return last solution found (possibly nullptr) + /// Contexts are not copied + MetaContext(const MetaContext&) = delete; + /// Contexts are not assigned + MetaContext& operator =(const MetaContext&) = delete; + /// Return the engine calling the hook + MetaEngine engine(void) const; + /// Return why the hook is called + MetaEvent event(void) const; + /** + * \brief Return the episode, counting from zero + * + * Each new spoke of RBS starts a new episode, whatever ended the + * previous one. In hub(), this is the episode that ended (zero for + * \c Start); in spoke(), the episode that starts. PBS always passes + * zero. + */ + unsigned long int episode(void) const; + /// Return the asset of a portfolio, counting from zero (zero for RBS) + unsigned int asset(void) const; + /// Return the number of assets of a portfolio (one for RBS) + unsigned int assets(void) const; + /** + * \brief Return the best solution the engine knows, or nullptr if none + * + * This is the most recent solution of the engine, or a better one that + * constrain() passed to the engine since, for example from another + * asset of a portfolio. The engine owns the solution, and the pointer is valid only while + * the hook runs: clone the solution to keep it. + */ const Space* last(void) const; /** - * \brief Return no-goods recorded from restart + * \brief Return the statistics of the finished episode * - * The no-goods are empty if the search on the spoke space was - * incomplete, as they only hold in the spoke's search space. + * Empty for \c Start. Use the statistics of the engine for totals. + */ + const Search::Statistics& statistics(void) const; + /** + * \brief Return the no-goods of the finished episode + * + * Empty unless the spoke of that episode has SpokeCoverage::Full, so + * they can always be posted in the hub. */ const NoGoods& nogoods(void) const; - //@} - /// \name Portfolio-based information - //@{ - /// Return number of asset in portfolio - unsigned int asset(void) const; - //@} }; + /// Context passed to Space::hub() + class HubContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The decision + MetaDecision _decision; + /// Whether decision \a d is legal for event \a e (see MetaDecision) + static bool legal(MetaEvent e, MetaDecision d); + private: + /// Initialize with the default decision \a d + HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the decision + MetaDecision decision(void) const; + /** + * \brief Set the decision to \a d, the last one set counts + * + * Throws IllegalMetaDecision if \a d is illegal for the event (see + * MetaDecision). + */ + void decision(MetaDecision d); + }; + + /// Context passed to Space::spoke() + class SpokeContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The coverage + SpokeCoverage _coverage; + private: + /// Initialize with coverage SpokeCoverage::Full + SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the coverage + SpokeCoverage coverage(void) const; + /// Set the coverage to \a c, the last one set counts + void coverage(SpokeCoverage c); + }; + + namespace Search { + /** + * \brief Creation of the contexts of meta search hooks + * + * For meta search engines, which create the contexts that they pass + * to Space::hub() and Space::spoke(). The arguments correspond to the + * access functions of MetaContext. + */ + class MetaContextAccess { + public: + /// Return a context for Space::hub() with the default decision \a d + static HubContext hub(MetaEngine engine, MetaEvent event, + MetaDecision d, unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + /// Return a context for Space::spoke() with coverage SpokeCoverage::Full + static SpokeContext spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + }; + } + + //@} + /** * \brief %Space status * \ingroup TaskSearch @@ -2192,55 +2377,69 @@ namespace Gecode { GECODE_KERNEL_EXPORT virtual SpaceComparison compare(const Space& other) const; /** - * \brief Hub configuration function for meta search engines - * - * \li Restart-based search (RBS) calls this function on its hub - * after each solution and before each restart. \a mi - * describes the restart. After a solution, returning true - * restarts search from a new spoke, and returning false - * continues the current search without calling spoke(). At a - * restart caused by the cutoff or by an incomplete spoke being - * exhausted, the result is ignored and search restarts. - * Whatever the result, if the hub fails after the call, RBS - * ends. - * - * The default function constrains the hub with the last - * solution, if any, posts the no-goods from \a mi, and - * returns true. - * - * \li Portfolio-based search (PBS) calls this function once on - * its hub before creating the assets. The result is ignored. - * - * The default function removes all branchers, so the spoke() - * function must post the branching for each asset. + * \brief Hub hook for meta search engines + * + * Restart-based search (RBS) calls hub() on its hub when search + * starts and whenever an episode ends with a solution, at the + * cutoff, or without a proof (see MetaEvent). An episode that + * exhausts a spoke of SpokeCoverage::Full or SpokeCoverage::Reduced + * ends RBS with Search::EndReason::Exhausted instead. + * Portfolio-based search (PBS) calls hub() once, with + * MetaEvent::Start, before it creates the assets. + * + * The hook may post constraints in the hub and sets what the engine + * does next with \a hc.decision() (see MetaDecision for the legal + * decisions and the default). The constraints reach the current spoke + * only with MetaDecision::Restart, which searches a new spoke. If the hub fails, the engine ends + * with Search::EndReason::Exhausted whatever the decision: failing + * the hub is how a hook declares that no further solution exists. + * + * In best solution search, RBS constrains the hub with each new + * solution before it calls hub(), so an override cannot lose the + * bound by not calling the default. + * + * The default hook posts \a hc.nogoods() for RBS. For PBS, it + * removes all branchers, so spoke() must post the branching of each + * asset. + * + * No-goods refer to the branchers that created their choices. RBS + * keeps a brancher that hub() posts from taking the identity of a + * brancher that spoke() posted, so the no-goods of a spoke are never + * posted for the wrong brancher. This does not cover branchers that + * other branchers post while a spoke is searched: if there are such + * branchers and the spoke has SpokeCoverage::Full, hub() must not + * post branchers. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool hub(const MetaInfo& mi); + virtual void hub(HubContext& hc); /** - * \brief Spoke configuration function for meta search engines + * \brief Spoke hook for meta search engines * - * \li RBS calls this function on each spoke, a clone of the hub, - * before searching it: once when search starts and once at - * each restart. \a mi describes the restart. Returning true - * declares the search of the spoke complete: when it is - * exhausted, RBS finishes. Returning false declares it - * incomplete: when it is exhausted, RBS restarts. The no-goods - * recorded by an incomplete search only hold in the spoke's - * search space, so RBS does not pass them to hub(). This also - * holds for the first search when search starts. + * RBS calls spoke() on each new spoke, a clone of the hub, before + * searching it: for the first episode with MetaEvent::Start, and + * for each later episode with the event that ended the previous + * one. PBS calls spoke() once on the spoke of each asset, the hub + * or a clone of it, with MetaEvent::Start and the asset number. * - * \li PBS calls this function once on the spoke of each asset, - * the hub or a clone of it, and passes the asset number, - * starting from zero. The result is ignored. + * The hook may post constraints and branching in the spoke and + * declares with \a sc.coverage() how much of the hub's search space + * the spoke covers (see SpokeCoverage, the default is Full). Large + * neighbourhood search, for example, fixes part of \a sc.last() and + * declares SpokeCoverage::Partial. The no-goods recorded while + * searching a spoke only hold in the hub for SpokeCoverage::Full, so + * RBS passes no no-goods to hub() for any other spoke. * - * The default function does nothing and returns true. + * PBS throws Search::SpokeNoBrancher if the hub had branchers before + * hub() and a spoke that has not failed has none after spoke(). + * + * The default hook does nothing. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool spoke(const MetaInfo& mi); + virtual void spoke(SpokeContext& sc); /* * Member functions for search engines @@ -2262,6 +2461,17 @@ namespace Gecode { SpaceStatus status(StatusStatistics& stat); /// Query space status without collecting statistics SpaceStatus status(void); + /** + * \brief Reserve in this space the brancher ids that clone \a s uses + * + * A meta search engine calls this on its hub after spoke() has run + * on the clone \a s. A brancher that hub() posts later then never + * gets the id of a brancher that spoke() posted, so a no-good + * recorded in the spoke cannot reach the wrong brancher of the hub. + * + * \ingroup TaskSearch + */ + void reserve_brancher_ids(const Space& s); /** * \brief Create new choice for current brancher @@ -3244,58 +3454,116 @@ namespace Gecode { /* - * Information from meta search engines + * Contexts of meta search hooks */ forceinline - MetaInfo::MetaInfo(unsigned long int r0, - RestartReason rr0, - unsigned long long int s0, - unsigned long long int f0, - const Space* l0, - NoGoods& ng0) - : t(RESTART), r(r0), rr(rr0), s(s0), f(f0), l(l0), ng(ng0), a(0) {} - - forceinline - MetaInfo::MetaInfo(unsigned int a0) - : t(PORTFOLIO), r(0), rr(RR_NO), s(0), f(0), l(nullptr), ng(NoGoods::eng), a(a0) {} - - forceinline MetaInfo::Type - MetaInfo::type(void) const { - return t; + MetaContext::MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : _engine(engine), _event(event), _episode(episode), + _asset(asset), _assets(assets), _last(last), + _statistics(statistics), _nogoods(nogoods) {} + forceinline MetaEngine + MetaContext::engine(void) const { + return _engine; + } + forceinline MetaEvent + MetaContext::event(void) const { + return _event; } forceinline unsigned long int - MetaInfo::restart(void) const { - assert(type() == RESTART); - return r; - } - forceinline MetaInfo::RestartReason - MetaInfo::reason(void) const { - return rr; + MetaContext::episode(void) const { + return _episode; } - forceinline unsigned long long int - MetaInfo::solution(void) const { - assert(type() == RESTART); - return s; + forceinline unsigned int + MetaContext::asset(void) const { + return _asset; } - forceinline unsigned long long int - MetaInfo::fail(void) const { - assert(type() == RESTART); - return f; + forceinline unsigned int + MetaContext::assets(void) const { + return _assets; } forceinline const Space* - MetaInfo::last(void) const { - assert(type() == RESTART); - return l; + MetaContext::last(void) const { + return _last; + } + forceinline const Search::Statistics& + MetaContext::statistics(void) const { + return _statistics; } forceinline const NoGoods& - MetaInfo::nogoods(void) const { - assert(type() == RESTART); - return ng; + MetaContext::nogoods(void) const { + return _nogoods; } - forceinline unsigned int - MetaInfo::asset(void) const { - assert(type() == PORTFOLIO); - return a; + + forceinline bool + HubContext::legal(MetaEvent e, MetaDecision d) { + // Only an episode that found a solution or reached the cutoff continues + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } + forceinline + HubContext::HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _decision(d) { + assert(legal(event,d)); + } + forceinline MetaDecision + HubContext::decision(void) const { + return _decision; + } + forceinline void + HubContext::decision(MetaDecision d) { + if (!legal(_event,d)) + throw IllegalMetaDecision("HubContext::decision"); + _decision = d; + } + + forceinline + SpokeContext::SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _coverage(SpokeCoverage::Full) {} + forceinline SpokeCoverage + SpokeContext::coverage(void) const { + return _coverage; + } + forceinline void + SpokeContext::coverage(SpokeCoverage c) { + _coverage = c; + } + + forceinline HubContext + Search::MetaContextAccess::hub(MetaEngine engine, MetaEvent event, + MetaDecision d, unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return HubContext(engine,event,d,episode,asset,assets,last,statistics, + nogoods); + } + forceinline SpokeContext + Search::MetaContextAccess::spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return SpokeContext(engine,event,episode,asset,assets,last,statistics, + nogoods); } @@ -3411,6 +3679,13 @@ namespace Gecode { return status(stat); } + forceinline void + Space::reserve_brancher_ids(const Space& s) { + unsigned int n = s.pc.p.bid_sc >> sc_bits; + if (n > (pc.p.bid_sc >> sc_bits)) + pc.p.bid_sc = (n << sc_bits) | (pc.p.bid_sc & ((1U << sc_bits) - 1U)); + } + forceinline Space* Space::clone(void) const { CloneStatistics stat; diff --git a/gecode/kernel/exception.cpp b/gecode/kernel/exception.cpp index a273a04699..8dc6000879 100644 --- a/gecode/kernel/exception.cpp +++ b/gecode/kernel/exception.cpp @@ -89,6 +89,9 @@ namespace Gecode { MoreThanOneTracer::MoreThanOneTracer(const char* l) : Exception(l,"Attempt create more than one non-variable tracer") {} + IllegalMetaDecision::IllegalMetaDecision(const char* l) + : Exception(l,"Illegal decision for the event of a meta search hook") {} + } // STATISTICS: kernel-other diff --git a/gecode/kernel/exception.hpp b/gecode/kernel/exception.hpp index 3c174d33bc..5d46874730 100644 --- a/gecode/kernel/exception.hpp +++ b/gecode/kernel/exception.hpp @@ -166,6 +166,13 @@ namespace Gecode { MoreThanOneTracer(const char* l); }; + /// %Exception: illegal decision of a meta search hook (see MetaDecision) + class GECODE_KERNEL_EXPORT IllegalMetaDecision : public Exception { + public: + /// Initialize with location \a l + IllegalMetaDecision(const char* l); + }; + //@} } diff --git a/gecode/search.hh b/gecode/search.hh index 05d2a8057c..bc0c7c35ac 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -487,6 +487,15 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const = 0; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void) = 0; + /** + * \brief Return a copy of this generator in its current state + * + * The copy continues the sequence independently of this generator, + * except that a copy of a random generator draws its own sequence + * (see CutoffRandom::copy()). A portfolio of restart-based engines + * gives each asset its own copy. + */ + virtual Cutoff* copy(void) const = 0; /// Destructor virtual ~Cutoff(void); //@} @@ -542,6 +551,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -561,6 +572,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -588,6 +601,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -609,6 +624,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -627,6 +644,8 @@ namespace Gecode { namespace Search { unsigned long long int step; /// Current value unsigned long long int cur; + /// Number of copies made of this generator + mutable unsigned int copies; public: /// Constructor CutoffRandom(unsigned int seed, @@ -636,6 +655,17 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /** + * \brief Return a copy of this generator with its own random sequence + * + * The copy draws its values, starting with its current one, from a + * seed that depends on the state of this generator and on how many + * copies of it have been made before. Copies made one after the + * other thus draw from different seeds, so that the assets of a + * portfolio usually restart at different times, and the same program + * creates the same sequences. + */ + virtual Cutoff* copy(void) const; }; /** @@ -657,6 +687,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffAppend(void); }; @@ -678,6 +710,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffMerge(void); }; @@ -703,6 +737,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffRepeat(void); }; @@ -1057,6 +1093,38 @@ namespace Gecode { namespace Search { namespace Gecode { namespace Search { + /** + * \brief Why the last call to next() of a search engine returned no solution + * + * A search engine reports the reason with end_reason(). Only + * Exhausted is a proof: the space that the engine was given has no + * further solutions (no better ones for best solution search). Any + * other reason after next() returned nullptr means that the engine + * ended without such a proof. + * + * A meta engine (restart-based or portfolio search) reports Limit + * for a stop object installed above it, not for its own cutoffs or + * slices. A portfolio also reports Limit when the stop objects of + * its assets have parked every asset that remains (see PBS), and + * calling next() again resumes them. + * + * \ingroup TaskModelSearch + */ + enum class EndReason : unsigned char { + /// next() has not been called, or the last call returned a solution + NotEnded, + /// The search space is exhausted, calling next() again finds nothing + Exhausted, + /** + * Search finished without exhausting its search space, for example + * at the discrepancy limit of LDS or the width limit of CABS. There + * may be further solutions, but calling next() again finds none. + */ + Incomplete, + /// A stop object stopped search, calling next() again resumes it + Limit, + }; + /** * \brief %Search engine implementation interface */ @@ -1073,12 +1141,8 @@ namespace Gecode { namespace Search { virtual Space* next(void) = 0; /// Return statistics virtual Statistics statistics(void) const = 0; - /// Check whether engine has been stopped - virtual bool stopped(void) const = 0; -#ifdef GECODE_HAS_EXPERIMENTAL - /// Whether the engine stopped at a local limit (such as a CABS width limit) and cannot continue - virtual bool limited(void) const; -#endif + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const = 0; /// Constrain future solutions to be better than \a b (raises exception) virtual void constrain(const Space& b); /// Reset engine to restart at space \a s (does nothing) @@ -1112,8 +1176,8 @@ namespace Gecode { namespace Search { virtual T* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~Base(void); private: @@ -1410,12 +1474,9 @@ namespace Gecode { * Search::Options::d_l discrepancies, allowing more discrepancies in each * iteration, starting from none. * - * When next() returns nullptr and stopped() returns false, either the - * search tree has been explored completely, or the discrepancy limit has - * been reached while parts of the tree are still unexplored. The engine - * does not report which: a search that finds no (further) solution only - * proves that none exists if no path of the tree has more discrepancies - * than the limit. + * When the search tree has choices that need more discrepancies than + * the limit in Search::Options::d_l, end_reason() returns + * Search::EndReason::Incomplete once the search ends. * * \ingroup TaskModelSearch */ @@ -1455,14 +1516,21 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * The engine calls hub() on its hub when search starts and when an + * episode ends while search continues: after a solution, at the + * cutoff, and when the search of a spoke ends without a proof. When a + * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its + * search space, search ends without a call to hub(). The engine calls + * hub() for a solution in the next call to next(). The engine calls + * spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ @@ -1470,7 +1538,12 @@ namespace Gecode { class RBS : public Search::Base { using Search::Base::e; public: - /// Initialize engine for space \a s and options \a o + /** + * \brief Initialize engine for space \a s and options \a o + * + * The engine takes ownership of the cutoff in \a o. If the + * constructor throws an exception, the caller keeps the cutoff. + */ RBS(T* s, const Search::Options& o); /// Whether engine does best solution search static const bool best = E::best; @@ -1482,14 +1555,22 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * The engine calls hub() on its hub when search starts and when an + * episode ends while search continues: after a solution, at the + * cutoff, and when the search of a spoke ends without a proof. When a + * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its + * search space, search ends without a call to hub(). The engine calls + * hub() for a solution in the next call to next(). The engine calls + * spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). As rbs() calls next() only once, hub() is not + * called for the solution it returns. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1536,8 +1617,24 @@ namespace Gecode { * \brief Meta engine using a portfolio of search engines * * The engine will run a portfolio with a number of assets as defined - * by the options \a o. The engine supports parallel execution of - * assets by using the number of threads as defined by the options. + * by the options \a o. With more than one thread in \a o, every asset + * runs in its own thread, also when there are more assets than threads, + * and the threads are divided evenly among the assets, with at least + * one thread for each asset. With one thread, the assets take turns in + * slices of failures (see Search::Options::slice). + * + * The stop object in \a o is checked with the statistics of the whole + * portfolio, that is, the sum of the statistics of all assets. The + * asset that checks contributes the statistics it checks with, which + * for a parallel asset are those of one worker, as for any parallel + * engine. With one thread, every other asset is paused and contributes + * its current statistics, for a parallel asset those of all its + * workers. With more threads, every other asset contributes the + * statistics with which it last checked its stop object, or its final + * statistics once it has ended. When the stop object stops search, + * end_reason() returns Search::EndReason::Limit and calling next() + * again resumes all assets. + * * For best-solution assets, a solution replaces the incumbent only if * Space::compare reports SpaceComparison::Better. * An external worker control in \a o is supported only for a single @@ -1546,17 +1643,34 @@ namespace Gecode { * PBS does not allocate workers or adjust those controls. * * When the assets are restart-based engines, the portfolio takes - * ownership of the cutoff in \a o and the assets share its sequence: - * each restart of an asset takes the next value of the sequence. + * ownership of the cutoff in \a o and gives each asset its own copy + * (see Cutoff::copy()). The exception is a single asset whose spoke has + * SpokeCoverage::Full or SpokeCoverage::Reduced: it runs as the + * restart-based engine itself, which takes the cutoff in \a o and so + * also its random sequence. If the constructor throws an exception, + * the caller keeps the cutoff. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The spoke of each asset declares its coverage in Space::spoke() (see + * SpokeCoverage). When an asset whose spoke has SpokeCoverage::Full or + * SpokeCoverage::Reduced exhausts its search space, the portfolio ends + * and end_reason() returns Search::EndReason::Exhausted. An asset that + * ends without a proof is dropped while the other assets continue: an + * asset whose spoke has SpokeCoverage::Partial and exhausts its search + * space, or an engine such as LDS at its discrepancy limit. When every + * asset has been dropped, end_reason() returns + * Search::EndReason::Incomplete. + * + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke that has + * not failed has none after spoke(), the engine throws + * Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1572,13 +1686,19 @@ namespace Gecode { /** * Initialize with engine builders \a sebs * - * The stop object of \a o is checked for each builder's engine with the - * statistics of that engine, as is the stop object of the builder. + * The stop object of \a o is checked with the statistics of the whole + * portfolio, the stop object of a builder with the statistics of the + * engine it builds. When the stop object of a builder stops its + * engine, that asset is parked while the other assets continue. When + * only parked assets remain, end_reason() returns + * Search::EndReason::Limit, and the parked assets resume with the + * next call to next(). * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. - * In parallel PBS, the outer thread count limits how many builders run, - * in array order; each builder's options set its own engine's thread count. + * In parallel PBS, the engine of every builder runs in its own thread, + * also when there are more builders than outer threads; each builder's + * options set its own engine's thread count. * * With experimental search, AStar and CABS builders can be used * together with BAB builders. @@ -1594,19 +1714,22 @@ namespace Gecode { * \brief Run a portfolio of search engines * * The engine will run a portfolio with a number of assets as defined - * by the options \a o. The engine supports parallel execution of - * assets by using the number of threads as defined by the options. + * by the options \a o. See PBS for how the assets use the threads in + * \a o. * An external worker control is supported only when \a o selects one * asset. PBS does not implement worker-allocation policy. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke that has + * not failed has none after spoke(), the engine throws + * Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/astar.cpp b/gecode/search/astar.cpp index 4bbef62db7..301a67397e 100644 --- a/gecode/search/astar.cpp +++ b/gecode/search/astar.cpp @@ -66,6 +66,9 @@ namespace Gecode { namespace Search { namespace Par { bool advance(void) override { return false; } + bool can_advance(void) const override { + return false; + } void clear(void) override { queue.clear(); } @@ -154,11 +157,12 @@ namespace Gecode { namespace Search { namespace Seq { AStar::next(void) { start(); while (true) { + // An exhausted search is complete, even when a limit has been reached + if (!expansion && queue.empty()) + return nullptr; if (stop_seq(opt)) return nullptr; if (!expansion) { - if (queue.empty()) - return nullptr; Entry e = queue.pop(); std::unique_ptr s(e.space); if (!best.improves(e.bound)) { diff --git a/gecode/search/base.hpp b/gecode/search/base.hpp index a00bcb5174..bdb78a1386 100644 --- a/gecode/search/base.hpp +++ b/gecode/search/base.hpp @@ -52,9 +52,9 @@ namespace Gecode { namespace Search { return e->statistics(); } template - forceinline bool - Base::stopped(void) const { - return e->stopped(); + forceinline EndReason + Base::end_reason(void) const { + return e->end_reason(); } template forceinline diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index f012bdb694..e9e6130cbd 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -103,6 +103,9 @@ namespace Gecode { namespace Search { namespace Par { void started(const Space& r) override { root.reset(r.clone()); } + bool can_advance(void) const override { + return !candidates.empty() || candidates.improving(best); + } public: /// Initialize for space \a s with options \a o CABS(Space* s, const Options& o) @@ -123,17 +126,6 @@ namespace Gecode { namespace Search { namespace Par { namespace Gecode { namespace Search { namespace Seq { - /// Sequential CABS engine - class CABSEngine : public WorkerToEngine { - public: - /// Initialize for space \a s with options \a o - CABSEngine(Space* s, const Options& o) : WorkerToEngine(s,o) {} - /// Whether search stopped at the width or frontier limit - bool limited(void) const override { - return w.limited(); - } - }; - }}} namespace Gecode { namespace Search { @@ -149,7 +141,7 @@ namespace Gecode { namespace Search { if (e.threads > 1.0) return new Par::CABS(s,e); #endif - return new Seq::CABSEngine(s,e); + return new WorkerToEngine< Seq::CABS>(s,e); } }} @@ -161,7 +153,7 @@ namespace Gecode { namespace Search { namespace Seq { priority{guidance.sense,static_cast(guidance.rank)}, candidates(priority,guidance.dominates && guidance.dominance_key), order(0), status(SS_FAILED), depth(0), revision(0), counted(false), - best(guidance.sense), _limited(false) { + best(guidance.sense), _limited(false), _exhausted(false) { initialize(s,o.clone); } @@ -247,12 +239,23 @@ namespace Gecode { namespace Search { namespace Seq { return nullptr; } start(); + // An exhausted search is complete, even when a limit has been reached + if (_exhausted) + return nullptr; while (true) { + // An exhausted search is complete, even when a limit has been reached + if (!expansion && layer.empty() && candidates.empty() && + !candidates.improving(best)) { + _exhausted = true; + return nullptr; + } if (stop_seq(opt)) return nullptr; if (!expansion) { - if (layer.empty() && !advance()) + if (layer.empty() && !advance()) { + _exhausted = !_limited; return nullptr; + } if (!expansion) { Entry e = layer.pop(); std::unique_ptr s(e.space); @@ -309,9 +312,9 @@ namespace Gecode { namespace Search { namespace Seq { return *this; } - bool - CABS::limited(void) const { - return _limited; + EndReason + CABS::end_reason(void) const { + return _limited ? EndReason::Incomplete : Worker::end_reason(); } void @@ -335,7 +338,7 @@ namespace Gecode { namespace Search { namespace Seq { order = 0; revision = 0; depth = 0; - counted = _limited = false; + counted = _limited = _exhausted = false; Worker::reset(); initialize(s,false); // The root is owned by the engine after initialize returns diff --git a/gecode/search/cutoff.cpp b/gecode/search/cutoff.cpp index 54a5483d4b..b9051d87c7 100755 --- a/gecode/search/cutoff.cpp +++ b/gecode/search/cutoff.cpp @@ -36,6 +36,7 @@ */ #include +#include #include namespace Gecode { namespace Search { @@ -49,6 +50,11 @@ namespace Gecode { namespace Search { return c; } + Cutoff* + CutoffConstant::copy(void) const { + return new CutoffConstant(*this); + } + unsigned long long int CutoffLinear::operator ()(void) const { @@ -60,6 +66,11 @@ namespace Gecode { namespace Search { return n; } + Cutoff* + CutoffLinear::copy(void) const { + return new CutoffLinear(*this); + } + unsigned long int CutoffLuby::start[CutoffLuby::n_start] = { @@ -75,6 +86,11 @@ namespace Gecode { namespace Search { return scale*luby(i++); } + Cutoff* + CutoffLuby::copy(void) const { + return new CutoffLuby(*this); + } + unsigned long long int CutoffGeometric::operator ()(void) const { @@ -86,6 +102,11 @@ namespace Gecode { namespace Search { return static_cast(scale * n); } + Cutoff* + CutoffGeometric::copy(void) const { + return new CutoffGeometric(*this); + } + unsigned long long int CutoffRandom::operator ++(void) { @@ -97,6 +118,17 @@ namespace Gecode { namespace Search { return cur; } + Cutoff* + CutoffRandom::copy(void) const { + CutoffRandom* c = new CutoffRandom(*this); + // Derive a distinct seed for each copy, the golden ratio spreads them + copies++; + c->rnd.seed(rnd.seed() + copies * 0x9e3779b9U); + c->copies = 0U; + (void) ++(*c); + return c; + } + unsigned long long int CutoffAppend::operator ()(void) const { @@ -116,6 +148,16 @@ namespace Gecode { namespace Search { } } + Cutoff* + CutoffAppend::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffAppend(d1.get(),n,d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffMerge::operator ()(void) const { @@ -128,6 +170,16 @@ namespace Gecode { namespace Search { return (*c1)(); } + Cutoff* + CutoffMerge::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffMerge(d1.get(),d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffRepeat::operator ()(void) const { @@ -137,12 +189,24 @@ namespace Gecode { namespace Search { CutoffRepeat::operator ++(void) { i++; if (i == n) { + // Read the current value, which ++ need not return for all generators + (void) ++(*c); cutoff = (*c)(); i = 0; } return cutoff; } + Cutoff* + CutoffRepeat::copy(void) const { + std::unique_ptr d1(c->copy()); + CutoffRepeat* d = new CutoffRepeat(d1.get(),n); + (void) d1.release(); + d->cutoff = cutoff; + d->i = i; + return d; + } + Cutoff* Cutoff::constant(unsigned long long int scale) { diff --git a/gecode/search/cutoff.hpp b/gecode/search/cutoff.hpp index 441a286e1f..c52b82d6b5 100755 --- a/gecode/search/cutoff.hpp +++ b/gecode/search/cutoff.hpp @@ -91,7 +91,8 @@ namespace Gecode { namespace Search { unsigned long long int n0) : rnd(seed), min(min0), n(n0), step(std::max(1ULL, - static_cast((max0-min0+1U)/n))) { + static_cast((max0-min0+1U)/n))), + copies(0U) { cur = ++(*this); } diff --git a/gecode/search/engine.cpp b/gecode/search/engine.cpp index b2a3d31851..63a71d98ff 100644 --- a/gecode/search/engine.cpp +++ b/gecode/search/engine.cpp @@ -49,13 +49,6 @@ namespace Gecode { namespace Search { (void) b; throw NoBest("Engine::constrain"); } -#ifdef GECODE_HAS_EXPERIMENTAL - bool - Engine::limited(void) const { - return false; - } - -#endif void Engine::reset(Space* s) { (void) s; diff --git a/gecode/search/exception.cpp b/gecode/search/exception.cpp index 8e3bcb8974..f1a36df33e 100644 --- a/gecode/search/exception.cpp +++ b/gecode/search/exception.cpp @@ -52,6 +52,10 @@ namespace Gecode { namespace Search { : Exception(l,"Illegal combination of best and non-best solution search") {} + SpokeNoBrancher::SpokeNoBrancher(const char* l) + : Exception(l,"Spoke of a portfolio has no brancher, but the hub had " + "branchers") {} + NoBest::NoBest(const char* l) : Exception(l,"Best solution search is not supported") {} diff --git a/gecode/search/exception.hpp b/gecode/search/exception.hpp index 16b65661f1..dc7ff26dc3 100644 --- a/gecode/search/exception.hpp +++ b/gecode/search/exception.hpp @@ -56,6 +56,12 @@ namespace Gecode { namespace Search { /// Initialize with location \a l MixedBest(const char* l); }; + /// %Exception: Portfolio spoke without brancher although the hub had branchers + class GECODE_SEARCH_EXPORT SpokeNoBrancher : public Exception { + public: + /// Initialize with location \a l + SpokeNoBrancher(const char* l); + }; /// %Exception: Best solution search is not supported class GECODE_SEARCH_EXPORT NoBest : public Exception { public: diff --git a/gecode/search/par/bab.hpp b/gecode/search/par/bab.hpp index e048391bf0..218e310c34 100755 --- a/gecode/search/par/bab.hpp +++ b/gecode/search/par/bab.hpp @@ -452,6 +452,7 @@ namespace Gecode { namespace Search { namespace Par { delete best; best = nullptr; n_busy = workers(); + this->end = EndReason::NotEnded; } for (unsigned int i=1U; ireset(nullptr,0); diff --git a/gecode/search/par/dfs.hpp b/gecode/search/par/dfs.hpp index 12a94b1cb8..8e5a62c653 100755 --- a/gecode/search/par/dfs.hpp +++ b/gecode/search/par/dfs.hpp @@ -341,6 +341,7 @@ namespace Gecode { namespace Search { namespace Par { e_reset_ack_start.wait(); // All workers are marked as busy again n_busy = workers(); + this->end = EndReason::NotEnded; for (unsigned int i=1U; ireset(nullptr,0); worker(0U)->reset(s,opt().nogoods_limit); diff --git a/gecode/search/par/engine.hh b/gecode/search/par/engine.hh index 3cd196e36e..49bb533745 100644 --- a/gecode/search/par/engine.hh +++ b/gecode/search/par/engine.hh @@ -238,10 +238,18 @@ namespace Gecode { namespace Search { namespace Par { Support::Event e_search; /// Queue of solutions Support::DynamicQueue solutions; - /// Number of busy workers - volatile unsigned int n_busy; + /** + * \brief Number of busy workers + * + * A worker that steals work counts itself while it holds the path lock + * of the victim, which is busy. So the count never reaches zero while a + * stolen subtree is still uncounted, and it stays zero once it is. + */ + std::atomic n_busy; /// Whether a worker had been stopped std::atomic has_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Number of calls to next() that have started search std::atomic n_runs; /// Whether search state changed such that signal is needed @@ -265,8 +273,8 @@ namespace Gecode { namespace Search { namespace Par { Engine(const Options& o); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; //@} /// Destructor diff --git a/gecode/search/par/engine.hpp b/gecode/search/par/engine.hpp index 35ed2bf141..f466b67516 100644 --- a/gecode/search/par/engine.hpp +++ b/gecode/search/par/engine.hpp @@ -57,9 +57,9 @@ namespace Gecode { namespace Search { namespace Par { return static_cast(opt().threads); } template - forceinline bool - Engine::stopped(void) const { - return has_stopped.load(std::memory_order_acquire); + forceinline EndReason + Engine::end_reason(void) const { + return end; } @@ -126,7 +126,7 @@ namespace Gecode { namespace Search { namespace Par { scheduler_fast_admit(nullptr), scheduler_worker(nullptr), scheduler_requested(workers()), scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), - _cmd(C_WAIT), solutions(heap) { + _cmd(C_WAIT), solutions(heap), end(EndReason::NotEnded) { // Initialize termination information _n_term_not_ack = workers(); _n_not_terminated = workers(); @@ -367,10 +367,10 @@ namespace Gecode { namespace Search { namespace Par { template forceinline void Engine::busy(void) { - m_search.acquire(); - assert(n_busy > 0); - n_busy++; - m_search.release(); + // Called with the path lock of a busy victim, so without m_search + unsigned int n = n_busy.fetch_add(1U); + assert(n > 0); + (void) n; } template @@ -499,10 +499,10 @@ namespace Gecode { namespace Search { namespace Par { */ m.acquire(); Space* s = path.steal() ? path.steal(*this,d,myt,ot) : nullptr; - m.release(); - // Tell that there will be one more busy worker + // Count the thief before this worker can report that it is idle if (s != nullptr) engine().busy(); + m.release(); return s; } @@ -526,6 +526,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // No search needs to be done, take leftover solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); return s; } @@ -533,6 +534,7 @@ namespace Gecode { namespace Search { namespace Par { has_stopped.store(false, std::memory_order_release); // No more solutions? if (n_busy == 0) { + end = EndReason::Exhausted; m_search.release(); return nullptr; } @@ -553,6 +555,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // Report solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); // Make workers wait again block(); @@ -560,6 +563,8 @@ namespace Gecode { namespace Search { namespace Par { } // No more solutions or stopped? if ((n_busy == 0) || has_stopped.load(std::memory_order_acquire)) { + // Workers that still have work have been stopped + end = (n_busy == 0) ? EndReason::Exhausted : EndReason::Limit; m_search.release(); // Make workers wait again block(); diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index 5977f8827f..ca0ad8945c 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -60,6 +60,8 @@ namespace Gecode { namespace Search { namespace Par { guidance(*o.guidance), best(guidance.sense), order(0), pending(heap), n_pending(0), runners(nullptr), active(0), running(false), shutdown(false), _stopped(false), _limited(false), + _exhausted(false), + end(EndReason::NotEnded), batch(1), keyed(false) {} void @@ -163,6 +165,11 @@ namespace Gecode { namespace Search { namespace Par { running = false; } + bool + Frontier::drained(void) const { + return (n_pending == 0) && !open() && (active == 0) && !can_advance(); + } + void Frontier::work(unsigned int id) { // The leased task and the incumbent used for constraining its children @@ -212,8 +219,10 @@ namespace Gecode { namespace Search { namespace Par { return; } while (running && enabled && (task == nullptr)) { - if ((n_pending == 0) && !open() && (active == 0) && !advance()) + if ((n_pending == 0) && !open() && (active == 0) && !advance()) { running = false; + _exhausted = !_limited; + } if (!running || ((n_pending == 0) && !open())) break; if (n_pending > 0) { @@ -335,6 +344,15 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(error); if (_limited) { _stopped = true; + end = EndReason::Incomplete; + return nullptr; + } + // An exhausted search is complete, even when a limit has been reached + if (drained()) + _exhausted = true; + if (_exhausted) { + _stopped = false; + end = EndReason::Exhausted; return nullptr; } _stopped = false; @@ -348,7 +366,16 @@ namespace Gecode { namespace Search { namespace Par { continue; if (error) std::rethrow_exception(error); - return solution.release(); + Space* s = solution.release(); + if (s != nullptr) + end = EndReason::NotEnded; + else if (_limited) + end = EndReason::Incomplete; + else if (_exhausted || drained()) + end = EndReason::Exhausted; + else + end = _stopped ? EndReason::Limit : EndReason::Exhausted; + return s; } } @@ -358,16 +385,10 @@ namespace Gecode { namespace Search { namespace Par { return stat; } - bool - Frontier::stopped(void) const { - Support::Lock lock(mutex); - return _stopped; - } - - bool - Frontier::limited(void) const { + EndReason + Frontier::end_reason(void) const { Support::Lock lock(mutex); - return _limited; + return end; } void @@ -391,7 +412,8 @@ namespace Gecode { namespace Search { namespace Par { best.reset(); solution.reset(); order = 0; - _stopped = _limited = false; + _stopped = _limited = _exhausted = false; + end = EndReason::NotEnded; error = nullptr; stat.reset(); initialize(s,false); diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index 23a5075a5a..a2810783a4 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -110,6 +110,10 @@ namespace Gecode { namespace Search { namespace Par { unsigned int active; /// Whether search is running, being shut down, stopped, or limited bool running, shutdown, _stopped, _limited; + /// Whether search has exhausted its search space + bool _exhausted; + /// Why the last call to next() returned no solution + EndReason end; /// First exception thrown by a worker std::exception_ptr error; @@ -123,6 +127,8 @@ namespace Gecode { namespace Search { namespace Par { virtual void submit(const Entry& e, bool leased) = 0; /// Called when all work is done, return whether there is new work virtual bool advance(void) = 0; + /// Whether advance() would find new work, without changing anything + virtual bool can_advance(void) const = 0; /// Delete all open nodes virtual void clear(void) = 0; /// Called with the root \a r when search starts @@ -153,6 +159,8 @@ namespace Gecode { namespace Search { namespace Par { bool enabled(unsigned int id); /// Run worker \a id void work(unsigned int id); + /// Whether no work is left (called with the mutex held) + bool drained(void) const; public: /// Destructor ~Frontier(void) override; @@ -160,10 +168,8 @@ namespace Gecode { namespace Search { namespace Par { Space* next(void) override; /// Return statistics Search::Statistics statistics(void) const override; - /// Whether search has been stopped - bool stopped(void) const override; - /// Whether search stopped at the width or frontier limit - bool limited(void) const override; + /// Return why the last call to next() returned no solution + EndReason end_reason(void) const override; /// Constrain future solutions to be better than \a s void constrain(const Space& s) override; /// Reset engine to restart at space \a s diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 2c8e06f0a8..35f99504ad 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -40,11 +40,31 @@ namespace Gecode { namespace Search { namespace Par { + Statistics + PortfolioStatistics::update(unsigned int i, const Statistics& s) { + Support::Lock lock(m); + stat[i + 1] = s; + Statistics t; + for (unsigned int j = 0U; j < n; j++) + t += stat[j]; + return t; + } + bool PortfolioStop::stop(const Statistics& s, const Options& o) { - return tostop->load(std::memory_order_acquire) || - ((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o)); + if (tostop->load(std::memory_order_acquire)) { + pbs_record_cause(_cause,PortfolioStopCause::Interrupt); + return true; + } + if ((po != nullptr) && po->stop(ps->update(asset,s),o)) { + pbs_record_cause(_cause,PortfolioStopCause::Portfolio); + return true; + } + if ((so != nullptr) && so->stop(s,o)) { + pbs_record_cause(_cause,PortfolioStopCause::Asset); + return true; + } + return false; } void diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index fb180a69f0..5c48ba69dd 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -39,12 +39,44 @@ #define GECODE_SEARCH_PAR_PBS_HH #include +#include #include #include namespace Gecode { namespace Search { namespace Par { - /// Stop object used for controlling assets in a portfolio + /** + * \brief Statistics of the assets of a parallel portfolio + * + * Each asset records the statistics that its engine passes to its stop + * object. For an asset with a parallel engine, these are the statistics + * of the worker that checks the stop object. + */ + class GECODE_SEARCH_EXPORT PortfolioStatistics { + private: + /// Mutex for access + Support::Mutex m; + /// Number of entries: propagating the model and one for each asset + unsigned int n; + /// Statistics of propagating the model followed by those of each asset + Statistics* stat; + + public: + /// Initialize with statistics \a s of propagating the model for \a n assets + PortfolioStatistics(const Statistics& s, unsigned int n); + /// Record statistics \a s of asset \a i and return those of the portfolio + Statistics update(unsigned int i, const Statistics& s); + /// Delete + ~PortfolioStatistics(void); + }; + + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets @@ -55,15 +87,28 @@ namespace Gecode { namespace Search { namespace Par { WorkerControl worker_control; /// Whether search must be stopped std::atomic* tostop; + /// Statistics of the portfolio + PortfolioStatistics* ps; + /// Index of the asset + unsigned int asset; + /// Which stop object stopped the asset + std::atomic _cause; public: /// Initialize with asset stop \a so, portfolio stop \a po, and \a control PortfolioStop(Stop* so, Stop* po, const WorkerControl& control); - /// Set pointer to shared \a tostop variable - void share(std::atomic* ts); + /// Share stop flag \a ts and statistics \a ps of the portfolio with asset \a i + void share(std::atomic* ts, PortfolioStatistics* ps, + unsigned int i); /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); + /// Record the final statistics \a s of the asset with the portfolio + void record(const Statistics& s); /// Wake workers so that a paused asset can observe the portfolio stop void wake(void); + /// Forget which stop object stopped the asset + void reset(void); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; /// Signal whether search must be stopped void stop(bool s); /// Whether search must be stopped @@ -97,23 +142,37 @@ namespace Gecode { namespace Search { namespace Par { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: - /// Initialize with portfolio \a p, engine \a e, and its stop object \a so - Asset(PBS* p, Engine* e, Stop* so); + /// Initialize with portfolio \a p, engine \a e, its stop object \a so, and the coverage \a c of its spoke + Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; /// Return the completion terminator virtual Support::Terminator* terminator(void) const; /// Wait for the asset to complete its current run void wait(void); + /// Restore the completion of a run that could not be started + void restore(void); + /// Record the final statistics of the asset with the portfolio + void record(void); /// 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); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; + /// Set whether the asset is parked + void parked(bool p); + /// Whether the asset is parked + bool parked(void) const; /// Perform one run virtual void run(void); /// Delete asset @@ -173,16 +232,20 @@ namespace Gecode { namespace Search { namespace Par { protected: /// Statistics of propagating the model Statistics stat; + /// Statistics of the portfolio for its stop object + PortfolioStatistics portfolio_stat; /// Asset engines Asset** assets; /// Number of asset engines unsigned int n_assets; /// Number of active asset engines unsigned int n_active; - /// Whether an asset has been stopped - std::atomic asset_stop; - /// Whether an asset stopped at a local limit - bool incomplete; + /// Whether the stop object of the portfolio has stopped an asset + std::atomic portfolio_stop; + /// Whether an asset has proven that no further solution exists + bool exhausted; + /// Why the last call to next() returned no solution + EndReason end; /// Shared stop flag std::atomic tostop; /// Collect solutions in this @@ -199,23 +262,34 @@ namespace Gecode { namespace Search { namespace Par { bool report(Asset* asset, Space* s); /// Process failure from asset void fail(void); + /** + * \brief Handle that asset \a i could not be started + * + * Of the \a n assets that the current round did not start, the first + * is \a i. Must be called with the mutex held, from the handler of the + * exception, and returns with the mutex released once the started + * assets are idle. + */ + void launch_failed(unsigned int i, unsigned int n); /** * 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 assets 0..n_active-1 still might not have exhausted their - * search space. - * - the assets n_active..n_assets-1 have exhausted their search space. + * search space, the parked ones among them are not run until the + * next call to next(). + * - the assets n_active..n_assets-1 have ended without a proof. */ public: - /// Initialize - PBS(Engine** s, Stop** so, unsigned int n, const Statistics& stat); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** s, Stop** so, const SpokeCoverage* c, unsigned int n, + const Statistics& stat); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 73c28cff03..0ff6ad3735 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -131,39 +131,65 @@ namespace Gecode { namespace Search { namespace Par { } + forceinline + PortfolioStatistics::PortfolioStatistics(const Statistics& s, unsigned int n0) + : n(n0 + 1), stat(heap.alloc(n0 + 1)) { + stat[0] = s; + } + + forceinline + PortfolioStatistics::~PortfolioStatistics(void) { + heap.free(stat, n); + } + forceinline PortfolioStop::PortfolioStop(Stop* so0, Stop* po0, const WorkerControl& control) - : so(so0), po(po0), worker_control(control), tostop(nullptr) {} + : so(so0), po(po0), worker_control(control), tostop(nullptr), ps(nullptr), asset(0U), + _cause(PortfolioStopCause::None) {} + + forceinline void + PortfolioStop::reset(void) { + _cause.store(PortfolioStopCause::None, std::memory_order_relaxed); + } + + forceinline PortfolioStopCause + PortfolioStop::cause(void) const { + return _cause.load(std::memory_order_relaxed); + } + + forceinline void + PortfolioStop::record(const Statistics& s) { + (void) ps->update(asset,s); + } forceinline void - PortfolioStop::share(std::atomic* ts) { + PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, unsigned int i) { tostop = ts; + ps = ps0; + asset = i; } template forceinline - Asset::Asset(PBS* p, Engine* e, Stop* so) - : Support::Runnable(false), portfolio(p), engine(e), stop(so) {} + Asset::Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c) + : Support::Runnable(false), portfolio(p), engine(e), stop(so), + _coverage(c), _parked(false) {} + template + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; + } template forceinline Statistics Asset::statistics(void) const { return engine->statistics(); } template - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); - } - template - forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } template forceinline Support::Terminator* @@ -177,6 +203,16 @@ namespace Gecode { namespace Search { namespace Par { } template forceinline void + Asset::restore(void) { + completion.terminated(); + } + template + forceinline void + Asset::record(void) { + static_cast(stop)->record(engine->statistics()); + } + template + forceinline void Asset::wake(void) { static_cast(stop)->wake(); } @@ -186,6 +222,21 @@ namespace Gecode { namespace Search { namespace Par { engine->constrain(b); } template + forceinline PortfolioStopCause + Asset::cause(void) const { + return static_cast(stop)->cause(); + } + template + forceinline void + Asset::parked(bool p) { + _parked = p; + } + template + forceinline bool + Asset::parked(void) const { + return _parked; + } + template Asset::~Asset(void) { delete engine; delete stop; @@ -195,15 +246,16 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - PBS::PBS(Engine** engines, Stop** stops, unsigned int n, - const Statistics& stat0) - : stat(stat0), assets(heap.alloc*>(n)), + PBS::PBS(Engine** engines, Stop** stops, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0) + : stat(stat0), portfolio_stat(stat0,n), + assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), incomplete(false), tostop(false), n_busy(0) { + portfolio_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); - static_cast(stops[i])->share(&tostop); + assets[i] = new Asset(this,engines[i],stops[i],c[i]); + static_cast(stops[i])->share(&tostop,&portfolio_stat,i); } } @@ -214,6 +266,12 @@ namespace Gecode { namespace Search { namespace Par { // If b is false the report should be repeated (solution was worse) bool b = true; bool wake = false; + if ((s == nullptr) && (asset->end_reason() != EndReason::Limit) && + !pbs_asset_proof(asset->end_reason(),asset->coverage())) + // The asset ended without a proof, its last stop check might not + // include its final work. Record it before taking the lock, as an + // exception from statistics() is reported by fail(), which takes it. + asset->record(); m.acquire(); if (s != nullptr) { try { @@ -229,17 +287,28 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } - } else if (asset->stopped() && !asset->limited()) { - if (!tostop.load(std::memory_order_acquire)) { - asset_stop.store(true, std::memory_order_release); + } else if (asset->end_reason() == EndReason::Limit) { + switch (asset->cause()) { + case PortfolioStopCause::Interrupt: + // The asset runs again with the next round + break; + case PortfolioStopCause::Portfolio: + portfolio_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; + break; + default: + // The stop object of the asset stopped it, the others continue + asset->parked(true); + break; } + } else if (pbs_asset_proof(asset->end_reason(),asset->coverage())) { + // Stop the other assets, no further solution exists + exhausted = true; + tostop.store(true, std::memory_order_release); + wake = true; } else { - // The asset is done or stopped at a local limit (then search is incomplete) - if (asset->limited()) - incomplete = true; - // Move asset to inactive + // The asset ended without a proof, move it to inactive unsigned int i=0; while (assets[i] != asset) i++; @@ -274,12 +343,31 @@ namespace Gecode { namespace Search { namespace Par { m.release(); } + template + void + PBS::launch_failed(unsigned int i, unsigned int n) { + // The asset did not start and so will not signal its completion + assets[i]->restore(); + if (failure == nullptr) + failure = std::current_exception(); + // Stop the assets that started and wait until they are idle + tostop.store(true, std::memory_order_release); + for (unsigned int j=0U; jwake(); + n_busy -= n; + bool started = n_busy > 0; + m.release(); + if (started) + idle.wait(); + } + template void Asset::run(void) { try { Space* s; do { + static_cast(stop)->reset(); s = engine->next(); } while (!portfolio->report(this,s)); } catch (...) { @@ -296,10 +384,28 @@ namespace Gecode { namespace Search { namespace Par { m.release(); std::rethrow_exception(f); } - if (solutions.empty()) - asset_stop.store(false, std::memory_order_release); - while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !asset_stop.load(std::memory_order_acquire)) { + if (solutions.empty()) { + if (!exhausted && portfolio_stop.load(std::memory_order_acquire)) { + // Report a portfolio stop that arrived with the solutions returned + // since, the next call resumes the assets + portfolio_stop.store(false, std::memory_order_release); + end = EndReason::Limit; + m.release(); + return nullptr; + } + // Resume the assets that their own stop objects stopped + for (unsigned int i=0U; iparked(false); + } + while (solutions.empty() && (failure == nullptr) && + !exhausted && !portfolio_stop.load(std::memory_order_acquire)) { + unsigned int n_run = 0; + for (unsigned int i=0U; iparked()) + n_run++; + if (n_run == 0) + break; + // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); @@ -307,14 +413,22 @@ namespace Gecode { namespace Search { namespace Par { assert(n_busy == 0); assert(!tostop.load(std::memory_order_acquire)); - // Run all active assets - n_busy = n_active; - for (unsigned int i=0U; iwait(); - Support::Thread::run(assets[i]); - } + // Run all active assets that are not parked + n_busy = n_run; + unsigned int n_started = 0; + for (unsigned int i=0U; iparked()) { + // Consume the previous completion before reusing this asset. The + // initial signal handles the first submission. + assets[i]->wait(); + try { + Support::Thread::run(assets[i]); + } catch (...) { + launch_failed(i,n_run-n_started); + throw; + } + n_started++; + } m.release(); // Wait for all assets to become idle idle.wait(); @@ -324,9 +438,6 @@ namespace Gecode { namespace Search { namespace Par { // Invariant all assets are idle! assert(n_busy == 0); - if (solutions.empty() && (n_active == 0) && incomplete) - asset_stop.store(true, std::memory_order_release); - // Report a stored failure before broadcasting a solution, which could // call into the failed asset and replace the original exception. if (failure != nullptr) { @@ -340,7 +451,18 @@ namespace Gecode { namespace Search { namespace Par { // Process solutions if (solutions.empty()) { s = nullptr; + if (exhausted) + end = EndReason::Exhausted; + else if (portfolio_stop.exchange(false, std::memory_order_acq_rel) || + (n_active > 0)) + // Stopped by the portfolio stop object, or only parked assets remain, + // the next call resumes the assets + end = EndReason::Limit; + else + // All assets ended without a proof + end = EndReason::Incomplete; } else { + end = EndReason::NotEnded; Asset* r; s = solutions.get(r); if (Collect::best) { @@ -363,9 +485,9 @@ namespace Gecode { namespace Search { namespace Par { } template - bool - PBS::stopped(void) const { - return asset_stop.load(std::memory_order_acquire); + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/pbs.cpp b/gecode/search/pbs.cpp index 70116536ac..6bcaf91b4b 100644 --- a/gecode/search/pbs.cpp +++ b/gecode/search/pbs.cpp @@ -46,12 +46,13 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); else - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); } }}} @@ -73,12 +74,12 @@ namespace Gecode { namespace Search { namespace Par { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); else - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); } }}} diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index b5d2a67c9e..041bb3225d 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -64,16 +64,6 @@ namespace Gecode { namespace Search { throw WorkerControlInUse("PBS::PBS"); } - /// Return the number of explicit builders admitted by this portfolio - forceinline int - pbsadmitted(const SEBs& sebs, const Options& opt) { -#ifdef GECODE_HAS_THREADS - if (opt.threads > 1.0) - return std::min(static_cast(opt.threads),sebs.size()); -#endif - return sebs.size(); - } - /// Validate worker-control placement for an explicit portfolio forceinline void pbscontrol(const SEBs& sebs, const Options& opt) { @@ -84,8 +74,7 @@ namespace Gecode { namespace Search { #else const bool parallel = false; #endif - int admitted = pbsadmitted(sebs,opt); - for (int i=0; ioptions().worker_control; if (!x.engaged()) continue; @@ -129,109 +118,81 @@ namespace Gecode { namespace Search { }; /** - * \brief Cutoff sequence shared by the assets of a portfolio + * \brief Return the cutoff for the next asset of a portfolio * - * A cutoff cannot be copied, so the assets of a portfolio that each take - * ownership of a cutoff get a PbsCutoff each, drawing from one sequence. - * The sequence is disposed with the last PbsCutoff and the reference held - * while the portfolio is built. The original cutoff is disposed as well - * only if building has succeeded, otherwise it stays with the caller. + * When the assets of engine \a E take ownership of the cutoff \a c, + * each asset gets its own copy of \a c, and the portfolio deletes \a c + * once it has been built. Otherwise the assets share \a c and the caller + * keeps it. * * \internal */ - class PbsCutoffs : public HeapAllocated { - public: - /// Mutex protecting the sequence, assets can run in parallel - Support::Mutex m; - /// The shared cutoff sequence - Cutoff* c; - /// Number of references - unsigned int n; - /// Whether the cutoff sequence is disposed with the last reference - bool owner; - /// Initialize for cutoff \a c0 with the reference held while building - PbsCutoffs(Cutoff* c0) : c(c0), n(1U), owner(false) {} - /// Release a reference - static void release(PbsCutoffs* s) { - bool last; - { - Support::Lock lock(s->m); - last = (--s->n == 0U); - } - if (last) { - if (s->owner) - delete s->c; - delete s; - } - } - }; + template + forceinline std::unique_ptr + pbs_cutoff(const Cutoff* c) { + if (!PbsOwnsCutoff::value || (c == nullptr)) + return nullptr; + return std::unique_ptr(c->copy()); + } /** - * \brief Cutoff of a portfolio asset, the assets share the sequence of values + * \brief Delete the cutoff \a c of a built portfolio if its assets of + * engine \a E own copies + * * \internal */ - class PbsCutoff : public Cutoff { - protected: - /// The shared sequence - PbsCutoffs* s; - /// The current cutoff value of this asset - unsigned long long int v; - public: - /// Initialize as a new reference to \a s0 - PbsCutoff(PbsCutoffs* s0) : s(s0) { - Support::Lock lock(s->m); - v = (*s->c)(); - s->n++; - } - /// Return the current cutoff value - unsigned long long int operator ()(void) const override { - return v; - } - /// Take the next value of the shared sequence and return it - unsigned long long int operator ++(void) override { - Support::Lock lock(s->m); - v = ++(*s->c); - return v; - } - /// Release the reference to the shared sequence - ~PbsCutoff(void) override { - PbsCutoffs::release(s); - } - }; + template + forceinline void + pbs_release_cutoff(Cutoff* c) { + if (PbsOwnsCutoff::value) + delete c; + } /** - * \brief Return the cutoffs shared by the assets of a portfolio - * - * Returns nullptr if the assets of engine \a E do not take ownership of - * the cutoff in \a opt, or if there are fewer than two assets. + * \brief Run hub() with MetaEvent::Start on the hub \a hub of a portfolio + * of \a n assets and propagate it * - * \internal + * Return EndReason::NotEnded if the portfolio must be built. Otherwise + * delete \a hub and return EndReason::Exhausted if the hub failed or + * EndReason::Incomplete if hub() decided to finish. */ - template - forceinline PbsCutoffs* - make_pbs_cutoffs(const Options& opt, unsigned int n_assets) { - if (!PbsOwnsCutoff::value || (opt.cutoff == nullptr) || - (n_assets < 2U)) - return nullptr; - return new PbsCutoffs(opt.cutoff); + template + EndReason + pbs_start(T* hub, unsigned int n, Statistics& stat) { + std::unique_ptr owned(hub); + Statistics start; + HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, + MetaEvent::Start, + MetaDecision::Restart,0UL,0U,n, + nullptr,start,NoGoods::eng); + hub->hub(hc); + if (hub->status(stat) == SS_FAILED) { + stat.fail++; + return EndReason::Exhausted; + } + if (hc.decision() == MetaDecision::Finish) + return EndReason::Incomplete; + (void) owned.release(); + return EndReason::NotEnded; } /** - * \brief Release the cutoffs \a cs held while building - * - * The flag \a built tells whether building has succeeded. + * \brief Run spoke() on the spoke \a s of asset \a i of \a n and return + * its coverage * - * \internal + * Throw SpokeNoBrancher if the hub had branchers (\a hub_branchers) and + * \a s has none, as the spoke would then be taken as a solution. */ - forceinline void - release_pbs_cutoffs(PbsCutoffs* cs, bool built) { - if (cs == nullptr) - return; - { - Support::Lock lock(cs->m); - cs->owner = built; - } - PbsCutoffs::release(cs); + forceinline SpokeCoverage + pbs_spoke(Space& s, unsigned int i, unsigned int n, bool hub_branchers) { + Statistics start; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, + MetaEvent::Start,0UL,i,n, + nullptr,start,NoGoods::eng); + s.spoke(sc); + if (hub_branchers && !s.failed() && (BrancherGroup::all.size(s) == 0U)) + throw SpokeNoBrancher("PBS::PBS"); + return sc.coverage(); } /// A PBS engine builder @@ -272,8 +233,9 @@ namespace Gecode { namespace Search { namespace Seq { /// Create sequential portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best); }}} @@ -289,8 +251,8 @@ namespace Gecode { namespace Search { namespace Par { /// Create parallel portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best); }}} @@ -298,7 +260,8 @@ namespace Gecode { namespace Search { template class E> Engine* - pbsseq(T* hub, const Search::Statistics& stat, Options& opt) { + pbsseq(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -311,6 +274,7 @@ namespace Gecode { namespace Search { unsigned int n_assets = opt.assets; Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; i >(opt,n_assets); try { for (unsigned int i=0U; i spoke((i == n_assets-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(); - } + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } Engine* e = Seq::pbsengine( - assets,stops,n_assets,stat,opt,E::best); - release_pbs_cutoffs(cutoffs,true); + assets,stops,coverage,n_assets,stat,opt,E::best); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } @@ -352,12 +313,14 @@ namespace Gecode { namespace Search { template class E> Engine* pbsseq(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; int n_assets = sebs.size(); Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Seq::pbsengine( - assets,stops,static_cast(n_assets),stat,opt,best); + assets,stops,coverage,static_cast(n_assets),stat,opt, + best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -399,53 +365,52 @@ namespace Gecode { namespace Search { template class E> Engine* - pbspar(T* hub, const Search::Statistics& stat, Options& opt) { + pbspar(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; Region r; - // Limit the number of assets to the number of threads - unsigned int n_assets = std::min(static_cast(opt.threads), - opt.assets); + // Run every asset in its own thread, even with fewer threads than assets + unsigned int n_assets = opt.assets; // Redistribute additional threads to assets - opt.threads = floor(opt.threads / static_cast(n_assets)); + opt.threads = std::max(floor(opt.threads / static_cast(n_assets)), 1.0); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, n_assets); Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; i >(opt,n_assets); try { for (unsigned int i=0U; i spoke((i == n_assets-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(); - } + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } - Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); - release_pbs_cutoffs(cutoffs,true); + Engine* e = Par::pbsengine(assets,stops,coverage,n_assets,stat, + E::best); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } @@ -453,12 +418,12 @@ namespace Gecode { namespace Search { template class E> Engine* pbspar(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; - // Limit the number of assets to the number of threads - int n_assets = std::min(static_cast(opt.threads), - sebs.size()); + // Run every asset in its own thread, even with fewer threads than assets + int n_assets = sebs.size(); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, @@ -466,6 +431,7 @@ namespace Gecode { namespace Search { Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Par::pbsengine( - assets,stops,static_cast(n_assets),stat,best); + assets,stops,coverage,static_cast(n_assets),stat,best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -520,7 +488,7 @@ namespace Gecode { stat.fail++; if (!opt.clone) delete s; - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); /* * The assets would own the cutoff, but a dead engine does not take * it. This includes the cutoff of an outer portfolio when this is @@ -536,25 +504,49 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - (void) hub->hub(0); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + Search::EndReason r = Search::pbs_start(hub,opt.assets,stat); + if (r != Search::EndReason::NotEnded) { + e = Search::Seq::dead(opt,stat,r); + Search::pbs_release_cutoff >(opt.cutoff); + return; + } // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - (void) hub->spoke(0); + SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U,hub_branchers); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; - e = Search::build(seed.get(),opt); + if (c != SpokeCoverage::Partial) { + e = Search::build(seed.get(),opt); + return; + } + // Only a portfolio engine reports an exhausted partial spoke as incomplete + std::unique_ptr stop(Search::Seq::pbsstop(nullptr,opt.stop)); + opt.stop = stop.get(); + // As for several assets, the asset owns a copy of the cutoff + Search::Cutoff* cutoff = opt.cutoff; + std::unique_ptr cc(Search::pbs_cutoff >(cutoff)); + if (cc != nullptr) + opt.cutoff = cc.get(); + std::unique_ptr asset(Search::build(seed.get(),opt)); + (void) cc.release(); + Search::Engine* a = asset.get(); + Search::Stop* so = stop.get(); + e = Search::Seq::pbsengine(&a,&so,&c,1U,stat,opt,E::best); + (void) asset.release(); + (void) stop.release(); + Search::pbs_release_cutoff >(cutoff); return; } #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,stat,opt); + e = Search::pbspar(hub,stat,opt,hub_branchers); else #endif - e = Search::pbsseq(hub,stat,opt); + e = Search::pbsseq(hub,stat,opt,hub_branchers); } template class E> @@ -581,7 +573,7 @@ namespace Gecode { if (!opt.clone) delete s; Search::pbscleanup(sebs); - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); return; } @@ -590,15 +582,26 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - (void) hub->hub(0); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + Search::EndReason r; + try { + r = Search::pbs_start(hub,static_cast(sebs.size()),stat); + } catch (...) { + Search::pbscleanup(sebs); + throw; + } + if (r != Search::EndReason::NotEnded) { + Search::pbscleanup(sebs); + e = Search::Seq::dead(opt,stat,r); + return; + } #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,sebs,stat,opt,best); + e = Search::pbspar(hub,sebs,stat,opt,best,hub_branchers); else #endif - e = Search::pbsseq(hub,sebs,stat,opt,best); + e = Search::pbsseq(hub,sebs,stat,opt,best,hub_branchers); } template class E> diff --git a/gecode/search/rbs.cpp b/gecode/search/rbs.cpp index 1b78157317..f54e6ff54d 100644 --- a/gecode/search/rbs.cpp +++ b/gecode/search/rbs.cpp @@ -43,15 +43,15 @@ namespace Gecode { namespace Search { namespace Seq { Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best) { - return rbsengine(hub,stop,engine,stat,opt,best,true); + return rbsengine(hub,stop,engine,stat,opt,best,SpokeCoverage::Full); } Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best, - bool complete) { + SpokeCoverage coverage) { return new RBS(hub,static_cast(stop), engine, - stat,opt,best,complete); + stat,opt,best,coverage); } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 89ffef358a..6352e9328d 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -43,7 +43,7 @@ namespace Gecode { namespace Search { namespace Seq { GECODE_SEARCH_EXPORT Stop* rbsstop(Stop* so); - /// Create restart engine whose first spoke search yields valid no-goods + /// Create restart engine whose first spoke has SpokeCoverage::Full GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, @@ -52,14 +52,13 @@ namespace Gecode { namespace Search { namespace Seq { /** * \brief Create restart engine * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first \a engine. It only determines whether - * the no-goods of that search hold in the hub. + * The value \a coverage is the coverage that the spoke hook declared for + * the space explored by the first \a engine. */ GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, - bool best, bool complete); + bool best, SpokeCoverage coverage); }}} @@ -108,18 +107,37 @@ namespace Gecode { stat.fail++; if (!m_opt.clone) delete s; - e = Search::Seq::dead(e_opt, stat); + e = Search::Seq::dead(e_opt,stat,Search::EndReason::Exhausted); // The engine owns the cutoff, but a dead engine does not take it delete m_opt.cutoff; } else { std::unique_ptr hub(m_opt.clone ? s->clone() : s); + Search::Statistics start; + HubContext hc = Search::MetaContextAccess::hub( + MetaEngine::Restart,MetaEvent::Start,MetaDecision::Restart,0UL,0U,1U, + nullptr,start,NoGoods::eng); + hub->hub(hc); + if ((hub->status(stat) == SS_FAILED) || + (hc.decision() == MetaDecision::Finish)) { + // A failed hub is a proof, finishing is not + Search::EndReason r = hub->failed() ? + Search::EndReason::Exhausted : Search::EndReason::Incomplete; + if (r == Search::EndReason::Exhausted) + stat.fail++; + e = Search::Seq::dead(e_opt,stat,r); + delete m_opt.cutoff; + return; + } std::unique_ptr spoke(hub->clone()); - MetaInfo mi(0,MetaInfo::RR_INIT,0,0,nullptr,NoGoods::eng); - bool complete = spoke->spoke(mi); + SpokeContext sc = Search::MetaContextAccess::spoke( + MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, + NoGoods::eng); + spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); std::unique_ptr leaf( Search::build(spoke.get(),e_opt)); e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), - stat,m_opt,E::best,complete); + stat,m_opt,E::best,sc.coverage()); hub.release(); stop.release(); leaf.release(); diff --git a/gecode/search/seq/cabs.hh b/gecode/search/seq/cabs.hh index f75e9ed056..9b1023a30d 100644 --- a/gecode/search/seq/cabs.hh +++ b/gecode/search/seq/cabs.hh @@ -73,6 +73,8 @@ namespace Gecode { namespace Search { namespace Seq { Incumbent best; /// Whether search stopped at the width or frontier limit bool _limited; + /// Whether search has exhausted its search space + bool _exhausted; /// Offer node \a s at depth \a d to the next layer, false if no room bool admit(std::unique_ptr s, unsigned long int d); /// Make \a s the incumbent and return a copy, if it improves @@ -88,8 +90,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* next(void); /// Return statistics Statistics statistics(void) const; - /// Whether search stopped at the width or frontier limit - bool limited(void) const; + /// Return why next() returned no solution, Incomplete at the width or frontier limit + EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b void constrain(const Space& b); /// Reset engine to restart at space \a s diff --git a/gecode/search/seq/dead.cpp b/gecode/search/seq/dead.cpp index fa8ac10a07..657af57540 100644 --- a/gecode/search/seq/dead.cpp +++ b/gecode/search/seq/dead.cpp @@ -35,7 +35,7 @@ namespace Gecode { namespace Search { namespace Seq { - /// A dead engine (failed root) + /// A dead engine (failed root, or a meta engine that has finished) template class GECODE_SEARCH_EXPORT Dead : public Engine { protected: @@ -43,22 +43,28 @@ namespace Gecode { namespace Search { namespace Seq { Tracer tracer; /// Statistics Statistics stat; + /// Why next() returns no solution + EndReason reason; + /// Why the last call to next() returned no solution + EndReason end; + public: - /// Initialize - Dead(const Options& o, const Statistics& stat0); + /// Initialize, next() returns no solution for reason \a r + Dead(const Options& o, const Statistics& stat0, EndReason r); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Delete virtual ~Dead(void); }; template - Dead::Dead(const Options& o, const Statistics& stat0) - : tracer(o.tracer), stat(stat0) { + Dead::Dead(const Options& o, const Statistics& stat0, + EndReason r) + : tracer(o.tracer), stat(stat0), reason(r), end(EndReason::NotEnded) { tracer.engine(SearchTracer::EngineType::AOE, 1U); tracer.worker(); } @@ -66,13 +72,14 @@ namespace Gecode { namespace Search { namespace Seq { template Space* Dead::next(void) { + end = reason; return nullptr; } template - bool - Dead::stopped(void) const { - return false; + EndReason + Dead::end_reason(void) const { + return end; } template @@ -87,11 +94,11 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - dead(const Options& o, const Statistics& stat) { + dead(const Options& o, const Statistics& stat, EndReason r) { if (o.tracer) - return new Dead(o,stat); + return new Dead(o,stat,r); else - return new Dead(o,stat); + return new Dead(o,stat,r); } diff --git a/gecode/search/seq/dead.hh b/gecode/search/seq/dead.hh index 4844a59f30..4355bfbb15 100644 --- a/gecode/search/seq/dead.hh +++ b/gecode/search/seq/dead.hh @@ -38,8 +38,9 @@ namespace Gecode { namespace Search { namespace Seq { + /// Create an engine without solutions whose next() ends for reason \a r GECODE_SEARCH_EXPORT - Engine* dead(const Options& o, const Statistics& stat); + Engine* dead(const Options& o, const Statistics& stat, EndReason r); }}} diff --git a/gecode/search/seq/lds.hh b/gecode/search/seq/lds.hh index d95869b55a..35e42f91c9 100644 --- a/gecode/search/seq/lds.hh +++ b/gecode/search/seq/lds.hh @@ -112,8 +112,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* root; /// Current discrepancy unsigned int d; - /// Solution found for current discrepancy - bool no_solution; + /// Why the last call to next() returned no solution + EndReason end; public: /// Initialize for space \a s with options \a o LDS(Space* s, const Options& o); @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Seq { void constrain(const Space& b); /// Reset engine to restart at space \a s void reset(Space* s); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~LDS(void); }; diff --git a/gecode/search/seq/lds.hpp b/gecode/search/seq/lds.hpp index 6a19404392..257b63e19e 100644 --- a/gecode/search/seq/lds.hpp +++ b/gecode/search/seq/lds.hpp @@ -276,7 +276,7 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline LDS::LDS(Space* s, const Options& o) - : opt(o), e(opt), root(nullptr), d(0) { + : opt(o), e(opt), root(nullptr), d(0) , end(EndReason::NotEnded) { e.node = 1; if (s->status(e) == SS_FAILED) { e.fail++; @@ -295,10 +295,23 @@ namespace Gecode { namespace Search { namespace Seq { LDS::next(void) { while (true) { Space* s = e.next(opt); - if (s != nullptr) + if (s != nullptr) { + end = EndReason::NotEnded; return s; - if (((s == nullptr) && e.stopped()) || (++d > opt.d_l) || e.done()) + } + if (e.stopped()) { + end = EndReason::Limit; + break; + } + if (e.done()) { + end = EndReason::Exhausted; break; + } + // Choices with more discrepancies than the limit were not explored + if (++d > opt.d_l) { + end = EndReason::Incomplete; + break; + } if (d == opt.d_l) { if (root != nullptr) e.reset(root,d); @@ -311,9 +324,9 @@ namespace Gecode { namespace Search { namespace Seq { } template - bool - LDS::stopped(void) const { - return e.stopped(); + EndReason + LDS::end_reason(void) const { + return end; } template @@ -327,6 +340,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline void LDS::reset(Space* s) { delete root; root=nullptr; d=0; + end = EndReason::NotEnded; // Reset the statistics first, so that a failed root is counted e.reset(nullptr,0); if (s == nullptr) diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 1e79557f76..59bac5b394 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -37,13 +37,23 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - if (((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o))) { - ssi->done = false; + if (po != nullptr) { + Statistics others; + { + Support::Lock lock(ssi->m); + others = ssi->others; + } + if (po->stop(others + s,o)) { + pbs_record_cause(ssi->cause,PortfolioStopCause::Portfolio); + return true; + } + } + if ((so != nullptr) && so->stop(s,o)) { + pbs_record_cause(ssi->cause,PortfolioStopCause::Asset); return true; } if (s.fail >= ssi->l) { - ssi->done = true; + pbs_record_cause(ssi->cause,PortfolioStopCause::Slice); return true; } return false; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index ef6cf4537b..4201b5a710 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -35,19 +35,36 @@ #define GECODE_SEARCH_SEQ_PBS_HH #include +#include namespace Gecode { namespace Search { namespace Seq { - /// Shared stop information + /** + * \brief Shared stop information + * + * A worker of a parallel asset can check its stop object after next() + * of the asset has returned, while the portfolio already prepares the + * next asset. + */ class SharedStopInfo { public: - /// Whether search stopped because the slice is done - bool done; + /// Which stop object stopped the running asset, its workers can run in parallel + std::atomic cause; /// The current failure limit, incremented for each slice - unsigned long long int l; + std::atomic l; + /// Mutex protecting others + Support::Mutex m; + /// Statistics of the portfolio except for the running asset + Statistics others; }; - /// Stop object used for controlling assets in a portfolio + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets @@ -61,6 +78,8 @@ namespace Gecode { namespace Search { namespace Seq { PortfolioStop(Stop* so, Stop* po=nullptr); /// Initialize shared stop information void share(SharedStopInfo* ssi); + /// Whether the portfolio has a stop object + bool portfolio_stop(void) const; /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); }; @@ -72,6 +91,10 @@ namespace Gecode { namespace Search { namespace Seq { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: /// Default constructor Asset(void); @@ -79,20 +102,26 @@ namespace Gecode { namespace Search { namespace Seq { Asset(const Asset& s) = default; /// Assignment operator Asset& operator =(const Asset& s) = default; - /// Initialize with engine \a e and its stop object \a so - void init(Engine* e, Stop* so); + /// Initialize with engine \a e, its stop object \a so, and the coverage \a c of its spoke + void init(Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return next solution Space* next(void); /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; + /// Whether the portfolio has a stop object + bool portfolio_stop(void) const; /// Constrain with better solution \a b void constrain(const Space& b); - /// Perform one run - void run(void); + /// Park the asset after its stop object stopped it + void park(void); + /// Resume a parked asset + void resume(void); + /// Whether the asset is parked + bool parked(void) const; /// Delete asset ~Asset(void); }; @@ -113,20 +142,18 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_assets; /// Current asset to run unsigned int cur; - /// Whether an asset has been stopped - bool asset_stop; - /// Whether an asset stopped at a local limit - bool incomplete; + /// Why the last call to next() returned no solution + EndReason end; public: - /// Initialize - PBS(Engine** assets, Stop** stops, unsigned int n, - const Statistics& stat, const Search::Options& opt); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n, const Statistics& stat, const Search::Options& opt); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 4164993c59..d49339d42a 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -43,14 +43,24 @@ namespace Gecode { namespace Search { namespace Seq { PortfolioStop::share(SharedStopInfo* ssi0) { ssi = ssi0; } + forceinline bool + PortfolioStop::portfolio_stop(void) const { + return po != nullptr; + } forceinline Asset::Asset(void) - : engine(nullptr), stop(nullptr) {} + : engine(nullptr), stop(nullptr), _coverage(SpokeCoverage::Full), + _parked(false) {} forceinline void - Asset::init(Engine* e, Stop* so) { + Asset::init(Engine* e, Stop* so, SpokeCoverage c) { engine = e; stop = so; + _coverage = c; + } + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; } forceinline Space* Asset::next(void) { @@ -60,24 +70,31 @@ namespace Gecode { namespace Search { namespace Seq { Asset::statistics(void) const { return engine->statistics(); } - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + Asset::portfolio_stop(void) const { + return static_cast(stop)->portfolio_stop(); } forceinline void Asset::constrain(const Space& b) { engine->constrain(b); } - forceinline - Asset::~Asset(void) { + forceinline void + Asset::park(void) { + _parked = true; + } + forceinline void + Asset::resume(void) { + _parked = false; + } + forceinline bool + Asset::parked(void) const { + return _parked; + } + forceinline Asset::~Asset(void) { delete engine; delete stop; } @@ -85,17 +102,18 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline - PBS::PBS(Engine** e, Stop** s, unsigned int n, - const Statistics& stat0, + PBS::PBS(Engine** e, Stop** s, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0, const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), - asset_stop(false), incomplete(false) { - ssi.done = false; - ssi.l = opt.slice; + end(EndReason::NotEnded) { + ssi.cause = PortfolioStopCause::None; + // A single asset needs no slices, and a slice of zero would never end + ssi.l = (n == 1U) ? ULLONG_MAX : opt.slice; for (unsigned int i=0U; i(s[i])); + assets[i].init(e[i],static_cast(s[i]),c[i]); static_cast(s[i])->share(&ssi); } } @@ -103,10 +121,31 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { - asset_stop = false; - unsigned int n_exhausted = 0; + // An asset has proven that no further solution exists + if (end == EndReason::Exhausted) + return nullptr; + // Resume the assets that their own stop objects stopped + for (unsigned int i=0U; i 0) { - ssi.done = false; + if (assets[cur].parked()) { + if (++cur == n_assets) + cur = 0; + continue; + } + ssi.cause = PortfolioStopCause::None; + // Only the stop object of the portfolio uses the other assets + if (assets[cur].portfolio_stop()) { + Statistics others(stat); + for (unsigned int i=0U; i 0) && (n_parked == n_assets)) { + // Only parked assets remain, they resume with the next call + end = EndReason::Limit; + return nullptr; + } + if (n_sliced + n_parked == n_assets) { + n_sliced = 0; + // Increment by one slice, a single asset has no limit to increment + if (n_assets > 1) + ssi.l += slice; + } } - asset_stop = incomplete; + // All assets ended without a proof + end = EndReason::Incomplete; return nullptr; } template - bool - PBS::stopped(void) const { - return asset_stop; + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index de656bee86..c08a9cf10c 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -38,16 +38,31 @@ #include +#include +#include + namespace Gecode { namespace Search { namespace Seq { + namespace { + + /// Return the default decision of hub() for event \a ev after a spoke of coverage \a c + MetaDecision + default_decision(MetaEvent ev, SpokeCoverage c) { + // A new spoke would repeat an incomplete search of a spoke that is not partial + if ((ev == MetaEvent::Incomplete) && (c != SpokeCoverage::Partial)) + return MetaDecision::Finish; + return MetaDecision::Restart; + } + + } + bool RestartStop::stop(const Statistics& s, const Options& o) { Support::Lock lock(m); // Stop if the fail limit for the engine says so if (s.fail > l) { - if (!e_stopped) - m_stat.restart++; e_stopped = true; + e_fail = std::max(e_fail,s.fail); return true; } // Stop if the stop object for the meta engine says so @@ -66,9 +81,8 @@ namespace Gecode { namespace Search { namespace Seq { NoGoods& RBS::hub_nogoods(void) { - // The no-goods of an incomplete spoke search only hold in its restricted - // search space, not in the hub. - if (!nogoods_valid) + // The no-goods hold in the hub only for a spoke of full coverage + if (coverage != SpokeCoverage::Full) return NoGoods::eng; NoGoods& ng = e->nogoods(); // Reset number of no-goods found @@ -76,82 +90,120 @@ namespace Gecode { namespace Search { namespace Seq { return ng; } + bool + RBS::hub_event(MetaEvent ev) { + // Constrain the hub with a new solution, whatever hub() does + if ((ev == MetaEvent::Solution) && best) + hub->constrain(*last); + Search::Statistics episode_stat = e->statistics(); + NoGoods& ng = hub_nogoods(); + HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev, + default_decision(ev,coverage), + episode,0U,1U,last,episode_stat, + ng); + hub->hub(hc); + stop->nogood(ng.ng()); + MetaDecision d = hc.decision(); + if (stop->status(hub) == SS_FAILED) { + // A failed hub proves that no further solution exists + stop->update(e->statistics()); + delete hub; + hub = nullptr; + e->reset(nullptr); + end = EndReason::Exhausted; + return false; + } + switch (d) { + case MetaDecision::Finish: + end = EndReason::Incomplete; + return false; + case MetaDecision::Continue: + // After a limit, the episode continues with the next cutoff as budget + if (ev == MetaEvent::Limit) + stop->extend(++(*co)); + return true; + case MetaDecision::Restart: + break; + default: + GECODE_NEVER; + } + stop->restart(); + // A restart after a solution keeps the cutoff, not an extended limit + if (ev == MetaEvent::Solution) + stop->renew(e->statistics()); + else + stop->limit(e->statistics(),++(*co)); + // The old hub becomes the spoke, which is deleted if spoke() throws + std::unique_ptr next_hub(hub->clone()); + std::unique_ptr spoke(hub); + hub = next_hub.release(); + episode++; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, + 0U,1U,last,episode_stat,ng); + spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); + coverage = sc.coverage(); + e->reset(spoke.release()); + return true; + } + Space* RBS::next(void) { - // A failed hub proves that no further solution exists - if (hub == nullptr) + // A proof or a decision to finish ends the search + if ((end == EndReason::Exhausted) || (end == EndReason::Incomplete)) return nullptr; - m_stopped = false; - if (restart) { - restart = false; - sslr++; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),MetaInfo::RR_SOL,sslr,e->statistics().fail,last,ng); - bool r = hub->hub(mi); - stop->nogood(ng.ng()); - if (stop->status(hub) == SS_FAILED) { - stop->update(e->statistics()); - delete hub; - hub = nullptr; - e->reset(nullptr); + if (solution) { + solution = false; + if (!hub_event(MetaEvent::Solution)) return nullptr; - } else if (r) { - stop->update(e->statistics()); - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - sslr = 0; - stop->restart(); - } } while (true) { Space* n = e->next(); if (n != nullptr) { // The engine found a solution - restart = true; + solution = true; delete last; last = n->clone(); + end = EndReason::NotEnded; return n; - } else if ( (!complete && !e->stopped()) || - (e->stopped() && stop->enginestopped()) ) { - // The engine must perform a true restart - // The number of the restart has been incremented in the stop object - if (!complete && !e->stopped()) { - /* - * The engine might not have checked its stop object, for example - * when the spoke failed at the root or a parallel engine had no - * work. Without this check, the restarts might never stop. - */ - if (stop->meta_stop(e->statistics(),m_opt)) { - m_stopped = true; - return nullptr; - } - stop->restart(); + } + MetaEvent ev; + switch (e->end_reason()) { + case EndReason::Limit: + if (!stop->enginestopped()) { + // A stop from above + end = EndReason::Limit; + return nullptr; } - sslr = 0; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),e->stopped() ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); - (void) hub->hub(mi); - stop->nogood(ng.ng()); - unsigned long long int nl = ++(*co); - stop->limit(e->statistics(),nl); - if (stop->status(hub) == SS_FAILED) { - // The statistics of the engine have been added by limit() - delete hub; - hub = nullptr; - e->reset(nullptr); + ev = MetaEvent::Limit; + break; + case EndReason::Exhausted: + if (coverage != SpokeCoverage::Partial) { + // The spoke covers the hub, so this is a proof + end = EndReason::Exhausted; return nullptr; } - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - } else { + ev = MetaEvent::Exhausted; + break; + case EndReason::Incomplete: + ev = MetaEvent::Incomplete; + break; + default: + GECODE_NEVER; + return nullptr; + } + /* + * The engine might not have checked its stop object, for example + * when the spoke failed at the root or a parallel engine had no + * work. Without this check, the restarts might never stop. + */ + if ((ev != MetaEvent::Limit) && + stop->meta_stop(e->statistics(),m_opt)) { + end = EndReason::Limit; return nullptr; } + if (!hub_event(ev)) + return nullptr; } GECODE_NEVER; return nullptr; @@ -176,19 +228,16 @@ namespace Gecode { namespace Search { namespace Seq { e->constrain(b); } - bool - RBS::stopped(void) const { + EndReason + RBS::end_reason(void) const { /* - * What might happen during parallel search is that the - * engine has been stopped but the meta engine has not, so - * the meta engine does not perform a restart. However the - * invocation of next will do so and no restart will be - * missed. - * - * The engine may still report a stop when the hub failed during a - * restart after a limit. A failed hub is a proof, not a stop. + * What might happen during parallel search is that the engine has + * been stopped by the cutoff but the meta engine reports a limit, + * because the stop object of the meta engine also fired. The next + * invocation of next() then performs the restart, and no restart + * will be missed. */ - return (hub != nullptr) && (m_stopped || e->stopped()); + return end; } RBS::~RBS(void) { diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 2c57744a59..610ecb2c21 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -40,6 +40,8 @@ #include +#include + namespace Gecode { namespace Search { namespace Seq { class RBS; @@ -53,10 +55,14 @@ namespace Gecode { namespace Search { namespace Seq { mutable Support::Mutex m; /// The failure limit for the engine unsigned long long int l; + /// The last cutoff, the failure budget of the current episode + unsigned long long int c; /// The stop object for the meta engine Stop* m_stop; /// Whether the engine was stopped bool e_stopped; + /// The largest failure count of a worker that the limit stopped + unsigned long long int e_fail; /// Accumulated statistics for the meta engine Statistics m_stat; public: @@ -66,16 +72,24 @@ namespace Gecode { namespace Search { namespace Seq { virtual bool stop(const Statistics& s, const Options& o); /// Return true if the stop object for the meta engine says so bool meta_stop(const Statistics& s, const Options& o); - /// Return current restart count - unsigned long int restarts(void) const; /// Increment current restart count void restart(void); /// Add no-goods to meta statistics void nogood(unsigned long int n); /// Test hub status with meta statistics SpaceStatus status(Space* s); - /// Set current limit for the engine to \a l fails - void limit(const Statistics& s, unsigned long long int l); + /// Add statistics \a s and start an episode with cutoff \a c + void limit(const Statistics& s, unsigned long long int c); + /// Add statistics \a s and start an episode with the last cutoff + void renew(const Statistics& s); + /** + * \brief Give the engine, which continues its search, a budget of \a c fails + * + * The budget counts from the failures of the worker that the limit + * stopped, as stop() compares the failures of each worker with the + * limit. The limit saturates instead of wrapping around. + */ + void extend(unsigned long long int c); /// Update statistics void update(const Search::Statistics& s); /// Return whether the engine has been stopped @@ -99,37 +113,36 @@ namespace Gecode { namespace Search { namespace Seq { RestartStop* stop; /// The options for the stop object of the meta engine Options m_opt; - /// How many solutions since the last restart - unsigned long int sslr; - /// Whether search for the next solution will be complete - bool complete; - /// Whether the no-goods of the current spoke search hold in the hub - bool nogoods_valid; - /// Whether a restart must be performed when next is called - bool restart; + /// The current episode + unsigned long int episode; + /// The coverage of the spoke of the current episode + SpokeCoverage coverage; + /// Whether the last call to next() returned a solution that hub() has not seen + bool solution; /// Whether the engine performs best solution search bool best; - /// Whether the stop object for the meta engine stopped a restart - bool m_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Return the no-goods of the last spoke search, valid in the hub NoGoods& hub_nogoods(void); + /// Call hub() for event \a ev and act on its decision, return whether search continues + bool hub_event(MetaEvent ev); public: /** * \brief Constructor * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first engine \a e0, and is used as for the - * searches after later restarts. + * The value \a coverage is the coverage that the spoke hook declared + * for the space explored by the first engine \a e0. */ RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& o, bool best, - bool complete); + SpokeCoverage coverage); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index a4bacb56e5..8938eca1e5 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -40,13 +40,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline RestartStop::RestartStop(Stop* s) - : l(0U), m_stop(s), e_stopped(false) {} - - forceinline unsigned long int - RestartStop::restarts(void) const { - Support::Lock lock(m); - return m_stat.restart; - } + : l(0U), c(0U), m_stop(s), e_stopped(false), e_fail(0U) {} forceinline void RestartStop::restart(void) { @@ -67,11 +61,30 @@ namespace Gecode { namespace Search { namespace Seq { } forceinline void - RestartStop::limit(const Search::Statistics& s, unsigned long long int l0) { + RestartStop::limit(const Search::Statistics& s, unsigned long long int c0) { + Support::Lock lock(m); + l = c = c0; + m_stat += s; + e_stopped = false; + e_fail = 0U; + } + + forceinline void + RestartStop::renew(const Search::Statistics& s) { Support::Lock lock(m); - l = l0; + l = c; m_stat += s; e_stopped = false; + e_fail = 0U; + } + + forceinline void + RestartStop::extend(unsigned long long int c0) { + Support::Lock lock(m); + c = c0; + l = (e_fail > ULLONG_MAX - c0) ? ULLONG_MAX : e_fail + c0; + e_stopped = false; + e_fail = 0U; } forceinline void @@ -96,11 +109,11 @@ namespace Gecode { namespace Search { namespace Seq { forceinline RBS::RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& opt, - bool best0, bool complete0) + bool best0, SpokeCoverage coverage0) : e(e0), hub(s), last(nullptr), co(opt.cutoff), stop(stop0), - m_opt(opt.expand()), sslr(0), - complete(complete0), nogoods_valid(complete0), restart(false), - best(best0), m_stopped(false) { + m_opt(opt.expand()), episode(0UL), coverage(coverage0), + solution(false), + best(best0), end(EndReason::NotEnded) { stop->limit(stat,(*co)()); } diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 6cdc0b2be4..bdc54954a1 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -36,6 +36,8 @@ #include +#include + namespace Gecode { namespace Search { /// Whether incoming solution \a s should replace incumbent \a b @@ -59,12 +61,53 @@ namespace Gecode { namespace Search { forceinline Space* snapshot(Space* s, const Options& o); + /** + * \brief Whether a portfolio asset whose spoke has coverage \a c and that + * ended for reason \a r proves that the hub has no further solution + * + * Only an asset that exhausted a spoke of full or reduced coverage ends + * the portfolio with a proof. An asset that exhausted a spoke of partial + * coverage, such as a fragment for large neighbourhood search, has proven + * nothing about the hub and is dropped. + */ + forceinline bool + pbs_asset_proof(EndReason r, SpokeCoverage c) { + return (r == EndReason::Exhausted) && (c != SpokeCoverage::Partial); + } + + /** + * \brief Which stop object stopped an asset of a portfolio + * + * The causes are listed in increasing priority. When the workers of a + * parallel asset stop for different causes, the one of highest priority + * is kept (see pbs_record_cause()). + */ + enum class PortfolioStopCause : unsigned char { + None, ///< No stop object has stopped the asset + Slice, ///< The asset used up its slice of a sequential portfolio + Interrupt, ///< Another asset of a parallel portfolio interrupted the asset + Asset, ///< The stop object of the asset + Portfolio, ///< The stop object of the portfolio + }; + + /// Record cause \a c in \a cause unless a cause of higher priority is recorded + forceinline void + pbs_record_cause(std::atomic& cause, + PortfolioStopCause c) { + PortfolioStopCause r = cause.load(std::memory_order_relaxed); + while ((r < c) && + !cause.compare_exchange_weak(r,c,std::memory_order_relaxed)) {} + } + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { protected: /// The worker to wrap into an engine Worker w; + /// Why the last call to next() returned no solution + EndReason end; + public: /// Initialization WorkerToEngine(Space* s, const Options& o); @@ -72,8 +115,8 @@ namespace Gecode { namespace Search { virtual Space* next(void); /// Return statistics virtual Search::Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Reset engine to restart at space \a s @@ -92,11 +135,13 @@ namespace Gecode { namespace Search { template WorkerToEngine::WorkerToEngine(Space* s, const Options& o) - : Engine(o,1U), w(s,o) {} + : Engine(o,1U), w(s,o) , end(EndReason::NotEnded) {} template Space* WorkerToEngine::next(void) { - return w.next(); + Space* s = w.next(); + end = (s != nullptr) ? EndReason::NotEnded : w.end_reason(); + return s; } template Search::Statistics @@ -104,14 +149,15 @@ namespace Gecode { namespace Search { return w.statistics(); } template - bool - WorkerToEngine::stopped(void) const { - return w.stopped(); + EndReason + WorkerToEngine::end_reason(void) const { + return end; } template void WorkerToEngine::reset(Space* s) { w.reset(s); + end = EndReason::NotEnded; } template void diff --git a/gecode/search/worker.hh b/gecode/search/worker.hh index 892cd85a59..16118f8717 100644 --- a/gecode/search/worker.hh +++ b/gecode/search/worker.hh @@ -58,6 +58,8 @@ namespace Gecode { namespace Search { bool stop_seq(Options& o); /// Check whether engine has been stopped bool stopped(void) const; + /// Return why next() returned no solution: Limit if stopped, otherwise Exhausted + EndReason end_reason(void) const; /// Reset statistics with root depth \a d void reset(unsigned long int d=0); /// Record stack depth \a d @@ -102,6 +104,11 @@ namespace Gecode { namespace Search { return _stopped; } + forceinline EndReason + Worker::end_reason(void) const { + return _stopped ? EndReason::Limit : EndReason::Exhausted; + } + forceinline void Worker::reset(unsigned long int d) { Statistics::reset(); diff --git a/gecode/support/failpoint.hpp b/gecode/support/failpoint.hpp index bfdabd1d12..18f920c7ec 100644 --- a/gecode/support/failpoint.hpp +++ b/gecode/support/failpoint.hpp @@ -56,7 +56,8 @@ namespace Gecode { namespace Support { namespace FailPoint { LocalObjectCopy, SpaceDisposeNoticeArray, SpaceDisposalArray, - MiniModel + MiniModel, + ThreadLaunch }; /// Reset all failpoint state diff --git a/gecode/support/thread/thread.hpp b/gecode/support/thread/thread.hpp index bd4408d39e..a7327479a7 100644 --- a/gecode/support/thread/thread.hpp +++ b/gecode/support/thread/thread.hpp @@ -175,6 +175,9 @@ namespace Gecode { namespace Support { } inline void Thread::run(Runnable* r) { +#ifdef GECODE_HAS_FAULT_INJECTION + FailPoint::check(FailPoint::Phase::ThreadLaunch); +#endif m()->acquire(); if (idle != nullptr) { Run* i = idle; diff --git a/test/fault.cpp b/test/fault.cpp index fb4a4847a6..cce3232fc4 100644 --- a/test/fault.cpp +++ b/test/fault.cpp @@ -886,6 +886,59 @@ namespace Test { namespace Fault { } } +#ifdef GECODE_HAS_THREADS + /// Space with two solutions whose portfolio hub keeps its branchers + class PortfolioSpace : public Space { + public: + IntVar x; + PortfolioSpace(void) : x(*this,0,1) { + branch(*this,x,INT_VAL_MIN()); + } + PortfolioSpace(PortfolioSpace& s) : Space(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { + return new PortfolioSpace(*this); + } + virtual void hub(HubContext&) {} + }; + + /// A parallel portfolio reports an asset it cannot start and stays usable + bool portfolio_launch_failure(void) { + FaultScope scope; + PortfolioSpace root; + Search::Options o; + o.assets = 3; + o.threads = 3; + PBS pbs(&root,o); + // The first asset starts, the second does not + Support::FailPoint::fail_after(Phase::ThreadLaunch,1); + try { + delete pbs.next(); + return false; + } catch (const MemoryExhausted&) {} + Support::FailPoint::reset(); + // The portfolio reports the failure again, its destructor then waits + // only for the asset that started + try { + delete pbs.next(); + return false; + } catch (const MemoryExhausted&) {} + return true; + } + + class PortfolioLaunchFailure : public Base { + public: + PortfolioLaunchFailure(void) + : Base("Fault::Search::PortfolioLaunchFailure") {} + virtual bool run(void) { + return portfolio_launch_failure(); + } + }; + + PortfolioLaunchFailure portfolio_launch_failure_test; +#endif + class FaultBoolMisc : public BoolExpr::Misc { public: static int disposed; diff --git a/test/int/open-var-list.cpp b/test/int/open-var-list.cpp index 03a9f5920f..9f959ed039 100644 --- a/test/int/open-var-list.cpp +++ b/test/int/open-var-list.cpp @@ -274,7 +274,7 @@ namespace Test { namespace Int { }; while (Space* solution = engine->next()) record(static_cast(solution)); - if (!engine->stopped()) + if (engine->end_reason() != Search::EndReason::Limit) return false; // Deeper choices refer to positions absent from the restart root. engine->nogoods().post(root); diff --git a/test/nogoods.cpp b/test/nogoods.cpp index 2e819fd5f2..e73258b761 100644 --- a/test/nogoods.cpp +++ b/test/nogoods.cpp @@ -231,6 +231,8 @@ namespace Test { Model* m = new Model(vb,a,n); // Solution without no-goods Model* s_plain = dfs(m); + // Whether the search ended with a solution or exhausted + bool ended = true; // Stop and re-start for a while to collect no-goods { Search::NodeStop ns(Model::nodeinc()); @@ -241,9 +243,14 @@ namespace Test { Search::Engine* e = Search::dfsengine(m,o); while (true) { Model* s = static_cast(e->next()); - delete s; - if (!e->stopped()) + if (s != nullptr) { + delete s; break; + } + if (e->end_reason() != Search::EndReason::Limit) { + ended = e->end_reason() == Search::EndReason::Exhausted; + break; + } // Add no-goods e->nogoods().post(*m); ns.limit(ns.limit()+Model::nodeinc()); @@ -253,7 +260,7 @@ namespace Test { // Compare whether the a or the same solution is found with no-goods Model* s_nogoods = dfs(m); - bool ok = ((s_nogoods != nullptr) && + bool ok = ended && ((s_nogoods != nullptr) && ((t != 1) || s_plain->same(*s_nogoods))); delete m; diff --git a/test/search.cpp b/test/search.cpp index 2a3000b1b8..fef40309a3 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -44,14 +44,18 @@ #include "test/test.hh" +#include #include #include +#include #include #include #include #include +#include #include #include +#include #include static_assert(std::is_copy_constructible::value, @@ -89,6 +93,19 @@ namespace Test { using namespace Gecode; using namespace Gecode::Int; + using Gecode::Search::EndReason; + + /// Stop object that stops once it is switched on + class Switch : public Gecode::Search::Stop { + public: + /// Whether search must stop + std::atomic on{false}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return on.load(); + } + }; + #ifdef GECODE_HAS_EXPERIMENTAL /// Explicit finite tree with prefix costs, admissible bounds, and ranks class TreeSpace : public Space { @@ -150,7 +167,7 @@ namespace Test { : Space(s), graph(s.graph), maximize(s.maximize), vertex(s.vertex), ceiling(s.ceiling) {} Space* copy(void) override { return new TreeSpace(*this); } - bool hub(const MetaInfo&) override { return true; } + void hub(HubContext&) override {} const Node& node(void) const { return (*graph)[vertex]; } void constrain(const Space& s) override { ceiling = static_cast(s).node().cost; @@ -255,7 +272,7 @@ namespace Test { break; } } - return e.stopped() || (last == (*root.graph)[0].best); + return (e.end_reason() != EndReason::Exhausted) || (last == (*root.graph)[0].best); } /// Heuristic search engines on random trees @@ -287,7 +304,7 @@ namespace Test { E e(&root,o); if (!improving(e,root,step > 0U ? &stop : nullptr)) return false; - if ((o.max_width == 0UL) && e.stopped()) + if ((o.max_width == 0UL) && (e.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -297,6 +314,94 @@ namespace Test { Heuristic astar_test("AStar"); Heuristic cabs_test("CABS"); + /// A heuristic search stays exhausted when its stop object fires later + template class E> + class HeuristicExhausted : public Base { + public: + HeuristicExhausted(const std::string& name) + : Base("Search::"+name+"::Exhausted") {} + bool run(void) override { + for (unsigned int threads : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (threads > 1U) continue; +#endif + TreeSpace root(TreeSpace::random(_rand),false); + Gecode::Search::HeuristicGuidance g = + TreeSpace::guidance(false,false,false,false); + Switch stop; + Gecode::Search::Options o; + o.threads = threads; + o.guidance = &g; + o.stop = &stop; + E e(&root,o); + while (TreeSpace* s = e.next()) + delete s; + if (e.end_reason() != EndReason::Exhausted) + return false; + stop.on = true; + if (TreeSpace* s = e.next()) { + delete s; + return false; + } + if (e.end_reason() != EndReason::Exhausted) + return false; + } + return true; + } + }; + + HeuristicExhausted astar_exhausted("AStar"); + HeuristicExhausted cabs_exhausted("CABS"); + + /// A heuristic search that has no work left after its last solution is + /// exhausted when its stop object fires before the next call + template class E> + class HeuristicExhaustedAfterSolution : public Base { + public: + HeuristicExhaustedAfterSolution(const std::string& name) + : Base("Search::"+name+"::ExhaustedAfterSolution") {} + bool run(void) override { + // A solved root, and a root whose only child is a solution + const std::vector graphs = { + {{0,0,0,0,{}}}, + {{0,0,0,1,{1}}, {1,1,0,1,{}}} + }; + for (const TreeSpace::Graph& graph : graphs) + for (unsigned int threads : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (threads > 1U) continue; +#endif + TreeSpace root(std::make_shared(graph), + false); + Gecode::Search::HeuristicGuidance g = + TreeSpace::guidance(false,false,false,false); + Switch stop; + Gecode::Search::Options o; + o.threads = threads; + o.guidance = &g; + o.stop = &stop; + E e(&root,o); + TreeSpace* s = e.next(); + if (s == nullptr) + return false; + delete s; + stop.on = true; + if (TreeSpace* t = e.next()) { + delete t; + return false; + } + if (e.end_reason() != EndReason::Exhausted) + return false; + } + return true; + } + }; + + HeuristicExhaustedAfterSolution + astar_exhausted_after_solution("AStar"); + HeuristicExhaustedAfterSolution + cabs_exhausted_after_solution("CABS"); + /// Portfolio of BAB, A*, and CABS assets class HeuristicPortfolio : public Base { /// Stop object that never stops but takes some time @@ -362,7 +467,7 @@ namespace Test { last = s->node().cost; delete s; } - return (last == 1) && e.stopped(); + return (last == 1) && (e.end_reason() == EndReason::Exhausted); } } heuristic_portfolio; #endif @@ -403,14 +508,13 @@ namespace Test { virtual int solutions(void) const = 0; /// Verify that this is best solution virtual bool best(void) const = 0; - /// Hub configuration function that does not restart - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { - if (mi.last() != nullptr) - constrain(*mi.last()); - return false; - } else { - return false; + /// Hub hook that does not restart after a solution and keeps the branchers of a portfolio + virtual void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + if (hc.last() != nullptr) + constrain(*hc.last()); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } } }; @@ -649,43 +753,40 @@ namespace Test { return "Sol"; } /// Rule out that solution is found more than once during restarts - virtual bool hub(const MetaInfo& mi) { - switch (mi.type()) { - case MetaInfo::RESTART: - // With an objective, restart from a bound improving on the last solution - if (htc != HTC_NONE) - return Space::hub(mi); - if (mi.last() != nullptr) { - const HasSolutions* s - = static_cast(mi.last()); - BoolVarArgs b; - for (int i=0; ix[i]); - rel(*this, BOT_AND, b, 0); - } - break; - case MetaInfo::PORTFOLIO: - // Do not kill the brancher! - break; - default: - break; + virtual void hub(HubContext& hc) { + // For portfolio search, keep the branchers + if (hc.engine() != MetaEngine::Restart) + return; + // With an objective, restart from a bound improving on the last solution + if (htc != HTC_NONE) { + Space::hub(hc); + return; } - return false; + if (hc.last() != nullptr) { + const HasSolutions* s + = static_cast(hc.last()); + BoolVarArgs b; + for (int i=0; ix[i]); + rel(*this, BOT_AND, b, 0); + } + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } }; - /// Return a bit for restart reason \a r + /// Return a bit for meta event \a e static unsigned int - reason_bit(MetaInfo::RestartReason r) { - return 1U << static_cast(r); + event_bit(MetaEvent e) { + return 1U << static_cast(e); } /// Observations shared by meta-search dispatch test spaces struct MetaDispatchState { std::atomic hub_calls{0}; std::atomic spoke_calls{0}; - std::atomic hub_reasons{0}; - std::atomic spoke_reasons{0}; + std::atomic hub_events{0}; + std::atomic spoke_events{0}; std::atomic assets{0}; std::atomic live_spaces{0}; std::atomic copies{0}; @@ -696,10 +797,17 @@ namespace Test { std::atomic constrain_hub_asset_mask{0}; std::atomic constrain_spoke_asset_mask{0}; std::atomic nogood_handoffs{0}; - bool restart_after_solution = true; - bool solution_spoke_complete = true; + /// Decision of hub() after a solution + MetaDecision solution_decision = MetaDecision::Restart; + /// Coverage that spoke() declares after a solution + SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; + /// Whether spoke() fails after a solution bool fail_solution_spoke = false; + /// Whether hub() leaves no solution after a solution, without failing + bool empty_hub_after_solution = false; bool nogood_model = false; + /// Whether the model posts a branching on x + bool model_branching = true; /// Whether a PBS spoke() posts the branching for its asset bool spoke_branching = true; /// Whether the first RBS spoke reaches the cutoff without a solution @@ -715,7 +823,7 @@ namespace Test { IntVar x; /// Optional queens model used to force restart no-good extraction IntVarArray q; - /// Optional variables without a solution, used to reach the cutoff + /// Optional variables without a solution, to reach the cutoff or empty the hub IntVarArray y; /// Shared hook observations and configuration MetaDispatchState* state; @@ -725,49 +833,57 @@ namespace Test { int portfolio_asset; /// Record and implement a Hub callback - bool - observe_hub(const MetaInfo& mi) { + void + observe_hub(HubContext& hc) { state->hub_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) - // PBS must ignore the callback result. - return false; + // Keep the branchers of a portfolio hub + if (hc.engine() == MetaEngine::Portfolio) + return; restart_role = RestartRole::Hub; - state->hub_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); - bool default_result = Space::hub(mi); - if ((mi.type() == MetaInfo::RESTART) && (mi.nogoods().ng() > 0)) + state->hub_events.fetch_or(event_bit(hc.event()), std::memory_order_relaxed); + Space::hub(hc); + if (hc.nogoods().ng() > 0) state->nogood_handoffs.fetch_add(1, std::memory_order_relaxed); - return (mi.reason() == MetaInfo::RR_SOL) ? state->restart_after_solution : default_result; + if (hc.event() == MetaEvent::Solution) { + if (state->empty_hub_after_solution) { + // Four distinct values from three fail only during search. + distinct(*this, y, IPL_VAL); + Gecode::branch(*this, y, INT_VAR_NONE(), INT_VAL_MIN()); + } + hc.decision(state->solution_decision); + } } /// Record and implement a Spoke callback - bool - observe_spoke(const MetaInfo& mi) { + void + observe_spoke(SpokeContext& sc) { state->spoke_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) { - portfolio_asset = static_cast(mi.asset()); - state->assets.fetch_or(1U << mi.asset(), std::memory_order_relaxed); + if (sc.engine() == MetaEngine::Portfolio) { + portfolio_asset = static_cast(sc.asset()); + state->assets.fetch_or(1U << sc.asset(), std::memory_order_relaxed); // The default hub() removes the model's branching. A hub() // override keeps it, and then this branching is redundant. if (state->spoke_branching) Gecode::branch(*this, x, INT_VAL_MIN()); - // PBS must ignore the callback result. - return false; + return; } - state->spoke_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); + state->spoke_events.fetch_or(event_bit(sc.event()), std::memory_order_relaxed); restart_role = RestartRole::Spoke; - if ((mi.reason() == MetaInfo::RR_INIT) && state->limit_first_spoke) { + if ((sc.event() == MetaEvent::Start) && state->limit_first_spoke) { // Four distinct values from three fail only during search. distinct(*this, y, IPL_VAL); Gecode::branch(*this, y, INT_VAR_NONE(), INT_VAL_MIN()); } - if ((mi.reason() == MetaInfo::RR_SOL) && state->fail_solution_spoke) - fail(); - return (mi.reason() == MetaInfo::RR_SOL) ? state->solution_spoke_complete : true; + if (sc.event() == MetaEvent::Solution) { + if (state->fail_solution_spoke) + fail(); + sc.coverage(state->solution_spoke_coverage); + } } public: /// Initialize with shared observations \a s MetaDispatchSpace(MetaDispatchState& s) - : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), y(*this, s.limit_first_spoke ? 4 : 0, 0, 2), + : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), y(*this, (s.limit_first_spoke || s.empty_hub_after_solution) ? 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) { @@ -776,7 +892,8 @@ namespace Test { distinct(*this, q, IPL_VAL); Gecode::branch(*this, q, INT_VAR_NONE(), INT_VAL_MIN()); } - Gecode::branch(*this, x, INT_VAL_MIN()); + if (state->model_branching) + Gecode::branch(*this, x, INT_VAL_MIN()); } /// Clone \a s MetaDispatchSpace(MetaDispatchSpace& s) @@ -844,9 +961,9 @@ namespace Test { return new HubDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } }; @@ -863,9 +980,9 @@ namespace Test { return new SpokeDispatchSpace(*this); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -882,14 +999,14 @@ namespace Test { return new HubSpokeDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -902,8 +1019,9 @@ namespace Test { RbsSpokeOnly, RbsHubContinue, RbsHubRestart, - RbsSpokeComplete, - RbsSpokeIncomplete, + RbsSpokeFull, + RbsSpokeReduced, + RbsSpokePartial, RbsLimit, PbsHubOnly, PbsSpokeOnly, @@ -915,7 +1033,8 @@ namespace Test { PbsParallelSpokeOnly, PbsParallel, PbsParallelThreadLimit, - PbsDefaultHubRemovesBranchers, + PbsSpokeWithoutBrancher, + PbsNoBrancher, RbsNoGoodsResetOwnership, MetaStopOwnership, BabIncumbent @@ -952,11 +1071,16 @@ namespace Test { } /// Run one RBS dispatch scenario static bool - rbs(bool restart_after_solution, bool fail_solution_spoke, bool solution_spoke_complete) { + rbs(MetaDecision solution_decision, bool empty_after_solution, + SpokeCoverage solution_spoke_coverage) { MetaDispatchState state; - state.restart_after_solution = restart_after_solution; - state.fail_solution_spoke = fail_solution_spoke; - state.solution_spoke_complete = solution_spoke_complete; + state.solution_decision = solution_decision; + // A spoke that is not partial keeps the solutions of the hub, so + // only a partial spoke may remove them + const bool partial = solution_spoke_coverage == SpokeCoverage::Partial; + state.fail_solution_spoke = empty_after_solution && partial; + state.empty_hub_after_solution = empty_after_solution && !partial; + state.solution_spoke_coverage = solution_spoke_coverage; HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); Gecode::Search::Options o; @@ -969,22 +1093,27 @@ namespace Test { bool ok = first != nullptr; delete first; + const unsigned int start = event_bit(MetaEvent::Start); + const unsigned int solution = event_bit(MetaEvent::Solution); + const unsigned int exhausted = event_bit(MetaEvent::Exhausted); HubSpokeDispatchSpace* second = search.next(); - if (!fail_solution_spoke) { - 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)); + if (!empty_after_solution) { + const bool restart = solution_decision == MetaDecision::Restart; + ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && + holds(state.spoke_calls, restart ? 2U : 1U) && + holds(state.hub_events, start | solution) && + holds(state.spoke_events, start | (restart ? solution : 0U)); + } else if (!partial) { + // Exhausting a spoke that is not partial is a proof + ok = ok && (second == nullptr) && + (search.end_reason() == EndReason::Exhausted) && + holds(state.hub_calls, 2U) && holds(state.spoke_calls, 2U) && + holds(state.hub_events, start | solution) && + holds(state.spoke_events, start | solution); } else { - ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, 3U) && - holds(state.hub_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)); + ok = ok && (second != nullptr) && holds(state.hub_calls, 3U) && holds(state.spoke_calls, 3U) && + holds(state.hub_events, start | solution | exhausted) && + holds(state.spoke_events, start | solution | exhausted); } delete second; return ok; @@ -1008,23 +1137,29 @@ namespace Test { delete solution; return ok; } - /// Check that the default PBS hub() removes the model's branching + /// Check that PBS rejects a spoke without branching when the hub had one static bool - pbs_default_hub_removes_branchers(void) { + pbs_spoke_without_brancher(bool model_branching) { MetaDispatchState state; state.spoke_branching = false; + state.model_branching = model_branching; SpokeDispatchSpace* m = new SpokeDispatchSpace(state); Gecode::Search::Options o; o.assets = 3; o.threads = 1; - Gecode::PBS search(m, o); - delete m; - - // A spoke without branching is a solution as soon as it is stable. - SpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && !solution->assigned() && holds(state.spoke_calls, 3U); - delete solution; - return ok; + try { + Gecode::PBS search(m, o); + delete m; + // A spoke without branching is a solution as soon as it is stable. + SpokeDispatchSpace* solution = search.next(); + bool ok = !model_branching && (solution != nullptr) && !solution->assigned() && + holds(state.spoke_calls, 3U); + delete solution; + return ok; + } catch (const Gecode::Search::SpokeNoBrancher&) { + delete m; + return model_branching && holds(state.live_spaces, 0U); + } } /// Check RBS dispatch when the first spoke reaches the cutoff static bool @@ -1041,9 +1176,10 @@ namespace Test { delete m; HubSpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, 2U) && holds(state.hub_reasons, reason_bit(MetaInfo::RR_LIM)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_LIM)); + const unsigned int events = event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit); + bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 2U) && + holds(state.spoke_calls, 2U) && holds(state.hub_events, events) && + holds(state.spoke_events, events); delete solution; return ok; } @@ -1063,7 +1199,8 @@ namespace Test { o.nogoods_limit = 16; o.stop = &stop; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS search(m, o); + // The engine constrains the hub by each solution + Gecode::RBS search(m, o); delete m; unsigned int solutions = 0; @@ -1071,7 +1208,8 @@ namespace Test { solutions++; delete solution; } - ok = !search.stopped() && (solutions == 2U) && (state.spoke_calls.load(std::memory_order_relaxed) >= 2U) && + ok = (search.end_reason() == EndReason::Exhausted) && (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); } @@ -1082,7 +1220,7 @@ namespace Test { meta_stop_ownership(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { Gecode::Search::NodeStop stop(0); @@ -1094,7 +1232,7 @@ namespace Test { Gecode::RBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = (solution == nullptr) && search.stopped(); + ok = (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } ok = ok && holds(rbs_state.live_spaces, 0U); @@ -1114,7 +1252,7 @@ namespace Test { Gecode::PBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = ok && (solution == nullptr) && search.stopped(); + ok = ok && (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } return ok && holds(pbs_state.live_spaces, 0U); @@ -1124,7 +1262,7 @@ namespace Test { bab_incumbent(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(rbs_state); @@ -1172,7 +1310,7 @@ namespace Test { ok = ok && holds(pbs_state.live_spaces, 0U); MetaDispatchState nested_state; - nested_state.restart_after_solution = false; + nested_state.solution_decision = MetaDecision::Continue; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(nested_state); Gecode::Search::Options outer; @@ -1210,17 +1348,19 @@ namespace Test { run(void) override { switch (scenario) { case Scenario::RbsHubOnly: - return rbs_dispatch(1, 0); + return rbs_dispatch(2, 0); case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); case Scenario::RbsHubContinue: - return rbs(false, false, true); + return rbs(MetaDecision::Continue, false, SpokeCoverage::Full); case Scenario::RbsHubRestart: - return rbs(true, false, true); - case Scenario::RbsSpokeComplete: - return rbs(true, true, true); - case Scenario::RbsSpokeIncomplete: - return rbs(true, true, false); + return rbs(MetaDecision::Restart, false, SpokeCoverage::Full); + case Scenario::RbsSpokeFull: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Full); + case Scenario::RbsSpokeReduced: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Reduced); + case Scenario::RbsSpokePartial: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Partial); case Scenario::RbsLimit: return rbs_limit(); case Scenario::PbsHubOnly: @@ -1242,10 +1382,12 @@ namespace Test { case Scenario::PbsParallel: return pbs(3, 3, 1, 3, 7); case Scenario::PbsParallelThreadLimit: - // Parallel PBS runs only as many assets as it has threads. - return pbs(3, 2, 1, 2, 3); - case Scenario::PbsDefaultHubRemovesBranchers: - return pbs_default_hub_removes_branchers(); + // Parallel PBS runs all assets, also with fewer threads. + return pbs(3, 2, 1, 3, 7); + case Scenario::PbsSpokeWithoutBrancher: + return pbs_spoke_without_brancher(true); + case Scenario::PbsNoBrancher: + return pbs_spoke_without_brancher(false); case Scenario::RbsNoGoodsResetOwnership: return rbs_nogoods_reset_ownership(); case Scenario::MetaStopOwnership: @@ -1480,7 +1622,7 @@ namespace Test { bool complete = E::best ? (last && last->best() && ((node != 0U) || (solutions >= 2))) : (solutions == root.solutions()); - return ok && !engine.stopped() && complete; + return ok && (engine.end_reason() == EndReason::Exhausted) && complete; } #ifdef GECODE_HAS_EXPERIMENTAL template class E> @@ -1509,7 +1651,7 @@ namespace Test { std::future_status::timeout; control.request(threads); result.get(); - return ok && !engine.stopped() && (last == (*root.graph)[0].best); + return ok && (engine.end_reason() == EndReason::Exhausted) && (last == (*root.graph)[0].best); } #endif @@ -1570,7 +1712,7 @@ namespace Test { resizer.join(); best = (last != nullptr) && last->best(); delete last; - return !engine.stopped(); + return engine.end_reason() == EndReason::Exhausted; } public: WorkerControlConcurrentResize(void) @@ -1831,6 +1973,11 @@ namespace Test { constraints->fetch_add(1); IntMinimizeSpace::constrain(s); } + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); + } }; /// Small objective whose solutions arrive from worst to best @@ -1846,10 +1993,10 @@ namespace Test { } virtual Space* copy(void) { return new ParallelObjective(*this); } virtual IntVar cost(void) const { return x; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -1889,10 +2036,10 @@ namespace Test { throw ComparisonError(); return SpaceComparison::Incomparable; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -2258,7 +2405,7 @@ namespace Test { if (value >= -1) return false; } - if (bounded->stopped()) + if (bounded->end_reason() != EndReason::Exhausted) return false; bounded.reset(); return missingFailure() && thrownFailure() && incomparableFailure(); @@ -2566,7 +2713,8 @@ namespace Test { (static_cast(s)->x.val().max() < 8.5); delete s; } - substep = substep && (found == 1) && !bab->stopped(); + substep = substep && (found == 1) && + (bab->end_reason() == EndReason::Exhausted); if (!substep) return false; #endif @@ -2709,11 +2857,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !dfs.stopped()) + if ((s == nullptr) && (dfs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (dfs.end_reason() == EndReason::Exhausted); } }; @@ -2746,11 +2894,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !lds.stopped()) + if ((s == nullptr) && (lds.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (lds.end_reason() == EndReason::Exhausted); } }; @@ -2790,11 +2938,11 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !bab.stopped()) + if ((s == nullptr) && (bab.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - bool ok = (b == nullptr) || b->best(); + bool ok = ((b == nullptr) || b->best()) && (bab.end_reason() == EndReason::Exhausted); delete b; return ok; } @@ -2838,18 +2986,89 @@ namespace Test { delete b; b = s; } } - if ((s == nullptr) && !rbs.stopped()) + if ((s == nullptr) && (rbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } if (htc == HTC_NONE) - return n == 0; - bool ok = improving && (b != nullptr) && b->best(); + return (n == 0) && (rbs.end_reason() == EndReason::Exhausted); + bool ok = improving && (b != nullptr) && b->best() && + (rbs.end_reason() == EndReason::Exhausted); delete b; return ok; } }; + /// Space whose spokes add constraints that keep some solution + class SatPreservingSpoke : public Gecode::Space { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Variable with four values + Gecode::IntVar x; + /// Four variables with three values + Gecode::IntVarArray y; + /// Initialize with declared coverage \a c + SatPreservingSpoke(Gecode::SpokeCoverage c) + : coverage(c), x(*this,0,3), y(*this,4,0,2) { + Gecode::branch(*this,x,Gecode::INT_VAL_MIN()); + Gecode::branch(*this,y,Gecode::INT_VAR_NONE(),Gecode::INT_VAL_MIN()); + } + /// Clone \a s + SatPreservingSpoke(SatPreservingSpoke& s) + : Gecode::Space(s), coverage(s.coverage) { + x.update(*this,s.x); + y.update(*this,s.y); + } + Gecode::Space* copy(void) override { + return new SatPreservingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + // The y must be distinct, which is impossible, for x < 3 in the + // first episode and for x > 0 later: either keeps a solution + Gecode::BoolVar b = (sc.episode() == 0) ? + Gecode::expr(*this,x < 3) : Gecode::expr(*this,x > 0); + for (int i=0; i rbs(m,o); + delete m; + SatPreservingSpoke* s = rbs.next(); + r = rbs.end_reason(); + return s; + } + public: + RBSSpokeCoverage(void) : Base("Search::RBS::SpokeCoverage") {} + bool run(void) override { + EndReason r; + // Declared Reduced: no-goods stay in their spoke, x = 0 remains. + // These spokes are not Full, declaring them so is undefined. + SatPreservingSpoke* s = solve(Gecode::SpokeCoverage::Reduced,r); + const bool reduced = (s != nullptr) && (s->x.val() == 0); + delete s; + return reduced; + } + }; + + RBSSpokeCoverage rbs_spoke_coverage; + /// Space whose first spoke search is restricted to x2, x3 in {0,1} class RestrictedFirstSpoke : public Gecode::IntMinimizeSpace { public: @@ -2869,21 +3088,20 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { Gecode::dom(*this,x[2],0,1); Gecode::dom(*this,x[3],0,1); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; - /// No-goods from an incomplete spoke search are not posted in the hub - class RBSIncompleteNoGoods : public Base { + /// No-goods from a partial spoke search are not posted in the hub + class RBSPartialNoGoods : public Base { public: - RBSIncompleteNoGoods(void) : Base("Search::RBS::IncompleteNoGoods") {} + RBSPartialNoGoods(void) : Base("Search::RBS::PartialNoGoods") {} bool run(void) override { RestrictedFirstSpoke* m = new RestrictedFirstSpoke; Gecode::Search::Options o; @@ -2897,11 +3115,77 @@ namespace Test { best = s->x[0].val(); delete s; } - return !rbs.stopped() && (best == 0); + return (rbs.end_reason() == EndReason::Exhausted) && (best == 0); + } + }; + + RBSPartialNoGoods rbs_partial_nogoods; + + /// Space whose hub posts a brancher after a spoke posted one + class LateHubBrancher : public Gecode::Space { + public: + /// Variables branched on by the spokes + Gecode::IntVarArray y; + /// Variables branched on by the hub after the first episode + Gecode::IntVarArray z; + /// Whether the hub branches on z + bool z_branching; + LateHubBrancher(void) + : y(*this,5,0,2), z(*this,2,0,1), z_branching(false) { + // For y0 = 0 the other y must be distinct, which is impossible + Gecode::BoolVar b = Gecode::expr(*this,y[0] == 0); + for (int i=1; i rbs(m,o); + delete m; + // A no-good taken for one on z would rule out z = (0,0) + LateHubBrancher* s = rbs.next(); + const bool ok = (s != nullptr) && + (s->z[0].val() == 0) && (s->z[1].val() == 0); + delete s; + return ok; } }; - RBSIncompleteNoGoods rbs_incomplete_nogoods; + RBSLateHubBrancher rbs_late_hub_brancher; /// Space without solutions whose search tree has several failures class NoSolution : public Gecode::IntMinimizeSpace { @@ -2923,11 +3207,10 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool hub(const Gecode::MetaInfo& mi) override { + void hub(Gecode::HubContext& hc) override { // Keep the branchers for the assets of a portfolio - if (mi.type() == Gecode::MetaInfo::PORTFOLIO) - return true; - return Gecode::IntMinimizeSpace::hub(mi); + if (hc.engine() == Gecode::MetaEngine::Restart) + Gecode::IntMinimizeSpace::hub(hc); } }; @@ -2939,11 +3222,9 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingHub(*this); } - bool hub(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_LIM)) + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Limit) fail(); - return true; } }; @@ -2965,10 +3246,12 @@ namespace Test { } Gecode::Search::Statistics s = rbs.statistics(); // The failures of the last spoke search are counted once - if (rbs.stopped() || (s.restart != 1U) || (s.fail < 2U) || + if ((rbs.end_reason() != EndReason::Exhausted) || + (s.restart != 0U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; - if ((rbs.next() != nullptr) || rbs.stopped() || + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted) || (rbs.statistics().fail != s.fail) || (rbs.statistics().node != s.node)) return false; @@ -2987,12 +3270,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.restart() > 0)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.episode() > 0)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -3023,7 +3306,7 @@ namespace Test { delete s; return false; } - return rbs.stopped() && (f.checks <= 1000) && + return (rbs.end_reason() == EndReason::Limit) && (f.checks <= 1000) && (rbs.statistics().fail >= 5); } public: @@ -3045,13 +3328,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingFirstSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -3082,6 +3364,59 @@ namespace Test { RBSFailedFirstSpoke rbs_failed_first_spoke; + /// Space without solutions whose spoke() throws after the first episode + class ThrowingSpoke : public NoSolution { + public: + /// Number of spaces alive, shared with the workers of a parallel engine + std::atomic* live; + ThrowingSpoke(std::atomic& l) : live(&l) { + (*live)++; + } + ThrowingSpoke(ThrowingSpoke& s) : NoSolution(s), live(s.live) { + (*live)++; + } + ~ThrowingSpoke(void) override { + (*live)--; + } + Gecode::Space* copy(void) override { + return new ThrowingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.episode() == 1) + throw std::runtime_error("spoke"); + } + }; + + /// RBS deletes the spoke when spoke() throws at a restart + class RBSSpokeException : public Base { + public: + RBSSpokeException(void) : Base("Search::RBS::SpokeException") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { + std::atomic live{0}; + bool thrown = false; + { + ThrowingSpoke root(live); + Gecode::Search::Options o; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS rbs(&root,o); + try { + if (ThrowingSpoke* s = rbs.next()) + delete s; + } catch (const std::runtime_error&) { + thrown = true; + } + } + if (!thrown || (live != 0)) + return false; + } + return true; + } + }; + + RBSSpokeException rbs_spoke_exception; + /// Stop after a number of failures, or after many checks as a safeguard class FailureLimit : public Gecode::Search::Stop { public: @@ -3096,7 +3431,7 @@ namespace Test { } }; - /// A search exhausted when it reaches a failure limit is not stopped + /// A search exhausted when it reaches a failure limit is exhausted class ExhaustedAtLimit : public Base { template class Engine> static bool test(void) { @@ -3118,7 +3453,7 @@ namespace Test { Gecode::Search::Options o; o.stop = &l; Engine e(&root,o); - if ((e.next() != nullptr) || e.stopped()) + if ((e.next() != nullptr) || (e.end_reason() != EndReason::Exhausted)) return false; } // Restarts at that limit post no no-goods and would repeat forever @@ -3129,7 +3464,8 @@ namespace Test { o.nogoods_limit = 128U; o.cutoff = Gecode::Search::Cutoff::constant(f-1); Gecode::RBS rbs(&root,o); - if ((rbs.next() != nullptr) || rbs.stopped()) + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -3143,6 +3479,126 @@ namespace Test { ExhaustedAtLimit exhausted_at_limit; + /// Resetting an engine forgets why its last search ended + class ResetEndReason : public Base { + static bool test(Gecode::Search::Engine* e) { + std::unique_ptr owned(e); + if ((e->next() != nullptr) || (e->end_reason() != EndReason::Exhausted)) + return false; + NoSolution root; + e->reset(root.clone()); + return e->end_reason() == EndReason::NotEnded; + } + public: + ResetEndReason(void) : Base("Search::ResetEndReason") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (t > 1U) continue; +#endif + NoSolution root; + Gecode::Search::Options o; + o.threads = t; + if (!test(Gecode::Search::dfsengine(&root,o)) || + !test(Gecode::Search::babengine(&root,o))) + return false; + } + return true; + } + }; + + ResetEndReason reset_end_reason; + + /// LDS reports an incomplete search at its discrepancy limit + class LDSIncomplete : public Base { + static EndReason end_reason(unsigned int d_l) { + NoSolution root; + Gecode::Search::Options o; + o.d_l = d_l; + Gecode::LDS lds(&root,o); + if (NoSolution* s = lds.next()) { + delete s; + return EndReason::NotEnded; + } + return lds.end_reason(); + } + public: + LDSIncomplete(void) : Base("Search::LDS::Incomplete") {} + bool run(void) override { + return (end_reason(0) == EndReason::Incomplete) && + (end_reason(1) == EndReason::Incomplete) && + (end_reason(100) == EndReason::Exhausted); + } + }; + + LDSIncomplete lds_incomplete; + + /// Space without solutions recording the default decisions after incomplete episodes + class IncompleteEpisodes : public NoSolution { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Default decisions of hub() after an incomplete episode + std::vector* defaults; + IncompleteEpisodes(Gecode::SpokeCoverage c, + std::vector& d) + : coverage(c), defaults(&d) {} + IncompleteEpisodes(IncompleteEpisodes& s) + : NoSolution(s), coverage(s.coverage), defaults(s.defaults) {} + Gecode::Space* copy(void) override { + return new IncompleteEpisodes(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Incomplete) { + defaults->push_back(hc.decision()); + // Finish after the second incomplete episode at the latest + if (defaults->size() == 2U) + hc.decision(Gecode::MetaDecision::Finish); + } + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + sc.coverage(coverage); + } + }; + + /// RBS finishes after an incomplete episode unless its spoke is partial + class RBSIncompleteDefault : public Base { + /// Return the default decisions when spokes of coverage \a c end incomplete + static std::vector + defaults(Gecode::SpokeCoverage c) { + std::vector d; + IncompleteEpisodes root(c,d); + Gecode::Search::Options o; + o.d_l = 1; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::RBS rbs(&root,o); + for (int i=0; i<2; i++) + if (IncompleteEpisodes* s = rbs.next()) { + delete s; + d.clear(); + } else if (rbs.end_reason() != EndReason::Incomplete) { + d.clear(); + } + return d; + } + public: + RBSIncompleteDefault(void) : Base("Search::RBS::IncompleteDefault") {} + bool run(void) override { + using Gecode::MetaDecision; + using Gecode::SpokeCoverage; + using Decisions = std::vector; + return (defaults(SpokeCoverage::Full) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Reduced) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Partial) == + Decisions{MetaDecision::Restart,MetaDecision::Restart}); + } + }; + + RBSIncompleteDefault rbs_incomplete_default; + /// Space for relaxing class RelaxSpace : public Gecode::Space { public: @@ -3203,7 +3659,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3211,14 +3667,14 @@ namespace Test { delete b; return ok; } else { - int n = ((t > 1) ? std::min(a,t) : a) * m->solutions(); + int n = a * m->solutions(); delete m; while (true) { Model* s = pbs.next(); if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3272,7 +3728,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3294,7 +3750,7 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3318,7 +3774,8 @@ namespace Test { sebs[0] = builder(Gecode::Search::Options::def); sebs[1] = builder(Gecode::Search::Options::def); Gecode::PBS pbs(&root,sebs,o); - return (pbs.next() == nullptr) && pbs.stopped() && (l.checks <= 1000); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit) && (l.checks <= 1000); } public: PBSBuilderStop(void) : Base("Search::PBS::SEB::Stop") {} @@ -3333,60 +3790,1078 @@ namespace Test { PBSBuilderStop pbs_builder_stop; - /// Restart-based assets of a portfolio share the cutoff sequence - class PBSRestartCutoff : public Base { - template class Engine> + /// An exhausted asset ends a portfolio whose other asset never ends + class PBSExhaustedAsset : public Base { + /// Stop after many checks, in case the portfolio does not end + class ManyChecks : public Gecode::Search::Stop { + public: + /// Number of checks + std::atomic checks{0UL}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return ++checks > 10000000UL; + } + }; static bool test(unsigned int threads) { - NoSolution root; + FailingSpoke root; + ManyChecks l; + Gecode::Search::Options a; + a.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::SEBs sebs(2); + sebs[0] = Gecode::rbs(a); + sebs[1] = Gecode::dfs(); Gecode::Search::Options o; - o.assets = 2; o.threads = threads; - o.cutoff = Gecode::Search::Cutoff::geometric(1,2); - Gecode::PBS pbs(&root,o); - return (pbs.next() == nullptr) && !pbs.stopped(); + o.stop = &l; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted) && + (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); } public: - PBSRestartCutoff(void) : Base("Search::PBS::RBS::Cutoff") {} + PBSExhaustedAsset(void) : Base("Search::PBS::ExhaustedAsset") {} bool run(void) override { - for (unsigned int t : {1U,2U,4U}) - if (!test(t) || !test(t)) - return false; - return true; + return test(1U) && test(2U); } }; - PBSRestartCutoff pbs_restart_cutoff; + PBSExhaustedAsset pbs_exhausted_asset; - /** - * \brief Constant cutoff counting its deletions - * - * The cutoff exceeds the failures of NoSolution, so a restart-based - * asset finishes without restarting. Without no-goods, restarts with a - * smaller constant cutoff would repeat the same search forever. - */ - class CountingCutoff : public Gecode::Search::CutoffConstant { + /// A single asset of a sequential portfolio runs without slices + class PBSSingleAssetSlice : public Base { + /// Space without a solution whose portfolio spoke is partial + class PartialSpoke : public NoSolution { + public: + PartialSpoke(void) = default; + PartialSpoke(PartialSpoke& s) : NoSolution(s) {} + Gecode::Space* copy(void) override { + return new PartialSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + sc.coverage(Gecode::SpokeCoverage::Partial); + } + }; public: - /// Number of deletions, owned by the test - std::atomic& deleted; - CountingCutoff(std::atomic& d) - : Gecode::Search::CutoffConstant(1000), deleted(d) {} - ~CountingCutoff(void) override { - deleted++; + PBSSingleAssetSlice(void) : Base("Search::PBS::SingleAssetSlice") {} + bool run(void) override { + PartialSpoke root; + // Stops after 1000 checks in case the asset makes no progress + FailureLimit l(ULLONG_MAX); + Gecode::Search::Options o; + o.assets = 1; + o.threads = 1; + o.slice = 0; + o.stop = &l; + Gecode::PBS pbs(&root,o); + if (PartialSpoke* s = pbs.next()) { + delete s; + return false; + } + return pbs.end_reason() == EndReason::Incomplete; } }; - /// Space without solutions whose first portfolio asset fails - class FailingAsset : public NoSolution { - public: - FailingAsset(void) = default; - FailingAsset(FailingAsset& s) : NoSolution(s) {} + PBSSingleAssetSlice pbs_single_asset_slice; + + /// The stop object of a portfolio sees the failures of all assets + class PBSPortfolioStop : public Base { + /// Whether restart-based assets stop at a portfolio-wide failure limit + static bool test(unsigned int threads, bool builders) { + FailingSpoke root; + const unsigned long long int limit = 40U; + Gecode::Search::FailStop f(limit); + Gecode::Search::Options o; + o.threads = threads; + o.stop = &f; + o.slice = 2; + Gecode::Search::Statistics s; + if (builders) { + // Each restart-based engine takes ownership of its cutoff + Gecode::Search::Options a, b; + a.cutoff = Gecode::Search::Cutoff::constant(1); + b.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::SEBs sebs(2); + sebs[0] = Gecode::rbs(a); + sebs[1] = Gecode::rbs(b); + Gecode::PBS pbs(&root,sebs,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } else { + o.assets = 2; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::PBS pbs(&root,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } + // Checked for each asset, the limit would allow twice the failures + return (s.fail > limit) && (s.fail < limit + limit / 2U); + } + public: + PBSPortfolioStop(void) : Base("Search::PBS::PortfolioStop") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + for (bool builders : {false,true}) + if (!test(t,builders)) + return false; + return true; + } + }; + + PBSPortfolioStop pbs_portfolio_stop; + + /// Portfolio search resumes with the next call after its stop object fired + class PBSPortfolioStopResume : public Base { + /// Whether the assets run again after a single limit + static bool test(unsigned int threads) { + NoSolution root; + Switch s; + s.on = true; + Gecode::Search::Options o; + o.threads = threads; + o.assets = 2; + o.stop = &s; + Gecode::PBS pbs(&root,o); + if ((pbs.next() != nullptr) || (pbs.end_reason() != EndReason::Limit)) + return false; + s.on = false; + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSPortfolioStopResume(void) : Base("Search::PBS::PortfolioStopResume") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + if (!test(t)) + return false; + return true; + } + }; + + PBSPortfolioStopResume pbs_portfolio_stop_resume; + + /// Space whose all-different variables give many failures and solutions + class Distinct : public Gecode::Space { + public: + Gecode::IntVarArray x; + Distinct(void) : x(*this,6,0,5) { + for (int i=0; i(a); + sebs[1] = Gecode::dfs(a); + Gecode::Search::Options o; + o.threads = 1; + o.slice = 1; + o.stop = &n; + Gecode::PBS pbs(&root,sebs,o); + // Each asset finds each of the 720 solutions + unsigned int solutions = 0; + while (Distinct* s = pbs.next()) { + delete s; + solutions++; + } + return (pbs.end_reason() == EndReason::Exhausted) && + (solutions >= 720U) && (solutions <= 2U * 720U); + } + }; + + PBSParallelAssets pbs_parallel_assets; + + /// An asset stopped by its own stop object is parked while the others continue + class PBSParkedAsset : public Base { + /// Stop object that always stops + class AlwaysStop : public Gecode::Search::Stop { + public: + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return true; + } + }; + /// Whether the other asset continues and exhausts the search space + static bool others_continue(unsigned int threads) { + NoSolution root; + AlwaysStop always; + Gecode::Search::Options a; + a.stop = &always; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a); + sebs[1] = Gecode::dfs(); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + /// Whether parked assets resume with the next call + static bool resume(unsigned int threads) { + NoSolution root; + Gecode::Search::FailStop f0(0), f1(0); + Gecode::Search::Options a0, a1; + a0.stop = &f0; + a1.stop = &f1; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a0); + sebs[1] = Gecode::lds(a1); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + unsigned int limits = 0; + while ((pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit)) { + if (++limits > 1000) + return false; + f0.limit(f0.limit() + 1); + f1.limit(f1.limit() + 1); + } + return (limits > 0) && (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSParkedAsset(void) : Base("Search::PBS::ParkedAsset") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + if (!others_continue(t) || !resume(t)) + return false; + return true; + } + }; + + PBSParkedAsset pbs_parked_asset; + + /// Space without solutions whose hub continues after a partial spoke is exhausted, which is illegal + class IllegalContinue : public NoSolution { + public: + IllegalContinue(void) = default; + IllegalContinue(IllegalContinue& s) : NoSolution(s) {} + Gecode::Space* copy(void) override { + return new IllegalContinue(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Exhausted) + hc.decision(Gecode::MetaDecision::Continue); + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.engine() == Gecode::MetaEngine::Restart) + sc.coverage(Gecode::SpokeCoverage::Partial); + } + }; + + /// An exception thrown in an asset of a portfolio is rethrown by next() + class PBSAssetException : public Base { + public: + PBSAssetException(void) : Base("Search::PBS::AssetException") {} + bool run(void) override { + for (unsigned int t : {1U,2U,4U}) { + IllegalContinue root; + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::PBS pbs(&root,o); + bool thrown = false; + try { + if (IllegalContinue* s = pbs.next()) + delete s; + } catch (const Gecode::IllegalMetaDecision&) { + thrown = true; + } + if (!thrown) + return false; + } + return true; + } + }; + + PBSAssetException pbs_asset_exception; + + /// Exception thrown by the statistics of NoStatistics + class StatisticsFailure {}; + + /// Engine without solutions that cannot report its statistics + class NoStatistics : public Gecode::Search::Engine { + protected: + /// Why next() returns no solution + EndReason r; + public: + NoStatistics(EndReason r0) : r(r0) {} + Gecode::Space* next(void) override { + return nullptr; + } + Gecode::Search::Statistics statistics(void) const override { + throw StatisticsFailure(); + } + EndReason end_reason(void) const override { + return r; + } + }; + + /// Builder for NoStatistics + class NoStatisticsBuilder : public Gecode::Search::Builder { + protected: + /// Why next() of the engine returns no solution + EndReason r; + public: + NoStatisticsBuilder(EndReason r0) + : Gecode::Search::Builder(Gecode::Search::Options::def,false), r(r0) {} + Gecode::Search::Engine* operator ()(Gecode::Space*) const override { + return new NoStatistics(r); + } + }; + + /// An exception from the statistics of an asset that ended is rethrown by next() + class PBSStatisticsException : public Base { + public: + PBSStatisticsException(void) : Base("Search::PBS::StatisticsException") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { + NoSolution root; + Gecode::SEBs sebs(2); + sebs[0] = new NoStatisticsBuilder(EndReason::Incomplete); + sebs[1] = new NoStatisticsBuilder(EndReason::Incomplete); + Gecode::Search::Options o; + o.threads = t; + Gecode::PBS pbs(&root,sebs,o); + try { + delete pbs.next(); + return false; + } catch (const StatisticsFailure&) {} + } + return true; + } + }; + + PBSStatisticsException pbs_statistics_exception; + + /// A sequential portfolio without a stop object needs no statistics of its assets + class PBSNoStopStatistics : public Base { + public: + PBSNoStopStatistics(void) : Base("Search::PBS::NoStopStatistics") {} + bool run(void) override { + NoSolution root; + Gecode::SEBs sebs(2); + sebs[0] = new NoStatisticsBuilder(EndReason::Limit); + sebs[1] = new NoStatisticsBuilder(EndReason::Limit); + Gecode::Search::Options o; + o.threads = 1; + Gecode::PBS pbs(&root,sebs,o); + try { + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit); + } catch (const StatisticsFailure&) { + return false; + } + } + }; + + PBSNoStopStatistics pbs_no_stop_statistics; + + /// A copy of a cutoff generator continues its sequence independently + class CutoffCopy : public Base { + /// Check that a copy of \a c continues as \a c, then delete \a c + static bool same(Gecode::Search::Cutoff* c) { + std::unique_ptr o(c); + for (int i=0; i<5; i++) + (void) ++(*o); + std::unique_ptr d(o->copy()); + if ((*d)() != (*o)()) + return false; + for (int i=0; i<20; i++) + if (++(*d) != ++(*o)) + return false; + return true; + } + public: + CutoffCopy(void) : Base("Search::Cutoff::Copy") {} + bool run(void) override { + using Gecode::Search::Cutoff; + return same(Cutoff::constant(3)) && same(Cutoff::linear(2)) && + same(Cutoff::geometric(2,1.5)) && same(Cutoff::luby(2)) && + same(Cutoff::append(Cutoff::linear(1),8,Cutoff::luby(3))) && + same(Cutoff::merge(Cutoff::linear(1),Cutoff::geometric(1,2.0))) && + same(Cutoff::repeat(Cutoff::linear(4),3)); + } + }; + + CutoffCopy cutoff_copy; + + /// Copies of a random cutoff generator draw distinct, reproducible sequences + class CutoffRandomCopy : public Base { + /// Return the first values of \a c, which is deleted + static std::vector + values(Gecode::Search::Cutoff* c) { + std::unique_ptr d(c); + std::vector v{(*d)()}; + for (int i=0; i<20; i++) { + v.push_back(++(*d)); + if ((v.back() < 1U) || (v.back() > 1000U)) + return {}; + } + return v; + } + /// Return the values of two copies of a generator with seed \a seed + static std::vector > + copies(unsigned int seed) { + std::unique_ptr + o(Gecode::Search::Cutoff::rnd(seed,1,1000,1000)); + (void) ++(*o); + std::vector > v; + v.push_back(values(o->copy())); + v.push_back(values(o->copy())); + v.push_back(values(o.release())); + return v; + } + public: + CutoffRandomCopy(void) : Base("Search::Cutoff::RandomCopy") {} + bool run(void) override { + std::vector > v = copies(7); + return !v[0].empty() && !v[1].empty() && !v[2].empty() && + (v[0] != v[1]) && (v[0] != v[2]) && (v[1] != v[2]) && + (copies(7) == v); + } + }; + + CutoffRandomCopy cutoff_random_copy; + + /// A repeating cutoff generator advances the generator it repeats + class CutoffRepeat : public Base { + public: + CutoffRepeat(void) : Base("Search::Cutoff::Repeat") {} + bool run(void) override { + std::unique_ptr c + (Gecode::Search::Cutoff::repeat(Gecode::Search::Cutoff::linear(4),3)); + std::vector v{(*c)()}; + for (int i=0; i<6; i++) + v.push_back(++(*c)); + if (v != std::vector{4,4,4,8,8,8,12}) + return false; + // An appended generator returns the value of its first generator + // from ++ when it switches to its second one + std::unique_ptr a + (Gecode::Search::Cutoff::repeat + (Gecode::Search::Cutoff::append(Gecode::Search::Cutoff::linear(10),1, + Gecode::Search::Cutoff::constant(100)),2)); + std::vector w{(*a)()}; + for (int i=0; i<3; i++) + w.push_back(++(*a)); + return w == std::vector{10,10,100,100}; + } + }; + + CutoffRepeat cutoff_repeat; + + /// Each restart-based asset of a portfolio owns a copy of the cutoff + class PBSRestartCutoff : public Base { + template class Engine> + static bool test(unsigned int threads) { + NoSolution root; + Gecode::Search::Options o; + o.assets = 2; + o.threads = threads; + o.cutoff = Gecode::Search::Cutoff::geometric(1,2); + Gecode::PBS pbs(&root,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSRestartCutoff(void) : Base("Search::PBS::RBS::Cutoff") {} + bool run(void) override { + for (unsigned int t : {1U,2U,4U}) + if (!test(t) || !test(t)) + return false; + return true; + } + }; + + PBSRestartCutoff pbs_restart_cutoff; + + /// Hook behaviour of ProtocolSpace + enum class Protocol { + Default, ///< Default hooks + ContinueAtStart, ///< hub() continues at Start, which is illegal + FinishAtStart, ///< hub() finishes at Start + FinishAtLimit, ///< hub() finishes at Limit + FailAtStart, ///< hub() fails at Start + FailAtSolution, ///< hub() fails at Solution + ContinueAtLimit, ///< hub() continues at Limit + EmptyHub, ///< hub() does nothing + BoundInHub, ///< hub() leaves c <= 1 to propagation at Start, keeps the branchers + Alternate, ///< Episodes alternate between a solution and the cutoff + }; + + /// Calls of the hooks of ProtocolSpace + struct ProtocolLog { + /// Event and episode of each hub() call + std::vector > hub; + /// Event and episode of each spoke() call + std::vector > spoke; + /// Number of spaces alive + std::atomic live{0}; + /// Number of hub() calls that returned with the hub not stable + std::atomic unstable{0U}; + }; + + /// Space whose hooks follow a Protocol + class ProtocolSpace : public IntMinimizeSpace { + public: + /// Hook behaviour + Protocol protocol; + /// Log of hook calls + ProtocolLog* log; + /// Cost + IntVar c; + /// Whether the y must be distinct, which is impossible + BoolVar p; + /// Four variables with three values + IntVarArray y; + /// Initialize with hook behaviour \a pr and log \a l + ProtocolSpace(Protocol pr, ProtocolLog& l) + : protocol(pr), log(&l), c(*this,0,3), p(*this,0,1), y(*this,4,0,2) { + log->live++; + for (int i=0; ilive++; + c.update(*this,s.c); + p.update(*this,s.p); + y.update(*this,s.y); + } + /// Record destruction + ~ProtocolSpace(void) override { + log->live--; + } + Space* copy(void) override { + return new ProtocolSpace(*this); + } + IntVar cost(void) const override { + return c; + } + void hub(HubContext& hc) override { + log->hub.emplace_back(hc.event(),hc.episode()); + switch (protocol) { + case Protocol::ContinueAtStart: + if (hc.event() == MetaEvent::Start) + hc.decision(MetaDecision::Continue); + break; + case Protocol::FinishAtStart: + if (hc.event() == MetaEvent::Start) { + hc.decision(MetaDecision::Finish); + return; + } + break; + case Protocol::FinishAtLimit: + if (hc.event() == MetaEvent::Limit) + hc.decision(MetaDecision::Finish); + break; + case Protocol::FailAtStart: + if (hc.event() == MetaEvent::Start) { + fail(); + return; + } + break; + case Protocol::FailAtSolution: + if (hc.event() == MetaEvent::Solution) { + fail(); + return; + } + break; + case Protocol::ContinueAtLimit: + // Finish instead of repeating a limit that leaves no budget + if (hc.event() == MetaEvent::Limit) + hc.decision((log->hub.size() > 100U) ? MetaDecision::Finish : + MetaDecision::Continue); + break; + case Protocol::EmptyHub: + return; + case Protocol::BoundInHub: + if (hc.event() == MetaEvent::Start) { + // Only propagation enforces c <= 1, posting does not prune c + BoolVar b(*this,0,1); + rel(*this,c,IRT_LQ,1,Reify(b,RM_IMP)); + rel(*this,b,IRT_EQ,1); + if (!stable()) + log->unstable++; + return; + } + break; + case Protocol::Default: + case Protocol::Alternate: + break; + } + IntMinimizeSpace::hub(hc); + } + void spoke(SpokeContext& sc) override { + log->spoke.emplace_back(sc.event(),sc.episode()); + if ((protocol == Protocol::Alternate) && + (sc.engine() == MetaEngine::Restart)) { + // Odd episodes search only the part without solutions + rel(*this,p,IRT_EQ,((sc.episode() % 2U) == 1U) ? 1 : 0); + sc.coverage(SpokeCoverage::Partial); + } + } + }; + + /// Decisions, events, and ends of the meta search protocol + class MetaProtocol : public Base { + public: + /// Scenario + enum class Scenario { + DecisionLegality, + IllegalDecisionInEngine, + FinishAtStart, + FinishAtLimit, + FailAtStart, + FailAtSolution, + ContinueAtLimit, + ContinueThenRestart, + ContinueWithLargestCutoff, + EngineConstrainsHub, + PortfolioHubConstraint, + Episodes, + }; + protected: + /// Scenario under test + Scenario scenario; + /// Return options for RBS with constant cutoff \a c + static Gecode::Search::Options rbs_options(unsigned long int c) { + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(c); + return o; + } + /// Return whether engine \a e has no further solution and ends with \a r + template + static bool ends(Engine& e, EndReason r) { + for (int i=0; i<2; i++) { + if (ProtocolSpace* s = e.next()) { + delete s; + return false; + } + if (e.end_reason() != r) + return false; + } + return true; + } + /// Return whether \a d is legal after event \a e + static bool legal(MetaEvent e, MetaDecision d) { + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } + /// Check the legality of each decision for each event + static bool decision_legality(void) { + const Gecode::Search::Statistics stat; + for (MetaEvent e : {MetaEvent::Start,MetaEvent::Solution, + MetaEvent::Exhausted,MetaEvent::Incomplete, + MetaEvent::Limit}) + for (MetaDecision d : {MetaDecision::Restart,MetaDecision::Continue, + MetaDecision::Finish}) { + HubContext hc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,e,MetaDecision::Restart,0,0,1,nullptr, + stat,NoGoods::eng); + if (hc.decision() != MetaDecision::Restart) + return false; + bool thrown = false; + try { + hc.decision(d); + } catch (const IllegalMetaDecision&) { + thrown = true; + } + if ((thrown == legal(e,d)) || + (hc.decision() != (thrown ? MetaDecision::Restart : d))) + return false; + } + // The engine sets the default decision + HubContext fc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,MetaEvent::Incomplete,MetaDecision::Finish, + 0,0,1,nullptr,stat,NoGoods::eng); + if (fc.decision() != MetaDecision::Finish) + return false; + SpokeContext sc = Gecode::Search::MetaContextAccess::spoke + (MetaEngine::Restart,MetaEvent::Start,0,0,1,nullptr,stat, + NoGoods::eng); + if (sc.coverage() != SpokeCoverage::Full) + return false; + sc.coverage(SpokeCoverage::Partial); + sc.coverage(SpokeCoverage::Reduced); + return sc.coverage() == SpokeCoverage::Reduced; + } + /// Check that an illegal decision throws from the engine + static bool illegal_decision_in_engine(void) { + ProtocolLog log; + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtStart,log); + Gecode::Search::Options o = rbs_options(10); + bool thrown = false; + try { + Gecode::RBS rbs(m,o); + } catch (const IllegalMetaDecision&) { + // The engine owns the cutoff only once it is constructed + delete o.cutoff; + thrown = true; + } + delete m; + return thrown && log.spoke.empty() && (log.live == 0); + } + /// Check that RBS and PBS end with \a r when hub() at Start follows \a pr + static bool ends_at_start(Protocol pr, EndReason r) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::RBS rbs(m,rbs_options(10)); + delete m; + if (!ends(rbs,r)) + return false; + } + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + Gecode::PBS pbs(m,o); + delete m; + if (!ends(pbs,r)) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + Gecode::PBS pbs(m,assets,o); + delete m; + if (!ends(pbs,r)) + return false; + } + return log.spoke.empty() && (log.hub.size() == 4U) && (log.live == 0); + } + /// Check that Finish at Limit ends RBS without a proof + static bool finish_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FinishAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + if (!ends(rbs,EndReason::Incomplete) || + (rbs.statistics().restart != 0U)) + return false; + } + using Call = std::pair; + return (log.hub == std::vector{{MetaEvent::Start,0}, + {MetaEvent::Limit,0}}) && + (log.spoke == std::vector{{MetaEvent::Start,0}}) && + (log.live == 0); + } + /// Check that a hub failing after a solution proves exhaustion + static bool fail_at_solution(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FailAtSolution,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + if (!ends(rbs,EndReason::Exhausted)) + return false; + } + return (log.spoke.size() == 1U) && (log.live == 0); + } + /// Check that Continue at Limit resumes the same spoke + static bool continue_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + const bool assigned = s->p.assigned() && (s->p.val() == 0); + delete s; + if (!assigned || (rbs.statistics().restart != 0U)) + return false; + } + if ((log.spoke.size() != 1U) || (log.hub.size() < 3U)) + return false; + for (std::size_t i=1; i( + std::count(log.hub.begin(),log.hub.end(), + std::make_pair(MetaEvent::Limit,e))); + } + /// Check that a restart after a solution uses the cutoff, not the extended limit + static bool continue_then_restart(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::RBS rbs(m,rbs_options(2)); + delete m; + for (int i=0; i<2; i++) { + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + } + // Each episode fails six times and so reaches the cutoff of two twice + return (limits(log,0UL) == 2L) && (limits(log,1UL) == 2L) && + (log.live == 0); + } + /// Cutoff generator whose values after the first are the largest possible + class LargestCutoff : public Gecode::Search::Cutoff { + protected: + /// The current value + unsigned long long int c; + public: + /// Initialize with first value \a c0 + explicit LargestCutoff(unsigned long long int c0) : c(c0) {} + unsigned long long int operator ()(void) const override { + return c; + } + unsigned long long int operator ++(void) override { + c = ULLONG_MAX; + return c; + } + Gecode::Search::Cutoff* copy(void) const override { + return new LargestCutoff(*this); + } + }; + /// Check that Continue with the largest cutoff does not wrap the limit around + static bool continue_with_largest_cutoff(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = new LargestCutoff(2); + Gecode::RBS rbs(m,o); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + return (limits(log,0UL) == 1L) && (log.live == 0); + } + /// Check that RBS constrains the hub when hub() does nothing + static bool engine_constrains_hub(void) { + ProtocolLog log; + std::vector costs; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::EmptyHub,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + // Without the bound, every spoke finds c = 3 again + while (ProtocolSpace* s = rbs.next()) { + costs.push_back(s->c.val()); + delete s; + if (costs.size() > 10U) + return false; + } + if (rbs.end_reason() != EndReason::Exhausted) + return false; + } + return (costs == std::vector{3,2,1,0}) && (log.live == 0); + } + /// Check that a constraint posted by hub() under PBS takes effect + static bool portfolio_hub_constraint(void) { + ProtocolLog log; + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + unsigned int unstable = log.unstable; + Gecode::PBS pbs(m,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1) && + (log.unstable == unstable+1U); + delete s; + if (!ok) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + unsigned int unstable = log.unstable; + Gecode::PBS pbs(m,assets,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1) && + (log.unstable == unstable+1U); + delete s; + if (!ok) + return false; + } + return log.live == 0; + } + /// Check episode numbering across solution and limit restarts + static bool episodes(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::Alternate,log); + Gecode::RBS rbs(m,rbs_options(2)); + delete m; + for (int i=0; i<3; i++) { + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + if (rbs.statistics().restart != 4U) + return false; + } + using Call = std::pair; + const std::vector hub{{MetaEvent::Start,0}, + {MetaEvent::Solution,0}, + {MetaEvent::Limit,1}, + {MetaEvent::Solution,2}, + {MetaEvent::Limit,3}}; + const std::vector spoke{{MetaEvent::Start,0}, + {MetaEvent::Solution,1}, + {MetaEvent::Limit,2}, + {MetaEvent::Solution,3}, + {MetaEvent::Limit,4}}; + return (log.hub == hub) && (log.spoke == spoke) && (log.live == 0); + } + public: + /// Initialize scenario \a s with name \a n + MetaProtocol(const std::string& n, Scenario s) + : Base("Search::Meta::"+n), scenario(s) {} + bool run(void) override { + switch (scenario) { + case Scenario::DecisionLegality: + return decision_legality(); + case Scenario::IllegalDecisionInEngine: + return illegal_decision_in_engine(); + case Scenario::FinishAtStart: + return ends_at_start(Protocol::FinishAtStart,EndReason::Incomplete); + case Scenario::FinishAtLimit: + return finish_at_limit(); + case Scenario::FailAtStart: + return ends_at_start(Protocol::FailAtStart,EndReason::Exhausted); + case Scenario::FailAtSolution: + return fail_at_solution(); + case Scenario::ContinueAtLimit: + return continue_at_limit(); + case Scenario::ContinueThenRestart: + return continue_then_restart(); + case Scenario::ContinueWithLargestCutoff: + return continue_with_largest_cutoff(); + case Scenario::EngineConstrainsHub: + return engine_constrains_hub(); + case Scenario::PortfolioHubConstraint: + return portfolio_hub_constraint(); + case Scenario::Episodes: + return episodes(); + default: + GECODE_NEVER; + } + return false; + } + }; + + MetaProtocol meta_decision_legality + ("DecisionLegality",MetaProtocol::Scenario::DecisionLegality); + MetaProtocol meta_illegal_decision_in_engine + ("IllegalDecisionInEngine", + MetaProtocol::Scenario::IllegalDecisionInEngine); + MetaProtocol meta_finish_at_start + ("FinishAtStart",MetaProtocol::Scenario::FinishAtStart); + MetaProtocol meta_finish_at_limit + ("FinishAtLimit",MetaProtocol::Scenario::FinishAtLimit); + MetaProtocol meta_fail_at_start + ("FailAtStart",MetaProtocol::Scenario::FailAtStart); + MetaProtocol meta_fail_at_solution + ("FailAtSolution",MetaProtocol::Scenario::FailAtSolution); + MetaProtocol meta_continue_at_limit + ("ContinueAtLimit",MetaProtocol::Scenario::ContinueAtLimit); + MetaProtocol meta_continue_then_restart + ("ContinueThenRestart",MetaProtocol::Scenario::ContinueThenRestart); + MetaProtocol meta_continue_with_largest_cutoff + ("ContinueWithLargestCutoff", + MetaProtocol::Scenario::ContinueWithLargestCutoff); + MetaProtocol meta_engine_constrains_hub + ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); + MetaProtocol meta_portfolio_hub_constraint + ("PortfolioHubConstraint",MetaProtocol::Scenario::PortfolioHubConstraint); + MetaProtocol meta_episodes("Episodes",MetaProtocol::Scenario::Episodes); + + /** + * \brief Constant cutoff counting its deletions + * + * The cutoff exceeds the failures of NoSolution, so a restart-based + * asset finishes without restarting. Without no-goods, restarts with a + * smaller constant cutoff would repeat the same search forever. + */ + class CountingCutoff : public Gecode::Search::CutoffConstant { + public: + /// Number of deletions, owned by the test + std::atomic& deleted; + CountingCutoff(std::atomic& d) + : Gecode::Search::CutoffConstant(1000), deleted(d) {} + ~CountingCutoff(void) override { + deleted++; + } + }; + + /// Space without solutions whose first portfolio asset fails + class FailingAsset : public NoSolution { + public: + FailingAsset(void) = default; + FailingAsset(FailingAsset& s) : NoSolution(s) {} Gecode::Space* copy(void) override { return new FailingAsset(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::PORTFOLIO) && (mi.asset() == 0U)) + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Portfolio) && + (sc.asset() == 0U)) fail(); - return true; } }; @@ -3405,7 +4880,7 @@ namespace Test { delete s; return false; } - if (pbs.stopped()) + if (pbs.end_reason() != EndReason::Exhausted) return false; } return deleted == 1U; @@ -3562,8 +5037,9 @@ namespace Test { (void)new MetaDispatch("RBS::SpokeOnly", MetaDispatch::Scenario::RbsSpokeOnly); (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RbsHubContinue); (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RbsHubRestart); - (void)new MetaDispatch("RBS::SpokeComplete", MetaDispatch::Scenario::RbsSpokeComplete); - (void)new MetaDispatch("RBS::SpokeIncomplete", MetaDispatch::Scenario::RbsSpokeIncomplete); + (void)new MetaDispatch("RBS::SpokeFull", MetaDispatch::Scenario::RbsSpokeFull); + (void)new MetaDispatch("RBS::SpokeReduced", MetaDispatch::Scenario::RbsSpokeReduced); + (void)new MetaDispatch("RBS::SpokePartial", MetaDispatch::Scenario::RbsSpokePartial); (void)new MetaDispatch("RBS::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", MetaDispatch::Scenario::RbsNoGoodsResetOwnership); @@ -3587,8 +5063,8 @@ namespace Test { (void)new MetaDispatch("PBS::SequentialHubOnly", MetaDispatch::Scenario::PbsSequentialHubOnly); (void)new MetaDispatch("PBS::SequentialSpokeOnly", MetaDispatch::Scenario::PbsSequentialSpokeOnly); (void)new MetaDispatch("PBS::Sequential", MetaDispatch::Scenario::PbsSequential); - (void)new MetaDispatch("PBS::DefaultHubRemovesBranchers", - MetaDispatch::Scenario::PbsDefaultHubRemovesBranchers); + (void)new MetaDispatch("PBS::SpokeWithoutBrancher", MetaDispatch::Scenario::PbsSpokeWithoutBrancher); + (void)new MetaDispatch("PBS::NoBrancher", MetaDispatch::Scenario::PbsNoBrancher); #ifdef GECODE_HAS_THREADS (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PbsParallelHubOnly); (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PbsParallelSpokeOnly);