import numpy as np
import radio_beam
from astropy import units as u
from astropy import wcs
from astropy.io import fits
import higal_sedfitter
import paths
import reproject
import dust_emissivity
from astropy import convolution
import pylab as pl

sharc_fn = paths.Fpath('other/SHARC_Herschel_Feathered.fits')
scuba_fn = paths.Fpath('other/scuba_Herschel_Feathered.fits')
scuba_hdr = fits.getheader(scuba_fn)

pixscale = wcs.WCS(scuba_hdr).celestial.pixel_scale_matrix[1,1]*u.deg

sharc_data,_ = reproject.reproject_interp(sharc_fn, scuba_hdr)
scuba_data = fits.getdata(scuba_fn)
ratio_map_sharc_to_scuba = sharc_data/scuba_data

# Column density is independent of pixel scale; it is related to surface
# brightness
imagecube = u.Quantity([sharc_data,scuba_data], u.MJy/u.sr)


if False:
    # don't need to fit it myself
    pixelfitter = higal_sedfitter.fit.PixelFitter(bfixed=True)
import aplpy
import paths
from astropy.io import fits
from astropy.nddata import Cutout2D
from astropy import wcs
import paths
from spectral_cube import SpectralCube
from astropy.visualization import SqrtStretch, AsinhStretch
from astropy.visualization.mpl_normalize import ImageNormalize

pl.style.use('classic')

annotation_fontsize = 10

for cubefn, suffix, (mn, mx), species in (
    (paths.Fpath('merge/lines/HNC.r2_TP_7m_12m_feather.fits'), '', (-5, 100),
     'HNC'),
        #(paths.Fpath('merge/lines/SgrB2_b3_7M_12M.HCN.image.pbcor_medsub.fits'), '_noTPnoTE', (-0.5,20), 'HCN'),
        #(paths.Fpath('merge/lines/SgrB2_b3_7M_12M.HNC.image.pbcor_medsub.fits'), '_noTPnoTE', (-0.5,20), 'HNC'),
        #(paths.Fpath('merge/lines/SgrB2_b3_7M_12M.HCOp.image.pbcor_medsub.fits'), '_noTPnoTE', (-0.5,20), 'HCOp'),
        #(paths.Fpath('merge/lines/SgrB2_b3_7M_12M.HC3N.image.pbcor_medsub.fits'), '_noTP', (-0.5,20), 'HC3N'),
        #(paths.Fpath('merge/lines/HC3N_TP_7m_12m_feather.fits'), '', (-2,200), 'HC3N'),
        #(paths.Fpath('merge/lines/HC3N_TP_7m_12m_feather_r05.fits'), 'r05', (-10,400), 'HC3N')
):

    sourcename = 'SgrB2'

    dx = 5
    slabs = [(x, x + dx) for x in range(5, 105, 5)] * u.km / u.s

    cube = SpectralCube.read(cubefn)
from astropy import coordinates
from astropy import units as u
from astropy import constants
import regions
import latex_info

from constants import distance

import reproject
from astropy import wcs
from astropy.io import fits
# workaround for new regions API
arbitrary_wcs = wcs.WCS(
    fits.getheader(
        paths.Fpath(
            'merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.image.tt0.pbcor.fits'
        )))

core_phot_tbl = Table.read(paths.tpath("continuum_photometry_withSIMBAD.ipac"),
                           format='ascii.ipac')
core_phot_tbl.add_column(
    Column(name='radius', data=np.zeros(len(core_phot_tbl)) + np.nan))

# measured from core_flux_distributions
core_powerlaw_index = 1.94

kroupa = imf.Kroupa()

o_mmin = 8
hii_cutoff = 20
Exemple #4
0
all_eigsvals = np.sort(all_eigsvals)[::-1]

eigims = []
for ii in range(20):
    eigim = np.zeros(cube.shape[1:])
    for channel in range(cube.shape[0]):
        eigim += np.nan_to_num(data[channel] *
                               np.real_if_close(eigvecs[channel, ii]))
    eigims.append(eigim)

hdul = fits.HDUList([
    fits.PrimaryHDU(np.array(eigims)),
    fits.ImageHDU(cov_matrix),
    fits.ImageHDU(all_eigsvals)
])
hdul.writeto(paths.Fpath('eigenimages_SgrB2N_spw1.fits'), overwrite=True)

