Пример #1
0
def part_8():

	object_list = ['ROXs12','ROXs42B','ROXs42B']
	filename_list = ['ROXs12','ROXs42Bb','ROXs42Bc']

	for i in range(len(filename_list)):
		outfile = open('position_'+filename_list[i]+'.dat','w')
		outfile.write('# '+'%25s'%'file name\t'\
							  +'%12s'%'x planet\t'\
							  +'%12s'%'y planet\t'\
							  +'%12s'%'position angle\t'\
							  +'%12s'%'projected separation (pixels)\n')


		if filename_list[i] == 'ROXs12': int_x,int_y = 562,685
		elif filename_list[i] == 'ROXs42Bb': int_x,int_y = 629,495
		elif filename_list[i] == 'ROXs42Bc': int_x,int_y = 546,465
		parts = ['','_CMsub','_ADIsub','_bPSFsub']
		for j in parts:

			filename = object_list[i]+j+'_aligned_median.fits'
			fit_radius = 16

			f = fits.open(filename)
			scidata = f[0].data

			x_data = scidata[int_y,int_x-fit_radius:int_x+fit_radius+1]
			x_data -= min(x_data)
			fit_x = np.linspace(-fit_radius,fit_radius,1+2*fit_radius)
			xfitParam, xfitCovar = curve_fit(gaussian_pdf,fit_x,x_data)
			
			y_data = scidata[int_y-fit_radius:int_y+fit_radius+1,int_x]
			y_data -= min(y_data)
			fit_y = np.linspace(-fit_radius,fit_radius,1+2*fit_radius)
			yfitParam, yfitCovar = curve_fit(gaussian_pdf,fit_y,y_data)

			thisPARANG   = f[0].header['PARANG']
			thisROTPPOSN = f[0].header['ROTPPOSN']
			thisEL       = f[0].header['EL']
			thisINSTANGL = f[0].header['INSTANGL']
			PA_yaxis     = thisPARANG +thisROTPPOSN -thisEL -thisINSTANGL

			PA_planet    = PA_yaxis -rad_to_deg(arctan2(float(xfitParam[0]+int_x-512),float(yfitParam[0]+int_y-512)))
			if PA_planet < 0: PA_planet += 360

			outfile.write('%25s'%str(object_list[i]+j+'_aligned_median.fits')+'\t'\
					+'%8s'%'%.3f'%(float(xfitParam[0]+int_x))+'\t'\
					+'%8s'%'%.3f'%(float(yfitParam[0]+int_y))+'\t'\
					+'%8s'%'%.3f'%(float(PA_planet))+'\t'\
					+'%8s'%'%.3f'%(float(sqrt((xfitParam[0]+int_x-512)**2+(yfitParam[0]+int_y-512)**2)))+'\n')

			tf = FITSFigure(filename)
			tf.show_colorscale(cmap='gray')
			tf.add_colorbar()
			tf.colorbar.show(location='top',box_orientation='horizontal')
			plt.savefig(object_list[i]+j+'_aligned_median.pdf',dpi=200)
			plt.close()

		outfile.close()
Пример #2
0
def test_colorbar_addremove():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.remove_colorbar()
    f.add_colorbar()
    f.close()
Пример #3
0
def test_colorbar_showhide():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.hide()
    f.colorbar.show()
    f.close()
Пример #4
0
def test_colorbar_addremove():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.remove_colorbar()
    f.add_colorbar()
    f.close()
Пример #5
0
def test_colorbar_showhide():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.hide()
    f.colorbar.show()
    f.close()
Пример #6
0
def test_colorbar_font():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_font(size='small', weight='bold', stretch='normal',
                        family='serif', style='normal', variant='normal')
    f.close()
Пример #7
0
def test_colorbar_pad():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_pad(0.1)
    f.colorbar.set_pad(0.2)
    f.colorbar.set_pad(0.5)
    f.close()
Пример #8
0
def test_colorbar_pad():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_pad(0.1)
    f.colorbar.set_pad(0.2)
    f.colorbar.set_pad(0.5)
    f.close()
Пример #9
0
def test_colorbar_location():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_location('top')
    f.colorbar.set_location('bottom')
    f.colorbar.set_location('left')
    f.colorbar.set_location('right')
    f.close()
Пример #10
0
def test_colorbar_location():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_location('top')
    f.colorbar.set_location('bottom')
    f.colorbar.set_location('left')
    f.colorbar.set_location('right')
    f.close()
Пример #11
0
def test_colorbar_font():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    f.show_grayscale()
    f.add_colorbar()
    f.colorbar.set_font(size='small',
                        weight='bold',
                        stretch='normal',
                        family='serif',
                        style='normal',
                        variant='normal')
    f.close()
Пример #12
0
def plot_exposure_image(filename):
    """Plot FOV image of exposure for one given energy slice"""
    from astropy.io import fits
    from aplpy import FITSFigure
    fig = FITSFigure(filename, dimensions=(0, 1), slices=[10], figsize=(5, 5))
    header = fits.getheader(filename)
    fig.show_grayscale()
    fig.add_colorbar()
    ra, dec = header['CRVAL1'], header['CRVAL2']
    
    # Bug: Marker doesn't show up at the center of the run
    # Bug: aplpy show_circles doesn't show a circle in degress.
    fig.show_markers(ra, dec)
    fig.show_circles(ra, dec, 1.)
    
    fig.tick_labels.set_xformat('dd')
    fig.tick_labels.set_yformat('dd')
    fig.ticks.set_xspacing(1)
    fig.ticks.set_yspacing(1)
    fig.colorbar.set_axis_label_text('Effective Area (cm^2)')
    
    fig.save('exposure_image.png')
Пример #13
0
def plot_exposure_image(filename):
    """Plot FOV image of exposure for one given energy slice"""
    from astropy.io import fits
    from aplpy import FITSFigure
    fig = FITSFigure(filename, dimensions=(0, 1), slices=[10], figsize=(5, 5))
    header = fits.getheader(filename)
    fig.show_grayscale()
    fig.add_colorbar()
    ra, dec = header['CRVAL1'], header['CRVAL2']

    # Bug: Marker doesn't show up at the center of the run
    # Bug: aplpy show_circles doesn't show a circle in degress.
    fig.show_markers(ra, dec)
    fig.show_circles(ra, dec, 1.)

    fig.tick_labels.set_xformat('dd')
    fig.tick_labels.set_yformat('dd')
    fig.ticks.set_xspacing(1)
    fig.ticks.set_yspacing(1)
    fig.colorbar.set_axis_label_text('Effective Area (cm^2)')

    fig.save('exposure_image.png')
Пример #14
0
def test_colorbar_invalid():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    with pytest.raises(Exception):
        f.add_colorbar()  # no grayscale/colorscale was shown
Пример #15
0
model, gtmodel, ratio, counts, header = prepare_images()

# Plotting
fig = plt.figure(figsize=(15, 5))

image1 = fits.ImageHDU(data=model, header=header)
f1 = FITSFigure(image1, figure=fig, subplot=(1, 3, 1), convention='wells')
f1.show_colorscale(vmin=0, vmax=0.3, cmap='afmhot')
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('dd')

image2 = fits.ImageHDU(data=gtmodel, header=header)
f2 = FITSFigure(image2, figure=fig, subplot=(1, 3, 2), convention='wells')
f2.show_colorscale(vmin=0, vmax=0.3, cmap='afmhot')
f2.tick_labels.set_xformat('ddd')
f2.tick_labels.set_yformat('dd')

image3 = fits.ImageHDU(data=ratio, header=header)
f3 = FITSFigure(image3, figure=fig, subplot=(1, 3, 3), convention='wells')
f3.show_colorscale(vmin=0.9, vmax=1.1, cmap='RdBu')
f3.tick_labels.set_xformat('ddd')
f3.tick_labels.set_yformat('dd')
f3.add_colorbar(ticks=[0.9, 0.95, 1, 1.05, 1.1])

fig.text(0.12, 0.95, "Gammapy Background")
fig.text(0.45, 0.95, "Fermi Tools Background")
fig.text(0.75, 0.95, "Ratio: Gammapy/Fermi Tools")
plt.tight_layout()
plt.show()
Пример #16
0
def test_colorbar_invalid():
    data = np.zeros((16, 16))
    f = FITSFigure(data)
    with pytest.raises(Exception):
        f.add_colorbar()  # no grayscale/colorscale was shown
Пример #17
0
"""Produces an image from 1FHL catalog point sources.
"""
import numpy as np
import matplotlib.pyplot as plt
from aplpy import FITSFigure
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import catalog_image, SkyImage
from gammapy.irf import EnergyDependentTablePSF

# Create image of defined size
reference = SkyImage.empty(nxpix=300, nypix=100, binsz=1).to_image_hdu()
psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# Create image
image = catalog_image(reference, psf, catalog='1FHL', source_type='point',
                      total_flux='True')

# Plot
fig = FITSFigure(image.to_fits()[0], figsize=(15, 5))
fig.show_colorscale(interpolation='bicubic', cmap='afmhot', stretch='log', vmin=1E-12, vmax=1E-8)
fig.tick_labels.set_xformat('ddd')
fig.tick_labels.set_yformat('dd')
ticks = np.logspace(-12, -8, 5)
fig.add_colorbar(ticks=ticks, axis_label_text='Flux (ph s^-1 cm^-2 TeV^-1)')
fig.colorbar._colorbar_axes.set_yticklabels(['{:.0e}'.format(_) for _ in ticks])
plt.tight_layout()
plt.show()
Пример #18
0
def make_polmap(filename, title=None, figure=None, subplot=(1, 1, 1)):
    hawc = fits.open(filename)
    p = hawc['DEBIASED PERCENT POL']  # %
    theta = hawc['ROTATED POL ANGLE']  # deg
    stokes_i = hawc['STOKES I']  # I
    error_i = hawc['ERROR I']  # error I

    # 1. plot Stokes I
    #  convert from Jy/pix to Jy/sq. arcsec
    pxscale = stokes_i.header['CDELT2'] * 3600  # map scale in arcsec/pix
    stokes_i.data /= pxscale**2
    error_i.data /= pxscale**2

    fig = FITSFigure(stokes_i, figure=figure, subplot=subplot)

    # 2. perform S/N cut on I/\sigma_I
    err_lim = 100
    mask = np.where(stokes_i.data / error_i.data < err_lim)

    # 3. mask out low S/N vectors by setting masked indices to NaN
    p.data[mask] = np.nan

    # 4. plot vectors
    scalevec = 0.4  # 1pix = scalevec * 1% pol          # scale vectors to make it easier to see
    fig.show_vectors(p, theta, scale=scalevec,
                     step=2)  # step size = display every 'step' vectors
    #   step size of 2 is effectively Nyquist sampling
    #   --close to the beam size

    # 5. plot contours
    ncontours = 30
    fig.show_contour(stokes_i,
                     cmap=cmap,
                     levels=ncontours,
                     filled=True,
                     smooth=1,
                     kernel='box')
    fig.show_contour(stokes_i,
                     colors='gray',
                     levels=ncontours,
                     smooth=1,
                     kernel='box',
                     linewidths=0.3)

    # Show image
    fig.show_colorscale(cmap=cmap)

    # If title, set it
    if title:
        fig.set_title(title)

    # Add colorbar
    fig.add_colorbar()
    fig.colorbar.set_axis_label_text('Flux (Jy/arcsec$^2$)')

    # Add beam indicator
    fig.add_beam(facecolor='red',
                 edgecolor='black',
                 linewidth=2,
                 pad=1,
                 corner='bottom left')
    fig.add_label(0.02,
                  0.02,
                  'Beam FWHM',
                  horizontalalignment='left',
                  weight='bold',
                  relative=True,
                  size='small')

    # Add vector scale
    #   polarization vectors are displayed such that 'scalevec' * 1% pol is 1 pix long
    #   must translate pixel size to angular degrees since the 'add_scalebar' function assumes a physical scale
    vectscale = scalevec * pxscale / 3600
    fig.add_scalebar(5 * vectscale, "p = 5%", corner='top right', frame=True)

    return stokes_i, p, mask, fig
