本文整理汇总了Python中astropy.table.QTable.read方法的典型用法代码示例。如果您正苦于以下问题:Python QTable.read方法的具体用法?Python QTable.read怎么用?Python QTable.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类astropy.table.QTable
的用法示例。
在下文中一共展示了QTable.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_HST_WFC3
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def load_HST_WFC3(cls):
""" Load the LLS survey using HST/WFC3
by O'Meara et al. 2013, ApJ, 765, 137
Parameters
----------
Returns
-------
lls_survey : IGMSurvey
"""
# LLS File
lls_fil = pyigm_path+'/data/LLS/HST/lls_wfc3_stat_LLS.fits.gz'
lls = QTable.read(lls_fil)
# Rename some columns?
lls.rename_column('QSO_RA', 'RA')
lls.rename_column('QSO_DEC', 'DEC')
# Read
lls_survey = cls.from_sfits(lls)
lls_survey.ref = 'HST-WFC3'
# QSOs file
qsos_fil = pyigm_path+'/data/LLS/HST/lls_wfc3_qsos_sn1020.fits.gz'
qsos = QTable.read(qsos_fil)
lls_survey.sightlines = qsos
# Return
print('HST-WFC3: Loaded')
return lls_survey
示例2: load_SDSS_DR7
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def load_SDSS_DR7(cls, sample='stat'):
""" Load the LLS from the SDSS-DR7 survey (Prochaska+10, ApJ, 718, 391)
Parameters
----------
sample : str, optional
LLS sample
stat : Statistical sample
all : All LLS
nonstat : Non-statistical sample
Returns
-------
lls_survey : IGMSurvey
"""
# LLS File
lls_fil = pyigm_path+'/data/LLS/SDSS/lls_dr7_stat_LLS.fits.gz'
print('SDSS-DR7: Loading LLS file {:s}'.format(lls_fil))
lls = QTable.read(lls_fil)
# Rename some columns?
lls.rename_column('QSO_RA', 'RA')
lls.rename_column('QSO_DEC', 'DEC')
# Read
lls_survey = cls.from_sfits(lls)
lls_survey.ref = 'SDSS-DR7'
# QSOs file
qsos_fil = pyigm_path+'/data/LLS/SDSS/lls_dr7_qsos_sn2050.fits.gz'
print('SDSS-DR7: Loading QSOs file {:s}'.format(qsos_fil))
qsos = QTable.read(qsos_fil)
lls_survey.sightlines = qsos
# All?
if sample == 'all':
return lls_survey
# Stat
# z_em cut
zem_min = 3.6
lowz_q = qsos['ZEM'] < zem_min
qsos['ZT2'][lowz_q] = 99.99
# Generate mask
print('SDSS-DR7: Performing stats (~60s)')
mask = lls_stat(lls_survey, qsos)
if sample == 'stat':
lls_survey.mask = mask
else:
lls_survey.mask = ~mask
# Return
print('SDSS-DR7: Loaded')
return lls_survey
示例3: read_verner94
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def read_verner94():
""" Read Verner1994 Table
"""
# Read
verner94 = lt_path + '/data/lines/verner94_tab6.fits'
print(
'linetools.lists.parse: Reading linelist --- \n {:s}'.format(
verner94))
tbl_6 = QTable.read(verner94)
# My table
ldict, data = line_data(nrows=len(tbl_6))
# Fill
data['wrest'] = tbl_6['lambda']
data['f'] = tbl_6['Fik']
data['gj'] = tbl_6['Gi']
data['gk'] = tbl_6['Gk']
data['Z'] = tbl_6['Z']
data['ion'] = tbl_6['Z'] - tbl_6['N'] + 1
for ii,row in enumerate(tbl_6):
data[ii]['name'] = (
row['Species'][0:2].strip() + row['Species'][2:].strip() +
' {:d}'.format(int(row['lambda'].value)))
#xdb.set_trace()
# Finish
data['group'] = 1
data['Ref'] = 'Verner1994'
data['mol'] = ''
# Return
return data
示例4: from_sfits
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def from_sfits(self):
'''Generate the Survey from a summary FITS file
'''
# Read
systems = QTable.read(self.summ_fits)
self.nsys = len(systems)
# Dict
kdict = dict(NHI=['NHI','logNHI'],
sigNHI=['sig(logNHI)'],
name=['Name'],
vlim=['vlim'],
zabs=['Z_LLS'],
zem=['Z_QSO'],
RA=['RA'],
Dec=['DEC','Dec'])
# Parse the Table
inputs = {}
for key in kdict.keys():
vals, tag = lsio.get_table_column(kdict[key],[systems],idx=0)
if vals is not None:
inputs[key] = vals
# Generate
for kk,row in enumerate(systems):
# Generate keywords
kwargs = {}
for key in inputs.keys():
kwargs[key] = inputs[key][kk]
# Instantiate
self._abs_sys.append(set_absclass(self.abs_type)(**kwargs))
示例5: from_sfits
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def from_sfits(cls, summ_fits, **kwargs):
"""Generate the Survey from a summary FITS file
Handles SPEC_FILES too.
Parameters
----------
summ_fits : str or Table or QTable
Summary FITS file
**kwargs : dict
passed to __init__
"""
# Init
slf = cls(**kwargs)
# Read
if isinstance(summ_fits, Table):
systems = summ_fits
else:
systems = QTable.read(summ_fits)
nsys = len(systems)
# Dict
kdict = dict(NHI=['NHI', 'logNHI'],
sig_NHI=['sig(logNHI)', 'SIGNHI'],
name=['Name'], vlim=['vlim'],
zabs=['Z_LLS', 'ZABS', 'zabs'],
zem=['Z_QSO', 'QSO_ZEM'],
RA=['RA'], Dec=['DEC', 'Dec'])
# Parse the Table
inputs = {}
for key in kdict.keys():
vals, tag = lsio.get_table_column(kdict[key], [systems],idx=0)
if vals is not None:
inputs[key] = vals
# vlim
if 'vlim' not in inputs.keys():
default_vlim = [-1000, 1000.]* u.km / u.s
inputs['vlim'] = [default_vlim]*nsys
# Generate
for kk in range(nsys):
# Generate keywords
kwargs = {}
args = {}
for key in inputs.keys():
if key in ['vlim', 'zabs', 'RA', 'Dec']:
args[key] = inputs[key][kk]
else:
kwargs[key] = inputs[key][kk]
# Instantiate
abssys = class_by_type(slf.abs_type)((args['RA'], args['Dec']), args['zabs'], args['vlim'], **kwargs)
# spec_files
try:
abssys.spec_files += systems[kk]['SPEC_FILES'].tolist()
except (KeyError, AttributeError):
pass
slf._abs_sys.append(abssys)
# Mask
slf.init_mask()
# Return
return slf
示例6: read_elvis_z0
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def read_elvis_z0(fn):
tab = QTable.read(fn, format='ascii.commented_header', data_start=0, header_start=1)
col_name_re = re.compile(r'(.*?)(\(.*\))?$')
for col in tab.columns.values():
match = col_name_re.match(col.name)
if match:
nm, unit = match.groups()
if nm != col.name:
col.name = nm
if unit is not None:
col.unit = u.Unit(unit[1:-1]) # 1:-1 to get rid of the parenthesis
return tab
示例7: test_create_grism_objects
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def test_create_grism_objects():
source_catalog = get_file_path('step_SourceCatalogStep_cat.ecsv')
# create from test ascii file
grism_objects = read_catalog(source_catalog)
assert isinstance(grism_objects, list), "return grism objects were not a list"
required_fields = list(SkyObject()._fields)
go_fields = grism_objects[0]._fields
assert all([a == b for a, b in zip(required_fields, go_fields)]), "Required fields mismatch for SkyObject and GrismObject"
# create from QTable object
tempcat = QTable.read(source_catalog, format='ascii.ecsv')
grism_object_from_table = read_catalog(tempcat)
assert isinstance(grism_object_from_table, list), "return grism objects were not a list"
示例8: __init__
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def __init__(self, filename='$GAMMA_CAT/docs/data/gammacat.fits.gz'):
filename = make_path(filename)
if not 'GAMMA_CAT' in os.environ:
msg = 'The gamma-cat repo is not available. '
msg += 'You have to set the GAMMA_CAT environment variable '
msg += 'to point to the location for it to be found.'
raise GammaCatNotFoundError(msg)
self.filename = str(filename)
table = QTable.read(self.filename)
source_name_key='common_name'
source_name_alias = ('other_names', 'gamma_names')
super(SourceCatalogGammaCat, self).__init__(table=table,
source_name_key=source_name_key,
source_name_alias=source_name_alias)
示例9: test_votable_quantity_write
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def test_votable_quantity_write(tmpdir):
"""
Test that table with Quantity mixin column can be round-tripped by
io.votable. Note that FITS and HDF5 mixin support are tested (much more
thoroughly) in their respective subpackage tests
(io/fits/tests/test_connect.py and io/misc/tests/test_hdf5.py).
"""
t = QTable()
t['a'] = u.Quantity([1, 2, 4], unit='Angstrom')
filename = str(tmpdir.join('table-tmp'))
t.write(filename, format='votable', overwrite=True)
qt = QTable.read(filename, format='votable')
assert isinstance(qt['a'], u.Quantity)
assert qt['a'].unit == 'Angstrom'
示例10: get_table_from_ldac
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def get_table_from_ldac(filename, frame=1):
"""
Load an astropy table from a fits_ldac by frame (Since the ldac format has column
info for odd tables, giving it twce as many tables as a regular fits BinTableHDU,
match the frame of a table to its corresponding frame in the ldac file).
Parameters
----------
filename: str
Name of the file to open
frame: int
Number of the frame in a regular fits file
"""
from astropy.table import QTable
if frame>0:
frame = frame*2
tbl = QTable.read(filename, hdu=frame)
return tbl
示例11: __init__
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def __init__(self, version=None, verbose=True):
# Set version
if version is None:
self._version = "DR7"
else:
self._version = version
self.verbose = verbose
# Paths
if os.getenv("SDSSPATH") is None:
print("SDSS_QUASAR: This code requires an SDSS database. Discuss with JXP")
return
self._path = os.getenv("SDSSPATH") + "/" + self._version + "_QSO/"
self._datdir = self._path + "spectro/1d_26/"
# Grab Summary FITS file
self._summf = self._path + self._version.lower() + "_qso.fits.gz"
if self.verbose:
print("SDSS_QUASAR: Using summary file {:s}".format(self._summf))
self._data = QTable.read(self._summf)
示例12: __init__
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def __init__(self, version=None, verbose=True):
# Set version
if version is None:
self._version = 'DR7'
else:
self._version = version
self.verbose = verbose
# Paths
if os.getenv('SDSSPATH') is None:
print('SDSS_QUASAR: This code requires an SDSS database. Discuss with JXP')
return
self._path = os.getenv('SDSSPATH')+'/'+self._version+'_QSO/'
self._datdir = self._path+'spectro/1d_26/'
# Grab Summary FITS file
self._summf = self._path+self._version.lower()+'_qso.fits.gz'
if self.verbose:
print('SDSS_QUASAR: Using summary file {:s}'.format(self._summf))
self._data = QTable.read(self._summf)
示例13: make_cutouts
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def make_cutouts(catalogname, imagename, image_label,
table_format='ascii.ecsv', image_ext=0, clobber=False,
verbose=True):
"""Make cutouts from a 2D image and write them to FITS files.
Catalog must have the following columns with unit info, where applicable:
* ``'id'`` - ID string; no unit necessary.
* ``'ra'`` - RA (e.g., in degrees).
* ``'dec'`` - DEC (e.g., in degrees).
* ``'cutout_x_size'`` - Cutout width (e.g., in arcsec).
* ``'cutout_y_size'`` - Cutout height (e.g., in arcsec).
* ``'spatial_pixel_scale'`` - Pixel scale (e.g., in arcsec/pix).
The following are no longer used, so they are now optional:
* ``'slit_pa'`` - Slit angle (e.g., in degrees).
* ``'slit_width'`` - Slit width (e.g., in arcsec).
* ``'slit_length'`` - Slit length (e.g., in arcsec).
Cutouts are organized as follows::
working_dir/
<image_label>_cutouts/
<id>_<image_label>_cutout.fits
Each cutout image is a simple single-extension FITS with updated WCS.
Its header has the following special keywords:
* ``OBJ_RA`` - RA of the cutout object in degrees.
* ``OBJ_DEC`` - DEC of the cutout object in degrees.
Parameters
----------
catalogname : str
Catalog table defining the sources to cut out.
imagename : str
Image to cut.
image_label : str
Label to name the cutout sub-directory and filenames.
table_format : str, optional
Format as accepted by `~astropy.table.QTable`. Default is ECSV.
image_ext : int, optional
Image extension to extract header and data. Default is 0.
clobber : bool, optional
Overwrite existing files. Default is `False`.
verbose : bool, optional
Print extra info. Default is `True`.
"""
table = QTable.read(catalogname, format=table_format)
with fits.open(imagename) as pf:
data = pf[image_ext].data
wcs = WCS(pf[image_ext].header)
# It is more efficient to operate on an entire column at once.
c = SkyCoord(table['ra'], table['dec'])
x = table['cutout_x_size'] / table['spatial_pixel_scale']
y = table['cutout_y_size'] / table['spatial_pixel_scale']
# Sub-directory, relative to working directory.
path = '{0}_cutouts'.format(image_label)
if not os.path.exists(path):
os.mkdir(path)
cutcls = partial(Cutout2D, data, wcs=wcs, mode='partial')
for position, x_pix, y_pix, row in zip(c, x, y, table):
try:
cutout = cutcls(position, size=(y_pix, x_pix))
except NoConvergence:
if verbose:
log.info('WCS solution did not converge: '
'Skipping {0}'.format(row['id']))
continue
if np.array_equiv(cutout.data, 0):
if verbose:
log.info('No data in cutout: Skipping {0}'.format(row['id']))
continue
fname = os.path.join(
path, '{0}_{1}_cutout.fits'.format(row['id'], image_label))
# Construct FITS HDU.
hdu = fits.PrimaryHDU(cutout.data)
hdu.header.update(cutout.wcs.to_header())
hdu.header['OBJ_RA'] = (position.ra.deg, 'Cutout object RA in deg')
hdu.header['OBJ_DEC'] = (position.dec.deg, 'Cutout object DEC in deg')
hdu.writeto(fname, clobber=clobber)
if verbose:
#.........这里部分代码省略.........
示例14: make_cutouts
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def make_cutouts(catalogname, imagename, image_label, apply_rotation=False,
table_format='ascii.ecsv', image_ext=0, clobber=False,
verbose=True):
"""Make cutouts from a 2D image and write them to FITS files.
Catalog must have the following columns with unit info, where applicable:
* ``'id'`` - ID string; no unit necessary.
* ``'ra'`` - RA (e.g., in degrees).
* ``'dec'`` - DEC (e.g., in degrees).
* ``'cutout_x_size'`` - Cutout width (e.g., in arcsec).
* ``'cutout_y_size'`` - Cutout height (e.g., in arcsec).
* ``'cutout_pa'`` - Cutout angle (e.g., in degrees). This is only
use if user chooses to rotate the cutouts. Positive value
will result in a clockwise rotation.
* ``'spatial_pixel_scale'`` - Pixel scale (e.g., in arcsec/pix).
The following are no longer used, so they are now optional:
* ``'slit_pa'`` - Slit angle (e.g., in degrees).
* ``'slit_width'`` - Slit width (e.g., in arcsec).
* ``'slit_length'`` - Slit length (e.g., in arcsec).
Cutouts are organized as follows::
working_dir/
<image_label>_cutouts/
<id>_<image_label>_cutout.fits
Each cutout image is a simple single-extension FITS with updated WCS.
Its header has the following special keywords:
* ``OBJ_RA`` - RA of the cutout object in degrees.
* ``OBJ_DEC`` - DEC of the cutout object in degrees.
* ``OBJ_ROT`` - Rotation of cutout object in degrees.
Parameters
----------
catalogname : str
Catalog table defining the sources to cut out.
imagename : str
Image to cut.
image_label : str
Label to name the cutout sub-directory and filenames.
apply_rotation : bool
Cutout will be rotated to a given angle. Default is `False`.
table_format : str, optional
Format as accepted by `~astropy.table.QTable`. Default is ECSV.
image_ext : int, optional
Image extension to extract header and data. Default is 0.
clobber : bool, optional
Overwrite existing files. Default is `False`.
verbose : bool, optional
Print extra info. Default is `True`.
"""
# Optional dependencies...
from reproject import reproject_interp
table = QTable.read(catalogname, format=table_format)
with fits.open(imagename) as pf:
data = pf[image_ext].data
wcs = WCS(pf[image_ext].header)
# It is more efficient to operate on an entire column at once.
c = SkyCoord(table['ra'], table['dec'])
x = (table['cutout_x_size'] / table['spatial_pixel_scale']).value # pix
y = (table['cutout_y_size'] / table['spatial_pixel_scale']).value # pix
pscl = table['spatial_pixel_scale'].to(u.deg / u.pix)
# Do not rotate if column is missing.
if 'cutout_pa' not in table.colnames:
apply_rotation = False
# Sub-directory, relative to working directory.
path = '{0}_cutouts'.format(image_label)
if not os.path.exists(path):
os.mkdir(path)
cutcls = partial(Cutout2D, data, wcs=wcs, mode='partial')
for position, x_pix, y_pix, pix_scl, row in zip(c, x, y, pscl, table):
if apply_rotation:
pix_rot = row['cutout_pa'].to(u.degree).value
cutout_wcs = WCS(naxis=2)
cutout_wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
cutout_wcs.wcs.crval = [position.ra.deg, position.dec.deg]
cutout_wcs.wcs.crpix = [(x_pix - 1) * 0.5, (y_pix - 1) * 0.5]
try:
#.........这里部分代码省略.........
示例15: get_object_info
# 需要导入模块: from astropy.table import QTable [as 别名]
# 或者: from astropy.table.QTable import read [as 别名]
def get_object_info(catalog_name=None):
"""Return a list of SkyObjects from the direct image
The source_catalog step catalog items are read into a list
of SkyObjects which can be referenced by catalog id. Only
the columns needed by the WFSS code are saved.
Parameters
----------
catalog_name : str, astropy.table.table.Qtable
The name of the photutils catalog or its quantities table
Returns
-------
objects : list[jwst.transforms.models.SkyObject]
A list of SkyObject tuples
Notes
-----
"""
if isinstance(catalog_name, (str)):
if len(catalog_name) == 0:
err_text = "Empty catalog filename"
log.error(err_text)
raise ValueError(err_text)
try:
catalog = QTable.read(catalog_name, format='ascii.ecsv')
except FileNotFoundError as e:
log.error("Could not find catalog file: {0}".format(e))
raise FileNotFoundError("Could not find catalog: {0}".format(e))
elif isinstance(catalog_name, QTable):
catalog = catalog_name
else:
err_text = "Need to input string name of catalog or astropy.table.table.QTable instance"
log.error(err_text)
raise TypeError(err_text)
objects = []
# validate that the expected columns are there
# id is just a bad name for a param, but it's used in the catalog
required_fields = list(SkyObject()._fields)
if "sid" in required_fields:
required_fields[required_fields.index("sid")] = "id"
try:
if not set(required_fields).issubset(set(catalog.colnames)):
difference = set(catalog.colnames).difference(required_fields)
err_text = "Missing required columns in source catalog: {0}".format(difference)
log.error(err_text)
raise KeyError(err_text)
except AttributeError as e:
err_text = "Problem validating object catalog columns: {0}".format(e)
log.error(err_text)
raise AttributeError
# The columns are named sky_bbox_ll, sky_bbox_ul, sky_bbox_lr,
# and sky_bbox_ur, each of which is a SkyCoord (i.e. RA & Dec & frame) at
# one corner of the minimal bounding box. There will also be a sky_bbox
# property as a 4-tuple of SkyCoord, but that is not serializable
# (hence, the four separate columns).
for row in catalog:
objects.append(SkyObject(sid=row['id'],
xcentroid=row['xcentroid'],
ycentroid=row['ycentroid'],
sky_centroid=row['sky_centroid'],
abmag=row['abmag'],
abmag_error=row['abmag_error'],
sky_bbox_ll=row['sky_bbox_ll'],
sky_bbox_lr=row['sky_bbox_lr'],
sky_bbox_ul=row['sky_bbox_ul'],
sky_bbox_ur=row['sky_bbox_ur'],
)
)
return objects