コード例 #1
0
def sb_profile_only(image_stamp,galmag,color,sblimit,threshold,redshift,title='',plot_profile=True):

    radius = np.arange(0,3/args.pixscale,1)
    fluxes = np.zeros(np.size(radius))-99

    sky_med,sky_std = mi.sky_value(image_stamp,args.ksky)

    if np.abs(color)<10:
        corrected_thresh = color_correction(threshold,color)
        new_sblimit = corrected_thresh*sblimit

        threshold=corrected_thresh
    else:
        if args.verbose:
            print("Invalid color value: %.4f"%color)
        return radius,fluxes,-99,-99,-99,-99

    if args.nodilation:
        image_stamp = mi.sci_nd.gaussian_filter(image_stamp,sigma=1.0)

    segmap = mi.gen_segmap_sbthresh(image_stamp-sky_med,hsize,hsize,sblimit,args.pixscale,thresh=threshold,Amin=args.areamin,all_detection=True)
    single_source_map = mi.select_object_map_connected(hsize,hsize,image_stamp,segmap,pixscale=args.pixscale)
    image_stamp,single_source_map,imglag,segflag = mi.image_validation(image_stamp,single_source_map,args.pixscale,1.0)

    if segflag==1:
        return radius,fluxes,-99,-99,-99,-99

    radius,fluxes,barx,bary,q,theta = compute_sbprofile(image_stamp-sky_med,single_source_map,args.pixscale)

    if plot_profile:
        segmap[segmap!=0]/=1
        fig,ax=mpl.subplots(1,2,figsize=(20.6,16))
        ax=ax.reshape(np.size(ax))

        fig.suptitle(title)
        ax[0].set_title(r'$K-I=%.4f\ F_\mathrm{correction} = %.5f$'%(color,10**(0.4*(color))))
        ax[1].set_title(r'$k=%.4f\ k\sigma=%.5f\ \mathrm{[e^{-}s^{-1}arcsec^{-2}]}\ \ k_\mathrm{uncorr}=%.4f$'%(threshold,new_sblimit,args.sigma0*((1+redshift)/(1+2.0))**(-3)))

        mpl.subplots_adjust(wspace=0.2,hspace=0.02)
        ax[0].imshow(np.sqrt(np.abs(image_stamp)),cmap='hot')
        mi.gen_ellipse(ax[0],barx,bary,3*(2*hsize/args.size),q,-theta)

        ax[1].plot(radius,fluxes,'o-',color='CornflowerBlue')

        ax[1].hlines(sblimit,min(radius),max(radius),linestyle='--',color='Crimson')
        ax[1].hlines(sblimit*threshold,min(radius),max(radius))
        ax[1].set_ylim(1.1*min(fluxes),1.1*max(fluxes))
#        ax[3].hlines(sblimit*1.5*((1+redshift)/(1+4.0))**(-3),min(rad),max(rad),linestyle='-',color='LimeGreen')

        ax[1].set_xlabel(r"$r\ [\mathrm{pix}]$")
        ax[1].set_ylabel(r"$f(r)\ [\mathrm{e^{-}s^{-1}arcsec^{-2}}]$")


        fig.canvas.mpl_connect('key_press_event',exit_code)
        mpl.show()

    return radius,fluxes,barx,bary,q,theta
コード例 #2
0
def compute_size(image,ra,dec,galmag,hsize,threshold,fractions,sblimit,size=6,safedist=1.0):

    Sizes = np.zeros(len(fractions)+1)
    Fluxes = np.zeros(len(fractions)+1)

    SizesPSF = np.zeros(len(fractions)+1)
    FluxesPSF = np.zeros(len(fractions)+1)


    image_stamp = load_data(image,ra,dec,hsize)
    if np.amax(image_stamp)==np.amin(image_stamp):
        return Sizes - 99,-9


    dilate = define_structure(size)
    sky_med,sky_std = mi.sky_value(image_stamp,args.ksky)

    psf_image = simulate_psf(galmag,hsize,sky_med)

    segmap_psf = mi.gen_segmap_sbthresh(psf_image-sky_med,hsize,hsize,sblimit,args.pixscale,thresh=threshold,Amin=args.areamin,all_detection=True)
    single_source_map_psf = mi.select_object_map(hsize,hsize,segmap_psf,pixscale=args.pixscale)

    segmap = mi.gen_segmap_sbthresh(image_stamp-sky_med,hsize,hsize,sblimit,args.pixscale,thresh=threshold,Amin=args.areamin,all_detection=True)
    single_source_map = mi.select_object_map(hsize,hsize,segmap,pixscale=args.pixscale)
    image_stamp,single_source_map,imglag,segflag = mi.image_validation(image_stamp,single_source_map,args.pixscale,safedist)

    if segflag==1:
        return Sizes - 99,segflag

    if args.nodilation:
        dilated_map = single_source_map
        dilated_map_psf = single_source_map_psf
    else:
        dilated_map = mi.sci_nd.binary_dilation(single_source_map,structure=dilate).astype(np.int32)
        dilated_map_psf = mi.sci_nd.binary_dilation(single_source_map_psf,structure=dilate).astype(np.int32)


    for i in range(len(fractions)):
        Sizes[i],TotalArea,Fluxes[i],TotalFlux = compute_fraction_area(image_stamp,dilated_map,fractions[i])
        SizesPSF[i],TotalAreaPSF,FluxesPSF[i],TotalFluxPSF = compute_fraction_area(psf_image,dilated_map_psf,fractions[i])

    Sizes[i+1]=TotalArea
    Fluxes[i+1]=TotalFlux

    SizesPSF[i+1]=TotalAreaPSF
    FluxesPSF[i+1]=TotalFluxPSF

    Real_Sizes  = Sizes - SizesPSF

    if args.nosaving:
        mpl.rcParams['image.cmap']='gist_stern_r'
        segmap[segmap!=0]/=1
        fig,ax=mpl.subplots(2,3,figsize=(20.6,12))
        mpl.subplots_adjust(wspace=0.2,hspace=0.02)
        ax=ax.reshape(np.size(ax))
        ax[0].imshow(np.sqrt(np.abs(image_stamp)),cmap='hot')
        mi.gen_circle(ax[1],hsize,hsize,hsize*(2*np.sqrt(2)*0.5/args.size),color='red')
        ax[1].imshow(segmap)
        ax[2].imshow(single_source_map)

        flux_map = np.zeros(image_stamp.shape)
        flux_map[dilated_map==1]=3
        for j in range(len(Fluxes)-2,-1,-1):
            flux_map[image_stamp>Fluxes[j]]=(len(Fluxes)-j)*4
        flux_map*=dilated_map
        imax,imin,jmax,jmin = mi.find_ij(dilated_map)
        ax[3].imshow(flux_map[imin:imax,jmin:jmax],aspect='equal',cmap='gist_heat_r')
        ax[3].text(12,9,'20',color='white',va='center',ha='center',weight='heavy')
        ax[3].text(10,7.5,'50',color='white',va='center',ha='center',weight='heavy')
        ax[3].text(8.5,5.5,'80',color='white',va='center',ha='center',weight='heavy')
        ax[3].text(6,3,'100',color='white',va='center',ha='center',weight='heavy')


#        masked_neighbours = mi.sci_nd.binary_dilation(segmap - single_source_map,structure=dilate)
        compute_fraction_area(image_stamp,dilated_map,1.0,flux_sampling=500,draw_ax=ax[4])

        ax[5].imshow(dilated_map)

        for i in range(len(ax)):
            if i!=4:
                ax[i].set_xticks([])
                ax[i].set_yticks([])

        fig.text(0.95,0.50,r'$\curvearrowright$',va='center',ha='center',weight='heavy',rotation=-90,fontsize=150)
#        fig.savefig('size_thresholding_example.png')
        def exit_code(event):
            if event.key=='escape':
                sys.exit()
            if event.key=='q':
                mpl.close('all')

        fig.canvas.mpl_connect('key_press_event',exit_code)
        mpl.show()


    return Real_Sizes,segflag
コード例 #3
0
def find_pairs_and_clumps(image_stamp,redshift,galmag,color,hsize,threshold,fractions,sblimit,pixelscale,zeropoint,ksky=3.0,Areamin=10,Aperture=0.5,no_dilation=True,degrade=None,size=5,safedist=1.0,title=None,plot_results=False,segmap_output=False,erosion=[3],verbose=False,ident=None,zphot_sel=None):


    if np.amax(image_stamp)==np.amin(image_stamp):
        if verbose:
            print("Invalid data values: %.4f,%.4f"%(np.amax(image_stamp),np.amin(image_stamp)))
        return {}

    dilate = define_structure(size)
    sky_med,sky_std = mi.sky_value(image_stamp,ksky)


    if degrade is not None:
        N,M=image_stamp.shape
        image_stamp = mi.rebin2d(image_stamp,int(N/degrade),int(M/degrade),flux_scale=True)
        pixelscale*=degrade


    if no_dilation:
        image_smooth = mi.sci_nd.gaussian_filter(image_stamp,sigma=1.0)


    if args.error:
        factor=-1.0
    else:
        factor=1.0

    if np.abs(color)<10:
        corrected_thresh = color_correction(threshold,color)
        new_sblimit = corrected_thresh*sblimit
#        if verbose:
#            print("K-I=%.4f\t old sb limit = %.5f\t new sb limit = %.5f counts/s/arcsec**2"%(color,threshold*sblimit,new_sblimit))
        threshold=corrected_thresh
    elif np.abs(color)>10:
        if verbose:
            print("Invalid color value: %.4f"%color)
        return {}

    segmap = mi.gen_segmap_sbthresh(factor*(image_smooth-sky_med),hsize,hsize,sblimit,pixelscale,thresh=threshold,Amin=Areamin,all_detection=True)
    single_source_map = mi.select_object_map_connected(hsize,hsize,factor*image_smooth,segmap,pixscale=pixelscale,radius=Aperture)
    image_smooth,single_source_map,imglag,segflag = mi.image_validation(image_smooth,single_source_map,pixelscale,safedist)

#    fig,ax=mpl.subplots(1,3,figsize=(25,10))
#    ax[0].imshow(image_smooth)
#    ax[1].imshow(segmap)
#    ax[2].imshow(single_source_map)
#    fig.canvas.mpl_connect('key_press_event',exit_code)
#    mpl.show()

    if no_dilation:
        dilated_map = single_source_map
    else:
        dilated_map = mi.sci_nd.binary_dilation(single_source_map,structure=dilate).astype(np.int32)


    gal_selection,gal_magnitudes = galaxy_map(image_stamp,segmap,zeropoint,sky_med,factor)
    ngals=np.amax(gal_selection)