Пример #19
0
from gammapy.image import catalog_image, SkyImage
from gammapy.irf import EnergyDependentTablePSF

# Create image of defined size
reference = SkyImage.empty(nxpix=300, nypix=100, binsz=1).to_image_hdu()
psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# Create image
image = catalog_image(reference,
                      psf,
                      catalog='1FHL',
                      source_type='point',
                      total_flux='True')

# Plot
fig = FITSFigure(image.to_fits(format='fermi-background')[0], figsize=(15, 5))
fig.show_colorscale(interpolation='bicubic',
                    cmap='afmhot',
                    stretch='log',
                    vmin=1E-12,
                    vmax=1E-8)
fig.tick_labels.set_xformat('ddd')
fig.tick_labels.set_yformat('dd')
ticks = np.logspace(-12, -8, 5)
fig.add_colorbar(ticks=ticks, axis_label_text='Flux (cm^-2 s^-1 TeV^-1)')
fig.colorbar._colorbar_axes.set_yticklabels(
    ['{:.0e}'.format(_) for _ in ticks])
plt.tight_layout()
plt.show()
Пример #20
0
stkI.data *= 1000.
stkIerr.data *= 1000.

#central coordinates
RA = (stkI.header['OBSRA'] * u.hourangle).to(u.deg)
DEC = stkI.header['OBSDEC'] * u.deg

###Figure
gc = FITSFigure(stkI, figure=fig)
#gc = FITSFigure(stkI,figure=fig)

##STOKES I
#colorscale
gc.show_colorscale(cmap=cmap, vmin=vmin, vmax=vmax, smooth=1, kernel='gauss')
#colorbae
gc.add_colorbar()
gc.colorbar.set_axis_label_text('I (mJy/sqarcsec)')
gc.colorbar.set_axis_label_font(size=label_colorbar)
gc.colorbar.set_font(size=tick_colorbar)
#recenter
gc.recenter(RA, DEC, width=width / 3600, height=height / 3600)
#contours
sigmaI = np.nanstd(stkIerr.data)
levelsI = sigmaI * 1.8**(np.arange(2, 12, 0.5))
#levelsI = np.arange(3,155,3)*sigmaI
gc.show_contour(colors='black',levels=levelsI,linewidth=0.1,\
    filled=False,smooth=1,kernel='box',alpha=0.4)
#gc.show_contour(levels=levelsI,\
#				filled=True,smooth=1,kernel='box',cmap='viridis')
#beam
gc.add_beam(color='red')
fermi_significance = np.nan_to_num(significance(correlated_counts, correlated_gtmodel, method="lima"))
# Gammapy significance
significance = np.nan_to_num(significance(correlated_counts, correlated_model, method="lima"))

titles = ["Gammapy Significance", "Fermi Tools Significance"]

# Plot

fig = plt.figure(figsize=(10, 5))
hdu1 = fits.ImageHDU(significance, header)
f1 = FITSFigure(hdu1, figure=fig, convention="wells", subplot=(1, 2, 1))
f1.set_tick_labels_font(size="x-small")
f1.tick_labels.set_xformat("ddd")
f1.tick_labels.set_yformat("ddd")
f1.show_colorscale(vmin=0, vmax=20, cmap="afmhot", stretch="sqrt")
f1.add_colorbar(axis_label_text="Significance")
f1.colorbar.set_width(0.1)
f1.colorbar.set_location("right")

hdu2 = fits.ImageHDU(fermi_significance, header)
f2 = FITSFigure(hdu2, figure=fig, convention="wells", subplot=(1, 2, 2))
f2.set_tick_labels_font(size="x-small")
f2.tick_labels.set_xformat("ddd")
f2.hide_ytick_labels()
f2.hide_yaxis_label()
f2.show_colorscale(vmin=0, vmax=20, cmap="afmhot", stretch="sqrt")
f2.add_colorbar(axis_label_text="Significance")
f2.colorbar.set_width(0.1)
f2.colorbar.set_location("right")
fig.text(0.15, 0.92, "Gammapy Significance")
fig.text(0.63, 0.92, "Fermi Tools Significance")
Пример #22
0
stokes_i = hawc['STOKES I']               # or hawc[0]. Note the extension is from the hawc.info() table above

fig = plt.figure(figsize=(7,7))
pxscale = stokes_i.header['CDELT2']*3600  # map scale in arcsec/pix
disp_i = stokes_i.copy()
disp_i.data /= pxscale**2
axs = FITSFigure(disp_i, figure=fig)    # load HDU into aplpy figure
axs.show_colorscale(cmap=cmap)            # display the data with WCS projection and chosen colormap

# FORMATTING
axs.set_tick_labels_font(size='small')
axs.set_axis_labels_font(size='small')

# Add colorbar
axs.add_colorbar()
axs.colorbar.set_axis_label_text('Flux (Jy/arcsec$^2$)')

plt.savefig('figs/Stokes_I.pdf',dpi=300)
plt.savefig('figs/Stokes_I.png',dpi=300)

# ### Stokes Q and U
# Similarly, we can plot the Stokes Q and Stokes U images:

# In[3]:


stokes_q = hawc['STOKES Q']
stokes_u = hawc['STOKES U']

fig = plt.figure(figsize=(12.8,9.6))
Пример #23
0
model, gtmodel, ratio, counts, header = prepare_images()

# Plotting
fig = plt.figure(figsize=(15, 5))

image1 = fits.ImageHDU(data=model, header=header)
f1 = FITSFigure(image1, figure=fig, subplot=(1, 3, 1), convention='wells')
f1.show_colorscale(vmin=0, vmax=0.3, cmap='afmhot')
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('dd')

image2 = fits.ImageHDU(data=gtmodel, header=header)
f2 = FITSFigure(image2, figure=fig, subplot=(1, 3, 2), convention='wells')
f2.show_colorscale(vmin=0, vmax=0.3, cmap='afmhot')
f2.tick_labels.set_xformat('ddd')
f2.tick_labels.set_yformat('dd')

image3 = fits.ImageHDU(data=ratio, header=header)
f3 = FITSFigure(image3, figure=fig, subplot=(1, 3, 3), convention='wells')
f3.show_colorscale(vmin=0.95, vmax=1.05, cmap='RdBu')
f3.tick_labels.set_xformat('ddd')
f3.tick_labels.set_yformat('dd')
f3.add_colorbar(ticks=[0.95, 0.975, 1, 1.025, 1.05])

fig.text(0.12, 0.95, "Gammapy Background")
fig.text(0.45, 0.95, "Fermi Tools Background")
fig.text(0.75, 0.95, "Ratio: Gammapy/Fermi Tools")
plt.tight_layout()
plt.show()
Пример #24
0
    n_sources=n_sources, rad_dis=rad_dis, vel_dis=vel_dis, max_age=1e6, spiralarms=spiralarms, random_state=0
)

# Minimum source luminosity (ph s^-1)
luminosity_min = 4e34
# Maximum source luminosity (ph s^-1)
luminosity_max = 4e37
# Luminosity function differential power-law index
luminosity_index = 1.5

# Assigns luminosities to sources
luminosity = sample_powerlaw(luminosity_min, luminosity_max, luminosity_index, n_sources, random_state=0)
table["luminosity"] = luminosity

# Adds parameters to table: distance, glon, glat, flux, angular_extension
table = population.add_observed_parameters(table)
table.meta["Energy Bins"] = np.array([10, 500]) * u.GeV
# Create image
image = catalog_image(reference, psf, catalog="simulation", source_type="point", total_flux=True, sim_table=table)

# Plot
fig = FITSFigure(image.to_fits(format="fermi-background")[0], figsize=(15, 5))
fig.show_colorscale(interpolation="bicubic", cmap="afmhot", stretch="log", vmin=1e30, vmax=1e35)
fig.tick_labels.set_xformat("ddd")
fig.tick_labels.set_yformat("dd")
ticks = np.logspace(30, 35, 6)
fig.add_colorbar(ticks=ticks, axis_label_text="Flux (ph s^-1)")
fig.colorbar._colorbar_axes.set_yticklabels(["{:.0e}".format(_) for _ in ticks])
plt.tight_layout()
plt.show()
Пример #25
0
"""Produces an image from 1FHL catalog point sources.
"""
from aplpy import FITSFigure
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import make_empty_image, catalog_image
from gammapy.irf import EnergyDependentTablePSF

# Create image of defined size
reference = make_empty_image(nxpix=300, nypix=100, binsz=1)
psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# Create image
image = catalog_image(reference, psf, catalog='1FHL', source_type='point',
                      total_flux='True')

# Plot
fig = FITSFigure(image.to_fits()[0])
fig.show_grayscale(stretch='linear', interpolation='none')
fig.add_colorbar()
Пример #26
0
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('ddd')
f1.axis_labels.hide_x()
f1.show_colorscale(vmin=0, vmax=0.3)

hdu2 = fits.ImageHDU(gtmodel, header)
f2 = FITSFigure(hdu2,
                figure=fig,
                convention='wells',
                subplot=[0.38, 0.25, 0.2, 0.26])
f2.tick_labels.set_font(size='x-small')
f2.tick_labels.set_xformat('ddd')
f2.tick_labels.hide_y()
f2.axis_labels.hide_y()
f2.show_colorscale(vmin=0, vmax=0.3)
f2.add_colorbar()
f2.colorbar.set_width(0.1)
f2.colorbar.set_location('right')

hdu3 = fits.ImageHDU(ratio, header)
f3 = FITSFigure(hdu3,
                figure=fig,
                convention='wells',
                subplot=[0.67, 0.25, 0.2, 0.26])
