22#include "absl/flags/flag.h"
23#include "absl/log/check.h"
24#include "absl/log/log.h"
25#include "absl/log/vlog_is_on.h"
26#include "absl/strings/str_cat.h"
27#include "absl/strings/str_format.h"
28#include "google/protobuf/text_format.h"
44#ifndef __PORTABLE_PLATFORM__
50 "Tells whether do dump the problem to a protobuf file.");
52 "Whether the proto dump file is compressed.");
54 "Whether the proto dump file is binary.");
56 "Number for the dump file, in the form name-000048.pb. "
57 "If < 0, the file is automatically numbered from the number of "
58 "calls to LPSolver::Solve().");
60 "Directory where dump files are written.");
62 "Base name for dump files. LinearProgram::name_ is used if "
63 "lp_dump_file_basename is empty. If LinearProgram::name_ is "
64 "empty, \"linear_program_dump_file\" is used.");
66 "Override any user parameters with the value of this flag. This is "
67 "interpreted as a GlopParameters proto in text format.");
80void DumpLinearProgramIfRequiredByFlags(
const LinearProgram& linear_program,
82 if (!absl::GetFlag(FLAGS_lp_dump_to_proto_file))
return;
83#ifdef __PORTABLE_PLATFORM__
84 LOG(WARNING) <<
"DumpLinearProgramIfRequiredByFlags(linear_program, num) "
85 "requested for linear_program.name()='"
86 << linear_program.name() <<
"', num=" << num
87 <<
" but is not implemented for this platform.";
89 std::string filename = absl::GetFlag(FLAGS_lp_dump_file_basename);
90 if (filename.empty()) {
91 if (linear_program.name().empty()) {
92 filename =
"linear_program_dump";
94 filename = linear_program.name();
97 const int file_num = absl::GetFlag(FLAGS_lp_dump_file_number) >= 0
98 ? absl::GetFlag(FLAGS_lp_dump_file_number)
100 absl::StrAppendFormat(&filename,
"-%06d.pb", file_num);
101 const std::string filespec =
102 absl::StrCat(absl::GetFlag(FLAGS_lp_dump_dir),
"/", filename);
105 const ProtoWriteFormat write_format = absl::GetFlag(FLAGS_lp_dump_binary_file)
109 absl::GetFlag(FLAGS_lp_dump_compressed_file)));
126 parameters_ = parameters;
127#ifndef __PORTABLE_PLATFORM__
128 if (!absl::GetFlag(FLAGS_glop_params).empty()) {
130 CHECK(google::protobuf::TextFormat::ParseFromString(
131 absl::GetFlag(FLAGS_glop_params), &flag_params));
132 parameters_.MergeFrom(flag_params);
137const GlopParameters& LPSolver::GetParameters()
const {
return parameters_; }
152 LOG(DFATAL) <<
"SolveWithTimeLimit() called with a nullptr time_limit.";
156 num_revised_simplex_iterations_ = 0;
157 DumpLinearProgramIfRequiredByFlags(lp, num_solves_);
161 <<
"\n******************************************************************"
162 "\n* WARNING: Glop will be very slow because it will use DCHECKs *"
163 "\n* to verify the results and the precision of the solver. *"
164 "\n* You can gain at least an order of magnitude speedup by *"
165 "\n* compiling with optimizations enabled and by defining NDEBUG. *"
166 "\n******************************************************************";
169 logger_.EnableLogging(parameters_.log_search_progress());
170 logger_.SetLogToStdOut(parameters_.log_to_stdout());
171 if (!parameters_.log_search_progress() && VLOG_IS_ON(1)) {
172 logger_.EnableLogging(
true);
173 logger_.SetLogToStdOut(
false);
177 if (logger_.LoggingIsEnabled()) {
187 LOG(DFATAL) <<
"The columns of the given linear program should be ordered "
188 <<
"by row and contain no zero coefficients. Call CleanUp() "
189 <<
"on it before calling Solve().";
191 return ProblemStatus::INVALID_PROBLEM;
197 if (!lp.
IsValid(parameters_.max_valid_magnitude())) {
199 "The given linear program is invalid. It contains NaNs, "
200 "coefficients too large or invalid bounds specification.");
202 return ProblemStatus::INVALID_PROBLEM;
206 current_linear_program_.PopulateFromLinearProgram(lp);
216 current_linear_program_.RemoveNearZeroEntries(parameters_.drop_magnitude());
219 MainLpPreprocessor preprocessor(¶meters_);
220 preprocessor.SetLogger(&logger_);
223 const bool postsolve_is_needed = preprocessor.Run(¤t_linear_program_);
225 if (logger_.LoggingIsEnabled()) {
228 current_linear_program_.GetDimensionString());
230 current_linear_program_.GetObjectiveStatsString());
232 current_linear_program_.GetBoundsStatsString());
237 ProblemSolution
solution(current_linear_program_.num_constraints(),
238 current_linear_program_.num_variables());
239 solution.status = preprocessor.status();
249 constraints_dual_ray_.clear();
250 variable_bounds_dual_ray_.clear();
256 RunRevisedSimplexIfNeeded(&solution,
time_limit);
258 if (postsolve_is_needed) preprocessor.DestructiveRecoverSolution(&solution);
259 const ProblemStatus status = LoadAndVerifySolution(lp, solution);
261 if (logger_.LoggingIsEnabled()) {
263 SOLVER_LOG(&logger_,
"objective: ", GetObjectiveValue());
264 SOLVER_LOG(&logger_,
"iterations: ", GetNumberOfSimplexIterations());
274void LPSolver::Clear() {
275 ResizeSolution(RowIndex(0), ColIndex(0));
276 revised_simplex_.reset(
nullptr);
306 if (revised_simplex_ ==
nullptr) {
307 revised_simplex_ = std::make_unique<RevisedSimplex>();
308 revised_simplex_->SetLogger(&logger_);
310 revised_simplex_->LoadStateForNextSolve(state);
311 if (parameters_.use_preprocessing()) {
312 LOG(WARNING) <<
"In GLOP, SetInitialBasis() was called but the parameter "
313 "use_preprocessing is true, this will likely not result in "
327Fractional AllowedError(Fractional tolerance, Fractional value) {
328 return tolerance * std::max(Fractional(1.0), std::abs(value));
334ProblemStatus LPSolver::LoadAndVerifySolution(
const LinearProgram& lp,
335 const ProblemSolution& solution) {
337 SOLVER_LOG(&logger_,
"Final unscaled solution:");
339 if (!IsProblemSolutionConsistent(lp,
solution)) {
340 SOLVER_LOG(&logger_,
"Inconsistency detected in the solution.");
341 ResizeSolution(lp.num_constraints(), lp.num_variables());
346 primal_values_ =
solution.primal_values;
347 dual_values_ =
solution.dual_values;
348 variable_statuses_ =
solution.variable_statuses;
349 constraint_statuses_ =
solution.constraint_statuses;
355 ComputeReducedCosts(lp);
356 const Fractional primal_objective_value = ComputeObjective(lp);
357 const Fractional dual_objective_value = ComputeDualObjective(lp);
358 SOLVER_LOG(&logger_,
"Primal objective (before moving primal/dual values) = ",
360 "%.15E", ProblemObjectiveValue(lp, primal_objective_value)));
361 SOLVER_LOG(&logger_,
"Dual objective (before moving primal/dual values) = ",
362 absl::StrFormat(
"%.15E",
363 ProblemObjectiveValue(lp, dual_objective_value)));
367 parameters_.provide_strong_optimal_guarantee()) {
368 MovePrimalValuesWithinBounds(lp);
369 MoveDualValuesWithinBounds(lp);
373 problem_objective_value_ = ProblemObjectiveValue(lp, ComputeObjective(lp));
374 SOLVER_LOG(&logger_,
"Primal objective (after moving primal/dual values) = ",
375 absl::StrFormat(
"%.15E", problem_objective_value_));
377 ComputeReducedCosts(lp);
378 ComputeConstraintActivities(lp);
388 bool rhs_perturbation_is_too_large =
false;
389 bool cost_perturbation_is_too_large =
false;
390 bool primal_infeasibility_is_too_large =
false;
391 bool dual_infeasibility_is_too_large =
false;
392 bool primal_residual_is_too_large =
false;
393 bool dual_residual_is_too_large =
false;
396 ComputeMaxRhsPerturbationToEnforceOptimality(lp,
397 &rhs_perturbation_is_too_large);
398 ComputeMaxCostPerturbationToEnforceOptimality(
399 lp, &cost_perturbation_is_too_large);
400 const double primal_infeasibility =
401 ComputePrimalValueInfeasibility(lp, &primal_infeasibility_is_too_large);
402 const double dual_infeasibility =
403 ComputeDualValueInfeasibility(lp, &dual_infeasibility_is_too_large);
404 const double primal_residual =
405 ComputeActivityInfeasibility(lp, &primal_residual_is_too_large);
406 const double dual_residual =
407 ComputeReducedCostInfeasibility(lp, &dual_residual_is_too_large);
412 max_absolute_primal_infeasibility_ =
413 std::max(primal_infeasibility, primal_residual);
414 max_absolute_dual_infeasibility_ =
415 std::max(dual_infeasibility, dual_residual);
416 SOLVER_LOG(&logger_,
"Max. primal infeasibility = ",
417 max_absolute_primal_infeasibility_);
419 "Max. dual infeasibility = ", max_absolute_dual_infeasibility_);
424 const double objective_error_ub = ComputeMaxExpectedObjectiveError(lp);
425 SOLVER_LOG(&logger_,
"Objective error <= ", objective_error_ub);
427 if (status == ProblemStatus::OPTIMAL &&
428 parameters_.provide_strong_optimal_guarantee()) {
431 if (primal_infeasibility != 0.0 || dual_infeasibility != 0.0) {
432 LOG(ERROR) <<
"Primal/dual values have been moved to their bounds. "
433 <<
"Therefore the primal/dual infeasibilities should be "
434 <<
"exactly zero (but not the residuals). If this message "
435 <<
"appears, there is probably a bug in "
436 <<
"MovePrimalValuesWithinBounds() or in "
437 <<
"MoveDualValuesWithinBounds().";
439 if (rhs_perturbation_is_too_large) {
440 SOLVER_LOG(&logger_,
"The needed rhs perturbation is too large !!");
441 if (parameters_.change_status_to_imprecise()) {
442 status = ProblemStatus::IMPRECISE;
445 if (cost_perturbation_is_too_large) {
446 SOLVER_LOG(&logger_,
"The needed cost perturbation is too large !!");
447 if (parameters_.change_status_to_imprecise()) {
448 status = ProblemStatus::IMPRECISE;
456 if (status == ProblemStatus::OPTIMAL) {
457 if (std::abs(primal_objective_value - dual_objective_value) >
458 objective_error_ub) {
460 "The objective gap of the final solution is too large.");
461 if (parameters_.change_status_to_imprecise()) {
462 status = ProblemStatus::IMPRECISE;
466 if ((status == ProblemStatus::OPTIMAL ||
467 status == ProblemStatus::PRIMAL_FEASIBLE) &&
468 (primal_residual_is_too_large || primal_infeasibility_is_too_large)) {
470 "The primal infeasibility of the final solution is too large.");
471 if (parameters_.change_status_to_imprecise()) {
472 status = ProblemStatus::IMPRECISE;
475 if ((status == ProblemStatus::OPTIMAL ||
476 status == ProblemStatus::DUAL_FEASIBLE) &&
477 (dual_residual_is_too_large || dual_infeasibility_is_too_large)) {
479 "The dual infeasibility of the final solution is too large.");
480 if (parameters_.change_status_to_imprecise()) {
481 status = ProblemStatus::IMPRECISE;
485 may_have_multiple_solutions_ =
486 (status == ProblemStatus::OPTIMAL) ? IsOptimalSolutionOnFacet(lp) :
false;
490bool LPSolver::IsOptimalSolutionOnFacet(
const LinearProgram& lp) {
495 const Fractional kReducedCostTolerance = 1e-9;
497 const ColIndex num_cols = lp.num_variables();
498 for (ColIndex col(0); col < num_cols; ++col) {
499 if (variable_statuses_[col] == VariableStatus::FIXED_VALUE)
continue;
500 const Fractional lower_bound = lp.variable_lower_bounds()[col];
501 const Fractional upper_bound = lp.variable_upper_bounds()[col];
504 kReducedCostTolerance) &&
510 const RowIndex num_rows = lp.num_constraints();
511 for (RowIndex row(0); row < num_rows; ++row) {
512 if (constraint_statuses_[row] == ConstraintStatus::FIXED_VALUE)
continue;
513 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
514 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
515 const Fractional activity = constraint_activities_[row];
517 kReducedCostTolerance) &&
526Fractional LPSolver::GetObjectiveValue()
const {
527 return problem_objective_value_;
531 return max_absolute_primal_infeasibility_;
535 return max_absolute_dual_infeasibility_;
539 return may_have_multiple_solutions_;
543 return num_revised_simplex_iterations_;
547 return revised_simplex_ ==
nullptr ? 0.0
548 : revised_simplex_->DeterministicTime();
551void LPSolver::MovePrimalValuesWithinBounds(
const LinearProgram& lp) {
553 DCHECK_EQ(num_cols, primal_values_.size());
555 for (ColIndex col(0); col < num_cols; ++col) {
558 DCHECK_LE(lower_bound, upper_bound);
560 error = std::max(error, primal_values_[col] - upper_bound);
561 error = std::max(error, lower_bound - primal_values_[col]);
562 primal_values_[col] = std::min(primal_values_[col], upper_bound);
563 primal_values_[col] = std::max(primal_values_[col], lower_bound);
565 SOLVER_LOG(&logger_,
"Max. primal values move = ", error);
568void LPSolver::MoveDualValuesWithinBounds(
const LinearProgram& lp) {
569 const RowIndex num_rows = lp.num_constraints();
570 DCHECK_EQ(num_rows, dual_values_.size());
571 const Fractional optimization_sign = lp.IsMaximizationProblem() ? -1.0 : 1.0;
572 Fractional error = 0.0;
573 for (RowIndex row(0); row < num_rows; ++row) {
574 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
575 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
578 Fractional minimization_dual_value = optimization_sign * dual_values_[row];
579 if (lower_bound == -kInfinity && minimization_dual_value > 0.0) {
580 error = std::max(error, minimization_dual_value);
581 minimization_dual_value = 0.0;
583 if (upper_bound == kInfinity && minimization_dual_value < 0.0) {
584 error = std::max(error, -minimization_dual_value);
585 minimization_dual_value = 0.0;
587 dual_values_[row] = optimization_sign * minimization_dual_value;
589 SOLVER_LOG(&logger_,
"Max. dual values move = ", error);
592void LPSolver::ResizeSolution(RowIndex num_rows, ColIndex num_cols) {
593 primal_values_.resize(num_cols, 0.0);
594 reduced_costs_.resize(num_cols, 0.0);
595 variable_statuses_.resize(num_cols, VariableStatus::FREE);
597 dual_values_.resize(num_rows, 0.0);
598 constraint_activities_.resize(num_rows, 0.0);
599 constraint_statuses_.resize(num_rows, ConstraintStatus::FREE);
602void LPSolver::RunRevisedSimplexIfNeeded(ProblemSolution* solution,
611 current_linear_program_.ClearTransposeMatrix();
612 if (
solution->status != ProblemStatus::INIT)
return;
613 if (revised_simplex_ ==
nullptr) {
614 revised_simplex_ = std::make_unique<RevisedSimplex>();
615 revised_simplex_->SetLogger(&logger_);
617 revised_simplex_->SetParameters(parameters_);
618 if (revised_simplex_->Solve(current_linear_program_,
time_limit).ok()) {
619 num_revised_simplex_iterations_ = revised_simplex_->GetNumberOfIterations();
620 solution->status = revised_simplex_->GetProblemStatus();
623 const ColIndex num_cols =
solution->primal_values.size();
624 DCHECK_LE(num_cols, revised_simplex_->GetProblemNumCols());
625 for (ColIndex col(0); col < num_cols; ++col) {
626 solution->primal_values[col] = revised_simplex_->GetVariableValue(col);
628 revised_simplex_->GetVariableStatus(col);
630 const RowIndex num_rows = revised_simplex_->GetProblemNumRows();
631 DCHECK_EQ(
solution->dual_values.size(), num_rows);
632 for (RowIndex row(0); row < num_rows; ++row) {
633 solution->dual_values[row] = revised_simplex_->GetDualValue(row);
634 solution->constraint_statuses[row] =
635 revised_simplex_->GetConstraintStatus(row);
637 if (!parameters_.use_preprocessing() && !parameters_.use_scaling()) {
638 if (
solution->status == ProblemStatus::PRIMAL_UNBOUNDED) {
639 primal_ray_ = revised_simplex_->GetPrimalRay();
641 primal_ray_.resize(num_cols);
642 }
else if (
solution->status == ProblemStatus::DUAL_UNBOUNDED) {
643 constraints_dual_ray_ = revised_simplex_->GetDualRay();
644 variable_bounds_dual_ray_ =
645 revised_simplex_->GetDualRayRowCombination();
647 variable_bounds_dual_ray_.resize(num_cols);
658 if (current_linear_program_.IsMaximizationProblem()) {
666 SOLVER_LOG(&logger_,
"Error during the revised simplex algorithm.");
667 solution->status = ProblemStatus::ABNORMAL;
673void LogVariableStatusError(ColIndex col, Fractional value,
674 VariableStatus status, Fractional lb,
676 VLOG(1) <<
"Variable " << col <<
" status is "
678 <<
" and its bounds are [" << lb <<
", " << ub <<
"].";
681void LogConstraintStatusError(RowIndex row, ConstraintStatus status,
682 Fractional lb, Fractional ub) {
683 VLOG(1) <<
"Constraint " << row <<
" status is "
685 <<
", " << ub <<
"].";
690bool LPSolver::IsProblemSolutionConsistent(
691 const LinearProgram& lp,
const ProblemSolution& solution)
const {
692 const RowIndex num_rows = lp.num_constraints();
693 const ColIndex num_cols = lp.num_variables();
694 if (
solution.variable_statuses.size() != num_cols)
return false;
695 if (
solution.constraint_statuses.size() != num_rows)
return false;
696 if (
solution.primal_values.size() != num_cols)
return false;
697 if (
solution.dual_values.size() != num_rows)
return false;
698 if (
solution.status != ProblemStatus::OPTIMAL &&
699 solution.status != ProblemStatus::PRIMAL_FEASIBLE &&
700 solution.status != ProblemStatus::DUAL_FEASIBLE) {
706 RowIndex num_basic_variables(0);
707 for (ColIndex col(0); col < num_cols; ++col) {
709 const Fractional lb = lp.variable_lower_bounds()[col];
710 const Fractional ub = lp.variable_upper_bounds()[col];
712 switch (
solution.variable_statuses[col]) {
713 case VariableStatus::BASIC:
716 ++num_basic_variables;
718 case VariableStatus::FIXED_VALUE:
728 if (value != ub && value != lb) {
729 LogVariableStatusError(col, value, status, lb, ub);
733 case VariableStatus::AT_LOWER_BOUND:
734 if (value != lb || lb == ub) {
735 LogVariableStatusError(col, value, status, lb, ub);
739 case VariableStatus::AT_UPPER_BOUND:
744 LogVariableStatusError(col, value, status, lb, ub);
748 case VariableStatus::FREE:
749 if (lb != -kInfinity || ub != kInfinity || value != 0.0) {
750 LogVariableStatusError(col, value, status, lb, ub);
756 for (RowIndex row(0); row < num_rows; ++row) {
758 const Fractional lb = lp.constraint_lower_bounds()[row];
759 const Fractional ub = lp.constraint_upper_bounds()[row];
766 case ConstraintStatus::BASIC:
767 if (dual_value != 0.0) {
768 VLOG(1) <<
"Constraint " << row <<
" is BASIC, but its dual value is "
769 << dual_value <<
" instead of 0.";
772 ++num_basic_variables;
774 case ConstraintStatus::FIXED_VALUE:
778 if (ub - lb > 1e-12) {
779 LogConstraintStatusError(row, status, lb, ub);
783 case ConstraintStatus::AT_LOWER_BOUND:
784 if (lb == -kInfinity) {
785 LogConstraintStatusError(row, status, lb, ub);
789 case ConstraintStatus::AT_UPPER_BOUND:
790 if (ub == kInfinity) {
791 LogConstraintStatusError(row, status, lb, ub);
795 case ConstraintStatus::FREE:
796 if (dual_value != 0.0) {
797 VLOG(1) <<
"Constraint " << row <<
" is FREE, but its dual value is "
798 << dual_value <<
" instead of 0.";
801 if (lb != -kInfinity || ub != kInfinity) {
802 LogConstraintStatusError(row, status, lb, ub);
811 if (num_basic_variables != num_rows) {
812 VLOG(1) <<
"Wrong number of basic variables: " << num_basic_variables;
822Fractional LPSolver::ComputeMaxCostPerturbationToEnforceOptimality(
823 const LinearProgram& lp,
bool* is_too_large) {
825 const ColIndex num_cols = lp.num_variables();
826 const Fractional optimization_sign = lp.IsMaximizationProblem() ? -1.0 : 1.0;
827 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
828 for (ColIndex col(0); col < num_cols; ++col) {
832 const Fractional reduced_cost = optimization_sign * reduced_costs_[col];
834 if (status == VariableStatus::BASIC || status == VariableStatus::FREE ||
835 (status == VariableStatus::AT_UPPER_BOUND && reduced_cost > 0.0) ||
836 (status == VariableStatus::AT_LOWER_BOUND && reduced_cost < 0.0)) {
837 max_cost_correction =
838 std::max(max_cost_correction, std::abs(reduced_cost));
840 std::abs(reduced_cost) >
841 AllowedError(tolerance, lp.objective_coefficients()[col]);
844 SOLVER_LOG(&logger_,
"Max. cost perturbation = ", max_cost_correction);
845 return max_cost_correction;
850Fractional LPSolver::ComputeMaxRhsPerturbationToEnforceOptimality(
851 const LinearProgram& lp,
bool* is_too_large) {
853 const RowIndex num_rows = lp.num_constraints();
854 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
855 for (RowIndex row(0); row < num_rows; ++row) {
856 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
857 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
858 const Fractional activity = constraint_activities_[row];
863 if (status == ConstraintStatus::AT_LOWER_BOUND || activity < lower_bound) {
864 rhs_error = std::abs(activity - lower_bound);
865 allowed_error = AllowedError(tolerance, lower_bound);
866 }
else if (status == ConstraintStatus::AT_UPPER_BOUND ||
867 activity > upper_bound) {
868 rhs_error = std::abs(activity - upper_bound);
869 allowed_error = AllowedError(tolerance, upper_bound);
871 max_rhs_correction = std::max(max_rhs_correction, rhs_error);
872 *is_too_large |= rhs_error > allowed_error;
874 SOLVER_LOG(&logger_,
"Max. rhs perturbation = ", max_rhs_correction);
875 return max_rhs_correction;
878void LPSolver::ComputeConstraintActivities(
const LinearProgram& lp) {
879 const RowIndex num_rows = lp.num_constraints();
880 const ColIndex num_cols = lp.num_variables();
881 DCHECK_EQ(num_cols, primal_values_.size());
882 constraint_activities_.assign(num_rows, 0.0);
883 for (ColIndex col(0); col < num_cols; ++col) {
884 lp.GetSparseColumn(col).AddMultipleToDenseVector(primal_values_[col],
885 &constraint_activities_);
889void LPSolver::ComputeReducedCosts(
const LinearProgram& lp) {
890 const RowIndex num_rows = lp.num_constraints();
891 const ColIndex num_cols = lp.num_variables();
892 DCHECK_EQ(num_rows, dual_values_.size());
893 reduced_costs_.resize(num_cols, 0.0);
894 for (ColIndex col(0); col < num_cols; ++col) {
895 reduced_costs_[col] = lp.objective_coefficients()[col] -
900double LPSolver::ComputeObjective(
const LinearProgram& lp) {
901 const ColIndex num_cols = lp.num_variables();
902 DCHECK_EQ(num_cols, primal_values_.size());
904 for (ColIndex col(0); col < num_cols; ++col) {
905 sum.Add(lp.objective_coefficients()[col] * primal_values_[col]);
926double LPSolver::ComputeDualObjective(
const LinearProgram& lp) {
930 const RowIndex num_rows = lp.num_constraints();
931 const Fractional optimization_sign = lp.IsMaximizationProblem() ? -1.0 : 1.0;
932 for (RowIndex row(0); row < num_rows; ++row) {
933 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
934 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
937 const Fractional corrected_value = optimization_sign * dual_values_[row];
938 if (corrected_value > 0.0 && lower_bound != -kInfinity) {
939 dual_objective.Add(dual_values_[row] * lower_bound);
941 if (corrected_value < 0.0 && upper_bound != kInfinity) {
942 dual_objective.Add(dual_values_[row] * upper_bound);
962 const ColIndex num_cols = lp.num_variables();
963 for (ColIndex col(0); col < num_cols; ++col) {
964 const Fractional lower_bound = lp.variable_lower_bounds()[col];
965 const Fractional upper_bound = lp.variable_upper_bounds()[col];
969 const Fractional reduced_cost = optimization_sign * reduced_costs_[col];
974 if (variable_statuses_[col] == VariableStatus::AT_LOWER_BOUND &&
975 reduced_cost > 0.0) {
976 correction = reduced_cost * lower_bound;
977 }
else if (variable_statuses_[col] == VariableStatus::AT_UPPER_BOUND &&
978 reduced_cost < 0.0) {
979 correction = reduced_cost * upper_bound;
980 }
else if (variable_statuses_[col] == VariableStatus::FIXED_VALUE) {
981 correction = reduced_cost * upper_bound;
984 dual_objective.Add(optimization_sign * correction);
986 return dual_objective.Value();
989double LPSolver::ComputeMaxExpectedObjectiveError(
const LinearProgram& lp) {
990 const ColIndex num_cols = lp.num_variables();
991 DCHECK_EQ(num_cols, primal_values_.size());
992 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
994 for (ColIndex col(0); col < num_cols; ++col) {
998 primal_objective_error += std::abs(lp.objective_coefficients()[col]) *
999 AllowedError(tolerance, primal_values_[col]);
1001 return primal_objective_error;
1004double LPSolver::ComputePrimalValueInfeasibility(
const LinearProgram& lp,
1005 bool* is_too_large) {
1007 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
1008 const ColIndex num_cols = lp.num_variables();
1009 for (ColIndex col(0); col < num_cols; ++col) {
1010 const Fractional lower_bound = lp.variable_lower_bounds()[col];
1011 const Fractional upper_bound = lp.variable_upper_bounds()[col];
1012 DCHECK(
IsFinite(primal_values_[col]));
1014 if (lower_bound == upper_bound) {
1015 const Fractional error = std::abs(primal_values_[col] - upper_bound);
1016 infeasibility = std::max(infeasibility, error);
1017 *is_too_large |= error > AllowedError(tolerance, upper_bound);
1020 if (primal_values_[col] > upper_bound) {
1021 const Fractional error = primal_values_[col] - upper_bound;
1022 infeasibility = std::max(infeasibility, error);
1023 *is_too_large |= error > AllowedError(tolerance, upper_bound);
1025 if (primal_values_[col] < lower_bound) {
1026 const Fractional error = lower_bound - primal_values_[col];
1027 infeasibility = std::max(infeasibility, error);
1028 *is_too_large |= error > AllowedError(tolerance, lower_bound);
1031 return infeasibility;
1034double LPSolver::ComputeActivityInfeasibility(
const LinearProgram& lp,
1035 bool* is_too_large) {
1037 int num_problematic_rows(0);
1038 const RowIndex num_rows = lp.num_constraints();
1039 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
1040 for (RowIndex row(0); row < num_rows; ++row) {
1041 const Fractional activity = constraint_activities_[row];
1042 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
1043 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
1046 if (lower_bound == upper_bound) {
1047 if (std::abs(activity - upper_bound) >
1048 AllowedError(tolerance, upper_bound)) {
1049 VLOG(2) <<
"Row " << row.value() <<
" has activity " << activity
1050 <<
" which is different from " << upper_bound <<
" by "
1051 << activity - upper_bound;
1052 ++num_problematic_rows;
1054 infeasibility = std::max(infeasibility, std::abs(activity - upper_bound));
1057 if (activity > upper_bound) {
1058 const Fractional row_excess = activity - upper_bound;
1059 if (row_excess > AllowedError(tolerance, upper_bound)) {
1060 VLOG(2) <<
"Row " << row.value() <<
" has activity " << activity
1061 <<
", exceeding its upper bound " << upper_bound <<
" by "
1063 ++num_problematic_rows;
1065 infeasibility = std::max(infeasibility, row_excess);
1067 if (activity < lower_bound) {
1068 const Fractional row_deficit = lower_bound - activity;
1069 if (row_deficit > AllowedError(tolerance, lower_bound)) {
1070 VLOG(2) <<
"Row " << row.value() <<
" has activity " << activity
1071 <<
", below its lower bound " << lower_bound <<
" by "
1073 ++num_problematic_rows;
1075 infeasibility = std::max(infeasibility, row_deficit);
1078 if (num_problematic_rows > 0) {
1079 *is_too_large =
true;
1080 VLOG(1) <<
"Number of infeasible rows = " << num_problematic_rows;
1082 return infeasibility;
1085double LPSolver::ComputeDualValueInfeasibility(
const LinearProgram& lp,
1086 bool* is_too_large) {
1087 const Fractional allowed_error = parameters_.solution_feasibility_tolerance();
1088 const Fractional optimization_sign = lp.IsMaximizationProblem() ? -1.0 : 1.0;
1090 const RowIndex num_rows = lp.num_constraints();
1091 for (RowIndex row(0); row < num_rows; ++row) {
1092 const Fractional dual_value = dual_values_[row];
1093 const Fractional lower_bound = lp.constraint_lower_bounds()[row];
1094 const Fractional upper_bound = lp.constraint_upper_bounds()[row];
1096 const Fractional minimization_dual_value = optimization_sign * dual_value;
1097 if (lower_bound == -kInfinity) {
1098 *is_too_large |= minimization_dual_value > allowed_error;
1099 infeasibility = std::max(infeasibility, minimization_dual_value);
1101 if (upper_bound == kInfinity) {
1102 *is_too_large |= -minimization_dual_value > allowed_error;
1103 infeasibility = std::max(infeasibility, -minimization_dual_value);
1106 return infeasibility;
1109double LPSolver::ComputeReducedCostInfeasibility(
const LinearProgram& lp,
1110 bool* is_too_large) {
1111 const Fractional optimization_sign = lp.IsMaximizationProblem() ? -1.0 : 1.0;
1113 const ColIndex num_cols = lp.num_variables();
1114 const Fractional tolerance = parameters_.solution_feasibility_tolerance();
1115 for (ColIndex col(0); col < num_cols; ++col) {
1116 const Fractional reduced_cost = reduced_costs_[col];
1117 const Fractional lower_bound = lp.variable_lower_bounds()[col];
1118 const Fractional upper_bound = lp.variable_upper_bounds()[col];
1121 optimization_sign * reduced_cost;
1123 AllowedError(tolerance, lp.objective_coefficients()[col]);
1124 if (lower_bound == -kInfinity) {
1125 *is_too_large |= minimization_reduced_cost > allowed_error;
1126 infeasibility = std::max(infeasibility, minimization_reduced_cost);
1128 if (upper_bound == kInfinity) {
1129 *is_too_large |= -minimization_reduced_cost > allowed_error;
1130 infeasibility = std::max(infeasibility, -minimization_reduced_cost);
1133 return infeasibility;
FpNumber Value() const
Gets the value of the sum.
static std::unique_ptr< TimeLimit > FromParameters(const Parameters ¶meters)
GlopParameters * GetMutableParameters()
SolverLogger & GetSolverLogger()
static std::string GlopVersion()
Returns a string that describes the version of the solver.
Fractional GetMaximumDualInfeasibility() const
void SetInitialBasis(const VariableStatusRow &variable_statuses, const ConstraintStatusColumn &constraint_statuses)
int GetNumberOfSimplexIterations() const
Returns the number of simplex iterations used by the last Solve().
double DeterministicTime() const
const ConstraintStatusColumn & constraint_statuses() const
const VariableStatusRow & variable_statuses() const
Fractional GetMaximumPrimalInfeasibility() const
ABSL_MUST_USE_RESULT ProblemStatus SolveWithTimeLimit(const LinearProgram &lp, TimeLimit *time_limit)
void SetParameters(const GlopParameters ¶meters)
bool MayHaveMultipleOptimalSolutions() const
ABSL_MUST_USE_RESULT ProblemStatus Solve(const LinearProgram &lp)
std::string GetDimensionString() const
A short string with the problem dimension.
bool IsValid(Fractional max_valid_magnitude=kInfinity) const
const DenseRow & variable_lower_bounds() const
const DenseRow & variable_upper_bounds() const
Fractional objective_scaling_factor() const
ColIndex num_variables() const
Returns the number of variables.
std::string GetObjectiveStatsString() const
A short line with some stats on the problem coefficients.
Fractional objective_offset() const
Returns the objective offset and scaling factor.
RowIndex num_constraints() const
Returns the number of constraints.
std::string GetBoundsStatsString() const
void push_back(const value_type &val)
ABSL_FLAG(bool, lp_dump_to_proto_file, false, "Tells whether do dump the problem to a protobuf file.")
StrictITIVector< RowIndex, ConstraintStatus > ConstraintStatusColumn
Column of constraints (slack variables) statuses.
Fractional ScalarProduct(const DenseRowOrColumn1 &u, const DenseRowOrColumn2 &v)
AccurateSum< Fractional > KahanSum
void LinearProgramToMPModelProto(const LinearProgram &input, MPModelProto *output)
Converts a LinearProgram to a MPModelProto.
std::string GetVariableStatusString(VariableStatus status)
Returns the string representation of the VariableStatus enum.
bool IsFinite(Fractional value)
void ChangeSign(StrictITIVector< IndexType, Fractional > *data)
Changes the sign of all the entries in the given vector.
std::string GetConstraintStatusString(ConstraintStatus status)
Returns the string representation of the ConstraintStatus enum.
StrictITIVector< ColIndex, VariableStatus > VariableStatusRow
Row of variable statuses.
ProblemStatus
Different statuses for a given problem.
@ ABNORMAL
An error occurred during the solving process.
std::string GetProblemStatusString(ProblemStatus problem_status)
Returns the string representation of the ProblemStatus enum.
In SWIG mode, we don't want anything besides these top-level includes.
std::string OrToolsVersionString()
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
bool AreWithinAbsoluteTolerance(FloatType x, FloatType y, FloatType absolute_tolerance)
std::string ProtobufShortDebugString(const P &message)
absl::Status WriteProtoToFile(absl::string_view filename, const google::protobuf::Message &proto, ProtoWriteFormat proto_write_format, bool gzipped, bool append_extension_to_file_name)
VariableStatusRow statuses
#define SOLVER_LOG(logger,...)