Coverage for gpkit/keydict.py: 87%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x 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, veclinkedfn
8DIMLESS_QUANTITY = Quantity(1, "dimensionless")
9INT_DTYPE = np.dtype(int)
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.
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
25class KeyMap:
26 """Helper class to provide KeyMapping to interfaces.
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:
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)
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
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
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
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 # sometimes not in keymap?
107 return key in self.keymap
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()
121class KeyDict(KeyMap, dict):
122 """KeyDicts do two things over a dict: map keys and collapse arrays.
124 >>>> kd = gpkit.keydict.KeyDict()
126 For mapping keys, see KeyMapper.__doc__
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.
135 See also: gpkit/tests/t_keydict.py.
136 """
137 collapse_arrays = True
139 def get(self, key, *alternative):
140 return alternative[0] if alternative and key not in self else self[key]
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)
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
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")
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
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 hasattr(value, "__call__"): # a linked vector-function
230 key.vecfn = value
231 value = np.empty(key.shape, dtype="object")
232 it = np.nditer(value, flags=['multi_index', 'refs_ok'])
233 while not it.finished:
234 i = it.multi_index
235 it.iternext()
236 value[i] = veclinkedfn(key.vecfn, i)
237 if getattr(value, "shape", None): # is the value an array?
238 if value.dtype == INT_DTYPE:
239 value = np.array(value, "f") # convert to float
240 if dict.__contains__(self, key):
241 old = super().__getitem__(key)
242 if old.dtype != value.dtype:
243 # e.g. replacing a number with a linked function
244 newly_typed_array = np.array(old, dtype=value.dtype)
245 super().__setitem__(key, newly_typed_array)
246 self.owned.add(key)
247 self._copyonwrite(key)
248 goodvals = ~isnan(value)
249 super().__getitem__(key)[goodvals] = value[goodvals]
250 return # successfully set only some indexes!
251 elif not is_sweepvar(value): # or needs to be made one?
252 if not hasattr(value, "__len__"):
253 value = np.full(key.shape, value, "f")
254 elif not isinstance(value[0], np.ndarray):
255 clean_values = [clean_value(key, v) for v in value]
256 dtype = None
257 if any(is_sweepvar(cv) for cv in clean_values):
258 dtype = "object"
259 value = np.array(clean_values, dtype=dtype)
260 super().__setitem__(key, value)
261 self.owned.add(key)
263 def __delitem__(self, key):
264 "Overloads del [] to work with all keys"
265 if not hasattr(key, "key"): # not a keyed object
266 self.update_keymap()
267 keys = self.keymap[key]
268 if not keys:
269 raise KeyError(key)
270 for k in keys:
271 del self[k]
272 else:
273 key = key.key
274 veckey, idx = self.parse_and_index(key)
275 if idx is None:
276 super().__delitem__(key)
277 else:
278 super().__getitem__(veckey)[idx] = np.nan
279 if isnan(super().__getitem__(veckey)).all():
280 super().__delitem__(veckey)
281 copiedonwrite = set() # to save time, .update() does not copy
282 mapkeys = set([key])
283 if key.keys:
284 mapkeys.update(key.keys)
285 for mapkey in mapkeys:
286 if mapkey in self.keymap:
287 if len(self.keymap[mapkey]) == 1:
288 del self.keymap[mapkey]
289 continue
290 if mapkey not in copiedonwrite:
291 self.keymap[mapkey] = set(self.keymap[mapkey])
292 copiedonwrite.add(mapkey)
293 self.keymap[mapkey].remove(key)
296class KeySet(KeyMap, set):
297 "KeyMaps that don't collapse arrays or store values."
298 collapse_arrays = False
300 def update(self, keys):
301 "Iterates through the dictionary created by args and kwargs"
302 for key in keys:
303 self.keymap[key].add(key)
304 self._unmapped_keys.update(keys)
305 super().update(keys)
307 def __getitem__(self, key):
308 "Gets the keys corresponding to a particular key."
309 key, _ = self.parse_and_index(key)
310 return self.keymap[key]