Last active
April 18, 2018 06:37
-
-
Save eric-wieser/d8790dede1c9311c5670018ee1cee83a to your computer and use it in GitHub Desktop.
Proposal for `np.field_info`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from field_info import field_info | |
dt = np.dtype([('time', [('subtime', np.int32, (30,20))], 200), ('value', np.float32, (10,2))]) | |
assert field_info(dt)['time'].offset == 0 | |
assert field_info(dt)['time'][1].offset == 30 * 20 * 4 | |
# etc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def _address_of(a): | |
return a.__array_interface__['data'][0] | |
class field_info(object): | |
def __init__(self, dtype): | |
self._arr = np.empty((0,), dtype) | |
@property | |
def dtype(self): | |
return np.dtype((self._arr.dtype, self._arr.shape)) | |
@property | |
def offset(self): | |
if self._arr.base is None: | |
return 0 | |
return _address_of(self._arr) - _address_of(self._arr.base) | |
@property | |
def strides(self): | |
return self._arr.strides[1:] | |
def __getitem__(self, item): | |
res = field_info.__new__(field_info) | |
if isinstance(item, str): | |
res._arr = self._arr[item] | |
return res | |
if not isinstance(item, tuple): | |
item = (item,) | |
res._arr = self._arr[(...,) + item] | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment