astropy: Slicing FITS_rec objects produces unexpected dtypes.
Consider the following snippet:
import numpy as np
from astropy.io import fits
def create_data():
tbhdu = fits.BinTableHDU.from_columns([
fits.Column(name='a', format='I', array=np.arange(2**16, dtype=np.int16)),
fits.Column(name='b', format='I', bscale=1, bzero=2**15, array=np.arange(2**16, dtype=np.uint16))])
tbhdu.writeto('test_scaled_slicing.fits')
def load_data(nonnegative=False):
with fits.open('test_scaled_slicing.fits') as hdulist:
data = hdulist[1].data
if nonnegative:
return data[data['a'] >= 0]
else:
return data
create_data()
t1 = load_data()
t2 = load_data(True)
assert t1['b'].dtype is np.dtype(np.uint16)
# assert t2['b'].dtype is np.dtype(np.float64)
assert t2['b'].dtype is np.dtype(np.uint16)
The second assert fails because the slicing the FITS_rec object does not trigger the mechanism that handles the scaling of the column ‘b’. In other words, some data access methods on FITS_rec trigger the scaling but some don’t.
If however, I use a method that forces the scaling, then this problem goes away. Here’s an example:
def load_data(nonnegative=False):
with fits.open('test_scaled_slicing.fits') as hdulist:
data = hdulist[1].data
#
# WORKAROUND
#
if any([c.bzero is not None for c in data.columns]):
foo = [data[k].dtype for k in data.dtype.names]
if nonnegative:
return data[data['a'] >= 0]
else:
return data
That is, merely accessing the dtype of each column triggers the scaling. Looking into the code itself, it looks like the ._converted attribute needs to be filled in for slicing to work properly.
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Comments: 16 (11 by maintainers)
Commits related to this issue
- Fix uint conversion after slicing Fix #5490. The _uint attribute was not transfered to the sliced array, so the data was later converted either correctly (if it was converted first before slicing) o... — committed to saimn/astropy by saimn 7 years ago
- Fix uint conversion after slicing Fix #5490. The _uint attribute was not transfered to the sliced array, so the data was later converted either correctly (if it was converted first before slicing) o... — committed to eblur/astropy by saimn 7 years ago
I realize that the commented assert should not work indeed. Thank you for having opened the new issue.
I know, this was meant for @weaverba137 or @saimn 😃
Yes sure i will. Are you sure you removed the comment to the second assert before trying it? I get: