def make_plot(model):

    # Extract model name
    model_name = os.path.basename(model).replace('_conv.fits', '').replace('external_', '')

    aplpy.make_rgb_image('models/external/external_%s_conv.fits' % model_name,
                         'models/external/external_%s.png' % model_name,
                         indices=[3, 1, 0],
                         vmax_r=4., stretch_r='sqrt',
                         vmax_g=3., stretch_g='sqrt',
                         vmax_b=3., stretch_b='sqrt')

    fig = plt.figure(figsize=(3.5, 3.5))
    ax = fig.add_axes([0.1, 0.1, 0.85, 0.85])
    ax.imshow(Image.open('models/external/external_%s.png' % model_name),
              extent=[-15, 15, -15, 15], origin='lower')

    for tick in ax.xaxis.get_ticklines():
        tick.set_color('white')

    for tick in ax.yaxis.get_ticklines():
        tick.set_color('white')

    for spine in ax.spines:
        ax.spines[spine].set_color('white')

    ax.set_xlabel('x [kpc]')
    ax.set_ylabel('y [kpc]')
    fig.savefig('plots/external_%s.png' % model_name, bbox_inches='tight')
    fig.savefig('plots/external_%s.eps' % model_name, bbox_inches='tight')
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 create_rgb_image(survey,ra,dec):
	"""
	Fetch the three FITS images for the given survey and combine
	into an RGB png.
	"""
	for i,band in enumerate(bands[survey][0]):
		fetch_image(band,ra,dec,output=survey+str(i)+'.fits')
	aplpy.make_rgb_image([survey+str(x)+'.fits' for x in range(3)],survey+'.png',\
			stretch_r='linear',stretch_g='linear',stretch_b='linear')
Exemplo n.º 5
0
def make_color_image(b, r, blue_filter, red_filter):
    print(b, r, blue_filter, red_filter)
    g = b.replace(blue_filter, 'GREEN')
    print('Making pseudo-green image {}'.format(g))
    shutil.copyfile(b, g)
    with fits.open(g, mode='update') as f:
        f[0].data = np.nanmean([fits.getdata(b), fits.getdata(r)], axis=0)
    outfile = g.split('GREEN')[0] + blue_filter + '_' + red_filter + '.png'
    aplpy.make_rgb_image([r,g,b], outfile, 
                         pmin_r=3, stretch_r='arcsinh', # pmax=99.75
                         pmin_g=3, stretch_g='arcsinh',
                         pmin_b=3, stretch_b='arcsinh')
Exemplo n.º 6
0
 def _create_rgb(line1_f_name, line2_f_name, cont_f_name, fqn):
     aplpy.make_rgb_image([line1_f_name, line2_f_name, cont_f_name],
                          fqn,
                          stretch_r='linear',
                          stretch_g='linear',
                          stretch_b='linear',
                          pmax_r=99.5,
                          pmax_g=99.5,
                          pmax_b=99.5,
                          pmin_r=50.0,
                          pmin_g=95.0,
                          pmin_b=50.0,
                          embed_avm_tags=False)
Exemplo n.º 7
0
def combine_rgb(instrument, dire):
    #noisy
    file_r = dire + "/image_noisy_%s_%s.fits" % (instrument.name,
                                                 instrument.rgb[0])
    file_g = dire + "/image_noisy_%s_%s.fits" % (instrument.name,
                                                 instrument.rgb[1])
    file_b = dire + "/image_noisy_%s_%s.fits" % (instrument.name,
                                                 instrument.rgb[2])
    cutout_r = pf.open(file_r)[0].data
    cutout_g = pf.open(file_g)[0].data
    cutout_b = pf.open(file_b)[0].data

    image_cube = np.zeros((3, cutout_r.shape[0], cutout_r.shape[1]),
                          dtype=np.float32)
    image_cube[0, :, :] = cutout_r
    image_cube[1, :, :] = cutout_g
    image_cube[2, :, :] = cutout_b

    pf.writeto(dire + '/new.fits', image_cube, clobber=True)

    aplpy.make_rgb_image(
        dire + '/new.fits', dire + "/combined_rgb_noisy_%s_%s_%s_%s.png" %
        (instrument.name, instrument.rgb[0], instrument.rgb[1],
         instrument.rgb[2]))

    # no noise
    file_r = dire + "/image_%s_%s.fits" % (instrument.name, instrument.rgb[0])
    file_g = dire + "/image_%s_%s.fits" % (instrument.name, instrument.rgb[1])
    file_b = dire + "/image_%s_%s.fits" % (instrument.name, instrument.rgb[2])
    cutout_r = pf.open(file_r)[0].data
    cutout_g = pf.open(file_g)[0].data
    cutout_b = pf.open(file_b)[0].data

    image_cube = np.zeros((3, cutout_r.shape[0], cutout_r.shape[1]),
                          dtype=np.float32)
    image_cube[0, :, :] = cutout_r
    image_cube[1, :, :] = cutout_g
    image_cube[2, :, :] = cutout_b

    pf.writeto(dire + '/new.fits', image_cube, clobber=True)

    aplpy.make_rgb_image(
        dire + '/new.fits', dire + "/combined_rgb_%s_%s_%s_%s.png" %
        (instrument.name, instrument.rgb[0], instrument.rgb[1],
         instrument.rgb[2]))

    #Clean up
    cmd = "rm %s/new.fits" % (dire)
    run_shell_cmd(cmd)
Exemplo n.º 8
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.º 9
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.º 10
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.º 11
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.º 12
0
 def do_image(self,undone_image,contour_file=None,contour_levels=5,contour_color=None):
     """Make an image"""
     version = 4
     success = False
     print("Making an image for "+undone_image)
     print("Using files... "+str(self.images[undone_image]))
     
     cube_data = pyfits.getdata(self.filenames[self.images[undone_image][0]])
     z1_k,z2_k = zscale.zscale(np.nan_to_num(cube_data[0,...]))
     z1_h,z2_h = zscale.zscale(np.nan_to_num(cube_data[1,...]))
     z1_j,z2_j = zscale.zscale(np.nan_to_num(cube_data[2,...]))
     
     aplpy.make_rgb_image(self.filenames[self.images[undone_image][0]],
                         self.filenames[self.images[undone_image][0]].replace('.fits','_2d.png'),
                         vmin_r = z1_k,vmax_r = z2_k,vmin_g = z1_h, vmax_g = z2_h, vmin_b = z1_j, vmax_b = z2_j)
     gc = aplpy.FITSFigure(self.filenames[self.images[undone_image][0]].replace('.fits','_2d.fits'))
     gc.show_rgb(self.filenames[self.images[undone_image][0]].replace('.fits','_2d.png'))
     gc.tick_labels.set_xformat("dd.dd")  
     gc.tick_labels.set_yformat("dd.dd")
     #out_filename = self.filenames[undone_image].replace('.fits','.pdf')
     
     if contour_file:
         #gc.show_contour(contour_file,levels=contour_levels,colors="black",linewidths = 3.,smooth=3.,alpha=0.5)
         gc.show_contour(contour_file,levels=contour_levels,colors=contour_color,linewidths = 1.)
         #chunks = contour_file.split('_')
         #print(chunks)
         #linename = chunks[3]
         #moment_name = chunks[4][0:-5]
         #tag = "_"+linename+"_"+moment_name
         #print(tag)
         #out_filename = out_filename.replace('.pdf',tag+'.pdf')
         #self.add_labels(gc,undone_image,linename,moment_name = moment_name,color=contour_color)
     else:
         pass
         #self.add_labels(gc,undone_image)
         
     #gc.show_rectangles(self.apos,self.bpos,0.0625,0.0625,ec='w',lw=2,facecolor='none',zorder=1)
     #gc.show_ellipses(self.apos,self.bpos,self.awin*2,self.bwin*2,angle=self.twin,facecolor='none',ec='green',lw=2)
     
     #print(self.awin,self.bwin)
     success = True
     if success:
         self.report_success(undone_image,version)
     return(gc)
Exemplo n.º 13
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()
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,
                              stretch_g='log',
                              embed_avm_tags=True)

