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 KeyDict and KeySet classes" 

2from collections import defaultdict 

3from collections.abc import Hashable 

4import numpy as np 

5from .small_classes import Numbers, Quantity, FixedScalar 

6from .small_scripts import is_sweepvar, isnan 

7 

8DIMLESS_QUANTITY = Quantity(1, "dimensionless") 

9INT_DTYPE = np.dtype(int) 

10 

11def clean_value(key, value): 

12 """Gets the value of variable-less monomials, so that 

13 `x.sub({x: gpkit.units.m})` and `x.sub({x: gpkit.ureg.m})` are equivalent. 

14 

15 Also converts any quantities to the key's units, because quantities 

16 can't/shouldn't be stored as elements of numpy arrays. 

17 """ 

18 if isinstance(value, FixedScalar): 

19 value = value.value 

20 if isinstance(value, Quantity): 

21 value = value.to(key.units or "dimensionless").magnitude 

22 return value 

23 

24 

25class KeyMap: 

26 """Helper class to provide KeyMapping to interfaces. 

27 

28 Mapping keys 

29 ------------ 

30 A KeyMap keeps an internal list of VarKeys as 

31 canonical keys, and their values can be accessed with any object whose 

32 `key` attribute matches one of those VarKeys, or with strings matching 

33 any of the multiple possible string interpretations of each key: 

34 

35 For example, after creating the KeyDict kd and setting kd[x] = v (where x 

36 is a Variable or VarKey), v can be accessed with by the following keys: 

37 - x 

38 - x.key 

39 - x.name (a string) 

40 - "x_modelname" (x's name including modelname) 

41 

42 Note that if a item is set using a key that does not have a `.key` 

43 attribute, that key can be set and accessed normally. 

44 """ 

45 collapse_arrays = False 

46 keymap = [] 

47 log_gets = False 

48 vks = varkeys = None 

49 

50 def __init__(self, *args, **kwargs): 

51 "Passes through to super().__init__ via the `update()` method" 

52 self.keymap = defaultdict(set) 

53 self._unmapped_keys = set() 

54 self.owned = set() 

55 self.update(*args, **kwargs) # pylint: disable=no-member 

56 

57 def parse_and_index(self, key): 

58 "Returns key if key had one, and veckey/idx for indexed veckeys." 

59 try: 

60 key = key.key 

61 if self.collapse_arrays and key.idx: 

62 return key.veckey, key.idx 

63 return key, None 

64 except AttributeError: 

65 if self.vks is None and self.varkeys is None: 

66 return key, self.update_keymap() 

67 # looks like we're in a substitutions dictionary 

68 if self.varkeys is None: 

69 self.varkeys = KeySet(self.vks) 

70 if key not in self.varkeys: 

71 raise KeyError(key) 

72 newkey, *otherkeys = self.varkeys[key] 

73 if otherkeys: 

74 if all(k.veckey == newkey.veckey for k in otherkeys): 

75 return newkey.veckey, None 

76 raise ValueError("%s refers to multiple keys in this substitutions" 

77 " KeyDict. Use `.variables_byname(%s)` to see all" 

78 " of them." % (key, key)) 

79 if self.collapse_arrays and newkey.idx: 

80 return newkey.veckey, newkey.idx 

81 return newkey, None 

82 

83 def __contains__(self, key): # pylint:disable=too-many-return-statements 

84 "In a winding way, figures out if a key is in the KeyDict" 

85 try: 

86 key, idx = self.parse_and_index(key) 

87 except KeyError: 

88 return False 

89 except ValueError: # multiple keys correspond 

90 return True 

91 if not isinstance(key, Hashable): 

92 return False 

93 if super().__contains__(key): # pylint: disable=no-member 

94 if idx: 

95 try: 

96 value = super().__getitem__(key)[idx] # pylint: disable=no-member 

97 return True if is_sweepvar(value) else not isnan(value) 

98 except TypeError: 

99 raise TypeError("%s has an idx, but its value in this" 

100 " KeyDict is the scalar %s." 

101 % (key, super().__getitem__(key))) # pylint: disable=no-member 

102 except IndexError: 

