diff --git a/changelog.in b/changelog.in index 543c60f69a..6e1eac7d45 100644 --- a/changelog.in +++ b/changelog.in @@ -650,6 +650,16 @@ Rank: minor [DESCRIPTION] Fix linking of the FloatValArgs initializer-list constructor. +[ENTRY] +Module: minimodel +What: bug +Rank: minor +[DESCRIPTION] +Fix float optimization cuts in FloatMinimizeSpace, FloatMaximizeSpace, and +FlatZinc: round the limit toward the incumbent so every solution that +improves by more than the step is admitted, and in MiniModel reject an +assigned cost one float wide whose ranked endpoint fails the cut. + [ENTRY] Module: driver What: new @@ -659,6 +669,20 @@ Add Driver::EnumOption, a string-valued option backed by an enum type so scripts can offer enum class choices without casting to int; used by the mode and restart options in Options and FlatZincOptions. +[ENTRY] +Module: flatzinc +What: new +Rank: minor +[DESCRIPTION] +Add a relative improvement step for float objectives: -rel-step r in +FlatZinc and scripts (Options::rel_step), and a second constructor argument +to FloatMinimizeSpace and FloatMaximizeSpace. Each new solution must +improve on the best objective v by more than max(step, r*|v|). Both steps +default to 0 for exact optimization; with a nonzero step, an exhausted +search proves only that no solution improves on v by more than that amount. +The absolute step must be finite and nonnegative, and r at least 0 and +below 1. The MiniZinc solver configurations list --step and --rel-step. + [ENTRY] Module: flatzinc What: change diff --git a/gecode/driver.hh b/gecode/driver.hh index a52a07556c..51f36f70a1 100644 --- a/gecode/driver.hh +++ b/gecode/driver.hh @@ -497,6 +497,7 @@ namespace Gecode { Driver::DoubleOption _decay; ///< Decay option Driver::RandomOption _seed; ///< Seed or complete random state Driver::DoubleOption _step; ///< Step option + Driver::DoubleOption _rel_step; ///< Relative step option //@} /// \name Search options @@ -595,6 +596,19 @@ namespace Gecode { void step(double s); /// Return step value double step() const; + + /** + * \brief Set default relative step value + * + * Float optimization scripts require each new solution to improve on + * the best cost by more than the larger of step() and \a s times the + * magnitude of that cost (see FloatMinimizeSpace). With a nonzero + * step, an exhausted search proves only that no solution improves by + * more than that amount. Must be at least 0 and below 1. + */ + void rel_step(double s); + /// Return relative step value + double rel_step() const; //@} /// \name Search options @@ -999,12 +1013,12 @@ namespace Gecode::Driver { #ifdef GECODE_HAS_FLOAT_VARS - /// Class to extract the step option value + /// Class to extract the step and relative step option values template class ExtractStepOption : public BaseSpace { public: - /// Constructor that extracts the step value - ExtractStepOption(const Options& opt) : BaseSpace(opt.step()) {} + /// Constructor that extracts the step and relative step values + ExtractStepOption(const Options& opt) : BaseSpace(opt.step(), opt.rel_step()) {} /// Constructor used for cloning ExtractStepOption(BaseSpace& e) : BaseSpace(e) {} }; diff --git a/gecode/driver/options.cpp b/gecode/driver/options.cpp index 6cac225264..5d0c766162 100644 --- a/gecode/driver/options.cpp +++ b/gecode/driver/options.cpp @@ -730,6 +730,7 @@ namespace Gecode { _propagation("propagation", "propagation variants"), _branching("branching", "branching variants"), _decay("decay", "decay factor", 1.0), _seed("seed", "random number generator seed", 1U), _step("step", "step distance for float optimization", 0.0), + _rel_step("rel-step", "step for float optimization relative to the cost (0 = none)", 0.0), _search("search", "search engine variants"), _solutions("solutions", "number of solutions (0 = all)", 1), _threads("threads", "number of threads (0 = #processing units)", Search::Config::threads), @@ -791,6 +792,7 @@ namespace Gecode { add(_decay); add(_seed); add(_step); + add(_rel_step); add(_search); add(_solutions); add(_threads); diff --git a/gecode/driver/options.hpp b/gecode/driver/options.hpp index 53defe83f2..116b03d903 100644 --- a/gecode/driver/options.hpp +++ b/gecode/driver/options.hpp @@ -321,6 +321,15 @@ namespace Gecode { return _step.value(); } + inline void + Options::rel_step(double s) { + _rel_step.value(s); + } + inline double + Options::rel_step() const { + return _rel_step.value(); + } + /* * Search options * diff --git a/gecode/driver/script.hpp b/gecode/driver/script.hpp index 96cac03435..051ae6bd7a 100644 --- a/gecode/driver/script.hpp +++ b/gecode/driver/script.hpp @@ -31,6 +31,7 @@ * */ +#include #include #include #include @@ -291,6 +292,14 @@ namespace Gecode::Driver { template class Engine, class Options> void ScriptBase::run(const Options& o, Script* s) { + if (!(std::isfinite(o.step()) && (o.step() >= 0.0))) { + std::cerr << "Option -step must be finite and nonnegative" << '\n' << std::flush; + exit(EXIT_FAILURE); + } + if (!((o.rel_step() >= 0.0) && (o.rel_step() < 1.0))) { + std::cerr << "Option -rel-step must be at least 0 and below 1" << '\n' << std::flush; + exit(EXIT_FAILURE); + } if ((o.restart() != RESTART_NONE) && (o.assets() > 0)) { std::cerr << "Cannot use restarts and portfolio..." << '\n' << std::flush; exit(EXIT_FAILURE); diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index 46145ef440..d3d90e4d8f 100644 --- a/gecode/flatzinc.hh +++ b/gecode/flatzinc.hh @@ -235,6 +235,7 @@ namespace Gecode::FlatZinc { Gecode::Driver::UnsignedIntOption _nogoods_limit; ///< Depth limit for extracting no-goods Gecode::Driver::BoolOption _interrupt; ///< Whether to catch SIGINT Gecode::Driver::DoubleOption _step; ///< Step option + Gecode::Driver::DoubleOption _rel_step; ///< Relative step option //@} /// \name Execution options @@ -269,6 +270,7 @@ namespace Gecode::FlatZinc { _nogoods_limit("nogoods-limit", "depth limit for no-good extraction", Search::Config::nogoods_limit), _interrupt("interrupt", "whether to catch Ctrl-C (true) or not (false)", true), _step("step", "step distance for float optimization", 0.0), + _rel_step("rel-step", "step for float optimization relative to the objective (0 = none)", 0.0), _mode("mode", "how to execute script", Gecode::SM_SOLUTION), _stat("s", "emit statistics"), _output("o", "file to send output to") @@ -300,6 +302,7 @@ namespace Gecode::FlatZinc { add(_interrupt); add(_seed); add(_step); + add(_rel_step); add(_restart); add(_r_base); add(_r_scale); @@ -380,6 +383,10 @@ namespace Gecode::FlatZinc { step() const { return _step.value(); } + double + rel_step() const { + return _rel_step.value(); + } const char* output() const { return _output.value(); @@ -647,8 +654,22 @@ namespace Gecode::FlatZinc { Gecode::FloatVarArray fv_aux; /// Indicates whether a float variable is introduced by mzn2fzn std::vector fv_introduced; - /// Step used by float optimization cuts and comparison compatibility + /** + * \brief Absolute improvement step for float optimization cuts + * + * Each new solution must improve on the incumbent objective \f$v\f$ by + * more than \f$d=\max(\mathit{step},\mathit{rel\_step}\cdot|v|)\f$, + * where \f$v\f$ is the lower bound of the incumbent when minimizing + * and the upper bound when maximizing. Rounding never excludes such a + * solution; it may admit one that misses \f$d\f$ by rounding error, + * but never one that is not strictly better than \f$v\f$. Both steps + * default to 0 for exact optimization; with a nonzero step, an + * exhausted search still prints "==========" and proves only that no + * solution improves on \f$v\f$ by more than \f$d\f$. + */ Gecode::FloatNum step; + /// Relative improvement step for float optimization cuts (see \a step) + Gecode::FloatNum rel_step; #endif /// Whether the introduced variables still need to be copied bool need_aux_vars; @@ -700,10 +721,10 @@ namespace Gecode::FlatZinc { * \brief Compare compatible optimization objectives * * Integer objectives compare assigned values. Float objectives require - * the same direction and step, and assigned intervals, which may span + * the same direction and steps, and assigned intervals, which may span * adjacent float values. Float minimization ranks lower endpoints and - * maximization ranks upper endpoints, independently of the step used by - * constrain(). + * maximization ranks upper endpoints, independently of the steps used + * by constrain(). */ SpaceComparison compare(const Space& s) const override; /// Compare this space with space \a s and print the differences on diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 23ed74d828..8f8d41fa06 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -824,7 +824,7 @@ namespace Gecode::FlatZinc { : Space(f), _init_data(nullptr), _random(f._random), _solve_annotations(nullptr), restart_data(f.restart_data), iv_boolalias(nullptr), #ifdef GECODE_HAS_FLOAT_VARS - step(f.step), + step(f.step), rel_step(f.rel_step), #endif need_aux_vars(f.need_aux_vars) { _opt_var = f._opt_var; @@ -904,7 +904,7 @@ namespace Gecode::FlatZinc { set_var_count(-1), _opt_var(-1), _opt_var_is_int(true), _lns(0), _lns_initial_solution(0), _random(random), _solve_annotations(nullptr), #ifdef GECODE_HAS_FLOAT_VARS - step(0.0), + step(0.0), rel_step(0.0), #endif need_aux_vars(true) { branch_info.init(); @@ -1876,11 +1876,15 @@ namespace Gecode::FlatZinc { void FlatZincSpace::run_meta(std::ostream& out, const Printer& p, const FlatZincOptions& opt, Support::Timer& t_total) { #ifdef GECODE_HAS_FLOAT_VARS - // A negative step lets constrain admit solutions that compare as no - // better than the incumbent. - if (!(opt.step() >= 0.0)) - throw FlatZinc::Error("FlatZinc", "step must be nonnegative"); + // A negative step can admit solutions no better than the incumbent, + // and a relative step above 1 can let a better incumbent loosen the + // cut (1 already cuts across zero). + if (!(std::isfinite(opt.step()) && (opt.step() >= 0.0))) + throw FlatZinc::Error("FlatZinc", "step must be finite and nonnegative"); + if (!((opt.rel_step() >= 0.0) && (opt.rel_step() < 1.0))) + throw FlatZinc::Error("FlatZinc", "rel-step must be at least 0 and below 1"); step = opt.step(); + rel_step = opt.rel_step(); #endif #ifdef GECODE_HAS_GIST if (opt.mode() == SM_GIST) { @@ -2054,6 +2058,15 @@ namespace Gecode::FlatZinc { } } +#ifdef GECODE_HAS_FLOAT_VARS + /// Required improvement over \a v from \a step and \a rel_step, rounded + /// down so rounding never tightens the cut + static FloatNum + float_improvement(FloatNum step, FloatNum rel_step, FloatNum v) { + return std::max(step, (FloatVal(rel_step) * std::abs(v)).min()); + } +#endif + void FlatZincSpace::constrain(const Space& s) { // Read the objective of the incumbent at its own index, as compare does @@ -2066,19 +2079,22 @@ namespace Gecode::FlatZinc { } else { #ifdef GECODE_HAS_FLOAT_VARS FloatVal best = b.fv[b._opt_var].val(); - // When minimizing, an assigned objective is below best - step - // exactly when its upper bound is below the lower bound of that - // interval (symmetrically when maximizing). Posting this strict - // bound prunes the incumbent value before the objective is - // assigned, and also guarantees progress when it never is. + // When minimizing, a solution improves on the incumbent by more + // than d = max(step, rel_step*|v|) when its lower bound is below + // v - d, where v = best.min() (symmetrically v = best.max() when + // maximizing). Rounding d down, rounding v - d upward, and stepping + // down one float gives an upper bound that never excludes such a + // solution and stays below v. Posting this bound prunes the + // incumbent value before the objective is assigned, and guarantees + // progress when it never is. if (_method == MIN) { - FloatNum n = (best - step).min(); + FloatNum n = (FloatVal(best.min()) - float_improvement(step, rel_step, best.min())).max(); if (n <= Float::Limits::min) fail(); else rel(*this, fv[_opt_var], FRT_LQ, std::nextafter(n, Float::Limits::min)); } else if (_method == MAX) { - FloatNum n = (best + step).max(); + FloatNum n = (FloatVal(best.max()) + float_improvement(step, rel_step, best.max())).min(); if (n >= Float::Limits::max) fail(); else @@ -2101,7 +2117,7 @@ namespace Gecode::FlatZinc { if (_opt_var_is_int) return compare_int(iv[_opt_var].val(), other->iv[other->_opt_var].val(), sense); #ifdef GECODE_HAS_FLOAT_VARS - if (step != other->step) + if ((step != other->step) || (rel_step != other->rel_step)) throw SpaceIncompatibleObjectives("FlatZincSpace::compare"); FloatVal a = fv[_opt_var].val(); FloatVal b = other->fv[other->_opt_var].val(); diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 002a7c0874..a561cd03aa 100644 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2407,6 +2407,11 @@ namespace Gecode { * SpaceNoComparison by default, so any override of constrain() must * also override compare(). * + * compare() ranks independently of any improvement step that + * constrain() requires (such as the float steps of + * FloatMinimizeSpace). With a nonzero step, an exhausted search proves + * only that no solution improves on the best by more than that step. + * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT virtual SpaceComparison compare(const Space& other) const; diff --git a/gecode/minimodel.hh b/gecode/minimodel.hh index 47dcc06365..d3a38982d4 100644 --- a/gecode/minimodel.hh +++ b/gecode/minimodel.hh @@ -59,6 +59,7 @@ #endif #include +#include #include #include #include @@ -2142,34 +2143,42 @@ namespace Gecode { /** * \brief Class for minimizing float cost * - * The class supports using a step value \a step that will make sure - * that better solutions must be better by at least the value of - * \a step. + * Each new solution must have a cost below \f$v-d\f$, where \f$v\f$ is + * the upper endpoint of the best cost and + * \f$d=\max(\mathit{step},\mathit{rel\_step}\cdot|v|)\f$. Near + * \f$v=0\f$ the absolute step governs. Rounding never excludes a cost + * below \f$v-d\f$; the cut may admit a cost that misses \f$v-d\f$ by + * rounding error, but never one at or above \f$v\f$. Both steps default + * to 0 for exact optimization; with a nonzero step, an exhausted search + * proves only that no solution has a cost below \f$v-d\f$. * * Comparison ranks the upper endpoint of assigned costs independently of - * the step. Both operands must use this base class and the same step. + * the steps. Both operands must use this base class and the same steps. * Assigned costs may be tight intervals between adjacent float values. * * \ingroup TaskModelMiniModelOptimize */ class GECODE_VTABLE_EXPORT FloatMinimizeSpace : public Space { protected: - /// Step by which a next solution has to have lower cost + /// Absolute improvement step FloatNum step; + /// Relative improvement step (see class documentation) + FloatNum rel_step; public: /** - * \brief Constructor with step \a s + * \brief Constructor with step \a s and relative step \a rs * - * Throws MiniModel::ArgumentOutOfRange if \a s is negative or NaN. + * Throws MiniModel::ArgumentOutOfRange unless \a s is finite and + * nonnegative and \a rs is at least 0 and below 1. */ - FloatMinimizeSpace(FloatNum s = 0.0); + FloatMinimizeSpace(FloatNum s = 0.0, FloatNum rs = 0.0); /// Constructor for cloning FloatMinimizeSpace(FloatMinimizeSpace& s); /// Member function constraining according to cost GECODE_MINIMODEL_EXPORT void constrain(const Space& best) override; - /// Compare upper endpoints of assigned costs (same step required) + /// Compare upper endpoints of assigned costs (same steps required) GECODE_MINIMODEL_EXPORT SpaceComparison compare(const Space& other) const override; /// Return variable with current cost @@ -2179,34 +2188,38 @@ namespace Gecode { /** * \brief Class for maximizing float cost * - * The class supports using a step value \a step that will make sure - * that better solutions must be better by at least the value of - * \a step. + * Each new solution must have a cost above \f$v+d\f$, where \f$v\f$ is + * the lower endpoint of the best cost and \f$d\f$ is as in + * FloatMinimizeSpace, which also describes rounding and what an exhausted + * search proves. * * Comparison ranks the lower endpoint of assigned costs independently of - * the step. Both operands must use this base class and the same step. + * the steps. Both operands must use this base class and the same steps. * Assigned costs may be tight intervals between adjacent float values. * * \ingroup TaskModelMiniModelOptimize */ class GECODE_VTABLE_EXPORT FloatMaximizeSpace : public Space { protected: - /// Step by which a next solution has to have lower cost + /// Absolute improvement step FloatNum step; + /// Relative improvement step (see FloatMinimizeSpace) + FloatNum rel_step; public: /** - * \brief Constructor with step \a s + * \brief Constructor with step \a s and relative step \a rs * - * Throws MiniModel::ArgumentOutOfRange if \a s is negative or NaN. + * Throws MiniModel::ArgumentOutOfRange unless \a s is finite and + * nonnegative and \a rs is at least 0 and below 1. */ - FloatMaximizeSpace(FloatNum s = 0.0); + FloatMaximizeSpace(FloatNum s = 0.0, FloatNum rs = 0.0); /// Constructor for cloning FloatMaximizeSpace(FloatMaximizeSpace& s); /// Member function constraining according to cost GECODE_MINIMODEL_EXPORT void constrain(const Space& best) override; - /// Compare lower endpoints of assigned costs (same step required) + /// Compare lower endpoints of assigned costs (same steps required) GECODE_MINIMODEL_EXPORT SpaceComparison compare(const Space& other) const override; /// Return variable with current cost diff --git a/gecode/minimodel/optimize.cpp b/gecode/minimodel/optimize.cpp index 2bf3c28829..f3d7ad2fc3 100644 --- a/gecode/minimodel/optimize.cpp +++ b/gecode/minimodel/optimize.cpp @@ -32,6 +32,7 @@ #include +#include #include namespace Gecode { @@ -120,20 +121,32 @@ namespace Gecode { #ifdef GECODE_HAS_FLOAT_VARS + /// Required improvement over \a v from \a step and \a rel_step, rounded + /// down so rounding never tightens the cut + static FloatNum + improvement(FloatNum step, FloatNum rel_step, FloatNum v) { + return std::max(step, (FloatVal(rel_step) * std::abs(v)).min()); + } + void FloatMinimizeSpace::constrain(const Space& _best) { const FloatMinimizeSpace* best = dynamic_cast(&_best); if (best == nullptr) throw DynamicCastFailed("FloatMinimizeSpace::constrain"); - // An assigned cost is below the bound of the best solution minus the - // step exactly when its upper bound is below the lower bound of that - // difference. Posting this strict bound prunes the incumbent value - // before the cost is assigned. - FloatNum n = (FloatVal(best->cost().max()) - step).min(); - if (n <= Float::Limits::min) + // A cost improves on v = best->cost().max() by more than + // d = max(step, rel_step*|v|) when its upper endpoint is below v - d. + // Rounding d down, rounding v - d upward, and stepping down one float + // gives a limit that never excludes such a cost and stays below v. + // Posting the bound prunes the incumbent before the cost is assigned. A + // bound update leaves an assigned cost alone unless it fails, so an + // assigned cost whose upper endpoint exceeds limit is rejected here. + FloatNum v = best->cost().max(); + FloatNum n = (FloatVal(v) - improvement(step, rel_step, v)).max(); + FloatNum limit = std::nextafter(n, Float::Limits::min); + if ((n <= Float::Limits::min) || (cost().assigned() && (cost().max() > limit))) fail(); else - rel(*this, cost(), FRT_LQ, std::nextafter(n, Float::Limits::min)); + rel(*this, cost(), FRT_LQ, limit); } SpaceComparison @@ -141,7 +154,7 @@ namespace Gecode { const FloatMinimizeSpace* s = dynamic_cast(&other); if (s == nullptr) throw DynamicCastFailed("FloatMinimizeSpace::compare"); - if (step != s->step) + if ((step != s->step) || (rel_step != s->rel_step)) throw SpaceIncompatibleObjectives("FloatMinimizeSpace::compare"); return compare_float(cost().val().max(), s->cost().val().max(), Sense::Minimize); } @@ -151,11 +164,14 @@ namespace Gecode { const FloatMaximizeSpace* best = dynamic_cast(&_best); if (best == nullptr) throw DynamicCastFailed("FloatMaximizeSpace::constrain"); - FloatNum n = (FloatVal(best->cost().min()) + step).max(); - if (n >= Float::Limits::max) + // Symmetric to FloatMinimizeSpace::constrain + FloatNum v = best->cost().min(); + FloatNum n = (FloatVal(v) + improvement(step, rel_step, v)).min(); + FloatNum limit = std::nextafter(n, Float::Limits::max); + if ((n >= Float::Limits::max) || (cost().assigned() && (cost().min() < limit))) fail(); else - rel(*this, cost(), FRT_GQ, std::nextafter(n, Float::Limits::max)); + rel(*this, cost(), FRT_GQ, limit); } SpaceComparison @@ -163,7 +179,7 @@ namespace Gecode { const FloatMaximizeSpace* s = dynamic_cast(&other); if (s == nullptr) throw DynamicCastFailed("FloatMaximizeSpace::compare"); - if (step != s->step) + if ((step != s->step) || (rel_step != s->rel_step)) throw SpaceIncompatibleObjectives("FloatMaximizeSpace::compare"); return compare_float(cost().val().min(), s->cost().val().min(), Sense::Maximize); } diff --git a/gecode/minimodel/optimize.hpp b/gecode/minimodel/optimize.hpp index ae6a599e4a..eb02e5c53c 100644 --- a/gecode/minimodel/optimize.hpp +++ b/gecode/minimodel/optimize.hpp @@ -54,27 +54,27 @@ namespace Gecode { #ifdef GECODE_HAS_FLOAT_VARS forceinline - FloatMinimizeSpace::FloatMinimizeSpace(FloatNum s) - : step(s) { - if (!(s >= 0.0)) + FloatMinimizeSpace::FloatMinimizeSpace(FloatNum s, FloatNum rs) + : step(s), rel_step(rs) { + if (!(std::isfinite(s) && (s >= 0.0)) || !((rs >= 0.0) && (rs < 1.0))) throw MiniModel::ArgumentOutOfRange("FloatMinimizeSpace::FloatMinimizeSpace"); } forceinline // NOLINTNEXTLINE(modernize-use-equals-default) FloatMinimizeSpace::FloatMinimizeSpace(FloatMinimizeSpace& s) - : Space(s), step(s.step) {} + : Space(s), step(s.step), rel_step(s.rel_step) {} forceinline - FloatMaximizeSpace::FloatMaximizeSpace(FloatNum s) - : step(s) { - if (!(s >= 0.0)) + FloatMaximizeSpace::FloatMaximizeSpace(FloatNum s, FloatNum rs) + : step(s), rel_step(rs) { + if (!(std::isfinite(s) && (s >= 0.0)) || !((rs >= 0.0) && (rs < 1.0))) throw MiniModel::ArgumentOutOfRange("FloatMaximizeSpace::FloatMaximizeSpace"); } forceinline FloatMaximizeSpace::FloatMaximizeSpace(FloatMaximizeSpace& s) - : Space(s), step(s.step) {} + : Space(s), step(s.step), rel_step(s.rel_step) {} #endif diff --git a/test/flatzinc.cpp b/test/flatzinc.cpp index ebf2302b2e..69d837bc76 100644 --- a/test/flatzinc.cpp +++ b/test/flatzinc.cpp @@ -112,10 +112,61 @@ namespace Test::FlatZinc { FloatCutExcludesIncumbent float_cut_excludes_incumbent; + /// A float objective model for option validation + const char* const step_model = "var 0.0..1.0: x :: output_var;\nsolve minimize x;\n"; + /// A negative step would let the cut admit solutions that are not better - FlatZincErrorTest float_negative_step("FlatZinc::Float::NegativeStep", - "var 0.0..1.0: x :: output_var;\nsolve minimize x;\n", {"-step", "-1"}, - "step must be nonnegative"); + FlatZincErrorTest float_negative_step("FlatZinc::Float::NegativeStep", step_model, {"-step", "-1"}, + "step must be finite and nonnegative"); + /// Verify that an infinite step is rejected. + FlatZincErrorTest float_infinite_step("Float::InfiniteStep", step_model, {"-step", "inf"}, + "step must be finite and nonnegative"); + /// Verify that a relative step of 1 or more is rejected. + FlatZincErrorTest float_rel_step_one("Float::RelStepOne", step_model, {"-rel-step", "1"}, + "rel-step must be at least 0 and below 1"); + /// Verify that a negative relative step is rejected. + FlatZincErrorTest float_rel_step_negative("Float::RelStepNegative", step_model, {"-rel-step", "-0.1"}, + "rel-step must be at least 0 and below 1"); + /// Verify that a relative step that is not a number is rejected. + FlatZincErrorTest float_rel_step_nan("Float::RelStepNaN", step_model, {"-rel-step", "nan"}, + "rel-step must be at least 0 and below 1"); + + /// Minimize over a domain of a few ulps, searching from the largest values + const char* const few_ulps_model = + "var 1.0..1.0000000000000009: x :: output_var;\n" + "solve :: float_search([x], 0.0, input_order, indomain_reverse_split, complete) minimize x;\n"; + + /// Return whether \a output reports more than one solution and optimality + bool + several_solutions(const std::string& output) { + std::string::size_type first = output.find("----------"); + return (first != std::string::npos) && (output.find("----------", first + 1) != std::string::npos) && + (output.contains("==========")); + } + + /// Verify that a relative step skips improvements of a few ulps. + FlatZincTest float_rel_step("Float::RelStep", few_ulps_model, "x = 1.0;\n----------\n==========\n", true, + {"-rel-step", "1e-6"}); + /// Verify that both steps at 0, the default, keep exact optimization. + FlatZincTest float_step_zero_exact("Float::StepZeroExact", few_ulps_model, "", true, {}, several_solutions); + + /// Optimize a float copy of an integer that improves in steps of 1: + /// improvements must exceed 1000 for the relative step 1e-3. + FlatZincTest float_rel_step_chain_min("Float::RelStepChainMin", + "var 1000000..1001000: y :: output_var;\n" + "var 0.0..2000000.0: x;\n" + "constraint int2float(y, x);\n" + "solve :: int_search([y], input_order, indomain_max, complete) " + "minimize x;\n", + "y = 1001000;\n----------\n==========\n", true, {"-rel-step", "1e-3"}); + /// Verify the chain for a negative objective that is maximized. + FlatZincTest float_rel_step_chain_max("Float::RelStepChainMax", + "var -1001000..-1000000: y :: output_var;\n" + "var -2000000.0..0.0: x;\n" + "constraint int2float(y, x);\n" + "solve :: int_search([y], input_order, indomain_min, complete) " + "maximize x;\n", + "y = -1001000;\n----------\n==========\n", true, {"-rel-step", "1e-3"}); #endif /// Verify integer objective comparison for FlatZinc spaces. @@ -181,7 +232,8 @@ namespace Test::FlatZinc { class FloatObjectiveComparison : public Base { private: static std::unique_ptr - model(const Gecode::FloatVal& v, bool minimize, Gecode::FloatNum step = 0.0) { + model(const Gecode::FloatVal& v, bool minimize, Gecode::FloatNum step = 0.0, + Gecode::FloatNum rel_step = 0.0) { std::stringstream source; source << std::showpoint << std::setprecision(std::numeric_limits::max_digits10) << "var float: x = " << v.min() << "; solve " << (minimize ? "minimize" : "maximize") << " x;\n"; @@ -190,14 +242,15 @@ namespace Test::FlatZinc { if (result) { result->fv[result->opt_var()] = Gecode::FloatVar(*result, v.min(), v.max()); result->step = step; + result->rel_step = rel_step; } return result; } static bool admitted(const Gecode::FloatVal& candidate, const Gecode::FlatZinc::FlatZincSpace& incumbent, bool minimize, - Gecode::FloatNum step) { - std::unique_ptr c = model(candidate, minimize, step); + Gecode::FloatNum step, Gecode::FloatNum rel_step = 0.0) { + std::unique_ptr c = model(candidate, minimize, step, rel_step); c->constrain(incumbent); return c->status() != Gecode::SS_FAILED; } @@ -248,6 +301,28 @@ namespace Test::FlatZinc { if (admitted(FloatVal(10.0), *zero, true, 0.0) || !admitted(FloatVal(9.0), *zero, true, 0.0) || admitted(FloatVal(11.0), *x10, false, 1.0) || !admitted(FloatVal(11.1), *x10, false, 1.0)) return false; + // Neither 1 - 0.1 nor 0.5 + 0.1 is a float. The float nearest to + // each on the improving side improves by more than the step and + // must be admitted; its neighbour towards the incumbent must not. + const FloatVal below = FloatVal(1.0) - 0.1; + const FloatVal above = FloatVal(0.5) + 0.1; + std::unique_ptr m1 = model(1.0, true, 0.1); + std::unique_ptr x05 = model(0.5, false, 0.1); + if (!m1 || !x05 || !(below.min() < below.max()) || !(above.min() < above.max()) || + !admitted(below.min(), *m1, true, 0.1) || admitted(below.max(), *m1, true, 0.1) || + !admitted(above.max(), *x05, false, 0.1) || admitted(above.min(), *x05, false, 0.1)) + return false; + // The relative step 0.5 cuts at -0.5 -/+ 0.25 for a negative + // incumbent, and next to an incumbent at 0. + std::unique_ptr rm = model(-0.5, true, 0.0, 0.5); + std::unique_ptr rx = model(-0.5, false, 0.0, 0.5); + std::unique_ptr r0 = model(0.0, true, 0.0, 0.5); + if (!rm || !rx || !r0 || !admitted(std::nextafter(-0.75, -1.0), *rm, true, 0.0, 0.5) || + admitted(-0.75, *rm, true, 0.0, 0.5) || + !admitted(std::nextafter(-0.25, 0.0), *rx, false, 0.0, 0.5) || + admitted(-0.25, *rx, false, 0.0, 0.5) || + !admitted(std::nextafter(0.0, -1.0), *r0, true, 0.0, 0.5) || admitted(0.0, *r0, true, 0.0, 0.5)) + return false; FloatVal before = m9->fv[m9->opt_var()].val(); FloatVal before_other = m10->fv[m10->opt_var()].val(); @@ -264,6 +339,13 @@ namespace Test::FlatZinc { } catch (const SpaceIncompatibleObjectives&) { // Expected } + std::unique_ptr different_rel_step = model(10.0, true, 1.0, 0.5); + try { + (void)m10->compare(*different_rel_step); + return false; + } catch (const SpaceIncompatibleObjectives&) { + // Expected + } try { (void)m10->compare(*x10); return false; diff --git a/test/float/basic.cpp b/test/float/basic.cpp index 72e90cbc8a..89b8279612 100644 --- a/test/float/basic.cpp +++ b/test/float/basic.cpp @@ -35,9 +35,14 @@ #include "test/float.hh" #include +#include #include +#include #include +#include +#include +#include /// %Tests for basic setup namespace Test::Float::Basic { @@ -119,8 +124,9 @@ namespace Test::Float::Basic { public: /// The cost variable Gecode::FloatVar x; - /// Create space with cost variable in [0,1] - OptimizeSpace() : x(*this, 0.0, 1.0) {} + /// Create space with cost variable in [-1,1], \a step, and \a rel_step + OptimizeSpace(Gecode::FloatNum step = 0.0, Gecode::FloatNum rel_step = 0.0) + : Optimize(step, rel_step), x(*this, -1.0, 1.0) {} /// Constructor for cloning \a s OptimizeSpace(OptimizeSpace& s) : Optimize(s) { x.update(*this, s.x); @@ -137,6 +143,26 @@ namespace Test::Float::Basic { } }; + /// Return whether a space with \a step and \a rel_step whose cost is + /// \a candidate survives constraining by an incumbent with cost + /// \a incumbent + template + static bool + admits(Gecode::FloatNum step, const Gecode::FloatVal& incumbent, const Gecode::FloatVal& candidate, + Gecode::FloatNum rel_step = 0.0) { + using namespace Gecode; + OptimizeSpace best(step, rel_step); + dom(best, best.x, incumbent.min(), incumbent.max()); + if ((best.status() == SS_FAILED) || !best.x.assigned()) + return false; + OptimizeSpace s(step, rel_step); + dom(s, s.x, candidate.min(), candidate.max()); + if (s.status() == SS_FAILED) + return false; + s.constrain(best); + return s.status() != SS_FAILED; + } + /// Test that the MiniModel float cuts prune the incumbent value class OptimizeCut : public Base { private: @@ -167,8 +193,26 @@ namespace Test::Float::Basic { run() override { using namespace Gecode; FloatVal min, max; - return cut(min) && cut(max) && (min.max() < 0.5) && - (max.min() > 0.5); + if (!cut(min) || !cut(max) || (min.max() >= 0.5) || + (max.min() <= 0.5)) + return false; + // An assigned cost one ulp wide that ranks equal to the incumbent + // is no improvement. + const FloatVal half_ulp(0.5, std::nextafter(0.5, 1.0)); + if (admits(0.0, half_ulp, half_ulp) || + admits(0.0, half_ulp, half_ulp)) + return false; + // Neither 1 - 0.1 nor 0.5 + 0.1 is a float. The float nearest to + // each on the improving side improves by more than the step and + // must be admitted; its neighbour towards the incumbent improves + // by less and must be excluded. + const FloatVal below = FloatVal(1.0) - 0.1; + const FloatVal above = FloatVal(0.5) + 0.1; + return (below.min() < below.max()) && (above.min() < above.max()) && + admits(0.1, 1.0, below.min()) && + !admits(0.1, 1.0, below.max()) && + admits(0.1, 0.5, above.max()) && + !admits(0.1, 0.5, above.min()); } }; @@ -213,6 +257,173 @@ namespace Test::Float::Basic { OptimizeCut optimize_cut; ViewCompare view_compare; } // namespace + + /// Test the relative step of the MiniModel float optimization spaces + class OptimizeRelStep : public Base { + private: + /// Return whether a space with \a step and \a rel_step admits the float + /// next to \a limit on the improving side but not \a limit itself, for + /// the incumbent \a incumbent + template + static bool + cuts_at(Gecode::FloatNum step, Gecode::FloatNum rel_step, Gecode::FloatNum incumbent, Gecode::FloatNum limit) { + constexpr bool minimize = std::is_same_v; + const Gecode::FloatNum beyond = std::nextafter(limit, minimize ? -2.0 : 2.0); + return admits(step, incumbent, beyond, rel_step) && + !admits(step, incumbent, limit, rel_step); + } + /// Return whether constructing a space with \a step and \a rel_step + /// throws + template + static bool + rejects(Gecode::FloatNum step, Gecode::FloatNum rel_step) { + try { + OptimizeSpace s(step, rel_step); + } catch (const Gecode::MiniModel::ArgumentOutOfRange&) { + return true; + } + return false; + } + /// Return whether comparing spaces with different relative steps throws + template + static bool + rejects_comparison() { + using namespace Gecode; + OptimizeSpace a(0.0, 0.0), b(0.0, 0.5); + rel(a, a.x, FRT_EQ, 0.5); + rel(b, b.x, FRT_EQ, 0.5); + if ((a.status() == SS_FAILED) || (b.status() == SS_FAILED)) + return false; + try { + (void)a.compare(b); + } catch (const SpaceIncompatibleObjectives&) { + return true; + } + return false; + } + + public: + /// Create and register test + OptimizeRelStep() : Base("Float::Basic::OptimizeRelStep") {} + /// Perform test + bool + run() override { + using namespace Gecode; + using Min = FloatMinimizeSpace; + using Max = FloatMaximizeSpace; + const FloatNum nan = std::numeric_limits::quiet_NaN(); + const FloatNum inf = std::numeric_limits::infinity(); + const FloatVal below = FloatVal(1.0) - 0.1; + // Steps 0 cut next to the incumbent, also at 0. The relative step + // 0.5 cuts at 0.5 -/+ 0.25 for positive and negative incumbents. + // Near 0 the absolute step governs: 0.25 beats 0.5 * 0.125. + // Rounding never excludes an improvement by more than the step. + return cuts_at(0.0, 0.0, 0.5, 0.5) && cuts_at(0.0, 0.0, 0.5, 0.5) && + cuts_at(0.0, 0.0, 0.0, 0.0) && cuts_at(0.0, 0.0, 0.0, 0.0) && + cuts_at(0.0, 0.5, 0.5, 0.25) && cuts_at(0.0, 0.5, 0.5, 0.75) && + cuts_at(0.0, 0.5, -0.5, -0.75) && cuts_at(0.0, 0.5, -0.5, -0.25) && + cuts_at(0.0, 0.5, 0.0, 0.0) && cuts_at(0.0, 0.5, 0.0, 0.0) && + cuts_at(0.25, 0.5, 0.125, -0.125) && cuts_at(0.25, 0.5, -0.125, 0.125) && + admits(0.0, 1.0, below.min(), 0.1) && !admits(0.0, 1.0, below.max(), 0.1) && + rejects(0.0, -0.1) && rejects(0.0, 1.0) && rejects(0.0, nan) && + rejects(0.0, inf) && rejects(inf, 0.0) && rejects(nan, 0.0) && + rejects(-1.0, 0.0) && rejects_comparison() && rejects_comparison(); + } + }; + + /** + * \brief Script optimizing a float copy of an integer in steps of 1 + * + * Minimizing ranges over 10^6 to 10^6 + 1000 and maximizing over the + * negated range, so the exact search finds 1001 ever better solutions. + */ + template + class ChainScript : public Gecode::Driver::ExtractStepOption { + public: + /// Whether the script minimizes + static constexpr bool minimize = std::is_same_v; + /// The integer + Gecode::IntVar y; + /// The cost variable + Gecode::FloatVar x; + /// Create script with the steps of \a opt + ChainScript(const Gecode::Options& opt) + : Gecode::Driver::ExtractStepOption(opt), + y(*this, minimize ? 1000000 : -1001000, minimize ? 1001000 : -1000000), x(*this, -2000000.0, 2000000.0) { + using namespace Gecode; + channel(*this, x, y); + branch(*this, y, minimize ? INT_VAL_MAX() : INT_VAL_MIN()); + } + /// Constructor for cloning \a s + ChainScript(ChainScript& s) : Gecode::Driver::ExtractStepOption(s) { + y.update(*this, s.y); + x.update(*this, s.x); + } + /// Copy during cloning + Gecode::Space* + copy() override { + return new ChainScript(*this); + } + /// Return cost + Gecode::FloatVar + cost() const override { + return x; + } + }; + + /// Test that a relative step from the command line cuts a chain of + /// small improvements short and stays within its distance of the optimum + class OptimizeRelStepChain : public Base { + private: + /// Search with the command-line relative step \a rel_step, and return + /// whether it finds \a min to \a max solutions, the last one within + /// the relative step of the optimum + template + static bool + chain(const std::string& rel_step, int min, int max) { + using namespace Gecode; + std::vector arguments = {"chain", "-rel-step", rel_step}; + std::vector argv; + argv.reserve(arguments.size()); + for (std::string& argument : arguments) + argv.push_back(argument.data()); + int argc = static_cast(argv.size()); + Gecode::Options opt("chain"); + opt.parse(argc, argv.data()); + ChainScript root(opt); + BAB> engine(&root); + int found = 0; + FloatNum last = 0.0; + while (ChainScript* s = engine.next()) { + last = s->y.val(); + found++; + delete s; + } + const FloatNum optimum = ChainScript::minimize ? 1000000.0 : -1000000.0; + return (engine.end_reason() == Search::EndReason::Exhausted) && (found >= min) && (found <= max) && + (std::abs(last - optimum) <= opt.rel_step() * std::abs(last)); + } + + public: + /// Create and register test + OptimizeRelStepChain() : Base("Float::Basic::OptimizeRelStepChain") {} + /// Perform test + bool + run() override { + using namespace Gecode; + // Each improvement must exceed 1 for 1e-6, 100 for 1e-4, and 1000 + // for 1e-3. + return chain("0", 1001, 1001) && chain("0", 1001, 1001) && + chain("1e-6", 501, 501) && chain("1e-4", 10, 10) && + chain("1e-4", 10, 10) && chain("1e-3", 1, 1) && + chain("1e-3", 1, 1); + } + }; + + namespace { + OptimizeRelStep optimize_rel_step; + OptimizeRelStepChain optimize_rel_step_chain; + } // namespace //@} } // namespace Test::Float::Basic diff --git a/tools/flatzinc/gecode-gist.msc.in b/tools/flatzinc/gecode-gist.msc.in index 9907ace10f..fb0080562b 100644 --- a/tools/flatzinc/gecode-gist.msc.in +++ b/tools/flatzinc/gecode-gist.msc.in @@ -23,7 +23,9 @@ ["--restart-scale", "Scale factor for restart sequence", "int", "250"], ["--restart-limit", "Restart cutoff", "int", "0"], ["--nogoods", "Use no-goods from restarts", "bool", "false"], - ["--nogoods-limit", "Depth limit for no-good extraction", "int", "128"] + ["--nogoods-limit", "Depth limit for no-good extraction", "int", "128"], + ["--step", "Absolute improvement step for float objectives", "float", "0"], + ["--rel-step", "Improvement step relative to the float objective", "float", "0"] ], "supportsMzn": false, "supportsFzn": true, diff --git a/tools/flatzinc/gecode.msc.in b/tools/flatzinc/gecode.msc.in index 5e04d5e85c..55c2388264 100644 --- a/tools/flatzinc/gecode.msc.in +++ b/tools/flatzinc/gecode.msc.in @@ -23,7 +23,9 @@ ["--restart-scale", "Scale factor for restart sequence", "int", "250"], ["--restart-limit", "Restart cutoff", "int", "0"], ["--nogoods", "Use no-goods from restarts", "bool", "false"], - ["--nogoods-limit", "Depth limit for no-good extraction", "int", "128"] + ["--nogoods-limit", "Depth limit for no-good extraction", "int", "128"], + ["--step", "Absolute improvement step for float objectives", "float", "0"], + ["--rel-step", "Improvement step relative to the float objective", "float", "0"] ], "supportsMzn": false, "supportsFzn": true,