本文整理汇总了Python中spectral_cube.SpectralCube类的典型用法代码示例。如果您正苦于以下问题:Python SpectralCube类的具体用法?Python SpectralCube怎么用?Python SpectralCube使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SpectralCube类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, cube, wcs=None, mask=None, sigma=None, empty_channel=0,
keep_threshold_mask=True, distance=None, galaxy_props={}):
super(BubbleFinder, self).__init__()
if not isinstance(cube, SpectralCube):
if wcs is None:
raise TypeError("When cube is not a SpectralCube, wcs must be"
" given.")
cube = SpectralCube(cube, wcs)
if mask is not None:
cube = cube.with_mask(mask)
self.cube = cube
self.empty_channel = empty_channel
if sigma is None:
self.estimate_sigma()
else:
self.sigma = sigma
self.keep_threshold_mask = keep_threshold_mask
self._mask = None
self.distance = distance
self.galaxy_props = galaxy_props
示例2: line_flux2
def line_flux2(catalog, line_name='13co10',
asgn=datadir + 'COHRS_all_asgn.fits',
cubefile=datadir + 'GRS_13CO_all.fits'):
flux = Column(np.zeros(len(catalog)),name=line_name)
asgn = SpectralCube.read(asgn)
linefile = SpectralCube.read(cubefile)
previous_file=''
fill_data=None
previous_cube_file=''
for idx, obj in enumerate(catalog):
if obj['orig_file'] != previous_cube_file:
print "Pulling line subcube for {0}".format(obj['orig_file'])
subx1 = obj['orig_file'].split('_')[2]
subx2 = obj['orig_file'].split('_')[3]
subcube = linefile[:, :, int(subx1):int(subx2)]
fill_cube_data = (subcube.filled_data[:].value)
previous_cube_file = obj['orig_file']
outtuple = sparse_mask(obj, asgn,
previous_file=previous_file,
fill_data=fill_data)
previous_file, fill_data, zcld, ycld, xcld = outtuple
if len(xcld)>0:
flux[idx] = np.nansum(fill_cube_data[zcld, ycld, xcld])
catalog.add_column(flux)
return catalog
示例3: load_and_reduce
def load_and_reduce(filename, add_noise=False, rms_noise=0.001,
nsig=3):
'''
Load the cube in and derive the property arrays.
'''
if add_noise:
if rms_noise is None:
raise TypeError("Must specify value of rms noise.")
cube, hdr = getdata(filename, header=True)
from scipy.stats import norm
cube += norm.rvs(0.0, rms_noise, cube.shape)
sc = SpectralCube(data=cube, wcs=WCS(hdr))
mask = LazyMask(np.isfinite, sc)
sc = sc.with_mask(mask)
else:
sc = filename
reduc = Mask_and_Moments(sc, scale=rms_noise)
reduc.make_mask(mask=reduc.cube > nsig * reduc.scale)
reduc.make_moments()
reduc.make_moment_errors()
return reduc.to_dict()
示例4: __init__
def __init__(self, highres, lowres):
super(MultiResObs, self).__init__()
self.highres = SpectralCube.read(highres)
self.lowres = SpectralCube.read(lowres)
self.highres_convolved = None
self.lowres_convolved = None
self.lowbeam = self.lowres.beam
self.highbeam = self.highres.beam
self.combined_beam = self.lowbeam.convolve(self.highbeam)
示例5: cubegen
def cubegen(ymin,ymax,xmin,xmax, deltaX=30):
"""Generates a subcube of the specified dimensions from the .fits files,
for 12CO and 13CO. Returns the subcubes for 12CO and 13CO, respectively.
Argument format: "(ymin,ymax, xmin,xmax.)"
^ These are the parameters of the desired subcubes."""
cube12 = SpectralCube.read("paws-30m-12co10-23as-cube.fits")
cube13 = SpectralCube.read("paws-30m-13co10-23as-cube.fits")
subcube12 = cube12[:,ymin:ymax,xmin:xmax]
subcube13 = cube13[:,ymin:ymax,xmin:xmax]
return subcube12,subcube13
示例6: reduce_and_save
def reduce_and_save(filename, add_noise=False, rms_noise=0.001,
output_path="", cube_output=None,
nsig=3, slicewise_noise=True):
'''
Load the cube in and derive the property arrays.
'''
if add_noise:
if rms_noise is None:
raise TypeError("Must specify value of rms noise.")
cube, hdr = getdata(filename, header=True)
# Optionally scale noise by 1/10th of the 98th percentile in the cube
if rms_noise == 'scaled':
rms_noise = 0.1*np.percentile(cube[np.isfinite(cube)], 98)
from scipy.stats import norm
if not slicewise_noise:
cube += norm.rvs(0.0, rms_noise, cube.shape)
else:
spec_shape = cube.shape[0]
slice_shape = cube.shape[1:]
for i in range(spec_shape):
cube[i, :, :] += norm.rvs(0.0, rms_noise, slice_shape)
sc = SpectralCube(data=cube, wcs=WCS(hdr))
mask = LazyMask(np.isfinite, sc)
sc = sc.with_mask(mask)
else:
sc = filename
reduc = Mask_and_Moments(sc, scale=rms_noise)
reduc.make_mask(mask=reduc.cube > nsig * reduc.scale)
reduc.make_moments()
reduc.make_moment_errors()
# Remove .fits from filename
save_name = filename.split("/")[-1][:-4]
reduc.to_fits(output_path+save_name)
# Save the noisy cube too
if add_noise:
if cube_output is None:
reduc.cube.hdu.writeto(output_path+save_name)
else:
reduc.cube.hdu.writeto(cube_output+save_name)
示例7: warp_ellipse_to_circle
def warp_ellipse_to_circle(cube, a, b, pa, stop_if_huge=True):
'''
Warp a SpectralCube such that the given ellipse is a circle int the
warped frame.
Since you should **NOT** be doing this with a large cube, we're going
to assume that the given cube is a subcube centered in the middle of the
cube.
This requires a rotation, then scaling. The equivalent matrix is:
[b cos PA b sin PA]
[-a sin PA a cos PA ].
'''
if cube._is_huge:
if stop_if_huge:
raise Warning("The cube has the huge flag enabled. Disable "
"'stop_if_huge' if you would like to continue "
"anyways with the warp.")
else:
warn("The cube has the huge flag enabled. This may use a lot "
"of memory!")
# Let NaNs be 0
data = cube.with_fill_value(0.0).filled_data[:].value
warped_array = []
for i in range(cube.shape[0]):
warped_array.append(nd.zoom(nd.rotate(data[i], np.rad2deg(-pa)),
(1, a / b)))
warped_array = np.array(warped_array)
# We want to mask outside of the original bounds
mask = np.ones(data.shape[1:])
warp_mask = \
np.isclose(nd.zoom(nd.rotate(mask, np.rad2deg(-pa)),
(1, a / b)), 1)
# There's probably a clever way to transform the WCS, but all the
# solutions appear to need pyast/starlink. The output of the wrap should
# give a radius of b and the spectral dimension is unaffected.
# Also this is hidden and users won't be able to use this weird cube
# directly
warped_cube = SpectralCube(warped_array * cube.unit, cube.wcs)
warped_cube = warped_cube.with_mask(warp_mask)
return warped_cube
示例8: select_cloud
def select_cloud(idxarray, cloudcat):
for idx in idxarray:
entry = cloudcat[idx]
asgn = SpectralCube.read(cohrsdir+'FINALASGNS/'+
entry['orig_file']+
'_fasgn.fits')
data = SpectralCube.read(cohrsdir+'DATA/'+
entry['orig_file']+
'.fits')
mask = (asgn == entry['_idx'] *
u.dimensionless_unscaled)
cube = data.with_mask(mask)
cube = cube.minimal_subcube()
cube.write('cohrscld_{0}'.format(entry['_idx'])+'.fits',
overwrite=True)
示例9: test_qglue
def test_qglue():
from spectral_cube import SpectralCube
cube = SpectralCube.read(os.path.join(DATA, 'cube_3d.fits'))
data = parse_data(cube, 'x')[0]
assert data.label == 'x'
data['STOKES I']
assert data.shape == (2, 3, 4)
示例10: FirstLook_Cepheus
def FirstLook_Cepheus():
print("Now NH3(1,1)")
a_rms = [ 0, 135, 290, 405, 505, 665]
b_rms = [ 70, 245, 350, 455, 625, 740]
index_rms=first_look.create_index( a_rms, b_rms)
index_peak=np.arange(350,410)
file_in='Cepheus/Cepheus_NH3_11.fits'
# 1st order polynomial
file_out=file_in.replace('.fits','_base1.fits')
file_new=first_look.baseline( file_in, file_out, index_clean=index_rms, polyorder=1)
first_look.peak_rms( file_new, index_rms=index_rms, index_peak=index_peak)
print("Now NH3(2,2)")
linelist = ['NH3_22','NH3_33','C2S','HC5N','HC7N_21_20','HC7N_22_21']
vsys = -3.8*u.km/u.s
throw = 2.0*u.km/u.s
for line in linelist:
file_in = 'Cepheus/Cepheus_{0}.fits'.format(line)
s = SpectralCube.read(file_in)
s = s.with_spectral_unit(u.km/u.s,velocity_convention='radio')
a_rms = [s.closest_spectral_channel(vsys+3*throw),
s.closest_spectral_channel(vsys-throw)]
b_rms = [s.closest_spectral_channel(vsys+throw),
s.closest_spectral_channel(vsys-3*throw)]
index_peak = np.arange(s.closest_spectral_channel(vsys+3*u.km/u.s),
s.closest_spectral_channel(vsys-3*u.km/u.s))
index_rms=first_look.create_index( a_rms, b_rms)
file_out=file_in.replace('.fits','_base1.fits')
file_new=first_look.baseline( file_in, file_out,
index_clean=index_rms, polyorder=1)
first_look.peak_rms( file_new, index_rms=index_rms,
index_peak=index_peak)
示例11: write_skycoord_table
def write_skycoord_table(data, cube_ref, **kwargs):
"""
Writes out a text file with flattened coordinates of the cube
stacked with input array data. Additional arguments are passed
to astropy's text writing function.
TODO: add a useful `names` keyword?
See astropy.io.ascii.write docstring for more info.
Parameters
----------
data : array-like structure of the same xy-grid as cube_ref.
cube_ref : a cube file to get the coordinate grid from.
"""
from astropy.table import Table
from astropy.io import ascii
from spectral_cube import SpectralCube
cube = SpectralCube.read(cube_ref)
flat_coords = [cube.spatial_coordinate_map[i].flatten() for i in [1,0]]
# TODO: finish this up for multiple components
#n_repeat = np.prod(np.array(data).shape)%np.prod(cube.shape[1:])+1
table = Table(np.vstack(flat_coords +
[np.array(xy_slice).flatten() for xy_slice in data]).T)
ascii.write(table, **kwargs)
示例12: moments
def moments(cube_fits, line_values, line_names, moment, save_file=False):
"""
cube: str
The datacube in fits format to open
line_values: list of floats
The wavelengths of the lines. !!! In general: if moment=0 the required wavelenth should be air, if moment=1 it should be vacuum !!!
line_names: list of str
The identifier of the lines
moment: 0 or 1
save_file: bool, optional
Set to True if the result is to be saved as a fits file. Default is False.
example:
moment = moments('cube.fits', [4861.33, 6562.8], ['Hb', 'Ha'], moment=0)
"""
print line_values, line_names
cube=SpectralCube.read(cube_fits)
for line,stri in zip(line_values,line_names):
if moment==0:
mom = cube.spectral_slab((line-3)*u.AA, (line+3)*u.AA).sum(axis=0)
if save_file==True:
mom.hdu.writeto(str(stri)+'_moment0.fits',clobber=True)
if moment==1:
mom = cube.with_spectral_unit(u.km/u.s, rest_value=line*u.AA,velocity_convention='optical').spectral_slab(-300*u.km/u.s,300*u.km/u.s).moment1()
if save_file==True:
mom.hdu.writeto(str(stri)+'_moment1.fits',clobber=True)
return mom
示例13: S2_drawM33
def S2_drawM33(vmin=40,vmax=80, deltaX=40, deltaV=6, deltadeltaX=10, deltadeltaV=1):
"""Activates S2_draw with each of the .py file's subcube selections,
with the same args as S2_arrayM33.
Argument format: "(vmin=40,vmax=80, deltaX=40, deltaV=6, deltadeltaX=10,
deltadeltaV=1).
These MUST match the args/kwargs used in S2_arrayM33!"""
galaxyname = 'M33'
filename = 'm33.co21_iram_CLEANED'
cube = SpectralCube.read(filename+".fits")
pixelwidthDEG = cube.header['CDELT2'] # The width of each pixel, in degrees.
distancePC = 840000.0 # The distance to the galaxy that M51's .fits file deals with, in parsecs. (???) Is this number accurate, though?
pixelwidthPC = pixelwidthDEG*np.pi/180.0*distancePC # The width of each pixel, in pc.
ymin = np.array([350,600,650,525,300,250]) # These are the minimum "y" values of the regions that we're dealing with.
ymax = np.array([550,800,850,725,500,450]) # These are the corresponding maximum "y" values of these regions.
xmin = np.array([500,100,400,288,200,550]) # These are the corresponding minimum "x" values of these regions.
xmax = np.array([700,300,600,488,400,750]) # These are the corresponding maximum "x" values of these regions. (Example: The first region has ymin=350, ymax=550, xmin=500, xmax=700.)
sets = np.ravel(ymin.shape)[0] # This is the number of regions that we're dealing with.
for i in range(0,sets):
S2_draw(vmin,vmax,ymin[i],ymax[i],xmin[i],xmax[i],deltaX,deltaV,deltadeltaX,deltadeltaV,filename,galaxyname)
示例14: cube_w11
def cube_w11(region='IC348'):
if region == 'IC348':
OneOneFile = 'IC348mm/IC348mm-11_cvel_clean_rob05.fits'
TwoTwoFile = 'IC348mm/IC348mm-11_cvel_clean_rob05.fits'
vmin=7.4
vmax=10.0
elif region == 'IRAS03282':
OneOneFile = 'IRAS03282/IRAS03282-11_cvel_clean_rob05.fits'
TwoTwoFile = 'IRAS03282/IRAS03282-11_cvel_clean_rob05.fits'
vmin=6.0
vmax=8.5
elif region == 'L1451mm':
OneOneFile = 'L1451mm/L1451MM-11_cvel_clean_rob05.fits'
TwoTwoFile = 'L1451mm/L1451MM-11_cvel_clean_rob05.fits'
vmin=3.2
vmax=4.9
cube = SpectralCube.read(OneOneFile)
vcube = cube.with_spectral_unit(u.km/u.s, rest_value=freq11, velocity_convention='radio')
slab = vcube.spectral_slab( vmax*u.km/u.s, vmin*u.km/u.s)
w11=slab.moment( order=0, axis=0)
#beam = Beam.from_fits_header(fits.getheader(OneOneFile))
# Next line is to solve bug in spectralcube:
# it should be something like this in line 2234 of spectral_cube.py:
# ```
# if axis == 0 and self._meta['beam'] is not None:
# meta = { blabla, 'beam':self._meta['beam']}
# else:
# meta = { blabla}
w11._meta['beam'] = slab.beam
w11.write(OneOneFile.replace('.fits','_w11.fits'), overwrite=True)
示例15: writeplanes
def writeplanes(save_name='/mnt/work/erosolow/GRS_13CO_all.fits'):
spatial_template = fits.open('INTEG/COHRS_RELEASE1_FULL_INTEG.fit')
spectral_template = SpectralCube.read('reprojected.fits')
# Smoosh astrometry components together
spatial_header = spatial_template[0].header
spectral_header = spectral_template.header
new_header = spatial_header.copy()
new_header["NAXIS"] = 3
for keyword in ['NAXIS3', 'CRVAL3', 'CDELT3','CRPIX3','CUNIT3']:
new_header[keyword] = spectral_header[keyword]
new_header['BMAJ'] = 14./3600
new_header['BMIN'] = 14./3600
new_header['BPA'] = 0.00
if os.path.exists(save_name):
raise Exception("The file name {} already "
"exists".format(save_name))
# Open a file and start filling this with planes.
output_fits = fits.StreamingHDU(save_name, new_header)
# Again, set up a common vel axis and spin out
vel = np.linspace(-30, 160, 191)
for v in vel:
output_fits.write(fits.getdata(planesdir +
'GRSPLANE_{0}'.format(v) +
'.fits'))
output_fits.close()