示例#1
1
    def test_convolve2d_king(self):
        
        gfn = lambda r, s: np.power(2*np.pi*s**2,-1)*np.exp(-r**2/(2*s**2))
        kfn = lambda r, s, g: np.power(2*np.pi*s**2,-1)*(1.-1./g)* \
            np.power(1+0.5/g*(r/s)**2,-g)

        kfn0 = lambda x, y, mux, muy, s, g: kfn(np.sqrt((x-mux)**2+(y-muy)**2),s,g)

        xaxis = Axis.create(-3,3,501)
        yaxis = Axis.create(-3,3,501)

        x, y = np.meshgrid(xaxis.center,yaxis.center)
        xbin, ybin = np.meshgrid(xaxis.width,yaxis.width)

        r = np.sqrt(x**2+y**2)

        # Scalar Input

        mux = 0.5
        muy = -0.2
        mur = (mux**2+muy**2)**0.5

        gsig = 0.1
        ksig = 0.2
        kgam = 4.0

        fval0 = np.sum(kfn0(x,y,mux,muy,ksig,kgam)*gfn(r,gsig)*xbin*ybin)
        fval1 = convolve2d_king(lambda t: gfn(t,gsig),mur,ksig,kgam,3.0,
                                nstep=10000)
#        fval2 = convolve2d_gauss(lambda t: kfn(t,ksig,kgam),mur,gsig,3.0,
#                                 nstep=1000)
#        print fval0, fval1, fval2, fval1/fval0

        assert_almost_equal(fval0,fval1,4)
示例#2
0
    def test_convolve2d_king(self):

        gfn = lambda r, s: np.power(2 * np.pi * s**2, -1) * np.exp(-r**2 /
                                                                   (2 * s**2))
        kfn = lambda r, s, g: np.power(2*np.pi*s**2,-1)*(1.-1./g)* \
            np.power(1+0.5/g*(r/s)**2,-g)

        kfn0 = lambda x, y, mux, muy, s, g: kfn(
            np.sqrt((x - mux)**2 + (y - muy)**2), s, g)

        xaxis = Axis.create(-3, 3, 501)
        yaxis = Axis.create(-3, 3, 501)

        x, y = np.meshgrid(xaxis.center, yaxis.center)
        xbin, ybin = np.meshgrid(xaxis.width, yaxis.width)

        r = np.sqrt(x**2 + y**2)

        # Scalar Input

        mux = 0.5
        muy = -0.2
        mur = (mux**2 + muy**2)**0.5

        gsig = 0.1
        ksig = 0.2
        kgam = 4.0

        fval0 = np.sum(
            kfn0(x, y, mux, muy, ksig, kgam) * gfn(r, gsig) * xbin * ybin)
        fval1 = convolve2d_king(lambda t: gfn(t, gsig),
                                mur,
                                ksig,
                                kgam,
                                3.0,
                                nstep=10000)
        #        fval2 = convolve2d_gauss(lambda t: kfn(t,ksig,kgam),mur,gsig,3.0,
        #                                 nstep=1000)
        #        print fval0, fval1, fval2, fval1/fval0

        assert_almost_equal(fval0, fval1, 4)
示例#3
0
    def createFromFITS(fitsfile,ihdu=0):
        
        hdulist = fits.open(fitsfile)        
        header = hdulist[ihdu].header
        wcs = WCS(header,naxis=[1,2],relax=True)

        hdunames = [t.name for t in hdulist]
        
        if 'ENERGIES' in hdunames and hdulist[1].name == 'ENERGIES':

            v = bintable_to_array(hdulist[1].data)
            v = np.log10(v)
            energy_axis = Axis.createFromArray(v)

            axes = copy.deepcopy(FITSAxis.create_axes(header))

            axes[2]._crval = energy_axis.edges[0]
            axes[2]._delta = energy_axis.width[0]
            axes[2]._crpix = 0.0

        else:        
            axes = copy.deepcopy(FITSAxis.create_axes(header))
        return SkyCube(wcs,axes,
                       copy.deepcopy(hdulist[ihdu].data.astype(float).T))