rgb_cube_png = rgb_cube_fits[:-5] + "_asinhgreen.png"
Exemplo n.º 15
0
targets =['S235','IRAS22198','NGC2071','CepE','L1206','IRAS22172','IRAS21391']
imglist = ['SOFIA37umarelative.fits','SOFIA19umarelative.fits','IRAC8umarelative.fits']
distance = {'S235':1800., 'IRAS22198':764., 'NGC2071':390., 'CepE':730., 'L1206':776., 'IRAS22172':2400., 'IRAS21391':750.}
beam = [2.0,3.3,3.5]


i = 0
for y in [0.29,0.05]:  
    for x in [0.03,0.27,0.51,0.75]:
        if i == 7:
            break
        target = targets[i]
        #os.system('cd '+name+'/Rebinned')
        os.chdir('/Users/cici/Desktop/research/SOFIA/SOMA III/'+target)
        #aplpy.make_rgb_cube(imglist,'thecube.fits')
        aplpy.make_rgb_image('thecube.fits',target+'_rgb.eps',stretch_r='arcsinh', stretch_g='arcsinh',stretch_b='arcsinh',vmin_r=1e-2,vmin_g=1e-2,vmin_b=1e-2,vmax_r=1., vmax_g=1.,vmax_b=1.)   
        #aplpy.make_rgb_image('thecube.fits',target+'_rgb.eps',stretch_r='power',stretch_g='power',stretch_b='power',vmin_r=1e-2,vmin_g=1e-2,vmin_b=1e-2,vmax_r=1.0,vmax_g=1.0,vmax_b=1.0,exponent_r =0.5,exponent_g=0.5,exponent_b=0.5)   
        f = aplpy.FITSFigure('thecube_2d.fits', subplot=[x,y,0.21,0.21],figure=fig)
        f.show_rgb(target+'_rgb.eps')
        
        
        # show the scalebar
        startpoint = f.pixel2world(900,60)
        scalebar = np.array(([startpoint[0],startpoint[0]-10./3600.],[startpoint[1],startpoint[1]]))
        f.show_lines([scalebar],edgecolor='w',linewidths=2.0,zorder=10)
        fig.text(x+0.195,y+0.015,'10"',color='w',size='large')
        length = 10./3600.*np.pi/180.*distance[target]
        fig.text(x+0.19,y+0.006,'%0.2f'%length+'pc',color='w',size='large')
        
        # Beam
        f.show_circles(f.pixel2world(50,180)[0],f.pixel2world(50,180)[1],beam[0]/7200.,edgecolor='none',facecolor='blue')
Exemplo n.º 16
0
        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,
                         vmax_g=max_r,
                         vmin_b=min_g,
                         vmax_b=max_g)

    os.remove(images_gband_path + str(gal) + '_kids_g_sb.fits')
    os.remove(images_rband_path + str(gal) + '_kids_r_sb.fits')
    os.remove(images_iband_path + str(gal) + '_kids_i_sb.fits')
    os.remove(str(gal) + '_cube.fits')

    img = fits.open(str(gal) + "_cube_2d.fits")
    subfig = aplpy.FITSFigure(img, figure=fig, subplot=plotting_pos[cont_gal])
    subfig.set_axis_labels_size(20)
    subfig.set_axis_labels_weight("bold")
Exemplo n.º 17
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.º 18
0
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)

rgb_image.recenter(218.5713, 35.546113, radius=0.032)
#rgb_image.recenter(176.65903,-0.19764512, width=0.066, height=0.07)
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,
                              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,
                              vmax_g=0.017,
                              vmax_b=6.5,
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,
                              stretch_g='log', embed_avm_tags=True)

