Exemplo n.º 1
0
def make_rgb(
    outname,
    redline="H2CO303_202",
    greenline="H2CO321_220",
    blueline="H2CO322_221",
    fntemplate=paths.dpath("merge/moments/W51_b6_7M_12M.{0}.image.pbcor_medsub_max.fits"),
    suffix="_auto",
    **kwargs
):

    print(outname, suffix)
    rgb_cube_fits = outname
    if not os.path.exists(rgb_cube_fits):
        # does not return anything
        aplpy.make_rgb_cube(
            [
                fntemplate.format(redline) if "fits" not in redline else redline,
                fntemplate.format(greenline) if "fits" not in greenline else greenline,
                fntemplate.format(blueline) if "fits" not in blueline else blueline,
            ],
            rgb_cube_fits,
        )

    rgb_cube_png = rgb_cube_fits[:-5] + suffix + ".png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png, embed_avm_tags=True, **kwargs)
    return rgb_im
Exemplo n.º 2
0
def cut_rgb_image(tract, patch, ra, dec):
    width = 10 / 3600.0  # in degree
    img_r, img_g, img_b = download_image(tract, patch)

    try:
        cutoutimg(img_r,
                  ra,
                  dec,
                  xw=width,
                  yw=width,
                  units='wcs',
                  outfile='central_r.fits',
                  overwrite=True,
                  useMontage=False,
                  coordsys='celestial',
                  verbose=False,
                  centerunits=None)
        cutoutimg(img_g,
                  ra,
                  dec,
                  xw=width,
                  yw=width,
                  units='wcs',
                  outfile='central_g.fits',
                  overwrite=True,
                  useMontage=False,
                  coordsys='celestial',
                  verbose=False,
                  centerunits=None)
        cutoutimg(img_b,
                  ra,
                  dec,
                  xw=width,
                  yw=width,
                  units='wcs',
                  outfile='central_us.fits',
                  overwrite=True,
                  useMontage=False,
                  coordsys='celestial',
                  verbose=False,
                  centerunits=None)
    except:
        os.system('rm ' + img_r + ' ' + img_g + ' ' + img_b)
        return 'no output img', False

    output_img = 'rgb_image.png'
    aplpy.make_rgb_cube(
        ['central_r.fits', 'central_g.fits', 'central_us.fits'], 'cube.fits')
    aplpy.make_rgb_image('cube.fits',
                         output_img,
                         stretch_r='log',
                         stretch_g='log',
                         stretch_b='log',
                         vmin_r=0,
                         vmin_g=0,
                         vmin_b=0)

    os.system('rm ' + img_r + ' ' + img_g + ' ' + img_b)
    os.system('rm cube.fits')
    return output_img, True
Exemplo n.º 3
0
    def show_contours_on_threecolor(self, color='c',clobber=False):
        """
        Make a three-color image

        """
        from extinction_distance.support import zscale        
        
        print("Making color-contour checkimage...")
        if (not os.path.isfile(self.rgbcube)) or clobber:
            aplpy.make_rgb_cube([self.kim,self.him,self.jim],self.rgbcube,north=True,system="GAL")
        k = fits.getdata(self.kim)
        r1,r2 = zscale.zscale(k)
        h = fits.getdata(self.him)
        g1,g2 = zscale.zscale(h)
        j = fits.getdata(self.jim)
        b1,b2 = zscale.zscale(j)
        aplpy.make_rgb_image(self.rgbcube,self.rgbpng,
                             #G337 hand-coded
                             #vmin_r = 5671., vmax_r = 5952.,
                             #vmin_g = 8117., vmax_g = 8688.,
                             #vmin_b = 1462., vmax_b = 1606.)
                             vmin_r = r1, vmax_r = r2,
                             vmin_g = g1, vmax_g = g2,
                             vmin_b = b1, vmax_b = b2)
        f = aplpy.FITSFigure(self.rgbcube2d)
        f.show_rgb(self.rgbpng)
        f.show_contour(self.continuum, colors='white', levels=[0.1,0.2,0.4,0.8,1.6,3.2],smooth=3,convention='calabretta')
        f.show_markers([self.glon],[self.glat])                
        try:
            f.show_polygons([self.contours],edgecolor='cyan',linewidth=2)
        except:
            pass
        #f.show_contour(self.continuum,levels=[self.contour_level],convention='calabretta',colors='white')
        f.save(self.contour_check)
Exemplo n.º 4
0
def make_rgb(
        outname,
        redline='H2CO303_202',
        greenline='H2CO321_220',
        blueline='H2CO322_221',
        fntemplate=paths.dpath(
            'merge/moments/W51_b6_7M_12M.{0}.image.pbcor_medsub_max.fits'),
        suffix="_auto",
        **kwargs):

    print(outname, suffix)
    rgb_cube_fits = outname
    if not os.path.exists(rgb_cube_fits):
        # does not return anything
        aplpy.make_rgb_cube([
            fntemplate.format(redline) if 'fits' not in redline else redline,
            fntemplate.format(greenline)
            if 'fits' not in greenline else greenline,
            fntemplate.format(blueline)
            if 'fits' not in blueline else blueline,
        ], rgb_cube_fits)

    rgb_cube_png = rgb_cube_fits[:-5] + suffix + ".png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                                  output=rgb_cube_png,
                                  embed_avm_tags=True,
                                  **kwargs)
    return rgb_im
Exemplo n.º 5
0
 def do_cube(self,undone_cube):
     """Make a cube"""
     version = 2
     success = False
     print("Making a cube for "+undone_cube)
     print("Using files... "+str(self.cubes[undone_cube]))
     aplpy.make_rgb_cube([self.filenames[self.cubes[undone_cube][0]],self.filenames[self.cubes[undone_cube][1]],
                          self.filenames[self.cubes[undone_cube][2]]],self.filenames[undone_cube],system="GAL")
     print("Saving to: "+self.filenames[undone_cube])
     success = True
     if success:
         self.report_success(undone_cube,version)
Exemplo n.º 6
0
def makergbimage(rgbarray,iname,field,ra,dec):

	os.system('rm -rf rgbcube.fits rgbcube2.fits rgbcube_2d.fits')
	aplpy.make_rgb_cube(rgbarray, 'rgbcube.fits')
	aplpy.make_rgb_image('rgbcube.fits', '%s_%s.png' % (field,iname), pmax_r=95., pmax_g=95., pmax_b=95.)
		# # # Set a CTYPE
	d = pyfits.open('rgbcube.fits')
	hdr,data = d[0].header,d[0].data
	hdr['CTYPE3'] = 'VELO-LSR'
	pyfits.writeto('rgbcube2.fits',data,hdr)
	f = aplpy.FITSFigure('rgbcube2.fits',dimensions=[0, 1], slices=[0])
	f.show_rgb('%s_%s.png' % (field,iname))
	f.show_circles(ra, dec, 30/3600.,facecolor='',edgecolor='w',alpha=0.5,linewidth=4)
	#f.show_markers(ra,dec,marker='o',facecolor='',edgecolor='w',alpha=0.5,s=4000,linewidth=3)
	savefig('results/%s_%s_rgb.png' % (field,iname),bbox_inches='tight',transparent=True,dpi=200)
	os.system('rm -rf %s_%s.png' % (field,iname))
Exemplo n.º 7
0
    def show_contours_on_threecolor(self, color='c', clobber=False):
        """
        Make a three-color image

        """
        from extinction_distance.support import zscale

        print("Making color-contour checkimage...")
        if (not os.path.isfile(self.rgbcube)) or clobber:
            aplpy.make_rgb_cube([self.kim, self.him, self.jim],
                                self.rgbcube,
                                north=True,
                                system="GAL")
        k = fits.getdata(self.kim)
        r1, r2 = zscale.zscale(k)
        h = fits.getdata(self.him)
        g1, g2 = zscale.zscale(h)
        j = fits.getdata(self.jim)
        b1, b2 = zscale.zscale(j)
        aplpy.make_rgb_image(
            self.rgbcube,
            self.rgbpng,
            #G337 hand-coded
            #vmin_r = 5671., vmax_r = 5952.,
            #vmin_g = 8117., vmax_g = 8688.,
            #vmin_b = 1462., vmax_b = 1606.)
            vmin_r=r1,
            vmax_r=r2,
            vmin_g=g1,
            vmax_g=g2,
            vmin_b=b1,
            vmax_b=b2)
        f = aplpy.FITSFigure(self.rgbcube2d)
        f.show_rgb(self.rgbpng)
        f.show_contour(self.continuum,
                       colors='white',
                       levels=[0.1, 0.2, 0.4, 0.8, 1.6, 3.2],
                       smooth=3,
                       convention='calabretta')
        f.show_markers([self.glon], [self.glat])
        try:
            f.show_polygons([self.contours], edgecolor='cyan', linewidth=2)
        except:
            pass
        #f.show_contour(self.continuum,levels=[self.contour_level],convention='calabretta',colors='white')
        f.save(self.contour_check)
Exemplo n.º 8
0
 def do_cube(self, undone_cube):
     """Make a cube"""
     version = 2
     success = False
     print("Making a cube for " + undone_cube)
     print("Using files... " + str(self.cubes[undone_cube]))
     aplpy.make_rgb_cube([
         self.filenames[self.cubes[undone_cube][0]],
         self.filenames[self.cubes[undone_cube][1]],
         self.filenames[self.cubes[undone_cube][2]]
     ],
                         self.filenames[undone_cube],
                         system="GAL")
     print("Saving to: " + self.filenames[undone_cube])
     success = True
     if success:
         self.report_success(undone_cube, version)
Exemplo n.º 9
0
def make_SDSS_FITSFigure(ra, dec, plate_num, width):
    '''
    aspect ratio is weird with this method, so trying something different
    '''

    ra, dec = str(ra), str(dec)
    plate_num = str(plate_num)

    aplpy.make_rgb_cube([plate_num + '_r.fits', plate_num +
                         '_g.fits', plate_num + '_u.fits'],
                        plate_num + '_cube.fits')
    aplpy.make_rgb_image(plate_num + '_cube.fits',
                         plate_num + '_rgb.png')
    plt.close('all')
    f = aplpy.FITSFigure(plate_num + '_cube_2d.fits', figsize=(10, 10))
    f.show_rgb(plate_num + '_rgb.png')
    f.add_grid()
    f.tick_labels.set_font(size='xx-small')
    f.axis_labels.set_font(size='x-small')
    f.axis_labels.set_xtext('Right Ascension (J2000)')
    f.axis_labels.set_ytext('Declination (J2000)')

    plt.tight_layout()
    plt.show()
Exemplo n.º 10
0
import numpy as np
import aplpy

fitslist = ['h_m51_h_s20_drz_sci.fits',
			'h_m51_v_s20_drz_sci.fits',
			'h_m51_b_s20_drz_sci.fits'
			]

# Reproject the images to a common projection - this will also produce
# ``2mass_cube_2d.fits``
aplpy.make_rgb_cube(fitslist, 'm51_cube.fits')

# Make an RGB image
aplpy.make_rgb_image('m51_cube.fits', 'm51_rgb.png')

# Plot the RGB image using the 2d image to indicate the projection
f = aplpy.FITSFigure('m51_cube_2d.fits')
f.show_rgb('m51_rgb.png')
Exemplo n.º 11
0
mean_SDOM_ZP_V = np.mean(SDOM_ZP_V)/np.sqrt(3)

#ZP in V filter is 21.68807 +/- 0.0058






##################################################################################
#                                                                                              +++RGB IMAGES+++                                                                                           #
##################################################################################


#ordered R-V-B inside the data cube:
aplpy.make_rgb_cube([dir + '/mosaic_R/mosaic.fits', dir +  '/mosaic_V/mosaic.fits', dir+  '/mosaic_B/mosaic.fits'], dir + '/rgb_cube.fits')

aplpy.make_rgb_image(dir + '/rgb_cube.fits', dir + '/cluster_rgb.png', embed_avm_tags=False)

fig = aplpy.FITSFigure(dir+'/rgb_cube_2d.fits')
fig.show_rgb(dir+'/cluster_rgb.png')

fig.add_grid()
fig.grid.set_linestyle('dotted')


##################################################################################
#                                                                                              +++HR DIAGRAM!+++                                                                                          #
##################################################################################

Exemplo n.º 12
0
def psocolor(source_name,keepfiles=False,allcolor='#FFFF00',rejcolor='b',tm_color='r',plot=False,savepdf=True,secondary='',skipdownloads=False,circle_radius=0.0015,size=2.0,override_directory=None,primarypos_label=None,title=None,filename=None,buffer=False):
    # Set $FINDER_PATH in your bash_profile if you would like to control where the finder charts are output
    # size: arcmin
    # allwise: overplot AllWISE catalog positions
    # rejallwise = overplot AllWISE reject positions
    # tmass = overplot 2MASS psc positions
    # keepfiles = keep fits, tbl, and xml files
    # allcolor = color of allwise symbols
    # rejcolor = color of allwise reject symbols
    # tm_color = color of tmass symbols
    # plot = show plot (otherwise, finder is just made)
    # savepdf = save a pdf of the finder    
    
    circle_width = 2.5
    circle_alpha = 0.8
    fig_xsize = 11
    fig_ysize = 8.5
    
    #Convert sexagecimal
    if source_name.find(' ') == -1:
    	symbol = '+'
    	if source_name.find('+') == -1:
    		symbol = '-'
    	radec = re.split('[\+ | -]',source_name)
    	ras = radec[0][0:2]+' '+radec[0][2:4]+' '+radec[0][4:]
    	decs = radec[1][0:2]+' '+radec[1][2:4]+' '+radec[1][4:]
    	ra = coord.Angle(ras, unit=u.hour)
    	dec = coord.Angle(symbol+decs,unit=u.degree)
    	source_name = str(ra.degree)+' '+str(dec.degree)
    
    #Use buffer if needed
    if buffer:
        import matplotlib
        matplotlib.use('Agg')
        plot=False
    import pylab,pyfits,aplpy
    
    #Verify whether a working directory is set in the bash profile
    main_dir = None
    if override_directory:
        main_dir = override_directory
    else:
        proc = subprocess.Popen(["echo $FINDER_PATH"], stdout=subprocess.PIPE,shell=True)
        (out, err) = proc.communicate()
        if out != '\n':
            main_dir = out.split('\n')[0]
    if main_dir:
        initial_dir = os.getcwd()
        if not os.path.exists(main_dir):
            os.makedirs(main_dir)
        os.chdir(main_dir)
    
    #List of colors
    color_blue = '#377eb8'#RGB=[55,126,184]
    color_red = '#e41a1c'#RGB=[228,26,28]
    color_purple = '#b27bba'#RGB=[178,123,186]
    color_green = '#4daf4a'#RGB = [77,175,74]
    
    t1 = datetime.now()    
    
    ra,de = simbad(source_name)
    ra2 = None
    de2 = None
    if secondary:
        ra2,de2 = simbad(secondary)
    if filename is None:
        filename = source_name
    
    if skipdownloads is not True:
        print("Downloading Pan-Starrs data")
        #Remove previous data
        os.system("rm *_PSO_TMP.fits*")
        query_pso_fits(ra,de,size=size,output_file='PSO_TMP.fits')
    
    #If no PSO data could be downloaded, return
    if len(glob.glob('*_PSO_TMP.fits*')) == 0:
        print("No PSO data !")
        return
    
    if plot:
        pylab.ion()
    fig = pylab.figure(figsize=(fig_xsize,fig_ysize))
    pylab.rcParams['font.family'] = 'serif'
    
    #Create and plot RGB PSO image
    files = ['y_PSO_TMP.fits','i_PSO_TMP.fits','g_PSO_TMP.fits']
    aplpy.make_rgb_cube(files,'PSO_rgb.fits')
    impsoc = aplpy.FITSFigure('PSO_rgb_2d.fits',figure=fig)
    impsoc.add_label(0.05,0.9,'PSO $y$/$i$/$g$',relative=True,size='medium',color='k',bbox=dict(facecolor='white', alpha=0.5),horizontalalignment='left')

    meds = []
    mads = []
    devs = []
    for filei in files:
        datai = pyfits.getdata(filei)
        medi = np.nanmedian(datai)
        madi = np.nanmedian(abs(datai - np.nanmedian(datai)))
        devi = np.nanpercentile(datai,95) - np.nanpercentile(datai,5)
        meds.append(medi)
        mads.append(madi)
        devs.append(devi)
    
    mins = []
    maxs = []
    for i in range(0,len(files)):
        mini = (meds[i] - 2.0*mads[i])
        #maxi = (meds[i] + 10.0*mads[i])
        maxi = meds[i] + 2.0*devs[i]
        mins.append(mini)
        maxs.append(maxi)
    
    aplpy.make_rgb_image('PSO_rgb.fits','PSO_rgb.png',vmin_r=mins[0],vmin_g=mins[1],vmin_b=mins[2],vmax_r=maxs[0],vmax_g=maxs[1],vmax_b=maxs[2])
    
    impsoc.show_rgb('PSO_rgb.png')
    impsoc.hide_tick_labels()
    impsoc.ticks.hide()
    impsoc.hide_xaxis_label()
    impsoc.hide_yaxis_label()
    impsoc.recenter(ra,de,width=(size/60.0),height=(size/60.0))
    impsoc.show_circles(ra,de,edgecolor=color_red,linewidth=circle_width,facecolor='none',radius=circle_radius,alpha=circle_alpha)
    if secondary:
        impsoc.show_circles(ra2,de2,edgecolor=color_blue,linewidth=circle_width,facecolor='none',    radius=circle_radius,alpha=circle_alpha)
    
    # Remove files (or not)
    if keepfiles:
        pass
    else:
        print("Removing files...")
        cmdrm1 = "rm PSO_rgb.png PSO_rgb*.fits"
        os.system(cmdrm1)
    if savepdf:
        pylab.savefig(filename+'_pso_color.pdf')
    
    #Return to initial directory
    if main_dir:
        os.chdir(initial_dir)
    
    t2 = datetime.now()
    tdiff = (t2 - t1)
    print("PSO image creation took %s seconds" % (round(tdiff.total_seconds(),0)))
Exemplo n.º 13
0
import sys,os
import aplpy
import random
from termcolor import colored

filelist = open('files_all','r').readlines()
random.shuffle(filelist)

for index in filelist[:1]:
	index = index.rstrip()
	print colored('RGB image gernerating :','green'), colored(' VCC'+index,'yellow')
	image_r = index+'.i.fits'
	image_g = index+'.g.fits'
	image_b = index+'.u.fits'
	cube_name = index+'_rgb.fits'
	cube_name2 = index +'_rgb_2d.fits'
	output_image_name =index+'.png'
	if os.path.exists('./'+output_image_name)==False and index !=1347 and index !=0167:
             	aplpy.make_rgb_cube([image_r,image_g,image_b],cube_name)
             	aplpy.make_rgb_image(cube_name,output_image_name,
             		stretch_r='arcsinh',stretch_g='arcsinh',stretch_b='arcsinh',
             		#vmin_r=0, vmin_g=0,vmin_b=0,
             		embed_avm_tags = False)
             	os.system('rm '+cube_name+' '+cube_name2)
             	
             	#os.system('shotwell '+output_image_name+'&')
Exemplo n.º 14
0
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)

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

for cont_gal, gal in enumerate(cataid):

    print(gal)

    create_sb_image(gal, images_gband_path, "g", zp, pix_scale)
    create_sb_image(gal, images_rband_path, "r", zp, pix_scale)
    create_sb_image(gal, images_iband_path, "i", zp, pix_scale)

    #aplpy.make_rgb_cube([images_gband_path+str(gal)+'_kids_g.fits', images_rband_path+str(gal)+'_kids_r.fits', images_iband_path+str(gal)+'_kids_i.fits'], str(gal)+'_cube.fits')
    aplpy.make_rgb_cube([
        images_iband_path + str(gal) + '_kids_i_sb.fits',
        images_rband_path + str(gal) + '_kids_r_sb.fits',
        images_gband_path + str(gal) + '_kids_g_sb.fits'
    ],
                        str(gal) + '_cube.fits')

    img_g = fits.open(images_gband_path + str(gal) + '_kids_g_sb.fits')
    img_r = fits.open(images_rband_path + str(gal) + '_kids_r_sb.fits')
    img_i = fits.open(images_iband_path + str(gal) + '_kids_i_sb.fits')

    aplpy.make_rgb_image(str(gal) + '_cube.fits',
                         './color_images/' + str(gal) + '_rgb.png',
                         stretch_r='linear',
                         stretch_g='linear',
                         stretch_b='linear',
                         vmin_r=min_i,
                         vmax_r=max_i,
                         vmin_g=min_r,
Exemplo n.º 15
0
import aplpy

# Convert all images to common projection
aplpy.make_rgb_cube(['m1.fits', 'i3.fits', 'i2.fits'], 'rgb.fits')

# Make 3-color image
aplpy.make_rgb_image('rgb.fits',
                     'rgb.png',
                     vmin_r=20,
                     vmax_r=400,
                     vmin_g=0,
                     vmax_g=150,
                     vmin_b=-2,
                     vmax_b=50)

# Create a new figure
f = aplpy.FITSFigure('rgb_2d.fits')

# Show the RGB image
f.show_rgb('rgb.png')

# Add contours
f.show_contour('sc.fits', cmap='gist_heat', levels=[0.2, 0.4, 0.6, 0.8, 1.0])

# Overlay a grid
f.add_grid()
f.grid.set_alpha(0.5)

# Save image
f.save('plot.png')
Exemplo n.º 16
0
import matplotlib.pyplot as plt
import numpy as np
import aplpy

# Convert all images to common projection
aplpy.make_rgb_cube([
    'C:/Users/chaowang/r.fits', 'C:/Users/chaowang/g.fits',
    'C:/Users/chaowang/u.fits'
], 'rgb.fits')

# Make 3-color image
aplpy.make_rgb_image('rgb.fits',
                     'rgb.png',
                     vmin_r=20,
                     vmax_r=400,
                     vmin_g=0,
                     vmax_g=150,
                     vmin_b=-2,
                     vmax_b=50)

# Create a new figure
fig = aplpy.FITSFigure('rgb.fits')

# Show the RGB image
fig.show_rgb('rgb.png')

# Add contours
fig.show_contour('sc.fits', cmap='gist_heat', levels=[0.2, 0.4, 0.6, 0.8, 1.0])

# Overlay a grid
fig.add_grid()
Exemplo n.º 17
0
def sdss(input_file, output_dir, filters, output_format, pmin_r, pmax_r,
         pmin_g, pmax_g, pmin_b, pmax_b):
    """
    Generates RGB images using SDSS data and APLPY. Information for parameters can be found in inputHandler(). I separated them up to allow easier access from makeTable.py
    """

    warnings.filterwarnings("ignore")

    # get parameters and inputs into a suitable format
    df = pd.read_csv(input_file, header=None)
    output_format = output_format.lower()
    filters = filters.split(',')

    if len(filters) != 3:
        raise Exception('Error. Please provide 3 filters separated by commas')

    try:
        os.mkdir(output_dir)
    except:
        typer.echo(
            f'A dir with the name {typer.style(output_dir, bold=True, fg=typer.colors.RED)} already exists'
        )

    for i, line in df.iterrows():
        try:

            name = line[0]
            ra = line[1]
            dec = line[2]

            styled_name = typer.style(name, fg=typer.colors.MAGENTA, bold=True)

            typer.echo(f'Plotting: ' + styled_name)

            pos = coords.SkyCoord(ra, dec, unit='deg')

            # query SDSS for each target and get the images
            try:
                xid = Table(SDSS.query_region(pos, spectro=False)[0])
            except:
                raise Exception(f'No images found on SDSS for target {name}')

            im = SDSS.get_images(matches=xid, band=filters)

            # raise exception if no images are found
            if len(im) == 0:
                raise Exception(f'No images found on SDSS for target {name}')

            # Obtain the PrimaryHDU from the HDUList for each band
            r, g, b = im[0][0], im[1][0], im[2][0]

            # save the fits files so they can be combined into a single rgb cube
            r.writeto('r.fits', overwrite=True)
            g.writeto('g.fits', overwrite=True)
            b.writeto('b.fits', overwrite=True)
            aplpy.make_rgb_cube(['r.fits', 'g.fits', 'b.fits'],
                                f'image.fits',
                                north=True)

            aplpy.make_rgb_image(f'image.fits',
                                 fr'{output_dir}/{name}.{output_format}',
                                 pmin_r=pmin_r,
                                 pmax_r=pmax_r,
                                 pmin_g=pmin_g,
                                 pmax_g=pmax_g,
                                 pmin_b=pmin_b,
                                 pmax_b=pmax_b)
            image = aplpy.FITSFigure(fr'{output_dir}/{name}.{output_format}')
            image.show_rgb()

            # add labels for filters used
            image.add_label(0.08,
                            0.15,
                            "FILTERS:",
                            relative=True,
                            color='white')

            filter_wavelengths = {
                'z': 913,
                'i': 763,
                'r': 623,
                'g': 477,
                'u': 354
            }
            bandColours = ['red', 'green', 'cyan']
            for i in range(3):
                w = filter_wavelengths[filters[i]]
                c = bandColours[i]
                image.add_label(0.08,
                                0.11 - 0.03 * i,
                                f"{filters[i]} ({w}nm)",
                                relative=True,
                                color=c)

            # add arrows pointing to object
            image.show_arrows(
                x=[ra + 0.01, ra - 0.01, ra + 0.01, ra - 0.01],
                y=[dec + 0.01, dec - 0.01, dec - 0.01, dec + 0.01],
                dx=[-0.007, 0.007, -0.007, 0.007],
                dy=[-0.007, 0.007, 0.007, -0.007],
                color='red')

            # add object name as label
            image.add_label(ra, dec + 0.02, name, color='red')

            # get redshift for scalebar
            resTable = Ned.query_region(pos, radius=0.01 * u.deg)
            resTable = resTable.to_pandas()
            redshift = 0
            for i, row in resTable.iterrows():
                if row['Redshift'] > 0:
                    redshift = row['Redshift']
                    break

            kpcArcmin = cosmo.kpc_proper_per_arcmin(float(redshift)).value
            length = round(kpcArcmin * 2, 1)

            # add scalebar
            image.add_scalebar(1 / 30,
                               label=f'120" | {length}kpc | r = {redshift}',
                               color='red')

            # save to output dir in the appropriate format
            image.save(fr'{output_dir}/{name}.{output_format}')

            typer.echo('Finished plotting: ' + styled_name)

        except Exception as e:
            typer.echo('Failed for: ' + styled_name)
            print(e)

    cleanup()
Exemplo n.º 18
0
def zoomfigure(target=e2e, targetname='e2e', radius=7.5*u.arcsec, cutout='e2e8',
               zoom_radius=3*u.arcsec, tick_spacing=1.8*u.arcsec):

    fn = paths.dpath('merge/cutouts/W51_b6_7M_12M.HNCO10010-909.image.pbcor_{0}cutout.fits'.format(cutout))
    m0hnco = get_mom0(fn, iterate=False)

    cutout_cont = Cutout2D(cont_fits[0].data, target, radius, wcs=wcs.WCS(cont_fits[0].header))
    cutout_ch3oh = Cutout2D(m0ch3oh.value, target, radius, wcs=wcs.WCS(m0ch3oh.header))
    cutout_hnco = Cutout2D(m0hnco.value, target, radius, wcs=wcs.WCS(m0hnco.header))

    cont_fits_cutout = fits.PrimaryHDU(data=cutout_cont.data, header=cutout_cont.wcs.to_header())
    ch3oh_fits_cutout = fits.PrimaryHDU(data=cutout_ch3oh.data, header=cutout_ch3oh.wcs.to_header())
    hnco_fits_cutout = fits.PrimaryHDU(data=cutout_hnco.data, header=cutout_hnco.wcs.to_header())
    cont_fits_fn = "rgb/continuum_{0}_cutout.fits".format(targetname)
    hnco_fits_fn = "rgb/hnco_{0}_cutout.fits".format(targetname)
    ch3oh_fits_fn = "rgb/ch3oh_{0}_cutout.fits".format(targetname)
    cont_fits_cutout.writeto(cont_fits_fn, clobber=True)
    ch3oh_fits_cutout.writeto(ch3oh_fits_fn, clobber=True)
    hnco_fits_cutout.writeto(hnco_fits_fn, clobber=True)


    rgb_cube_fits = '{0}_ch3oh_hnco_cont.fits'.format(targetname)
    if not os.path.exists(rgb_cube_fits):
        # does not return anything
        aplpy.make_rgb_cube([ch3oh_fits_fn, hnco_fits_fn, cont_fits_fn,], rgb_cube_fits)

    rgb_cube_png = rgb_cube_fits[:-5]+"_auto.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  embed_avm_tags=True)

    rgb_cube_png = rgb_cube_fits[:-5]+"_logcont.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  #vmin_b=0.005,
                                  #vmax_b=0.15,
                                  stretch_b='log', embed_avm_tags=True)

    #rgb_cube_png = rgb_cube_fits[:-5]+"_asinhgreen.png"
    #rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
    #                              vmax_g=0.017,
    #                              vmax_b=6.5,
    #                              vmax_r=7.0,
    #                              vmin_g=0.0001,
    #                              stretch_g='arcsinh', 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.00075)
    F.recenter(target.ra.deg, target.dec.deg, radius=zoom_radius.to(u.deg).value)
    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.set_tick_xspacing(tick_spacing.to(u.deg).value)
    F.add_label(0.05, 0.95, "CH$_3$OH", relative=True, color='r', horizontalalignment='left')
    F.add_label(0.05, 0.91, "HNCO", relative=True, color='g', horizontalalignment='left')
    F.add_label(0.05, 0.87, "Continuum", relative=True, color='b', horizontalalignment='left')
    F.save(paths.fpath("W51{0}_ch3oh_hnco_continuum_aplpy.png".format(targetname)))
    F.save(paths.fpath("W51{0}_ch3oh_hnco_continuum_aplpy.pdf".format(targetname)))

    F.show_contour(paths.vpath('data/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'),
                   levels=np.array([0.0015,0.0045,0.0135,0.0270,0.054,0.108])*1.25,
                   colors=['w']*7, layer='evla_cont')
    F.save(paths.fpath("W51{0}_ch3oh_hnco_continuum_aplpy_kucontours.png".format(targetname)))
    F.save(paths.fpath("W51{0}_ch3oh_hnco_continuum_aplpy_kucontours.pdf".format(targetname)))
