14"""The solution to an optimization problem defined by Model in model.py."""
17from typing
import Dict, Optional, TypeVar
26 """Status of a variable/constraint in a LP basis.
29 FREE: The variable/constraint is free (it has no finite bounds).
30 AT_LOWER_BOUND: The variable/constraint is at its lower bound (which must be
32 AT_UPPER_BOUND: The variable/constraint is at its upper bound (which must be
34 FIXED_VALUE: The variable/constraint has identical finite lower and upper
36 BASIC: The variable/constraint is basic.
39 FREE = solution_pb2.BASIS_STATUS_FREE
40 AT_LOWER_BOUND = solution_pb2.BASIS_STATUS_AT_LOWER_BOUND
41 AT_UPPER_BOUND = solution_pb2.BASIS_STATUS_AT_UPPER_BOUND
42 FIXED_VALUE = solution_pb2.BASIS_STATUS_FIXED_VALUE
43 BASIC = solution_pb2.BASIS_STATUS_BASIC
48 """Feasibility of a primal or dual solution as claimed by the solver.
51 UNDETERMINED: Solver does not claim a feasibility status.
52 FEASIBLE: Solver claims the solution is feasible.
53 INFEASIBLE: Solver claims the solution is infeasible.
56 UNDETERMINED = solution_pb2.SOLUTION_STATUS_UNDETERMINED
57 FEASIBLE = solution_pb2.SOLUTION_STATUS_FEASIBLE
58 INFEASIBLE = solution_pb2.SOLUTION_STATUS_INFEASIBLE
62 proto: solution_pb2.SolutionStatusProto,
63) -> Optional[SolutionStatus]:
64 """Converts a proto SolutionStatus to an optional Python SolutionStatus."""
67 if proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED
73 status: Optional[SolutionStatus],
74) -> solution_pb2.SolutionStatusProto:
75 """Converts an optional Python SolutionStatus to a proto SolutionStatus."""
76 return solution_pb2.SOLUTION_STATUS_UNSPECIFIED
if status
is None else status.value
81 """A solution to the optimization problem in a Model.
83 E.g. consider a simple linear program:
87 A primal solution is assignment values to x. It is feasible if it satisfies
88 A * x >= b and x >= 0 from above. In the class PrimalSolution variable_values
89 is x and objective_value is c * x.
91 For the general case of a MathOpt optimization model, see go/mathopt-solutions
95 variable_values: The value assigned for each Variable in the model.
96 objective_value: The value of the objective value at this solution. This
97 value may not be always populated.
98 feasibility_status: The feasibility of the solution as claimed by the
105 objective_value: float = 0.0
106 feasibility_status: SolutionStatus = SolutionStatus.UNDETERMINED
108 def to_proto(self) -> solution_pb2.PrimalSolutionProto:
109 """Returns an equivalent proto for a primal solution."""
110 return solution_pb2.PrimalSolutionProto(
111 variable_values=sparse_containers.to_sparse_double_vector_proto(
120 proto: solution_pb2.PrimalSolutionProto, mod:
model.Model
122 """Returns an equivalent PrimalSolution from the input proto."""
124 result.objective_value = proto.objective_value
125 result.variable_values = sparse_containers.parse_variable_map(
126 proto.variable_values, mod
128 status_proto = proto.feasibility_status
129 if status_proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED:
130 raise ValueError(
"Primal solution feasibility status should not be UNSPECIFIED")
135@dataclasses.dataclass
137 """A direction of unbounded objective improvement in an optimization Model.
139 Equivalently, a certificate of infeasibility for the dual of the optimization
142 E.g. consider a simple linear program:
146 A primal ray is an x that satisfies:
150 Observe that given a feasible solution, any positive multiple of the primal
151 ray plus that solution is still feasible, and gives a better objective
152 value. A primal ray also proves the dual optimization problem infeasible.
154 In the class PrimalRay, variable_values is this x.
156 For the general case of a MathOpt optimization model, see
157 go/mathopt-solutions for details.
160 variable_values: The value assigned for each Variable in the model.
168 """Returns an equivalent proto to this PrimalRay."""
169 return solution_pb2.PrimalRayProto(
170 variable_values=sparse_containers.to_sparse_double_vector_proto(
177 """Returns an equivalent PrimalRay from the input proto."""
179 result.variable_values = sparse_containers.parse_variable_map(
180 proto.variable_values, mod
185@dataclasses.dataclass
187 """A solution to the dual of the optimization problem given by a Model.
189 E.g. consider the primal dual pair linear program pair:
192 s.t. A * x >= b s.t. y * A + r = c
194 The dual solution is the pair (y, r). It is feasible if it satisfies the
195 constraints from (Dual) above.
197 Below, y is dual_values, r is reduced_costs, and b * y is objective_value.
199 For the general case, see go/mathopt-solutions and go/mathopt-dual (and note
200 that the dual objective depends on r in the general case).
203 dual_values: The value assigned for each LinearConstraint in the model.
204 reduced_costs: The value assigned for each Variable in the model.
205 objective_value: The value of the dual objective value at this solution.
206 This value may not be always populated.
207 feasibility_status: The feasibility of the solution as claimed by the
214 reduced_costs: Dict[
model.Variable, float] = dataclasses.field(default_factory=dict)
215 objective_value: Optional[float] =
None
216 feasibility_status: SolutionStatus = SolutionStatus.UNDETERMINED
218 def to_proto(self) -> solution_pb2.DualSolutionProto:
219 """Returns an equivalent proto for a dual solution."""
220 return solution_pb2.DualSolutionProto(
221 dual_values=sparse_containers.to_sparse_double_vector_proto(
224 reduced_costs=sparse_containers.to_sparse_double_vector_proto(
233 proto: solution_pb2.DualSolutionProto, mod:
model.Model
235 """Returns an equivalent DualSolution from the input proto."""
237 result.objective_value = (
238 proto.objective_value
if proto.HasField(
"objective_value")
else None
240 result.dual_values = sparse_containers.parse_linear_constraint_map(
241 proto.dual_values, mod
243 result.reduced_costs = sparse_containers.parse_variable_map(
244 proto.reduced_costs, mod
246 status_proto = proto.feasibility_status
247 if status_proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED:
248 raise ValueError(
"Dual solution feasibility status should not be UNSPECIFIED")
253@dataclasses.dataclass
255 """A direction of unbounded objective improvement in an optimization Model.
257 A direction of unbounded improvement to the dual of an optimization,
258 problem; equivalently, a certificate of primal infeasibility.
260 E.g. consider the primal dual pair linear program pair:
263 s.t. A * x >= b s.t. y * A + r = c
266 The dual ray is the pair (y, r) satisfying:
270 Observe that adding a positive multiple of (y, r) to dual feasible solution
271 maintains dual feasibility and improves the objective (proving the dual is
272 unbounded). The dual ray also proves the primal problem is infeasible.
274 In the class DualRay below, y is dual_values and r is reduced_costs.
276 For the general case, see go/mathopt-solutions and go/mathopt-dual (and note
277 that the dual objective depends on r in the general case).
280 dual_values: The value assigned for each LinearConstraint in the model.
281 reduced_costs: The value assigned for each Variable in the model.
287 reduced_costs: Dict[
model.Variable, float] = dataclasses.field(default_factory=dict)
290 """Returns an equivalent proto to this PrimalRay."""
291 return solution_pb2.DualRayProto(
292 dual_values=sparse_containers.to_sparse_double_vector_proto(
295 reduced_costs=sparse_containers.to_sparse_double_vector_proto(
302 """Returns an equivalent DualRay from the input proto."""
304 result.dual_values = sparse_containers.parse_linear_constraint_map(
305 proto.dual_values, mod
307 result.reduced_costs = sparse_containers.parse_variable_map(
308 proto.reduced_costs, mod
313@dataclasses.dataclass
315 """A combinatorial characterization for a solution to a linear program.
317 The simplex method for solving linear programs always returns a "basic
318 feasible solution" which can be described combinatorially as a Basis. A basis
319 assigns a BasisStatus for every variable and linear constraint.
321 E.g. consider a standard form LP:
325 that has more variables than constraints and with full row rank A.
327 Let n be the number of variables and m the number of linear constraints. A
328 valid basis for this problem can be constructed as follows:
329 * All constraints will have basis status FIXED.
330 * Pick m variables such that the columns of A are linearly independent and
331 assign the status BASIC.
332 * Assign the status AT_LOWER for the remaining n - m variables.
334 The basic solution for this basis is the unique solution of A * x = b that has
335 all variables with status AT_LOWER fixed to their lower bounds (all zero). The
336 resulting solution is called a basic feasible solution if it also satisfies
339 See go/mathopt-basis for treatment of the general case and an explanation of
340 how a dual solution is determined for a basis.
343 variable_status: The basis status for each variable in the model.
344 constraint_status: The basis status for each linear constraint in the model.
345 basic_dual_feasibility: This is an advanced feature used by MathOpt to
346 characterize feasibility of suboptimal LP solutions (optimal solutions
347 will always have status SolutionStatus.FEASIBLE). For single-sided LPs it
348 should be equal to the feasibility status of the associated dual solution.
349 For two-sided LPs it may be different in some edge cases (e.g. incomplete
350 solves with primal simplex). For more details see
351 go/mathopt-basis-advanced#dualfeasibility. If you are providing a starting
352 basis via ModelSolveParameters.initial_basis, this value is ignored and
353 can be None. It is only relevant for the basis returned by Solution.basis,
354 and it is never None when returned from solve(). This is an advanced
355 status. For single-sided LPs it should be equal to the feasibility status
356 of the associated dual solution. For two-sided LPs it may be different in
357 some edge cases (e.g. incomplete solves with primal simplex). For more
358 details see go/mathopt-basis-advanced#dualfeasibility.
367 basic_dual_feasibility: Optional[SolutionStatus] =
None
370 """Returns an equivalent proto for the basis."""
371 return solution_pb2.BasisProto(
383 """Returns an equivalent Basis to the input proto."""
385 for index, vid
in enumerate(proto.variable_status.ids):
386 status_proto = proto.variable_status.values[index]
387 if status_proto == solution_pb2.BASIS_STATUS_UNSPECIFIED:
388 raise ValueError(
"Variable basis status should not be UNSPECIFIED")
389 result.variable_status[mod.get_variable(vid)] =
BasisStatus(status_proto)
390 for index, cid
in enumerate(proto.constraint_status.ids):
391 status_proto = proto.constraint_status.values[index]
392 if status_proto == solution_pb2.BASIS_STATUS_UNSPECIFIED:
393 raise ValueError(
"Constraint basis status should not be UNSPECIFIED")
394 result.constraint_status[mod.get_linear_constraint(cid)] =
BasisStatus(
398 proto.basic_dual_feasibility
407 terms: Dict[T, BasisStatus]
408) -> solution_pb2.SparseBasisStatusVector:
409 """Converts a basis vector from a python Dict to a protocol buffer."""
410 result = solution_pb2.SparseBasisStatusVector()
412 id_and_status = sorted(
413 (key.id, status.value)
for (key, status)
in terms.items()
415 ids, values = zip(*id_and_status)
417 result.values[:] = values
421@dataclasses.dataclass
423 """A solution to the optimization problem in a Model."""
425 primal_solution: Optional[PrimalSolution] =
None
426 dual_solution: Optional[DualSolution] =
None
427 basis: Optional[Basis] =
None
430 """Returns an equivalent proto for a solution."""
431 return solution_pb2.SolutionProto(
447 """Returns a Solution equivalent to the input proto."""
449 if proto.HasField(
"primal_solution"):
451 if proto.HasField(
"dual_solution"):
453 result.basis =
parse_basis(proto.basis, mod)
if proto.HasField(
"basis")
else None