OR-Tools  9.3
sat_decision.h
Go to the documentation of this file.
1// Copyright 2010-2021 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#ifndef OR_TOOLS_SAT_SAT_DECISION_H_
15#define OR_TOOLS_SAT_SAT_DECISION_H_
16
17#include <cstdint>
18#include <utility>
19#include <vector>
20
23#include "ortools/sat/model.h"
26#include "ortools/sat/sat_parameters.pb.h"
27#include "ortools/sat/util.h"
28#include "ortools/util/bitset.h"
30
31namespace operations_research {
32namespace sat {
33
34// Implement the SAT branching policy responsible for deciding the next Boolean
35// variable to branch on, and its polarity (true or false).
37 public:
38 explicit SatDecisionPolicy(Model* model);
39
40 // Notifies that more variables are now present. Note that currently this may
41 // change the current variable order because the priority queue need to be
42 // reconstructed.
43 void IncreaseNumVariables(int num_variables);
44
45 // Reinitializes the decision heuristics (which variables to choose with which
46 // polarity) according to the current parameters. Note that this also resets
47 // the activity of the variables to 0. Note that this function is lazy, and
48 // the work will only happen on the first NextBranch() to cover the cases when
49 // this policy is not used at all.
51
52 // Returns next decision to branch upon. This shouldn't be called if all the
53 // variables are assigned.
55
56 // Updates statistics about literal occurences in constraints.
57 // Input is a canonical linear constraint of the form (terms <= rhs).
58 void UpdateWeightedSign(const std::vector<LiteralWithCoeff>& terms,
59 Coefficient rhs);
60
61 // Bumps the activity of all variables appearing in the conflict. All literals
62 // must be currently assigned. See VSIDS decision heuristic: Chaff:
63 // Engineering an Efficient SAT Solver. M.W. Moskewicz et al. ANNUAL ACM IEEE
64 // DESIGN AUTOMATION CONFERENCE 2001.
65 void BumpVariableActivities(const std::vector<Literal>& literals);
66
67 // Updates the increment used for activity bumps. This is basically the same
68 // as decaying all the variable activities, but it is a lot more efficient.
70
71 // Called on Untrail() so that we can update the set of possible decisions.
72 void Untrail(int target_trail_index);
73
74 // Called on a new conflict before Untrail(). The trail before the given index
75 // is used in the phase saving heuristic as a partial assignment.
76 void BeforeConflict(int trail_index);
77
78 // By default, we alternate between a stable phase (better suited for finding
79 // SAT solution) and a more restart heavy phase more suited for proving UNSAT.
80 // This changes a bit the polarity heuristics and is controlled from within
81 // SatRestartPolicy.
82 void SetStablePhase(bool is_stable) { in_stable_phase_ = is_stable; }
83 bool InStablePhase() const { return in_stable_phase_; }
84
85 // This is used to temporarily disable phase_saving when we do some probing
86 // during search for instance.
87 void MaybeEnablePhaseSaving(bool save_phase) {
88 maybe_enable_phase_saving_ = save_phase;
89 }
90
91 // Gives a hint so the solver tries to find a solution with the given literal
92 // set to true. Currently this take precedence over the phase saving heuristic
93 // and a variable with a preference will always be branched on according to
94 // this preference.
95 //
96 // The weight is used as a tie-breaker between variable with the same
97 // activities. Larger weight will be selected first. A weight of zero is the
98 // default value for the other variables.
99 //
100 // Note(user): Having a lot of different weights may slow down the priority
101 // queue operations if there is millions of variables.
103
104 // Returns the vector of the current assignment preferences.
105 std::vector<std::pair<Literal, double>> AllPreferences() const;
106
107 private:
108 // Computes an initial variable ordering.
109 void InitializeVariableOrdering();
110
111 // Rescales activity value of all variables when one of them reached the max.
112 void RescaleVariableActivities(double scaling_factor);
113
114 // Reinitializes the inital polarity of all the variables with an index
115 // greater than or equal to the given one.
116 void ResetInitialPolarity(int from, bool inverted = false);
117
118 // Code used for resetting the initial polarity at the beginning of each
119 // phase.
120 void RephaseIfNeeded();
121 void UseLongestAssignmentAsInitialPolarity();
122 void FlipCurrentPolarity();
123 void RandomizeCurrentPolarity();
124
125 // Adds the given variable to var_ordering_ or updates its priority if it is
126 // already present.
127 void PqInsertOrUpdate(BooleanVariable var);
128
129 // Singleton model objects.
130 const SatParameters& parameters_;
131 const Trail& trail_;
132 ModelRandomGenerator* random_;
133
134 // Variable ordering (priority will be adjusted dynamically). queue_elements_
135 // holds the elements used by var_ordering_ (it uses pointers).
136 //
137 // Note that we recover the variable that a WeightedVarQueueElement refers to
138 // by its position in the queue_elements_ vector, and we can recover the later
139 // using (pointer - &queue_elements_[0]).
140 struct WeightedVarQueueElement {
141 // Interface for the IntegerPriorityQueue.
142 int Index() const { return var.value(); }
143
144 // Priority order. The IntegerPriorityQueue returns the largest element
145 // first.
146 //
147 // Note(user): We used to also break ties using the variable index, however
148 // this has two drawbacks:
149 // - On problem with many variables, this slow down quite a lot the priority
150 // queue operations (which do as little work as possible and hence benefit
151 // from having the majority of elements with a priority of 0).
152 // - It seems to be a bad heuristics. One reason could be that the priority
153 // queue will automatically diversify the choice of the top variables
154 // amongst the ones with the same priority.
155 //
156 // Note(user): For the same reason as explained above, it is probably a good
157 // idea not to have too many different values for the tie_breaker field. I
158 // am not even sure we should have such a field...
159 bool operator<(const WeightedVarQueueElement& other) const {
160 return weight < other.weight ||
161 (weight == other.weight && (tie_breaker < other.tie_breaker));
162 }
163
164 BooleanVariable var;
165 float tie_breaker;
166
167 // TODO(user): Experiment with float. In the rest of the code, we use
168 // double, but maybe we don't need that much precision. Using float here may
169 // save memory and make the PQ operations faster.
170 double weight;
171 };
172 static_assert(sizeof(WeightedVarQueueElement) == 16,
173 "ERROR_WeightedVarQueueElement_is_not_well_compacted");
174
175 bool var_ordering_is_initialized_ = false;
176 IntegerPriorityQueue<WeightedVarQueueElement> var_ordering_;
177
178 // This is used for the branching heuristic described in "Learning Rate Based
179 // Branching Heuristic for SAT solvers", J.H.Liang, V. Ganesh, P. Poupart,
180 // K.Czarnecki, SAT 2016.
181 //
182 // The entries are sorted by trail index, and one can get the number of
183 // conflicts during which a variable at a given trail index i was assigned by
184 // summing the entry.count for all entries with a trail index greater than i.
185 struct NumConflictsStackEntry {
186 int trail_index;
187 int64_t count;
188 };
189 int64_t num_conflicts_ = 0;
190 std::vector<NumConflictsStackEntry> num_conflicts_stack_;
191
192 // Whether the priority of the given variable needs to be updated in
193 // var_ordering_. Note that this is only accessed for assigned variables and
194 // that for efficiency it is indexed by trail indices. If
195 // pq_need_update_for_var_at_trail_index_[trail_->Info(var).trail_index] is
196 // true when we untrail var, then either var need to be inserted in the queue,
197 // or we need to notify that its priority has changed.
198 BitQueue64 pq_need_update_for_var_at_trail_index_;
199
200 // Increment used to bump the variable activities.
201 double variable_activity_increment_ = 1.0;
202
203 // Stores variable activity and the number of time each variable was "bumped".
204 // The later is only used with the ERWA heuristic.
208
209 // If the polarity if forced (externally) we alway use this first.
212
213 // If we are in a stable phase, we follow the current target.
214 bool in_stable_phase_ = false;
215 int target_length_ = 0;
218
219 // Otherwise we follow var_polarity_ which is reset at the beginning of
220 // each new polarity phase. This is also overwritten by phase saving.
221 // Each phase last for an arithmetically increasing number of conflicts.
223 bool maybe_enable_phase_saving_ = true;
224 int64_t polarity_phase_ = 0;
225 int64_t num_conflicts_until_rephase_ = 1000;
226
227 // The longest partial assignment since the last reset.
228 std::vector<Literal> best_partial_assignment_;
229
230 // Used in initial polarity computation.
232
233 // Used in InitializeVariableOrdering().
234 std::vector<BooleanVariable> tmp_variables_;
235};
236
237} // namespace sat
238} // namespace operations_research
239
240#endif // OR_TOOLS_SAT_SAT_DECISION_H_
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:42
std::vector< std::pair< Literal, double > > AllPreferences() const
void IncreaseNumVariables(int num_variables)
Definition: sat_decision.cc:41
void SetAssignmentPreference(Literal literal, double weight)
void MaybeEnablePhaseSaving(bool save_phase)
Definition: sat_decision.h:87
void Untrail(int target_trail_index)
void BumpVariableActivities(const std::vector< Literal > &literals)
void UpdateWeightedSign(const std::vector< LiteralWithCoeff > &terms, Coefficient rhs)
IntVar * var
Definition: expr_array.cc:1874
GRBmodel * model
std::tuple< int64_t, int64_t, const double > Coefficient
Collection of objects used to extend the Constraint Solver library.
Literal literal
Definition: optimization.cc:89
int64_t weight
Definition: pack.cc:510