Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"Implement CostedConstraintSet"
2import numpy as np
3from .set import ConstraintSet
4from ..small_scripts import maybe_flatten
5from ..repr_conventions import lineagestr
8class CostedConstraintSet(ConstraintSet):
9 """A ConstraintSet with a cost
11 Arguments
12 ---------
13 cost : gpkit.Posynomial
14 constraints : Iterable
15 substitutions : dict
16 """
17 lineage = None
19 def __init__(self, cost, constraints, substitutions=None):
20 self.cost = maybe_flatten(cost)
21 if isinstance(self.cost, np.ndarray): # if it's still a vector
22 raise ValueError("Cost must be scalar, not the vector %s." % cost)
23 subs = {k: k.value for k in self.cost.varkeys if "value" in k.descr}
24 if substitutions:
25 subs.update(substitutions)
26 ConstraintSet.__init__(self, constraints, subs)
27 self.varkeys.update(self.cost.varkeys)
29 def constrained_varkeys(self):
30 "Return all varkeys in the cost and non-ConstraintSet constraints"
31 constrained_varkeys = ConstraintSet.constrained_varkeys(self)
32 constrained_varkeys.update(self.cost.varkeys)
33 return constrained_varkeys
35 def _rootlines(self, excluded=()):
36 "String showing cost, to be used when this is the top constraint"
37 if self.cost.varkeys:
38 description = ["", "Cost Function", "-------------",
39 " %s" % self.cost.str_without(excluded),
40 "", "Constraints", "-----------"]
41 else: # don't print the cost if it's a constant
42 description = ["", "Constraints", "-----------"]
43 if self.lineage:
44 fullname = lineagestr(self)
45 description = [fullname, "="*len(fullname)] + description
46 return description
48 def _rootlatex(self, excluded=()):
49 "Latex showing cost, to be used when this is the top constraint"
50 return "\n".join(["\\text{minimize}",
51 " & %s \\\\" % self.cost.latex(excluded),
52 "\\text{subject to}"])