103 raise IndexError("key %s with idx %s is out of bounds" 

104 " for value %s" % 

105 (key, idx, super().__getitem__(key))) # pylint: disable=no-member 

106 return True 

107 return key in self.keymap 

108 

109 def update_keymap(self): 

110 "Updates the keymap with the keys in _unmapped_keys" 

111 copied = set() # have to copy bc update leaves duplicate sets 

112 for key in self._unmapped_keys: 

113 for mapkey in key.keys: 

114 if mapkey not in copied and mapkey in self.keymap: 

115 self.keymap[mapkey] = set(self.keymap[mapkey]) 

116 copied.add(mapkey) 

117 self.keymap[mapkey].add(key) 

118 self._unmapped_keys = set() 

119 

120 

121class KeyDict(KeyMap, dict): 

122 """KeyDicts do two things over a dict: map keys and collapse arrays. 

123 

124 >>>> kd = gpkit.keydict.KeyDict() 

125 

126 For mapping keys, see KeyMapper.__doc__ 

127 

128 Collapsing arrays 

129 ----------------- 

130 If ``.collapse_arrays`` is True then VarKeys which have a `shape` 

131 parameter (indicating they are part of an array) are stored as numpy 

132 arrays, and automatically de-indexed when a matching VarKey with a 

133 particular `idx` parameter is used as a key. 

134 

135 See also: gpkit/tests/t_keydict.py. 

136 """ 

137 collapse_arrays = True 

138 

139 def get(self, key, *alternative): 

140 return alternative[0] if alternative and key not in self else self[key] 

141 

142 def _copyonwrite(self, key): 

143 "Copys arrays before they are written to" 

144 if not hasattr(self, "owned"): # backwards pickle compatibility 

145 self.owned = set() 

146 if key not in self.owned: 

147 super().__setitem__(key, super().__getitem__(key).copy()) 

148 self.owned.add(key) 

149 

150 def update(self, *args, **kwargs): 

151 "Iterates through the dictionary created by args and kwargs" 

152 if not self and len(args) == 1 and isinstance(args[0], KeyDict): 

153 super().update(args[0]) 

154 self.keymap.update(args[0].keymap) 

155 self._unmapped_keys.update(args[0]._unmapped_keys) # pylint:disable=protected-access 

156 else: 

157 for k, v in dict(*args, **kwargs).items(): 

158 self[k] = v 

159 

160 def __call__(self, key): # if uniting is ever a speed hit, cache it 

161 got = self[key] 

162 if isinstance(got, dict): 

163 for k, v in got.items(): 

164 got[k] = v*(k.units or DIMLESS_QUANTITY) 

165 return got 

166 if not hasattr(key, "units"): 

167 key, = self.keymap[self.parse_and_index(key)[0]] 

168 return Quantity(got, key.units or "dimensionless") 

169 

170 def __getitem__(self, key): 

171 "Overloads __getitem__ and [] access to work with all keys" 

172 key, idx = self.parse_and_index(key) 

173 keys = self.keymap[key] 

174 if not keys: 

175 del self.keymap[key] # remove blank entry added by defaultdict 

176 raise KeyError(key) 

177 got = {} 

178 for k in keys: 

179 if not idx and k.shape: 

180 self._copyonwrite(k) 

181 val = dict.__getitem__(self, k) 

182 if idx: 

183 val = val[idx] 

184 if len(keys) == 1: 

185 return val 

186 got[k] = val 

187 return got 

188 

189 def __setitem__(self, key, value): 

190 "Overloads __setitem__ and []= to work with all keys" 

191 # pylint: disable=too-many-boolean-expressions,too-many-branches,too-many-statements 

192 try: 

193 key, idx = self.parse_and_index(key) 

194 except KeyError as e: # may be indexed VectorVariable 

195 # NOTE: this try/except takes ~4% of the time in this loop 

196 if not hasattr(key, "shape"): 

197 raise e 

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

199 value = np.full(key.shape, value) 

200 elif key.shape != value.shape: 

201 raise KeyError("Key and value have different shapes") from e 

202 for subkey, subval in zip(key.flat, value.flat): 

203 self[subkey] = subval 

204 return 

205 value = clean_value(key, value) 

206 if key not in self.keymap: 