#


    FullSet={}
    if verbose:
        print('Ngals=%i'%ngals)

    for i in range(ngals):
        GalPositionsBar={}
        GalPositionsMax={}
        GalMags={}
        GalDistances={}
        GalSizes={}

        single_gal_map=gal_selection.copy()
        single_gal_map[gal_selection!=(i+1)]=0
        single_gal_map[gal_selection==(i+1)]=1

#        fig,ax=mpl.subplots(1,4,figsize=(25,12))
#        ax[0].imshow(factor*image_smooth,vmin=0)
#        ax[1].imshow(segmap)
#        ax[2].imshow(gal_selection)
#        ax[3].imshow(single_gal_map)
#        fig.canvas.mpl_connect('key_press_event',exit_code)
#        mpl.show()


        nregs=[]
        nregs2=[]
#        fractions = [0.2,1.0]#np.linspace(0,1,101)
        Xcen,Ycen=mi.barycenter(factor*image_stamp,single_gal_map)


        if zphot_sel is None:
            prob_dist = 1.0
            prob_dist_area = 1.0
        else:
            GalDists = mi.dist(Ycen,Xcen,zphot_sel[:,0],zphot_sel[:,1])
            kmin = np.argmin(GalDists)
            dmin = GalDists[kmin]

            vpair=500. #km/s
            redshift_error = np.sqrt( vpair*vpair + 200*200. + 20000*20000.)/2.9979e5*(1+redshift)

            if dmin < 1.0/pixelscale:
                z,zl,zu = zphot_sel[kmin,2],zphot_sel[kmin,3],zphot_sel[kmin,4]
                prob_dist = probability_zphot(z,zl,zu,redshift-redshift_error,redshift+redshift_error)
            else:
                prob_dist = -99

            if gal_magnitudes[i]<MagCapak[0]:
                prob_dist_area=0.0
            else:
                NCounts = simps(NumCapak[MagCapak<gal_magnitudes[i]],MagCapak[MagCapak<gal_magnitudes[i]])
                radius = mi.dist(Ycen,Xcen,hsize,hsize)*pixelscale
                prob_dist_area = max(1-NCounts/(3600.*3600.)*radius*radius*np.pi,0)

        for f in fractions:
            S = get_segmap_level(factor*image_smooth,single_gal_map,f)

            clump_map_full,nr= mi.sci_nd.label(S)
            clump_map_clean,nr2 = clean_map(clump_map_full,minarea=Areamin)
#            fig,ax=mpl.subplots(1,2)
#            ax[0].imshow(clump_map_full)
#            ax[1].imshow(clump_map_clean)
#            mpl.show()

            M,Pb,Pm,Sc=get_clump_stats(factor*image_stamp,clump_map_clean,zeropoint)
            GalMags[str(f)]=M
            GalPositionsBar[str(f)]=Pb
            GalPositionsMax[str(f)]=Pm
            GalSizes[str(f)]=Sc

            nregs.append(nr)
            nregs2.append(nr2)

        for f in fractions:
            FP = GalPositionsBar[str(f)]
            nclumps=np.shape(FP)[0]

            DistsSingle=np.zeros(nclumps)
            for n in range(nclumps):
                DistsSingle[n] = pixelscale*np.sqrt((FP[n,0]-Xcen)*(FP[n,0]-Xcen)+(FP[n,1]-Ycen)*(FP[n,1]-Ycen))

            GalDistances[f]=DistsSingle

            if verbose:
                print('\t %i ----> f=%.2f \t nclumps=%i'%(i,f,nclumps))

        if verbose:
            print(50*'=')


        FullSet[i+1]={}
        FullSet[i+1]['weight']=[prob_dist,prob_dist_area]
        FullSet[i+1]['mags']=GalMags
        FullSet[i+1]['posibar']=GalPositionsBar
        FullSet[i+1]['posimax']=GalPositionsMax
        FullSet[i+1]['dist']=GalDistances
        FullSet[i+1]['size']=GalSizes



##    Real_Sizes  = Sizes - SizesPSF

    if plot_results:
        print("mag_cat=",galmag)
        print('sky median = %.5f +- %.6f'%(sky_med,sky_std))
        print("sky_threshold = %.8f (sigma = %.8f)"%(sblimit*threshold,threshold))
        print("Redshift = %.4f"%redshift)

#        mpl.rcParams['image.cmap']='gist_stern_r'
#        mpl.rcParams['axes.labelsize']=12
#        mpl.rcParams['xtick.labelsize']=10
#        mpl.rcParams['ytick.labelsize']=10

#        rad,flux,xc,yc,q,theta = compute_sbprofile(image_smooth-sky_med,single_source_map,pixelscale)
#        radPSF,fluxPSF,xcPSF,ycPSF,qPSF,thetaPSF = compute_sbprofile(psf_image-sky_med,single_source_map_psf,pixelscale)

#==============================================================================
# PAPER FIGURE
#==============================================================================
        sidecut=40
        import matplotlib.colors as mpc
        import matplotlib.cm as cm
