Beispiel #1
0
    def doplot(self):
        tab = Table(2, 1)
        tab.title = self.title

        xfit, yfit, gprior = self.get_prior_vals()

        nrand = 100000
        binsize = self.binsize
        h = self.h
        h1 = self.h1
        h2 = self.h2

        g1rand, g2rand = gprior.sample2d(nrand)
        grand = gprior.sample1d(nrand)

        hrand = histogram(grand, binsize=binsize, min=0.0, max=1.0, more=True)
        h1rand = histogram(g1rand, binsize=binsize, min=-1.0, max=1.0, more=True)

        fbinsize = xfit[1] - xfit[0]
        hrand["hist"] = hrand["hist"] * float(yfit.sum()) / hrand["hist"].sum() * fbinsize / binsize
        h1rand["hist"] = h1rand["hist"] * float(h1["hist"].sum()) / h1rand["hist"].sum()

        pltboth = FramedPlot()
        pltboth.xlabel = r"$g$"

        hplt1 = Histogram(h1["hist"], x0=h1["low"][0], binsize=binsize, color="red")
        hplt2 = Histogram(h2["hist"], x0=h2["low"][0], binsize=binsize, color="blue")
        hpltrand = Histogram(hrand["hist"], x0=hrand["low"][0], binsize=binsize, color="magenta")
        hplt1rand = Histogram(h1rand["hist"], x0=h1rand["low"][0], binsize=binsize, color="magenta")

        hplt1.label = r"$g_1$"
        hplt2.label = r"$g_2$"
        hplt1rand.label = "rand"
        hpltrand.label = "rand"
        keyboth = PlotKey(0.9, 0.9, [hplt1, hplt2, hplt1rand], halign="right")

        pltboth.add(hplt1, hplt2, hplt1rand, keyboth)
        tab[0, 0] = pltboth

        plt = FramedPlot()
        plt.xlabel = r"$|g|$"

        hplt = Histogram(h["hist"], x0=h["low"][0], binsize=binsize)
        hplt.label = "|g|"

        line = Curve(xfit, yfit, color="blue")
        line.label = "model"

        key = PlotKey(0.9, 0.9, [hplt, line, hpltrand], halign="right")
        plt.add(line, hplt, hpltrand, key)

        tab[1, 0] = plt

        if self.show:
            tab.show()

        return tab
Beispiel #2
0
    def plot(self, yrange=None):
        from biggles import FramedPlot, Points, Curve, PlotKey, Table,PlotLabel

        res=self.res

        etrue = res['etrue']
        e1true = res['e1true']
        e2true = res['e2true']

        facvals = res['facvals']
        sigma = res['sigma']
        e1=res['e1']
        e2=res['e2']
        e=res['e']

        T=res['T']
        Ttrue=res['Ttrue']*facvals**2


        e_pdiff = e/etrue-1
        T_pdiff = T/Ttrue-1
        

        compc= Curve(sigma, sigma*0)

        ce = Curve(sigma, e_pdiff, color='red')
        pe = Points(sigma, e_pdiff, type='filled circle')

        e_plt = FramedPlot()
        e_plt.add(ce,pe,compc)
        e_plt.xlabel = r'$\sigma$'
        e_plt.ylabel = r'$e/e_{true}-1$'

        cT = Curve(sigma, T_pdiff, color='red')
        pT = Points(sigma, T_pdiff, type='filled circle')

        T_plt = FramedPlot()
        T_plt.add(cT,pT,compc)
        T_plt.xlabel = r'$\sigma$'
        T_plt.ylabel = r'$T/T_{true}-1$'

        lab=PlotLabel(0.9,0.9,self.model,halign='right')
        T_plt.add(lab)

        if yrange is not None:
            e_plt.yrange=yrange
            T_plt.yrange=yrange
        
        tab=Table(2,1)

        tab[0,0] = T_plt
        tab[1,0] = e_plt


        tab.show()
Beispiel #3
0
    def compare_r(self, run, recache=False):
        self.load_matches(run, recache=recache)
        if self.match_data is None:
            return

        binsize=0.025
        min = 0.0
        max = 1.1

        tab = Table(2,1) 

        plt, pltdiff = self.compare_plots('r', min, max, binsize)
        tab[0,0] = plt
        tab[1,0] = pltdiff
        tab.show()
def main():
    biggles.configure('default','fontsize_min',2.0)
    s2n,r50=read_data()

    tab=Table(1,2)

    tab[0,0] = make_s2n_plot(s2n)
    tab[0,1] = make_r50_plot(r50)

    epsfile='/u/ki/esheldon/public_html/tmp/tmp.eps'
    print(epsfile)
    tab.write_eps(epsfile)

    pngfile=epsfile.replace('.eps','.png')
    print(pngfile)
    tab.write_img(800,800,pngfile)
Beispiel #5
0
def test_xi_converge_nplk(epsfile=None):
    """
    Test how xi converges with the number of k points per log10(k)
    Note we should test other convergence factors too!
    """

    tab=Table(2,1) 
    pltbig = FramedPlot()
    pltzoom = FramedPlot()

    pltbig.xlabel='r'
    pltbig.ylabel='xi(r)'
    pltbig.xlog=True
    pltbig.ylog=True
    pltzoom.xlabel='r'
    pltzoom.ylabel='xi(r)'

    l=Linear()
    r=10.0**linspace(0.0,2.3,1000) 
    nplk_vals  = [20,60,100,140,160]
    color_vals = ['blue','skyblue','green','orange','magenta','red']

    plist=[]
    lw=2.4
    for nplk,color in zip(nplk_vals,color_vals):
        print 'nplk:',nplk
        xi =  l.xi(r, nplk=nplk)

        limxi = where(xi < 1.e-5, 1.e-5, xi)
        climxi = Curve(r,limxi,color=color,linewidth=lw)
        climxi.label = 'nplk: %i' % nplk
        pltbig.add(climxi)

        plist.append(climxi)

        w=where1(r > 50.0)
        cxi = Curve(r[w], xi[w], color=color, linewidth=lw)
        pltzoom.add(cxi)

    key = PlotKey(0.7,0.8, plist)
    pltzoom.add(key)
    tab[0,0] = pltbig
    tab[1,0] = pltzoom
    if epsfile is not None:
        tab.write_eps(epsfile)
    else:
        tab.show()
Beispiel #6
0
    def plot_fits(self, st):
        import biggles

        biggles.configure("default", "fontsize_min", 2)
        parnames = ["A", "a", "g0", "gmax"]

        npars = len(parnames)
        tab = Table(npars, 1)

        magmiddle = (st["minmag"] + st["maxmag"]) / 2
        for i in xrange(npars):

            yval = st["pars"][:, i]
            yerr = st["perr"][:, i]

            ymean = yval.mean()
            ystd = yval.std()
            yrange = [ymean - 3.5 * ystd, ymean + 3.5 * ystd]

            pts = Points(magmiddle, yval, type="filled circle")
            yerrpts = SymmetricErrorBarsY(magmiddle, yval, yerr)
            xerrpts = ErrorBarsX(yval, st["minmag"], st["maxmag"])

            plt = FramedPlot()
            plt.yrange = yrange
            plt.add(pts, xerrpts, yerrpts)
            plt.xlabel = "mag"
            plt.ylabel = parnames[i]

            tab[i, 0] = plt

        if self.show:
            tab.show()

        d = files.get_prior_dir()
        d = os.path.join(d, "plots")
        epsfile = "pofe-pars-%s.eps" % self.otype
        epsfile = os.path.join(d, epsfile)
        eu.ostools.makedirs_fromfile(epsfile)
        print epsfile
        tab.write_eps(epsfile)
        os.system("converter -d 100 %s" % epsfile)
Beispiel #7
0
    def plot_fits(self,st):
        import biggles
        biggles.configure( 'default', 'fontsize_min', 2)
        parnames=['A','a','g0','gmax']

        npars=len(parnames)
        tab=Table(npars,1)

        magmiddle=(st['minmag'] + st['maxmag'])/2
        for i in xrange(npars):

            yval=st['pars'][:,i]
            yerr=st['perr'][:,i]

            ymean=yval.mean()
            ystd=yval.std()
            yrange=[ymean-3.5*ystd, ymean+3.5*ystd]
            
            pts=Points(magmiddle, yval, type='filled circle')
            yerrpts=SymmetricErrorBarsY(magmiddle,yval,yerr)
            xerrpts=ErrorBarsX(yval, st['minmag'], st['maxmag'])

            
            plt=FramedPlot()
            plt.yrange=yrange
            plt.add(pts,xerrpts, yerrpts)
            plt.xlabel='mag'
            plt.ylabel=parnames[i]

            tab[i,0] = plt

        if self.show:
            tab.show()

        d=files.get_prior_dir()
        d=os.path.join(d, 'plots')
        epsfile='pofe-pars-%s.eps' % self.otype
        epsfile=os.path.join(d,epsfile)
        eu.ostools.makedirs_fromfile(epsfile)
        print epsfile
        tab.write_eps(epsfile)
        os.system('converter -d 100 %s' % epsfile)
Beispiel #8
0
    def plot_fits(self,st):
        import biggles
        biggles.configure( 'default', 'fontsize_min', 2)
        if self.objtype=='gexp':
            parnames=['A','a','g0','gmax']

        else:
            parnames=['A','b','c']

        npars=len(parnames)
        tab=Table(npars,1)

        magmiddle=(st['minmag'] + st['maxmag'])/2
        for i in xrange(npars):

            yval=st['pars'][:,i]
            yerr=st['perr'][:,i]

            ymean=yval.mean()
            ystd=yval.std()
            yrange=[ymean-3.5*ystd, ymean+3.5*ystd]
            
            pts=Points(magmiddle, yval, type='filled circle')
            yerrpts=SymmetricErrorBarsY(magmiddle,yval,yerr)
            xerrpts=ErrorBarsX(yval, st['minmag'], st['maxmag'])

            
            plt=FramedPlot()
            plt.yrange=yrange
            plt.add(pts,xerrpts, yerrpts)
            plt.xlabel='mag'
            plt.ylabel=parnames[i]

            tab[i,0] = plt

        tab.show()
Beispiel #9
0
    def compare_ellip(self, run):
        self.load_matches(run, recache=recache)
        if self.match_data is None:
            return
        binsize=0.025
        min = -1.0
        max = 1.1

        tab = Table(2,2) 

        #
        # e1
        #

        column = 0
        for type in ['e1','e2']:

            plt, pltdiff = self.compare_plots(type, min, max, binsize)
            tab[0,column] = plt
            tab[1,column] = pltdiff

            column += 1

        tab.show()