cov_matrix = var_cov_cube(data, mean_sub=True)
all_eigsvals, eigvecs = np.linalg.eigh(cov_matrix)
all_eigsvals = np.real_if_close(all_eigsvals)
eigvecs = eigvecs[:, np.argsort(all_eigsvals)[::-1]]
all_eigsvals = np.sort(all_eigsvals)[::-1]

eigims = []
for ii in range(20):
    eigim = np.zeros(cube.shape[1:])
    for channel in range(cube.shape[0]):
        mean_value = np.nanmean(data[channel])
        eigim += np.nan_to_num((data[channel] - mean_value) *
                               np.real_if_close(eigvecs[channel, ii]))
    eigims.append(eigim)
Exemple #5
0
import paths
from astropy import units as u
from astropy.io import fits
from astropy import wcs
import reproject

b3 = fits.open(paths.Fpath('SgrB2_B3_continuum_QA2_minimumcutout_K.fits'))
b6 = fits.open(
    paths.Fpath('sgr_b2m.N.allspw.continuum.clean1000.image.tt0.pbcor_K.fits'))

b3r, _ = reproject.reproject_interp(
    input_data=(b3[0].data.squeeze(), wcs.WCS(b3[0].header).celestial),
    output_projection=wcs.WCS(b6[0].header).celestial,
    shape_out=b6[0].data.shape)

ratio = b3r / b6[0].data.squeeze()

ratiohdu = fits.PrimaryHDU(data=ratio, header=b6[0].header)
ratiohdu.writeto(paths.Fpath('ratio_B3toB6_N.fits'), overwrite=True)
            bottomleft = coordinates.SkyCoord(*mylims_fk5[0],
                                              unit=(u.deg, u.deg),
                                              frame='fk5')
            scalebarpos = coordinates.SkyCoord("17:47:27",
                                               "-28:26:15.0",
                                               unit=(u.h, u.deg),
                                               frame='fk5')
        else:
            raise Exception

        if line in filenames:
            hdu_line = fits.open(filenames[line])[0]
        else:
            hdu_line = fits.open(
                paths.Fpath(
                    'merge/max/SgrB2_b3_7M_12M.{0}.image.pbcor_max_medsub.fits'
                    .format(line)))[0]
        toplevel_wcs = wcs.WCS(hdu_line.header).celestial
        #wcsaxes = WCSaxes(mywcs.to_header())
        #toplevel_wcs = mywcs # hack for newer version of toplevel_wcs that is included in astropy

        fig3 = pl.figure(3,
                         figsize=bigregion_parameters[regionname]['figsize'])
        fig3.clf()
        ax = fig3.add_axes([0.15, 0.1, 0.8, 0.8], projection=toplevel_wcs)

        ra = ax.coords['ra']
        ra.set_major_formatter('hh:mm:ss.s')
        dec = ax.coords['dec']
        ra.set_axislabel("RA (J2000)", fontsize=pl.rcParams['axes.labelsize'])
        dec.set_axislabel("Dec (J2000)",
def rgbfig(
        figfilename="SgrB2N_RGB.pdf",
        lims=[([266.83404223, 266.83172659]), ([-28.373138, -28.3698755])],
        scalebarx=coordinates.SkyCoord(266.833545 * u.deg,
                                       -28.37283819 * u.deg),
        redfn=paths.Fpath('SGRB2N-2012-Q.DePree_K.recentered.fits'),
        greenfn=paths.
    Fpath('sgr_b2m.N.B3.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits'),
        bluefn=paths.
    Fpath('sgr_b2m.N.B6.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits'),
        redpercentile=99.99,
        greenpercentile=99.99,
        bluepercentile=99.99,
        stretch=visualization.AsinhStretch(),
):

    header = fits.getheader(redfn)
    celwcs = wcs.WCS(header).celestial

    redhdu = fits.open(redfn)
    greenhdu = fits.open(greenfn)
    bluehdu = fits.open(bluefn)

    greendata, _ = reproject.reproject_interp(
        (greenhdu[0].data, wcs.WCS(greenhdu[0].header).celestial),
        celwcs,
        shape_out=redhdu[0].data.squeeze().shape)
    bluedata, _ = reproject.reproject_interp(
        (bluehdu[0].data, wcs.WCS(bluehdu[0].header).celestial),
        celwcs,
        shape_out=redhdu[0].data.squeeze().shape)

    #def rescale(x):
    #    return (x-np.nanmin(x))/(np.nanmax(x) - np.nanmin(x))
    redrescale = visualization.PercentileInterval(redpercentile)
    greenrescale = visualization.PercentileInterval(greenpercentile)
    bluerescale = visualization.PercentileInterval(bluepercentile)

    rgb = np.array([
        stretch(redrescale(redhdu[0].data.squeeze())),
        stretch(greenrescale(greendata)),
        stretch(bluerescale(bluedata)),
    ]).swapaxes(0, 2).swapaxes(0, 1)

    norm = visualization.ImageNormalize(
        rgb, interval=visualization.MinMaxInterval(), stretch=stretch)

    fig1 = pl.figure(1)
    fig1.clf()
    ax = fig1.add_subplot(1, 1, 1, projection=celwcs)
    pl.imshow(rgb, origin='lower', interpolation='none', norm=norm)

    (x1, x2), (y1, y2) = celwcs.wcs_world2pix(lims[0], lims[1], 0)
    ax.axis((x1, x2, y1, y2))

    visualization_tools.make_scalebar(ax,
                                      left_side=scalebarx,
                                      length=1.213 * u.arcsec,
                                      label='0.05 pc')

    pl.savefig(paths.fpath(figfilename), bbox_inches='tight')
pl.matplotlib.rc_file('pubfiguresrc')

pl.rcParams['figure.figsize'] = (12, 8)
pl.rcParams['figure.dpi'] = 75.
pl.rcParams['savefig.dpi'] = 300.
pl.rcParams['axes.labelsize'] = 9
pl.rcParams['xtick.labelsize'] = 8
pl.rcParams['ytick.labelsize'] = 8
tick_fontsize = 6
if matplotlib.__version__[0] == '1':
    markersize = 10
elif matplotlib.__version__[0] == '2':
    markersize = 0.5

hdu = fits.open(paths.Fpath('./other/scuba_Herschel_Feathered.fits'))[0]
mywcs = wcs.WCS(hdu.header).celestial
wcsaxes = mywcs  # WCSaxes(mywcs.to_header())

fig3 = pl.figure(3)
fig3.clf()
ax = fig3.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcsaxes)

ra = ax.coords['ra']
ra.set_major_formatter('hh:mm:ss.s')
dec = ax.coords['dec']
ra.set_axislabel("RA (J2000)", fontsize=pl.rcParams['axes.labelsize'])
dec.set_axislabel("Dec (J2000)",
                  fontsize=pl.rcParams['axes.labelsize'],
                  minpad=0)
ra.ticklabels.set_fontsize(tick_fontsize)
pl.matplotlib.rc_file('pubfiguresrc')

pl.rcParams['figure.figsize'] = (12,8)
pl.rcParams['figure.dpi'] = 75.
pl.rcParams['savefig.dpi'] = 300.
pl.rcParams['axes.labelsize'] = 15
pl.rcParams['xtick.labelsize'] = 14
pl.rcParams['ytick.labelsize'] = 14
tick_fontsize = 14
if matplotlib.__version__[0] == '1':
    markersize = 6
elif matplotlib.__version__[0] == '2':
    markersize = 0.5


hdu = fits.open(paths.Fpath('column_maps/scuba_col_herscheltem.fits'))[0]
mywcs = wcs.WCS(hdu.header).celestial
wcsaxes = mywcs # WCSaxes(mywcs.to_header())

fig3 = pl.figure(3)
fig3.clf()
ax = fig3.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcsaxes)

ra = ax.coords['ra']
ra.set_major_formatter('hh:mm:ss.s')
dec = ax.coords['dec']
ra.set_axislabel("RA (J2000)", fontsize=pl.rcParams['axes.labelsize'])
dec.set_axislabel("Dec (J2000)", fontsize=pl.rcParams['axes.labelsize'], minpad=0)
ra.ticklabels.set_fontsize(tick_fontsize)
ra.set_ticks(exclude_overlapping=True)
dec.ticklabels.set_fontsize(tick_fontsize)
    visualization_tools.make_scalebar(ax,
                                      left_side=scalebarx,
                                      length=1.213 * u.arcsec,
                                      label='0.05 pc')

    pl.savefig(paths.fpath(figfilename), bbox_inches='tight')