f3.tick_labels.set_font(size='x-small')
f3.tick_labels.set_xformat('ddd')
f3.tick_labels.hide_y()
f3.axis_labels.hide()
f3.show_colorscale(vmin=0.9, vmax=1.1)
f3.add_colorbar()
f3.colorbar.set_width(0.1)
Пример #27
0
                             n_sources,
                             random_state=0)
table['luminosity'] = luminosity

# Adds parameters to table: distance, glon, glat, flux, angular_extension
table = population.add_observed_parameters(table)
table.meta['Energy Bins'] = np.array([10, 500]) * u.GeV
# Create image
image = catalog_image(reference,
                      psf,
                      catalog='simulation',
                      source_type='point',
                      total_flux=True,
                      sim_table=table)

# Plot
fig = FITSFigure(image.to_fits()[0], figsize=(15, 5))
fig.show_colorscale(interpolation='bicubic',
                    cmap='afmhot',
                    stretch='log',
                    vmin=1E30,
                    vmax=1E35)
fig.tick_labels.set_xformat('ddd')
fig.tick_labels.set_yformat('dd')
ticks = np.logspace(30, 35, 6)
fig.add_colorbar(ticks=ticks, axis_label_text='Flux (ph s^-1)')
fig.colorbar._colorbar_axes.set_yticklabels(
    ['{:.0e}'.format(_) for _ in ticks])
