54#include "Eigen/SparseCore"
55#include "absl/algorithm/container.h"
56#include "absl/base/nullability.h"
57#include "absl/base/optimization.h"
58#include "absl/log/check.h"
59#include "absl/log/log.h"
60#include "absl/status/status.h"
61#include "absl/status/statusor.h"
62#include "absl/strings/str_cat.h"
63#include "absl/strings/str_format.h"
64#include "absl/strings/string_view.h"
65#include "absl/time/clock.h"
66#include "absl/time/time.h"
67#include "google/protobuf/repeated_ptr_field.h"
92using ::Eigen::VectorXd;
93using ::operations_research::SolverLogger;
95using IterationStatsCallback =
100int NumThreads(
const int num_threads,
const int num_shards,
102 int capped_num_threads = num_threads;
103 if (num_shards > 0) {
104 capped_num_threads = std::min(capped_num_threads, num_shards);
106 const int64_t problem_limit = std::max(qp.variable_lower_bounds.size(),
107 qp.constraint_lower_bounds.size());
109 static_cast<int>(std::min(int64_t{capped_num_threads}, problem_limit));
110 capped_num_threads = std::max(capped_num_threads, 1);
111 if (capped_num_threads != num_threads) {
112 SOLVER_LOG(&logger,
"WARNING: Reducing num_threads from ", num_threads,
113 " to ", capped_num_threads,
114 " because additional threads would be useless.");
116 return capped_num_threads;
122int NumShards(
const int num_threads,
const int num_shards) {
123 if (num_shards > 0)
return num_shards;
124 return num_threads == 1 ? 1 : 4 * num_threads;
127std::string ConvergenceInformationString(
131 constexpr absl::string_view kFormatStr =
132 "%#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g %#12.6g | %#12.6g %#12.6g | "
134 switch (residual_norm) {
136 return absl::StrFormat(
137 kFormatStr, relative_information.relative_l_inf_primal_residual,
138 relative_information.relative_l_inf_dual_residual,
139 relative_information.relative_optimality_gap,
140 convergence_information.l_inf_primal_residual(),
141 convergence_information.l_inf_dual_residual(),
142 convergence_information.primal_objective() -
143 convergence_information.dual_objective(),
144 convergence_information.primal_objective(),
145 convergence_information.dual_objective(),
146 convergence_information.l2_primal_variable(),
147 convergence_information.l2_dual_variable());
149 return absl::StrFormat(kFormatStr,
150 relative_information.relative_l2_primal_residual,
151 relative_information.relative_l2_dual_residual,
152 relative_information.relative_optimality_gap,
153 convergence_information.l2_primal_residual(),
154 convergence_information.l2_dual_residual(),
155 convergence_information.primal_objective() -
156 convergence_information.dual_objective(),
157 convergence_information.primal_objective(),
158 convergence_information.dual_objective(),
159 convergence_information.l2_primal_variable(),
160 convergence_information.l2_dual_variable());
162 return absl::StrFormat(
164 convergence_information.l_inf_componentwise_primal_residual(),
165 convergence_information.l_inf_componentwise_dual_residual(),
166 relative_information.relative_optimality_gap,
167 convergence_information.l_inf_primal_residual(),
168 convergence_information.l_inf_dual_residual(),
169 convergence_information.primal_objective() -
170 convergence_information.dual_objective(),
171 convergence_information.primal_objective(),
172 convergence_information.dual_objective(),
173 convergence_information.l2_primal_variable(),
174 convergence_information.l2_dual_variable());
176 LOG(FATAL) <<
"Residual norm not specified.";
178 LOG(FATAL) <<
"Invalid residual norm " << residual_norm <<
".";
181std::string ConvergenceInformationShortString(
185 constexpr absl::string_view kFormatStr =
186 "%#10.4g %#10.4g %#10.4g | %#10.4g %#10.4g";
187 switch (residual_norm) {
189 return absl::StrFormat(
190 kFormatStr, relative_information.relative_l_inf_primal_residual,
191 relative_information.relative_l_inf_dual_residual,
192 relative_information.relative_optimality_gap,
193 convergence_information.primal_objective(),
194 convergence_information.dual_objective());
196 return absl::StrFormat(kFormatStr,
197 relative_information.relative_l2_primal_residual,
198 relative_information.relative_l2_dual_residual,
199 relative_information.relative_optimality_gap,
200 convergence_information.primal_objective(),
201 convergence_information.dual_objective());
203 return absl::StrFormat(
205 convergence_information.l_inf_componentwise_primal_residual(),
206 convergence_information.l_inf_componentwise_dual_residual(),
207 relative_information.relative_optimality_gap,
208 convergence_information.primal_objective(),
209 convergence_information.dual_objective());
211 LOG(FATAL) <<
"Residual norm not specified.";
213 LOG(FATAL) <<
"Invalid residual norm " << residual_norm <<
".";
221void LogIterationStats(
int verbosity_level,
bool use_feasibility_polishing,
227 std::string iteration_string =
229 ? absl::StrFormat(
"%6d %8.1f %6.1f", iter_stats.iteration_number(),
230 iter_stats.cumulative_kkt_matrix_passes(),
231 iter_stats.cumulative_time_sec())
232 : absl::StrFormat(
"%6d %6.1f", iter_stats.iteration_number(),
233 iter_stats.cumulative_time_sec());
234 auto convergence_information =
236 if (!convergence_information.has_value() &&
237 iter_stats.convergence_information_size() > 0) {
238 convergence_information = iter_stats.convergence_information(0);
240 const char* phase_string = [&]() {
241 if (use_feasibility_polishing) {
242 switch (iteration_type) {
259 if (convergence_information.has_value()) {
260 const char* iterate_string = [&]() {
261 if (verbosity_level >= 4) {
262 switch (convergence_information->candidate_type()) {
281 *convergence_information, bound_norms);
282 std::string convergence_string =
284 ? ConvergenceInformationString(
285 *convergence_information, relative_information,
286 termination_criteria.optimality_norm())
287 : ConvergenceInformationShortString(
288 *convergence_information, relative_information,
289 termination_criteria.optimality_norm());
290 SOLVER_LOG(&logger, phase_string, iterate_string, iteration_string,
" | ",
294 SOLVER_LOG(&logger, phase_string, verbosity_level >= 4 ?
"? " :
"",
299void LogIterationStatsHeader(
int verbosity_level,
300 bool use_feasibility_polishing,
302 std::string work_labels =
304 ? absl::StrFormat(
"%6s %8s %6s",
"iter#",
"kkt_pass",
"time")
305 : absl::StrFormat(
"%6s %6s",
"iter#",
"time");
306 std::string convergence_labels =
309 "%12s %12s %12s | %12s %12s %12s | %12s %12s | %12s %12s",
310 "rel_prim_res",
"rel_dual_res",
"rel_gap",
"prim_resid",
311 "dual_resid",
"obj_gap",
"prim_obj",
"dual_obj",
"prim_var_l2",
313 : absl::StrFormat(
"%10s %10s %10s | %10s %10s",
"rel_p_res",
314 "rel_d_res",
"rel_gap",
"prim_obj",
"dual_obj");
315 SOLVER_LOG(&logger, use_feasibility_polishing ?
"f " :
"",
316 verbosity_level >= 4 ?
"I " :
"", work_labels,
" | ",
320enum class InnerStepOutcome {
322 kForceNumericalTermination,
330 VectorXd dual_solution,
334 solve_log.set_iteration_count(stats.iteration_number());
335 solve_log.set_termination_reason(termination_reason);
336 solve_log.set_solution_type(output_type);
337 solve_log.set_solve_time_sec(stats.cumulative_time_sec());
338 *solve_log.mutable_solution_stats() = stats;
340 .dual_solution = std::move(dual_solution),
341 .solve_log = std::move(solve_log)};
345class PreprocessSolver {
354 explicit PreprocessSolver(QuadraticProgram qp,
355 const PrimalDualHybridGradientParams& params,
356 SolverLogger* logger);
359 PreprocessSolver(
const PreprocessSolver&) =
delete;
360 PreprocessSolver& operator=(
const PreprocessSolver&) =
delete;
361 PreprocessSolver(PreprocessSolver&&) =
delete;
362 PreprocessSolver& operator=(PreprocessSolver&&) =
delete;
371 SolverResult PreprocessAndSolve(
372 const PrimalDualHybridGradientParams& params,
373 std::optional<PrimalAndDualSolution> initial_solution,
374 const std::atomic<bool>* interrupt_solve,
375 IterationStatsCallback iteration_stats_callback);
386 std::optional<TerminationReasonAndPointType>
387 UpdateIterationStatsAndCheckTermination(
388 const PrimalDualHybridGradientParams& params,
389 bool force_numerical_termination,
const VectorXd& working_primal_current,
390 const VectorXd& working_dual_current,
391 const VectorXd* working_primal_average,
392 const VectorXd* working_dual_average,
393 const VectorXd* working_primal_delta,
const VectorXd* working_dual_delta,
394 const VectorXd& last_primal_start_point,
395 const VectorXd& last_dual_start_point,
396 const std::atomic<bool>* interrupt_solve,
IterationType iteration_type,
397 const IterationStats& full_stats, IterationStats& stats);
404 void ComputeConvergenceAndInfeasibilityFromWorkingSolution(
405 const PrimalDualHybridGradientParams& params,
406 const VectorXd& working_primal,
const VectorXd& working_dual,
407 PointType candidate_type, ConvergenceInformation* convergence_information,
408 InfeasibilityInformation* infeasibility_information)
const;
414 SolverResult ConstructOriginalSolverResult(
415 const PrimalDualHybridGradientParams& params, SolverResult result,
416 SolverLogger& logger)
const;
418 const ShardedQuadraticProgram& ShardedWorkingQp()
const {
424 void SwapVariableBounds(VectorXd& variable_lower_bounds,
425 VectorXd& variable_upper_bounds) {
426 sharded_qp_.SwapVariableBounds(variable_lower_bounds,
427 variable_upper_bounds);
432 void SwapConstraintBounds(VectorXd& constraint_lower_bounds,
433 VectorXd& constraint_upper_bounds) {
434 sharded_qp_.SwapConstraintBounds(constraint_lower_bounds,
435 constraint_upper_bounds);
441 void SwapObjectiveVector(VectorXd& objective) {
442 sharded_qp_.SwapObjectiveVector(objective);
445 const QuadraticProgramBoundNorms& OriginalBoundNorms()
const {
446 return original_bound_norms_;
449 SolverLogger& Logger() {
return logger_; }
452 struct PresolveInfo {
453 explicit PresolveInfo(ShardedQuadraticProgram original_qp,
454 const PrimalDualHybridGradientParams& params)
455 : preprocessor_parameters(PreprocessorParameters(params)),
456 preprocessor(&preprocessor_parameters),
457 sharded_original_qp(std::move(original_qp)),
458 trivial_col_scaling_vec(
459 OnesVector(sharded_original_qp.PrimalSharder())),
460 trivial_row_scaling_vec(
461 OnesVector(sharded_original_qp.DualSharder())) {}
463 glop::GlopParameters preprocessor_parameters;
464 glop::MainLpPreprocessor preprocessor;
465 ShardedQuadraticProgram sharded_original_qp;
466 bool presolved_problem_was_maximization =
false;
467 const VectorXd trivial_col_scaling_vec, trivial_row_scaling_vec;
471 static glop::GlopParameters PreprocessorParameters(
472 const PrimalDualHybridGradientParams& params);
480 std::optional<TerminationReason> ApplyPresolveIfEnabled(
481 const PrimalDualHybridGradientParams& params,
482 std::optional<PrimalAndDualSolution>* initial_solution);
484 void ComputeAndApplyRescaling(
const PrimalDualHybridGradientParams& params,
485 VectorXd& starting_primal_solution,
486 VectorXd& starting_dual_solution);
488 void LogQuadraticProgramStats(
const QuadraticProgramStats& stats)
const;
490 double InitialPrimalWeight(
const PrimalDualHybridGradientParams& params,
491 double l2_norm_primal_linear_objective,
492 double l2_norm_constraint_bounds)
const;
494 PrimalAndDualSolution RecoverOriginalSolution(
495 PrimalAndDualSolution working_solution)
const;
498 void AddPointMetadata(
const PrimalDualHybridGradientParams& params,
500 const VectorXd& dual_solution,
PointType point_type,
501 const VectorXd& last_primal_start_point,
502 const VectorXd& last_dual_start_point,
503 IterationStats& stats)
const;
505 const QuadraticProgram& Qp()
const {
return sharded_qp_.Qp(); }
507 const int num_threads_;
508 const int num_shards_;
511 QuadraticProgramBoundNorms original_bound_norms_;
519 ShardedQuadraticProgram sharded_qp_;
522 std::optional<PresolveInfo> presolve_info_;
527 VectorXd col_scaling_vec_;
528 VectorXd row_scaling_vec_;
531 int log_counter_ = 0;
532 absl::Time time_of_last_log_ = absl::InfinitePast();
533 SolverLogger& logger_;
534 IterationStatsCallback iteration_stats_callback_;
542 explicit Solver(
const PrimalDualHybridGradientParams& params,
543 VectorXd starting_primal_solution,
544 VectorXd starting_dual_solution,
double initial_step_size,
545 double initial_primal_weight,
546 PreprocessSolver* preprocess_solver);
549 Solver(
const Solver&) =
delete;
550 Solver& operator=(
const Solver&) =
delete;
551 Solver(Solver&&) =
delete;
552 Solver& operator=(Solver&&) =
delete;
554 const QuadraticProgram& WorkingQp()
const {
return ShardedWorkingQp().Qp(); }
556 const ShardedQuadraticProgram& ShardedWorkingQp()
const {
557 return preprocess_solver_->ShardedWorkingQp();
569 const std::atomic<bool>* interrupt_solve,
573 struct NextSolutionAndDelta {
579 struct DistanceBasedRestartInfo {
580 double distance_moved_last_restart_period;
581 int length_of_last_restart_period;
587 constexpr static double kDivergentMovement = 1.0e100;
596 constexpr static int kFeasibilityIterationFraction = 8;
603 std::optional<SolverResult> TryFeasibilityPolishing(
604 int iteration_limit,
const std::atomic<bool>* interrupt_solve,
605 SolveLog& solve_log);
609 SolverResult TryPrimalPolishing(VectorXd starting_primal_solution,
611 const std::atomic<bool>* interrupt_solve,
612 SolveLog& solve_log);
616 SolverResult TryDualPolishing(VectorXd starting_dual_solution,
618 const std::atomic<bool>* interrupt_solve,
619 SolveLog& solve_log);
621 NextSolutionAndDelta ComputeNextPrimalSolution(
double primal_step_size)
const;
623 NextSolutionAndDelta ComputeNextDualSolution(
624 double dual_step_size,
double extrapolation_factor,
625 const NextSolutionAndDelta& next_primal_solution,
626 const VectorXd* absl_nullable next_primal_product =
nullptr)
const;
628 std::pair<double, double> ComputeMovementTerms(
629 const VectorXd& delta_primal,
const VectorXd& delta_dual)
const;
631 double ComputeMovement(
const VectorXd& delta_primal,
632 const VectorXd& delta_dual)
const;
634 double ComputeNonlinearity(
const VectorXd& delta_primal,
635 const VectorXd& next_dual_product)
const;
639 void SetCurrentPrimalAndDualProducts();
642 IterationStats CreateSimpleIterationStats(
RestartChoice restart_used)
const;
646 IterationStats TotalWorkSoFar(
const SolveLog& solve_log)
const;
650 VectorXd PrimalAverage()
const;
652 VectorXd DualAverage()
const;
654 double ComputeNewPrimalWeight()
const;
666 SolverResult PickSolutionAndConstructSolverResult(
669 PointType output_type, SolveLog solve_log)
const;
672 const VectorXd& dual_solution)
const;
674 LocalizedLagrangianBounds ComputeLocalizedBoundsAtCurrent()
const;
676 LocalizedLagrangianBounds ComputeLocalizedBoundsAtAverage()
const;
682 std::optional<SolverResult> MajorIterationAndTerminationCheck(
683 IterationType iteration_type,
bool force_numerical_termination,
684 const std::atomic<bool>* interrupt_solve,
685 const IterationStats& work_from_feasibility_polishing,
686 SolveLog& solve_log);
688 bool ShouldDoAdaptiveRestartHeuristic(
double candidate_normalized_gap)
const;
692 void ResetAverageToCurrent();
694 void LogNumericalTermination(
const Eigen::VectorXd& primal_delta,
695 const Eigen::VectorXd& dual_delta)
const;
697 void LogInnerIterationLimitHit()
const;
706 InnerStepOutcome TakeMalitskyPockStep();
710 InnerStepOutcome TakeAdaptiveStep();
713 InnerStepOutcome TakeConstantSizeStep();
715 const PrimalDualHybridGradientParams params_;
717 VectorXd current_primal_solution_;
718 VectorXd current_dual_solution_;
719 VectorXd current_primal_delta_;
720 VectorXd current_dual_delta_;
722 ShardedWeightedAverage primal_average_;
723 ShardedWeightedAverage dual_average_;
726 double primal_weight_;
728 PreprocessSolver* preprocess_solver_;
731 double ratio_last_two_step_sizes_;
733 double normalized_gap_at_last_trial_ =
734 std::numeric_limits<double>::infinity();
736 double normalized_gap_at_last_restart_ =
737 std::numeric_limits<double>::infinity();
741 double preprocessing_time_sec_;
743 int iterations_completed_;
744 int num_rejected_steps_;
747 std::optional<VectorXd> current_primal_product_;
749 VectorXd current_dual_product_;
752 VectorXd last_primal_start_point_;
755 VectorXd last_dual_start_point_;
759 DistanceBasedRestartInfo distance_based_restart_info_ = {
760 .distance_moved_last_restart_period =
761 std::numeric_limits<double>::infinity(),
762 .length_of_last_restart_period = 1,
770 NumThreads(params.num_threads(), params.num_shards(), qp, *logger)),
771 num_shards_(NumShards(num_threads_, params.num_shards())),
772 sharded_qp_(std::move(qp), num_threads_, num_shards_,
773 params.scheduler_type(), nullptr),
776SolverResult ErrorSolverResult(
const TerminationReason reason,
777 const std::string& message,
780 error_log.set_termination_reason(reason);
781 error_log.set_termination_string(message);
783 "The solver did not run because of invalid input: ", message);
784 return SolverResult{.solve_log = error_log};
791std::optional<SolverResult> CheckProblemStats(
792 const QuadraticProgramStats& problem_stats,
const double objective_offset,
793 bool check_excessively_small_values,
SolverLogger& logger) {
794 const double kExcessiveInputValue = 1e50;
795 const double kExcessivelySmallInputValue = 1e-50;
796 const double kMaxDynamicRange = 1e20;
797 if (std::isnan(problem_stats.constraint_matrix_l2_norm())) {
798 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
799 "Constraint matrix has a NAN.", logger);
801 if (problem_stats.constraint_matrix_abs_max() > kExcessiveInputValue) {
802 return ErrorSolverResult(
803 TERMINATION_REASON_INVALID_PROBLEM,
804 absl::StrCat(
"Constraint matrix has a non-zero with absolute value ",
805 problem_stats.constraint_matrix_abs_max(),
806 " which exceeds limit of ", kExcessiveInputValue,
"."),
809 if (problem_stats.constraint_matrix_abs_max() >
810 kMaxDynamicRange * problem_stats.constraint_matrix_abs_min()) {
812 &logger,
"WARNING: Constraint matrix has largest absolute value ",
813 problem_stats.constraint_matrix_abs_max(),
814 " and smallest non-zero absolute value ",
815 problem_stats.constraint_matrix_abs_min(),
" performance may suffer.");
817 if (problem_stats.constraint_matrix_col_min_l_inf_norm() > 0 &&
818 problem_stats.constraint_matrix_col_min_l_inf_norm() <
819 kExcessivelySmallInputValue) {
820 return ErrorSolverResult(
821 TERMINATION_REASON_INVALID_PROBLEM,
822 absl::StrCat(
"Constraint matrix has a column with Linf norm ",
823 problem_stats.constraint_matrix_col_min_l_inf_norm(),
824 " which is less than limit of ",
825 kExcessivelySmallInputValue,
"."),
828 if (problem_stats.constraint_matrix_row_min_l_inf_norm() > 0 &&
829 problem_stats.constraint_matrix_row_min_l_inf_norm() <
830 kExcessivelySmallInputValue) {
831 return ErrorSolverResult(
832 TERMINATION_REASON_INVALID_PROBLEM,
833 absl::StrCat(
"Constraint matrix has a row with Linf norm ",
834 problem_stats.constraint_matrix_row_min_l_inf_norm(),
835 " which is less than limit of ",
836 kExcessivelySmallInputValue,
"."),
839 if (std::isnan(problem_stats.combined_bounds_l2_norm())) {
840 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
841 "Constraint bounds vector has a NAN.", logger);
843 if (problem_stats.combined_bounds_max() > kExcessiveInputValue) {
844 return ErrorSolverResult(
845 TERMINATION_REASON_INVALID_PROBLEM,
846 absl::StrCat(
"Combined constraint bounds vector has a non-zero with "
848 problem_stats.combined_bounds_max(),
849 " which exceeds limit of ", kExcessiveInputValue,
"."),
852 if (check_excessively_small_values &&
853 problem_stats.combined_bounds_min() > 0 &&
854 problem_stats.combined_bounds_min() < kExcessivelySmallInputValue) {
855 return ErrorSolverResult(
856 TERMINATION_REASON_INVALID_PROBLEM,
857 absl::StrCat(
"Combined constraint bounds vector has a non-zero with "
859 problem_stats.combined_bounds_min(),
860 " which is less than the limit of ",
861 kExcessivelySmallInputValue,
"."),
864 if (problem_stats.combined_bounds_max() >
865 kMaxDynamicRange * problem_stats.combined_bounds_min()) {
867 "WARNING: Combined constraint bounds vector has largest "
869 problem_stats.combined_bounds_max(),
870 " and smallest non-zero absolute value ",
871 problem_stats.combined_bounds_min(),
872 "; performance may suffer.");
874 if (std::isnan(problem_stats.combined_variable_bounds_l2_norm())) {
875 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
876 "Variable bounds vector has a NAN.", logger);
878 if (problem_stats.combined_variable_bounds_max() > kExcessiveInputValue) {
879 return ErrorSolverResult(
880 TERMINATION_REASON_INVALID_PROBLEM,
881 absl::StrCat(
"Combined variable bounds vector has a non-zero with "
883 problem_stats.combined_variable_bounds_max(),
884 " which exceeds limit of ", kExcessiveInputValue,
"."),
887 if (check_excessively_small_values &&
888 problem_stats.combined_variable_bounds_min() > 0 &&
889 problem_stats.combined_variable_bounds_min() <
890 kExcessivelySmallInputValue) {
891 return ErrorSolverResult(
892 TERMINATION_REASON_INVALID_PROBLEM,
893 absl::StrCat(
"Combined variable bounds vector has a non-zero with "
895 problem_stats.combined_variable_bounds_min(),
896 " which is less than the limit of ",
897 kExcessivelySmallInputValue,
"."),
900 if (problem_stats.combined_variable_bounds_max() >
901 kMaxDynamicRange * problem_stats.combined_variable_bounds_min()) {
904 "WARNING: Combined variable bounds vector has largest absolute value ",
905 problem_stats.combined_variable_bounds_max(),
906 " and smallest non-zero absolute value ",
907 problem_stats.combined_variable_bounds_min(),
908 "; performance may suffer.");
910 if (problem_stats.variable_bound_gaps_max() >
911 kMaxDynamicRange * problem_stats.variable_bound_gaps_min()) {
913 "WARNING: Variable bound gap vector has largest absolute value ",
914 problem_stats.variable_bound_gaps_max(),
915 " and smallest non-zero absolute value ",
916 problem_stats.variable_bound_gaps_min(),
917 "; performance may suffer.");
919 if (std::isnan(objective_offset)) {
920 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
921 "Objective offset is NAN.", logger);
923 if (std::abs(objective_offset) > kExcessiveInputValue) {
924 return ErrorSolverResult(
925 TERMINATION_REASON_INVALID_PROBLEM,
926 absl::StrCat(
"Objective offset ", objective_offset,
927 " has absolute value which exceeds limit of ",
928 kExcessiveInputValue,
"."),
931 if (std::isnan(problem_stats.objective_vector_l2_norm())) {
932 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
933 "Objective vector has a NAN.", logger);
935 if (problem_stats.objective_vector_abs_max() > kExcessiveInputValue) {
936 return ErrorSolverResult(
937 TERMINATION_REASON_INVALID_PROBLEM,
938 absl::StrCat(
"Objective vector has a non-zero with absolute value ",
939 problem_stats.objective_vector_abs_max(),
940 " which exceeds limit of ", kExcessiveInputValue,
"."),
943 if (check_excessively_small_values &&
944 problem_stats.objective_vector_abs_min() > 0 &&
945 problem_stats.objective_vector_abs_min() < kExcessivelySmallInputValue) {
946 return ErrorSolverResult(
947 TERMINATION_REASON_INVALID_PROBLEM,
948 absl::StrCat(
"Objective vector has a non-zero with absolute value ",
949 problem_stats.objective_vector_abs_min(),
950 " which is less than the limit of ",
951 kExcessivelySmallInputValue,
"."),
954 if (problem_stats.objective_vector_abs_max() >
955 kMaxDynamicRange * problem_stats.objective_vector_abs_min()) {
956 SOLVER_LOG(&logger,
"WARNING: Objective vector has largest absolute value ",
957 problem_stats.objective_vector_abs_max(),
958 " and smallest non-zero absolute value ",
959 problem_stats.objective_vector_abs_min(),
960 "; performance may suffer.");
962 if (std::isnan(problem_stats.objective_matrix_l2_norm())) {
963 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
964 "Objective matrix has a NAN.", logger);
966 if (problem_stats.objective_matrix_abs_max() > kExcessiveInputValue) {
967 return ErrorSolverResult(
968 TERMINATION_REASON_INVALID_PROBLEM,
969 absl::StrCat(
"Objective matrix has a non-zero with absolute value ",
970 problem_stats.objective_matrix_abs_max(),
971 " which exceeds limit of ", kExcessiveInputValue,
"."),
974 if (problem_stats.objective_matrix_abs_max() >
975 kMaxDynamicRange * problem_stats.objective_matrix_abs_min()) {
976 SOLVER_LOG(&logger,
"WARNING: Objective matrix has largest absolute value ",
977 problem_stats.objective_matrix_abs_max(),
978 " and smallest non-zero absolute value ",
979 problem_stats.objective_matrix_abs_min(),
980 "; performance may suffer.");
985std::optional<SolverResult> CheckInitialSolution(
986 const ShardedQuadraticProgram& sharded_qp,
987 const PrimalAndDualSolution& initial_solution,
SolverLogger& logger) {
988 const double kExcessiveInputValue = 1e50;
989 if (initial_solution.primal_solution.size() != sharded_qp.PrimalSize()) {
990 return ErrorSolverResult(
991 TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
992 absl::StrCat(
"Initial primal solution has size ",
993 initial_solution.primal_solution.size(),
994 " which differs from problem primal size ",
995 sharded_qp.PrimalSize()),
999 Norm(initial_solution.primal_solution, sharded_qp.PrimalSharder()))) {
1000 return ErrorSolverResult(TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
1001 "Initial primal solution has a NAN.", logger);
1003 if (
const double norm =
LInfNorm(initial_solution.primal_solution,
1004 sharded_qp.PrimalSharder());
1005 norm > kExcessiveInputValue) {
1006 return ErrorSolverResult(
1007 TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
1009 "Initial primal solution has an entry with absolute value ", norm,
1010 " which exceeds limit of ", kExcessiveInputValue),
1013 if (initial_solution.dual_solution.size() != sharded_qp.DualSize()) {
1014 return ErrorSolverResult(
1015 TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
1016 absl::StrCat(
"Initial dual solution has size ",
1017 initial_solution.dual_solution.size(),
1018 " which differs from problem dual size ",
1019 sharded_qp.DualSize()),
1023 Norm(initial_solution.dual_solution, sharded_qp.DualSharder()))) {
1024 return ErrorSolverResult(TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
1025 "Initial dual solution has a NAN.", logger);
1027 if (
const double norm =
1028 LInfNorm(initial_solution.dual_solution, sharded_qp.DualSharder());
1029 norm > kExcessiveInputValue) {
1030 return ErrorSolverResult(
1031 TERMINATION_REASON_INVALID_INITIAL_SOLUTION,
1032 absl::StrCat(
"Initial dual solution has an entry with absolute value ",
1033 norm,
" which exceeds limit of ", kExcessiveInputValue),
1036 return std::nullopt;
1039SolverResult PreprocessSolver::PreprocessAndSolve(
1040 const PrimalDualHybridGradientParams& params,
1041 std::optional<PrimalAndDualSolution> initial_solution,
1042 const std::atomic<bool>* interrupt_solve,
1043 IterationStatsCallback iteration_stats_callback) {
1047 if (params.verbosity_level() >= 1) {
1048 SOLVER_LOG(&logger_,
"Solving with PDLP parameters: ", params);
1050 if (Qp().problem_name.has_value()) {
1051 solve_log.set_instance_name(*Qp().problem_name);
1053 *solve_log.mutable_params() = params;
1054 sharded_qp_.ReplaceLargeConstraintBoundsWithInfinity(
1055 params.infinite_constraint_bound_threshold());
1057 return ErrorSolverResult(
1058 TERMINATION_REASON_INVALID_PROBLEM,
1059 "The input problem has invalid bounds (after replacing large "
1060 "constraint bounds with infinity): some variable or constraint has "
1061 "lower_bound > upper_bound, lower_bound == inf, or upper_bound == "
1065 if (Qp().objective_matrix.has_value() &&
1066 !sharded_qp_.PrimalSharder().ParallelTrueForAllShards(
1067 [&](
const Sharder::Shard& shard) ->
bool {
1068 return (shard(Qp().objective_matrix->diagonal()).array() >= 0.0)
1071 return ErrorSolverResult(TERMINATION_REASON_INVALID_PROBLEM,
1072 "The objective is not convex (i.e., the objective "
1073 "matrix contains negative or NAN entries).",
1076 *solve_log.mutable_original_problem_stats() =
ComputeStats(sharded_qp_);
1077 const QuadraticProgramStats& original_problem_stats =
1078 solve_log.original_problem_stats();
1079 if (
auto maybe_result =
1080 CheckProblemStats(original_problem_stats, Qp().objective_offset,
1081 params.presolve_options().use_glop(), logger_);
1082 maybe_result.has_value()) {
1083 return *maybe_result;
1085 if (initial_solution.has_value()) {
1086 if (
auto maybe_result =
1087 CheckInitialSolution(sharded_qp_, *initial_solution, logger_);
1088 maybe_result.has_value()) {
1089 return *maybe_result;
1093 const std::string preprocessing_string = absl::StrCat(
1094 params.presolve_options().use_glop() ?
"presolving and " :
"",
1096 if (params.verbosity_level() >= 1) {
1097 SOLVER_LOG(&logger_,
"Problem stats before ", preprocessing_string);
1098 LogQuadraticProgramStats(solve_log.original_problem_stats());
1100 iteration_stats_callback_ = std::move(iteration_stats_callback);
1101 std::optional<TerminationReason> maybe_terminate =
1102 ApplyPresolveIfEnabled(params, &initial_solution);
1103 if (maybe_terminate.has_value()) {
1109 IterationStats iteration_stats;
1110 iteration_stats.set_cumulative_time_sec(timer.
Get());
1111 solve_log.set_preprocessing_time_sec(iteration_stats.cumulative_time_sec());
1112 VectorXd working_primal =
ZeroVector(sharded_qp_.PrimalSharder());
1113 VectorXd working_dual =
ZeroVector(sharded_qp_.DualSharder());
1114 ComputeConvergenceAndInfeasibilityFromWorkingSolution(
1115 params, working_primal, working_dual, POINT_TYPE_PRESOLVER_SOLUTION,
1116 iteration_stats.add_convergence_information(),
1117 iteration_stats.add_infeasibility_information());
1118 std::optional<TerminationReasonAndPointType> earned_termination =
1120 iteration_stats, original_bound_norms_,
1122 if (!earned_termination.has_value()) {
1124 params.termination_criteria(), iteration_stats, interrupt_solve);
1127 if (earned_termination.has_value() &&
1128 (earned_termination->reason == TERMINATION_REASON_OPTIMAL ||
1129 earned_termination->reason == TERMINATION_REASON_PRIMAL_INFEASIBLE ||
1130 earned_termination->reason == TERMINATION_REASON_DUAL_INFEASIBLE)) {
1131 final_termination_reason = earned_termination->reason;
1133 if (*maybe_terminate == TERMINATION_REASON_OPTIMAL) {
1137 "WARNING: Presolve claimed to solve the LP optimally but the "
1138 "solution doesn't satisfy the optimality criteria.");
1140 final_termination_reason = *maybe_terminate;
1143 return ConstructOriginalSolverResult(
1145 ConstructSolverResult(
1146 std::move(working_primal), std::move(working_dual),
1147 std::move(iteration_stats), final_termination_reason,
1148 POINT_TYPE_PRESOLVER_SOLUTION, std::move(solve_log)),
1152 VectorXd starting_primal_solution;
1153 VectorXd starting_dual_solution;
1155 if (initial_solution.has_value()) {
1156 starting_primal_solution = std::move(initial_solution->primal_solution);
1157 starting_dual_solution = std::move(initial_solution->dual_solution);
1159 SetZero(sharded_qp_.PrimalSharder(), starting_primal_solution);
1160 SetZero(sharded_qp_.DualSharder(), starting_dual_solution);
1167 ComputeAndApplyRescaling(params, starting_primal_solution,
1168 starting_dual_solution);
1169 *solve_log.mutable_preprocessed_problem_stats() =
ComputeStats(sharded_qp_);
1170 if (params.verbosity_level() >= 1) {
1171 SOLVER_LOG(&logger_,
"Problem stats after ", preprocessing_string);
1172 LogQuadraticProgramStats(solve_log.preprocessed_problem_stats());
1175 double step_size = 0.0;
1176 if (params.linesearch_rule() ==
1177 PrimalDualHybridGradientParams::CONSTANT_STEP_SIZE_RULE) {
1178 std::mt19937 random(1);
1179 double inverse_step_size;
1180 const auto lipschitz_result =
1182 sharded_qp_, std::nullopt, std::nullopt,
1188 const double lipschitz_term_upper_bound =
1189 lipschitz_result.singular_value /
1190 (1.0 - lipschitz_result.estimated_relative_error);
1191 inverse_step_size = lipschitz_term_upper_bound;
1192 step_size = inverse_step_size > 0.0 ? 1.0 / inverse_step_size : 1.0;
1207 solve_log.preprocessed_problem_stats().constraint_matrix_abs_max());
1209 step_size *= params.initial_step_size_scaling();
1211 const double primal_weight = InitialPrimalWeight(
1212 params, solve_log.preprocessed_problem_stats().objective_vector_l2_norm(),
1213 solve_log.preprocessed_problem_stats().combined_bounds_l2_norm());
1215 Solver solver(params, starting_primal_solution, starting_dual_solution,
1216 step_size, primal_weight,
this);
1217 solve_log.set_preprocessing_time_sec(timer.
Get());
1218 SolverResult result = solver.Solve(IterationType::kNormal, interrupt_solve,
1219 std::move(solve_log));
1220 return ConstructOriginalSolverResult(params, std::move(result), logger_);
1223glop::GlopParameters PreprocessSolver::PreprocessorParameters(
1224 const PrimalDualHybridGradientParams& params) {
1225 glop::GlopParameters glop_params;
1227 glop_params.set_solve_dual_problem(glop::GlopParameters::NEVER_DO);
1230 glop_params.set_use_implied_free_preprocessor(
false);
1232 glop_params.set_use_scaling(
false);
1233 if (params.presolve_options().has_glop_parameters()) {
1234 glop_params.MergeFrom(params.presolve_options().glop_parameters());
1240 const glop::ProblemStatus glop_status,
SolverLogger& logger) {
1241 switch (glop_status) {
1242 case glop::ProblemStatus::OPTIMAL:
1244 case glop::ProblemStatus::INVALID_PROBLEM:
1246 case glop::ProblemStatus::ABNORMAL:
1247 case glop::ProblemStatus::IMPRECISE:
1249 case glop::ProblemStatus::PRIMAL_INFEASIBLE:
1250 case glop::ProblemStatus::DUAL_INFEASIBLE:
1251 case glop::ProblemStatus::INFEASIBLE_OR_UNBOUNDED:
1252 case glop::ProblemStatus::DUAL_UNBOUNDED:
1253 case glop::ProblemStatus::PRIMAL_UNBOUNDED:
1256 SOLVER_LOG(&logger,
"WARNING: Unexpected preprocessor status ",
1262std::optional<TerminationReason> PreprocessSolver::ApplyPresolveIfEnabled(
1263 const PrimalDualHybridGradientParams& params,
1264 std::optional<PrimalAndDualSolution>*
const initial_solution) {
1265 const bool presolve_enabled = params.presolve_options().use_glop();
1266 if (!presolve_enabled) {
1267 return std::nullopt;
1271 "WARNING: Skipping presolve, which is only supported for linear "
1273 return std::nullopt;
1278 "WARNING: Skipping presolve because of error converting to "
1281 return std::nullopt;
1283 if (initial_solution->has_value()) {
1285 "WARNING: Ignoring initial solution. Initial solutions are "
1286 "ignored when presolve is on.");
1287 initial_solution->reset();
1289 glop::LinearProgram glop_lp;
1290 glop::MPModelProtoToLinearProgram(*model, &glop_lp);
1293 presolve_info_.emplace(std::move(sharded_qp_), params);
1297 presolve_info_->preprocessor.Run(&glop_lp);
1298 presolve_info_->presolved_problem_was_maximization =
1299 glop_lp.IsMaximizationProblem();
1300 MPModelProto output;
1301 glop::LinearProgramToMPModelProto(glop_lp, &output);
1303 absl::StatusOr<QuadraticProgram> presolved_qp =
1305 CHECK_OK(presolved_qp.status());
1310 presolved_qp->objective_scaling_factor = glop_lp.objective_scaling_factor();
1311 sharded_qp_ = ShardedQuadraticProgram(std::move(*presolved_qp), num_threads_,
1312 num_shards_, params.scheduler_type());
1316 if (presolve_info_->preprocessor.status() != glop::ProblemStatus::INIT) {
1317 col_scaling_vec_ =
OnesVector(sharded_qp_.PrimalSharder());
1318 row_scaling_vec_ =
OnesVector(sharded_qp_.DualSharder());
1319 return GlopStatusToTerminationReason(presolve_info_->preprocessor.status(),
1322 return std::nullopt;
1325void PreprocessSolver::ComputeAndApplyRescaling(
1326 const PrimalDualHybridGradientParams& params,
1327 VectorXd& starting_primal_solution, VectorXd& starting_dual_solution) {
1329 RescalingOptions{.l_inf_ruiz_iterations = params.l_inf_ruiz_iterations(),
1330 .l2_norm_rescaling = params.l2_norm_rescaling()},
1332 row_scaling_vec_ = std::move(scaling.row_scaling_vec);
1333 col_scaling_vec_ = std::move(scaling.col_scaling_vec);
1336 starting_primal_solution);
1338 starting_dual_solution);
1341void PreprocessSolver::LogQuadraticProgramStats(
1342 const QuadraticProgramStats& stats)
const {
1344 absl::StrFormat(
"There are %i variables, %i constraints, and %i "
1345 "constraint matrix nonzeros.",
1346 stats.num_variables(), stats.num_constraints(),
1347 stats.constraint_matrix_num_nonzeros()));
1348 if (Qp().constraint_matrix.nonZeros() > 0) {
1350 absl::StrFormat(
"Absolute values of nonzero constraint matrix "
1351 "elements: largest=%f, "
1352 "smallest=%f, avg=%f",
1353 stats.constraint_matrix_abs_max(),
1354 stats.constraint_matrix_abs_min(),
1355 stats.constraint_matrix_abs_avg()));
1358 absl::StrFormat(
"Constraint matrix, infinity norm: max(row & col)=%f, "
1359 "min_col=%f, min_row=%f",
1360 stats.constraint_matrix_abs_max(),
1361 stats.constraint_matrix_col_min_l_inf_norm(),
1362 stats.constraint_matrix_row_min_l_inf_norm()));
1366 "Constraint bounds statistics (max absolute value per row): "
1367 "largest=%f, smallest=%f, avg=%f, l2_norm=%f",
1368 stats.combined_bounds_max(), stats.combined_bounds_min(),
1369 stats.combined_bounds_avg(), stats.combined_bounds_l2_norm()));
1373 absl::StrFormat(
"There are %i nonzero diagonal coefficients in "
1374 "the objective matrix.",
1375 stats.objective_matrix_num_nonzeros()));
1379 "Absolute values of nonzero objective matrix elements: largest=%f, "
1380 "smallest=%f, avg=%f",
1381 stats.objective_matrix_abs_max(), stats.objective_matrix_abs_min(),
1382 stats.objective_matrix_abs_avg()));
1384 SOLVER_LOG(&logger_, absl::StrFormat(
"Absolute values of objective vector "
1385 "elements: largest=%f, smallest=%f, "
1386 "avg=%f, l2_norm=%f",
1387 stats.objective_vector_abs_max(),
1388 stats.objective_vector_abs_min(),
1389 stats.objective_vector_abs_avg(),
1390 stats.objective_vector_l2_norm()));
1394 "Gaps between variable upper and lower bounds: #finite=%i of %i, "
1395 "largest=%f, smallest=%f, avg=%f",
1396 stats.variable_bound_gaps_num_finite(), stats.num_variables(),
1397 stats.variable_bound_gaps_max(), stats.variable_bound_gaps_min(),
1398 stats.variable_bound_gaps_avg()));
1401double PreprocessSolver::InitialPrimalWeight(
1402 const PrimalDualHybridGradientParams& params,
1403 const double l2_norm_primal_linear_objective,
1404 const double l2_norm_constraint_bounds)
const {
1405 if (params.has_initial_primal_weight()) {
1406 return params.initial_primal_weight();
1408 if (l2_norm_primal_linear_objective > 0.0 &&
1409 l2_norm_constraint_bounds > 0.0) {
1415 return l2_norm_primal_linear_objective / l2_norm_constraint_bounds;
1421PrimalAndDualSolution PreprocessSolver::RecoverOriginalSolution(
1422 PrimalAndDualSolution working_solution)
const {
1423 glop::ProblemSolution glop_solution(glop::RowIndex{0}, glop::ColIndex{0});
1424 if (presolve_info_.has_value()) {
1428 glop_solution = internal::ComputeStatuses(Qp(), working_solution);
1431 working_solution.primal_solution);
1433 working_solution.dual_solution);
1434 if (presolve_info_.has_value()) {
1435 glop_solution.primal_values =
1436 glop::DenseRow(working_solution.primal_solution.begin(),
1437 working_solution.primal_solution.end());
1438 glop_solution.dual_values =
1439 glop::DenseColumn(working_solution.dual_solution.begin(),
1440 working_solution.dual_solution.end());
1444 if (presolve_info_->presolved_problem_was_maximization) {
1445 for (glop::RowIndex i{0};
i < glop_solution.dual_values.size(); ++
i) {
1446 glop_solution.dual_values[
i] *= -1;
1449 presolve_info_->preprocessor.RecoverSolution(&glop_solution);
1452 Eigen::Map<Eigen::VectorXd>(glop_solution.primal_values.data(),
1453 glop_solution.primal_values.size().value());
1455 Eigen::Map<Eigen::VectorXd>(glop_solution.dual_values.data(),
1456 glop_solution.dual_values.size().value());
1463 presolve_info_->sharded_original_qp.Qp().objective_scaling_factor;
1472 return working_solution;
1476void SetActiveSetInformation(
const ShardedQuadraticProgram& sharded_qp,
1477 const VectorXd& primal_solution,
1478 const VectorXd& dual_solution,
1479 const VectorXd& primal_start_point,
1480 const VectorXd& dual_start_point,
1481 PointMetadata& metadata) {
1483 CHECK_EQ(dual_solution.size(), sharded_qp.DualSize());
1484 CHECK_EQ(primal_start_point.size(), sharded_qp.PrimalSize());
1485 CHECK_EQ(dual_start_point.size(), sharded_qp.DualSize());
1487 const QuadraticProgram& qp = sharded_qp.Qp();
1488 metadata.set_active_primal_variable_count(
1489 static_cast<int64_t
>(sharded_qp.PrimalSharder().ParallelSumOverShards(
1490 [&](
const Sharder::Shard& shard) {
1491 const auto primal_shard = shard(primal_solution);
1492 const auto lower_bound_shard = shard(qp.variable_lower_bounds);
1493 const auto upper_bound_shard = shard(qp.variable_upper_bounds);
1494 return (primal_shard.array() > lower_bound_shard.array() &&
1495 primal_shard.array() < upper_bound_shard.array())
1502 metadata.set_active_primal_variable_change(
1503 static_cast<int64_t
>(sharded_qp.PrimalSharder().ParallelSumOverShards(
1504 [&](
const Sharder::Shard& shard) {
1505 const auto primal_shard = shard(primal_solution);
1506 const auto primal_start_shard = shard(primal_start_point);
1507 const auto lower_bound_shard = shard(qp.variable_lower_bounds);
1508 const auto upper_bound_shard = shard(qp.variable_upper_bounds);
1509 return ((primal_shard.array() > lower_bound_shard.array() &&
1510 primal_shard.array() < upper_bound_shard.array()) !=
1511 (primal_start_shard.array() > lower_bound_shard.array() &&
1512 primal_start_shard.array() < upper_bound_shard.array()))
1516 metadata.set_active_dual_variable_count(
1517 static_cast<int64_t
>(sharded_qp.DualSharder().ParallelSumOverShards(
1518 [&](
const Sharder::Shard& shard) {
1519 const auto dual_shard = shard(dual_solution);
1520 const auto lower_bound_shard = shard(qp.constraint_lower_bounds);
1521 const auto upper_bound_shard = shard(qp.constraint_upper_bounds);
1522 const double kInfinity = std::numeric_limits<double>::infinity();
1523 return (dual_shard.array() != 0.0 ||
1524 (lower_bound_shard.array() == -kInfinity &&
1525 upper_bound_shard.array() == kInfinity))
1529 metadata.set_active_dual_variable_change(
1530 static_cast<int64_t
>(sharded_qp.DualSharder().ParallelSumOverShards(
1531 [&](
const Sharder::Shard& shard) {
1532 const auto dual_shard = shard(dual_solution);
1533 const auto dual_start_shard = shard(dual_start_point);
1534 const auto lower_bound_shard = shard(qp.constraint_lower_bounds);
1535 const auto upper_bound_shard = shard(qp.constraint_upper_bounds);
1536 const double kInfinity = std::numeric_limits<double>::infinity();
1537 return ((dual_shard.array() != 0.0 ||
1538 (lower_bound_shard.array() == -kInfinity &&
1539 upper_bound_shard.array() == kInfinity)) !=
1540 (dual_start_shard.array() != 0.0 ||
1541 (lower_bound_shard.array() == -kInfinity &&
1542 upper_bound_shard.array() == kInfinity)))
1547void PreprocessSolver::AddPointMetadata(
1548 const PrimalDualHybridGradientParams& params,
1549 const VectorXd& primal_solution,
const VectorXd& dual_solution,
1550 PointType point_type,
const VectorXd& last_primal_start_point,
1551 const VectorXd& last_dual_start_point, IterationStats& stats)
const {
1552 PointMetadata metadata;
1553 metadata.set_point_type(point_type);
1554 std::vector<int> random_projection_seeds(
1555 params.random_projection_seeds().begin(),
1556 params.random_projection_seeds().end());
1558 random_projection_seeds, metadata);
1559 if (point_type != POINT_TYPE_ITERATE_DIFFERENCE) {
1560 SetActiveSetInformation(sharded_qp_, primal_solution, dual_solution,
1561 last_primal_start_point, last_dual_start_point,
1564 *stats.add_point_metadata() = metadata;
1567std::optional<TerminationReasonAndPointType>
1568PreprocessSolver::UpdateIterationStatsAndCheckTermination(
1569 const PrimalDualHybridGradientParams& params,
1570 bool force_numerical_termination,
const VectorXd& working_primal_current,
1571 const VectorXd& working_dual_current,
1572 const VectorXd* working_primal_average,
1573 const VectorXd* working_dual_average,
const VectorXd* working_primal_delta,
1574 const VectorXd* working_dual_delta,
const VectorXd& last_primal_start_point,
1575 const VectorXd& last_dual_start_point,
1576 const std::atomic<bool>* interrupt_solve,
1577 const IterationType iteration_type,
const IterationStats& full_stats,
1578 IterationStats& stats) {
1579 ComputeConvergenceAndInfeasibilityFromWorkingSolution(
1580 params, working_primal_current, working_dual_current,
1581 POINT_TYPE_CURRENT_ITERATE, stats.add_convergence_information(),
1582 stats.add_infeasibility_information());
1583 AddPointMetadata(params, working_primal_current, working_dual_current,
1584 POINT_TYPE_CURRENT_ITERATE, last_primal_start_point,
1585 last_dual_start_point, stats);
1586 if (working_primal_average !=
nullptr && working_dual_average !=
nullptr) {
1587 ComputeConvergenceAndInfeasibilityFromWorkingSolution(
1588 params, *working_primal_average, *working_dual_average,
1589 POINT_TYPE_AVERAGE_ITERATE, stats.add_convergence_information(),
1590 stats.add_infeasibility_information());
1591 AddPointMetadata(params, *working_primal_average, *working_dual_average,
1592 POINT_TYPE_AVERAGE_ITERATE, last_primal_start_point,
1593 last_dual_start_point, stats);
1596 if (!presolve_info_.has_value() && working_primal_delta !=
nullptr &&
1597 working_dual_delta !=
nullptr) {
1598 ComputeConvergenceAndInfeasibilityFromWorkingSolution(
1599 params, *working_primal_delta, *working_dual_delta,
1600 POINT_TYPE_ITERATE_DIFFERENCE,
nullptr,
1601 stats.add_infeasibility_information());
1602 AddPointMetadata(params, *working_primal_delta, *working_dual_delta,
1603 POINT_TYPE_ITERATE_DIFFERENCE, last_primal_start_point,
1604 last_dual_start_point, stats);
1606 constexpr int kLogEvery = 15;
1607 absl::Time logging_time = absl::Now();
1608 if (params.verbosity_level() >= 2 &&
1609 (params.log_interval_seconds() == 0.0 ||
1610 logging_time - time_of_last_log_ >=
1611 absl::Seconds(params.log_interval_seconds()))) {
1612 if (log_counter_ == 0) {
1613 LogIterationStatsHeader(params.verbosity_level(),
1614 params.use_feasibility_polishing(), logger_);
1616 LogIterationStats(params.verbosity_level(),
1617 params.use_feasibility_polishing(), iteration_type, stats,
1618 params.termination_criteria(), original_bound_norms_,
1619 POINT_TYPE_AVERAGE_ITERATE, logger_);
1620 if (params.verbosity_level() >= 4) {
1627 params.verbosity_level(), params.use_feasibility_polishing(),
1628 iteration_type, stats, params.termination_criteria(),
1629 original_bound_norms_, POINT_TYPE_CURRENT_ITERATE, logger_);
1632 time_of_last_log_ = logging_time;
1633 if (++log_counter_ >= kLogEvery) {
1637 if (iteration_stats_callback_ !=
nullptr) {
1638 iteration_stats_callback_(
1639 {.iteration_type = iteration_type,
1640 .termination_criteria = params.termination_criteria(),
1641 .iteration_stats = stats,
1642 .bound_norms = original_bound_norms_});
1646 params.termination_criteria(), stats, original_bound_norms_,
1647 force_numerical_termination);
1648 termination.has_value()) {
1652 full_stats, interrupt_solve);
1655void PreprocessSolver::ComputeConvergenceAndInfeasibilityFromWorkingSolution(
1656 const PrimalDualHybridGradientParams& params,
1657 const VectorXd& working_primal,
const VectorXd& working_dual,
1658 PointType candidate_type, ConvergenceInformation* convergence_information,
1659 InfeasibilityInformation* infeasibility_information)
const {
1660 const TerminationCriteria::DetailedOptimalityCriteria criteria =
1662 const double primal_epsilon_ratio =
1663 EpsilonRatio(criteria.eps_optimal_primal_residual_absolute(),
1664 criteria.eps_optimal_primal_residual_relative());
1665 const double dual_epsilon_ratio =
1666 EpsilonRatio(criteria.eps_optimal_dual_residual_absolute(),
1667 criteria.eps_optimal_dual_residual_relative());
1668 if (presolve_info_.has_value()) {
1670 CHECK_NE(candidate_type, POINT_TYPE_ITERATE_DIFFERENCE);
1672 PrimalAndDualSolution original = RecoverOriginalSolution(
1673 {.primal_solution = working_primal, .dual_solution = working_dual});
1674 if (convergence_information !=
nullptr) {
1676 params, presolve_info_->sharded_original_qp,
1677 presolve_info_->trivial_col_scaling_vec,
1678 presolve_info_->trivial_row_scaling_vec, original.primal_solution,
1679 original.dual_solution, primal_epsilon_ratio, dual_epsilon_ratio,
1682 if (infeasibility_information !=
nullptr) {
1683 VectorXd primal_copy =
1685 presolve_info_->sharded_original_qp.PrimalSharder());
1692 params, presolve_info_->sharded_original_qp,
1693 presolve_info_->trivial_col_scaling_vec,
1694 presolve_info_->trivial_row_scaling_vec, primal_copy,
1695 original.dual_solution, original.primal_solution, candidate_type);
1698 if (convergence_information !=
nullptr) {
1700 params, sharded_qp_, col_scaling_vec_, row_scaling_vec_,
1701 working_primal, working_dual, primal_epsilon_ratio,
1702 dual_epsilon_ratio, candidate_type);
1704 if (infeasibility_information !=
nullptr) {
1705 VectorXd primal_copy =
1706 CloneVector(working_primal, sharded_qp_.PrimalSharder());
1709 if (candidate_type == POINT_TYPE_ITERATE_DIFFERENCE) {
1711 VectorXd dual_copy =
1712 CloneVector(working_dual, sharded_qp_.DualSharder());
1715 params, sharded_qp_, col_scaling_vec_, row_scaling_vec_,
1716 primal_copy, dual_copy, working_primal, candidate_type);
1719 params, sharded_qp_, col_scaling_vec_, row_scaling_vec_,
1720 primal_copy, working_dual, working_primal, candidate_type);
1728SolverResult PreprocessSolver::ConstructOriginalSolverResult(
1729 const PrimalDualHybridGradientParams& params, SolverResult result,
1731 const bool use_zero_primal_objective =
1732 result.solve_log.termination_reason() ==
1734 if (presolve_info_.has_value()) {
1736 PrimalAndDualSolution original_solution = RecoverOriginalSolution(
1737 {.primal_solution = std::move(result.primal_solution),
1738 .dual_solution = std::move(result.dual_solution)});
1739 result.primal_solution = std::move(original_solution.primal_solution);
1740 if (result.solve_log.termination_reason() ==
1741 TERMINATION_REASON_DUAL_INFEASIBLE) {
1743 result.primal_solution,
1748 result.dual_solution = std::move(original_solution.dual_solution);
1752 params, presolve_info_->sharded_original_qp, result.primal_solution,
1753 result.dual_solution, use_zero_primal_objective);
1755 if (result.solve_log.termination_reason() ==
1756 TERMINATION_REASON_DUAL_INFEASIBLE) {
1760 if (result.solve_log.termination_reason() ==
1761 TERMINATION_REASON_PRIMAL_INFEASIBLE) {
1764 result.reduced_costs =
1765 ReducedCosts(params, sharded_qp_, result.primal_solution,
1766 result.dual_solution, use_zero_primal_objective);
1769 result.primal_solution);
1771 result.dual_solution);
1773 col_scaling_vec_, sharded_qp_.PrimalSharder(), result.reduced_costs);
1776 switch (result.solve_log.solution_type()) {
1778 iteration_type = IterationType::kFeasibilityPolishingTermination;
1781 iteration_type = IterationType::kPresolveTermination;
1784 iteration_type = IterationType::kNormalTermination;
1787 if (iteration_stats_callback_ !=
nullptr) {
1788 iteration_stats_callback_(
1789 {.iteration_type = iteration_type,
1790 .termination_criteria = params.termination_criteria(),
1791 .iteration_stats = result.solve_log.solution_stats(),
1792 .bound_norms = original_bound_norms_});
1795 if (params.verbosity_level() >= 1) {
1800 SOLVER_LOG(&logger,
"Final solution stats:");
1801 LogIterationStatsHeader(params.verbosity_level(),
1802 params.use_feasibility_polishing(), logger);
1803 LogIterationStats(params.verbosity_level(),
1804 params.use_feasibility_polishing(), iteration_type,
1805 result.solve_log.solution_stats(),
1806 params.termination_criteria(), original_bound_norms_,
1807 result.solve_log.solution_type(), logger);
1809 result.solve_log.solution_stats(), result.solve_log.solution_type());
1810 if (convergence_info.has_value()) {
1811 if (std::isfinite(convergence_info->corrected_dual_objective())) {
1812 SOLVER_LOG(&logger,
"Dual objective after infeasibility correction: ",
1813 convergence_info->corrected_dual_objective());
1820Solver::Solver(
const PrimalDualHybridGradientParams& params,
1821 VectorXd starting_primal_solution,
1822 VectorXd starting_dual_solution,
const double initial_step_size,
1823 const double initial_primal_weight,
1824 PreprocessSolver* preprocess_solver)
1826 current_primal_solution_(
std::move(starting_primal_solution)),
1827 current_dual_solution_(
std::move(starting_dual_solution)),
1828 primal_average_(&preprocess_solver->ShardedWorkingQp().PrimalSharder()),
1829 dual_average_(&preprocess_solver->ShardedWorkingQp().DualSharder()),
1830 step_size_(initial_step_size),
1831 primal_weight_(initial_primal_weight),
1832 preprocess_solver_(preprocess_solver) {}
1834Solver::NextSolutionAndDelta Solver::ComputeNextPrimalSolution(
1835 double primal_step_size)
const {
1836 const int64_t primal_size = ShardedWorkingQp().PrimalSize();
1837 NextSolutionAndDelta result = {
1838 .value = VectorXd(primal_size),
1839 .delta = VectorXd(primal_size),
1841 const QuadraticProgram& qp = WorkingQp();
1850 ShardedWorkingQp().PrimalSharder().ParallelForEachShard(
1851 [&](
const Sharder::Shard& shard) {
1855 const VectorXd diagonal_scaling =
1857 shard(qp.objective_matrix->diagonal()).array() +
1859 shard(result.value) =
1860 (shard(current_primal_solution_) -
1862 (shard(qp.objective_vector) - shard(current_dual_product_)))
1864 .cwiseQuotient(diagonal_scaling)
1865 .cwiseMin(shard(qp.variable_upper_bounds))
1866 .cwiseMax(shard(qp.variable_lower_bounds));
1869 shard(result.value) =
1870 (shard(current_primal_solution_) -
1872 (shard(qp.objective_vector) - shard(current_dual_product_)))
1873 .cwiseMin(shard(qp.variable_upper_bounds))
1874 .cwiseMax(shard(qp.variable_lower_bounds));
1876 shard(result.delta) =
1877 shard(result.value) - shard(current_primal_solution_);
1882Solver::NextSolutionAndDelta Solver::ComputeNextDualSolution(
1883 double dual_step_size,
double extrapolation_factor,
1884 const NextSolutionAndDelta& next_primal_solution,
1885 const VectorXd* absl_nullable next_primal_product)
const {
1886 const int64_t dual_size = ShardedWorkingQp().DualSize();
1887 NextSolutionAndDelta result = {
1888 .value = VectorXd(dual_size),
1889 .delta = VectorXd(dual_size),
1891 const QuadraticProgram& qp = WorkingQp();
1892 std::optional<VectorXd> extrapolated_primal;
1893 if (!next_primal_product) {
1894 extrapolated_primal.emplace(ShardedWorkingQp().PrimalSize());
1895 ShardedWorkingQp().PrimalSharder().ParallelForEachShard(
1896 [&](
const Sharder::Shard& shard) {
1897 shard(*extrapolated_primal) =
1898 (shard(next_primal_solution.value) +
1899 extrapolation_factor * shard(next_primal_solution.delta));
1902 ShardedWorkingQp().TransposedConstraintMatrixSharder().ParallelForEachShard(
1903 [&](
const Sharder::Shard& shard) {
1905 if (next_primal_product) {
1906 CHECK(current_primal_product_.has_value());
1907 temp = shard(current_dual_solution_) -
1909 (-extrapolation_factor * shard(*current_primal_product_) +
1910 (extrapolation_factor + 1) * shard(*next_primal_product));
1912 temp = shard(current_dual_solution_) -
1914 shard(ShardedWorkingQp().TransposedConstraintMatrix())
1916 extrapolated_primal.value();
1923 shard(result.value) =
1924 VectorXd::Zero(temp.size())
1926 dual_step_size * shard(qp.constraint_upper_bounds))
1928 dual_step_size * shard(qp.constraint_lower_bounds));
1929 shard(result.delta) =
1930 (shard(result.value) - shard(current_dual_solution_));
1935std::pair<double, double> Solver::ComputeMovementTerms(
1936 const VectorXd& delta_primal,
const VectorXd& delta_dual)
const {
1937 return {
SquaredNorm(delta_primal, ShardedWorkingQp().PrimalSharder()),
1938 SquaredNorm(delta_dual, ShardedWorkingQp().DualSharder())};
1941double Solver::ComputeMovement(
const VectorXd& delta_primal,
1942 const VectorXd& delta_dual)
const {
1943 const auto [primal_squared_norm, dual_squared_norm] =
1944 ComputeMovementTerms(delta_primal, delta_dual);
1945 return (0.5 * primal_weight_ * primal_squared_norm) +
1946 (0.5 / primal_weight_) * dual_squared_norm;
1949double Solver::ComputeNonlinearity(
const VectorXd& delta_primal,
1950 const VectorXd& next_dual_product)
const {
1953 return ShardedWorkingQp().PrimalSharder().ParallelSumOverShards(
1954 [&](
const Sharder::Shard& shard) {
1955 return -shard(delta_primal)
1956 .dot(shard(next_dual_product) -
1957 shard(current_dual_product_));
1961void Solver::SetCurrentPrimalAndDualProducts() {
1962 if (params_.linesearch_rule() ==
1963 PrimalDualHybridGradientParams::MALITSKY_POCK_LINESEARCH_RULE) {
1965 ShardedWorkingQp().TransposedConstraintMatrix(),
1966 current_primal_solution_,
1967 ShardedWorkingQp().TransposedConstraintMatrixSharder());
1969 current_primal_product_.reset();
1972 WorkingQp().constraint_matrix, current_dual_solution_,
1973 ShardedWorkingQp().ConstraintMatrixSharder());
1976IterationStats Solver::CreateSimpleIterationStats(
1977 RestartChoice restart_used)
const {
1978 IterationStats stats;
1979 double num_kkt_passes_per_rejected_step = 1.0;
1980 if (params_.linesearch_rule() ==
1981 PrimalDualHybridGradientParams::MALITSKY_POCK_LINESEARCH_RULE) {
1982 num_kkt_passes_per_rejected_step = 0.5;
1984 stats.set_iteration_number(iterations_completed_);
1985 stats.set_cumulative_rejected_steps(num_rejected_steps_);
1988 stats.set_cumulative_kkt_matrix_passes(iterations_completed_ +
1989 num_kkt_passes_per_rejected_step *
1990 num_rejected_steps_);
1991 stats.set_cumulative_time_sec(preprocessing_time_sec_ + timer_.Get());
1992 stats.set_restart_used(restart_used);
1993 stats.set_step_size(step_size_);
1994 stats.set_primal_weight(primal_weight_);
1998double Solver::DistanceTraveledFromLastStart(
1999 const VectorXd& primal_solution,
const VectorXd& dual_solution)
const {
2000 return std::sqrt((0.5 * primal_weight_) *
2002 last_primal_start_point_,
2003 ShardedWorkingQp().PrimalSharder()) +
2004 (0.5 / primal_weight_) *
2006 ShardedWorkingQp().DualSharder()));
2009LocalizedLagrangianBounds Solver::ComputeLocalizedBoundsAtCurrent()
const {
2010 const double distance_traveled_by_current = DistanceTraveledFromLastStart(
2011 current_primal_solution_, current_dual_solution_);
2013 ShardedWorkingQp(), current_primal_solution_, current_dual_solution_,
2014 PrimalDualNorm::kEuclideanNorm, primal_weight_,
2015 distance_traveled_by_current,
2016 current_primal_product_.has_value()
2017 ? ¤t_primal_product_.value()
2019 ¤t_dual_product_, params_.use_diagonal_qp_trust_region_solver(),
2020 params_.diagonal_qp_trust_region_solver_tolerance());
2023LocalizedLagrangianBounds Solver::ComputeLocalizedBoundsAtAverage()
const {
2026 VectorXd average_primal = PrimalAverage();
2027 VectorXd average_dual = DualAverage();
2029 const double distance_traveled_by_average =
2030 DistanceTraveledFromLastStart(average_primal, average_dual);
2033 ShardedWorkingQp(), average_primal, average_dual,
2034 PrimalDualNorm::kEuclideanNorm, primal_weight_,
2035 distance_traveled_by_average,
2037 params_.use_diagonal_qp_trust_region_solver(),
2038 params_.diagonal_qp_trust_region_solver_tolerance());
2041bool AverageHasBetterPotential(
2042 const LocalizedLagrangianBounds& local_bounds_at_average,
2043 const LocalizedLagrangianBounds& local_bounds_at_current) {
2044 return BoundGap(local_bounds_at_average) /
2045 MathUtil::Square(local_bounds_at_average.radius) <
2046 BoundGap(local_bounds_at_current) /
2047 MathUtil::Square(local_bounds_at_current.radius);
2050double NormalizedGap(
2051 const LocalizedLagrangianBounds& local_bounds_at_candidate) {
2052 const double distance_traveled_by_candidate =
2053 local_bounds_at_candidate.radius;
2054 return BoundGap(local_bounds_at_candidate) / distance_traveled_by_candidate;
2058bool Solver::ShouldDoAdaptiveRestartHeuristic(
2059 double candidate_normalized_gap)
const {
2060 const double gap_reduction_ratio =
2061 candidate_normalized_gap / normalized_gap_at_last_restart_;
2062 if (gap_reduction_ratio < params_.sufficient_reduction_for_restart()) {
2065 if (gap_reduction_ratio < params_.necessary_reduction_for_restart() &&
2066 candidate_normalized_gap > normalized_gap_at_last_trial_) {
2074RestartChoice Solver::DetermineDistanceBasedRestartChoice()
const {
2076 if (primal_average_.NumTerms() == 0) {
2078 }
else if (distance_based_restart_info_.length_of_last_restart_period == 0) {
2081 const int restart_period_length = primal_average_.NumTerms();
2082 const double distance_moved_this_restart_period_by_average =
2083 DistanceTraveledFromLastStart(primal_average_.ComputeAverage(),
2084 dual_average_.ComputeAverage());
2085 const double distance_moved_last_restart_period =
2086 distance_based_restart_info_.distance_moved_last_restart_period;
2092 if ((distance_moved_this_restart_period_by_average / restart_period_length) <
2093 params_.sufficient_reduction_for_restart() *
2094 (distance_moved_last_restart_period /
2095 distance_based_restart_info_.length_of_last_restart_period)) {
2098 if (AverageHasBetterPotential(ComputeLocalizedBoundsAtAverage(),
2099 ComputeLocalizedBoundsAtCurrent())) {
2109RestartChoice Solver::ChooseRestartToApply(
const bool is_major_iteration) {
2110 if (!primal_average_.HasNonzeroWeight() &&
2111 !dual_average_.HasNonzeroWeight()) {
2120 const int restart_length = primal_average_.NumTerms();
2121 if (restart_length >= iterations_completed_ / 2 &&
2122 params_.restart_strategy() ==
2123 PrimalDualHybridGradientParams::ADAPTIVE_HEURISTIC) {
2124 if (AverageHasBetterPotential(ComputeLocalizedBoundsAtAverage(),
2125 ComputeLocalizedBoundsAtCurrent())) {
2131 if (is_major_iteration) {
2132 switch (params_.restart_strategy()) {
2133 case PrimalDualHybridGradientParams::NO_RESTARTS:
2135 case PrimalDualHybridGradientParams::EVERY_MAJOR_ITERATION:
2137 case PrimalDualHybridGradientParams::ADAPTIVE_HEURISTIC: {
2138 const LocalizedLagrangianBounds local_bounds_at_average =
2139 ComputeLocalizedBoundsAtAverage();
2140 const LocalizedLagrangianBounds local_bounds_at_current =
2141 ComputeLocalizedBoundsAtCurrent();
2142 double normalized_gap;
2144 if (AverageHasBetterPotential(local_bounds_at_average,
2145 local_bounds_at_current)) {
2146 normalized_gap = NormalizedGap(local_bounds_at_average);
2149 normalized_gap = NormalizedGap(local_bounds_at_current);
2152 if (ShouldDoAdaptiveRestartHeuristic(normalized_gap)) {
2155 normalized_gap_at_last_trial_ = normalized_gap;
2159 case PrimalDualHybridGradientParams::ADAPTIVE_DISTANCE_BASED: {
2160 return DetermineDistanceBasedRestartChoice();
2163 LOG(FATAL) <<
"Unrecognized restart_strategy "
2164 << params_.restart_strategy();
2172VectorXd Solver::PrimalAverage()
const {
2173 if (primal_average_.HasNonzeroWeight()) {
2174 return primal_average_.ComputeAverage();
2176 return current_primal_solution_;
2180VectorXd Solver::DualAverage()
const {
2181 if (dual_average_.HasNonzeroWeight()) {
2182 return dual_average_.ComputeAverage();
2184 return current_dual_solution_;
2188double Solver::ComputeNewPrimalWeight()
const {
2189 const double primal_distance =
2190 Distance(current_primal_solution_, last_primal_start_point_,
2191 ShardedWorkingQp().PrimalSharder());
2192 const double dual_distance =
2193 Distance(current_dual_solution_, last_dual_start_point_,
2194 ShardedWorkingQp().DualSharder());
2199 constexpr double kNonzeroTol = 1.0e-10;
2200 if (primal_distance <= kNonzeroTol || primal_distance >= 1.0 / kNonzeroTol ||
2201 dual_distance <= kNonzeroTol || dual_distance >= 1.0 / kNonzeroTol) {
2202 return primal_weight_;
2204 const double smoothing_param = params_.primal_weight_update_smoothing();
2205 const double unsmoothed_new_primal_weight = dual_distance / primal_distance;
2206 const double new_primal_weight =
2207 std::exp(smoothing_param * std::log(unsmoothed_new_primal_weight) +
2208 (1.0 - smoothing_param) * std::log(primal_weight_));
2209 if (params_.verbosity_level() >= 4) {
2210 SOLVER_LOG(&preprocess_solver_->Logger(),
"New computed primal weight is ",
2211 new_primal_weight,
" at iteration ", iterations_completed_);
2213 return new_primal_weight;
2216SolverResult Solver::PickSolutionAndConstructSolverResult(
2217 VectorXd primal_solution, VectorXd dual_solution,
2218 const IterationStats& stats, TerminationReason termination_reason,
2219 PointType output_type, SolveLog solve_log)
const {
2220 switch (output_type) {
2222 AssignVector(current_primal_solution_, ShardedWorkingQp().PrimalSharder(),
2224 AssignVector(current_dual_solution_, ShardedWorkingQp().DualSharder(),
2228 AssignVector(current_primal_delta_, ShardedWorkingQp().PrimalSharder(),
2230 AssignVector(current_dual_delta_, ShardedWorkingQp().DualSharder(),
2241 return ConstructSolverResult(
2242 std::move(primal_solution), std::move(dual_solution), stats,
2243 termination_reason, output_type, std::move(solve_log));
2246void Solver::ApplyRestartChoice(
const RestartChoice restart_to_apply) {
2247 switch (restart_to_apply) {
2252 if (params_.verbosity_level() >= 4) {
2254 "Restarted to current on iteration ", iterations_completed_,
2255 " after ", primal_average_.NumTerms(),
" iterations");
2259 if (params_.verbosity_level() >= 4) {
2261 "Restarted to average on iteration ", iterations_completed_,
2262 " after ", primal_average_.NumTerms(),
" iterations");
2264 current_primal_solution_ = primal_average_.ComputeAverage();
2265 current_dual_solution_ = dual_average_.ComputeAverage();
2266 SetCurrentPrimalAndDualProducts();
2269 primal_weight_ = ComputeNewPrimalWeight();
2270 ratio_last_two_step_sizes_ = 1;
2271 if (params_.restart_strategy() ==
2272 PrimalDualHybridGradientParams::ADAPTIVE_HEURISTIC) {
2275 const LocalizedLagrangianBounds local_bounds_at_last_restart =
2276 ComputeLocalizedBoundsAtCurrent();
2277 const double distance_traveled_since_last_restart =
2278 local_bounds_at_last_restart.radius;
2279 normalized_gap_at_last_restart_ =
BoundGap(local_bounds_at_last_restart) /
2280 distance_traveled_since_last_restart;
2281 normalized_gap_at_last_trial_ = std::numeric_limits<double>::infinity();
2282 }
else if (params_.restart_strategy() ==
2283 PrimalDualHybridGradientParams::ADAPTIVE_DISTANCE_BASED) {
2285 distance_based_restart_info_ = {
2286 .distance_moved_last_restart_period = DistanceTraveledFromLastStart(
2287 current_primal_solution_, current_dual_solution_),
2288 .length_of_last_restart_period = primal_average_.NumTerms()};
2290 primal_average_.Clear();
2291 dual_average_.Clear();
2292 AssignVector(current_primal_solution_, ShardedWorkingQp().PrimalSharder(),
2293 last_primal_start_point_);
2294 AssignVector(current_dual_solution_, ShardedWorkingQp().DualSharder(),
2295 last_dual_start_point_);
2302IterationStats AddWorkStats(IterationStats stats,
2303 const IterationStats& additional_work_stats) {
2304 stats.set_iteration_number(stats.iteration_number() +
2305 additional_work_stats.iteration_number());
2306 stats.set_cumulative_kkt_matrix_passes(
2307 stats.cumulative_kkt_matrix_passes() +
2308 additional_work_stats.cumulative_kkt_matrix_passes());
2309 stats.set_cumulative_rejected_steps(
2310 stats.cumulative_rejected_steps() +
2311 additional_work_stats.cumulative_rejected_steps());
2312 stats.set_cumulative_time_sec(stats.cumulative_time_sec() +
2313 additional_work_stats.cumulative_time_sec());
2320IterationStats WorkFromFeasibilityPolishing(
const SolveLog& solve_log) {
2321 IterationStats result;
2322 for (
const FeasibilityPolishingDetails& feasibility_polishing_detail :
2323 solve_log.feasibility_polishing_details()) {
2324 result = AddWorkStats(std::move(result),
2325 feasibility_polishing_detail.solution_stats());
2330bool TerminationReasonIsInterrupted(
const TerminationReason reason) {
2334bool TerminationReasonIsWorkLimitNotInterrupted(
2335 const TerminationReason reason) {
2343bool TerminationReasonIsWorkLimit(
const TerminationReason reason) {
2344 return TerminationReasonIsWorkLimitNotInterrupted(reason) ||
2345 TerminationReasonIsInterrupted(reason);
2348bool DoFeasibilityPolishingAfterLimitsReached(
2349 const PrimalDualHybridGradientParams& params,
2350 const TerminationReason reason) {
2351 if (TerminationReasonIsWorkLimitNotInterrupted(reason)) {
2352 return params.apply_feasibility_polishing_after_limits_reached();
2354 if (TerminationReasonIsInterrupted(reason)) {
2355 return params.apply_feasibility_polishing_if_solver_is_interrupted();
2360std::optional<SolverResult> Solver::MajorIterationAndTerminationCheck(
2361 const IterationType iteration_type,
const bool force_numerical_termination,
2362 const std::atomic<bool>* interrupt_solve,
2363 const IterationStats& work_from_feasibility_polishing,
2364 SolveLog& solve_log) {
2365 const int major_iteration_cycle =
2366 iterations_completed_ % params_.major_iteration_frequency();
2367 const bool is_major_iteration =
2368 major_iteration_cycle == 0 && iterations_completed_ > 0;
2373 : ChooseRestartToApply(is_major_iteration);
2374 IterationStats stats = CreateSimpleIterationStats(restart);
2375 IterationStats full_work_stats =
2376 AddWorkStats(stats, work_from_feasibility_polishing);
2377 std::optional<TerminationReasonAndPointType> simple_termination_reason =
2379 full_work_stats, interrupt_solve);
2380 const bool check_termination =
2381 major_iteration_cycle % params_.termination_check_frequency() == 0 ||
2382 simple_termination_reason.has_value() || force_numerical_termination;
2384 DCHECK(!is_major_iteration || check_termination);
2385 if (check_termination) {
2389 VectorXd primal_average = PrimalAverage();
2390 VectorXd dual_average = DualAverage();
2392 const std::optional<TerminationReasonAndPointType>
2393 maybe_termination_reason =
2394 preprocess_solver_->UpdateIterationStatsAndCheckTermination(
2395 params_, force_numerical_termination, current_primal_solution_,
2396 current_dual_solution_,
2397 primal_average_.HasNonzeroWeight() ? &primal_average :
nullptr,
2398 dual_average_.HasNonzeroWeight() ? &dual_average :
nullptr,
2399 current_primal_delta_.size() > 0 ? ¤t_primal_delta_
2401 current_dual_delta_.size() > 0 ? ¤t_dual_delta_ :
nullptr,
2402 last_primal_start_point_, last_dual_start_point_,
2403 interrupt_solve, iteration_type, full_work_stats, stats);
2404 if (params_.record_iteration_stats()) {
2405 *solve_log.add_iteration_stats() = stats;
2408 if (maybe_termination_reason.has_value()) {
2409 if (iteration_type == IterationType::kNormal &&
2410 DoFeasibilityPolishingAfterLimitsReached(
2411 params_, maybe_termination_reason->reason)) {
2412 const std::optional<SolverResult> feasibility_result =
2413 TryFeasibilityPolishing(
2414 iterations_completed_ / kFeasibilityIterationFraction,
2415 interrupt_solve, solve_log);
2416 if (feasibility_result.has_value()) {
2417 LOG(INFO) <<
"Returning result from feasibility polishing after "
2419 return *feasibility_result;
2422 IterationStats terminating_full_stats =
2423 AddWorkStats(stats, work_from_feasibility_polishing);
2424 return PickSolutionAndConstructSolverResult(
2425 std::move(primal_average), std::move(dual_average),
2426 terminating_full_stats, maybe_termination_reason->reason,
2427 maybe_termination_reason->type, std::move(solve_log));
2429 }
else if (params_.record_iteration_stats()) {
2431 *solve_log.add_iteration_stats() = stats;
2433 ApplyRestartChoice(restart);
2434 return std::nullopt;
2437void Solver::ResetAverageToCurrent() {
2438 primal_average_.Clear();
2439 dual_average_.Clear();
2440 primal_average_.Add(current_primal_solution_, 1.0);
2441 dual_average_.Add(current_dual_solution_, 1.0);
2444void Solver::LogNumericalTermination(
const Eigen::VectorXd& primal_delta,
2445 const Eigen::VectorXd& dual_delta)
const {
2446 if (params_.verbosity_level() >= 2) {
2447 auto [primal_squared_norm, dual_squared_norm] =
2448 ComputeMovementTerms(primal_delta, dual_delta);
2450 "Forced numerical termination at iteration ",
2451 iterations_completed_,
" with primal delta squared norm ",
2452 primal_squared_norm,
" dual delta squared norm ",
2453 dual_squared_norm,
" primal weight ", primal_weight_);
2457void Solver::LogInnerIterationLimitHit()
const {
2459 "WARNING: Inner iteration limit reached at iteration ",
2460 iterations_completed_);
2463InnerStepOutcome Solver::TakeMalitskyPockStep() {
2464 InnerStepOutcome outcome = InnerStepOutcome::kSuccessful;
2465 const double primal_step_size = step_size_ / primal_weight_;
2466 NextSolutionAndDelta next_primal_solution =
2467 ComputeNextPrimalSolution(primal_step_size);
2472 double dilating_coeff =
2473 1 + (params_.malitsky_pock_parameters().step_size_interpolation() *
2474 (sqrt(1 + ratio_last_two_step_sizes_) - 1));
2475 double new_primal_step_size = primal_step_size * dilating_coeff;
2476 double step_size_downscaling =
2477 params_.malitsky_pock_parameters().step_size_downscaling_factor();
2478 double contraction_factor =
2479 params_.malitsky_pock_parameters().linesearch_contraction_factor();
2480 const double dual_weight = primal_weight_ * primal_weight_;
2481 int inner_iterations = 0;
2482 VectorXd next_primal_product(current_dual_solution_.size());
2483 ShardedWorkingQp().TransposedConstraintMatrixSharder().ParallelForEachShard(
2484 [&](
const Sharder::Shard& shard) {
2485 shard(next_primal_product) =
2486 shard(ShardedWorkingQp().TransposedConstraintMatrix()).transpose() *
2487 next_primal_solution.value;
2490 for (
bool accepted_step =
false; !accepted_step; ++inner_iterations) {
2491 if (inner_iterations >= 60) {
2492 LogInnerIterationLimitHit();
2493 ResetAverageToCurrent();
2494 outcome = InnerStepOutcome::kForceNumericalTermination;
2497 const double new_last_two_step_sizes_ratio =
2498 new_primal_step_size / primal_step_size;
2499 NextSolutionAndDelta next_dual_solution = ComputeNextDualSolution(
2500 dual_weight * new_primal_step_size, new_last_two_step_sizes_ratio,
2501 next_primal_solution, &next_primal_product);
2504 WorkingQp().constraint_matrix, next_dual_solution.value,
2505 ShardedWorkingQp().ConstraintMatrixSharder());
2506 double delta_dual_norm =
2507 Norm(next_dual_solution.delta, ShardedWorkingQp().DualSharder());
2508 double delta_dual_prod_norm =
2509 Distance(current_dual_product_, next_dual_product,
2510 ShardedWorkingQp().PrimalSharder());
2511 if (primal_weight_ * new_primal_step_size * delta_dual_prod_norm <=
2512 contraction_factor * delta_dual_norm) {
2514 step_size_ = new_primal_step_size * primal_weight_;
2515 ratio_last_two_step_sizes_ = new_last_two_step_sizes_ratio;
2520 if (!primal_average_.HasNonzeroWeight()) {
2521 primal_average_.Add(
2522 current_primal_solution_,
2523 new_primal_step_size * new_last_two_step_sizes_ratio);
2526 current_primal_solution_ = std::move(next_primal_solution.value);
2527 current_dual_solution_ = std::move(next_dual_solution.value);
2528 current_dual_product_ = std::move(next_dual_product);
2529 current_primal_product_ = std::move(next_primal_product);
2530 primal_average_.Add(current_primal_solution_,
2531 new_primal_step_size);
2532 dual_average_.Add(current_dual_solution_,
2533 new_primal_step_size);
2534 const double movement =
2535 ComputeMovement(next_primal_solution.delta, next_dual_solution.delta);
2536 if (movement == 0.0) {
2537 LogNumericalTermination(next_primal_solution.delta,
2538 next_dual_solution.delta);
2539 ResetAverageToCurrent();
2540 outcome = InnerStepOutcome::kForceNumericalTermination;
2541 }
else if (movement > kDivergentMovement) {
2542 LogNumericalTermination(next_primal_solution.delta,
2543 next_dual_solution.delta);
2544 outcome = InnerStepOutcome::kForceNumericalTermination;
2546 current_primal_delta_ = std::move(next_primal_solution.delta);
2547 current_dual_delta_ = std::move(next_dual_solution.delta);
2550 new_primal_step_size = step_size_downscaling * new_primal_step_size;
2554 num_rejected_steps_ += inner_iterations;
2558InnerStepOutcome Solver::TakeAdaptiveStep() {
2559 InnerStepOutcome outcome = InnerStepOutcome::kSuccessful;
2560 int inner_iterations = 0;
2561 for (
bool accepted_step =
false; !accepted_step; ++inner_iterations) {
2562 if (inner_iterations >= 60) {
2563 LogInnerIterationLimitHit();
2564 ResetAverageToCurrent();
2565 outcome = InnerStepOutcome::kForceNumericalTermination;
2568 const double primal_step_size = step_size_ / primal_weight_;
2569 const double dual_step_size = step_size_ * primal_weight_;
2570 NextSolutionAndDelta next_primal_solution =
2571 ComputeNextPrimalSolution(primal_step_size);
2572 NextSolutionAndDelta next_dual_solution = ComputeNextDualSolution(
2573 dual_step_size, 1.0, next_primal_solution);
2574 const double movement =
2575 ComputeMovement(next_primal_solution.delta, next_dual_solution.delta);
2576 if (movement == 0.0) {
2577 LogNumericalTermination(next_primal_solution.delta,
2578 next_dual_solution.delta);
2579 ResetAverageToCurrent();
2580 outcome = InnerStepOutcome::kForceNumericalTermination;
2582 }
else if (movement > kDivergentMovement) {
2583 LogNumericalTermination(next_primal_solution.delta,
2584 next_dual_solution.delta);
2585 outcome = InnerStepOutcome::kForceNumericalTermination;
2589 WorkingQp().constraint_matrix, next_dual_solution.value,
2590 ShardedWorkingQp().ConstraintMatrixSharder());
2591 const double nonlinearity =
2592 ComputeNonlinearity(next_primal_solution.delta, next_dual_product);
2595 const double step_size_limit =
2596 nonlinearity > 0 ? movement / nonlinearity
2597 : std::numeric_limits<double>::infinity();
2599 if (step_size_ <= step_size_limit) {
2600 current_primal_solution_ = std::move(next_primal_solution.value);
2601 current_dual_solution_ = std::move(next_dual_solution.value);
2602 current_dual_product_ = std::move(next_dual_product);
2603 current_primal_product_.reset();
2604 current_primal_delta_ = std::move(next_primal_solution.delta);
2605 current_dual_delta_ = std::move(next_dual_solution.delta);
2606 primal_average_.Add(current_primal_solution_, step_size_);
2607 dual_average_.Add(current_dual_solution_, step_size_);
2608 accepted_step =
true;
2610 const double total_steps_attempted =
2611 num_rejected_steps_ + inner_iterations + iterations_completed_ + 1;
2616 const double first_term =
2617 std::isinf(step_size_limit)
2619 : (1 - std::pow(total_steps_attempted + 1.0,
2620 -params_.adaptive_linesearch_parameters()
2621 .step_size_reduction_exponent())) *
2623 const double second_term =
2624 (1 + std::pow(total_steps_attempted + 1.0,
2625 -params_.adaptive_linesearch_parameters()
2626 .step_size_growth_exponent())) *
2637 step_size_ = std::min(first_term, second_term);
2640 num_rejected_steps_ += inner_iterations - 1;
2644InnerStepOutcome Solver::TakeConstantSizeStep() {
2645 const double primal_step_size = step_size_ / primal_weight_;
2646 const double dual_step_size = step_size_ * primal_weight_;
2647 NextSolutionAndDelta next_primal_solution =
2648 ComputeNextPrimalSolution(primal_step_size);
2649 NextSolutionAndDelta next_dual_solution = ComputeNextDualSolution(
2650 dual_step_size, 1.0, next_primal_solution);
2651 const double movement =
2652 ComputeMovement(next_primal_solution.delta, next_dual_solution.delta);
2653 if (movement == 0.0) {
2654 LogNumericalTermination(next_primal_solution.delta,
2655 next_dual_solution.delta);
2656 ResetAverageToCurrent();
2657 return InnerStepOutcome::kForceNumericalTermination;
2658 }
else if (movement > kDivergentMovement) {
2659 LogNumericalTermination(next_primal_solution.delta,
2660 next_dual_solution.delta);
2661 return InnerStepOutcome::kForceNumericalTermination;
2664 WorkingQp().constraint_matrix, next_dual_solution.value,
2665 ShardedWorkingQp().ConstraintMatrixSharder());
2666 current_primal_solution_ = std::move(next_primal_solution.value);
2667 current_dual_solution_ = std::move(next_dual_solution.value);
2668 current_dual_product_ = std::move(next_dual_product);
2669 current_primal_product_.reset();
2670 current_primal_delta_ = std::move(next_primal_solution.delta);
2671 current_dual_delta_ = std::move(next_dual_solution.delta);
2672 primal_average_.Add(current_primal_solution_, step_size_);
2673 dual_average_.Add(current_dual_solution_, step_size_);
2674 return InnerStepOutcome::kSuccessful;
2677IterationStats Solver::TotalWorkSoFar(
const SolveLog& solve_log)
const {
2678 IterationStats stats = CreateSimpleIterationStats(RESTART_CHOICE_NO_RESTART);
2679 IterationStats full_stats =
2680 AddWorkStats(stats, WorkFromFeasibilityPolishing(solve_log));
2684FeasibilityPolishingDetails BuildFeasibilityPolishingDetails(
2685 PolishingPhaseType phase_type,
int iteration_count,
2686 const PrimalDualHybridGradientParams& params,
const SolveLog& solve_log) {
2687 FeasibilityPolishingDetails details;
2688 details.set_polishing_phase_type(phase_type);
2689 details.set_main_iteration_count(iteration_count);
2690 *details.mutable_params() = params;
2691 details.set_termination_reason(solve_log.termination_reason());
2692 details.set_iteration_count(solve_log.iteration_count());
2693 details.set_solve_time_sec(solve_log.solve_time_sec());
2694 *details.mutable_solution_stats() = solve_log.solution_stats();
2695 details.set_solution_type(solve_log.solution_type());
2696 absl::c_copy(solve_log.iteration_stats(),
2697 google::protobuf::RepeatedPtrFieldBackInserter(
2698 details.mutable_iteration_stats()));
2702std::optional<SolverResult> Solver::TryFeasibilityPolishing(
2703 const int iteration_limit,
const std::atomic<bool>* interrupt_solve,
2704 SolveLog& solve_log) {
2705 TerminationCriteria::DetailedOptimalityCriteria optimality_criteria =
2708 VectorXd average_primal = PrimalAverage();
2709 VectorXd average_dual = DualAverage();
2711 ConvergenceInformation first_convergence_info;
2712 preprocess_solver_->ComputeConvergenceAndInfeasibilityFromWorkingSolution(
2713 params_, average_primal, average_dual, POINT_TYPE_AVERAGE_ITERATE,
2714 &first_convergence_info,
nullptr);
2720 std::optional<TerminationReasonAndPointType> simple_termination_reason =
2722 TotalWorkSoFar(solve_log),
2724 if (!(simple_termination_reason.has_value() &&
2725 DoFeasibilityPolishingAfterLimitsReached(
2726 params_, simple_termination_reason->reason))) {
2727 if (params_.verbosity_level() >= 2) {
2729 "Skipping feasibility polishing because the objective gap "
2732 return std::nullopt;
2736 if (params_.verbosity_level() >= 2) {
2738 "Starting primal feasibility polishing");
2740 SolverResult primal_result = TryPrimalPolishing(
2741 std::move(average_primal), iteration_limit, interrupt_solve, solve_log);
2743 if (params_.verbosity_level() >= 2) {
2745 &preprocess_solver_->Logger(),
2746 "Primal feasibility polishing termination reason: ",
2749 if (TerminationReasonIsWorkLimit(
2750 primal_result.solve_log.termination_reason())) {
2753 std::optional<TerminationReasonAndPointType> simple_termination_reason =
2755 TotalWorkSoFar(solve_log),
2757 if (!(simple_termination_reason.has_value() &&
2758 DoFeasibilityPolishingAfterLimitsReached(
2759 params_, simple_termination_reason->reason))) {
2760 return std::nullopt;
2762 }
else if (primal_result.solve_log.termination_reason() !=
2763 TERMINATION_REASON_OPTIMAL) {
2770 "WARNING: Primal feasibility polishing terminated with error ",
2771 primal_result.solve_log.termination_reason());
2772 return std::nullopt;
2775 if (params_.verbosity_level() >= 2) {
2777 "Starting dual feasibility polishing");
2779 SolverResult dual_result = TryDualPolishing(
2780 std::move(average_dual), iteration_limit, interrupt_solve, solve_log);
2782 if (params_.verbosity_level() >= 2) {
2784 &preprocess_solver_->Logger(),
2785 "Dual feasibility polishing termination reason: ",
2789 IterationStats full_stats = TotalWorkSoFar(solve_log);
2790 std::optional<TerminationReasonAndPointType> simple_termination_reason =
2793 if (TerminationReasonIsWorkLimit(
2794 dual_result.solve_log.termination_reason())) {
2797 if (simple_termination_reason.has_value() &&
2798 DoFeasibilityPolishingAfterLimitsReached(
2799 params_, simple_termination_reason->reason)) {
2800 preprocess_solver_->ComputeConvergenceAndInfeasibilityFromWorkingSolution(
2801 params_, primal_result.primal_solution, dual_result.dual_solution,
2802 POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION,
2803 full_stats.add_convergence_information(),
nullptr);
2804 return ConstructSolverResult(
2805 std::move(primal_result.primal_solution),
2806 std::move(dual_result.dual_solution), full_stats,
2807 simple_termination_reason->reason,
2808 POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION, solve_log);
2810 return std::nullopt;
2812 }
else if (dual_result.solve_log.termination_reason() !=
2813 TERMINATION_REASON_OPTIMAL) {
2818 "WARNING: Dual feasibility polishing terminated with error ",
2819 dual_result.solve_log.termination_reason());
2820 return std::nullopt;
2823 preprocess_solver_->ComputeConvergenceAndInfeasibilityFromWorkingSolution(
2824 params_, primal_result.primal_solution, dual_result.dual_solution,
2825 POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION,
2826 full_stats.add_convergence_information(),
nullptr);
2827 if (params_.verbosity_level() >= 2) {
2829 "solution stats for polished solution:");
2830 LogIterationStatsHeader(params_.verbosity_level(),
2832 preprocess_solver_->Logger());
2833 LogIterationStats(params_.verbosity_level(),
2835 IterationType::kFeasibilityPolishingTermination,
2836 full_stats, params_.termination_criteria(),
2837 preprocess_solver_->OriginalBoundNorms(),
2838 POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION,
2839 preprocess_solver_->Logger());
2841 std::optional<TerminationReasonAndPointType> earned_termination =
2844 preprocess_solver_->OriginalBoundNorms(),
2846 if (earned_termination.has_value() ||
2847 (simple_termination_reason.has_value() &&
2848 DoFeasibilityPolishingAfterLimitsReached(
2849 params_, simple_termination_reason->reason))) {
2850 return ConstructSolverResult(
2851 std::move(primal_result.primal_solution),
2852 std::move(dual_result.dual_solution), full_stats,
2853 earned_termination.has_value() ? earned_termination->reason
2854 : simple_termination_reason->reason,
2855 POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION, solve_log);
2864 return std::nullopt;
2867TerminationCriteria ReduceWorkLimitsByPreviousWork(
2868 TerminationCriteria criteria,
const int iteration_limit,
2869 const IterationStats& previous_work,
2870 bool apply_feasibility_polishing_after_limits_reached) {
2871 if (apply_feasibility_polishing_after_limits_reached) {
2872 criteria.set_iteration_limit(iteration_limit);
2873 criteria.set_kkt_matrix_pass_limit(std::numeric_limits<double>::infinity());
2874 criteria.set_time_sec_limit(std::numeric_limits<double>::infinity());
2876 criteria.set_iteration_limit(std::max(
2877 0, std::min(iteration_limit, criteria.iteration_limit() -
2878 previous_work.iteration_number())));
2879 criteria.set_kkt_matrix_pass_limit(
2880 std::max(0.0, criteria.kkt_matrix_pass_limit() -
2881 previous_work.cumulative_kkt_matrix_passes()));
2882 criteria.set_time_sec_limit(std::max(
2883 0.0, criteria.time_sec_limit() - previous_work.cumulative_time_sec()));
2888SolverResult Solver::TryPrimalPolishing(
2889 VectorXd starting_primal_solution,
const int iteration_limit,
2890 const std::atomic<bool>* interrupt_solve, SolveLog& solve_log) {
2891 PrimalDualHybridGradientParams primal_feasibility_params = params_;
2892 *primal_feasibility_params.mutable_termination_criteria() =
2893 ReduceWorkLimitsByPreviousWork(
2894 params_.termination_criteria(), iteration_limit,
2895 TotalWorkSoFar(solve_log),
2896 params_.apply_feasibility_polishing_after_limits_reached());
2897 if (params_.apply_feasibility_polishing_if_solver_is_interrupted()) {
2898 interrupt_solve =
nullptr;
2903 SetZero(ShardedWorkingQp().PrimalSharder(), objective);
2904 preprocess_solver_->SwapObjectiveVector(objective);
2906 TerminationCriteria::DetailedOptimalityCriteria criteria =
2908 const double kInfinity = std::numeric_limits<double>::infinity();
2909 criteria.set_eps_optimal_dual_residual_absolute(
kInfinity);
2910 criteria.set_eps_optimal_dual_residual_relative(
kInfinity);
2911 criteria.set_eps_optimal_objective_gap_absolute(
kInfinity);
2912 criteria.set_eps_optimal_objective_gap_relative(
kInfinity);
2913 *primal_feasibility_params.mutable_termination_criteria()
2914 ->mutable_detailed_optimality_criteria() = criteria;
2917 VectorXd primal_feasibility_starting_dual;
2918 SetZero(ShardedWorkingQp().DualSharder(), primal_feasibility_starting_dual);
2919 Solver primal_solver(primal_feasibility_params,
2920 std::move(starting_primal_solution),
2921 std::move(primal_feasibility_starting_dual), step_size_,
2922 primal_weight_, preprocess_solver_);
2923 SolveLog primal_solve_log;
2927 SolverResult primal_result = primal_solver.Solve(
2928 IterationType::kPrimalFeasibility, interrupt_solve, primal_solve_log);
2931 preprocess_solver_->SwapObjectiveVector(objective);
2933 *solve_log.add_feasibility_polishing_details() =
2934 BuildFeasibilityPolishingDetails(
2935 POLISHING_PHASE_TYPE_PRIMAL_FEASIBILITY, iterations_completed_,
2936 primal_feasibility_params, primal_result.solve_log);
2937 return primal_result;
2940VectorXd MapFiniteValuesToZero(
const Sharder& sharder,
const VectorXd&
input) {
2941 VectorXd output(
input.size());
2942 const auto make_finite_values_zero = [](
const double x) {
2943 return std::isfinite(x) ? 0.0 :
x;
2945 sharder.ParallelForEachShard([&](
const Sharder::Shard& shard) {
2946 shard(output) = shard(
input).unaryExpr(make_finite_values_zero);
2951SolverResult Solver::TryDualPolishing(VectorXd starting_dual_solution,
2952 const int iteration_limit,
2953 const std::atomic<bool>* interrupt_solve,
2954 SolveLog& solve_log) {
2955 PrimalDualHybridGradientParams dual_feasibility_params = params_;
2956 *dual_feasibility_params.mutable_termination_criteria() =
2957 ReduceWorkLimitsByPreviousWork(
2958 params_.termination_criteria(), iteration_limit,
2959 TotalWorkSoFar(solve_log),
2960 params_.apply_feasibility_polishing_after_limits_reached());
2961 if (params_.apply_feasibility_polishing_if_solver_is_interrupted()) {
2962 interrupt_solve =
nullptr;
2968 VectorXd constraint_lower_bounds = MapFiniteValuesToZero(
2969 ShardedWorkingQp().DualSharder(), WorkingQp().constraint_lower_bounds);
2970 VectorXd constraint_upper_bounds = MapFiniteValuesToZero(
2971 ShardedWorkingQp().DualSharder(), WorkingQp().constraint_upper_bounds);
2972 VectorXd variable_lower_bounds = MapFiniteValuesToZero(
2973 ShardedWorkingQp().PrimalSharder(), WorkingQp().variable_lower_bounds);
2974 VectorXd variable_upper_bounds = MapFiniteValuesToZero(
2975 ShardedWorkingQp().PrimalSharder(), WorkingQp().variable_upper_bounds);
2976 preprocess_solver_->SwapConstraintBounds(constraint_lower_bounds,
2977 constraint_upper_bounds);
2978 preprocess_solver_->SwapVariableBounds(variable_lower_bounds,
2979 variable_upper_bounds);
2981 TerminationCriteria::DetailedOptimalityCriteria criteria =
2983 const double kInfinity = std::numeric_limits<double>::infinity();
2984 criteria.set_eps_optimal_primal_residual_absolute(
kInfinity);
2985 criteria.set_eps_optimal_primal_residual_relative(
kInfinity);
2986 criteria.set_eps_optimal_objective_gap_absolute(
kInfinity);
2987 criteria.set_eps_optimal_objective_gap_relative(
kInfinity);
2988 *dual_feasibility_params.mutable_termination_criteria()
2989 ->mutable_detailed_optimality_criteria() = criteria;
2992 VectorXd dual_feasibility_starting_primal;
2993 SetZero(ShardedWorkingQp().PrimalSharder(), dual_feasibility_starting_primal);
2994 Solver dual_solver(dual_feasibility_params,
2995 std::move(dual_feasibility_starting_primal),
2996 std::move(starting_dual_solution), step_size_,
2997 primal_weight_, preprocess_solver_);
2998 SolveLog dual_solve_log;
3002 SolverResult dual_result = dual_solver.Solve(IterationType::kDualFeasibility,
3003 interrupt_solve, dual_solve_log);
3006 preprocess_solver_->SwapConstraintBounds(constraint_lower_bounds,
3007 constraint_upper_bounds);
3008 preprocess_solver_->SwapVariableBounds(variable_lower_bounds,
3009 variable_upper_bounds);
3010 *solve_log.add_feasibility_polishing_details() =
3011 BuildFeasibilityPolishingDetails(
3012 POLISHING_PHASE_TYPE_DUAL_FEASIBILITY, iterations_completed_,
3013 dual_feasibility_params, dual_result.solve_log);
3017SolverResult Solver::Solve(
const IterationType iteration_type,
3018 const std::atomic<bool>* interrupt_solve,
3019 SolveLog solve_log) {
3020 preprocessing_time_sec_ = solve_log.preprocessing_time_sec();
3022 last_primal_start_point_ =
3023 CloneVector(current_primal_solution_, ShardedWorkingQp().PrimalSharder());
3024 last_dual_start_point_ =
3025 CloneVector(current_dual_solution_, ShardedWorkingQp().DualSharder());
3029 ratio_last_two_step_sizes_ = 1;
3030 SetCurrentPrimalAndDualProducts();
3034 bool force_numerical_termination =
false;
3036 int next_feasibility_polishing_iteration = 100;
3038 num_rejected_steps_ = 0;
3040 IterationStats work_from_feasibility_polishing =
3041 WorkFromFeasibilityPolishing(solve_log);
3042 for (iterations_completed_ = 0;; ++iterations_completed_) {
3046 const std::optional<SolverResult> maybe_result =
3047 MajorIterationAndTerminationCheck(
3048 iteration_type, force_numerical_termination, interrupt_solve,
3049 work_from_feasibility_polishing, solve_log);
3050 if (maybe_result.has_value()) {
3051 return maybe_result.value();
3054 if (params_.use_feasibility_polishing() &&
3055 iteration_type == IterationType::kNormal &&
3056 iterations_completed_ >= next_feasibility_polishing_iteration) {
3057 const std::optional<SolverResult> feasibility_result =
3058 TryFeasibilityPolishing(
3059 iterations_completed_ / kFeasibilityIterationFraction,
3060 interrupt_solve, solve_log);
3061 if (feasibility_result.has_value()) {
3062 return *feasibility_result;
3064 next_feasibility_polishing_iteration *= 2;
3066 work_from_feasibility_polishing = WorkFromFeasibilityPolishing(solve_log);
3073 InnerStepOutcome outcome;
3074 switch (params_.linesearch_rule()) {
3075 case PrimalDualHybridGradientParams::MALITSKY_POCK_LINESEARCH_RULE:
3076 outcome = TakeMalitskyPockStep();
3078 case PrimalDualHybridGradientParams::ADAPTIVE_LINESEARCH_RULE:
3079 outcome = TakeAdaptiveStep();
3081 case PrimalDualHybridGradientParams::CONSTANT_STEP_SIZE_RULE:
3082 outcome = TakeConstantSizeStep();
3085 LOG(FATAL) <<
"Unrecognized linesearch rule "
3086 << params_.linesearch_rule();
3088 if (outcome == InnerStepOutcome::kForceNumericalTermination) {
3089 force_numerical_termination =
true;
3098 const std::atomic<bool>* interrupt_solve,
3099 std::function<
void(
const std::string&)> message_callback,
3100 IterationStatsCallback iteration_stats_callback) {
3102 interrupt_solve, std::move(message_callback),
3103 std::move(iteration_stats_callback));
3109 std::optional<PrimalAndDualSolution> initial_solution,
3110 const std::atomic<bool>* interrupt_solve,
3111 std::function<
void(
const std::string&)> message_callback,
3112 IterationStatsCallback iteration_stats_callback) {
3115 if (message_callback) {
3120 const absl::Status params_status =
3122 if (!params_status.ok()) {
3124 params_status.ToString(), logger);
3128 "constraint_matrix must be in compressed format. "
3129 "Call constraint_matrix.makeCompressed()",
3133 if (!dimensions_status.ok()) {
3135 dimensions_status.ToString(), logger);
3139 "The objective scaling factor cannot be zero.",
3143 return ErrorSolverResult(
3145 "use_feasibility_polishing is only implemented for linear programs.",
3148 PreprocessSolver solver(std::move(qp), params, &logger);
3149 return solver.PreprocessAndSolve(params, std::move(initial_solution),
3151 std::move(iteration_stats_callback));
3159 glop::RowIndex(
solution.dual_solution.size()),
3160 glop::ColIndex(
solution.primal_solution.size()));
3164 for (glop::RowIndex i{0}; i.value() <
solution.dual_solution.size(); ++i) {
3169 }
else if (
solution.dual_solution[i.value()] > 0) {
3172 }
else if (
solution.dual_solution[i.value()] < 0) {
3180 for (glop::ColIndex i{0}; i.value() <
solution.primal_solution.size(); ++i) {
3181 const bool at_lb =
solution.primal_solution[i.value()] <=
3183 const bool at_ub =
solution.primal_solution[i.value()] >=
3203 return glop_solution;
bool use_feasibility_polishing() const
void EnableLogging(bool enable)
void SetLogToStdOut(bool enable)
void AddInfoLoggingCallback(std::function< void(const std::string &message)> callback)
constexpr Fractional kInfinity
Fractional SquaredNorm(const SparseColumn &v)
@ TERMINATION_REASON_OPTIMAL
@ TERMINATION_REASON_NUMERICAL_ERROR
absl::StatusOr< SolveResult > Solve(const Model &model, const SolverType solver_type, const SolveArguments &solve_args, const SolverInitArguments &init_args)
glop::ProblemSolution ComputeStatuses(const QuadraticProgram &qp, const PrimalAndDualSolution &solution)
std::optional< TerminationReasonAndPointType > CheckSimpleTerminationCriteria(const TerminationCriteria &criteria, const IterationStats &stats, const std::atomic< bool > *interrupt_solve)
absl::StatusOr< MPModelProto > QpToMpModelProto(const QuadraticProgram &qp)
void SetZero(const Sharder &sharder, VectorXd &dest)
InfeasibilityInformation ComputeInfeasibilityInformation(const PrimalDualHybridGradientParams ¶ms, const ShardedQuadraticProgram &scaled_sharded_qp, const Eigen::VectorXd &col_scaling_vec, const Eigen::VectorXd &row_scaling_vec, const Eigen::VectorXd &scaled_primal_ray, const Eigen::VectorXd &scaled_dual_ray, const Eigen::VectorXd &primal_solution_for_residual_tests, PointType candidate_type)
QuadraticProgramStats ComputeStats(const ShardedQuadraticProgram &qp)
std::optional< ConvergenceInformation > GetConvergenceInformation(const IterationStats &stats, PointType candidate_type)
absl::Status ValidateQuadraticProgramDimensions(const QuadraticProgram &qp)
absl::Status ValidatePrimalDualHybridGradientParams(const PrimalDualHybridGradientParams ¶ms)
void SetRandomProjections(const ShardedQuadraticProgram &sharded_qp, const Eigen::VectorXd &primal_solution, const Eigen::VectorXd &dual_solution, const std::vector< int > &random_projection_seeds, PointMetadata &metadata)
double SquaredDistance(const VectorXd &vector1, const VectorXd &vector2, const Sharder &sharder)
double LInfNorm(const VectorXd &vector, const Sharder &sharder)
TerminationCriteria::DetailedOptimalityCriteria EffectiveOptimalityCriteria(const TerminationCriteria &termination_criteria)
@ POINT_TYPE_FEASIBILITY_POLISHING_SOLUTION
@ POINT_TYPE_PRESOLVER_SOLUTION
@ POINT_TYPE_AVERAGE_ITERATE
@ POINT_TYPE_ITERATE_DIFFERENCE
@ POINT_TYPE_CURRENT_ITERATE
double Distance(const VectorXd &vector1, const VectorXd &vector2, const Sharder &sharder)
VectorXd ReducedCosts(const PrimalDualHybridGradientParams ¶ms, const ShardedQuadraticProgram &sharded_qp, const VectorXd &primal_solution, const VectorXd &dual_solution, bool use_zero_primal_objective)
VectorXd TransposedMatrixVectorProduct(const Eigen::SparseMatrix< double, Eigen::ColMajor, int64_t > &matrix, const VectorXd &vector, const Sharder &sharder)
const ::std::string & PointType_Name(T value)
QuadraticProgramBoundNorms BoundNormsFromProblemStats(const QuadraticProgramStats &stats)
double EpsilonRatio(const double epsilon_absolute, const double epsilon_relative)
SingularValueAndIterations EstimateMaximumSingularValueOfConstraintMatrix(const ShardedQuadraticProgram &sharded_qp, const std::optional< VectorXd > &primal_solution, const std::optional< VectorXd > &dual_solution, const double desired_relative_error, const double failure_probability, std::mt19937 &mt_generator)
@ RESTART_CHOICE_RESTART_TO_AVERAGE
@ RESTART_CHOICE_UNSPECIFIED
@ RESTART_CHOICE_NO_RESTART
@ RESTART_CHOICE_WEIGHTED_AVERAGE_RESET
void ProjectToPrimalVariableBounds(const ShardedQuadraticProgram &sharded_qp, VectorXd &primal, const bool use_feasibility_bounds)
absl::StatusOr< QuadraticProgram > QpFromMpModelProto(const MPModelProto &proto, bool relax_integer_variables, bool include_names)
const ::std::string & TerminationReason_Name(T value)
bool IsLinearProgram(const QuadraticProgram &qp)
@ OPTIMALITY_NORM_UNSPECIFIED
@ OPTIMALITY_NORM_L_INF_COMPONENTWISE
void ProjectToDualVariableBounds(const ShardedQuadraticProgram &sharded_qp, VectorXd &dual)
std::optional< TerminationReasonAndPointType > CheckIterateTerminationCriteria(const TerminationCriteria &criteria, const IterationStats &stats, const QuadraticProgramBoundNorms &bound_norms, const bool force_numerical_termination)
void CoefficientWiseProductInPlace(const VectorXd &scale, const Sharder &sharder, VectorXd &dest)
void CoefficientWiseQuotientInPlace(const VectorXd &scale, const Sharder &sharder, VectorXd &dest)
VectorXd ZeroVector(const Sharder &sharder)
VectorXd CloneVector(const VectorXd &vec, const Sharder &sharder)
SolverResult PrimalDualHybridGradient(QuadraticProgram qp, const PrimalDualHybridGradientParams ¶ms, const std::atomic< bool > *interrupt_solve, std::function< void(const std::string &)> message_callback, IterationStatsCallback iteration_stats_callback)
VectorXd OnesVector(const Sharder &sharder)
bool HasValidBounds(const ShardedQuadraticProgram &sharded_qp)
ScalingVectors ApplyRescaling(const RescalingOptions &rescaling_options, ShardedQuadraticProgram &sharded_qp)
bool ObjectiveGapMet(const TerminationCriteria::DetailedOptimalityCriteria &optimality_criteria, const ConvergenceInformation &stats)
ConvergenceInformation ComputeConvergenceInformation(const PrimalDualHybridGradientParams ¶ms, const ShardedQuadraticProgram &scaled_sharded_qp, const Eigen::VectorXd &col_scaling_vec, const Eigen::VectorXd &row_scaling_vec, const Eigen::VectorXd &scaled_primal_solution, const Eigen::VectorXd &scaled_dual_solution, const double componentwise_primal_residual_offset, const double componentwise_dual_residual_offset, PointType candidate_type)
LocalizedLagrangianBounds ComputeLocalizedLagrangianBounds(const ShardedQuadraticProgram &sharded_qp, const VectorXd &primal_solution, const VectorXd &dual_solution, const PrimalDualNorm primal_dual_norm, const double primal_weight, const double radius, const VectorXd *primal_product, const VectorXd *dual_product, const bool use_diagonal_qp_trust_region_solver, const double diagonal_qp_trust_region_solver_tolerance)
double Norm(const VectorXd &vector, const Sharder &sharder)
@ TERMINATION_REASON_TIME_LIMIT
@ TERMINATION_REASON_KKT_MATRIX_PASS_LIMIT
@ TERMINATION_REASON_PRIMAL_OR_DUAL_INFEASIBLE
@ TERMINATION_REASON_INVALID_PROBLEM
@ TERMINATION_REASON_PRIMAL_INFEASIBLE
@ TERMINATION_REASON_ITERATION_LIMIT
@ TERMINATION_REASON_INVALID_PARAMETER
@ TERMINATION_REASON_OTHER
@ TERMINATION_REASON_INTERRUPTED_BY_USER
RelativeConvergenceInformation ComputeRelativeResiduals(const TerminationCriteria::DetailedOptimalityCriteria &optimality_criteria, const ConvergenceInformation &stats, const QuadraticProgramBoundNorms &bound_norms)
void AssignVector(const VectorXd &vec, const Sharder &sharder, VectorXd &dest)
double BoundGap(const LocalizedLagrangianBounds &bounds)
@ kFeasibilityPolishingTermination
Select next search node to expand Select next item_i to add this new search node to the search Generate a new search node where item_i is not in the knapsack Check validity of this new partial solution(using propagators) - If valid
static int input(yyscan_t yyscanner)
ConstraintStatusColumn constraint_statuses
VariableStatusRow variable_statuses
double objective_scaling_factor
Eigen::VectorXd variable_lower_bounds
Eigen::VectorXd constraint_lower_bounds
Eigen::SparseMatrix< double, Eigen::ColMajor, int64_t > constraint_matrix
Eigen::VectorXd variable_upper_bounds
Eigen::VectorXd constraint_upper_bounds
#define SOLVER_LOG(logger,...)