forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathprimal_dual_hybrid_gradient.cc
3023 lines (2834 loc) · 137 KB
/
primal_dual_hybrid_gradient.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-2024 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/pdlp/primal_dual_hybrid_gradient.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <functional>
#include <limits>
#include <optional>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "Eigen/Core"
#include "Eigen/SparseCore"
#include "absl/algorithm/container.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "google/protobuf/repeated_ptr_field.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/timer.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/glop/preprocessor.h"
#include "ortools/linear_solver/linear_solver.pb.h"
#include "ortools/lp_data/lp_data.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/lp_data/proto_utils.h"
#include "ortools/pdlp/iteration_stats.h"
#include "ortools/pdlp/quadratic_program.h"
#include "ortools/pdlp/sharded_optimization_utils.h"
#include "ortools/pdlp/sharded_quadratic_program.h"
#include "ortools/pdlp/sharder.h"
#include "ortools/pdlp/solve_log.pb.h"
#include "ortools/pdlp/solvers.pb.h"
#include "ortools/pdlp/solvers_proto_validation.h"
#include "ortools/pdlp/termination.h"
#include "ortools/pdlp/trust_region.h"
#include "ortools/util/logging.h"
namespace operations_research::pdlp {
namespace {
using ::Eigen::VectorXd;
using ::operations_research::SolverLogger;
using IterationStatsCallback =
std::function<void(const IterationCallbackInfo&)>;
// Computes a `num_threads` that is capped by the problem size and `num_shards`,
// if specified, to avoid creating unusable threads.
int NumThreads(const int num_threads, const int num_shards,
const QuadraticProgram& qp, SolverLogger& logger) {
int capped_num_threads = num_threads;
if (num_shards > 0) {
capped_num_threads = std::min(capped_num_threads, num_shards);
}
const int64_t problem_limit = std::max(qp.variable_lower_bounds.size(),
qp.constraint_lower_bounds.size());
capped_num_threads =
static_cast<int>(std::min(int64_t{capped_num_threads}, problem_limit));
capped_num_threads = std::max(capped_num_threads, 1);
if (capped_num_threads != num_threads) {
SOLVER_LOG(&logger, "WARNING: Reducing num_threads from ", num_threads,
" to ", capped_num_threads,
" because additional threads would be useless.");
}
return capped_num_threads;
}
// If `num_shards` is positive, returns it. Otherwise returns a reasonable
// number of shards to use with `ShardedQuadraticProgram` for the given
// `num_threads`.
int NumShards(const int num_threads, const int num_shards) {
if (num_shards > 0) return num_shards;
return num_threads == 1 ? 1 : 4 * num_threads;
}
std::string ConvergenceInformationString(
const ConvergenceInformation& convergence_information,
const RelativeConvergenceInformation& relative_information,
const OptimalityNorm residual_norm) {
constexpr absl::string_view kFormatStr =
"%#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g | "
"%#12.6g %#12.6g";
switch (residual_norm) {
case OPTIMALITY_NORM_L_INF:
return absl::StrFormat(
kFormatStr, relative_information.relative_l_inf_primal_residual,
relative_information.relative_l_inf_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.l_inf_primal_residual(),
convergence_information.l_inf_dual_residual(),
convergence_information.primal_objective() -
convergence_information.dual_objective(),
convergence_information.primal_objective(),
convergence_information.dual_objective(),
convergence_information.l2_primal_variable(),
convergence_information.l2_dual_variable());
case OPTIMALITY_NORM_L2:
return absl::StrFormat(kFormatStr,
relative_information.relative_l2_primal_residual,
relative_information.relative_l2_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.l2_primal_residual(),
convergence_information.l2_dual_residual(),
convergence_information.primal_objective() -
convergence_information.dual_objective(),
convergence_information.primal_objective(),
convergence_information.dual_objective(),
convergence_information.l2_primal_variable(),
convergence_information.l2_dual_variable());
case OPTIMALITY_NORM_L_INF_COMPONENTWISE:
return absl::StrFormat(
kFormatStr,
convergence_information.l_inf_componentwise_primal_residual(),
convergence_information.l_inf_componentwise_dual_residual(),
relative_information.relative_optimality_gap,
convergence_information.l_inf_primal_residual(),
convergence_information.l_inf_dual_residual(),
convergence_information.primal_objective() -
convergence_information.dual_objective(),
convergence_information.primal_objective(),
convergence_information.dual_objective(),
convergence_information.l2_primal_variable(),
convergence_information.l2_dual_variable());
case OPTIMALITY_NORM_UNSPECIFIED:
LOG(FATAL) << "Residual norm not specified.";
}
LOG(FATAL) << "Invalid residual norm " << residual_norm << ".";
}
std::string ConvergenceInformationShortString(
const ConvergenceInformation& convergence_information,
const RelativeConvergenceInformation& relative_information,
const OptimalityNorm residual_norm) {
constexpr absl::string_view kFormatStr =
"%#10.4g %#10.4g %#10.4g | %#10.4g %#10.4g";
switch (residual_norm) {
case OPTIMALITY_NORM_L_INF:
return absl::StrFormat(
kFormatStr, relative_information.relative_l_inf_primal_residual,
relative_information.relative_l_inf_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.primal_objective(),
convergence_information.dual_objective());
case OPTIMALITY_NORM_L2:
return absl::StrFormat(kFormatStr,
relative_information.relative_l2_primal_residual,
relative_information.relative_l2_dual_residual,
relative_information.relative_optimality_gap,
convergence_information.primal_objective(),
convergence_information.dual_objective());
case OPTIMALITY_NORM_L_INF_COMPONENTWISE:
return absl::StrFormat(
kFormatStr,
convergence_information.l_inf_componentwise_primal_residual(),
convergence_information.l_inf_componentwise_dual_residual(),
relative_information.relative_optimality_gap,
convergence_information.primal_objective(),
convergence_information.dual_objective());
case OPTIMALITY_NORM_UNSPECIFIED:
LOG(FATAL) << "Residual norm not specified.";
}
LOG(FATAL) << "Invalid residual norm " << residual_norm << ".";
}
// Logs a description of `iter_stats`, based on the
// `iter_stats.convergence_information` entry with
// `.candidate_type()==preferred_candidate` if one exists, otherwise based on
// the first value, if any. `termination_criteria.optimality_norm` determines
// which residual norms from `iter_stats.convergence_information` are used.
void LogIterationStats(int verbosity_level, bool use_feasibility_polishing,
IterationType iteration_type,
const IterationStats& iter_stats,
const TerminationCriteria& termination_criteria,
const QuadraticProgramBoundNorms& bound_norms,
PointType preferred_candidate, SolverLogger& logger) {
std::string iteration_string =
verbosity_level >= 3
? absl::StrFormat("%6d %8.1f %6.1f", iter_stats.iteration_number(),
iter_stats.cumulative_kkt_matrix_passes(),
iter_stats.cumulative_time_sec())
: absl::StrFormat("%6d %6.1f", iter_stats.iteration_number(),
iter_stats.cumulative_time_sec());
auto convergence_information =
GetConvergenceInformation(iter_stats, preferred_candidate);
if (!convergence_information.has_value() &&
iter_stats.convergence_information_size() > 0) {
convergence_information = iter_stats.convergence_information(0);
}
const char* phase_string = [&]() {
if (use_feasibility_polishing) {
switch (iteration_type) {
case IterationType::kNormal:
return "n ";
case IterationType::kPrimalFeasibility:
return "p ";
case IterationType::kDualFeasibility:
return "d ";
case IterationType::kNormalTermination:
case IterationType::kFeasibilityPolishingTermination:
case IterationType::kPresolveTermination:
return "t ";
}
} else {
return "";
}
}();
if (convergence_information.has_value()) {
const char* iterate_string = [&]() {
if (verbosity_level >= 4) {
switch (convergence_information->candidate_type()) {
case POINT_TYPE_CURRENT_ITERATE:
return "C ";
case POINT_TYPE_AVERAGE_ITERATE:
return "A ";
case POINT_TYPE_ITERATE_DIFFERENCE:
return "D ";
case POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION:
return "F ";
default:
return "? ";
}
} else {
return "";
}
}();
const RelativeConvergenceInformation relative_information =
ComputeRelativeResiduals(
EffectiveOptimalityCriteria(termination_criteria),
*convergence_information, bound_norms);
std::string convergence_string =
verbosity_level >= 3
? ConvergenceInformationString(
*convergence_information, relative_information,
termination_criteria.optimality_norm())
: ConvergenceInformationShortString(
*convergence_information, relative_information,
termination_criteria.optimality_norm());
SOLVER_LOG(&logger, phase_string, iterate_string, iteration_string, " | ",
convergence_string);
} else {
// No convergence information, just log the basic work stats.
SOLVER_LOG(&logger, phase_string, verbosity_level >= 4 ? "? " : "",
iteration_string);
}
}
void LogIterationStatsHeader(int verbosity_level,
bool use_feasibility_polishing,
SolverLogger& logger) {
std::string work_labels =
verbosity_level >= 3
? absl::StrFormat("%6s %8s %6s", "iter#", "kkt_pass", "time")
: absl::StrFormat("%6s %6s", "iter#", "time");
std::string convergence_labels =
verbosity_level >= 3
? absl::StrFormat(
"%12s %12s %12s | %12s %12s %12s | %12s %12s | %12s %12s",
"rel_prim_res", "rel_dual_res", "rel_gap", "prim_resid",
"dual_resid", "obj_gap", "prim_obj", "dual_obj", "prim_var_l2",
"dual_var_l2")
: absl::StrFormat("%10s %10s %10s | %10s %10s", "rel_p_res",
"rel_d_res", "rel_gap", "prim_obj", "dual_obj");
SOLVER_LOG(&logger, use_feasibility_polishing ? "f " : "",
verbosity_level >= 4 ? "I " : "", work_labels, " | ",
convergence_labels);
}
enum class InnerStepOutcome {
kSuccessful,
kForceNumericalTermination,
};
// Makes the closing changes to `solve_log` and builds a `SolverResult`.
// NOTE: `primal_solution`, `dual_solution`, and `solve_log` are passed by
// value. To avoid unnecessary copying, move these objects (i.e. use
// `std::move()`).
SolverResult ConstructSolverResult(VectorXd primal_solution,
VectorXd dual_solution,
const IterationStats& stats,
TerminationReason termination_reason,
PointType output_type, SolveLog solve_log) {
solve_log.set_iteration_count(stats.iteration_number());
solve_log.set_termination_reason(termination_reason);
solve_log.set_solution_type(output_type);
solve_log.set_solve_time_sec(stats.cumulative_time_sec());
*solve_log.mutable_solution_stats() = stats;
return SolverResult{.primal_solution = std::move(primal_solution),
.dual_solution = std::move(dual_solution),
.solve_log = std::move(solve_log)};
}
class PreprocessSolver {
public:
// Assumes that `qp` and `params` are valid.
// Note that the `qp` is intentionally passed by value.
// `logger` is captured, and must outlive the class.
// NOTE: Many `PreprocessSolver` methods accept a `params` argument. This is
// passed as an argument instead of stored as a member variable to support
// using different `params` in different contexts with the same
// `PreprocessSolver` object.
explicit PreprocessSolver(QuadraticProgram qp,
const PrimalDualHybridGradientParams& params,
SolverLogger* logger);
// Not copyable or movable (because `glop::MainLpPreprocessor` isn't).
PreprocessSolver(const PreprocessSolver&) = delete;
PreprocessSolver& operator=(const PreprocessSolver&) = delete;
PreprocessSolver(PreprocessSolver&&) = delete;
PreprocessSolver& operator=(PreprocessSolver&&) = delete;
// Zero is used if `initial_solution` is nullopt. If `interrupt_solve` is not
// nullptr, then the solver will periodically check if
// `interrupt_solve->load()` is true, in which case the solve will terminate
// with `TERMINATION_REASON_INTERRUPTED_BY_USER`. Ownership is not
// transferred. If `iteration_stats_callback` is not nullptr, then at each
// termination step (when iteration stats are logged),
// `iteration_stats_callback` will also be called with those iteration stats.
SolverResult PreprocessAndSolve(
const PrimalDualHybridGradientParams& params,
std::optional<PrimalAndDualSolution> initial_solution,
const std::atomic<bool>* interrupt_solve,
IterationStatsCallback iteration_stats_callback);
// Returns a `TerminationReasonAndPointType` when the termination criteria are
// satisfied, otherwise returns nothing. The pointers to working_* can be
// nullptr if an iterate of that type is not available. For the iterate types
// that are available, uses the primal and dual vectors to compute solution
// statistics and adds them to the stats proto.
// `full_stats` is used for checking work-based termination criteria,
// but `stats` is updated with convergence information.
// NOTE: The primal and dual input pairs should be scaled solutions.
// TODO(user): Move this long argument list into a struct.
std::optional<TerminationReasonAndPointType>
UpdateIterationStatsAndCheckTermination(
const PrimalDualHybridGradientParams& params,
bool force_numerical_termination, const VectorXd& working_primal_current,
const VectorXd& working_dual_current,
const VectorXd* working_primal_average,
const VectorXd* working_dual_average,
const VectorXd* working_primal_delta, const VectorXd* working_dual_delta,
const VectorXd& last_primal_start_point,
const VectorXd& last_dual_start_point,
const std::atomic<bool>* interrupt_solve, IterationType iteration_type,
const IterationStats& full_stats, IterationStats& stats);
// Computes solution statistics for the primal and dual input pair, which
// should be a scaled solution. If `convergence_information != nullptr`,
// populates it with convergence information, and similarly if
// `infeasibility_information != nullptr`, populates it with infeasibility
// information.
void ComputeConvergenceAndInfeasibilityFromWorkingSolution(
const PrimalDualHybridGradientParams& params,
const VectorXd& working_primal, const VectorXd& working_dual,
PointType candidate_type, ConvergenceInformation* convergence_information,
InfeasibilityInformation* infeasibility_information) const;
// Returns a `SolverResult` for the original problem, given a `SolverResult`
// from the scaled or preprocessed problem. Also computes the reduced costs.
// NOTE: `result` is passed by value. To avoid unnecessary copying, move this
// object (i.e. use `std::move()`).
SolverResult ConstructOriginalSolverResult(
const PrimalDualHybridGradientParams& params, SolverResult result,
SolverLogger& logger) const;
const ShardedQuadraticProgram& ShardedWorkingQp() const {
return sharded_qp_;
}
// Swaps `variable_lower_bounds` and `variable_upper_bounds` with the ones on
// the sharded quadratic program.
void SwapVariableBounds(VectorXd& variable_lower_bounds,
VectorXd& variable_upper_bounds) {
sharded_qp_.SwapVariableBounds(variable_lower_bounds,
variable_upper_bounds);
}
// Swaps `constraint_lower_bounds` and `constraint_upper_bounds` with the ones
// on the sharded quadratic program.
void SwapConstraintBounds(VectorXd& constraint_lower_bounds,
VectorXd& constraint_upper_bounds) {
sharded_qp_.SwapConstraintBounds(constraint_lower_bounds,
constraint_upper_bounds);
}
// Swaps `objective` with the objective vector on the quadratic program.
// Swapping `objective_matrix` is not yet supported because it hasn't been
// needed.
void SwapObjectiveVector(VectorXd& objective) {
sharded_qp_.SwapObjectiveVector(objective);
}
const QuadraticProgramBoundNorms& OriginalBoundNorms() const {
return original_bound_norms_;
}
SolverLogger& Logger() { return logger_; }
private:
struct PresolveInfo {
explicit PresolveInfo(ShardedQuadraticProgram original_qp,
const PrimalDualHybridGradientParams& params)
: preprocessor_parameters(PreprocessorParameters(params)),
preprocessor(&preprocessor_parameters),
sharded_original_qp(std::move(original_qp)),
trivial_col_scaling_vec(
OnesVector(sharded_original_qp.PrimalSharder())),
trivial_row_scaling_vec(
OnesVector(sharded_original_qp.DualSharder())) {}
glop::GlopParameters preprocessor_parameters;
glop::MainLpPreprocessor preprocessor;
ShardedQuadraticProgram sharded_original_qp;
bool presolved_problem_was_maximization = false;
const VectorXd trivial_col_scaling_vec, trivial_row_scaling_vec;
};
// TODO(user): experiment with different preprocessor types.
static glop::GlopParameters PreprocessorParameters(
const PrimalDualHybridGradientParams& params);
// If presolve is enabled, moves `sharded_qp_` to
// `presolve_info_.sharded_original_qp` and computes the presolved linear
// program and installs it in `sharded_qp_`. Clears `initial_solution` if
// presolve is enabled. If presolve solves the problem completely returns the
// appropriate `TerminationReason`. Otherwise returns nullopt. If presolve
// is disabled or an error occurs modifies nothing and returns nullopt.
std::optional<TerminationReason> ApplyPresolveIfEnabled(
const PrimalDualHybridGradientParams& params,
std::optional<PrimalAndDualSolution>* initial_solution);
void ComputeAndApplyRescaling(const PrimalDualHybridGradientParams& params,
VectorXd& starting_primal_solution,
VectorXd& starting_dual_solution);
void LogQuadraticProgramStats(const QuadraticProgramStats& stats) const;
double InitialPrimalWeight(const PrimalDualHybridGradientParams& params,
double l2_norm_primal_linear_objective,
double l2_norm_constraint_bounds) const;
PrimalAndDualSolution RecoverOriginalSolution(
PrimalAndDualSolution working_solution) const;
// Adds one entry of `PointMetadata` to `stats` using the input solutions.
void AddPointMetadata(const PrimalDualHybridGradientParams& params,
const VectorXd& primal_solution,
const VectorXd& dual_solution, PointType point_type,
const VectorXd& last_primal_start_point,
const VectorXd& last_dual_start_point,
IterationStats& stats) const;
const QuadraticProgram& Qp() const { return sharded_qp_.Qp(); }
const int num_threads_;
const int num_shards_;
// The bound norms of the original problem.
QuadraticProgramBoundNorms original_bound_norms_;
// This is the QP that PDHG is run on. It is modified by presolve and
// rescaling, if those are enabled, and then serves as the
// `ShardedWorkingQp()` when calling `Solver::Solve()`. The original problem
// is available in `presolve_info_->sharded_original_qp` if
// `presolve_info_.has_value()`, and otherwise can be obtained by undoing the
// scaling of `sharded_qp_` by `col_scaling_vec_` and `row_scaling_vec_`.
ShardedQuadraticProgram sharded_qp_;
// Set iff presolve is enabled.
std::optional<PresolveInfo> presolve_info_;
// The scaling vectors that map the original (or presolved) quadratic program
// to the working version. See
// `ShardedQuadraticProgram::RescaleQuadraticProgram()` for details.
VectorXd col_scaling_vec_;
VectorXd row_scaling_vec_;
// A counter used to trigger writing iteration headers.
int log_counter_ = 0;
absl::Time time_of_last_log_ = absl::InfinitePast();
SolverLogger& logger_;
IterationStatsCallback iteration_stats_callback_;
};
class Solver {
public:
// `preprocess_solver` should not be nullptr, and the `PreprocessSolver`
// object must outlive this `Solver` object. Ownership is not transferred.
explicit Solver(const PrimalDualHybridGradientParams& params,
VectorXd starting_primal_solution,
VectorXd starting_dual_solution, double initial_step_size,
double initial_primal_weight,
PreprocessSolver* preprocess_solver);
// Not copyable or movable (because there are const members).
Solver(const Solver&) = delete;
Solver& operator=(const Solver&) = delete;
Solver(Solver&&) = delete;
Solver& operator=(Solver&&) = delete;
const QuadraticProgram& WorkingQp() const { return ShardedWorkingQp().Qp(); }
const ShardedQuadraticProgram& ShardedWorkingQp() const {
return preprocess_solver_->ShardedWorkingQp();
}
// Runs PDHG iterations on the instance that has been initialized in `Solver`.
// If `interrupt_solve` is not nullptr, then the solver will periodically
// check if `interrupt_solve->load()` is true, in which case the solve will
// terminate with `TERMINATION_REASON_INTERRUPTED_BY_USER`. Ownership is not
// transferred.
// `solve_log` should contain initial problem statistics.
// On return, `SolveResult.reduced_costs` will be empty, and the solution will
// be to the preprocessed/scaled problem.
SolverResult Solve(IterationType iteration_type,
const std::atomic<bool>* interrupt_solve,
SolveLog solve_log);
private:
struct NextSolutionAndDelta {
VectorXd value;
// `delta` is `value` - current_solution.
VectorXd delta;
};
struct DistanceBasedRestartInfo {
double distance_moved_last_restart_period;
int length_of_last_restart_period;
};
// Movement terms (weighted squared norms of primal and dual deltas) larger
// than this cause termination because iterates are diverging, and likely to
// cause infinite and NaN values.
constexpr static double kDivergentMovement = 1.0e100;
// Attempts to solve primal and dual feasibility subproblems starting at the
// average iterate, for at most `iteration_limit` iterations each. If
// successful, returns a `SolverResult`, otherwise nullopt. Appends
// information about the polishing phases to
// `solve_log.feasibility_polishing_details`.
std::optional<SolverResult> TryFeasibilityPolishing(
int iteration_limit, const std::atomic<bool>* interrupt_solve,
SolveLog& solve_log);
// Tries to find primal feasibility, adds the solve log details to
// `solve_log.feasibility_polishing_details`, and returns the result.
SolverResult TryPrimalPolishing(VectorXd starting_primal_solution,
int iteration_limit,
const std::atomic<bool>* interrupt_solve,
SolveLog& solve_log);
// Tries to find dual feasibility, adds the solve log details to
// `solve_log.feasibility_polishing_details`, and returns the result.
SolverResult TryDualPolishing(VectorXd starting_dual_solution,
int iteration_limit,
const std::atomic<bool>* interrupt_solve,
SolveLog& solve_log);
NextSolutionAndDelta ComputeNextPrimalSolution(double primal_step_size) const;
NextSolutionAndDelta ComputeNextDualSolution(
double dual_step_size, double extrapolation_factor,
const NextSolutionAndDelta& next_primal) const;
double ComputeMovement(const VectorXd& delta_primal,
const VectorXd& delta_dual) const;
double ComputeNonlinearity(const VectorXd& delta_primal,
const VectorXd& next_dual_product) const;
// Creates all the simple-to-compute statistics in stats.
IterationStats CreateSimpleIterationStats(RestartChoice restart_used) const;
// Returns the total work so far from the main iterations and feasibility
// polishing phases.
IterationStats TotalWorkSoFar(const SolveLog& solve_log) const;
RestartChoice ChooseRestartToApply(bool is_major_iteration);
VectorXd PrimalAverage() const;
VectorXd DualAverage() const;
double ComputeNewPrimalWeight() const;
// Picks the primal and dual solutions according to `output_type`, and makes
// the closing changes to `solve_log`. This function should only be called
// once when the solver is finishing its execution.
// NOTE: `primal_solution` and `dual_solution` are used as the output except
// when `output_type` is `POINT_TYPE_CURRENT_ITERATE` or
// `POINT_TYPE_ITERATE_DIFFERENCE`, in which case the values are computed from
// `Solver` data.
// NOTE: `primal_solution`, `dual_solution`, and `solve_log` are passed by
// value. To avoid unnecessary copying, move these objects (i.e. use
// `std::move()`).
SolverResult PickSolutionAndConstructSolverResult(
VectorXd primal_solution, VectorXd dual_solution,
const IterationStats& stats, TerminationReason termination_reason,
PointType output_type, SolveLog solve_log) const;
double DistanceTraveledFromLastStart(const VectorXd& primal_solution,
const VectorXd& dual_solution) const;
LocalizedLagrangianBounds ComputeLocalizedBoundsAtCurrent() const;
LocalizedLagrangianBounds ComputeLocalizedBoundsAtAverage() const;
// Applies the given `RestartChoice`. If a restart is chosen, updates the
// state of the algorithm accordingly and computes a new primal weight.
void ApplyRestartChoice(RestartChoice restart_to_apply);
std::optional<SolverResult> MajorIterationAndTerminationCheck(
IterationType iteration_type, bool force_numerical_termination,
const std::atomic<bool>* interrupt_solve,
const IterationStats& work_from_feasibility_polishing,
SolveLog& solve_log);
bool ShouldDoAdaptiveRestartHeuristic(double candidate_normalized_gap) const;
RestartChoice DetermineDistanceBasedRestartChoice() const;
void ResetAverageToCurrent();
void LogNumericalTermination() const;
void LogInnerIterationLimitHit() const;
// Takes a step based on the Malitsky and Pock linesearch algorithm.
// (https://arxiv.org/pdf/1608.08883.pdf)
// The current implementation is provably convergent (at an optimal rate)
// for LP programs (provided we do not change the primal weight at every major
// iteration). Further, we have observed that this rule is very sensitive to
// the parameter choice whenever we apply the primal weight recomputation
// heuristic.
InnerStepOutcome TakeMalitskyPockStep();
// Takes a step based on the adaptive heuristic presented in Section 3.1 of
// https://arxiv.org/pdf/2106.04756.pdf (further generalized to QP).
InnerStepOutcome TakeAdaptiveStep();
// Takes a constant-size step.
InnerStepOutcome TakeConstantSizeStep();
const PrimalDualHybridGradientParams params_;
VectorXd current_primal_solution_;
VectorXd current_dual_solution_;
VectorXd current_primal_delta_;
VectorXd current_dual_delta_;
ShardedWeightedAverage primal_average_;
ShardedWeightedAverage dual_average_;
double step_size_;
double primal_weight_;
PreprocessSolver* preprocess_solver_;
// For Malitsky-Pock linesearch only: `step_size_` / previous_step_size
double ratio_last_two_step_sizes_;
// For adaptive restarts only.
double normalized_gap_at_last_trial_ =
std::numeric_limits<double>::infinity();
// For adaptive restarts only.
double normalized_gap_at_last_restart_ =
std::numeric_limits<double>::infinity();
// `preprocessing_time_sec_` is added to the current value of `timer_` when
// computing `cumulative_time_sec` in iteration stats.
double preprocessing_time_sec_;
WallTimer timer_;
int iterations_completed_;
int num_rejected_steps_;
// A cache of `constraint_matrix.transpose() * current_dual_solution_`.
VectorXd current_dual_product_;
// The primal point at which the algorithm was last restarted from, or
// the initial primal starting point if no restart has occurred.
VectorXd last_primal_start_point_;
// The dual point at which the algorithm was last restarted from, or
// the initial dual starting point if no restart has occurred.
VectorXd last_dual_start_point_;
// Information for deciding whether to trigger a distance-based restart.
// The distances are initialized to +inf to force a restart during the first
// major iteration check.
DistanceBasedRestartInfo distance_based_restart_info_ = {
.distance_moved_last_restart_period =
std::numeric_limits<double>::infinity(),
.length_of_last_restart_period = 1,
};
};
PreprocessSolver::PreprocessSolver(QuadraticProgram qp,
const PrimalDualHybridGradientParams& params,
SolverLogger* logger)
: num_threads_(
NumThreads(params.num_threads(), params.num_shards(), qp, *logger)),
num_shards_(NumShards(num_threads_, params.num_shards())),
sharded_qp_(std::move(qp), num_threads_, num_shards_,
params.scheduler_type(), nullptr),
logger_(*logger) {}
SolverResult ErrorSolverResult(const TerminationReason reason,
const std::string& message,
SolverLogger& logger) {
SolveLog error_log;
error_log.set_termination_reason(reason);
error_log.set_termination_string(message);
SOLVER_LOG(&logger,
"The solver did not run because of invalid input: ", message);
return SolverResult{.solve_log = error_log};
}
// If `check_excessively_small_values`, in addition to checking for extreme
// values that PDLP can't handle, also check for extremely small constraint
// bounds, variable bound gaps, and objective vector values that PDLP can handle
// but that cause problems for other code such as glop's presolve.
std::optional<SolverResult> CheckProblemStats(
const QuadraticProgramStats& problem_stats, const double objective_offset,
bool check_excessively_small_values, SolverLogger& logger) {
const double kExcessiveInputValue = 1e50;
const double kExcessivelySmallInputValue = 1e-50;
const double kMaxDynamicRange = 1e20;
if (std::isnan(problem_stats.constraint_matrix_l2_norm())) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Constraint matrix has a NAN.", logger);
}
if (problem_stats.constraint_matrix_abs_max() > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Constraint matrix has a non-zero with absolute value ",
problem_stats.constraint_matrix_abs_max(),
" which exceeds limit of ", kExcessiveInputValue, "."),
logger);
}
if (problem_stats.constraint_matrix_abs_max() >
kMaxDynamicRange * problem_stats.constraint_matrix_abs_min()) {
SOLVER_LOG(
&logger, "WARNING: Constraint matrix has largest absolute value ",
problem_stats.constraint_matrix_abs_max(),
" and smallest non-zero absolute value ",
problem_stats.constraint_matrix_abs_min(), " performance may suffer.");
}
if (problem_stats.constraint_matrix_col_min_l_inf_norm() > 0 &&
problem_stats.constraint_matrix_col_min_l_inf_norm() <
kExcessivelySmallInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Constraint matrix has a column with Linf norm ",
problem_stats.constraint_matrix_col_min_l_inf_norm(),
" which is less than limit of ",
kExcessivelySmallInputValue, "."),
logger);
}
if (problem_stats.constraint_matrix_row_min_l_inf_norm() > 0 &&
problem_stats.constraint_matrix_row_min_l_inf_norm() <
kExcessivelySmallInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Constraint matrix has a row with Linf norm ",
problem_stats.constraint_matrix_row_min_l_inf_norm(),
" which is less than limit of ",
kExcessivelySmallInputValue, "."),
logger);
}
if (std::isnan(problem_stats.combined_bounds_l2_norm())) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Constraint bounds vector has a NAN.", logger);
}
if (problem_stats.combined_bounds_max() > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Combined constraint bounds vector has a non-zero with "
"absolute value ",
problem_stats.combined_bounds_max(),
" which exceeds limit of ", kExcessiveInputValue, "."),
logger);
}
if (check_excessively_small_values &&
problem_stats.combined_bounds_min() > 0 &&
problem_stats.combined_bounds_min() < kExcessivelySmallInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Combined constraint bounds vector has a non-zero with "
"absolute value ",
problem_stats.combined_bounds_min(),
" which is less than the limit of ",
kExcessivelySmallInputValue, "."),
logger);
}
if (problem_stats.combined_bounds_max() >
kMaxDynamicRange * problem_stats.combined_bounds_min()) {
SOLVER_LOG(&logger,
"WARNING: Combined constraint bounds vector has largest "
"absolute value ",
problem_stats.combined_bounds_max(),
" and smallest non-zero absolute value ",
problem_stats.combined_bounds_min(),
"; performance may suffer.");
}
if (std::isnan(problem_stats.combined_variable_bounds_l2_norm())) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Variable bounds vector has a NAN.", logger);
}
if (problem_stats.combined_variable_bounds_max() > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Combined variable bounds vector has a non-zero with "
"absolute value ",
problem_stats.combined_variable_bounds_max(),
" which exceeds limit of ", kExcessiveInputValue, "."),
logger);
}
if (check_excessively_small_values &&
problem_stats.combined_variable_bounds_min() > 0 &&
problem_stats.combined_variable_bounds_min() <
kExcessivelySmallInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Combined variable bounds vector has a non-zero with "
"absolute value ",
problem_stats.combined_variable_bounds_min(),
" which is less than the limit of ",
kExcessivelySmallInputValue, "."),
logger);
}
if (problem_stats.combined_variable_bounds_max() >
kMaxDynamicRange * problem_stats.combined_variable_bounds_min()) {
SOLVER_LOG(
&logger,
"WARNING: Combined variable bounds vector has largest absolute value ",
problem_stats.combined_variable_bounds_max(),
" and smallest non-zero absolute value ",
problem_stats.combined_variable_bounds_min(),
"; performance may suffer.");
}
if (problem_stats.variable_bound_gaps_max() >
kMaxDynamicRange * problem_stats.variable_bound_gaps_min()) {
SOLVER_LOG(&logger,
"WARNING: Variable bound gap vector has largest absolute value ",
problem_stats.variable_bound_gaps_max(),
" and smallest non-zero absolute value ",
problem_stats.variable_bound_gaps_min(),
"; performance may suffer.");
}
if (std::isnan(objective_offset)) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Objective offset is NAN.", logger);
}
if (std::abs(objective_offset) > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Objective offset ", objective_offset,
" has absolute value which exceeds limit of ",
kExcessiveInputValue, "."),
logger);
}
if (std::isnan(problem_stats.objective_vector_l2_norm())) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Objective vector has a NAN.", logger);
}
if (problem_stats.objective_vector_abs_max() > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Objective vector has a non-zero with absolute value ",
problem_stats.objective_vector_abs_max(),
" which exceeds limit of ", kExcessiveInputValue, "."),
logger);
}
if (check_excessively_small_values &&
problem_stats.objective_vector_abs_min() > 0 &&
problem_stats.objective_vector_abs_min() < kExcessivelySmallInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Objective vector has a non-zero with absolute value ",
problem_stats.objective_vector_abs_min(),
" which is less than the limit of ",
kExcessivelySmallInputValue, "."),
logger);
}
if (problem_stats.objective_vector_abs_max() >
kMaxDynamicRange * problem_stats.objective_vector_abs_min()) {
SOLVER_LOG(&logger, "WARNING: Objective vector has largest absolute value ",
problem_stats.objective_vector_abs_max(),
" and smallest non-zero absolute value ",
problem_stats.objective_vector_abs_min(),
"; performance may suffer.");
}
if (std::isnan(problem_stats.objective_matrix_l2_norm())) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
"Objective matrix has a NAN.", logger);
}
if (problem_stats.objective_matrix_abs_max() > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_PROBLEM,
absl::StrCat("Objective matrix has a non-zero with absolute value ",
problem_stats.objective_matrix_abs_max(),
" which exceeds limit of ", kExcessiveInputValue, "."),
logger);
}
if (problem_stats.objective_matrix_abs_max() >
kMaxDynamicRange * problem_stats.objective_matrix_abs_min()) {
SOLVER_LOG(&logger, "WARNING: Objective matrix has largest absolute value ",
problem_stats.objective_matrix_abs_max(),
" and smallest non-zero absolute value ",
problem_stats.objective_matrix_abs_min(),
"; performance may suffer.");
}
return std::nullopt;
}
std::optional<SolverResult> CheckInitialSolution(
const ShardedQuadraticProgram& sharded_qp,
const PrimalAndDualSolution& initial_solution, SolverLogger& logger) {
const double kExcessiveInputValue = 1e50;
if (initial_solution.primal_solution.size() != sharded_qp.PrimalSize()) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
absl::StrCat("Initial primal solution has size ",
initial_solution.primal_solution.size(),
" which differs from problem primal size ",
sharded_qp.PrimalSize()),
logger);
}
if (std::isnan(
Norm(initial_solution.primal_solution, sharded_qp.PrimalSharder()))) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
"Initial primal solution has a NAN.", logger);
}
if (const double norm = LInfNorm(initial_solution.primal_solution,
sharded_qp.PrimalSharder());
norm > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
absl::StrCat(
"Initial primal solution has an entry with absolute value ", norm,
" which exceeds limit of ", kExcessiveInputValue),
logger);
}
if (initial_solution.dual_solution.size() != sharded_qp.DualSize()) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
absl::StrCat("Initial dual solution has size ",
initial_solution.dual_solution.size(),
" which differs from problem dual size ",
sharded_qp.DualSize()),
logger);
}
if (std::isnan(
Norm(initial_solution.dual_solution, sharded_qp.DualSharder()))) {
return ErrorSolverResult(TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
"Initial dual solution has a NAN.", logger);
}
if (const double norm =
LInfNorm(initial_solution.dual_solution, sharded_qp.DualSharder());
norm > kExcessiveInputValue) {
return ErrorSolverResult(
TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
absl::StrCat("Initial dual solution has an entry with absolute value ",
norm, " which exceeds limit of ", kExcessiveInputValue),
logger);
}
return std::nullopt;
}
SolverResult PreprocessSolver::PreprocessAndSolve(
const PrimalDualHybridGradientParams& params,
std::optional<PrimalAndDualSolution> initial_solution,
const std::atomic<bool>* interrupt_solve,
IterationStatsCallback iteration_stats_callback) {
WallTimer timer;
timer.Start();
SolveLog solve_log;
if (params.verbosity_level() >= 1) {
SOLVER_LOG(&logger_, "Solving with PDLP parameters: ", params);
}
if (Qp().problem_name.has_value()) {
solve_log.set_instance_name(*Qp().problem_name);