Coverage for gpkit/nomials/data.py: 100%

45 statements  

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

1"""Machinery for exps, cs, varlocs data -- common to nomials and programs""" 

2import numpy as np 

3from ..keydict import KeySet 

4from ..repr_conventions import ReprMixin 

5from ..varkey import VarKey 

6 

7 

8class NomialData(ReprMixin): 

9 """Object for holding cs, exps, and other basic 'nomial' properties. 

10 

11 cs: array (coefficient of each monomial term) 

12 exps: tuple of {VarKey: float} (exponents of each monomial term) 

13 varlocs: {VarKey: list} (terms each variable appears in) 

14 units: pint.UnitsContainer 

15 """ 

16 # pylint: disable=too-many-instance-attributes 

17 _hashvalue = _varlocs = _exps = _cs = _varkeys = None 

18 

19 def __init__(self, hmap): 

20 self.hmap = hmap 

21 self.units = self.hmap.units 

22 self.any_nonpositive_cs = any(c <= 0 for c in self.hmap.values()) 

23 

24 def to(self, units): 

25 "Create new Signomial converted to new units" 

26 return self.__class__(self.hmap.to(units)) 

27 

28 @property 

29 def exps(self): 

30 "Create exps or return cached exps" 

31 if self._exps is None: 

32 self._exps = tuple(self.hmap.keys()) 

33 return self._exps 

34 

35 @property 

36 def cs(self): 

37 "Create cs or return cached cs" 

38 if self._cs is None: 

39 self._cs = np.array(list(self.hmap.values())) 

40 if self.hmap.units: 

41 # TODO: treat vars as dimensionless, it's a hack 

42 self._cs = self._cs*self.hmap.units 

43 return self._cs 

44 

45 def __hash__(self): 

46 return hash(self.hmap) 

47 

48 @property 

49 def vks(self): 

50 "Set of a NomialData's varkeys, created as necessary." 

51 vks = set() 

52 for exp in self.hmap: 

53 vks.update(exp) 

54 return vks 

55 

56 @property # TODO: remove this 

57 def varkeys(self): 

58 "KeySet of a NomialData's varkeys, created as necessary." 

59 return KeySet(self.vks) 

60 

61 def __eq__(self, other): 

62 "Equality test" 

63 if not hasattr(other, "hmap"): 

64 return NotImplemented 

65 if isinstance(other, VarKey): 

66 return False 

67 if self.hmap != other.hmap: 

68 return False 

69 if self.units != other.units: 

70 return False 

71 return True