if __name__ == "__main__":

    rgbfig(stretch=visualization.LinearStretch(), )

    rgbfig(
        figfilename='SgrB2M_RGB.pdf',
        lims=[(266.8359, 266.8325), (-28.38600555, -28.3832)],
        redfn=paths.Fpath('SGRB2M-2012-Q-MEAN.DePree.recentered.fits'),
        greenfn=paths.Fpath(
            'sgr_b2m.M.B3.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits'
        ),
        bluefn=paths.Fpath(
            'sgr_b2m.M.B6.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits'
        ),
        scalebarx=coordinates.SkyCoord(266.8336007 * u.deg,
                                       -28.38553839 * u.deg),
        redpercentile=99.99,
        greenpercentile=99.98,
        bluepercentile=99.98,
        stretch=visualization.AsinhStretch(),
    )
import numpy as np
import paths
from astropy.io import fits
from astropy.utils.console import ProgressBar
import fil_finder
from spectral_cube import SpectralCube

cube = SpectralCube.read(
    paths.Fpath('12m/SgrB2_b3_12M.HC3N.image.pbcor.contsub.fits'))
subcube = cube[100:155].minimal_subcube()

newcube = np.empty_like(subcube, dtype='int16')

for ii, imslice in enumerate(ProgressBar(subcube)):
    img = imslice.value
    hdr = header = imslice.header
    try:
        ff = fil_finder.fil_finder_2D(
            img,
            hdr,
            beamwidth=3.5,
            distance=8500,
            skel_thresh=20,
            branch_thresh=10,
            glob_thresh=65,
            adapt_thresh=10,
            pad_size=1,
        )
    except ValueError:
        print("FilFinder creation failed on iter {0}".format(ii))
        continue
Exemple #12
0
import numpy as np
from astropy import wcs
import aplpy
import paths
from astropy.io import fits
import reproject
from matplotlib.colors import Normalize, LogNorm
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
import PIL
from PIL import ImageEnhance
import pyavm
from astropy import log

if 'fncont' not in locals():
    log.info("Loading and reprojecting FITS files")
    fncont = paths.Fpath(
        'merge/SgrB2_selfcal_full_TCTE7m_selfcal4_ampphase.image.pbcor.fits')
    fnhc3n = paths.Fpath(
        'merge/max/SgrB2_b3_7M_12M.HC3N.image.pbcor_max_medsub.fits')
    fnhcn = paths.Fpath(
        'merge/max/SgrB2_b3_7M_12M.HCN.image.pbcor_max_medsub.fits')
    fnhnc = paths.Fpath(
        'merge/max/SgrB2_b3_7M_12M.HNC.image.pbcor_max_medsub.fits')
    fnhcop = paths.Fpath(
        'merge/max/SgrB2_b3_7M_12M.HCOp.image.pbcor_max_medsub.fits')

    outhdr = fits.getheader(fncont)
    cont = fits.getdata(fncont)
    hcn = reproject.reproject_interp(fnhcn, outhdr, order=1)[0]
    hc3n = reproject.reproject_interp(fnhc3n, outhdr, order=1)[0]
    hnc = reproject.reproject_interp(fnhnc, outhdr, order=1)[0]
    hcop = reproject.reproject_interp(fnhcop, outhdr, order=1)[0]
Exemple #13
0
from spectral_cube import SpectralCube, Projection

import paths
import files
import regions

import pylab as pl

regs = regions.read_ds9(paths.rpath('sio_masers.reg'))
v2maser = regs[2]

cont_b6 = fits.open(files.contb6_rm2)
cont_b3 = fits.open(files.contb3_rm2)

siov2j2im = paths.Fpath('SiO_v2_j2_peak_N.fits')
if os.path.exists(siov2j2im):
    siov2j2 = Projection.from_hdu(fits.open(siov2j2im))
