15"""The solution to an optimization problem defined by Model in model.py."""
18from typing
import Dict, Optional, TypeVar
31 """Status of a variable/constraint in a LP basis.
34 FREE: The variable/constraint is free (it has no finite bounds).
35 AT_LOWER_BOUND: The variable/constraint is at its lower bound (which must be
37 AT_UPPER_BOUND: The variable/constraint is at its upper bound (which must be
39 FIXED_VALUE: The variable/constraint has identical finite lower and upper
41 BASIC: The variable/constraint is basic.
44 FREE = solution_pb2.BASIS_STATUS_FREE
45 AT_LOWER_BOUND = solution_pb2.BASIS_STATUS_AT_LOWER_BOUND
46 AT_UPPER_BOUND = solution_pb2.BASIS_STATUS_AT_UPPER_BOUND
47 FIXED_VALUE = solution_pb2.BASIS_STATUS_FIXED_VALUE
48 BASIC = solution_pb2.BASIS_STATUS_BASIC
53 """Feasibility of a primal or dual solution as claimed by the solver.
56 UNDETERMINED: Solver does not claim a feasibility status.
57 FEASIBLE: Solver claims the solution is feasible.
58 INFEASIBLE: Solver claims the solution is infeasible.
61 UNDETERMINED = solution_pb2.SOLUTION_STATUS_UNDETERMINED
62 FEASIBLE = solution_pb2.SOLUTION_STATUS_FEASIBLE
63 INFEASIBLE = solution_pb2.SOLUTION_STATUS_INFEASIBLE
67 proto: solution_pb2.SolutionStatusProto,
68) -> Optional[SolutionStatus]:
69 """Converts a proto SolutionStatus to an optional Python SolutionStatus."""
72 if proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED
78 status: Optional[SolutionStatus],
79) -> solution_pb2.SolutionStatusProto:
80 """Converts an optional Python SolutionStatus to a proto SolutionStatus."""
81 return solution_pb2.SOLUTION_STATUS_UNSPECIFIED
if status
is None else status.value
86 """A solution to the optimization problem in a Model.
88 E.g. consider a simple linear program:
92 A primal solution is assignment values to x. It is feasible if it satisfies
93 A * x >= b and x >= 0 from above. In the class PrimalSolution variable_values
94 is x and objective_value is c * x.
96 For the general case of a MathOpt optimization model, see go/mathopt-solutions
100 variable_values: The value assigned for each Variable in the model.
101 objective_value: The value of the objective value at this solution. This
102 value may not be always populated.
103 auxiliary_objective_values: Set only for multi objective problems, the
104 objective value for each auxiliary objective, as computed by the solver.
105 This value will not always be populated.
106 feasibility_status: The feasibility of the solution as claimed by the
113 objective_value: float = 0.0
115 dataclasses.field(default_factory=dict)
117 feasibility_status: SolutionStatus = SolutionStatus.UNDETERMINED
119 def to_proto(self) -> solution_pb2.PrimalSolutionProto:
120 """Returns an equivalent proto for a primal solution."""
121 return solution_pb2.PrimalSolutionProto(
122 variable_values=sparse_containers.to_sparse_double_vector_proto(
126 auxiliary_objective_values={
135 proto: solution_pb2.PrimalSolutionProto,
138 validate: bool =
True,
140 """Returns an equivalent PrimalSolution from the input proto."""
142 result.objective_value = proto.objective_value
143 for aux_id, obj_value
in proto.auxiliary_objective_values.items():
144 result.auxiliary_objective_values[
145 mod.get_auxiliary_objective(aux_id, validate=validate)
147 result.variable_values = sparse_containers.parse_variable_map(
148 proto.variable_values, mod, validate=validate
150 status_proto = proto.feasibility_status
151 if status_proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED:
152 raise ValueError(
"Primal solution feasibility status should not be UNSPECIFIED")
157@dataclasses.dataclass
159 """A direction of unbounded objective improvement in an optimization Model.
161 Equivalently, a certificate of infeasibility for the dual of the optimization
164 E.g. consider a simple linear program:
168 A primal ray is an x that satisfies:
172 Observe that given a feasible solution, any positive multiple of the primal
173 ray plus that solution is still feasible, and gives a better objective
174 value. A primal ray also proves the dual optimization problem infeasible.
176 In the class PrimalRay, variable_values is this x.
178 For the general case of a MathOpt optimization model, see
179 go/mathopt-solutions for details.
182 variable_values: The value assigned for each Variable in the model.
190 """Returns an equivalent proto to this PrimalRay."""
191 return solution_pb2.PrimalRayProto(
192 variable_values=sparse_containers.to_sparse_double_vector_proto(
199 proto: solution_pb2.PrimalRayProto,
202 validate: bool =
True,
204 """Returns an equivalent PrimalRay from the input proto."""
206 result.variable_values = sparse_containers.parse_variable_map(
207 proto.variable_values, mod, validate=validate
212@dataclasses.dataclass
214 """A solution to the dual of the optimization problem given by a Model.
216 E.g. consider the primal dual pair linear program pair:
219 s.t. A * x >= b s.t. y * A + r = c
221 The dual solution is the pair (y, r). It is feasible if it satisfies the
222 constraints from (Dual) above.
224 Below, y is dual_values, r is reduced_costs, and b * y is objective_value.
226 For the general case, see go/mathopt-solutions and go/mathopt-dual (and note
227 that the dual objective depends on r in the general case).
230 dual_values: The value assigned for each LinearConstraint in the model.
231 quadratic_dual_values: The value assigned for each QuadraticConstraint in
233 reduced_costs: The value assigned for each Variable in the model.
234 objective_value: The value of the dual objective value at this solution.
235 This value may not be always populated.
236 feasibility_status: The feasibility of the solution as claimed by the
244 dataclasses.field(default_factory=dict)
249 objective_value: Optional[float] =
None
250 feasibility_status: SolutionStatus = SolutionStatus.UNDETERMINED
252 def to_proto(self) -> solution_pb2.DualSolutionProto:
253 """Returns an equivalent proto for a dual solution."""
254 return solution_pb2.DualSolutionProto(
255 dual_values=sparse_containers.to_sparse_double_vector_proto(
258 reduced_costs=sparse_containers.to_sparse_double_vector_proto(
261 quadratic_dual_values=sparse_containers.to_sparse_double_vector_proto(
270 proto: solution_pb2.DualSolutionProto,
273 validate: bool =
True,
275 """Returns an equivalent DualSolution from the input proto."""
277 result.objective_value = (
278 proto.objective_value
if proto.HasField(
"objective_value")
else None
280 result.dual_values = sparse_containers.parse_linear_constraint_map(
281 proto.dual_values, mod, validate=validate
283 result.quadratic_dual_values = sparse_containers.parse_quadratic_constraint_map(
284 proto.quadratic_dual_values, mod, validate=validate
286 result.reduced_costs = sparse_containers.parse_variable_map(
287 proto.reduced_costs, mod, validate=validate
289 status_proto = proto.feasibility_status
290 if status_proto == solution_pb2.SOLUTION_STATUS_UNSPECIFIED:
291 raise ValueError(
"Dual solution feasibility status should not be UNSPECIFIED")
296@dataclasses.dataclass
298 """A direction of unbounded objective improvement in an optimization Model.
300 A direction of unbounded improvement to the dual of an optimization,
301 problem; equivalently, a certificate of primal infeasibility.
303 E.g. consider the primal dual pair linear program pair:
306 s.t. A * x >= b s.t. y * A + r = c
309 The dual ray is the pair (y, r) satisfying:
313 Observe that adding a positive multiple of (y, r) to dual feasible solution
314 maintains dual feasibility and improves the objective (proving the dual is
315 unbounded). The dual ray also proves the primal problem is infeasible.
317 In the class DualRay below, y is dual_values and r is reduced_costs.
319 For the general case, see go/mathopt-solutions and go/mathopt-dual (and note
320 that the dual objective depends on r in the general case).
323 dual_values: The value assigned for each LinearConstraint in the model.
324 reduced_costs: The value assigned for each Variable in the model.
335 """Returns an equivalent proto to this PrimalRay."""
336 return solution_pb2.DualRayProto(
337 dual_values=sparse_containers.to_sparse_double_vector_proto(
340 reduced_costs=sparse_containers.to_sparse_double_vector_proto(
347 proto: solution_pb2.DualRayProto, mod:
model.Model, *, validate: bool =
True
349 """Returns an equivalent DualRay from the input proto."""
351 result.dual_values = sparse_containers.parse_linear_constraint_map(
352 proto.dual_values, mod, validate=validate
354 result.reduced_costs = sparse_containers.parse_variable_map(
355 proto.reduced_costs, mod, validate=validate
360@dataclasses.dataclass
362 """A combinatorial characterization for a solution to a linear program.
364 The simplex method for solving linear programs always returns a "basic
365 feasible solution" which can be described combinatorially as a Basis. A basis
366 assigns a BasisStatus for every variable and linear constraint.
368 E.g. consider a standard form LP:
372 that has more variables than constraints and with full row rank A.
374 Let n be the number of variables and m the number of linear constraints. A
375 valid basis for this problem can be constructed as follows:
376 * All constraints will have basis status FIXED.
377 * Pick m variables such that the columns of A are linearly independent and
378 assign the status BASIC.
379 * Assign the status AT_LOWER for the remaining n - m variables.
381 The basic solution for this basis is the unique solution of A * x = b that has
382 all variables with status AT_LOWER fixed to their lower bounds (all zero). The
383 resulting solution is called a basic feasible solution if it also satisfies
386 See go/mathopt-basis for treatment of the general case and an explanation of
387 how a dual solution is determined for a basis.
390 variable_status: The basis status for each variable in the model.
391 constraint_status: The basis status for each linear constraint in the model.
392 basic_dual_feasibility: This is an advanced feature used by MathOpt to
393 characterize feasibility of suboptimal LP solutions (optimal solutions
394 will always have status SolutionStatus.FEASIBLE). For single-sided LPs it
395 should be equal to the feasibility status of the associated dual solution.
396 For two-sided LPs it may be different in some edge cases (e.g. incomplete
397 solves with primal simplex). For more details see
398 go/mathopt-basis-advanced#dualfeasibility. If you are providing a starting
399 basis via ModelSolveParameters.initial_basis, this value is ignored and
400 can be None. It is only relevant for the basis returned by Solution.basis,
401 and it is never None when returned from solve(). This is an advanced
402 status. For single-sided LPs it should be equal to the feasibility status
403 of the associated dual solution. For two-sided LPs it may be different in
404 some edge cases (e.g. incomplete solves with primal simplex). For more
405 details see go/mathopt-basis-advanced#dualfeasibility.
412 dataclasses.field(default_factory=dict)
414 basic_dual_feasibility: Optional[SolutionStatus] =
None
417 """Returns an equivalent proto for the basis."""
418 return solution_pb2.BasisProto(
430 proto: solution_pb2.BasisProto, mod:
model.Model, *, validate: bool =
True
432 """Returns an equivalent Basis to the input proto."""
434 for index, vid
in enumerate(proto.variable_status.ids):
435 status_proto = proto.variable_status.values[index]
436 if status_proto == solution_pb2.BASIS_STATUS_UNSPECIFIED:
437 raise ValueError(
"Variable basis status should not be UNSPECIFIED")
438 result.variable_status[mod.get_variable(vid, validate=validate)] =
BasisStatus(
441 for index, cid
in enumerate(proto.constraint_status.ids):
442 status_proto = proto.constraint_status.values[index]
443 if status_proto == solution_pb2.BASIS_STATUS_UNSPECIFIED:
444 raise ValueError(
"Constraint basis status should not be UNSPECIFIED")
445 result.constraint_status[mod.get_linear_constraint(cid, validate=validate)] = (
449 proto.basic_dual_feasibility
458 terms: Dict[T, BasisStatus],
459) -> solution_pb2.SparseBasisStatusVector:
460 """Converts a basis vector from a python Dict to a protocol buffer."""
461 result = solution_pb2.SparseBasisStatusVector()
463 id_and_status = sorted(
464 (key.id, status.value)
for (key, status)
in terms.items()
466 ids, values = zip(*id_and_status)
468 result.values[:] = values
472@dataclasses.dataclass
474 """A solution to the optimization problem in a Model."""
476 primal_solution: Optional[PrimalSolution] =
None
477 dual_solution: Optional[DualSolution] =
None
478 basis: Optional[Basis] =
None
481 """Returns an equivalent proto for a solution."""
482 return solution_pb2.SolutionProto(
498 proto: solution_pb2.SolutionProto,
501 validate: bool =
True,
503 """Returns a Solution equivalent to the input proto."""
505 if proto.HasField(
"primal_solution"):
507 proto.primal_solution, mod, validate=validate
509 if proto.HasField(
"dual_solution"):
511 proto.dual_solution, mod, validate=validate
515 if proto.HasField(
"basis")