Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
lp_data.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14//
15// Storage classes for Linear Programs.
16//
17// LinearProgram stores the complete data for a Linear Program:
18// - objective coefficients and offset,
19// - cost coefficients,
20// - coefficient matrix,
21// - bounds for each variable,
22// - bounds for each constraint.
23
24#ifndef OR_TOOLS_LP_DATA_LP_DATA_H_
25#define OR_TOOLS_LP_DATA_LP_DATA_H_
26
27#include <algorithm> // for max
28#include <cmath>
29#include <cstdint>
30#include <map>
31#include <string> // for string
32#include <vector> // for vector
33
34#include "absl/container/flat_hash_map.h"
35#include "absl/container/flat_hash_set.h"
36#include "absl/log/check.h"
37#include "absl/strings/string_view.h"
38#include "ortools/base/hash.h"
39#include "ortools/base/logging.h" // for CHECK*
40#include "ortools/glop/parameters.pb.h"
47
48namespace operations_research {
49namespace glop {
50
51class SparseMatrixScaler;
52
53// The LinearProgram class is used to store a linear problem in a form
54// accepted by LPSolver.
55//
56// In addition to the simple setter functions used to create such problems, the
57// class also contains a few more advanced modification functions used primarily
58// by preprocessors. A client shouldn't need to use them directly.
60 public:
61 enum class VariableType {
62 // The variable can take any value between and including its lower and upper
63 // bound.
65 // The variable must only take integer values.
66 INTEGER,
67 // The variable is implied integer variable i.e. it was continuous variable
68 // in the LP and was detected to take only integer values.
70 };
71
73
74 // This type is neither copyable nor movable.
75 LinearProgram(const LinearProgram&) = delete;
77
78 // Clears, i.e. reset the object to its initial value.
79 void Clear();
80
81 // Name setter and getter.
82 void SetName(absl::string_view name) { name_ = name; }
83 const std::string& name() const { return name_; }
84
85 // Creates a new variable and returns its index.
86 // By default, the column bounds will be [0, infinity).
87 ColIndex CreateNewVariable();
88
89 // Creates a new slack variable and returns its index. Do not use this method
90 // to create non-slack variables.
91 ColIndex CreateNewSlackVariable(bool is_integer_slack_variable,
94 const std::string& name);
95
96 // Creates a new constraint and returns its index.
97 // By default, the constraint bounds will be [0, 0].
98 RowIndex CreateNewConstraint();
99
100 // Same as CreateNewVariable() or CreateNewConstraint() but also assign an
101 // immutable id to the variable or constraint so they can be retrieved later.
102 // By default, the name is also set to this id, but it can be changed later
103 // without changing the id.
104 //
105 // Note that these ids are NOT copied over by the Populate*() functions.
106 //
107 // TODO(user): Move these and the two corresponding hash_table into a new
108 // LinearProgramBuilder class to simplify the code of some functions like
109 // DeleteColumns() here and make the behavior on copy clear? or simply remove
110 // them as it is almost as easy to maintain a hash_table on the client side.
111 ColIndex FindOrCreateVariable(absl::string_view variable_id);
112 RowIndex FindOrCreateConstraint(absl::string_view constraint_id);
113
114 // Functions to set the name of a variable or constraint. Note that you
115 // won't be able to find those named variables/constraints with
116 // FindOrCreate{Variable|Constraint}().
117 // TODO(user): Add PopulateIdsFromNames() so names added via
118 // Set{Variable|Constraint}Name() can be found.
119 void SetVariableName(ColIndex col, absl::string_view name);
120 void SetConstraintName(RowIndex row, absl::string_view name);
121
122 // Set the type of the variable.
123 void SetVariableType(ColIndex col, VariableType type);
124
125 // Returns whether the variable at column col is constrained to be integer.
126 bool IsVariableInteger(ColIndex col) const;
127
128 // Returns whether the variable at column col must take binary values or not.
129 bool IsVariableBinary(ColIndex col) const;
130
131 // Defines lower and upper bounds for the variable at col. Note that the
132 // bounds may be set to +/- infinity. The variable must have been created
133 // before or this will crash in non-debug mode.
136
137 // Defines lower and upper bounds for the constraint at row. Note that the
138 // bounds may be set to +/- infinity. If the constraint wasn't created before,
139 // all the rows from the current GetNumberOfRows() to the given row will be
140 // created with a range [0,0].
143
144 // Defines the coefficient for col / row.
145 void SetCoefficient(RowIndex row, ColIndex col, Fractional value);
146
147 // Defines the objective coefficient of column col.
148 // It is set to 0.0 by default.
150
151 // Define the objective offset (0.0 by default) and scaling factor (positive
152 // and equal to 1.0 by default). This is mainly used for displaying purpose
153 // and the real objective is factor * (objective + offset).
156
157 // Defines the optimization direction. When maximize is true (resp. false),
158 // the objective is maximized (resp. minimized). The default is false.
159 void SetMaximizationProblem(bool maximize);
160
161 // Calls CleanUp() on each columns.
162 // That is, removes duplicates, zeros, and orders the coefficients by row.
163 void CleanUp();
164
165 // Returns true if all the columns are ordered by rows and contain no
166 // duplicates or zero entries (i.e. if IsCleanedUp() is true for all columns).
167 bool IsCleanedUp() const;
168
169 // Functions that return the name of a variable or constraint. If the name is
170 // empty, they return a special name that depends on the index.
171 std::string GetVariableName(ColIndex col) const;
172 std::string GetConstraintName(RowIndex row) const;
173
174 // Returns the type of variable.
175 VariableType GetVariableType(ColIndex col) const;
176
177 // Returns true (resp. false) when the problem is a maximization
178 // (resp. minimization) problem.
179 bool IsMaximizationProblem() const { return maximize_; }
180
181 // Returns the underlying SparseMatrix or its transpose (which may need to be
182 // computed).
183 const SparseMatrix& GetSparseMatrix() const { return matrix_; }
185
186 // Some transformations are better done on the transpose representation. These
187 // two functions are here for that. Note that calling the first function and
188 // modifying the matrix does not change the result of any function in this
189 // class until UseTransposeMatrixAsReference() is called. This is because the
190 // transpose matrix is only used by GetTransposeSparseMatrix() and this
191 // function will recompute the whole transpose from the matrix. In particular,
192 // do not call GetTransposeSparseMatrix() while you modify the matrix returned
193 // by GetMutableTransposeSparseMatrix() otherwise all your changes will be
194 // lost.
195 //
196 // IMPORTANT: The matrix dimension cannot change. Otherwise this will cause
197 // problems. This is checked in debug mode when calling
198 // UseTransposeMatrixAsReference().
201
202 // Release the memory used by the transpose matrix.
204
205 // Gets the underlying SparseColumn with the given index.
206 // This is the same as GetSparseMatrix().column(col);
207 const SparseColumn& GetSparseColumn(ColIndex col) const;
208
209 // Gets a pointer to the underlying SparseColumn with the given index.
211
212 // Returns the number of variables.
213 ColIndex num_variables() const { return matrix_.num_cols(); }
214
215 // Returns the number of constraints.
216 RowIndex num_constraints() const { return matrix_.num_rows(); }
217
218 // Returns the number of entries in the linear program matrix.
219 EntryIndex num_entries() const { return matrix_.num_entries(); }
220
221 // Return the lower bounds (resp. upper bounds) of constraints as a column
222 // vector. Note that the bound values may be +/- infinity.
224 return constraint_lower_bounds_;
225 }
227 return constraint_upper_bounds_;
228 }
229
230 // Returns the objective coefficients (or cost) of variables as a row vector.
232 return objective_coefficients_;
233 }
234
235 // Return the lower bounds (resp. upper bounds) of variables as a row vector.
236 // Note that the bound values may be +/- infinity.
238 return variable_lower_bounds_;
239 }
241 return variable_upper_bounds_;
242 }
243
244 // Returns a row vector of VariableType representing types of variables.
246 return variable_types_;
247 }
248
249 // Returns a list (technically a vector) of the ColIndices of the integer
250 // variables. This vector is lazily computed.
251 const std::vector<ColIndex>& IntegerVariablesList() const;
252
253 // Returns a list (technically a vector) of the ColIndices of the binary
254 // integer variables. This vector is lazily computed.
255 const std::vector<ColIndex>& BinaryVariablesList() const;
256
257 // Returns a list (technically a vector) of the ColIndices of the non-binary
258 // integer variables. This vector is lazily computed.
259 const std::vector<ColIndex>& NonBinaryVariablesList() const;
260
261 // Returns the objective coefficient (or cost) of the given variable for the
262 // minimization version of the problem. That is, this is the same as
263 // GetObjectiveCoefficient() for a minimization problem and the opposite for a
264 // maximization problem.
266
267 // Returns the objective offset and scaling factor.
268 Fractional objective_offset() const { return objective_offset_; }
270 return objective_scaling_factor_;
271 }
272
273 // Checks if each variable respects its bounds, nothing else.
275 Fractional absolute_tolerance) const;
276
277 // Tests if the solution is LP-feasible within the given tolerance,
278 // i.e., satisfies all linear constraints within the absolute tolerance level.
279 // The solution does not need to satisfy the integer constraints.
281 Fractional absolute_tolerance) const;
282
283 // Tests if the solution is integer within the given tolerance, i.e., all
284 // integer variables have integer values within the absolute tolerance level.
285 // The solution does not need to satisfy the linear constraints.
287 Fractional absolute_tolerance) const;
288
289 // Tests if the solution is both LP-feasible and integer within the tolerance.
291 Fractional absolute_tolerance) const;
292
293 // Fills the value of the slack from the other variable values.
294 // This requires that the slack have been added.
296
297 // Functions to translate the sum(solution * objective_coefficients()) to
298 // the real objective of the problem and back. Note that these can also
299 // be used to translate bounds of the objective in the same way.
302
303 // A short string with the problem dimension.
304 std::string GetDimensionString() const;
305
306 // A short line with some stats on the problem coefficients.
307 std::string GetObjectiveStatsString() const;
308 std::string GetBoundsStatsString() const;
309
310 // Returns a stringified LinearProgram. We use the LP file format used by
311 // lp_solve (see http://lpsolve.sourceforge.net/5.1/index.htm).
312 std::string Dump() const;
313
314 // Returns a string that contains the provided solution of the LP in the
315 // format var1 = X, var2 = Y, var3 = Z, ...
316 std::string DumpSolution(const DenseRow& variable_values) const;
317
318 // Returns a comma-separated string of integers containing (in that order)
319 // num_constraints_, num_variables_in_file_, num_entries_,
320 // num_objective_non_zeros_, num_rhs_non_zeros_, num_less_than_constraints_,
321 // num_greater_than_constraints_, num_equal_constraints_,
322 // num_range_constraints_, num_non_negative_variables_, num_boxed_variables_,
323 // num_free_variables_, num_fixed_variables_, num_other_variables_
324 // Very useful for reporting in the way used in journal articles.
325 std::string GetProblemStats() const;
326
327 // Returns a string containing the same information as with GetProblemStats(),
328 // but in a much more human-readable form, for example:
329 // Number of rows : 27
330 // Number of variables in file : 32
331 // Number of entries (non-zeros) : 83
332 // Number of entries in the objective : 5
333 // Number of entries in the right-hand side : 7
334 // Number of <= constraints : 19
335 // Number of >= constraints : 0
336 // Number of = constraints : 8
337 // Number of range constraints : 0
338 // Number of non-negative variables : 32
339 // Number of boxed variables : 0
340 // Number of free variables : 0
341 // Number of fixed variables : 0
342 // Number of other variables : 0
343 std::string GetPrettyProblemStats() const;
344
345 // Returns a comma-separated string of numbers containing (in that order)
346 // fill rate, max number of entries (length) in a row, average row length,
347 // standard deviation of row length, max column length, average column length,
348 // standard deviation of column length
349 // Useful for profiling algorithms.
350 //
351 // TODO(user): Theses are statistics about the underlying matrix and should be
352 // moved to SparseMatrix.
353 std::string GetNonZeroStats() const;
354
355 // Returns a string containing the same information as with GetNonZeroStats(),
356 // but in a much more human-readable form, for example:
357 // Fill rate : 9.61%
358 // Entries in row (Max / average / std, dev.) : 9 / 3.07 / 1.94
359 // Entries in column (Max / average / std, dev.): 4 / 2.59 / 0.96
360 std::string GetPrettyNonZeroStats() const;
361
362 // Adds slack variables to the problem for all rows which don't have slack
363 // variables. The new slack variables have bounds set to opposite of the
364 // bounds of the corresponding constraint, and changes all constraints to
365 // equality constraints with both bounds set to 0.0. If a constraint uses only
366 // integer variables and all their coefficients are integer, it will mark the
367 // slack variable as integer too.
368 //
369 // It is an error to call CreateNewVariable() or CreateNewConstraint() on a
370 // linear program on which this method was called.
371 //
372 // Note that many of the slack variables may not be useful at all, but in
373 // order not to recompute the matrix from one Solve() to the next, we always
374 // include all of them for a given lp matrix.
375 //
376 // TODO(user): investigate the impact on the running time. It seems low
377 // because we almost never iterate on fixed variables.
378 void AddSlackVariablesWhereNecessary(bool detect_integer_constraints);
379
380 // Returns the index of the first slack variable in the linear program.
381 // Returns kInvalidCol if slack variables were not injected into the problem
382 // yet.
383 ColIndex GetFirstSlackVariable() const;
384
385 // Returns the index of the slack variable corresponding to the given
386 // constraint. Returns kInvalidCol if slack variables were not injected into
387 // the problem yet.
388 ColIndex GetSlackVariable(RowIndex row) const;
389
390 // Populates the calling object with the dual of the LinearProgram passed as
391 // parameter.
392 // For the general form that we solve,
393 // min c.x
394 // s.t. A_1 x = b_1
395 // A_2 x <= b_2
396 // A_3 x >= b_3
397 // l <= x <= u
398 // With x: n-column of unknowns
399 // l,u: n-columns of bound coefficients
400 // c: n-row of cost coefficients
401 // A_i: m_i×n-matrix of coefficients
402 // b_i: m_i-column of right-hand side coefficients
403 //
404 // The dual is
405 //
406 // max b_1.y_1 + b_2.y_2 + b_3.y_3 + l.v + u.w
407 // s.t. y_1 A_1 + y_2 A_2 + y_3 A_3 + v + w = c
408 // y_1 free, y_2 <= 0, y_3 >= 0, v >= 0, w <= 0
409 // With:
410 // y_i: m_i-row of unknowns
411 // v,w: n-rows of unknowns
412 //
413 // If range constraints are present, each of the corresponding row is
414 // duplicated (with one becoming lower bounded and the other upper bounded).
415 // For such ranged row in the primal, duplicated_rows[row] is set to the
416 // column index in the dual of the corresponding column duplicate. For
417 // non-ranged row, duplicated_rows[row] is set to kInvalidCol.
418 //
419 // IMPORTANT: The linear_program argument must not have any free constraints.
420 //
421 // IMPORTANT: This function always interprets the argument in its minimization
422 // form. So the dual solution of the dual needs to be negated if we want to
423 // compute the solution of a maximization problem given as an argument.
424 //
425 // TODO(user): Do not interpret as a minimization problem?
426 void PopulateFromDual(const LinearProgram& dual,
427 RowToColMapping* duplicated_rows);
428
429 // Populates the calling object with the given LinearProgram.
430 void PopulateFromLinearProgram(const LinearProgram& linear_program);
431
432 // Populates the calling object with the given LinearProgram while permuting
433 // variables and constraints. This is useful mainly for testing to generate
434 // a model with the same optimal objective value.
436 const LinearProgram& lp, const RowPermutation& row_permutation,
437 const ColumnPermutation& col_permutation);
438
439 // Populates the calling object with the variables of the given LinearProgram.
440 // The function preserves the bounds, the integrality, the names of the
441 // variables and their objective coefficients. No constraints are copied (the
442 // matrix in the destination has 0 rows).
443 void PopulateFromLinearProgramVariables(const LinearProgram& linear_program);
444
445 // Adds constraints to the linear program. The constraints are specified using
446 // a sparse matrix of the coefficients, and vectors that represent the
447 // left-hand side and the right-hand side of the constraints, i.e.
448 // left_hand_sides <= coefficients * variables <= right_hand_sides.
449 // The sizes of the columns and the names must be the same as the number of
450 // rows of the sparse matrix; the number of columns of the matrix must be
451 // equal to the number of variables of the linear program.
453 const DenseColumn& left_hand_sides,
454 const DenseColumn& right_hand_sides,
456
457 // Calls the AddConstraints method. After adding the constraints it adds slack
458 // variables to the constraints.
460 const SparseMatrix& coefficients, const DenseColumn& left_hand_sides,
461 const DenseColumn& right_hand_sides,
463 bool detect_integer_constraints_for_slack);
464
465 // Swaps the content of this LinearProgram with the one passed as argument.
466 // Works in O(1).
467 void Swap(LinearProgram* linear_program);
468
469 // Removes the given column indices from the LinearProgram.
470 // This needs to allocate O(num_variables) memory to update variable_table_.
471 void DeleteColumns(const DenseBooleanRow& columns_to_delete);
472
473 // Removes slack variables from the linear program. The method restores the
474 // bounds on constraints from the bounds of the slack variables, resets the
475 // index of the first slack variable, and removes the relevant columns from
476 // the matrix.
478
479 // Scales the problem using the given scaler.
481
482 // While Scale() makes sure the coefficients inside the linear program matrix
483 // are in [-1, 1], the objective coefficients, variable bounds and constraint
484 // bounds can still take large values (originally or due to the matrix
485 // scaling).
486 //
487 // It makes a lot of sense to also scale them given that internally we use
488 // absolute tolerances, and that it is nice to have the same behavior if users
489 // scale their problems. For instance one could change the unit of ALL the
490 // variables from Bytes to MBytes if they denote memory quantities. Or express
491 // a cost in dollars instead of thousands of dollars.
492 //
493 // Here, we are quite prudent and just make sure that the range of the
494 // non-zeros magnitudes contains one. So for instance if all non-zeros costs
495 // are in [1e4, 1e6], we will divide them by 1e4 so that the new range is
496 // [1, 1e2].
497 //
498 // TODO(user): Another more aggressive idea is to set the median/mean/geomean
499 // of the magnitudes to one. Investigate if this leads to better results. It
500 // does look more robust.
501 //
502 // Both functions update objective_scaling_factor()/objective_offset() and
503 // return the scaling coefficient so that:
504 // - For ScaleObjective(), the old coefficients can be retrieved by
505 // multiplying the new ones by the returned factor.
506 // - For ScaleBounds(), the old variable and constraint bounds can be
507 // retrieved by multiplying the new ones by the returned factor.
508 Fractional ScaleObjective(GlopParameters::CostScalingAlgorithm method);
510
511 // Removes the given row indices from the LinearProgram.
512 // This needs to allocate O(num_variables) memory.
513 void DeleteRows(const DenseBooleanColumn& rows_to_delete);
514
515 // Does basic checking on the linear program:
516 // - returns false if some coefficient are NaNs.
517 // - returns false if some coefficient other than the bounds are +/- infinity.
518 // Note that these conditions are also guarded by DCHECK on each of the
519 // SetXXX() function above.
520 //
521 // This also returns false if any finite value has a magnitude larger than
522 // the given threshold.
523 bool IsValid(Fractional max_valid_magnitude = kInfinity) const;
524
525 // Updates the bounds of the variables to the intersection of their original
526 // bounds and the bounds specified by variable_lower_bounds and
527 // variable_upper_bounds. If the new bounds of all variables are non-empty,
528 // returns true; otherwise, returns false.
532
533 // Returns true if the linear program is in equation form Ax = 0 and all slack
534 // variables have been added. This is also called "computational form" in some
535 // of the literature.
536 bool IsInEquationForm() const;
537
538 // Returns true if all integer variables in the linear program have strictly
539 // integer bounds.
541
542 // Returns true if all integer constraints in the linear program have strictly
543 // integer bounds.
545
546 // Advanced usage. Bypass the costly call to CleanUp() when we known that the
547 // change we made kept the matrix columns "clean" (see the comment of
548 // CleanUp()). This is unsafe but can save a big chunk of the running time
549 // when one does a small amount of incremental changes to the problem (like
550 // adding a new row with no duplicates or zero entries).
552 DCHECK(matrix_.IsCleanedUp());
553 columns_are_known_to_be_clean_ = true;
554 }
555
556 // If true, checks bound validity in debug mode.
557 void SetDcheckBounds(bool dcheck_bounds) { dcheck_bounds_ = dcheck_bounds; }
558
559 // In our presolve, the calls and the extra test inside SetConstraintBounds()
560 // can be visible when a lot of substitutions are performed.
562 return &constraint_lower_bounds_;
563 }
565 return &constraint_upper_bounds_;
566 }
567
568 // Removes objective and coefficient with magnitude <= threshold.
569 void RemoveNearZeroEntries(Fractional threshold);
570
571 private:
572 // A helper function that updates the vectors integer_variables_list_,
573 // binary_variables_list_, and non_binary_variables_list_.
574 void UpdateAllIntegerVariableLists() const;
575
576 // A helper function to format problem statistics. Used by GetProblemStats()
577 // and GetPrettyProblemStats().
578 std::string ProblemStatFormatter(absl::string_view format) const;
579
580 // A helper function to format non-zero statistics. Used by GetNonZeroStats()
581 // and GetPrettyNonZeroStats().
582 std::string NonZeroStatFormatter(absl::string_view format) const;
583
584 // Resizes all row vectors to include index 'row'.
585 void ResizeRowsIfNeeded(RowIndex row);
586
587 // Populates the definitions of variables, name and objective in the calling
588 // linear program with the data from the given linear program. The method does
589 // not touch the data structures for storing constraints.
590 void PopulateNameObjectiveAndVariablesFromLinearProgram(
591 const LinearProgram& linear_program);
592
593 // Stores the linear program coefficients.
594 SparseMatrix matrix_;
595
596 // The transpose of matrix_. This will be lazily recomputed by
597 // GetTransposeSparseMatrix() if transpose_matrix_is_consistent_ is false.
598 mutable SparseMatrix transpose_matrix_;
599
600 // Constraint related quantities.
601 DenseColumn constraint_lower_bounds_;
602 DenseColumn constraint_upper_bounds_;
604
605 // Variable related quantities.
606 DenseRow objective_coefficients_;
607 DenseRow variable_lower_bounds_;
608 DenseRow variable_upper_bounds_;
611
612 // The vector of the indices of variables constrained to be integer.
613 // Note(user): the set of indices in integer_variables_list_ is the union
614 // of the set of indices in binary_variables_list_ and of the set of indices
615 // in non_binary_variables_list_ below.
616 mutable std::vector<ColIndex> integer_variables_list_;
617
618 // The vector of the indices of variables constrained to be binary.
619 mutable std::vector<ColIndex> binary_variables_list_;
620
621 // The vector of the indices of variables constrained to be integer, but not
622 // binary.
623 mutable std::vector<ColIndex> non_binary_variables_list_;
624
625 // Map used to find the index of a variable based on its id.
626 absl::flat_hash_map<std::string, ColIndex> variable_table_;
627
628 // Map used to find the index of a constraint based on its id.
629 absl::flat_hash_map<std::string, RowIndex> constraint_table_;
630
631 // Offset of the objective, i.e. value of the objective when all variables
632 // are set to zero.
633 Fractional objective_offset_;
634 Fractional objective_scaling_factor_;
635
636 // Boolean true (resp. false) when the problem is a maximization
637 // (resp. minimization) problem.
638 bool maximize_;
639
640 // Boolean to speed-up multiple calls to IsCleanedUp() or
641 // CleanUp(). Mutable so IsCleanedUp() can be const.
642 mutable bool columns_are_known_to_be_clean_;
643
644 // Whether transpose_matrix_ is guaranteed to be the transpose of matrix_.
645 mutable bool transpose_matrix_is_consistent_;
646
647 // Whether integer_variables_list_ is consistent with the current
648 // LinearProgram.
649 mutable bool integer_variables_list_is_consistent_;
650
651 // The name of the LinearProgram.
652 std::string name_;
653
654 // The index of the first slack variable added to the linear program by
655 // LinearProgram::AddSlackVariablesForAllRows().
656 ColIndex first_slack_variable_;
657
658 // If true, checks bounds in debug mode.
659 bool dcheck_bounds_ = true;
660
661 friend void Scale(LinearProgram* lp, SparseMatrixScaler* scaler,
662 GlopParameters::ScalingAlgorithm scaling_method);
663};
664
665// --------------------------------------------------------
666// ProblemSolution
667// --------------------------------------------------------
668// Contains the solution of a LinearProgram as returned by a preprocessor.
669struct ProblemSolution {
670 ProblemSolution(RowIndex num_rows, ColIndex num_cols)
672 primal_values(num_cols, 0.0),
673 dual_values(num_rows, 0.0),
676 // The solution status.
678
679 // The actual primal/dual solution values. This is what most clients will
680 // need, and this is enough for LPSolver to easily check the optimality.
684 // The status of the variables and constraints which is difficult to
685 // reconstruct from the solution values alone. Some remarks:
686 // - From this information alone, by factorizing the basis, it is easy to
687 // reconstruct the primal and dual values.
688 // - The main difficulty to construct this from the solution values is to
689 // reconstruct the optimal basis if some basic variables are exactly at
690 // one of their bounds (and their reduced costs are close to zero).
691 // - The non-basic information (VariableStatus::FIXED_VALUE,
692 // VariableStatus::AT_LOWER_BOUND, VariableStatus::AT_UPPER_BOUND,
693 // VariableStatus::FREE) is easy to construct for variables (because
694 // they are at their exact bounds). They can be guessed for constraints
695 // (here a small precision error is unavoidable). However, it is useful to
696 // carry this exact information during post-solve.
700 std::string DebugString() const;
701};
702
703// Helper function to check the bounds of the SetVariableBounds() and
704// SetConstraintBounds() functions.
706 if (std::isnan(lower_bound)) return false;
707 if (std::isnan(upper_bound)) return false;
708 if (lower_bound == kInfinity && upper_bound == kInfinity) return false;
709 if (lower_bound == -kInfinity && upper_bound == -kInfinity) return false;
710 if (lower_bound > upper_bound) return false;
711 return true;
712}
713
714} // namespace glop
715} // namespace operations_research
716
717#endif // OR_TOOLS_LP_DATA_LP_DATA_H_
void SetName(absl::string_view name)
Name setter and getter.
Definition lp_data.h:82
bool BoundsOfIntegerConstraintsAreInteger(Fractional tolerance) const
Definition lp_data.cc:1523
std::string GetDimensionString() const
A short string with the problem dimension.
Definition lp_data.cc:434
const DenseRow & objective_coefficients() const
Returns the objective coefficients (or cost) of variables as a row vector.
Definition lp_data.h:231
void Clear()
Clears, i.e. reset the object to its initial value.
Definition lp_data.cc:143
void SetConstraintName(RowIndex row, absl::string_view name)
Definition lp_data.cc:254
const std::vector< ColIndex > & NonBinaryVariablesList() const
Definition lp_data.cc:299
friend void Scale(LinearProgram *lp, SparseMatrixScaler *scaler, GlopParameters::ScalingAlgorithm scaling_method)
@ INTEGER
The variable must only take integer values.
StrictITIVector< ColIndex, VariableType > variable_types() const
Returns a row vector of VariableType representing types of variables.
Definition lp_data.h:245
std::string GetPrettyNonZeroStats() const
Definition lp_data.cc:701
void DeleteColumns(const DenseBooleanRow &columns_to_delete)
Definition lp_data.cc:1076
void RemoveNearZeroEntries(Fractional threshold)
Removes objective and coefficient with magnitude <= threshold.
Definition lp_data.cc:1561
bool BoundsOfIntegerVariablesAreInteger(Fractional tolerance) const
Definition lp_data.cc:1507
void ComputeSlackVariableValues(DenseRow *solution) const
Definition lp_data.cc:544
bool IsValid(Fractional max_valid_magnitude=kInfinity) const
Definition lp_data.cc:1316
Fractional GetObjectiveCoefficientForMinimizationVersion(ColIndex col) const
Definition lp_data.cc:428
void PopulateFromPermutedLinearProgram(const LinearProgram &lp, const RowPermutation &row_permutation, const ColumnPermutation &col_permutation)
Definition lp_data.cc:894
void PopulateFromLinearProgramVariables(const LinearProgram &linear_program)
Definition lp_data.cc:946
bool SolutionIsInteger(const DenseRow &solution, Fractional absolute_tolerance) const
Definition lp_data.cc:526
void SetObjectiveOffset(Fractional objective_offset)
Definition lp_data.cc:340
std::string GetConstraintName(RowIndex row) const
Definition lp_data.cc:375
DenseColumn * mutable_constraint_upper_bounds()
Definition lp_data.h:564
void SetObjectiveCoefficient(ColIndex col, Fractional value)
Definition lp_data.cc:335
bool SolutionIsLPFeasible(const DenseRow &solution, Fractional absolute_tolerance) const
Definition lp_data.cc:506
std::string GetPrettyProblemStats() const
Definition lp_data.cc:675
void Scale(SparseMatrixScaler *scaler)
Scales the problem using the given scaler.
const std::string & name() const
Definition lp_data.h:83
bool SolutionIsWithinVariableBounds(const DenseRow &solution, Fractional absolute_tolerance) const
Checks if each variable respects its bounds, nothing else.
Definition lp_data.cc:490
Fractional RemoveObjectiveScalingAndOffset(Fractional value) const
Definition lp_data.cc:564
void SetObjectiveScalingFactor(Fractional objective_scaling_factor)
Definition lp_data.cc:345
const DenseColumn & constraint_lower_bounds() const
Definition lp_data.h:223
const SparseMatrix & GetTransposeSparseMatrix() const
Definition lp_data.cc:385
void AddSlackVariablesWhereNecessary(bool detect_integer_constraints)
Definition lp_data.cc:708
void ClearTransposeMatrix()
Release the memory used by the transpose matrix.
Definition lp_data.cc:413
const DenseRow & variable_lower_bounds() const
Definition lp_data.h:237
void SetVariableBounds(ColIndex col, Fractional lower_bound, Fractional upper_bound)
Definition lp_data.cc:258
ColIndex GetSlackVariable(RowIndex row) const
Definition lp_data.cc:766
const std::vector< ColIndex > & BinaryVariablesList() const
Definition lp_data.cc:294
EntryIndex num_entries() const
Returns the number of entries in the linear program matrix.
Definition lp_data.h:219
DenseColumn * mutable_constraint_lower_bounds()
Definition lp_data.h:561
SparseMatrix * GetMutableTransposeSparseMatrix()
Definition lp_data.cc:395
SparseColumn * GetMutableSparseColumn(ColIndex col)
Gets a pointer to the underlying SparseColumn with the given index.
Definition lp_data.cc:422
const SparseMatrix & GetSparseMatrix() const
Definition lp_data.h:183
void AddConstraintsWithSlackVariables(const SparseMatrix &coefficients, const DenseColumn &left_hand_sides, const DenseColumn &right_hand_sides, const StrictITIVector< RowIndex, std::string > &names, bool detect_integer_constraints_for_slack)
Definition lp_data.cc:1008
const std::vector< ColIndex > & IntegerVariablesList() const
Definition lp_data.cc:289
bool IsVariableBinary(ColIndex col) const
Returns whether the variable at column col must take binary values or not.
Definition lp_data.cc:309
Fractional ScaleObjective(GlopParameters::CostScalingAlgorithm method)
Definition lp_data.cc:1199
void Swap(LinearProgram *linear_program)
Definition lp_data.cc:1042
void DeleteRows(const DenseBooleanColumn &rows_to_delete)
Definition lp_data.cc:1269
void SetVariableType(ColIndex col, VariableType type)
Set the type of the variable.
Definition lp_data.cc:245
ColIndex FindOrCreateVariable(absl::string_view variable_id)
Definition lp_data.cc:214
std::string DumpSolution(const DenseRow &variable_values) const
Definition lp_data.cc:658
bool SolutionIsMIPFeasible(const DenseRow &solution, Fractional absolute_tolerance) const
Tests if the solution is both LP-feasible and integer within the tolerance.
Definition lp_data.cc:538
void SetConstraintBounds(RowIndex row, Fractional lower_bound, Fractional upper_bound)
Definition lp_data.cc:318
void SetCoefficient(RowIndex row, ColIndex col, Fractional value)
Defines the coefficient for col / row.
Definition lp_data.cc:326
std::string GetVariableName(ColIndex col) const
Definition lp_data.cc:369
LinearProgram(const LinearProgram &)=delete
This type is neither copyable nor movable.
const DenseRow & variable_upper_bounds() const
Definition lp_data.h:240
void AddConstraints(const SparseMatrix &coefficients, const DenseColumn &left_hand_sides, const DenseColumn &right_hand_sides, const StrictITIVector< RowIndex, std::string > &names)
Definition lp_data.cc:983
void SetVariableName(ColIndex col, absl::string_view name)
Definition lp_data.cc:241
ColIndex CreateNewSlackVariable(bool is_integer_slack_variable, Fractional lower_bound, Fractional upper_bound, const std::string &name)
Definition lp_data.cc:185
VariableType GetVariableType(ColIndex col) const
Returns the type of variable.
Definition lp_data.cc:381
const DenseColumn & constraint_upper_bounds() const
Definition lp_data.h:226
const SparseColumn & GetSparseColumn(ColIndex col) const
Definition lp_data.cc:418
bool IsVariableInteger(ColIndex col) const
Returns whether the variable at column col is constrained to be integer.
Definition lp_data.cc:304
void PopulateFromLinearProgram(const LinearProgram &linear_program)
Populates the calling object with the given LinearProgram.
Definition lp_data.cc:873
bool UpdateVariableBoundsToIntersection(const DenseRow &variable_lower_bounds, const DenseRow &variable_upper_bounds)
Definition lp_data.cc:1017
LinearProgram & operator=(const LinearProgram &)=delete
void SetDcheckBounds(bool dcheck_bounds)
If true, checks bound validity in debug mode.
Definition lp_data.h:557
Fractional objective_scaling_factor() const
Definition lp_data.h:269
Fractional ApplyObjectiveScalingAndOffset(Fractional value) const
Definition lp_data.cc:559
ColIndex num_variables() const
Returns the number of variables.
Definition lp_data.h:213
std::string GetObjectiveStatsString() const
A short line with some stats on the problem coefficients.
Definition lp_data.cc:461
Fractional objective_offset() const
Returns the objective offset and scaling factor.
Definition lp_data.h:268
RowIndex num_constraints() const
Returns the number of constraints.
Definition lp_data.h:216
std::string GetBoundsStatsString() const
Definition lp_data.cc:474
RowIndex FindOrCreateConstraint(absl::string_view constraint_id)
Definition lp_data.cc:227
void PopulateFromDual(const LinearProgram &dual, RowToColMapping *duplicated_rows)
Definition lp_data.cc:775
void SetMaximizationProblem(bool maximize)
Definition lp_data.cc:352
bool IsCleanedUp() const
Call IsCleanedUp() on all columns, useful for doing a DCHECK.
Definition sparse.cc:144
RowIndex num_rows() const
Return the matrix dimension.
Definition sparse.h:190
int64_t value
double upper_bound
double lower_bound
absl::Span< const double > coefficients
ColIndex col
Definition markowitz.cc:187
RowIndex row
Definition markowitz.cc:186
double solution
bool AreBoundsValid(Fractional lower_bound, Fractional upper_bound)
Definition lp_data.h:707
VariableType
Different types of variables.
Definition lp_types.h:180
ProblemStatus
Different statuses for a given problem.
Definition lp_types.h:107
In SWIG mode, we don't want anything besides these top-level includes.
ConstraintStatusColumn constraint_statuses
Definition lp_data.h:700
ProblemSolution(RowIndex num_rows, ColIndex num_cols)
Definition lp_data.h:672
ProblemStatus status
The solution status.
Definition lp_data.h:679