Coverage for gpkit/repr_conventions.py: 93%

131 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-07 22:13 -0500

1"Repository for representation standards" 

2import sys 

3import re 

4import numpy as np 

5from .small_classes import Quantity, Numbers 

6from .small_scripts import try_str_without 

7 

8INSIDE_PARENS = re.compile(r"\(.*\)") 

9 

10if sys.platform[:3] == "win": # pragma: no cover 

11 MUL = "*" 

12 PI_STR = "PI" 

13 UNICODE_EXPONENTS = False 

14 UNIT_FORMATTING = ":~" 

15else: # pragma: no cover 

16 MUL = "·" 

17 PI_STR = "π" 

18 UNICODE_EXPONENTS = True 

19 UNIT_FORMATTING = ":P~" 

20 

21def lineagestr(lineage, modelnums=True): 

22 "Returns properly formatted lineage string" 

23 if not isinstance(lineage, tuple): 

24 lineage = getattr(lineage, "lineage", None) 

25 return ".".join([f"{name}{num}" if (num and modelnums) else name 

26 for name, num in lineage]) if lineage else "" 

27 

28 

29def unitstr(units, into="%s", options=UNIT_FORMATTING, dimless=""): 

30 "Returns the string corresponding to an object's units." 

31 if hasattr(units, "units") and isinstance(units.units, Quantity): 

32 units = units.units 

33 if not isinstance(units, Quantity): 

34 return dimless 

35 if options == ":~" and "ohm" in str(units.units): # pragma: no cover 

36 rawstr = str(units.units) # otherwise it'll be a capital Omega 

37 else: 

38 rawstr = ("{%s}" % options).format(units.units) 

39 units = rawstr.replace(" ", "").replace("dimensionless", dimless) 

40 return into % units or dimless 

41 

42def latex_unitstr(units): 

43 "Returns latex unitstr" 

44 us = unitstr(units, r"~\mathrm{%s}", ":L~") 

45 utf = us.replace("frac", "tfrac").replace(r"\cdot", r"\cdot ") 

46 return utf if utf != r"~\mathrm{-}" else "" 

47 

48 

49def strify(val, excluded): 

50 "Turns a value into as pretty a string as possible." 

51 if isinstance(val, Numbers): 

52 isqty = hasattr(val, "magnitude") 

53 if isqty: 

54 units = val 

55 val = val.magnitude 

56 if np.pi/12 < val < 100*np.pi and abs(12*val/np.pi % 1) <= 1e-2: 

57 # val is in bounds and a clean multiple of PI! 

58 if val > 3.1: # product of PI 

59 val = f"{val/np.pi:.3g}{PI_STR}" 

60 if val == f"1{PI_STR}": 

61 val = PI_STR 

62 else: # division of PI 

63 val = f"({PI_STR}/{np.pi/val:.3g})" 

64 else: 

65 val = f"{val:.3g}" 

66 if isqty: 

67 val += unitstr(units, " [%s]") 

68 else: 

69 val = try_str_without(val, excluded) 

70 return val 

71 

72 

73def parenthesize(string, addi=True, mult=True): 

74 "Parenthesizes a string if it needs it and isn't already." 

75 parensless = string if "(" not in string else INSIDE_PARENS.sub("", string) 

76 bare_addi = (" + " in parensless or " - " in parensless) 

77 bare_mult = ("·" in parensless or "/" in parensless) 

78 if parensless and (addi and bare_addi) or (mult and bare_mult): 

79 return f"({string})" 

80 return string 

81 

82 

83class ReprMixin: 

84 "This class combines various printing methods for easier adoption." 

85 lineagestr = lineagestr 

86 unitstr = unitstr 

87 latex_unitstr = latex_unitstr 

88 

89 cached_strs = None 

90 ast = None 

91 # pylint: disable=too-many-branches, too-many-statements 

92 def parse_ast(self, excluded=()): 

93 "Turns the AST of this object's construction into a faithful string" 