Exemplo n.º 19
0
input_fits_image_band6='./input/G12v230_IRAC_Mosaic_45.fits'

band4_present=1  #=================================================================1:yes 0:no (I band)
band5_present=1  #=================================================================1:yes 0:no (3.6 band)
band6_present=1  #=================================================================1:yes 0:no (4.5 band)



#montage.mSubimage(input_fits_image_band5, './G12_3p6_trimmed.fits', ra=, dec=, xsize=0.0023)






aplpy.make_rgb_cube([input_fits_image_band1, input_fits_image_band2, input_fits_image_band4], 'G12_cube.fits')   #R, G, B
#aplpy.make_rgb_image('G12_cube.fits','G12_cube.png')
aplpy.make_rgb_image('G12_cube.fits','G12_cube.png', vmin_b=500.0, vmax_b=3000.0, vmax_r=73.0, vmin_r=-20.0)
#aplpy.make_rgb_image('G12_JHK_cube.fits', 'G12_JHK_cube.png', pmin_r=0., pmax_r=80., pmin_g=0., pmax_g=80., pmin_b=0., pmax_b=80.)




rgb_image = aplpy.FITSFigure('./G12_cube_2d.fits')
rgb_image.show_rgb('G12_cube.png')
#rgb_image.show_contour(input_fits_image_band5, levels=3, colors='red', linewidths=0.5)

#rgb_image.recenter(176.65903,-0.19764512, radius=0.036)
rgb_image.recenter(176.65903,-0.19764512, width=0.066, height=0.07)

rgb_image.add_scalebar(1.0/60.0)
Exemplo n.º 20
0
def plot_RGB(
	figname,
	filename,
	title,
	subplot=None,
	rgb = [10,99.75],rgb_stretch=['linear'], # can put lists here
	show_circles = False,show_grid=False,show_xaxis=True,show_yaxis=True,show_contours=True,
	show_scalebar=True,show=True,show_fields=True,show_labels=False,show_focus=False,
	focus = [], #ra,dec,size
	labels=[],
	fields=[['20h07m07.178s','+27d28m23.79s',-15,180],['20h07m02.561s','+27d30m25.90s',25,180]],
	scale_bar=20, #arcsec
	dist = 700., # pc
	name='IRAS20050', contours=None,
	contours_levels=[],
	radius_source = 2.4, # arcsec
	ra='20:07:06.70',dec='27:28:54.5',
	radius = 200.): # of snapshot, arcsec
	'''
	this function displays the file in filename in all a uniform format
	all defaults to IRAS20050
	dist in pc
	radius in asec
	radius_source in asec
	'''

	aplpy.make_rgb_cube([filename[0],filename[1],filename[2]],title+'_rgb_cube.fits')
	if len(rgb_stretch)==1:
		stretch_r= stretch_g= stretch_b = rgb_stretch[0]
	else:
		[stretch_r, stretch_g, stretch_b] = rgb_stretch
	if len(rgb)==2: 
		pmin_r=pmin_g=pmin_b=rgb[0]; pmax_r=pmax_g=pmax_b=rgb[1]
	else:
		[pmin_r,pmin_g,pmin_b,pmax_r,pmax_g,pmax_b] = rgb
	aplpy.make_rgb_image(title+'_rgb_cube.fits', title+'_rgb_cube.png',pmin_r=pmin_r,pmin_g=pmin_g,pmin_b=pmin_b,
		pmax_r=pmax_r,pmax_g=pmax_g,pmax_b=pmax_b,stretch_r=stretch_r, stretch_g=stretch_g, stretch_b=stretch_b)
	if subplot==None:
		fig = aplpy.FITSFigure(title+'_rgb_cube_2d.fits',figure=figname)
	else:
		fig = aplpy.FITSFigure(title+'_rgb_cube_2d.fits',figure=figname,subplot=subplot)
	fig.show_rgb(title+'_rgb_cube.png')	

	# coordinates of the center of the image
	c = SkyCoord(ra=ra,dec=dec,frame='fk5',unit=(u.hour,u.deg))

	# recenter image
	fig.recenter(c.ra.deg,c.dec.deg,radius=radius/3600.)
	
	# put axes on top
	fig.tick_labels.set_xposition('top')
	fig.axis_labels.set_xposition('top')
	fig.tick_labels.set_font(size='small')
	fig.tick_labels.set_xformat('hh:mm:ss')
	fig.tick_labels.set_yformat('dd:mm:ss')
	#fig.ticks.set_xspacing(10./3600.)

	# turn grid on
	if show_grid:
		fig.add_grid()

	# show/hide axes
	if not show_xaxis:
		fig.axis_labels.hide_x()	
		fig.tick_labels.hide_x()
	if not show_yaxis:
		fig.axis_labels.hide_y()	
		fig.tick_labels.hide_y()

	if show_labels:
		c = SkyCoord(ra='20h07m06.782s',dec='27d28m43.00s',frame='fk5',unit=(u.hour,u.deg))
		fig.add_label(c.ra.deg,c.dec.deg,'SOF1',color='red',weight='bold',size=20)
		c = SkyCoord(ra='20h07m06.798s',dec='27d28m56.48s',frame='fk5',unit=(u.hour,u.deg))
		fig.add_label(c.ra.deg,c.dec.deg,'SOF2',color='red',weight='bold',size=20)
		c = SkyCoord(ra='20h07m06.458s',dec='27d29m00.78s',frame='fk5',unit=(u.hour,u.deg))
		fig.add_label(c.ra.deg,c.dec.deg,'SOF3',color='red',weight='bold',size=20)
		c = SkyCoord(ra='20h07m05.592s',dec='27d29m03.0s',frame='fk5',unit=(u.hour,u.deg))
		fig.add_label(c.ra.deg,c.dec.deg,'SOF4',color='red',weight='bold',size=20)
		c = SkyCoord(ra='20h07m05.795s',dec='27d28m46.82s',frame='fk5',unit=(u.hour,u.deg))
		fig.add_label(c.ra.deg,c.dec.deg,'SOF5',color='red',weight='bold',size=20)

	# add title
	fig.add_label(0.2,0.9,title,relative=True,color='red',weight='bold')
	#fig.set_title(title)
	
	# load source list
	sources = pickle.load(open(folder_export+"totsourcetable_fits.data","r"))

	# extract only the RA, DEC column for name
	if show_circles:
		for i in range(len(sources)):
			if name in sources['SOFIA_name'][i] and "Total_Cluster" not in sources['Property'][i]:
				s = "%d" % (i)
				fig.show_circles(sources['RA'][i],sources['DEC'][i],radius_source/3600.,edgecolor='red',facecolor='none',alpha=0.8,lw=2,label=s)

	# add scalebar
	if show_scalebar:
		scale_pc = 1./dist*scale_bar
		fig.add_scalebar(scale_bar/3600.)
		#fig.scalebar.set_frame(True)
		fig.scalebar.set_alpha(0.7)
		fig.scalebar.set_color('red')
		fig.scalebar.set_label('%d" = %.3f pc' % (scale_bar,scale_pc))
		fig.scalebar.set_linewidth(3)
		fig.scalebar.set_font(weight='bold')

	# add another dashed rectangle showing the region of interest
	if show_focus:
		rafoc,decfoc,sizefoc=focus
		foc = SkyCoord(ra=rafoc,dec=decfoc,frame='fk5',unit=(u.hour,u.deg))
		fig.show_rectangles(foc.ra.deg,foc.dec.deg,sizefoc/3600.,decfoc/3600.,edgecolor='red',facecolor='none',alpha=0.8,lw=2,linestyle='dashed')
				
	# show the SOFIA fields
	if show_fields:
		patches = []
		for field in fields:
			raf,decf,ang,width = field
			c = SkyCoord(ra=raf,dec=decf,frame='fk5',unit=(u.hour,u.deg))

			xp, yp = wcs_util.world2pix(fig._wcs, c.ra, c.dec)
			wp = hp = width/3600. / wcs_util.celestial_pixel_scale(fig._wcs)
			
			rect = Rectangle((-wp/2., -hp/2), width=wp, height=hp)
			t1 = mpl.transforms.Affine2D().rotate_deg(ang).translate(xp, yp)
			rect.set_transform(t1)
			patches.append(rect)

		# add all patches to the collection
		p = PatchCollection(patches, edgecolor='white',facecolor='none',alpha=0.8,lw=2)
		
		# add collection to figure
		t = fig._ax1.add_collection(p)

	# display contours
	if contours != None:
		fig.show_contour(contours,colors='white',returnlevels=True,levels=contours_levels)

	if show:
		plt.show()