#        from sklearn.cluster import MeanShift, estimate_bandwidth
#        from sklearn.datasets.samples_generator import make_blobs
#
#        centers = [[1, 1], [-1, -1], [1, -1]]
#        X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)


        figS,axS=mpl.subplots()
        dmax = 20/(cosmos.angular_distance(redshift)/(180/np.pi*3600)*1000)

        new_image = (factor*image_stamp)
        hsize_new = new_image.shape[0]/2

        if 'Hband' in args.image:
            CMAP='Reds_r'
        elif 'Iband' in args.image:
            CMAP='YlGnBu_r'
        else:
            CMAP='viridis'

        VMAX = np.amax(new_image[hsize_new-15:hsize_new+15,hsize_new-15:hsize_new+15])
        axS.imshow(np.abs(new_image),cmap=CMAP,extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale),vmax=VMAX)

        mi.gen_circle(axS,0,0,dmax,color='white',lw=3)
        colors = ['gold','lime','red','cyan','cyan',\
        'orange','blue','black','yellow','magenta',\
        'brown','gray','Olive','OrangeRed','Coral','Yellow','Magenta','Thistle',\
        'SpringGreen','Turquoise','RosyBrown','Silver','SlateGray','Black',\
        'Aquamarine','LimeGreen','PeachPuff','Lavender','MediumOrchid']


        P=np.array([])
        for k in range(ngals):

            single_gal_map=gal_selection.copy()
            single_gal_map[gal_selection!=(k+1)]=0
            single_gal_map[gal_selection==(k+1)]=1

            gps,nc = detect_all_clumps(FullSet[k+1],np.arange(0.1,0.8,0.1))
            P=np.append(P,gps)

            Xcen,Ycen=mi.barycenter(new_image,single_gal_map)
            GalDists = mi.dist(Ycen,Xcen,zphot_sel[:,0],zphot_sel[:,1])
            kmin = np.argmin(GalDists)
            dmin = GalDists[kmin]



#            vpair=500. #km/s
#            z_search = vpair/2.9979e5*(1+redshift)
#            z_spec_err = 0.0017*(1+redshift)
#            z_phot_err = 0.1*(1+redshift)
#            redshift_error = np.sqrt( z_search*z_search + z_spec_err*z_spec_err + z_phot_err*z_phot_err)
            vpair=500. #km/s
            redshift_error = np.sqrt( vpair*vpair + 200*200. + 20000*20000.)/2.9979e5*(1+redshift)

            if dmin < 1.0/pixelscale:
                z,zl,zu = zphot_sel[kmin,2],zphot_sel[kmin,3],zphot_sel[kmin,4]
                prob_dist = probability_zphot(z,zl,zu,redshift-redshift_error,redshift+redshift_error,plot_results=True)
            else:
                prob_dist = -99

            print('p(z), on this run',prob_dist)

            X = pixelscale*(gps[:,1]-hsize_new+0.5)
            Y = pixelscale*(gps[:,0]-hsize_new+0.5)
            axS.plot(X,Y,'o',mfc='none',mec=colors[k],ms=20,mew=3)

            S = get_segmap_level(factor*image_smooth,single_gal_map,1.0)
#            mi.draw_border(axS,S,colors[k],extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))
            NDS = define_structure(3)
            axS.contour(mi.sci_nd.binary_dilation(S,structure=NDS).astype(np.int),levels=[0.5],colors=colors[k],linewidths=3.0,extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))


        for eixo in [axS]:
            for t in eixo.xaxis.get_ticklines():
                t.set_color('white')
            for t in eixo.yaxis.get_ticklines():
                t.set_color('white')
            for side in ['left','top','bottom','right']:
                eixo.spines[side].set_color('white')

        P = P.reshape([len(P)/2,2])
        ZF=1.30
        axS.set_xlim(-hsize_new*pixelscale/ZF,hsize_new*pixelscale/ZF)
        axS.set_ylim(-hsize_new*pixelscale/ZF,hsize_new*pixelscale/ZF)
        axS.set_xlabel(r'$\Delta \alpha\ [\mathrm{arcsec}]$')
        axS.set_ylabel(r'$\Delta \delta\ [\mathrm{arcsec}]$')
#        figS.savefig('clumps_first_pass_SingleGalaxy.png')

        if args.zphot:
            fig2,ax2=mpl.subplots()
            for element in zphot_sel:
                xc,yc=element[:2]
                ax2.plot(xc,yc,'s',mfc='none',mec='k',markersize=12)

            for k in range(ngals):
                gps,nc = detect_all_clumps(FullSet[k+1],np.arange(0.1,0.8,0.1))
                Weights = FullSet[k+1]['weight']
                X = gps[:,1]
                Y = gps[:,0]
                print(X,Y,Weights)




                ax2.plot(X,Y,'o',mfc='none',mec=colors[k],ms=20,mew=3)

#        figS.savefig('../ClumpyGalaxies/images/clumps_example_SingleGalaxy.pdf')
#        figS.savefig('../ClumpyGalaxies/images/clumps_example_SingleGalaxy.png')



        fig,ax=mpl.subplots(ngals,3,figsize=(20,18))
        ax=ax.reshape(np.size(ax))
        mpl.subplots_adjust(wspace=0)
        jetcmap = cm.get_cmap('YlGnBu_r', 10) #generate a jet map with 10 values
        jet_vals = jetcmap(np.arange(10)) #extract those values as an array
        jet_vals[0] = [0., 0, 0., 0.] #change the first value
#        new_jet = mpc.LinearSegmentedColormap.from_list("newjet", jet_vals)




        for i in range(ngals):

            axnum=i*3

            single_gal_map=gal_selection.copy()
            single_gal_map[gal_selection!=(i+1)]=0
            single_gal_map[gal_selection==(i+1)]=1

            ax[axnum+1].imshow(new_image,cmap=CMAP,extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))
            ax[axnum+2].imshow(gal_selection,cmap='viridis',extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))

            nregs=[]
            nregs2=[]
#            fractions = [0.2,0.51.0]#np.linspace(0,1,101)
            for f in fractions:
                S = get_segmap_level(image_smooth,single_gal_map,f)

                clump_map_full,nr= mi.sci_nd.label(S)
                clump_map_clean,nr2 = clean_map(clump_map_full,minarea=5)
                M,P,Pm,Sc=get_clump_stats(factor*image_stamp,clump_map_clean,zeropoint)
                nregs.append(nr)
                nregs2.append(nr2)

            Xcen,Ycen=mi.barycenter(factor*image_stamp,single_gal_map)
            ax[axnum+1].set_ylim((Xcen-hsize_new-50)*pixelscale,(Xcen-hsize_new+50)*pixelscale)
            ax[axnum+1].set_xlim((Ycen-hsize_new-50)*pixelscale,(Ycen-hsize_new+50)*pixelscale)

            mi.gen_circle(ax[axnum+2],(Ycen-hsize_new)*pixelscale,(Xcen-hsize_new)*pixelscale,0.75,color='cyan',lw=2)
#            ax[axnum+2].set_ylim((Xcen-hsize_new-50)*pixelscale,(Xcen-hsize_new+50)*pixelscale)
#            ax[axnum+2].set_xlim((Ycen-hsize_new-50)*pixelscale,(Ycen-hsize_new+50)*pixelscale)


            ax[axnum].plot(np.array(fractions),nregs,'s-',color='DarkRed',label='All Disconnected')
            ax[axnum].plot(np.array(fractions),nregs2,'o-',color='Navy',label='A>10pix Disconnected')

            for f,c in zip([0.2,0.5,1.0],['red','lime','cyan','gold']):
                S = get_segmap_level(image_smooth,single_gal_map,f)
                labelmap,nr= mi.sci_nd.label(S)
#                ax[axnum+1].hlines(pixelscale*f*((new_image.shape[0]-2*sidecut)/2),-2,-1,color=c,lw=3)
#                ax[axnum+1].text(-1.5,pixelscale*f*((new_image.shape[0]-2*sidecut)/2),r'$f=%.2f$'%f,color=c,fontsize=12,va='bottom',ha='center')
                ax[axnum].vlines(f,0,nr,color=c,lw=3)
                mi.draw_border(ax[axnum+1],S,c,extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))
#                NDS = define_structure(3)
#                ax[axnum].contour(mi.sci_nd.binary_dilation(S,structure=NDS).astype(np.int),levels=[0.5],colors=c,linewidths=3.0,extent=(-hsize_new*pixelscale,hsize_new*pixelscale,-hsize_new*pixelscale,hsize_new*pixelscale))


#        for eixo in ax[1:]:
#            mi.gen_circle(eixo,hsize_new,hsize_new,(2*hsize/args.size)*args.aperture,color='red')
#            eixo.tick_params(labelleft='off',labelbottom='off')


            ax[axnum].hlines(1,0,1.1,'k',':')
            ax[axnum].set_xlim(0,1.1)
            ax[axnum].set_ylim(0,1.4*max(nregs))
            ax[axnum].set_xlabel(r'$f$')
            ax[axnum].set_ylabel(r'$N_c$')

        ax[0].legend(loc='best')
#        fig.savefig('clumps_first_pass.png')
        fig.canvas.mpl_connect('key_press_event',exit_code)
        mpl.show()
        sys.exit()

#==============================================================================
# END PAPER FIGURE
#==============================================================================
    return FullSet
def compute_size(image_list,
                 pixscales,
                 ra,
                 dec,
                 hsize,
                 threshold,
                 fractions,
                 sblimit,
                 color,
                 size=6,
                 safedist=1.0):

    nimages = len(image_list)
    Sizes = np.zeros([len(fractions) + 1, nimages])
    Fluxes = np.zeros([len(fractions) + 1, nimages])
    segflags = np.zeros(nimages)

    hsize_pix = [int(hsize / pixscales[k]) / 2 for k in range(nimages)]

    image_stamps = [
        load_data(image, ra, dec, hs)
        for image, hs in zip(image_list, hsize_pix)
    ]
    headers = [pyfits.getheader(image) for image in image_list]

    #    if np.amax(image_stamp)==np.amin(image_stamp):
    #        return Sizes - 99,-9

    zp = np.zeros(nimages)
    sblimits = np.zeros(nimages)
    for k in range(nimages):
        PHOTFLAM = float(headers[k]['PHOTFLAM'])
        PHOTPLAM = float(headers[k]['PHOTPLAM'])
        zp[k] = -2.5 * np.log10(PHOTFLAM) - 5 * np.log10(PHOTPLAM) - 2.408

    sblimits[0] = sblimit
    for k in range(nimages - 1):
        ColorCorretion = 10**(0.4 * (color[k] - (zp[0] - zp[k + 1])))
        sblimits[k + 1] = sblimit * ColorCorretion
        if args.verbose:
            print("Color Correction Term: %.5f" % ColorCorretion)
            print("New Surface Brightness Limit: %.5f counts/s/arcsec**2" %
                  sblimits[k + 1])

    dilate = define_structure(size)

    for k in range(nimages):
        if np.amax(image_stamps[k]) == np.amin(image_stamps[k]):
            segflag = -9
        else:
            segmap = mi.gen_segmap_sbthresh(image_stamps[k],
                                            hsize_pix[k],
                                            hsize_pix[k],
                                            sblimits[k],
                                            pixscales[k],
                                            thresh=threshold,
                                            Amin=args.areamin,
                                            all_detection=True)
            single_source_map = mi.select_object_map(hsize_pix[k],
                                                     hsize_pix[k],
                                                     segmap,
                                                     pixscale=pixscales[k])
            image_stamps[
                k], single_source_map, imglag, segflag = mi.image_validation(
                    image_stamps[k], single_source_map, pixscales[k], safedist)

        if np.abs(segflag) != 0:
            Sizes[:, k] -= 99
            segflags[k] = segflag
        else:
            if args.nodilation:
                dilated_map = single_source_map
            else:
                dilated_map = mi.sci_nd.binary_dilation(
                    single_source_map, structure=dilate).astype(np.int32)

            for i in range(len(fractions)):
                Sizes[i, k], TotalArea, Fluxes[
                    i, k], TotalFlux = compute_fraction_area(
                        image_stamps[k], dilated_map, fractions[i])
            Sizes[i + 1, k] = TotalArea
            Fluxes[i + 1, k] = TotalFlux

            if args.nosaving:
                mpl.rcParams['image.cmap'] = 'gist_stern_r'
                segmap[segmap != 0] /= 1
                fig, ax = mpl.subplots(2, 3, figsize=(20.6, 12))
                mpl.subplots_adjust(wspace=0.2, hspace=0.02)
                ax = ax.reshape(np.size(ax))
                ax[0].imshow(np.sqrt(np.abs(image_stamps[k])), cmap='hot')
                mi.gen_circle(ax[1],
                              hsize_pix[k],
                              hsize_pix[k],
                              hsize_pix[k] *
                              (2 * np.sqrt(2) * 0.5 / args.size),
                              color='red')
                ax[1].imshow(segmap)
                ax[2].imshow(single_source_map)

                flux_map = np.zeros(image_stamps[k].shape)
                flux_map[dilated_map == 1] = 3
                for j in range(len(Fluxes[:, k]) - 2, -1, -1):
                    flux_map[image_stamps[k] > Fluxes[j, k]] = (
                        len(Fluxes[:, k]) - j) * 4
                flux_map *= dilated_map
                imax, imin, jmax, jmin = mi.find_ij(dilated_map)
                ax[3].imshow(flux_map[imin:imax, jmin:jmax],
                             aspect='equal',
                             cmap='gist_heat_r')
                ax[3].text(12,
                           9,
                           '20',
                           color='white',
                           va='center',
                           ha='center',
                           weight='heavy')
                ax[3].text(10,
                           7.5,
                           '50',
                           color='white',
                           va='center',
                           ha='center',
                           weight='heavy')
                ax[3].text(8.5,
                           5.5,
                           '80',
                           color='white',
                           va='center',
                           ha='center',
                           weight='heavy')
                ax[3].text(6,
                           3,
                           '100',
                           color='white',
                           va='center',
                           ha='center',
                           weight='heavy')

                #        masked_neighbours = mi.sci_nd.binary_dilation(segmap - single_source_map,structure=dilate)
                compute_fraction_area(image_stamps[k],
                                      dilated_map,
                                      1.0,
                                      flux_sampling=500,
                                      draw_ax=ax[4])

                ax[5].imshow(dilated_map)

                for i in range(len(ax)):
                    if i != 4:
                        ax[i].set_xticks([])
                        ax[i].set_yticks([])

                fig.text(0.95,
                         0.50,
                         r'$\curvearrowright$',
                         va='center',
                         ha='center',
                         weight='heavy',
                         rotation=-90,
                         fontsize=150)
                #        fig.savefig('size_thresholding_example.png')
                fig.canvas.mpl_connect('key_press_event', exit_code)

    if args.nosaving:
        mpl.show()

    return Sizes, segflags
コード例 #5
0
def find_pairs_and_clumps(image_stamp,
                          redshift,
                          galmag,
                          color,
                          hsize,
                          threshold,
                          fractions,
                          sblimit,
                          pixelscale,
                          zeropoint,
                          ksky=3.0,
                          Areamin=10,
                          Aperture=0.5,
                          no_dilation=True,
                          degrade=None,
                          size=5,
                          safedist=1.0,
                          title=None,
                          plot_results=False,
                          segmap_output=False,
                          erosion=[3],
                          verbose=False,
                          ident=None):

    if np.amax(image_stamp) == np.amin(image_stamp):
        if verbose:
            print("Invalid data values: %.4f,%.4f" %
                  (np.amax(image_stamp), np.amin(image_stamp)))
        return {}

    dilate = define_structure(size)
    sky_med, sky_std = mi.sky_value(image_stamp, ksky)

    if args.error:
        factor = -1.0
    else:
        factor = 1.0

    if degrade is not None:
        N, M = image_stamp.shape
        image_stamp = mi.rebin2d(image_stamp,
                                 int(N / degrade),
                                 int(M / degrade),
                                 flux_scale=True)
        pixelscale *= degrade

    if no_dilation:
        image_smooth = mi.sci_nd.gaussian_filter(image_stamp, sigma=1.0)

    if np.abs(color) < 10:
        corrected_thresh = color_correction(threshold, color)
        new_sblimit = corrected_thresh * sblimit
        if verbose:
            print(
                "Color=%.4f\t old sb limit = %.5f\t new sb limit = %.5f counts/s/arcsec**2"
                % (color, threshold * sblimit, new_sblimit))
        threshold = corrected_thresh
    elif np.abs(color) > 10:
        if verbose:
            print("Invalid color value: %.4f" % color)
        return {}

    segmap = mi.gen_segmap_sbthresh(factor * (image_smooth - sky_med),
                                    hsize,
                                    hsize,
                                    sblimit,
                                    pixelscale,
                                    thresh=threshold,
                                    Amin=Areamin,
                                    all_detection=True)
    single_source_map = mi.select_object_map_connected(hsize,
                                                       hsize,
                                                       factor * image_smooth,
                                                       segmap,
                                                       pixscale=pixelscale,
                                                       radius=Aperture)
    image_smooth, single_source_map, imglag, segflag = mi.image_validation(
        image_smooth, single_source_map, pixelscale, safedist)

    if no_dilation:
        dilated_map = single_source_map
    else:
        dilated_map = mi.sci_nd.binary_dilation(single_source_map,
                                                structure=dilate).astype(
                                                    np.int32)

    gal_selection = galaxy_map(image_stamp, segmap, zeropoint, sky_med, factor)
    ngals = np.amax(gal_selection)
    FullSet = {}
    if verbose:
        print('Ngals=%i' % ngals)

    for i in range(ngals):
        single_gal_map = gal_selection.copy()
        single_gal_map[gal_selection != (i + 1)] = 0
        single_gal_map[gal_selection == (i + 1)] = 1

        Imap, LM = MID.local_maxims(factor * image_smooth, single_gal_map)
        Mimap, PMimap, PBimap, Simap = get_clump_stats_imap(
            factor * image_stamp, Imap, zeropoint)

        nclumps = len(Mimap)
        nclumpsbright = np.size(Mimap[Mimap < 28])
        Xcen, Ycen = mi.barycenter(factor * image_smooth, single_gal_map)
        DistsSingle = np.zeros(nclumps)
        for n in range(nclumps):
            DistsSingle[n] = pixelscale * np.sqrt((PBimap[n, 0] - Xcen) *
                                                  (PBimap[n, 0] - Xcen) +
                                                  (PBimap[n, 1] - Ycen) *
                                                  (PBimap[n, 1] - Ycen))

        if verbose:
            print('\t %i ----> \t nclumps=%i (m<28: %i)' %
                  (i, nclumps, nclumpsbright))

#        nregs=[]
#        nregs2=[]
##        fractions = [0.2,1.0]#np.linspace(0,1,101)
#        for f in fractions:
#            S = get_segmap_level(image_smooth,single_gal_map,f)
#
#            clump_map_full,nr= mi.sci_nd.label(S)
#            clump_map_clean,nr2 = clean_map(clump_map_full,minarea=Areamin)
#            M,Pb,Pm,Sc=get_clump_stats(image_stamp,clump_map_clean,zeropoint)
#            GalMags[str(f)]=M
#            GalPositionsBar[str(f)]=Pb
#            GalPositionsMax[str(f)]=Pm
#            GalSizes[str(f)]=Sc
#
#            nregs.append(nr)
#            nregs2.append(nr2)
#
#
#        for f in fractions:
#            FP = GalPositionsBar[str(f)]
#            Xcen,Ycen=GalPositionsBar['1.0'][0]
#            nclumps=np.shape(FP)[0]
#
#            DistsSingle=np.zeros(nclumps)
#            for n in range(nclumps):
#                DistsSingle[n] = pixelscale*np.sqrt((FP[n,0]-Xcen)*(FP[n,0]-Xcen)+(FP[n,1]-Ycen)*(FP[n,1]-Ycen))
#
#            GalDistances[f]=DistsSingle
#
#            if verbose:
#                print '\t %i ----> f=%.2f \t nclumps=%i'%(i,f,nclumps)

        if verbose:
            print(50 * '=')

        FullSet[i + 1] = {}
        FullSet[i + 1]['galpos'] = (Xcen, Ycen)
        FullSet[i + 1]['mags'] = Mimap
        FullSet[i + 1]['posibar'] = PBimap
        FullSet[i + 1]['posimax'] = PMimap
        FullSet[i + 1]['dist'] = DistsSingle
        FullSet[i + 1]['size'] = Simap

##    Real_Sizes  = Sizes - SizesPSF

    if plot_results:
        print("mag_cat=", galmag)
        print('sky median = %.5f +- %.6f' % (sky_med, sky_std))
        print("sky_threshold = %.8f (sigma = %.8f)" %
              (sblimit * threshold, threshold))
        print("Redshift = %.4f" % redshift)

        mpl.rcParams['image.cmap'] = 'gist_stern_r'
        mpl.rcParams['axes.labelsize'] = 12
        mpl.rcParams['xtick.labelsize'] = 10
        mpl.rcParams['ytick.labelsize'] = 10

        #        rad,flux,xc,yc,q,theta = compute_sbprofile(image_smooth-sky_med,single_source_map,pixelscale)
        #        radPSF,fluxPSF,xcPSF,ycPSF,qPSF,thetaPSF = compute_sbprofile(psf_image-sky_med,single_source_map_psf,pixelscale)

        #==============================================================================
        # PAPER FIGURE
        #==============================================================================
        sidecut = 40
        import matplotlib.colors as mpc
        import matplotlib.cm as cm

        fig, ax = mpl.subplots(2, ngals, figsize=(25, 15))
        ax = ax.reshape(np.size(ax))
        mpl.subplots_adjust(wspace=0)
        jetcmap = cm.get_cmap('YlGnBu_r',
                              10)  #generate a jet map with 10 values
        jet_vals = jetcmap(np.arange(10))  #extract those values as an array
        jet_vals[0] = [0., 0, 0., 0.]  #change the first value
        new_jet = mpc.LinearSegmentedColormap.from_list("newjet", jet_vals)

        new_image = (factor * (image_stamp))
        hsize_new = new_image.shape[0] / 2

        for i in range(ngals):

            axnum = i

            single_gal_map = gal_selection.copy()
            single_gal_map[gal_selection != (i + 1)] = 0
            single_gal_map[gal_selection == (i + 1)] = 1

            ax[axnum].imshow(
                new_image,
                cmap='YlGnBu_r',
                extent=(-hsize_new * pixelscale, hsize_new * pixelscale,
                        -hsize_new * pixelscale, hsize_new * pixelscale),
                vmin=0)

            Imap, LM = MID.local_maxims(factor * image_smooth, single_gal_map)
            Mimap, PMimap, PBimap, Simap = get_clump_stats_imap(
                factor * image_stamp, Imap, zeropoint)
            ax[axnum + ngals].imshow(
                Imap,
                cmap='viridis',
                extent=(-hsize_new * pixelscale, hsize_new * pixelscale,
                        -hsize_new * pixelscale, hsize_new * pixelscale))

            for k in range(len(Mimap)):
                pos = PMimap[k][0]
                if Mimap[k] < 28:
                    ax[axnum + ngals].plot((pos[1] - hsize_new) * pixelscale,
                                           (pos[0] - hsize_new) * pixelscale,
                                           'x',
                                           color='white')
                    ax[axnum + ngals].text((pos[1] - hsize_new) * pixelscale,
                                           (pos[0] - hsize_new) * pixelscale,
                                           '%.3f' % Mimap[k],
                                           color='white',
                                           fontsize=8,
                                           ha='left',
                                           va='bottom')

            Xcen, Ycen = FullSet[i + 1]['galpos']
            ax[axnum + ngals].set_ylim((Xcen - hsize_new - 50) * pixelscale,
                                       (Xcen - hsize_new + 50) * pixelscale)
            ax[axnum + ngals].set_xlim((Ycen - hsize_new - 50) * pixelscale,
                                       (Ycen - hsize_new + 50) * pixelscale)
            mi.gen_circle(ax[axnum], (Ycen - hsize_new) * pixelscale,
                          (Xcen - hsize_new) * pixelscale,
                          0.75,
                          color='white',
                          lw=2)

        for eixo in ax:
            eixo.set_xticks([])
            eixo.set_yticks([])

#            nregs=[]
#            nregs2=[]
##            fractions = [0.2,0.51.0]#np.linspace(0,1,101)
#            for f in fractions:
#                S = get_segmap_level(image_smooth,single_gal_map,f)
#
#                clump_map_full,nr= mi.sci_nd.label(S)
#                clump_map_clean,nr2 = clean_map(clump_map_full,minarea=5)
#                M,P,Pm,Sc=get_clump_stats(image_stamp,clump_map_clean,zeropoint)
#                nregs.append(nr)
#                nregs2.append(nr2)
#
#            for f in fractions:
#                FP = GalPositionsBar[str(f)]
#                FPm = GalPositionsMax[str(f)]
#
#                Xcen,Ycen=GalPositionsBar['1.0'][0]
#                nclumps=np.shape(FP)[0]
#
#                DistsSingle=np.zeros(nclumps)
#                for n in range(nclumps):
#                    DistsSingle[n] = pixelscale*np.sqrt((FP[n,0]-Xcen)*(FP[n,0]-Xcen)+(FP[n,1]-Ycen)*(FP[n,1]-Ycen))
#
#                GalDistances[f]=DistsSingle
#
#            ax[axnum].plot(np.array(fractions),nregs,'s-',color='DarkRed',label='All Disconnected')
#            ax[axnum].plot(np.array(fractions),nregs2,'o-',color='Navy',label='A>10pix Disconnected')
#
#            for f,c in zip([0.2,0.5,1.0],['red','lime','cyan','gold']):
#                S = get_segmap_level(image_smooth,single_gal_map,f)
#                labelmap,nr= mi.sci_nd.label(S)
#                ax[axnum+1].hlines(f*((new_image.shape[0]-2*sidecut)/2),5,15,color=c,lw=3)
#                ax[axnum+1].text(10,f*((new_image.shape[0]-2*sidecut)/2),r'$f=%.2f$'%f,color=c,fontsize=12,va='bottom',ha='center')
#                ax[axnum].vlines(f,0,nr,color=c,lw=3)
#                mi.draw_border(ax[axnum+1],S,c)
#
##        for eixo in ax[1:]:
##            mi.gen_circle(eixo,hsize_new,hsize_new,(2*hsize/args.size)*args.aperture,color='red')
##            eixo.tick_params(labelleft='off',labelbottom='off')
#
#            ax[axnum].hlines(1,0,1.1,'k',':')
#            ax[axnum].set_xlim(0,1.1)
#            ax[axnum].set_ylim(0,1.4*max(nregs))
#            ax[axnum].set_xlabel(r'$f$')
#            ax[axnum].set_ylabel(r'$N_c$')

#        ax[0].legend(loc='best')
#        fig.savefig('clumps_first_pass_INTESNITY.png')
        fig.canvas.mpl_connect('key_press_event', exit_code)
        mpl.show()
        sys.exit()


#==============================================================================
# END PAPER FIGURE
#==============================================================================
    return FullSet