else:
    region, spw, band, freq = 'N', 0, 3, 85.640452 * u.GHz
    fn = paths.eFpath(
        'sgr_b2m.{0}.spw{1}.B{2}.lines.clarkclean1000.robust0.5.image.pbcor.medsub.fits'
        .format(region, spw, band))
    siov2j2 = (SpectralCube.read(fn).with_spectral_unit(
        u.km / u.s, velocity_convention='radio',
        rest_value=freq).spectral_slab(55 * u.km / u.s,
                                       110 * u.km / u.s).to(u.K)).max(axis=0)
    siov2j2.write(siov2j2im)

hcnv3j1im = paths.Fpath('HCN_v3_j1_peak_N.fits')
if os.path.exists(hcnv3j1im):
Exemple #14
0
})

print(freqs)

cubes = {}
mx = {}

for region in ("N", "M"):
    for spw in (0, 1, 2, 3):
        for band in (3, 6):
            for line in freqs:
                fn = 'full_SgrB2{0}_spw{1}_lines_cutout{0}_medsub.fits'.format(
                    region, spw)
                fn = 'sgr_b2m.{0}.spw{1}.B{2}.lines.clarkclean1000.robust0.5.image.pbcor.medsub.fits'.format(
                    region, spw, band)
                cube = SpectralCube.read(paths.Fpath(fn))
                freq = freqs[line]
                if cube.spectral_extrema[0] < freq < cube.spectral_extrema[1]:
                    print("Matched {line} to spw {spw}".format(line=line,
                                                               spw=spw))
                    subcube = (cube.with_spectral_unit(
                        u.km / u.s,
                        velocity_convention='radio',
                        rest_value=freq).spectral_slab(25 * u.km / u.s,
                                                       95 * u.km / u.s))
                    try:
                        subcube = subcube.to(u.K)
                    except Exception as ex:
                        print("Failed: {0}".format(ex))
                    if 'OBJECT' in subcube.meta:
                        subcube.meta['OBJECT'] = subcube.meta['OBJECT'] + line
Exemple #15
0
from spectral_cube import SpectralCube
from astropy import coordinates
import paths

from astropy import units as u

sgb2m = coordinates.SkyCoord.from_name('Sgr B2 (M)')

cube = (SpectralCube.read(
    paths.Fpath(
        'merge/lines/HCN.r2_TP_7m_12m_feather.fits')).with_spectral_unit(
            u.km / u.s, velocity_convention='radio'))

xp, yp = map(int,
             cube.wcs.celestial.wcs_world2pix(sgb2m.ra.deg, sgb2m.dec.deg, 0))

s19cube = SpectralCube.read(paths.Fpath('tp/tp_concat.spw19.image.fits'))
s19cube = s19cube.to(u.K, s19cube.beam.jtok_equiv(s19cube.spectral_axis))
hcncube = s19cube.with_spectral_unit(u.km / u.s,
                                     velocity_convention='radio',
                                     rest_value=cube.wcs.wcs.restfrq * u.Hz)
hcnspec = hcncube.spectral_slab(-165 * u.km / u.s,
                                130 * u.km / u.s).mean(axis=(1, 2))

import pylab as pl

pl.clf()
(5 * hcnspec).quicklook(color='k')
hcnsgb2spec = cube[:, yp, xp]
(hcnsgb2spec - 4 * hcnsgb2spec.unit).quicklook(color='k')
otherhcnspec = cube[:, yp - 60, xp - 20]
Exemple #16
0
yy,xx = np.indices([grid_size, grid_size])
x_centers,y_centers = mywcs.wcs_pix2world(xx.flat, yy.flat, 0)
grid_coords = coordinates.SkyCoord(x_centers*u.deg, y_centers*u.deg, frame='fk5')


cont_tbl = Table.read(paths.tpath('continuum_photometry.ipac'), format='ascii.ipac')
sgrb2_coords = coordinates.SkyCoord(cont_tbl['RA'], cont_tbl['Dec'],
                                    unit=(u.deg, u.deg), frame='fk5',)

gridded_stars = np.histogram2d(sgrb2_coords.ra.deg, sgrb2_coords.dec.deg,
                               bins=[x_edges[::-1], y_edges])[0][::-1,:].T

hdu = fits.PrimaryHDU(data=gridded_stars, header=header)

hdu.writeto(paths.Fpath('stellar_density_grid.fits'), overwrite=True)
hdu.data *= mass_represented_by_a_source.value
hdu.writeto(paths.Fpath('stellar_mass_density_grid.fits'), overwrite=True)

_,nn11_grid,_ = coordinates.match_coordinates_sky(grid_coords, sgrb2_coords,
                                                  nthneighbor=11)
nn11_grid = nn11_grid.reshape([grid_size, grid_size])
nn11_grid_pc = (nn11_grid * distance).to(u.pc, u.dimensionless_angles())



herschel25 = fits.open(paths.cpath('gcmosaic_column_conv25.fits'))
herschel36 = fits.open(paths.cpath('gcmosaic_column_conv36.fits'))

herschel25reproj,_ = reproject.reproject_interp(herschel25, header)
herschel36reproj,_ = reproject.reproject_interp(herschel36, header)
import radio_beam
import paths

from restfreqs import restfreqs

import pylab as pl
pl.close('all')

apertures = ((1, 2, 3, 4) * u.pc / (8.4 * u.kpc)).to

velo = 62.5 * u.km / u.s

species_names = list(restfreqs.keys())
frequencies = u.Quantity([restfreqs[key] for key in species_names], unit=u.GHz)

for fn in glob.glob(paths.Fpath('tp/tp_concat*fits')):
    basefn = os.path.basename(fn)
    outf = paths.Fpath('tp/avgspectra/avg_{0}'.format(basefn))
    if not os.path.exists(outf):
        cube = SpectralCube.read(fn)
        cube.allow_huge_operations = True
        mad = cube.mad_std(axis=0)
        sum = (cube * mad).sum(axis=(1, 2))
        mean = sum / np.nansum(mad)
        mean.write(paths.Fpath(
            'tp/avgspectra/weighted_avg_{0}'.format(basefn)),
                   overwrite=True)
        mn = cube.mean(axis=(1, 2))
        mn.write(outf, overwrite=True)

for fn in glob.glob(paths.Fpath('tp/tp_concat*fits')):
Exemple #18
0
import numpy as np
from constants import distance
import radio_beam
from astropy import units as u
from astropy import wcs
from astropy.io import fits
import higal_sedfitter
import paths
import reproject
import dust_emissivity
from astropy import convolution
import pylab as pl

herschel25_colfile = paths.Fpath(
    'other/Herschel25umcolum_regridded_match_stellar.fits')
herschel36_colfile = paths.Fpath(
    'other/Herschel36umcolum_regridded_match_stellar.fits')
herschel25 = fits.getdata(herschel25_colfile) * u.M_sun / u.pc**2
herschel36 = fits.getdata(herschel36_colfile) * u.M_sun / u.pc**2

sharc_colfile = paths.cpath('column_maps/sharc_col_herscheltem.fits')
scuba_colfile = paths.cpath('column_maps/scuba_col_herscheltem.fits')
sharc_col = fits.getdata(sharc_colfile) * u.cm**-2
scuba_col = fits.getdata(scuba_colfile) * u.cm**-2

sharc_beam = 10 * u.arcsec
scuba_beam = 10 * u.arcsec
scuba_beam_pc = (scuba_beam * distance).to(u.pc, u.dimensionless_angles())
h25bm_pc = (25 * u.arcsec * distance).to(u.pc, u.dimensionless_angles())
h36bm_pc = (36 * u.arcsec * distance).to(u.pc, u.dimensionless_angles())
FWHM_SCALE = np.sqrt(8 * np.log(2))
Exemple #19
0
import paths

# old
#contfnpath = paths.tmpath('te/SgrB2_selfcal_full_TE_selfcal4_ampphase.image.pbcor.fits')
#contfnpath = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.image.tt0.pbcor.fits')

# contfilename = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal6_ampphase_taylorterms_multiscale_deeper_mask1.5mJy.image.tt0.pbcor.fits')
# alphafilename = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.alpha.fits')
# alphaerrorfilename = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.alpha.error.fits')
contfilename = paths.Fpath(
    'merge/continuum/SgrB2_selfcal_full_TCTE7m_try2_selfcal6_ampphase_deeper_mask1.5mJy.image.tt0.pbcor.fits'
)
alphafilename = paths.Fpath(
    'merge/continuum/SgrB2_selfcal_full_TCTE7m_try2_selfcal6_ampphase_deeper_mask1.5mJy.alpha.fits'
)
alphaerrorfilename = paths.Fpath(
    'merge/continuum/SgrB2_selfcal_full_TCTE7m_try2_selfcal6_ampphase_deeper_mask1.5mJy.alpha.error.fits'
)
import pyspeckit
import pyregion
import paths
import pylab as pl
import warnings

from latex_info import (latexdict, format_float, round_to_n,
                        strip_trailing_zeros, exp_to_tex)
latexdict = latexdict.copy()

warnings.filterwarnings('ignore', category=PossiblySlowWarning)

regs = pyregion.open(paths.rpath('SgrB2_1.3cm_hiiRegions_shiftedtoALMA.reg'))

cube = SpectralCube.read(
    paths.Fpath(
        'M_cutouts/SgrB2_b3_12M_TE.H41a.image.pbcor_M_cutout.medsub.fits'))

if 'fit_values' not in locals():
    fit_values = {}
    coords = {}

    for reg in regs:
        if 'text' not in reg.attr[1]:
            continue
        name = reg.attr[1]['text'].strip("{}")

        try:
            cutout = cube.subcube_from_ds9region(pyregion.ShapeList([reg])).to(
                u.K,
                cube.beam.jtok_equiv(
                    cube.with_spectral_unit(u.GHz).spectral_axis))
    pl.rcParams['axes.labelsize'] = 8
    pl.rcParams['axes.titlesize'] = 8
    pl.rcParams['xtick.labelsize'] = 6
    pl.rcParams['ytick.labelsize'] = 6
    pl.rcParams['axes.linewidth'] = 0.15
    tick_fontsize = 6
    markersize = 3
else:
    pl.rcParams['savefig.dpi'] = 300.
    tick_fontsize = 10
    markersize = 8


scalebarpos = coordinates.SkyCoord("17:47:32.", "-28:26:33.0", unit=(u.h, u.deg), frame='fk5')

contfnr2 = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_try2_selfcal6_ampphase_taper1.5as_r2_mask5mJy.image.tt0.pbcor.fits')
contfnr0 = paths.Fpath('merge/continuum/SgrB2_selfcal_full_TCTE7m_try2_selfcal6_ampphase_deeper_mask1.5mJy.image.tt0.pbcor.fits')
for contfn,name,(vmin,vmax,truemax) in [(contfnr2, "taper", (-1,50,2000)), (contfnr0, "hires",(-1,5,200))]:
    hdu = fits.open(contfn)[0]

    mywcs = wcs.WCS(hdu.header).celestial
    wcsaxes = mywcs # hack for newer version of wcsaxes that is included in astropy

    fig3 = pl.figure(3)
    fig3.clf()
    ax = fig3.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcsaxes)

    ra = ax.coords['ra']
    ra.set_major_formatter('hh:mm:ss.s')
    dec = ax.coords['dec']
    ra.set_axislabel("RA (J2000)", fontsize=pl.rcParams['axes.labelsize'])
Exemple #22
0
import os
from astropy import constants, units as u, table, stats, coordinates, wcs, log, coordinates as coord
from astropy.io import fits

from spectral_cube import SpectralCube, Projection

import paths
import files
import regions

import pylab as pl

regs = regions.read_ds9(paths.rpath('sio_masers.reg'))
v2maser = regs[2]

bluefile = paths.Fpath('SgrB2_N_SiO_blue_20to50kms.fits')
redfile = paths.Fpath('SgrB2_N_SiO_blue_77to100kms.fits')
if os.path.exists(bluefile):
    blue = Projection.from_hdu(fits.open(bluefile))
    red = Projection.from_hdu(fits.open(redfile))
else:

    siocube = (SpectralCube.read(
        '/Volumes/external/sgrb2/full_SgrB2N_spw0_lines_cutoutN_medsub.fits').
               with_spectral_unit(u.km / u.s,
                                  velocity_convention='radio',
                                  rest_value=217.10498 * u.GHz).spectral_slab(
                                      -200 * u.km / u.s, 250 * u.km / u.s))
    siocube.spectral_slab(0 * u.km / u.s, 120 * u.km / u.s).write(
        'SgrB2_N_SiO_medsub_cutout.fits', overwrite=True)
Exemple #23
0
import paths

contb6_rm2 = paths.Fpath(
    'sgr_b2m.N.B6.allspw.continuum.r-2.cleanto2mJy_2terms.image.tt0.pbcor.fits'
)

# TODO: use clean version
contb3_rm2 = paths.Fpath(
    'sgr_b2m.N.B3.allspw.continuum.r-2.dirty.image.tt0.pbcor.fits')

contb6_M_rm2 = paths.Fpath(
    'sgr_b2m.M.B6.allspw.continuum.r-2.cleanto2mJy_2terms.image.tt0.pbcor.fits'
)
contb3_M_rm2 = paths.Fpath(
    'sgr_b2m.M.B3.allspw.continuum.r-2.dirty.image.tt0.pbcor.fits')
import reproject

import pylab as pl

pl.matplotlib.rc_file('pubfiguresrc')

pl.rcParams['figure.figsize'] = (12, 8)
pl.rcParams['figure.dpi'] = 300.
pl.rcParams['savefig.dpi'] = 300.
pl.rcParams['axes.labelsize'] = 9
pl.rcParams['xtick.labelsize'] = 8
pl.rcParams['ytick.labelsize'] = 8
pl.rcParams['font.size'] = 6
tick_fontsize = 6

fnhc3n = paths.Fpath(
    'merge/max/SgrB2_b3_7M_12M.HC3N.image.pbcor_max_medsub.fits')
fnhcn = paths.Fpath(
    'merge/max/SgrB2_b3_7M_12M.HCN.image.pbcor_max_medsub.fits')

# FF2 = aplpy.FITSFigure(fnhc3n)
# FF2.show_grayscale(vmax=0.06, invert=True)
# FF2.show_contour(fnhcn, levels=[0.02,0.03,0.04,0.05,0.06,0.1,0.2,0.3,0.4],
#                  colors=[(1,0,0,x) for x in np.linspace(0,1,10)],
#                  filled=True, )
# FF2.save(paths.fpath("HC3N_grayscale_with_HCN_red_filled_contours.png"), dpi=150)
# FF2.recenter(266.8318615, -28.3940598, width=0.062, height=0.105)
# FF2.save(paths.fpath("HC3N_grayscale_with_HCN_red_filled_contours_zoom.png"), dpi=150)

hdu = fits.open(fnhc3n)[0]
mywcs = wcs.WCS(hdu.header).sub([wcs.WCSSUB_CELESTIAL])
wcsaxes = WCSaxes(mywcs.to_header())
Exemple #25
0
from astropy.io import fits
from astropy import coordinates
import radio_beam

for fn in (
        'SgrB2_B3_continuum_QA2_minimumcutout.fits',
        'sgr_b2m.N.allspw.continuum.clean1000.image.tt0.pbcor.fits',
        'sgr_b2m.N.B6.allspw.continuum.r-2.cleanto2mJy_2terms.image.tt0.pbcor.fits',
        #'sgr_b2m.M.B3.allspw.continuum.r-2.dirty.image.tt0.pbcor.fits',
        'sgr_b2m.N.B3.allspw.continuum.r-2.dirty.image.tt0.pbcor.fits',
        #'sgr_b2m.M.B3.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits',
        #'sgr_b2m.N.B3.allspw.continuum.r0.5.clean1000.image.tt0.pbcor.fits',
        #'sgr_b2m.M.B3.allspw.continuum.r-2.clean1000.image.tt0.pbcor.fits',
):

    fh = fits.open(paths.Fpath(fn))

    if fh[0].header['RADESYS'] == 'FK5':
        refcen = coordinates.SkyCoord(fh[0].header['CRVAL1'] * u.deg,
                                      fh[0].header['CRVAL2'] * u.deg,
                                      frame='fk5').icrs
        fh[0].header['CRVAL1'] = refcen.ra.deg
        fh[0].header['CRVAL2'] = refcen.dec.deg
        fh[0].header['RADESYS'] = 'ICRS'

    beam = radio_beam.Beam.from_fits_header(fh[0].header)

    fh[0].data = (fh[0].data * beam.jtok(fh[0].header['CRVAL3'] * u.Hz)).value

    fh.writeto(paths.Fpath(fn.replace(".fits", "_K.fits")), overwrite=True)