94 excluded = frozenset({"units"}.union(excluded)) 

95 if self.cached_strs is None: 

96 self.cached_strs = {} 

97 elif excluded in self.cached_strs: 

98 return self.cached_strs[excluded] 

99 oper, values = self.ast # pylint: disable=unpacking-non-sequence 

100 

101 if oper == "add": 

102 left = strify(values[0], excluded) 

103 right = strify(values[1], excluded) 

104 if right[0] == "-": 

105 aststr = f"{left} - {right[1:]}" 

106 else: 

107 aststr = f"{left} + {right}" 

108 elif oper == "mul": 

109 left = parenthesize(strify(values[0], excluded), mult=False) 

110 right = parenthesize(strify(values[1], excluded), mult=False) 

111 if left == "1": 

112 aststr = right 

113 elif right == "1": 

114 aststr = left 

115 else: 

116 aststr = f"{left}{MUL}{right}" 

117 elif oper == "div": 

118 left = parenthesize(strify(values[0], excluded), mult=False) 

119 right = parenthesize(strify(values[1], excluded)) 

120 if right == "1": 

121 aststr = left 

122 else: 

123 aststr = f"{left}/{right}" 

124 elif oper == "neg": 

125 val = parenthesize(strify(values, excluded), mult=False) 

126 aststr = f"-{val}" 

127 elif oper == "pow": 

128 left = parenthesize(strify(values[0], excluded)) 

129 x = values[1] 

130 if left == "1": 

131 aststr = "1" 

132 elif (UNICODE_EXPONENTS and not getattr(x, "shape", None) 

133 and int(x) == x and 2 <= x <= 9): 

134 x = int(x) 

135 if x in (2, 3): 

136 aststr = f"{left}{chr(176 + x)}" 

137 elif x in (4, 5, 6, 7, 8, 9): 

138 aststr = f"{left}{chr(8304 + x)}" 

139 else: 

140 aststr = f"{left}^{x}" 

141 elif oper == "prod": # TODO: only do if it makes a shorter string 

142 val = parenthesize(strify(values[0], excluded)) 

143 aststr = f"{val}.prod()" 

144 elif oper == "sum": # TODO: only do if it makes a shorter string 

145 val = parenthesize(strify(values[0], excluded)) 

146 aststr = f"{val}.sum()" 

147 elif oper == "index": # TODO: label vectorization idxs 

148 left = parenthesize(strify(values[0], excluded)) 

149 idx = values[1] 

150 if left[-3:] == "[:]": # pure variable access 

151 left = left[:-3] 

152 if isinstance(idx, tuple): 

153 elstrs = [] 

154 for el in idx: 

155 if isinstance(el, slice): 

156 start = el.start or "" 

157 stop = (el.stop if el.stop and el.stop < sys.maxsize 

158 else "") 

159 step = f":{el.step}" if el.step is not None else "" 

160 elstrs.append(f"{start}:{stop}{step}") 

161 elif isinstance(el, Numbers): 

162 elstrs.append(str(el)) 

163 idx = ",".join(elstrs) 

164 elif isinstance(idx, slice): 

165 start = idx.start or "" 

166 stop = idx.stop if idx.stop and idx.stop < 1e6 else "" 

167 step = f":{idx.step}" if idx.step is not None else "" 

168 idx = f"{start}:{stop}{step}" 

169 aststr = f"{left}[{idx}]" 

170 else: 

171 raise ValueError(oper) 

172 self.cached_strs[excluded] = aststr 

173 return aststr 

174 

175 def __repr__(self): 

176 "Returns namespaced string." 

177 return f"gpkit.{self.__class__.__name__}({self})" 

178 

179 def __str__(self): 

180 "Returns default string." 

181 return self.str_without() # pylint: disable=no-member 

182 

183 def _repr_latex_(self): 

184 "Returns default latex for automatic iPython Notebook rendering." 

185 return "$$"+self.latex()+"$$" # pylint: disable=no-member