Beispiel #10
0
    def doplot(self, fitres, h1, h2, h, minmag, maxmag):
        tab=Table(2,1)
        tab.title='%s %.2f %.2f ' % (self.objtype, minmag, maxmag)

        #xfit,yfit,gprior = self.get_prior_vals(fitres, h)
        gprior=self.get_prior(fitres)

        nrand=100000
        binsize=self.binsize


        g1rand,g2rand=gprior.sample2d(nrand)
        grand=gprior.sample1d(nrand)

        hrand=histogram(grand, binsize=binsize, min=0., max=1., more=True)
        h1rand=histogram(g1rand, binsize=binsize, min=-1., max=1., more=True)

        #fbinsize=xfit[1]-xfit[0]
        #hrand['hist'] = hrand['hist']*float(yfit.sum())/hrand['hist'].sum()*fbinsize/binsize
        hrand['hist'] = hrand['hist']*float(h['hist'].sum())/nrand
        h1rand['hist'] = h1rand['hist']*float(h1['hist'].sum())/h1rand['hist'].sum()


        pltboth=FramedPlot()
        pltboth.xlabel=r'$g$'

        hplt1=Histogram(h1['hist'], x0=h1['low'][0], binsize=binsize,color='red')
        hplt2=Histogram(h2['hist'], x0=h2['low'][0], binsize=binsize,color='blue')
        hpltrand=Histogram(hrand['hist'], x0=hrand['low'][0], binsize=binsize,
                           color='magenta')
        hplt1rand=Histogram(h1rand['hist'], x0=h1rand['low'][0], binsize=binsize,
                           color='magenta')

        hplt1.label=r'$g_1$'
        hplt2.label=r'$g_2$'
        hplt1rand.label='rand'
        hpltrand.label='rand'
        keyboth=PlotKey(0.9,0.9,[hplt1,hplt2,hplt1rand],halign='right')

        pltboth.add(hplt1, hplt2, hplt1rand, keyboth)
        tab[0,0]=pltboth
        

        plt=FramedPlot()
        plt.xlabel=r'$|g|$'

        hplt=Histogram(h['hist'], x0=h['low'][0], binsize=binsize)
        hplt.label='|g|'

        
        #line=Curve(xfit, yfit, color='blue')
        #line.label='model'

        #key=PlotKey(0.9,0.9,[hplt,line,hpltrand],halign='right')
        #plt.add(line, hplt, hpltrand, key)
        key=PlotKey(0.9,0.9,[hplt,hpltrand],halign='right')
        plt.add(hplt, hpltrand, key)


        tab[1,0]=plt
        
        if self.show:
            tab.show()

        return tab
Beispiel #11
0
    def test(self, relerr=0.2,dowrite=False, epsfile=None):
        omega_m=0.25
        z = 0.3
        nfw = lensing.nfw.NFW(omega_m, z)
        lin = lensing.linear.Linear(omega_m=omega_m)

        r200=0.5
        c=5.0
        B=1.0

        print 'generating fake data with %i%% errors' % (relerr*100,)
        nr = 21
        logrmin=-2.0
        logrmax=1.5
        r = logspace(logrmin,logrmax,nr)
        ds = nfw.dsig(r,r200,c) + B*lin.dsig(r)
        dserr = ds*relerr
        ds += dserr*numpy.random.standard_normal(nr)

        if dowrite:
            f='~/tmp/fake-dsig.dat'
            print 'Writing fake data to:',f
            colprint(r,ds,dserr,format='%0.8f', file=f)

        print 'generating fine grid truth values'
        rtrue = logspace(logrmin,logrmax,nr*5)
        dstrue  = nfw.dsig(rtrue,r200,c) + B*lin.dsig(rtrue)
        drhotrue = nfw.rho(rtrue,r200,c)  + B*lin.drho(rtrue)
        # add linear term
        mnfw = nfw.m(rtrue, r200,c)
        mlin = lin.m(rtrue, B)
        mtrue = mnfw + mlin

        print 'Doing inversion'
        odict = self.invert(r,ds,dserr=dserr)

        tab = Table(2,2)

        od = lensing.plotting.plot_dsig(odict, noshow=True)

        # show some log-interpolated points of dsig
        nper = 10
        for i in xrange(nr-1):
            amp = odict['ds_amp'][i]
            slope = odict['ds_slope'][i]
            off = odict['ds_offset'][i]
            x = logspace(log10(r[i]),log10(r[i+1]),nper)
            y = amp*x**(-slope) - off
            od['plt'].add(Curve(x,y,color='blue'))

        od['plt'].add(Curve(rtrue,dstrue,color='red'))
        tab[0,0] = od['plt']

        # plot uncorrected with no error bar
        rod = lensing.plotting.plot_drho(r=odict['rdrho'],
                                         drho=odict['drho_noendc'],
                                         drhoerr=odict['drhoerr']*0,
                                         noshow=True)
        rod2 = lensing.plotting.add_to_log_plot(rod['plt'],
                                                odict['rdrho'],
                                                odict['drho'],
                                                odict['drhoerr'],
                                                color='blue')
        
        pnocorr = rod['p']
        p = rod2['p']
        pnocorr.label = 'no end correction'
        p.label = 'end correction'

        plist = [pnocorr,p]
        drhotrue_curve = Curve(rtrue,drhotrue,color='red')
        drhotrue_curve.label = 'Truth'
        rod['plt'].add(drhotrue_curve)
        plist.append(drhotrue_curve)

        rod['plt'].add(PlotKey(0.1,0.2,plist))


        tab[0,1] = rod['plt']



        # for the mass stuff
        # first show log-interpolated points of drho to see how
        # it looks

        rod_interp = lensing.plotting.plot_drho(odict, noshow=True)
        nper = 10
        for i in xrange(odict['drho'].size-1):
            amp = odict['drho_amp'][i]
            slope = odict['drho_slope'][i]
            off = odict['drho_offset'][i]
            x = logspace(log10(r[i]),log10(r[i+1]),nper)
            y = amp*x**(-slope) - off
            y = where(y < 1.e-5, 1.e-5, y)
            rod_interp['plt'].add(Curve(x,y,color='blue'))

        tab[1,0] = rod_interp['plt']
       
        mod = lensing.plotting.plot_mass(odict, noshow=True)
        
        mp = mod['p']
        mp.label = 'Recovered Mass'

        nfw_curve = Curve(rtrue,mnfw,color='green')
        nfw_curve.label = 'NFW'
        mod['plt'].add(nfw_curve)

        lin_curve = Curve(rtrue,mlin,color='orange')
        lin_curve.label = 'linear'
        mod['plt'].add(lin_curve)

        true_curve = Curve(rtrue,mtrue,color='magenta')
        true_curve.label = 'True'
        mod['plt'].add(true_curve)

        #m200 = nfw.m200(r200)
        #m200p = Points([r200],[m200],type='cross',color='blue')
        #m200p.label = r'$M_{200} true'

        #mod['plt'].add(m200p)

        # now find r200 from the mass profile
        #mvf = MvirFinder(omega_m, z, 200)
        #rvir,rvir_err,mvir,mvir_err = mvf.find_mvir(odict['rmass'],
        #                                            odict['mass'],
        #                                            odict['masserr'])

        #mvp = Points([rvir],[mvir],type='filled square',color='red')
        #mvexp = SymErrX([rvir],[mvir],[rvir_err],color='red')
        #mveyp = SymErrY([rvir],[mvir],[mvir_err],color='red')
        #mvp.label = r'$M_{200}'

        #mod['plt'].add(mvp,mvexp,mveyp)

        #mod['plt'].add(PlotKey(0.1,0.9,[mp,true_curve,nfw_curve,lin_curve,
        #                                m200p,mvp]))
        mod['plt'].add(PlotKey(0.1,0.9,[mp,true_curve,nfw_curve,lin_curve]))


        tab[1,1] = mod['plt']


        if dowrite:
            f='~/tmp/fake-dsig-invert.dat'
            print 'Writing inverted fake data to:',f
            colprint(odict['rdrho'], odict['drho'],odict['mass'],odict['masserr'],
                     format='%20.8e',file=f)

        if epsfile is not None:
            print 'Writing eps file:',epsfile
            tab.write_eps(epsfile)
        else:
            tab.show()
Beispiel #12
0
    def plot(self, odict, epsfile=None, show=True, overdrho=True):
        """
        odict is the output of invert()
        """

        tab = Table(2,2)
        od = lensing.plotting.plot_dsig(odict, noshow=True)
        # show some log-interpolated points of dsig
        nper = 10
        r = odict['r']
        for i in xrange(r.size-1):
            amp = odict['ds_amp'][i]
            slope = odict['ds_slope'][i]
            off = odict['ds_offset'][i]
            x = logspace(log10(r[i]),log10(r[i+1]),nper)
            y = amp*x**(-slope) - off
            od['plt'].add(Curve(x,y,color='blue'))

        tab[0,0] = od['plt']

        # plot uncorrected with no error bar
        rod = lensing.plotting.plot_drho(r=odict['rdrho'],
                                         drho=odict['drho_noendc'],
                                         drhoerr=odict['drhoerr']*0,
                                         noshow=True)
        rod2 = lensing.plotting.add_to_log_plot(rod['plt'],
                                                odict['rdrho'],
                                                odict['drho'],
                                                odict['drhoerr'],
                                                color='blue')
        pnocorr = rod['p']
        p = rod2['p']
        pnocorr.label = 'no end correction'
        p.label = 'end correction'

        rod['plt'].add(PlotKey(0.1,0.2,[pnocorr,p]))
        tab[0,1] = rod['plt']


        # for the mass stuff
        # first show log-interpolated points of drho to see how
        # it looks

        rod_interp = lensing.plotting.plot_drho(odict, noshow=True)
        nper = 10
        for i in xrange(odict['drho'].size-1):
            amp = odict['drho_amp'][i]
            slope = odict['drho_slope'][i]
            off = odict['drho_offset'][i]
            x = logspace(log10(r[i]),log10(r[i+1]),nper)
            y = amp*x**(-slope) - off
            y = where(y < 1.e-5, 1.e-5, y)
            rod_interp['plt'].add(Curve(x,y,color='blue'))

        tab[1,0] = rod_interp['plt']
       

        mod = lensing.plotting.plot_mass(odict, noshow=True)
        mp = mod['p']
        mp.label = 'Mass Avg'

        odin=lensing.plotting.add_to_log_plot(mod['plt'], 
                                              odict['rmass'], 
                                              odict['massin'], 
                                              odict['massinerr'],
                                              color='green', type='filled diamond')
        pin = odin['p']
        pin.label = 'Mass In'
        mod['plt'].add(pin)

        odout=lensing.plotting.add_to_log_plot(mod['plt'], 
                                               odict['rmass'], 
                                               odict['massout'], 
                                               odict['massouterr'],
                                               color='magenta', type='filled diamond')
        
        pout = odout['p']
        pout.label = 'Mass Out'

        rhoc0 = 0.27752
        mdel = (4./3.)*PI*200*rhoc0*1.e12*odict['rmass']**3

        pdel = Curve(odict['rmass'],mdel,color='blue')
        pdel.label = r'$200 \rho_{c} V$'
        mod['plt'].add(pdel)
        mod['plt'].add(PlotKey(0.1,0.9,[mp,pin,pout,pdel]))

        tab[1,1] = mod['plt']


        if epsfile is not None:
            print 'Writing to epsfile:',epsfile
            tab.write_eps(epsfile)
        if show:
            tab.show()
