Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
CpSolver.cs
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
14using System;
15using System.Collections.Generic;
16using System.Runtime.CompilerServices;
17
18namespace Google.OrTools.Sat
19{
29public class CpSolver
30{
33 {
34 // Setup search.
35 CreateSolveWrapper();
36 if (string_parameters_ is not null)
37 {
38 solve_wrapper_.SetStringParameters(string_parameters_);
39 }
40 if (log_callback_ is not null)
41 {
42 solve_wrapper_.AddLogCallbackFromClass(log_callback_);
43 }
44 if (best_bound_callback_ is not null)
45 {
46 solve_wrapper_.AddBestBoundCallbackFromClass(best_bound_callback_);
47 }
48 if (cb is not null)
49 {
50 solve_wrapper_.AddSolutionCallback(cb);
51 }
52
53 response_ = solve_wrapper_.Solve(model.Model);
54
55 // Cleanup search.
56 if (cb is not null)
57 {
58 solve_wrapper_.ClearSolutionCallback(cb);
59 }
60 ReleaseSolveWrapper();
61
62 return response_.Status;
63 }
64
66 [ObsoleteAttribute("This method is obsolete. Call Solve instead.", false)]
68 {
69 return Solve(model, cb);
70 }
71
73 [ObsoleteAttribute("This method is obsolete. Call Solve instead with the enumerate_all_solutions parameter.",
74 false)]
76 {
77 string old_parameters = string_parameters_;
78 string_parameters_ += " enumerate_all_solutions:true";
79 Solve(model, cb);
80 string_parameters_ = old_parameters;
81 return response_.Status;
82 }
83
85 [MethodImpl(MethodImplOptions.Synchronized)]
86 public void StopSearch()
87 {
88 if (solve_wrapper_ is not null)
89 {
90 solve_wrapper_.StopSearch();
91 }
92 }
93
94 [MethodImpl(MethodImplOptions.Synchronized)]
95 private void CreateSolveWrapper()
96 {
97 solve_wrapper_ = new SolveWrapper();
98 }
99
100 [MethodImpl(MethodImplOptions.Synchronized)]
101 private void ReleaseSolveWrapper()
102 {
103 solve_wrapper_ = null;
104 }
105
107 public String ResponseStats()
108 {
109 return CpSatHelper.SolverResponseStats(response_);
110 }
111
113 public double ObjectiveValue
114 {
115 get {
116 return response_.ObjectiveValue;
117 }
118 }
119
125 public double BestObjectiveBound
126 {
127 get {
128 return response_.BestObjectiveBound;
129 }
130 }
131
133 public string StringParameters
134 {
135 get {
136 return string_parameters_;
137 }
138 set {
139 string_parameters_ = value;
140 }
141 }
142
144 {
145 log_callback_ = new LogCallbackDelegate(del);
146 }
147
148 public void ClearLogCallback()
149 {
150 log_callback_ = null;
151 }
152
154 {
155 best_bound_callback_ = new BestBoundCallbackDelegate(del);
156 }
157
159 {
160 best_bound_callback_ = null;
161 }
162
164 {
165 get {
166 return response_;
167 }
168 }
169
175 public long Value(IntVar intVar)
176 {
177 int index = intVar.GetIndex();
178 long value = index >= 0 ? response_.Solution[index] : -response_.Solution[-index - 1];
179 return value;
180 }
181
187 public long Value(LinearExpr e)
188 {
189 long constant = 0;
190 long coefficient = 1;
191 LinearExpr expr = e;
192 if (terms_ is null)
193 {
194 terms_ = new Queue<Term>();
195 }
196 else
197 {
198 terms_.Clear();
199 }
200
201 do
202 {
203 switch (expr)
204 {
205 case LinearExprBuilder a:
206 constant += coefficient * a.Offset;
207 if (coefficient == 1)
208 {
209 foreach (Term sub in a.Terms)
210 {
211 terms_.Enqueue(sub);
212 }
213 }
214 else
215 {
216 foreach (Term sub in a.Terms)
217 {
218 terms_.Enqueue(new Term(sub.expr, sub.coefficient * coefficient));
219 }
220 }
221 break;
222 case IntVar intVar:
223 int index = intVar.GetIndex();
224 long value = index >= 0 ? response_.Solution[index] : -response_.Solution[-index - 1];
225 constant += coefficient * value;
226 break;
227 case NotBoolVar:
228 throw new ArgumentException("Cannot evaluate a literal in an integer expression.");
229 default:
230 throw new ArgumentException("Cannot evaluate '" + expr + "' in an integer expression");
231 }
232
233 if (!terms_.TryDequeue(out var term))
234 {
235 break;
236 }
237 expr = term.expr;
238 coefficient = term.coefficient;
239 } while (true);
240
241 return constant;
242 }
243
249 public Boolean BooleanValue(ILiteral literal)
250 {
251 if (literal is BoolVar || literal is NotBoolVar)
252 {
253 int index = literal.GetIndex();
254 if (index >= 0)
255 {
256 return response_.Solution[index] != 0;
257 }
258 else
259 {
260 return response_.Solution[-index - 1] == 0;
261 }
262 }
263 else
264 {
265 throw new ArgumentException("Cannot evaluate '" + literal.ToString() + "' as a boolean literal");
266 }
267 }
268
270 public long NumBranches()
271 {
272 return response_.NumBranches;
273 }
274
276 public long NumConflicts()
277 {
278 return response_.NumConflicts;
279 }
280
282 public double WallTime()
283 {
284 return response_.WallTime;
285 }
286
288 {
289 return response_.SufficientAssumptionsForInfeasibility;
290 }
291
298 public String SolutionInfo()
299 {
300 return response_.SolutionInfo;
301 }
302
303 private CpSolverResponse response_;
304 private LogCallback log_callback_;
305 private BestBoundCallback best_bound_callback_;
306 private string string_parameters_;
307 private SolveWrapper solve_wrapper_;
308 private Queue<Term> terms_;
309}
310
311class LogCallbackDelegate : LogCallback
312{
314 {
315 this.delegate_ = del;
316 }
317
318 public override void NewMessage(string message)
319 {
320 delegate_(message);
321 }
322
323 private StringToVoidDelegate delegate_;
324}
325
326class BestBoundCallbackDelegate : BestBoundCallback
327{
329 {
330 this.delegate_ = del;
331 }
332
333 public override void NewBestBound(double bound)
334 {
335 delegate_(bound);
336 }
337
338 private DoubleToVoidDelegate delegate_;
339}
340
341} // namespace Google.OrTools.Sat
override void NewBestBound(double bound)
Definition CpSolver.cs:333
BestBoundCallbackDelegate(DoubleToVoidDelegate del)
Definition CpSolver.cs:328
Holds a Boolean variable.
Wrapper class around the cp_model proto.
Definition CpModel.cs:24
CpModelProto Model
Getters.
Definition CpModel.cs:41
static string SolverResponseStats(Google.OrTools.Sat.CpSolverResponse response)
The response returned by a solver trying to solve a CpModelProto.
Wrapper around the SAT solver.
Definition CpSolver.cs:30
String SolutionInfo()
Returns some information on how the solution was found, or the reason why the model or the parameters...
Definition CpSolver.cs:298
double ObjectiveValue
The best objective value found during search.
Definition CpSolver.cs:114
long Value(IntVar intVar)
Returns the value of an integer variable in the last solution found.
Definition CpSolver.cs:175
long NumBranches()
Returns the number of branches explored during search.
Definition CpSolver.cs:270
void SetBestBoundCallback(DoubleToVoidDelegate del)
Definition CpSolver.cs:153
CpSolverStatus SearchAllSolutions(CpModel model, SolutionCallback cb)
Deprecated, use Solve() instead.
Definition CpSolver.cs:75
IList< int > SufficientAssumptionsForInfeasibility()
Definition CpSolver.cs:287
long NumConflicts()
Returns the number of conflicts created during search.
Definition CpSolver.cs:276
void StopSearch()
Stops the search asynchronously.
Definition CpSolver.cs:86
double WallTime()
Returns the wall time of the search.
Definition CpSolver.cs:282
CpSolverStatus Solve(CpModel model, SolutionCallback cb=null)
Solves the given model, and returns the solve status.
Definition CpSolver.cs:32
double BestObjectiveBound
The best lower bound found when minimizing, of the best upper bound found when maximizing.
Definition CpSolver.cs:126
CpSolverResponse Response
Definition CpSolver.cs:164
Boolean BooleanValue(ILiteral literal)
Returns the Boolean value of a literal in the last solution found.
Definition CpSolver.cs:249
CpSolverStatus SolveWithSolutionCallback(CpModel model, SolutionCallback cb)
Deprecated, use Solve() instead.
Definition CpSolver.cs:67
long Value(LinearExpr e)
Returns the value of a linear expression in the last solution found.
Definition CpSolver.cs:187
void SetLogCallback(StringToVoidDelegate del)
Definition CpSolver.cs:143
String ResponseStats()
Statistics on the solution found as a string.
Definition CpSolver.cs:107
Holds a integer variable with a discrete domain.
A builder class for linear expressions.
Holds a linear expression: sum (ai * xi) + b.
LogCallbackDelegate(StringToVoidDelegate del)
Definition CpSolver.cs:313
override void NewMessage(string message)
Definition CpSolver.cs:318
Holds a Boolean variable or its negation.
int GetIndex()
Returns the logical index of the literal.
CpSolverStatus
The status returned by a solver trying to solve a CpModelProto.
delegate void DoubleToVoidDelegate(double bound)
Used to wrap best bound callbacks (std::function<void(double>)
delegate void StringToVoidDelegate(string message)
Used to wrap log callbacks (std::function<void(const std::string&>)
Holds a term (expression * coefficient)