diff --git a/changelog.in b/changelog.in index 543c60f69a..0583ea9da9 100644 --- a/changelog.in +++ b/changelog.in @@ -415,6 +415,24 @@ Rank: minor Throw Search::SpokeNoBrancher when a non-failed PBS spoke has no branchers after spoke() although the hub had branchers. +[ENTRY] +Module: search +What: new +Rank: minor +[DESCRIPTION] +Add Choice::alternative_failed(), which search engines call when an +alternative of a choice fails, so branchers can learn from failures. +[MORE] +Not all search engines call it; LDS does not. The default does nothing. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Report the alternative actually taken to tracers of parallel DFS and BAB after +work stealing, instead of possibly a later one. + [ENTRY] Module: search What: bug @@ -487,6 +505,40 @@ Make IntPropLevel an enum class with underlying type unsigned int and add operator|, operator&, and operator|=. Test bits with (ipl & IPL_BASIC) != IPL_DEF; remove IPL_BITS_. +[ENTRY] +Module: kernel +What: new +Rank: minor +[DESCRIPTION] +Add last-conflict variable selection: INT_VAR_LAST_CONFLICT(k, vars), +BOOL_VAR_LAST_CONFLICT(k, vars), SET_VAR_LAST_CONFLICT(k, vars), and +FLOAT_VAR_LAST_CONFLICT(k, vars) select the unassigned variable whose +alternative failed most recently, among the last k such variables, and +otherwise select as vars does. +[MORE] +Supported only by branch() (not by assign(), with INT_VALUES_MIN/MAX, LDSB, +or open lists), as the only or first selection of a tie-break. The brancher +learns only from engines that report failures, so with LDS it selects as +vars does. + +[ENTRY] +Module: kernel +What: new +Rank: minor +[DESCRIPTION] +Add solution-guided value selection: INT_VAL_SOLUTION(v, fallback), +BOOL_VAL_SOLUTION(v, fallback), SET_VAL_SOLUTION(v, fallback), and +FLOAT_VAL_SOLUTION(v, fallback) follow the solution stored for the variable +in a shared handle v (IntSolutionValues, SetSolutionValues, or +FloatSolutionValues), and otherwise select as fallback does. +[MORE] +Integer and Boolean variables try the stored value. Set variables include an +undecided element of the stored set, or else exclude one. Float variables +split at the median and try the half containing the stored value first. A +restart-based search can store each new solution in v from hub(). Choices +record their value, so later updates affect neither recomputation nor +no-goods. + [ENTRY] Module: int What: bug diff --git a/cmake/GecodeSources.cmake b/cmake/GecodeSources.cmake index 0a82bb1979..4411cdc295 100644 --- a/cmake/GecodeSources.cmake +++ b/cmake/GecodeSources.cmake @@ -17,6 +17,7 @@ set(GECODE_KERNEL_SOURCES gecode/kernel/branch/afc.cpp gecode/kernel/branch/chb.cpp gecode/kernel/branch/function.cpp + gecode/kernel/branch/last-conflict.cpp gecode/kernel/core.cpp gecode/kernel/data/array.cpp gecode/kernel/exception.cpp @@ -70,6 +71,7 @@ set(GECODE_INT_SOURCES gecode/int/branch.cpp gecode/int/branch/action.cpp gecode/int/branch/chb.cpp + gecode/int/branch/solution-values.cpp gecode/int/branch/val-sel-commit.cpp gecode/int/branch/view-sel.cpp gecode/int/branch/view-values.cpp @@ -132,6 +134,7 @@ set(GECODE_SET_SOURCES gecode/set/branch/action.cpp gecode/set/branch/chb.cpp gecode/set/branch/ngl.cpp + gecode/set/branch/solution-values.cpp gecode/set/branch/val-sel-commit.cpp gecode/set/branch/view-sel.cpp gecode/set/cardinality.cpp @@ -184,6 +187,7 @@ set(GECODE_FLOAT_SOURCES gecode/float/branch.cpp gecode/float/branch/action.cpp gecode/float/branch/chb.cpp + gecode/float/branch/solution-values.cpp gecode/float/branch/val-sel-commit.cpp gecode/float/branch/view-sel.cpp gecode/float/channel.cpp diff --git a/gecode/float.hh b/gecode/float.hh index c5072fa4d5..32c2291574 100644 --- a/gecode/float.hh +++ b/gecode/float.hh @@ -1804,12 +1804,63 @@ namespace Gecode { FloatVarBranch FLOAT_VAR_CHB_SIZE_MAX(BranchTbl tbl = nullptr); /// Select variable with largest CHB Q-score divided by domain size FloatVarBranch FLOAT_VAR_CHB_SIZE_MAX(const FloatCHB& c, BranchTbl tbl = nullptr); + /** + * \brief Select the variable that failed most recently, otherwise as + * \a vars + * + * As INT_VAR_LAST_CONFLICT, with any float value selection. + */ + FloatVarBranch FLOAT_VAR_LAST_CONFLICT(int k, const FloatVarBranch& vars); //@} } // namespace Gecode #include +namespace Gecode { + + /** + * \brief Stored solution values for solution-guided value selection + * + * Holds one value per variable position for FLOAT_VAL_SOLUTION. Empty + * until update() stores values, typically from a solution, and updated as + * IntSolutionValues is. + * + * Copies share the stored values across clones and threads. Updates are + * serialized and reads take no lock. + * + * \ingroup TaskModelFloatBranch + */ + class FloatSolutionValues : public SharedHandle { + protected: + class Storage; + /// Return object of correct type + Storage& object() const; + + public: + /// Construct as not yet initialized; only assignment may be used + FloatSolutionValues(); + /// Create handle for \a n positions with no stored values + GECODE_FLOAT_EXPORT explicit FloatSolutionValues(int n); + /** + * \brief Store the medians of \a x + * + * Throws Float::ArgumentSizeMismatch if sizes differ, leaving stored + * values unchanged. + */ + GECODE_FLOAT_EXPORT void update(const FloatVarArgs& x); + /// Whether no values have been stored yet + bool empty() const; + /// Return number of positions + int size() const; + /// Return stored value at position \a i + FloatNum operator[](int i) const; + }; + +} // namespace Gecode + +#include + namespace Gecode { /** @@ -1824,13 +1875,18 @@ namespace Gecode { SEL_SPLIT_MIN, ///< Select values not greater than mean of smallest and largest value SEL_SPLIT_MAX, ///< Select values greater than mean of smallest and largest value SEL_SPLIT_RND, ///< Select values randomly which are not greater or not smaller than mean of largest and smallest value - SEL_VAL_COMMIT ///< Select value according to user-defined functions + SEL_VAL_COMMIT, ///< Select value according to user-defined functions + SEL_SOLUTION_SPLIT_MIN, ///< Follow stored solution value, otherwise as SEL_SPLIT_MIN + SEL_SOLUTION_SPLIT_MAX, ///< Follow stored solution value, otherwise as SEL_SPLIT_MAX + SEL_SOLUTION_SPLIT_RND ///< Follow stored solution value, otherwise as SEL_SPLIT_RND }; using enum Select; protected: /// Which value to select Select s; + /// Stored solution values for solution-guided selection + FloatSolutionValues sv; public: /// Initialize with selection strategy \a s @@ -1839,8 +1895,12 @@ namespace Gecode { FloatValBranch(const Rnd& r); /// Initialize with value function \a f and commit function \a c FloatValBranch(FloatBranchVal v, FloatBranchCommit c); + /// Initialize to follow \a v, otherwise as \a fallback + FloatValBranch(const FloatSolutionValues& v, const FloatValBranch& fallback); /// Return selection strategy Select select() const; + /// Return stored solution values + const FloatSolutionValues& solution_values() const; }; /** @@ -1861,6 +1921,20 @@ namespace Gecode { * alternative and that \a x must be greater or equal than \a n otherwise. */ FloatValBranch FLOAT_VAL(FloatBranchVal v, FloatBranchCommit c = nullptr); + /** + * \brief Follow the value stored in \a v, otherwise as \a fallback + * + * Splits at the median and tries first the half containing the value + * stored at the variable's position \a i in \a v. Falls back to + * \a fallback when \a v is empty, \a i is at least v.size(), or the + * stored value is outside the domain. + * + * \a fallback must be FLOAT_VAL_SPLIT_MIN, FLOAT_VAL_SPLIT_MAX, or + * FLOAT_VAL_SPLIT_RND; others throw UnsupportedFallback. An uninitialized + * \a v throws UninitializedSolutionValues. + */ + FloatValBranch FLOAT_VAL_SOLUTION(const FloatSolutionValues& v, + const FloatValBranch& fallback = FLOAT_VAL_SPLIT_MIN()); //@} } // namespace Gecode diff --git a/gecode/float/branch.cpp b/gecode/float/branch.cpp index bf77f56190..852fe50269 100644 --- a/gecode/float/branch.cpp +++ b/gecode/float/branch.cpp @@ -43,8 +43,8 @@ namespace Gecode { vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; - post_view_value_brancher( - home, xv, vs, Branch::value_selection_commit(home, vals), std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.last_conflict(), std::move(bf), std::move(vvp)); } void @@ -53,6 +53,7 @@ namespace Gecode { using namespace Float; if (home.failed()) return; + check_last_conflict_tie_break(vars, "Float::branch"); vars.a.expand(home, x); if ((vars.a.select() == FloatVarBranch::SEL_NONE) || (vars.a.select() == FloatVarBranch::SEL_RND)) vars.b = FLOAT_VAR_NONE(); @@ -71,19 +72,19 @@ namespace Gecode { if (vars.c.select() == FloatVarBranch::SEL_NONE) { ViewSel* vs[2] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), - std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), + std::move(bf), std::move(vvp)); } else if (vars.d.select() == FloatVarBranch::SEL_NONE) { ViewSel* vs[3] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), - std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), + std::move(bf), std::move(vvp)); } else { ViewSel* vs[4] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c), Branch::view_selection(home, vars.d)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), - std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), + std::move(bf), std::move(vvp)); } } } @@ -101,6 +102,8 @@ namespace Gecode { using namespace Float; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Float::assign"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -114,6 +117,9 @@ namespace Gecode { using namespace Float; if (home.failed()) return; + if (vars.a.last_conflict() > 0) + throw UnsupportedLastConflict("Float::assign"); + check_last_conflict_tie_break(vars, "Float::assign"); vars.a.expand(home, x); if ((vars.a.select() == FloatVarBranch::SEL_NONE) || (vars.a.select() == FloatVarBranch::SEL_RND)) vars.b = FLOAT_VAR_NONE(); diff --git a/gecode/float/branch.hh b/gecode/float/branch.hh index 28e7edff81..f1684f7296 100644 --- a/gecode/float/branch.hh +++ b/gecode/float/branch.hh @@ -282,6 +282,48 @@ namespace Gecode::Float::Branch { void dispose(Space& home); }; + /** + * \brief Value selection class for the stored solution value of a view + * + * Splits at the median and tries first the half containing the stored + * value at the view's position when available and in the domain; + * otherwise delegates to \a Fallback. + * + * Requires \code #include \endcode + * \ingroup FuncFloatValSel + */ + template + class ValSelSolution : public ValSel { + protected: + /// The stored solution values + FloatSolutionValues sv; + /// The fallback value selection + Fallback fb; + + public: + /// Constructor for initialization + ValSelSolution(Space& home, const ValBranch& vb); + /// Constructor for cloning + ValSelSolution(Space& home, ValSelSolution& vs); + /// Split the random state of the fallback by \a a + void + random_split(unsigned int a) { + fb.random_split(a); + } + /// Whether the fallback has random state + bool + random() const { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.rand): a member random(), not the C library function + return fb.random(); + } + /// Return value of view \a x at position \a i + FloatNumBranch val(const Space& home, FloatView x, int i); + /// Whether dispose must always be called (that is, notice is needed) + bool notice() const; + /// Delete value selection + void dispose(Space& home); + }; + } // namespace Gecode::Float::Branch #include diff --git a/gecode/float/branch/solution-values.cpp b/gecode/float/branch/solution-values.cpp new file mode 100644 index 0000000000..0ff8a02a8c --- /dev/null +++ b/gecode/float/branch/solution-values.cpp @@ -0,0 +1,63 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + // An empty value array allocates nothing (heap allocations must be positive) + FloatSolutionValues::Storage::Storage(int n0) + : n(n0), filled(false), v(n0 > 0 ? heap.alloc>(n0) : nullptr) { + for (int i = 0; i < n; i++) + v[i].store(0.0, std::memory_order_relaxed); + } + + FloatSolutionValues::Storage::~Storage() { + heap.free>(v, n); + } + + FloatSolutionValues::FloatSolutionValues(int n) : SharedHandle(new Storage(n)) {} + + void + FloatSolutionValues::update(const FloatVarArgs& x) { + Storage& o = object(); + if (x.size() != o.n) + throw Float::ArgumentSizeMismatch("FloatSolutionValues::update"); + Support::Lock lock(o.m); + for (int i = 0; i < o.n; i++) + o.v[i].store(x[i].med(), std::memory_order_relaxed); + o.filled.store(true, std::memory_order_release); + } + +} // namespace Gecode + +// STATISTICS: float-branch diff --git a/gecode/float/branch/solution-values.hpp b/gecode/float/branch/solution-values.hpp new file mode 100644 index 0000000000..8e573f67b4 --- /dev/null +++ b/gecode/float/branch/solution-values.hpp @@ -0,0 +1,77 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + /// Object for storing solution values + class GECODE_VTABLE_EXPORT FloatSolutionValues::Storage : public SharedHandle::Object { + public: + /// Mutex to serialize updates + Support::Mutex m; + /// Number of positions + int n; + /// Whether values have been stored, set after the values are stored + std::atomic filled; + /// Stored values + std::atomic* v; + /// Initialize for \a n positions with no stored values + Storage(int n); + /// Delete object + GECODE_FLOAT_EXPORT ~Storage() override; + }; + + forceinline FloatSolutionValues::Storage& + FloatSolutionValues::object() const { + return static_cast(*SharedHandle::object()); + } + + forceinline FloatSolutionValues::FloatSolutionValues() = default; + + forceinline bool + FloatSolutionValues::empty() const { + return !object().filled.load(std::memory_order_acquire); + } + forceinline int + FloatSolutionValues::size() const { + return object().n; + } + forceinline FloatNum + FloatSolutionValues::operator[](int i) const { + assert((i >= 0) && (i < object().n)); + return object().v[i].load(std::memory_order_relaxed); + } + +} // namespace Gecode + +// STATISTICS: float-branch diff --git a/gecode/float/branch/val-sel-commit.cpp b/gecode/float/branch/val-sel-commit.cpp index d5acf5b67f..12c668e443 100644 --- a/gecode/float/branch/val-sel-commit.cpp +++ b/gecode/float/branch/val-sel-commit.cpp @@ -49,6 +49,12 @@ namespace Gecode::Float::Branch { } else { return new (home) ValSelCommit, ValCommitFunction>(home, fvb); } + case FloatValBranch::SEL_SOLUTION_SPLIT_MIN: + return new (home) ValSelCommit, ValCommitLqGq>(home, fvb); + case FloatValBranch::SEL_SOLUTION_SPLIT_MAX: + return new (home) ValSelCommit, ValCommitLqGq>(home, fvb); + case FloatValBranch::SEL_SOLUTION_SPLIT_RND: + return new (home) ValSelCommit, ValCommitLqGq>(home, fvb); default: throw UnknownBranching("Float::branch"); } diff --git a/gecode/float/branch/val-sel.hpp b/gecode/float/branch/val-sel.hpp index a2718af9a3..bb99343577 100644 --- a/gecode/float/branch/val-sel.hpp +++ b/gecode/float/branch/val-sel.hpp @@ -99,6 +99,42 @@ namespace Gecode::Float::Branch { r.~Rnd(); } + template + forceinline + ValSelSolution::ValSelSolution(Space& home, const ValBranch& vb) + : ValSel(home, vb), sv(static_cast(vb).solution_values()), + fb(home, vb) {} + template + forceinline + ValSelSolution::ValSelSolution(Space& home, ValSelSolution& vs) + : ValSel(home, vs), sv(vs.sv), fb(home, vs.fb) {} + template + forceinline FloatNumBranch + ValSelSolution::val(const Space& home, FloatView x, int i) { + if (!sv.empty() && (i < sv.size())) { + // Read the stored value once, as another thread may update it + FloatNum v = sv[i]; + if ((x.min() <= v) && (v <= x.max())) { + FloatNumBranch nl; + nl.n = x.med(); + nl.l = (v <= nl.n); + return nl; + } + } + return fb.val(home, x, i); + } + template + forceinline bool + ValSelSolution::notice() const { + return true; + } + template + forceinline void + ValSelSolution::dispose(Space& home) { + sv.~FloatSolutionValues(); + fb.dispose(home); + } + } // namespace Gecode::Float::Branch // STATISTICS: float-branch diff --git a/gecode/float/branch/val.hpp b/gecode/float/branch/val.hpp index f81c47ee9a..070e430359 100644 --- a/gecode/float/branch/val.hpp +++ b/gecode/float/branch/val.hpp @@ -44,11 +44,35 @@ namespace Gecode { FloatValBranch::FloatValBranch(FloatBranchVal v, FloatBranchCommit c) : ValBranch(std::move(v), std::move(c)), s(SEL_VAL_COMMIT) {} + inline FloatValBranch::FloatValBranch(const FloatSolutionValues& v, const FloatValBranch& fallback) + : ValBranch(fallback), sv(v) { + if (!sv) + throw UninitializedSolutionValues("Float::FLOAT_VAL_SOLUTION"); + switch (fallback.select()) { + case SEL_SPLIT_MIN: + s = SEL_SOLUTION_SPLIT_MIN; + break; + case SEL_SPLIT_MAX: + s = SEL_SOLUTION_SPLIT_MAX; + break; + case SEL_SPLIT_RND: + s = SEL_SOLUTION_SPLIT_RND; + break; + default: + throw UnsupportedFallback("Float::FLOAT_VAL_SOLUTION"); + } + } + forceinline FloatValBranch::Select FloatValBranch::select() const { return s; } + forceinline const FloatSolutionValues& + FloatValBranch::solution_values() const { + return sv; + } + inline FloatValBranch FLOAT_VAL_SPLIT_MIN() { return FloatValBranch(FloatValBranch::SEL_SPLIT_MIN); @@ -69,6 +93,11 @@ namespace Gecode { return FloatValBranch(std::move(v), std::move(c)); } + inline FloatValBranch + FLOAT_VAL_SOLUTION(const FloatSolutionValues& v, const FloatValBranch& fallback) { + return FloatValBranch(v, fallback); + } + } // namespace Gecode // STATISTICS: float-branch diff --git a/gecode/float/branch/var.hpp b/gecode/float/branch/var.hpp index 39bc7c3708..2f7dc33d8c 100644 --- a/gecode/float/branch/var.hpp +++ b/gecode/float/branch/var.hpp @@ -289,6 +289,13 @@ namespace Gecode { return FloatVarBranch(FloatVarBranch::SEL_CHB_SIZE_MAX, c, std::move(tbl)); } + inline FloatVarBranch + FLOAT_VAR_LAST_CONFLICT(int k, const FloatVarBranch& vars) { + FloatVarBranch v(vars); + v.last_conflict(k); + return v; + } + } // namespace Gecode // STATISTICS: float-branch diff --git a/gecode/int.hh b/gecode/int.hh index 3c319b9fad..af5b223f5c 100644 --- a/gecode/int.hh +++ b/gecode/int.hh @@ -5217,6 +5217,68 @@ namespace Gecode { #include +namespace Gecode { + + /** + * \brief Stored solution values for solution-guided value selection + * + * Holds one value per variable position for INT_VAL_SOLUTION and + * BOOL_VAL_SOLUTION. Empty until update() stores values from assigned + * variables, typically a solution. A restart-based search can update it + * from Space::hub(): + * \code + * void hub(HubContext& hc) override { + * if ((hc.engine() == MetaEngine::Restart) && (hc.event() == MetaEvent::Solution)) + * sv.update(down_cast(*hc.last()).x); + * Space::hub(hc); + * } + * \endcode + * + * Copies share the stored values across clones and threads. Updates are + * serialized and reads take no lock: a concurrent reader may see a mix of + * old and new values, which only affects which value is tried first. + * + * \ingroup TaskModelIntBranch + */ + class IntSolutionValues : public SharedHandle { + protected: + class Storage; + /// Return object of correct type + Storage& object() const; + + public: + /// Construct as not yet initialized; only assignment may be used + IntSolutionValues(); + /// Create handle for \a n positions with no stored values + GECODE_INT_EXPORT explicit IntSolutionValues(int n); + /** + * \brief Store the values of the assigned integer variables \a x + * + * Throws Int::ArgumentSizeMismatch if sizes differ or + * Int::ValOfUnassignedVar if a variable is unassigned, leaving stored + * values unchanged. + */ + GECODE_INT_EXPORT void update(const IntVarArgs& x); + /** + * \brief Store the values of the assigned Boolean variables \a x + * + * Throws Int::ArgumentSizeMismatch if sizes differ or + * Int::ValOfUnassignedVar if a variable is unassigned, leaving stored + * values unchanged. + */ + GECODE_INT_EXPORT void update(const BoolVarArgs& x); + /// Whether no values have been stored yet + bool empty() const; + /// Return number of positions + int size() const; + /// Return stored value at position \a i + int operator[](int i) const; + }; + +} // namespace Gecode + +#include + namespace Gecode { /// Function type for printing branching alternatives for integer variables @@ -5476,6 +5538,34 @@ namespace Gecode { * largest and second-largest value still in the domain. */ IntVarBranch INT_VAR_REGRET_MAX_MAX(BranchTbl tbl = nullptr); + /** + * \brief Select the variable that failed most recently, otherwise as + * \a vars + * + * Keeps up to \a k variables whose alternatives failed most recently, + * selecting the most recent one that is unassigned and passes the branch + * filter, or falling back to \a vars. Value selection is unchanged. Throws + * IllegalConflictSetSize if \a k is less than 1. + * + * Each branch() call has its own conflict set, shared across clones, + * threads, portfolio assets, and restarts. Learns only from engines that + * report failures (see Choice::alternative_failed()), so with LDS it + * selects as \a vars does. Choices record their variable, so recomputation + * and archives commit as before. With BAB, which stored nodes fail + * unreported under a new bound depends on the recomputation distances, and + * so can the search. + * + * Supported only by branch(), as the only or first selection of a + * tie-break, and not with INT_VALUES_MIN or INT_VALUES_MAX. Other uses + * (including assign(), symmetry breaking, and open lists) throw + * UnsupportedLastConflict. + * + * Based on: + * Christophe Lecoutre, Lakhdar Saïs, Sébastien Tabary, Vincent Vidal. + * Reasoning from last conflict(s) in constraint programming. + * Artificial Intelligence 173(18), 2009. + */ + IntVarBranch INT_VAR_LAST_CONFLICT(int k, const IntVarBranch& vars); /// Select first unassigned variable BoolVarBranch BOOL_VAR_NONE(); @@ -5513,6 +5603,13 @@ namespace Gecode { BoolVarBranch BOOL_VAR_CHB_MAX(const BoolCHB& c, BranchTbl tbl = nullptr); /// Select variable with largest CHB Q-score BoolVarBranch BOOL_VAR_CHB_MAX(BranchTbl tbl = nullptr); + /** + * \brief Select the variable that failed most recently, otherwise as + * \a vars + * + * As INT_VAR_LAST_CONFLICT, with any Boolean value selection. + */ + BoolVarBranch BOOL_VAR_LAST_CONFLICT(int k, const BoolVarBranch& vars); //@} } // namespace Gecode @@ -5538,15 +5635,21 @@ namespace Gecode { SEL_SPLIT_MAX, ///< Select values greater than mean of smallest and largest value SEL_RANGE_MIN, ///< Select the smallest range of the variable domain if it has several ranges, otherwise select values not greater than mean of smallest and largest value SEL_RANGE_MAX, ///< Select the largest range of the variable domain if it has several ranges, otherwise select values greater than mean of smallest and largest value - SEL_VAL_COMMIT, ///< Select value according to user-defined functions - SEL_VALUES_MIN, ///< Select all values starting from smallest - SEL_VALUES_MAX ///< Select all values starting from largest + SEL_VAL_COMMIT, ///< Select value according to user-defined functions + SEL_VALUES_MIN, ///< Select all values starting from smallest + SEL_VALUES_MAX, ///< Select all values starting from largest + SEL_SOLUTION_MIN, ///< Select stored solution value, otherwise smallest value + SEL_SOLUTION_MED, ///< Select stored solution value, otherwise greatest value not greater than the median + SEL_SOLUTION_MAX, ///< Select stored solution value, otherwise largest value + SEL_SOLUTION_RND ///< Select stored solution value, otherwise random value }; using enum Select; protected: /// Which value to select Select s; + /// Stored solution values (only for solution-guided selection) + IntSolutionValues sv; public: /// Initialize with selection strategy \a s @@ -5555,8 +5658,12 @@ namespace Gecode { IntValBranch(const Rnd& r); /// Initialize with value function \a f and commit function \a c IntValBranch(IntBranchVal v, IntBranchCommit c); + /// Initialize with solution values \a v and \a fallback (see INT_VAL_SOLUTION) + IntValBranch(const IntSolutionValues& v, const IntValBranch& fallback); /// Return selection strategy Select select() const; + /// Return stored solution values (uninitialized if not solution-guided) + const IntSolutionValues& solution_values() const; }; /** @@ -5568,16 +5675,21 @@ namespace Gecode { public: /// Which value selection enum class Select { - SEL_MIN, ///< Select smallest value - SEL_MAX, ///< Select largest value - SEL_RND, ///< Select random value - SEL_VAL_COMMIT ///< Select value according to user-defined functions + SEL_MIN, ///< Select smallest value + SEL_MAX, ///< Select largest value + SEL_RND, ///< Select random value + SEL_VAL_COMMIT, ///< Select value according to user-defined functions + SEL_SOLUTION_MIN, ///< Select stored solution value, otherwise smallest value + SEL_SOLUTION_MAX, ///< Select stored solution value, otherwise largest value + SEL_SOLUTION_RND ///< Select stored solution value, otherwise random value }; using enum Select; protected: /// Which value to select Select s; + /// Stored solution values (only for solution-guided selection) + IntSolutionValues sv; public: /// Initialize with selection strategy \a s @@ -5586,8 +5698,12 @@ namespace Gecode { BoolValBranch(const Rnd& r); /// Initialize with value function \a f and commit function \a c BoolValBranch(BoolBranchVal v, BoolBranchCommit c); + /// Initialize with solution values \a v and \a fallback (see BOOL_VAL_SOLUTION) + BoolValBranch(const IntSolutionValues& v, const BoolValBranch& fallback); /// Return selection strategy Select select() const; + /// Return stored solution values (uninitialized if not solution-guided) + const IntSolutionValues& solution_values() const; }; /** @@ -5622,6 +5738,29 @@ namespace Gecode { IntValBranch INT_VALUES_MIN(); /// Try all values starting from largest IntValBranch INT_VALUES_MAX(); + /** + * \brief Select the value stored in \a v, otherwise as \a fallback + * + * Selects the value stored at the variable's position \a i in \a v, or + * falls back to \a fallback when \a v is empty, \a i is at least + * v.size(), or the stored value is not in the domain. The first + * alternative assigns the selected value and the second removes it. + * Choices record their value, so later updates to \a v affect neither + * recomputation nor no-goods. + * + * \a fallback must be INT_VAL_MIN, INT_VAL_MED, INT_VAL_MAX, or + * INT_VAL_RND; others throw UnsupportedFallback. An uninitialized + * \a v throws UninitializedSolutionValues. + * + * Based on solution-based phase saving: + * Emir Demirović, Geoffrey Chu, Peter J. Stuckey. Solution-based phase + * saving for CP: A value-selection heuristic to simulate local search + * behavior in complete solvers. CP 2018. + * which follows: + * J. Christopher Beck. Solution-guided multi-point constructive search + * for job shop scheduling. JAIR 29, 2007. + */ + IntValBranch INT_VAL_SOLUTION(const IntSolutionValues& v, const IntValBranch& fallback = INT_VAL_MIN()); /// Select smallest value BoolValBranch BOOL_VAL_MIN(); @@ -5636,6 +5775,13 @@ namespace Gecode { * and that \a x must be different from \a n for the second alternative. */ BoolValBranch BOOL_VAL(BoolBranchVal v, BoolBranchCommit c = nullptr); + /** + * \brief Select the value stored in \a v, otherwise as \a fallback + * + * As INT_VAL_SOLUTION, with BOOL_VAL_MIN, BOOL_VAL_MAX, or BOOL_VAL_RND + * as fallback. + */ + BoolValBranch BOOL_VAL_SOLUTION(const IntSolutionValues& v, const BoolValBranch& fallback = BOOL_VAL_MIN()); //@} } // namespace Gecode diff --git a/gecode/int/branch.cpp b/gecode/int/branch.cpp index 5fed8cff21..799063bd81 100644 --- a/gecode/int/branch.cpp +++ b/gecode/int/branch.cpp @@ -32,6 +32,16 @@ #include +namespace Gecode::Int::Branch { namespace { + + /// Whether \a vals tries all values (unsupported with last-conflict) + bool + all_values(const IntValBranch& vals) { + return (vals.select() == IntValBranch::SEL_VALUES_MIN) || (vals.select() == IntValBranch::SEL_VALUES_MAX); + } + +}} // namespace Gecode::Int::Branch + namespace Gecode { void @@ -40,6 +50,8 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if ((vars.last_conflict() > 0) && Branch::all_values(vals)) + throw UnsupportedLastConflict("Int::branch"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -51,8 +63,8 @@ namespace Gecode { Branch::post_view_values_brancher<1, false>(home, xv, vs, std::move(bf), std::move(vvp)); break; default: - post_view_value_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), - std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.last_conflict(), std::move(bf), std::move(vvp)); break; } } @@ -63,6 +75,9 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + check_last_conflict_tie_break(vars, "Int::branch"); + if ((vars.a.last_conflict() > 0) && Branch::all_values(vals)) + throw UnsupportedLastConflict("Int::branch"); vars.a.expand(home, x); if ((vars.a.select() == IntVarBranch::SEL_NONE) || (vars.a.select() == IntVarBranch::SEL_RND)) vars.b = INT_VAR_NONE(); @@ -87,8 +102,8 @@ namespace Gecode { Branch::post_view_values_brancher<2, false>(home, xv, vs, std::move(bf), std::move(vvp)); break; default: - post_view_value_brancher( - home, xv, vs, Branch::value_selection_commit(home, vals), std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.a.last_conflict(), std::move(bf), std::move(vvp)); } } else if (vars.d.select() == IntVarBranch::SEL_NONE) { ViewSel* vs[3] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), @@ -101,8 +116,8 @@ namespace Gecode { Branch::post_view_values_brancher<3, false>(home, xv, vs, std::move(bf), std::move(vvp)); break; default: - post_view_value_brancher( - home, xv, vs, Branch::value_selection_commit(home, vals), std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.a.last_conflict(), std::move(bf), std::move(vvp)); } } else { ViewSel* vs[4] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), @@ -115,8 +130,8 @@ namespace Gecode { Branch::post_view_values_brancher<4, false>(home, xv, vs, std::move(bf), std::move(vvp)); break; default: - post_view_value_brancher( - home, xv, vs, Branch::value_selection_commit(home, vals), std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.a.last_conflict(), std::move(bf), std::move(vvp)); } } } @@ -135,6 +150,8 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Int::assign"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -148,6 +165,9 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.a.last_conflict() > 0) + throw UnsupportedLastConflict("Int::assign"); + check_last_conflict_tie_break(vars, "Int::assign"); vars.a.expand(home, x); if ((vars.a.select() == IntVarBranch::SEL_NONE) || (vars.a.select() == IntVarBranch::SEL_RND)) vars.b = INT_VAR_NONE(); @@ -196,8 +216,8 @@ namespace Gecode { vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; - post_view_value_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), - std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.last_conflict(), std::move(bf), std::move(vvp)); } void @@ -206,6 +226,7 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + check_last_conflict_tie_break(vars, "Int::branch"); vars.a.expand(home, x); if ((vars.a.select() == BoolVarBranch::SEL_NONE) || (vars.a.select() == BoolVarBranch::SEL_RND)) vars.b = BOOL_VAR_NONE(); @@ -223,15 +244,18 @@ namespace Gecode { ValSelCommitBase* vsc = Branch::value_selection_commit(home, vals); if (vars.c.select() == BoolVarBranch::SEL_NONE) { ViewSel* vs[2] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + std::move(vvp)); } else if (vars.d.select() == BoolVarBranch::SEL_NONE) { ViewSel* vs[3] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + std::move(vvp)); } else { ViewSel* vs[4] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c), Branch::view_selection(home, vars.d)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + std::move(vvp)); } } } @@ -249,6 +273,8 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Int::assign"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -262,6 +288,9 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.a.last_conflict() > 0) + throw UnsupportedLastConflict("Int::assign"); + check_last_conflict_tie_break(vars, "Int::assign"); vars.a.expand(home, x); if ((vars.a.select() == BoolVarBranch::SEL_NONE) || (vars.a.select() == BoolVarBranch::SEL_RND)) vars.b = BOOL_VAR_NONE(); diff --git a/gecode/int/branch.hh b/gecode/int/branch.hh index f51c7876f2..0153b2fac7 100644 --- a/gecode/int/branch.hh +++ b/gecode/int/branch.hh @@ -416,6 +416,50 @@ namespace Gecode::Int::Branch { int val(const Space& home, IntView x, int i); }; + /** + * \brief Value selection class for the stored solution value of a view + * + * Selects the stored value at the view's position when available and in + * the domain; otherwise delegates to \a Fallback. + * + * Requires \code #include \endcode + * \ingroup FuncIntValSel + */ + template + class ValSelSolution : public ValSel { + public: + using typename ValSel::Var; + + protected: + /// The stored solution values + IntSolutionValues sv; + /// The fallback value selection + Fallback fb; + + public: + /// Constructor for initialization + ValSelSolution(Space& home, const ValBranch& vb); + /// Constructor for cloning + ValSelSolution(Space& home, ValSelSolution& vs); + /// Split the random state of the fallback by \a a + void + random_split(unsigned int a) { + fb.random_split(a); + } + /// Whether the fallback has random state + bool + random() const { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.rand): a member random(), not the C library function + return fb.random(); + } + /// Return value of view \a x at position \a i + int val(const Space& home, View x, int i); + /// Whether dispose must always be called (that is, notice is needed) + bool notice() const; + /// Delete value selection + void dispose(Space& home); + }; + } // namespace Gecode::Int::Branch #include diff --git a/gecode/int/branch/open.hpp b/gecode/int/branch/open.hpp index 4e33dd416a..4ed78162c8 100644 --- a/gecode/int/branch/open.hpp +++ b/gecode/int/branch/open.hpp @@ -337,6 +337,9 @@ namespace Gecode::Int::Branch { post_open_brancher(Home home, OpenViewList list, const TieBreak& vars, const ValBranch& vals, BranchFilter bf, VarValPrint vvp) { VarBranch selectors[4] = {vars.a, vars.b, vars.c, vars.d}; + for (const VarBranch& s : selectors) + if (s.last_conflict() > 0) + throw UnsupportedLastConflict("Int::branch"); int n = 1; while ((n < 4) && (selectors[n - 1].select() != VarBranch::SEL_NONE) && (selectors[n - 1].select() != VarBranch::SEL_RND) && (selectors[n].select() != VarBranch::SEL_NONE)) diff --git a/gecode/int/branch/solution-values.cpp b/gecode/int/branch/solution-values.cpp new file mode 100644 index 0000000000..29b056882c --- /dev/null +++ b/gecode/int/branch/solution-values.cpp @@ -0,0 +1,76 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + // An empty value array allocates nothing (heap allocations must be positive) + IntSolutionValues::Storage::Storage(int n0) + : n(n0), filled(false), v(n0 > 0 ? heap.alloc>(n0) : nullptr) { + for (int i = 0; i < n; i++) + v[i].store(0, std::memory_order_relaxed); + } + + template + void + IntSolutionValues::Storage::update(const VarArgs& x, const char* l) { + if (x.size() != n) + throw Int::ArgumentSizeMismatch(l); + for (int i = 0; i < n; i++) + if (!x[i].assigned()) + throw Int::ValOfUnassignedVar(l); + Support::Lock lock(m); + for (int i = 0; i < n; i++) + v[i].store(x[i].val(), std::memory_order_relaxed); + filled.store(true, std::memory_order_release); + } + + IntSolutionValues::Storage::~Storage() { + heap.free>(v, n); + } + + IntSolutionValues::IntSolutionValues(int n) : SharedHandle(new Storage(n)) {} + + void + IntSolutionValues::update(const IntVarArgs& x) { + object().update(x, "IntSolutionValues::update"); + } + + void + IntSolutionValues::update(const BoolVarArgs& x) { + object().update(x, "IntSolutionValues::update"); + } + +} // namespace Gecode + +// STATISTICS: int-branch diff --git a/gecode/int/branch/solution-values.hpp b/gecode/int/branch/solution-values.hpp new file mode 100644 index 0000000000..6005907926 --- /dev/null +++ b/gecode/int/branch/solution-values.hpp @@ -0,0 +1,78 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +namespace Gecode { + + /// Object for storing solution values + class GECODE_VTABLE_EXPORT IntSolutionValues::Storage : public SharedHandle::Object { + public: + /// Mutex to serialize updates + Support::Mutex m; + /// Number of positions + int n; + /// Whether values have been stored, set after the values are stored + std::atomic filled; + /// Stored values + std::atomic* v; + /// Initialize for \a n positions with no stored values + Storage(int n); + /// Store the values of the assigned variables \a x + template + void update(const VarArgs& x, const char* l); + /// Delete object + GECODE_INT_EXPORT ~Storage() override; + }; + + forceinline IntSolutionValues::Storage& + IntSolutionValues::object() const { + return static_cast(*SharedHandle::object()); + } + + forceinline IntSolutionValues::IntSolutionValues() = default; + + forceinline bool + IntSolutionValues::empty() const { + return !object().filled.load(std::memory_order_acquire); + } + forceinline int + IntSolutionValues::size() const { + return object().n; + } + forceinline int + IntSolutionValues::operator[](int i) const { + assert((i >= 0) && (i < object().n)); + return object().v[i].load(std::memory_order_relaxed); + } + +} // namespace Gecode + +// STATISTICS: int-branch diff --git a/gecode/int/branch/val-sel-commit.cpp b/gecode/int/branch/val-sel-commit.cpp index 3a4809c025..f07db0c35b 100644 --- a/gecode/int/branch/val-sel-commit.cpp +++ b/gecode/int/branch/val-sel-commit.cpp @@ -60,6 +60,18 @@ namespace Gecode::Int::Branch { } else { return new (home) ValSelCommit, ValCommitFunction>(home, ivb); } + case IntValBranch::SEL_SOLUTION_MIN: + return new (home) + ValSelCommit>, ValCommitEq>(home, ivb); + case IntValBranch::SEL_SOLUTION_MED: + return new (home) + ValSelCommit>, ValCommitEq>(home, ivb); + case IntValBranch::SEL_SOLUTION_MAX: + return new (home) + ValSelCommit>, ValCommitEq>(home, ivb); + case IntValBranch::SEL_SOLUTION_RND: + return new (home) + ValSelCommit>, ValCommitEq>(home, ivb); default: throw UnknownBranching("Int::branch"); } @@ -102,6 +114,15 @@ namespace Gecode::Int::Branch { } else { return new (home) ValSelCommit, ValCommitFunction>(home, bvb); } + case BoolValBranch::SEL_SOLUTION_MIN: + return new (home) + ValSelCommit>, ValCommitEq>(home, bvb); + case BoolValBranch::SEL_SOLUTION_MAX: + return new (home) + ValSelCommit>, ValCommitEq>(home, bvb); + case BoolValBranch::SEL_SOLUTION_RND: + return new (home) + ValSelCommit>, ValCommitEq>(home, bvb); default: throw UnknownBranching("Int::branch"); } diff --git a/gecode/int/branch/val-sel.hpp b/gecode/int/branch/val-sel.hpp index ab64e3cd5b..8b0f8b64e7 100644 --- a/gecode/int/branch/val-sel.hpp +++ b/gecode/int/branch/val-sel.hpp @@ -155,6 +155,48 @@ namespace Gecode::Int::Branch { return min; } + /// Return the solution values of the integer value branching \a vb + forceinline const IntSolutionValues& + solution_values_of(const ValBranch& vb) { + return static_cast(vb).solution_values(); + } + /// Return the solution values of the Boolean value branching \a vb + forceinline const IntSolutionValues& + solution_values_of(const ValBranch& vb) { + return static_cast(vb).solution_values(); + } + + template + forceinline + ValSelSolution::ValSelSolution(Space& home, const ValBranch& vb) + : ValSel(home, vb), sv(solution_values_of(vb)), fb(home, vb) {} + template + forceinline + ValSelSolution::ValSelSolution(Space& home, ValSelSolution& vs) + : ValSel(home, vs), sv(vs.sv), fb(home, vs.fb) {} + template + forceinline int + ValSelSolution::val(const Space& home, View x, int i) { + if (!sv.empty() && (i < sv.size())) { + // Read the stored value once, as another thread may update it + int n = sv[i]; + if (x.in(n)) + return n; + } + return fb.val(home, x, i); + } + template + forceinline bool + ValSelSolution::notice() const { + return true; + } + template + forceinline void + ValSelSolution::dispose(Space& home) { + sv.~IntSolutionValues(); + fb.dispose(home); + } + } // namespace Gecode::Int::Branch // STATISTICS: int-branch diff --git a/gecode/int/branch/val.hpp b/gecode/int/branch/val.hpp index 6cb4b02cd0..392137e9ae 100644 --- a/gecode/int/branch/val.hpp +++ b/gecode/int/branch/val.hpp @@ -44,11 +44,38 @@ namespace Gecode { IntValBranch::IntValBranch(IntBranchVal v, IntBranchCommit c) : ValBranch(std::move(v), std::move(c)), s(SEL_VAL_COMMIT) {} + inline IntValBranch::IntValBranch(const IntSolutionValues& v, const IntValBranch& fallback) + : ValBranch(fallback), sv(v) { + if (!sv) + throw UninitializedSolutionValues("Int::INT_VAL_SOLUTION"); + switch (fallback.select()) { + case SEL_MIN: + s = SEL_SOLUTION_MIN; + break; + case SEL_MED: + s = SEL_SOLUTION_MED; + break; + case SEL_MAX: + s = SEL_SOLUTION_MAX; + break; + case SEL_RND: + s = SEL_SOLUTION_RND; + break; + default: + throw UnsupportedFallback("Int::INT_VAL_SOLUTION"); + } + } + forceinline IntValBranch::Select IntValBranch::select() const { return s; } + forceinline const IntSolutionValues& + IntValBranch::solution_values() const { + return sv; + } + inline IntValBranch INT_VAL_MIN() { return IntValBranch(IntValBranch::SEL_MIN); @@ -104,6 +131,11 @@ namespace Gecode { return IntValBranch(IntValBranch::SEL_VALUES_MAX); } + inline IntValBranch + INT_VAL_SOLUTION(const IntSolutionValues& v, const IntValBranch& fallback) { + return IntValBranch(v, fallback); + } + forceinline BoolValBranch::BoolValBranch(Select s0) : s(s0) {} @@ -116,11 +148,35 @@ namespace Gecode { BoolValBranch::BoolValBranch(BoolBranchVal v, BoolBranchCommit c) : ValBranch(std::move(v), std::move(c)), s(SEL_VAL_COMMIT) {} + inline BoolValBranch::BoolValBranch(const IntSolutionValues& v, const BoolValBranch& fallback) + : ValBranch(fallback), sv(v) { + if (!sv) + throw UninitializedSolutionValues("Int::BOOL_VAL_SOLUTION"); + switch (fallback.select()) { + case SEL_MIN: + s = SEL_SOLUTION_MIN; + break; + case SEL_MAX: + s = SEL_SOLUTION_MAX; + break; + case SEL_RND: + s = SEL_SOLUTION_RND; + break; + default: + throw UnsupportedFallback("Int::BOOL_VAL_SOLUTION"); + } + } + forceinline BoolValBranch::Select BoolValBranch::select() const { return s; } + forceinline const IntSolutionValues& + BoolValBranch::solution_values() const { + return sv; + } + inline BoolValBranch BOOL_VAL_MIN() { return BoolValBranch(BoolValBranch::SEL_MIN); @@ -141,6 +197,11 @@ namespace Gecode { return BoolValBranch(std::move(v), std::move(c)); } + inline BoolValBranch + BOOL_VAL_SOLUTION(const IntSolutionValues& v, const BoolValBranch& fallback) { + return BoolValBranch(v, fallback); + } + } // namespace Gecode // STATISTICS: int-branch diff --git a/gecode/int/branch/var.hpp b/gecode/int/branch/var.hpp index 19acf339cb..75dea3510a 100644 --- a/gecode/int/branch/var.hpp +++ b/gecode/int/branch/var.hpp @@ -309,6 +309,13 @@ namespace Gecode { return IntVarBranch(IntVarBranch::SEL_REGRET_MAX_MAX, std::move(tbl)); } + inline IntVarBranch + INT_VAR_LAST_CONFLICT(int k, const IntVarBranch& vars) { + IntVarBranch v(vars); + v.last_conflict(k); + return v; + } + forceinline BoolVarBranch::BoolVarBranch() : s(SEL_NONE) {} @@ -458,6 +465,13 @@ namespace Gecode { return BoolVarBranch(BoolVarBranch::SEL_CHB_MAX, std::move(tbl)); } + inline BoolVarBranch + BOOL_VAR_LAST_CONFLICT(int k, const BoolVarBranch& vars) { + BoolVarBranch v(vars); + v.last_conflict(k); + return v; + } + } // namespace Gecode // STATISTICS: int-branch diff --git a/gecode/int/ldsb.cpp b/gecode/int/ldsb.cpp index de6d21cd5d..2e3066d40a 100644 --- a/gecode/int/ldsb.cpp +++ b/gecode/int/ldsb.cpp @@ -291,6 +291,8 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Int::LDSB::branch"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -332,6 +334,9 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if ((vars.a.last_conflict() > 0) || (vars.b.last_conflict() > 0) || (vars.c.last_conflict() > 0) || + (vars.d.last_conflict() > 0)) + throw UnsupportedLastConflict("Int::LDSB::branch"); vars.a.expand(home, x); if ((vars.a.select() == IntVarBranch::SEL_NONE) || (vars.a.select() == IntVarBranch::SEL_RND)) vars.b = INT_VAR_NONE(); @@ -432,6 +437,8 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Int::LDSB::branch"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -470,6 +477,9 @@ namespace Gecode { using namespace Int; if (home.failed()) return; + if ((vars.a.last_conflict() > 0) || (vars.b.last_conflict() > 0) || (vars.c.last_conflict() > 0) || + (vars.d.last_conflict() > 0)) + throw UnsupportedLastConflict("Int::LDSB::branch"); vars.a.expand(home, x); if ((vars.a.select() == BoolVarBranch::SEL_NONE) || (vars.a.select() == BoolVarBranch::SEL_RND)) vars.b = BOOL_VAR_NONE(); diff --git a/gecode/kernel.hh b/gecode/kernel.hh index 9403df7da6..6fbf27d1f6 100644 --- a/gecode/kernel.hh +++ b/gecode/kernel.hh @@ -220,6 +220,7 @@ namespace Gecode { #include #include #include +#include /* * Automatically generated variable implementations diff --git a/gecode/kernel/branch/last-conflict.cpp b/gecode/kernel/branch/last-conflict.cpp new file mode 100644 index 0000000000..61cc449fa8 --- /dev/null +++ b/gecode/kernel/branch/last-conflict.cpp @@ -0,0 +1,63 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + ConflictSet::Storage::~Storage() { + heap.free>(pos, k); + } + + ConflictSet::ConflictSet(int k) : SharedHandle(new Storage(k)) {} + + void + ConflictSet::add(int p) const noexcept { + Storage& s = object(); + Support::Lock lock(s.m); + // Find p, the first empty entry, or else the least recent entry + int i = 0; + while (i < s.k - 1) { + const int q = s.pos[i].load(std::memory_order_relaxed); + if ((q == p) || (q < 0)) + break; + i++; + } + // Move the entries before i back by one and put p first + for (; i > 0; i--) + s.pos[i].store(s.pos[i - 1].load(std::memory_order_relaxed), std::memory_order_relaxed); + s.pos[0].store(p, std::memory_order_relaxed); + } + +} // namespace Gecode + +// STATISTICS: kernel-branch diff --git a/gecode/kernel/branch/last-conflict.hpp b/gecode/kernel/branch/last-conflict.hpp new file mode 100644 index 0000000000..c37617dabe --- /dev/null +++ b/gecode/kernel/branch/last-conflict.hpp @@ -0,0 +1,304 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include + +namespace Gecode { + + /** + * \defgroup TaskBranchLastConflict Last-conflict variable selection + * + * Branchers posted with a last-conflict variable selection (such as + * INT_VAR_LAST_CONFLICT) first select a view whose alternative failed + * recently and otherwise use the wrapped view selections. + * + * \ingroup TaskActor + */ + //@{ + /** + * \brief Conflict set of a brancher with last-conflict selection + * + * Holds up to \a k view positions whose alternatives failed most recently, + * most recent first. Copies share the set across a brancher, its clones in + * all threads, and its choices. + * + * Insertions take a lock; reads do not and may see a concurrent insertion + * partly done. + */ + class ConflictSet : public SharedHandle { + protected: + /// The shared positions + class GECODE_VTABLE_EXPORT Storage : public SharedHandle::Object { + public: + /// Mutex to serialize insertions + Support::Mutex m; + /// Maximal number of positions + int k; + /// Positions, most recent first, followed by -1 for each empty entry + std::atomic* pos; + /// Initialize as empty for at most \a k positions + Storage(int k); + /// Delete positions + GECODE_KERNEL_EXPORT ~Storage() override; + }; + /// Return the shared positions + Storage& object() const; + + public: + /// Initialize as empty for at most \a k positions + GECODE_KERNEL_EXPORT explicit ConflictSet(int k); + /// Return maximal number of positions + int size() const; + /// Return the \a i-th most recent position, or -1 if there is none + int operator[](int i) const; + /// Make \a p the most recent position + GECODE_KERNEL_EXPORT void add(int p) const noexcept; + }; + + /// %Choice that adds its position to a conflict set when an alternative fails + template + class GECODE_VTABLE_EXPORT LastConflictChoice : public PosValChoice { + private: + /// The conflict set + ConflictSet cs; + + public: + /// Initialize for brancher \a b, conflict set \a cs, position \a p, and value \a n + LastConflictChoice(const Brancher& b, const ConflictSet& cs, const Pos& p, const Val& n); + /// Add the position to the conflict set + void alternative_failed(unsigned int a) const noexcept override; + }; + + /** + * \brief %Brancher by view and value selection with last-conflict selection + * + * Selects the most recent unassigned view in the conflict set that passes + * the filter, or falls back to the view selections. Branches on the + * selected view as ViewValBrancher does. + */ + template + class LastConflictBrancher : public ViewValBrancher { + protected: + using ViewBrancher::x; + using ViewBrancher::start; + using ViewBrancher::f; + using ViewValBrancher::vsc; + /// The corresponding variable + using Var = View::VarType; + /// Shared conflict set + ConflictSet cs; + /// Return position of the most recent selectable view in the conflict set, or -1 + int conflict(const Space& home) const; + /// Constructor for cloning \a b + LastConflictBrancher(Space& home, LastConflictBrancher& b); + /// Constructor for creation + LastConflictBrancher(Home home, ViewArray& x, ViewSel* vs[n], ValSelCommitBase* vsc, + const ConflictSet& cs, BranchFilter bf, VarValPrint vvp); + + public: + /// Return choice + const Choice* choice(Space& home) override; + /// Return choice + const Choice* choice(const Space& home, Archive& e) override; + /// Perform cloning + Actor* copy(Space& home) override; + /// Delete brancher and return its size + size_t dispose(Space& home) override; + /// Post brancher with a new conflict set for at most \a k views + static void post(Home home, ViewArray& x, ViewSel* vs[n], ValSelCommitBase* vsc, int k, + BranchFilter bf, VarValPrint vvp); + }; + + /** + * \brief Post binary view-value brancher + * + * Uses last-conflict selection over at most \a k views if \a k > 0, and + * otherwise posts a ViewValBrancher. + */ + template + void post_binary_brancher(Home home, ViewArray& x, ViewSel* vs[n], ValSelCommitBase* vsc, + int k, BranchFilter bf, + VarValPrint vvp); + + /// Throw UnsupportedLastConflict at \a l if a selection after the first in \a vars uses last-conflict + template + void check_last_conflict_tie_break(const TieBreak& vars, const char* l); + //@} + + /* + * Conflict set + * + */ + forceinline + ConflictSet::Storage::Storage(int k0) + : k(k0), pos(heap.alloc>(k0)) { + for (int i = 0; i < k; i++) + pos[i].store(-1, std::memory_order_relaxed); + } + forceinline ConflictSet::Storage& + ConflictSet::object() const { + return static_cast(*SharedHandle::object()); + } + forceinline int + ConflictSet::size() const { + return object().k; + } + forceinline int + ConflictSet::operator[](int i) const { + assert((i >= 0) && (i < size())); + return object().pos[i].load(std::memory_order_relaxed); + } + + /* + * Choice adding its position to a conflict set + * + */ + template + forceinline + LastConflictChoice::LastConflictChoice(const Brancher& b, const ConflictSet& cs0, const Pos& p, const Val& n) + : PosValChoice(b, 2, p, n), cs(cs0) {} + + template + void + LastConflictChoice::alternative_failed(unsigned int) const noexcept { + cs.add(this->pos().pos); + } + + /* + * Brancher with last-conflict selection + * + */ + template + forceinline + LastConflictBrancher::LastConflictBrancher( + Home home, ViewArray& x, ViewSel* vs[n], ValSelCommitBase* vsc, const ConflictSet& cs0, + BranchFilter bf, VarValPrint vvp) + : ViewValBrancher(home, x, vs, vsc, std::move(bf), std::move(vvp)), cs(cs0) { + home.notice(*this, AP_DISPOSE, true); + } + + template + forceinline void + LastConflictBrancher::post(Home home, ViewArray& x, ViewSel* vs[n], + ValSelCommitBase* vsc, int k, + BranchFilter bf, VarValPrint vvp) { + ConflictSet cs(k); + (void)new (home) + LastConflictBrancher(home, x, vs, vsc, cs, std::move(bf), std::move(vvp)); + } + + template + forceinline + LastConflictBrancher::LastConflictBrancher(Space& home, LastConflictBrancher& b) + : ViewValBrancher(home, b), cs(b.cs) {} + + template + Actor* + LastConflictBrancher::copy(Space& home) { + return new (home) LastConflictBrancher(home, *this); + } + + template + forceinline int + LastConflictBrancher::conflict(const Space& home) const { + for (int i = 0; i < cs.size(); i++) { + const int j = cs[i]; + if (j < 0) + break; + // Views before start are assigned or rejected by the filter + if ((j >= start) && !x[j].assigned() && f(home, x[j], j)) + return j; + } + return -1; + } + + template + const Choice* + LastConflictBrancher::choice(Space& home) { + const int j = conflict(home); + const Pos p = (j >= 0) ? Pos(j) : ViewBrancher::pos(home); + return new LastConflictChoice(*this, cs, p, vsc->val(home, x[p.pos], p.pos)); + } + + template + const Choice* + LastConflictBrancher::choice(const Space&, Archive& e) { + int p; + e >> p; + Val v; + e >> v; + return new LastConflictChoice(*this, cs, p, v); + } + + template + size_t + LastConflictBrancher::dispose(Space& home) { + home.ignore(*this, AP_DISPOSE, true); + cs.~ConflictSet(); + (void)ViewValBrancher::dispose(home); + return sizeof(LastConflictBrancher); + } + + template + forceinline void + post_binary_brancher(Home home, ViewArray& x, ViewSel* vs[n], ValSelCommitBase* vsc, int k, + BranchFilter bf, VarValPrint vvp) { + if (k == 0) { + post_view_value_brancher(home, x, vs, vsc, std::move(bf), std::move(vvp)); + } else if (bf) { + if (vvp) + LastConflictBrancher, BrancherPrint>::post( + home, x, vs, vsc, k, std::move(bf), std::move(vvp)); + else + LastConflictBrancher, BrancherNoPrint>::post( + home, x, vs, vsc, k, std::move(bf), std::move(vvp)); + } else { + if (vvp) + LastConflictBrancher, BrancherPrint>::post( + home, x, vs, vsc, k, std::move(bf), std::move(vvp)); + else + LastConflictBrancher, BrancherNoPrint>::post( + home, x, vs, vsc, k, std::move(bf), std::move(vvp)); + } + } + + template + forceinline void + check_last_conflict_tie_break(const TieBreak& vars, const char* l) { + if ((vars.b.last_conflict() > 0) || (vars.c.last_conflict() > 0) || (vars.d.last_conflict() > 0)) + throw UnsupportedLastConflict(l); + } + +} // namespace Gecode + +// STATISTICS: kernel-branch diff --git a/gecode/kernel/branch/var.hpp b/gecode/kernel/branch/var.hpp index d6d2875544..d7c8d8a235 100644 --- a/gecode/kernel/branch/var.hpp +++ b/gecode/kernel/branch/var.hpp @@ -71,6 +71,8 @@ namespace Gecode { CHB _chb; /// Merit function MeritFunction _mf; + /// Conflict-set size of last-conflict selection, or 0 if not used + int _lc = 0; public: /// Initialize @@ -109,6 +111,10 @@ namespace Gecode { void chb(const CHB& chb); /// Return merit function MeritFunction merit() const; + /// Return conflict-set size of last-conflict selection, or 0 if not used + int last_conflict() const; + /// Use last-conflict selection with conflict-set size \a k + void last_conflict(int k); }; // Variable branching @@ -206,6 +212,20 @@ namespace Gecode { return _mf; } + template + inline int + VarBranch::last_conflict() const { + return _lc; + } + + template + inline void + VarBranch::last_conflict(int k) { + if (k < 1) + throw IllegalConflictSetSize("VarBranch::last_conflict"); + _lc = k; + } + } // namespace Gecode // STATISTICS: kernel-branch diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index 395840bcbd..fc1b9bc45e 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -968,6 +968,9 @@ namespace Gecode { e << id(); } + void + Choice::alternative_failed(unsigned int) const noexcept {} + bool NGL::notice() const { return false; diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 002a7c0874..37298880c5 100644 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1510,6 +1510,17 @@ namespace Gecode { /// Archive into \a e GECODE_KERNEL_EXPORT virtual void archive(Archive& e) const; + /** + * \brief Note that alternative \a a of this choice failed + * + * Called when the space fails after committing to \a a and + * propagating. The default does nothing; branchers that learn from + * failures override it. Must not throw; may be called concurrently + * from several threads. Whether and for which alternatives it is + * called depends on the search engine; not all engines call it. + */ + GECODE_KERNEL_EXPORT + virtual void alternative_failed(unsigned int a) const noexcept; }; /** diff --git a/gecode/kernel/exception.cpp b/gecode/kernel/exception.cpp index 97a7742c31..dfccc17260 100644 --- a/gecode/kernel/exception.cpp +++ b/gecode/kernel/exception.cpp @@ -75,6 +75,18 @@ namespace Gecode { MoreThanOneTracer::MoreThanOneTracer(const char* l) : Exception(l, "Attempt create more than one non-variable tracer") {} + IllegalConflictSetSize::IllegalConflictSetSize(const char* l) + : Exception(l, "Conflict-set size must be at least 1") {} + + UnsupportedLastConflict::UnsupportedLastConflict(const char* l) + : Exception(l, "Last-conflict variable selection not supported here") {} + + UninitializedSolutionValues::UninitializedSolutionValues(const char* l) + : Exception(l, "Attempt to use uninitialized solution values") {} + + UnsupportedFallback::UnsupportedFallback(const char* l) + : Exception(l, "Unsupported fallback for solution-guided value selection") {} + IllegalMetaDecision::IllegalMetaDecision(const char* l) : Exception(l, "Illegal decision for the event of a meta search hook") {} diff --git a/gecode/kernel/exception.hpp b/gecode/kernel/exception.hpp index 745613814a..58e1789a67 100644 --- a/gecode/kernel/exception.hpp +++ b/gecode/kernel/exception.hpp @@ -165,6 +165,34 @@ namespace Gecode { MoreThanOneTracer(const char* l); }; + /// %Exception: illegal conflict-set size for last-conflict selection + class GECODE_KERNEL_EXPORT IllegalConflictSetSize : public Exception { + public: + /// Initialize with location \a l + IllegalConflictSetSize(const char* l); + }; + + /// %Exception: last-conflict selection not supported where requested + class GECODE_KERNEL_EXPORT UnsupportedLastConflict : public Exception { + public: + /// Initialize with location \a l + UnsupportedLastConflict(const char* l); + }; + + /// %Exception: uninitialized solution values for solution-guided value selection + class GECODE_KERNEL_EXPORT UninitializedSolutionValues : public Exception { + public: + /// Initialize with location \a l + UninitializedSolutionValues(const char* l); + }; + + /// %Exception: fallback not supported by solution-guided value selection + class GECODE_KERNEL_EXPORT UnsupportedFallback : public Exception { + public: + /// Initialize with location \a l + UnsupportedFallback(const char* l); + }; + /// %Exception: illegal decision of a meta search hook (see MetaDecision) class GECODE_KERNEL_EXPORT IllegalMetaDecision : public Exception { public: diff --git a/gecode/search.hh b/gecode/search.hh index 19367f6cb1..79a760e48e 100644 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1453,6 +1453,8 @@ namespace Gecode { * the limit in Search::Options::d_l, end_reason() returns * Search::EndReason::Incomplete once the search ends. * + * The engine does not call Choice::alternative_failed(). + * * \ingroup TaskModelSearch */ template diff --git a/gecode/search/par/bab.hpp b/gecode/search/par/bab.hpp index 71a7bf27bc..4134a55c0c 100644 --- a/gecode/search/par/bab.hpp +++ b/gecode/search/par/bab.hpp @@ -347,6 +347,9 @@ namespace Gecode::Search::Par { SearchTracer::NodeInfo ni(SearchTracer::NodeType::FAILED, tracer.wid(), nid, *cur); tracer.node(ei, ni); } + // A stolen alternative leaves the path empty and is not reported + if (path.entries() > 0) + path.top().choice()->alternative_failed(path.top().true_alternative()); fail++; delete cur; cur = nullptr; diff --git a/gecode/search/par/dfs.hpp b/gecode/search/par/dfs.hpp index 2392aae459..69eb6befcd 100644 --- a/gecode/search/par/dfs.hpp +++ b/gecode/search/par/dfs.hpp @@ -245,6 +245,9 @@ namespace Gecode::Search::Par { SearchTracer::NodeInfo ni(SearchTracer::NodeType::FAILED, tracer.wid(), nid, *cur); tracer.node(ei, ni); } + // A stolen alternative leaves the path empty and is not reported + if (path.entries() > 0) + path.top().choice()->alternative_failed(path.top().true_alternative()); fail++; delete cur; cur = nullptr; diff --git a/gecode/search/par/path.hpp b/gecode/search/par/path.hpp index 7094cbfc04..aaa211a3b1 100644 --- a/gecode/search/par/path.hpp +++ b/gecode/search/par/path.hpp @@ -78,7 +78,8 @@ namespace Gecode::Search::Par { template forceinline unsigned int Path::Edge::true_alternative() const { - return std::min(_alt, _choice->alternatives() - 1); + // After stealing, LAO may move past a last alternative below alternatives() - 1 + return std::min(_alt, _alt_max); } template forceinline bool diff --git a/gecode/search/seq/bab.hpp b/gecode/search/seq/bab.hpp index 1bbb9fd24f..dc6eaef5ad 100644 --- a/gecode/search/seq/bab.hpp +++ b/gecode/search/seq/bab.hpp @@ -104,6 +104,8 @@ namespace Gecode::Search::Seq { SearchTracer::NodeInfo ni(SearchTracer::NodeType::FAILED, tracer.wid(), nid, *cur); tracer.node(ei, ni); } + if (path.entries() > 0) + path.top().choice()->alternative_failed(path.top().true_alternative()); fail++; delete cur; cur = nullptr; diff --git a/gecode/search/seq/choice-expansion.hh b/gecode/search/seq/choice-expansion.hh index 44485f7322..eabda668c5 100644 --- a/gecode/search/seq/choice-expansion.hh +++ b/gecode/search/seq/choice-expansion.hh @@ -139,6 +139,8 @@ namespace Gecode::Search::Seq { worker.node++; worker.stack_depth(depth); SpaceStatus status = child->status(worker); + if (status == SS_FAILED) + c->alternative_failed(alternative); alternative++; return {ExpansionStep::CHILD, std::move(child), status}; } diff --git a/gecode/search/seq/dfs.hpp b/gecode/search/seq/dfs.hpp index 3c4480ae08..70f61522f6 100644 --- a/gecode/search/seq/dfs.hpp +++ b/gecode/search/seq/dfs.hpp @@ -118,6 +118,8 @@ namespace Gecode::Search::Seq { SearchTracer::NodeInfo ni(SearchTracer::NodeType::FAILED, tracer.wid(), nid, *cur); tracer.node(ei, ni); } + if (path.entries() > 0) + path.top().choice()->alternative_failed(path.top().true_alternative()); fail++; delete cur; cur = nullptr; diff --git a/gecode/set.hh b/gecode/set.hh index 6201357be2..9cdccaac36 100644 --- a/gecode/set.hh +++ b/gecode/set.hh @@ -1345,12 +1345,64 @@ namespace Gecode { SetVarBranch SET_VAR_CHB_SIZE_MAX(BranchTbl tbl = nullptr); /// Select variable with largest CHB Q-score divided by domain size SetVarBranch SET_VAR_CHB_SIZE_MAX(const SetCHB& c, BranchTbl tbl = nullptr); + /** + * \brief Select the variable that failed most recently, otherwise as + * \a vars + * + * As INT_VAR_LAST_CONFLICT, with any set value selection. + */ + SetVarBranch SET_VAR_LAST_CONFLICT(int k, const SetVarBranch& vars); //@} } // namespace Gecode #include +namespace Gecode { + + /** + * \brief Stored solution sets for solution-guided value selection + * + * Holds one set per variable position for SET_VAL_SOLUTION. Empty until + * update() stores sets, typically from a solution, and updated as + * IntSolutionValues is. + * + * Copies share the stored sets across clones and threads. Updates and + * reads take a lock. + * + * \ingroup TaskModelSetBranch + */ + class SetSolutionValues : public SharedHandle { + protected: + class Storage; + /// Return object of correct type + Storage& object() const; + + public: + /// Construct as not yet initialized; only assignment may be used + SetSolutionValues(); + /// Create handle for \a n positions with no stored sets + GECODE_SET_EXPORT explicit SetSolutionValues(int n); + /** + * \brief Store the greatest lower bounds of \a x + * + * For assigned variables, these are their values. Throws + * Set::ArgumentSizeMismatch if sizes differ, leaving stored sets + * unchanged. + */ + GECODE_SET_EXPORT void update(const SetVarArgs& x); + /// Whether no sets have been stored yet + bool empty() const; + /// Return number of positions + int size() const; + /// Return stored set at position \a i + GECODE_SET_EXPORT IntSet operator[](int i) const; + }; + +} // namespace Gecode + +#include + namespace Gecode { /** @@ -1362,21 +1414,31 @@ namespace Gecode { public: /// Which value selection enum class Select { - SEL_MIN_INC, ///< Include smallest element - SEL_MIN_EXC, ///< Exclude smallest element - SEL_MED_INC, ///< Include median element (rounding downwards) - SEL_MED_EXC, ///< Exclude median element (rounding downwards) - SEL_MAX_INC, ///< Include largest element - SEL_MAX_EXC, ///< Exclude largest element - SEL_RND_INC, ///< Include random element - SEL_RND_EXC, ///< Exclude random element - SEL_VAL_COMMIT ///< Select value according to user-defined functions + SEL_MIN_INC, ///< Include smallest element + SEL_MIN_EXC, ///< Exclude smallest element + SEL_MED_INC, ///< Include median element (rounding downwards) + SEL_MED_EXC, ///< Exclude median element (rounding downwards) + SEL_MAX_INC, ///< Include largest element + SEL_MAX_EXC, ///< Exclude largest element + SEL_RND_INC, ///< Include random element + SEL_RND_EXC, ///< Exclude random element + SEL_VAL_COMMIT, ///< Select value according to user-defined functions + SEL_SOLUTION_MIN_INC, ///< Follow stored solution set, otherwise include smallest element + SEL_SOLUTION_MIN_EXC, ///< Follow stored solution set, otherwise exclude smallest element + SEL_SOLUTION_MED_INC, ///< Follow stored solution set, otherwise include median element + SEL_SOLUTION_MED_EXC, ///< Follow stored solution set, otherwise exclude median element + SEL_SOLUTION_MAX_INC, ///< Follow stored solution set, otherwise include largest element + SEL_SOLUTION_MAX_EXC, ///< Follow stored solution set, otherwise exclude largest element + SEL_SOLUTION_RND_INC, ///< Follow stored solution set, otherwise include random element + SEL_SOLUTION_RND_EXC ///< Follow stored solution set, otherwise exclude random element }; using enum Select; protected: /// Which value to select Select s; + /// Stored solution sets (only for solution-guided selection) + SetSolutionValues sv; public: /// Initialize with selection strategy \a s @@ -1385,8 +1447,12 @@ namespace Gecode { SetValBranch(Select s, const Rnd& r); /// Initialize with value function \a f and commit function \a c SetValBranch(SetBranchVal v, SetBranchCommit c); + /// Initialize with solution sets \a v and \a fallback (see SET_VAL_SOLUTION) + SetValBranch(const SetSolutionValues& v, const SetValBranch& fallback); /// Return selection strategy Select select() const; + /// Return stored solution sets (uninitialized if not solution-guided) + const SetSolutionValues& solution_values() const; }; /** @@ -1418,6 +1484,23 @@ namespace Gecode { * and that \a n must be excluded from \a x otherwise. */ SetValBranch SET_VAL(SetBranchVal v, SetBranchCommit c = nullptr); + /** + * \brief Follow the set stored in \a v, otherwise as \a fallback + * + * Includes first the smallest undecided element of the set stored at the + * variable's position \a i in \a v. If no undecided element is in that + * set, excludes first the smallest undecided element. Falls back to + * \a fallback when \a v is empty or \a i is at least v.size(). Choices + * record their element, so later updates to \a v affect neither + * recomputation nor no-goods. Print functions receive the element, with + * alternative 0 for including it and 1 for excluding it. + * + * \a fallback must be one of SET_VAL_MIN_INC to SET_VAL_RND_EXC; others + * throw UnsupportedFallback. An uninitialized \a v throws + * UninitializedSolutionValues. Symmetry breaking with LDSB throws + * Int::LDSBBadValueSelection. + */ + SetValBranch SET_VAL_SOLUTION(const SetSolutionValues& v, const SetValBranch& fallback = SET_VAL_MIN_INC()); //@} } // namespace Gecode diff --git a/gecode/set/branch.cpp b/gecode/set/branch.cpp index ce908504f0..55ee7eb3ef 100644 --- a/gecode/set/branch.cpp +++ b/gecode/set/branch.cpp @@ -34,6 +34,23 @@ namespace Gecode { + namespace { + + /// Return \a vvp for \a vals, decoding solution-guided values first + SetVarValPrint + value_print(const SetValBranch& vals, SetVarValPrint vvp) { + using namespace Set::Branch; + if (!solution_guided(vals) || !vvp) + return vvp; + return [vvp = std::move(vvp)](const Space& home, const Brancher& b, unsigned int a, SetVar x, int i, + const int& n, std::ostream& o) { + const bool include = ((a == 0) == solution_includes_first(n)); + vvp(home, b, include ? 0U : 1U, x, i, solution_element(n), o); + }; + } + + } // namespace + void branch(Home home, const SetVarArgs& x, SetVarBranch vars, const SetValBranch& vals, SetBranchFilter bf, SetVarValPrint vvp) { @@ -43,8 +60,8 @@ namespace Gecode { vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; - post_view_value_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), - std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, Branch::value_selection_commit(home, vals), + vars.last_conflict(), std::move(bf), value_print(vals, std::move(vvp))); } void @@ -53,6 +70,7 @@ namespace Gecode { using namespace Set; if (home.failed()) return; + check_last_conflict_tie_break(vars, "Set::branch"); vars.a.expand(home, x); if ((vars.a.select() == SetVarBranch::SEL_NONE) || (vars.a.select() == SetVarBranch::SEL_RND)) vars.b = SET_VAR_NONE(); @@ -70,15 +88,18 @@ namespace Gecode { ValSelCommitBase* vsc = Branch::value_selection_commit(home, vals); if (vars.c.select() == SetVarBranch::SEL_NONE) { ViewSel* vs[2] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + value_print(vals, std::move(vvp))); } else if (vars.d.select() == SetVarBranch::SEL_NONE) { ViewSel* vs[3] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + value_print(vals, std::move(vvp))); } else { ViewSel* vs[4] = {Branch::view_selection(home, vars.a), Branch::view_selection(home, vars.b), Branch::view_selection(home, vars.c), Branch::view_selection(home, vars.d)}; - post_view_value_brancher(home, xv, vs, vsc, std::move(bf), std::move(vvp)); + post_binary_brancher(home, xv, vs, vsc, vars.a.last_conflict(), std::move(bf), + value_print(vals, std::move(vvp))); } } } @@ -96,6 +117,8 @@ namespace Gecode { using namespace Set; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Set::assign"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -109,6 +132,9 @@ namespace Gecode { using namespace Set; if (home.failed()) return; + if (vars.a.last_conflict() > 0) + throw UnsupportedLastConflict("Set::assign"); + check_last_conflict_tie_break(vars, "Set::assign"); vars.a.expand(home, x); if ((vars.a.select() == SetVarBranch::SEL_NONE) || (vars.a.select() == SetVarBranch::SEL_RND)) vars.b = SET_VAR_NONE(); diff --git a/gecode/set/branch.hh b/gecode/set/branch.hh index a209f33960..91a075e5d5 100644 --- a/gecode/set/branch.hh +++ b/gecode/set/branch.hh @@ -302,6 +302,69 @@ namespace Gecode::Set::Branch { void dispose(Space& home); }; + /** + * \name Values of solution-guided value selection + * + * A value holds an element and whether to include or exclude it first. + */ + //@{ + /// Return value for including element \a n first + int solution_include(int n); + /// Return value for excluding element \a n first + int solution_exclude(int n); + /// Return the element of value \a v + int solution_element(int v); + /// Whether value \a v includes its element first + bool solution_includes_first(int v); + //@} + + /// Whether \a vals is a solution-guided value selection + bool solution_guided(const SetValBranch& vals); + + /// Which alternative to try first for an element selected by the fallback + enum class Fallback { Include, Exclude }; + + /** + * \brief Value selection class following the stored solution set of a view + * + * Returns a value as encoded by solution_include() or solution_exclude(). + * Uses \a FallbackSel and \a first when no set is stored. + * + * Requires \code #include \endcode + * \ingroup FuncSetValSel + */ + template + class ValSelSolution : public ValSel { + protected: + /// The stored solution sets + SetSolutionValues sv; + /// The fallback value selection + FallbackSel fb; + + public: + /// Split the random state of the fallback by \a a + void + random_split(unsigned int a) { + fb.random_split(a); + } + /// Whether the fallback has random state + bool + random() const { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.rand): a member random(), not the C library function + return fb.random(); + } + /// Constructor for initialization + ValSelSolution(Space& home, const ValBranch& vb); + /// Constructor for cloning + ValSelSolution(Space& home, ValSelSolution& vs); + /// Return value of view \a x at position \a i + int val(const Space& home, SetView x, int i); + /// Whether dispose must always be called (that is, notice is needed) + bool notice() const; + /// Delete value selection + void dispose(Space& home); + }; + } // namespace Gecode::Set::Branch #include @@ -402,6 +465,28 @@ namespace Gecode::Set::Branch { void print(const Space& home, unsigned int a, SetView x, int i, int n, std::ostream& o) const; }; + /** + * \brief Value commit class for solution-guided value selection + * + * Includes or excludes the element of the value first, as the value says. + * + * Requires \code #include \endcode + * \ingroup FuncSetValCommit + */ + class ValCommitSolution : public ValCommit { + public: + /// Constructor for initialization + ValCommitSolution(Space& home, const ValBranch& vb); + /// Constructor for cloning + ValCommitSolution(Space& home, ValCommitSolution& vc); + /// Commit view \a x at position \a i to value \a n for alternative \a a + ModEvent commit(Space& home, unsigned int a, SetView x, int i, int n); + /// Create no-good literal for alternative \a a + NGL* ngl(Space& home, unsigned int a, View x, int n) const; + /// Print on \a o the alternative \a with view \a x at position \a i and value \a n + void print(const Space& home, unsigned int a, SetView x, int i, int n, std::ostream& o) const; + }; + } // namespace Gecode::Set::Branch #include diff --git a/gecode/set/branch/solution-values.cpp b/gecode/set/branch/solution-values.cpp new file mode 100644 index 0000000000..f3577602ba --- /dev/null +++ b/gecode/set/branch/solution-values.cpp @@ -0,0 +1,82 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + // An empty set array allocates nothing (heap allocations must be positive) + SetSolutionValues::Storage::Storage(int n0) : n(n0), filled(false), s(n0 > 0 ? heap.alloc(n0) : nullptr) {} + + SetSolutionValues::Storage::~Storage() { + heap.free(s, n); + } + + SetSolutionValues::SetSolutionValues(int n) : SharedHandle(new Storage(n)) {} + + void + SetSolutionValues::update(const SetVarArgs& x) { + Storage& o = object(); + if (x.size() != o.n) + throw Set::ArgumentSizeMismatch("SetSolutionValues::update"); + // Build the sets first, so a failed allocation changes nothing + Region r; + IntSet* t = r.alloc(o.n); + try { + for (int i = 0; i < o.n; i++) { + SetVarGlbRanges g(x[i]); + t[i] = IntSet(g); + } + } catch (...) { + r.free(t, o.n); + throw; + } + { + Support::Lock lock(o.m); + for (int i = 0; i < o.n; i++) + o.s[i] = t[i]; + o.filled.store(true, std::memory_order_release); + } + r.free(t, o.n); + } + + IntSet + SetSolutionValues::operator[](int i) const { + Storage& o = object(); + assert((i >= 0) && (i < o.n)); + Support::Lock lock(o.m); + return o.s[i]; + } + +} // namespace Gecode + +// STATISTICS: set-branch diff --git a/gecode/set/branch/solution-values.hpp b/gecode/set/branch/solution-values.hpp new file mode 100644 index 0000000000..c66f2db30c --- /dev/null +++ b/gecode/set/branch/solution-values.hpp @@ -0,0 +1,72 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include + +namespace Gecode { + + /// Object for storing solution sets + class GECODE_VTABLE_EXPORT SetSolutionValues::Storage : public SharedHandle::Object { + public: + /// Mutex to serialize updates and reads + Support::Mutex m; + /// Number of positions + int n; + /// Whether sets have been stored, set after the sets are stored + std::atomic filled; + /// Stored sets + IntSet* s; + /// Initialize for \a n positions with no stored sets + Storage(int n); + /// Delete object + GECODE_SET_EXPORT ~Storage() override; + }; + + forceinline SetSolutionValues::Storage& + SetSolutionValues::object() const { + return static_cast(*SharedHandle::object()); + } + + forceinline SetSolutionValues::SetSolutionValues() = default; + + forceinline bool + SetSolutionValues::empty() const { + return !object().filled.load(std::memory_order_acquire); + } + forceinline int + SetSolutionValues::size() const { + return object().n; + } + +} // namespace Gecode + +// STATISTICS: set-branch diff --git a/gecode/set/branch/val-commit.hpp b/gecode/set/branch/val-commit.hpp index 70b8b708ca..2433d91887 100644 --- a/gecode/set/branch/val-commit.hpp +++ b/gecode/set/branch/val-commit.hpp @@ -80,6 +80,32 @@ namespace Gecode::Set::Branch { o << "var[" << i << "]." << ((a == 0) ? "exclude" : "include") << "(" << n << ")"; } + forceinline + ValCommitSolution::ValCommitSolution(Space& home, const ValBranch& vb) + : ValCommit(home, vb) {} + forceinline + ValCommitSolution::ValCommitSolution(Space& home, ValCommitSolution& vc) + : ValCommit(home, vc) {} + forceinline ModEvent + ValCommitSolution::commit(Space& home, unsigned int a, SetView x, int, int n) { + const int e = solution_element(n); + return ((a == 0) == solution_includes_first(n)) ? x.include(home, e) : x.exclude(home, e); + } + forceinline NGL* + ValCommitSolution::ngl(Space& home, unsigned int a, SetView x, int n) const { + if (a != 0) + return nullptr; + const int e = solution_element(n); + if (solution_includes_first(n)) + return new (home) IncNGL(home, x, e); + return new (home) ExcNGL(home, x, e); + } + forceinline void + ValCommitSolution::print(const Space&, unsigned int a, SetView, int i, int n, std::ostream& o) const { + const bool include = ((a == 0) == solution_includes_first(n)); + o << "var[" << i << "]." << (include ? "include" : "exclude") << "(" << solution_element(n) << ")"; + } + } // namespace Gecode::Set::Branch // STATISTICS: set-branch diff --git a/gecode/set/branch/val-sel-commit.cpp b/gecode/set/branch/val-sel-commit.cpp index c225a6ae13..ec59729caf 100644 --- a/gecode/set/branch/val-sel-commit.cpp +++ b/gecode/set/branch/val-sel-commit.cpp @@ -59,6 +59,22 @@ namespace Gecode::Set::Branch { } else { return new (home) ValSelCommit, ValCommitFunction>(home, svb); } + case SetValBranch::SEL_SOLUTION_MIN_INC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_MIN_EXC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_MED_INC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_MED_EXC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_MAX_INC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_MAX_EXC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_RND_INC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); + case SetValBranch::SEL_SOLUTION_RND_EXC: + return new (home) ValSelCommit, ValCommitSolution>(home, svb); default: throw UnknownBranching("Set::branch"); } diff --git a/gecode/set/branch/val-sel.hpp b/gecode/set/branch/val-sel.hpp index 105f8d2301..6de2b511b2 100644 --- a/gecode/set/branch/val-sel.hpp +++ b/gecode/set/branch/val-sel.hpp @@ -116,6 +116,78 @@ namespace Gecode::Set::Branch { r.~Rnd(); } + // Elements are within Set::Limits, so 2n + 1 does not overflow + forceinline int + solution_include(int n) { + return 2 * n; + } + forceinline int + solution_exclude(int n) { + return (2 * n) + 1; + } + forceinline int + solution_element(int v) { + return v >> 1; + } + forceinline bool + solution_includes_first(int v) { + return (v & 1) == 0; + } + + forceinline bool + solution_guided(const SetValBranch& vals) { + switch (vals.select()) { + case SetValBranch::SEL_SOLUTION_MIN_INC: + case SetValBranch::SEL_SOLUTION_MIN_EXC: + case SetValBranch::SEL_SOLUTION_MED_INC: + case SetValBranch::SEL_SOLUTION_MED_EXC: + case SetValBranch::SEL_SOLUTION_MAX_INC: + case SetValBranch::SEL_SOLUTION_MAX_EXC: + case SetValBranch::SEL_SOLUTION_RND_INC: + case SetValBranch::SEL_SOLUTION_RND_EXC: + return true; + default: + return false; + } + } + + template + forceinline + ValSelSolution::ValSelSolution(Space& home, const ValBranch& vb) + : ValSel(home, vb), sv(static_cast(vb).solution_values()), fb(home, vb) {} + template + forceinline + ValSelSolution::ValSelSolution(Space& home, ValSelSolution& vs) + : ValSel(home, vs), sv(vs.sv), fb(home, vs.fb) {} + template + forceinline int + ValSelSolution::val(const Space& home, SetView x, int i) { + if (!sv.empty() && (i < sv.size())) { + // Copy the stored set once, as another thread may update it + IntSet s = sv[i]; + UnknownRanges u(x); + IntSetRanges r(s); + Iter::Ranges::Inter, IntSetRanges> in(u, r); + if (in()) + return solution_include(in.min()); + UnknownRanges v(x); + return solution_exclude(v.min()); + } + const int n = fb.val(home, x, i); + return (first == Fallback::Include) ? solution_include(n) : solution_exclude(n); + } + template + forceinline bool + ValSelSolution::notice() const { + return true; + } + template + forceinline void + ValSelSolution::dispose(Space& home) { + sv.~SetSolutionValues(); + fb.dispose(home); + } + } // namespace Gecode::Set::Branch // STATISTICS: set-branch diff --git a/gecode/set/branch/val.hpp b/gecode/set/branch/val.hpp index 553765a90a..f70a1b228b 100644 --- a/gecode/set/branch/val.hpp +++ b/gecode/set/branch/val.hpp @@ -44,11 +44,50 @@ namespace Gecode { SetValBranch::SetValBranch(SetBranchVal v, SetBranchCommit c) : ValBranch(std::move(v), std::move(c)), s(SEL_VAL_COMMIT) {} + inline SetValBranch::SetValBranch(const SetSolutionValues& v, const SetValBranch& fallback) + : ValBranch(fallback), sv(v) { + if (!sv) + throw UninitializedSolutionValues("Set::SET_VAL_SOLUTION"); + switch (fallback.select()) { + case SEL_MIN_INC: + s = SEL_SOLUTION_MIN_INC; + break; + case SEL_MIN_EXC: + s = SEL_SOLUTION_MIN_EXC; + break; + case SEL_MED_INC: + s = SEL_SOLUTION_MED_INC; + break; + case SEL_MED_EXC: + s = SEL_SOLUTION_MED_EXC; + break; + case SEL_MAX_INC: + s = SEL_SOLUTION_MAX_INC; + break; + case SEL_MAX_EXC: + s = SEL_SOLUTION_MAX_EXC; + break; + case SEL_RND_INC: + s = SEL_SOLUTION_RND_INC; + break; + case SEL_RND_EXC: + s = SEL_SOLUTION_RND_EXC; + break; + default: + throw UnsupportedFallback("Set::SET_VAL_SOLUTION"); + } + } + forceinline SetValBranch::Select SetValBranch::select() const { return s; } + forceinline const SetSolutionValues& + SetValBranch::solution_values() const { + return sv; + } + inline SetValBranch SET_VAL_MIN_INC() { return SetValBranch(SetValBranch::SEL_MIN_INC); @@ -94,6 +133,11 @@ namespace Gecode { return SetValBranch(std::move(v), std::move(c)); } + inline SetValBranch + SET_VAL_SOLUTION(const SetSolutionValues& v, const SetValBranch& fallback) { + return SetValBranch(v, fallback); + } + } // namespace Gecode // STATISTICS: set-branch diff --git a/gecode/set/branch/var.hpp b/gecode/set/branch/var.hpp index 8300b1cd3f..3ccf80548f 100644 --- a/gecode/set/branch/var.hpp +++ b/gecode/set/branch/var.hpp @@ -289,6 +289,13 @@ namespace Gecode { return SetVarBranch(SetVarBranch::SEL_CHB_SIZE_MAX, c, std::move(tbl)); } + inline SetVarBranch + SET_VAR_LAST_CONFLICT(int k, const SetVarBranch& vars) { + SetVarBranch v(vars); + v.last_conflict(k); + return v; + } + } // namespace Gecode // STATISTICS: set-branch diff --git a/gecode/set/ldsb.cpp b/gecode/set/ldsb.cpp index dfd4f750f2..168fc1b449 100644 --- a/gecode/set/ldsb.cpp +++ b/gecode/set/ldsb.cpp @@ -154,6 +154,10 @@ namespace Gecode { using namespace Set; if (home.failed()) return; + if (vars.last_conflict() > 0) + throw UnsupportedLastConflict("Set::LDSB::branch"); + if (Branch::solution_guided(vals)) + throw Int::LDSBBadValueSelection("Set::LDSB::branch"); vars.expand(home, x); ViewArray xv(home, x); ViewSel* vs[1] = {Branch::view_selection(home, vars)}; @@ -179,6 +183,11 @@ namespace Gecode { using namespace Set; if (home.failed()) return; + if ((vars.a.last_conflict() > 0) || (vars.b.last_conflict() > 0) || (vars.c.last_conflict() > 0) || + (vars.d.last_conflict() > 0)) + throw UnsupportedLastConflict("Set::LDSB::branch"); + if (Branch::solution_guided(vals)) + throw Int::LDSBBadValueSelection("Set::LDSB::branch"); vars.a.expand(home, x); if ((vars.a.select() == SetVarBranch::SEL_NONE) || (vars.a.select() == SetVarBranch::SEL_RND)) vars.b = SET_VAR_NONE(); diff --git a/test/branch.cpp b/test/branch.cpp index 537f323559..34d3c9d544 100644 --- a/test/branch.cpp +++ b/test/branch.cpp @@ -149,22 +149,46 @@ namespace Test::Branch { */ //@{ /// Names for integer variable selections - const char* int_var_branch_name[] = { - "SINGLE VARIABLE", "INT_VAR_NONE", "INT_VAR_RND", "INT_VAR_MERIT_MIN", - "INT_VAR_MERIT_MAX", "INT_VAR_DEGREE_MIN", "INT_VAR_DEGREE_MAX", "INT_VAR_AFC_MIN", - "INT_VAR_AFC_MAX", "INT_VAR_ACTION_MIN", "INT_VAR_ACTION_MAX", "INT_VAR_CHB_MIN", - "INT_VAR_CHB_MAX", "INT_VAR_MIN_MIN", "INT_VAR_MIN_MAX", "INT_VAR_MAX_MIN", - "INT_VAR_MAX_MAX", "INT_VAR_SIZE_MIN", "INT_VAR_SIZE_MAX", "INT_VAR_DEGREE_SIZE_MIN", - "INT_VAR_DEGREE_SIZE_MAX", "INT_VAR_AFC_SIZE_MIN", "INT_VAR_AFC_SIZE_MAX", "INT_VAR_ACTION_SIZE_MIN", - "INT_VAR_ACTION_SIZE_MAX", "INT_VAR_CHB_SIZE_MIN", "INT_VAR_CHB_SIZE_MAX", "INT_VAR_REGRET_MIN_MIN", - "INT_VAR_REGRET_MIN_MAX", "INT_VAR_REGRET_MAX_MIN", "INT_VAR_REGRET_MAX_MAX"}; + const char* int_var_branch_name[] = {"SINGLE VARIABLE", + "INT_VAR_NONE", + "INT_VAR_RND", + "INT_VAR_MERIT_MIN", + "INT_VAR_MERIT_MAX", + "INT_VAR_DEGREE_MIN", + "INT_VAR_DEGREE_MAX", + "INT_VAR_AFC_MIN", + "INT_VAR_AFC_MAX", + "INT_VAR_ACTION_MIN", + "INT_VAR_ACTION_MAX", + "INT_VAR_CHB_MIN", + "INT_VAR_CHB_MAX", + "INT_VAR_MIN_MIN", + "INT_VAR_MIN_MAX", + "INT_VAR_MAX_MIN", + "INT_VAR_MAX_MAX", + "INT_VAR_SIZE_MIN", + "INT_VAR_SIZE_MAX", + "INT_VAR_DEGREE_SIZE_MIN", + "INT_VAR_DEGREE_SIZE_MAX", + "INT_VAR_AFC_SIZE_MIN", + "INT_VAR_AFC_SIZE_MAX", + "INT_VAR_ACTION_SIZE_MIN", + "INT_VAR_ACTION_SIZE_MAX", + "INT_VAR_CHB_SIZE_MIN", + "INT_VAR_CHB_SIZE_MAX", + "INT_VAR_REGRET_MIN_MIN", + "INT_VAR_REGRET_MIN_MAX", + "INT_VAR_REGRET_MAX_MIN", + "INT_VAR_REGRET_MAX_MAX", + "INT_VAR_LAST_CONFLICT"}; /// Number of integer variable selections const int n_int_var_branch = sizeof(int_var_branch_name) / sizeof(const char*); /// Names for Boolean variable selections - const char* bool_var_branch_name[] = { - "SINGLE VARIABLE", "BOOL_VAR_NONE", "BOOL_VAR_RND", "BOOL_VAR_MERIT_MIN", "BOOL_VAR_MERIT_MAX", - "BOOL_VAR_DEGREE_MIN", "BOOL_VAR_DEGREE_MAX", "BOOL_VAR_AFC_MIN", "BOOL_VAR_AFC_MAX", "BOOL_VAR_ACTION_MIN", - "BOOL_VAR_ACTION_MAX", "BOOL_VAR_CHB_MIN", "BOOL_VAR_CHB_MAX"}; + const char* bool_var_branch_name[] = {"SINGLE VARIABLE", "BOOL_VAR_NONE", "BOOL_VAR_RND", + "BOOL_VAR_MERIT_MIN", "BOOL_VAR_MERIT_MAX", "BOOL_VAR_DEGREE_MIN", + "BOOL_VAR_DEGREE_MAX", "BOOL_VAR_AFC_MIN", "BOOL_VAR_AFC_MAX", + "BOOL_VAR_ACTION_MIN", "BOOL_VAR_ACTION_MAX", "BOOL_VAR_CHB_MIN", + "BOOL_VAR_CHB_MAX", "BOOL_VAR_LAST_CONFLICT"}; /// Number of integer variable selections const int n_bool_var_branch = sizeof(bool_var_branch_name) / sizeof(const char*); /// Test function for branch merit function @@ -181,11 +205,12 @@ namespace Test::Branch { const char* int_val_branch_name[] = {"INT_VAL_MIN", "INT_VAL_MED", "INT_VAL_MAX", "INT_VAL_RND", "INT_VAL_SPLIT_MIN", "INT_VAL_SPLIT_MAX", "INT_VAL_RANGE_MIN", "INT_VAL_RANGE_MAX", "INT_VAL", - "INT_VALUES_MIN", "INT_VALUES_MAX"}; + "INT_VALUES_MIN", "INT_VALUES_MAX", "INT_VAL_SOLUTION"}; /// Number of integer value selections const int n_int_val_branch = sizeof(int_val_branch_name) / sizeof(const char*); /// Names for Boolean value selections - const char* bool_val_branch_name[] = {"BOOL_VAL_MIN", "BOOL_VAL_MAX", "BOOL_VAL_RND", "BOOL_VAL"}; + const char* bool_val_branch_name[] = {"BOOL_VAL_MIN", "BOOL_VAL_MAX", "BOOL_VAL_RND", "BOOL_VAL", + "BOOL_VAL_SOLUTION"}; /// Number of Boolean value selections const int n_bool_val_branch = sizeof(bool_val_branch_name) / sizeof(const char*); /// Test function for branch value function @@ -214,7 +239,7 @@ namespace Test::Branch { "SET_VAR_CHB_MAX", "SET_VAR_MIN_MIN", "SET_VAR_MIN_MAX", "SET_VAR_MAX_MIN", "SET_VAR_MAX_MAX", "SET_VAR_SIZE_MIN", "SET_VAR_SIZE_MAX", "SET_VAR_DEGREE_SIZE_MIN", "SET_VAR_DEGREE_SIZE_MAX", "SET_VAR_AFC_SIZE_MIN", "SET_VAR_AFC_SIZE_MAX", "SET_VAR_ACTION_SIZE_MIN", - "SET_VAR_ACTION_SIZE_MAX", "SET_VAR_CHB_SIZE_MIN", "SET_VAR_CHB_SIZE_MAX"}; + "SET_VAR_ACTION_SIZE_MAX", "SET_VAR_CHB_SIZE_MIN", "SET_VAR_CHB_SIZE_MAX", "SET_VAR_LAST_CONFLICT"}; /// Number of set variable selections const int n_set_var_branch = sizeof(set_var_branch_name) / sizeof(const char*); /// Test function for branch merit function @@ -223,9 +248,9 @@ namespace Test::Branch { return 2.0; } /// Names for set value selections - const char* set_val_branch_name[] = {"SET_VAL_MIN_INC", "SET_VAL_MIN_EXC", "SET_VAL_MED_INC", - "SET_VAL_MED_EXC", "SET_VAL_MAX_INC", "SET_VAL_MAX_EXC", - "SET_VAL_RND_INC", "SET_VAL_RND_EXC", "SET_VAL"}; + const char* set_val_branch_name[] = {"SET_VAL_MIN_INC", "SET_VAL_MIN_EXC", "SET_VAL_MED_INC", "SET_VAL_MED_EXC", + "SET_VAL_MAX_INC", "SET_VAL_MAX_EXC", "SET_VAL_RND_INC", "SET_VAL_RND_EXC", + "SET_VAL", "SET_VAL_SOLUTION"}; /// Number of set value selections const int n_set_val_branch = sizeof(set_val_branch_name) / sizeof(const char*); /// Test function for branch value function @@ -251,7 +276,7 @@ namespace Test::Branch { "FLOAT_VAR_CHB_MAX", "FLOAT_VAR_MIN_MIN", "FLOAT_VAR_MIN_MAX", "FLOAT_VAR_MAX_MIN", "FLOAT_VAR_MAX_MAX", "FLOAT_VAR_SIZE_MIN", "FLOAT_VAR_SIZE_MAX", "FLOAT_VAR_DEGREE_SIZE_MIN", "FLOAT_VAR_DEGREE_SIZE_MAX", "FLOAT_VAR_AFC_SIZE_MIN", "FLOAT_VAR_AFC_SIZE_MAX", "FLOAT_VAR_ACTION_SIZE_MIN", - "FLOAT_VAR_ACTION_SIZE_MAX", "FLOAT_VAR_CHB_SIZE_MIN", "FLOAT_VAR_CHB_SIZE_MAX"}; + "FLOAT_VAR_ACTION_SIZE_MAX", "FLOAT_VAR_CHB_SIZE_MIN", "FLOAT_VAR_CHB_SIZE_MAX", "FLOAT_VAR_LAST_CONFLICT"}; /// Number of float variable selections const int n_float_var_branch = sizeof(float_var_branch_name) / sizeof(const char*); /// Test function for branch merit function @@ -261,7 +286,7 @@ namespace Test::Branch { } /// Names for float value selections const char* float_val_branch_name[] = {"FLOAT_VAL_SPLIT_MIN", "FLOAT_VAL_SPLIT_MAX", "FLOAT_VAL_SPLIT_RND", - "FLOAT_VAL"}; + "FLOAT_VAL", "FLOAT_VAL_SOLUTION"}; /// Number of float value selections const int n_float_val_branch = sizeof(float_val_branch_name) / sizeof(const char*); /// Test function for branch value function @@ -344,9 +369,26 @@ namespace Test::Branch { for (int i = arity; i--;) d[i] = i; + // Values of one solution for solution-guided value selection + IntSolutionValues sv(arity); + { + IntTestSpace* s = root->clone(); + branch(*s, s->x, INT_VAR_NONE(), INT_VAL_MAX()); + DFS e(s); + delete s; + IntTestSpace* solution = e.next(); + sv.update(solution->x); + delete solution; + } + + // Last-conflict selection comes last and is only supported as the + // first tie-break selection and not with INT_VALUES_MIN/MAX + const int last_conflict = n_int_var_branch - 1; for (int vara = 0; vara < n_int_var_branch; vara++) { - for (int varb = 1; varb < n_int_var_branch; varb++) { + for (int varb = 1; varb < last_conflict; varb++) { for (int val = 0; val < n_int_val_branch; val++) { + if ((vara == last_conflict) && ((val == 9) || (val == 10))) + continue; Rnd r(1); IntValBranch ivb; @@ -384,6 +426,9 @@ namespace Test::Branch { case 10: ivb = INT_VALUES_MAX(); break; + case 11: + ivb = INT_VAL_SOLUTION(sv, INT_VAL_RND(r)); + break; } IntTestSpace* c = root->clone(); @@ -490,6 +535,9 @@ namespace Test::Branch { case 30: ivba = INT_VAR_REGRET_MAX_MAX(); break; + case 31: + ivba = INT_VAR_LAST_CONFLICT(2, INT_VAR_SIZE_MIN()); + break; } Rnd rb(2); @@ -592,7 +640,10 @@ namespace Test::Branch { break; } - switch (_rand(9U)) { + // Cases with ivba as the first selection + const unsigned int first[3] = {0U, 2U, 5U}; + const unsigned int tb = (vara == last_conflict) ? first[_rand(3U)] : _rand(9U); + switch (tb) { case 0U: branch(*c, c->x, ivba, ivb); break; @@ -663,8 +714,23 @@ namespace Test::Branch { post(*root, root->x); results.clear(); + // Values of one solution for solution-guided value selection + IntSolutionValues sv(arity); + { + BoolTestSpace* s = root->clone(); + branch(*s, s->x, BOOL_VAR_NONE(), BOOL_VAL_MIN()); + DFS e(s); + delete s; + BoolTestSpace* solution = e.next(); + sv.update(solution->x); + delete solution; + } + + // Last-conflict selection comes last and is only supported as the + // first tie-break selection + const int last_conflict = n_bool_var_branch - 1; for (int vara = 0; vara < n_bool_var_branch; vara++) { - for (int varb = 1; varb < n_bool_var_branch; varb++) { + for (int varb = 1; varb < last_conflict; varb++) { for (int val = 0; val < n_bool_val_branch; val++) { Rnd r(1); @@ -683,6 +749,9 @@ namespace Test::Branch { case 3: bvb = BOOL_VAL(&bool_val); break; + case 4: + bvb = BOOL_VAL_SOLUTION(sv, BOOL_VAL_RND(r)); + break; } BoolTestSpace* c = root->clone(); @@ -736,6 +805,9 @@ namespace Test::Branch { case 12: bvba = BOOL_VAR_CHB_MAX(bca); break; + case 13: + bvba = BOOL_VAR_LAST_CONFLICT(2, BOOL_VAR_DEGREE_MAX()); + break; } Rnd rb(2); @@ -784,7 +856,10 @@ namespace Test::Branch { break; } - switch (_rand(9U)) { + // Cases with bvba as the first selection + const unsigned int first[3] = {0U, 2U, 5U}; + const unsigned int tb = (vara == last_conflict) ? first[_rand(3U)] : _rand(9U); + switch (tb) { case 0U: branch(*c, c->x, bvba, bvb); break; @@ -860,8 +935,25 @@ namespace Test::Branch { root->status(); results.clear(); + // Sets of one solution for solution-guided value selection + SetSolutionValues sv(arity); + { + SetTestSpace* s = root->clone(); + branch(*s, s->x, SET_VAR_NONE(), SET_VAL_MAX_EXC()); + DFS e(s); + delete s; + // Without a solution, the stored values stay empty + if (SetTestSpace* solution = e.next()) { + sv.update(solution->x); + delete solution; + } + } + + // Last-conflict selection comes last and is only supported as the + // first tie-break selection + const int last_conflict = n_set_var_branch - 1; for (int vara = 0; vara < n_set_var_branch; vara++) { - for (int varb = 1; varb < n_set_var_branch; varb++) { + for (int varb = 1; varb < last_conflict; varb++) { for (int val = 0; val < n_set_val_branch; val++) { Rnd r(1); @@ -894,11 +986,14 @@ namespace Test::Branch { case 8: svb = SET_VAL(&set_val); break; + case 9: + svb = SET_VAL_SOLUTION(sv, SET_VAL_RND_EXC(r)); + break; } SetTestSpace* c = root->clone(); - if (vara == 0) { + if ((vara == 0) && (val < 9)) { for (int i = 0; i < c->x.size(); i++) branch(*c, c->x[i], svb); } else { @@ -987,6 +1082,9 @@ namespace Test::Branch { case 26: svba = SET_VAR_CHB_SIZE_MAX(sca); break; + case 27: + svba = SET_VAR_LAST_CONFLICT(2, SET_VAR_SIZE_MIN()); + break; } Rnd rb(2); @@ -1076,7 +1174,10 @@ namespace Test::Branch { break; } - switch (_rand(9U)) { + // Cases with svba as the first selection + const unsigned int first[3] = {0U, 2U, 5U}; + const unsigned int tb = (vara == last_conflict) ? first[_rand(3U)] : _rand(9U); + switch (tb) { case 0U: branch(*c, c->x, svba, svb); break; @@ -1151,8 +1252,25 @@ namespace Test::Branch { root->status(); results.clear(); + // Values of one solution for solution-guided value selection + FloatSolutionValues sv(arity); + { + FloatTestSpace* s = root->clone(); + branch(*s, s->x, FLOAT_VAR_NONE(), FLOAT_VAL_SPLIT_MAX()); + DFS e(s); + delete s; + // Without a solution, the stored values stay empty + if (FloatTestSpace* solution = e.next()) { + sv.update(solution->x); + delete solution; + } + } + + // Last-conflict selection comes last and is only supported as the + // first tie-break selection + const int last_conflict = n_float_var_branch - 1; for (int vara = 0; vara < n_float_var_branch; vara++) { - for (int varb = 1; varb < n_float_var_branch; varb++) { + for (int varb = 1; varb < last_conflict; varb++) { for (int val = 0; val < n_float_val_branch; val++) { Rnd r(1); @@ -1170,10 +1288,13 @@ namespace Test::Branch { case 3: fvb = FLOAT_VAL(&float_val); break; + case 4: + fvb = FLOAT_VAL_SOLUTION(sv, FLOAT_VAL_SPLIT_RND(r)); + break; } FloatTestSpace* c = root->clone(); - if (vara == 0) { + if ((vara == 0) && (val < 4)) { for (int i = 0; i < c->x.size(); i++) branch(*c, c->x[i], fvb); } else { @@ -1262,6 +1383,9 @@ namespace Test::Branch { case 26: fvba = FLOAT_VAR_CHB_SIZE_MAX(fca); break; + case 27: + fvba = FLOAT_VAR_LAST_CONFLICT(2, FLOAT_VAR_SIZE_MIN()); + break; } Rnd rb(2); @@ -1351,7 +1475,10 @@ namespace Test::Branch { break; } - switch (_rand(9U)) { + // Cases with fvba as the first selection + const unsigned int first[3] = {0U, 2U, 5U}; + const unsigned int tb = (vara == last_conflict) ? first[_rand(3U)] : _rand(9U); + switch (tb) { case 0U: branch(*c, c->x, fvba, fvb); break; diff --git a/test/branch/bool.cpp b/test/branch/bool.cpp index 8f3401d9fc..adaf61d32d 100644 --- a/test/branch/bool.cpp +++ b/test/branch/bool.cpp @@ -32,6 +32,9 @@ #include "test/branch.hh" +#include +#include + namespace Test::Branch { /// %Test brancher with distinct propagator @@ -50,6 +53,109 @@ namespace Test::Branch { Bool b_5("5", 5); Bool b_7("7", 7); + /// Space for testing solution-guided Boolean value selection + class BoolSolutionSpace : public Gecode::Space { + public: + /// Variables to branch on + Gecode::BoolVarArray x; + + /// Initialize space branching with value selection \a vals + BoolSolutionSpace(const Gecode::BoolValBranch& vals) : x(*this, 3, 0, 1) { + Gecode::rel(*this, Gecode::BOT_OR, x, 1); + Gecode::branch(*this, x, Gecode::BOOL_VAR_NONE(), vals); + } + + /// Constructor for cloning + BoolSolutionSpace(BoolSolutionSpace& s) : Gecode::Space(s) { + x.update(*this, s.x); + } + + /// Copy space during cloning + Gecode::Space* + copy() override { + return new BoolSolutionSpace(*this); + } + + /// Return the value of the first alternative of the next choice + int + first() { + (void)status(); + const Gecode::Choice* ch = choice(); + int n = static_cast&>(*ch).val(); + delete ch; + return n; + } + }; + + /// Return the first solution found with value selection \a vals + static BoolSolutionSpace* + first_solution(const Gecode::BoolValBranch& vals) { + BoolSolutionSpace* s = new BoolSolutionSpace(vals); + Gecode::DFS e(s); + delete s; + return e.next(); + } + + /// Return supported Boolean fallback number \a i + static Gecode::BoolValBranch + bool_fallback(int i) { + switch (i) { + case 0: + return Gecode::BOOL_VAL_MIN(); + case 1: + return Gecode::BOOL_VAL_MAX(); + default: + return Gecode::BOOL_VAL_RND(Gecode::Rnd(7U)); + } + } + + /// Value function for testing rejected fallbacks + static int + bool_min_value(const Gecode::Space&, Gecode::BoolVar x, int) { + return x.min(); + } + + /// Test choosing stored Boolean values, falling back, and errors + class BoolSolution : public Base { + public: + /// Create and register test + BoolSolution() : Base("Bool::Branch::Solution") {} + + /// Run test + bool + run() override { + using namespace Gecode; + // Stores 0, 0, 1 + IntSolutionValues sv(3); + BoolSolutionSpace* s = first_solution(BOOL_VAL_MIN()); + sv.update(s->x); + delete s; + s = first_solution(BOOL_VAL_SOLUTION(sv, BOOL_VAL_MAX())); + bool guided = (s->x[0].val() == 0) && (s->x[1].val() == 0) && (s->x[2].val() == 1); + delete s; + if (!guided) + return false; + + IntSolutionValues empty(3); + for (int i = 0; i < 3; i++) { + BoolSolutionSpace g(BOOL_VAL_SOLUTION(empty, bool_fallback(i))); + BoolSolutionSpace p(bool_fallback(i)); + if (g.first() != p.first()) + return false; + } + + try { + (void)BOOL_VAL_SOLUTION(sv, BOOL_VAL(&bool_min_value)); + return false; + } catch (UnsupportedFallback&) { + // Expected + } + return true; + } + }; + + BoolSolution bool_solution; + } // namespace Test::Branch // STATISTICS: test-branch diff --git a/test/branch/float.cpp b/test/branch/float.cpp index c08d3f013e..44f2e9704a 100644 --- a/test/branch/float.cpp +++ b/test/branch/float.cpp @@ -34,6 +34,8 @@ #include "test/branch.hh" +#include + #ifdef GECODE_HAS_FLOAT_VARS namespace Test::Branch { @@ -61,6 +63,55 @@ namespace Test::Branch { Float l_3("Large::3", d_large, 3, 10); } // namespace + /// Space with two unconstrained float variables over [-2, 2] + class FloatSolutionSpace : public Gecode::Space { + public: + /// Variables + Gecode::FloatVarArray x; + /// Initialize + FloatSolutionSpace() : x(*this, 2, -2.0, 2.0) {} + /// Constructor for cloning \a s + FloatSolutionSpace(FloatSolutionSpace& s) : Gecode::Space(s) { + x.update(*this, s.x); + } + /// Copy space during cloning + Gecode::Space* + copy() override { + return new FloatSolutionSpace(*this); + } + }; + + /// Test that solution-guided selection finds the stored values first + class FloatSolutionValue : public Base { + public: + /// Create and register test + FloatSolutionValue() : Base("Float::Branch::Solution::Value") {} + /// Run test + bool + run() override { + using namespace Gecode; + FloatSolutionSpace stored; + rel(stored, stored.x[0], FRT_EQ, 1.5); + rel(stored, stored.x[1], FRT_EQ, -1.0); + (void)stored.status(); + FloatSolutionValues sv(2); + sv.update(stored.x); + + // The fallback alone would split towards -2 first + auto* root = new FloatSolutionSpace(); + branch(*root, root->x, FLOAT_VAR_NONE(), FLOAT_VAL_SOLUTION(sv, FLOAT_VAL_SPLIT_MIN())); + DFS e(root); + delete root; + FloatSolutionSpace* s = e.next(); + const bool ok = (s != nullptr) && (s->x[0].min() <= 1.5) && (1.5 <= s->x[0].max()) && + (s->x[1].min() <= -1.0) && (-1.0 <= s->x[1].max()); + delete s; + return ok; + } + }; + + FloatSolutionValue float_solution_value; + } // namespace Test::Branch #endif diff --git a/test/branch/int.cpp b/test/branch/int.cpp index 9463771c60..441299566f 100644 --- a/test/branch/int.cpp +++ b/test/branch/int.cpp @@ -33,9 +33,13 @@ #include "test/branch.hh" #include +#include #include +#include +#include #include +#include namespace Test::Branch { @@ -182,6 +186,574 @@ namespace Test::Branch { CBS cbs; #endif + /// Space for testing solution-guided value selection + class SolutionSpace : public Gecode::IntMinimizeSpace { + public: + /// Variables to branch on + Gecode::IntVarArray x; + /// Sum of the variables + Gecode::IntVar c; + /// Solution values updated on RBS solutions + Gecode::IntSolutionValues sv; + + /// Initialize space branching with value selection \a vals + SolutionSpace(const Gecode::IntValBranch& vals) + : x(*this, 3, 0, 4), c(*this, 0, 12), sv(vals.solution_values()) { + Gecode::distinct(*this, x); + Gecode::linear(*this, x, Gecode::IRT_EQ, c); + Gecode::branch(*this, x, Gecode::INT_VAR_NONE(), vals); + } + + /// Constructor for cloning + SolutionSpace(SolutionSpace& s) : Gecode::IntMinimizeSpace(s), sv(s.sv) { + x.update(*this, s.x); + c.update(*this, s.c); + } + + /// Copy space during cloning + Gecode::Space* + copy() override { + return new SolutionSpace(*this); + } + + /// Return cost + Gecode::IntVar + cost() const override { + return c; + } + + /// Store each new solution in RBS + void + hub(Gecode::HubContext& hc) override { + if (sv && (hc.engine() == Gecode::MetaEngine::Restart) && (hc.event() == Gecode::MetaEvent::Solution)) + sv.update(down_cast(*hc.last()).x); + Gecode::IntMinimizeSpace::hub(hc); + } + + /// Return the value of the first alternative of the next choice + int + first() { + (void)status(); + const Gecode::Choice* ch = choice(); + int n = static_cast&>(*ch).val(); + delete ch; + return n; + } + }; + + /// Return the first solution found with value selection \a vals + static SolutionSpace* + first_solution(const Gecode::IntValBranch& vals) { + SolutionSpace* s = new SolutionSpace(vals); + Gecode::DFS e(s); + delete s; + return e.next(); + } + + /// Return solution values storing the first solution found with \a vals + static Gecode::IntSolutionValues + solution_values(const Gecode::IntValBranch& vals) { + Gecode::IntSolutionValues sv(3); + SolutionSpace* s = first_solution(vals); + sv.update(s->x); + delete s; + return sv; + } + + /// Return supported fallback number \a i + static Gecode::IntValBranch + fallback(int i) { + switch (i) { + case 0: + return Gecode::INT_VAL_MIN(); + case 1: + return Gecode::INT_VAL_MED(); + case 2: + return Gecode::INT_VAL_MAX(); + default: + return Gecode::INT_VAL_RND(Gecode::Rnd(7U)); + } + } + + /// Number of supported fallbacks + const int n_fallbacks = 4; + + /// Test choosing stored values and falling back + class SolutionValue : public Base { + public: + /// Create and register test + SolutionValue() : Base("Int::Branch::Solution::Value") {} + + /// Whether \a guided and \a plain choose the same first value + static bool + same(const Gecode::IntValBranch& guided, const Gecode::IntValBranch& plain, bool exclude_stored) { + SolutionSpace g(guided), p(plain); + if (exclude_stored) { + Gecode::rel(g, g.x[0], Gecode::IRT_NQ, 4); + Gecode::rel(p, p.x[0], Gecode::IRT_NQ, 4); + } + return g.first() == p.first(); + } + + /// Run test + bool + run() override { + using namespace Gecode; + // Stores 4, 3, 2 + IntSolutionValues sv = solution_values(INT_VAL_MAX()); + SolutionSpace* s = first_solution(INT_VAL_SOLUTION(sv, INT_VAL_MIN())); + bool guided = (s->x[0].val() == 4) && (s->x[1].val() == 3) && (s->x[2].val() == 2); + delete s; + if (!guided) + return false; + + IntSolutionValues empty(3); + for (int i = 0; i < n_fallbacks; i++) { + if (!same(INT_VAL_SOLUTION(empty, fallback(i)), fallback(i), false) || + !same(INT_VAL_SOLUTION(sv, fallback(i)), fallback(i), true)) + return false; + } + return true; + } + }; + + SolutionValue solution_value; + + /// Value function for testing rejected fallbacks + static int + min_value(const Gecode::Space&, Gecode::IntVar x, int) { + return x.min(); + } + + /// Test errors of solution values and solution-guided value selection + class SolutionErrors : public Base { + public: + /// Create and register test + SolutionErrors() : Base("Int::Branch::Solution::Errors") {} + + /// Run test + bool + run() override { + using namespace Gecode; + IntSolutionValues sv = solution_values(INT_VAL_MAX()); + IntValBranch unsupported[] = {INT_VAL_SPLIT_MIN(), INT_VAL_RANGE_MAX(), INT_VAL(&min_value), + INT_VALUES_MIN()}; + for (const IntValBranch& f : unsupported) { + try { + (void)INT_VAL_SOLUTION(sv, f); + return false; + } catch (UnsupportedFallback&) { + // Expected + } + } + try { + (void)INT_VAL_SOLUTION(IntSolutionValues(), INT_VAL_MIN()); + return false; + } catch (UninitializedSolutionValues&) { + // Expected + } + + SolutionSpace s(INT_VAL_MIN()); + Gecode::rel(s, s.x[0], IRT_EQ, 1); + (void)s.status(); + try { + sv.update(s.x); + return false; + } catch (Int::ValOfUnassignedVar&) { + // Expected + } + try { + IntSolutionValues(2).update(s.x); + return false; + } catch (Int::ArgumentSizeMismatch&) { + // Expected + } + // A rejected update leaves the stored values unchanged + return sv[0] == 4; + } + }; + + SolutionErrors solution_errors; + + /// Test that choices keep their value after the handle is updated + class SolutionArchive : public Base { + public: + /// Create and register test + SolutionArchive() : Base("Int::Branch::Solution::Archive") {} + + /// Run test + bool + run() override { + using namespace Gecode; + IntSolutionValues sv = solution_values(INT_VAL_MAX()); + SolutionSpace* s = new SolutionSpace(INT_VAL_SOLUTION(sv, INT_VAL_MIN())); + (void)s->status(); + const Choice* original = s->choice(); + Archive a; + original->archive(a); + // Now stores 0, 1, 2 + SolutionSpace* t = first_solution(INT_VAL_MIN()); + sv.update(t->x); + delete t; + const Choice* restored = s->choice(a); + + SolutionSpace* o = s->clone(); + SolutionSpace* r = s->clone(); + SolutionSpace* n = s->clone(); + o->commit(*original, 0); + r->commit(*restored, 0); + (void)o->status(); + (void)r->status(); + bool ok = (o->x[0].val() == 4) && (r->x[0].val() == 4) && (n->first() == 0); + delete original; + delete restored; + delete o; + delete r; + delete n; + delete s; + return ok; + } + }; + + SolutionArchive solution_archive; + + /// Test recomputation and threads while the handle is updated during search + class SolutionRecompute : public Base { + public: + /// Create and register test + SolutionRecompute() : Base("Int::Branch::Solution::Recompute") {} + + /// Run test + bool + run() override { + using namespace Gecode; + for (double threads : {1.0, 4.0}) { + IntSolutionValues sv = solution_values(INT_VAL_MAX()); + std::unique_ptr root(new SolutionSpace(INT_VAL_SOLUTION(sv, INT_VAL_MIN()))); + Search::Options o; + o.c_d = 3; + o.a_d = 1; + o.threads = threads; + DFS e(root.get(), o); + + bool seen[125] = {}; + int n = 0; + while (SolutionSpace* s = e.next()) { + int k = 25 * s->x[0].val() + 5 * s->x[1].val() + s->x[2].val(); + bool duplicate = seen[k]; + seen[k] = true; + sv.update(s->x); + delete s; + if (duplicate) + return false; + n++; + } + if (n != 60) + return false; + } + return true; + } + }; + + SolutionRecompute solution_recompute; + + /// Test updating the handle between restarts with no-goods + class SolutionRestart : public Base { + public: + /// Create and register test + SolutionRestart() : Base("Int::Branch::Solution::Restart") {} + + /// Run test + bool + run() override { + using namespace Gecode; + IntSolutionValues sv(3); + SolutionSpace* root = new SolutionSpace(INT_VAL_SOLUTION(sv, INT_VAL_MAX())); + Search::Options o; + o.cutoff = Search::Cutoff::constant(1); + o.nogoods_limit = 64U; + RBS e(root, o); + delete root; + + SolutionSpace* best = nullptr; + while (SolutionSpace* s = e.next()) { + delete best; + best = s; + } + // sv retains the best solution from the last solution event + bool ok = (best != nullptr) && (best->c.val() == 3) && !sv.empty() && (e.statistics().restart > 0); + for (int i = 0; ok && (i < 3); i++) + ok = (sv[i] == best->x[i].val()); + delete best; + return ok; + } + }; + + SolutionRestart solution_restart; + + /// Whether a choice reports its first alternative as failed + enum class Report { + None, ///< Report nothing + Failed ///< Report the first alternative as failed + }; + + /// Space for testing last-conflict variable selection + class LastConflictSpace : public Gecode::Space { + public: + /// Variables to branch on + Gecode::IntVarArray x; + + /// Initialize space with conflict-set size 2 over INT_VAR_NONE + LastConflictSpace() : x(*this, 4, 0, 1) { + Gecode::branch(*this, x, Gecode::INT_VAR_LAST_CONFLICT(2, Gecode::INT_VAR_NONE()), Gecode::INT_VAL_MIN()); + } + + /// Constructor for cloning + LastConflictSpace(LastConflictSpace& s) : Gecode::Space(s) { + x.update(*this, s.x); + } + + /// Copy space during cloning + Gecode::Space* + copy() override { + return new LastConflictSpace(*this); + } + + /// Return the position of choice \a c + static int + position(const Gecode::Choice& c) { + return static_cast&>(c).pos().pos; + } + + /// Return the choice of a clone with the variables at \a fixed assigned + const Gecode::Choice* + choice_with(std::initializer_list fixed) const { + std::unique_ptr c(clone()); + for (int i : fixed) + Gecode::rel(*c, c->x[i], Gecode::IRT_EQ, 0); + (void)c->status(); + return c->choice(); + } + + /// Return position chosen with \a fixed assigned, reporting as \a r + int + choose(std::initializer_list fixed, Report r = Report::None) const { + std::unique_ptr c(choice_with(fixed)); + if (r == Report::Failed) + c->alternative_failed(0U); + return position(*c); + } + }; + + /// Test selection and errors of last-conflict variable selection + class LastConflictSelect : public Base { + public: + /// Create and register test + LastConflictSelect() : Base("Int::Branch::LastConflict::Select", TestTags::check()) {} + + /// Run test + bool + run() override { + using namespace Gecode; + const Report failed = Report::Failed; + LastConflictSpace s; + (void)s.status(); + // Choices without a reported failure must not enter the set + bool ok = (s.choose({}) == 0) && + // Set: 2, then 3 2 + (s.choose({0, 1}, failed) == 2) && (s.choose({0, 1, 2}, failed) == 3) && (s.choose({}) == 3) && + (s.choose({3}) == 2) && + // Set: 0 3, so 2 is evicted + (s.choose({2, 3}, failed) == 0) && (s.choose({}) == 0) && (s.choose({0}) == 3) && + (s.choose({0, 3}) == 1) && + // Set: 3 0 + (s.choose({0}, failed) == 3) && (s.choose({}) == 3); + if (!ok) + return false; + + // A choice restored from an archive keeps its position + std::unique_ptr original(s.choice_with({})); + Archive a; + original->archive(a); + // Set: 0 3 + if (s.choose({3}, failed) != 0) + return false; + std::unique_ptr restored(s.choice(a)); + if ((LastConflictSpace::position(*restored) != 3) || (s.choose({}) != 0)) + return false; + + try { + (void)INT_VAR_LAST_CONFLICT(0, INT_VAR_NONE()); + return false; + } catch (IllegalConflictSetSize&) { + // Expected + } + try { + (void)BOOL_VAR_LAST_CONFLICT(0, BOOL_VAR_NONE()); + return false; + } catch (IllegalConflictSetSize&) { + // Expected + } + const IntVarBranch lc = INT_VAR_LAST_CONFLICT(1, INT_VAR_NONE()); + LastConflictSpace t; + try { + branch(t, t.x, lc, INT_VALUES_MIN()); + return false; + } catch (UnsupportedLastConflict&) { + // Expected + } + try { + branch(t, t.x, tiebreak(INT_VAR_SIZE_MIN(), lc), INT_VAL_MIN()); + return false; + } catch (UnsupportedLastConflict&) { + // Expected + } + try { + assign(t, t.x, lc, INT_ASSIGN_MIN()); + return false; + } catch (UnsupportedLastConflict&) { + // Expected + } + try { + Symmetries syms; + syms << variable_symmetry(t.x); + branch(t, t.x, lc, INT_VAL_MIN(), syms); + return false; + } catch (UnsupportedLastConflict&) { + // Expected + } + try { + OpenIntVarList o(t, IntSet(0, 1), 2); + branch(t, o, lc, INT_VAL_MIN()); + return false; + } catch (UnsupportedLastConflict&) { + // Expected + } + return true; + } + }; + + LastConflictSelect last_conflict_select; + + /// Queens problem branching with a given variable selection + class LastConflictQueens : public Gecode::Space { + public: + /// Queen positions + Gecode::IntVarArray q; + + /// Initialize \a n queens branching with variable selection \a vars + LastConflictQueens(int n, const Gecode::IntVarBranch& vars) : q(*this, n, 0, n - 1) { + using namespace Gecode; + distinct(*this, q); + distinct(*this, IntArgs::create(n, 0, 1), q); + distinct(*this, IntArgs::create(n, 0, -1), q); + branch(*this, q, vars, INT_VAL_MIN()); + } + + /// Constructor for cloning + LastConflictQueens(LastConflictQueens& s) : Gecode::Space(s) { + q.update(*this, s.q); + } + + /// Copy space during cloning + Gecode::Space* + copy() override { + return new LastConflictQueens(*this); + } + }; + + /// Solutions and statistics of a queens search + class LastConflictRun { + public: + /// Solutions in the order found + std::vector> solutions; + /// Statistics of the engine + Gecode::Search::Statistics statistics; + + /// Run engine \a E with options \a o on \a n queens branching with \a vars + template