207 if not hasattr(self, "_unmapped_keys"): 

208 self.__init__() # py3's pickle sets items before init... :( 

209 self.keymap[key].add(key) 

210 self._unmapped_keys.add(key) 

211 if idx: 

212 dty = {} if isinstance(value, Numbers) else {"dtype": "object"} 

213 if getattr(value, "shape", None) and value.dtype != INT_DTYPE: 

214 dty["dtype"] = value.dtype 

215 dict.__setitem__(self, key, np.full(key.shape, np.nan, **dty)) 

216 self.owned.add(key) 

217 if idx: 

218 if is_sweepvar(value): 

219 old = super().__getitem__(key) 

220 super().__setitem__(key, np.array(old, "object")) 

221 self.owned.add(key) 

222 self._copyonwrite(key) 

223 if hasattr(value, "__call__"): # a linked function 

224 old = super().__getitem__(key) 

225 super().__setitem__(key, np.array(old, dtype="object")) 

226 super().__getitem__(key)[idx] = value 

227 return # successfully set a single index! 

228 if key.shape: # now if we're setting an array... 

229 if getattr(value, "shape", None): # is the value an array? 

230 if value.dtype == INT_DTYPE: 

231 value = np.array(value, "f") # convert to float 

232 if dict.__contains__(self, key): 

233 old = super().__getitem__(key) 

234 if old.dtype != value.dtype: 

235 # e.g. replacing a number with a linked function 

236 newly_typed_array = np.array(old, dtype=value.dtype) 

237 super().__setitem__(key, newly_typed_array) 

238 self.owned.add(key) 

239 self._copyonwrite(key) 

240 goodvals = ~isnan(value) 

241 super().__getitem__(key)[goodvals] = value[goodvals] 

242 return # successfully set only some indexes! 

243 elif not is_sweepvar(value): # or needs to be made one? 

244 if not hasattr(value, "__len__"): 

245 value = np.full(key.shape, value, "f") 

246 elif not isinstance(value[0], np.ndarray): 

247 clean_values = [clean_value(key, v) for v in value] 

248 dtype = None 

249 if any(is_sweepvar(cv) for cv in clean_values): 

250 dtype = "object" 

251 value = np.array(clean_values, dtype=dtype) 

252 # else: 

253 # value = np.array(clean_values) # can't use dtype=None 

254 super().__setitem__(key, value) 

255 self.owned.add(key) 

256 

257 def __delitem__(self, key): 

258 "Overloads del [] to work with all keys" 

259 if not hasattr(key, "key"): # not a keyed object 

260 self.update_keymap() 

261 keys = self.keymap[key] 

262 if not keys: 

263 raise KeyError(key) 

264 for k in keys: 

265 del self[k] 

266 else: 

267 key = key.key 

268 veckey, idx = self.parse_and_index(key) 

269 if idx is None: 

270 super().__delitem__(key) 

271 else: 

272 super().__getitem__(veckey)[idx] = np.nan 

273 if isnan(super().__getitem__(veckey)).all(): 

274 super().__delitem__(veckey) 

275 copiedonwrite = set() # to save time, .update() does not copy 

276 mapkeys = set([key]) 

277 if key.keys: 

278 mapkeys.update(key.keys) 

279 for mapkey in mapkeys: 

280 if mapkey in self.keymap: 

281 if len(self.keymap[mapkey]) == 1: 

282 del self.keymap[mapkey] 

283 continue 

284 if mapkey not in copiedonwrite: 

285 self.keymap[mapkey] = set(self.keymap[mapkey]) 

286 copiedonwrite.add(mapkey) 

287 self.keymap[mapkey].remove(key) 

288 

289 

290class KeySet(KeyMap, set): 

291 "KeyMaps that don't collapse arrays or store values." 

292 collapse_arrays = False 

293 

294 def update(self, keys): 

295 "Iterates through the dictionary created by args and kwargs" 

296 for key in keys: 

297 self.keymap[key].add(key) 

298 self._unmapped_keys.update(keys) 

299 super().update(keys) 

300 

301 def __getitem__(self, key): 

302 "Gets the keys corresponding to a particular key." 

303 key, _ = self.parse_and_index(key) 

304 return self.keymap[key]