OR-Tools  8.1
sat/lp_utils.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 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 #include "ortools/sat/lp_utils.h"
15 
16 #include <stdlib.h>
17 
18 #include <algorithm>
19 #include <cmath>
20 #include <limits>
21 #include <string>
22 #include <vector>
23 
24 #include "absl/strings/str_cat.h"
25 #include "ortools/base/int_type.h"
27 #include "ortools/base/logging.h"
29 #include "ortools/glop/lp_solver.h"
34 #include "ortools/sat/integer.h"
35 #include "ortools/sat/sat_base.h"
36 #include "ortools/util/fp_utils.h"
37 
38 namespace operations_research {
39 namespace sat {
40 
41 using glop::ColIndex;
42 using glop::Fractional;
43 using glop::kInfinity;
44 using glop::RowIndex;
45 
49 
50 namespace {
51 
52 void ScaleConstraint(const std::vector<double>& var_scaling,
53  MPConstraintProto* mp_constraint) {
54  const int num_terms = mp_constraint->coefficient_size();
55  for (int i = 0; i < num_terms; ++i) {
56  const int var_index = mp_constraint->var_index(i);
57  mp_constraint->set_coefficient(
58  i, mp_constraint->coefficient(i) / var_scaling[var_index]);
59  }
60 }
61 
62 void ApplyVarScaling(const std::vector<double> var_scaling,
63  MPModelProto* mp_model) {
64  const int num_variables = mp_model->variable_size();
65  for (int i = 0; i < num_variables; ++i) {
66  const double scaling = var_scaling[i];
67  const MPVariableProto& mp_var = mp_model->variable(i);
68  const double old_lb = mp_var.lower_bound();
69  const double old_ub = mp_var.upper_bound();
70  const double old_obj = mp_var.objective_coefficient();
71  mp_model->mutable_variable(i)->set_lower_bound(old_lb * scaling);
72  mp_model->mutable_variable(i)->set_upper_bound(old_ub * scaling);
73  mp_model->mutable_variable(i)->set_objective_coefficient(old_obj / scaling);
74  }
75  for (MPConstraintProto& mp_constraint : *mp_model->mutable_constraint()) {
76  ScaleConstraint(var_scaling, &mp_constraint);
77  }
78  for (MPGeneralConstraintProto& general_constraint :
79  *mp_model->mutable_general_constraint()) {
80  switch (general_constraint.general_constraint_case()) {
81  case MPGeneralConstraintProto::kIndicatorConstraint:
82  ScaleConstraint(var_scaling,
83  general_constraint.mutable_indicator_constraint()
84  ->mutable_constraint());
85  break;
86  case MPGeneralConstraintProto::kAndConstraint:
87  case MPGeneralConstraintProto::kOrConstraint:
88  // These constraints have only Boolean variables and no constants. They
89  // don't need scaling.
90  break;
91  default:
92  LOG(FATAL) << "Scaling unsupported for general constraint of type "
93  << general_constraint.general_constraint_case();
94  }
95  }
96 }
97 
98 } // namespace
99 
100 std::vector<double> ScaleContinuousVariables(double scaling, double max_bound,
101  MPModelProto* mp_model) {
102  const int num_variables = mp_model->variable_size();
103  std::vector<double> var_scaling(num_variables, 1.0);
104  for (int i = 0; i < num_variables; ++i) {
105  if (mp_model->variable(i).is_integer()) continue;
106  const double lb = mp_model->variable(i).lower_bound();
107  const double ub = mp_model->variable(i).upper_bound();
108  const double magnitude = std::max(std::abs(lb), std::abs(ub));
109  if (magnitude == 0 || magnitude > max_bound) continue;
110  var_scaling[i] = std::min(scaling, max_bound / magnitude);
111  }
112  ApplyVarScaling(var_scaling, mp_model);
113  return var_scaling;
114 }
115 
116 // This uses the best rational approximation of x via continuous fractions. It
117 // is probably not the best implementation, but according to the unit test, it
118 // seems to do the job.
119 int FindRationalFactor(double x, int limit, double tolerance) {
120  const double initial_x = x;
121  x = std::abs(x);
122  x -= std::floor(x);
123  int q = 1;
124  int prev_q = 0;
125  while (q < limit) {
126  if (std::abs(q * initial_x - std::round(q * initial_x)) < q * tolerance) {
127  return q;
128  }
129  x = 1 / x;
130  const int new_q = prev_q + static_cast<int>(std::floor(x)) * q;
131  prev_q = q;
132  q = new_q;
133  x -= std::floor(x);
134  }
135  return 0;
136 }
137 
138 namespace {
139 
140 // Returns a factor such that factor * var only need to take integer values to
141 // satisfy the given constraint. Return 0.0 if we didn't find such factor.
142 //
143 // Precondition: var must be the only non-integer in the given constraint.
144 double GetIntegralityMultiplier(const MPModelProto& mp_model,
145  const std::vector<double>& var_scaling, int var,
146  int ct_index, double tolerance) {
147  DCHECK(!mp_model.variable(var).is_integer());
148  const MPConstraintProto& ct = mp_model.constraint(ct_index);
149  double multiplier = 1.0;
150  double var_coeff = 0.0;
151  const double max_multiplier = 1e4;
152  for (int i = 0; i < ct.var_index().size(); ++i) {
153  if (var == ct.var_index(i)) {
154  var_coeff = ct.coefficient(i);
155  continue;
156  }
157 
158  DCHECK(mp_model.variable(ct.var_index(i)).is_integer());
159  // This actually compute the smallest multiplier to make all other
160  // terms in the constraint integer.
161  const double coeff =
162  multiplier * ct.coefficient(i) / var_scaling[ct.var_index(i)];
163  multiplier *=
164  FindRationalFactor(coeff, /*limit=*/100, multiplier * tolerance);
165  if (multiplier == 0 || multiplier > max_multiplier) return 0.0;
166  }
167  DCHECK_NE(var_coeff, 0.0);
168 
169  // The constraint bound need to be infinite or integer.
170  for (const double bound : {ct.lower_bound(), ct.upper_bound()}) {
171  if (!std::isfinite(bound)) continue;
172  if (std::abs(std::round(bound * multiplier) - bound * multiplier) >
173  tolerance * multiplier) {
174  return 0.0;
175  }
176  }
177  return std::abs(multiplier * var_coeff);
178 }
179 
180 } // namespace
181 
182 void RemoveNearZeroTerms(const SatParameters& params, MPModelProto* mp_model) {
183  const int num_variables = mp_model->variable_size();
184 
185  // Compute for each variable its current maximum magnitude. Note that we will
186  // only scale variable with a coefficient >= 1, so it is safe to use this
187  // bound.
188  std::vector<double> max_bounds(num_variables);
189  for (int i = 0; i < num_variables; ++i) {
190  double value = std::abs(mp_model->variable(i).lower_bound());
191  value = std::max(value, std::abs(mp_model->variable(i).upper_bound()));
192  value = std::min(value, params.mip_max_bound());
193  max_bounds[i] = value;
194  }
195 
196  // We want the maximum absolute error while setting coefficients to zero to
197  // not exceed our mip wanted precision. So for a binary variable we might set
198  // to zero coefficient around 1e-7. But for large domain, we need lower coeff
199  // than that, around 1e-12 with the default params.mip_max_bound(). This also
200  // depends on the size of the constraint.
201  int64 num_removed = 0;
202  double largest_removed = 0.0;
203  const int num_constraints = mp_model->constraint_size();
204  for (int c = 0; c < num_constraints; ++c) {
205  MPConstraintProto* ct = mp_model->mutable_constraint(c);
206  int new_size = 0;
207  const int size = ct->var_index().size();
208  if (size == 0) continue;
209  const double threshold =
210  params.mip_wanted_precision() / static_cast<double>(size);
211  for (int i = 0; i < size; ++i) {
212  const int var = ct->var_index(i);
213  const double coeff = ct->coefficient(i);
214  if (std::abs(coeff) * max_bounds[var] < threshold) {
215  largest_removed = std::max(largest_removed, std::abs(coeff));
216  continue;
217  }
218  ct->set_var_index(new_size, var);
219  ct->set_coefficient(new_size, coeff);
220  ++new_size;
221  }
222  num_removed += size - new_size;
223  ct->mutable_var_index()->Truncate(new_size);
224  ct->mutable_coefficient()->Truncate(new_size);
225  }
226 
227  const bool log_info = VLOG_IS_ON(1) || params.log_search_progress();
228  if (log_info && num_removed > 0) {
229  LOG(INFO) << "Removed " << num_removed
230  << " near zero terms with largest magnitude of "
231  << largest_removed << ".";
232  }
233 }
234 
235 std::vector<double> DetectImpliedIntegers(bool log_info,
236  MPModelProto* mp_model) {
237  const int num_variables = mp_model->variable_size();
238  std::vector<double> var_scaling(num_variables, 1.0);
239 
240  int initial_num_integers = 0;
241  for (int i = 0; i < num_variables; ++i) {
242  if (mp_model->variable(i).is_integer()) ++initial_num_integers;
243  }
244  VLOG(1) << "Initial num integers: " << initial_num_integers;
245 
246  // We will process all equality constraints with exactly one non-integer.
247  const double tolerance = 1e-6;
248  std::vector<int> constraint_queue;
249 
250  const int num_constraints = mp_model->constraint_size();
251  std::vector<int> constraint_to_num_non_integer(num_constraints, 0);
252  std::vector<std::vector<int>> var_to_constraints(num_variables);
253  for (int i = 0; i < num_constraints; ++i) {
254  const MPConstraintProto& mp_constraint = mp_model->constraint(i);
255 
256  for (const int var : mp_constraint.var_index()) {
257  if (!mp_model->variable(var).is_integer()) {
258  var_to_constraints[var].push_back(i);
259  constraint_to_num_non_integer[i]++;
260  }
261  }
262  if (constraint_to_num_non_integer[i] == 1) {
263  constraint_queue.push_back(i);
264  }
265  }
266  VLOG(1) << "Initial constraint queue: " << constraint_queue.size() << " / "
267  << num_constraints;
268 
269  int num_detected = 0;
270  double max_scaling = 0.0;
271  auto scale_and_mark_as_integer = [&](int var, double scaling) mutable {
272  CHECK_NE(var, -1);
273  CHECK(!mp_model->variable(var).is_integer());
274  CHECK_EQ(var_scaling[var], 1.0);
275  if (scaling != 1.0) {
276  VLOG(2) << "Scaled " << var << " by " << scaling;
277  }
278 
279  ++num_detected;
280  max_scaling = std::max(max_scaling, scaling);
281 
282  // Scale the variable right away and mark it as implied integer.
283  // Note that the constraints will be scaled later.
284  var_scaling[var] = scaling;
285  mp_model->mutable_variable(var)->set_is_integer(true);
286 
287  // Update the queue of constraints with a single non-integer.
288  for (const int ct_index : var_to_constraints[var]) {
289  constraint_to_num_non_integer[ct_index]--;
290  if (constraint_to_num_non_integer[ct_index] == 1) {
291  constraint_queue.push_back(ct_index);
292  }
293  }
294  };
295 
296  int num_fail_due_to_rhs = 0;
297  int num_fail_due_to_large_multiplier = 0;
298  int num_processed_constraints = 0;
299  while (!constraint_queue.empty()) {
300  const int top_ct_index = constraint_queue.back();
301  constraint_queue.pop_back();
302 
303  // The non integer variable was already made integer by one other
304  // constraint.
305  if (constraint_to_num_non_integer[top_ct_index] == 0) continue;
306 
307  // Ignore non-equality here.
308  const MPConstraintProto& ct = mp_model->constraint(top_ct_index);
309  if (ct.lower_bound() + tolerance < ct.upper_bound()) continue;
310 
311  ++num_processed_constraints;
312 
313  // This will be set to the unique non-integer term of this constraint.
314  int var = -1;
315  double var_coeff;
316 
317  // We are looking for a "multiplier" so that the unique non-integer term
318  // in this constraint (i.e. var * var_coeff) times this multiplier is an
319  // integer.
320  //
321  // If this is set to zero or becomes too large, we fail to detect a new
322  // implied integer and ignore this constraint.
323  double multiplier = 1.0;
324  const double max_multiplier = 1e4;
325 
326  for (int i = 0; i < ct.var_index().size(); ++i) {
327  if (!mp_model->variable(ct.var_index(i)).is_integer()) {
328  CHECK_EQ(var, -1);
329  var = ct.var_index(i);
330  var_coeff = ct.coefficient(i);
331  } else {
332  // This actually compute the smallest multiplier to make all other
333  // terms in the constraint integer.
334  const double coeff =
335  multiplier * ct.coefficient(i) / var_scaling[ct.var_index(i)];
336  multiplier *=
337  FindRationalFactor(coeff, /*limit=*/100, multiplier * tolerance);
338  if (multiplier == 0 || multiplier > max_multiplier) {
339  break;
340  }
341  }
342  }
343 
344  if (multiplier == 0 || multiplier > max_multiplier) {
345  ++num_fail_due_to_large_multiplier;
346  continue;
347  }
348 
349  // These "rhs" fail could be handled by shifting the variable.
350  const double rhs = ct.lower_bound();
351  if (std::abs(std::round(rhs * multiplier) - rhs * multiplier) >
352  tolerance * multiplier) {
353  ++num_fail_due_to_rhs;
354  continue;
355  }
356 
357  // We want to multiply the variable so that it is integer. We know that
358  // coeff * multiplier is an integer, so we just multiply by that.
359  //
360  // But if a variable appear in more than one equality, we want to find the
361  // smallest integrality factor! See diameterc-msts-v40a100d5i.mps
362  // for an instance of this.
363  double best_scaling = std::abs(var_coeff * multiplier);
364  for (const int ct_index : var_to_constraints[var]) {
365  if (ct_index == top_ct_index) continue;
366  if (constraint_to_num_non_integer[ct_index] != 1) continue;
367 
368  // Ignore non-equality here.
369  const MPConstraintProto& ct = mp_model->constraint(top_ct_index);
370  if (ct.lower_bound() + tolerance < ct.upper_bound()) continue;
371 
372  const double multiplier = GetIntegralityMultiplier(
373  *mp_model, var_scaling, var, ct_index, tolerance);
374  if (multiplier != 0.0 && multiplier < best_scaling) {
375  best_scaling = multiplier;
376  }
377  }
378 
379  scale_and_mark_as_integer(var, best_scaling);
380  }
381 
382  // Process continuous variables that only appear as the unique non integer
383  // in a set of non-equality constraints.
384  //
385  // Note that turning to integer such variable cannot in turn trigger new
386  // integer detection, so there is no point doing that in a loop.
387  int num_in_inequalities = 0;
388  int num_to_be_handled = 0;
389  for (int var = 0; var < num_variables; ++var) {
390  if (mp_model->variable(var).is_integer()) continue;
391 
392  // This should be presolved and not happen.
393  if (var_to_constraints[var].empty()) continue;
394 
395  bool ok = true;
396  for (const int ct_index : var_to_constraints[var]) {
397  if (constraint_to_num_non_integer[ct_index] != 1) {
398  ok = false;
399  break;
400  }
401  }
402  if (!ok) continue;
403 
404  std::vector<double> scaled_coeffs;
405  for (const int ct_index : var_to_constraints[var]) {
406  const double multiplier = GetIntegralityMultiplier(
407  *mp_model, var_scaling, var, ct_index, tolerance);
408  if (multiplier == 0.0) {
409  ok = false;
410  break;
411  }
412  scaled_coeffs.push_back(multiplier);
413  }
414  if (!ok) continue;
415 
416  // The situation is a bit tricky here, we have a bunch of coeffs c_i, and we
417  // know that X * c_i can take integer value without changing the constraint
418  // i meaning.
419  //
420  // For now we take the min, and scale only if all c_i / min are integer.
421  double scaling = scaled_coeffs[0];
422  for (const double c : scaled_coeffs) {
423  scaling = std::min(scaling, c);
424  }
425  CHECK_GT(scaling, 0.0);
426  for (const double c : scaled_coeffs) {
427  const double fraction = c / scaling;
428  if (std::abs(std::round(fraction) - fraction) > tolerance) {
429  ok = false;
430  break;
431  }
432  }
433  if (!ok) {
434  // TODO(user): be smarter! we should be able to handle these cases.
435  ++num_to_be_handled;
436  continue;
437  }
438 
439  // Tricky, we also need the bound of the scaled variable to be integer.
440  for (const double bound : {mp_model->variable(var).lower_bound(),
441  mp_model->variable(var).upper_bound()}) {
442  if (!std::isfinite(bound)) continue;
443  if (std::abs(std::round(bound * scaling) - bound * scaling) >
444  tolerance * scaling) {
445  ok = false;
446  break;
447  }
448  }
449  if (!ok) {
450  // TODO(user): If we scale more we migth be able to turn it into an
451  // integer.
452  ++num_to_be_handled;
453  continue;
454  }
455 
456  ++num_in_inequalities;
457  scale_and_mark_as_integer(var, scaling);
458  }
459  VLOG(1) << "num_new_integer: " << num_detected
460  << " num_processed_constraints: " << num_processed_constraints
461  << " num_rhs_fail: " << num_fail_due_to_rhs
462  << " num_multiplier_fail: " << num_fail_due_to_large_multiplier;
463 
464  if (log_info && num_to_be_handled > 0) {
465  LOG(INFO) << "Missed " << num_to_be_handled
466  << " potential implied integer.";
467  }
468 
469  const int num_integers = initial_num_integers + num_detected;
470  LOG_IF(INFO, log_info) << "Num integers: " << num_integers << "/"
471  << num_variables << " (implied: " << num_detected
472  << " in_inequalities: " << num_in_inequalities
473  << " max_scaling: " << max_scaling << ")"
474  << (num_integers == num_variables ? " [IP] "
475  : " [MIP] ");
476 
477  ApplyVarScaling(var_scaling, mp_model);
478  return var_scaling;
479 }
480 
481 namespace {
482 
483 // We use a class to reuse the temporay memory.
484 struct ConstraintScaler {
485  // Scales an individual constraint.
486  ConstraintProto* AddConstraint(const MPModelProto& mp_model,
487  const MPConstraintProto& mp_constraint,
488  CpModelProto* cp_model);
489 
492  double max_scaling_factor = 0.0;
493 
494  double wanted_precision = 1e-6;
496  std::vector<int> var_indices;
497  std::vector<double> coefficients;
498  std::vector<double> lower_bounds;
499  std::vector<double> upper_bounds;
500 };
501 
502 namespace {
503 
504 double FindFractionalScaling(const std::vector<double>& coefficients,
505  double tolerance) {
506  double multiplier = 1.0;
507  for (const double coeff : coefficients) {
508  multiplier *=
509  FindRationalFactor(coeff, /*limit=*/1e8, multiplier * tolerance);
510  if (multiplier == 0.0) break;
511  }
512  return multiplier;
513 }
514 
515 } // namespace
516 
517 ConstraintProto* ConstraintScaler::AddConstraint(
518  const MPModelProto& mp_model, const MPConstraintProto& mp_constraint,
519  CpModelProto* cp_model) {
520  if (mp_constraint.lower_bound() == -kInfinity &&
521  mp_constraint.upper_bound() == kInfinity) {
522  return nullptr;
523  }
524 
525  auto* constraint = cp_model->add_constraints();
526  constraint->set_name(mp_constraint.name());
527  auto* arg = constraint->mutable_linear();
528 
529  // First scale the coefficients of the constraints so that the constraint
530  // sum can always be computed without integer overflow.
531  var_indices.clear();
532  coefficients.clear();
533  lower_bounds.clear();
534  upper_bounds.clear();
535  const int num_coeffs = mp_constraint.coefficient_size();
536  for (int i = 0; i < num_coeffs; ++i) {
537  const auto& var_proto = cp_model->variables(mp_constraint.var_index(i));
538  const int64 lb = var_proto.domain(0);
539  const int64 ub = var_proto.domain(var_proto.domain_size() - 1);
540  if (lb == 0 && ub == 0) continue;
541 
542  const double coeff = mp_constraint.coefficient(i);
543  if (coeff == 0.0) continue;
544 
545  var_indices.push_back(mp_constraint.var_index(i));
546  coefficients.push_back(coeff);
547  lower_bounds.push_back(lb);
548  upper_bounds.push_back(ub);
549  }
550 
551  // We compute the worst case error relative to the magnitude of the bounds.
552  Fractional lb = mp_constraint.lower_bound();
553  Fractional ub = mp_constraint.upper_bound();
554  const double ct_norm = std::max(1.0, std::min(std::abs(lb), std::abs(ub)));
555 
556  double scaling_factor = GetBestScalingOfDoublesToInt64(
558 
559  // Returns the smallest factor of the form 2^i that gives us a relative sum
560  // error of wanted_precision and still make sure we will have no integer
561  // overflow.
562  //
563  // TODO(user): Make this faster.
564  double x = std::min(scaling_factor, 1.0);
565  double relative_coeff_error;
566  double scaled_sum_error;
567  for (; x <= scaling_factor; x *= 2) {
569  &relative_coeff_error, &scaled_sum_error);
570  if (scaled_sum_error < wanted_precision * x * ct_norm) break;
571  }
572  scaling_factor = x;
573 
574  // Because we deal with an approximate input, scaling with a power of 2 might
575  // not be the best choice. It is also possible user used rational coeff and
576  // then converted them to double (1/2, 1/3, 4/5, etc...). This scaling will
577  // recover such rational input and might result in a smaller overall
578  // coefficient which is good.
579  const double integer_factor = FindFractionalScaling(coefficients, 1e-8);
580  if (integer_factor != 0 && integer_factor < scaling_factor) {
582  &relative_coeff_error, &scaled_sum_error);
583  if (scaled_sum_error < wanted_precision * integer_factor * ct_norm) {
584  scaling_factor = integer_factor;
585  }
586  }
587 
588  const int64 gcd = ComputeGcdOfRoundedDoubles(coefficients, scaling_factor);
590  std::max(relative_coeff_error, max_relative_coeff_error);
591  max_scaling_factor = std::max(scaling_factor / gcd, max_scaling_factor);
592 
593  // We do not relax the constraint bound if all variables are integer and
594  // we made no error at all during our scaling.
595  bool relax_bound = scaled_sum_error > 0;
596 
597  for (int i = 0; i < coefficients.size(); ++i) {
598  const double scaled_value = coefficients[i] * scaling_factor;
599  const int64 value = static_cast<int64>(std::round(scaled_value)) / gcd;
600  if (value != 0) {
601  if (!mp_model.variable(var_indices[i]).is_integer()) {
602  relax_bound = true;
603  }
604  arg->add_vars(var_indices[i]);
605  arg->add_coeffs(value);
606  }
607  }
609  max_relative_rhs_error, scaled_sum_error / (scaling_factor * ct_norm));
610 
611  // Add the constraint bounds. Because we are sure the scaled constraint fit
612  // on an int64, if the scaled bounds are too large, the constraint is either
613  // always true or always false.
614  if (relax_bound) {
615  lb -= std::max(std::abs(lb), 1.0) * wanted_precision;
616  }
617  const Fractional scaled_lb = std::ceil(lb * scaling_factor);
618  if (lb == -kInfinity || scaled_lb <= kint64min) {
619  arg->add_domain(kint64min);
620  } else {
621  arg->add_domain(CeilRatio(IntegerValue(static_cast<int64>(scaled_lb)),
622  IntegerValue(gcd))
623  .value());
624  }
625 
626  if (relax_bound) {
627  ub += std::max(std::abs(ub), 1.0) * wanted_precision;
628  }
629  const Fractional scaled_ub = std::floor(ub * scaling_factor);
630  if (ub == kInfinity || scaled_ub >= kint64max) {
631  arg->add_domain(kint64max);
632  } else {
633  arg->add_domain(FloorRatio(IntegerValue(static_cast<int64>(scaled_ub)),
634  IntegerValue(gcd))
635  .value());
636  }
637 
638  return constraint;
639 }
640 
641 } // namespace
642 
643 bool ConvertMPModelProtoToCpModelProto(const SatParameters& params,
644  const MPModelProto& mp_model,
645  CpModelProto* cp_model) {
646  CHECK(cp_model != nullptr);
647  cp_model->Clear();
648  cp_model->set_name(mp_model.name());
649 
650  // To make sure we cannot have integer overflow, we use this bound for any
651  // unbounded variable.
652  //
653  // TODO(user): This could be made larger if needed, so be smarter if we have
654  // MIP problem that we cannot "convert" because of this. Note however than we
655  // cannot go that much further because we need to make sure we will not run
656  // into overflow if we add a big linear combination of such variables. It
657  // should always be possible for a user to scale its problem so that all
658  // relevant quantities are a couple of millions. A LP/MIP solver have a
659  // similar condition in disguise because problem with a difference of more
660  // than 6 magnitudes between the variable values will likely run into numeric
661  // trouble.
662  const int64 kMaxVariableBound = static_cast<int64>(params.mip_max_bound());
663 
664  int num_truncated_bounds = 0;
665  int num_small_domains = 0;
666  const int64 kSmallDomainSize = 1000;
667  const double kWantedPrecision = params.mip_wanted_precision();
668 
669  // Add the variables.
670  const int num_variables = mp_model.variable_size();
671  for (int i = 0; i < num_variables; ++i) {
672  const MPVariableProto& mp_var = mp_model.variable(i);
673  IntegerVariableProto* cp_var = cp_model->add_variables();
674  cp_var->set_name(mp_var.name());
675 
676  // Deal with the corner case of a domain far away from zero.
677  //
678  // TODO(user): We should deal with these case by shifting the domain so
679  // that it includes zero instead of just fixing the variable. But that is a
680  // bit of work as it requires some postsolve.
681  if (mp_var.lower_bound() > kMaxVariableBound) {
682  // Fix var to its lower bound.
683  ++num_truncated_bounds;
684  const int64 value = static_cast<int64>(std::round(mp_var.lower_bound()));
685  cp_var->add_domain(value);
686  cp_var->add_domain(value);
687  continue;
688  } else if (mp_var.upper_bound() < -kMaxVariableBound) {
689  // Fix var to its upper_bound.
690  ++num_truncated_bounds;
691  const int64 value = static_cast<int64>(std::round(mp_var.upper_bound()));
692  cp_var->add_domain(value);
693  cp_var->add_domain(value);
694  continue;
695  }
696 
697  // Note that we must process the lower bound first.
698  for (const bool lower : {true, false}) {
699  const double bound = lower ? mp_var.lower_bound() : mp_var.upper_bound();
700  if (std::abs(bound) >= kMaxVariableBound) {
701  ++num_truncated_bounds;
702  cp_var->add_domain(bound < 0 ? -kMaxVariableBound : kMaxVariableBound);
703  continue;
704  }
705 
706  // Note that the cast is "perfect" because we forbid large values.
707  cp_var->add_domain(
708  static_cast<int64>(lower ? std::ceil(bound - kWantedPrecision)
709  : std::floor(bound + kWantedPrecision)));
710  }
711 
712  if (cp_var->domain(0) > cp_var->domain(1)) {
713  LOG(WARNING) << "Variable #" << i << " cannot take integer value. "
714  << mp_var.ShortDebugString();
715  return false;
716  }
717 
718  // Notify if a continuous variable has a small domain as this is likely to
719  // make an all integer solution far from a continuous one.
720  if (!mp_var.is_integer() && cp_var->domain(0) != cp_var->domain(1) &&
721  cp_var->domain(1) - cp_var->domain(0) < kSmallDomainSize) {
722  ++num_small_domains;
723  }
724  }
725 
726  LOG_IF(WARNING, num_truncated_bounds > 0)
727  << num_truncated_bounds << " bounds were truncated to "
728  << kMaxVariableBound << ".";
729  LOG_IF(WARNING, num_small_domains > 0)
730  << num_small_domains << " continuous variable domain with fewer than "
731  << kSmallDomainSize << " values.";
732 
733  ConstraintScaler scaler;
734  const int64 kScalingTarget = int64{1} << params.mip_max_activity_exponent();
735  scaler.wanted_precision = kWantedPrecision;
736  scaler.scaling_target = kScalingTarget;
737 
738  // Add the constraints. We scale each of them individually.
739  for (const MPConstraintProto& mp_constraint : mp_model.constraint()) {
740  scaler.AddConstraint(mp_model, mp_constraint, cp_model);
741  }
742  for (const MPGeneralConstraintProto& general_constraint :
743  mp_model.general_constraint()) {
744  switch (general_constraint.general_constraint_case()) {
745  case MPGeneralConstraintProto::kIndicatorConstraint: {
746  const auto& indicator_constraint =
747  general_constraint.indicator_constraint();
748  const MPConstraintProto& mp_constraint =
749  indicator_constraint.constraint();
750  ConstraintProto* ct =
751  scaler.AddConstraint(mp_model, mp_constraint, cp_model);
752  if (ct == nullptr) continue;
753 
754  // Add the indicator.
755  const int var = indicator_constraint.var_index();
756  const int value = indicator_constraint.var_value();
757  ct->add_enforcement_literal(value == 1 ? var : NegatedRef(var));
758  break;
759  }
760  case MPGeneralConstraintProto::kAndConstraint: {
761  const auto& and_constraint = general_constraint.and_constraint();
762  const std::string& name = general_constraint.name();
763 
764  ConstraintProto* ct_pos = cp_model->add_constraints();
765  ct_pos->set_name(name.empty() ? "" : absl::StrCat(name, "_pos"));
766  ct_pos->add_enforcement_literal(and_constraint.resultant_var_index());
767  *ct_pos->mutable_bool_and()->mutable_literals() =
768  and_constraint.var_index();
769 
770  ConstraintProto* ct_neg = cp_model->add_constraints();
771  ct_neg->set_name(name.empty() ? "" : absl::StrCat(name, "_neg"));
772  ct_neg->add_enforcement_literal(
773  NegatedRef(and_constraint.resultant_var_index()));
774  for (const int var_index : and_constraint.var_index()) {
775  ct_neg->mutable_bool_or()->add_literals(NegatedRef(var_index));
776  }
777  break;
778  }
779  case MPGeneralConstraintProto::kOrConstraint: {
780  const auto& or_constraint = general_constraint.or_constraint();
781  const std::string& name = general_constraint.name();
782 
783  ConstraintProto* ct_pos = cp_model->add_constraints();
784  ct_pos->set_name(name.empty() ? "" : absl::StrCat(name, "_pos"));
785  ct_pos->add_enforcement_literal(or_constraint.resultant_var_index());
786  *ct_pos->mutable_bool_or()->mutable_literals() =
787  or_constraint.var_index();
788 
789  ConstraintProto* ct_neg = cp_model->add_constraints();
790  ct_neg->set_name(name.empty() ? "" : absl::StrCat(name, "_neg"));
791  ct_neg->add_enforcement_literal(
792  NegatedRef(or_constraint.resultant_var_index()));
793  for (const int var_index : or_constraint.var_index()) {
794  ct_neg->mutable_bool_and()->add_literals(NegatedRef(var_index));
795  }
796  break;
797  }
798  default:
799  LOG(ERROR) << "Can't convert general constraints of type "
800  << general_constraint.general_constraint_case()
801  << " to CpModelProto.";
802  return false;
803  }
804  }
805 
806  // Display the error/scaling on the constraints.
807  const bool log_info = VLOG_IS_ON(1) || params.log_search_progress();
808  LOG_IF(INFO, log_info) << "Maximum constraint coefficient relative error: "
809  << scaler.max_relative_coeff_error;
810  LOG_IF(INFO, log_info)
811  << "Maximum constraint worst-case activity relative error: "
812  << scaler.max_relative_rhs_error
813  << (scaler.max_relative_rhs_error > params.mip_check_precision()
814  ? " [Potentially IMPRECISE]"
815  : "");
816  LOG_IF(INFO, log_info) << "Maximum constraint scaling factor: "
817  << scaler.max_scaling_factor;
818 
819  // Add the objective.
820  std::vector<int> var_indices;
821  std::vector<double> coefficients;
822  std::vector<double> lower_bounds;
823  std::vector<double> upper_bounds;
824  double min_magnitude = std::numeric_limits<double>::infinity();
825  double max_magnitude = 0.0;
826  double l1_norm = 0.0;
827  for (int i = 0; i < num_variables; ++i) {
828  const MPVariableProto& mp_var = mp_model.variable(i);
829  if (mp_var.objective_coefficient() == 0.0) continue;
830 
831  const auto& var_proto = cp_model->variables(i);
832  const int64 lb = var_proto.domain(0);
833  const int64 ub = var_proto.domain(var_proto.domain_size() - 1);
834  if (lb == 0 && ub == 0) continue;
835 
836  var_indices.push_back(i);
837  coefficients.push_back(mp_var.objective_coefficient());
838  lower_bounds.push_back(lb);
839  upper_bounds.push_back(ub);
840  min_magnitude = std::min(min_magnitude, std::abs(coefficients.back()));
841  max_magnitude = std::max(max_magnitude, std::abs(coefficients.back()));
842  l1_norm += std::abs(coefficients.back());
843  }
844  if (!coefficients.empty()) {
845  const double average_magnitude =
846  l1_norm / static_cast<double>(coefficients.size());
847  LOG_IF(INFO, log_info) << "Objective magnitude in [" << min_magnitude
848  << ", " << max_magnitude
849  << "] average = " << average_magnitude;
850  }
851  if (!coefficients.empty() || mp_model.objective_offset() != 0.0) {
852  double scaling_factor = GetBestScalingOfDoublesToInt64(
853  coefficients, lower_bounds, upper_bounds, kScalingTarget);
854 
855  // Returns the smallest factor of the form 2^i that gives us an absolute
856  // error of kWantedPrecision and still make sure we will have no integer
857  // overflow.
858  //
859  // TODO(user): Make this faster.
860  double x = std::min(scaling_factor, 1.0);
861  double relative_coeff_error;
862  double scaled_sum_error;
863  for (; x <= scaling_factor; x *= 2) {
865  &relative_coeff_error, &scaled_sum_error);
866  if (scaled_sum_error < kWantedPrecision * x) break;
867  }
868  scaling_factor = x;
869 
870  // Same remark as for the constraint.
871  // TODO(user): Extract common code.
872  const double integer_factor = FindFractionalScaling(coefficients, 1e-8);
873  if (integer_factor != 0 && integer_factor < scaling_factor) {
875  &relative_coeff_error, &scaled_sum_error);
876  if (scaled_sum_error < kWantedPrecision * integer_factor) {
877  scaling_factor = integer_factor;
878  }
879  }
880 
881  const int64 gcd = ComputeGcdOfRoundedDoubles(coefficients, scaling_factor);
882 
883  // Display the objective error/scaling.
884  LOG_IF(INFO, log_info)
885  << "Objective coefficient relative error: " << relative_coeff_error
886  << (relative_coeff_error > params.mip_check_precision() ? " [IMPRECISE]"
887  : "");
888  LOG_IF(INFO, log_info) << "Objective worst-case absolute error: "
889  << scaled_sum_error / scaling_factor;
890  LOG_IF(INFO, log_info) << "Objective scaling factor: "
891  << scaling_factor / gcd;
892 
893  // Note that here we set the scaling factor for the inverse operation of
894  // getting the "true" objective value from the scaled one. Hence the
895  // inverse.
896  auto* objective = cp_model->mutable_objective();
897  const int mult = mp_model.maximize() ? -1 : 1;
898  objective->set_offset(mp_model.objective_offset() * scaling_factor / gcd *
899  mult);
900  objective->set_scaling_factor(1.0 / scaling_factor * gcd * mult);
901  for (int i = 0; i < coefficients.size(); ++i) {
902  const int64 value =
903  static_cast<int64>(std::round(coefficients[i] * scaling_factor)) /
904  gcd;
905  if (value != 0) {
906  objective->add_vars(var_indices[i]);
907  objective->add_coeffs(value * mult);
908  }
909  }
910  }
911 
912  return true;
913 }
914 
915 bool ConvertBinaryMPModelProtoToBooleanProblem(const MPModelProto& mp_model,
916  LinearBooleanProblem* problem) {
917  CHECK(problem != nullptr);
918  problem->Clear();
919  problem->set_name(mp_model.name());
920  const int num_variables = mp_model.variable_size();
921  problem->set_num_variables(num_variables);
922 
923  // Test if the variables are binary variables.
924  // Add constraints for the fixed variables.
925  for (int var_id(0); var_id < num_variables; ++var_id) {
926  const MPVariableProto& mp_var = mp_model.variable(var_id);
927  problem->add_var_names(mp_var.name());
928 
929  // This will be changed to false as soon as we detect the variable to be
930  // non-binary. This is done this way so we can display a nice error message
931  // before aborting the function and returning false.
932  bool is_binary = mp_var.is_integer();
933 
934  const Fractional lb = mp_var.lower_bound();
935  const Fractional ub = mp_var.upper_bound();
936  if (lb <= -1.0) is_binary = false;
937  if (ub >= 2.0) is_binary = false;
938  if (is_binary) {
939  // 4 cases.
940  if (lb <= 0.0 && ub >= 1.0) {
941  // Binary variable. Ok.
942  } else if (lb <= 1.0 && ub >= 1.0) {
943  // Fixed variable at 1.
944  LinearBooleanConstraint* constraint = problem->add_constraints();
945  constraint->set_lower_bound(1);
946  constraint->set_upper_bound(1);
947  constraint->add_literals(var_id + 1);
948  constraint->add_coefficients(1);
949  } else if (lb <= 0.0 && ub >= 0.0) {
950  // Fixed variable at 0.
951  LinearBooleanConstraint* constraint = problem->add_constraints();
952  constraint->set_lower_bound(0);
953  constraint->set_upper_bound(0);
954  constraint->add_literals(var_id + 1);
955  constraint->add_coefficients(1);
956  } else {
957  // No possible integer value!
958  is_binary = false;
959  }
960  }
961 
962  // Abort if the variable is not binary.
963  if (!is_binary) {
964  LOG(WARNING) << "The variable #" << var_id << " with name "
965  << mp_var.name() << " is not binary. "
966  << "lb: " << lb << " ub: " << ub;
967  return false;
968  }
969  }
970 
971  // Variables needed to scale the double coefficients into int64.
972  const int64 kInt64Max = std::numeric_limits<int64>::max();
973  double max_relative_error = 0.0;
974  double max_bound_error = 0.0;
975  double max_scaling_factor = 0.0;
976  double relative_error = 0.0;
977  double scaling_factor = 0.0;
978  std::vector<double> coefficients;
979 
980  // Add all constraints.
981  for (const MPConstraintProto& mp_constraint : mp_model.constraint()) {
982  LinearBooleanConstraint* constraint = problem->add_constraints();
983  constraint->set_name(mp_constraint.name());
984 
985  // First scale the coefficients of the constraints.
986  coefficients.clear();
987  const int num_coeffs = mp_constraint.coefficient_size();
988  for (int i = 0; i < num_coeffs; ++i) {
989  coefficients.push_back(mp_constraint.coefficient(i));
990  }
991  GetBestScalingOfDoublesToInt64(coefficients, kInt64Max, &scaling_factor,
992  &relative_error);
993  const int64 gcd = ComputeGcdOfRoundedDoubles(coefficients, scaling_factor);
994  max_relative_error = std::max(relative_error, max_relative_error);
995  max_scaling_factor = std::max(scaling_factor / gcd, max_scaling_factor);
996 
997  double bound_error = 0.0;
998  for (int i = 0; i < num_coeffs; ++i) {
999  const double scaled_value = mp_constraint.coefficient(i) * scaling_factor;
1000  bound_error += std::abs(round(scaled_value) - scaled_value);
1001  const int64 value = static_cast<int64>(round(scaled_value)) / gcd;
1002  if (value != 0) {
1003  constraint->add_literals(mp_constraint.var_index(i) + 1);
1004  constraint->add_coefficients(value);
1005  }
1006  }
1007  max_bound_error = std::max(max_bound_error, bound_error);
1008 
1009  // Add the bounds. Note that we do not pass them to
1010  // GetBestScalingOfDoublesToInt64() because we know that the sum of absolute
1011  // coefficients of the constraint fit on an int64. If one of the scaled
1012  // bound overflows, we don't care by how much because in this case the
1013  // constraint is just trivial or unsatisfiable.
1014  const Fractional lb = mp_constraint.lower_bound();
1015  if (lb != -kInfinity) {
1016  if (lb * scaling_factor > static_cast<double>(kInt64Max)) {
1017  LOG(WARNING) << "A constraint is trivially unsatisfiable.";
1018  return false;
1019  }
1020  if (lb * scaling_factor > -static_cast<double>(kInt64Max)) {
1021  // Otherwise, the constraint is not needed.
1022  constraint->set_lower_bound(
1023  static_cast<int64>(round(lb * scaling_factor - bound_error)) / gcd);
1024  }
1025  }
1026  const Fractional ub = mp_constraint.upper_bound();
1027  if (ub != kInfinity) {
1028  if (ub * scaling_factor < -static_cast<double>(kInt64Max)) {
1029  LOG(WARNING) << "A constraint is trivially unsatisfiable.";
1030  return false;
1031  }
1032  if (ub * scaling_factor < static_cast<double>(kInt64Max)) {
1033  // Otherwise, the constraint is not needed.
1034  constraint->set_upper_bound(
1035  static_cast<int64>(round(ub * scaling_factor + bound_error)) / gcd);
1036  }
1037  }
1038  }
1039 
1040  // Display the error/scaling without taking into account the objective first.
1041  LOG(INFO) << "Maximum constraint relative error: " << max_relative_error;
1042  LOG(INFO) << "Maximum constraint bound error: " << max_bound_error;
1043  LOG(INFO) << "Maximum constraint scaling factor: " << max_scaling_factor;
1044 
1045  // Add the objective.
1046  coefficients.clear();
1047  for (int var_id = 0; var_id < num_variables; ++var_id) {
1048  const MPVariableProto& mp_var = mp_model.variable(var_id);
1049  coefficients.push_back(mp_var.objective_coefficient());
1050  }
1051  GetBestScalingOfDoublesToInt64(coefficients, kInt64Max, &scaling_factor,
1052  &relative_error);
1053  const int64 gcd = ComputeGcdOfRoundedDoubles(coefficients, scaling_factor);
1054  max_relative_error = std::max(relative_error, max_relative_error);
1055 
1056  // Display the objective error/scaling.
1057  LOG(INFO) << "objective relative error: " << relative_error;
1058  LOG(INFO) << "objective scaling factor: " << scaling_factor / gcd;
1059 
1060  LinearObjective* objective = problem->mutable_objective();
1061  objective->set_offset(mp_model.objective_offset() * scaling_factor / gcd);
1062 
1063  // Note that here we set the scaling factor for the inverse operation of
1064  // getting the "true" objective value from the scaled one. Hence the inverse.
1065  objective->set_scaling_factor(1.0 / scaling_factor * gcd);
1066  for (int var_id = 0; var_id < num_variables; ++var_id) {
1067  const MPVariableProto& mp_var = mp_model.variable(var_id);
1068  const int64 value = static_cast<int64>(round(
1069  mp_var.objective_coefficient() * scaling_factor)) /
1070  gcd;
1071  if (value != 0) {
1072  objective->add_literals(var_id + 1);
1073  objective->add_coefficients(value);
1074  }
1075  }
1076 
1077  // If the problem was a maximization one, we need to modify the objective.
1078  if (mp_model.maximize()) ChangeOptimizationDirection(problem);
1079 
1080  // Test the precision of the conversion.
1081  const double kRelativeTolerance = 1e-8;
1082  if (max_relative_error > kRelativeTolerance) {
1083  LOG(WARNING) << "The relative error during double -> int64 conversion "
1084  << "is too high!";
1085  return false;
1086  }
1087  return true;
1088 }
1089 
1090 void ConvertBooleanProblemToLinearProgram(const LinearBooleanProblem& problem,
1091  glop::LinearProgram* lp) {
1092  lp->Clear();
1093  for (int i = 0; i < problem.num_variables(); ++i) {
1094  const ColIndex col = lp->CreateNewVariable();
1096  lp->SetVariableBounds(col, 0.0, 1.0);
1097  }
1098 
1099  // Variables name are optional.
1100  if (problem.var_names_size() != 0) {
1101  CHECK_EQ(problem.var_names_size(), problem.num_variables());
1102  for (int i = 0; i < problem.num_variables(); ++i) {
1103  lp->SetVariableName(ColIndex(i), problem.var_names(i));
1104  }
1105  }
1106 
1107  for (const LinearBooleanConstraint& constraint : problem.constraints()) {
1108  const RowIndex constraint_index = lp->CreateNewConstraint();
1109  lp->SetConstraintName(constraint_index, constraint.name());
1110  double sum = 0.0;
1111  for (int i = 0; i < constraint.literals_size(); ++i) {
1112  const int literal = constraint.literals(i);
1113  const double coeff = constraint.coefficients(i);
1114  const ColIndex variable_index = ColIndex(abs(literal) - 1);
1115  if (literal < 0) {
1116  sum += coeff;
1117  lp->SetCoefficient(constraint_index, variable_index, -coeff);
1118  } else {
1119  lp->SetCoefficient(constraint_index, variable_index, coeff);
1120  }
1121  }
1122  lp->SetConstraintBounds(
1123  constraint_index,
1124  constraint.has_lower_bound() ? constraint.lower_bound() - sum
1125  : -kInfinity,
1126  constraint.has_upper_bound() ? constraint.upper_bound() - sum
1127  : kInfinity);
1128  }
1129 
1130  // Objective.
1131  {
1132  double sum = 0.0;
1133  const LinearObjective& objective = problem.objective();
1134  const double scaling_factor = objective.scaling_factor();
1135  for (int i = 0; i < objective.literals_size(); ++i) {
1136  const int literal = objective.literals(i);
1137  const double coeff =
1138  static_cast<double>(objective.coefficients(i)) * scaling_factor;
1139  const ColIndex variable_index = ColIndex(abs(literal) - 1);
1140  if (literal < 0) {
1141  sum += coeff;
1142  lp->SetObjectiveCoefficient(variable_index, -coeff);
1143  } else {
1144  lp->SetObjectiveCoefficient(variable_index, coeff);
1145  }
1146  }
1147  lp->SetObjectiveOffset((sum + objective.offset()) * scaling_factor);
1148  lp->SetMaximizationProblem(scaling_factor < 0);
1149  }
1150 
1151  lp->CleanUp();
1152 }
1153 
1155  int num_fixed_variables = 0;
1156  const Trail& trail = solver.LiteralTrail();
1157  for (int i = 0; i < trail.Index(); ++i) {
1158  const BooleanVariable var = trail[i].Variable();
1159  const int value = trail[i].IsPositive() ? 1.0 : 0.0;
1160  if (trail.Info(var).level == 0) {
1161  ++num_fixed_variables;
1162  lp->SetVariableBounds(ColIndex(var.value()), value, value);
1163  }
1164  }
1165  return num_fixed_variables;
1166 }
1167 
1169  const glop::LinearProgram& lp, SatSolver* sat_solver,
1170  double max_time_in_seconds) {
1171  glop::LPSolver solver;
1172  glop::GlopParameters glop_parameters;
1173  glop_parameters.set_max_time_in_seconds(max_time_in_seconds);
1174  solver.SetParameters(glop_parameters);
1175  const glop::ProblemStatus& status = solver.Solve(lp);
1176  if (status != glop::ProblemStatus::OPTIMAL &&
1177  status != glop::ProblemStatus::IMPRECISE &&
1178  status != glop::ProblemStatus::PRIMAL_FEASIBLE) {
1179  return false;
1180  }
1181  for (ColIndex col(0); col < lp.num_variables(); ++col) {
1182  const Fractional& value = solver.variable_values()[col];
1183  sat_solver->SetAssignmentPreference(
1184  Literal(BooleanVariable(col.value()), round(value) == 1),
1185  1 - std::abs(value - round(value)));
1186  }
1187  return true;
1188 }
1189 
1191  LinearBooleanProblem* problem) {
1192  glop::LPSolver solver;
1193  const glop::ProblemStatus& status = solver.Solve(lp);
1194  if (status != glop::ProblemStatus::OPTIMAL &&
1195  status != glop::ProblemStatus::PRIMAL_FEASIBLE)
1196  return false;
1197  int num_variable_fixed = 0;
1198  for (ColIndex col(0); col < lp.num_variables(); ++col) {
1199  const Fractional tolerance = 1e-5;
1200  const Fractional& value = solver.variable_values()[col];
1201  if (value > 1 - tolerance) {
1202  ++num_variable_fixed;
1203  LinearBooleanConstraint* constraint = problem->add_constraints();
1204  constraint->set_lower_bound(1);
1205  constraint->set_upper_bound(1);
1206  constraint->add_coefficients(1);
1207  constraint->add_literals(col.value() + 1);
1208  } else if (value < tolerance) {
1209  ++num_variable_fixed;
1210  LinearBooleanConstraint* constraint = problem->add_constraints();
1211  constraint->set_lower_bound(0);
1212  constraint->set_upper_bound(0);
1213  constraint->add_coefficients(1);
1214  constraint->add_literals(col.value() + 1);
1215  }
1216  }
1217  LOG(INFO) << "LNS with " << num_variable_fixed << " fixed variables.";
1218  return true;
1219 }
1220 
1221 } // namespace sat
1222 } // namespace operations_research
var
IntVar * var
Definition: expr_array.cc:1858
INFO
const int INFO
Definition: log_severity.h:31
min
int64 min
Definition: alldiff_cst.cc:138
integral_types.h
operations_research::sat::SatSolver::SetAssignmentPreference
void SetAssignmentPreference(Literal literal, double weight)
Definition: sat_solver.h:151
VLOG
#define VLOG(verboselevel)
Definition: base/logging.h:978
operations_research::sat::FloorRatio
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:90
max
int64 max
Definition: alldiff_cst.cc:139
coefficients
std::vector< double > coefficients
Definition: sat/lp_utils.cc:497
bound
int64 bound
Definition: routing_search.cc:971
operations_research::ComputeGcdOfRoundedDoubles
int64 ComputeGcdOfRoundedDoubles(const std::vector< double > &x, double scaling_factor)
Definition: fp_utils.cc:189
LOG
#define LOG(severity)
Definition: base/logging.h:420
ERROR
const int ERROR
Definition: log_severity.h:32
operations_research::sat::CeilRatio
IntegerValue CeilRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:81
operations_research::glop::LinearProgram::SetVariableType
void SetVariableType(ColIndex col, VariableType type)
Definition: lp_data.cc:234
wanted_precision
double wanted_precision
Definition: sat/lp_utils.cc:494
operations_research::sat::RemoveNearZeroTerms
void RemoveNearZeroTerms(const SatParameters &params, MPModelProto *mp_model)
Definition: sat/lp_utils.cc:182
FATAL
const int FATAL
Definition: log_severity.h:32
operations_research::sat::Trail::Info
const AssignmentInfo & Info(BooleanVariable var) const
Definition: sat_base.h:381
logging.h
operations_research::sat::SatSolver
Definition: sat_solver.h:58
operations_research::sat::FindRationalFactor
int FindRationalFactor(double x, int limit, double tolerance)
Definition: sat/lp_utils.cc:119
operations_research::glop::LinearProgram::SetConstraintBounds
void SetConstraintBounds(RowIndex row, Fractional lower_bound, Fractional upper_bound)
Definition: lp_data.cc:307
var_indices
std::vector< int > var_indices
Definition: sat/lp_utils.cc:496
value
int64 value
Definition: demon_profiler.cc:43
CHECK_GT
#define CHECK_GT(val1, val2)
Definition: base/logging.h:702
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
WARNING
const int WARNING
Definition: log_severity.h:31
kint64min
static const int64 kint64min
Definition: integral_types.h:60
int64
int64_t int64
Definition: integral_types.h:34
operations_research::glop::LinearProgram::SetMaximizationProblem
void SetMaximizationProblem(bool maximize)
Definition: lp_data.cc:341
operations_research::sat::ConvertBooleanProblemToLinearProgram
void ConvertBooleanProblemToLinearProgram(const LinearBooleanProblem &problem, glop::LinearProgram *lp)
Definition: sat/lp_utils.cc:1090
sat_base.h
max_scaling_factor
double max_scaling_factor
Definition: sat/lp_utils.cc:492
operations_research::sat::ChangeOptimizationDirection
void ChangeOptimizationDirection(LinearBooleanProblem *problem)
Definition: boolean_problem.cc:208
operations_research::MPVariableProto
operations_research::glop::Fractional
double Fractional
Definition: lp_types.h:77
operations_research::glop::LinearProgram::CreateNewVariable
ColIndex CreateNewVariable()
Definition: lp_data.cc:160
operations_research::sat::Trail::Index
int Index() const
Definition: sat_base.h:378
operations_research::glop::LinearProgram::CreateNewConstraint
RowIndex CreateNewConstraint()
Definition: lp_data.cc:189
operations_research::glop::LinearProgram::Clear
void Clear()
Definition: lp_data.cc:132
DCHECK_NE
#define DCHECK_NE(val1, val2)
Definition: base/logging.h:886
operations_research::MPModelProto
operations_research::MPConstraintProto
operations_research::glop::kInfinity
const double kInfinity
Definition: lp_types.h:83
operations_research::sat::SatSolver::LiteralTrail
const Trail & LiteralTrail() const
Definition: sat_solver.h:362
operations_research::glop::LinearProgram::SetVariableBounds
void SetVariableBounds(ColIndex col, Fractional lower_bound, Fractional upper_bound)
Definition: lp_data.cc:247
int_type.h
fp_utils.h
operations_research::ComputeScalingErrors
void ComputeScalingErrors(const std::vector< double > &input, const std::vector< double > &lb, const std::vector< double > &ub, double scaling_factor, double *max_relative_coeff_error, double *max_scaled_sum_error)
Definition: fp_utils.cc:159
CHECK_EQ
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:697
operations_research::glop::LinearProgram::CleanUp
void CleanUp()
Definition: lp_data.cc:345
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::glop::LinearProgram::SetCoefficient
void SetCoefficient(RowIndex row, ColIndex col, Fractional value)
Definition: lp_data.cc:315
LOG_IF
#define LOG_IF(severity, condition)
Definition: base/logging.h:479
DCHECK
#define DCHECK(condition)
Definition: base/logging.h:884
operations_research::sat::NegatedRef
int NegatedRef(int ref)
Definition: cp_model_utils.h:32
operations_research::glop::LinearProgram::SetConstraintName
void SetConstraintName(RowIndex row, absl::string_view name)
Definition: lp_data.cc:243
scaling_target
int64 scaling_target
Definition: sat/lp_utils.cc:495
operations_research::sat::ScaleContinuousVariables
std::vector< double > ScaleContinuousVariables(double scaling, double max_bound, MPModelProto *mp_model)
Definition: sat/lp_utils.cc:100
operations_research::sat::ConvertMPModelProtoToCpModelProto
bool ConvertMPModelProtoToCpModelProto(const SatParameters &params, const MPModelProto &mp_model, CpModelProto *cp_model)
Definition: sat/lp_utils.cc:643
operations_research::glop::LinearProgram::SetObjectiveOffset
void SetObjectiveOffset(Fractional objective_offset)
Definition: lp_data.cc:329
operations_research::sat::SolveLpAndUseSolutionForSatAssignmentPreference
bool SolveLpAndUseSolutionForSatAssignmentPreference(const glop::LinearProgram &lp, SatSolver *sat_solver, double max_time_in_seconds)
Definition: sat/lp_utils.cc:1168
operations_research::sat::Literal
Definition: sat_base.h:64
operations_research::glop::LPSolver::variable_values
const DenseRow & variable_values() const
Definition: lp_solver.h:100
operations_research::glop::LinearProgram::VariableType::INTEGER
@ INTEGER
operations_research::sat::AssignmentInfo::level
uint32 level
Definition: sat_base.h:199
operations_research::glop::ProblemStatus::OPTIMAL
@ OPTIMAL
col
ColIndex col
Definition: markowitz.cc:176
operations_research::GetBestScalingOfDoublesToInt64
double GetBestScalingOfDoublesToInt64(const std::vector< double > &input, const std::vector< double > &lb, const std::vector< double > &ub, int64 max_absolute_sum)
Definition: fp_utils.cc:168
operations_research::glop::LPSolver::Solve
ABSL_MUST_USE_RESULT ProblemStatus Solve(const LinearProgram &lp)
Definition: lp_solver.cc:121
operations_research::glop::ProblemStatus
ProblemStatus
Definition: lp_types.h:101
operations_research::glop::LinearProgram::SetVariableName
void SetVariableName(ColIndex col, absl::string_view name)
Definition: lp_data.cc:230
operations_research::glop::LinearProgram
Definition: lp_data.h:55
operations_research::glop::LinearProgram::SetObjectiveCoefficient
void SetObjectiveCoefficient(ColIndex col, Fractional value)
Definition: lp_data.cc:324
lower_bounds
std::vector< double > lower_bounds
Definition: sat/lp_utils.cc:498
operations_research::glop::LPSolver
Definition: lp_solver.h:29
operations_research::glop::LinearProgram::num_variables
ColIndex num_variables() const
Definition: lp_data.h:205
lp_utils.h
strong_vector.h
VLOG_IS_ON
#define VLOG_IS_ON(verboselevel)
Definition: vlog_is_on.h:41
max_relative_rhs_error
double max_relative_rhs_error
Definition: sat/lp_utils.cc:491
boolean_problem.h
operations_research::sat::DetectImpliedIntegers
std::vector< double > DetectImpliedIntegers(bool log_info, MPModelProto *mp_model)
Definition: sat/lp_utils.cc:235
CHECK_NE
#define CHECK_NE(val1, val2)
Definition: base/logging.h:698
operations_research::sat::SolveLpAndUseIntegerVariableToStartLNS
bool SolveLpAndUseIntegerVariableToStartLNS(const glop::LinearProgram &lp, LinearBooleanProblem *problem)
Definition: sat/lp_utils.cc:1190
operations_research::glop::LPSolver::SetParameters
void SetParameters(const GlopParameters &parameters)
Definition: lp_solver.cc:113
lp_types.h
operations_research::sat::ConvertBinaryMPModelProtoToBooleanProblem
bool ConvertBinaryMPModelProtoToBooleanProblem(const MPModelProto &mp_model, LinearBooleanProblem *problem)
Definition: sat/lp_utils.cc:915
max_relative_coeff_error
double max_relative_coeff_error
Definition: sat/lp_utils.cc:490
upper_bounds
std::vector< double > upper_bounds
Definition: sat/lp_utils.cc:499
literal
Literal literal
Definition: optimization.cc:84
CHECK
#define CHECK(condition)
Definition: base/logging.h:495
operations_research::sat::FixVariablesFromSat
int FixVariablesFromSat(const SatSolver &solver, glop::LinearProgram *lp)
Definition: sat/lp_utils.cc:1154
integer.h
name
const std::string name
Definition: default_search.cc:808
operations_research::sat::Trail
Definition: sat_base.h:233
parameters.pb.h
kint64max
static const int64 kint64max
Definition: integral_types.h:62
lp_solver.h
cp_model_utils.h