def plotit():
    import astropy.stats
    import pylab as pl

    pl.figure(1).clf()
    pl.figure(2).clf()
    for ii,imname in enumerate(files):

        print(imname)
        data = files[imname]['file'].data
        brickdata = brick_files[imname]['file'].data
        # https://github.com/astropy/astropy/pull/5232 for ignore_nan
        lo = astropy.stats.mad_std(data, ignore_nan=True)
        hi = np.nanmax(data)
        bins = np.logspace(np.log10(lo), np.log10(hi), 100)

        pl.figure(1)
        pl.subplot(3,3,ii+1)
        brickweights = np.ones(np.isfinite(brickdata).sum(), dtype='float')/np.isfinite(brickdata).sum()*np.isfinite(data).sum()
        bH,bL,bP = pl.hist(brickdata[np.isfinite(brickdata)], bins=bins,
                           log=True, alpha=0.5, histtype='step',
                           #weights=brickweights, 
                           bottom=1e-100,
                           color='b', zorder=-1)
        #weights = np.ones(np.isfinite(data).sum(), dtype='float')/np.isfinite(data).sum()
        H,L,P = pl.hist(data[np.isfinite(data)], bins=bins, log=True,
                        alpha=0.5, color='k',
                        #normed=True, 
                        histtype='step')
        #pl.hist(tbl[imname], bins=bins, log=True, alpha=0.5)
        pl.xlim(np.min([bL.min(), L.min()]), L.max())
        pl.semilogx()
        pl.yscale('log', nonposy='clip')
        ax2 = pl.gca().twinx()
        ax2.plot(sorted(tbl[imname]), np.arange(len(tbl),
                                                dtype='float')/len(tbl),
                 'k-', linewidth=3, alpha=0.5, zorder=10)
        ax2.set_xlim(L.min(), L.max())
        ax2.set_ylim(0,1)
        pl.title(imname)

        pl.savefig(paths.fpath("flux_histograms_with_core_location_CDF.png"))

        pl.figure(2)
        pl.subplot(3,3,ii+1)
        pl.imshow(data, cmap='gray_r')
        pl.contour(data, levels=np.percentile(tbl[imname],[5,10,25,50,75,90,95]))
        pl.title(imname)
def main():
    make_model()
    
    densities, dgrid_exp, dgrid_ML, dngrid_exp, dngrid_ML = diffplot_t_of_n()
    pl.figure(1).savefig(paths.fpath('param_fits/modeled_temperature_vs_density_real_vs_recovered_C=13.5.png'), bbox_inches='tight')
    pl.figure(2).savefig(paths.fpath('param_fits/modeled_temperature_vs_density_real_vs_recovered_fractions_C=13.5.png'), bbox_inches='tight')
    pl.figure(3).savefig(paths.fpath('param_fits/modeled_density_vs_density_real_vs_recovered_C=13.5.png'), bbox_inches='tight')
    pl.figure(4).savefig(paths.fpath('param_fits/modeled_density_vs_density_real_vs_recovered_fractions_C=13.5.png'), bbox_inches='tight')

    columns, cgrid_exp, cgrid_ML = diffplot_t_of_c()
    pl.figure(1).savefig(paths.fpath('param_fits/modeled_temperature_vs_column_real_vs_recovered_n=4.5.png'), bbox_inches='tight')
    pl.figure(2).savefig(paths.fpath('param_fits/modeled_temperature_vs_column_real_vs_recovered_fractions_n=4.5.png'), bbox_inches='tight')

    return locals()
def make_model_plot(**kwargs):
    constraints,mf,density,column,temperature = make_model(**kwargs)


    pl.figure(1)
    mf.parplot1d('dens')
    pl.vlines(density, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.figure(2)
    mf.parplot1d('tem')
    pl.vlines(temperature, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.figure(3)
    mf.parplot1d('col')
    pl.vlines(column, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.figure(4)
    mf.parplot1d_all(levels=[0.68268949213708585])
    pl.subplot(3,1,1).vlines(column, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.subplot(3,1,2).vlines(density, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.subplot(3,1,3).vlines(temperature, 0, pl.gca().get_ylim()[1], color='k', zorder=-10)
    pl.suptitle('t={0:0.1f}_c={1:0.1f}_n={2:0.1f}.png'.format(temperature,
                                                              column,
                                                              density,))

    pl.savefig(paths.fpath('param_fits/oned_fit_parameters_example_t={0:0.1f}_c={1:0.1f}_n={2:0.1f}.png'.format(temperature,
                                                                                                                column,
                                                                                                                density,)),
               bbox_inches='tight')
    pl.figure(5)
    mf.denstemplot()
    pl.plot(density, temperature, 'o', markerfacecolor='none', markeredgecolor='r', markeredgewidth=2)
    pl.figure(7)
    mf.denscolplot()
    pl.plot(density, column, 'o', markerfacecolor='none', markeredgecolor='r', markeredgewidth=2)
    pl.figure(8)
    mf.coltemplot()
    pl.plot(column, temperature, 'o', markerfacecolor='none', markeredgecolor='r', markeredgewidth=2)

    pl.draw()
    pl.show()
    return constraints,mf
def fit_all_objects(dend=dend, **kwargs):
    fits = {}

    for obj in dend:
        if obj.bad:
            log.info("Skipping object {0} because it is HC3N or other.".format(obj.idx))
            continue
        log.info("Operating on object {0}".format(obj.idx))
        try:
            sp = fit_object(obj, plot=False, **kwargs)
        except ValueError as ex:
            log.info("Exception for {0}: {1}".format(obj.idx, ex.message))
            continue
        if sp is None:
            log.info("No result for {0}".format(obj.idx))
            continue
        sp.plotter(figure=pl.figure(1))
        sp.specfit.plot_fit(show_components=True)
        sp.plotter.savefig(fpath('dendro/dendro_fit_obj{0:04d}.png'.format(obj.idx)))
        fits[obj.idx] = sp.specfit.parinfo

    return fits
示例#5
0
                                                                min_cut=vmin*1e3,
                                                                max_cut=vmax*1e3,
                                                                asinh_a=0.001),
                         transform=ax.get_transform(cutout_res.wcs),
                         origin='lower',)

        #(x1,y1),(x2,y2) = mywcs.wcs_world2pix([[ra1,dec1]],0)[0], mywcs.wcs_world2pix([[ra2,dec2]],0)[0]
        (x1,y1),(x2,y2) = cutout_im.wcs.wcs_world2pix([[ra1,dec1]],0)[0], cutout_im.wcs.wcs_world2pix([[ra2,dec2]],0)[0]
        ax.axis([x1,x2,y1,y2])
        ax2.axis([x1,x2,y1,y2])
        #tr_fk5 = ax.get_transform("fk5")
        hide_labels(ax)
        hide_labels(ax2)
        #ax.plot([ra1,ra2], [dec1,dec2], transform=tr_fk5, marker='o', color='r', zorder=50)

    fig.subplots_adjust(wspace=0, hspace=0)
    fig.canvas.draw()

    x1 = ax.bbox.x1 / (fig.bbox.x1-fig.bbox.x0)
    # y0 = ax.bbox.y0 / (fig.bbox.y1-fig.bbox.y0)
    y0 = ax2.bbox.y0 / (fig.bbox.y1-fig.bbox.y0)
    # single-ax version height = (ax.bbox.y1-ax.bbox.y0) / (fig.bbox.y1-fig.bbox.y0)
    height = (ax.bbox.y1-ax2.bbox.y0) / (fig.bbox.y1-fig.bbox.y0)
    cax_bbox = [x1 + 0.02, y0, 0.02, height]
    cb = pl.colorbar(mappable=im, cax=fig.add_axes(cax_bbox))
    cb.set_label('mJy/beam')


    fig.savefig(paths.fpath("selfcal_progression_TCTE7m_try2_{0}.pdf".format(name)),
                bbox_inches='tight', dpi=300)
def fourier_suppression(e1,
                        hdr,
                        withline=False,
                        vrange=[100, 'max'],
                        linewidth=20.,
                        linecen=250.,
                        save=False,
                        suppression_factor=3,
                        amplitude=10,
                        interpolate=False,
                        convinterp=True,
                        smooth_width=2):
    """
    Given a spectrum (fn), suppress a velocity range `vrange` by dividing it by
    some factor.  Then plot...
    """

    vres = hdr['CDELT1']
    ff = np.fft.fftfreq(e1.size)

    fvr = e1.size * vres
    fvelo = fvr / (ff / ff[1]) / 2.
    fvelo[0] = fvr
    velo = vres * (np.arange(e1.size) + 1 - hdr['CRPIX1']) + hdr['CRVAL1']

    # Add a 20 km/s wide Gaussian line, see what happens to it
    line = np.exp(-(velo + linecen)**2 / (linewidth**2 * 2.)) * amplitude
    e2 = line + e1

    ft = np.fft.fft(e1)
    ft2 = np.fft.fft(e2)

    #ft[(abs(fvelo)>100) & (abs(fvelo<165))] /= abs(ft[(abs(fvelo)>100) & (abs(fvelo<165))])/1000
    #ft[(abs(fvelo)>230) & (abs(fvelo<556))] /= abs(ft[(abs(fvelo)>230) & (abs(fvelo<556))])/1000
    if 'max' in vrange:
        vrange[1] = max(fvelo) + 1
        offset = 0
    else:
        offset = 10

    lmask = (abs(fvelo) < vrange[1])
    umask = (abs(fvelo) > vrange[0])
    mask = lmask & umask
    levelmask = (abs(fvelo) < vrange[0])

    if interpolate:
        midpt = len(mask) / 2
        whmask, = np.where(mask)
        startpt = whmask[whmask < midpt][0] - 1
        endpt = whmask[whmask < midpt][-1] + 1
        if endpt >= len(mask):
            endpt = len(mask) - 1
        for fff in (ft, ft2):

            if convinterp:
                mdata = fff.copy()
                mdata[mask] = np.nan
                #realdata = convolve(mdata.real, Gaussian1DKernel(1, x_size=51), boundary='extend')
                #imagdata = convolve(mdata.imag, Gaussian1DKernel(1, x_size=51), boundary='extend')
                #interpdata = (realdata[mask]+1j*imagdata[mask])
                amp = convolve(np.abs(mdata),
                               Gaussian1DKernel(smooth_width, x_size=51),
                               boundary='extend')
                phase = convolve(np.angle(mdata),
                                 Gaussian1DKernel(smooth_width, x_size=51),
                                 boundary='extend')
                interpdata = (np.cos(phase) * amp +
                              1j * np.sin(phase) * amp)[mask]
                #pl.figure(5)
                #pl.clf()
                #ax1 = pl.subplot(3,1,1)
                #ax1.plot(np.arange(1,30), fff.real[1:30])
                #ax1.plot(np.arange(1,30), mdata.real[1:30])
                #ax1.plot(whmask[:len(whmask)/2], interpdata.real[:len(whmask)/2],'--')
                #ax2 = pl.subplot(3,1,2)
                #ax2.plot(np.arange(1,30), fff.imag[1:30])
                #ax2.plot(np.arange(1,30), mdata.imag[1:30])
                #ax2.plot(whmask[:len(whmask)/2], interpdata.imag[:len(whmask)/2],'--')
                #ax3 = pl.subplot(3,1,3)
                #ax3.plot(np.arange(1,30), abs(fff)[1:30])
                #ax3.plot(np.arange(1,30), abs(mdata)[1:30])
                #ax3.plot(whmask[:len(whmask)/2], abs(interpdata[:len(whmask)/2]),'--')
                fff[mask] = interpdata
                #ax1.plot(np.arange(1,30), fff.real[1:30],':')
                #ax2.plot(np.arange(1,30), fff.imag[1:30],':')
                #ax3.plot(np.arange(1,30), abs(fff)[1:30],':')
            else:
                for order, compare in zip((-1, 1),
                                          (np.less, np.greater_equal)):
                    mm = mask & compare(np.arange(len(mask), dtype='int'),
                                        midpt)
                    realdata = np.interp(np.arange(startpt + 1,
                                                   endpt), [startpt, endpt],
                                         [fff.real[startpt], fff.real[endpt]])
                    imagdata = np.interp(np.arange(startpt + 1,
                                                   endpt), [startpt, endpt],
                                         [fff.imag[startpt], fff.imag[endpt]])
                    fff[mm] = (realdata + 1j * imagdata)[::order]
    else:
        level = max(abs(ft)[levelmask]) / suppression_factor
        level2 = max(abs(ft2)[levelmask]) / suppression_factor

        ft[(mask)] /= abs(ft[(mask)]) / level
        ft2[(mask)] /= abs(ft2[(mask)]) / level2

    ax1 = pl.figure(1).gca()
    ax1.cla()
    ax1.plot(velo, e1, linestyle='none', color='k', marker=',', label='Input')
    ax1.plot(velo,
             np.fft.ifft(ft) + offset,
             alpha=0.8,
             linestyle='none',
             marker=',',
             color='r',
             label='FT suppressed')
    ax1.set_xlabel("Velocity")
    ax1.set_ylabel("Brightness (K-ish)")
    leg = ax1.legend(loc='best', markerscale=20)
    for ll in leg.get_lines():
        ll.set_marker('o')
        ll.set_markersize(5)
    if save:
        pl.figure(1).savefig(
            paths.fpath('baselines/ft_suppression_spectra.png'))

    ax4 = pl.figure(4).gca()
    ax4.cla()
    ax4.set_title("Synthetic {0} km/s line".format(linewidth))
    ax4.plot(velo,
             e2 - np.median(e2),
             linestyle='none',
             color='b',
             marker=',',
             zorder=-1,
             alpha=0.5,
             label='Input')
    ax4.plot(velo,
             np.fft.ifft(ft2) + offset - np.median(e2),
             alpha=0.5,
             linestyle='none',
             marker=',',
             color='g',
             zorder=-1,
             label='FT Suppressed')
    ax4.plot(velo,
             e2 - np.fft.ifft(ft2) - offset,
             alpha=0.5,
             linestyle='none',
             marker=',',
             color='r',
             zorder=-1,
             label='(a) Diff')
    ax4.plot(velo,
             e1 - np.fft.ifft(ft) - offset * 2,
             alpha=0.5,
             linestyle='none',
             marker=',',
             color='m',
             zorder=-1,
             label='(b) Diff with no synthetic line')
    ax4.plot(velo,
             (e2 - np.fft.ifft(ft2)) - (e1 - np.fft.ifft(ft)) - offset * 3,
             alpha=0.5,
             linestyle='none',
             marker=',',
             color='k',
             zorder=-1,
             label='(a)-(b)')
    ax4.plot(velo,
             line + offset,
             alpha=0.5,
             linewidth=0.5,
             color='k',
             zorder=1,
             label='Synthetic Line')
    ax4.set_xlabel("Velocity")
    ax4.set_ylabel("Brightness (K-ish)")
    leg = ax4.legend(loc='lower left', markerscale=20, fontsize=16)
    for ll in leg.get_lines():
        ll.set_marker('o')
        ll.set_markersize(5)
    if save:
        pl.figure(4).savefig(
            paths.fpath('baselines/ft_suppression_spectra_synthline.png'))
        ax4.axis([1300, 1700, -35, 21])
        pl.figure(4).savefig(
            paths.fpath('baselines/ft_suppression_spectra_synthline_zoom.png'))

    ax2 = pl.figure(2).gca()
    ax2.cla()
    ax2.loglog(fvelo, abs(np.fft.fft(e1)), linewidth=1, label='Input')
    ax2.loglog(fvelo,
               abs(np.fft.fft(e2)),
               linewidth=1,
               label='Synthetic {0} km/s line'.format(linewidth))
    ax2.loglog(fvelo, abs(ft), linewidth=1, label='FT Suppressed (Input)')
    ax2.loglog(fvelo, abs(ft2), linewidth=1, label='FT Suppressed (Synthetic)')
    ax2.set_xlabel("Velocity Scale")
    ax2.set_ylabel("$|FT(spectrum)|$")
    ax2.legend(loc='best')
    if save:
        pl.figure(2).savefig(
            paths.fpath('baselines/ft_suppression_fourierpower.png'))

    ax3 = pl.figure(3).gca()
    ax3.cla()
    ax3.plot(velo, e1 - np.fft.ifft(ft), label='Original')
    ax3.plot(velo,
             e2 - np.fft.ifft(ft2),
             label='Synthetic {0} km/s line'.format(linewidth))
    ax3.set_xlabel("Velocity")
    ax3.set_ylabel("Difference (Input-FT_suppressed)")
    leg = ax3.legend(loc='best', markerscale=20)
    if save:
        pl.figure(3).savefig(
            paths.fpath('baselines/ft_suppression_differences.png'))

    pl.draw()
    pl.show()
示例#7
0
#    FFB6.remove_layer(lyr)

for ii,ind in enumerate(whmask):
    ind = int(ind)
    vel = downsampled_contsub_rrl30a.spectral_axis[ind]
    slc = downsampled_contsub_rrl30a[ind,:,:]
    color = pl.cm.Spectral((ind-whmask.min())/mask.sum())
    FFB6.show_contour(slc.hdu, levels=[slc.max().value*0.95], colors=[color])
    FFB6.ax.annotate("{0:0.1f}".format(vel),
                     (0.20, 0.88-0.02*ii),
                     xycoords='figure fraction',
                     color=color)

#FFB6.ax.axis((41.559800470110005, 76.83040770863137, 38.045746948239589, 63.824569975782737))
FFB6.recenter(83.80877507, -5.372957363, radius=(0.10*u.arcsec).to(u.deg).value)
FFB6.save(paths.fpath('rrls/BN_H30a_velocity_contours_on_BNcontinuum.pdf'), dpi=150)
FFB6.save(paths.fpath('rrls/BN_H30a_velocity_contours_on_BNcontinuum.png'))







mask = ((downsampled_contsub_rrl40a.spectral_axis > -10*u.km/u.s) & (downsampled_contsub_rrl40a.spectral_axis < 50*u.km/u.s))
whmask = np.where(mask)[0]

cont_B3 = spectral_cube.lower_dimensional_structures.Projection.from_hdu(fits.open(paths.dpath('Orion_SourceI_B3_continuum_r-2.clean0.1mJy.image.tt0.pbcor.fits')))

BNcutout_cont_B3 = cont_B3[5569:5627,5333:5397]
BNcutout_cont_B3.quicklook()
def spectral_overlays(fn, name, freq_name_mapping, frequencies, yoffset,
                      minvelo, maxvelo, suffix="", background_fn=None,
                      return_spectra=False, plot_fullspec=True):

    object_data_dict = {}

    spectra = pyspeckit.Spectra([fn.format(name=name, ii=ii)
                                 for ii in range(4)])
    bad_1 = (233.74*u.GHz<spectra.xarr.to(u.GHz)) & (spectra.xarr.to(u.GHz)<234.036*u.GHz)
    bad_2 = (230.00*u.GHz<spectra.xarr.to(u.GHz)) & (spectra.xarr.to(u.GHz)<230.523*u.GHz)
    bad_3 = (spectra.xarr.to(u.GHz) < 218.11*u.GHz)
    spectra.data[bad_1 | bad_2 | bad_3] = np.nan
    beams = [radio_beam.Beam.from_fits_header(sp.header) for sp in spectra]

    # scaling: determine how much to separate spectra by vertically
    scaling = np.nanmax(spectra.data) - np.nanpercentile(spectra.data, 20)
    print("Scaling for {fn} = {scaling}".format(fn=fn.format(name=name, ii=0),
                                                scaling=scaling))
    if np.isnan(scaling):
        raise ValueError("All-nan slice encountered.  There is apparently no data in this file?")

    if background_fn is not None:
        bgspectra = pyspeckit.Spectra([background_fn.format(name=name, ii=ii)
                                       for ii in range(4)])
        bgspectra.data[bad_1 | bad_2 | bad_3] = np.nan
        bg = True
    else:
        bg = False

    fig = pl.figure(0)
    fig.clf()

    for spwnum,sp in enumerate(spectra):
        bad_1 = (233.74*u.GHz<sp.xarr.to(u.GHz)) & (sp.xarr.to(u.GHz)<234.036*u.GHz)
        bad_2 = (230.00*u.GHz<sp.xarr.to(u.GHz)) & (sp.xarr.to(u.GHz)<230.523*u.GHz)
        bad_3 = (sp.xarr.to(u.GHz) < 218.11*u.GHz)
        sp.data[bad_1 | bad_2 | bad_3] = np.nan
        
        # temporary hack for bad data
        if bg and all(bgspectra[spwnum].data == 0):
            bg = False

        (cont, peak, peakfreq, peakfreq_shifted, bestmatch, peakvelo, velo_OK,
         peakspecies, argmax) = quick_analyze(sp, freq_name_mapping, minvelo, maxvelo)

        object_data_dict['continuum20pct{0}'.format(spwnum)] = cont
        object_data_dict['peak{0}freq'.format(spwnum)] = peakfreq

        object_data_dict['peak{0}velo'.format(spwnum)] = peakvelo if velo_OK else np.nan*u.km/u.s
        object_data_dict['peak{0}species'.format(spwnum)] = peakspecies
        object_data_dict['peak{0}'.format(spwnum)] = (peak if velo_OK else np.nan)*u.Jy/u.beam
        object_data_dict['beam{0}area'.format(spwnum)] = beams[spwnum].sr.value

        if bg:
            (bgcont, bgpeak, bgpeakfreq, bgpeakfreq_shifted, bgbestmatch,
             bgpeakvelo, bgvelo_OK, bgpeakspecies,
             bgargmax) = quick_analyze(bgspectra[spwnum], freq_name_mapping,
                                       minvelo, maxvelo)
            object_data_dict['bgpeak{0}freq'.format(spwnum)] = bgpeakfreq

            object_data_dict['bgpeak{0}velo'.format(spwnum)] = bgpeakvelo if bgvelo_OK else np.nan*u.km/u.s
            object_data_dict['bgpeak{0}species'.format(spwnum)] = bgpeakspecies
            object_data_dict['bgpeak{0}'.format(spwnum)] = (bgpeak if bgvelo_OK else np.nan)*u.Jy/u.beam


        log.debug("spw{0} peak{0}={1} line={2}".format(spwnum,
                                                       peak,
                                                       peakspecies)
                 )

        for linename, freq in frequencies.items():
            if sp.xarr.in_range(freq):
                print("Plotting {0} for {1} from spw {2}.  Peakspecies={3}".format(linename, name, spwnum, peakspecies))
                temp = np.array(sp.xarr)
                sp.xarr.convert_to_unit(u.km/u.s, refX=freq)
                if np.isnan(yoffset[linename]) or np.isnan(scaling):
                    raise ValueError("NAN scaling is stupid.")
                if sp.slice(0*u.km/u.s, 120*u.km/u.s).data.max() > sp.slice(0*u.km/u.s, 120*u.km/u.s).data.min():
                    sp.plotter(figure=fig, clear=False, offset=yoffset[linename]*scaling,
                               xmin=0, xmax=120)
                    sp.plotter.axis.text(122, yoffset[linename]*scaling,
                                         "{0}: {1}".format(spwnum, linename))
                sp.xarr.convert_to_unit(u.GHz, refX=freq)
                np.testing.assert_allclose(temp, np.array(sp.xarr))

                if bg:
                    bgs = bgspectra[spwnum]
                    bgs.xarr.convert_to_unit(u.km/u.s, refX=freq)
                    if bgs.slice(0*u.km/u.s, 120*u.km/u.s).data.max() > bgs.slice(0*u.km/u.s, 120*u.km/u.s).data.min():
                        bgs.plotter(axis=sp.plotter.axis,
                                                  clear=False,
                                                  color='b',
                                                  offset=yoffset[linename]*scaling,
                                                  zorder=-100,
                                                  xmin=0,
                                                  xmax=120,
                                                 )
                    bgs.xarr.convert_to_unit(u.GHz, refX=freq)

                if sp.plotter.axis is not None:
                    sp.plotter.axis.set_ylim(-0.1, max(yoffset.values())*scaling+scaling)

                if linename == peakspecies:
                    print('peakvelo, offset, maxdata: ', peakvelo,
                          yoffset[linename]*scaling, sp.data[argmax])
                    sp.plotter.axis.plot(peakvelo, yoffset[linename]*scaling +
                                         sp.data[argmax], 'rx')

    okvelos = [object_data_dict['peak{0}velo'.format(ii)] for ii in range(4) if
               (minvelo < object_data_dict['peak{0}velo'.format(ii)]) and
               (object_data_dict['peak{0}velo'.format(ii)] < maxvelo)]
    if okvelos:
        velo = np.median(u.Quantity(okvelos))
        object_data_dict['mean_velo'] = velo
        sp.plotter.axis.vlines(velo.to(u.km/u.s).value,
                               sp.plotter.axis.get_ylim()[0],
                               sp.plotter.axis.get_ylim()[1],
                               linestyle='--', linewidth=2, color='r',
                               zorder=-50, alpha=0.5)
    else:
        object_data_dict['mean_velo'] = np.nan*u.km/u.s
        velo = 60*u.km/u.s

    fig.savefig(paths.fpath("spectral_overlays/{name}_overlaid_spectra{suffix}.png".format(name=name, suffix=suffix)),
                bbox_inches='tight', bbox_extra_artists=[])

    # plot type #2: full spectrum, with lines ID'd
    if plot_fullspec:
        linenames = list(frequencies.keys())
        freqs_ghz = list(frequencies.values())
        plot_kwargs = {'color':'r', 'linestyle':'--'}
        annotate_kwargs = {'color': 'r'}

        for spwnum,sp in enumerate(spectra):
            fig = pl.figure(spwnum+1)
            fig.clf()
            sp.xarr.convert_to_unit(u.GHz)
            sp.plotter(figure=fig, axis=fig.gca())
            # labels don't update.  still don't know why
            sp.plotter(figure=fig, axis=fig.gca())
            assert sp.plotter._xunit == u.GHz
            assert sp.plotter.xlabel == 'Frequency (GHz)'
            sp.plotter.line_ids(linenames,
                                u.Quantity(freqs_ghz),
                                velocity_offset=velo,
                                plot_kwargs=plot_kwargs,
                                annotate_kwargs=annotate_kwargs)
            assert sp.plotter.xlabel == 'Frequency (GHz)'

            if bg:
                bgs = bgspectra[spwnum]
                bgs.xarr.convert_to_unit(u.GHz)
                bgs.plotter(axis=sp.plotter.axis,
                            clear=False,
                            color='b',
                            zorder=-100,
                           )
                assert bgs.plotter.xlabel == 'Frequency (GHz)'
            assert sp.plotter.xlabel == 'Frequency (GHz)'

            fig.savefig(paths.fpath("spectral_overlays/{name}_spw{spw}_fullspec{suffix}.png".format(name=name,
                                                                                                    spw=spwnum,
                                                                                                    suffix=suffix)),
                        bbox_inches='tight', bbox_extra_artists=[])

            

    if return_spectra:
        return object_data_dict, spectra
    else:
        return object_data_dict
def plot_whole_spectrum(spectra, line_id=line_ids, velocity=55*u.km/u.s,
                        fignum=1, figsize=(8.3,11.7), figname=None,
                        title=None, do_line_ids=True,
                        fontsize=4, linewidth=0.25):
    pl.close(fignum)
    fig = pl.figure(fignum, figsize=figsize)
    
    with mpl.rc_context(rc={'font.size': 12,
                            'axes.labelsize':'medium',
                            'axes.titlesize':'medium'}):

        ax = fig.add_subplot(7,1,1)
        spectra[0].xarr.convert_to_unit(u.GHz)
        spectra[0].xarr.convert_to_unit(u.GHz)
        spectra[0].plotter(axis=ax)
        assert spectra[0].plotter.xlabel == 'Frequency (GHz)'
        if do_line_ids:
            spectra[0].plotter.line_ids(list(line_id.keys()),
                                        list(line_id.values()),
                                        velocity_offset=velocity,
                                        label1_size=fontsize,
                                        plot_kwargs={'linewidth':linewidth},
                                        max_iter=10,
                                       )

        for ii in (1,2,3):
            ax = fig.add_subplot(7,1,2*ii)
            spectra[ii].xarr.convert_to_unit(u.GHz)
            cropspec = spectra[ii][:spectra[ii].shape[0]/2]
            cropspec.plotter(axis=ax)
            if do_line_ids:
                cropspec.plotter.line_ids(list(line_id.keys()),
                                          list(line_id.values()),
                                          velocity_offset=velocity,
                                          label1_size=fontsize,
                                          plot_kwargs={'linewidth':linewidth},
                                          #annotate_kwargs={'fontsize':fontsize},
                                          max_iter=10,
                                         )

            ax = fig.add_subplot(7,1,2*ii+1)
            cropspec = spectra[ii][spectra[ii].shape[0]/2:]
            cropspec.plotter(axis=ax)
            if do_line_ids:
                cropspec.plotter.line_ids(list(line_id.keys()),
                                          list(line_id.values()),
                                          velocity_offset=velocity,
                                          label1_size=fontsize,
                                          plot_kwargs={'linewidth':linewidth},
                                          max_iter=10,
                                          #annotate_kwargs={'fontsize':fontsize},
                                         )

        for ii in range(1,8):
            ax = pl.subplot(7,1,ii)
            ax.set_ylabel("$T_B$ [K]")

        if title is not None:
            pl.subplot(7,1,1).set_title(title)

        if figname is not None:
            pl.savefig(paths.fpath(figname), dpi=300, bbox_inches='tight',
                       bbox_extra_artists=[])
F.tick_labels.set_yformat('dd.dd')
F.tick_labels.set_font(size=20)
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)]
def measure_dendrogram_properties(dend=None, cube303=cube303,
                                  cube321=cube321, cube13co=cube13co,
                                  cube18co=cube18co, noise_cube=noise_cube,
                                  sncube=sncube,
                                  suffix="",
                                  last_index=None,
                                  plot_some=True,
                                  line='303',
                                  write=True):

    assert (cube321.shape == cube303.shape == noise_cube.shape ==
            cube13co.shape == cube18co.shape == sncube.shape)
    assert sncube.wcs is cube303.wcs is sncube.mask._wcs

    metadata = {}
    metadata['data_unit'] = u.K
    metadata['spatial_scale'] =  7.2 * u.arcsec
    metadata['beam_major'] =  30 * u.arcsec
    metadata['beam_minor'] =  30 * u.arcsec
    metadata['wavelength'] =  218.22219*u.GHz
    metadata['velocity_scale'] = u.km/u.s
    metadata['wcs'] = cube303.wcs

    keys = [
            'density_chi2',
            'expected_density',
            'dmin1sig_chi2',
            'dmax1sig_chi2',
            'column_chi2',
            'expected_column',
            'cmin1sig_chi2',
            'cmax1sig_chi2',
            'temperature_chi2',
            'expected_temperature',
            'tmin1sig_chi2',
            'tmax1sig_chi2',
            'eratio321303',
            'ratio321303',
            'logh2column',
            'elogh2column',
            'logabundance',
            'elogabundance',
           ]
    obs_keys = [
            'Stot303',
            'Smin303',
            'Smax303',
            'Stot321',
            'Smean303',
            'Smean321',
            'npix',
            'e303',
            'e321',
            'r321303',
            'er321303',
            '13cosum',
            'c18osum',
            '13comean',
            'c18omean',
            's_ntotal',
            'index',
            'is_leaf',
            'parent',
            'root',
            'lon',
            'lat',
            'vcen',
            'higaldusttem',
            'reff',
            'dustmass',
            'dustmindens',
            'bad',
            #'tkin_turb',
    ]
    columns = {k:[] for k in (keys+obs_keys)}

    log.debug("Initializing dendrogram temperature fitting loop")

    # FORCE wcs to match
    # (technically should reproject here)
    cube13co._wcs = cube18co._wcs = cube303.wcs
    cube13co.mask._wcs = cube18co.mask._wcs = cube303.wcs

    if line == '303':
        maincube = cube303
    elif line == '321':
        maincube = cube321
    else:
        raise ValueError("Unrecognized line: {0}".format(line))

    # Prepare an array to hold the fitted temperatures
    tcubedata = np.empty(maincube.shape, dtype='float32')
    tcubedata[:] = np.nan
    tcubeleafdata = np.empty(maincube.shape, dtype='float32')
    tcubeleafdata[:] = np.nan


    nbad = 0

    catalog = ppv_catalog(dend, metadata)
    pb = ProgressBar(len(catalog))
    for ii,row in enumerate(catalog):
        structure = dend[row['_idx']]
        assert structure.idx == row['_idx'] == ii
        dend_obj_mask = BooleanArrayMask(structure.get_mask(), wcs=cube303.wcs)
        dend_inds = structure.indices()

        view = (slice(dend_inds[0].min(), dend_inds[0].max()+1),
                slice(dend_inds[1].min(), dend_inds[1].max()+1),
                slice(dend_inds[2].min(), dend_inds[2].max()+1),)
        #view2 = cube303.subcube_slices_from_mask(dend_obj_mask)
        submask = dend_obj_mask[view]
        #assert np.count_nonzero(submask.include()) == np.count_nonzero(dend_obj_mask.include())

        sn = sncube[view].with_mask(submask)
        sntot = sn.sum().value
        #np.testing.assert_almost_equal(sntot, structure.values().sum(), decimal=0)

        c303 = cube303[view].with_mask(submask)
        c321 = cube321[view].with_mask(submask)
        co13sum = cube13co[view].with_mask(submask).sum().value
        co18sum = cube18co[view].with_mask(submask).sum().value
        if hasattr(co13sum,'__len__'):
            raise TypeError(".sum() applied to an array has yielded a non scalar.")

        npix = submask.include().sum()
        assert npix == structure.get_npix()
        Stot303 = c303.sum().value
        if np.isnan(Stot303):
            raise ValueError("NaN in cube.  This can't happen: the data from "
                             "which the dendrogram was derived can't have "
                             "NaN pixels.")
        Smax303 = c303.max().value
        Smin303 = c303.min().value

        Stot321 = c321.sum().value
        if npix == 0:
            raise ValueError("npix=0. This is impossible.")
        Smean303 = Stot303/npix
        if Stot303 <= 0 and line=='303':
            raise ValueError("The 303 flux is <=0.  This isn't possible because "
                             "the dendrogram was derived from the 303 data with a "
                             "non-zero threshold.")
        elif Stot303 <= 0 and line=='321':
            Stot303 = 0
            Smean303 = 0
        elif Stot321 <= 0 and line=='321':
            raise ValueError("The 321 flux is <=0.  This isn't possible because "
                             "the dendrogram was derived from the 321 data with a "
                             "non-zero threshold.")
        if np.isnan(Stot321):
            raise ValueError("NaN in 321 line")
        Smean321 = Stot321/npix

        #error = (noise_cube[view][submask.include()]).sum() / submask.include().sum()**0.5
        var = ((noise_cube[dend_obj_mask.include()]**2).sum() / npix**2)
        error = var**0.5
        if np.isnan(error):
            raise ValueError("error is nan: this is impossible by definition.")

        if line == '321' and Stot303 == 0:
            r321303 = np.nan
            er321303 = np.nan
        elif Stot321 < 0:
            r321303 = error / Smean303
            er321303 = (r321303**2 * (var/Smean303**2 + 1))**0.5
        else:
            r321303 = Stot321 / Stot303
            er321303 = (r321303**2 * (var/Smean303**2 + var/Smean321**2))**0.5

        for c in columns:
            assert len(columns[c]) == ii

        columns['index'].append(row['_idx'])
        columns['s_ntotal'].append(sntot)
        columns['Stot303'].append(Stot303)
        columns['Smax303'].append(Smax303)
        columns['Smin303'].append(Smin303)
        columns['Stot321'].append(Stot321)
        columns['Smean303'].append(Smean303)
        columns['Smean321'].append(Smean321)
        columns['npix'].append(npix)
        columns['e303'].append(error)
        columns['e321'].append(error)
        columns['r321303'].append(r321303)
        columns['er321303'].append(er321303)
        columns['13cosum'].append(co13sum)
        columns['c18osum'].append(co18sum)
        columns['13comean'].append(co13sum/npix)
        columns['c18omean'].append(co18sum/npix)
        columns['is_leaf'].append(structure.is_leaf)
        columns['parent'].append(structure.parent.idx if structure.parent else -1)
        columns['root'].append(get_root(structure).idx)
        s_main = maincube._data[dend_inds]
        x,y,z = maincube.world[dend_inds]
        lon = ((z.value-(360*(z.value>180)))*s_main).sum()/s_main.sum()
        lat = (y*s_main).sum()/s_main.sum()
        vel = (x*s_main).sum()/s_main.sum()
        columns['lon'].append(lon)
        columns['lat'].append(lat.value)
        columns['vcen'].append(vel.value)

        mask2d = dend_obj_mask.include().max(axis=0)[view[1:]]
        logh2column = np.log10(np.nanmean(column_regridded.data[view[1:]][mask2d]) * 1e22)
        if np.isnan(logh2column):
            log.info("Source #{0} has NaNs".format(ii))
            logh2column = 24
        elogh2column = elogabundance
        columns['higaldusttem'].append(np.nanmean(dusttem_regridded.data[view[1:]][mask2d]))

        r_arcsec = row['radius']*u.arcsec
        reff = (r_arcsec*(8.5*u.kpc)).to(u.pc, u.dimensionless_angles())
        mass = ((10**logh2column*u.cm**-2)*np.pi*reff**2*2.8*constants.m_p).to(u.M_sun)
        density = (mass/(4/3.*np.pi*reff**3)/constants.m_p/2.8).to(u.cm**-3)

        columns['reff'].append(reff.value)
        columns['dustmass'].append(mass.value)
        columns['dustmindens'].append(density.value)
        mindens = np.log10(density.value)
        if mindens < 3:
            mindens = 3

        if (r321303 < 0 or np.isnan(r321303)) and line != '321':
            raise ValueError("Ratio <0: This can't happen any more because "
                             "if either num/denom is <0, an exception is "
                             "raised earlier")
            #for k in columns:
            #    if k not in obs_keys:
            #        columns[k].append(np.nan)
        elif (r321303 < 0 or np.isnan(r321303)) and line == '321':
            for k in keys:
                columns[k].append(np.nan)
        else:
            # Replace negatives for fitting
            if Smean321 <= 0:
                Smean321 = error
            mf.set_constraints(ratio321303=r321303, eratio321303=er321303,
                               #ratio321322=ratio2, eratio321322=eratio2,
                               logh2column=logh2column, elogh2column=elogh2column,
                               logabundance=logabundance, elogabundance=elogabundance,
                               taline303=Smean303, etaline303=error,
                               taline321=Smean321, etaline321=error,
                               mindens=mindens,
                               linewidth=10)
            row_data = mf.get_parconstraints()
            row_data['ratio321303'] = r321303
            row_data['eratio321303'] = er321303

            for k in row_data:
                columns[k].append(row_data[k])

            # Exclude bad velocities from cubes
            if row['v_cen'] < -80e3 or row['v_cen'] > 180e3:
                # Skip: there is no real structure down here
                nbad += 1
                is_bad = True
            else:
                is_bad = False
                tcubedata[dend_obj_mask.include()] = row_data['expected_temperature']
                if structure.is_leaf:
                    tcubeleafdata[dend_obj_mask.include()] = row_data['expected_temperature']

            columns['bad'].append(is_bad)

            width = row['v_rms']*u.km/u.s
            lengthscale = reff

            #REMOVED in favor of despotic version done in dendrograms.py
            # we use the analytic version here; the despotic version is
            # computed elsewhere (with appropriate gcor factors)
            #columns['tkin_turb'].append(heating.tkin_all(10**row_data['density_chi2']*u.cm**-3,
            #                                             width,
            #                                             lengthscale,
            #                                             width/lengthscale,
            #                                             columns['higaldusttem'][-1]*u.K,
            #                                             crir=0./u.s))

        if len(set(len(c) for k,c in columns.items())) != 1:
            print("Columns are different lengths.  This is not allowed.")
            import ipdb; ipdb.set_trace()

        for c in columns:
            assert len(columns[c]) == ii+1

        if plot_some and not is_bad and (ii-nbad % 100 == 0 or ii-nbad < 50):
            try:
                log.info("T: [{tmin1sig_chi2:7.2f},{expected_temperature:7.2f},{tmax1sig_chi2:7.2f}]"
                         "  R={ratio321303:8.4f}+/-{eratio321303:8.4f}"
                         "  Smean303={Smean303:8.4f} +/- {e303:8.4f}"
                         "  Stot303={Stot303:8.2e}  npix={npix:6d}"
                         .format(Smean303=Smean303, Stot303=Stot303,
                                 npix=npix, e303=error, **row_data))

                pl.figure(1)
                pl.clf()
                mf.denstemplot()
                pl.savefig(fpath("dendrotem/diagnostics/{0}_{1}.png".format(suffix,ii)))
                pl.figure(2).clf()
                mf.parplot1d_all(levels=[0.68268949213708585])
                pl.savefig(fpath("dendrotem/diagnostics/1dplot{0}_{1}.png".format(suffix,ii)))
                pl.draw()
                pl.show()
            except Exception as ex:
                print ex
                pass
        else:
            pb.update(ii+1)

        if last_index is not None and ii >= last_index:
            break

    if last_index is not None:
        catalog = catalog[:last_index+1]

    for k in columns:
        if k not in catalog.keys():
            catalog.add_column(table.Column(name=k, data=columns[k]))

    for mid,lo,hi,letter in (('expected_temperature','tmin1sig_chi2','tmax1sig_chi2','t'),
                             ('expected_density','dmin1sig_chi2','dmax1sig_chi2','d'),
                             ('expected_column','cmin1sig_chi2','cmax1sig_chi2','c')):
        catalog.add_column(table.Column(name='elo_'+letter,
                                        data=catalog[mid]-catalog[lo]))
        catalog.add_column(table.Column(name='ehi_'+letter,
                                        data=catalog[hi]-catalog[mid]))

    if write:
        catalog.write(tpath('PPV_H2CO_Temperature{0}.ipac'.format(suffix)), format='ascii.ipac')

    # Note that there are overlaps in the catalog, which means that ORDER MATTERS
    # in the above loop.  I haven't yet checked whether large scale overwrites
    # small or vice-versa; it may be that both views of the data are interesting.
    tcube = SpectralCube(data=tcubedata, wcs=cube303.wcs,
                         mask=cube303.mask, meta={'unit':'K'},
                         header=cube303.header,
                        )
    tcubeleaf = SpectralCube(data=tcubeleafdata, wcs=cube303.wcs,
                         mask=cube303.mask, meta={'unit':'K'},
                         header=cube303.header,
                        )

    if write:
        log.info("Writing TemperatureCube")
        outpath = 'TemperatureCube_DendrogramObjects{0}.fits'
        tcube.write(hpath(outpath.format(suffix)),
                    overwrite=True)

        outpath_leaf = 'TemperatureCube_DendrogramObjects{0}_leaves.fits'
        tcubeleaf.write(hpath(outpath_leaf.format(suffix)),
                    overwrite=True)


    return catalog, tcube
示例#12
0
                    relative=True,
                    color='r',
                    horizontalalignment='left')
        F.add_label(0.05,
                    0.91,
                    glabel,
                    relative=True,
                    color='g',
                    horizontalalignment='left')
        F.add_label(0.05,
                    0.87,
                    blabel,
                    relative=True,
                    color='b',
                    horizontalalignment='left')
        F.save(paths.fpath("W51e2_{0}_aplpy.png".format(name)))
        F.save(paths.fpath("W51e2_{0}_aplpy.pdf".format(name)))

        cmcontsrc = Table.read(
            paths.vpath('tables/EVLA_VLA_PointSourcePhotometry.ipac'),
            format='ascii.ipac')
        cmok = (cmcontsrc['Frequency'] == 5.9) & (cmcontsrc['Epoch'] == '3')
        cmcoords = coordinates.SkyCoord(cmcontsrc['gracen'][cmok],
                                        cmcontsrc['gdeccen'][cmok],
                                        frame='fk5')

        core_phot_tbl = Table.read(paths.tpath("continuum_photometry.ipac"),
                                   format='ascii.ipac')
        cores = coordinates.SkyCoord(core_phot_tbl['RA'],
                                     core_phot_tbl['Dec'],
                                     frame='fk5')
    print(name)
    print("nn11 ({2}): {0} +/- {1}".format(nn11.mean(), nn11.std(),
                                           distances.shape[0]))
    print("nn11m1 ({2}): {0} +/- {1}".format(nn11m1.mean(), nn11m1.std(),
                                             distancesm1.shape[0]))
    print("nn11m10 ({2}): {0} +/- {1}".format(nn11m10.mean(), nn11m10.std(),
                                              distancesm10.shape[0]))

    pl.figure(6 + nplots * ii).clf()
    pl.title(name)
    pl.plot(distances.mean(axis=0), label="all")
    pl.plot(distancesm1.mean(axis=0), label="M>1")
    pl.plot(distancesm10.mean(axis=0), label="M>10")
    pl.legend(loc='best')
    pl.savefig(paths.fpath(
        'nndensity_experiments/{0}_mean_neighbor_distance_sample_size_effect.pdf'
    ).format(name),
               bbox_inches='tight')

    pl.figure(1 + nplots * ii)
    pl.clf()
    pl.title("{0} random distribution".format(name))
    pl.hist(nn11, label='Full sample', density=True,
            bins=25)  #np.linspace(gridlims[0], gridlims[1], 20))
    pl.hist(nn11m1, label='>1 Msun', alpha=0.5, density=True,
            bins=25)  #np.linspace(gridlims[0], gridlims[1], 20))
    pl.hist(nn11m10, label='>10 Msun', alpha=0.5, density=True,
            bins=25)  #np.linspace(gridlims[0], gridlims[1], 20))
    pl.legend(loc='best')
    pl.savefig(paths.fpath(
        'nndensity_experiments/{0}_mean_neighbor_distance_histogram.pdf').
示例#14
0
            fig5.clf()
            Fsn = aplpy.FITSFigure(snhdu, convention='calabretta', figure=fig5)
            Fsn.show_grayscale(vmin=0, vmax=10, stretch='linear', invert=True)
            Fsn.add_colorbar()
            Fsn.colorbar.set_axis_label_text('Peak S/N')
            Fsn.recenter(**recen)
            Fsn.axis_labels.set_xtext(r'Galactic Longitude')
            Fsn.tick_labels.set_xformat('d.dd')

            Fsn.refresh()
            Fsn._ax1.set_ylabel("$V_{LSR} (\mathrm{km\ s}^{-1})$")
            Fsn._ax1.set_yticklabels([(str(int(x.get_text()) / 1000))
                                      for x in Fsn._ax1.get_yticklabels()])
            Fsn.refresh()

            Fsn.save(fpath("big_maps/pv_peaksn{0}.pdf".format(smooth)))

            for ftemplate, outtype in toloop:

                log.info("Starting " + ftemplate.format(smooth))

                if 'pv' not in ftemplate:
                    cube = SpectralCube.read(hpath(ftemplate.format(smooth)))
                    if weight:
                        wcube = (SpectralCube.read(
                            hpath('APEX_H2CO_303_202_smooth_bl.fits'))
                                 if 'smooth' in smooth else SpectralCube.read(
                                     hpath('APEX_H2CO_303_202_bl.fits')))
                        mcube = (SpectralCube.read(
                            hpath('APEX_H2CO_303_202_smooth_bl_mask.fits'))
                                 if 'smooth' in smooth else SpectralCube.read(
示例#15
0
):

    hdu = fits.open(
        paths.dpath('12m/moments/CH3OH_{0}_cutout_temperaturemap.fits'.format(
            sourcename)))
    tmap = hdu[0].data
    header = hdu[0].header
    mywcs = wcs.WCS(header)
    crd = coordinates.SkyCoord(center[0],
                               center[1],
                               frame='fk5',
                               unit=(u.hour, u.deg))
    pixcen = mywcs.wcs_world2pix(crd.ra.deg, crd.dec.deg, 0)

    weights = ((tmap > 0) & (tmap < 1000)).astype('float')

    nr, bins, rprof = image_tools.radialprofile.azimuthalAverage(
        tmap, binsize=1.0, weights=weights, center=pixcen, 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.ylim(0, 1000)
    pl.xlim(0, 2.5)
    pl.xlabel("Radius (arcsec)")
    pl.ylabel("Average Temperature (K)")
    pl.savefig(
        paths.fpath(
            "chemistry/ch3oh_temperature_radial_profile_{0}.png".format(
                sourcename)))
data = (cutout_e2 * u.beam).to(u.K,
                               beam_e2e8.jtok_equiv(masscalc.centerfreq)).value
norm = astropy.visualization.ImageNormalize(
    data, stretch=astropy.visualization.AsinhStretch())
im = ax.imshow(data,
               origin='lower',
               interpolation='none',
               cmap='gray',
               norm=norm)
ax.contour(struct.get_mask(), levels=[0.5], colors=['orange'], origin='lower')
ax.contour(trunk.get_mask(), levels=[0.5], colors=['red'], origin='lower')
ax.set_xlabel("Right Ascension")
ax.set_ylabel("Declination")
cb = fig1.colorbar(mappable=im)
cb.set_label("$T_B$ [K]")
fig1.savefig(paths.fpath("longbaseline/e2cutout_contours_for_masscalc.pdf"),
             bbox_inches='tight')

print("e2 upper contour Jy, K: {0}, {1}, {2}%".format(
    struct.vmin * u.Jy,
    u.Quantity(struct.vmin, u.Jy).to(u.K, beam_e2e8.jtok_equiv(226 * u.GHz)),
    struct.vmin / struct.values().max() * 100,
))
print("e2 lower contour Jy, K: {0}, {1}, {2}%".format(
    trunk.vmin * u.Jy,
    u.Quantity(trunk.vmin, u.Jy).to(u.K, beam_e2e8.jtok_equiv(226 * u.GHz)),
    trunk.vmin / struct.values().max() * 100))

dende8 = astrodendro.Dendrogram.compute(cutout_e8.value,
                                        min_value=0.0005,
                                        min_delta=0.00001,
                     negamp=False,
                     limited=[(True, False), (False, False), (True, False)])
    thisspec.baseline(excludefit=True, order=2, subtract=True)
    thisspec.specfit(fittype='gaussian',
                     guesses='moments',
                     negamp=False,
                     limited=[(True, False), (False, False), (True, False)])
    log.info(thisspec.specname +
             " fitting: {0}".format(thisspec.specfit.parinfo))
    thisspec.plotter.ymin -= 0.0005
    thisspec.specfit.plotresiduals(axis=thisspec.plotter.axis,
                                   clear=False,
                                   yoffset=-0.005,
                                   label=False)
    thisspec.plotter.savefig(
        paths.fpath('spectra/emission/' + thisspec.specname +
                    "_h2co22emisson_fit.png"),
        bbox_inches='tight')

    thisspec.plotter(xmin=30, xmax=90, errstyle='fill')
    # Jy -> mJy
    thisspec.data *= 1e3
    thisspec.error *= 1e3
    #thisspec.unit = '$T_B$ (K)'
    thisspec.unit = 'mJy/beam'
    thisspec.plotter(errstyle='fill')
    ax2 = thisspec.plotter.axis.twinx()
    ax2.set_ylim(*(np.array(thisspec.plotter.axis.get_ylim()) *
                   thisspec.header['JYTOK'] / 1e3))
    ax2.set_ylabel("$T_B$ (K)")
    thisspec.plotter.savefig(
        paths.fpath('spectra/emission/' + thisspec.specname +
示例#18
0
rgb_mm_im = np.zeros(nir_im.shape + (3, ))
rgb_mm_im[:, :, blue] = np.nan_to_num(monochrome_mm_im)
#rgb_mm_im[:,:,blue] = monochrome_mm_im.filled()
hsv_mm_im = rgb_to_hsv(rgb_mm_im)
hsv_mm_im[:, :, hue] = 20 / 360.
rgb_mm_im = hsv_to_rgb(hsv_mm_im)
rgb_im[:, :, :alpha] += rgb_mm_im

#rgb_im[rgb_im>1] = 1
#rgb_im /= rgb_im.max()

avm = pyavm.AVM.from_header(outhdr)

im = PIL.Image.fromarray((rgb_im[:, :, :alpha] / rgb_im[:, :, :alpha].max() *
                          255).astype('uint8')[::-1, :])
outname = fpath("rgb_irs2_default.png")
im.save(outname)
avm.embed(outname, outname)
im = ImageEnhance.Contrast(im).enhance(1.5)
outname = fpath("rgb_irs2_contrast.png")
im.save(outname)
avm.embed(outname, outname)
im = ImageEnhance.Brightness(im).enhance(1.5)
outname = fpath("rgb_irs2_brightness.png")
im.save(outname)
avm.embed(outname, outname)
#im = ImageEnhance.Brightness(im).enhance(1.5)
#outname = paths.fpath("rgb_irs2_brightness_1.5.png")
#im.save(outname)
#avm.embed(outname, outname)
        if len(cax.yaxis.get_ticklabels()) < 2:
            ticks = np.logspace(np.log10(vmin), np.log10(vmax), 5)
            cax.yaxis.set_ticks(ticks)
            cax.yaxis.set_ticklabels(["{0:0.2g}".format(x) for x in ticks])
        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)
            spectra = spectra_from_cubefn(cubefn, reg, bins_arcsec, coordinate)

            pl.figure(1).clf()

            for bins, (key, spectrum) in zip(bins_arcsec, spectra.items()):
                if hasattr(spectrum, 'beams'):
                    include = np.isfinite(spectrum) & np.array([(bm.major < 1*u.arcsec) &
                                                                (bm.minor < 1*u.arcsec)
                                                                for bm in spectrum.beams])
                    avg_beam = spectral_cube.cube_utils.average_beams(spectrum.beams,
                                                                      includemask=include)
                    spectrum.meta['beam'] = avg_beam
                spectrum.write(paths.spath('{3}_radial_bin_{0:0.2f}to{1:0.2f}_spw{2}.fits'
                                           .format(bins[0], bins[1], spw, pfx)),
                               overwrite=True
                              )


                pl.plot(spectrum.spectral_axis.to(u.GHz).value, spectrum.value,
                        label='{0:0.1f}-{1:0.1f}'.format(*bins))

            pl.xlabel("Frequency (GHz)")
            pl.ylabel("Intensity (Jy)")
            pl.gca().ticklabel_format(useOffset=False)
            pl.gca().get_xaxis().get_major_formatter().set_scientific(False)
            pl.gca().get_yaxis().get_major_formatter().set_scientific(False)
            
            pl.legend(loc='best')
            pl.savefig(paths.fpath('radial_spectra/{1}_radial_spectra_spw{0}.png'
                                   .format(spw, pfx)))
for source in ('e8','north','e2',):

    matplotlib.pyplot.figure(1).clf()
    F1 = aplpy.FITSFigure(paths.dpath('chemslices/chemical_m0_slabs_{0}_CH3OH1029-936_merge.fits'.format(source)),
                          figure=matplotlib.pyplot.figure(1))
    F1.show_grayscale(invert=True, vmax=1100, vmin=-20)
    F1.show_contour(paths.dpath('W51_te_continuum_best.fits'),
                    colors=['r']*11,
                    levels=[0.015, 0.0256944, 0.0577778, 0.11125, 0.186111,
                            0.282361, 0.4, ])

    F1.add_scalebar((0.025*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
    F1.scalebar.set_label('5000 au / 0.025 pc')
    F1.scalebar.set_color('k')

    F1.save(paths.fpath("{0}_continuum_contours_on_ch3oh1029.png".format(source)))

    matplotlib.pyplot.figure(2).clf()
    F = aplpy.FITSFigure(paths.dpath('W51_te_continuum_best.fits'),
                         figure=matplotlib.pyplot.figure(2))
    if source == 'e2': # TODO: mapping for each source
        F.recenter(290.93315, 14.5097, 2.8/3600.)
    F.show_grayscale(invert=True, vmax=0.43, vmin=-0.01, stretch='arcsinh')
    F.show_contour(paths.dpath('chemslices/chemical_m0_slabs_{0}_CH3OH1029-936_merge.fits'.format(source)),
                   colors=['b']*11,
                   levels=np.linspace(200,1100,6), layer='CH3OH')
    #F.ticks.set_xspacing(0.0005)

    F.add_scalebar((0.025*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
    F.scalebar.set_label('5000 au / 0.025 pc')
    F.scalebar.set_color('k')
                  ]])
    ],
                  color='r')
    FF.recenter(pars['cx'], pars['cv'], width=pars['wx'], height=pars['wv'])

    # show() is unfortunately required before the text labels are set
    pl.draw()
    pl.show()
    # may have to find a better way to force this to work:
    FF._ax1.set_yticklabels(
        [str(float(L.get_text()) / 1e3) for L in FF._ax1.get_yticklabels()])
    FF._ax1.set_ylabel("Velocity (km/s)")
    FF._ax1.set_xticklabels(
        [str(float(L.get_text()) * 3600) for L in FF._ax1.get_xticklabels()])
    FF._ax1.set_xlabel("Offset (arcsec)")
    FF.save(paths.fpath('outflows_pv/' + outname.format(extension='png')))

    h2pixels = pars['path'].sample_points(1.0, h2wcs)
    h2velos = [
        h2velomap[0].data[x, y] for y, x in zip(*h2pixels) if x > 0 and y > 0
        and x < h2velomap[0].data.shape[1] and y < h2velomap[0].data.shape[0]
    ]
    h2radec = [
        h2wcs.wcs_pix2world(x, y, 0) for y, x in zip(*h2pixels)
        if x > 0 and y > 0 and x < h2velomap[0].data.shape[1]
        and y < h2velomap[0].data.shape[0]
    ]
    h2offset = [offset_to_point(ra, dec, pars['path']) for ra, dec in h2radec]
    #h2widths = h2velowidthmap[h2pixels]
    if h2offset:
        FF.show_markers(h2offset, (np.array(h2velos) * 1000).tolist(),
        for i in range(Nrows):
            for j in range(Ncols):
                if i == 0:
                    axes[i,j].xaxis.set_ticks_position('top')
                    pl.setp(axes[i,j].get_xticklabels(), visible=False)
                    axes[i,j].xaxis.set_ticklabels([])
                elif i == Nrows-1:
                    axes[i,j].xaxis.set_ticks_position('bottom')
                    pl.setp(axes[i,j].get_xticklabels(), visible=True)
                else:
                    axes[i,j].xaxis.set_ticks_position('none')
                    pl.setp(axes[i,j].get_xticklabels(), visible=False)
                    axes[i,j].xaxis.set_ticklabels([])

                if j == 0:
                    axes[i,j].yaxis.set_ticks_position('left')
                elif j == Ncols-1:
                    axes[i,j].yaxis.set_ticks_position('right')
                    pl.setp(axes[i,j].get_yticklabels(), visible=False)
                    axes[i,j].yaxis.set_ticklabels([])
                else:
                    axes[i,j].yaxis.set_ticks_position('none')
                    pl.setp(axes[i,j].get_yticklabels(), visible=False)
                    axes[i,j].yaxis.set_ticklabels([])

        pl.subplots_adjust(hspace=0,
                           wspace=0)
        pl.savefig(paths.fpath('outflows/{0}_{1}_channelmaps.png'.format(sourcename,species)),
                   bbox_inches='tight')
示例#24
0
            if (plotnum - 1) >= (ny * (nx - 1)):
                pl.xlabel("$E_u$ [K]")
                tl = pl.gca().get_yaxis().get_ticklabels()
                xax = pl.gca().get_xaxis()
                if (plotnum - 1) == (nx * ny - 1):
                    xax.set_ticks((0, 200, 400, 600, 800))
                else:
                    xax.set_ticks((0, 200, 400, 600))
                xax.set_tick_params(labelsize=14)
            else:
                pl.gca().get_xaxis().set_ticklabels([])
                pl.xlabel("")
            #pl.legend(loc='best', fontsize='small')
        pl.subplots_adjust(hspace=0, wspace=0)
        pl.savefig(
            paths.fpath("chemistry/ch3oh_rotation_diagrams_{0}.png".format(
                sourcename)))

        if True:
            tmap, Nmap = fit_all_tex(xaxis,
                                     cube,
                                     cubefrequencies,
                                     indices,
                                     degeneracies,
                                     ecube=ecube,
                                     replace_bad=replace_bad)

            pl.figure(1).clf()
            pl.imshow(tmap, vmin=0, vmax=600, cmap='hot')
            cb = pl.colorbar()
            cb.set_label("Temperature (K)")
            pl.savefig(
    except AssertionError:
        print("Label is {0} instead of Velocity (km / s)".format(ss.plotter.xlabel))
        print("Drawn label is {0}".format(ss.plotter.axis.get_xlabel()))
    ss.specfit(fittype='gaussian',
               guesses=[1,55,10],
               limited=[(True,False),(False,False),(True,False)])
    log.info(ss.specname+" fitting: {0}".format(ss.specfit.parinfo))
    ss.plotter.ymin -= 0.3
    ss.plotter.label(ylabel='$S_\\nu$ (mJy beam$^{-1}$)')

    ax2 = ss.plotter.axis.twinx()
    ax2.set_ylim(*(np.array(ss.plotter.axis.get_ylim()) * ss.header['JYTOK']/1e3))
    ax2.set_ylabel("$T_B$ (K)")

    ss.specfit.plotresiduals(axis=ss.plotter.axis,clear=False,yoffset=-0.3,label=False)
    ss.plotter.savefig(paths.fpath('spectra/h77/'+ss.specname+"_h77a_fit.png"),
                                  bbox_inches='tight')

    pl.figure(ii).clf()
    ss.plotter(xmin=-10,xmax=120, figure=pl.figure(ii), axis=pl.subplot(2,1,1))
    ss.plotter.ymin -= 0.3
    ss.plotter.label(ylabel='$S_\\nu$ (mJy beam$^{-1}$)')
    ss.specfit.plot_fit()

    ax2 = ss.plotter.axis.twinx()
    ax2.set_ylim(*(np.array(ss.plotter.axis.get_ylim()) * ss.header['JYTOK']/1e3))
    ax2.set_ylabel("$T_B$ (K)")

    ss.specfit.plotresiduals(axis=ss.plotter.axis,clear=False,yoffset=-0.3,label=False)

    ss_he = ss.copy()
示例#26
0
    ax1.lines[-1],
    Line2D([0], [0], linestyle=':', color='k', linewidth=2),
    Line2D([0], [0], linestyle='--', color='k', linewidth=2),
    Line2D([0], [0], linestyle='-', color='k', linewidth=2),
), (
    '$20$ K',
    '$50$ K',
    '$100$ K',
    '$10^{13}$ cm$^{-2}$',
    '$10^{14}$ cm$^{-2}$',
    '$10^{15}$ cm$^{-2}$',
),
           loc='best')
#ax1.set_title("$N(p-H_2CO)=10^{14}$")

fig1.savefig(paths.fpath('radex_ratio_lines_vs_density.pdf'),
             bbox_inches='tight')

crange1 = np.logspace(12, 16.5, 100)
fortho = 0.1

fig2 = pl.figure(2)
fig2.clf()
ax2 = fig2.gca()
for density, linestyle in zip((1e3, 1e5, 1e7), (':', '--', '-')):
    for temperature, color in zip((20, 50, 100), ('r', 'b', 'purple')):
        tables1 = [
            RR(density={
                'oH2': density * fortho,
                'pH2': density * (1 - fortho)
            },
示例#27
0
F.show_grayscale(stretch='log',vmin=-1,vmid=-1.5,vmax=1e2,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.add_scalebar(length=((0.5 * u.pc)/distance*u.radian).to(u.degree).value)

F.recenter(290.91669,14.518151,radius=8./3600.)
set_tight_ticks(F)
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('black')
F.scalebar.set_linewidth(3)
F.scalebar.set_font_size(20)

F.save(fpath('IRS2_NACO_Kband.pdf'), dpi=150)

radiohdu = fits.open(dpath('W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'))
for ii in [3,4]:
    for kk in ['CRVAL','CTYPE','CDELT','CRPIX','CUNIT','NAXIS']:
        k = (kk+'{0}').format(str(ii))
        if k in radiohdu[0].header:
            del radiohdu[0].header[k]
for k in set(radiohdu[0].header.keys()):
    if k[:2] == 'PC':
        del radiohdu[0].header[k]
radiohdu[0].header['NAXIS'] = 2
radiohdu[0].data = radiohdu[0].data.squeeze()

F.show_contour(radiohdu,
               levels=np.logspace(np.log10(0.001), np.log10(0.07), 12),
fit.plot_ccdf(color='k')
fit.power_law.plot_ccdf(color='r', linestyle='--')
ax2.set_ylabel("Fraction of sources")

ax3 = fig2.add_subplot(212)

fit = powerlaw.Fit(dendro_merge['peak_cont_flux'])
# doesn't work at all fit.plot_pdf(color='k')
ax3.hist(dendro_merge['peak_cont_flux'], bins=np.logspace(-3,-0.5,15),
         color='k', facecolor='none', histtype='step')
ax3.set_xscale('log')
fit.power_law.plot_pdf(color='r', linestyle='--')
ax3.set_ylim(0.3, 51)
ax3.set_xlabel("Peak flux density (Jy/beam)")
ax3.set_ylabel("Number of sources")
fig2.savefig(paths.fpath('coreplots/dendro_flux_powerlaw_histogram_fit.png'))

print("Fit parameters: alpha={0}".format(fit.power_law.alpha))

radii = (0.2,0.4,0.6,0.8,1.0,1.5)*u.arcsec
lines = np.array([[row['peak_cont_flux']] + [row['cont_flux{0}arcsec'.format(rad).replace(".","p")]
                                        for rad in radii.value]
                  for row in dendro_merge])
pradii = (0.0,0.2,0.4,0.6,0.8,1.0,1.5)

pl.clf()
pl.plot(pradii, lines.T)
pl.plot(pradii, lines[corelike].T)
pl.xlabel("Aperture Radius (\")")
pl.ylabel("Flux (Jy)")
pl.savefig(paths.fpath('coreplots/flux_vs_aperture_radius_alldendrosources.png'))
fig.clf()
FF = aplpy.FITSFigure(paths.dpath('12m/continuum/selfcal_allspw_selfcal_3_mfs_deeper_r0.0.image.pbcor.fits'),
                      figure=fig)
FF.show_colorscale(cmap='bone_r', vmin=-0.005, vmax=0.025, stretch='log', vmid=-0.006)
FF.recenter(center.ra.deg, center.dec.deg, radius=0.0025)
FF.show_colorbar()
FF.add_scalebar((0.1*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
FF.scalebar.set_color('w')
FF.scalebar.set_linewidth(4)
FF.scalebar.set_label("0.1 pc")
FF.scalebar.set_font_size(20)
FF.add_beam()
FF.beam.set_facecolor('none')
FF.beam.set_linewidth(2)
FF.beam.set_edgecolor('w')
FF.save(paths.fpath("e5_bubble.png"))

fig = pl.figure(1)
fig.clf()
FF = aplpy.FITSFigure(paths.dpath('12m/continuum/selfcal_allspw_selfcal_3_mfs_deeper_r2.0.image.pbcor.fits'),
                      figure=fig)
FF.show_colorscale(cmap='bone_r', vmin=-0.015, vmax=0.095, stretch='log', vmid=-0.016)
FF.recenter(center.ra.deg, center.dec.deg, radius=0.0025)
FF.show_colorbar()
FF.add_scalebar((0.1*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
FF.scalebar.set_color('w')
FF.scalebar.set_linewidth(4)
FF.scalebar.set_label("0.1 pc")
FF.scalebar.set_font_size(20)
FF.show_contour(ku_fn, levels=[0.0015, 0.003, 0.006], colors=['w']*5)
FF.add_beam()
            m0 = vcube.with_mask(vcube>0.05*u.Jy).moment0()
            m1 = vcube.with_mask(vcube>0.05*u.Jy).moment1()
            m2 = vcube.with_mask(vcube>0.05*u.Jy).moment2()


    m0.quicklook()
    m0.hdu.writeto(m0fn, clobber=True)

    m1.quicklook()
    m1.hdu.writeto(m1fn, clobber=True)

    m2.quicklook()
    m2.hdu.writeto(m2fn, clobber=True)

    try:
        m0.FITSFigure.save(fpath("moments/{0}_moment0.png".format(fname)))
        m1.FITSFigure.show_colorscale(cmap='viridis', vmin=45, vmax=68)
        m1.FITSFigure.show_contour(m0.hdu, levels=[4], colors=['k'])
        m1.FITSFigure.save(fpath("moments/{0}_moment1.png".format(fname)))
        m2.FITSFigure.show_colorscale(cmap='viridis', vmin=0, vmax=30)
        m2.FITSFigure.show_contour(m0.hdu, levels=[4], colors=['k'])
        m2.FITSFigure.save(fpath("moments/{0}_moment2.png".format(fname)))

        for ra,dec,rad,name in ((290.93253, 14.508016, 0.00311407, 'e2e8'),
                                (290.9118, 14.512366, 0.00311407, 'southeast'),
                                (290.9166, 14.518094, 0.00311407, 'north')):

            m0.FITSFigure.recenter(ra, dec, rad)
            m0.FITSFigure.save(fpath("moments/{0}_{1}zoom_moment0.png".format(fname,name)))
            m1.FITSFigure.recenter(ra, dec, rad)
            m1.FITSFigure.save(fpath("moments/{0}_{1}zoom_moment1.png".format(fname,name)))
示例#31
0
def multiscale_fit(pcube,
                   centerx,
                   centery,
                   offset_scale=0.3,
                   savedir=None,
                   savepre=None,
                   exclude=(236, 323, 539, 654, 972, 1049, 1180, 1238),
                   radii=(2, 3, 4, 5, 6, 7, 8, 9),
                   guesses=[0.84, 37.9, 6.5, 0.5, 0.8, 1.0]):

    pcube.plotter.figure = pl.figure(1)
    pcube.plotter.axis = pl.figure(1).gca()
    pcube.specfit.Registry.add_fitter('h2co_simple',
                                      simple_fitter2,
                                      6,
                                      multisingle='multi')

    sp = pcube.get_spectrum(centerx, centery)
    sp.plotter.figure = pl.figure(1)
    sp.plotter.axis = pl.figure(1).gca()
    fitspec(sp, exclude, guesses)
    sp.specfit.plotresiduals(axis=pcube.plotter.axis,
                             yoffset=-sp.specfit.parinfo[0].value *
                             offset_scale,
                             clear=False,
                             color='#444444',
                             label=False)
    sp.plotter.axis.set_ylim(
        -5 * sp.specfit.residuals.std() -
        sp.specfit.parinfo[0].value * offset_scale,
        pcube.plotter.axis.get_ylim()[1])
    sp.plotter.savefig(paths.fpath('{0}/{1}_r0.pdf'.format(savedir, savepre)))

    r1b = []
    er1b = []
    sigb = []
    esigb = []
    r1 = [sp.specfit.parinfo[3].value]
    er1 = [sp.specfit.parinfo[3].error]
    sig = [sp.specfit.parinfo[2].value]
    esig = [sp.specfit.parinfo[2].error]
    cen = [sp.specfit.parinfo[1].value]
    ecen = [sp.specfit.parinfo[1].error]

    mergefig = pl.figure(0)
    mergefig.clf()
    splast = sp

    for ii, radius in enumerate(radii):
        sp = pcube.get_apspec([centerx, centery, radius], wunit='pixel')
        sp.plotter(figure=pl.figure(1))
        fitspec(sp, exclude, guesses)
        sp.specfit.plotresiduals(axis=pcube.plotter.axis,
                                 yoffset=-sp.specfit.parinfo[0].value *
                                 offset_scale,
                                 clear=False,
                                 color='#444444',
                                 label=False)
        sp.plotter.axis.set_ylim(
            -5 * sp.specfit.residuals.std() -
            sp.specfit.parinfo[0].value * offset_scale,
            sp.plotter.axis.get_ylim()[1])
        sp.plotter.savefig(
            paths.fpath('{0}/{1}_r{2}.pdf'.format(savedir, savepre, radius)))

        r1.append(sp.specfit.parinfo[3].value)
        er1.append(sp.specfit.parinfo[3].error)
        sig.append(sp.specfit.parinfo[2].value)
        esig.append(sp.specfit.parinfo[2].error)
        cen.append(sp.specfit.parinfo[1].value)
        ecen.append(sp.specfit.parinfo[1].error)

        spannulus = sp - splast
        spannulus.plotter.figure = sp.plotter.figure
        spannulus.plotter.axis = sp.plotter.axis
        fitspec(spannulus, exclude, guesses=sp.specfit.parinfo.values)

        spannulus.specfit.plotresiduals(
            axis=pcube.plotter.axis,
            yoffset=-spannulus.specfit.parinfo[0].value * offset_scale,
            clear=False,
            color='#444444',
            label=False)
        spannulus.plotter.axis.set_ylim(
            -5 * spannulus.specfit.residuals.std() -
            spannulus.specfit.parinfo[0].value * offset_scale,
            spannulus.plotter.axis.get_ylim()[1])
        spannulus.plotter.savefig(
            paths.fpath('{0}/{1}_r{2}_annulus.pdf'.format(
                savedir, savepre, radius)))

        r1b.append(spannulus.specfit.parinfo[3].value)
        er1b.append(spannulus.specfit.parinfo[3].error)
        sigb.append(spannulus.specfit.parinfo[2].value)
        esigb.append(spannulus.specfit.parinfo[2].error)

        splast = sp.copy()

        sp.smooth(4)
        sp.plotter(figure=mergefig,
                   clear=False,
                   axis=mergefig.gca(),
                   color=pl.cm.spectral(ii / float(len(radii))),
                   label="{0:0.1f}".format(radius * 7.2))
        sp.plotter.axis.relim()
        sp.plotter.axis.autoscale()

    pl.figure(mergefig.number)
    pl.legend(loc='upper right', fontsize=16)
    mergefig.savefig(
        paths.fpath('{0}/{1}_mergefig.pdf'.format(savedir, savepre)))

    pl.figure(2)
    pl.clf()
    ax1 = pl.subplot(2, 1, 1)
    ax1.errorbar(np.arange(1, 10) * 7.2,
                 r1,
                 yerr=er1,
                 linestyle='none',
                 marker='s',
                 color='k')
    ax1.set_xlim(0.5 * 7.2, 9.5 * 7.2)
    #ax1.set_xlabel("Aperture Radius (arcseconds)")
    ax1.set_ylabel("Ratio $3_{2,1}-2_{2,0} / 3_{0,3} - 2_{0,2}$")
    ax1.xaxis.set_ticklabels([])

    # Remove the bottom label (overlap)
    tl = ax1.yaxis.get_ticklabels()
    tl[0].set_visible(False)

    ax1b = ax1.twinx()
    # set the y limits to pwtem(the ratio limits)
    ylim = ax1.get_ylim()
    # pwtem can't go above 0.6; returns NaN above that
    if ylim[1] > 0.599999:
        ylim = (ylim[0], 0.599999)
        ax1.set_ylim(*ylim)
    ax1b.set_ylim(*pwtem(ylim))
    ax1b.xaxis.set_ticklabels([])
    ax1b.set_ylabel('Temperature (K)')

    ax2 = pl.subplot(2, 1, 2)
    pl.subplots_adjust(hspace=0)
    ax2.errorbar(np.arange(1, 10) * 7.2,
                 sig,
                 yerr=esig,
                 linestyle='none',
                 marker='s',
                 color='k')
    ax2.set_xlim(0.5 * 7.2, 9.5 * 7.2)
    ax2.set_xlabel("Aperture Radius (arcseconds)")
    ax2.set_ylabel("$\sigma$ (km s$^{-1}$)")

    # Steve suggested adding a Mach number label, but this isn't possible:
    # it would require a 3rd graph, since M ~ sigma/sqrt(T)
    # ax2b = ax2.twinx()
    # # set the y limits to the sigma limits
    # ylim = ax2.get_ylim()
    # ax2b.set_ylim()
    # ax2b.xaxis.set_ticklabels([])
    # ax2b.set_ylabel('Temperature (K)')

    pl.savefig(
        paths.fpath('{0}/{1}_ratio_vs_scale.pdf'.format(savedir, savepre)))

    ax1.errorbar(np.arange(2, 10) * 7.2,
                 r1b,
                 yerr=er1b,
                 linestyle='none',
                 marker='s',
                 color='b',
                 zorder=-1,
                 alpha=0.5)
    ax2.errorbar(np.arange(2, 10) * 7.2,
                 sigb,
                 yerr=esigb,
                 linestyle='none',
                 marker='s',
                 color='b',
                 zorder=-1,
                 alpha=0.5)
    pl.savefig(
        paths.fpath('{0}/{1}_ratio_vs_scale_annuli.pdf'.format(
            savedir, savepre)))

    return r1, er1, sig, esig, cen, ecen, r1b, er1b, sigb, esigb
import os
import paths
import glob

figstr = """
\Figure{{figures/pointsource_seds/{fname}}}
{{Point source photometry of {objname}.  See Figure \\ref{{fig:d4sed}} for
details}}
{{fig:{objname}sed}}{{1}}{{7in}}\n\clearpage\n"""

with open(paths.texpath("ptsrcphotometryfigures.tex"), "w") as f:
    for fn in glob.glob(paths.fpath("pointsource_seds/*png")):
        fname = os.path.split(fn)[-1]
        objname = fname.split("_")[0]
        f.write(figstr.format(fname=fname, objname=objname))
    for ii in range(1, plotnum):
        ax = pl.subplot(7, 7, ii)
        ymin = min(ax.get_ylim()[0], ymin)
        ymax = max(ax.get_ylim()[1], ymax)

    for ii in range(1, plotnum):
        ax = pl.subplot(7, 7, ii)
        #ax.set_ylim(ymin, ymax)
        #if ii % 7 != 1:
        ax.yaxis.set_ticklabels([])
        ax.yaxis.set_label("")
        if ii < plotnum - 7:
            ax.xaxis.set_ticklabels([])
            ax.xaxis.set_label("")

    pl.savefig(paths.fpath('spectral_fits/{0}_linefits.png'.format(name)),
               bbox_inches='tight',
               bbox_extra_artists=[])

    pl.figure(2).clf()
    widths = line_table['{0}FittedWidth'.format(name)]
    ewidths = line_table['{0}FittedWidthError'.format(name)]
    labels = line_table['Species']
    inds = np.argsort(widths)
    mask = (widths[inds] > 0) & (widths[inds] < 5) & (
        ewidths[inds] < widths[inds]) & (ewidths[inds] < 5)
    pl.errorbar(x=np.arange(mask.sum()),
                y=widths[inds][mask],
                yerr=ewidths[inds][mask],
                linestyle='none',
                color='k')
    tbl.add_column(Column(data=10**tbl['log10_Aij'], unit=u.s**-1, name='Aij'))
    tbl.rename_column('Upper State Degeneracy', 'gu')

if __name__ == "__main__":

    # investigate difference between splatalogue & Barton cats
    KCl_diff = match_splat_barton(KCls, KCl[KCl['vu'] < 4])
    NaCl_diff = match_splat_barton(NaCls, NaCl[NaCl['vu'] < 6])

    import pylab as pl
    pl.figure(1).clf()
    pl.plot(KCl_diff['Freq_1'], KCl_diff['Splat-Barton'], '.')
    pl.title("KCl")
    pl.xlabel("Frequency (GHz)")
    pl.ylabel("Splatalogue - Barton frequency difference (GHz)")
    pl.savefig(paths.fpath('Splatalogue-Barton_comparison_KCl.pdf'))

    pl.clf()
    pl.plot(KCl_diff['Freq_1'],
            (KCl_diff['Splat-Barton'].quantity / KCl_diff['Freq_1'].quantity *
             constants.c).to(u.km / u.s), '.')
    pl.title("KCl")
    pl.xlabel("Frequency (GHz)")
    pl.ylabel("Splatalogue - Barton frequency difference (km/s)")
    pl.savefig(paths.fpath('Splatalogue-Barton_comparison_KCl_kms.pdf'))

    pl.clf()
    pl.plot(KCl_diff['EU_K'],
            (KCl_diff['Splat-Barton'].quantity / KCl_diff['Freq_1'].quantity *
             constants.c).to(u.km / u.s), '.')
    pl.title("KCl")
fittable = table.Table.read(tpath("fitted_line_parameters.ipac"),
                            format='ascii.ipac')
fittable.add_columns([table.Column(name=name, dtype='float', length=len(fittable))
                      for name in ['temperature_chi2','tmin1sig_chi2','tmax1sig_chi2',
                                   'expected_temperature',
                                   'column_chi2','cmin1sig_chi2','cmax1sig_chi2',
                                   'expected_column',
                                   'density_chi2','dmin1sig_chi2','dmax1sig_chi2',
                                   'expected_density',
                                   'logh2column','elogh2column',
                                   'logabundance','elogabundance',
                                   'tkin_turb', 'reff_pc',
                                  ]])

if not os.path.exists(paths.fpath('param_fits')):
    os.makedirs(paths.fpath('param_fits'))

nlevs = 4
#levels = [stats.norm.cdf(ii)-stats.norm.cdf(-ii)
#           for ii in range(1,nlevs)]
ndof = 3
levels = ([0]+
          [stats.chi2.ppf(stats.norm.cdf(ii)-stats.norm.cdf(-ii),
                          ndof)
           for ii in range(1,nlevs)])

density_label = 'Density $n(\mathrm{H}_2)$ [log cm$^{-3}$]'
column_label = 'Column p-H$_2$CO [log cm$^{-2}$/(km s$^{-1}$ pc)]'
density_label_short = "$n(\mathrm{H}_2) (\mathrm{cm}^{-3})$"
column_label_short = "$N(\mathrm{p-H}_2\mathrm{CO}) (\mathrm{cm}^{-2})$"
示例#36
0
    for regfn, contfn, name in (
        ('w51north_protostars.reg', 'W51n_cont_uniform.image.tt0.pbcor.fits',
         'NorthUniform'),
        ('w51north_protostars.reg', 'W51n.cont.image.allEB.fits',
         'NorthRobust'),
        ('w51e_protostars.reg', 'W51e2_cont_uniform.image.tt0.pbcor.fits',
         'W51eUniform'),
        ('w51e_protostars.reg', 'W51e2_cont_briggs.image.fits', 'W51eRobust'),
    ):

        regs = regions.read_ds9(paths.rpath(regfn))

        contfn = paths.dpath('longbaseline/' + contfn)

        fit_data = gaussfit_catalog(
            contfn,
            regs,
            radius=0.1 * u.arcsec,
            prefix=name + "_",
            max_radius_in_beams=5,
            max_offset_in_beams=2,
            savepath=paths.fpath('longbaseline/gaussfits'))

        tbl = data_to_table(fit_data)

        tbl.rename_column("chi2/n", "chi2_n")
        tbl.write(paths.tpath("gaussian_fit_table_{0}.ipac".format(name)),
                  format='ascii.ipac',
                  overwrite=True)
        sblength = 0.05*u.pc
    F.add_scalebar(length=(sblength/distance*u.radian).to(u.degree).value)
    F.scalebar.set_label(sblength)
    F.scalebar.set_color('black')
    F.scalebar.set_linewidth(3)
    F.scalebar.set_font_size(20)
    pixscale = np.abs(F._wcs.pixel_scale_matrix[1,1])
    if name in annotations:
        for (x,y), to_offset, from_offset, color, kwargs in annotations[name]:
            dx = (from_offset[0]-to_offset[0]) / pixscale
            dy = (from_offset[1]-to_offset[1]) / pixscale
            F.show_arrows(x, y, dx, dy, color=color)

    F.show_colorbar()
    F.colorbar.set_axis_label_text("mJy/beam")
    F.save(paths.fpath("diffuse/{0}_aplpy.png".format(name)))

    fig = pl.figure(2)
    fig.clf()
    ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcsaxes)
    im = ax.imshow(hdu.data.squeeze()*1e3, cmap=pl.cm.gray_r, origin='lower',
                   vmin=vmin, vmax=vmax,
                   norm=ImageNormalize(stretch=stretch))

    (x1,y1),(x2,y2) = mywcs.wcs_world2pix(coord_limits, 0)
    ax.set_xlim(x1,x2)
    ax.set_ylim(y1,y2)
    ra = ax.coords['ra']
    ra.set_major_formatter('hh:mm:ss.s')
    ra.set_ticks(spacing=spacing*u.deg)
    dec = ax.coords['dec']
                return ["%.1f" % z for z in newx]

            new_tick_locations = np.arange(0, 8000, 1000) * u.au
            new_tick_locs_as = (new_tick_locations / masscalc.distance).to(
                u.arcsec, u.dimensionless_angles())
            ax2.set_xlim(ax.get_xlim())
            ax2.set_xticks(new_tick_locs_as.value)
            ax2.set_xticklabels(tick_function(new_tick_locs_as.value))
            ax2.set_xlabel(r"Radius [au]")


regions = pyregion.open(paths.rpath("hmcore_centroids.reg"))
make_rprof(regions, ploteach=True)
nplots = len(regions)
pl.figure(nplots * 3 + 2).savefig(
    paths.fpath("cumulative_radial_flux_massivecores.png"))
pl.figure(nplots * 3 + 3).savefig(
    paths.fpath("cumulative_radial_mass_massivecores.png"))
pl.figure(nplots * 3 + 4).savefig(
    paths.fpath("cumulative_density_40K_massivecores.png"))
pl.figure(nplots * 3 + 5).savefig(
    paths.fpath("azimuthalaverage_density_40K_massivecores.png"))
pl.figure(nplots * 3 + 6).savefig(
    paths.fpath("azimuthalaverage_radial_mj_40K_massivecores.png"))
pl.figure(nplots * 3 + 7).savefig(
    paths.fpath("azimuthalaverage_radial_mj_of_TCH3OH_massivecores.png"))
pl.figure(nplots * 3 + 8).savefig(
    paths.fpath("cumulative_radial_mass_of_TCH3OH_massivecores.png"))
pl.figure(nplots * 3 + 9).savefig(
    paths.fpath("azimuthalaverage_radial_TCH3OH_massivecores.png"))
pl.figure(nplots * 3 + 10).savefig(
data = np.linspace(0.01, 0.7)

fig = pl.figure(1)
pl.clf()

ax = fig.gca()

ax.plot(data, ratio_to_temperature(data), alpha=0.5, linewidth=2,
        label='LTE',
       )
ax.set_ylim(0,150)
ax.set_xlabel("Ratio H$_2$CO $3_{2,1}-2_{2,0} / 3_{0,3}-2_{0,2}$")
ax.set_ylabel("Temperature (K)")

fig.savefig(paths.fpath('h2co_temperature_vs_ratio_lte.png'))

pm = paraH2COmodel()

densind = np.argmin(np.abs(pm.densityarr[0,:,0]-4.5))
colind = np.argmin(np.abs(pm.columnarr[0,:,0]-13.5))

ax.plot(pm.modelratio1[:,densind,colind],
        pm.temparr[:,densind,colind],
        'r',
        alpha=0.5,
        linewidth=2,
        label='$n=10^{4.5}$ cm$^{-3}$, $N=10^{13.5}$ cm$^{-2}$',
       )

pl.legend(loc='best')
    cube = SpectralCube.read(dpath(cube_fn)).with_spectral_unit(u.km/u.s,
                                                                velocity_convention='radio')
    errspec = cube.std(axis=(1,2))
    pix_area = np.abs(np.product(np.diag(cube.wcs.celestial.pixel_scale_matrix)))
    beam = radio_beam.Beam.from_fits_header(cube.header)
    ppbeam = beam.sr.to(u.deg**2).value/pix_area

    JyToK = u.Jy.to(u.K, equivalencies=u.brightness_temperature(beam,
                                                                cube.wcs.wcs.restfrq*u.Hz))

    for regname, outdir in [('W51_22_emission.reg', 'emission'),
                            ('W51_e_apertures.reg', 'hiiregionh2co')]:

        outpath = dpath('spectra/{0}'.format(outdir))
        figpath = fpath('spectra/{0}'.format(outdir))

        if not os.path.exists(outpath):
            os.makedirs(outpath)
        if not os.path.exists(figpath):
            os.makedirs(figpath)


        regions = pyregion.open(rpath(regname))


        prefix = os.path.basename(cube_fn)

        t0 = time.time()
        
        for R in regions:
                linestyle=linestyles[temperature], alpha=0.5, linewidth=3,
                label="NH$_3$ 1-1 $T={0}$K".format(temperature))
        ax.plot(densities, tex_nh322[temperature], color='m',
                linestyle=linestyles[temperature], alpha=0.5, linewidth=3,
                label="NH$_3$ 2-2 $T={0}$K".format(temperature))
        ax.plot(densities, tex_h2co[temperature], color='r',
                linestyle=linestyles[temperature], alpha=0.5, linewidth=3,
                label="p-H$_2$CO $3_{{0,3}}-2_{{0,2}} T={0}$K".format(temperature))
        ax.plot(densities, tex_h2co321[temperature], color='g',
                linestyle=linestyles[temperature], alpha=0.5, linewidth=3,
                label="p-H$_2$CO $3_{{2,1}}-2_{{2,0}} T={0}$K".format(temperature))
    ax.vlines(1e3,0,55,color='k', alpha=0.5, linewidth=2, zorder=-10,
              linestyle='--')
    ax.vlines(1e4,0,55,color='k', alpha=0.5, linewidth=2, zorder=-10,
              linestyle=':')
    ax.vlines(1e5,0,55,color='k', alpha=0.5, linewidth=2, zorder=-10,
              linestyle='-')
    ax.set_xscale('log')
ax1,ax2 = fig1.axes
ax1.set_ylim(2.5,50)
ax2.set_ylim(2.5,5)
ax2.set_xlabel("Volume Density ($n(H_2)$ cm$^{-3}$)")
fig1.text(0.05, 0.5, "Excitation Temperature $T_{ex}$ (K)", rotation=90,
          ha='center', va='center')
fig1.subplots_adjust(hspace=0)
ax2.legend(loc='lower right', fontsize=14)
fig1.savefig(paths.fpath("radex/NH3andH2COexcitation.pdf"))

pl.draw()
pl.show()
示例#42
0
           linewidths=0.9,
           transform=ax.get_transform(
               wcs.WCS(cont_b3[0].header).celestial[2700:-2700, 2700:-2700]))
ax.axis((525, 725, 375, 625))

ax.contour(hcnv1j1.value,
           colors=['lime'] * 10,
           levels=[100, 150],
           linewidths=0.9,
           transform=ax.get_transform(hcnv1j1.wcs))
ax.contour(hcnv3j1.value,
           colors=['r'] * 10,
           levels=[150, 200, 250, 300, 450, 500],
           linewidths=0.9,
           transform=ax.get_transform(hcnv3j1.wcs))
ax.contour(siov2j2.value,
           colors=['c'] * 10,
           levels=np.linspace(500, 10000, 5),
           linewidths=0.9,
           transform=ax.get_transform(siov2j2.wcs))

#ax.plot(v2maser.center.ra, v2maser.center.dec, marker='x', color='w',
#        markersize=7,
#        markeredgewidth=0.5,
#        transform=ax.get_transform('icrs'))

ax.set_xlabel("RA (ICRS)")
ax.set_ylabel("Dec (ICRS)")

fig.savefig(paths.fpath('sgrb2n_sio_maser_and_hcn.pdf'), bbox_inches='tight')
        pl.figure(ii)
        pl.clf()

    figs = [FITSFigure(fn, figure=pl.figure(ii+1))
            for ii,fn in enumerate(files)]

    for fig,fn in zip(figs,files):
        if '11' in fn:
            cblabel = (r'$\tau_{1-1}$')
        elif '22' in fn:
            cblabel = (r'$\tau_{2-2}$')
        elif 'ratio' in fn:
            cblabel = (r'$\tau_{1-1} / \tau_{2-2}$')
        else:
            raise ValueError("This is not a file: {0}".format(fn))

        fig.colorbar.set_axis_label_text(cblabel)
        fig.colorbar.set_axis_label_rotation(270)
        fig.colorbar.set_axis_label_pad(30)


    figs[2].show_colorscale(cmap=pl.cm.gist_stern, vmin=0, vmax=15)
    figs[5].show_colorscale(cmap=pl.cm.gist_stern, vmin=0, vmax=15)

    figs[0].save(fpath(label+'peak_observed_opticaldepth_11.pdf'), dpi=72)
    figs[1].save(fpath(label+'peak_observed_opticaldepth_22.pdf'), dpi=72)
    figs[2].save(fpath(label+'peak_observed_opticaldepth_ratio.pdf'), dpi=72)
    figs[5].save(fpath(label+'peak_observed_opticaldepth_ratio_tex.pdf'), dpi=72)

pl.show()
    'north': 58 * u.km / u.s,
}

pl.figure(1).clf()

for target in snu_min:
    files = glob.glob(paths.spath("*{0}*fits".format(target)))
    if len(files) == 0:
        print("No matches for {0}".format(target))
        continue

    spectra = pyspeckit.Spectra(files)

    for ii in range(4):
        spectra[ii].plotter(figure=pl.figure(1))

        species_names = [x[0] for x in line_to_image_list]
        frequencies = u.Quantity(
            [float(x[1].strip("GHz")) for x in line_to_image_list], unit=u.GHz)

        spectra[ii].plotter.axis.set_ylim(
            snu_min[target], spectra[ii].plotter.axis.get_ylim()[1])
        spectra[ii].plotter.line_ids(species_names,
                                     u.Quantity(frequencies),
                                     velocity_offset=velo[target],
                                     plot_kwargs=plot_kwargs,
                                     annotate_kwargs=annotate_kwargs)
        outname = paths.fpath('line_id_spectra/{target}_spw{0}.png'.format(
            ii, target=target))
        spectra[ii].plotter.savefig(outname, bbox_extra_artists=[])
for name, center, size in (('e2e', e2e, 7.5*u.arcsec),
                           ('between_e2e_and_e8', between_e2e_and_e8, 15*u.arcsec),
                           ('e8fil', e8fil, 12.5*u.arcsec),
                           ('north', north, 7.5*u.arcsec)):

    cutout_red = Cutout2D(red_fits[0].data, center, size, wcs=red_wcs)
    cutout_blue = Cutout2D(blue_fits[0].data, center, size, wcs=blue_wcs)

    cutout_m0 = Cutout2D(m0.value, center, size, wcs=cube.wcs.celestial)

    fig1 = pl.figure(1)
    fig1.clf()
    cutout_m0_hdu = fits.PrimaryHDU(data=cutout_m0.data, header=cutout_m0.wcs.to_header())
    FF = aplpy.FITSFigure(cutout_m0_hdu, figure=fig1)
    FF.show_grayscale()
    fig1.savefig(paths.fpath("methanol_{0}.png".format(name)))
    
    levels = [0.5,1,2,3,4,5,6,7,8,9,10,15]
    alphas = np.linspace(0.1, 0.9, len(levels))

    FF.add_scalebar((0.1*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
    FF.scalebar.set_label('0.1 pc')
    FF.scalebar.set_color('w')

    FF.show_contour(fits.PrimaryHDU(data=cutout_blue.data, header=cutout_blue.wcs.to_header()),
                    levels=levels,
                    filled=True,
                    colors=[(0,0,1,ii) for ii in alphas])
    FF.show_contour(fits.PrimaryHDU(data=cutout_red.data, header=cutout_red.wcs.to_header()),
                    filled=True,
                    levels=levels,
示例#46
0
                              vmin_r=-0.0025,
                              vmin_b=-0.0025,
                              vmin_g=0.0001,
                              stretch_g='linear', embed_avm_tags=True)


pl.rcParams['font.size'] = 18
fig1 = pl.figure(1)
fig1.clf()
F = aplpy.FITSFigure(rgb_cube_png, figure=fig1)
F.show_rgb(rgb_cube_png)
F.recenter(290.93315, 14.509584, radius=0.0004)
F.add_scalebar((0.025*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
F.scalebar.set_label('5000 au / 0.025 pc')
F.scalebar.set_color('w')
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy.png"))
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy.pdf"))


F.recenter(290.93318, 14.509591, radius=0.0001)
F.scalebar.set_length((0.005*u.pc / (5400*u.pc)).to(u.deg,u.dimensionless_angles()))
F.scalebar.set_label('1000 au / 0.005 pc')
F.scalebar.set_color('w')
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy_zoom.png"))
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy_zoom.pdf"))

F.show_contour(e2_green_fits, levels=[0.0007], colors=['w']*10)
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy_zoom_continuumcontours.png"))
F.save(paths.fpath("outflows/W51e2_cycle3green_SiO_outflows_aplpy_zoom_continuumcontours.pdf"))

示例#47
0
def multiscale_fit(pcube, centerx, centery, offset_scale=0.3, savedir=None,
                   savepre=None, exclude=(236,323, 539,654, 972,1049,
                                          1180,1238),
                   radii=(2,3,4,5,6,7,8,9),
                   guesses=[0.84,37.9,6.5,0.5,0.8,1.0]):

    pcube.plotter.figure = pl.figure(1)
    pcube.plotter.axis = pl.figure(1).gca()
    pcube.specfit.Registry.add_fitter('h2co_simple', simple_fitter2, 6,
                                      multisingle='multi')
    
    sp = pcube.get_spectrum(centerx, centery)
    sp.plotter.figure = pl.figure(1)
    sp.plotter.axis = pl.figure(1).gca()
    fitspec(sp, exclude, guesses)
    sp.specfit.plotresiduals(axis=pcube.plotter.axis,
                             yoffset=-sp.specfit.parinfo[0].value*offset_scale,
                             clear=False, color='#444444', label=False)
    sp.plotter.axis.set_ylim(-5*sp.specfit.residuals.std()
                             -sp.specfit.parinfo[0].value*offset_scale,
                             pcube.plotter.axis.get_ylim()[1])
    sp.plotter.savefig(paths.fpath('{0}/{1}_r0.pdf'.format(savedir, savepre)))

    r1b = []
    er1b = []
    sigb = []
    esigb = []
    r1 = [sp.specfit.parinfo[3].value]
    er1 = [sp.specfit.parinfo[3].error]
    sig = [sp.specfit.parinfo[2].value]
    esig = [sp.specfit.parinfo[2].error]
    cen = [sp.specfit.parinfo[1].value]
    ecen = [sp.specfit.parinfo[1].error]

    mergefig = pl.figure(0)
    mergefig.clf()
    splast = sp

    for ii,radius in enumerate(radii):
        sp = pcube.get_apspec([centerx, centery, radius], wunit='pixel')
        sp.plotter(figure=pl.figure(1))
        fitspec(sp, exclude, guesses)
        sp.specfit.plotresiduals(axis=pcube.plotter.axis,
                                 yoffset=-sp.specfit.parinfo[0].value*offset_scale,
                                 clear=False, color='#444444', label=False)
        sp.plotter.axis.set_ylim(-5*sp.specfit.residuals.std()
                                 -sp.specfit.parinfo[0].value*offset_scale,
                                 sp.plotter.axis.get_ylim()[1])
        sp.plotter.savefig(paths.fpath('{0}/{1}_r{2}.pdf'.format(savedir,
                                                                    savepre,
                                                                    radius)))

        r1.append(sp.specfit.parinfo[3].value)
        er1.append(sp.specfit.parinfo[3].error)
        sig.append(sp.specfit.parinfo[2].value)
        esig.append(sp.specfit.parinfo[2].error)
        cen.append(sp.specfit.parinfo[1].value)
        ecen.append(sp.specfit.parinfo[1].error)

        spannulus = sp - splast
        spannulus.plotter.figure = sp.plotter.figure
        spannulus.plotter.axis = sp.plotter.axis
        fitspec(spannulus, exclude, guesses=sp.specfit.parinfo.values)

        spannulus.specfit.plotresiduals(axis=pcube.plotter.axis,
                                 yoffset=-spannulus.specfit.parinfo[0].value*offset_scale,
                                 clear=False, color='#444444', label=False)
        spannulus.plotter.axis.set_ylim(-5*spannulus.specfit.residuals.std()
                                 -spannulus.specfit.parinfo[0].value*offset_scale,
                                 spannulus.plotter.axis.get_ylim()[1])
        spannulus.plotter.savefig(paths.fpath('{0}/{1}_r{2}_annulus.pdf'.format(savedir,
                                                                    savepre,
                                                                    radius)))

        r1b.append(spannulus.specfit.parinfo[3].value)
        er1b.append(spannulus.specfit.parinfo[3].error)
        sigb.append(spannulus.specfit.parinfo[2].value)
        esigb.append(spannulus.specfit.parinfo[2].error)


        splast = sp.copy()

        sp.smooth(4)
        sp.plotter(figure=mergefig, clear=False,
                   axis=mergefig.gca(),
                   color=pl.cm.spectral(ii/float(len(radii))),
                   label="{0:0.1f}".format(radius*7.2))
        sp.plotter.axis.relim()
        sp.plotter.axis.autoscale()

    pl.figure(mergefig.number)
    pl.legend(loc='upper right', fontsize=16)
    mergefig.savefig(paths.fpath('{0}/{1}_mergefig.pdf'.format(savedir,
                                                               savepre)))

    pl.figure(2)
    pl.clf()
    ax1 = pl.subplot(2,1,1)
    ax1.errorbar(np.arange(1,10)*7.2, r1, yerr=er1, linestyle='none',
                 marker='s', color='k')
    ax1.set_xlim(0.5*7.2,9.5*7.2)
    #ax1.set_xlabel("Aperture Radius (arcseconds)")
    ax1.set_ylabel("Ratio $3_{2,1}-2_{2,0} / 3_{0,3} - 2_{0,2}$")
    ax1.xaxis.set_ticklabels([])

    # Remove the bottom label (overlap)
    tl = ax1.yaxis.get_ticklabels()
    tl[0].set_visible(False)

    ax1b = ax1.twinx()
    # set the y limits to pwtem(the ratio limits)
    ylim = ax1.get_ylim()
    # pwtem can't go above 0.6; returns NaN above that
    if ylim[1] > 0.599999:
        ylim = (ylim[0], 0.599999)
        ax1.set_ylim(*ylim)
    ax1b.set_ylim(*pwtem(ylim))
    ax1b.xaxis.set_ticklabels([])
    ax1b.set_ylabel('Temperature (K)')

    ax2 = pl.subplot(2,1,2)
    pl.subplots_adjust(hspace=0)
    ax2.errorbar(np.arange(1,10)*7.2, sig, yerr=esig, linestyle='none',
                 marker='s', color='k')
    ax2.set_xlim(0.5*7.2,9.5*7.2)
    ax2.set_xlabel("Aperture Radius (arcseconds)")
    ax2.set_ylabel("$\sigma$ (km s$^{-1}$)")

    # Steve suggested adding a Mach number label, but this isn't possible:
    # it would require a 3rd graph, since M ~ sigma/sqrt(T)
    # ax2b = ax2.twinx()
    # # set the y limits to the sigma limits
    # ylim = ax2.get_ylim()
    # ax2b.set_ylim()
    # ax2b.xaxis.set_ticklabels([])
    # ax2b.set_ylabel('Temperature (K)')

    pl.savefig(paths.fpath('{0}/{1}_ratio_vs_scale.pdf'.format(savedir, savepre)))

    ax1.errorbar(np.arange(2,10)*7.2, r1b, yerr=er1b, linestyle='none',
                 marker='s', color='b', zorder=-1, alpha=0.5)
    ax2.errorbar(np.arange(2,10)*7.2, sigb, yerr=esigb, linestyle='none',
                 marker='s', color='b', zorder=-1, alpha=0.5)
    pl.savefig(paths.fpath('{0}/{1}_ratio_vs_scale_annuli.pdf'.format(savedir, savepre)))

    return r1,er1,sig,esig,cen,ecen,r1b,er1b,sigb,esigb
示例#48
0
        err=noise_norm,
        return_error=True)
        for v in ProgressBar(np.arange(vr[0],vr[1]+dv.value,dv.value))]

    integrated_image = (scube.spectral_slab(vr[0]*u.km/u.s,
                                            vr[1]*u.km/u.s).moment0(axis=0))
    gaussfit_total,fitimage = gaussfitter.gaussfit(np.nan_to_num(integrated_image.value),
                                                   err=noise.value,
                                                   returnfitimage=True
                                         )
    # sanity check: make sure the fit is OK (it is)
    pl.figure(2).clf()
    pl.imshow(integrated_image.value, cmap=pl.cm.bone_r)
    cb = pl.colorbar()
    pl.contour(fitimage, cmap=pl.cm.spectral)
    pl.savefig(fpath('sanitycheck_w51e8_core_gaussfits_{0}.png'.format(name)))

    pl.figure(3).clf()
    pl.imshow((u.Quantity(integrated_image)/(u.km/u.s))
              .to(u.K, u.brightness_temperature(beam, 14.488*u.GHz)).value,
              cmap=pl.cm.bone_r)
    cb = pl.colorbar()
    pl.contour(fitimage, cmap=pl.cm.spectral)
    pl.savefig(fpath('sanitycheck_K_w51e8_core_gaussfits_{0}.png'.format(name)))

    print(name)
    print("Integrated gaussfit: ", gaussfit_total)
    centerx, centery = gaussfit_total[2:4]
    celwcs = scube.wcs.sub([wcs.WCSSUB_CELESTIAL])
    cx_w, cy_w = celwcs.wcs_pix2world([[centerx, centery]], 0)[0]
    center_coord = coordinates.SkyCoord(cx_w, cy_w, unit=('deg','deg'), frame='fk5')
#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)
F.scalebar.set_label("10 pc")
F.scalebar.set_font_size(18)
F.scalebar.set_font_weight('bold')
F.scalebar.set_color('w')
F.scalebar.set_linewidth(3)
F.save(paths.fpath('W51_wisecolor_modified_largescale_labeled_scalebar.pdf'), dpi=150)
F.scalebar.hide()

for L in list(F._layers.keys()):
    if L in F._layers:
    .format(cl_masses_flat[n_ostars == 12].mean(),
            cl_masses_flat[n_ostars == 12].std()))
print(
    "Implied stellar mass of e1e2IRS2 cluster, assuming 18 stars are O stars: {0} +/- {1} M_sun"
    .format(cl_masses_flat[n_ostars == 18].mean(),
            cl_masses_flat[n_ostars == 18].std()))

pl.figure(6).clf()
pl.semilogx(cl_masses_flat, luminosities, '.', alpha=0.5)
pl.axhline(np.log10(8.3e6), linewidth=10, alpha=0.1, zorder=-5)
pl.axhline(np.log10(2e7), linewidth=10, alpha=0.1, zorder=-5)
pl.xlim(10**2.5, (maxmass))
pl.ylim(5.5, 8.1)
pl.xlabel("Cluster mass ($M_\odot$)")
pl.ylabel("Cluster luminosity (log $L_\odot$)")
pl.savefig(paths.fpath("clusters/cluster_mass_vs_luminosity.png"))

pl.figure(9).clf()
pl.loglog(cl_masses_flat,
          n_ostars,
          '.',
          alpha=0.5,
          label='O-stars $(M>{0} M_\odot)$'.format(mmin_ostar))
pl.loglog(cl_masses_flat,
          n_obstars,
          '.',
          alpha=0.5,
          label='B-stars $(M>{0} M_\odot)$'.format(mmin_bstar))
pl.xlim(10**2.5, (maxmass))
pl.ylim(0, n_ostars.max())
pl.ylim(0, n_obstars.max())
示例#51
0
from astropy import log
import paths
from spectral_cube import SpectralCube, BooleanArrayMask
import matplotlib
matplotlib.rc_file(paths.pcpath('pubfiguresrc'))
from temperature_cubes import (tcube_dend, tcube_dend_smooth, tcube_direct,
                               tcubesm_direct)
from ratio_cubes import (ratiocube_303321, ratiocubesm_303321)
from masked_cubes import (cube303m, cube303msm, cube303, cube303sm)
from astropy import units as u
from image_registration.fft_tools import downsample

for ii in range(1,5):
    pl.close(ii)

if not os.path.isdir(paths.fpath('temvslon')):
    os.mkdir(paths.fpath('temvslon'))

figsize=(20,10)
vmin,vmax = -145.,135.
cbvmin,cbvmax = -80, 120
dv = 20.
vranges = np.arange(vmin, vmax, dv)
cm = pl.cm.rainbow_r

segmentdata = {'alpha': [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)],
               'blue': [(0.0, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)],
               'green': [(0.0, 0.0, 0.0), (0.5, 0.75, 0.75), (1.0, 0.0, 0.0)],
               'red': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]}
cm = matplotlib.colors.LinearSegmentedColormap(name='rgb',
                                               segmentdata=segmentdata)
    m1.hdu.writeto(m1fn, clobber=True)

    m2.quicklook()
    m2.hdu.writeto(m2fn, clobber=True)

    pmax.quicklook()
    pmax.hdu.writeto(maxfn, clobber=True)

    madstd.quicklook()
    madstd.hdu.writeto(madstdfn, clobber=True)

    #    argmax.quicklook()
    #    argmax.hdu.writeto(argmaxfn, clobber=True)

    try:
        m0.FITSFigure.save(fpath("moments/{0}_moment0.png".format(fname)))
        m1.FITSFigure.show_colorscale(cmap='viridis', vmin=45, vmax=68)
        m1.FITSFigure.show_contour(m0.hdu, levels=[4], colors=['k'])
        m1.FITSFigure.save(fpath("moments/{0}_moment1.png".format(fname)))
        m2.FITSFigure.show_colorscale(cmap='viridis', vmin=0, vmax=30)
        m2.FITSFigure.show_contour(m0.hdu, levels=[4], colors=['k'])
        m2.FITSFigure.save(fpath("moments/{0}_moment2.png".format(fname)))
        pmax.FITSFigure.show_colorscale(cmap='viridis')
        pmax.FITSFigure.show_contour(m0.hdu, levels=[4], colors=['k'])
        pmax.FITSFigure.save(fpath("moments/{0}_max.png".format(fname)))
        #        argmax.FITSFigure.show_colorscale(cmap='RdYlBu_r', vmin=45, vmax=68)
        #        argmax.FITSFigure.save(fpath("moments/{0}_argmax.png".format(fname)))

        for ra, dec, rad, name in ((290.93253, 14.508016, 0.00311407, 'e2e8'),
                                   (290.9118, 14.512366, 0.00311407,
                                    'southeast'), (290.9166, 14.518094,
示例#53
0
if __name__ == "__main__":
    import matplotlib
    matplotlib.rc_file(paths.pcpath('pubfiguresrc'))

    densities = np.logspace(3,7,20)
    tem = [tkin_all(n*u.cm**-3, 10*u.km/u.s, lengthscale=5*u.pc,
                    gradient=5*u.km/u.s/u.pc, tdust=25*u.K,
                    crir=1e-17*u.s**-1) for n in ProgressBar(densities)]
    pl.figure(1)
    pl.clf()
    pl.plot(densities, tem, 'k--', label='CRIR=1e-17, $\sigma=10$ km/s')
    pl.xlabel(r'$\log\,N_{\rm H}$')
    pl.ylabel('Temperature (K)')
    pl.xscale('log')
    pl.legend(loc='best')
    pl.savefig(paths.fpath("despotic/TvsN.png"))


    linewidths = np.arange(0.5,30,2)
    linewidths = np.logspace(np.log10(0.5), np.log10(30), 15)
    fiducial = tem2 = [tkin_all(1e4*u.cm**-3, sigma*u.km/u.s, lengthscale=5*u.pc,
                    gradient=5*u.km/u.s/u.pc, tdust=25*u.K,
                     tdust_rad=10*u.K,
                    crir=1e-17*u.s**-1) for sigma in ProgressBar(linewidths)]
    tem3 = [tkin_all(1e5*u.cm**-3, sigma*u.km/u.s, lengthscale=5*u.pc,
                    gradient=5*u.km/u.s/u.pc, tdust=25*u.K,
                     tdust_rad=10*u.K,
                    crir=1e-17*u.s**-1) for sigma in ProgressBar(linewidths)]
    tem4 = [tkin_all(1e5*u.cm**-3, sigma*u.km/u.s, lengthscale=5*u.pc,
                    gradient=5*u.km/u.s/u.pc, tdust=25*u.K,
                     tdust_rad=10*u.K,
示例#54
0
pl.clf()

ax = fig.gca()

ax.plot(
    data,
    ratio_to_temperature(data),
    alpha=0.5,
    linewidth=2,
    label='LTE',
)
ax.set_ylim(0, 150)
ax.set_xlabel("Ratio H$_2$CO $3_{2,1}-2_{2,0} / 3_{0,3}-2_{0,2}$")
ax.set_ylabel("Temperature (K)")

fig.savefig(paths.fpath('h2co_temperature_vs_ratio_lte.png'))

pm = paraH2COmodel()

densind = np.argmin(np.abs(pm.densityarr[0, :, 0] - 4.5))
colind = np.argmin(np.abs(pm.columnarr[0, :, 0] - 13.5))

ax.plot(
    pm.modelratio1[:, densind, colind],
    pm.temparr[:, densind, colind],
    'r',
    alpha=0.5,
    linewidth=2,
    label='$n=10^{4.5}$ cm$^{-3}$, $N=10^{13.5}$ cm$^{-2}$',
)
                            velocity=row['velocity']*u.km/u.s,
                           )

        spectra = pyspeckit.Spectra(speclist)
        spectra.xarr.convert_to_unit(u.GHz)
        mod = methanolmodel_osu.lte_model(spectra.xarr,
                                          row['velocity']*u.km/u.s, 5*u.km/u.s,
                                          300*u.K, 5e17*u.cm**-2)

        median = np.nanmedian(spectra.data)

        for ii in range(1,8):
            pl.subplot(7,1,ii)
            pl.plot(spectra.xarr, mod+median, color='r', linewidth=1, alpha=0.5)

        pl.savefig(paths.fpath(figname[:-4]+"_model.png"), dpi=300,
                   bbox_inches='tight', bbox_extra_artists=[])

    # Acetone lines (for identification purposes)
    from astroquery.splatalogue import Splatalogue
    Splatalogue.LINES_LIMIT=5000
    acetone_lines = Splatalogue.query_lines(218*u.GHz, 235*u.GHz,
                                            energy_max=800,
                                            energy_type='eu_k',
                                            chemical_name='Acetone')

    from generic_lte_molecule_model import LTEModel
    acetonemodel = LTEModel(chemical_name='Acetone')

    for row in myvtbl:
ax3 = fig2.add_subplot(212)

with contextlib.redirect_stderr(devnull):
    fit = powerlaw.Fit(core_phot_tbl['peak'])
# doesn't work at all fit.plot_pdf(color='k')
ax3.hist(core_phot_tbl['peak'],
         bins=np.logspace(-3, -0.5, 15),
         color='k',
         facecolor='none',
         histtype='step')
ax3.set_xscale('log')
fit.power_law.plot_pdf(color='r', linestyle='--')
ax3.set_ylim(0.3, 15)
ax3.set_xlabel("Peak flux density (Jy/beam)")
ax3.set_ylabel("Number of sources")
fig2.savefig(paths.fpath('coreplots/flux_powerlaw_histogram_fit.png'))

print("Flux Fit parameters: alpha={0}".format(fit.power_law.alpha))

fig2 = pl.figure(2)
fig2.clf()
ax2 = fig2.add_subplot(211)

print()
print("Core distribution: tem-corrected peak mass")
with contextlib.redirect_stderr(devnull):
    fit = powerlaw.Fit(cores_merge['T_corrected_peakmass'])
fit.plot_ccdf(color='k')
fit.power_law.plot_ccdf(color='r', linestyle='--')
ax2.set_ylabel("Fraction of sources")
    for species_tuple in species_list:
        species_name, chemid, tmax = species_tuple

        for ii in range(4):
            cat = Splatalogue.query_lines(
                spectra[ii].xarr.min(),
                spectra[ii].xarr.max(),
                chemical_name=chemid,
                energy_max=tmax,
                energy_type="eu_k",
                noHFS=True,
                line_lists=["SLAIM"],
            )
            spectra[ii].plotter(figure=pl.figure(1))
            spectra[ii].plotter.axis.set_ylim(snu_min[target], spectra[ii].plotter.axis.get_ylim()[1])
            spectra[ii].plotter.line_ids(
                cat["Resolved QNs"],
                cat["Freq-GHz"] * u.GHz,
                velocity_offset=velo[target],
                plot_kwargs=plot_kwargs,
                annotate_kwargs=annotate_kwargs,
            )
            spectra[ii].plotter.savefig(
                paths.fpath(
                    "line_id_spectra/{target}_{species_name}_{chemid}_spw{0}.png".format(
                        ii, target=target, chemid=chemid, species_name=species_name
                    )
                ),
                bbox_extra_artists=[],
            )
"""
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'))
    img = locals()[name].value
    hdu = fits.PrimaryHDU(data=img, header=h112h)
    pl.figure(ii)
    pl.clf()
    F = aplpy.FITSFigure(hdu, figure=pl.figure(ii))
    vmax = [vmaxes[k] for k in vmaxes if k in name][0]
    vmin = [vmins[k] for k in vmins if k in name][0]
    F.show_colorscale(vmin=vmin, vmax=vmax, cmap=cmap)
    F.recenter(49.235, -0.303, width=0.952, height=0.433)
    F.add_colorbar()
    F._ax1.set_title(titles[name])
    F.set_tick_labels_xformat("dd.d")
    F.set_tick_labels_yformat("dd.d")
    # F.set_tick_xspacing(0.3)
    figs.append(F)
    F.save(fpath("ratiomap_cont_%s.pdf" % name))
    F.save(fpath("ratiomap_cont_%s.png" % name))
    F.show_contour(
        he77a_name, convention="calabretta", levels=[0.0125, 0.025, 0.05, 0.1, 0.15, 0.2], colors="w", linewidth=0.5
    )
    F.save(fpath("ratiomap_cont_%s_HeContours.pdf" % name))

pl.figure(ii + 1)
pl.clf()
F = aplpy.FITSFigure(h77cname, figure=pl.figure(ii + 1), convention="calabretta")
F.show_grayscale(vmin=-0.1, vmid=-0.4, vmax=550, invert=True, stretch="log")
F.recenter(49.235, -0.303, width=0.952, height=0.433)
F.show_contour(hdu, levels=[0.3, 0.5, 0.7], colors=["b", (0.2, 1, 0.4, 0.8), "r"])
F.add_colorbar()

pl.figure(ii + 2)
示例#60
0
sp.specfit.Registry.add_fitter('h2co_simple', simple_fitter2, 6,
                               multisingle='multi')
sp.baseline(exclude=[151, 761, 916, 1265], selectregion=True,
            highlight_fitregion=True, xtype='pixel', subtract=True)

sp.error[:] = sp.data[761:916].std()

sp.plotter()
sp.specfit(fittype='h2co_simple',
           guesses=[0.06, 10, 20, 0.5, 0.7, 0.03],
           limited=[(True,True)] * 6,
           limits=[(0,20),[-150,150],(1, 60),(0,1),(0.3,1.1),(0,1e5)],
          )

sp.specfit.plot_fit(show_components=True)
sp.plotter.savefig(paths.fpath('simple/WholeCMZ_6parameter.pdf'),
                   bbox_inches='tight')

lat,lon = full_cubes.cube_merge_high.world[0,:,:][1:]
sgrb2_cloud_mask = ((lon-0.674*u.deg)**2 + (lat+0.027*u.deg)**2)**0.5 < 5*u.arcmin
spd_nob2 = full_cubes.cube_merge_high.with_mask(~sgrb2_cloud_mask).mean(axis=(1,2)).value

sp2 = pyspeckit.Spectrum(xarr=full_cubes.cube_merge_high.spectral_axis,
                         data=spd_nob2,
                         xarrkwargs={'velocity_convention': 'radio'},
                        )
sp2.xarr.refX = full_cubes.pcube_merge_high.xarr.refX
sp2.xarr.refX_unit = full_cubes.pcube_merge_high.xarr.refX_unit
sp2.xarr.convert_to_unit(u.GHz)
sp2.specname = 'Whole CMZ'
sp2.unit = 'K'