Beispiel #13
0
def compare_idl(ratios=False, epsfile=None):
    from biggles import FramedPlot,Points, Table
    omega_m=0.25
    omega_b=0.055
    sigma_8=1.0
    h=1.0
    ns=0.98

    r=eu.recfile.Open('/home/esheldon/tmp/linear-compare/pkidl.dat',
                      delim=' ',dtype=[('k','f8'),('pk','f8')])
    pkidlst = r.read()
    r.close()

    k,pkidl = pkidlst['k'],pkidlst['pk']

    r=eu.recfile.Open('/home/esheldon/tmp/linear-compare/xiidl.dat',
                      delim=' ',dtype=[('r','f8'),('xi','f8')])
    xiidlst = r.read()
    r.close()

    r,xiidl = xiidlst['r'],xiidlst['xi']

    l = Linear(omega_m=omega_m,omega_b=omega_b,sigma_8=sigma_8,h=h,ns=ns)

    pk = l.pk(k)
    xi = l.xi(r, nplk=1000)
    #xi = l.xi(r)

    pkrat = pk/pkidl
    xirat = xi/xiidl

    tab=Table(2,1)

    symsize=1

    if ratios:

        pkplt = FramedPlot()
        pkplt.xlabel='k'
        pkplt.xlog=True
        pkplt.ylabel='P(k)/P(k) dave'
        pkplt.add( Points(k,pkrat,type='filled circle',size=symsize) )
        pkplt.add( Curve(k,pkrat,color='blue') )

        tab[0,0] = pkplt

 
    if ratios:

        xiplt = FramedPlot()
        xiplt.xlabel='r'
        xiplt.xlog=True

        xiplt.ylabel='xi(r)/xi(r) dave'
        xiplt.add( Points(r,xirat,type='filled circle',size=symsize) )
        xiplt.add( Curve(r,xirat,color='blue') )

        tab[1,0] = xiplt
    else:

        # big log-log plot
        limxi = where(xi < 1.e-5, 1.e-5, xi)
        #pxi = Points(r,limxi,type='filled circle',size=symsize)
        cxi = Curve(r,limxi,color='blue')

        limxiidl = where(xiidl < 1.e-5, 1.e-5, xiidl)
        #pxiidl = Points(r,limxiidl,type='filled circle',size=symsize)
        cxiidl = Curve(r,limxiidl,color='red')

        xipltall = FramedPlot()
        xipltall.xlabel='r'
        xipltall.xlog=True
        xipltall.ylog=True
        xipltall.ylabel='xi(r)'

        #xipltall.add(pxi,cxi,pxiidl,cxiidl)
        xipltall.add(cxi,cxiidl)
       
        tab[0,0] = xipltall

        # zoomed in plot
        xiplt = FramedPlot()
        xiplt.xlabel='r'
        xiplt.xlog=True
        xiplt.ylabel='xi(r)'

        pxi = Points(r,xi,type='filled circle',size=symsize) 
        cxi = Curve(r,xi,color='blue')
        cxi.label = 'Mine'

        pxiidl = Points(r,xiidl,type='filled circle',size=symsize)
        cxiidl = Curve(r,xiidl,color='red')
        cxiidl.label = 'Dave'

        key=PlotKey(0.8,0.9, [cxi,cxiidl])

        xiplt.add(pxi,cxi,pxiidl,cxiidl)
        xiplt.xrange = [50.0,r.max()]
        xiplt.yrange=[-2.e-3,1.e-2]
        xiplt.add(key)

        tab[1,0] = xiplt



    if epsfile is not None:
        tab.write_eps(epsfile)
    else:
        tab.show()
Beispiel #14
0
    def plot_detrend(self, data, e1dt, e2dt, w, camcol, rmag_min, rmag_max, 
                     coeffs, show=False):
        """
        Make a table of plots.  
        """
        band=self.band
        d=self.plotdir()
        f = 'rg-%(run)s%(band)s-meane-vs-R-%(rmag_max)0.2f-%(camcol)s-detrend.eps'
        f = f % {'run':self.procrun,'band':self.band,
                 'rmag_max':rmag_max,'camcol':camcol}
        epsfile=path_join(d,'bycamcol',f)

        # one column for each type (R,e1psf,e2psf)
        tab=Table(1,3)
        gratio=1.61803399
        #tab.aspect_ratio = 1/gratio
        tab.aspect_ratio = 1./2.

        weights = 1.0/(0.32**2 + data['uncer_rg_'+band][w]**2)
        nperbin = 200000

        # trends vs R
        print("\n* R")
        xmin=0.29
        xmax=1.01
        if band=='r':
            ymin = -0.03
            ymax =  0.03
        else:
            ymin = -0.03
            ymax =  0.06
        pe1,pe1err,pe2,pe2err,ph,t1,t2 = \
            self.make_plot_components(data['R_rg_'+band][w],
                                      data['e1_rg_'+band][w], 
                                      data['e2_rg_'+band][w], 
                                      weights, nperbin, ymin, ymax,
                                      fmin=xmin,fmax=xmax,
                                      coeffs=coeffs)

        pe1dt,pe1dterr,pe2dt,pe2dterr,phdt = \
            self.make_plot_components(data['R_rg_'+band][w],
                                      e1dt[w], 
                                      e2dt[w], 
                                      weights, nperbin, ymin, ymax,
                                      fmin=xmin,fmax=xmax)



        # one row for before and after detrend
        Ra=FramedArray(2,1)
        Ra.xrange = [xmin,xmax]
        Ra.yrange = [ymin,ymax]
        Ra.xlabel = 'R'
        Ra.ylabel = '<e>'

        rmag_lab = \
            PlotLabel(0.1,0.07,'%0.2f < rmag < %0.2f' % (rmag_min,rmag_max), 
                      halign='left')
        cflab = PlotLabel(0.1,0.15,
                          'camcol: %s filter: %s' % (camcol, self.band), 
                          halign='left')

        key = PlotKey(0.1,0.9, [pe1,pe2])
        keydt = PlotKey(0.1,0.9, [pe1dt,pe2dt])
        Rz=Curve([xmin,xmax],[0,0])
        Ra[0,0].add( Rz,pe1,pe1err,pe2,pe2err,ph,t1,t2,key)
        Ra[1,0].add( Rz,pe1dt,pe1dterr,pe2dt,pe2dterr,phdt,keydt,rmag_lab,cflab)

        if show:
            Ra.show()
        tab[0,0] = Ra

        # trends vs e1 psf
        print("\n* e1_psf")
        xmin = -0.275
        xmax =  0.275
        #ymin = -0.015
        #ymax =  0.015

        pe1psf_e1,pe1psf_e1err,pe1psf_e2,pe1psf_e2err,pe1psf_ph = \
                self.make_plot_components(data['e1_psf_'+band][w],
                                          data['e1_rg_'+band][w], 
                                          data['e2_rg_'+band][w], 
                                          weights, nperbin, ymin, ymax,
                                          fmin=xmin,fmax=xmax)

        pe1psf_e1_dt,pe1psf_e1_dterr,pe1psf_e2_dt,pe1psf_e2_dterr,pe1psf_ph_dt = \
                self.make_plot_components(data['e1_psf_'+band][w],
                                          e1dt[w], 
                                          e2dt[w], 
                                          weights, nperbin, ymin, ymax,
                                          fmin=xmin,fmax=xmax)



        # one row for before and after detrend
        e1psf_a=FramedArray(2,1)
        e1psf_a.xrange = [xmin,xmax]
        e1psf_a.yrange = [ymin,ymax]
        e1psf_a.xlabel = r'$e1_{PSF}$'
        #e1psf_a.ylabel = '<e>'

        e1psf_key = PlotKey(0.1,0.9, [pe1psf_e1,pe1psf_e2])
        e1psf_keydt = PlotKey(0.1,0.9, [pe1psf_e1_dt,pe1psf_e2_dt])
        e1psf_z=Curve([xmin,xmax],[0,0])
        e1psf_a[0,0].add(e1psf_z, 
                         pe1psf_e1,pe1psf_e1err, 
                         pe1psf_e2, pe1psf_e2err,
                         pe1psf_ph, e1psf_key)
        e1psf_a[1,0].add(e1psf_z, 
                         pe1psf_e1_dt, pe1psf_e1_dterr,
                         pe1psf_e2_dt, pe1psf_e2_dterr,
                         pe1psf_ph_dt, 
                         e1psf_keydt)

        if show:
            e1psf_a.show()
        tab[0,1] = e1psf_a


        # trends vs e2 psf
        print("\n* e2_psf")
        pe2psf_e1,pe2psf_e1err,pe2psf_e2,pe2psf_e2err,pe2psf_ph = \
                self.make_plot_components(data['e2_psf_'+band][w],
                                          data['e1_rg_'+band][w], 
                                          data['e2_rg_'+band][w], 
                                          weights, nperbin, ymin, ymax,
                                          fmin=xmin,fmax=xmax)

        pe2psf_e1_dt,pe2psf_e1_dterr,pe2psf_e2_dt,pe2psf_e2_dterr,pe2psf_ph_dt = \
                self.make_plot_components(data['e2_psf_'+band][w],
                                          e1dt[w], 
                                          e2dt[w], 
                                          weights, nperbin, ymin, ymax,
                                          fmin=xmin,fmax=xmax)



        # one row for before and after detrend
        e2psf_a=FramedArray(2,1)
        e2psf_a.xrange = [xmin,xmax]
        e2psf_a.yrange = [ymin,ymax]
        e2psf_a.xlabel = r'$e2_{PSF}$'
        #e2psf_a.ylabel = '<e>'

        e2psf_key = PlotKey(0.1,0.9, [pe2psf_e1,pe2psf_e2])
        e2psf_keydt = PlotKey(0.1,0.9, [pe2psf_e1_dt,pe2psf_e2_dt])
        e2psf_z=Curve([xmin,xmax],[0,0])
        e2psf_a[0,0].add(e2psf_z, 
                         pe2psf_e1, pe2psf_e1err,
                         pe2psf_e2, pe2psf_e2err,
                         pe2psf_ph, e2psf_key)
        e2psf_a[1,0].add(e2psf_z, 
                         pe2psf_e1_dt, pe2psf_e1_dterr,
                         pe2psf_e2_dt, pe2psf_e2_dterr,
                         pe2psf_ph_dt, 
                         e2psf_keydt)

        if show:
            e2psf_a.show()
        tab[0,2] = e2psf_a

        if show:
            tab.show()

        tab.write_eps(epsfile)
        converter.convert(epsfile, dpi=150, verbose=True)
