Hide keyboard shortcuts

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"Implements ConstraintSet" 

2import sys 

3from collections import defaultdict, OrderedDict 

4from itertools import chain 

5import numpy as np 

6from ..keydict import KeySet, KeyDict 

7from ..small_scripts import try_str_without 

8from ..repr_conventions import ReprMixin 

9from .single_equation import SingleEquationConstraint 

10 

11 

12def add_meq_bounds(bounded, meq_bounded): #TODO: collapse with GP version? 

13 "Iterates through meq_bounds until convergence" 

14 still_alive = True 

15 while still_alive: 

16 still_alive = False # if no changes are made, the loop exits 

17 for bound in list(meq_bounded): 

18 if bound in bounded: # bound already exists 

19 del meq_bounded[bound] 

20 continue 

21 for condition in meq_bounded[bound]: 

22 if condition.issubset(bounded): # bound's condition is met 

23 del meq_bounded[bound] 

24 bounded.add(bound) 

25 still_alive = True 

26 break 

27 

28def _sort_by_name_and_idx(var): 

29 "return tuple for Variable sorting" 

30 return (var.key.str_without(["units", "idx"]), var.key.idx or ()) 

31 

32def _sort_constraints(item): 

33 "return tuple for Constraint sorting" 

34 label, constraint = item 

35 return (not isinstance(constraint, SingleEquationConstraint), 

36 bool(getattr(constraint, "lineage", None)), label) 

37 

38def sort_constraints_dict(iterable): 

39 "Sort a dictionary of {k: constraint} and return its keys and values" 

40 if sys.version_info >= (3, 7) or isinstance(iterable, OrderedDict): 

41 return iterable.keys(), iterable.values() 

42 items = sorted(list(iterable.items()), key=_sort_constraints) 

43 return (item[0] for item in items), (item[1] for item in items) 

44 

45def flatiter(iterable, yield_if_hasattr=None): 

46 "Yields contained constraints, optionally including constraintsets." 

47 if isinstance(iterable, dict): 

48 _, iterable = sort_constraints_dict(iterable) 

49 for constraint in iterable: 

50 if (not hasattr(constraint, "__iter__") 

51 or (yield_if_hasattr 

52 and hasattr(constraint, yield_if_hasattr))): 

53 yield constraint 

54 else: 

55 try: # numpy array 

56 yield from constraint.flat 

57 except TypeError: # ConstrainSet 

58 yield from constraint.flat(yield_if_hasattr) 

59 except AttributeError: # probably a list or dict 

60 yield from flatiter(constraint, yield_if_hasattr) 

61 

62 

63class ConstraintSet(list, ReprMixin): 

64 "Recursive container for ConstraintSets and Inequalities" 

65 unique_varkeys, idxlookup = frozenset(), {} 

66 _name_collision_varkeys = None 

67 _varkeys = None 

68 

69 def __init__(self, constraints, substitutions=None, *, bonusvks=None): # pylint: disable=too-many-branches,too-many-statements 

70 if isinstance(constraints, dict): 

71 keys, constraints = sort_constraints_dict(constraints) 

72 self.idxlookup = {k: i for i, k in enumerate(keys)} 

73 elif isinstance(constraints, ConstraintSet): 

74 constraints = [constraints] # put it one level down 

75 list.__init__(self, constraints) 

76 self.vks = set(self.unique_varkeys) 

77 self.substitutions = KeyDict({k: k.value for k in self.unique_varkeys 

78 if "value" in k.descr}) 

79 self.substitutions.vks = self.vks 

80 self.bounded, self.meq_bounded = set(), defaultdict(set) 

81 for i, constraint in enumerate(self): 

82 if hasattr(constraint, "vks"): 

83 self._update(constraint) 

84 elif not (hasattr(constraint, "as_hmapslt1") 

85 or hasattr(constraint, "as_gpconstr")): 

86 try: 

87 for subconstraint in flatiter(constraint, "vks"): 

88 self._update(subconstraint) 

89 except Exception as e: 

90 raise badelement(self, i, constraint) from e 

91 elif isinstance(constraint, ConstraintSet): 

92 raise badelement(self, i, constraint, 

93 " It had not yet been initialized!") 

94 if bonusvks: 

95 self.vks.update(bonusvks) 

96 if substitutions: 

97 self.substitutions.update(substitutions) 

98 for key in self.vks: 

99 if key not in self.substitutions: 

100 if key.veckey is None or key.veckey not in self.substitutions: 

101 continue 

102 if np.isnan(self.substitutions[key.veckey][key.idx]): 

103 continue 

104 self.bounded.add((key, "upper")) 

105 self.bounded.add((key, "lower")) 

106 if key.value is not None and not key.constant: 

107 del key.descr["value"] 

108 if key.veckey and key.veckey.value is not None: 

109 del key.veckey.descr["value"] 

110 add_meq_bounds(self.bounded, self.meq_bounded) 

