Skip to content

Instantly share code, notes, and snippets.

@zachlewis
Last active May 23, 2022 22:31
Show Gist options
  • Save zachlewis/b7b6acf98484e7fabc40ed3e7b4f1366 to your computer and use it in GitHub Desktop.
Save zachlewis/b7b6acf98484e7fabc40ed3e7b4f1366 to your computer and use it in GitHub Desktop.
NumericLookup
import numpy as np
class NumericLookup(dict):
"""
Extends *dict* type to provide a lookup by value(s), including numpy arrays.
Methods
-------
keys_from_value
first_key_from_value
References
----------
:cite:`Mansencalc`
Examples
--------
>>> test = NumericLookup(abc=100.001, defg=102.3, hij=123)
>>> test.first_key_from_value(100)
'abc'
>>> tests = NumericLookup(abc=100.001, defg=99.99999999, hij=100.00111)
>>> sorted(tests.keys_from_value(100)) # noqa
['abc', 'defg']
Notes
-----
Stolen from the colour.utilities.Lookup; modified to permit lookups by np arrays
"""
def keys_from_value(self, value, rtol=1e-05, atol=1e-08):
"""
Gets the keys with given value.
Parameters
----------
value : object
Value.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
Returns
-------
object
Keys.
"""
keys = []
for key, data in self.items():
try:
matching = np.allclose(data, value, rtol=rtol, atol=atol)
except ValueError:
matching = all((data == value,))
if matching:
keys.append(key)
return keys
def first_key_from_value(self, value, rtol=1e-05, atol=1e-08):
"""
Gets the first key with given value.
Parameters
----------
value : object
Value.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
Returns
-------
object
Key.
"""
try:
return self.keys_from_value(value, rtol=rtol, atol=atol)[0]
except IndexError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment