forked from rte-france/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
revised_simplex.cc
3890 lines (3519 loc) · 160 KB
/
revised_simplex.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-2022 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/glop/revised_simplex.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/strong_vector.h"
#include "ortools/glop/initial_basis.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/lp_data/lp_data.h"
#include "ortools/lp_data/lp_print_utils.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/lp_data/lp_utils.h"
#include "ortools/lp_data/matrix_utils.h"
#include "ortools/lp_data/permutation.h"
#include "ortools/util/fp_utils.h"
ABSL_FLAG(bool, simplex_display_numbers_as_fractions, false,
"Display numbers as fractions.");
ABSL_FLAG(bool, simplex_stop_after_first_basis, false,
"Stop after first basis has been computed.");
ABSL_FLAG(bool, simplex_stop_after_feasibility, false,
"Stop after first phase has been completed.");
ABSL_FLAG(bool, simplex_display_stats, false, "Display algorithm statistics.");
namespace operations_research {
namespace glop {
namespace {
// Calls the given closure upon destruction. It can be used to ensure that a
// closure is executed whenever a function returns.
class Cleanup {
public:
explicit Cleanup(std::function<void()> closure)
: closure_(std::move(closure)) {}
~Cleanup() { closure_(); }
private:
std::function<void()> closure_;
};
} // namespace
#define DCHECK_COL_BOUNDS(col) \
{ \
DCHECK_LE(0, col); \
DCHECK_GT(num_cols_, col); \
}
// TODO(user): Remove this function.
#define DCHECK_ROW_BOUNDS(row) \
{ \
DCHECK_LE(0, row); \
DCHECK_GT(num_rows_, row); \
}
constexpr const uint64_t kDeterministicSeed = 42;
RevisedSimplex::RevisedSimplex()
: problem_status_(ProblemStatus::INIT),
objective_(),
basis_(),
variable_name_(),
direction_(),
error_(),
deterministic_random_(kDeterministicSeed),
random_(deterministic_random_),
basis_factorization_(&compact_matrix_, &basis_),
variables_info_(compact_matrix_),
primal_edge_norms_(compact_matrix_, variables_info_,
basis_factorization_),
dual_edge_norms_(basis_factorization_),
dual_prices_(random_),
variable_values_(parameters_, compact_matrix_, basis_, variables_info_,
basis_factorization_, &dual_edge_norms_, &dual_prices_),
update_row_(compact_matrix_, transposed_matrix_, variables_info_, basis_,
basis_factorization_),
reduced_costs_(compact_matrix_, objective_, basis_, variables_info_,
basis_factorization_, random_),
entering_variable_(variables_info_, random_, &reduced_costs_),
primal_prices_(random_, variables_info_, &primal_edge_norms_,
&reduced_costs_),
iteration_stats_(),
ratio_test_stats_(),
function_stats_("SimplexFunctionStats"),
parameters_(),
test_lu_() {
SetParameters(parameters_);
}
void RevisedSimplex::ClearStateForNextSolve() {
SCOPED_TIME_STAT(&function_stats_);
solution_state_.statuses.clear();
variable_starting_values_.clear();
}
void RevisedSimplex::LoadStateForNextSolve(const BasisState& state) {
SCOPED_TIME_STAT(&function_stats_);
solution_state_ = state;
solution_state_has_been_set_externally_ = true;
}
void RevisedSimplex::SetStartingVariableValuesForNextSolve(
const DenseRow& values) {
variable_starting_values_ = values;
}
void RevisedSimplex::NotifyThatMatrixIsUnchangedForNextSolve() {
notify_that_matrix_is_unchanged_ = true;
}
Status RevisedSimplex::Solve(const LinearProgram& lp, TimeLimit* time_limit) {
SCOPED_TIME_STAT(&function_stats_);
DCHECK(lp.IsCleanedUp());
GLOP_RETURN_ERROR_IF_NULL(time_limit);
Cleanup update_deterministic_time_on_return(
[this, time_limit]() { AdvanceDeterministicTime(time_limit); });
default_logger_.EnableLogging(parameters_.log_search_progress());
default_logger_.SetLogToStdOut(parameters_.log_to_stdout());
SOLVER_LOG(logger_, "");
// Initialization. Note That Initialize() must be called first since it
// analyzes the current solver state.
const double start_time = time_limit->GetElapsedTime();
GLOP_RETURN_IF_ERROR(Initialize(lp));
if (logger_->LoggingIsEnabled()) {
DisplayBasicVariableStatistics();
}
dual_infeasibility_improvement_direction_.clear();
update_row_.Invalidate();
test_lu_.Clear();
problem_status_ = ProblemStatus::INIT;
phase_ = Phase::FEASIBILITY;
num_iterations_ = 0;
num_feasibility_iterations_ = 0;
num_optimization_iterations_ = 0;
num_push_iterations_ = 0;
feasibility_time_ = 0.0;
optimization_time_ = 0.0;
push_time_ = 0.0;
total_time_ = 0.0;
// In case we abort because of an error, we cannot assume that the current
// solution state will be in sync with all our internal data structure. In
// case we abort without resetting it, setting this allow us to still use the
// previous state info, but we will double-check everything.
solution_state_has_been_set_externally_ = true;
if (VLOG_IS_ON(2)) {
ComputeNumberOfEmptyRows();
ComputeNumberOfEmptyColumns();
DisplayProblem();
}
if (absl::GetFlag(FLAGS_simplex_stop_after_first_basis)) {
DisplayAllStats();
return Status::OK();
}
const bool use_dual = parameters_.use_dual_simplex();
// TODO(user): Avoid doing the first phase checks when we know from the
// incremental solve that the solution is already dual or primal feasible.
SOLVER_LOG(logger_, "");
primal_edge_norms_.SetPricingRule(parameters_.feasibility_rule());
if (use_dual) {
if (parameters_.perturb_costs_in_dual_simplex()) {
reduced_costs_.PerturbCosts();
}
if (parameters_.use_dedicated_dual_feasibility_algorithm()) {
variables_info_.MakeBoxedVariableRelevant(false);
GLOP_RETURN_IF_ERROR(
DualMinimize(phase_ == Phase::FEASIBILITY, time_limit));
if (problem_status_ != ProblemStatus::DUAL_INFEASIBLE) {
// Note(user): In most cases, the matrix will already be refactorized
// and both Refactorize() and PermuteBasis() will do nothing. However,
// if the time limit is reached during the first phase, this might not
// be the case and RecomputeBasicVariableValues() below DCHECKs that the
// matrix is refactorized. This is not required, but we currently only
// want to recompute values from scratch when the matrix was just
// refactorized to maximize precision.
GLOP_RETURN_IF_ERROR(basis_factorization_.Refactorize());
PermuteBasis();
variables_info_.MakeBoxedVariableRelevant(true);
reduced_costs_.MakeReducedCostsPrecise();
// This is needed to display errors properly.
MakeBoxedVariableDualFeasible(
variables_info_.GetNonBasicBoxedVariables(),
/*update_basic_values=*/false);
variable_values_.RecomputeBasicVariableValues();
}
} else {
// Test initial dual infeasibility, ignoring boxed variables. We currently
// refactorize/recompute the reduced costs if not already done.
// TODO(user): Not ideal in an incremental setting.
reduced_costs_.MakeReducedCostsPrecise();
bool refactorize = reduced_costs_.NeedsBasisRefactorization();
GLOP_RETURN_IF_ERROR(RefactorizeBasisIfNeeded(&refactorize));
const Fractional initial_infeasibility =
reduced_costs_.ComputeMaximumDualInfeasibilityOnNonBoxedVariables();
if (initial_infeasibility <
reduced_costs_.GetDualFeasibilityTolerance()) {
SOLVER_LOG(logger_, "Initial basis is dual feasible.");
problem_status_ = ProblemStatus::DUAL_FEASIBLE;
MakeBoxedVariableDualFeasible(
variables_info_.GetNonBasicBoxedVariables(),
/*update_basic_values=*/false);
variable_values_.RecomputeBasicVariableValues();
} else {
// Transform problem and recompute variable values.
variables_info_.TransformToDualPhaseIProblem(
reduced_costs_.GetDualFeasibilityTolerance(),
reduced_costs_.GetReducedCosts());
DenseRow zero; // We want the FREE variable at zero here.
variable_values_.ResetAllNonBasicVariableValues(zero);
variable_values_.RecomputeBasicVariableValues();
// Optimize.
DisplayErrors();
GLOP_RETURN_IF_ERROR(DualMinimize(false, time_limit));
// Restore original problem and recompute variable values. Note that we
// need the reduced cost on the fixed positions here.
variables_info_.EndDualPhaseI(
reduced_costs_.GetDualFeasibilityTolerance(),
reduced_costs_.GetFullReducedCosts());
variable_values_.ResetAllNonBasicVariableValues(
variable_starting_values_);
variable_values_.RecomputeBasicVariableValues();
// TODO(user): Note that if there was cost shifts, we just keep them
// until the end of the optim.
//
// TODO(user): What if slightly infeasible? we shouldn't really stop.
// Call primal ? use higher tolerance ? It seems we can always kind of
// continue and deal with the issue later. Find a way other than this +
// 1e-6 hack.
if (problem_status_ == ProblemStatus::OPTIMAL) {
if (reduced_costs_.ComputeMaximumDualInfeasibility() <
reduced_costs_.GetDualFeasibilityTolerance() + 1e-6) {
problem_status_ = ProblemStatus::DUAL_FEASIBLE;
} else {
SOLVER_LOG(logger_, "Infeasible after first phase.");
problem_status_ = ProblemStatus::DUAL_INFEASIBLE;
}
}
}
}
} else {
GLOP_RETURN_IF_ERROR(PrimalMinimize(time_limit));
// After the primal phase I, we need to restore the objective.
if (problem_status_ != ProblemStatus::PRIMAL_INFEASIBLE) {
InitializeObjectiveAndTestIfUnchanged(lp);
reduced_costs_.ResetForNewObjective();
}
}
DisplayErrors();
phase_ = Phase::OPTIMIZATION;
feasibility_time_ = time_limit->GetElapsedTime() - start_time;
primal_edge_norms_.SetPricingRule(parameters_.optimization_rule());
num_feasibility_iterations_ = num_iterations_;
// Because of shifts or perturbations, we may need to re-run a dual simplex
// after the primal simplex finished, or the opposite.
//
// We alter between solving with primal and dual Phase II algorithm as long as
// time limit permits *and* we did not yet achieve the desired precision.
// I.e., we run iteration i if the solution from iteration i-1 was not precise
// after we removed the bound and cost shifts and perturbations.
//
// NOTE(user): We may still hit the limit of max_number_of_reoptimizations()
// which means the status returned can be PRIMAL_FEASIBLE or DUAL_FEASIBLE
// (i.e., these statuses are not necesserily a consequence of hitting a time
// limit).
SOLVER_LOG(logger_, "");
for (int num_optims = 0;
// We want to enter the loop when both num_optims and num_iterations_ are
// *equal* to the corresponding limits (to return a meaningful status
// when the limits are set to 0).
num_optims <= parameters_.max_number_of_reoptimizations() &&
!objective_limit_reached_ &&
(num_iterations_ == 0 ||
num_iterations_ < parameters_.max_number_of_iterations()) &&
!time_limit->LimitReached() &&
!absl::GetFlag(FLAGS_simplex_stop_after_feasibility) &&
(problem_status_ == ProblemStatus::PRIMAL_FEASIBLE ||
problem_status_ == ProblemStatus::DUAL_FEASIBLE);
++num_optims) {
if (problem_status_ == ProblemStatus::PRIMAL_FEASIBLE) {
// Run the primal simplex.
GLOP_RETURN_IF_ERROR(PrimalMinimize(time_limit));
} else {
// Run the dual simplex.
GLOP_RETURN_IF_ERROR(
DualMinimize(phase_ == Phase::FEASIBILITY, time_limit));
}
// PrimalMinimize() or DualMinimize() always double check the result with
// maximum precision by refactoring the basis before exiting (except if an
// iteration or time limit was reached).
DCHECK(problem_status_ == ProblemStatus::PRIMAL_FEASIBLE ||
problem_status_ == ProblemStatus::DUAL_FEASIBLE ||
basis_factorization_.IsRefactorized());
// If SetIntegralityScale() was called, we preform a polish operation.
if (!integrality_scale_.empty() &&
problem_status_ == ProblemStatus::OPTIMAL) {
GLOP_RETURN_IF_ERROR(Polish(time_limit));
}
// Remove the bound and cost shifts (or perturbations).
//
// Note(user): Currently, we never do both at the same time, so we could
// be a bit faster here, but then this is quick anyway.
variable_values_.ResetAllNonBasicVariableValues(variable_starting_values_);
GLOP_RETURN_IF_ERROR(basis_factorization_.Refactorize());
PermuteBasis();
variable_values_.RecomputeBasicVariableValues();
reduced_costs_.ClearAndRemoveCostShifts();
DisplayErrors();
// TODO(user): We should also confirm the PRIMAL_UNBOUNDED or DUAL_UNBOUNDED
// status by checking with the other phase I that the problem is really
// DUAL_INFEASIBLE or PRIMAL_INFEASIBLE. For instance we currently report
// PRIMAL_UNBOUNDED with the primal on the problem l30.mps instead of
// OPTIMAL and the dual does not have issues on this problem.
//
// TODO(user): There is another issue on infeas/qual.mps. I think we should
// just check the dual ray, not really the current solution dual
// feasibility.
if (problem_status_ == ProblemStatus::PRIMAL_UNBOUNDED) {
const Fractional tolerance = parameters_.solution_feasibility_tolerance();
if (reduced_costs_.ComputeMaximumDualResidual() > tolerance ||
variable_values_.ComputeMaximumPrimalResidual() > tolerance ||
variable_values_.ComputeMaximumPrimalInfeasibility() > tolerance) {
SOLVER_LOG(logger_,
"PRIMAL_UNBOUNDED was reported, but the residual and/or "
"dual infeasibility is above the tolerance");
if (parameters_.change_status_to_imprecise()) {
problem_status_ = ProblemStatus::IMPRECISE;
}
break;
}
// All of our tolerance are okay, but the dual ray might be fishy. This
// happens on l30.mps and on L1_sixm250obs.mps.gz. If the ray do not
// seems good enough, we might actually just be at the optimal and have
// trouble going down to our relatively low default tolerances.
//
// The difference bettween optimal and unbounded can be thin. Say you
// have a free variable with no constraint and a cost of epsilon,
// depending on epsilon and your tolerance, this will either cause the
// problem to be unbounded, or can be ignored.
//
// Here, we compute what is the cost gain if we move from the current
// value with the ray up to the bonds + tolerance. If this gain is < 1,
// it is hard to claim we are really unbounded. This is a quick
// heuristic to error on the side of optimality rather than
// unboundedness.
double max_magnitude = 0.0;
double min_distance = kInfinity;
const DenseRow& lower_bounds = variables_info_.GetVariableLowerBounds();
const DenseRow& upper_bounds = variables_info_.GetVariableUpperBounds();
double cost_delta = 0.0;
for (ColIndex col(0); col < num_cols_; ++col) {
cost_delta += solution_primal_ray_[col] * objective_[col];
if (solution_primal_ray_[col] > 0 && upper_bounds[col] != kInfinity) {
const Fractional value = variable_values_.Get(col);
const Fractional distance = (upper_bounds[col] - value + tolerance) /
solution_primal_ray_[col];
min_distance = std::min(distance, min_distance);
max_magnitude = std::max(solution_primal_ray_[col], max_magnitude);
}
if (solution_primal_ray_[col] < 0 && lower_bounds[col] != -kInfinity) {
const Fractional value = variable_values_.Get(col);
const Fractional distance = (value - lower_bounds[col] + tolerance) /
-solution_primal_ray_[col];
min_distance = std::min(distance, min_distance);
max_magnitude = std::max(-solution_primal_ray_[col], max_magnitude);
}
}
SOLVER_LOG(logger_, "Primal unbounded ray: max blocking magnitude = ",
max_magnitude, ", min distance to bound + ", tolerance, " = ",
min_distance, ", ray cost delta = ", cost_delta);
if (min_distance * std::abs(cost_delta) < 1 &&
reduced_costs_.ComputeMaximumDualInfeasibility() <= tolerance) {
SOLVER_LOG(logger_,
"PRIMAL_UNBOUNDED was reported, but the tolerance are good "
"and the unbounded ray is not great.");
SOLVER_LOG(logger_,
"The difference between unbounded and optimal can depends "
"on a slight change of tolerance, trying to see if we are "
"at OPTIMAL after postsolve.");
problem_status_ = ProblemStatus::OPTIMAL;
}
break;
}
if (problem_status_ == ProblemStatus::DUAL_UNBOUNDED) {
const Fractional tolerance = parameters_.solution_feasibility_tolerance();
if (reduced_costs_.ComputeMaximumDualResidual() > tolerance ||
variable_values_.ComputeMaximumPrimalResidual() > tolerance ||
reduced_costs_.ComputeMaximumDualInfeasibility() > tolerance) {
SOLVER_LOG(logger_,
"DUAL_UNBOUNDED was reported, but the residual and/or "
"dual infeasibility is above the tolerance");
if (parameters_.change_status_to_imprecise()) {
problem_status_ = ProblemStatus::IMPRECISE;
}
}
// Validate the dual ray that prove primal infeasibility.
//
// By taking the linear combination of the constraint, we should arrive
// to an infeasible <= 0 constraint using the variable bounds.
const DenseRow& lower_bounds = variables_info_.GetVariableLowerBounds();
const DenseRow& upper_bounds = variables_info_.GetVariableUpperBounds();
Fractional implied_lb = 0.0;
Fractional error = 0.0;
for (ColIndex col(0); col < num_cols_; ++col) {
const Fractional coeff = solution_dual_ray_row_combination_[col];
if (coeff > 0) {
if (lower_bounds[col] == -kInfinity) {
error = std::max(error, coeff);
} else {
implied_lb += coeff * lower_bounds[col];
}
} else if (coeff < 0) {
if (upper_bounds[col] == kInfinity) {
error = std::max(error, -coeff);
} else {
implied_lb += coeff * upper_bounds[col];
}
}
}
SOLVER_LOG(logger_, "Dual ray error=", error,
" infeasibility=", implied_lb);
if (implied_lb < tolerance || error > tolerance) {
SOLVER_LOG(logger_,
"DUAL_UNBOUNDED was reported, but the dual ray is not "
"proving infeasibility with high enough tolerance");
if (parameters_.change_status_to_imprecise()) {
problem_status_ = ProblemStatus::IMPRECISE;
}
}
break;
}
// Change the status, if after the shift and perturbation removal the
// problem is not OPTIMAL anymore.
if (problem_status_ == ProblemStatus::OPTIMAL) {
const Fractional solution_tolerance =
parameters_.solution_feasibility_tolerance();
const Fractional primal_residual =
variable_values_.ComputeMaximumPrimalResidual();
const Fractional dual_residual =
reduced_costs_.ComputeMaximumDualResidual();
if (primal_residual > solution_tolerance ||
dual_residual > solution_tolerance) {
SOLVER_LOG(logger_,
"OPTIMAL was reported, yet one of the residuals is "
"above the solution feasibility tolerance after the "
"shift/perturbation are removed.");
if (parameters_.change_status_to_imprecise()) {
problem_status_ = ProblemStatus::IMPRECISE;
}
} else {
// We use the "precise" tolerances here to try to report the best
// possible solution. Note however that we cannot really hope for an
// infeasibility lower than its corresponding residual error. Note that
// we already adapt the tolerance like this during the simplex
// execution.
const Fractional primal_tolerance = std::max(
primal_residual, parameters_.primal_feasibility_tolerance());
const Fractional dual_tolerance =
std::max(dual_residual, parameters_.dual_feasibility_tolerance());
const Fractional primal_infeasibility =
variable_values_.ComputeMaximumPrimalInfeasibility();
const Fractional dual_infeasibility =
reduced_costs_.ComputeMaximumDualInfeasibility();
if (primal_infeasibility > primal_tolerance &&
dual_infeasibility > dual_tolerance) {
SOLVER_LOG(logger_,
"OPTIMAL was reported, yet both of the infeasibility "
"are above the tolerance after the "
"shift/perturbation are removed.");
if (parameters_.change_status_to_imprecise()) {
problem_status_ = ProblemStatus::IMPRECISE;
}
} else if (primal_infeasibility > primal_tolerance) {
if (num_optims == parameters_.max_number_of_reoptimizations()) {
SOLVER_LOG(logger_,
"The primal infeasibility is still higher than the "
"requested internal tolerance, but the maximum "
"number of optimization is reached.");
break;
}
SOLVER_LOG(logger_, "");
SOLVER_LOG(logger_, "Re-optimizing with dual simplex ... ");
problem_status_ = ProblemStatus::DUAL_FEASIBLE;
} else if (dual_infeasibility > dual_tolerance) {
if (num_optims == parameters_.max_number_of_reoptimizations()) {
SOLVER_LOG(logger_,
"The dual infeasibility is still higher than the "
"requested internal tolerance, but the maximum "
"number of optimization is reached.");
break;
}
SOLVER_LOG(logger_, "");
SOLVER_LOG(logger_, "Re-optimizing with primal simplex ... ");
problem_status_ = ProblemStatus::PRIMAL_FEASIBLE;
}
}
}
}
// Check that the return status is "precise".
//
// TODO(user): we currently skip the DUAL_INFEASIBLE status because the
// quantities are not up to date in this case.
if (parameters_.change_status_to_imprecise() &&
problem_status_ != ProblemStatus::DUAL_INFEASIBLE) {
const Fractional tolerance = parameters_.solution_feasibility_tolerance();
if (variable_values_.ComputeMaximumPrimalResidual() > tolerance ||
reduced_costs_.ComputeMaximumDualResidual() > tolerance) {
problem_status_ = ProblemStatus::IMPRECISE;
} else if (problem_status_ == ProblemStatus::DUAL_FEASIBLE ||
problem_status_ == ProblemStatus::DUAL_UNBOUNDED ||
problem_status_ == ProblemStatus::PRIMAL_INFEASIBLE) {
if (reduced_costs_.ComputeMaximumDualInfeasibility() > tolerance) {
problem_status_ = ProblemStatus::IMPRECISE;
}
} else if (problem_status_ == ProblemStatus::PRIMAL_FEASIBLE ||
problem_status_ == ProblemStatus::PRIMAL_UNBOUNDED ||
problem_status_ == ProblemStatus::DUAL_INFEASIBLE) {
if (variable_values_.ComputeMaximumPrimalInfeasibility() > tolerance) {
problem_status_ = ProblemStatus::IMPRECISE;
}
}
}
total_time_ = time_limit->GetElapsedTime() - start_time;
optimization_time_ = total_time_ - feasibility_time_;
num_optimization_iterations_ = num_iterations_ - num_feasibility_iterations_;
// If the user didn't provide starting variable values, then there is no need
// to check for super-basic variables.
if (!variable_starting_values_.empty()) {
const int num_super_basic = ComputeNumberOfSuperBasicVariables();
if (num_super_basic > 0) {
SOLVER_LOG(logger_,
"Num super-basic variables left after optimize phase: ",
num_super_basic);
if (parameters_.push_to_vertex()) {
if (problem_status_ == ProblemStatus::OPTIMAL) {
SOLVER_LOG(logger_, "");
phase_ = Phase::PUSH;
GLOP_RETURN_IF_ERROR(PrimalPush(time_limit));
// TODO(user): We should re-check for feasibility at this point and
// apply clean-up as needed.
} else {
SOLVER_LOG(logger_,
"Skipping push phase because optimize didn't succeed.");
}
}
}
}
total_time_ = time_limit->GetElapsedTime() - start_time;
push_time_ = total_time_ - feasibility_time_ - optimization_time_;
num_push_iterations_ = num_iterations_ - num_feasibility_iterations_ -
num_optimization_iterations_;
// Store the result for the solution getters.
solution_objective_value_ = ComputeInitialProblemObjectiveValue();
solution_dual_values_ = reduced_costs_.GetDualValues();
solution_reduced_costs_ = reduced_costs_.GetReducedCosts();
SaveState();
if (lp.IsMaximizationProblem()) {
ChangeSign(&solution_dual_values_);
ChangeSign(&solution_reduced_costs_);
}
// If the problem is unbounded, set the objective value to +/- infinity.
if (problem_status_ == ProblemStatus::DUAL_UNBOUNDED ||
problem_status_ == ProblemStatus::PRIMAL_UNBOUNDED) {
solution_objective_value_ =
(problem_status_ == ProblemStatus::DUAL_UNBOUNDED) ? kInfinity
: -kInfinity;
if (lp.IsMaximizationProblem()) {
solution_objective_value_ = -solution_objective_value_;
}
}
variable_starting_values_.clear();
DisplayAllStats();
return Status::OK();
}
ProblemStatus RevisedSimplex::GetProblemStatus() const {
return problem_status_;
}
Fractional RevisedSimplex::GetObjectiveValue() const {
return solution_objective_value_;
}
int64_t RevisedSimplex::GetNumberOfIterations() const {
return num_iterations_;
}
RowIndex RevisedSimplex::GetProblemNumRows() const { return num_rows_; }
ColIndex RevisedSimplex::GetProblemNumCols() const { return num_cols_; }
Fractional RevisedSimplex::GetVariableValue(ColIndex col) const {
return variable_values_.Get(col);
}
Fractional RevisedSimplex::GetReducedCost(ColIndex col) const {
return solution_reduced_costs_[col];
}
const DenseRow& RevisedSimplex::GetReducedCosts() const {
return solution_reduced_costs_;
}
Fractional RevisedSimplex::GetDualValue(RowIndex row) const {
return solution_dual_values_[row];
}
VariableStatus RevisedSimplex::GetVariableStatus(ColIndex col) const {
return variables_info_.GetStatusRow()[col];
}
const BasisState& RevisedSimplex::GetState() const { return solution_state_; }
Fractional RevisedSimplex::GetConstraintActivity(RowIndex row) const {
// Note the negative sign since the slack variable is such that
// constraint_activity + slack_value = 0.
return -variable_values_.Get(SlackColIndex(row));
}
ConstraintStatus RevisedSimplex::GetConstraintStatus(RowIndex row) const {
// The status of the given constraint is the same as the status of the
// associated slack variable with a change of sign.
const VariableStatus s = variables_info_.GetStatusRow()[SlackColIndex(row)];
if (s == VariableStatus::AT_LOWER_BOUND) {
return ConstraintStatus::AT_UPPER_BOUND;
}
if (s == VariableStatus::AT_UPPER_BOUND) {
return ConstraintStatus::AT_LOWER_BOUND;
}
return VariableToConstraintStatus(s);
}
const DenseRow& RevisedSimplex::GetPrimalRay() const {
DCHECK_EQ(problem_status_, ProblemStatus::PRIMAL_UNBOUNDED);
return solution_primal_ray_;
}
const DenseColumn& RevisedSimplex::GetDualRay() const {
DCHECK_EQ(problem_status_, ProblemStatus::DUAL_UNBOUNDED);
return solution_dual_ray_;
}
const DenseRow& RevisedSimplex::GetDualRayRowCombination() const {
DCHECK_EQ(problem_status_, ProblemStatus::DUAL_UNBOUNDED);
return solution_dual_ray_row_combination_;
}
ColIndex RevisedSimplex::GetBasis(RowIndex row) const { return basis_[row]; }
const BasisFactorization& RevisedSimplex::GetBasisFactorization() const {
DCHECK(basis_factorization_.GetColumnPermutation().empty());
return basis_factorization_;
}
std::string RevisedSimplex::GetPrettySolverStats() const {
return absl::StrFormat(
"Problem status : %s\n"
"Solving time : %-6.4g\n"
"Number of iterations : %u\n"
"Time for solvability (first phase) : %-6.4g\n"
"Number of iterations for solvability : %u\n"
"Time for optimization : %-6.4g\n"
"Number of iterations for optimization : %u\n"
"Stop after first basis : %d\n",
GetProblemStatusString(problem_status_), total_time_, num_iterations_,
feasibility_time_, num_feasibility_iterations_, optimization_time_,
num_optimization_iterations_,
absl::GetFlag(FLAGS_simplex_stop_after_first_basis));
}
double RevisedSimplex::DeterministicTime() const {
// TODO(user): Count what is missing.
return DeterministicTimeForFpOperations(num_update_price_operations_) +
basis_factorization_.DeterministicTime() +
update_row_.DeterministicTime() +
entering_variable_.DeterministicTime() +
reduced_costs_.DeterministicTime() +
primal_edge_norms_.DeterministicTime();
}
void RevisedSimplex::SetVariableNames() {
variable_name_.resize(num_cols_, "");
for (ColIndex col(0); col < first_slack_col_; ++col) {
const ColIndex var_index = col + 1;
variable_name_[col] = absl::StrFormat("x%d", ColToIntIndex(var_index));
}
for (ColIndex col(first_slack_col_); col < num_cols_; ++col) {
const ColIndex var_index = col - first_slack_col_ + 1;
variable_name_[col] = absl::StrFormat("s%d", ColToIntIndex(var_index));
}
}
void RevisedSimplex::SetNonBasicVariableStatusAndDeriveValue(
ColIndex col, VariableStatus status) {
variables_info_.UpdateToNonBasicStatus(col, status);
variable_values_.SetNonBasicVariableValueFromStatus(col);
}
bool RevisedSimplex::BasisIsConsistent() const {
const DenseBitRow& is_basic = variables_info_.GetIsBasicBitRow();
const VariableStatusRow& variable_statuses = variables_info_.GetStatusRow();
for (RowIndex row(0); row < num_rows_; ++row) {
const ColIndex col = basis_[row];
if (!is_basic.IsSet(col)) return false;
if (variable_statuses[col] != VariableStatus::BASIC) return false;
}
ColIndex cols_in_basis(0);
ColIndex cols_not_in_basis(0);
for (ColIndex col(0); col < num_cols_; ++col) {
cols_in_basis += is_basic.IsSet(col);
cols_not_in_basis += !is_basic.IsSet(col);
if (is_basic.IsSet(col) !=
(variable_statuses[col] == VariableStatus::BASIC)) {
return false;
}
}
if (cols_in_basis != RowToColIndex(num_rows_)) return false;
if (cols_not_in_basis != num_cols_ - RowToColIndex(num_rows_)) return false;
return true;
}
// Note(user): The basis factorization is not updated by this function but by
// UpdateAndPivot().
void RevisedSimplex::UpdateBasis(ColIndex entering_col, RowIndex basis_row,
VariableStatus leaving_variable_status) {
SCOPED_TIME_STAT(&function_stats_);
DCHECK_COL_BOUNDS(entering_col);
DCHECK_ROW_BOUNDS(basis_row);
// Check that this is not called with an entering_col already in the basis
// and that the leaving col is indeed in the basis.
DCHECK(!variables_info_.GetIsBasicBitRow().IsSet(entering_col));
DCHECK_NE(basis_[basis_row], entering_col);
DCHECK_NE(basis_[basis_row], kInvalidCol);
const ColIndex leaving_col = basis_[basis_row];
DCHECK(variables_info_.GetIsBasicBitRow().IsSet(leaving_col));
// Make leaving_col leave the basis and update relevant data.
// Note thate the leaving variable value is not necessarily at its exact
// bound, which is like a bound shift.
variables_info_.UpdateToNonBasicStatus(leaving_col, leaving_variable_status);
DCHECK(leaving_variable_status == VariableStatus::AT_UPPER_BOUND ||
leaving_variable_status == VariableStatus::AT_LOWER_BOUND ||
leaving_variable_status == VariableStatus::FIXED_VALUE);
basis_[basis_row] = entering_col;
variables_info_.UpdateToBasicStatus(entering_col);
update_row_.Invalidate();
}
namespace {
// Comparator used to sort column indices according to a given value vector.
class ColumnComparator {
public:
explicit ColumnComparator(const DenseRow& value) : value_(value) {}
bool operator()(ColIndex col_a, ColIndex col_b) const {
return value_[col_a] < value_[col_b];
}
private:
const DenseRow& value_;
};
} // namespace
// To understand better what is going on in this function, let us say that this
// algorithm will produce the optimal solution to a problem containing only
// singleton columns (provided that the variables start at the minimum possible
// cost, see DefaultVariableStatus()). This is unit tested.
//
// The error_ must be equal to the constraint activity for the current variable
// values before this function is called. If error_[row] is 0.0, that mean this
// constraint is currently feasible.
void RevisedSimplex::UseSingletonColumnInInitialBasis(RowToColMapping* basis) {
SCOPED_TIME_STAT(&function_stats_);
// Computes the singleton columns and the cost variation of the corresponding
// variables (in the only possible direction, i.e away from its current bound)
// for a unit change in the infeasibility of the corresponding row.
//
// Note that the slack columns will be treated as normal singleton columns.
std::vector<ColIndex> singleton_column;
DenseRow cost_variation(num_cols_, 0.0);
const DenseRow& lower_bounds = variables_info_.GetVariableLowerBounds();
const DenseRow& upper_bounds = variables_info_.GetVariableUpperBounds();
for (ColIndex col(0); col < num_cols_; ++col) {
if (compact_matrix_.column(col).num_entries() != 1) continue;
if (lower_bounds[col] == upper_bounds[col]) continue;
const Fractional slope = compact_matrix_.column(col).GetFirstCoefficient();
if (variable_values_.Get(col) == lower_bounds[col]) {
cost_variation[col] = objective_[col] / std::abs(slope);
} else {
cost_variation[col] = -objective_[col] / std::abs(slope);
}
singleton_column.push_back(col);
}
if (singleton_column.empty()) return;
// Sort the singleton columns for the case where many of them correspond to
// the same row (equivalent to a piecewise-linear objective on this variable).
// Negative cost_variation first since moving the singleton variable away from
// its current bound means the least decrease in the objective function for
// the same "error" variation.
ColumnComparator comparator(cost_variation);
std::sort(singleton_column.begin(), singleton_column.end(), comparator);
DCHECK_LE(cost_variation[singleton_column.front()],
cost_variation[singleton_column.back()]);
// Use a singleton column to "absorb" the error when possible to avoid
// introducing unneeded artificial variables. Note that with scaling on, the
// only possible coefficient values are 1.0 or -1.0 (or maybe epsilon close to
// them) and that the SingletonColumnSignPreprocessor makes them all positive.
// However, this code works for any coefficient value.
const DenseRow& variable_values = variable_values_.GetDenseRow();
for (const ColIndex col : singleton_column) {
const RowIndex row = compact_matrix_.column(col).EntryRow(EntryIndex(0));
// If no singleton columns have entered the basis for this row, choose the
// first one. It will be the one with the least decrease in the objective
// function when it leaves the basis.
if ((*basis)[row] == kInvalidCol) {
(*basis)[row] = col;
}
// If there is already no error in this row (i.e. it is primal-feasible),
// there is nothing to do.
if (error_[row] == 0.0) continue;
// In this case, all the infeasibility can be "absorbed" and this variable
// may not be at one of its bound anymore, so we have to use it in the
// basis.
const Fractional coeff =
compact_matrix_.column(col).EntryCoefficient(EntryIndex(0));
const Fractional new_value = variable_values[col] + error_[row] / coeff;
if (new_value >= lower_bounds[col] && new_value <= upper_bounds[col]) {
error_[row] = 0.0;
// Use this variable in the initial basis.
(*basis)[row] = col;
continue;
}
// The idea here is that if the singleton column cannot be used to "absorb"
// all error_[row], if it is boxed, it can still be used to make the
// infeasibility smaller (with a bound flip).
const Fractional box_width = variables_info_.GetBoundDifference(col);
DCHECK_NE(box_width, 0.0);
DCHECK_NE(error_[row], 0.0);
const Fractional error_sign = error_[row] / coeff;
if (variable_values[col] == lower_bounds[col] && error_sign > 0.0) {
DCHECK(IsFinite(box_width));
error_[row] -= coeff * box_width;
SetNonBasicVariableStatusAndDeriveValue(col,
VariableStatus::AT_UPPER_BOUND);
continue;
}
if (variable_values[col] == upper_bounds[col] && error_sign < 0.0) {
DCHECK(IsFinite(box_width));
error_[row] += coeff * box_width;
SetNonBasicVariableStatusAndDeriveValue(col,
VariableStatus::AT_LOWER_BOUND);
continue;
}
}
}
bool RevisedSimplex::InitializeMatrixAndTestIfUnchanged(
const LinearProgram& lp, bool lp_is_in_equation_form,
bool* only_change_is_new_rows, bool* only_change_is_new_cols,
ColIndex* num_new_cols) {
SCOPED_TIME_STAT(&function_stats_);
DCHECK(only_change_is_new_rows != nullptr);
DCHECK(only_change_is_new_cols != nullptr);
DCHECK(num_new_cols != nullptr);
DCHECK_EQ(num_cols_, compact_matrix_.num_cols());
DCHECK_EQ(num_rows_, compact_matrix_.num_rows());
// This works whether the lp is in equation form (with slack) or not.
const bool old_part_of_matrix_is_unchanged =
AreFirstColumnsAndRowsExactlyEquals(
num_rows_, first_slack_col_, lp.GetSparseMatrix(), compact_matrix_);
// This is the only adaptation we need for the test below.
const ColIndex lp_first_slack =
lp_is_in_equation_form ? lp.GetFirstSlackVariable() : lp.num_variables();
// Test if the matrix is unchanged, and if yes, just returns true. Note that
// this doesn't check the columns corresponding to the slack variables,
// because they were checked by lp.IsInEquationForm() when Solve() was called.
if (old_part_of_matrix_is_unchanged && lp.num_constraints() == num_rows_ &&
lp_first_slack == first_slack_col_) {
// Tricky: if the parameters "use_transposed_matrix" changed since last call
// we want to reflect the current state. We use the empty transposed matrix
// to detect that. Recomputing the transpose when the matrix is empty is not
// really a big overhead.
if (parameters_.use_transposed_matrix()) {
if (transposed_matrix_.IsEmpty()) {
transposed_matrix_.PopulateFromTranspose(compact_matrix_);
}
} else {
transposed_matrix_.Reset(RowIndex(0));
}
return true;
}
// Check if the new matrix can be derived from the old one just by adding
// new rows (i.e new constraints).
*only_change_is_new_rows = old_part_of_matrix_is_unchanged &&
lp.num_constraints() > num_rows_ &&
lp_first_slack == first_slack_col_;
// Check if the new matrix can be derived from the old one just by adding
// new columns (i.e new variables).
*only_change_is_new_cols = old_part_of_matrix_is_unchanged &&
lp.num_constraints() == num_rows_ &&
lp_first_slack > first_slack_col_;
*num_new_cols = *only_change_is_new_cols ? lp_first_slack - first_slack_col_
: ColIndex(0);
// Initialize first_slack_.
first_slack_col_ = lp_first_slack;
// Initialize the new dimensions.
num_rows_ = lp.num_constraints();
num_cols_ = lp_first_slack + RowToColIndex(lp.num_constraints());
// Populate compact_matrix_ and transposed_matrix_ if needed.
if (lp_is_in_equation_form) {
// TODO(user): This can be sped up by removing the MatrixView, but then
// this path will likely go away.
compact_matrix_.PopulateFromMatrixView(MatrixView(lp.GetSparseMatrix()));
} else {
compact_matrix_.PopulateFromSparseMatrixAndAddSlacks(lp.GetSparseMatrix());
}
if (parameters_.use_transposed_matrix()) {
transposed_matrix_.PopulateFromTranspose(compact_matrix_);
} else {
transposed_matrix_.Reset(RowIndex(0));
}
return false;
}
// Preconditions: This should only be called if there are only new variable
// in the lp.