111 

112 def _update(self, constraint): 

113 "Update parameters with a given constraint" 

114 self.vks.update(constraint.vks) 

115 if hasattr(constraint, "substitutions"): 

116 self.substitutions.update(constraint.substitutions) 

117 else: 

118 self.substitutions.update({k: k.value \ 

119 for k in constraint.vks if "value" in k.descr}) 

120 self.bounded.update(constraint.bounded) 

121 for bound, solutionset in constraint.meq_bounded.items(): 

122 self.meq_bounded[bound].update(solutionset) 

123 

124 def __getitem__(self, key): 

125 if key in self.idxlookup: 

126 key = self.idxlookup[key] 

127 if isinstance(key, int): 

128 return list.__getitem__(self, key) 

129 return self._choosevar(key, self.variables_byname(key)) 

130 

131 def _choosevar(self, key, variables): 

132 if not variables: 

133 raise KeyError(key) 

134 firstvar, *othervars = variables 

135 veckey = firstvar.key.veckey 

136 if veckey is None or any(v.key.veckey != veckey for v in othervars): 

137 if not othervars: 

138 return firstvar 

139 raise ValueError("multiple variables are called '%s'; show them" 

140 " with `.variables_byname('%s')`" % (key, key)) 

141 from ..nomials import NomialArray # all one vector! 

142 arr = NomialArray(np.full(veckey.shape, np.nan, dtype="object")) 

143 for v in variables: 

144 arr[v.key.idx] = v 

145 arr.key = veckey 

146 return arr 

147 

148 def variables_byname(self, key): 

149 "Get all variables with a given name" 

150 from ..nomials import Variable 

151 return sorted([Variable(k) for k in self.varkeys[key]], 

152 key=_sort_by_name_and_idx) 

153 

154 @property 

155 def varkeys(self): 

156 "The NomialData's varkeys, created when necessary for a substitution." 

157 if self._varkeys is None: 

158 self._varkeys = KeySet(self.vks) 

159 return self._varkeys 

160 

161 def constrained_varkeys(self): 

162 "Return all varkeys in non-ConstraintSet constraints" 

163 return self.vks - self.unique_varkeys 

164 

165 flat = flatiter 

166 

167 def as_hmapslt1(self, subs): 

168 "Yields hmaps<=1 from self.flat()" 

169 yield from chain(*(c.as_hmapslt1(subs) 

170 for c in flatiter(self, 

171 yield_if_hasattr="as_hmapslt1"))) 

172 

173 def process_result(self, result): 

174 """Does arbitrary computation / manipulation of a program's result 

175 

176 There's no guarantee what order different constraints will process 

177 results in, so any changes made to the program's result should be 

178 careful not to step on other constraint's toes. 

179 

180 Potential Uses 

181 -------------- 

182 - check that an inequality was tight 

183 - add values computed from solved variables 

184 

185 """ 

186 for constraint in self.flat(yield_if_hasattr="process_result"): 

187 if hasattr(constraint, "process_result"): 

188 constraint.process_result(result) 

189 evalfn_vars = {v.veckey or v for v in self.unique_varkeys 

190 if v.evalfn and v not in result["variables"]} 

191 for v in evalfn_vars: 

192 val = v.evalfn(result["variables"]) 

193 result["variables"][v] = result["freevariables"][v] = val 

194 

195 def __repr__(self): 

196 "Returns namespaced string." 

197 if not self: 

198 return "<gpkit.%s object>" % self.__class__.__name__ 

199 return ("<gpkit.%s object containing %i top-level constraint(s)" 

200 " and %i variable(s)>" % (self.__class__.__name__, 

201 len(self), len(self.varkeys))) 

202 

203 def name_collision_varkeys(self): 

204 "Returns the set of contained varkeys whose names are not unique" 

205 if self._name_collision_varkeys is None: 

206 self._name_collision_varkeys = { 

207 key for key in self.varkeys 

208 if len(self.varkeys[key.str_without(["lineage", "vec"])]) > 1} 

209 return self._name_collision_varkeys 

210 

211 def lines_without(self, excluded): 

212 "Lines representation of a ConstraintSet." 

213 excluded = frozenset(excluded) 

214 root, rootlines = "root" not in excluded, [] 

215 if root: 

216 excluded = excluded.union(["root"]) 

217 if "unnecessary lineage" in excluded: 

218 for key in self.name_collision_varkeys(): 

219 key.descr["necessarylineage"] = True 

220 if hasattr(self, "_rootlines"): 

221 rootlines = self._rootlines(excluded) # pylint: disable=no-member 

222 lines = recursively_line(self, excluded) 

223 indent = " " if getattr(self, "lineage", None) else "" 

224 if root and "unnecessary lineage" in excluded: 

225 indent += " " 

226 for key in self.name_collision_varkeys(): 

227 del key.descr["necessarylineage"] 

228 return rootlines + [(indent+line).rstrip() for line in lines] 

