forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cp_model_lns.cc
1410 lines (1243 loc) · 52.7 KB
/
cp_model_lns.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/cp_model_lns.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <numeric>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "ortools/sat/cp_model.pb.h"
#include "ortools/sat/cp_model_mapping.h"
#include "ortools/sat/cp_model_utils.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/linear_programming_constraint.h"
#include "ortools/sat/rins.h"
#include "ortools/sat/synchronization.h"
#include "ortools/util/saturated_arithmetic.h"
namespace operations_research {
namespace sat {
NeighborhoodGeneratorHelper::NeighborhoodGeneratorHelper(
CpModelProto const* model_proto, SatParameters const* parameters,
SharedResponseManager* shared_response, SharedTimeLimit* shared_time_limit,
SharedBoundsManager* shared_bounds)
: SubSolver(""),
parameters_(*parameters),
model_proto_(*model_proto),
shared_time_limit_(shared_time_limit),
shared_bounds_(shared_bounds),
shared_response_(shared_response) {
CHECK(shared_response_ != nullptr);
if (shared_bounds_ != nullptr) {
shared_bounds_id_ = shared_bounds_->RegisterNewId();
}
*model_proto_with_only_variables_.mutable_variables() =
model_proto_.variables();
InitializeHelperData();
RecomputeHelperData();
Synchronize();
}
void NeighborhoodGeneratorHelper::Synchronize() {
if (shared_bounds_ != nullptr) {
std::vector<int> model_variables;
std::vector<int64_t> new_lower_bounds;
std::vector<int64_t> new_upper_bounds;
shared_bounds_->GetChangedBounds(shared_bounds_id_, &model_variables,
&new_lower_bounds, &new_upper_bounds);
bool new_variables_have_been_fixed = false;
{
absl::MutexLock domain_lock(&domain_mutex_);
for (int i = 0; i < model_variables.size(); ++i) {
const int var = model_variables[i];
const int64_t new_lb = new_lower_bounds[i];
const int64_t new_ub = new_upper_bounds[i];
if (VLOG_IS_ON(3)) {
const auto& domain =
model_proto_with_only_variables_.variables(var).domain();
const int64_t old_lb = domain.Get(0);
const int64_t old_ub = domain.Get(domain.size() - 1);
VLOG(3) << "Variable: " << var << " old domain: [" << old_lb << ", "
<< old_ub << "] new domain: [" << new_lb << ", " << new_ub
<< "]";
}
const Domain old_domain = ReadDomainFromProto(
model_proto_with_only_variables_.variables(var));
const Domain new_domain =
old_domain.IntersectionWith(Domain(new_lb, new_ub));
if (new_domain.IsEmpty()) {
// This can mean two things:
// 1/ This variable is a normal one and the problem is UNSAT or
// 2/ This variable is optional, and its associated literal must be
// set to false.
//
// Currently, we wait for any full solver to pick the crossing bounds
// and do the correct stuff on their own. We do not want to have empty
// domain in the proto as this would means INFEASIBLE. So we just
// ignore such bounds here.
//
// TODO(user): We could set the optional literal to false directly in
// the bound sharing manager. We do have to be careful that all the
// different solvers have the same optionality definition though.
continue;
}
FillDomainInProto(
new_domain,
model_proto_with_only_variables_.mutable_variables(var));
new_variables_have_been_fixed |= new_domain.IsFixed();
}
}
// Only trigger the computation if needed.
if (new_variables_have_been_fixed) {
RecomputeHelperData();
}
}
}
void NeighborhoodGeneratorHelper::InitializeHelperData() {
type_to_constraints_.clear();
const int num_constraints = model_proto_.constraints_size();
for (int c = 0; c < num_constraints; ++c) {
const int type = model_proto_.constraints(c).constraint_case();
if (type >= type_to_constraints_.size()) {
type_to_constraints_.resize(type + 1);
}
type_to_constraints_[type].push_back(c);
}
}
void NeighborhoodGeneratorHelper::RecomputeHelperData() {
// Recompute all the data in case new variables have been fixed.
//
// TODO(user): Ideally we should ignore trivially true/false constraint, but
// this will duplicate already existing code :-( we should probably still do
// at least enforcement literal and clauses? We could maybe run a light
// presolve?
absl::MutexLock graph_lock(&graph_mutex_);
absl::ReaderMutexLock domain_lock(&domain_mutex_);
var_to_constraint_.assign(model_proto_.variables_size(), {});
constraint_to_var_.assign(model_proto_.constraints_size(), {});
for (int ct_index = 0; ct_index < model_proto_.constraints_size();
++ct_index) {
for (const int var : UsedVariables(model_proto_.constraints(ct_index))) {
DCHECK(RefIsPositive(var));
if (IsConstant(var)) continue;
var_to_constraint_[var].push_back(ct_index);
constraint_to_var_[ct_index].push_back(var);
}
// We replace intervals by their underlying integer variables.
if (parameters_.lns_expand_intervals_in_constraint_graph()) {
for (const int interval :
UsedIntervals(model_proto_.constraints(ct_index))) {
for (const int var :
UsedVariables(model_proto_.constraints(interval))) {
DCHECK(RefIsPositive(var));
if (IsConstant(var)) continue;
var_to_constraint_[var].push_back(ct_index);
constraint_to_var_[ct_index].push_back(var);
}
}
}
}
active_variables_.clear();
active_variables_set_.assign(model_proto_.variables_size(), false);
if (parameters_.lns_focus_on_decision_variables()) {
for (const auto& search_strategy : model_proto_.search_strategy()) {
for (const int var : search_strategy.variables()) {
const int pos_var = PositiveRef(var);
if (!active_variables_set_[pos_var] && !IsConstant(pos_var)) {
active_variables_set_[pos_var] = true;
active_variables_.push_back(pos_var);
}
}
}
// Revert to no focus if active_variables_ is empty().
if (!active_variables_.empty()) return;
}
// Add all non-constant variables.
for (int i = 0; i < model_proto_.variables_size(); ++i) {
if (!IsConstant(i)) {
active_variables_.push_back(i);
active_variables_set_[i] = true;
}
}
}
bool NeighborhoodGeneratorHelper::IsActive(int var) const {
return active_variables_set_[var];
}
bool NeighborhoodGeneratorHelper::IsConstant(int var) const {
return model_proto_with_only_variables_.variables(var).domain_size() == 2 &&
model_proto_with_only_variables_.variables(var).domain(0) ==
model_proto_with_only_variables_.variables(var).domain(1);
}
bool NeighborhoodGeneratorHelper::CopyAndFixVariables(
const CpModelProto& source_model,
const absl::flat_hash_set<int>& fixed_variables_set,
const CpSolverResponse& initial_solution,
CpModelProto* output_model) const {
output_model->mutable_variables()->Clear();
output_model->mutable_variables()->Reserve(source_model.variables_size());
for (int i = 0; i < source_model.variables_size(); ++i) {
IntegerVariableProto* var_proto = output_model->add_variables();
const IntegerVariableProto& source_var_proto = source_model.variables(i);
// We only copy the variable names in debug mode.
if (DEBUG_MODE && !source_var_proto.name().empty()) {
var_proto->set_name(source_var_proto.name());
}
if (fixed_variables_set.contains(i)) {
const int64_t value = initial_solution.solution(i);
if (!DomainInProtoContains(source_model.variables(i), value)) {
return false;
}
var_proto->add_domain(value);
var_proto->add_domain(value);
} else {
*var_proto->mutable_domain() = source_var_proto.domain();
}
}
return true;
}
Neighborhood NeighborhoodGeneratorHelper::FullNeighborhood() const {
Neighborhood neighborhood;
neighborhood.is_reduced = false;
neighborhood.is_generated = true;
{
absl::ReaderMutexLock lock(&domain_mutex_);
*neighborhood.delta.mutable_variables() =
model_proto_with_only_variables_.variables();
}
return neighborhood;
}
Neighborhood NeighborhoodGeneratorHelper::NoNeighborhood() const {
Neighborhood neighborhood;
neighborhood.is_generated = false;
return neighborhood;
}
std::vector<int> NeighborhoodGeneratorHelper::GetActiveIntervals(
const CpSolverResponse& initial_solution) const {
std::vector<int> active_intervals;
absl::ReaderMutexLock lock(&domain_mutex_);
for (const int i : TypeToConstraints(ConstraintProto::kInterval)) {
const ConstraintProto& interval_ct = ModelProto().constraints(i);
// We only look at intervals that are performed in the solution. The
// unperformed intervals should be automatically freed during the generation
// phase.
if (interval_ct.enforcement_literal().size() == 1) {
const int enforcement_ref = interval_ct.enforcement_literal(0);
const int enforcement_var = PositiveRef(enforcement_ref);
const int value = initial_solution.solution(enforcement_var);
if (RefIsPositive(enforcement_ref) == (value == 0)) {
continue;
}
}
// We filter out fixed intervals. Because of presolve, if there is an
// enforcement literal, it cannot be fixed.
if (interval_ct.enforcement_literal().empty()) {
if (interval_ct.interval().has_start_view()) {
bool is_constant = true;
for (const int v : interval_ct.interval().start_view().vars()) {
if (!IsConstant(v)) {
is_constant = false;
break;
}
}
for (const int v : interval_ct.interval().size_view().vars()) {
if (!IsConstant(v)) {
is_constant = false;
break;
}
}
for (const int v : interval_ct.interval().end_view().vars()) {
if (!IsConstant(v)) {
is_constant = false;
break;
}
}
if (is_constant) continue;
} else {
if (IsConstant(PositiveRef(interval_ct.interval().start())) &&
IsConstant(PositiveRef(interval_ct.interval().size())) &&
IsConstant(PositiveRef(interval_ct.interval().end()))) {
continue;
}
}
}
active_intervals.push_back(i);
}
return active_intervals;
}
std::vector<std::vector<int>> NeighborhoodGeneratorHelper::GetRoutingPaths(
const CpSolverResponse& initial_solution) const {
struct HeadAndArcLiteral {
int head;
int literal;
};
std::vector<std::vector<int>> result;
absl::flat_hash_map<int, HeadAndArcLiteral> tail_to_head_and_arc_literal;
for (const int i : TypeToConstraints(ConstraintProto::kCircuit)) {
const CircuitConstraintProto& ct = ModelProto().constraints(i).circuit();
// Collect arcs.
int min_node = std::numeric_limits<int>::max();
tail_to_head_and_arc_literal.clear();
for (int i = 0; i < ct.literals_size(); ++i) {
const int literal = ct.literals(i);
const int head = ct.heads(i);
const int tail = ct.tails(i);
const int bool_var = PositiveRef(literal);
const int64_t value = initial_solution.solution(bool_var);
// Skip unselected arcs.
if (RefIsPositive(literal) == (value == 0)) continue;
// Ignore self loops.
if (head == tail) continue;
tail_to_head_and_arc_literal[tail] = {head, bool_var};
min_node = std::min(tail, min_node);
}
if (tail_to_head_and_arc_literal.empty()) continue;
// Unroll the path.
int current_node = min_node;
std::vector<int> path;
do {
auto it = tail_to_head_and_arc_literal.find(current_node);
CHECK(it != tail_to_head_and_arc_literal.end());
current_node = it->second.head;
path.push_back(it->second.literal);
} while (current_node != min_node);
result.push_back(std::move(path));
}
std::vector<HeadAndArcLiteral> route_starts;
for (const int i : TypeToConstraints(ConstraintProto::kRoutes)) {
const RoutesConstraintProto& ct = ModelProto().constraints(i).routes();
tail_to_head_and_arc_literal.clear();
route_starts.clear();
// Collect route starts and arcs.
for (int i = 0; i < ct.literals_size(); ++i) {
const int literal = ct.literals(i);
const int head = ct.heads(i);
const int tail = ct.tails(i);
const int bool_var = PositiveRef(literal);
const int64_t value = initial_solution.solution(bool_var);
// Skip unselected arcs.
if (RefIsPositive(literal) == (value == 0)) continue;
// Ignore self loops.
if (head == tail) continue;
if (tail == 0) {
route_starts.push_back({head, bool_var});
} else {
tail_to_head_and_arc_literal[tail] = {head, bool_var};
}
}
// Unroll all routes.
for (const HeadAndArcLiteral& head_var : route_starts) {
std::vector<int> path;
int current_node = head_var.head;
path.push_back(head_var.literal);
do {
auto it = tail_to_head_and_arc_literal.find(current_node);
CHECK(it != tail_to_head_and_arc_literal.end());
current_node = it->second.head;
path.push_back(it->second.literal);
} while (current_node != 0);
result.push_back(std::move(path));
}
}
return result;
}
Neighborhood NeighborhoodGeneratorHelper::FixGivenVariables(
const CpSolverResponse& initial_solution,
const absl::flat_hash_set<int>& variables_to_fix) const {
Neighborhood neighborhood;
bool copy_is_successful = true;
{
absl::ReaderMutexLock domain_lock(&domain_mutex_);
copy_is_successful =
CopyAndFixVariables(model_proto_with_only_variables_, variables_to_fix,
initial_solution, &neighborhood.delta);
}
if (!copy_is_successful) {
return NoNeighborhood();
}
AddSolutionHinting(initial_solution, &neighborhood.delta);
neighborhood.is_generated = true;
neighborhood.is_reduced = !variables_to_fix.empty();
// TODO(user): force better objective? Note that this is already done when the
// hint above is successfully loaded (i.e. if it passes the presolve
// correctly) since the solver will try to find better solution than the
// current one.
return neighborhood;
}
void NeighborhoodGeneratorHelper::AddSolutionHinting(
const CpSolverResponse& initial_solution, CpModelProto* model_proto) const {
// Set the current solution as a hint.
model_proto->clear_solution_hint();
const auto is_fixed = [model_proto](int var) {
const IntegerVariableProto& var_proto = model_proto->variables(var);
return var_proto.domain_size() == 2 &&
var_proto.domain(0) == var_proto.domain(1);
};
for (int var = 0; var < model_proto->variables_size(); ++var) {
if (is_fixed(var)) continue;
model_proto->mutable_solution_hint()->add_vars(var);
model_proto->mutable_solution_hint()->add_values(
initial_solution.solution(var));
}
}
Neighborhood NeighborhoodGeneratorHelper::RemoveMarkedConstraints(
const std::vector<int>& constraints_to_remove) const {
Neighborhood neighborhood = FullNeighborhood();
if (constraints_to_remove.empty()) return neighborhood;
neighborhood.is_reduced = false;
neighborhood.constraints_to_ignore = constraints_to_remove;
return neighborhood;
}
Neighborhood NeighborhoodGeneratorHelper::RelaxGivenVariables(
const CpSolverResponse& initial_solution,
const std::vector<int>& relaxed_variables) const {
std::vector<bool> relaxed_variables_set(model_proto_.variables_size(), false);
for (const int var : relaxed_variables) relaxed_variables_set[var] = true;
absl::flat_hash_set<int> fixed_variables;
{
absl::ReaderMutexLock graph_lock(&graph_mutex_);
for (const int i : active_variables_) {
if (!relaxed_variables_set[i]) {
fixed_variables.insert(i);
}
}
}
return FixGivenVariables(initial_solution, fixed_variables);
}
Neighborhood NeighborhoodGeneratorHelper::FixAllVariables(
const CpSolverResponse& initial_solution) const {
const std::vector<int>& all_variables = ActiveVariables();
const absl::flat_hash_set<int> fixed_variables(all_variables.begin(),
all_variables.end());
return FixGivenVariables(initial_solution, fixed_variables);
}
bool NeighborhoodGenerator::ReadyToGenerate() const {
return (helper_.shared_response().SolutionsRepository().NumSolutions() > 0);
}
double NeighborhoodGenerator::GetUCBScore(int64_t total_num_calls) const {
absl::ReaderMutexLock mutex_lock(&generator_mutex_);
DCHECK_GE(total_num_calls, num_calls_);
if (num_calls_ <= 10) return std::numeric_limits<double>::infinity();
return current_average_ + sqrt((2 * log(total_num_calls)) / num_calls_);
}
void NeighborhoodGenerator::Synchronize() {
absl::MutexLock mutex_lock(&generator_mutex_);
// To make the whole update process deterministic, we currently sort the
// SolveData.
std::sort(solve_data_.begin(), solve_data_.end());
// This will be used to update the difficulty of this neighborhood.
int num_fully_solved_in_batch = 0;
int num_not_fully_solved_in_batch = 0;
for (const SolveData& data : solve_data_) {
AdditionalProcessingOnSynchronize(data);
++num_calls_;
// INFEASIBLE or OPTIMAL means that we "fully solved" the local problem.
// If we didn't, then we cannot be sure that there is no improving solution
// in that neighborhood.
if (data.status == CpSolverStatus::INFEASIBLE ||
data.status == CpSolverStatus::OPTIMAL) {
++num_fully_solved_calls_;
++num_fully_solved_in_batch;
} else {
++num_not_fully_solved_in_batch;
}
// It seems to make more sense to compare the new objective to the base
// solution objective, not the best one. However this causes issue in the
// logic below because on some problems the neighborhood can always lead
// to a better "new objective" if the base solution wasn't the best one.
//
// This might not be a final solution, but it does work ok for now.
const IntegerValue best_objective_improvement =
IsRelaxationGenerator()
? IntegerValue(CapSub(data.new_objective_bound.value(),
data.initial_best_objective_bound.value()))
: IntegerValue(CapSub(data.initial_best_objective.value(),
data.new_objective.value()));
if (best_objective_improvement > 0) {
num_consecutive_non_improving_calls_ = 0;
} else {
++num_consecutive_non_improving_calls_;
}
// TODO(user): Weight more recent data.
// degrade the current average to forget old learnings.
const double gain_per_time_unit =
std::max(0.0, static_cast<double>(best_objective_improvement.value())) /
(1.0 + data.deterministic_time);
if (num_calls_ <= 100) {
current_average_ += (gain_per_time_unit - current_average_) / num_calls_;
} else {
current_average_ = 0.9 * current_average_ + 0.1 * gain_per_time_unit;
}
deterministic_time_ += data.deterministic_time;
}
// Update the difficulty.
difficulty_.Update(/*num_decreases=*/num_not_fully_solved_in_batch,
/*num_increases=*/num_fully_solved_in_batch);
// Bump the time limit if we saw no better solution in the last few calls.
// This means that as the search progress, we likely spend more and more time
// trying to solve individual neighborhood.
//
// TODO(user): experiment with resetting the time limit if a solution is
// found.
if (num_consecutive_non_improving_calls_ > 50) {
num_consecutive_non_improving_calls_ = 0;
deterministic_limit_ *= 1.02;
// We do not want the limit to go to high. Intuitively, the goal is to try
// out a lot of neighborhoods, not just spend a lot of time on a few.
deterministic_limit_ = std::min(60.0, deterministic_limit_);
}
solve_data_.clear();
}
namespace {
void GetRandomSubset(double relative_size, std::vector<int>* base,
absl::BitGenRef random) {
if (base->empty()) return;
// TODO(user): we could generate this more efficiently than using random
// shuffle.
std::shuffle(base->begin(), base->end(), random);
const int target_size = std::round(relative_size * base->size());
base->resize(target_size);
}
} // namespace
Neighborhood RelaxRandomVariablesGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
std::vector<int> fixed_variables = helper_.ActiveVariables();
GetRandomSubset(1.0 - difficulty, &fixed_variables, random);
return helper_.FixGivenVariables(
initial_solution, {fixed_variables.begin(), fixed_variables.end()});
}
Neighborhood RelaxRandomConstraintsGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
std::vector<int> active_constraints;
for (int ct = 0; ct < helper_.ModelProto().constraints_size(); ++ct) {
if (helper_.ModelProto().constraints(ct).constraint_case() ==
ConstraintProto::CONSTRAINT_NOT_SET) {
continue;
}
active_constraints.push_back(ct);
}
if (active_constraints.empty() ||
helper_.DifficultyMeansFullNeighborhood(difficulty)) {
return helper_.FullNeighborhood();
}
std::shuffle(active_constraints.begin(), active_constraints.end(), random);
const int num_model_vars = helper_.ModelProto().variables_size();
const int num_model_constraints = helper_.ModelProto().constraints_size();
std::vector<bool> visited_variables_set(num_model_vars, false);
std::vector<int> relaxed_variables;
{
absl::ReaderMutexLock graph_lock(&helper_.graph_mutex_);
const int num_active_vars =
helper_.ActiveVariablesWhileHoldingLock().size();
const int target_size = std::ceil(difficulty * num_active_vars);
CHECK_GT(target_size, 0);
for (const int constraint_index : active_constraints) {
CHECK_LT(constraint_index, num_model_constraints);
for (const int var : helper_.ConstraintToVar()[constraint_index]) {
if (visited_variables_set[var]) continue;
visited_variables_set[var] = true;
if (helper_.IsActive(var)) {
relaxed_variables.push_back(var);
if (relaxed_variables.size() == target_size) break;
}
}
if (relaxed_variables.size() == target_size) break;
}
}
return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
}
Neighborhood VariableGraphNeighborhoodGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
if (helper_.DifficultyMeansFullNeighborhood(difficulty)) {
return helper_.FullNeighborhood();
}
const int num_model_vars = helper_.ModelProto().variables_size();
std::vector<bool> visited_variables_set(num_model_vars, false);
std::vector<int> relaxed_variables;
std::vector<int> visited_variables;
// It is important complexity wise to never scan a constraint twice!
const int num_model_constraints = helper_.ModelProto().constraints_size();
std::vector<bool> scanned_constraints(num_model_constraints, false);
std::vector<int> random_variables;
{
absl::ReaderMutexLock graph_lock(&helper_.graph_mutex_);
// The number of active variables can decrease asynchronously.
// We read the exact number while locked.
const int num_active_vars =
helper_.ActiveVariablesWhileHoldingLock().size();
const int target_size = std::ceil(difficulty * num_active_vars);
CHECK_GT(target_size, 0) << difficulty << " " << num_active_vars;
const int first_var =
helper_.ActiveVariablesWhileHoldingLock()[absl::Uniform<int>(
random, 0, num_active_vars)];
visited_variables_set[first_var] = true;
visited_variables.push_back(first_var);
relaxed_variables.push_back(first_var);
for (int i = 0; i < visited_variables.size(); ++i) {
random_variables.clear();
// Collect all the variables that appears in the same constraints as
// visited_variables[i].
for (const int ct : helper_.VarToConstraint()[visited_variables[i]]) {
if (scanned_constraints[ct]) continue;
scanned_constraints[ct] = true;
for (const int var : helper_.ConstraintToVar()[ct]) {
if (visited_variables_set[var]) continue;
visited_variables_set[var] = true;
random_variables.push_back(var);
}
}
// We always randomize to change the partial subgraph explored
// afterwards.
std::shuffle(random_variables.begin(), random_variables.end(), random);
for (const int var : random_variables) {
if (relaxed_variables.size() < target_size) {
visited_variables.push_back(var);
if (helper_.IsActive(var)) {
relaxed_variables.push_back(var);
}
} else {
break;
}
}
if (relaxed_variables.size() >= target_size) break;
}
}
return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
}
Neighborhood ConstraintGraphNeighborhoodGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
const int num_model_constraints = helper_.ModelProto().constraints_size();
if (num_model_constraints == 0 ||
helper_.DifficultyMeansFullNeighborhood(difficulty)) {
return helper_.FullNeighborhood();
}
const int num_model_vars = helper_.ModelProto().variables_size();
std::vector<bool> visited_variables_set(num_model_vars, false);
std::vector<int> relaxed_variables;
std::vector<bool> added_constraints(num_model_constraints, false);
std::vector<int> next_constraints;
// Start by a random constraint.
next_constraints.push_back(
absl::Uniform<int>(random, 0, num_model_constraints));
added_constraints[next_constraints.back()] = true;
std::vector<int> random_variables;
{
absl::ReaderMutexLock graph_lock(&helper_.graph_mutex_);
const int num_active_vars =
helper_.ActiveVariablesWhileHoldingLock().size();
const int target_size = std::ceil(difficulty * num_active_vars);
CHECK_GT(target_size, 0);
while (relaxed_variables.size() < target_size) {
// Stop if we have a full connected component.
if (next_constraints.empty()) break;
// Pick a random unprocessed constraint.
const int i = absl::Uniform<int>(random, 0, next_constraints.size());
const int constraint_index = next_constraints[i];
std::swap(next_constraints[i], next_constraints.back());
next_constraints.pop_back();
// Add all the variable of this constraint and increase the set of next
// possible constraints.
CHECK_LT(constraint_index, num_model_constraints);
random_variables = helper_.ConstraintToVar()[constraint_index];
std::shuffle(random_variables.begin(), random_variables.end(), random);
for (const int var : random_variables) {
if (visited_variables_set[var]) continue;
visited_variables_set[var] = true;
if (helper_.IsActive(var)) {
relaxed_variables.push_back(var);
}
if (relaxed_variables.size() == target_size) break;
for (const int ct : helper_.VarToConstraint()[var]) {
if (added_constraints[ct]) continue;
added_constraints[ct] = true;
next_constraints.push_back(ct);
}
}
}
}
return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
}
namespace {
LinearExpressionProto GetStart(const IntervalConstraintProto& interval) {
if (interval.has_start_view()) return interval.start_view();
LinearExpressionProto result;
result.add_vars(interval.start());
result.add_coeffs(1);
return result;
}
LinearExpressionProto GetSize(const IntervalConstraintProto& interval) {
if (interval.has_size_view()) return interval.size_view();
LinearExpressionProto result;
result.add_vars(interval.size());
result.add_coeffs(1);
return result;
}
LinearExpressionProto GetEnd(const IntervalConstraintProto& interval) {
if (interval.has_end_view()) return interval.end_view();
LinearExpressionProto result;
result.add_vars(interval.end());
result.add_coeffs(1);
return result;
}
int64_t GetLinearExpressionValue(const LinearExpressionProto& expr,
const CpSolverResponse& initial_solution) {
int64_t result = expr.offset();
for (int i = 0; i < expr.vars_size(); ++i) {
result += expr.coeffs(i) * initial_solution.solution(expr.vars(i));
}
return result;
}
void AddLinearExpressionToConstraint(const int64_t coeff,
const LinearExpressionProto& expr,
LinearConstraintProto* constraint,
int64_t* rhs_offset) {
*rhs_offset -= coeff * expr.offset();
for (int i = 0; i < expr.vars_size(); ++i) {
constraint->add_vars(expr.vars(i));
constraint->add_coeffs(expr.coeffs(i) * coeff);
}
}
void AddPrecedenceConstraints(const absl::Span<const int> intervals,
const absl::flat_hash_set<int>& ignored_intervals,
const CpSolverResponse& initial_solution,
const NeighborhoodGeneratorHelper& helper,
Neighborhood* neighborhood) {
// Sort all non-relaxed intervals of this constraint by current start
// time.
std::vector<std::pair<int64_t, int>> start_interval_pairs;
for (const int i : intervals) {
if (ignored_intervals.contains(i)) continue;
const ConstraintProto& interval_ct = helper.ModelProto().constraints(i);
// TODO(user): we ignore size zero for now.
const LinearExpressionProto size_var = GetSize(interval_ct.interval());
if (GetLinearExpressionValue(size_var, initial_solution) == 0) continue;
const LinearExpressionProto start_var = GetStart(interval_ct.interval());
const int64_t start_value =
GetLinearExpressionValue(start_var, initial_solution);
start_interval_pairs.push_back({start_value, i});
}
std::sort(start_interval_pairs.begin(), start_interval_pairs.end());
// Add precedence between the remaining intervals, forcing their order.
for (int i = 0; i + 1 < start_interval_pairs.size(); ++i) {
const LinearExpressionProto before_start =
GetStart(helper.ModelProto()
.constraints(start_interval_pairs[i].second)
.interval());
const LinearExpressionProto before_end =
GetEnd(helper.ModelProto()
.constraints(start_interval_pairs[i].second)
.interval());
const LinearExpressionProto after_start =
GetStart(helper.ModelProto()
.constraints(start_interval_pairs[i + 1].second)
.interval());
// If the end was smaller we keep it that way, otherwise we just order the
// start variables.
LinearConstraintProto* linear =
neighborhood->delta.add_constraints()->mutable_linear();
linear->add_domain(std::numeric_limits<int64_t>::min());
int64_t rhs_offset = 0;
if (GetLinearExpressionValue(before_end, initial_solution) <=
GetLinearExpressionValue(after_start, initial_solution)) {
// If the end was smaller than the next start, keep it that way.
AddLinearExpressionToConstraint(1, before_end, linear, &rhs_offset);
} else {
// Otherwise, keep the same minimum separation. This is done in order
// to "simplify" the neighborhood.
rhs_offset = GetLinearExpressionValue(before_start, initial_solution) -
GetLinearExpressionValue(after_start, initial_solution);
AddLinearExpressionToConstraint(1, before_start, linear, &rhs_offset);
}
AddLinearExpressionToConstraint(-1, after_start, linear, &rhs_offset);
linear->add_domain(rhs_offset);
// The linear constraint should be satisfied by the current solution.
if (DEBUG_MODE) {
int64_t activity = 0;
for (int i = 0; i < linear->vars().size(); ++i) {
activity +=
linear->coeffs(i) * initial_solution.solution(linear->vars(i));
}
CHECK_GE(activity, linear->domain(0));
CHECK_LE(activity, linear->domain(1));
}
}
}
} // namespace
Neighborhood GenerateSchedulingNeighborhoodForRelaxation(
const absl::Span<const int> intervals_to_relax,
const CpSolverResponse& initial_solution,
const NeighborhoodGeneratorHelper& helper) {
Neighborhood neighborhood = helper.FullNeighborhood();
neighborhood.is_reduced =
(intervals_to_relax.size() <
helper.TypeToConstraints(ConstraintProto::kInterval).size());
// We will extend the set with some interval that we cannot fix.
absl::flat_hash_set<int> ignored_intervals(intervals_to_relax.begin(),
intervals_to_relax.end());
// Fix the presence/absence of non-relaxed intervals.
for (const int i : helper.TypeToConstraints(ConstraintProto::kInterval)) {
DCHECK_GE(i, 0);
if (ignored_intervals.contains(i)) continue;
const ConstraintProto& interval_ct = helper.ModelProto().constraints(i);
if (interval_ct.enforcement_literal().empty()) continue;
CHECK_EQ(interval_ct.enforcement_literal().size(), 1);
const int enforcement_ref = interval_ct.enforcement_literal(0);
const int enforcement_var = PositiveRef(enforcement_ref);
const int value = initial_solution.solution(enforcement_var);
// If the interval is not enforced, we just relax it. If it belongs to an
// exactly one constraint, and the enforced interval is not relaxed, then
// propagation will force this interval to stay not enforced. Otherwise,
// LNS will be able to change which interval will be enforced among all
// alternatives.
if (RefIsPositive(enforcement_ref) == (value == 0)) {
ignored_intervals.insert(i);
continue;
}
// Fix the value.
neighborhood.delta.mutable_variables(enforcement_var)->clear_domain();
neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
}
for (const int c : helper.TypeToConstraints(ConstraintProto::kNoOverlap)) {
AddPrecedenceConstraints(
helper.ModelProto().constraints(c).no_overlap().intervals(),
ignored_intervals, initial_solution, helper, &neighborhood);
}
for (const int c : helper.TypeToConstraints(ConstraintProto::kCumulative)) {
AddPrecedenceConstraints(
helper.ModelProto().constraints(c).cumulative().intervals(),
ignored_intervals, initial_solution, helper, &neighborhood);
}
for (const int c : helper.TypeToConstraints(ConstraintProto::kNoOverlap2D)) {
AddPrecedenceConstraints(
helper.ModelProto().constraints(c).no_overlap_2d().x_intervals(),
ignored_intervals, initial_solution, helper, &neighborhood);
AddPrecedenceConstraints(
helper.ModelProto().constraints(c).no_overlap_2d().y_intervals(),
ignored_intervals, initial_solution, helper, &neighborhood);
}
// Set the current solution as a hint.
helper.AddSolutionHinting(initial_solution, &neighborhood.delta);
neighborhood.is_generated = true;
return neighborhood;
}
Neighborhood SchedulingNeighborhoodGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
std::vector<int> intervals_to_relax =
helper_.GetActiveIntervals(initial_solution);
GetRandomSubset(difficulty, &intervals_to_relax, random);
return GenerateSchedulingNeighborhoodForRelaxation(intervals_to_relax,
initial_solution, helper_);
}
Neighborhood SchedulingTimeWindowNeighborhoodGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
std::vector<std::pair<int64_t, int>> start_interval_pairs;
const std::vector<int> active_intervals =
helper_.GetActiveIntervals(initial_solution);
std::vector<int> intervals_to_relax;
if (active_intervals.empty()) return helper_.FullNeighborhood();
for (const int i : active_intervals) {
const ConstraintProto& interval_ct = helper_.ModelProto().constraints(i);
const LinearExpressionProto start_var = GetStart(interval_ct.interval());
const int64_t start_value =
GetLinearExpressionValue(start_var, initial_solution);
start_interval_pairs.push_back({start_value, i});
}
std::sort(start_interval_pairs.begin(), start_interval_pairs.end());
const int relaxed_size = std::floor(difficulty * start_interval_pairs.size());
std::uniform_int_distribution<int> random_var(
0, start_interval_pairs.size() - relaxed_size - 1);
const int random_start_index = random_var(random);
// TODO(user): Consider relaxing more than one time window
// intervals. This seems to help with Giza models.
for (int i = random_start_index; i < relaxed_size; ++i) {
intervals_to_relax.push_back(start_interval_pairs[i].second);
}
return GenerateSchedulingNeighborhoodForRelaxation(intervals_to_relax,
initial_solution, helper_);
}
Neighborhood RoutingRandomNeighborhoodGenerator::Generate(
const CpSolverResponse& initial_solution, double difficulty,
absl::BitGenRef random) {
const std::vector<std::vector<int>> all_paths =