Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
sat_decision.h
Go to the documentation of this file.
1// Copyright 2010-2025 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
21#include "absl/types/span.h"
23#include "ortools/sat/model.h"
25#include "ortools/sat/sat_parameters.pb.h"
27#include "ortools/sat/util.h"
28#include "ortools/util/bitset.h"
31
32namespace operations_research {
33namespace sat {
34
35// Implement the SAT branching policy responsible for deciding the next Boolean
36// variable to branch on, and its polarity (true or false).
38 public:
39 explicit SatDecisionPolicy(Model* model);
40
41 // Notifies that more variables are now present. Note that currently this may
42 // change the current variable order because the priority queue need to be
43 // reconstructed.
44 void IncreaseNumVariables(int num_variables);
45
46 // Reinitializes the decision heuristics (which variables to choose with which
47 // polarity) according to the current parameters. Note that this also resets
48 // the activity of the variables to 0. Note that this function is lazy, and
49 // the work will only happen on the first NextBranch() to cover the cases when
50 // this policy is not used at all.
52
53 // Returns next decision to branch upon. This shouldn't be called if all the
54 // variables are assigned.
56
57 // Bumps the activity of all variables appearing in the conflict. All literals
58 // must be currently assigned. See VSIDS decision heuristic: Chaff:
59 // Engineering an Efficient SAT Solver. M.W. Moskewicz et al. ANNUAL ACM IEEE
60 // DESIGN AUTOMATION CONFERENCE 2001.
61 void BumpVariableActivities(absl::Span<const Literal> literals);
62
63 // Updates the increment used for activity bumps. This is basically the same
64 // as decaying all the variable activities, but it is a lot more efficient.
66
67 // Called on Untrail() so that we can update the set of possible decisions.
68 void Untrail(int target_trail_index);
69
70 // Called on a new conflict before Untrail(). The trail before the given index
71 // is used in the phase saving heuristic as a partial assignment.
72 void BeforeConflict(int trail_index);
73
74 // By default, we alternate between a stable phase (better suited for finding
75 // SAT solution) and a more restart heavy phase more suited for proving UNSAT.
76 // This changes a bit the polarity heuristics and is controlled from within
77 // SatRestartPolicy.
78 void SetStablePhase(bool is_stable) { in_stable_phase_ = is_stable; }
79 bool InStablePhase() const { return in_stable_phase_; }
80
81 // This is used to temporarily disable phase_saving when we do some probing
82 // during search for instance.
83 void MaybeEnablePhaseSaving(bool save_phase) {
84 maybe_enable_phase_saving_ = save_phase;
85 }
86
87 // Gives a hint so the solver tries to find a solution with the given literal
88 // set to true. Currently this take precedence over the phase saving heuristic
89 // and a variable with a preference will always be branched on according to
90 // this preference.
91 //
92 // The weight is used as a tie-breaker between variable with the same
93 // activities. Larger weight will be selected first. A weight of zero is the
94 // default value for the other variables.
95 //
96 // Note(user): Having a lot of different weights may slow down the priority
97 // queue operations if there is millions of variables.
98 void SetAssignmentPreference(Literal literal, float weight);
99
100 // Returns the vector of the current assignment preferences.
101 std::vector<std::pair<Literal, float>> AllPreferences() const;
102
103 // Returns the current activity of a BooleanVariable.
104 double Activity(Literal l) const {
105 if (l.Variable() < activities_.size()) return activities_[l.Variable()];
106 return 0.0;
107 }
108
109 // Like SetAssignmentPreference() but it can be overridden by phase-saving.
111 var_polarity_[l.Variable()] = l.IsPositive();
112 }
113 absl::Span<const Literal> GetBestPartialAssignment() const {
114 return best_partial_assignment_;
115 }
116 void ClearBestPartialAssignment() { best_partial_assignment_.clear(); }
117
118 private:
119 // Computes an initial variable ordering.
120 void InitializeVariableOrdering();
121
122 // Rescales activity value of all variables when one of them reached the max.
123 void RescaleVariableActivities(double scaling_factor);
124
125 // Reinitializes the initial polarity of all the variables with an index
126 // greater than or equal to the given one.
127 void ResetInitialPolarity(int from, bool inverted = false);
128
129 // Code used for resetting the initial polarity at the beginning of each
130 // phase.
131 void RephaseIfNeeded();
132 void UseLongestAssignmentAsInitialPolarity();
133 void FlipCurrentPolarity();
134 void RandomizeCurrentPolarity();
135
136 // This one returns false if there is no such solution to use.
137 bool UseLsSolutionAsInitialPolarity();
138
139 // Adds the given variable to var_ordering_ or updates its priority if it is
140 // already present.
141 void PqInsertOrUpdate(BooleanVariable var);
142
143 // Singleton model objects.
144 const SatParameters& parameters_;
145 const Trail& trail_;
146 ModelRandomGenerator* random_;
147
148 // TODO(user): This is in term of proto indices. Ideally we would need
149 // CpModelMapping to map that to Booleans but this currently lead to cyclic
150 // dependencies. For now we just assume one to one correspondence for the
151 // first entries. This will only work on pure Boolean problems.
153
154 // Variable ordering (priority will be adjusted dynamically). queue_elements_
155 // holds the elements used by var_ordering_ (it uses pointers).
156 //
157 // Note that we recover the variable that a WeightedVarQueueElement refers to
158 // by its position in the queue_elements_ vector, and we can recover the later
159 // using (pointer - &queue_elements_[0]).
160 struct WeightedVarQueueElement {
161 // Interface for the IntegerPriorityQueue.
162 int Index() const { return var.value(); }
163
164 // Priority order. The IntegerPriorityQueue returns the largest element
165 // first.
166 //
167 // Note(user): We used to also break ties using the variable index, however
168 // this has two drawbacks:
169 // - On problem with many variables, this slow down quite a lot the priority
170 // queue operations (which do as little work as possible and hence benefit
171 // from having the majority of elements with a priority of 0).
172 // - It seems to be a bad heuristics. One reason could be that the priority
173 // queue will automatically diversify the choice of the top variables
174 // amongst the ones with the same priority.
175 //
176 // Note(user): For the same reason as explained above, it is probably a good
177 // idea not to have too many different values for the tie_breaker field. I
178 // am not even sure we should have such a field...
179 bool operator<(const WeightedVarQueueElement& other) const {
180 return weight < other.weight ||
181 (weight == other.weight && (tie_breaker < other.tie_breaker));
182 }
183
184 BooleanVariable var;
185 float tie_breaker;
186
187 // TODO(user): Experiment with float. In the rest of the code, we use
188 // double, but maybe we don't need that much precision. Using float here may
189 // save memory and make the PQ operations faster.
190 double weight;
191 };
192 static_assert(sizeof(WeightedVarQueueElement) == 16,
193 "ERROR_WeightedVarQueueElement_is_not_well_compacted");
194
195 bool var_ordering_is_initialized_ = false;
196 IntegerPriorityQueue<WeightedVarQueueElement> var_ordering_;
197
198 // This is used for the branching heuristic described in "Learning Rate Based
199 // Branching Heuristic for SAT solvers", J.H.Liang, V. Ganesh, P. Poupart,
200 // K.Czarnecki, SAT 2016.
201 //
202 // The entries are sorted by trail index, and one can get the number of
203 // conflicts during which a variable at a given trail index i was assigned by
204 // summing the entry.count for all entries with a trail index greater than i.
205 struct NumConflictsStackEntry {
206 int trail_index;
207 int64_t count;
208 };
209 int64_t num_conflicts_ = 0;
210 std::vector<NumConflictsStackEntry> num_conflicts_stack_;
211
212 // Whether the priority of the given variable needs to be updated in
213 // var_ordering_. Note that this is only accessed for assigned variables and
214 // that for efficiency it is indexed by trail indices. If
215 // pq_need_update_for_var_at_trail_index_[trail_->Info(var).trail_index] is
216 // true when we untrail var, then either var need to be inserted in the queue,
217 // or we need to notify that its priority has changed.
218 BitQueue64 pq_need_update_for_var_at_trail_index_;
219
220 // Increment used to bump the variable activities.
221 double variable_activity_increment_ = 1.0;
222
223 // Stores variable activity and the number of time each variable was "bumped".
224 // The later is only used with the ERWA heuristic.
225 util_intops::StrongVector<BooleanVariable, double> activities_;
226 util_intops::StrongVector<BooleanVariable, float> tie_breakers_;
227 util_intops::StrongVector<BooleanVariable, int64_t> num_bumps_;
228
229 // If the polarity if forced (externally) we always use this first.
230 util_intops::StrongVector<BooleanVariable, bool> has_forced_polarity_;
231 util_intops::StrongVector<BooleanVariable, bool> forced_polarity_;
232
233 // If we are in a stable phase, we follow the current target.
234 bool in_stable_phase_ = false;
235 int target_length_ = 0;
236 util_intops::StrongVector<BooleanVariable, bool> has_target_polarity_;
237 util_intops::StrongVector<BooleanVariable, bool> target_polarity_;
238
239 // Otherwise we follow var_polarity_ which is reset at the beginning of
240 // each new polarity phase. This is also overwritten by phase saving.
241 // Each phase last for an arithmetically increasing number of conflicts.
242 util_intops::StrongVector<BooleanVariable, bool> var_polarity_;
243 bool maybe_enable_phase_saving_ = true;
244 int64_t polarity_phase_ = 0;
245 int64_t num_conflicts_until_rephase_ = 1000;
246
247 // The longest partial assignment since the last reset.
248 std::vector<Literal> best_partial_assignment_;
249
250 // Used in InitializeVariableOrdering().
251 std::vector<BooleanVariable> tmp_variables_;
252};
253
254} // namespace sat
255} // namespace operations_research
256
257#endif // OR_TOOLS_SAT_SAT_DECISION_H_
BooleanVariable Variable() const
Definition sat_base.h:87
void BumpVariableActivities(absl::Span< const Literal > literals)
std::vector< std::pair< Literal, float > > AllPreferences() const
Returns the vector of the current assignment preferences.
void SetAssignmentPreference(Literal literal, float weight)
void SetTargetPolarity(Literal l)
Like SetAssignmentPreference() but it can be overridden by phase-saving.
double Activity(Literal l) const
Returns the current activity of a BooleanVariable.
absl::Span< const Literal > GetBestPartialAssignment() const
void Untrail(int target_trail_index)
Called on Untrail() so that we can update the set of possible decisions.
In SWIG mode, we don't want anything besides these top-level includes.