229 

230 def str_without(self, excluded=("unnecessary lineage", "units")): 

231 "String representation of a ConstraintSet." 

232 return "\n".join(self.lines_without(excluded)) 

233 

234 def latex(self, excluded=("units",)): 

235 "LaTeX representation of a ConstraintSet." 

236 lines = [] 

237 root = "root" not in excluded 

238 if root: 

239 excluded += ("root",) 

240 lines.append("\\begin{array}{ll} \\text{}") 

241 if hasattr(self, "_rootlatex"): 

242 lines.append(self._rootlatex(excluded)) # pylint: disable=no-member 

243 for constraint in self: 

244 cstr = try_str_without(constraint, excluded, latex=True) 

245 if cstr[:6] != " & ": # require indentation 

246 cstr = " & " + cstr + " \\\\" 

247 lines.append(cstr) 

248 if root: 

249 lines.append("\\end{array}") 

250 return "\n".join(lines) 

251 

252 def as_view(self): 

253 "Return a ConstraintSetView of this ConstraintSet." 

254 return ConstraintSetView(self) 

255 

256def recursively_line(iterable, excluded): 

257 "Generates lines in a recursive tree-like fashion, the better to indent." 

258 named_constraints = {} 

259 if isinstance(iterable, dict): 

260 keys, iterable = sort_constraints_dict(iterable) 

261 named_constraints = dict(enumerate(keys)) 

262 elif hasattr(iterable, "idxlookup"): 

263 named_constraints = {i: k for k, i in iterable.idxlookup.items()} 

264 lines = [] 

265 for i, constraint in enumerate(iterable): 

266 if hasattr(constraint, "lines_without"): 

267 clines = constraint.lines_without(excluded) 

268 elif not hasattr(constraint, "__iter__"): 

269 clines = try_str_without(constraint, excluded).split("\n") 

270 elif iterable is constraint: 

271 clines = ["(constraint contained itself)"] 

272 else: 

273 clines = recursively_line(constraint, excluded) 

274 if (getattr(constraint, "lineage", None) 

275 and isinstance(constraint, ConstraintSet)): 

276 name, num = constraint.lineage[-1] 

277 if not any(clines): 

278 clines = [" " + "(no constraints)"] # named model indent 

279 if lines: 

280 lines.append("") 

281 lines.append(name if not num else name + str(num)) 

282 elif "constraint names" not in excluded and i in named_constraints: 

283 lines.append("\"%s\":" % named_constraints[i]) 

284 clines = [" " + line for line in clines] # named constraint indent 

285 lines.extend(clines) 

286 return lines 

287 

288 

289class ConstraintSetView: 

290 "Class to access particular views on a set's variables" 

291 

292 def __init__(self, constraintset, index=()): 

293 self.constraintset = constraintset 

294 try: 

295 self.index = tuple(index) 

296 except TypeError: # probably not iterable 

297 self.index = (index,) 

298 

299 def __getitem__(self, index): 

300 "Appends the index to its own and returns a new view." 

301 if not isinstance(index, tuple): 

302 index = (index,) 

303 # indexes are preprended to match Vectorize convention 

304 return ConstraintSetView(self.constraintset, index + self.index) 

305 

306 def __getattr__(self, attr): 

307 """Returns attribute from the base ConstraintSets 

308 

309 If it's a another ConstraintSet, return the matching View; 

310 if it's an array, return it at the specified index; 

311 otherwise, raise an error. 

312 """ 

313 if not hasattr(self.constraintset, attr): 

314 raise AttributeError("the underlying object lacks `.%s`." % attr) 

315 

316 value = getattr(self.constraintset, attr) 

317 if isinstance(value, ConstraintSet): 

318 return ConstraintSetView(value, self.index) 

319 if not hasattr(value, "shape"): 

320 raise ValueError("attribute %s with value %s did not have" 

321 " a shape, so ConstraintSetView cannot" 

322 " return an indexed view." % (attr, value)) 

323 index = self.index 

324 newdims = len(value.shape) - len(self.index) 

325 if newdims > 0: # indexes are put last to match Vectorize 

326 index = (slice(None),)*newdims + index 

327 return value[index] 

328 

329 

330 

331def badelement(cns, i, constraint, cause=""): 

332 "Identify the bad element and raise a ValueError" 

333 cause = cause if not isinstance(constraint, bool) else ( 

334 " Did the constraint list contain an accidental equality?") 

335 if len(cns) == 1: 

336 loc = "the only constraint" 

337 elif i == 0: 

338 loc = "at the start, before %s" % cns[i+1] 

339 elif i == len(cns) - 1: 

340 loc = "at the end, after %s" % cns[i-1] 

341 else: 

342 loc = "between %s and %s" % (cns[i-1], cns[i+1]) 

343 return ValueError("Invalid ConstraintSet element '%s' %s was %s.%s" 

344 % (repr(constraint), type(constraint), loc, cause))