Google OR-Tools v9.11
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-2024 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
22#include "ortools/base/types.h"
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"
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.
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 // Adds the given variable to var_ordering_ or updates its priority if it is
137 // already present.
138 void PqInsertOrUpdate(BooleanVariable var);
139
140 // Singleton model objects.
141 const SatParameters& parameters_;
142 const Trail& trail_;
143 ModelRandomGenerator* random_;
144
145 // Variable ordering (priority will be adjusted dynamically). queue_elements_
146 // holds the elements used by var_ordering_ (it uses pointers).
147 //
148 // Note that we recover the variable that a WeightedVarQueueElement refers to
149 // by its position in the queue_elements_ vector, and we can recover the later
150 // using (pointer - &queue_elements_[0]).
151 struct WeightedVarQueueElement {
152 // Interface for the IntegerPriorityQueue.
153 int Index() const { return var.value(); }
154
155 // Priority order. The IntegerPriorityQueue returns the largest element
156 // first.
157 //
158 // Note(user): We used to also break ties using the variable index, however
159 // this has two drawbacks:
160 // - On problem with many variables, this slow down quite a lot the priority
161 // queue operations (which do as little work as possible and hence benefit
162 // from having the majority of elements with a priority of 0).
163 // - It seems to be a bad heuristics. One reason could be that the priority
164 // queue will automatically diversify the choice of the top variables
165 // amongst the ones with the same priority.
166 //
167 // Note(user): For the same reason as explained above, it is probably a good
168 // idea not to have too many different values for the tie_breaker field. I
169 // am not even sure we should have such a field...
170 bool operator<(const WeightedVarQueueElement& other) const {
171 return weight < other.weight ||
172 (weight == other.weight && (tie_breaker < other.tie_breaker));
173 }
174
175 BooleanVariable var;
176 float tie_breaker;
177
178 // TODO(user): Experiment with float. In the rest of the code, we use
179 // double, but maybe we don't need that much precision. Using float here may
180 // save memory and make the PQ operations faster.
181 double weight;
182 };
183 static_assert(sizeof(WeightedVarQueueElement) == 16,
184 "ERROR_WeightedVarQueueElement_is_not_well_compacted");
185
186 bool var_ordering_is_initialized_ = false;
187 IntegerPriorityQueue<WeightedVarQueueElement> var_ordering_;
188
189 // This is used for the branching heuristic described in "Learning Rate Based
190 // Branching Heuristic for SAT solvers", J.H.Liang, V. Ganesh, P. Poupart,
191 // K.Czarnecki, SAT 2016.
192 //
193 // The entries are sorted by trail index, and one can get the number of
194 // conflicts during which a variable at a given trail index i was assigned by
195 // summing the entry.count for all entries with a trail index greater than i.
196 struct NumConflictsStackEntry {
197 int trail_index;
198 int64_t count;
199 };
200 int64_t num_conflicts_ = 0;
201 std::vector<NumConflictsStackEntry> num_conflicts_stack_;
202
203 // Whether the priority of the given variable needs to be updated in
204 // var_ordering_. Note that this is only accessed for assigned variables and
205 // that for efficiency it is indexed by trail indices. If
206 // pq_need_update_for_var_at_trail_index_[trail_->Info(var).trail_index] is
207 // true when we untrail var, then either var need to be inserted in the queue,
208 // or we need to notify that its priority has changed.
209 BitQueue64 pq_need_update_for_var_at_trail_index_;
210
211 // Increment used to bump the variable activities.
212 double variable_activity_increment_ = 1.0;
213
214 // Stores variable activity and the number of time each variable was "bumped".
215 // The later is only used with the ERWA heuristic.
219
220 // If the polarity if forced (externally) we always use this first.
223
224 // If we are in a stable phase, we follow the current target.
225 bool in_stable_phase_ = false;
226 int target_length_ = 0;
229
230 // Otherwise we follow var_polarity_ which is reset at the beginning of
231 // each new polarity phase. This is also overwritten by phase saving.
232 // Each phase last for an arithmetically increasing number of conflicts.
234 bool maybe_enable_phase_saving_ = true;
235 int64_t polarity_phase_ = 0;
236 int64_t num_conflicts_until_rephase_ = 1000;
237
238 // The longest partial assignment since the last reset.
239 std::vector<Literal> best_partial_assignment_;
240
241 // Used in InitializeVariableOrdering().
242 std::vector<BooleanVariable> tmp_variables_;
243};
244
245} // namespace sat
246} // namespace operations_research
247
248#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.
IntVar * var
GRBmodel * model
int literal
In SWIG mode, we don't want anything besides these top-level includes.
int64_t weight
Definition pack.cc:510