rgb_cube_png = e2_rgb_cube_fits[:-5]+"_asinhgreen.png"
rgb_im = aplpy.make_rgb_image(data=e2_rgb_cube_fits, output=rgb_cube_png,
                              vmax_g=0.017,
                              vmax_b=0.5,
                                      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"
    rgb_im = aplpy.make_rgb_image(data=rgb_cube_fits, output=rgb_cube_png,
                                  stretch_g='arcsinh', embed_avm_tags=True)

    naco_green = '/Users/adam/work/w51/paper_w51_evla/data/naco_Kband_W51.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.º 23
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.º 24
0
#!/usr/bin/python
import astropy.io.fits as pyfits
import aplpy
import numpy as np

#cutout_r=pyfits.open("./testimage_noisy_WFIRST_F184.fits")[0].data
#cutout_g=pyfits.open("./testimage_noisy_WFIRST_H158.fits")[0].data
#cutout_b=pyfits.open("./testimage_noisy_WFIRST_J129.fits")[0].data

cutout_r = pyfits.open("./old_fits/testimage_noisy_jwst_F115W.fits")[0].data
cutout_g = pyfits.open("./old_fits/testimage_noisy_jwst_F090W.fits")[0].data
cutout_b = pyfits.open("./old_fits/testimage_noisy_jwst_F070W.fits")[0].data

image_cube = np.zeros((3, cutout_r.shape[0], cutout_r.shape[1]),
                      dtype=np.float32)
image_cube[0, :, :] = cutout_r
image_cube[1, :, :] = cutout_g
image_cube[2, :, :] = cutout_b

pyfits.writeto('new.fits', image_cube, clobber=True)

aplpy.make_rgb_image('new.fits', "color_JWST.png")
Exemplo n.º 25
0
# ax=fig.add_subplot(111,projection=w)
# plt.imshow(rgb_default,vmin=0,vmax=1)
# lon = ax.coords[0]
# lat = ax.coords[1]
# lon.set_major_formatter('hh:mm:ss')
# plt.show()

# aplpy.make_rgb_image('test_uv'+'_cube.fits','test_uv_cube.png',vmin_r=0,vmin_g=0, vmin_b=0,stretch_r='arcsinh',stretch_g='arcsinh',stretch_b='arcsinh',vmid_g=0.1,vmid_b=0.003)


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'+'_cube1.fits')
aplpy.make_rgb_image('test_uv'+'_cube.fits','test_uv_cube.png',vmin_r=0,vmin_g=0, vmin_b=0,stretch_r='arcsinh',stretch_g='arcsinh',stretch_b='arcsinh')
'''

'''
isolate_image_extension('u6dw6201r_drz.fits',1)
'''

aplpy.make_rgb_image('test_uv_cube.fits','test_uv_cube.png',vmin_r=0,vmin_g=0, vmin_b=0,stretch_r='arcsinh',stretch_g='arcsinh',stretch_b='arcsinh')
Exemplo n.º 26
0
    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,
)

rgb_cube_fits = "c18o_h2co_ku_rgb.fits"
Exemplo n.º 27
0
input_fits_image_band4 = './input/G12_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],
    'G12_cube.fits')  #R, G, B
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_cube.fits','G12_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('./G12_cube_2d.fits')
rgb_image.show_rgb('G12_cube.png')
rgb_image.show_contour(input_fits_image_band4,
                       levels=5,
                       colors='white',
                       linewidths=0.5)

rgb_image.recenter(176.65864, -0.19688142, radius=0.035)
#rgb_image.recenter(176.65903,-0.19764512, width=0.066, height=0.07)
Exemplo n.º 28
0
#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)
#rgb.show_colorscale(cmap='cubehelix', vmax=0.0005, vmin=-0.000537558, interpolation='nearest')
#rgb.save('test.png')
##rgb.show_rgb()
Exemplo n.º 29
0
         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,
                              vmin_r=-0.005,
                              vmax_r=0.4,
                              embed_avm_tags=True)

rgb_cube_fits = 'c18o_h2co_ku_rgb.fits'
if not os.path.exists(rgb_cube_fits):
Exemplo n.º 30
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.º 31
0
def FitsRGB(ra, dec, rad_arcsec, in_paths, out_dir, pmin=False, pmax=False, stretch='log', keep_temp=False):

    # Prepare storage list for paths, then loop over bands
    path_list = [''] * 3
    for b in range(len(path_list)):

        # If this band gives a single path for a specific file, record it
        if in_paths[b].__class__ == str:
            path_list[b] = in_paths[b]

        # Else if this band gives a list of paths (ie, an order of preference), find the first file that exists and record it
        elif hasattr(in_paths[b], '__iter__'):
            for path in in_paths[b]:
                if not os.path.exists(path):
                    continue
                else:
                    path_list[b] = path
                    break

    # Find which band's data has the smallest pixel size
    pix_width_arcsec = 3600
    for k in range(len(path_list)):
        temp_header = astropy.io.fits.getheader(path_list[k])
        temp_wcs = astropy.wcs.WCS(temp_header)
        temp_wcs_pix_matrix = temp_wcs.pixel_scale_matrix
        temp_pix_width_arcsec = 3600.0 * np.mean(np.abs(temp_wcs_pix_matrix[np.where(temp_wcs_pix_matrix!=0)]))
        if temp_pix_width_arcsec<pix_width_arcsec:
            pix_width_arcsec = temp_pix_width_arcsec

    # Loop over data, reprojecting to a common projection that uses the smallest pixel size
    path_zoomed_list = []
    for k in range(len(path_list)):
        path_zoomed_list.append(os.path.join(out_dir, 'RGB_Temp_'+str(k)+'.fits.gz'))
        FitsCutout(path_list[k], ra, dec, rad_arcsec=rad_arcsec, pix_width_arcsec=pix_width_arcsec, reproj=True, outfile=path_zoomed_list[k])

    # Extract pmin values
    if pmin == False:
        pass
    elif hasattr(pmin, '__iter__'):
        pmin_list = pmin
    elif isinstance(float(pmin), float):
        pmin_list = [pmin] * 3

    # Extract pmax values
    if pmax == False:
        pmax_list = [99.75, 99.75, 99.75]
    elif hasattr(pmax, '__iter__'):
        pmax_list = pmax
    elif isinstance(float(pmax), float):
        pmax_list = [pmax] * 3

    # Set up vmin and vmax storage lists, then loop over each band
    vmin_list = [0.0] * 3
    vmax_list = [0.0] * 3
    for k in range(len(path_list)):

        # Calculate band vmin
        vmin_phot = astropy.io.fits.getdata(path_list[k])
        if pmin == False:
            vmin_phot_clip = SigmaClip(vmin_phot, median=True, sigma_thresh=3.0, tolerance=0.0005)
            vmin_list[k] = vmin_phot_clip[1] + (1.75 * vmin_phot_clip[0])
        else:
            vmin_list[k] = np.percentile(Nanless(vmin_phot), pmin_list[k])

        # Calculate band vmax, making sure vmin and vmax end up in right order
        vmax_phot = astropy.io.fits.getdata(path_zoomed_list[k])
        vmax_list[k] = np.percentile(Nanless(vmax_phot), pmax_list[k])
        if vmax_list[k]<vmin_list[k]:
            vmin_list[k] = np.percentile(vmax_phot, pmax_list[k])
            vmax_list[k] = vmin_phot_clip[1] + (1.25 * vmin_phot_clip[0])
        if vmin_list[k]>vmax_list[k]:
            vmin_temp = vmin_list[k]
            vmin_list[k] = vmax_list[k]
            vmax_list[k] = vmin_temp

    # Extract stretch types
    if isinstance(stretch, str):
        stretch_list = [stretch] * 3
    elif hasattr(stretch, '__iter__'):
        stretch_list = stretch

    # Generate RGB image
    aplpy.make_rgb_image(path_zoomed_list,
                         os.path.join(out_dir, 'RGB.bmp'),
                         stretch_r=stretch_list[0], stretch_g=stretch_list[1], stretch_b=stretch_list[2],
                         vmin_r=vmin_list[0], vmin_g=vmin_list[1], vmin_b=vmin_list[2],
                         vmax_r=vmax_list[0], vmax_g=vmax_list[1], vmax_b=vmax_list[2])

    # Clean up temporary files
    if not keep_temp:
        [os.remove(path_zoomed) for path_zoomed in path_zoomed_list]
Exemplo n.º 32
0
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], 'NGP6_cube.fits')   #R, G, B
aplpy.make_rgb_image('NGP6_cube.fits','NGP6_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('./NGP6_cube_2d.fits')
rgb_image.show_rgb('NGP6_cube.png')
rgb_image.show_contour(input_fits_image_band4, levels=5, colors='white', linewidths=0.5)

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

rgb_image.add_scalebar(1.0/60.0)
rgb_image.scalebar.set_label("1'")
Exemplo n.º 33
0
#################

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

##################  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')
plt.figure(1)
plt.imshow(mosaic_area_b, origin='lower')
plt.xlabel('Pixels', fontsize=15)
plt.ylabel('Pixels', fontsize=15)
Exemplo n.º 34
0
				im_h_cube['RGB_'+stack_filter[j]]= ','.join(np.char.mod('%.2f', stack_rgb_limit[j,:]))

				plt.subplot(3,2,1+2*j+1)
				plt.bar(bin_edges[:-1], hist, width = bin_edges[1]-bin_edges[0], linewidth=0., log=True)
				plt.xlim(stack_rgb_limit[j,0], stack_rgb_limit[j,1])
				plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
				plt.title('Tile '+stack_tile[i]+' - '+stack_filter[j])
				plt.xlabel('Flux')
				plt.ylabel('Number count')

			else:
				print '\nNo valid pixels for filter '+stack_filter[j]

		print 'Updating the rgb cube file ', stack_rgb_file
		pyfits.writeto(stack_rgb_file, im_data_cube, header=im_h_cube, clobber=True)
	
		plt.tight_layout()
		plt.savefig(stack_dir+'/stack_tile'+stack_tile[i]+'_histogram_v'+stack_version+'.pdf')
		plt.close(fig)
	
		print "stack_rgb_limit: \n", stack_rgb_limit
		
		im_rgb_file=stack_rgb_file.replace('.fits','_asinh_v'+stack_version+'.jpg')
		print 'Creating RGB image file ', im_rgb_file
		aplpy.make_rgb_image(stack_rgb_file, im_rgb_file, stretch_r='arcsinh', stretch_g='arcsinh', stretch_b='arcsinh', vmin_r=stack_rgb_limit[0,0], vmin_g=stack_rgb_limit[1,0], vmin_b=stack_rgb_limit[2,0], vmax_r=stack_rgb_limit[0,1], vmax_g=stack_rgb_limit[1,1], vmax_b=stack_rgb_limit[2,1], vmid_r=-0.07, vmid_g=-0.07, vmid_b=-0.07, make_nans_transparent=True, embed_avm_tags=True)

		im_rgb_file=stack_rgb_file.replace('.fits','_linear_v'+stack_version+'.jpg')
		print 'Creating RGB image file ', im_rgb_file
		aplpy.make_rgb_image(stack_rgb_file, im_rgb_file, stretch_r='linear', stretch_g='linear', stretch_b='linear', vmin_r=stack_rgb_limit[0,0], vmin_g=stack_rgb_limit[1,0], vmin_b=stack_rgb_limit[2,0], vmax_r=stack_rgb_limit[0,1], vmax_g=stack_rgb_limit[1,1], vmax_b=stack_rgb_limit[2,1], make_nans_transparent=True, embed_avm_tags=True)

Exemplo n.º 35
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+'&')
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.º 37
0
from aplpy import FITSFigure, make_rgb_image
import os

'''
For proposal: 2016.1.00750.S
'''

path = "/media/eric/Data_3/NGC1313/"
fits_cube = os.path.join(path, "ngc1313_noao.fits")
fits_twod = os.path.join(path, "ngc1313_noao_2d.fits")
rgb_image = os.path.join(path, "ngc1313_noao_rgb.png")

# Make RGB image if it isn't there
if not os.path.exists(rgb_image):
    make_rgb_image(fits_cube, rgb_image)

fig = FITSFigure(fits_twod)
fig.show_rgb(rgb_image)
# fig.show_grayscale(invert=True)
# ALMA regions
fig.show_regions("ngc1313_targets.reg")
# Hubble ACS field outlines
fig.show_regions(os.path.join(path, "HST/final_mosaic/coverage_outline.reg"))
fig.hide_tick_labels()
fig.hide_xaxis_label()
fig.hide_yaxis_label()

# Should be zoomed in on before saving
# fig.save(os.path.join(path, "ngc1313_noao_field_overlays.png"))
Exemplo n.º 38
0
        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',
        stretch_g='log',
        stretch_b='log',
        embed_avm_tags=False)

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

    fb1 = ap.FITSFigure(iracDir + sour_name + '/' + sour_name + '_I4.fits',
                        figure=fig,
                        subplot=[0.1, 0.1, 0.2, 0.2],
                        aspect="auto")
    fb1.ticks.set_length(10)
    fb1.show_rgb(iracDir + sour_name + '/' + sour_name + '_Spitzer_rgb.png')
Exemplo n.º 39
0
# b = stretch(g)

# Flat Fielding RED
# do a Image registration OR ASTRO ALIGN ???
image = r
shifted = g
dx, dy, edx, edy = image_registration.chi2_shift(image,
                                                 shifted,
                                                 upsample_factor='auto')
g = shift.shiftnd(shifted, (dx, dy))

image = r
shifted = b
dx, dy, edx, edy = image_registration.chi2_shift(image,
                                                 shifted,
                                                 upsample_factor='auto')
b = shift.shiftnd(shifted, (dx, dy))

# saving as a fits
fits.writeto('M66_R.fits', r, header=h_r, overwrite=True)
fits.writeto('M66_G.fits', g, header=h_g, overwrite=True)
fits.writeto('M66_B.fits', b, header=h_b, overwrite=True)

############ Creating RGB Image
# aplpy.make_rgb_image(['data/M66-Blue.fts', 'data/M66-Green.fts',
#                      'data/M66-Red.fts'],
#                      output = 'M66_rgb.png')

aplpy.make_rgb_image(['M66_R.fits', 'M66_G.fits', 'M66_B.fits'],
                     output='M66_rgb.png')
Exemplo n.º 40
0
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',
                              embed_avm_tags=True)

naco_green = '/Users/adam/work/w51/paper_w51_evla/data/naco_Kband_W51.fits'
Exemplo n.º 41
0
    def do_image(self,
                 undone_image,
                 contour_file=None,
                 contour_levels=5,
                 contour_color=None):
        """Make an image"""
        version = 4
        success = False
        print("Making an image for " + undone_image)
        print("Using files... " + str(self.images[undone_image]))

        cube_data = pyfits.getdata(
            self.filenames[self.images[undone_image][0]])
        z1_k, z2_k = zscale.zscale(np.nan_to_num(cube_data[0, ...]))
        z1_h, z2_h = zscale.zscale(np.nan_to_num(cube_data[1, ...]))
        z1_j, z2_j = zscale.zscale(np.nan_to_num(cube_data[2, ...]))

        aplpy.make_rgb_image(
            self.filenames[self.images[undone_image][0]],
            self.filenames[self.images[undone_image][0]].replace(
                '.fits', '_2d.png'),
            vmin_r=z1_k,
            vmax_r=z2_k,
            vmin_g=z1_h,
            vmax_g=z2_h,
            vmin_b=z1_j,
            vmax_b=z2_j)
        gc = aplpy.FITSFigure(
            self.filenames[self.images[undone_image][0]].replace(
                '.fits', '_2d.fits'))
        gc.show_rgb(self.filenames[self.images[undone_image][0]].replace(
            '.fits', '_2d.png'))
        gc.tick_labels.set_xformat("dd.dd")
        gc.tick_labels.set_yformat("dd.dd")
        #out_filename = self.filenames[undone_image].replace('.fits','.pdf')

        if contour_file:
            #gc.show_contour(contour_file,levels=contour_levels,colors="black",linewidths = 3.,smooth=3.,alpha=0.5)
            gc.show_contour(contour_file,
                            levels=contour_levels,
                            colors=contour_color,
                            linewidths=1.)
            #chunks = contour_file.split('_')
            #print(chunks)
            #linename = chunks[3]
            #moment_name = chunks[4][0:-5]
            #tag = "_"+linename+"_"+moment_name
            #print(tag)
            #out_filename = out_filename.replace('.pdf',tag+'.pdf')
            #self.add_labels(gc,undone_image,linename,moment_name = moment_name,color=contour_color)
        else:
            pass
            #self.add_labels(gc,undone_image)

        #gc.show_rectangles(self.apos,self.bpos,0.0625,0.0625,ec='w',lw=2,facecolor='none',zorder=1)
        #gc.show_ellipses(self.apos,self.bpos,self.awin*2,self.bwin*2,angle=self.twin,facecolor='none',ec='green',lw=2)

        #print(self.awin,self.bwin)
        success = True
        if success:
            self.report_success(undone_image, version)
        return (gc)
Exemplo n.º 42
0
for agc in targets:
    folder = agc.lower()
    img_g = path+'/'+folder+'/'+agc+'_g.fits'
    img_i = path+'/'+folder+'/'+agc+'_i.fits'
      
    fits_g = fits.open(img_g)
    fits_i = fits.open(img_i)

    # first make the green channel from an average of the g and i images
    if not os.path.isfile(path+'/'+folder+'/'+agc+'_avg.fits'):
        newheader = fits_i[0].header
        newimage = (fits_g[0].data+fits_i[0].data)/2.0
        newhdu = fits.PrimaryHDU(data=newimage,header=newheader)
        newhdu.writeto(path+'/'+folder+'/'+agc+'_avg.fits') 
    # use aplpy to generate the actual png image  
    aplpy.make_rgb_image([img_i,path+'/'+folder+'/'+agc+'_avg.fits',img_g],path+'/'+folder+'/'+agc+'_rgb.png')
    if not os.path.isfile(path+'/'+folder+'/'+agc+'_rgb_thumb.png'):
        thumb_size = 1024,1024
        im = Image.open(path+'/'+folder+'/'+agc+'_rgb.png')
        im.thumbnail(thumb_size)
        im.save(path+'/'+folder+'/'+agc+'_rgb_thumb.png', "PNG")
# print os.listdir('.')         

# fig = mpl.figure(figsize=(10,10))

# f24 = aplpy.FITSFigure("agc268069/20130414T012307.1_AGC_268069_odi_g.7019.fits", hdu='OTA24.SCI', figure=fig, subplot=(3,3,1))
# f24.show_grayscale(vmin=145.0, vmax=285.0)
# f24.set_theme('publication')
# f24.frame.set_color('none')
# f24.axis_labels.hide()
# f24.tick_labels.hide()
Exemplo n.º 43
0
  pmin,pmax = 50.0,99.0
  stretch = 'arcsinh'
  mid = 100.0

#   aplpy.make_rgb_image([redfile,greenfile,bluefile],output,
#                        pmin_r=pmin, pmax_r=pmax, 
#                          stretch_r=stretch, vmid_r=mid, 
#                        pmin_g=pmin, pmax_g=pmax, 
#                          stretch_g=stretch, vmid_g=mid, 
#                        pmin_b=pmin, pmax_b=pmax, 
#                          stretch_b=stretch, vmid_b=mid, )
#   
  aplpy.make_rgb_image([redfile,greenfile,bluefile],output,
                       vmin_r=vmin_r, vmax_r=vmax_r, 
                         stretch_r=stretch, vmid_r=mid, 
                       vmin_g=vmin_g, vmax_g=vmax_g, 
                         stretch_g=stretch, vmid_g=mid, 
                       vmin_b=vmin_b, vmax_b=vmax_b, 
                         stretch_b=stretch, vmid_b=mid, )
  
  # See http://aplpy.github.com/documentation/api.html#rgb-images for
  # more information.
  
  if vb: print "Finished RGB image file:",output
              
  return

# ======================================================================

# If called as a script, the python variable __name__ will be set to 
# "__main__" - so test for this, and execute the main program if so.
Exemplo n.º 44
0
def coadd_rgb(name_red=None,
              name_green=None,
              name_blue=None,
              out=None,
              pmin=0.02,
              pmax=0.98,
              ra0=None,
              dec0=None,
              sr0=None,
              north=False,
              match=True):
    if ((not name_red or not posixpath.isfile(name_red))
            and (not name_green or not posixpath.isfile(name_green))
            and (not name_blue or not posixpath.isfile(name_blue))):

        print "Not enough frames to make three-color image!"
        return

    if not out:
        out = "rgb.jpg"

    fd, cube = tempfile.mkstemp(prefix='cube', suffix='.fits')
    os.close(fd)

    print "Co-adding three-color image: red=%s green=%s blue=%s" % (
        name_red, name_green, name_blue)

    if match:
        matched_red = blind_match(name_red)
        matched_green = blind_match(name_green)
        matched_blue = blind_match(name_blue)
    else:
        matched_red = make_temp_file(name_red)
        matched_green = make_temp_file(name_green)
        matched_blue = make_temp_file(name_blue)

    fix_fits_crop(matched_red)
    fix_fits_crop(matched_green)
    fix_fits_crop(matched_blue)

    if ra0 or dec0 or sr0:
        import montage_wrapper as montage
        montage.mSubimage(matched_red, matched_red, ra0, dec0, sr0)
        montage.mSubimage(matched_green, matched_green, ra0, dec0, sr0)
        montage.mSubimage(matched_blue, matched_blue, ra0, dec0, sr0)

    if match and (not matched_red or not matched_green or not matched_blue):
        print "Can't match input frames"
        return None

    make_rgb_cube([matched_red, matched_green, matched_blue],
                  cube,
                  north=north)
    make_rgb_image(cube,
                   out,
                   embed_avm_tags=False,
                   make_nans_transparent=True,
                   pmin_r=pmin * 100,
                   pmin_g=pmin * 100,
                   pmin_b=pmin * 100,
                   pmax_r=pmax * 100,
                   pmax_g=pmax * 100,
                   pmax_b=pmax * 100)

    os.unlink(cube)

    if matched_red:
        os.unlink(matched_red)
    if matched_green:
        os.unlink(matched_green)
    if matched_blue:
        os.unlink(matched_blue)

    if posixpath.isfile(out):
        print "Successfully created RGB image %s" % out
    else:
        out = None

    return out
Exemplo n.º 45
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.º 46
0
def show_overlay(lofarhdu,
                 opthdu,
                 ra,
                 dec,
                 size,
                 firsthdu=None,
                 vlasshdu=None,
                 rms_use=None,
                 bmaj=None,
                 bmin=None,
                 bpa=None,
                 title=None,
                 save_name=None,
                 plotpos=None,
                 block=True,
                 interactive=False,
                 plot_coords=True,
                 overlay_cat=None,
                 lw=1.0,
                 show_lofar=True,
                 no_labels=False,
                 show_grid=True,
                 overlay_region=None,
                 overlay_scale=1.0,
                 circle_radius=None,
                 coords_color='white',
                 coords_lw=1,
                 coords_ra=None,
                 coords_dec=None,
                 marker_ra=None,
                 marker_dec=None,
                 marker_color='white',
                 marker_lw=3,
                 noisethresh=1,
                 lofarlevel=2.0,
                 first_color='lightgreen',
                 vlass_color='salmon',
                 drlimit=500,
                 interactive_handler=None,
                 peak=None,
                 ellipse_color='red',
                 lw_ellipse=3,
                 ellipse_style='solid'):
    '''
    show_overlay: make an overlay using AplPY.
    lofarhdu: the LOFAR cutout to use for contours
    opthdu: the optical image to use (may be 2D image or RGB cube)
    ra, dec: position to use, in degrees
    size: size in arcseconds
    firsthdu: FIRST cutout to use for contours or None if not required
    vlasshdu: VLASS cutout to use for contours or None if not required
    rms_use: Use a particular LOFAR rms or None to compute it from cutout
    bmaj, bmin, bpa: Beam sizes to use or None to take from the headers
    title: title at the top of the plot or None for no title
    save_name: filename to save image as
    plotpos: list of RA, Dec to plot as markers
    block: if True, wait before exiting if not saving an image
    interactive: if True, allow interaction with the image
    plot_coords: plot a set of co-ordinates as a large cross
    overlay_cat: plot a catalogue (astropy Table) as a set of ellipses with BMaj, BMin, BPA, or None to disable
    lw: line width for contours in Matplotlib units
    show_lofar: if True, show the LOFAR contours
    no_labels: if True, don't produce co-ordinate labels
    show_grid: if True, show a co-ordinate grid
    overlay_region: overlay a ds9-style region if not None
    overlay_scale: scaling factor for catalogue in overlay_cat
    circle_radius: if not None, draw a circle of this radius around the image centre
    coords_color: colour for plot_coords
    coords_lw: line width for plot_coords
    coords_ra, coords_dec: use these co-ordinates for plot_coords
    marker_ra, marker_dec: old marker list specification; deprecated, use plotpos instead
    marker_color,marker_lw: attributes for markers
    noisethresh: scaling noise for the optical images (lower cutoff at mean + rms*noisethresh)
    lofarlevel: lowest LOFAR contour (units sigma)
    first_color: colour for FIRST contours
    vlass_color: colour for VLASS contours
    drlimit: dynamic range limit for LOFAR data
    interactive_handler: function to call for clicks on an interactive map
    peak: use this LOFAR flux density as the peak value; if None, calculate from the map
    ellipse_color: colour for the ellipses in overlay_cat: either a string or a list with entries for each ellipse
    lw_ellipse: line width for the ellipses; either a string or a list with entries for each ellipse
    ellipse_style: line style for the ellipses; either a string or a list with entries for each ellipse

    '''
    if lofarhdu is None:
        print 'LOFAR HDU is missing, not showing it'
        show_lofar = False
    try:
        from matplotlib.cbook import MatplotlibDeprecationWarning
        import warnings
        warnings.simplefilter('ignore', MatplotlibDeprecationWarning)
    except:
        print 'Cannot hide warnings'

    print '========== Doing overlay at', ra, dec, 'with size', size, '==========='
    print '========== Title is', title, '=========='

    if coords_ra is None:
        coords_ra = ra
        coords_dec = dec

    if show_lofar:
        if peak is None:
            lofarmax = np.nanmax(lofarhdu[0].data)
        else:
            print 'Using user-specified peak flux of', peak
            lofarmax = peak
        if rms_use is None:
            rms_use = find_noise_area(lofarhdu, ra, dec, size)[1]
            print 'Using LOFAR rms', rms_use
        print lofarmax / drlimit, rms_use * lofarlevel
        minlevel = max([lofarmax / drlimit, rms_use * lofarlevel])
        levels = minlevel * 2.0**np.linspace(0, 14, 30)

    hdu = opthdu

    if len(hdu[0].data.shape) > 2:
        # This is an RGB image. Try to do something sensible with it
        vmins = []
        for i in range(3):
            mean, noise, vmax = find_noise_area(hdu, ra, dec, size, channel=i)
            vmin = mean + noisethresh * noise
            vmins.append(vmin)
        aplpy.make_rgb_image(hdu.filename(),
                             'rgb.png',
                             stretch_r='log',
                             stretch_g='log',
                             stretch_b='log',
                             vmin_r=vmins[0],
                             vmin_g=vmins[1],
                             vmin_b=vmins[2])  # FILENAME NOT SAFE
        f = aplpy.FITSFigure('rgb.png', north=True)
        print 'centring on', ra, dec, size
        f.recenter(ra, dec, width=size, height=size)
        f.show_rgb()

    else:
        print 'I do not want to be here'
        mean, noise, vmax = find_noise_area(hdu, ra, dec, size)
        print 'Optical parameters are', mean, noise, vmax
        f = aplpy.FITSFigure(hdu, north=True)
        print 'centring on', ra, dec, size
        f.recenter(ra, dec, width=size, height=size)
        f.show_colorscale(vmin=mean + noisethresh * noise,
                          vmax=vmax,
                          stretch='log')

    if bmaj is not None:
        f._header['BMAJ'] = bmaj
        f._header['BMIN'] = bmin
        f._header['BPA'] = bpa

    if show_lofar:
        f.show_contour(lofarhdu, colors='yellow', linewidths=lw, levels=levels)

    if firsthdu is not None:
        firstrms = find_noise_area(firsthdu, ra, dec, size)[1]
        print 'Using FIRST rms', firstrms
        firstlevels = firstrms * 3 * 2.0**np.linspace(0, 14, 30)
        f.show_contour(firsthdu,
                       colors=first_color,
                       linewidths=lw,
                       levels=firstlevels)

    if vlasshdu is not None:
        vlassrms = find_noise_area(vlasshdu, ra, dec, size)[1]
        print 'Using VLASS rms', vlassrms
        vlasslevels = vlassrms * 3 * 2.0**np.linspace(0, 14, 30)
        f.show_contour(vlasshdu,
                       colors=vlass_color,
                       linewidths=lw,
                       levels=vlasslevels)

    if bmaj is not None:
        f.add_beam()
        f.beam.set_corner('bottom left')
        f.beam.set_edgecolor('red')
        f.beam.set_facecolor('white')

    if plot_coords:
        f.show_markers(coords_ra,
                       coords_dec,
                       marker='+',
                       facecolor=coords_color,
                       edgecolor=coords_color,
                       linewidth=coords_lw,
                       s=1500,
                       zorder=100)

    if marker_ra is not None:
        f.show_markers(marker_ra,
                       marker_dec,
                       marker='x',
                       facecolor=marker_color,
                       edgecolor=marker_color,
                       linewidth=marker_lw,
                       s=1500,
                       zorder=100)

    if plotpos is not None:
        if not isinstance(plotpos, list):
            plotpos = [
                (plotpos, 'x'),
            ]
        for element in plotpos:
            # if a colour is specified assume it's for a filled shape and unfill it
            if len(element) == 3:
                t, marker, edgecolor = element
                facecolor = 'None'
            else:
                t, marker = element
                edgecolor = 'white'
                facecolor = edgecolor
            if len(t) > 0:
                f.show_markers(t['ra'],
                               t['dec'],
                               marker=marker,
                               facecolor=facecolor,
                               edgecolor=edgecolor,
                               linewidth=2,
                               s=750,
                               zorder=100)

    if circle_radius is not None:
        f.show_circles([
            ra,
        ], [
            dec,
        ], [
            circle_radius,
        ],
                       facecolor='none',
                       edgecolor='cyan',
                       linewidth=5)

    if overlay_cat is not None:
        t = overlay_cat
        f.show_ellipses(t['RA'],
                        t['DEC'],
                        t['Maj'] * 2 / overlay_scale,
                        t['Min'] * 2 / overlay_scale,
                        angle=90 + t['PA'],
                        edgecolor=ellipse_color,
                        linewidth=lw_ellipse,
                        linestyle=ellipse_style,
                        zorder=100)

    if overlay_region is not None:
        f.show_regions(overlay_region)

    if no_labels:
        f.axis_labels.hide()
        f.tick_labels.hide()
    if show_grid:
        f.add_grid()
        f.grid.show()
        f.grid.set_xspacing(1.0 / 60.0)
        f.grid.set_yspacing(1.0 / 60.0)

    if title is not None:
        plt.title(title)
    plt.tight_layout()
    if save_name is None:
        plt.show(block=block)
    else:
        plt.savefig(save_name)

    def onclick(event):
        xp = event.xdata
        yp = event.ydata
        xw, yw = f.pixel2world(xp, yp)
        if event.button == 2:
            print title, xw, yw

    if interactive:
        fig = plt.gcf()
        if interactive_handler is None:
            cid = fig.canvas.mpl_connect('button_press_event', onclick)
        else:
            I = interactive_handler(f)
            fig.canvas.mpl_connect('button_press_event', I.onclick)
    return f
Exemplo n.º 47
0
def main(argv):
	
	config_file=None
	list_file=None

	try:
		opts, args = getopt.getopt(argv,"hc:l:p:f:",["config=","list=","prefix=","filters="])
	except getopt.GetoptError:
		print 'make_rgb_image.py -c <configuration file> -l <image file list> -p <prefix> -f <filters>'
		sys.exit(2)

	for opt, arg in opts:
		if opt == '-h':
			print 'make_rgb_image.py -c <configuration file> -l <image file list> -p <prefix> -f <filters>'
			sys.exit()
		elif opt in ("-c", "--config"):
			config_file = arg
		elif opt in ("-l", "--list"):
			list_file = arg
		elif opt in ("-p", "--prefix"):
			prefix = arg
		elif opt in ("-f", "--filters"):
			filters = string.split(arg,',')

	if config_file is None or list_file is None:
		raise ArgumentError("You need to supply a configuration file and an image file list")

	print 'Configuration file is ', config_file
	print 'Image file list is ', list_file

	config_data = ConfigParser.ConfigParser()
	config_data.read(config_file)

	prefix=config_data.get('Stack','prefix')
	filters=string.split(config_data.get('Stack','filters'),',')
	stack_name=config_data.get('Stack','stack_name')
	stack_version=config_data.get('Stack','stack_version')
	stack_tile_ref=config_data.get('Stack','stack_tile_ref')
	stack_filter_ref=config_data.get('Stack','stack_filter_ref')

	list_data = np.loadtxt(list_file, dtype={'names': ('tile', 'filter', 'image', 'weight'), 'formats': ('S10', 'S10', 'S50', 'S50')})

	stack_tile=np.unique(list_data['tile'])
	stack_filter=filters
	print "List of tiles: ", stack_tile
	print "List of filters: ", stack_filter

	for i in range(len(stack_tile)):
		print '\nProcessing tile ', stack_tile[i]

		stack_im_file=[prefix+'/'+list_data['image'][np.where( (list_data['tile'] == stack_tile[i]) & (list_data['filter'] == f) )][0] for f in filters]
		stack_weight_file=[prefix+'/'+list_data['weight'][np.where( (list_data['tile'] == stack_tile[i]) & (list_data['filter'] == f) )][0] for f in filters]
		stack_rgb_file=prefix+'/'+stack_name+'_TILE'+stack_tile[i]+'_FILTERS'+string.join(filters,'')+'.fits'
		stack_hist_sky_file=prefix+'/'+stack_name+'_TILE'+stack_tile[i]+'_FILTERS'+string.join(filters,'')+'_histogram_sky_v'+stack_version+'.pdf'
		stack_hist_file=prefix+'/'+stack_name+'_TILE'+stack_tile[i]+'_FILTERS'+string.join(filters,'')+'_histogram_v'+stack_version+'.pdf'
		stack_rgb_limit=np.zeros((3,2), dtype=np.float32)

		hist_nbin=200
		hist_percentile=[0.25,99.5] #[0.25,99.8] #[0.25,99.5]  #([0.25,99.5],[0.25,99.55],[0.22,99.8])
		
		hdulist = pyfits.open(stack_im_file[0])
		im_h=hdulist[0].header
		hdulist.close()
		
		nx = int(im_h['NAXIS1'])
		ny = int(im_h['NAXIS2'])
		im_data_cube = np.zeros((3, ny, nx), dtype=np.float32)
			
		if not os.path.exists(stack_rgb_file):
		
			print '\nCreating rgb cube ', stack_rgb_file
			for j in range(len(stack_filter)):
		
				print '\nProcessing image ', stack_im_file[j], ' - filter ', stack_filter[j]
				im_file=stack_im_file[j]
				weight_file=stack_weight_file[j]
				#mask_file=stack_mask_file[j]
			
				if os.path.exists(im_file):
					print '\nReading image file ', im_file
					hdulist = pyfits.open(im_file)
					im_data=hdulist[0].data
					im_h=hdulist[0].header
					hdulist.close()
			
					print 'Reading weight file ', weight_file
					hdulist = pyfits.open(weight_file)
					weight_data=hdulist[0].data
					hdulist.close()
			
					bv_weight = (weight_data==0.)
					im_data[bv_weight]=np.nan
			
					print 'Image size along X-axis ', im_h['NAXIS1']
					print 'Image size along Y-axis ', im_h['NAXIS2']
			
					ypad = ny - im_data.shape[0]
					xpad = nx - im_data.shape[1]
					pad_width = ((0, ypad), (0, xpad))

					im_data_pad = np.pad(im_data, pad_width, mode='constant', constant_values=[np.nan])
					im_data_cube[j,:,:]=im_data_pad
				else:
					print 'The image file does not exists ', im_file
		
					nim_data = np.empty((ny, nx), dtype=np.float32)
					nim_data[:] = np.nan
					try:
						gv = stack_tile.index(stack_tile_ref)
						im_file=stack_im_file_full[gv][j]
						weight_file=stack_weight_file_full[gv][j]
						mask_file=stack_mask_file_full[gv][j]

						print '\nReading image file ', im_file
						hdulist = pyfits.open(im_file)
						im_data=hdulist[0].data
						hdulist.close()
			
						print 'Reading weight file ', weight_file
						hdulist = pyfits.open(weight_file)
						weight_data=hdulist[0].data
						hdulist.close()
			
						print 'Reading mask file ', mask_file
						hdulist = pyfits.open(mask_file)
						mask_data=hdulist[0].data
						hdulist.close()

						gv = np.logical_and(weight_data>0,mask_data==0)
				
						if np.count_nonzero(gv)>1:
							sky_data=im_data[gv]
							hist_limit= np.abs(np.percentile(sky_data, 0.001))
							hist_xmin=-1.*hist_limit
							hist_xmax=1.*hist_limit
							hist, bin_edges = np.histogram( sky_data, bins=np.linspace(hist_xmin, hist_xmax, hist_nbin), range=(hist_xmin, hist_xmax))
							plt.bar(bin_edges[:-1], hist, width = bin_edges[1]-bin_edges[0], linewidth=0., log=True)
							plt.xlim(hist_xmin, hist_xmax)
							plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
							plt.xlabel('Flux')
							plt.ylabel('Number count')
							plt.savefig(stack_hist_sky_file)

							weight_file=stack_weight_file[0]
							print 'Reading weight file ', weight_file
							hdulist = pyfits.open(weight_file)
							weight_data=hdulist[0].data
							hdulist.close()

							print 'Random sample from the reference image'
							gv=(weight_data>0)
							nim_data[gv]=np.random.choice(sky_data, np.count_nonzero(gv))
							im_data_cube[j,:,:]=nim_data

					except ValueError:
						print 'Adding gaussian model'
						im_data_cube[j,:,:]= 6. * np.random.randn(ny, nx)
						im_data_cube[j,:,:][bv_weight]=np.nan

			
			print 'Saving the rgb cube file ', stack_rgb_file
			pyfits.writeto(stack_rgb_file, im_data_cube, header=im_h)
		else:
			print 'RGB cube already exists'
		

		im_rgb_file=stack_rgb_file.replace('.fits','_asinh_v'+stack_version+'.jpg')
		if not os.path.exists(im_rgb_file):

			print "Reading the RGB fits cube file: ", stack_rgb_file		
			hdulist = pyfits.open(stack_rgb_file)
			im_data_cube=hdulist[0].data
			im_h_cube=hdulist[0].header
			hdulist.close()

			try:
				stack_rgb_limit=stack_rgb_limit_ref
			except:	
				print '\nComputing the RGB limits using the current image'

				w, h = 2*matplotlib.figure.figaspect(1.2)
				fig = plt.figure(figsize=(w,h))
				for j in range(len(stack_filter)):
					print '\nProcessing filter ', stack_filter[j]
					im_data=im_data_cube[j,:,:]
					gv=np.isfinite(im_data)
		
					if np.count_nonzero(gv)>1:
		
						if os.path.exists(stack_im_file[j]):
		
							stack_rgb_limit[j,:]= np.percentile(im_data[gv], hist_percentile)  #[plot_xmin, plot_xmax]
							if stack_rgb_limit[j,0]==stack_rgb_limit[j,1]:
								print 'The data seems to contain a constant value. Filter '+stack_filter[j]
								continue
		
							hist_xmin=np.amin(im_data[gv])
							hist_xmax=np.amax(im_data[gv])
			
							print 'Percentiles for computing RGB min and max ', hist_percentile
							print 'Histogram min and max ', hist_xmin, hist_xmax
							print 'RGB image min and max ', stack_rgb_limit[j,:]
			
			#hist_min=np.nanmin(im_data)
			#hist_max=np.nanmax(im_data)
			#fig = plt.figure()
			#ax = fig.add_subplot(1,1,1,)
			#n, bins, patches = ax.hist( np.ravel(im_data), bins=2., range=(hist_min, hist_max), histtype='bar')
			
							hist, bin_edges = np.histogram( im_data, bins=np.linspace(hist_xmin, hist_xmax, hist_nbin), range=(hist_xmin, hist_xmax))
				
			#	ax = fig.add_subplot(2,3,1+2*i,)
							plt.subplot(3,2,1+2*j)
							plt.bar(bin_edges[:-1], hist, width = bin_edges[1]-bin_edges[0], linewidth=0., log=True)
							plt.xlim(hist_xmin, hist_xmax)
							plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
			#	ax.set_yscale('log')
							plt.title('Tile '+stack_tile[i]+' - '+stack_filter[j])
							plt.xlabel('Flux')
							plt.ylabel('Number count')
			
							if stack_filter[j]==stack_filter_ref:
								hist, bin_edges = np.histogram( im_data, bins=np.linspace(stack_rgb_limit[j,0], stack_rgb_limit[j,1], hist_nbin), range=stack_rgb_limit[j,:] )
								stack_rgb_ratio_ref= [ hist[0]*1./np.amax(hist), hist[-1]*1./np.amax(hist) ]
								gv_max=np.argmax(hist)
								stack_rgb_limit_ratio_ref= (bin_edges[gv_max]-stack_rgb_limit[j,0])*1./(stack_rgb_limit[j,1]-stack_rgb_limit[j,0])
								print 'stack_rgb_ratio_ref ', stack_rgb_ratio_ref
								print 'stack_rgb_limit_ratio_ref ', stack_rgb_limit_ratio_ref
							else:
			#		if stack_filter[i]=='u': stack_rgb_ratio=[ stack_rgb_ratio_ref[0]**0.25, stack_rgb_ratio_ref[1] ]
			#		else: stack_rgb_ratio=stack_rgb_ratio_ref
								stack_rgb_ratio=stack_rgb_ratio_ref
								print 'stack_rgb_ratio ', stack_rgb_ratio
			
								delta=stack_rgb_limit[j,1]-stack_rgb_limit[j,0]
								if stack_filter[j]=='u':
									stack_rgb_limit[j,0] -= delta/8.
									stack_rgb_limit[j,1] += 2*delta
								else:
									stack_rgb_limit[j,0] -= delta/8.
									stack_rgb_limit[j,1] += delta/4.
			
								print "Guess RGB image min and max ", stack_rgb_limit[j,:]
						
								hist, bin_edges = np.histogram( im_data, bins=np.linspace(stack_rgb_limit[j,0], stack_rgb_limit[j,1], 2*hist_nbin), range=stack_rgb_limit[j,:] )
								gv_max=np.argmax(hist)
			#		stack_rgb_limit[i,:]= [ bin_edges[ np.argmin( np.abs(hist[0:gv_max]*1./np.amax(hist) - stack_rgb_ratio[0]) )], bin_edges[ gv_max + np.argmin( np.abs(hist[gv_max:-1]*1./np.amax(hist) - stack_rgb_ratio[1]) ) ] ]
								gv_limit_max=gv_max + np.argmin( np.abs(hist[gv_max:-1]*1./np.amax(hist) - stack_rgb_ratio[1]) )
								gv_limit_min=np.argmin( np.abs( (bin_edges[gv_max]- bin_edges[0:gv_max])*1./(bin_edges[gv_limit_max]-bin_edges[0:gv_max]) - stack_rgb_limit_ratio_ref) )
								stack_rgb_limit[j,:]=bin_edges[[gv_limit_min,gv_limit_max]]
								print "Computed RGB limit ", stack_rgb_limit[j,:]
		#						print "New stack_rgb_ratio ", hist[gv_limit_min]*1./hist[gv_max], hist[gv_limit_max]*1./hist[gv_max]
		
						else:
							print 'Computing the rgb limit using the reference tile'
		
							gv_tile = stack_tile.index(stack_tile_ref)
							gv_filter = stack_filter.index(stack_filter_ref)
							hdulist = pyfits.open(stack_rgb_file_full[gv_tile])
							im_h=hdulist[0].header
							hdulist.close()
		
							stack_rgb_limit[j,:]=np.asarray(im_h['RGB_'+stack_filter[j]].split(',')).astype(np.float)
							delta=stack_rgb_limit[j,1]-stack_rgb_limit[j,0]
							stack_rgb_limit[j,0] -= delta/4.
							stack_rgb_limit[j,1] += delta/4.
		
							hist, bin_edges = np.histogram( im_data, bins=np.linspace(stack_rgb_limit[j,0], stack_rgb_limit[j,1], hist_nbin), range=stack_rgb_limit[j,:] )
							gv_max=np.argmax(hist)
		
							stack_rgb_limit[j,1]= np.asarray(im_h['RGB_'+stack_filter[j]].split(',')).astype(np.float)[1]/np.asarray(im_h['RGB_'+stack_filter_ref].split(',')).astype(np.float)[1]*stack_rgb_limit[gv_filter,1]
							stack_rgb_limit[j,0]= bin_edges[ np.argmin( np.abs( (bin_edges[gv_max]- bin_edges[0:gv_max])*1./(stack_rgb_limit[j,1]-bin_edges[0:gv_max]) - stack_rgb_limit_ratio_ref) ) ]
							print "Computed RGB limit ", stack_rgb_limit[j,:]
		#					stack_rgb_limit[j,:]=np.asarray(im_h['RGB_'+stack_filter[j]].split(',')).astype(np.float)
							
						hist, bin_edges = np.histogram( im_data, bins=np.linspace(stack_rgb_limit[j,0], stack_rgb_limit[j,1], hist_nbin), range=stack_rgb_limit[j,:] )
			
			#	ax = fig.add_subplot(2,3,1+2*i+1,)
		
						plt.subplot(3,2,1+2*j+1)
						plt.bar(bin_edges[:-1], hist, width = bin_edges[1]-bin_edges[0], linewidth=0., log=True)
						plt.xlim(stack_rgb_limit[j,0], stack_rgb_limit[j,1])
						plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
			#	ax.set_yscale('log')
						plt.title('Tile '+stack_tile[i]+' - '+stack_filter[j])
						plt.xlabel('Flux')
						plt.ylabel('Number count')
		
					else:
						print '\nNo valid pixels for filter '+stack_filter[j]
			else:
				print '\nReading the RGB limits from the reference tile'

			if stack_tile[i]==stack_tile_ref:
				stack_rgb_limit_ref=stack_rgb_limit

			print 'Updating the rgb cube file ', stack_rgb_file

			for j in range(len(stack_filter)):
				print "\nFilter "+stack_filter[j]
				print stack_rgb_limit[j,:]
				im_h_cube['RGB_'+stack_filter[j]]= ','.join(np.char.mod('%.2f', stack_rgb_limit[j,:]))

			pyfits.writeto(stack_rgb_file, im_data_cube, header=im_h_cube, clobber=True)
		
			plt.tight_layout()
			plt.savefig(stack_hist_file)
			plt.close(fig)
		
			print "stack_rgb_limit: \n", stack_rgb_limit
			
			im_rgb_file=stack_rgb_file.replace('.fits','_asinh_v'+stack_version+'.jpg')
			print 'Creating RGB image file ', im_rgb_file
			aplpy.make_rgb_image(stack_rgb_file, im_rgb_file, stretch_r='arcsinh', stretch_g='arcsinh', stretch_b='arcsinh', vmin_r=stack_rgb_limit[0,0], vmin_g=stack_rgb_limit[1,0], vmin_b=stack_rgb_limit[2,0], vmax_r=stack_rgb_limit[0,1], vmax_g=stack_rgb_limit[1,1], vmax_b=stack_rgb_limit[2,1], vmid_r=-0.07, vmid_g=-0.07, vmid_b=-0.07, make_nans_transparent=True, embed_avm_tags=True)
		else:
			print 'RGB image already exists'
Exemplo n.º 48
0
def plot_image(ra=None, dec=None, pos=None, **kwargs):
    """
    Use SkyView to get a cutout image

    :param ra: float or string or None, right ascension (deg or hh:mm:ss)
    :param dec: float or string or None, declination (deg or dd:mm:ss)
    :param pos: string or None,
                Determines the center of the field to be retrieved. Both
                coordinates (also equatorial ones) and object names are
                supported. Object names are converted to coordinates via the
                SIMBAD or NED name resolver. See the reference for more info
                on the supported syntax for coordinates.
    :param kwargs: see below

    kwargs are as follows
    - coords
                Choose among common equatorial, galactic and ecliptic
                coordinate systems ("J2000", "B1950", "Galactic",
                "E2000", "ICRS") or pass a custom string.
    - survey string, surveys used in SkyView.get_images

              define survey (can find info in SkyView.list_surveys())

              e.g.:

                    SDSSg, SDSSi, SDSSr, SDSSu, SDSSz, 2MASS-J, 2MASS-H,
                    2MASS-K, UKIDSS-Y, UKIDSS-J, UKIDSS-H, UKIDSS-K,
                    WISE 3.4, WISE 4.6, WISE 12, WISE 22

              if colour kwarg is True this is a list of three strings
              and is from red --> blue i.e. ['WISE 12', 'WISE 4.6', 'WISE 3.4']

    - radius
                float, half width of image
    - pixels
                int, size of the image produced in pixels (for x and y)
    - colour
                bool, whether to plot rgb or not, default=False
    - cmap
                string, matplotlib colormap indicator
                    (used if not rgb), default='gist_gray'
    - stretches
                tuple, defines the rgb stretches to use on rgb plot
                 [stretch in r, stretch in g, stretch in b]
                 default is ['log', 'log', 'log'] can have:
                'linear', 'log', 'sqrt', 'arcsinh', 'power'
    - gridc
                string, colour of the grid
    - gridl
                string, linestyle of the grid

    :return:
    """
    # load params from kwargs
    coords = kwargs.get('coords', 'J2000')
    s = kwargs.get('survey', '2MASS-J')
    radius = kwargs.get('radius', 1.0 * u.deg)
    pixels = kwargs.get('pixels', 1024)
    colour = kwargs.get('colour', False)
    cmap = kwargs.get('cmap', 'gist_gray')
    stretches = kwargs.get('stretches', ('log', 'log', 'log'))
    gridc = kwargs.get('gridc', '0.75')
    gridl = kwargs.get('gridl', '--')
    # get position as ra dec string
    if ra is not None and dec is not None:
        pos = '{0} {1}'.format(ra, dec)
    elif pos is not None:
        pos = pos
    else:
        raise Exception('Error need RA, Dec or Pos to get image')
    # download images
    giargs = dict(position=pos, survey=s, radius=radius, pixels=pixels,
                  coordinates=coords)
    images = SkyView.get_images(**giargs)
    # plot aplpy FITS figure
    apx = aplpy.FITSFigure(images[0][0])
    # if colour expect 3 surveys and make an rgb plot
    if colour:
        files = []
        # loops round each image
        for i, j in enumerate(images):
            # defines a tmp filename for each iamge
            fname = '{0}.fits'.format(i)
            # writes fits to file
            j[0].writeto(fname, clobber=True)
            # appends filename to file list
            files.append(fname)
        # add rgb image to file list
        files.append('rgb.png')
        # create rgb image
        rgbargs = dict(zip(['stretch_r', 'stretch_g', 'stretch_b'], stretches))
        aplpy.make_rgb_image(files[:3], files[3], **rgbargs)
        # show rgb plot on top
        apx.show_rgb('rgb.png')
        for fn in files:
            os.remove(fn)
    # if not colour just show the colour scale
    else:
        apx.show_colorscale(cmap=cmap)
    # add grid
    apx.add_grid()
    apx.grid.set_color(gridc)
    apx.grid.set_linestyle(gridl)
    # return aplpy figure
    return apx
Exemplo n.º 49
0
import psi.process

import pyregion
import astropy.coordinates as coords
import astropy.units as units


def get_mem():
    pid = psi.process.ProcessTable()[os.getpid()]
    return pid.vsz

if False:
    aplpy.make_rgb_image(['big_mosaic_ks.fits','big_mosaic_h2_normed.fits','big_mosaic_feii_normed.fits'],
            'Big_Orion_RGB.png',
            stretch_r='log',vmin_r=220,vmax_r=600,
            stretch_g='log',vmin_g=-0.05,vmax_g=0.4,
            stretch_b='log',vmin_b=-0.05,vmax_b=0.4,
            embed_avm_tags=True,
            )

    F = aplpy.FITSFigure('Big_Orion_RGB.png',convention='calabretta')


print "Memory Check (ps): ",get_mem()/1024.**3
F = aplpy.FITSFigure('Trapezium_GEMS_mosaic_redblueorange_normed_large_contrast_bright.png')

reg = pyregion.open('proplyds.reg')
jetheads = pyregion.open('jetheads.reg')
def plotthings(F,prefix="cutouts/",rgb=True, **kwargs):
    if rgb:
        F.show_rgb()
Exemplo n.º 50
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.º 51
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.º 52
0
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')
    aplpy.make_rgb_image('./rgb_cubes/SiO_29_36__23_29__16_22.fits',
                         './rgb_pngs/SiO_29_36__23_29__16_22.png',
                         pmin_r=20,
                         pmax_r=100,
                         pmin_g=10,
                         pmax_g=100,
Exemplo n.º 53
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