plt.tight_layout()
plt.show()
Пример #28
0
def calc_physics(ra=None,
                 dec=None,
                 r=0.17 * u.pc,
                 dr=0.05 * u.pc,
                 vexp=4 * u.km / u.s,
                 v0=14 * u.km / u.s,
                 cube_12co=None,
                 cube_13co=None,
                 dist=414 * u.pc,
                 snr_cutoff=5.,
                 shell_snr_cutoff=3.,
                 shell=True,
                 plot=False,
                 linewidth_mode='fwhm',
                 average_Tex=True):
    """
    shell_snr_cutoff is the sigma cutoff for extracting the shell
    voxels.
    """
    #print(cube_12co.header['CDELT3'])
    from spectral_cube.lower_dimensional_structures import Projection

    pix_size = (cube_12co.header['CDELT2'] * u.deg).to(u.arcsec)
    vstep = (cube_12co.header['CDELT3'] * (u.m / u.s)).to(u.km / u.s)

    if shell:
        model_pars = {
            'dist': dist,  # pc
            'pix_size': pix_size,  # arcsec
            'vstep': vstep,  # km/s
            'acen': ra.to(u.deg),  # deg
            'dcen': dec.to(u.deg),  # deg
            'thickness': 0.0,  # pc
            'fwhm': 0.0,  # km/s
            'beta': 0.0,  # spectral index
            'R': r,  # pc
            'dr': dr,  # pc
            'vexp': vexp,  # km/s
            'depth_offset': 0.0,  # pc
            'vel_offset': 0.0,  # km/s
            'v0': v0,  # km/s
            'ignore_cloud': 1,  #Ignore cloud.
            'method': 'sample',
            'write_fits': False,
            'samples_per_voxel': 27
        }

        #Extract 12co shell voxels using model.
        model_cube = SpectralCube.read(shell_model.ppv_model(**model_pars))
        #shell_masked, shell_mask = extract_shell(
        #    cube_file=cube_12co, model_pars=model_pars, return_mask=True)
        #Extract subcubes with same ra/dec range as shell voxel cube, but
        #full velocity range.
        subcube_shell_12co = cube_12co.subcube(model_cube.longitude_extrema[1],
                                               model_cube.longitude_extrema[0],
                                               model_cube.latitude_extrema[0],
                                               model_cube.latitude_extrema[1])
        subcube_shell_13co = cube_13co.subcube(model_cube.longitude_extrema[1],
                                               model_cube.longitude_extrema[0],
                                               model_cube.latitude_extrema[0],
                                               model_cube.latitude_extrema[1])
        #print(subcube_shell_12co, subcube_shell_13co, model_cube)
        if plot:
            plt.figure()
            plt.subplot(131)
            plt.imshow(subcube_shell_12co.moment0().data)
            plt.subplot(132)
            plt.imshow(subcube_shell_13co.moment0().data)
            plt.subplot(133)
            plt.imshow(model_cube.moment0().data)
            plt.show()
    else:
        subcube_shell_12co = cube_12co
        subcube_shell_13co = cube_13co

    rms_12co = rms_map(cube=subcube_shell_12co)
    rms_13co = rms_map(cube=subcube_shell_13co)

    ###
    ### Use 13co if 3sigma detected, otherwise use corrected 12co if 3sigma detected.
    mask_use_13co = (subcube_shell_13co >= shell_snr_cutoff * rms_13co)
    mask_use_12co = (~mask_use_13co) & (subcube_shell_12co >=
                                        shell_snr_cutoff * rms_12co)

    ### Excitation Temperature
    Tex = cube_Tex(subcube_shell_12co,
                   average_first=True,
                   plot=False,
                   average=average_Tex)
    print("Tex is {}".format(Tex))
    ### Correct 12co for opacity.
    subcube_shell_12co_correct = opacity_correct(subcube_shell_12co,
                                                 cube_thin=subcube_shell_13co,
                                                 snr_cutoff=snr_cutoff,
                                                 plot_ratio='ratio.png')
    #print(subcube_shell_12co_correct)

    subcube_shell_12co_correct = subcube_shell_12co_correct.with_mask(
        mask_use_12co)
    subcube_shell_13co = subcube_shell_13co.with_mask(mask_use_13co)

    # if plot:
    #     plt.figure()
    #     plt.subplot(121)
    #     plt.imshow(subcube_shell_12co_correct.moment0().data)
    #     plt.subplot(122)
    #     plt.imshow(subcube_shell_13co.moment0().data)
    #     plt.show()

    if shell:
        ### Extract shell voxels from opacity-corrected 12co
        shell_12co_correct = extract_shell(subcube_shell_12co_correct,
                                           keep_latlon=True,
                                           model_cube=model_cube)
        shell_13co = extract_shell(subcube_shell_13co,
                                   keep_latlon=True,
                                   model_cube=model_cube)
    else:
        shell_12co_correct = subcube_shell_12co_correct
        shell_13co = subcube_shell_13co

    # if plot:
    #     plt.figure()
    #     plt.subplot(121)
    #     plt.imshow(shell_12co_correct.moment0().data)
    #     plt.subplot(122)
    #     plt.imshow(shell_13co.moment0().data)
    #     plt.show()
    ###
    ### Use 13co if 3sigma detected, otherwise use corrected 12co if 3sigma detected.
    # mask_use_13co = (shell_13co >= shell_snr_cutoff * rms_13co)
    # mask_use_12co = (~mask_use_13co) & (subcube_shell_12co >= shell_snr_cutoff * rms_12co)

    ### Calculate column density of H2 from 13co where 13co is 3sig,
    ### otherwise use opacity-corrected 12co.

    shell_nH2_12co = column_density_H2(shell_12co_correct,
                                       Tex=Tex,
                                       molecule="12co")
    shell_nH2_13co = column_density_H2(shell_13co, Tex=Tex, molecule="13co")

    #print(shell_nH2_12co.shape, shell_nH2_13co.shape)
    print(np.nansum([shell_nH2_12co, shell_nH2_13co], axis=0),
          shell_nH2_12co.unit)
    shell_nH2 = Projection(np.nansum([shell_nH2_12co, shell_nH2_13co], axis=0),
                           header=shell_nH2_12co.header,
                           wcs=shell_nH2_12co.wcs,
                           unit=shell_nH2_12co.unit,
                           dtype=shell_nH2_12co.dtype,
                           meta=shell_nH2_12co.meta,
                           mask=shell_nH2_12co.mask)

    #print(shell_nH2.shape)

    # if plot:
    #     plt.figure()
    #     plt.subplot(131)
    #     plt.title("H2 from 12co")
    #     plt.imshow(shell_nH2_12co.data)
    #     plt.subplot(132)
    #     plt.title("H2 from 13co")
    #     plt.imshow(shell_nH2_13co.data)
    #     plt.subplot(133)
    #     plt.title("Total H2")
    #     plt.imshow(shell_nH2)

    ### Calculate Mass, Momentum, and Energy of Shell!
    if shell:
        shell_mass = mass(shell_nH2,
                          distance=414 * u.pc,
                          molecule='H2',
                          mass_unit=u.Msun)
        shell_momentum = momentum(shell_mass, vexp)
        shell_energy = energy(shell_mass, vexp)
        shell_luminosity = (shell_energy / (r / vexp)).to(u.erg / u.s)
    else:

        mass_map = mass(shell_nH2,
                        distance=414 * u.pc,
                        molecule='H2',
                        mass_unit=u.Msun,
                        return_map=True)
        if linewidth_mode == "fwhm":
            vel_map = subcube_shell_13co.linewidth_fwhm()
        elif linewidth_mode == "sigma":
            vel_map = subcube_shell_13co.linewidth_sigma()
        elif linewidth_mode == "sigma3D":
            vel_map = 3.**0.5 * subcube_shell_13co.linewidth_sigma()

        # plt.figure()
        # plt.imshow(vel_map)
        # plt.show()
        #vel_average = np.nanmean(vel_map.value)
        shell_mass = u.Quantity(np.nansum(mass_map))
        shell_momentum = u.Quantity(np.nansum(mass_map * vel_map))
        #shell_momentum = vel
        shell_energy = 0.5 * u.Quantity(np.nansum(
            mass_map * vel_map * vel_map))
        #shell_energy = 0.5 * shell_mass
        #print(u.Quantity(0.5*shell_mass*u.Quantity(np.nanmean(vel_map))**2.).to(u.erg))
        if plot:
            from aplpy import FITSFigure
            from astropy.io import fits
            hdu = shell_nH2.hdu
            hdu.data = np.log10(shell_nH2.data)
            fig = FITSFigure(hdu.data)
            fig.show_colorscale(vmin=21.5, vmax=23.65, interpolation='none')
            fig.add_colorbar()
            # plt.imshow(np.log10(shell_nH2.value), interpolation='none',
            #     vmin=21.5, vmax=23.648)
            # plt.colorbar()
            # plt.title("log(n(H2) [cm^-2])")

            #plt.show()
            plt.savefig("../subregions/berneregion_lognH2.png")

            hdu = fits.open("../berne_Nh_2.fits")[0]
            hdu.data = np.log10(hdu.data)
            fig = FITSFigure(hdu.data)
            fig.show_colorscale(vmin=21.5, vmax=23.65, interpolation='none')
            fig.add_colorbar()

            #plt.show()
            plt.savefig("../subregions/berne_lognH2.png")

            # plt.figure()
            # plt.imshow(vel_map.to(u.km/u.s).value, interpolation='none')
            # #energy_map = (0.5*mass_map*vel_map*vel_map).to(u.erg).value
            # vels = vel_map.to(u.km/u.s).value.flatten()
            # plt.figure()
            # plt.hist(vels[vels>0], normed=True, log=True, bins=40)
            # plt.xlabel("Velocity FWHM (km/s)")
            # plt.ylabel("PDF")
            # plt.title('Velocity FWHM PDF')
            # plt.show()
        # plt.figure()
        # plt.imshow(vel_map.data)
        # plt.colorbar()
        # plt.show()

    return shell_mass, shell_momentum, shell_energy
