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