Beispiel #15
0
    def plot_sheardiff_bys2n(self, nperbin, nperbin_sub, show=False):
        import biggles
        from biggles import FramedPlot,PlotLabel, Curve, Points, Table, PlotKey

        data=self.get_sheardiff_data()
        
        epsfile=get_shear_compare_plot_url(self['serun'],self['merun'])
        print >>stderr,'Will write summary plot:',epsfile

        print >>stderr,'histogramming shear_s2n',nperbin
        hdict=eu.stat.histogram(data['shear_s2n'],nperbin=nperbin,
                                rev=True,more=True)
        rev=hdict['rev']
        cdlist=[]
        for i in xrange(hdict['hist'].size):
            if rev[i] != rev[i+1]:
                w=rev[ rev[i]:rev[i+1] ]
                label=r'$%0.3g < S/N < %0.3g$' \
                    % (hdict['low'][i],hdict['high'][i])
                print >>stderr,label,'mean:',hdict['mean'][i],'num:',w.size
                cd=self.plot_sheardiff(nperbin_sub,indices=w,label=label,
                                       num=i,
                                       show=show)
                cdlist.append(cd)
        
        slopes1=[cd['coeff1'][0] for cd in cdlist]
        offsets1=[cd['coeff1'][1] for cd in cdlist]
        slopes2=[cd['coeff2'][0] for cd in cdlist]
        offsets2=[cd['coeff2'][1] for cd in cdlist]

        tab=Table(2,1)

        plt_slope=FramedPlot()
        cslope1 = Curve(hdict['mean'],slopes1,color='red')
        cslope2 = Curve(hdict['mean'],slopes2,color='blue')
        pslope1 = Points(hdict['mean'],slopes1,color='red',
                         type='filled circle')
        pslope2 = Points(hdict['mean'],slopes2,color='blue',
                         type='filled circle')

        cslope1.label = r'$\gamma_1$'
        cslope2.label = r'$\gamma_2$'
        key=PlotKey(0.1,0.2,[cslope1,cslope2],halign='left')

        plt_slope.add(cslope1,cslope2,pslope1,pslope2,key)
        plt_slope.xlabel = 'Shear S/N'
        plt_slope.ylabel = 'Slope'
        plt_slope.xlog=True
        plt_slope.xrange = eu.plotting.get_log_plot_range(hdict['mean'])

        plt_offset=FramedPlot()
        coffset1 = Curve(hdict['mean'],offsets1,color='red')
        coffset2 = Curve(hdict['mean'],offsets2,color='blue')
        poffset1 = Points(hdict['mean'],offsets1,color='red',
                          type='filled circle')
        poffset2 = Points(hdict['mean'],offsets2,color='blue',
                          type='filled circle')
        plt_offset.add(coffset1,coffset2,poffset1,poffset2)
        plt_offset.xlabel = 'Shear S/N'
        plt_offset.ylabel = 'Offset'
        plt_offset.xlog=True
        plt_offset.xrange = eu.plotting.get_log_plot_range(hdict['mean'])


        tab[0,0] = plt_slope
        tab[1,0] = plt_offset
        if show:
            tab.show()

        print >>stderr,'Writing summary plot:',epsfile
        tab.write_eps(epsfile)
        converter.convert(epsfile,dpi=90,verbose=True)
Beispiel #16
0
    def doplot(self, fitres, h1, h2, h, minmag, maxmag):
        tab=Table(2,1)
        tab.title='%s %.2f %.2f ' % (self.objtype, minmag, maxmag)

        #xfit,yfit,gprior = self.get_prior_vals(fitres, h)
        gprior=self.get_prior(fitres)

        nrand=100000
        binsize=self.binsize


        g1rand,g2rand=gprior.sample2d(nrand)
        grand=gprior.sample1d(nrand)

        #hrand=histogram(grand, binsize=binsize, min=0., max=1., more=True)
        hrand=histogram(grand, binsize=binsize, min=h['low'][0], max=h['high'][-1], more=True)
        h1rand=histogram(g1rand, binsize=binsize, min=-1., max=1., more=True)

        #fbinsize=xfit[1]-xfit[0]
        #hrand['hist'] = hrand['hist']*float(yfit.sum())/hrand['hist'].sum()*fbinsize/binsize
        hrand['hist'] = hrand['hist']*float(h['hist'].sum())/nrand
        h1rand['hist'] = h1rand['hist']*float(h1['hist'].sum())/h1rand['hist'].sum()


        pltboth=FramedPlot()
        pltboth.xlabel=r'$g$'

        hplt1=Histogram(h1['hist'], x0=h1['low'][0], binsize=binsize,color='red')
        hplt2=Histogram(h2['hist'], x0=h2['low'][0], binsize=binsize,color='blue')
        hpltrand=Histogram(hrand['hist'], x0=hrand['low'][0], binsize=binsize,
                           color='magenta')
        hplt1rand=Histogram(h1rand['hist'], x0=h1rand['low'][0], binsize=binsize,
                           color='magenta')

        hplt1.label=r'$g_1$'
        hplt2.label=r'$g_2$'
        hplt1rand.label='rand'
        hpltrand.label='rand'
        keyboth=PlotKey(0.9,0.9,[hplt1,hplt2,hplt1rand],halign='right')

        pltboth.add(hplt1, hplt2, hplt1rand, keyboth)
        tab[0,0]=pltboth
        

        plt=FramedPlot()
        plt.xlabel=r'$|g|$'

        hplt=Histogram(h['hist'], x0=h['low'][0], binsize=binsize)
        hplt.label='|g|'

        
        #line=Curve(xfit, yfit, color='blue')
        #line.label='model'

        #key=PlotKey(0.9,0.9,[hplt,line,hpltrand],halign='right')
        #plt.add(line, hplt, hpltrand, key)
        key=PlotKey(0.9,0.9,[hplt,hpltrand],halign='right')
        plt.add(hplt, hpltrand, key)


        tab[1,0]=plt
        
        if self.show:
            tab.show()

        d=files.get_prior_dir()
        d=os.path.join(d, 'plots')
        epsfile='pofe-%.2f-%.2f-%s.eps' % (minmag,maxmag,self.objtype)
        epsfile=os.path.join(d,epsfile)
        eu.ostools.makedirs_fromfile(epsfile)
        print epsfile
        tab.write_eps(epsfile)
        os.system('converter -d 100 %s' % epsfile)

        return tab
Beispiel #17
0
    def doplot(self, gprior, minmag, maxmag):
        from lensing.util import eta1eta2_to_g1g2

        tab = Table(2, 2)
        tab.title = "%s %.2f %.2f " % (self.otype, minmag, maxmag)

        h1_g, h2_g, h_g = self.do_histograms(minmag, maxmag, "g")
        h1_eta, h2_eta, h_eta = self.do_histograms(minmag, maxmag, "eta")

        nrand = 1000000
        binsize_eta = self.binsize_eta
        binsize_g = self.binsize_g

        rbinsize_eta = binsize_eta * 0.2
        rbinsize_g = binsize_g * 0.2

        gr = gprior.sample(nrand)
        eta1_rand = gr[:, 0]
        eta2_rand = gr[:, 1]
        eta_rand = numpy.sqrt(eta1_rand ** 2 + eta2_rand ** 2)

        g1_rand, g2_rand = eta1eta2_to_g1g2(eta1_rand, eta2_rand)
        g_rand = numpy.sqrt(g1_rand ** 2 + g2_rand ** 2)

        hrand_eta = histogram(eta_rand, binsize=rbinsize_eta, min=0, max=self.max_eta, more=True)
        h1rand_eta = histogram(eta1_rand, binsize=rbinsize_eta, min=self.min_eta_2d, max=self.max_eta_2d, more=True)

        hrand_g = histogram(g_rand, binsize=rbinsize_g, min=0, max=self.max_g, more=True)
        h1rand_g = histogram(g1_rand, binsize=rbinsize_g, min=self.min_g_2d, max=self.max_g_2d, more=True)

        # eta 2d plots
        bratio_eta = self.binsize_eta / rbinsize_eta
        hrand_eta["hist"] = hrand_eta["hist"] * bratio_eta * float(h_eta["hist"].sum()) / nrand
        h1rand_eta["hist"] = h1rand_eta["hist"] * bratio_eta * float(h1_eta["hist"].sum()) / h1rand_eta["hist"].sum()

        pltboth_eta = FramedPlot()
        pltboth_eta.xlabel = r"$\eta$"

        hplt1_eta = Histogram(h1_eta["hist"], x0=h1_eta["low"][0], binsize=binsize_eta, color="darkgreen")
        hplt2_eta = Histogram(h2_eta["hist"], x0=h2_eta["low"][0], binsize=binsize_eta, color="blue")
        hpltrand_eta = Histogram(hrand_eta["hist"], x0=hrand_eta["low"][0], binsize=rbinsize_eta, color="red")
        hplt1rand_eta = Histogram(h1rand_eta["hist"], x0=h1rand_eta["low"][0], binsize=rbinsize_eta, color="red")

        hplt1_eta.label = r"$\eta_1$"
        hplt2_eta.label = r"$\eta_2$"
        hplt1rand_eta.label = "rand"
        hpltrand_eta.label = "rand"
        keyboth_eta = PlotKey(0.9, 0.9, [hplt1_eta, hplt2_eta, hplt1rand_eta], halign="right")

        pltboth_eta.add(hplt1_eta, hplt2_eta, hplt1rand_eta, keyboth_eta)

        tab[0, 0] = pltboth_eta

        plt1d_eta = FramedPlot()
        plt1d_eta.xlabel = r"$|\eta|$"

        hplt_eta = Histogram(h_eta["hist"], x0=h_eta["low"][0], binsize=binsize_eta)
        hplt_eta.label = r"$|\eta|$"

        key_eta = PlotKey(0.9, 0.9, [hplt_eta, hpltrand_eta], halign="right")
        plt1d_eta.add(hplt_eta, hpltrand_eta, key_eta)

        tab[1, 0] = plt1d_eta

        # g plots

        bratio_g = self.binsize_g / rbinsize_g
        hrand_g["hist"] = hrand_g["hist"] * bratio_g * float(h_g["hist"].sum()) / nrand
        h1rand_g["hist"] = h1rand_g["hist"] * bratio_g * float(h1_g["hist"].sum()) / h1rand_g["hist"].sum()

        pltboth_g = FramedPlot()
        pltboth_g.xlabel = r"$g$"

        hplt1_g = Histogram(h1_g["hist"], x0=h1_g["low"][0], binsize=binsize_g, color="darkgreen")
        hplt2_g = Histogram(h2_g["hist"], x0=h2_g["low"][0], binsize=binsize_g, color="blue")
        hpltrand_g = Histogram(hrand_g["hist"], x0=hrand_g["low"][0], binsize=rbinsize_g, color="red")
        hplt1rand_g = Histogram(h1rand_g["hist"], x0=h1rand_g["low"][0], binsize=rbinsize_g, color="red")

        hplt1_g.label = r"$g_1$"
        hplt2_g.label = r"$g_2$"
        hplt1rand_g.label = "rand"
        hpltrand_g.label = "rand"
        keyboth_g = PlotKey(0.9, 0.9, [hplt1_g, hplt2_g, hplt1rand_g], halign="right")

        pltboth_g.add(hplt1_g, hplt2_g, hplt1rand_g, keyboth_g)

        tab[0, 1] = pltboth_g

        plt1d_g = FramedPlot()
        plt1d_g.xlabel = r"$|g|$"

        hplt_g = Histogram(h_g["hist"], x0=h_g["low"][0], binsize=binsize_g)
        hplt_g.label = "|g|"

        key_g = PlotKey(0.9, 0.9, [hplt_g, hpltrand_g], halign="right")
        plt1d_g.add(hplt_g, hpltrand_g, key_g)

        tab[1, 1] = plt1d_g

        if self.show:
            tab.show()

        d = files.get_prior_dir()
        d = os.path.join(d, "plots")
        epsfile = "pofe-pofeta-%.2f-%.2f-%s.eps" % (minmag, maxmag, self.otype)
        epsfile = os.path.join(d, epsfile)
        eu.ostools.makedirs_fromfile(epsfile)
        print epsfile
        tab.write_eps(epsfile)
        os.system("converter -d 100 %s" % epsfile)

        return tab