示例#4
0
    def test_convolve2d_gauss(self):

        gfn0 = lambda x, y, mux, muy, s: np.power(2*np.pi*s**2,-1)* \
            np.exp(-((x-mux)**2+(y-muy)**2)/(2*s**2))

        gfn1 = lambda r, s: np.power(2*np.pi*s**2,-1)*np.exp(-r**2/(2*s**2))
        
        

        xaxis = Axis.create(-3,3,501)
        yaxis = Axis.create(-3,3,501)

        x, y = np.meshgrid(xaxis.center,yaxis.center)
        xbin, ybin = np.meshgrid(xaxis.width,yaxis.width)

        # Scalar Input

        sigma0 = 0.1
        sigma1 = 0.2

        mux = 0.5
        muy = -0.2
        mur = (mux**2+muy**2)**0.5

        fval0 = np.sum(gfn0(x,y,mux,muy,sigma1)*gfn0(x,y,0,0,sigma0)*xbin*ybin)
        fval1 = convolve2d_gauss(lambda t: gfn1(t,sigma0),mur,sigma1,3.0,
                                 nstep=1000)

        assert_almost_equal(fval0,fval1,4)

        # Vector Input for Gaussian Width

        sigma0 = 0.1
        sigma1 = np.array([0.1,0.15,0.2])

        mux = 0.5
        muy = -0.2
        mur = (mux**2+muy**2)**0.5

        fval0 = []
        for i in range(len(sigma1)):
            fval0.append(np.sum(gfn0(x,y,mux,muy,sigma1[i])*
                           gfn0(x,y,0,0,sigma0)*xbin*ybin))
        
        fval1 = convolve2d_gauss(lambda t: gfn1(t,sigma0),mur,sigma1,3.0,
                                 nstep=1000)

        assert_almost_equal(np.ravel(fval0),np.ravel(fval1),4)

        # Vector Input

        sigma0 = 0.1
        sigma1 = 0.2

        mux = np.array([0.3,0.4,0.5])
        muy = np.array([-0.2,-0.2,0.2])
        mur = (mux**2+muy**2)**0.5

        fval0 = []
        for i in range(len(mux)):
            fval0.append(np.sum(gfn0(x,y,mux[i],muy[i],sigma1)*
                                gfn0(x,y,0,0,sigma0)*
                                xbin*ybin))

        fval1 = convolve2d_gauss(lambda t: gfn1(t,sigma0),mur,sigma1,3.0,
                                 nstep=1000)

        assert_almost_equal(fval0,fval1,4)
示例#5
0
    def make_image_plot(self,subplot,h,fig,fig2,title,rpsf68,rpsf95,
                        smooth=False,
                        resid_type=None,mc_resid=None,**kwargs):

        plt.figure(fig.get_label())

        cb_label='Counts'

        if resid_type == 'significance':
            kwargs['vmin'] = -5
            kwargs['vmax'] = 5
            kwargs['levels'] = [-5.0,-3.0,3.0,5.0]
            cb_label = 'Significance [$\sigma$]'
        elif resid_type == 'fractional':
            kwargs['vmin'] = -1.0
            kwargs['vmax'] = 1.0
            kwargs['levels'] = [-1.0,-0.5,0.5,1.0]
            cb_label = 'Fractional Residual'

        if smooth:
            kwargs['beam_size'] = [self._rsmooth,self._rsmooth,0.0,4]
            
        axim = h.plot(subplot=subplot,cmap='ds9_b',**kwargs)
        h.plot_circle(rpsf68,color='w',lw=1.5)
        h.plot_circle(rpsf95,color='w',linestyle='--',lw=1.5)
        h.plot_marker(marker='+',color='w',linestyle='--')
        ax = h.ax()
        ax.set_title(title)
        cb = plt.colorbar(axim,orientation='horizontal',
                          shrink=0.9,pad=0.15,
                          fraction=0.05)

        cb.set_label(cb_label)

        cat = Catalog.get('3fgl')
        cat.plot(h,ax=ax,src_color='w',label_threshold=5.0)

        if resid_type is None: return
        
        plt.figure(fig2.get_label())        
        ax2 = fig2.add_subplot(subplot)

        z = h.counts[10:-10,10:-10]

        if resid_type == 'significance':
            zproj_axis = Axis.create(-6,6,120)
        elif resid_type == 'fractional':
            zproj_axis = Axis.create(-1.0,1.0,120)
        else:
            zproj_axis = Axis.create(-10,10,120)


        hz = Histogram(zproj_axis)
        hz.fill(np.ravel(z))

        nbin = np.prod(z.shape)
        
        hz_mc = Histogram(zproj_axis)    
        
        if mc_resid:
            for mch in mc_resid:
                z = mch.counts[10:-10,10:-10]
                hz_mc.fill(np.ravel(z))

            hz_mc /= float(len(mc_resid))

            
        fn = lambda t : 1./np.sqrt(2*np.pi)*np.exp(-t**2/2.)
        
        hz.plot(label='Data',linestyle='None')

        if resid_type == 'significance':
            plt.plot(hz.axis().center,
                     fn(hz.axis().center)*hz.axis().width*nbin,
                     color='k',label='Gaussian ($\sigma = 1$)')
        
        hz_mc.plot(label='MC',hist_style='line')
        plt.gca().grid(True)
        plt.gca().set_yscale('log')
        plt.gca().set_ylim(0.5)

        ax2.legend(loc='upper right',prop= {'size' : 10 })

        data_stats = 'Mean = %.2f\nRMS = %.2f'%(hz.mean(),hz.stddev())
        mc_stats = 'MC Mean = %.2f\nMC RMS = %.2f'%(hz_mc.mean(),
                                                    hz_mc.stddev())
        
        ax2.set_xlabel(cb_label)
        ax2.set_title(title)
        ax2.text(0.05,0.95,
                 '%s\n%s'%(data_stats,mc_stats),
                 verticalalignment='top',
                 transform=ax2.transAxes,fontsize=10)
示例#6
0
    def make_image_plot(self,
                        subplot,
                        h,
                        fig,
                        fig2,
                        title,
                        rpsf68,
                        rpsf95,
                        smooth=False,
                        resid_type=None,
                        mc_resid=None,
                        **kwargs):

        plt.figure(fig.get_label())

        cb_label = 'Counts'

        if resid_type == 'significance':
            kwargs['vmin'] = -5
            kwargs['vmax'] = 5
            kwargs['levels'] = [-5.0, -3.0, 3.0, 5.0]
            cb_label = 'Significance [$\sigma$]'
        elif resid_type == 'fractional':
            kwargs['vmin'] = -1.0
            kwargs['vmax'] = 1.0
            kwargs['levels'] = [-1.0, -0.5, 0.5, 1.0]
            cb_label = 'Fractional Residual'

        if smooth:
            kwargs['beam_size'] = [self._rsmooth, self._rsmooth, 0.0, 4]

        axim = h.plot(subplot=subplot, cmap='ds9_b', **kwargs)
        h.plot_circle(rpsf68, color='w', lw=1.5)
        h.plot_circle(rpsf95, color='w', linestyle='--', lw=1.5)
        h.plot_marker(marker='x', color='w', linestyle='--')
        ax = h.ax()
        ax.set_title(title)
        cb = plt.colorbar(axim,
                          orientation='horizontal',
                          shrink=0.9,
                          pad=0.15,
                          fraction=0.05)

        if kwargs.get('zscale', None) is not None:
            import matplotlib.ticker
            cb.locator = matplotlib.ticker.MaxNLocator(nbins=5)
            cb.update_ticks()

        cb.set_label(cb_label)

        cat = Catalog.get('3fgl')
        cat.plot(h,
                 ax=ax,
                 src_color='w',
                 label_threshold=self._srclabels_thresh)

        if resid_type is None: return

        plt.figure(fig2.get_label())
        ax2 = fig2.add_subplot(subplot)

        z = h.counts[10:-10, 10:-10]

        if resid_type == 'significance':
            zproj_axis = Axis.create(-6, 6, 120)
        elif resid_type == 'fractional':
            zproj_axis = Axis.create(-1.0, 1.0, 120)
        else:
            zproj_axis = Axis.create(-10, 10, 120)

        hz = Histogram(zproj_axis)
        hz.fill(np.ravel(z))

        nbin = np.prod(z.shape)

        hz_mc = Histogram(zproj_axis)

        if mc_resid:
            for mch in mc_resid:
                z = mch.counts[10:-10, 10:-10]
                hz_mc.fill(np.ravel(z))

            hz_mc /= float(len(mc_resid))

        fn = lambda t: 1. / np.sqrt(2 * np.pi) * np.exp(-t**2 / 2.)

        hz.plot(label='Data', linestyle='None')

        if resid_type == 'significance':
            plt.plot(hz.axis().center,
                     fn(hz.axis().center) * hz.axis().width * nbin,
                     color='k',
                     label='Gaussian ($\sigma = 1$)')

        hz_mc.plot(label='MC', hist_style='line')
        plt.gca().grid(True)
        plt.gca().set_yscale('log')
        plt.gca().set_ylim(0.5)

        ax2.legend(loc='upper right', prop={'size': 10})

        data_stats = 'Mean = %.2f\nRMS = %.2f' % (hz.mean(), hz.stddev())
        mc_stats = 'MC Mean = %.2f\nMC RMS = %.2f' % (hz_mc.mean(),
                                                      hz_mc.stddev())

        ax2.set_xlabel(cb_label)
        ax2.set_title(title)
        ax2.text(0.05,
                 0.95,
                 '%s\n%s' % (data_stats, mc_stats),
                 verticalalignment='top',
                 transform=ax2.transAxes,
                 fontsize=10)
示例#7
0
    parser.add_argument('--labels', default=None)
    parser.add_argument('--colors', default=None)
    parser.add_argument('--ylim_ratio', default='0.6/1.4')
    parser.add_argument('--prefix', default='')

    args = parser.parse_args()

    labels = args.labels.split(',')

    if args.colors: colors = args.colors.split(',')
    else: colors = ['b','g','r','m','c']

    ylim_ratio = [float(t) for t in args.ylim_ratio.split('/')]
    
    hist_set = {'title' : 'test',
                'ts' : Histogram(Axis.create(0.,16.,160)),                
                'fluxul' : Histogram(Axis.create(-12,-8,100)) }
    
    pwl_hists = []
    dm_hists = []

    hists = {}
    
    results = []


    limits = {}
    
    for f in args.files:
        
#        results = AnalysisResults(f)
示例#8
0
    def test_convolve2d_gauss(self):

        gfn0 = lambda x, y, mux, muy, s: np.power(2*np.pi*s**2,-1)* \
            np.exp(-((x-mux)**2+(y-muy)**2)/(2*s**2))

        gfn1 = lambda r, s: np.power(2 * np.pi * s**2, -1) * np.exp(-r**2 /
                                                                    (2 * s**2))

        xaxis = Axis.create(-3, 3, 501)
        yaxis = Axis.create(-3, 3, 501)

        x, y = np.meshgrid(xaxis.center, yaxis.center)
        xbin, ybin = np.meshgrid(xaxis.width, yaxis.width)

        # Scalar Input

        sigma0 = 0.1
        sigma1 = 0.2

        mux = 0.5
        muy = -0.2
        mur = (mux**2 + muy**2)**0.5

        fval0 = np.sum(
            gfn0(x, y, mux, muy, sigma1) * gfn0(x, y, 0, 0, sigma0) * xbin *
            ybin)
        fval1 = convolve2d_gauss(lambda t: gfn1(t, sigma0),
                                 mur,
                                 sigma1,
                                 3.0,
                                 nstep=1000)

        assert_almost_equal(fval0, fval1, 4)

        # Vector Input for Gaussian Width

        sigma0 = 0.1
        sigma1 = np.array([0.1, 0.15, 0.2])

        mux = 0.5
        muy = -0.2
        mur = (mux**2 + muy**2)**0.5

        fval0 = []
        for i in range(len(sigma1)):
            fval0.append(
                np.sum(
                    gfn0(x, y, mux, muy, sigma1[i]) *
                    gfn0(x, y, 0, 0, sigma0) * xbin * ybin))

        fval1 = convolve2d_gauss(lambda t: gfn1(t, sigma0),
                                 mur,
                                 sigma1,
                                 3.0,
                                 nstep=1000)

        assert_almost_equal(np.ravel(fval0), np.ravel(fval1), 4)

        # Vector Input

        sigma0 = 0.1
        sigma1 = 0.2

        mux = np.array([0.3, 0.4, 0.5])
        muy = np.array([-0.2, -0.2, 0.2])
        mur = (mux**2 + muy**2)**0.5

        fval0 = []
        for i in range(len(mux)):
            fval0.append(
                np.sum(
                    gfn0(x, y, mux[i], muy[i], sigma1) *
                    gfn0(x, y, 0, 0, sigma0) * xbin * ybin))

        fval1 = convolve2d_gauss(lambda t: gfn1(t, sigma0),
                                 mur,
                                 sigma1,
                                 3.0,
                                 nstep=1000)

        assert_almost_equal(fval0, fval1, 4)
    parser.add_argument('--colors', default=None)
    parser.add_argument('--ylim_ratio', default='0.6/1.4')
    parser.add_argument('--prefix', default='')

    args = parser.parse_args()

    labels = args.labels.split(',')

    if args.colors: colors = args.colors.split(',')
    else: colors = ['b', 'g', 'r', 'm', 'c']

    ylim_ratio = [float(t) for t in args.ylim_ratio.split('/')]

    hist_set = {
        'title': 'test',
        'ts': Histogram(Axis.create(0., 16., 160)),
        'fluxul': Histogram(Axis.create(-12, -8, 100))
    }

    pwl_hists = []
    dm_hists = []

    hists = {}

    results = []

    limits = {}

    for f in args.files:

        #        results = AnalysisResults(f)