def w51main(table=None):
    if table is None:
        table = initialize_table()
    return do_indiv_fits(rpath("w51main_spectral_apertures.reg"),
                         'spectralfits/spectralfits_w51main',
                         ncomp=2,
                         tableprefix="w51main_",
                         table=table)
def filaments_left(table=None):
    if table is None:
        table = initialize_table()
    ncomp = [2,2,2,2,1,2,1]
    outpfx = 'spectralfits/spectralfits_70kmscloudLeft'
    spectra = do_indiv_fits(rpath("filament_leftside_spectral_apertures.reg"),
                            outpfx, ncomp=ncomp,
                            tableprefix="filamentsleft_",
                            table=table)
    dofit(spectra[0], spectra[0].header['CONT11'], spectra[0].header['CONT22'], vguesses=[64, 68], ncomp=2)
    plotitem(spectra[0], 0, dolegend=True)
    pl.figure(spectra[0].plotter.figure.number)
    pl.savefig(os.path.join(datapath, outpfx+'_aperture_%s_%s_legend.pdf' % (spectra[0].specname,'back')),
               bbox_extra_artists=[spectra[0].specfit.fitleg])

    return spectra
def maus(table=None):
    if table is None:
        table = initialize_table()

    limits, limited = modelpars()
    limits[12] = (40, 80)
    limits[13] = (1,3)
    limits[5] = (1,3)
    limited[5] = (True,True)
    limited[13] = (True,True)

    ncomp = [2,2,2,2,2,2]
    # front2nd means "continuum in front of 2nd component?"
    # front2nd[3] is sketchy, 5 is uncertain
    front2nd = [True, False, True, False, True, True]

    outpfx = 'spectralfits/spectralfits_maus'

    spectra = do_indiv_fits(rpath("maus_spectral_apertures.reg"),
                            outpfx,
                            ncomp=ncomp,
                            limits=limits,
                            limited=limited,
                            vguesses=[64,50],
                            tableprefix="maus_",
                            table=table)


    for ii,sp in enumerate(spectra):

        if front2nd[ii]:
            dofit(sp, sp.header['CONT11'], sp.header['CONT22'],
                  vguesses=[68,50],
                  limits=limits,
                  limited=limited,
                  c11b=2.7315, c22b=2.7315,
                  ncomp=ncomp[ii])

            plotitem(sp, ii, dolegend=True)

            pl.figure(sp.plotter.figure.number)
            pl.savefig(os.path.join(datapath,outpfx+'_aperture_%s_%s_legend.pdf' % (sp.specname,'both')),
                       bbox_extra_artists=[sp.specfit.fitleg])
def middlechunk(table=None):
    if table is None:
        table = initialize_table()
    ncomp = [2,2,1,1,1,1,1]
    ncomp = [2,2,2,2,1,1,2] # in 3,4,7, second comp is at 70 kms
    outpfx = 'spectralfits/spectralfits_63kmscloud'
    spectra = do_indiv_fits(rpath("middlechunk_spectral_apertures.reg"),
                            outpfx,
                            ncomp=ncomp,
                            tableprefix="middlechunk_",
                            table=table)

    sp = spectra[0]
    dofit(sp, sp.header['CONT11'], sp.header['CONT22'],
          vguesses=[59,63], ncomp=2)

    plotitem(sp, 0, dolegend=True)

    pl.figure(sp.plotter.figure.number)
    pl.savefig(outpfx+'_aperture_%s_%s_legend.pdf' % (sp.specname,'back'),
               bbox_extra_artists=[sp.specfit.fitleg])

    for ii,sp in enumerate(spectra):
        if ii == 0:
            continue
        dofit(sp, sp.header['CONT11'], sp.header['CONT22'],
              vguesses=[60,68],
              c11b=2.7315, c22b=2.7315,
              ncomp=ncomp[ii])

        plotitem(sp, ii, dolegend=True)

        pl.figure(sp.plotter.figure.number)
        pl.savefig(outpfx+'_aperture_%s_%s_legend.pdf' % (sp.specname,'both'),
                   bbox_extra_artists=[sp.specfit.fitleg])

    return spectra
Beispiel #5
0
#
## perpendicular to outflow (ish)
#e2diskycoords = "19:23:44.197,+14:30:37.34,19:23:43.960,+14:30:34.55,19:23:43.882,+14:30:32.21,19:23:43.851,+14:30:31.26".split(",")
## perpendicular to SiO outflow
#e2diskycoords = "19:23:44.032,+14:30:36.29,19:23:43.909,+14:30:32.90".split(",")
#
## big, perp to CO (very, very coarsely)
#e8diskycoords = "19:23:43.913,+14:30:29.96,19:23:43.874,+14:30:26.09".split(",")
## small, perp to SiO outflow
#e8diskycoords = "19:23:43.928,+14:30:29.17,19:23:43.882,+14:30:27.18".split(",")

for ii, direction in enumerate(('perpco', 'perpsio')):
    diskycoorddict = {}
    for source in ('e2e', 'e8', 'north', 'lacy'):
        diskycoord_list = pyregion.open(
            paths.rpath(
                "{0}_disk_pvextract.reg".format(source)))[ii].coord_list
        diskycoords = coordinates.SkyCoord([
            "{0} {1}".format(diskycoord_list[jj], diskycoord_list[jj + 1])
            for jj in range(0, len(diskycoord_list), 2)
        ],
                                           unit=(u.deg, u.deg),
                                           frame='fk5')
        diskycoorddict[source] = diskycoords

    diskycoorddict['e2'] = diskycoorddict['e2e']

    for name, cutoutname, source, vrange in (
        ('lacy', 'north', lacy, (50, 75)),
        ('north', 'north', north, (45, 75)),
        ('e8', 'e8', e8, (45, 75)),
        ('e2', 'e2', e2e, (45, 70)),
pl.close(1)
fig = pl.figure(1,figsize=(15,10))
fig.clf()
F = aplpy.FITSFigure(datapath+'v2.0_ds2_l050_13pca_map20_reproject.fits',
                     figure=fig, convention='calabretta', colorbar=False,
                     color=False)

H = fits.Header.fromtextfile(paths.pdpath('hdr4096.hdr'))
hwcs = wcs.WCS(H)
#F.show_rgb('/Volumes/128gbdisk/w51/pngs/W51_4096sq_WISE_bolo_mosaic_rotated_blackbg.png',wcs=hwcs)
F.show_rgb(paths.pdpath('W51_4096sq_WISE_bolo_mosaic_rotated_blackbg.png'),
           wcs=hwcs)

#F.show_regions(paths.rpath('large_scale_regions.reg'))
regions = pyregion.open(paths.rpath('large_scale_regions.reg'))
#text = re.compile("text={([^}]*)}")
for reg in regions:
    #t = text.search(reg.comment).groups()[0]
    t = reg.attr[1]['text']
    F.add_label(reg.coord_list[0], reg.coord_list[1], t, color='white',
                size=16, weight='bold')
F.set_tick_labels_xformat('dd.d')
F.set_tick_labels_yformat('dd.d')
F.recenter(49.27, -0.32, width=0.9, height=0.4)
F.save(paths.fpath('W51_wisecolor_largescale_labeled.pdf'), dpi=72)
F.show_rgb(paths.dpath("make_pretty_picture/W51_modified.png",paths.datapath_w51),
           wcs=hwcs)
F.save(paths.fpath('W51_wisecolor_modified_largescale_labeled.pdf'), dpi=72)

F.add_scalebar(((10*u.pc)/(5.1*u.kpc)*u.radian).to(u.deg).value)
import numpy as np
from astropy import coordinates
from astropy import units as u
from astropy.io import fits
from astropy import wcs
import pyregion
import paths

fh = fits.open(paths.dpath('longbaseline/W51e2cax.cont.image.pbcor.fits'))
mywcs = wcs.WCS(fh[0].header).sub([wcs.WCSSUB_CELESTIAL])
pixscale = (mywcs.pixel_scale_matrix**2).sum()**0.5
reg = pyregion.open(
    paths.rpath('cores_longbaseline_spectralextractionregions_pix.reg'))

with open(paths.rpath('cores_longbaseline_spectralextractionregions.reg'),
          'w') as rfh:
    rfh.write("global color=red\n")
    rfh.write("fk5\n")

    for rr in reg:
        if rr.name == 'circle':
            x, y = mywcs.wcs_pix2world(rr.coord_list[0], rr.coord_list[1], 1)
            r = pixscale * rr.coord_list[2]
            rfh.write("circle({0}, {1}, {2}) # text={{{3}}}\n".format(
                x, y, r, rr.attr[1]['text']))
        elif rr.name == 'ellipse':
            x, y = mywcs.wcs_pix2world(rr.coord_list[0], rr.coord_list[1], 1)
            maj, min = pixscale * np.array(rr.coord_list[2:4])
            pa = rr.coord_list[4]
            rfh.write(
                "ellipse({0}, {1}, {2}, {3}, {4}) # text={{{5}}}\n".format(
        plotnum += 1

    if figsavename is not None:
        pl.savefig(figsavename, bbox_inches='tight')



if __name__ == "__main__":

    import pyregion
    import paths
    import pyspeckit
    import glob
    from ch3oh_model import load_and_convert_spectra

    core_regions = pyregion.open(paths.rpath('cores.reg'))

    core_names = [r.attr[1]['text'] for r in core_regions]

    full_results = {}

    """
    NOTE: the J=25 lines are in the line wings of SO.  That can artificially
    inflate the fitted amplitude if a spw-wide continuum subtraction is done.
    """

    # now fit 'em all...
    #for cn in core_names:
    for cn in ['ALMAmm51',]: # debug
        spectra = load_and_convert_spectra('{corename}_spw[0-4]_mean.fits'
                                           .format(corename=cn))
Beispiel #9
0
    cube = SpectralCube.read(
        paths.dpath(
            'cubes/OrionSourceI_Unknown_4_robust0.5.maskedclarkclean10000_medsub_K.fits'
        ))
    cube = SpectralCube.read(
        paths.dpath(
            'cubes/OrionSourceI_Unknown_4_robust0.5maskedclarkclean10000_medsub_K.fits'
        ))
    m1 = cube.moment1()
    m0 = cube.moment0()
    mask = m0.value > 300

    vmap = m1
    vmap[~mask] = np.nan

    r = regions.read_ds9(paths.rpath('sourceI_enclosing_ellipse.reg'))[0]
    rp = r.to_pixel(vmap.wcs)
    mask = rp.to_mask()

    vmap_ = np.empty(vmap.shape) * np.nan
    vmap_[mask.bbox.slices] = vmap[mask.bbox.slices].value * mask.data
    hdu = vmap.hdu
    hdu.data = vmap_
    hdu.writeto(vmap_name, overwrite=True)
else:
    hdu = fits.open(vmap_name)[0]
vmap = spectral_cube.lower_dimensional_structures.Projection.from_hdu(hdu)

# step 2: stack

for band in ('B3', 'B6', 'B7'):
from astropy import coordinates
#e2e = coordinates.SkyCoord("19:23:43.939", "14:30:34.57", frame='fk5', unit=(u.hour, u.deg))
pcube_cont_K7.show_fit_param(2,vmin=50,vmax=63)
#pcube_cont_K7.mapplot.FITSFigure.recenter(e2e.ra.deg, e2e.dec.deg, 0.3/3600.)




guesses[0,:] = 1
guesses[1,:] = -1
guesses[2,:] = 56
guesses[3,:] = 1.5

cube_k8 = SpectralCube.read(paths.dpath('longbaseline/velo_cutouts/e2e_CH3CNv_0_12_8_-11_8_.fits'))
cube_k8 = cube_k8.subcube_from_ds9region(pyregion.open(paths.rpath('w51e2box_ch3cn.reg')))

pcube_cont_K8 = pyspeckit.Cube(cube=cube_k8)
start_point = (43,43) # np.unravel_index(np.nanargmax(peak*mask), peak.shape)
sp = pcube_cont_K8.get_spectrum(start_point[0], start_point[1])
sp.plotter()
sp.specfit(fittype='vheightgaussian', guesses=guesses[:,43,43],
           limitedmax=[T,T,T,T,T], limitedmin=[T,T,T,T,T],
           maxpars=[5,0,61,6],
           minpars=[0,-5,52,0],)

k8fitfn = 'e2e_CH3CN_K8_Gaussian_Absorption_fits'
if os.path.exists(k8fitfn):
    pcube_cont_K8.load_model_fit(k8fitfn, npars=4)
else:
    pcube_cont_K8.fiteach(fittype='vheightgaussian', guesses=guesses, integral=False,
    assert w.naxis == 2

    F = aplpy.FITSFigure(hdu,convention='calabretta',figure=figure)
    #F = aplpy.FITSFigure(dpath+'W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.rot45.fits',convention='calabretta',figure=figure)
    #F.tick_labels.set_xformat('dd.dd')
    #F.tick_labels.set_yformat('dd.dd')
    F.tick_labels.set_font(size=18)
    F.axis_labels.set_font(size=20)
    F.show_grayscale(stretch='arcsinh',vmin=vmin,vmax=vmax, invert=True)
    #e1 = coordinates.ICRS(290.93263,14.50745,unit=('deg','deg'))
    #F.recenter(e1.ra.value,e1.dec.value,width=1/60.,height=1/60.)
    #F.recenter(290.92633,14.514769,radius=1.4/60.)
    F.recenter(290.92345,14.511772,radius=1.1/60.)
    F.tick_labels.set_x_full_label_side('left')
    F.add_scalebar(length=((0.5 * u.pc)/(5.4*u.kpc)*u.radian).to(u.degree).value)
    F.scalebar.set_label('0.5 pc')
    F.scalebar.set_color('black')
    F.scalebar.set_linewidth(3)
    F.scalebar.set_font_size(20)
    F.add_colorbar()
    F.colorbar.set_axis_label_text("Jy")
    F.save(paths.fpath('diffuse/{0}_overview.pdf'.format(name)), dpi=300)

    F.recenter(290.92345,14.511772,radius=1.6/60.)
    F.show_regions(paths.rpath("diffuse_hii_region_labels.reg"))
    F.save(paths.fpath('diffuse/{0}_overview_diffusehiiregionlabels.pdf'.format(name)), dpi=300)

    F.remove_layer('region_set_1')
    F.show_regions(paths.rpath("pointsource_labels.reg"))
    F.save(paths.fpath('diffuse/{0}_overview_pointsourcelabels.pdf'.format(name)), dpi=300)
Beispiel #12
0
import copy
import numpy as np
import pyregion
from astropy import units as u
from astropy import coordinates
from astropy.utils.console import ProgressBar
from scipy.sparse.csgraph import minimum_spanning_tree
import paths
from common_constants import distance

regions = pyregion.open(paths.rpath('pointsource_centroids.reg'))

coords = coordinates.SkyCoord([x.coord_list for x in regions],
                              unit=('deg', 'deg'))

separation_matrix = np.array(
    [coords.separation(y) for y in ProgressBar(coords)])

ordered_separation_matrix = np.argsort(separation_matrix.ravel()).reshape(
    separation_matrix.shape)
ordered_separation_matrix[separation_matrix == 0] = 0

ordered_edges = np.argsort(separation_matrix.ravel())
lefts, rights = np.unravel_index(ordered_edges, separation_matrix.shape)

separation_matrix[separation_matrix == 0] = np.inf

#Prim's algorithm:
vertices = [0]
all_vertices = list(range(len(coords)))
all_vertices.remove(0)
        if k not in pruned_ppcat.keys():
            pruned_ppcat.add_column(Column(name=k, data=columns[k]))

    for k in pruned_ppcat.colnames:
        if "." in k:
            pruned_ppcat.rename_column(k, k.replace(".","p"))

annulus_mean = ((pruned_ppcat['cont_flux0p4arcsec']-pruned_ppcat['cont_flux0p2arcsec']) /
                (np.pi*(0.4-0.2)**2/pixel_scale_as**2) * ppbeam)
core_ish = pruned_ppcat['peak_cont_flux'] > annulus_mean
pruned_ppcat.add_column(Column(data=core_ish, name='corelike'))

pruned_ppcat.meta = {'keywords':
                     {'ppbeam': {'value': ppbeam},
                      'beam_area_sr': {'value': beam.sr.value},
                      'pixel_scale_as': {'value': pixel_scale_as},
                      'mass_conversion_factor': {'value': masscalc.mass_conversion_factor()},
                      'column_conversion_factor': {'value': masscalc.col_conversion_factor(beam.sr)},
                     }
                    }

pruned_ppcat.write(paths.tpath("dendrogram_continuum_catalog.ipac"),
                   format='ascii.ipac')

with open(paths.rpath("dendrogram_cores.reg"), 'w') as fh:
    fh.write("fk5\n")
    for row in pruned_ppcat:
        fh.write("ellipse({x_cen}, {y_cen}, {major_sigma}, "
                 "{minor_sigma}, {position_angle}) # text={{{_idx}}}\n"
                 .format(**dict(zip(row.colnames, row))))
    ax.set_xlabel("Galactic Longitude")
    ax.set_ylabel(r'$V_{LSR} [$km s$^{-1}]$')
    ax.set_title(r"Slice $\ell=%0.2f$" % (zax[slice_pix]))

    pl.savefig(fpath('pvdiagram_slice_ell=%0.2f.pdf' % zax[slice_pix]),
               bbox_inches='tight')



oneone = SpectralCube.read(dpath('W51_H2CO11_taucube_supersampled.fits'))
twotwo = SpectralCube.read(dpath('W51_H2CO22_pyproc_taucube_lores_supersampled.fits'))
thirteen = SpectralCube.read(dpath('grs_48and50_cube_supersampledh2cogrid.fits',datapath_w51))
thirteen._mask = LazyMask(lambda x: 1, thirteen)
#sl13 = thirteen.spectral_slab(40*u.km/u.s, 80*u.km/u.s)
#sl13mom0 = sl13.moment0()
mask = (thirteen > 0.1) | (LazyMask(np.isnan, thirteen))
comasked = oneone.with_mask(mask)
slab_masked = comasked.spectral_slab(40*u.km/u.s, 80*u.km/u.s)
#spectral_cube.wcs_utils.check_equality(mask._wcs, comasked.wcs, verbose=True)
mom0 = slab_masked.moment0()
fig2 = pl.figure(2)
fig2.clf()
F = aplpy.FITSFigure(mom0.hdu, figure=fig2)
F.show_grayscale()
F.recenter(49.182984, -0.33612413, width=0.7, height=0.45)
F.show_regions(rpath('cyan_segments.reg'))


pl.draw()
pl.show()
                                       u.M_sun/u.Jy /
                                       (0.0027*u.deg*masscalc.distance).to(u.pc, u.dimensionless_angles())
                                      )
     )

dendro_merge = Table.read(paths.tpath('dendro_merge_continuum_and_line.ipac'), format='ascii.ipac')
corelike = dendro_merge['corelike'] == 'True'
dendro_protostars_pt2 = dendro_merge['cont_flux0p2arcsec'].sum()*u.Jy
print("Total protostar flux (0.2): {0}".format(dendro_protostars_pt2))
print("Total protostar flux (peak): {0}".format(dendro_merge['peak_cont_flux'].sum()*u.Jy))
total_minus_protostars = total_signal - dendro_protostars_pt2
print("Total recovered flux minus protostars: {0}".format(total_minus_protostars))
print("Total mass minus protostars (20K): {0}".format(total_minus_protostars * masscalc.mass_conversion_factor()*u.M_sun/u.Jy))

# determine BGPS total mass
regions = pyregion.open(paths.rpath("12m_pointings.reg"))
bgps_fh = fits.open("/Users/adam/work/w51/v2.0_ds2_l050_13pca_map20.fits")
mask = regions.get_mask(bgps_fh[0])
bgps_sum = bgps_fh[0].data[mask].sum() * u.Jy
bgps_ppbeam = bgps_fh[0].header['PPBEAM']
bgps_totalflux = bgps_sum/bgps_ppbeam
print("Total flux (BGPS, 271 GHz): {0}".format(bgps_totalflux))
bgps_scaled_225 = bgps_totalflux*(masscalc.centerfreq/(271.4*u.GHz))**3.5
bgps_scaled_225_4 = bgps_totalflux*(masscalc.centerfreq/(271.4*u.GHz))**4.0
bgps_scaled_225_3 = bgps_totalflux*(masscalc.centerfreq/(271.4*u.GHz))**3.0
print("Total flux (BGPS, 225 GHz, alpha=3.5): {0}".format(bgps_scaled_225))
bgps_totalmass = masscalc.dust.massofsnu(nu=271.4*u.GHz,
                                         snu=bgps_totalflux,
                                         distance=masscalc.distance)
print("Total mass (BGPS, 20K): {0}".format(bgps_totalmass))
print("*total* Fraction of recovered flux alpha=3.5: {0}".format(total_signal / bgps_scaled_225))
import radio_beam
from spectral_cube import SpectralCube
import paths
from astropy.io import fits
from astropy import wcs

tmplt = '{reg}cax.SPW{0}_ALL.image.fits'

#region_list = pyregion.open("cores_longbaseline_spectralextractionregions.reg")
#region_list += pyregion.open("e2e_se_jet.reg")
#region_list += pyregion.open("e2w_nitrogenic_bubble.reg")
#region_list = pyregion.open("cores_longbaseline_spectralextractionregions_pix.reg")
#fh = fits.open('W51e2cax.cont.image.pbcor.fits')
#mywcs = wcs.WCS(fh[0].header)

for region, region_list in (('W51e2', pyregion.open(paths.rpath("cores_longbaseline_spectralextractionregions_pix.reg"))),
                            ('W51n', pyregion.open(paths.rpath("cores_longbaseline_spectralextractionregions_pix_north.reg")))):
    for spw in range(0,10): #(2,4,6):
        try:
            cube = SpectralCube.read(tmplt.format(spw, reg=region))
        except IOError:
            print("didn't find {0}".format(tmplt.format(spw, reg=region)))
            continue
        print(cube)
        try:
            beam = radio_beam.Beam.from_fits_header(cube.header)
        except TypeError:
            if hasattr(cube, 'beams'):
                beam = radio_beam.Beam(major=np.nanmedian([bm.major.to(u.deg).value for bm in cube.beams]),
                                       minor=np.nanmedian([bm.minor.to(u.deg).value for bm in cube.beams]),
                                       pa=np.nanmedian([bm.pa.to(u.deg).value for bm in cube.beams]),
from gaussfitter import gaussfit
from astropy import units as u
from spectral_cube import SpectralCube
import pyregion
import paths
from astropy.table import Table, Column
from astropy import wcs
import pylab as pl

regions = pyregion.open(paths.rpath('ch3oh_maser_spots_channellabels.reg'))

cube = SpectralCube.read(paths.dpath('ch3oh_256_e2zoom_chan550to700.image.fits'))
vcube = cube.with_spectral_unit(u.km/u.s, velocity_convention='radio',
                                rest_value=6.668518*u.GHz)

dx, dy = 4,4

parnames = ("height", "amplitude", "x", "y", "width_x", "width_y", "rota")
tbl = Table(names=['velocity'] + [x for p in parnames for x in p,'e'+p])

for ii in pl.get_fignums(): pl.figure(ii).clf()

for ii,region in enumerate(regions):
    channel = int(region.attr[1]['text'])

    x,y = cube.wcs.sub([wcs.WCSSUB_CELESTIAL]).wcs_world2pix([region.coord_list], 0)[0]

    # not sure why, but it looks like all the images are offset by 1 pix
    x = x+1
    y = y+1
e2e_dustmass = dust_emissivity.dust.massofsnu(freq,
                                              e2e_peak_flux,
                                              distance=distance,
                                              temperature=e2e_peak_tb)
print("e2e dust mass: {0}".format(e2e_dustmass))

e2e_peak_column = dust_emissivity.dust.colofsnu(freq,
                                                e2e_peak_flux,
                                                beamomega=beam,
                                                temperature=100 * u.K).to(
                                                    u.cm**-2,
                                                    u.dimensionless_angles())
print("e2e peak column (T=100K): {0}".format(e2e_peak_column))

regfn = 'e2_exclude_e2w.reg'
reg_noe2w = pyregion.open(paths.rpath(regfn))
regfn = 'e2_exclude_e2w_and_e2e.reg'
reg_noe2w_or_e2e = pyregion.open(paths.rpath(regfn))

mywcs = wcs.WCS(hd)
pixscale = (mywcs.pixel_scale_matrix.diagonal()**2).sum()**0.5
ppbeam = (beam.sr / (pixscale**2 * u.deg**2)).decompose().value / u.beam

mask = reg_noe2w.get_mask(header=hd, shape=im.shape)

e2_total_flux = im[mask].sum() * u.Jy / u.beam / ppbeam
e2_median_flux = np.nanmedian(im[mask]) * u.Jy
e2_median_tb = e2_median_flux.to(u.K, beam.jtok_equiv(freq))
print("Median brightness temperature: {0}".format(e2_median_tb))
e2_max_flux = np.nanmax(im[mask]) * u.Jy
e2_max_tb = e2_max_flux.to(u.K, beam.jtok_equiv(freq))
import numpy as np
import paths
import pyregion
from astropy import coordinates
from astropy import units as u
from astropy import table
from astropy.table import Table,Column
from latex_info import latexdict, exp_to_tex, format_float

points = pyregion.open(paths.rpath("pointsource_centroids.reg"))
diffuse = pyregion.open(paths.rpath("diffuse_hii_regions.reg"))

# filter out sources we don't want repeated
diffuse_list = ('d3_diffuse', 'e1', 'e6', 'e7',)
points = [reg for reg in points if reg.attr[1]['text'] not in diffuse_list]

# slower but correct by doing it twice (in case one is fk5 and one is galactic)
coords = coordinates.SkyCoord([coordinates.SkyCoord(*reg.coord_list[:2],
                                                    unit=(u.deg, u.deg),
                                                    frame=reg.coord_format) for
                               reg in points+diffuse])
radii = ([(reg.coord_list[2]) if len(reg.coord_list) > 2 else np.nan
          for reg in points+diffuse]*u.deg).to(u.arcsec)
names = [reg.attr[1]['text'] for reg in points+diffuse]
                              
postbl = Table([Column(data=names, name='Source Name'),
                Column(data=coords.ra.to_string(unit=u.hour, sep=':'), name='RA'),
                Column(data=coords.dec.to_string(unit=u.deg, sep=':'), name='Dec'),
                Column(data=radii, name='Radius'),
                Column(data=(radii*5.1*u.kpc).to(u.pc, u.dimensionless_angles()), name='Phys. Radius'),
               ])
Beispiel #20
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)
print "Unfiltered voxels: ",nfin," of ", nok," or ",nfin/float(nok)*100,"%"
nfinpix = np.isfinite(ratio).max(axis=0).sum()
nokpix = (np.isfinite(sn11)*np.isfinite(sn22)).max(axis=0).sum()
print "Unfiltered pixels ",nfinpix," of ", nokpix," or ",nfinpix/float(nokpix)*100,"%"

ratioF = fits.open(datapath+'W51_H2CO11_taucube_supersampled.fits')


cont11 = fits.getdata(datapath+'W51_H2CO11_cube_supersampled_continuum.fits') + TCMB
cont22 = fits.getdata(datapath+'W51_H2CO22_pyproc_cube_lores_supersampled_continuum.fits') + TCMB
cont11[cont11<TCMB] = TCMB
cont22[cont22<TCMB] = TCMB

header = fits.getheader(datapath+'W51_H2CO11_cube_supersampled_continuum.fits')

contfrontregions = pyregion.open(rpath('continuum_in_the_front.reg'))
contfrontmask = contfrontregions.get_mask(fits.PrimaryHDU(data=cont11,header=header))
cont11[contfrontmask] = TCMB
cont22[contfrontmask] = TCMB







def get_extrema(x, w=2, threshold=0.01):
    """
    Return the valid range in pixels.

    This function tries to find the first local maximum and minimum and select
Beispiel #22
0
            'Dec': reg.center.dec[0],
            'color': reg.visual['color'],
        }

        if alphamap is not None and alphaerrmap is not None:
            alphacutout = mask.cutout(alphamap) * mask.data
            alphaerrcutout = mask.cutout(alphaerrmap) * mask.data
            argmax = np.unravel_index(cutout.argmax(), cutout.shape)
            results[name]['alpha'] = alphacutout[argmax]
            results[name]['alphaerror'] = alphaerrcutout[argmax]

    return results


if __name__ == "__main__":
    regs = regions.read_ds9(paths.rpath('sgrb2_cores_TE.reg'))
    regs = regions.read_ds9(paths.rpath('cores_with_names.reg'))

    from files import (contfilename as contfnpath, alphaerrorfilename as
                       alphaerrorpath, alphafilename as alphapath)

    contfile = fits.open(contfnpath)
    data = contfile[0].data
    beam = radio_beam.Beam.from_fits_header(contfnpath)
    mywcs = wcs.WCS(contfile[0].header)

    alphamap = fits.getdata(alphapath)
    alphaerrmap = fits.getdata(alphaerrorpath)

    units = {
        'peak': u.Jy / u.beam,
def get_pvs(cubefn, endpoints):
    fullcubefn = os.path.join(datapath_w51, cubefn)
    cube = spectral_cube.SpectralCube.read(fullcubefn)
    velo = cube.spectral_axis
    cdelt = pvextractor.utils.wcs_utils.get_spectral_scale(cube.wcs)
    #cube,velo,cdelt = pvextractor.utils.get_cube_info(cubefn)
    pvPath = pvextractor.geometry.path.Path(endpoints, width=60*u.arcsec)
    pv = pvextractor.extract_pv_slice(cube, pvPath)
                                      #respect_nan=False)
    npv = len(endpoints)
    return (pv,npv,velo,cdelt)


if __name__ == "__main__":
    endpoints_wcs = pyregion.open(rpath('pvendpoints.reg'))

    if not 'colorpvs' in locals():
        colorpvs = {}

    for jj,color in enumerate(('green','red','blue','purple','cyan','yellow','orange')):
        coords = np.array([s.coord_list for s in endpoints_wcs if s.attr[1]['color'] == color])

        pl.figure(jj+1)
        pl.clf()

        if color in colorpvs: #caching^2
            print "Loading from cache: ",color
            pvs = colorpvs[color]
        else:
            print "Processing from scratch: ",color
Beispiel #24
0
from edge_on_ring_velocity_model import thindiskcurve, thindiskcurve_fitter, trace_plotter

if 'cached_gaussfit_results' not in locals():
    cached_gaussfit_results = {}

fitresult_list = []

for linename,(vmin,vmax),limits,(cenx, ceny) in (
    ('Unknown_4', (-15, 27), (-0.1, 0.1, -0.12, 0.12), (65.1, 60.5)),
    ('H2Ov2=1_5(5,0)-6(4,3)', (-28, 38), (-0.2, 0.2, -0.2, 0.2), (68.8, 65.5)),
    ('Unknown_1', (-15, 27), (-0.1, 0.1, -0.12, 0.12), (65.1, 60.5)),
    ('Unknown_2', (-15, 27), (-0.1, 0.1, -0.12, 0.12), (65.1, 60.5)),
    ('SiOv=1_5-4', (-30, 45), (-0.2, 0.2, -0.2, 0.2), (65.1, 60.5)),
   ):

    regs = regions.read_ds9(paths.rpath('velo_centroid_guesses_{linename}.reg').format(linename=linename))

    guesses = {}

    for reg in regs:
        vel = float(reg.meta['text'].strip("{}"))
        if vel in guesses:
            guesses[vel].append(reg)
        else:
            guesses[vel] = [reg]

    velocities = np.array(sorted(guesses.keys()))*u.km/u.s

    cubefn = paths.dpath('cubes/OrionSourceI_{linename}_robust0.5maskedclarkclean10000_medsub_K.fits'
                         .format(linename=linename))
    basename = os.path.splitext(os.path.basename(cubefn))[0]
from astropy.visualization.mpl_normalize import ImageNormalize
import common_constants
from common_constants import distance

pl.matplotlib.rc_file("pubfiguresrc")

files = {
    "natural": "W51Ku_BD_h2co_v30to90_natural_contsub.image.fits",
    "briggs": "W51Ku_BD_h2co_v30to90_briggs0_contsub.image.fits",
}
levels = {
    "natural": [-0.4, -0.3, -0.2, -0.1, 0.010, 0.020, 0.030, 0.040],
    "briggs": [-0.28, -0.21, -0.14, -0.07, 0.007, 0.0105, 0.014],
}

region = pyregion.open(rpath("w51e2zoom.reg"))


def set_tight_ticks(F):
    F.tick_labels.set_yformat("dd:mm:ss.ss")
    F.tick_labels.set_xformat("hh:mm:ss.ss")
    F.tick_labels.set_x_full_label_side("left")


for name, fn in files.iteritems():
    cube = SpectralCube.read(paths.dpath(fn))
    scube = (
        cube.subcube_from_ds9region(region)
        .with_spectral_unit(u.km / u.s, velocity_convention="radio")
        .spectral_slab(50 * u.km / u.s, 63 * u.km / u.s)
    )
Beispiel #26
0
    fig1 = pl.figure(1)
    fig1.clf()
    FF1 = aplpy.FITSFigure(rhdu, figure=fig1)
    FF1.show_colorscale(cmap=cm, vmin=0, vmax=1, stretch='log', vmid=-50)
    FF1.show_colorbar()
    FF1.colorbar.set_axis_label_text("Ratio $E_U=68/E_U=23$")
    FF1.add_scalebar((1*u.pc/distance).to(u.deg, u.dimensionless_angles()).value,)
    FF1.scalebar.set_label('1 pc')
    FF1.save(paths.fpath('H2CO_{0}_RatioMap.png'.format(label)))


    fig2 = pl.figure(2)
    pl.clf()
    FF2 = aplpy.FITSFigure(hdu, figure=fig2)
    FF2.show_colorscale(cmap=cm, vmin=10, vmax=vmax, stretch='log', vmid=-50)
    FF2.show_colorbar()
    FF2.colorbar.set_axis_label_text("Temperature [K]")
    FF2.add_scalebar((1*u.pc/distance).to(u.deg, u.dimensionless_angles()).value,)
    FF2.scalebar.set_label('1 pc')
    FF2.save(paths.fpath('H2CO_{0}_LTEtemperaturemap.png'.format(label)))
    FF2.show_contour(paths.dpath('evla/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'),
                     colors=['k'], levels=[0.001], layer='black_contours')
    FF2.save(paths.fpath('H2CO_{0}_LTEtemperaturemap_withCMcontours.png'.format(label)))
    FF2.hide_layer('black_contours')
    FF2.show_contour(paths.dpath('evla/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'),
                     colors=['w'], levels=[0.001], layer='white_contours')
    FF2.save(paths.fpath('H2CO_{0}_LTEtemperaturemap_withwhiteCMcontours.png'.format(label)))
    FF2.hide_layer('white_contours')
    FF2.show_regions(paths.rpath('cores.reg'), layer='cores')
    FF2.save(paths.fpath('H2CO_{0}_LTEtemperaturemap_withcores.png'.format(label)))
import radio_beam
from astropy.io import fits
from astropy import wcs

from photom_files import files

# add images that merge subbands
files["5.5 GHz Epoch 3"] = paths.dpath("W51C_ACarray_continuum_4096_both_uniform_contsplit.clean.image.fits")
files["13.4 GHz Epoch 2"] = paths.dpath('W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits')

beams = {name: radio_beam.Beam.from_fits_header(fits.getheader(fn))
         for name,fn in files.items()}
dates = {name: fits.getheader(fn)['DATE-OBS']
         for name,fn in files.items()}

noisereg = pyregion.open(paths.rpath("noise_estimate_region.reg"))

noise_est = {}
peak = {}

# noise estimate
for ep in files:
    im = fits.open(files[ep])
    header = im[0].header
    w = wcs.WCS(header).sub([wcs.WCSSUB_CELESTIAL])
    mask = noisereg.get_mask(header=w.to_header(), shape=im[0].data.squeeze().shape)
    noise_est[ep] = im[0].data.squeeze()[mask].std() * 1000
    peak[ep] = im[0].data.max()*1000
    

obstbl = Table([Column(data=[ep.split()[-1] for ep in beams], name='Epoch'),
    e2med = e2slab.median(axis=0)
    e2mslab = e2slab-e2med

    e2sioblue = e2mslab.spectral_slab(-32*u.km/u.s, 55*u.km/u.s).moment0()
    e2sioblue.write('/Users/adam/work/w51/alma/FITS/longbaseline/{line}_m32to55kms_e2.fits'.format(line=line), overwrite=True)

    e2siored = e2mslab.spectral_slab(74*u.km/u.s, 118*u.km/u.s).moment0()
    e2siored.write('/Users/adam/work/w51/alma/FITS/longbaseline/{line}_74to118kms_e2.fits'.format(line=line), overwrite=True)



    import pvextractor
    from pvextractor.pvregions import paths_from_regions
    import pyregion
    import paths
    reg = pyregion.open(paths.rpath('../regions/e2eoutflow_reference_vector.reg'))
    outflowcoords = paths_from_regions(reg)
    outflowpath = outflowcoords[0]
    outflowpath.width = 0.15*u.arcsec

    extracted = pvextractor.extract_pv_slice(e2slab, outflowpath)

    import aplpy
    FF = aplpy.FITSFigure(extracted)
    FF.show_grayscale(aspect='auto')
    FF.save(paths.fpath('outflows/{line}_PV_e2e.png'.format(line=line)))



    e8cube = SpectralCube.read('/Volumes/passport/alma/w51/longbaseline/W51e8cax.SPW0_ALL_medsub_cutout.fits')
    e8vcube = e8cube.with_spectral_unit(u.km/u.s, rest_value=freq,
from astropy.table import Table
from astropy import table
from astropy.utils.console import ProgressBar
import pylab as pl
import pyregion
import velo_guesses
import radio_beam

import warnings
from numpy.ma.core import MaskedArrayFutureWarning
warnings.filterwarnings('ignore', category=MaskedArrayFutureWarning)

line_table = table.Table.read(paths.apath('full_line_table.csv'))
line_table.sort('Species')

regions = (pyregion.open(paths.rpath("cores.reg")))

# check that it will finish before running everything
for region in regions:
    name = region.attr[1]['text']
    if region.name == 'point':
        # when we're using peak pixels from the photometry catalog, the 'point'
        # objects can be skipped
        continue

    spectral_files = glob.glob(paths.spath('{0}_spw[0123]_peak.fits'.format(name)))
    #background_spectral_files = glob.glob(paths.spath('{0}_spw[0123]_background_mean.fits'.format(name)))
    assert len(spectral_files) == 4#len(background_spectral_files) == 4
    vcen = velo_guesses.guesses[name]

for region in regions:
from spectral_cube import SpectralCube
from spectral_cube.utils import PossiblySlowWarning
from astropy import units as u, table, coordinates
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:
import copy
import numpy as np
import pyregion
from astropy import units as u
from astropy import coordinates
from astropy.utils.console import ProgressBar
from scipy.sparse.csgraph import minimum_spanning_tree
import paths

regions = pyregion.open(paths.rpath('pointsource_centroids.reg'))

coords = coordinates.SkyCoord([x.coord_list for x in regions], unit=('deg','deg'))

separation_matrix = np.array([coords.separation(y) for y in ProgressBar(coords)])

ordered_separation_matrix = np.argsort(separation_matrix.ravel()).reshape(separation_matrix.shape)
ordered_separation_matrix[separation_matrix==0] = 0


ordered_edges = np.argsort(separation_matrix.ravel())
lefts, rights = np.unravel_index(ordered_edges, separation_matrix.shape)

separation_matrix[separation_matrix==0] = np.inf

#Prim's algorithm:
vertices = [0]
all_vertices = list(range(len(coords)))
all_vertices.remove(0)
edges = []
while len(vertices) < len(coords):
    smallest_edge = (-1,-1)
from astropy import wcs
import masscalc

fh = fits.open(paths.dpath('12m/continuum/selfcal_allspw_selfcal_3_mfs_deeper_r2.0.image.pbcor.fits'))

mywcs = wcs.WCS(fh[0].header)

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

pixscale = (mywcs.pixel_scale_matrix.diagonal()**2).sum()**0.5
ppbeam = (beam.sr/(pixscale**2*u.deg**2)).decompose().value / u.beam


for rpath in ('e5bubble_inclusive.reg', 'e5bubble_dustonly.reg'):
    print(rpath)
    reg = pyregion.open(paths.rpath(rpath))

    mask = reg.get_mask(fh[0])
    cutout = fh[0].data*mask

    limits = [0.005, 0.015]

    total_flux_perbeam = cutout[(cutout > limits[0]) & (cutout < limits[1])].sum()
    total_flux = total_flux_perbeam / ppbeam.value
    print("Total flux: {0}".format(total_flux))

    rad = reg[0].coord_list[-1]*u.deg
    rad_pc = (rad*masscalc.distance).to(u.pc, u.dimensionless_angles())

    print("Total mass(20K): {0}".format(total_flux*masscalc.mass_conversion_factor(TK=20)))
    print("Total mass(50K): {0}".format(total_flux*masscalc.mass_conversion_factor(TK=50)))
        cax.set_ylabel(method_label[method])
        cb.ax.yaxis.set_label_position('right')

        ax.set_xlabel("Galactic Longitude")
        ax.set_ylabel("Galactic Latitude")

        tr = ax.get_transform(dustcolwcs)
        con = ax.contour(dustcoldata, levels=[5], colors=[(0,0,0,0.5)],
                         zorder=15, alpha=0.5, linewidths=[0.5], transform=tr)
        ax.axis(limits)

        pl.savefig(fpath('integrated/{0}'.format(outname.replace(".fits",".pdf"))),
                   bbox_inches='tight')
        for c in con.collections: c.set_visible(False)
        
        labels = pyregion.open(rpath('ridge_names.reg'))
        PC, TC = ds9(labels, im.header, text_offset=0)
        #PC.add_to_axes(ax)
        TC = aplpyregions.ArtistCollection([x for x in TC.artistlist if isinstance(x, matplotlib.text.Annotation)])
        TC.add_to_axes(ax)

        pl.savefig(fpath('integrated/{0}'.format(outname.replace(".fits","_labeled.pdf"))),
                   bbox_inches='tight')


        for c in con.collections: c.set_visible(True)
        ax.axis(limits)
        pl.savefig(fpath('integrated/{0}'.format(outname.replace(".fits",
                                                                 "_labeled_dustcontours.pdf"))),
                   bbox_inches='tight')
Beispiel #34
0
from astropy.table import Table
from paths import opath, rpath
import pyregion

tbl = Table.read(opath('observing_logs.ipac'), format='ipac')
co_good = co_ok = tbl['restf'] == 218900
co_bad = tbl['restf'] == 219000
maps_bad = [
    s.strip() for row in tbl[co_bad] for s in row['sources'].split(", ")
]
maps_good = [
    s.strip() for row in tbl[co_good] for s in row['sources'].split(", ")
]
bad_only = [m for m in maps_bad if m not in maps_good]

map_regions = pyregion.open(rpath('target_fields_8x8.reg'))

bad_regions = [
    m for m in map_regions if m.attr[1]['text'].split()[0].upper() in bad_only
]
not_good_regions = [
    m for m in map_regions if m.attr[1]['text'].split()[0].upper() in maps_bad
]
marked_regions = bad_regions + not_good_regions
for m in marked_regions:
    if m in bad_regions:
        m.attr[1]['color'] = 'red'
    else:
        m.attr[1]['color'] = 'green'
marked_regions = list(set(marked_regions))
pyregion.ShapeList(marked_regions).write(rpath("co_c18o_overlap.reg"))
import pyspeckit
from astropy.io import fits
import astropy.table
import pyregion
import types
from pyspeckit.wrappers import fith2co
import numpy as np
import pylab as pl
import os
from paths import (datapath, datapath_w51, figurepath, datapath_spectra, dpath,
                   rpath, analysis_path)
import paths

pl.rcParams['font.size'] = 18

regfiledict = {rpath("dense_filament_spectral_apertures.reg"):
               'spectralfits/spectralfits_70kmscloud',
               rpath("filament_leftside_spectral_apertures.reg"):
               'spectralfits/spectralfits_70kmscloudLeft',
               rpath("w51main_spectral_apertures.reg"):
               'spectralfits/spectralfits_w51main',
               rpath("maus_spectral_apertures.reg"):
               'spectralfits/spectralfits_maus',
               rpath("middlechunk_spectral_apertures.reg"):
               'spectralfits/spectralfits_63kmscloud'}


def modelpars():
    
    limits = [(1, 8), # dens
              (11, 16), # col
Beispiel #36
0
import spectral_cube
import aplpy
import pylab as pl
import matplotlib
import pyregion
import copy
from paths import mpath, apath, fpath, molpath, hpath, rpath, h2copath
from astropy import units as u
from astropy import coordinates
from astropy.io import ascii
from astropy import log
import paths
import matplotlib
matplotlib.rc_file(paths.pcpath('pubfiguresrc'))

reg = pyregion.open(rpath('backstream.reg'))[0].coord_list
glon, glat = np.array(reg[::2]), np.array(reg[1::2])
coords = coordinates.SkyCoord(glon * u.deg, glat * u.deg, frame='galactic')
P = pvextractor.Path(coords, width=300 * u.arcsec)

vlos = glon * 0  # TODO: replace this

dl = (glon[1:] - glon[:-1])
db = (glat[1:] - glat[:-1])
dist = (dl**2 + db**2)**0.5
cdist = np.zeros(dist.size + 1)
cdist[1:] = dist.cumsum()

molecules = ('13CO_2014_merge', 'C18O_2014_merge', 'H2CO_303_202_bl',
             'SiO_54_bl')
import numpy as np
from astropy import units as u
from astropy import coordinates
from spectral_cube import SpectralCube
from astropy.io import fits
from astropy import wcs
import line_to_image_list
import pyregion
import paths
import pylab as pl

#raise ValueError("TODO: fix the cutout regions and make sure the cubes are cut out"
#                 "from the same region as the continuum.   A change to the region "
#                 "file below has resulted in a mismatch in the emi/abs masks below")

regions = pyregion.open(paths.rpath("e2e8northcutouts.reg"))

corners = {reg.attr[1]['text']: {'lowerleft': coordinates.SkyCoord([reg.coord_list[:2]], frame='fk5', unit=(u.deg, u.deg)),
                                 'upperright': coordinates.SkyCoord([reg.coord_list[2:4]], frame='fk5', unit=(u.deg, u.deg)),}
           for reg in regions
          }

files = {'e2':[
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW1_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW2_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW3_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW4_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW5_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW6_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW7_ALL_medsub_cutout.fits",
"/Volumes/passport/alma/w51/longbaseline/W51e2cax.SPW8_ALL_medsub_cutout.fits",
Beispiel #38
0
F.axis_labels.set_font(size=20)
F.show_grayscale(stretch='arcsinh', vmin=-5e-4, vmax=0.011, invert=True)
#e1 = coordinates.ICRS(290.93263,14.50745,unit=('deg','deg'))
#F.recenter(e1.ra.value,e1.dec.value,width=1/60.,height=1/60.)
#F.recenter(290.92633,14.514769,radius=1.4/60.)
F.recenter(290.92345, 14.511772, radius=1.5 / 60.)

F.add_scalebar(length=((0.5 * u.pc) / distance * u.radian).to(u.degree).value)
F.scalebar.set_label('0.5 pc')
F.scalebar.set_color('black')
F.scalebar.set_linewidth(3)
F.scalebar.set_font_size(20)

F.save(fpath('W51_Ku_grayscale.pdf'))

F.show_regions(rpath('HCHII_candidates.reg'))
#F.show_regions('/Users/adam/work/w51/cycle2_ALMA_frame2.reg')

F.save(fpath('W51_Ku_grayscale_HCHIIcandidates.pdf'))

F.scalebar.set_length(((0.1 * u.pc) / distance * u.radian).to(u.degree).value)
F.scalebar.set_label('0.1 pc')

F.recenter(290.91644, 14.518939, radius=0.3 / 60.)
log.info("Reading briggs0_contsub image cube")
cube = SpectralCube.read(
    dpath('W51Ku_BD_h2co_v30to90_briggs0_contsub.image.fits')
).with_spectral_unit(u.km / u.s, velocity_convention='radio')
# 53 for e1e2
for velo in ProgressBar(np.arange(53, 72, 0.5)):
    #log.info("Velocity {0}".format(velo))
import pyregion
import paths

apregfiles = ['dense_filament_spectral_apertures.reg',
              'maus_spectral_apertures.reg',
              'filament_leftside_spectral_apertures.reg',
              'middlechunk_spectral_apertures.reg',
              'w51main_spectral_apertures.reg', ]

regions = pyregion.ShapeList(reduce(pyregion.ShapeList.__add__,
                                    [pyregion.open(paths.rpath(r))
                                     for r in apregfiles]))

regions.write(paths.rpath('merged_spectral_apertures.reg'))
Beispiel #40
0
        pl.subplots_adjust(hspace=0, wspace=0)
        plotnum += 1

    if figsavename is not None:
        pl.savefig(figsavename, bbox_inches='tight')


if __name__ == "__main__":

    import pyregion
    import paths
    import pyspeckit
    import glob
    from ch3oh_model import load_and_convert_spectra

    core_regions = pyregion.open(paths.rpath('cores.reg'))

    core_names = [r.attr[1]['text'] for r in core_regions]

    full_results = {}
    """
    NOTE: the J=25 lines are in the line wings of SO.  That can artificially
    inflate the fitted amplitude if a spw-wide continuum subtraction is done.
    """

    # now fit 'em all...
    #for cn in core_names:
    for cn in [
            'ALMAmm51',
    ]:  # debug
        spectra = load_and_convert_spectra(
Beispiel #41
0
from astropy.table import Table
from astropy import table
from astropy.utils.console import ProgressBar
import pylab as pl
import pyregion
import velo_guesses
import radio_beam

import warnings
from numpy.ma.core import MaskedArrayFutureWarning
warnings.filterwarnings('ignore', category=MaskedArrayFutureWarning)

line_table = table.Table.read(paths.apath('full_line_table.csv'))
line_table.sort('Species')

regions = (pyregion.open(paths.rpath("cores.reg")))

for region in regions:
    name = region.attr[1]['text']

    spectral_files = glob.glob(paths.spath('{0}_spw[0123]_mean.fits'.format(name)))
    #background_spectral_files = glob.glob(paths.spath('{0}_spw[0123]_background_mean.fits'.format(name)))
    assert len(spectral_files) == 4#len(background_spectral_files) == 4
    spectra = pyspeckit.Spectra(spectral_files)
    #bgspectra = pyspeckit.Spectra(background_spectral_files)
    stats = spectra.stats()
    err = stats['std'] # overly conservative guess

    for sp in spectra:
        sp.data -= np.nanpercentile(sp.data, 25)
    #med = stats['median']
    #    hdu.writeto(paths.dpath('12m/cutouts/CH3OH_{0}_cutout_columnmap.fits'.format(sourcename)), clobber=True)

    #    nr, bins, rprof = image_tools.radialprofile.azimuthalAverage(tmap,
    #                                                                 binsize=1.0,
    #                                                                 return_nr=True)
    #    mywcs = wcs.WCS(header)
    #    pixscale = (mywcs.pixel_scale_matrix.diagonal()**2).sum()**0.5
    #    pl.figure(4).clf()
    #    pl.plot(bins*pixscale*3600, rprof)
    #    pl.xlabel("Radius (arcsec)")
    #    pl.ylabel("Average Temperature (K)")
    #    pl.savefig(paths.fpath("chemistry/ch3oh_temperature_radial_profile_{0}.png".format(sourcename)))


    import pyregion
    pixels = pyregion.open(paths.rpath('three_e2_pixels.reg'))
    sourcename='e2'
    _ = cutout_id_chem_map(source=sources[sourcename],
                           radius=radii[sourcename],
                           sourcename=sourcename,
                           filelist=glob.glob(paths.dpath('12m/moments/*medsub_moment0.fits')),
                           chem_name='.CH3OH', # use dot to exclude 13CH3OH
                          )
    xaxis,cube,ecube,maps,map_error,energies,cubefrequencies,indices,degeneracies,header = _
    mywcs = wcs.WCS(header)
    replace_bad = dthresh[sourcename]

    pl.figure(4).clf()
    for reg in pixels:
        coord = coordinates.SkyCoord(reg.coord_list[0], reg.coord_list[1],
                                     frame='fk5', unit=(u.deg, u.deg))
import radio_beam
from astropy import units as u
from astropy import log
from astropy import wcs
from astropy.stats import mad_std
from astropy.io import fits
from astropy.table import Table,Column

import paths
from core_photometry import photometry

lines = ["CFp", "CH3OH7m26-716", "H15NC", "H2CO615-616", "H2CS303-202",
         "H2CS313-212", "H2CS322-221", "H41a", "HC3N", "HCN", "HNC",]

if __name__ == "__main__":
    regs = regions.read_ds9(paths.rpath('sgrb2_cores_TE.reg'))

    all_results = {}

    for line in lines:
        fn = paths.mergepath("max/SgrB2_b3_7M_12M.{0}.image.pbcor_max_medsub.fits".format(line))
        ffile = fits.open(fn)
        data = ffile[0].data
        header = ffile[0].header
        beam = radio_beam.Beam.from_fits_header(header)
        mywcs = wcs.WCS(header)

        units = {'peak':u.Jy/u.beam,
                 'sum':u.Jy/u.beam,
                 'npix':u.dimensionless_unscaled,
                 'beam_area':u.sr,
import paths
import aplpy
import pyregion
import pylab as pl
from astropy import units as u

pl.figure(1).clf()
pl.figure(2).clf()

# sanity check: are the regions in the right place?
F = aplpy.FITSFigure(
    paths.dpath('longbaseline/W51e2cax.cont.image.pbcor.fits'),
    figure=pl.figure(1))
F.show_grayscale(vmax=0.015)
region_list = pyregion.open(
    paths.rpath("cores_longbaseline_spectralextractionregions.reg"))
F.show_regions(region_list)
F.recenter(290.9332, 14.509589, 0.5 / 3600.)

spectra_se_emission = pyspeckit.Spectra(
    glob.glob(
        paths.dpath('longbaseline/spectra/e2e_se_emission_W51e2_spw*fits')))
spectra_center = pyspeckit.Spectra(
    glob.glob(paths.dpath('longbaseline/spectra/e2e_center_W51e2_spw*fits')))
spectra_left = pyspeckit.Spectra(
    glob.glob(paths.dpath('longbaseline/spectra/e2e_left_W51e2_spw*fits')))
spectra_right = pyspeckit.Spectra(
    glob.glob(paths.dpath('longbaseline/spectra/e2e_right_W51e2_spw*fits')))

spectra_center.xarr.convert_to_unit(u.GHz)
spectra_right.xarr.convert_to_unit(u.GHz)
Beispiel #45
0
from __future__ import print_function
from astropy import units as u
import numpy as np
import pyspeckit
from spectral_cube import SpectralCube
import paths
import pyregion

cube11 = SpectralCube.read(paths.adpath('G357.3-003.9-NH3-11-cube.fits'))
cube22 = SpectralCube.read(paths.adpath('G357.3-003.9-NH3-22-cube.fits'))
regions = pyregion.open(paths.rpath('target_fields_8x8.reg'))

sc11 = cube11.subcube_from_ds9region(regions)
sc22 = cube22.subcube_from_ds9region(regions)
sp_s11 = sc11.mean(axis=(1, 2))
sp_s22 = sc22.mean(axis=(1, 2))
print("Integrated line ratio 1-1/2-2: {0}".format(sp_s11.sum() / sp_s22.sum()))

filling_factor = 0.1

sp11 = pyspeckit.Spectrum(data=sp_s11.value / filling_factor,
                          xarr=cube11.spectral_axis,
                          header=cube11.header,
                          xarrkwargs={
                              'refX': cube11.wcs.wcs.restfrq * u.Hz,
                              'velocity_convention': 'radio'
                          })
sp22 = pyspeckit.Spectrum(data=sp_s22.value / filling_factor,
                          xarr=cube22.spectral_axis,
                          header=cube22.header,
                          xarrkwargs={
print("200mmax,  >8 fraction: {0}, mean = {1}".format(over8fraction,
                                                      over8mean))

nsources = len(core_phot_tbl)

print("Mass fraction M>8 = {0}".format(over8fraction))
print("Mean mass Mbar(M>8) = {0}".format(over8mean))
print("Mass of observed sources, assuming all are 8 msun = {0}".format(
    nsources * 8))
print("Total Mass estimate if all sources are 8 msun = {0}".format(
    nsources * 8 / over8fraction))
print("Total Mass estimate if Mbar={1} = {0}".format(
    nsources * over8mean / over8fraction, over8mean))

# Comparison to Schmiedeke et al, 2016 tbl 2
clusters = regions.read_ds9(paths.rpath('schmiedeke_clusters.reg'))
clusters.append(
    regions.CircleSkyRegion(clusters[0].center,
                            radius=1 * u.deg,
                            meta={'text': 'Total'}))
#this can be used to determine n_cores and n_hii in a bigger region,
#but is incompatible with something else below...
# clusters.append(regions.CircleSkyRegion(clusters[0].center,
#                                         radius=35*u.arcsec,
#                                         meta={'text':'M Bigger'})
#                )
# Cluster M Bigger: N(cores)= 52 N(HII)= 49 counted mass=   2852.28 inferred mass=  11522.81 HII-only inferred mass:   16003.53 core-inferred mass=   7042.09

# add in DePree HII regions based on whether or not their names
# are already in the table, since we didn't count the larger HII regions
hii_regions = regions.read_ds9(
"""
Quick-look to demonstrate that the off positions are relatively emission-free
"""
import aplpy
from astropy.utils.data import download_file
import paths
dame2001 = download_file('http://www.cfa.harvard.edu/mmw/Wco_DHT2001.fits.gz', cache=True)
F = aplpy.FITSFigure(dame2001, convention='calabretta')
F.show_grayscale()
F.recenter(0,0,width=5,height=3) # center on the inner 5x3 degrees
F.show_regions(paths.rpath('target_fields_8x8.reg'))
F.show_regions(paths.rpath('off_positions_selectedfromDame2001.reg'))
F.save(paths.fpath('Dame2001_APEXCMZ_offpositions.png'))
F.save(paths.fpath('Dame2001_APEXCMZ_offpositions.pdf'))

F.hide_layer('region_set_1')
F.hide_layer('region_set_1_txt')
F.show_regions(paths.rpath('target_fields_8x8_coloredbyoffposition.reg'))
F.save(paths.fpath('Dame2001_APEXCMZ_offpositions_coloredbyoff.png'))
Beispiel #48
0
beam = radio_beam.Beam.from_fits_header(contfile[0].header)
metadata = {}
metadata['data_unit'] = u.Jy/u.beam
pixel_scale = np.abs(mywcs.pixel_scale_matrix.diagonal().prod())**0.5 * u.deg
pixel_scale_as = pixel_scale.to(u.arcsec).value
metadata['spatial_scale'] = pixel_scale
metadata['beam_major'] = beam.major
metadata['beam_minor'] = beam.minor
metadata['wavelength'] = 218.22219*u.GHz
metadata['velocity_scale'] = u.km/u.s
metadata['wcs'] = mywcs
ppbeam = (beam.sr/(pixel_scale**2)).decompose().value

ppcat = astrodendro.pp_catalog(dend, metadata)

with open(paths.rpath("raw_dendrogram_cores.reg"), 'w') as fh:
    fh.write("fk5\n")
    for row in ppcat:
        fh.write("ellipse({x_cen}, {y_cen}, {major_sigma}, "
                 "{minor_sigma}, {position_angle}) # text={{{_idx}}}\n"
                 .format(**dict(zip(row.colnames, row))))

# add a 'noise' column to the catalog
keys = ['noise', 'is_leaf', 'peak_cont_flux', 'min_cont_flux',
        'mean_cont_flux', 'peak_cont_mass', 'peak_cont_col', 'beam_area']
radii = (0.2,0.4,0.6,0.8,1.0,1.5)*u.arcsec
columns = {k:[] for k in (keys)}

log.info("Doing photometry")
for ii, row in enumerate(ProgressBar(ppcat)):
    structure = dend[row['_idx']]
F.axis_labels.set_font(size=20)
F.show_grayscale(stretch='arcsinh',vmin=-5e-4,vmax=0.011)
#e1 = coordinates.ICRS(290.93263,14.50745,unit=('deg','deg'))
#F.recenter(e1.ra.value,e1.dec.value,width=1/60.,height=1/60.)
#F.recenter(290.92633,14.514769,radius=1.4/60.)
F.recenter(290.92345,14.511772,radius=1.5/60.)

F.add_scalebar(length=((0.5 * u.pc)/distance*u.radian).to(u.degree).value)
F.scalebar.set_label('0.5 pc')
F.scalebar.set_color('orange')
F.scalebar.set_linewidth(3)
F.scalebar.set_font_size(20)

F.save(fpath('W51_C_grayscale.pdf'))

F.show_regions(rpath('HCHII_candidates.reg'))
#F.show_regions('/Users/adam/work/w51/cycle2_ALMA_frame2.reg')

F.save(fpath('W51_C_grayscale_HCHIIcandidates.pdf'))


F.scalebar.set_length(((0.1 * u.pc)/distance*u.radian).to(u.degree).value)
F.scalebar.set_label('0.1 pc')

F.recenter(290.91644,14.518939,radius=0.3/60.)
cube = SpectralCube.read(dpath(cube_names['11_uniform'])).with_spectral_unit(u.km/u.s, velocity_convention='radio')
for velo in np.arange(60,72,0.5):
    c = pl.cm.jet_r((70-velo)/10.)
    colors = [c[:3] + (x,) for x in (0.9,0.7,0.5,0.3,0.1)]
    F.show_contour(cube[cube.closest_spectral_channel(velo*u.km/u.s)].hdu,
                   levels=[-1,-0.003,-0.002,-0.001],colors=colors,
import os
import pyspeckit
import pyregion
import pylab as pl
from load_pyspeckit_cubes import cube1 as scube1
from load_pyspeckit_cubes import cube2 as scube2
from load_pyspeckit_taucubes import h2co11 as taucube11
from load_pyspeckit_taucubes import h2co22 as taucube22

scube11.xarr.convert_to_unit("km/s")
scube22.xarr.convert_to_unit("km/s")
# taucube11_13 = pyspeckit.Cube(datapath+'W51_H213CO_taucube.fits')
# scube11_13 = pyspeckit.Cube(datapath+'W51_H213CO_cube_sub.fits')
# scube11_13.xarr.convert_to_unit('km/s')

regfn = rpath("w51main_spectral_apertures.reg")
regions = pyregion.open(regfn)

spectra11 = {}
spectra22 = {}

# Loading
for ii, reg in enumerate(regions):
    sp11 = scube11.get_apspec(reg.coord_list, coordsys=reg.coord_format, wunit="degree")
    sp22 = scube22.get_apspec(reg.coord_list, coordsys=reg.coord_format, wunit="degree")
    taup11 = taucube11.get_apspec(reg.coord_list, coordsys=reg.coord_format, wunit="degree")
    taup22 = taucube22.get_apspec(reg.coord_list, coordsys=reg.coord_format, wunit="degree")

    sp11.specname = reg.attr[1]["text"]
    sp22.specname = reg.attr[1]["text"]
    taup11.specname = reg.attr[1]["text"]
Beispiel #51
0


# constants used for centroid_planes and seifried_analysis

source = 'sourceI'
#diskycoord_list = pyregion.open(paths.rpath("{0}_disk_pvextract.reg"
#                                            .format(source)))[0].coord_list
#diskycoords = coordinates.SkyCoord(["{0} {1}".format(diskycoord_list[jj],
#                                                     diskycoord_list[jj+1])
#                                    for jj in range(0,
#                                                    len(diskycoord_list),
#                                                    2)], unit=(u.deg,
#                                                               u.deg),
#                                   frame='fk5')
diskycoord_list = regions.read_ds9(paths.rpath("{0}_disk_pvextract.reg"
                                               .format(source)))
diskycoords = coordinates.SkyCoord([diskycoord_list[0].start,
                                    diskycoord_list[0].end])

#source = coordinates.SkyCoord(83.81048617*u.deg, -5.37516858*u.deg, frame='icrs')
source = coordinates.SkyCoord(regions.read_ds9(paths.rpath('sourceI_center.reg'))[0].center)

extraction_path = pvextractor.Path(diskycoords, width=0.01*u.arcsec)
origin = offset_to_point(source.ra.deg,
                         source.dec.deg,
                         extraction_path)*u.deg

# only approximate
central_freqs = {'B6': 224*u.GHz, 'B7': 345*u.GHz, 'B3': 95*u.GHz}
Beispiel #52
0
        target_resolution = 10.0 * u.km / u.s
        pixel_scale = current_resolution
        gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 /
                          pixel_scale / fwhm_factor)
        kernel = Gaussian1DKernel(gaussian_width)

        new_xaxis = np.arange(-140, 265, 5) * u.km / u.s
        sm_sio_cube = siocube.spectral_smooth(kernel).spectral_interpolate(
            new_xaxis)

        sm_sio_cube.write(north_ds)

    celhdr = sm_sio_cube.wcs.celestial.to_header()
    celhdr['NAXIS1'] = sm_sio_cube.shape[2]
    celhdr['NAXIS2'] = sm_sio_cube.shape[1]
    bluemask = pyregion.open(paths.rpath(
        'sio_blue_boxmask_lb_north.reg')).as_imagecoord(celhdr).get_mask(
            sm_sio_cube[0, :, :].hdu)
    redmask = pyregion.open(paths.rpath(
        'sio_red_boxmask_lb_north.reg')).as_imagecoord(celhdr).get_mask(
            sm_sio_cube[0, :, :].hdu)

    sio_m0_blue_north = sm_sio_cube.with_mask(
        sm_sio_cube > 3 * u.mJy).with_mask(bluemask).spectral_slab(
            -140 * u.km / u.s,
            60 * u.km / u.s).moment0() / u.Jy * sm_sio_cube.beam.jtok(ref_freq)
    sio_m0_red_north = sm_sio_cube.with_mask(
        sm_sio_cube > 3 * u.mJy).with_mask(redmask).spectral_slab(
            60 * u.km / u.s, 260 * u.km /
            u.s).moment0() / u.Jy * sm_sio_cube.beam.jtok(ref_freq)
    sio_m1_blue_north = sm_sio_cube.with_mask(
        sm_sio_cube > 3 * u.mJy).with_mask(bluemask).spectral_slab(
Beispiel #53
0
"""
Make bite-sized cutouts of full cube data around the main sources
"""
from astropy import units as u
from astropy import coordinates
from spectral_cube import SpectralCube
import pyregion
import glob

try:
    import paths
    regions = pyregion.open(paths.rpath("e2e8northcutouts.reg"))
except ImportError:
    regions = pyregion.open("e2e8northcutouts.reg")

corners = {
    reg.attr[1]['text']: {
        'lowerleft':
        coordinates.SkyCoord([reg.coord_list[:2]],
                             frame='fk5',
                             unit=(u.deg, u.deg)),
        'upperright':
        coordinates.SkyCoord([reg.coord_list[2:4]],
                             frame='fk5',
                             unit=(u.deg, u.deg)),
    }
    for reg in regions
}

for source in ('e2', 'e8', 'north', 'northoutflow'):
    for cubefn in glob.glob("full*fits"):
Beispiel #54
0
import numpy as np
import paths
from astropy.io import fits
import pylab as pl
from astropy import wcs
import astropy.visualization
from astropy.nddata import Cutout2D
from astropy import coordinates
from astropy import units as u
import regions

noise_regions = regions.read_ds9(paths.rpath('noise_regions.reg'))

sc5tt = fits.open(
    paths.mergepath(
        'continuum/SgrB2_selfcal_full_TCTE7m_selfcal5_ampphase_taylorterms_multiscale_deeper_mask2.5mJy.image.tt0.pbcor.fits'
    ))
mywcs = wcs.WCS(sc5tt[0].header)

data = sc5tt[0].data
peak = np.nanmax(data)
print("Peak flux: {0} Jy".format(peak))

for reg in noise_regions:

    pixreg = reg.to_pixel(mywcs)
    mask = pixreg.to_mask()
    cutout = mask.cutout(data) * mask.data

    name = reg.meta['text'].strip("{}")
# make metadata table for images used in analysis

from files import b6_hires_cont, b3_hires_cont
import numpy as np
import paths
from astropy.io import fits
from astropy import units as u
from astropy import wcs
import regions
from radio_beam import Beam

noiseregion = regions.read_ds9(paths.rpath('noise_estimate_region.reg'))[0]
sourceIcircle = regions.read_ds9(
    paths.rpath('sourceI_enclosing_circle.reg'))[0]

tabletext = (r"""
\begin{table*}[htp]
\centering
\caption{Continuum Image Parameters}
\begin{tabular}{ccccccccc}
\label{tab:image_metadata}
Band & Robust & Beam Major & Beam Minor & Beam PA               & $T_B$/$S_\nu$      & RMS & Source I $S_{\nu,max}$ & Dynamic Range\\
     &        & \arcsec    & \arcsec    & $\mathrm{{}^{\circ}}$ & $10^3$ K Jy$^{-1}$ & $\mathrm{mJy}~\mathrm{beam}^{-1}$ & $\mathrm{mJy}~\mathrm{beam}^{-1}$ & \\
\hline

XXDATAXX

\hline
\end{tabular}

\end{table*}
Beispiel #56
0
import re
import glob

region_names = {'e2': 'e2_exclude_e2w.reg'}

for regfn, region, fignum, imtype, suffix in (
    ('e2_exclude_e2w.reg', 'e2', 1, 'm0', ''),
    ('e2_exclude_e2w.reg', 'e2', 2, 'm0', '_merge'),
    ('e2_exclude_e2w.reg', 'e2', 3, 'm0', '_merge_natural'),
    ('e2_exclude_e2w.reg', 'e2', 1, 'max', ''),
    ('e2_exclude_e2w.reg', 'e2', 2, 'max', '_merge'),
    ('e2_exclude_e2w.reg', 'e2', 3, 'max', '_merge_natural'),
):

    reg = pyregion.open(paths.rpath(regfn))

    path_template = paths.dpath(
        "chemslices/chemical_{2}_slabs*_{0}*{1}.fits".format(
            region, suffix, imtype))

    files = glob.glob(path_template)

    linestyles = {
        name: itertools.cycle(['-'] + ['--'] + [':'] + ['-.'])
        for name in region_names
    }

    linere = re.compile(
        "chemical_{0}_slabs_[^_]*_(.*?)(_merge.fits|.fits)".format(imtype))
Beispiel #57
0
        im6 = ax6.imshow(LJ_map.value, cmap='gray', vmin=0, vmax=1e4)
        ax6.contourf(LJ_map.value,
                     levels=[
                         0, 2 * (bm_cm_fwhm.to(u.au)).value *
                         gaussian_fwhm_to_sphere_r
                     ],
                     colors=['r', 'r'])
        ax6.set_title("Jeans Length (AU)")
        fig.colorbar(im6)

        for jj in range(1, 7):
            pl.subplot(2, 3, jj).xaxis.set_major_formatter(pl.NullFormatter())
            pl.subplot(2, 3, jj).yaxis.set_major_formatter(pl.NullFormatter())

        if smooth == 0:
            fig.savefig(paths.fpath("jeans_maps_{0}.png".format(name)))
        else:
            fig.savefig(
                paths.fpath("jeans_maps_{0}_smooth{1}.png".format(
                    name, smooth)))

        mass_maps[name] = (mass_map, MJ_map)

    return mass_maps


regions = pyregion.open(paths.rpath("hmcore_centroids.reg"))
jmps = {}
for smooth in (0, 1100, 1300, 1500, 1700, 2000, 3000) * u.AU:
    jmps[smooth] = jeans_maps(regions, smooth=smooth)
Beispiel #58
0
                             -5.3751716623649575,
                             frame='icrs',
                             unit=(u.hour, u.deg))

#diskycoord_list = pyregion.open(paths.rpath("{0}_disk_pvextract.reg"
#                                            .format(source)))[0].coord_list
#diskycoords = coordinates.SkyCoord(["{0} {1}".format(diskycoord_list[jj],
#                                                     diskycoord_list[jj+1])
#                                    for jj in range(0,
#                                                    len(diskycoord_list),
#                                                    2)], unit=(u.deg,
#                                                               u.deg),
#                                   frame='icrs')
#diskycoorddict[source] = diskycoords
diskycoord_list = regions.read_ds9(
    paths.rpath("{0}_disk_pvextract.reg".format(source)))
diskycoorddict[source] = coordinates.SkyCoord(
    [diskycoord_list[0].start, diskycoord_list[0].end])

for width in (0.01, 0.05, 0.1, 0.2, 0.3, 0.4):
    for name, cutoutname, source, vrange, vcen in (('sourceI', 'sourceI',
                                                    coord, (-30, 40),
                                                    assumed_vcen), ):

        diskycoords = diskycoorddict[name]

        for fnt in (
                #'/Volumes/external/orion/OrionSourceI_only.B6.robust0.5.spw{0}.maskedclarkclean10000.image.pbcor.fits',
                #'/Volumes/external/orion/OrionSourceI_only.B6.robust-2.spw{0}.maskedclarkclean10000.image.pbcor.fits',
                #'/Volumes/external/orion/OrionSourceI_only.B6.robust-2.longbaselines.spw{0}.maskedclarkclean10000.image.pbcor.fits',
                #'/Volumes/external/orion/OrionSourceI_only.B3.robust-2.spw{0}.clarkclean10000.image.pbcor.fits',
F.scalebar.set_length(((0.1 * u.pc)/distance*u.radian).to(u.degree).value)
F.scalebar.set_label('0.1 pc')
F.scalebar.set_color('orange')
F.scalebar.set_linewidth(3)
F.scalebar.set_font_size(20)


h77a = SpectralCube.read(paths.dpath('W51north_H77_Outflow_cutout.fits'))
h77a_outflow = h77a.spectral_slab(-16*u.km/u.s, -60*u.km/u.s).sum(axis=0)
c = (0,0.1,0.9)
h77acolors = [c[:3] + (1,) for x in (0.1,0.2,0.3,0.4,0.5,0.6,0.7)]
h77alevels = np.arange(0.02,0.05,0.005)
F.show_contour(h77a_outflow.hdu, levels=h77alevels, colors=h77acolors,
               filled=False, layer='h77a')

cutout_coords = {'xlo':290.91974*u.deg, 'xhi':290.90926*u.deg, 'ylo':14.51492*u.deg, 'yhi':14.523815*u.deg}
cube = SpectralCube.read(dpath('W51Ku_BD_h2co_v30to90_natural_contsub.image.fits')).with_spectral_unit(u.km/u.s, velocity_convention='radio').subcube(**cutout_coords)

vr = [56,60]
core = cube.spectral_slab(vr[0]*u.km/u.s, vr[1]*u.km/u.s).sum(axis=0)
c = (0.9,0.1,0.0)
corecolors = [c[:3] + (1,) for x in (0.1,0.2,0.3,0.4,0.5,0.6,0.7)]
corelevels = np.arange(0.02,0.05,0.005)
F.show_contour(core.hdu, levels=corelevels, colors=corecolors,
               filled=False, layer='core')

F.show_regions(paths.rpath('w51_sinfoni_pointings.reg'))
F.save(os.path.expanduser('~/proposals/vlt/p96/w51/SINFONI_pointings_on_NACO.png'))

pl.draw(); pl.show()