Coverage for gpkit\constraints\costed.py: 0%

28 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-03 16:57 -0500

1"Implement CostedConstraintSet" 

2import numpy as np 

3from .set import ConstraintSet 

4from ..small_scripts import maybe_flatten 

5from ..repr_conventions import lineagestr 

6 

7 

8class CostedConstraintSet(ConstraintSet): 

9 """A ConstraintSet with a cost 

10 

11 Arguments 

12 --------- 

13 cost : gpkit.Posynomial 

14 constraints : Iterable 

15 substitutions : dict 

16 """ 

17 lineage = None 

18 

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.vks if "value" in k.descr} 

24 if substitutions: 

25 subs.update(substitutions) 

26 ConstraintSet.__init__(self, constraints, subs, bonusvks=self.cost.vks) 

27 

28 def constrained_varkeys(self): 

29 "Return all varkeys in the cost and non-ConstraintSet constraints" 

30 constrained_varkeys = ConstraintSet.constrained_varkeys(self) 

31 constrained_varkeys.update(self.cost.vks) 

32 return constrained_varkeys 

33 

34 def _rootlines(self, excluded=()): 

35 "String showing cost, to be used when this is the top constraint" 

36 if self.cost.vks: 

37 description = ["", "Cost Function", "-------------", 

38 " %s" % self.cost.str_without(excluded), 

39 "", "Constraints", "-----------"] 

40 else: # don't print the cost if it's a constant 

41 description = ["", "Constraints", "-----------"] 

42 if self.lineage: 

43 fullname = lineagestr(self) 

44 description = [fullname, "="*len(fullname)] + description 

45 return description 

46 

47 def _rootlatex(self, excluded=()): 

48 "Latex showing cost, to be used when this is the top constraint" 

49 return "\n".join(["\\text{minimize}", 

50 " & %s \\\\" % self.cost.latex(excluded), 

51 "\\text{subject to}"])