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
24VarOrConstraintType = TypeVar(
30 terms: Mapping[VarOrConstraintType, float]
31) -> sparse_containers_pb2.SparseDoubleVectorProto:
32 """Converts a sparse vector from proto to dict representation."""
33 result = sparse_containers_pb2.SparseDoubleVectorProto()
35 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
37 ids, values = zip(*id_and_values)
39 result.values[:] = values
44 terms: Mapping[VarOrConstraintType, int]
45) -> sparse_containers_pb2.SparseInt32VectorProto:
46 """Converts a sparse vector from proto to dict representation."""
47 result = sparse_containers_pb2.SparseInt32VectorProto()
49 id_and_values = [(key.id, value)
for (key, value)
in terms.items()]
51 ids, values = zip(*id_and_values)
53 result.values[:] = values
58 proto: sparse_containers_pb2.SparseDoubleVectorProto, mod:
model.Model
60 """Converts a sparse vector of variables from proto to dict representation."""
62 for index, var_id
in enumerate(proto.ids):
63 result[mod.get_variable(var_id)] = proto.values[index]
68 proto: sparse_containers_pb2.SparseDoubleVectorProto, mod:
model.Model
70 """Converts a sparse vector of linear constraints from proto to dict representation."""
72 for index, lin_con_id
in enumerate(proto.ids):
73 result[mod.get_linear_constraint(lin_con_id)] = proto.values[index]
78 """Restricts the variables or constraints returned in a sparse vector.
80 The default behavior is to return entries for all variables/constraints.
82 E.g. when requesting the solution to an optimization problem, use this class
83 to restrict the variables that values are returned for.
86 skip_zero_values: Do not include key value pairs with value zero.
87 filtered_items: If not None, include only key value pairs these keys. Note
88 that the empty set is different (don't return any keys) from None (return
95 skip_zero_values: bool =
False,
96 filtered_items: Optional[Iterable[VarOrConstraintType]] =
None,
100 None if filtered_items
is None else frozenset(filtered_items)
114 """Returns an equivalent proto representation."""
115 result = sparse_containers_pb2.SparseVectorFilterProto()
118 result.filter_by_ids =
True