14"""Sparse vectors and matrices using variables and constraints from Model.
16Analogous to sparse_containers.proto, with bidirectional conversion.
18from typing
import Dict, FrozenSet, Generic, Iterable, Mapping, Optional, Set, TypeVar
27VarOrConstraintType = TypeVar(
28 "VarOrConstraintType",
36 terms: Mapping[VarOrConstraintType, float],
37) -> sparse_containers_pb2.SparseDoubleVectorProto:
38 """Converts a sparse vector from proto to dict representation."""
39 result = sparse_containers_pb2.SparseDoubleVectorProto()
41 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
43 ids, values = zip(*id_and_values)
45 result.values[:] = values
50 terms: Mapping[VarOrConstraintType, int],
51) -> sparse_containers_pb2.SparseInt32VectorProto:
52 """Converts a sparse vector from proto to dict representation."""
53 result = sparse_containers_pb2.SparseInt32VectorProto()
55 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
57 ids, values = zip(*id_and_values)
59 result.values[:] = values
64 proto: sparse_containers_pb2.SparseDoubleVectorProto,
66 validate: bool =
True,
68 """Converts a sparse vector of variables from proto to dict representation."""
70 for index, var_id
in enumerate(proto.ids):
71 result[mod.get_variable(var_id, validate=validate)] = proto.values[index]
76 proto: sparse_containers_pb2.SparseDoubleVectorProto,
78 validate: bool =
True,
80 """Converts a sparse vector of linear constraints from proto to dict representation."""
82 for index, lin_con_id
in enumerate(proto.ids):
83 result[mod.get_linear_constraint(lin_con_id, validate=validate)] = proto.values[
90 proto: sparse_containers_pb2.SparseDoubleVectorProto,
92 validate: bool =
True,
94 """Converts a sparse vector of quadratic constraints from proto to dict representation."""
96 for index, quad_con_id
in enumerate(proto.ids):
97 result[mod.get_quadratic_constraint(quad_con_id, validate=validate)] = (
104 """Restricts the variables or constraints returned in a sparse vector.
106 The default behavior is to return entries for all variables/constraints.
108 E.g. when requesting the solution to an optimization problem, use this class
109 to restrict the variables that values are returned for.
112 skip_zero_values: Do not include key value pairs with value zero.
113 filtered_items: If not None, include only key value pairs these keys. Note
114 that the empty set is different (don't return any keys) from None (return
121 skip_zero_values: bool =
False,
122 filtered_items: Optional[Iterable[VarOrConstraintType]] =
None,
126 None if filtered_items
is None else frozenset(filtered_items)
139 def to_proto(self) -> sparse_containers_pb2.SparseVectorFilterProto:
140 """Returns an equivalent proto representation."""
141 result = sparse_containers_pb2.SparseVectorFilterProto()
144 result.filter_by_ids =
True
151QuadraticConstraintFilter = SparseVectorFilter[