15"""Sparse vectors and matrices using variables and constraints from Model.
17Analogous to sparse_containers.proto, with bidirectional conversion.
19from typing
import Dict, FrozenSet, Generic, Iterable, Mapping, Optional, Set, TypeVar
28VarOrConstraintType = TypeVar(
29 "VarOrConstraintType",
37 terms: Mapping[VarOrConstraintType, float],
38) -> sparse_containers_pb2.SparseDoubleVectorProto:
39 """Converts a sparse vector from proto to dict representation."""
40 result = sparse_containers_pb2.SparseDoubleVectorProto()
42 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
44 ids, values = zip(*id_and_values)
46 result.values[:] = values
51 terms: Mapping[VarOrConstraintType, int],
52) -> sparse_containers_pb2.SparseInt32VectorProto:
53 """Converts a sparse vector from proto to dict representation."""
54 result = sparse_containers_pb2.SparseInt32VectorProto()
56 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
58 ids, values = zip(*id_and_values)
60 result.values[:] = values
65 proto: sparse_containers_pb2.SparseDoubleVectorProto,
67 validate: bool =
True,
69 """Converts a sparse vector of variables from proto to dict representation."""
71 for index, var_id
in enumerate(proto.ids):
72 result[mod.get_variable(var_id, validate=validate)] = proto.values[index]
77 proto: sparse_containers_pb2.SparseDoubleVectorProto,
79 validate: bool =
True,
81 """Converts a sparse vector of linear constraints from proto to dict representation."""
83 for index, lin_con_id
in enumerate(proto.ids):
84 result[mod.get_linear_constraint(lin_con_id, validate=validate)] = proto.values[
91 proto: sparse_containers_pb2.SparseDoubleVectorProto,
93 validate: bool =
True,
95 """Converts a sparse vector of quadratic constraints from proto to dict representation."""
97 for index, quad_con_id
in enumerate(proto.ids):
98 result[mod.get_quadratic_constraint(quad_con_id, validate=validate)] = (
105 """Restricts the variables or constraints returned in a sparse vector.
107 The default behavior is to return entries for all variables/constraints.
109 E.g. when requesting the solution to an optimization problem, use this class
110 to restrict the variables that values are returned for.
113 skip_zero_values: Do not include key value pairs with value zero.
114 filtered_items: If not None, include only key value pairs these keys. Note
115 that the empty set is different (don't return any keys) from None (return
122 skip_zero_values: bool =
False,
123 filtered_items: Optional[Iterable[VarOrConstraintType]] =
None,
127 None if filtered_items
is None else frozenset(filtered_items)
140 def to_proto(self) -> sparse_containers_pb2.SparseVectorFilterProto:
141 """Returns an equivalent proto representation."""
142 result = sparse_containers_pb2.SparseVectorFilterProto()
145 result.filter_by_ids =
True
152QuadraticConstraintFilter = SparseVectorFilter[