Exemplo n.º 21
0
def make_cube(process=True):
    '''
	Turn all the UV data into a cube!
	'''

    cr_img_exists = glob.glob(
        '*cr.fits'
    )  #makes a list of count rate images that exist in the current directory, checks if uvot_deep done

    filter_list = ['w2', 'm2', 'w1']

    if len(cr_img_exists) == 0:

        id_list = glob.glob('000*')

        try:
            uvot_deep.uvot_deep(id_list, gal + '_',
                                filter_list)  #tool adapted by Lea Hagen
        except FileNotFoundError:
            print('* Required files not made out of uvot_deep for ' + gal +
                  ', moving on...')
            unprocessed_gals.write(gal + '\n')
            why_bypass.write(gal +
                             ': required files not made out of uvot_deep' +
                             '\n')
            process = False

        except OSError:
            print(
                'Too many open files error thrown, whatever that means. Moving on...'
            )  #sass maybe not good, maybe chill
            unprocessed_gals.write(gal + '\n')
            why_bypass.write(gal + ': too many open files error' + '\n')
            process = False  #does this work here?

    else:
        print("* uvot_deep already completed successfully, moving on!")
        #input()

    #offset_mosaic running over and over again, need to skip over this right now
    #if images have been created already, don't run it again
    #later will have to take into consideration whether or not there is new data that requires a rerun of uvot_deep

    offset_done = glob.glob(gal + '_offset_*')

    if len(offset_done) == 0:
        try:  #make sure this does run again
            if True:
                print('* running offset_mosaic')
                offset_mosaic.offset_mosaic(gal + '_',
                                            gal + '_offset_',
                                            filter_list,
                                            min_exp_w2=150,
                                            min_exp_m2=150,
                                            min_exp_w1=150,
                                            restack_id=True)
        except IndexError:
            print("* index 0 is out of bounds for axis 0 with size zero")
            unprocessed_gals.write(gal + '\n')
            why_bypass.write(
                gal +
                ': offset mosaic problem, index 0 is out of bounds for axis 0 with size zero'
                + '\n')
            #continue #fix continue
            process = False

    else:
        print('* offset_mosaic has been run already, moving on!')

    #list of uv filters, can be changed if someone needs optical filter images as well.
    #filter_list = ['w1', 'm2', 'w2']

    idl = pidly.IDL('/bulk/pkg/local/bin/idl')

    for filt in filter_list:

        #taken from Lea's code stack_uvot
        with fits.open(gal + "_" + filt +
                       '_cr.fits') as hdu_cr:  #cr = count rate

            pix_clip = sigma_clip(hdu_cr[0].data, sigma=2.5, maxiters=3)
            cr_mode = biweight_location(pix_clip.data[~pix_clip.mask])
            #print('cr_mode: ', cr_mode)

            hdu_cr[0].data -= cr_mode

            hdu_cr.writeto(gal + '_offset_' + filt + '_cr_bgsub.fits',
                           overwrite=True)

        idl.pro('image_shift',
                gal)  #idl procedure that aligns all the image_shift

    idl.close()

    #replaces mkcolor idl script (credits to Lea)
    # make RGB image

    cube_done = glob.glob(gal + '_rgb_cube*')
    if len(cube_done) == 0:
        #if no data for the filter, gotta skip over the image that would be created
        im_r = gal + '_offset_w1_cr_bgsub.fits'
        im_g = gal + '_offset_m2_cr_bgsub.fits'
        im_b = gal + '_offset_w2_cr_bgsub.fits'

        vmid_list = 0.001
        vmin_list = []

        for i, im in enumerate([im_r, im_g, im_b]):
            hdu_list = fits.open(im)
            filt = sigma_clip(hdu_list[0].data, sigma=2, maxiters=5)
            vmin_list.append(
                np.mean(filt.data[~filt.mask]) +
                1.5 * np.std(filt.data[~filt.mask]))
            hdu_list.close()

        # - create fits images in same projection
        print('* creating rgb fits cube for ' + gal)
        aplpy.make_rgb_cube([im_r, im_g, im_b],
                            gal + '_rgb_cube.fits',
                            north=True)
        # - make the rgb image
        print('* creating rgb png image of ' + gal)
        aplpy.make_rgb_image(gal + '_rgb_cube.fits',
                             gal + '_image' + '.png',
                             stretch_r='log',
                             stretch_g='log',
                             stretch_b='log',
                             vmin_r=vmin_list[0],
                             vmin_g=vmin_list[1],
                             vmin_b=vmin_list[2],
                             vmid_r=vmid_list,
                             vmid_g=vmid_list,
                             vmid_b=vmid_list,
                             pmax_r=99.95,
                             pmax_g=99.9,
                             pmax_b=99.9,
                             make_nans_transparent=True)
    else:
        print(
            'rgb_cube FITS file already exists, moving on to .png creation and photometry!'
        )

    return process
Exemplo n.º 22
0
make_rgb(
    "ku_so_c18o_rgb.fits",
    greenline="SO65-54",
    redline=fnku,
    blueline="C18O2-1",
    pmax_g=99.99,
    pmax_r=99.95,
    pmax_b=99.99,
)