Пример #29
0
hdu1 = fits.ImageHDU(model, header)
f1 = FITSFigure(hdu1, figure=fig, convention='wells', subplot=[0.18, 0.264, 0.18, 0.234])
f1.tick_labels.set_font(size='x-small')
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('ddd')
f1.axis_labels.hide_x()
f1.show_colorscale(vmin=0, vmax=0.3)

hdu2 = fits.ImageHDU(gtmodel, header)
f2 = FITSFigure(hdu2, figure=fig, convention='wells', subplot=[0.38, 0.25, 0.2, 0.26])
f2.tick_labels.set_font(size='x-small')
f2.tick_labels.set_xformat('ddd')
f2.tick_labels.hide_y()
f2.axis_labels.hide_y()
f2.show_colorscale(vmin=0, vmax=0.3)
f2.add_colorbar()
f2.colorbar.set_width(0.1)
f2.colorbar.set_location('right')

hdu3 = fits.ImageHDU(ratio, header)
f3 = FITSFigure(hdu3, figure=fig, convention='wells', subplot=[0.67, 0.25, 0.2, 0.26])
f3.tick_labels.set_font(size='x-small')
f3.tick_labels.set_xformat('ddd')
f3.tick_labels.hide_y()
f3.axis_labels.hide()
f3.show_colorscale(vmin=0.9, vmax=1.1)
f3.add_colorbar()
f3.colorbar.set_width(0.1)
f3.colorbar.set_location('right')

fig.text(0.19, 0.53, "Gammapy Background", color='black', size='9')
Пример #30
0
    def Bmap(self,
             idi=50.0,
             pdp=3.0,
             pmax=30.0,
             color='rainbow',
             scalevec=1.0,
             clevels=100,
             imin=0.0,
             imax=None,
             size_x=9.0,
             size_y=9.0,
             dpi=100.0):
        # Initialization
        # idi : Signal-to-noise ratio for Stokes I total intensity. Default is
        #       idi = 50.0, which leads to an upper limit of at least dP = 5.0%
        #       for the error on the polarization fraction P.
        # pdp : Signal-to-noise ratio for the de-biased polarization fraction P.
        #       Default is pdp = 3.0, which is the commonly accepted detection
        #       threshold in the litterature.
        # pmax : Maximum polarization fraction allowed.
        # color : Color scheme used for the plots. Default is rainbow.
        # scalevec : Length of the vectors plotted on the map.
        # clevels : Number of contours plotted on the contour plot.
        # imin : Minimum value plotted in the Stokes I intensity map.
        #        Default is 0.0.
        # imax : Maximum value plotted in the Stokes I intensity map.
        #        If no value is provided, maximum is automatically detected.

        print()
        print('=====================================')
        print('Plotting a lovable magnetic field map')
        print('=====================================')
        print()

        # Creating a new fits object for APLpy's FITSFigure method to recognize
        # for the Stokes I total intensity
        plot_hdu = fits.PrimaryHDU(data=self.I, header=self.header)
        # Loading the data in an APLpy figure
        Bmap = FITSFigure(plot_hdu,
                          dpi=dpi,
                          figsize=(size_x, size_y),
                          slices=[0, 1])

        print('Plotting the Stokes I total intensity map')
        print()

        # Showing the pixelated image and setting the aspect ratio
        Bmap.show_colorscale(cmap=color, vmin=imin, vmax=imax)
        # Plotting a filled contour plot of the data
        Bmap.show_contour(cmap=color,
                          levels=clevels,
                          filled=True,
                          extend='both',
                          vmin=imin,
                          vmax=imax)
        # Inverting ticks
        #Bmap.ticks.set_tick_direction('in') # Not working in APLpy

        # Adding a colorbar to the plot
        Bmap.add_colorbar(pad=0.125)
        # Adding the units to the colorbar
        Bmap.colorbar.set_axis_label_text(self.units)
        # Moving the colorbar to be on top of the figure
        Bmap.colorbar.set_location('top')

        # Creating a new fits object for APLpy's FITSFigure method to recognize
        # for the polarization fraction P
        pref = fits.PrimaryHDU(data=self.P, header=self.header)
        pmap = pref.copy()
        # for the magnetic field angle B
        oref = fits.PrimaryHDU(data=self.B, header=self.header)
        omap = oref.copy()
        # A copy of the HDU is created before any masking is done.
        # This fixes an issue where modifying pmap was carried to other
        # instances of this method. Future fix should make sure pref is
        # closed/deleted at the end of this method.

        # Muting the numpy alerts triggered by nan values
        np.warnings.filterwarnings('ignore')

        print()
        print('Applying happy selection criteria on polarization vectors')
        print()

        # Creating a mask to hide polarization vectors with low signal-to-noise ratios
        imask_01 = np.where(
            self.I / self.dI < idi)  # Total intensity SNR threshold
        imask_02 = np.where(self.I < 0)  # Total intensity positive threshold
        pmask = np.where(self.P / self.dP < pdp)  # Polarization SNR threshold
        pmaxmask = np.where(self.P > pmax)  # Polarization SNR threshold
        # Forcing the polarization vectors to share the same amplitude
        pmap.data[np.where(self.P > 0.0)] = 1.0
        # Masking all the indices for which the selection criteria failed
        pmap.data[imask_01] = np.nan
        pmap.data[imask_02] = np.nan
        pmap.data[pmask] = np.nan
        pmap.data[pmaxmask] = np.nan

        print('Plotting the magnetic field segments')
        print()

        # Plotting the polarization vectors
        Bmap.show_vectors(pmap, omap, scale=scalevec)

        # Adding the beam size
        Bmap.add_beam(facecolor='white',
                      edgecolor='black',
                      linewidth=2,
                      pad=1,
                      corner='bottom left')

        # Removing the pixelated structure under the figure
        Bmap.hide_colorscale(
        )  # Warning: You need to reopen it to create a new
        # colorbar, APLpy deals poorly with
        # contour maps by themselves

        print('Returning the APLpy figure as output, please feel free to' +
              ' improve it (see online APLpy.FITSFigure documentation)')
        print()
        print('Don\'t forget to save the results using the' +
              ' .savefig(\'name.png\') function')
        print()
        print('Have fun!')

        return Bmap
Пример #31
0
# Gammapy significance
significance = np.nan_to_num(significance(correlated_counts, correlated_model,
                                          method='lima'))

titles = ['Gammapy Significance', 'Fermi Tools Significance']

# Plot

fig = plt.figure(figsize=(10, 5))
hdu1 = fits.ImageHDU(significance, header)
f1 = FITSFigure(hdu1, figure=fig, convention='wells', subplot=(1,2,1))
f1.set_tick_labels_font(size='x-small')
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('ddd')
f1.show_colorscale(vmin=0, vmax=10, cmap='afmhot')
f1.add_colorbar(axis_label_text='Significance')
f1.colorbar.set_width(0.1)
f1.colorbar.set_location('right')


hdu2 = fits.ImageHDU(fermi_significance, header)
f2 = FITSFigure(hdu2, figure=fig, convention='wells', subplot=(1,2,2))
f2.set_tick_labels_font(size='x-small')
f2.tick_labels.set_xformat('ddd')
f2.hide_ytick_labels()
f2.hide_yaxis_label()
f2.show_colorscale(vmin=0, vmax=10, cmap='afmhot')
f2.add_colorbar(axis_label_text='Significance')
f2.colorbar.set_width(0.1)
f2.colorbar.set_location('right')
fig.text(0.15, 0.92,"Gammapy Significance")
Пример #32
0
"""Produces an image from 1FHL catalog point sources.
"""
from aplpy import FITSFigure
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import make_empty_image, catalog_image
from gammapy.irf import EnergyDependentTablePSF

# Create image of defined size
reference = make_empty_image(nxpix=300, nypix=100, binsz=1)
psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# Create image
image = catalog_image(reference,
                      psf,
                      catalog='1FHL',
                      source_type='point',
                      total_flux='True')

# Plot
fig = FITSFigure(image.to_fits()[0])
fig.show_grayscale(stretch='linear', interpolation='none')
fig.add_colorbar()
# Gammapy significance
significance = np.nan_to_num(significance(correlated_counts, correlated_model,
                                          method='lima'))

titles = ['Gammapy Significance', 'Fermi Tools Significance']

# Plot

fig = plt.figure(figsize=(10, 5))
hdu1 = fits.ImageHDU(significance, header)
f1 = FITSFigure(hdu1, figure=fig, convention='wells', subplot=(1, 2, 1))
f1.set_tick_labels_font(size='x-small')
f1.tick_labels.set_xformat('ddd')
f1.tick_labels.set_yformat('ddd')
f1.show_colorscale(vmin=0, vmax=10, cmap='afmhot')
f1.add_colorbar(axis_label_text='Significance')
f1.colorbar.set_width(0.1)
f1.colorbar.set_location('right')

hdu2 = fits.ImageHDU(fermi_significance, header)
f2 = FITSFigure(hdu2, figure=fig, convention='wells', subplot=(1, 2, 2))
f2.set_tick_labels_font(size='x-small')
f2.tick_labels.set_xformat('ddd')
f2.hide_ytick_labels()
f2.hide_yaxis_label()
f2.show_colorscale(vmin=0, vmax=10, cmap='afmhot')
f2.add_colorbar(axis_label_text='Significance')
f2.colorbar.set_width(0.1)
f2.colorbar.set_location('right')
fig.text(0.15, 0.92, "Gammapy Significance")
fig.text(0.63, 0.92, "Fermi Tools Significance")
Пример #34
0
stokes_i = hawc[
    'STOKES I']  # or hawc[0]. Note the extension is from the hawc.info() table above

fig = plt.figure(figsize=(7, 7))

axs = FITSFigure(stokes_i, figure=fig)  # load HDU into aplpy figure
axs.show_colorscale(
    cmap=cmap)  # display the data with WCS projection and chosen colormap

# FORMATTING
axs.set_tick_labels_font(size='small')
axs.set_axis_labels_font(size='small')

# Add colorbar
axs.add_colorbar()
axs.colorbar.set_axis_label_text('Flux (Jy/pix)')

# ## Stokes Q and U
# Similarly, we can plot the Stokes Q and Stokes U images:

# In[3]:

stokes_q = hawc['STOKES Q']
stokes_u = hawc['STOKES U']

axq = FITSFigure(
    stokes_q,
    subplot=(1, 2,
             1))  # generate FITSFigure as subplot to have two axes together
axq.show_colorscale(cmap=cmap)  # show Q