Beispiel #18
0
    def doplot(self, gprior, h1, h2, h, minmag, maxmag):
        tab=Table(2,1)
        tab.title='%s %.2f %.2f ' % (self.otype, minmag, maxmag)


        nrand=1000000
        binsize=self.binsize
        rbinsize=binsize*0.2


        gr = gprior.sample(nrand)
        g1rand=gr[:,0]
        g2rand=gr[:,1]

        grand = numpy.sqrt( g1rand**2 + g2rand**2 )

        #hrand=histogram(grand, binsize=rbinsize, min=h['low'][0], max=h['high'][-1], more=True)
        hrand=histogram(grand, binsize=rbinsize, min=0,max=self.maxe, more=True)
        h1rand=histogram(g1rand, binsize=rbinsize, min=self.mine_2d, max=self.maxe_2d, more=True)

        bratio = self.binsize/rbinsize
        hrand['hist'] = hrand['hist']*bratio*float(h['hist'].sum())/nrand
        h1rand['hist'] = h1rand['hist']*bratio*float(h1['hist'].sum())/h1rand['hist'].sum()


        pltboth=FramedPlot()
        pltboth.xlabel=r'$%s$' % self.ellip_name

        hplt1=Histogram(h1['hist'], x0=h1['low'][0], binsize=binsize,color='darkgreen')
        hplt2=Histogram(h2['hist'], x0=h2['low'][0], binsize=binsize,color='blue')
        hpltrand=Histogram(hrand['hist'], x0=hrand['low'][0], binsize=rbinsize,
                           color='red')
        hplt1rand=Histogram(h1rand['hist'], x0=h1rand['low'][0], binsize=rbinsize,
                           color='red')

        hplt1.label=r'$g_1$'
        hplt2.label=r'$g_2$'
        hplt1rand.label='rand'
        hpltrand.label='rand'
        keyboth=PlotKey(0.9,0.9,[hplt1,hplt2,hplt1rand],halign='right')

        pltboth.add(hplt1, hplt2, hplt1rand, keyboth)


        tab[0,0]=pltboth
        

        plt=FramedPlot()
        plt.xlabel=r'$|%s|$' % self.ellip_name

        hplt=Histogram(h['hist'], x0=h['low'][0], binsize=binsize)
        hplt.label='|%s|' % self.ellip_name

        
        #line=Curve(xfit, yfit, color='blue')
        #line.label='model'

        #key=PlotKey(0.9,0.9,[hplt,line,hpltrand],halign='right')
        #plt.add(line, hplt, hpltrand, key)
        key=PlotKey(0.9,0.9,[hplt,hpltrand],halign='right')
        plt.add(hplt, hpltrand, key)


        tab[1,0]=plt
        
        if self.show:
            tab.show()

        d=files.get_prior_dir()
        d=os.path.join(d, 'plots')
        epsfile='pofe-%.2f-%.2f-%s.eps' % (minmag,maxmag,self.otype)
        epsfile=os.path.join(d,epsfile)
        eu.ostools.makedirs_fromfile(epsfile)
        print epsfile
        tab.write_eps(epsfile)
        os.system('converter -d 100 %s' % epsfile)

        return tab
Beispiel #19
0
def doplot(run, st, s2n_field, setname, s2n_range, sratio_range, psfnums, nobj):
    tab=Table(2,1)

    color1='blue'
    color2='red'

    m1pts=Points(st['s2n'],st['m1'],type='filled circle',color=color1)
    m1errpts=SymmetricErrorBarsY(st['s2n'],st['m1'],st['m1_err'],color=color1)
    m2pts=Points(st['s2n'],st['m2'],type='filled circle',color=color2)
    m2errpts=SymmetricErrorBarsY(st['s2n'],st['m2'],st['m2_err'],color=color2)

    c1pts=Points(st['s2n'],st['c1'],type='filled circle',color=color1)
    c1errpts=SymmetricErrorBarsY(st['s2n'],st['c1'],st['c1_err'],color=color1)
    c2pts=Points(st['s2n'],st['c2'],type='filled circle',color=color2)
    c2errpts=SymmetricErrorBarsY(st['s2n'],st['c2'],st['c2_err'],color=color2)

    m1pts.label=r'$\gamma_1$'
    m2pts.label=r'$\gamma_2$'

    key=PlotKey(0.9,0.2,[m1pts,m2pts], halign='right')

    xrng=array( [0.5*s2n_range[0], 1.5*s2n_range[1]])
    cyrng=get_symmetric_range(st['c1'],st['c1_err'],st['c2'],st['c2_err'])
    myrng=get_symmetric_range(st['m1'],st['m1_err'],st['m2'],st['m2_err'])

    mplt=FramedPlot()
    cplt=FramedPlot()
    mplt.xlog=True
    cplt.xlog=True

    mplt.xrange=xrng
    cplt.xrange=xrng
    #mplt.yrange=myrng
    #cplt.yrange=cyrng
    mplt.yrange=[-0.15,0.15]
    cplt.yrange=[-0.01,0.01]

    mplt.xlabel=s2n_field
    mplt.ylabel='m'
    cplt.xlabel=s2n_field
    cplt.ylabel='c'

    zplt=Curve(xrng, [0,0])
    mallow=Curve(xrng, [-0.004, 0.004])
    callow=Curve(xrng, [-0.0004, 0.0004])

    mallow=FillBetween(xrng, [0.004,0.004], 
                       xrng, [-0.004,-0.004],
                       color='grey80')
    callow=FillBetween(xrng, [0.0004,0.0004], 
                       xrng, [-0.0004,-0.0004],
                       color='grey80')



    labels=get_labels(run,
                      psfnums,
                      setname,
                      nobj,
                      sratio_range)

    mplt.add( mallow, zplt, m1pts, m1errpts, m2pts, m2errpts, key )
    mplt.add(*labels)

    cplt.add( callow, zplt, c1pts, c1errpts, c2pts, c2errpts )

    tab[0,0] = mplt
    tab[1,0] = cplt

    tab.show()
Beispiel #20
0
def main():
    options,args = parser.parse_args(sys.argv[1:])

    if len(args) < 3:
        parser.print_help()
        sys.exit(1)

    run1 = args[0]
    run2 = args[1]
    bintype = args[2]

    rrange=options.rrange
    if rrange is not None:
        rrange=[float(r) for r in rrange.split(',')]

    biggles.configure('screen','width', 1400)
    biggles.configure('default','fontsize_min',1.0)

    b = lensing.binning.instantiate_binner(bintype)

    name=b.get_name()
    data1 = lensing.files.sample_read(type=options.type, sample=run1, name=name)
    data2 = lensing.files.sample_read(type=options.type, sample=run2, name=name)

    nbin=data1.size

    tab=Table(1,2)
    for i in xrange(nbin):
        tab[0,0] = plot2dsig_over(
            data1['r'][i],data1['dsig'][i],data1['dsigerr'][i],
            data2['r'][i],data2['dsig'][i],data2['dsigerr'][i],
            label1=run1,label2=run2,label=b.bin_label(i),
            show=False)
        tab[0,0].aspect_ratio=1

        pbot = FramedPlot()

        rat=data1['dsig'][i]/data2['dsig'][i]
        raterr = rat*numpy.sqrt( (data1['dsigerr'][i]/data1['dsig'][i])**2
                                +(data2['dsigerr'][i]/data2['dsig'][i])**2 )

        rpts=Points(data1['r'][i], rat, type='filled circle',color='blue')
        rerr=SymErrY(data1['r'][i], rat, raterr,color='blue')

        if rrange is None:
            rat_use,raterr_use=rat,raterr
        else:
            w,=numpy.where( (data1['r'][i] > rrange[0]) & (data1['r'][i] < rrange[1]))
            rat_use,raterr_use=rat[w],raterr[w]
        mn,err = eu.stat.wmom(rat_use, 1/raterr_use**2, calcerr=True)

        plot_rrange=[0.5*data1['r'][i].min(),data1['r'][i].max()*2]
        z=Curve(plot_rrange, [1,1])
        pbot.add(rpts,rerr,z)
        pbot.xlog=True
        pbot.xlabel = lensing.plotting.labels['rproj']
        pbot.ylabel = '%s/%s' % (run1,run2)
        pbot.yrange=[0,2]
        pbot.xrange = plot_rrange
        pbot.aspect_ratio=1

        lab='<ratio>'
        if rrange is not None:
            lab = r'$%s r \in [%.2f,%.2f]$' % (lab,rrange[0],rrange[1])

        lab='%s: %0.2f +/- %0.2f' % (lab,mn,err)
        pbot.add(PlotLabel(0.9,0.9,lab,halign='right'))

        tab[0,1] = pbot
        tab.show()

        epsfile=lensing.files.sample_file(type='binned-plots',
                                          sample=run1,
                                          name=name,
                                          extra='compare-%s-%02d' % (run2,i),
                                          ext='eps')
        print("writing:",epsfile)
        tab.write_eps(epsfile)
        if nbin > 1:
            key=raw_input('hit a key: ')
            if key.lower() == 'q':
                return
Beispiel #21
0
    def xi_int_pk_slow(self, k, Pk, r, debug=False, doplot=False):
        """
        Maybe try a slow but more accurate version here
        get xi at position r by integrating P(k). r should be a scalar

        the integral is done in two parts

        """
        import scipy.integrate

        # some of this could be pre-computed, but it might
        # not matter

        NumPerPer = 30.0
        # Number of samples per period, should always be > 5 at least
        npd = 100
        # depends on cosmology but this is ballpark                  
        L_wiggle=170.0

        Pref=1.0 /(2.0 * PI**2 * r)


        dk1=2.0 *PI/(NumPerPer*L_wiggle)
        dk2=2.0 *PI/(NumPerPer*r)
        dktry=min([dk1,dk2])


        # first section
        kmin=0.0
        kmax=2.0
        numk=int32((kmax-kmin)/dktry)
        dk=(kmax-kmin)/(1.0*numk-1)


        kk=arange(numk,dtype='f8')*dk+kmin

        # Dave used *local* cubic spline interpolation (the /spline)
        # keyword for interpol.  This seems to give radically different
        # results!  Using interpsp2 above gets us within about 6%
        # of dave's answer.  Which is right?  I think the right thing
        # to do is use more values for Pk,k and do linear interpolation

        Pkk=interplin(Pk,k,kk)
        #Pkk=interp(kk,k,Pk)
        tab=Pkk*kk*sin(kk*r)


        integ = scipy.integrate.simps(tab,x=kk)
        xi_1=Pref*integ

        if debug:
            print 'r=',r
            if dk1 < dk2:
                print 'Baryon wiggle limited' 
            else: 
                print 'Sin(k*r) limited'
            print 'Numk=',numk
            print 'dk=',dk

            integ_trap = scipy.integrate.trapz(tab,x=kk)
            integ_qg1000 = self.qg1000.integrate(kk,tab)
            print 'integ=',integ
            print 'integ_trap=',integ_trap
            print 'integ_qg1000=',integ_qg1000
            nprint=20
            
            if doplot:
                wk=where1(k < kmax)
                wkk=where1(kk > 1.e-8)

                ptab=Table(2,1)

                lplt=FramedPlot()
                lplt.add( Points(k[wk],Pk[wk],type='filled circle',size=1) )
                lplt.add( Points(kk[wkk],Pkk[wkk], color='red', 
                                 type='filled circle', size=0.7))
                lplt.add( Curve(kk[wkk],Pkk[wkk], color='blue'))
                lplt.xlog=True
                ptab[0,0] = lplt

                splt = FramedPlot()
                splt.add(Points(k[wk],Pk[wk]*k[wk]*sin(k[wk]*r),
                                type='filled circle',size=1))
                splt.add(Points(kk[wkk],tab[wkk],
                                 color='red',type='filled circle',size=0.7))
                splt.add(Curve(kk[wkk],tab[wkk], color='blue'))
                splt.xlog=True

                ptab[1,0] = splt
                ptab.show()


        # next  section/method

        # now need integral \int_xmax^infinity x P(x/r) sin(x)
        Pref2=Pref/(r**2)

        xmax=r*kmax
        num_dec=5
        num_per_dec=npd

        numx=num_dec*num_per_dec
        x=xmax*10.0**(arange(numx,dtype='f8')/num_per_dec)
        Px=interplin(Pk,k,x/r)
        y=x*Px
        ly=log(y)
        n=numx

        al=(roll(ly,-1)-ly)/(roll(x,-1)-x)
        al[n-1]=al[n-2]

        Amp=y/exp(al*x)

        # integral boundaries
        a=x
        b=roll(x,-1)

        norm=y/(1+al**2)
        Ta=al*sin(a)-cos(a)
        Tb=al*sin(b)-cos(b)
        dif=exp(al*(b-a))*Tb-Ta
        d=norm*dif
        d=d[0:n-2]

        integ=d.sum()

        xi_2=integ*Pref2
        xi=xi_1+xi_2
        if debug:
            print 'xi_1:',xi_1
            print 'xi_2:',xi_2

        return xi
Beispiel #22
0
def test(data=None, logc=False):
    from biggles import Histogram, FramedPlot, PlotKey, Table
    if data is None:
        data = read_test_data()

    
    modelflux, modelflux_ivar = avg_gri(data['modelflux'][:,1],data['modelflux_ivar'][:,1],
                                        data['modelflux'][:,2],data['modelflux_ivar'][:,2],
                                        data['modelflux'][:,3],data['modelflux_ivar'][:,3])
    #psfflux, psfflux_ivar = avg_gri(data['psfflux'][:,1],data['psfflux_ivar'][:,1],
    #                                data['psfflux'][:,2],data['psfflux_ivar'][:,2],
    #                                data['psfflux'][:,3],data['psfflux_ivar'][:,3])
    psfflux, psfflux_ivar = avg_gri(data['psfflux'][:,1],data['modelflux_ivar'][:,1],
                                    data['psfflux'][:,2],data['modelflux_ivar'][:,2],
                                    data['psfflux'][:,3],data['modelflux_ivar'][:,3])

    fmin_log=1.e-3
    fmax_log=4.


    tab = Table(2,2)
    binsize=0.05
    col=0
    for type in ['modelflux','psfflux']:

        flux_plt = FramedPlot()

        h = eu.stat.histogram(log10(data[type][:,1]), min=fmin_log, max=fmax_log, binsize=binsize)
        gmod_h = Histogram(h, x0=fmin_log, binsize=binsize, color='green')
        gmod_h.label = 'g '+type

        h = eu.stat.histogram(log10(data[type][:,2]), min=fmin_log, max=fmax_log, binsize=binsize)
        rmod_h = Histogram(h, x0=fmin_log, binsize=binsize, color='red')
        rmod_h.label = 'r '+type

        h = eu.stat.histogram(log10(data[type][:,3]), min=fmin_log, max=fmax_log, binsize=binsize)
        imod_h = Histogram(h, x0=fmin_log, binsize=binsize, color='magenta')
        imod_h.label = 'i '+type


        if type == 'modelflux':
            h = eu.stat.histogram(log10(modelflux), min=fmin_log, max=fmax_log, binsize=binsize)
        else:
            h = eu.stat.histogram(log10(psfflux), min=fmin_log, max=fmax_log, binsize=binsize)

        mod_h = Histogram(h, x0=fmin_log, binsize=binsize, width=2)
        mod_h.label = 'combined '+type

        key = PlotKey(0.5,0.9,[gmod_h, rmod_h, imod_h, mod_h])
        
        flux_plt.add(gmod_h, rmod_h, imod_h, mod_h, key)
        flux_plt.xlabel = 'flux'

        tab[0,col] = flux_plt

        col += 1



    col=0
    for logc in [False,True]:
        if logc:
            xmin=-0.1
            #xmax=1
            xmax=0.6
            binsize = 0.01
        else:
            xmin=-0.1
            xmax=1.0
            binsize = 0.01

        gc = calc_c(data['modelflux'][:,1], data['psfflux'][:,1], log=logc)
        rc = calc_c(data['modelflux'][:,2], data['psfflux'][:,2], log=logc)
        ic = calc_c(data['modelflux'][:,3], data['psfflux'][:,3], log=logc)
        allc = calc_c(modelflux, psfflux, log=logc)
        
        c_plt = FramedPlot()

        h = eu.stat.histogram(gc, min=xmin, max=xmax, binsize=binsize)
        gch = Histogram(h, x0=xmin, binsize=binsize, color='green')
        gch.label = 'g'

        h = eu.stat.histogram(rc, min=xmin, max=xmax, binsize=binsize)
        rch = Histogram(h, x0=xmin, binsize=binsize, color='red')
        rch.label = 'r'

        h = eu.stat.histogram(ic, min=xmin, max=xmax, binsize=binsize)
        ich = Histogram(h, x0=xmin, binsize=binsize, color='magenta')
        ich.label = 'i'


        h = eu.stat.histogram(allc, min=xmin, max=xmax, binsize=binsize)
        ch = Histogram(h, x0=xmin, binsize=binsize, width=2)
        ch.label = 'combined '

        key = PlotKey(0.7,0.9,[gch, rch, ich, ch])
        
        c_plt.add(gch, rch, ich, ch, key)
        if logc:
            c_plt.xlabel = r'$-log_{10}(psf/model)$'
        else:
            c_plt.xlabel = '1-psf/model'

        tab[1,col] = c_plt
        col += 1

    tab.show()
Beispiel #23
0
    def test_scinv_dz(self, beg, end, yrange=[0, 2.1e-4], show=False, reload=False, type="png"):
        """

        Test accuracy of interpolating scinv as a function of dzl, the
        lens redshift spacing.

        """
        import biggles
        from biggles import Points, FramedPlot, PlotKey, Table, Histogram, Curve
        from time import time
        import lensing
        import pcolors

        biggles.configure("default", "fontface", "HersheySans")
        biggles.configure("default", "fontsize_min", 1.3)

        zsmin = self.zs[0]
        zsmax = self.zs[-1]

        zlmin = 0.00
        zlmax = 1.0

        # dzl_vals = numpy.linspace(0.001,0.015,10)
        dzl_vals = numpy.linspace(0.001, 0.015, 4)
        nzl_vals = ((zlmax - zlmin) / dzl_vals).astype("i8")

        numcheck = len(dzl_vals)
        colors = pcolors.rainbow(numcheck, "hex")
        scalc = []
        for nzl in nzl_vals:
            s = ScinvCalculator(zlmin, zlmax, nzl, zsmin, zsmax, npts=100)
            scalc.append(s)

        times = numpy.zeros(numcheck, dtype="f8")

        # we'll fill this in
        # scinv_all = numpy.zeros( (numcheck, scalc[0].zlvals.size) )

        xlim = [0, zsmax]
        for i in xrange(beg, end):
            scinv_all = []
            pz = self.data["pofz"][i]

            # print(pz)

            for j in xrange(numcheck):
                dzl = dzl_vals[j]
                nzl = nzl_vals[j]
                print("    nzl: %s dzl: %g" % (nzl, dzl))
                tm0 = time()
                # scinv_all[j,:] = scalc[j].calc_mean_scinv(pz)
                sc = scalc[j].calc_mean_scinv(self.zs, pz)
                # sc=sc.clip(min=0.0)
                # print("sc",j,sc)
                scinv_all.append(sc)
                times[j] += time() - tm0

            print("\nplotting")

            # plot the p(z)
            tab = Table(3, 1)

            binsize = self.zs[1] - self.zs[0]
            pzh = Histogram(pz, x0=self.zs[0], binsize=binsize)
            plt_pzh = FramedPlot()
            plt_pzh.xrange = xlim

            plt_pzh.xtitle = r"$z_s$"
            plt_pzh.ytitle = r"$P(z_s)$"
            plt_pzh.add(pzh)
            tab[0, 0] = plt_pzh
            # plt_pzh.show()

            # plot scinv for each dzl
            plt_scinv = FramedPlot()
            plt_scinv.xrange = xlim

            scinv_plots = []
            for j in xrange(numcheck):
                dzl = dzl_vals[j]
                nzl = nzl_vals[j]
                p = Curve(scalc[j].zlvals, scinv_all[j], type="solid", color=colors[j])
                p.label = r"$nz_{lens}: %s dz_{lens}: %0.3f$" % (nzl, dzl)

                plt_scinv.add(p)
                scinv_plots.append(p)

            scinv_key = PlotKey(0.95, 0.9, scinv_plots, halign="right")
            plt_scinv.add(scinv_key)

            plt_scinv.ylabel = r"$\Sigma_{crit}^{-1}(z_{lens})$"
            plt_scinv.xlabel = r"$z_{lens}$"
            plt_scinv.yrange = yrange

            # plt_scinv.show()
            tab[1, 0] = plt_scinv

            # %diff to best dz

            plt_pdiff = FramedPlot()
            plt_pdiff.xrange = xlim
            plt_pdiff.yrange = [-0.05, 0.05]
            pdiff_plots = []

            zl_interp = numpy.linspace(zlmin, zlmax, 1000)
            scinv_interp_best = esutil.stat.interplin(scinv_all[0], scalc[0].zlvals, zl_interp)

            w = where1(scinv_interp_best > 0)
            for j in xrange(numcheck):
                dzl = dzl_vals[j]
                nzl = nzl_vals[j]

                scinv_interp = esutil.stat.interplin(scinv_all[j], scalc[j].zlvals, zl_interp)

                if w.size > 0:
                    pdiff = scinv_interp[w] / scinv_interp_best[w] - 1.0
                    p = Curve(zl_interp[w], pdiff, type="solid", color=colors[j])
                else:
                    pdiff = numpy.ones(scinv_interp.size)
                    p = Curve(zl_interp, pdiff, type="solid", color=colors[j])

                p.label = r"$nz_{lens}: %s dz_{lens}: %0.3f$" % (nzl, dzl)

                plt_pdiff.add(p)
                pdiff_plots.append(p)

            key = PlotKey(0.95, 0.9, pdiff_plots, halign="right")
            plt_pdiff.add(key)

            plt_pdiff.ylabel = r"$\Sigma_{crit}^{-1} /  \Sigma_{crit}^{-1}_{best} - 1$"
            plt_pdiff.xlabel = r"$z_{lens}$"

            tab[2, 0] = plt_pdiff

            if show:
                tab.show()

            plotfile = self.dzl_plot_file(i, type)
            print("writing to file:", plotfile)
            if type == "png":
                tab.write_img(1000, 1000, plotfile)
            else:
                tab.write_eps(plotfile)

        for j in xrange(numcheck):
            dzl = dzl_vals[j]
            print("time dzl=%s: %s" % (dzl, times[j]))
Beispiel #24
0
def plot_lens_s2n(zl, zslow, zshigh, pzs, cumulative=True):
    """

    Calculate the cumulative expected usefulness of lenses as a function of
    redshift for the given source N(z).

    """

    import biggles
    from biggles import FramedPlot, Curve, PlotLabel, PlotKey, Table, Histogram

    biggles.configure('screen','width',1140)
    biggles.configure('screen','height',1140)
    nzl=zshigh.size
    zlmin = 0.0
    zlmax = max([zl.max(), zshigh.max()])

    # first get the mean inverse critical density as a function
    # of lens redshift
    zsmid = (zshigh+zslow)/2.
    sc = lensing.sigmacrit.ScinvCalculator(zlmin, zlmax, nzl, zsmid[0], zsmind[-1])

    mean_scinv = sc.calc_mean_scinv(pzs)


    # histogram the lens redshifts in a binning corresponding
    # to the mean_scinv

    hdict = eu.stat.histogram(zl, min=zlmin, max=zlmax, binsize=dz, more=True)

    # get distances to the bin centers
    cosmo=cosmology.Cosmo()
    Dlens = cosmo.Da(0.0, hdict['center'])

    # interpolate the mean_scinv onto the centers
    mean_scinv = eu.stat.interplin(mean_scinv, sc.zlvals, hdict['center'])

    # this is the S/N at a given lens redshift
    s2n = sqrt(hdict['hist']/Dlens**2)*mean_scinv

    hd = hdict['hist']/Dlens**2
    hdcum = hd.cumsum()
    s2ncum = (mean_scinv*hd).cumsum()/sqrt(hdcum.clip(1.,hdcum.max()))


    s2n /= s2n.max()
    s2ncum /= s2ncum.max()

    
    tab = Table(2,2)
    tab.aspect_ratio=1

    # redshift histograms
    tab[0,0] = FramedPlot()
    zl_histp = Histogram(hdict['hist']/float(hdict['hist'].sum()), x0=hdict['low'][0], binsize=dz, color='blue')
    zl_histp.label = 'lenses'
    zs_histp = Histogram(pzs/float(pzs.sum()), x0=zslow[0], binsize=dz, color='red')
    zs_histp.label = 'sources'

    hkey=PlotKey(0.9,0.9,[zl_histp,zs_histp],halign='right')
    tab[0,0].add(zl_histp, zs_histp, hkey)
    tab[0,0].xlabel = 'z'

    # mean inverse critical density
    tab[0,1] = FramedPlot()
    tab[0,1].xlabel = 'lens redshift'
    tab[0,1].ylabel = r'$\langle \Sigma_{crit}^{-1} \rangle$'

    mc = Curve(hdict['center'], mean_scinv)
    tab[0,1].add(mc)


    # cumulative volume
    tab[1,0] = FramedPlot()
    tab[1,0].xlabel = 'z'
    tab[1,0].ylabel = 'cumulative volume'
    v=zeros(hdict['center'].size)
    for i in xrange(v.size):
        v[i] = cosmo.V(0.0, hdict['center'][i])
    v /= v.max()
    cv=Curve(hdict['center'], v)
    tab[1,0].add(cv)


    # S/N
    tab[1,1] = FramedPlot()
    tab[1,1].xlabel = 'lens redshift'
    tab[1,1].ylabel = 'S/N'

    cs2n = Curve(hdict['center'], s2n, color='blue')
    cs2ncum = Curve(hdict['center'], s2ncum, color='red')

    cs2n.label = 'S/N'
    cs2ncum.label = 'Cumulative S/N'
    ckey=PlotKey(0.9,0.9,[cs2n, cs2ncum],halign='right')

    tab[1,1].add(cs2n, cs2ncum, ckey)


    tab.show()

    return tab
Beispiel #25
0
    def test_scinv_npts(self, nplot, show=False, reload=False, type="png"):
        """

        Test accuracy as a function of the numer of points used in the
        integration.


        """

        dzl = 0.015
        zlmin = 0.02
        zlmax = 0.6

        from biggles import Points, FramedPlot, PlotKey, Table, Histogram, Curve
        from time import time
        import lensing
        import pcolors

        if self.data is None or reload:
            self.load_example_data()

        # this is old ScinvCalculator, need to make work
        # with new one
        scalc1000 = ScinvCalculator(self.zs, dzl, zlmin, zlmax, npts=1000)

        nptsvals = [100, 200, 300, 400, 500, 600, 700, 800, 900]
        numcheck = len(nptsvals)
        # colors=['black','magenta','blue','green','orange','red']
        colors = pcolors.rainbow(len(nptsvals), "hex")
        scalc = []
        for npts in nptsvals:
            scalc.append(ScinvCalculator(self.zs, dzl, zlmin, zlmax, npts=npts))

        times = numpy.zeros(numcheck, dtype="f8")
        time1000 = 0.0

        # we'll fill this in
        scinv_all = numpy.zeros((numcheck, scalc1000.zlvals.size))

        xlim = [0, scalc1000.zsvals.max()]
        for i in xrange(nplot):
            pz = self.data["pofz"][i]

            print("Doing 1000...", end="")

            tm0 = time()
            scinv1000 = scalc1000.calc_mean_scinv(pz)
            time1000 += time() - tm0

            print("done")

            for j in xrange(numcheck):
                npts = nptsvals[j]
                print("%d " % npts, end="")
                tm0 = time()
                scinv_all[j, :] = scalc[j].calc_mean_scinv(pz)
                times[j] += time() - tm0

            print("\nplotting")

            # plot the p(z)
            tab = Table(3, 1)

            binsize = scalc1000.zsvals[1] - scalc1000.zsvals[0]
            pzh = Histogram(pz, x0=scalc1000.zsvals[0], binsize=binsize)
            plt_pzh = FramedPlot()
            plt_pzh.xrange = xlim

            plt_pzh.xtitle = r"$z_s$"
            plt_pzh.ytitle = r"$P(z_s)$"
            plt_pzh.add(pzh)
            tab[0, 0] = plt_pzh

            # plot scinv for each npts value
            plt_scinv = FramedPlot()
            plt_scinv.xrange = xlim

            scinv_plots = []
            for j in xrange(numcheck):
                npts = nptsvals[j]
                p = Curve(scalc[j].zlvals, scinv_all[j, :], type="solid", color=colors[j])
                p.label = "npts: %d" % npts

                plt_scinv.add(p)
                scinv_plots.append(p)

            scinv_key = PlotKey(0.95, 0.9, scinv_plots, halign="right")
            plt_scinv.add(scinv_key)

            plt_scinv.ylabel = r"$\langle \Sigma_{crit}^{-1}(z_{lens}) \rangle$"
            plt_scinv.xlabel = r"$z_{lens}$"
            plt_scinv.yrange = [0, 2.1e-4]

            tab[1, 0] = plt_scinv

            # ratio to 1000 points

            plt_rat = FramedPlot()
            plt_rat.xrange = xlim
            plt_rat.yrange = [1 - 1.0e-2, 1 + 1.0e-2]
            rat_plots = []
            for j in xrange(numcheck):
                npts = nptsvals[j]
                w = where1(scinv1000 > 0)
                ratio = scinv_all[j, w] / scinv1000[w]
                # ratio=scinv_all[j,:]/scinv1000[:]

                p = Curve(scalc[j].zlvals[w], ratio, type="solid", color=colors[j])
                p.label = "npts: %d" % npts

                plt_rat.add(p)
                rat_plots.append(p)

            key = PlotKey(0.95, 0.9, rat_plots, halign="right")
            plt_rat.add(key)

            plt_rat.ylabel = r"$\langle \Sigma_{crit}^{-1} \rangle / \langle \Sigma_{crit}^{-1} \rangle_{1000}$"
            plt_rat.xlabel = r"$z_{lens}$"

            tab[2, 0] = plt_rat

            if show:
                tab.show()

            plotfile = self.npts_plot_file(i, type)
            print("writing to file:", plotfile)
            if type == "png":
                tab.write_img(1000, 1000, plotfile)
            else:
                tab.write_eps(plotfile)

        print("time npts=1000:", time1000)
        for j in xrange(numcheck):
            npts = nptsvals[j]
            print("time npts=%s: %s" % (npts, times[j]))
Beispiel #26
0
def test_sigmacritinv_npts(epsfile=None):
    """
    Test accuracy of sigmacrit inv as a function of number
    of points
    """

    from biggles import FramedPlot, PlotKey, PlotLabel, Curve, FramedArray, Table

    c1000 = Cosmo(npts=1000)
    c5 = Cosmo(npts=5)
    c4 = Cosmo(npts=4)
    c3 = Cosmo(npts=3)
    c2 = Cosmo(npts=2)

    tab = Table(2, 2)
    tab.uniform_limits = 0
    tab.cellspacing = 1

    p5 = FramedPlot()
    p5.xlabel = 'zsource'
    p5.ylabel = '% diff'
    p4 = FramedPlot()
    p4.xlabel = 'zsource'
    p4.ylabel = '% diff'
    p3 = FramedPlot()
    p3.xlabel = 'zsource'
    p3.ylabel = '% diff'
    p2 = FramedPlot()
    p2.xlabel = 'zsource'
    p2.ylabel = '% diff'

    l5 = PlotLabel(0.2, 0.7, 'npts = 5')
    p5.add(l5)
    l4 = PlotLabel(0.2, 0.1, 'npts = 4')
    p4.add(l4)
    l3 = PlotLabel(0.2, 0.9, 'npts = 3')
    p3.add(l3)
    l2 = PlotLabel(0.2, 0.9, 'npts = 2')
    p2.add(l2)

    colors = [
        'black', 'violet', 'blue', 'green', 'orange', 'magenta', 'firebrick',
        'red'
    ]
    zlvals = numpy.arange(0.1, 0.9, 0.1)
    if zlvals.size != len(colors):
        raise ValueError("mismatch colors and zlvals")

    i = 0

    allc5 = []
    for zl in zlvals:

        zs = numpy.arange(zl + 0.01, 2.0, 0.01)

        scinv = c1000.sigmacritinv(zl, zs)
        scinv5 = c5.sigmacritinv(zl, zs)
        scinv4 = c4.sigmacritinv(zl, zs)
        scinv3 = c3.sigmacritinv(zl, zs)
        scinv2 = c2.sigmacritinv(zl, zs)

        curve5 = Curve(zs, 100 * (scinv - scinv5) / scinv, color=colors[i])
        curve5.label = 'zlens: %0.2f' % zl
        allc5.append(curve5)
        p5.add(curve5)

        curve4 = Curve(zs, 100 * (scinv - scinv4) / scinv, color=colors[i])
        p4.add(curve4)

        curve3 = Curve(zs, 100 * (scinv - scinv3) / scinv, color=colors[i])
        p3.add(curve3)

        curve2 = Curve(zs, 100 * (scinv - scinv2) / scinv, color=colors[i])
        p2.add(curve2)

        i += 1

    key = PlotKey(0.15, 0.5, allc5)
    p5.add(key)

    tab[0, 0] = p5
    tab[0, 1] = p4
    tab[1, 0] = p3
    tab[1, 1] = p2

    tab.show()

    if epsfile is not None:
        tab.write_eps(epsfile)
Beispiel #27
0
def test_sigmacritinv_npts(epsfile=None):
    """
    Test accuracy of sigmacrit inv as a function of number
    of points
    """

    from biggles import FramedPlot, PlotKey, PlotLabel, Curve, FramedArray, Table

    c1000 = Cosmo(npts=1000)
    c5 = Cosmo(npts=5)
    c4 = Cosmo(npts=4)
    c3 = Cosmo(npts=3)
    c2 = Cosmo(npts=2)


    tab = Table( 2, 2 )
    tab.uniform_limits = 0
    tab.cellspacing = 1

    p5 = FramedPlot()
    p5.xlabel = 'zsource'
    p5.ylabel = '% diff'
    p4 = FramedPlot()
    p4.xlabel = 'zsource'
    p4.ylabel = '% diff'
    p3 = FramedPlot()
    p3.xlabel = 'zsource'
    p3.ylabel = '% diff'
    p2 = FramedPlot()
    p2.xlabel = 'zsource'
    p2.ylabel = '% diff'

    l5 = PlotLabel(0.2,0.7,'npts = 5')
    p5.add(l5)
    l4 = PlotLabel(0.2,0.1,'npts = 4')
    p4.add(l4)
    l3 = PlotLabel(0.2,0.9,'npts = 3')
    p3.add(l3)
    l2 = PlotLabel(0.2,0.9,'npts = 2')
    p2.add(l2)


    colors = ['black','violet','blue','green','orange','magenta','firebrick','red']
    zlvals = numpy.arange(0.1,0.9,0.1)
    if zlvals.size != len(colors):
        raise ValueError("mismatch colors and zlvals")



    i=0

    allc5 = []
    for zl in zlvals:

        zs = numpy.arange(zl+0.01, 2.0, 0.01)

        scinv = c1000.sigmacritinv(zl, zs)
        scinv5 = c5.sigmacritinv(zl, zs)
        scinv4 = c4.sigmacritinv(zl, zs)
        scinv3 = c3.sigmacritinv(zl, zs)
        scinv2 = c2.sigmacritinv(zl, zs)

        curve5 = Curve(zs, 100*(scinv-scinv5)/scinv, color=colors[i])
        curve5.label = 'zlens: %0.2f' % zl
        allc5.append(curve5)
        p5.add(curve5)

        curve4 = Curve(zs, 100*(scinv-scinv4)/scinv, color=colors[i])
        p4.add(curve4)

        curve3 = Curve(zs, 100*(scinv-scinv3)/scinv, color=colors[i])
        p3.add(curve3)

        curve2 = Curve(zs, 100*(scinv-scinv2)/scinv, color=colors[i])
        p2.add(curve2)

        i+=1

    key = PlotKey(0.15,0.5,allc5)
    p5.add(key)


    tab[0,0] = p5
    tab[0,1] = p4
    tab[1,0] = p3
    tab[1,1] = p2

    tab.show()

    if epsfile is not None:
        tab.write_eps(epsfile)
Beispiel #28
0
    def plot_meanshear_vs_trueshear_bys2n(self, nperbin, nperbin_sub, show=False):
        from biggles import FramedPlot, Curve, Points, Table, PlotKey

        type = "vs_shear"

        html_file = get_shear_compare_html_url(self["run"], self["mock_catalog"], type)
        print "html_file:", html_file

        data = self.get_data()

        epsfile = get_shear_compare_plot_url(self["run"], self["mock_catalog"], type)
        print >> stderr, "Will write summary plot:", epsfile

        print >> stderr, "histogramming shear_s2n", nperbin
        hdict = eu.stat.histogram(data["shear_s2n"], nperbin=nperbin, rev=True, more=True)
        rev = hdict["rev"]
        cdlist = []
        pngfiles = []
        for i in xrange(hdict["hist"].size):
            if rev[i] != rev[i + 1]:
                w = rev[rev[i] : rev[i + 1]]
                label = r"$%0.3g < S/N < %0.3g$" % (hdict["low"][i], hdict["high"][i])
                print >> stderr, label, "mean:", hdict["mean"][i], "num:", w.size
                cd, png = self.plot_meanshear_vs_trueshear(nperbin_sub, indices=w, label=label, num=i, show=show)
                cdlist.append(cd)
                pngfiles.append(png)

        slopes1 = [cd["coeff1"][0] for cd in cdlist]
        offsets1 = [cd["coeff1"][1] for cd in cdlist]
        slopes2 = [cd["coeff2"][0] for cd in cdlist]
        offsets2 = [cd["coeff2"][1] for cd in cdlist]

        tab = Table(2, 1)

        plt_slope = FramedPlot()
        cslope1 = Curve(hdict["mean"], slopes1, color="red")
        cslope2 = Curve(hdict["mean"], slopes2, color="blue")
        pslope1 = Points(hdict["mean"], slopes1, color="red", type="filled circle")
        pslope2 = Points(hdict["mean"], slopes2, color="blue", type="filled circle")

        cslope1.label = r"$\gamma_1$"
        cslope2.label = r"$\gamma_2$"
        key = PlotKey(0.1, 0.2, [cslope1, cslope2], halign="left")

        plt_slope.add(cslope1, cslope2, pslope1, pslope2, key)
        plt_slope.xlabel = "Shear S/N"
        plt_slope.ylabel = "Slope"
        plt_slope.xlog = True
        plt_slope.xrange = eu.plotting.get_log_plot_range(hdict["mean"])

        plt_offset = FramedPlot()
        coffset1 = Curve(hdict["mean"], offsets1, color="red")
        coffset2 = Curve(hdict["mean"], offsets2, color="blue")
        poffset1 = Points(hdict["mean"], offsets1, color="red", type="filled circle")
        poffset2 = Points(hdict["mean"], offsets2, color="blue", type="filled circle")
        plt_offset.add(coffset1, coffset2, poffset1, poffset2)
        plt_offset.xlabel = "Shear S/N"
        plt_offset.ylabel = "Offset"
        plt_offset.xlog = True
        plt_offset.xrange = eu.plotting.get_log_plot_range(hdict["mean"])

        tab[0, 0] = plt_slope
        tab[1, 0] = plt_offset
        if show:
            tab.show()

        print >> stderr, "Writing summary plot:", epsfile
        tab.write_eps(epsfile)
        converter.convert(epsfile, dpi=90, verbose=True)
        png = epsfile.replace(".eps", ".png")
        pngfiles = [png] + pngfiles

        self.write_html(pngfiles, html_file)