rgb_cube_fits = "full_h2co_rgb.fits"
if not os.path.exists(rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube([fn303, fn321, fn322], rgb_cube_fits)

rgb_cube_png = rgb_cube_fits[:-5] + "_auto.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png, embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_setlevels.png"
rgb_im = aplpy.make_rgb_image(
    data=rgb_cube_fits,
    output=rgb_cube_png,
    vmin_b=-0.005,
    vmax_b=0.4,
    vmin_g=-0.005,
    vmax_g=0.4,
    vmin_r=-0.005,
    vmax_r=0.4,
    embed_avm_tags=True,
import paths

for species, blue_fits, red_fits in (('co',
                                      paths.dpath('moments/w51_12co2-1_blue0to45_masked.fits'),
                                      paths.dpath('moments/w51_12co2-1_red73to130_masked.fits')),
                                     ('so',
                                      paths.dpath('moments/w51_so_65-54_blue0to45.fits'),
                                      paths.dpath('moments/w51_so_65-54_red65to130.fits'))
                                    ):

    green_fits = '/Users/adam/work/w51/paper_w51_evla/data/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'
    rgb_cube_fits = 'outflow_co_redblue_kucont_green.fits'

    if not os.path.exists(rgb_cube_fits):
        # does not return anything
        aplpy.make_rgb_cube([red_fits, green_fits, blue_fits], rgb_cube_fits)

    rgb_cube_png = rgb_cube_fits[:-5]+"_auto.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  embed_avm_tags=True)

    rgb_cube_png = rgb_cube_fits[:-5]+"_loggreen.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  stretch_g='log', embed_avm_tags=True)

    rgb_cube_png = rgb_cube_fits[:-5]+"_loggreen_max.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  pmax_g=99.99,
                                  stretch_g='log', embed_avm_tags=True)

    rgb_cube_png = rgb_cube_fits[:-5]+"_asinhgreen.png"
Exemplo n.º 24
0
##############
# ASTROPY WAY
##############

#the SPT0348 fits files: bands 3, 6, 7
#b3 = dir+'spt0348_b3ctm_dirty_briggs_robust05_15klambda_uvtaperbeam_2.fits' #red: 3.6mm to 2.6mm
#b6 = dir+'spt0348_b6ctm_dirty_briggs_robust05_15klambda_uvtaperbeam_2.fits' #green: 1.4mm to 1.1mm
#b7 = dir+'spt0348_b7ctm_dirty_briggs_robust05_15klambda_uvtaperbeam_2.fits' #blue: 1.1mm to 0.8mm

b3 = 'best/spt0348_band3_clean1000_cont.fits'
b6 = 'best/spt0348_band6_clean1000_cont.fits'
b7 = 'best/spt0348_band7_clean1000_cont.fits'

#making a 3D cube from the bands

ap.make_rgb_cube([b3, b6, b7], 'spt0348_cube.fits')
ap.make_rgb_cube([b3, b6, b7], 'spt0348_cube')

##making an image from the cubes
ap.make_rgb_image(data='spt0348_cube.fits',
                  output='spt0348_rgb_astropy.png',
                  vmax_r=0.4 * 0.000553248,
                  vmax_g=0.3 * 0.00875461,
                  vmax_b=0.3 * 0.016697,
                  vmin_r=1.2 * -7.19859e-05,
                  vmin_g=1.2 * -0.000468956,
                  vmin_b=1.2 * -0.000726759)

###show the rgb image of SPT0348
#rgb = ap.FITSFigure('spt0348_cube_2d.fits')
##rgb.recenter(co.convDMS('3:48:42.312'), co.convHMS('-62:20:50.63'),width = 10.0/3600, height= 10.0/3600)
Exemplo n.º 25
0
cmd_args = parser.parse_args()
image_r = cmd_args.image_r + ".fits"
image_g = cmd_args.image_g + ".fits"
image_b = cmd_args.image_b + ".fits"

hdul_r = fits.open(image_r)
instrument_r = hdul_r[0].header['FILTER']
hdul_g = fits.open(image_g)
instrument_g = hdul_g[0].header['FILTER']
hdul_b = fits.open(image_b)
instrument_b = hdul_b[0].header['FILTER']

#aplpy.make_rgb_cube(['1000001-JPLUS-01485-v2_iSDSS_swp-crop.fits', '1000001-JPLUS-01485-v2_rSDSS_swp-crop.fits',
                     #'1000001-JPLUS-01485-v2_gSDSS_swp-crop.fits'], 'JPLUS_cube.fits')

aplpy.make_rgb_cube([image_r, image_g, image_b], image_r.replace('.fits', '_cube.fits'))

aplpy.make_rgb_image(image_r.replace('.fits', '_cube.fits'),
                              image_r.replace('.fits', '_rgb.png'),
                      vmin_r=cmd_args.vmin_r, vmax_r=cmd_args.vmax_r, vmin_g=cmd_args.vmin_g,
                                                      vmax_g=cmd_args.vmax_g, vmin_b=cmd_args.vmin_b, vmax_b=cmd_args.vmax_b)

#aplpy.make_rgb_image('JPLUS_cube.fits','JPLUS_linear.png')
#hdul = fits.open('JPLUS_cube_2d.fits')
# aplpy.make_rgb_image('JPLUS_cube.fits','JPLUS_rgb.png',
#                       stretch_r='arcsinh', stretch_g='arcsinh',
#                       stretch_b='arcsinh')


# With the mask regions, the file may not exist
position = cmd_args.position + ".reg"
red_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_red73to130_masked_cutoute2e.fits'
redhead.update(cutout_red.wcs.to_header())
red_fits_co = fits.PrimaryHDU(data=cutout_red.data, header=redhead)
red_fits_co.writeto(red_fits_cutoute2e_fn, clobber=True)

blue_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_blue0to45_masked_cutoute2e.fits'
bluehead.update(cutout_blue.wcs.to_header())
blue_fits_co = fits.PrimaryHDU(data=cutout_blue.data, header=bluehead)
blue_fits_co.writeto(blue_fits_cutoute2e_fn, clobber=True)


rgb_cube_fits = 'e2e_outflow_co_redblue_cycle3green.fits'
if not os.path.exists(rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube([red_fits_cutoute2e_fn, e2_green_fits, blue_fits_cutoute2e_fn], rgb_cube_fits)

rgb_cube_png = rgb_cube_fits[:-5]+"_auto.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=6.5,
                              vmax_r=7.0,
                              vmin_g=0.0001,
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5]+"_loggreen.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=6.5,
                              vmax_r=7.0,
                              vmin_g=0.0001,
Exemplo n.º 27
0
gc = aplpy.FITSFigure('j9cv49010_drz.fits',north=True)
gc.show_grayscale(invert=False)
gc.add_scalebar(0.000562,color='white')
gc.scalebar.set_corner('top left')
gc.scalebar.set_label('1kpc')
gc.show_contour(contour,levels=levels,colors=['white','green','yellow','orange','red'])
gc.show_contour(contour1,levels=levels,colors=['white','green','yellow','orange','red'])
gc.axis_labels.hide()
gc.tick_labels.hide()
gc.save('test.png')
'''
# files1=['icom15030_drz.fits','j9cv49020_drz.fits','j9cv49010_drz.fits']
# aplpy.make_rgb_cube(files1,'hst_combine.fits')
# aplpy.make_rgb_image('test2_cube.fits','test_cube.png')

'''
files1=['icom15030_drz.fits','j9cv49020_drz.fits','j9cv49010_drz.fits']
files=['j9cv49020_drz.fits','j9cv49010_drz.fits','u6dw6201r_drz.fits']

def isolate_image_extension(fits_file, extension):
    header = fits.getheader(fits_file, extension)
    data = fits.getdata(fits_file, extension)
    fits.writeto('%s_image.fits' % fits_file.rstrip('.fits'), data, header)

for i in range(len(files)):
    files[i]=files[i].replace('.fits','_image.fits')

aplpy.make_rgb_cube(files,output='test_uv'+'_cube.fits',north=True)
aplpy.make_rgb_image('test_uv'+'_cube.fits','test_uv_cube.png')

Exemplo n.º 28
0
input_fits_image_band1 = './input/bootes1_ks_2h_20160228_astro_2MASS_0p248rms.fits'
input_fits_image_band2 = './input/bootes1_j_1h12min_20160226_astro_2MASS_0p182rms.fits'
input_fits_image_band3 = './input/bootes1_h_42min_20160226_astro_2MASS_0p220rms.fits'
input_fits_image_band4 = './input/Bootes1_cutout_herschel_250.fits'
#input_fits_image_band5='./input/G12v230_IRAC_Mosaic_36.fits'
#input_fits_image_band6='./input/G12v230_IRAC_Mosaic_45.fits'

band4_present = 1  #=================================================================1:yes 0:no (I band)
band5_present = 1  #=================================================================1:yes 0:no (3.6 band)
band6_present = 1  #=================================================================1:yes 0:no (4.5 band)

#montage.mSubimage(input_fits_image_band5, './G12_3p6_trimmed.fits', ra=, dec=, xsize=0.0023)

aplpy.make_rgb_cube(
    [input_fits_image_band1, input_fits_image_band3, input_fits_image_band2],
    'Bootes1_cube.fits')  #R, G, B
aplpy.make_rgb_image('Bootes1_cube.fits',
                     'Bootes1_cube.png',
                     vmin_g=-20.0,
                     vmin_r=-10.0,
                     vmin_b=-10.0)
#aplpy.make_rgb_image('NGP7_cube.fits','NGP7_cube.png', vmin_b=-30.0, vmax_b=3000.0, vmax_r=73.0)
#aplpy.make_rgb_image('G12_JHK_cube.fits', 'G12_JHK_cube.png', pmin_r=0., pmax_r=80., pmin_g=0., pmax_g=80., pmin_b=0., pmax_b=80.)

rgb_image = aplpy.FITSFigure('./Bootes1_cube_2d.fits')
rgb_image.show_rgb('Bootes1_cube.png')
rgb_image.show_contour(input_fits_image_band4,
                       levels=5,
                       colors='white',
                       linewidths=0.5)
red_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_red73to130_masked_cutoute2e.fits'
redhead.update(cutout_red.wcs.to_header())
red_fits_co = fits.PrimaryHDU(data=cutout_red.data, header=redhead)
red_fits_co.writeto(red_fits_cutoute2e_fn, clobber=True)

blue_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_blue0to45_masked_cutoute2e.fits'
bluehead.update(cutout_blue.wcs.to_header())
blue_fits_co = fits.PrimaryHDU(data=cutout_blue.data, header=bluehead)
blue_fits_co.writeto(blue_fits_cutoute2e_fn, clobber=True)

rgb_cube_fits = 'e2e_outflow_co_redblue_cycle3green.fits'
if not os.path.exists(rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube(
        [red_fits_cutoute2e_fn, e2_green_fits, blue_fits_cutoute2e_fn],
        rgb_cube_fits)

rgb_cube_png = rgb_cube_fits[:-5] + "_auto.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=6.5,
                              vmax_r=7.0,
                              vmin_g=0.0001,
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_loggreen.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              vmax_g=0.017,
import aplpy

# Convert all images to common projection
aplpy.make_rgb_cube(['m1.fits', 'i3.fits', 'i2.fits'], 'rgb.fits')

# Make 3-color image
aplpy.make_rgb_image('rgb.fits', 'rgb.png', vmin_r=20, vmax_r=400,
                     vmin_g=0, vmax_g=150, vmin_b=-2,vmax_b=50)

# Create a new figure
f = aplpy.FITSFigure('rgb_2d.fits')

# Show the RGB image
f.show_rgb('rgb.png')

# Add contours
f.show_contour('sc.fits', cmap='gist_heat', levels=[0.2,0.4,0.6,0.8,1.0])

# Overlay a grid
f.add_grid()
f.grid.set_alpha(0.5)

# Save image
f.save('plot.png')
Exemplo n.º 31
0
    default=None,
    help="""Set maximum brightness directly - overrides maxfactor - b""")

parser.add_argument("--debug",
                    action="store_true",
                    help="Print out verbose debugging info")

cmd_args = parser.parse_args()
image_r = cmd_args.image_r + ".fits"
image_g = cmd_args.image_g + ".fits"
image_b = cmd_args.image_b + ".fits"

#aplpy.make_rgb_cube(['1000001-JPLUS-01485-v2_iSDSS_swp-crop.fits', '1000001-JPLUS-01485-v2_rSDSS_swp-crop.fits',
#'1000001-JPLUS-01485-v2_gSDSS_swp-crop.fits'], 'JPLUS_cube.fits')

aplpy.make_rgb_cube([image_r, image_g, image_b], 'JPLUS_cube.fits')

aplpy.make_rgb_image('JPLUS_cube.fits',
                     'JPLUS_rgb.png',
                     vmin_r=cmd_args.vmin_r,
                     vmax_r=cmd_args.vmax_r,
                     vmin_g=cmd_args.vmin_g,
                     vmax_g=cmd_args.vmax_g,
                     vmin_b=cmd_args.vmin_b,
                     vmax_b=cmd_args.vmax_b)

#aplpy.make_rgb_image('JPLUS_cube.fits','JPLUS_linear.png')
#hdul = fits.open('JPLUS_cube_2d.fits')
# aplpy.make_rgb_image('JPLUS_cube.fits','JPLUS_rgb.png',
#                       stretch_r='arcsinh', stretch_g='arcsinh',
#                       stretch_b='arcsinh')
Exemplo n.º 32
0
    dec_0 = sourList['dec'][isour]
    coor = coords.SkyCoord(ra_0, dec_0, frame='icrs', unit=(u.deg, u.deg))
    ra_0 = coor.fk5.ra.deg
    dec_0 = coor.fk5.dec.deg
    c1 = coords.SkyCoord(ra_0, dec_0, frame='fk5', unit=(u.deg, u.deg))
    c2 = coords.SkyCoord(ra_0, dec_0 + 0.01, frame='fk5', unit=(u.deg, u.deg))
    c1G = c1.galactic
    ang = c1G.position_angle(c2.galactic).deg
    pa = paG + 90 - ang
    #radi = sourList['amaj'][isour] / 3600.0 / 2

    ap.make_rgb_cube([
        iracDir + sour_name + '/' + sour_name + '_I4.fits',
        iracDir + sour_name + '/' + sour_name + '_I2.fits',
        iracDir + sour_name + '/' + sour_name + '_I1.fits'
    ],
                     iracDir + sour_name + '/' + sour_name +
                     'Spitzer_cube.fits',
                     system='EQUJ',
                     north='Ture')

    ap.make_rgb_image(
        iracDir + sour_name + '/' + sour_name + 'Spitzer_cube.fits',
        iracDir + sour_name + '/' + sour_name + '_Spitzer_rgb.png',
        pmin_r=0.5,
        pmax_r=99.6,
        pmin_g=0.5,
        pmax_g=99.6,
        pmin_b=0.5,
        pmax_b=99.6,
        stretch_r='log',
Exemplo n.º 33
0
def make_RGBplot(fns, ofn, stretch = 'linear', 
                 plims = [None, None, None, None, None, None], 
                 vlims = [None, None, None, None, None, None],
                 title = None,
                 scalebar = None,
                ):
    '''Creates an RGB image from three fits files.
    
    :Args:
        fn: list strings
            The filename (+path!) fo the  3 fits file to display (in R, G and B orders).
        ofn: string
            The filneame (+path) of the output file.
        stretch: string [default: 'log']
                 The stretch to apply to the data, e.g. 'linear', 'log', 'arcsinh'.
        plims: list of floats [default: [None, None, None, None, None, None]]
               The limiting percentiles for the plot, as 
               [pmin_r, pmax_r, pmin_g, pmax_g, pmin_b, pmax_b]
        vlims: list of floats [default: [None, None, None, None, None, None]]
               The limtiing values for the plot (superseeds plims), as
               [vmin_r, vmax_r, vmin_g, vmax_g, vmin_b, vmax_b]
        scalebar: list [default: None]
            If set, adds a scale bar to the plot. Format: [lenght arcsec, length kpc, loc]    

    :Returns:
        out: True
             Always.
    :Notes:
        This function absolutely requires WCS coordinates, and a 2-D array.
    '''  
      
    # First, make an RGB cube
    fn_RGB = os.path.join('.','RGB_tmp_cube.fits')
    aplpy.make_rgb_cube(fns, fn_RGB)
                          
    # And an RGB image
    fn_RGB_im = os.path.join('.','RGB_tmp_im.png')
    aplpy.make_rgb_image(fn_RGB, fn_RGB_im, 
                         stretch_r=stretch,
                         stretch_g=stretch,
                         stretch_b=stretch,
                         vmin_r = vlims[0], 
                         vmin_g = vlims[2], 
                         vmin_b = vlims[4],
                         vmax_r = vlims[1], 
                         vmax_g = vlims[3], 
                         vmax_b = vlims[5], 
                         pmin_r = plims[0],
                         pmax_r = plims[1],
                         pmin_g = plims[2],
                         pmax_g = plims[3],
                         pmin_b = plims[4],
                         pmax_b = plims[5],
                         embed_avm_tags = False, make_nans_transparent=True)

    # Plot the RGB image using the 2d image to indicate the projection
    plt.close(1)
    fig1 = plt.figure(1, figsize=(10,9))

    fn_RGB_2d = os.path.join('.','RGB_tmp_cube_2d.fits')
    ax1 = aplpy.FITSFigure(fn_RGB_2d, figure=fig1)
    ax1.show_rgb(fn_RGB_im, interpolation='nearest')

    ax1.set_tick_color('k')
 
    if not(title is None):
        ax1.set_title(title, y=1.025)
 
    ax1.add_grid()
    # Make it look pretty
    ax1.grid.set_color('k')
    ax1.grid.set_linestyle('dotted')
    ax1.set_nan_color((0.5,0.5,0.5))
    ax1._ax1.set_axis_bgcolor((0.5, 0.5, 0.5))

     # Do I want to add a scalebar ?
    if not(scalebar is None):
        show_scale(ax1, scale_length = scalebar[:2], scale_loc = scalebar[2])

    # Make it look pretty
    ax1.set_axis_labels(ylabel='Dec. (J2000)')
    ax1.set_axis_labels(xlabel='R.A. (J2000)')
    ax1.tick_labels.set_xformat('hh:mm:ss')
    ax1.tick_labels.set_yformat('dd:mm:ss')
    
    # Save it
    fig1.savefig(ofn, bbox_inches='tight')
    
    # And remember to delete all the temporary files
    for f in [fn_RGB_im, fn_RGB_2d, fn_RGB]:
        os.remove(f)    
        
    return True
Exemplo n.º 34
0
from astropy import units as u
import pylab as pl
from spectral_cube import SpectralCube
import aplpy
import os
import paths

green_fits = '/Users/adam/work/w51/paper_w51_evla/data/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits'
blue_fits = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_blue0to45_masked.fits'
red_fits = '/Users/adam/work/w51/alma/FITS/moments/w51_12co2-1_red73to130_masked.fits'
rgb_cube_fits = 'outflow_co_redblue_kucont_green.fits'

if not os.path.exists(rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube([red_fits, green_fits, blue_fits], rgb_cube_fits)

rgb_cube_png = rgb_cube_fits[:-5] + "_auto.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_loggreen.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              stretch_g='log',
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_asinhgreen.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              stretch_g='arcsinh',
Exemplo n.º 35
0
red_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_LB_SiO_red74to118_masked_cutoute2e.fits'
redhead.update(cutout_red.wcs.to_header())
red_fits_co = fits.PrimaryHDU(data=cutout_red.data, header=redhead)
red_fits_co.writeto(red_fits_cutoute2e_fn, clobber=True)

blue_fits_cutoute2e_fn = '/Users/adam/work/w51/alma/FITS/moments/w51_LB_SiO_bluem32to55_masked_cutoute2e.fits'
bluehead.update(cutout_blue.wcs.to_header())
blue_fits_co = fits.PrimaryHDU(data=cutout_blue.data, header=bluehead)
blue_fits_co.writeto(blue_fits_cutoute2e_fn, clobber=True)


e2_rgb_cube_fits = 'e2e_outflow_SiO_redblue_cycle3green.fits'
if not os.path.exists(e2_rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube([red_fits_cutoute2e_fn, e2_green_fits, blue_fits_cutoute2e_fn], e2_rgb_cube_fits)

rgb_cube_png = e2_rgb_cube_fits[:-5]+"_auto.png"
rgb_im = aplpy.make_rgb_image(data=e2_rgb_cube_fits, output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=0.3,
                              vmax_r=0.6,
                              vmin_g=0.0001,
                              embed_avm_tags=True)

rgb_cube_png = e2_rgb_cube_fits[:-5]+"_loggreen.png"
rgb_im = aplpy.make_rgb_image(data=e2_rgb_cube_fits, output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=0.3,
                              vmax_r=0.6,
                              vmin_g=0.0001,
Exemplo n.º 36
0
SDOM_ZP_V = np.std(ZP_V, axis=0) / np.sqrt(5)
mean_SDOM_ZP_V = np.mean(SDOM_ZP_V) / np.sqrt(3)

#ZP in V filter is 21.68807 +/- 0.0058

#################

#################

##################  RBG IMAGING ########################

#################

aplpy.make_rgb_cube([
    dir + '/Data_r/mosaic_r/mosaic.fits', dir + '/Data_v/mosaic_v/mosaic.fits',
    dir + '/Data_b/mosaic_b/mosaic.fits'
], dir + '/rgb_cube.fits')

aplpy.make_rgb_image(dir + '/rgb_cube.fits',
                     dir + '/cluster_rgb.png',
                     embed_avm_tags=False)

fig = aplpy.FITSFigure(dir + '/rgb_cube_2d.fits')
fig.show_rgb(dir + '/cluster_rgb.png')

fig.add_grid()
fig.grid.set_linestyle('dotted')

#############  HR Diagram ################

mosaic_area_b = fits.getdata(dir + '/Data_b/mosaic_b/mosaic_area.fits')
def zoomfigure(
    target=e2e,
    targetname="e2e",
    radius=7.5 * u.arcsec,
    cutout="e2e8",
    zoom_radius=3 * u.arcsec,
    tick_spacing=1.8 * u.arcsec,
):

    fn = paths.dpath("merge/cutouts/W51_b6_7M_12M.HNCO10010-909.image.pbcor_{0}cutout.fits".format(cutout))
    m0hnco = get_mom0(fn, iterate=False)

    cutout_cont = Cutout2D(cont_fits[0].data, target, radius, wcs=wcs.WCS(cont_fits[0].header))
    cutout_ch3oh = Cutout2D(m0ch3oh.value, target, radius, wcs=wcs.WCS(m0ch3oh.header))
    cutout_hnco = Cutout2D(m0hnco.value, target, radius, wcs=wcs.WCS(m0hnco.header))

    cont_fits_cutout = fits.PrimaryHDU(data=cutout_cont.data, header=cutout_cont.wcs.to_header())
    ch3oh_fits_cutout = fits.PrimaryHDU(data=cutout_ch3oh.data, header=cutout_ch3oh.wcs.to_header())
    hnco_fits_cutout = fits.PrimaryHDU(data=cutout_hnco.data, header=cutout_hnco.wcs.to_header())
    cont_fits_fn = "rgb/continuum_{0}_cutout.fits".format(targetname)
    hnco_fits_fn = "rgb/hnco_{0}_cutout.fits".format(targetname)
    ch3oh_fits_fn = "rgb/ch3oh_{0}_cutout.fits".format(targetname)
    cont_fits_cutout.writeto(cont_fits_fn, clobber=True)
    ch3oh_fits_cutout.writeto(ch3oh_fits_fn, clobber=True)
    hnco_fits_cutout.writeto(hnco_fits_fn, clobber=True)

    rgb_cube_fits = "{0}_ch3oh_hnco_cont.fits".format(targetname)
    if not os.path.exists(rgb_cube_fits):
        # does not return anything
        aplpy.make_rgb_cube([ch3oh_fits_fn, hnco_fits_fn, cont_fits_fn], rgb_cube_fits)

    rgb_cube_png = rgb_cube_fits[:-5] + "_auto.png"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png, embed_avm_tags=True)

    rgb_cube_png = rgb_cube_fits[:-5] + "_logcont.png"
    rgb_im = aplpy.make_rgb_image(
        data=rgb_cube_fits,
        output=rgb_cube_png,
        # vmin_b=0.005,
        # vmax_b=0.15,
        stretch_b="log",
        embed_avm_tags=True,
    )

    # rgb_cube_png = rgb_cube_fits[:-5]+"_asinhgreen.png"
    # rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
    #                              vmax_g=0.017,
    #                              vmax_b=6.5,
    #                              vmax_r=7.0,
    #                              vmin_g=0.0001,
    #                              stretch_g='arcsinh', 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.00075)
    F.recenter(target.ra.deg, target.dec.deg, radius=zoom_radius.to(u.deg).value)
    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.set_tick_xspacing(tick_spacing.to(u.deg).value)
    F.add_label(0.05, 0.95, "CH$_3$OH", relative=True, color="r", horizontalalignment="left")
    F.add_label(0.05, 0.91, "HNCO", relative=True, color="g", horizontalalignment="left")
    F.add_label(0.05, 0.87, "Continuum", relative=True, color="b", horizontalalignment="left")
    F.save(paths.fpath("rgb_zooms/W51{0}_ch3oh_hnco_continuum_aplpy.png".format(targetname)))
    F.save(paths.fpath("rgb_zooms/W51{0}_ch3oh_hnco_continuum_aplpy.pdf".format(targetname)))

    F.show_contour(
        paths.vpath("data/W51Ku_BDarray_continuum_2048_both_uniform.hires.clean.image.fits"),
        levels=np.array([0.0015, 0.0045, 0.0135, 0.0270, 0.054, 0.108]) * 1.25,
        colors=["w"] * 7,
        layer="evla_cont",
    )
    F.save(paths.fpath("rgb_zooms/W51{0}_ch3oh_hnco_continuum_aplpy_kucontours.png".format(targetname)))
    F.save(paths.fpath("rgb_zooms/W51{0}_ch3oh_hnco_continuum_aplpy_kucontours.pdf".format(targetname)))
Exemplo n.º 38
0
import aplpy

# Reproject all images to same projection (requires Montage and
# python-montage)
aplpy.make_rgb_cube(["data/2MASS_k.fits.gz", "data/2MASS_h.fits.gz", "data/2MASS_j.fits.gz"], "2MASS_cube.fits")

# Make an RGB image with embedded AVM metadata containing the WCS information
# (requires PyAVM). This function takes many arguments to control levels and
# stretch functions. See the full documentation for more details
aplpy.make_rgb_image("2MASS_cube.fits", "2MASS_rgb.png", embed_avm_tags=True)

# Make the plot using the RGB image directly
f = aplpy.FITSFigure("2MASS_rgb.png")
f.show_rgb()
f.save("make_rgb.png")
Exemplo n.º 39
0
         pmax_b=99.9,
         pmax_g=99.9999,
         redline=fnku,
         blueline='HC3N24-23',
         greenline='CH3OH422-312')
make_rgb('hc3n_ch3oh_ocs_rgb.fits',
         greenline='OCS18-17',
         redline='HC3N24-23',
         blueline='CH3OH422-312')

rgb_cube_fits = 'full_h2co_rgb.fits'
if not os.path.exists(rgb_cube_fits):
    # does not return anything
    aplpy.make_rgb_cube([
        fn303,
        fn321,
        fn322,
    ], rgb_cube_fits)

rgb_cube_png = rgb_cube_fits[:-5] + "_auto.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_setlevels.png"
rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits,
                              output=rgb_cube_png,
                              vmin_b=-0.005,
                              vmax_b=0.4,
                              vmin_g=-0.005,
                              vmax_g=0.4,
Exemplo n.º 40
0
"""

import aplpy
from pathlib import Path
import os
"""
SiO first ...
"""

os.chdir(
    '/Users/danielwalker/Dropbox/Papers_DB/Brick_core/SiO_13CO_figs/Moments_SiO/'
)

if Path('./rgb_cubes/SiO_29_42__43_56.fits').exists() == False:
    aplpy.make_rgb_cube([
        'SiO_mom0_43_to_56.fits', 'SiO_mom0_29_to_42.fits',
        'SiO_mom0_29_to_42.fits'
    ], './rgb_cubes/SiO_29_42__43_56.fits')
    aplpy.make_rgb_image('./rgb_cubes/SiO_29_42__43_56.fits',
                         './rgb_pngs/SiO_29_42__43_56.png',
                         pmin_r=45,
                         pmax_r=100,
                         pmin_g=80,
                         pmax_g=100,
                         pmin_b=16,
                         pmax_b=99.9)

if Path('./rgb_cubes/SiO_29_36__23_29__16_22.fits').exists() == False:
    aplpy.make_rgb_cube([
        'SiO_mom0_29_to_36.fits', 'SiO_mom0_23_to_29.fits',
        'SiO_mom0_16_to_22.fits'
    ], './rgb_cubes/SiO_29_36__23_29__16_22.fits')
Exemplo n.º 41
0
def make_RGBplot(
    fns,
    ofn,
    stretch='linear',
    plims=[None, None, None, None, None, None],
    vlims=[None, None, None, None, None, None],
    title=None,
    scalebar=None,
):
    '''Creates an RGB image from three fits files.
    
    :Args:
        fn: list strings
            The filename (+path!) fo the  3 fits file to display (in R, G and B orders).
        ofn: string
            The filneame (+path) of the output file.
        stretch: string [default: 'log']
                 The stretch to apply to the data, e.g. 'linear', 'log', 'arcsinh'.
        plims: list of floats [default: [None, None, None, None, None, None]]
               The limiting percentiles for the plot, as 
               [pmin_r, pmax_r, pmin_g, pmax_g, pmin_b, pmax_b]
        vlims: list of floats [default: [None, None, None, None, None, None]]
               The limtiing values for the plot (superseeds plims), as
               [vmin_r, vmax_r, vmin_g, vmax_g, vmin_b, vmax_b]
        scalebar: list [default: None]
            If set, adds a scale bar to the plot. Format: [lenght arcsec, length kpc, loc]    

    :Returns:
        out: True
             Always.
    :Notes:
        This function absolutely requires WCS coordinates, and a 2-D array.
    '''

    # First, make an RGB cube
    fn_RGB = os.path.join('.', 'RGB_tmp_cube.fits')
    aplpy.make_rgb_cube(fns, fn_RGB)

    # And an RGB image
    fn_RGB_im = os.path.join('.', 'RGB_tmp_im.png')
    aplpy.make_rgb_image(fn_RGB,
                         fn_RGB_im,
                         stretch_r=stretch,
                         stretch_g=stretch,
                         stretch_b=stretch,
                         vmin_r=vlims[0],
                         vmin_g=vlims[2],
                         vmin_b=vlims[4],
                         vmax_r=vlims[1],
                         vmax_g=vlims[3],
                         vmax_b=vlims[5],
                         pmin_r=plims[0],
                         pmax_r=plims[1],
                         pmin_g=plims[2],
                         pmax_g=plims[3],
                         pmin_b=plims[4],
                         pmax_b=plims[5],
                         embed_avm_tags=False,
                         make_nans_transparent=True)

    # Plot the RGB image using the 2d image to indicate the projection
    plt.close(1)
    fig1 = plt.figure(1, figsize=(10, 9))

    fn_RGB_2d = os.path.join('.', 'RGB_tmp_cube_2d.fits')
    ax1 = aplpy.FITSFigure(fn_RGB_2d, figure=fig1)
    ax1.show_rgb(fn_RGB_im, interpolation='nearest')

    ax1.set_tick_color('k')

    if not (title is None):
        ax1.set_title(title, y=1.025)

    ax1.add_grid()
    # Make it look pretty
    ax1.grid.set_color('k')
    ax1.grid.set_linestyle('dotted')
    ax1.set_nan_color((0.5, 0.5, 0.5))
    ax1._ax1.set_axis_bgcolor((0.5, 0.5, 0.5))

    # Do I want to add a scalebar ?
    if not (scalebar is None):
        show_scale(ax1, scale_length=scalebar[:2], scale_loc=scalebar[2])

    # Make it look pretty
    ax1.set_axis_labels(ylabel='Dec. (J2000)')
    ax1.set_axis_labels(xlabel='R.A. (J2000)')
    ax1.tick_labels.set_xformat('hh:mm:ss')
    ax1.tick_labels.set_yformat('dd:mm:ss')

    # Save it
    fig1.savefig(ofn, bbox_inches='tight')

    # And remember to delete all the temporary files
    for f in [fn_RGB_im, fn_RGB_2d, fn_RGB]:
        os.remove(f)

    return True