Пример #1
0
def test_hist_match(binsize, binnum=9, l=None, r=None, remove=False):
    import lensing
    import biggles
    biggles.configure('screen','width', 1140)
    biggles.configure('screen','height', 1140)


    if l is None or r is None:
        l,r = load_test_data()

    binner=lensing.binning.N200Binner(12)
    print("selecting ",binner.bin_label(binnum))
    w=binner.select_bin(l, binnum)
    print("    kept %d/%d" % (w.size,l.size))

    if remove:
        keep = hist_match_remove(r['z'], l['z'][w], binsize)
        perc = keep.size/(1.*r.size)
        print("used number: %d/%d = %0.2f" % (keep.size,r.size, perc))

        weights = ones(keep.size)
        plot_results1d(r['z'][keep], l['z'][w], weights, binsize)
    else:
        weights = hist_match(r['z'], l['z'][w], binsize)

        effnum = weights.sum()
        effperc = effnum/r.size
        print("effective number: %d/%d = %0.2f" % (effnum,r.size, effperc))

        plot_results1d(r['z'], l['z'][w], weights, binsize)
    return weights
Пример #2
0
def prepare_plot( xlabel='', ylabel='', yrange=None, xrange=None,
                  width=500, height=350 ):
    """
    Initiate a biggles.FramedPlot object.

    @param xlabel: label for x-axis 
    @type  xlabel: str
    @param ylabel: label for y-axis 
    @type  ylabel: str
    @param yrange: range of y-axis
    @type  yrange: (float,float)
    @param xrange: range of x-axis
    @type  xrange: (float,float)
    @param width: hard plot width (in pixels or cm)
    @type  width: int
    @param height: hard plot height
    @type  height: int

    @return: biggles plot object
    @rtype: biggles.FillBetween    
    """
    B.configure( 'screen', 'height', height )
    B.configure( 'screen', 'width', width )

    p = B.FramedPlot()

    p.xlabel = xlabel
    p.ylabel = ylabel
    if yrange: p.yrange = yrange
    if xrange: p.xrange = xrange

    return p
Пример #3
0
    def plotMemberProfiles( self, *name, **arg ):
        """
        Plot profiles of all member trajectories seperately::
          plotMemberProfiles( name1, [name2, .. ],[ arg1=x,..])
            -> biggles.Table

        :param name: profile name(s)
        :type  name: str
        :param arg: pairs for biggles.Curve() and/or xlabel=..,ylabel=..
        :type  arg: key=value

        :return: biggles plot object
        :rtype: biggles.FramedArray()   
        """
        if not biggles:
            raise ImportError('biggles module could not be imported.')
        
        rows = self.n_members // 2 + self.n_members % 2
        page = biggles.FramedArray( rows , 2)

        biggles.configure('fontsize_min', 1)
        colors = T.colorSpectrum( len( name ) , '00FF00', 'FF00FF') 

        ml = self.memberList()

        i = 0
        minV = maxV = None

        for t in ml:

            for j in range( len(name)):

                p = t.profile( name[j] )

                if minV is None or minV > min( p ):
                    minV = min(p)
                if maxV is None or maxV < max( p ):
                    maxV = max(p)

                page[i//2, i%2].add( biggles.Curve( list(range( len(p))), list(p),
                                                   color=colors[j], **arg ) )

                page[i//2, i%2].add( biggles.PlotLabel( 0.8, 0.8-j/8.0, name[j],
                                                       color=colors[j]) )

            page[i//2, i%2].add( biggles.PlotLabel( 0.1, 0.9, 'Traj %i' % i))

            i += 1

        if self.n_members % 2 != 0:
            line = biggles.Line( (0,minV), (len(p),maxV) )
            page[ self.n_members//2, 1 ].add( line )

        page.uniform_limits = 1
        page.xlabel = arg.get('xlabel',None)
        page.ylabel = arg.get('ylabel',None)

        return page
Пример #4
0
    def plotMemberProfiles( self, *name, **arg ):
        """
        Plot profiles of all member trajectories seperately::
          plotMemberProfiles( name1, [name2, .. ],[ arg1=x,..])
            -> biggles.Table

        :param name: profile name(s)
        :type  name: str
        :param arg: pairs for biggles.Curve() and/or xlabel=..,ylabel=..
        :type  arg: key=value

        :return: biggles plot object
        :rtype: biggles.FramedArray()   
        """
        if not biggles:
            raise ImportError('biggles module could not be imported.')
        
        rows = self.n_members // 2 + self.n_members % 2
        page = biggles.FramedArray( rows , 2)

        biggles.configure('fontsize_min', 1)
        colors = T.colorSpectrum( len( name ) , '00FF00', 'FF00FF') 

        ml = self.memberList()

        i = 0
        minV = maxV = None

        for t in ml:

            for j in range( len(name)):

                p = t.profile( name[j] )

                if minV is None or minV > min( p ):
                    minV = min(p)
                if maxV is None or maxV < max( p ):
                    maxV = max(p)

                page[i//2, i%2].add( biggles.Curve( list(range( len(p))), list(p),
                                                   color=colors[j], **arg ) )

                page[i//2, i%2].add( biggles.PlotLabel( 0.8, 0.8-j/8.0, name[j],
                                                       color=colors[j]) )

            page[i//2, i%2].add( biggles.PlotLabel( 0.1, 0.9, 'Traj %i' % i))

            i += 1

        if self.n_members % 2 != 0:
            line = biggles.Line( (0,minV), (len(p),maxV) )
            page[ self.n_members//2, 1 ].add( line )

        page.uniform_limits = 1
        page.xlabel = arg.get('xlabel',None)
        page.ylabel = arg.get('ylabel',None)

        return page
Пример #5
0
def test_em_sdss(ngauss=2,
                 run=756,
                 field=45,
                 camcol=1,
                 filter='r',
                 row=123.1,
                 col=724.8,
                 cocenter=False,
                 show=False):
    import sdsspy
    fnum=sdsspy.FILTERNUM[filter]

    psfield=sdsspy.read('psField', run=run, camcol=camcol, field=field,
                        lower=True)
    psfkl=sdsspy.read('psField', run=run, camcol=camcol, field=field,
                      filter=filter)
    if psfkl is None:
        print 'no such field'
        return

    im_nonoise=psfkl.rec(row, col, trim=True)
    im0,skysig=add_noise_matched(im_nonoise, 1.e8)

    ivar=1./skysig**2

    dims=im0.shape
    cen=[(dims[0]-1.)/2., (dims[1]-1.)/2.]
    fwhm=psfield['psf_width'][0,fnum]
    sigma_guess=fimage.fwhm2sigma(fwhm)
    sigma_guess /= 0.4 # pixels
    print 'guess fwhm:',fwhm

    gm=gmix_image.gmix_em.GMixEMBoot(im0, ngauss, cen,
                                     sigma_guess=sigma_guess,
                                     ivar=ivar,
                                     cocenter=cocenter)
    res=gm.get_result()
    gmx=gm.get_gmix()

    print 'numiter:',res['numiter']
    if show and have_images:
        import biggles

        biggles.configure('screen','width',1000)
        biggles.configure('screen','height',1000)
        mod=gmix2image(gmx,im0.shape)
        counts=im0.sum()
        mod *= counts/mod.sum()

        if cocenter:
            title='cocenter ngauss: %d' % ngauss
        else:
            title='free centers: %d' % ngauss
        images.compare_images(im0, mod, label1='image',label2='model',
                              title=title)
    print gmx
    return res
Пример #6
0
def plot_fits(pars, samples, dolog=True, show=False, eps=None, par_labels=None):
    """
    """
    import esutil as eu
    import biggles
    import images

    biggles.configure('screen','width', 1400)
    biggles.configure('screen','height', 800)

    num=pars.shape[0]
    ndim=pars.shape[1]

    if par_labels[0]=='fracdev':
        nrow=1
        ncol=2
        tab=biggles.Table(nrow,ncol)
        plin = _plot_single(pars[:,0], samples[:,0], do_ylog=False)
        plog = _plot_single(pars[:,0], samples[:,0], do_ylog=True)
        plin.xlabel='fracdev'
        plog.xlabel='fracdev'
        tab[0,0]=plin
        tab[0,1]=plog
    else:
        nrow,ncol = images.get_grid(ndim) 
        tab=biggles.Table(nrow,ncol)


        for dim in xrange(ndim):
            plt = _plot_single(pars[:,dim], samples[:,dim],do_ylog=True)
            if par_labels is not None:
                plt.xlabel=par_labels[dim]
            else:
                plt.xlabel=r'$P_%s$' % dim

            row=(dim)/ncol
            col=(dim) % ncol

            tab[row,col] = plt

    tab.aspect_ratio=nrow/float(ncol)

    if eps:
        import converter
        print(eps)
        d=os.path.dirname(eps)
        if not os.path.exists(d):
            os.makedirs(d)
        tab.write_eps(eps)
        converter.convert(eps, verbose=True, dpi=200)

    if show:
        tab.show()
Пример #7
0
def find_good_s2n(version, model):
    """
    Make a plot of T_s2n/flux_s2n vs log10(flux)

    Indicates good ranges are
        exp
            log10 flux between [-1.2, 1.4]
            T_s2n/flux_s2n between [0.1,0.7]
        dev
            log10 flux between [-1.2, 1.6]
            T_s2n/flux_s2n between [0.1,0.6]

    """
    import biggles

    biggles.configure('screen','width',1200)
    biggles.configure('screen','height',1200)

    t=files.read_output(version)

    flux, flux_err, T, T_err = get_flux_T(t, model)
    flux_s2n = flux/flux_err
    T_s2n = T/T_err

    s2n_rat = T_s2n/flux_s2n

    logflux=numpy.log10(flux)

    wbad=select_by_s2n_flux(t, model, good=False)

    xlabel=r'$log_{10}(flux)$'
    ylabel=r'$(S/N)_T / (S/N)_{flux}$'

    xrange=[-2.6,2.2]
    yrange=[0.0,1.0]

    plt=biggles.FramedPlot()
    plt.title=model
    plt.xlabel=xlabel
    plt.ylabel=ylabel
    plt.xrange=xrange
    plt.yrange=yrange

    pts = biggles.Points(logflux, s2n_rat,
                         type='filled circle', size=0.3)
    bad_pts = biggles.Points(logflux[wbad], s2n_rat[wbad],
                             type='filled circle', size=0.3, color='red')
    
    plt.add(pts)
    plt.add(bad_pts)

    plt.show()
Пример #8
0
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)
Пример #9
0
    def doplots(self, xfield='coadd_mag_auto', type='normal', show=False):
        import biggles
        biggles.configure('default','fontsize_min',1.5)
        nexp=len(self.expdict)
        i=1
        for expname,exp_objs in self.expdict.iteritems():
            print >>stderr,'%d/%d' % (i,nexp)

            if type=='em2_widths':
                self._process_exp_em2_widths(expname,exp_objs,xfield,show=show)
            elif type=='widths':
                self._process_exp_widths(expname,exp_objs,xfield,show=show)
            elif type=='normal':
                self._process_exp(expname,exp_objs,show=show)
            else:
                raise ValueError("bad type: '%s'" % type)
            i += 1
Пример #10
0
    def __init__(self):
        biggles.configure( 'default', 'fontsize_min', 2)
        options,args = parser.parse_args(sys.argv[1:])

        self.options=options

        if options.run is None or options.shnum is None:
            parser.print_help()
            sys.exit(1)

        self.yrange=options.yrange
        if self.yrange is not None:
            self.yrange=[float(s) for s in options.yrange.split(',')]

        self.run=options.run
        self.shnum=int(options.shnum)
        self.setname=options.set

        self.psfnums=[int(s) for s in options.psfnums.split(',')]

        self.nbin=int(options.nbin)

        self.s2n_range=[float(s) for s in options.s2n.split(',')]
        self.sratio_range=[float(s) for s in options.sratio.split(',')]

        self.doshow = options.show

        self.bin_field=options.field

        reader=files.Reader(run=self.run, 
                            shnums=self.shnum,
                            psfnums=self.psfnums,
                            s2n_range=self.s2n_range,
                            sratio_range=self.sratio_range,
                            setname=self.setname,
                            ignore_missing=options.ignore_missing,
                            progress=options.progress)

        self.data=reader.get_data()
        
        self.set_bindata()
        if self.options.frac:
            self.make_frac_plot()
        else:
            self.make_plot()
Пример #11
0
def plotorders(orders,
               interlacedorders=None,
               xsize=2048,
               ysize=2048,
               npoints=50,
               title=''):

    "Plot an overview of the order locations"

    # Set the plotting screen size (square!)
    biggles.configure('screen', 'width', 600)
    biggles.configure('screen', 'height', 600)

    # Find the number of orders and determine if there are any interlaced
    # orders to be plotted
    norders = len(orders)
    if interlacedorders:
        ninterlacedorders = len(interlacedorders)

    # Create the 'frame' object that will hold the plot and give it a title
    frame = biggles.FramedPlot()
    frame.title = title

    # Set the x- and y-ranges
    frame.xrange = (0, xsize)
    frame.yrange = (0, ysize)

    # Loop over orders
    for order in orders:

        # Determine the x and y positions of the orders on the detector
        (xvec, yvec) = frameUtils.getorderxy(order, npoints=npoints)
        # And plot these into 'frame'
        frame.add(biggles.Curve(xvec, yvec))

    if interlacedorders:

        # Do similar procedure for the interlaced orders
        for order in interlacedorders:

            (xvec, yvec) = frameUtils.getorderxy(order, npoints=npoints)
            frame.add(biggles.Curve(xvec, yvec, color='blue'))

    # Display the plot on screen
    frame.show()
Пример #12
0
def plotorders(orders, interlacedorders=None, xsize=2048, ysize=2048,
               npoints=50, title=''):

  "Plot an overview of the order locations"

  # Set the plotting screen size (square!)
  biggles.configure('screen', 'width',  600)
  biggles.configure('screen', 'height', 600)

  # Find the number of orders and determine if there are any interlaced
  # orders to be plotted
  norders = len(orders)
  if interlacedorders:
    ninterlacedorders = len(interlacedorders)


  # Create the 'frame' object that will hold the plot and give it a title
  frame = biggles.FramedPlot()
  frame.title = title

  # Set the x- and y-ranges
  frame.xrange = (0, xsize)
  frame.yrange = (0, ysize)

  # Loop over orders
  for order in orders:

    # Determine the x and y positions of the orders on the detector
    (xvec, yvec) = frameUtils.getorderxy(order, npoints=npoints)
    # And plot these into 'frame'
    frame.add(biggles.Curve(xvec, yvec))


  if interlacedorders:

    # Do similar procedure for the interlaced orders
    for order in interlacedorders:

      (xvec, yvec) = frameUtils.getorderxy(order, npoints=npoints)
      frame.add(biggles.Curve(xvec, yvec, color='blue'))


  # Display the plot on screen
  frame.show()
Пример #13
0
def plot_fits(pars, samples, comps, dolog=True, show=False, eps=None, par_labels=None):
    """
    """
    import esutil as eu
    import biggles
    import images

    biggles.configure('screen','width', 1400)
    biggles.configure('screen','height', 800)

    num=pars.shape[0]
    ndim=pars.shape[1]

    nrow,ncol = images.get_grid(ndim) 
    tab=biggles.Table(nrow,ncol)


    for dim in xrange(ndim):
        plt = _plot_single(pars[:,dim], samples[:,dim], comps, do_ylog=True)
        if par_labels is not None:
            plt.xlabel=par_labels[dim]
        else:
            plt.xlabel=r'$P_%s$' % dim

        row=(dim)/ncol
        col=(dim) % ncol

        tab[row,col] = plt

    tab.aspect_ratio=nrow/float(ncol)

    if eps:
        import converter
        print(eps)
        d=os.path.dirname(eps)
        if not os.path.exists(d):
            os.makedirs(d)
        tab.write_eps(eps)
        converter.convert(eps, verbose=True, dpi=200)

    if show:
        tab.show()
Пример #14
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)
Пример #15
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)
Пример #16
0
    def __init__(self, **keys):
        self.omega_m=keys.get('omega_m',0.25)
        self.omega_b=keys.get('omega_b',0.055)
        self.sigma_8=keys.get('sigma_8',0.8)
        self.h=keys.get('h',1.0)
        self.ns=keys.get('ns',0.98)

        self.ehu = EisenHu(**keys)

        self.qg1000 = eu.integrate.QGauss(npts=1000)

        # rhocrit at z=0
        self.rhocrit0 = 0.277520

        try:
            import biggles
            biggles.configure('screen','width', 800)
            biggles.configure('screen','height', 800)
        except:
            pass
Пример #17
0
    def __init__(self):
        biggles.configure("default", "fontsize_min", 1)
        options, args = parser.parse_args(sys.argv[1:])

        self.options = options

        if options.run is None or options.shnum is None or options.psfnum is None or options.model is None:
            parser.print_help()
            sys.exit(1)

        self.run = options.run
        self.shnum = int(options.shnum)
        self.psfnum = int(options.psfnum)
        self.model = options.model

        self._load_data()

        self.parsname = self.model + "_pars"
        if self.parsname not in self._data.dtype.names:
            raise ValueError("tag '%s' not found" % self.parsname)
Пример #18
0
    def plot_sheardiff_vs_field(self, nperbin, field, show=False):
        import biggles

        biggles.configure("default", "fontsize_min", 1.5)
        biggles.configure("_HalfAxis", "ticks_size", 2.5)
        biggles.configure("_HalfAxis", "subticks_size", 1.25)
        data = self.get_data()
        type = "vs_" + field

        epsfile = get_shear_compare_plot_url(self["run"], self["mock_catalog"], type)

        tab = biggles.Table(1, 2)
        names = {"shear1_diff": r"$\gamma_1-\gamma_1^{true}", "shear2_diff": r"$\gamma_2-\gamma_2^{true}"}
        if field == "shear_s2n":
            xlog = True
        else:
            xlog = False
        plots = eu.plotting.bhist_vs(
            data, field, "shear1_diff", "shear2_diff", nperbin=nperbin, names=names, size=2.5, xlog=xlog, show=False
        )
        tab[0, 0] = plots[0]
        tab[0, 1] = plots[1]
        tab[0, 0].aspect_ratio = 1
        tab[0, 1].aspect_ratio = 1
        tab.write_eps(epsfile)
        converter.convert(epsfile, dpi=120, verbose=True)
        pngfile = epsfile.replace(".eps", ".png")
        if show:
            tab.show()
        return pngfile
Пример #19
0
def main():

    biggles.configure('default','fontsize_min',2.5)

    args=parser.parse_args()

    s2n_min = numpy.array( [7,10,13,16,19] )

    fitlist=[]
    for smin in s2n_min:
        means, means_nocorr = read_means(smin, args)

        fits=nsim.averaging_new.get_m_c_oneshear(means)
        fits_nocorr=nsim.averaging_new.get_m_c_oneshear(means_nocorr)

        dt=[
            ('m_nocorr','f8'),
            ('merr_nocorr','f8'),
            ('c_nocorr','f8'),
            ('cerr_nocorr','f8'),
        ]
        allfits=eu.numpy_util.add_fields(fits, dt)
        allfits['m_nocorr'] = fits_nocorr['m']
        allfits['merr_nocorr'] = fits_nocorr['merr']
        allfits['c_nocorr'] = fits_nocorr['c']
        allfits['cerr_nocorr'] = fits_nocorr['cerr']

        fitlist.append(allfits)

    
    data=eu.numpy_util.combine_arrlist(fitlist)

    doplot_with_uncorrected(s2n_min, data, args)
    doplot(s2n_min, data, args)

    doprint_table(s2n_min, data)
Пример #20
0
def plot_many_hist(arr):
    import biggles
    import esutil as eu
    biggles.configure('default','fontsize_min',1)
    ndim = arr.shape[1]

    nrow,ncol = eu.plotting.get_grid(ndim)

    plt=biggles.Table(nrow,ncol)

    names=['cen1','cen1','g1','g2','T','counts']
    for dim in xrange(ndim):
        row=dim/ncol
        col=dim % ncol

        bsize=0.2*arr[:,dim].std()

        p=eu.plotting.bhist(arr[:,dim],binsize=bsize,
                            xlabel=names[dim],
                            show=False)
        p.aspect_ratio=1
        plt[row,col] = p

    plt.show()
Пример #21
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()
Пример #22
0
def main(fname):
    w, h = getres()
    biggles.configure("default", "fontsize_min", 0.8)
    biggles.configure("screen", "width", w * 0.9)
    biggles.configure("screen", "height", h * 0.9)
    data = read_chain(fname)

    xdata = numpy.arange(data.size)

    npars = data["pars"][0, :].size
    if npars in [6, 7, 8]:
        nrows = 3
        ncols = 3
    elif npars in [9, 10, 11]:
        nrows = 4
        ncols = 3
    else:
        raise ValueError("support mor npars")
    tab = biggles.Table(nrows, ncols)

    plt = biggles.FramedPlot()
    lnprob = data["lnprob"] - data["lnprob"].max()
    plt.add(biggles.Curve(xdata, lnprob))
    plt.xlabel = "step"
    plt.ylabel = "ln(prob)"

    tab[0, 0] = plt

    npar = data["pars"].shape[1]

    iplt = 1
    for i in xrange(npar):
        std = data["pars"][:, i].std()
        binsize = 0.2 * std

        plt = eu.plotting.bhist(data["pars"][:, i], binsize=binsize, xlabel="par %s" % (i + 1), show=False)

        prow = iplt / ncols
        pcol = iplt % ncols
        tab[prow, pcol] = plt
        iplt += 1
    tab.show()
Пример #23
0
def plot_results(trials, **keys):
    """
    Plot the points and histograms of trials from an MCMC chain.
    """
    import biggles
    import esutil

    npars=trials.shape[1]

    fontsize_min=keys.get('fontsize_min',1)
    biggles.configure( 'default', 'fontsize_min', fontsize_min)
    weights=keys.get('weights',None)

    binfac=keys.get('binfac',0.2)
    names=keys.get('names',None)
    show=keys.get('show',True)
    ptypes=keys.get('ptypes',['linear']*npars)

    means,cov = extract_stats(trials,weights=weights)
    errs=sqrt(diag(cov)) 

    plt=biggles.Table(npars,2)

    ind = numpy.arange(trials.shape[0])

    for i in xrange(npars):
        if names is not None:
            name=names[i]
        else:
            name=r'$p_{%d}$' % i

        burn_plot_i = esutil.plotting.bscatter(ind,trials[:,i],
                                               type='solid',
                                               xlabel='step',
                                               ylabel=name,
                                               show=False)
        plt[i,0] = burn_plot_i

        if ptypes[i] == 'linear':
            vals=trials[:,i]
            bsize = binfac*errs[i]
            xlabel=name
        else:
            vals=numpy.log10(trials[:,i])
            bsize=0.2*vals.std()
            xlabel=r'$log_{10}(%s)$' % name

        hdict = esutil.stat.histogram(vals,
                                      binsize=bsize, 
                                      weights=weights,
                                      more=True)
        if weights is not None:
            hist=hdict['whist']
            hplot = biggles.Curve(hdict['center'],
                                  hdict['whist'])
        else:
            hist=hdict['hist']
            hplot = biggles.Histogram(hdict['hist'], 
                                      x0=hdict['low'][0], 
                                      binsize=bsize)
        plti=biggles.FramedPlot()

        plti.xlabel=xlabel

        hmax=hist.max()
        plti.yrange=[-0.05*hmax, 1.2*hmax]

        plti.add(hplot)
            
        lab = r'$<%s> = %0.4g \pm %0.4g$' % (name,means[i],errs[i])
        plab = biggles.PlotLabel(0.1,0.8,lab,
                                 halign='left',
                                 color='blue')

        plti.add(plab)

        plt[i,1]=plti
    
    plt.title=keys.get('title',None)

    if show:
        plt.show()

    return plt
Пример #24
0
def compare_images(im1, im2, **keys):
    import biggles

    show=keys.get('show',True)
    skysig=keys.get('skysig',None)
    dof=keys.get('dof',None)
    cross_sections=keys.get('cross_sections',True)
    ymin=keys.get('min',None)
    ymax=keys.get('max',None)

    color1=keys.get('color1','blue')
    color2=keys.get('color2','orange')
    colordiff=keys.get('colordiff','red')

    nrow=2
    if cross_sections:
        ncol=3
    else:
        ncol=2

    label1=keys.get('label1','im1')
    label2=keys.get('label2','im2')

    cen=keys.get('cen',None)
    if cen is None:
        cen = [(im1.shape[0]-1)/2., (im1.shape[1]-1)/2.]

    labelres='%s-%s' % (label1,label2)

    biggles.configure( 'default', 'fontsize_min', 1.)

    if im1.shape != im2.shape:
        raise ValueError("images must be the same shape")


    #resid = im2-im1
    resid = im1-im2

    # will only be used if type is contour
    tab=biggles.Table(nrow,ncol)
    if 'title' in keys:
        tab.title=keys['title']

    tkeys=copy.deepcopy(keys)
    tkeys['show']=False
    tkeys['file']=None
    im1plt=view(im1, **tkeys)
    im2plt=view(im2, **tkeys)

    tkeys['nonlinear']=None
    # this has no effect
    tkeys['min'] = resid.min()
    tkeys['max'] = resid.max()
    residplt=view(resid, **tkeys)

    if skysig is not None:
        if dof is None:
            dof=im1.size
        chi2per = (resid**2).sum()/skysig**2/dof
        lab = biggles.PlotLabel(0.1,0.1,
                                r'$\chi^2/dof$: %0.2f' % chi2per,
                                color='red',
                                halign='left')
    else:
        if dof is None:
            dof=im1.size
        chi2per = (resid**2).sum()/dof
        lab = biggles.PlotLabel(0.1,0.1,
                                r'$\chi^2/npix$: %.3e' % chi2per,
                                color='red',
                                halign='left')
    residplt.add(lab)

    im1plt.title=label1
    im2plt.title=label2
    residplt.title=labelres


    # cross-sections
    if cross_sections:
        cen0=int(cen[0])
        cen1=int(cen[1])
        im1rows = im1[:,cen1]
        im1cols = im1[cen0,:]
        im2rows = im2[:,cen1]
        im2cols = im2[cen0,:]
        resrows = resid[:,cen1]
        rescols = resid[cen0,:]

        him1rows = biggles.Histogram(im1rows, color=color1)
        him1cols = biggles.Histogram(im1cols, color=color1)
        him2rows = biggles.Histogram(im2rows, color=color2)
        him2cols = biggles.Histogram(im2cols, color=color2)
        hresrows = biggles.Histogram(resrows, color=colordiff)
        hrescols = biggles.Histogram(rescols, color=colordiff)

        him1rows.label = label1
        him2rows.label = label2
        hresrows.label = labelres
        key = biggles.PlotKey(0.1,0.9,[him1rows,him2rows,hresrows]) 

        rplt=biggles.FramedPlot()
        rplt.add( him1rows, him2rows, hresrows,key )
        rplt.xlabel = 'Center Rows'

        cplt=biggles.FramedPlot()
        cplt.add( him1cols, him2cols, hrescols )
        cplt.xlabel = 'Center Columns'

        rplt.aspect_ratio=1
        cplt.aspect_ratio=1

        tab[0,0] = im1plt
        tab[0,1] = im2plt
        tab[0,2] = residplt
        tab[1,0] = rplt
        tab[1,1] = cplt
    else:
        tab[0,0] = im1plt
        tab[0,1] = im2plt
        tab[1,0] = residplt

    _writefile_maybe(tab, **keys)
    _show_maybe(tab, **keys)

    return tab
Пример #25
0
import biggles
from numpy import log10, logspace, random

biggles.configure('default', 'fontsize_min', 2.5)

# set up some data
x = logspace(log10(0.1), log10(10.0), 10)

model = 1.0 / x
yerr = 0.1 * model
y = model + yerr * random.normal(size=x.size)

yratio = y / model
yratio_err = yerr / model


# build the FramedArray.  Note the x axis
# is set to log for all plots
a = biggles.FramedArray(
    2, 1,
    xlog=True,
    aspect_ratio=1.2,
    xlabel=r'$R [h^{-1} Mpc]$',
    row_fractions=[0.75, 0.25],
)

color = 'blue'
sym = 'filled circle'

mcurve = biggles.Curve(x, model)
pts = biggles.Points(x, y, type=sym, color=color)
Пример #26
0
def compare_images(im1_in, im2_in, wt_in, **keys):
    import biggles
    import copy
    import images

    """
    wt = wt_in.copy()
    maxwt = wt.max()
    noiseval = np.sqrt(1.0/maxwt)

    w = np.where(wt <= 0.0)
    if w[0].size > 0:
        wt[w] = maxwt
    noise = np.random.normal(size=wt.shape)
    noise *= np.sqrt(1.0/wt)
    """

    if im1_in.shape != im2_in.shape:
        raise ValueError("images must be the same shape")

    color1 = keys.get('color1', 'blue')
    color2 = keys.get('color2', 'orange')
    colordiff = keys.get('colordiff', 'red')

    label1 = keys.get('label1', 'im1')
    label2 = keys.get('label2', 'im2')

    resid = (im1_in - im2_in)

    im1 = im1_in
    im2 = im2_in

    cen = [(im1.shape[0]-1)/2., (im1.shape[1]-1)/2.]

    labelres = '%s-%s' % (label1, label2)

    biggles.configure('default', 'fontsize_min', 1.)

    # will only be used if type is contour
    tab = biggles.Table(2, 3)
    if 'title' in keys:
        tab.title = keys['title']

    tkeys = copy.deepcopy(keys)
    tkeys.pop('title', None)
    tkeys['show'] = False
    tkeys['file'] = None

    autoscale = True
    tab[0, 0] = images.view(im1, autoscale=autoscale, **tkeys)
    tab[0, 1] = images.view(im2, autoscale=autoscale, **tkeys)
    tab[0, 2] = residplt = images.view(
        resid*np.sqrt(wt_in.clip(min=0)), **tkeys
    )

    wgood = np.where(wt_in > 0.0)
    dof = wgood[0].size
    chi2per = (resid**2 * wt_in).sum()/dof
    lab = biggles.PlotLabel(0.9, 0.9,
                            r'$\chi^2/dof$: %.2f' % chi2per,
                            color='red',
                            halign='right')
    residplt.add(lab)

    cen0 = int(cen[0])
    cen1 = int(cen[1])
    im1rows = im1_in[:, cen1]
    im1cols = im1_in[cen0, :]
    im2rows = im2_in[:, cen1]
    im2cols = im2_in[cen0, :]
    resrows = resid[:, cen1]
    rescols = resid[cen0, :]

    him1rows = biggles.Histogram(im1rows, color=color1)
    him1cols = biggles.Histogram(im1cols, color=color1)
    him2rows = biggles.Histogram(im2rows, color=color2)
    him2cols = biggles.Histogram(im2cols, color=color2)
    hresrows = biggles.Histogram(resrows, color=colordiff)
    hrescols = biggles.Histogram(rescols, color=colordiff)

    him1rows.label = label1
    him2rows.label = label2
    hresrows.label = labelres
    key = biggles.PlotKey(0.1, 0.9,
                          [him1rows, him2rows, hresrows])

    rplt = biggles.FramedPlot()
    rplt.add(him1rows, him2rows, hresrows, key)
    rplt.xlabel = 'Center Rows'

    cplt = biggles.FramedPlot()
    cplt.add(him1cols, him2cols, hrescols)
    cplt.xlabel = 'Center Columns'

    rplt.aspect_ratio = 1
    cplt.aspect_ratio = 1

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

    images._writefile_maybe(tab, **keys)
    images._show_maybe(tab, **keys)

    return tab
Пример #27
0
def compare_images_mosaic(im1, im2, **keys):
    import biggles
    import copy
    import images

    show = keys.get('show', True)
    ymin = keys.get('min', None)
    ymax = keys.get('max', None)

    color1 = keys.get('color1', 'blue')
    color2 = keys.get('color2', 'orange')
    colordiff = keys.get('colordiff', 'red')

    nrow = 2
    ncol = 3

    label1 = keys.get('label1', 'im1')
    label2 = keys.get('label2', 'im2')

    cen = keys.get('cen', None)
    if cen is None:
        cen = [(im1.shape[0] - 1) / 2., (im1.shape[1] - 1) / 2.]

    labelres = '%s-%s' % (label1, label2)

    biggles.configure('default', 'fontsize_min', 1.)

    if im1.shape != im2.shape:
        raise ValueError("images must be the same shape")

    #resid = im2-im1
    resid = im1 - im2

    # will only be used if type is contour
    tab = biggles.Table(2, 1)
    if 'title' in keys:
        tab.title = keys['title']

    tkeys = copy.deepcopy(keys)
    tkeys.pop('title', None)
    tkeys['show'] = False
    tkeys['file'] = None

    tkeys['nonlinear'] = None
    # this has no effect
    tkeys['min'] = resid.min()
    tkeys['max'] = resid.max()

    mosaic = np.zeros((im1.shape[0], 3 * im1.shape[1]))
    ncols = im1.shape[1]
    mosaic[:, 0:ncols] = im1
    mosaic[:, ncols:2 * ncols] = im2
    mosaic[:, 2 * ncols:3 * ncols] = resid

    residplt = images.view(mosaic, **tkeys)

    dof = im1.size
    chi2per = (resid**2).sum() / dof
    lab = biggles.PlotLabel(0.9,
                            0.9,
                            r'$\chi^2/npix$: %.3e' % chi2per,
                            color='red',
                            halign='right')
    residplt.add(lab)

    cen0 = int(cen[0])
    cen1 = int(cen[1])
    im1rows = im1[:, cen1]
    im1cols = im1[cen0, :]
    im2rows = im2[:, cen1]
    im2cols = im2[cen0, :]
    resrows = resid[:, cen1]
    rescols = resid[cen0, :]

    him1rows = biggles.Histogram(im1rows, color=color1)
    him1cols = biggles.Histogram(im1cols, color=color1)
    him2rows = biggles.Histogram(im2rows, color=color2)
    him2cols = biggles.Histogram(im2cols, color=color2)
    hresrows = biggles.Histogram(resrows, color=colordiff)
    hrescols = biggles.Histogram(rescols, color=colordiff)

    him1rows.label = label1
    him2rows.label = label2
    hresrows.label = labelres
    key = biggles.PlotKey(0.1, 0.9, [him1rows, him2rows, hresrows])

    rplt = biggles.FramedPlot()
    rplt.add(him1rows, him2rows, hresrows, key)
    rplt.xlabel = 'Center Rows'

    cplt = biggles.FramedPlot()
    cplt.add(him1cols, him2cols, hrescols)
    cplt.xlabel = 'Center Columns'

    rplt.aspect_ratio = 1
    cplt.aspect_ratio = 1

    ctab = biggles.Table(1, 2)
    ctab[0, 0] = rplt
    ctab[0, 1] = cplt

    tab[0, 0] = residplt
    tab[1, 0] = ctab

    images._writefile_maybe(tab, **keys)
    images._show_maybe(tab, **keys)

    return tab
Пример #28
0
def plot(yvecarr,
         xvecarr=None,
         color="black",
         title="",
         xsize=600,
         ysize=300,
         xrange=None,
         yrange=None,
         psfile=None):
    """
     Use biggles to plot the spectrum in the 'yvecarr' array. 'yvecarr' may be
     a 1-dimensional or a 2-dimensional array containing a single spectrum
     or a set of spectra, respectively
  """

    # Set the plotting screen to the demanded size
    biggles.configure('screen', 'width', xsize)
    biggles.configure('screen', 'height', ysize)

    # Prepare the frame object and give it a title
    frame = biggles.FramedPlot()
    frame.aspect_ratio = 0.5
    frame.title = title

    # Make sure yvecarr is defined and make sense of it
    if yvecarr is None:
        return
    else:
        try:
            nyvec, nypixels = numpy.shape(yvecarr)
        except ValueError:
            # Apparently, yvecarr is a one-dimensional array
            nyvec = 1
            nypixels = len(yvecarr)
            yvecarr = numpy.array([yvecarr])

    # If no xvecarr is defined, fill the x-axis array with increasing
    # integers
    if xvecarr is None:
        xvecarr = numpy.zeros((nyvec, nypixels), dtype=numpy.float64)
        nxpixels = nypixels
        for i in range(nyvec):
            xvecarr[i, :] = numpy.arange(nypixels)
    else:
        # If not, it is either a 1- or 2-dimensional array (similar to yvecarr)
        try:
            nxvec, nxpixels = numpy.shape(xvecarr)
        except ValueError:
            nxvec = 1
            nxpixels = len(xvecarr)
            xvecarr = numpy.array([xvecarr])

    # Make sure that x and y arrays have identical length.
    if (nxpixels != nypixels):
        print 'Unequal length of x- and y-data'
        return

    # Set the plotting x-range if this was specified
    if xrange:
        frame.xrange = xrange
    else:
        frame.xrange = (xvecarr.min(), xvecarr.max())

    # And similar for the y-range
    if yrange:
        frame.yrange = yrange
#  else :
#    frame.yrange = (yvecarr.min(), yvecarr.max())

# Now, start the loop over the spectra (or spectrum)
    for i in range(nyvec):

        # Select the x- and y-vectors

        try:
            xvec = xvecarr[i]
        except IndexError:
            xvec = range(0, len(yvec))

        yvec = yvecarr[i]

        # And plot these in the 'frame' object
        frame.add(biggles.Curve(xvec, yvec, color=color))

    # Also add a line indicating the zero-level
    frame.add(biggles.LineY(0, color='blue'))

    # And display this plot on screen
    frame.show()

    # Save to encapsulated postscript
    # CURRENTLY NOT IMPLEMENTED. FOR LARGE PLOTS THIS MAY RESULT IN HEAVY DISK I/O
    if psfile is not None:
        frame.write_img(xsize, ysize, psfile)

    # Return the object to the caller, in case it would like to do more with it...
    return frame
Пример #29
0
    def plot_fits(self):

        means=self.means
        if means.size == 1:
            return
        else:
            import biggles
            biggles.configure('default','fontsize_min',1.5)

            fits=self.fits
            args=self.args
            #Q=calc_q(fits)

            if args.yrange is not None:
                yrange=[float(r) for r in args.yrange.split(',')]
            else:
                yrange=[-0.01,0.01]

            xrng=args.xrange
            if xrng is not None:
                xrng=[float(r) for r in args.xrange.split(',')]

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

            diff = means['shear'] - means['shear_true']

            plts=[]
            for i in [0,1]:

                x = means['shear_true'][:,i]
                plt =biggles.plot(
                    x,
                    diff[:,i],
                    xlabel=r'$\gamma_{%d}$ true' % (i+1,),
                    ylabel=r'$\Delta \gamma_{%d}$' % (i+1,),
                    yrange=yrange,
                    xrange=xrng,
                    visible=False,
                )
                yfit=fits['m'][0,i]*x + fits['c'][0,i]

                z=biggles.Curve(x, x*0, color='black')
                c=biggles.Curve(x, yfit, color='red')
                plt.add(z,c)

                '''
                mstr='m%d: %.2g +/- %.2g' % (i+1,fits['m'][0,i],fits['merr'][0,i])
                cstr='c%d: %.2g +/- %.2g' % (i+1,fits['c'][0,i],fits['cerr'][0,i])
                mlab=biggles.PlotLabel(0.1,0.9,
                                       mstr,
                                       halign='left')
                clab=biggles.PlotLabel(0.1,0.85,
                                       cstr,
                                       halign='left')
                plt.add(mlab,clab)
                '''
                if False and i==0:
                    Qstr='Q: %d' % (int(Q),)
                    Qlab=biggles.PlotLabel(0.1,0.8,
                                           Qstr,
                                           halign='left')
                    plt.add(Qlab)


                tab[0,i] = plt

            fname=self._get_fit_plot_file()
            eu.ostools.makedirs_fromfile(fname)
            print("writing:",fname)
            tab.write_eps(fname)

            if args.show:
                tab.show(width=1000, height=1000)
Пример #30
0
def plot_results(trials, **keys):
    """
    Plot the points and histograms of trials from an MCMC chain.
    """
    import biggles
    import esutil
    from esutil.numpy_util import where1, between

    npars = trials.shape[1]

    fontsize_min = keys.get("fontsize_min", 1)
    biggles.configure("default", "fontsize_min", fontsize_min)
    weights = keys.get("weights", None)

    nbin = keys.get("nbin", 35)
    names = keys.get("names", None)
    show = keys.get("show", True)

    nsigma = keys.get("nsigma", None)

    means, cov = extract_stats(trials, weights=weights)
    errs = sqrt(diag(cov))

    plt = biggles.Table(npars, 2)

    ind = numpy.arange(trials.shape[0])

    for i in xrange(npars):
        if names is not None:
            name = names[i]
        else:
            name = r"$p_{%d}$" % i

        use_trials = trials[:, i]
        use_ind = ind
        use_wts = weights
        if nsigma is not None:
            w = where1(between(trials[:, i], means[i] - nsigma * errs[i], means[i] + nsigma * errs[i]))
            use_trials = trials[w, i]
            use_ind = ind[w]
            if weights is not None:
                use_wts = weights[w]

        burn_plot_i = biggles.plot(use_ind, use_trials, type="solid", xlabel="step", ylabel=name, visible=False)
        plt[i, 0] = burn_plot_i

        hcurve, bin_edges, harray = biggles.make_histc(use_trials, nbin=nbin, weights=use_wts, get_hdata=True)

        plti = biggles.FramedPlot()

        plti.xlabel = name

        hmax = harray.max()
        plti.yrange = [-0.05 * hmax, 1.2 * hmax]

        plti.add(hcurve)

        lab = r"$<%s> = %0.4g \pm %0.4g$" % (name, means[i], errs[i])
        plab = biggles.PlotLabel(0.1, 0.8, lab, halign="left", color="blue")

        plti.add(plab)

        plt[i, 1] = plti

    plt.title = keys.get("title", None)

    if show:
        plt.show()

    return plt
Пример #31
0
import biggles
from numpy import log10, logspace, random

biggles.configure('default', 'fontsize_min', 2.5)

# set up some data
x = logspace(log10(0.1), log10(10.0), 10)

model = 1.0 / x
yerr = 0.1 * model
y = model + yerr * random.normal(size=x.size)

yratio = y / model
yratio_err = yerr / model

# build the FramedArray.  Note the x axis
# is set to log for all plots
a = biggles.FramedArray(
    2,
    1,
    xlog=True,
    aspect_ratio=1.2,
    xlabel=r'$R [h^{-1} Mpc]$',
    row_fractions=[0.75, 0.25],
)

color = 'blue'
sym = 'filled circle'

mcurve = biggles.Curve(x, model)
pts = biggles.Points(x, y, type=sym, color=color)
Пример #32
0
def fit_prior(run, is2n=0, field='pars_noshear',show=False):
    import biggles
    import esutil as eu
    from sklearn.mixture import GMM
    import fitsio
    gm=ngmix.gmix.GMixND()

    alldata=files.read_output(run, is2n)
    data=alldata[field]

    # fit |g|
    g=sqrt(data[:,2]**2 + data[:,3]**2)

    gp=ngmix.priors.GPriorBA()

    bs=eu.stat.Binner(g)
    bs.dohist(nbin=100)
    bs.calc_stats()
    xvals=bs['center']
    yvals=bs['hist'].astype('f8')
    gp.dofit(xvals, yvals)
    rg=gp.sample1d(1000000)

    #eta1,eta2,good=ngmix.shape.g1g2_to_eta1eta2_array(data[:,2],
    #                                                  data[:,3])
    #eta = 2*numpy.arctanh(g)
    #logg=log(g)


    outfile=files.get_fitprior_url(run, is2n)
    epsfile=files.get_fitprior_url(run, is2n, ext='eps')

    # fit TF with n-dimensional gaussian
    ngauss=20
    gm.fit(data[:, 4:], ngauss, min_covar=1.0e-4)

    '''
    print("fitting log(g)")
    g_gmm=GMM(n_components=10,
                 n_iter=5000,
                 min_covar=1.0e-4,
                 covariance_type='full')
    g_gmm.fit(eta[:,newaxis])

    if not g_gmm.converged_:
        print("DID NOT CONVERGE")

    rg=g_gmm.sample(1000000)
    gplt=biggles.plot_hist(eta,nbin=100,xlabel='|g|',
                           norm=1,
                           visible=False)
    '''
    gplt=biggles.plot_hist(g,nbin=100,xlabel='|g|',
                           norm=1,
                           visible=False)
    #gplt=biggles.plot_hist(rg[:,0],nbin=100,
    gplt=biggles.plot_hist(rg,nbin=100,
                           plt=gplt,
                           norm=1,
                           color='red',
                           visible=False)

    print("saving mixture to:",outfile)
    gm.save_mixture(outfile)
    with fitsio.FITS(outfile,'rw') as fits:
        gout=numpy.zeros(1, dtype=[('sigma','f8')])
        gout['sigma'] = gp.fit_pars[1]

        fits.write(gout, extname='gfit')

    #
    # plots
    #
    r=gm.sample(1000000)

    tab=biggles.Table(2,2)

    Tplt=biggles.plot_hist(data[:,4], nbin=100,
                          xlabel='log(T)',
                          norm=1,
                          visible=False)
    biggles.plot_hist(r[:,0], nbin=100,
                      color='red',
                      norm=1,
                      plt=Tplt,
                      visible=False)

    Fplt=biggles.plot_hist(data[:,5], nbin=100,
                          xlabel='log(F)',
                          norm=1,
                          visible=False)
    biggles.plot_hist(r[:,1], nbin=100,
                      color='red',
                      norm=1,
                      plt=Fplt,
                      visible=False)

    '''
    eta1plt=biggles.plot_hist(eta1, nbin=100,
                              xlabel='eta1',
                              norm=1,
                              visible=False)
    eta2plt=biggles.plot_hist(eta2, nbin=100,
                              xlabel='eta2',
                              norm=1,
                              visible=False)
    '''

    tab[0,0] = Tplt
    tab[0,1] = Fplt
    #tab[1,0] = eta1plt
    #tab[1,1] = eta2plt
    tab[1,0] = gplt
    tab[1,1] = gplt

    tab.aspect_ratio=0.5

    print("writing:",epsfile)
    tab.write_eps(epsfile)

    if show:
        biggles.configure('screen','width',1200)
        biggles.configure('screen','height',700)
        tab.show()
Пример #33
0
#!/usr/bin/env python

import Numeric
import biggles

def congestion_window():
    yvalues = [1,2,4,8,12,13,14,15,16,1,2,4,8,9,10,11,12,13,14,1]
    return Numeric.array(range(1,len(yvalues)+1)),Numeric.array(yvalues)

def line(x1,y1,x2,y2):
    yvalues = [y1,y2]
    xvalues = [x1,x2]
    return Numeric.array(xvalues),Numeric.array(yvalues)
    
biggles.configure( 'default', 'fontface', 'Times')
p = biggles.FramedPlot()
p.aspect_ratio = 0.5
p.y1.subticks = 1
p.y2.subticks = 1
p.xlabel = 'Transmission Round'
p.ylabel = 'TCP Congestion Window'
x,y = congestion_window()
a = biggles.Curve(x,y,color="blue")
b = biggles.Points(x,y,color="blue",type="filled circle",size=1)
c = biggles.DataLine((1,12),(9,12),type="dashed")
d = biggles.DataLabel(3,12.5,"Threshold",halign="center")
e = biggles.DataLine((10,8),(19,8),type="dashed")
f = biggles.DataLine((20,7),(21,7),type="dashed")
p.add(a, b, c, d, e, f)
p.write_img(2000,1000,'tcp.png')
p.write_eps('tcp.eps')
Пример #34
0
    def plot_fits(self):

        means = self.means
        if means.size == 1:
            return
        else:
            import biggles
            biggles.configure('default', 'fontsize_min', 1.5)

            fits = self.fits
            args = self.args
            #Q=calc_q(fits)

            if args.yrange is not None:
                yrange = [float(r) for r in args.yrange.split(',')]
            else:
                yrange = [-0.01, 0.01]

            xrng = args.xrange
            if xrng is not None:
                xrng = [float(r) for r in args.xrange.split(',')]

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

            diff = means['shear'] - means['shear_true']

            plts = []
            for i in [0, 1]:

                x = means['shear_true'][:, i]
                plt = biggles.plot(
                    x,
                    diff[:, i],
                    xlabel=r'$\gamma_{%d}$ true' % (i + 1, ),
                    ylabel=r'$\Delta \gamma_{%d}$' % (i + 1, ),
                    yrange=yrange,
                    xrange=xrng,
                    visible=False,
                )
                yfit = fits['m'][0, i] * x + fits['c'][0, i]

                z = biggles.Curve(x, x * 0, color='black')
                c = biggles.Curve(x, yfit, color='red')
                plt.add(z, c)
                '''
                mstr='m%d: %.2g +/- %.2g' % (i+1,fits['m'][0,i],fits['merr'][0,i])
                cstr='c%d: %.2g +/- %.2g' % (i+1,fits['c'][0,i],fits['cerr'][0,i])
                mlab=biggles.PlotLabel(0.1,0.9,
                                       mstr,
                                       halign='left')
                clab=biggles.PlotLabel(0.1,0.85,
                                       cstr,
                                       halign='left')
                plt.add(mlab,clab)
                '''
                if False and i == 0:
                    Qstr = 'Q: %d' % (int(Q), )
                    Qlab = biggles.PlotLabel(0.1, 0.8, Qstr, halign='left')
                    plt.add(Qlab)

                tab[0, i] = plt

            fname = self._get_fit_plot_file()
            eu.ostools.makedirs_fromfile(fname)
            print("writing:", fname)
            tab.write_eps(fname)

            if args.show:
                tab.show(width=1000, height=1000)
Пример #35
0
## delete temp receptor pdbs
cleanup(rec_pdbs)

## Plot results
##
import biggles

## get individual energy terms, remove non calculated terms
for t in bind.keys():
    zero_mask = [bind[k] == 0.0 for k in bind.keys()]
    e_val = transpose(compress(logical_not(zero_mask), l_energy))
    e_key = sum(transpose(take(bind.keys(), nonzero(sum(l_energy)))))
    e_key = [string.strip(key) for key in e_key]

## initiale FramedArray
biggles.configure('fontsize_min', .5)
p = biggles.FramedArray(len(e_key), 1)

## labels etc.
p.title = '/'.join(string.split(options['o'], '/')[-4:-1])
p.xlabel = 'fraction of native contacts'
p.ylabel = 'fold_X binding energy'

## Y-data
d0 = biggles.Points(l_fnc, l_tot, type='circle', size=1)

p_energy = []
p_label = []
p_average = []
p_reference = []
p_histogram = []
Пример #36
0
                  lm=range(1, nr_lig + 1),
                  soln=len(cList) / (nr_rec * nr_lig))

## sort data
sorted_data = sort(data, 2)

## get the lowest number of zeros in any array
lenZeros = leastNumberOfZeros(sorted_data)

colorDic = {
    'x': 'red',
    'r': 'cornflower blue',
    'l': 'pale green',
    'a': 'grey54'
}
biggles.configure('fontsize_min', 0.7)

#################
## EXTRA PLOTS
hexE = cList.valuesOf('hex_etotal')
order = argsort(hexE)
soln = 512


def singleDataPlot(data, inverse, sorted_ref, zeros, soln, color):
    sorted_data = sort(data)
    if inverse:
        data = (1. / array(data)).tolist()
        sorted_data = sort(data)
    # log plot
    log_p = logPlot([[sorted_data]], zeros, color, ref=None, ave=5)
Пример #37
0
def plot_results_separate(trials, **keys):
    """
    Plot the points and histograms of trials from an MCMC chain.
    """
    import biggles
    import esutil
    import images

    npars=trials.shape[1]

    fontsize_min=keys.get('fontsize_min',1)
    biggles.configure( 'default', 'fontsize_min', fontsize_min)
    weights=keys.get('weights',None)

    binfac=keys.get('binfac',0.2)
    names=keys.get('names',None)
    show=keys.get('show',True)
    ptypes=keys.get('ptypes',['linear']*npars)

    means,cov = extract_stats(trials,weights=weights)
    errs=sqrt(diag(cov)) 

    nrows, ncols =images.get_grid(npars)
    burn_plt=biggles.Table(nrows, ncols)
    hist_plt=biggles.Table(nrows, ncols)

    ind = numpy.arange(trials.shape[0])

    prow=0
    pcol=0
    for i in xrange(npars):

        prow=i/ncols
        pcol=i % ncols

        if names is not None:
            name=names[i]
        else:
            name=r'$p_{%d}$' % i

        lab = r'$<%s> = %0.4g \pm %0.4g$' % (name,means[i],errs[i])
        plab = biggles.PlotLabel(0.1,0.8,lab,
                                 halign='left',
                                 color='blue')

        # steps
        burn_plot_i = esutil.plotting.bscatter(ind,trials[:,i],
                                               type='solid',
                                               xlabel='step',
                                               ylabel=name,
                                               show=False)

        burn_plot_i.add(plab)
        burn_plt[prow,pcol] = burn_plot_i

        # hist
        vals=trials[:,i]
        bsize = binfac*errs[i]

        hdict = esutil.stat.histogram(vals,
                                      binsize=bsize, 
                                      weights=weights,
                                      more=True)
        if weights is not None:
            hist=hdict['whist']
            hplot = biggles.Curve(hdict['center'],
                                  hdict['whist'])
        else:
            hist=hdict['hist']
            hplot = biggles.Histogram(hdict['hist'], 
                                      x0=hdict['low'][0], 
                                      binsize=bsize)
        plti=biggles.FramedPlot()

        plti.xlabel=name

        hmax=hist.max()
        plti.yrange=[-0.05*hmax, 1.2*hmax]

        plti.add(hplot)
        plti.add(plab)

        hist_plt[prow,pcol]=plti
   
    burn_plt.title=keys.get('title',None)
    hist_plt.title=keys.get('title',None)

    if show:
        burn_plt.show()
        hist_plt.show()

    return burn_plt, hist_plt
Пример #38
0
def plot_results_separate(trials, **keys):
    """
    Plot the points and histograms of trials from an MCMC chain.
    """
    import biggles
    import esutil
    import images

    npars = trials.shape[1]

    fontsize_min = keys.get("fontsize_min", 1)
    biggles.configure("default", "fontsize_min", fontsize_min)
    weights = keys.get("weights", None)

    binfac = keys.get("binfac", 0.2)
    names = keys.get("names", None)
    show = keys.get("show", True)
    ptypes = keys.get("ptypes", ["linear"] * npars)

    means, cov = extract_stats(trials, weights=weights)
    errs = sqrt(diag(cov))

    nrows, ncols = images.get_grid(npars)
    burn_plt = biggles.Table(nrows, ncols)
    hist_plt = biggles.Table(nrows, ncols)

    ind = numpy.arange(trials.shape[0])

    prow = 0
    pcol = 0
    for i in xrange(npars):

        prow = i / ncols
        pcol = i % ncols

        if names is not None:
            name = names[i]
        else:
            name = r"$p_{%d}$" % i

        lab = r"$<%s> = %0.4g \pm %0.4g$" % (name, means[i], errs[i])
        plab = biggles.PlotLabel(0.1, 0.8, lab, halign="left", color="blue")

        # steps
        burn_plot_i = esutil.plotting.bscatter(ind, trials[:, i], type="solid", xlabel="step", ylabel=name, show=False)

        burn_plot_i.add(plab)
        burn_plt[prow, pcol] = burn_plot_i

        # hist
        vals = trials[:, i]
        bsize = binfac * errs[i]

        hdict = esutil.stat.histogram(vals, binsize=bsize, weights=weights, more=True)
        if weights is not None:
            hist = hdict["whist"]
            hplot = biggles.Curve(hdict["center"], hdict["whist"])
        else:
            hist = hdict["hist"]
            hplot = biggles.Histogram(hdict["hist"], x0=hdict["low"][0], binsize=bsize)
        plti = biggles.FramedPlot()

        plti.xlabel = name

        hmax = hist.max()
        plti.yrange = [-0.05 * hmax, 1.2 * hmax]

        plti.add(hplot)
        plti.add(plab)

        hist_plt[prow, pcol] = plti

    burn_plt.title = keys.get("title", None)
    hist_plt.title = keys.get("title", None)

    if show:
        burn_plt.show()
        hist_plt.show()

    return burn_plt, hist_plt
Пример #39
0
def remove_bg(frame, extension=0, poly_order_x=10, poly_order_y=8, nsteps=100, max_gradient=5, orderdef=None):

  medianfiltersize = 5
  minfiltersize  = 10

  if nsteps <= poly_order_y: poly_order_y = int(nsteps / 2)

  im = frame[extension].data
  (ysize, xsize) = im.shape

  bgim    = numpy.zeros((ysize, xsize),  dtype=numpy.float64)
  xfitarr = numpy.zeros((nsteps, xsize), dtype=numpy.float64)

  xx = numpy.arange(xsize, dtype=numpy.float64)
  yy = numpy.arange(ysize, dtype=numpy.float64)
  
  xx_mean = xx.mean()
  yy_mean = yy.mean()

  ystep = int(ysize / (nsteps - 1))

  yvals = (numpy.arange(nsteps) * ystep).round()

  ycount = 0


  
  for yind in yvals:

    #medianvec = numpy.zeros(xsize, dtype=numpy.float64)
    minvec  = numpy.zeros(xsize, dtype=numpy.float64)

    ymin_ind = numpy.max([yind-medianfiltersize, 0])
    ymax_ind = numpy.min([yind+medianfiltersize, ysize-1])

    naver = ymax_ind - ymin_ind + 1

    meanvec = numpy.average(im[ymin_ind:ymax_ind, :], axis=0)
    kernel = numpy.repeat(0.2, 5)
    d_meanvec = numpy.gradient(numpy.convolve(meanvec, kernel, mode='sample'))
    d_meanvec[0:10] = 0
    d_meanvec[xsize-11:xsize-1] = 0


    order_throughs = []
    order_throughs2 = []
    order_peaks = []
    all_peaks = []



    # First try to detect the peaks myself...
    for j in numpy.arange(xsize-1) + 1:
     if (d_meanvec[j-1] > max_gradient and d_meanvec[j] < max_gradient): all_peaks.append(j)


    # Now make use of existing orderdef if it exists
    if orderdef is not None:

      for order in orderdef:
        centery  = order['centerpix']
        centerx  = order['centerval']

        cheb_min = order['coefs'][2]
        cheb_max = order['coefs'][3]
        chebcoef = order['coefs'][4:]

	orderpos = _chebev(cheb_min, cheb_max, chebcoef, numpy.array([yind+1]))
        order_peaks.append(int(orderpos[0] + centerx) - 1)

      # But also append 'own' peaks below and above defined orders
      min_order_peak = numpy.min(order_peaks)
      max_order_peak = numpy.max(order_peaks)
      for peak in all_peaks:
        if peak < min_order_peak: order_peaks.append(peak)
        if peak > max_order_peak: order_peaks.append(peak)

    else:
      # Use whatever we have
      order_peaks = all_peaks

    order_peaks = numpy.array(order_peaks)
    npeaks = order_peaks.size
    order_throughs = (order_peaks[1:] + order_peaks[:npeaks-1]) / 2

    # Correct the max gradient for frames with very low pixel counts
    max_gradient = numpy.min((5, numpy.mean(meanvec.take(order_peaks)) / 4))


    # Now start searching for points that sample the background
    # (scattered light level)

    # First, find low points before first order, with
    # at least one point every 20 pixels
    for xpix in numpy.arange(0, order_peaks.min(), 20):
      shortvec = numpy.arange(20) + xpix
      shortvec = numpy.extract(shortvec < order_peaks.min(), shortvec)

      if (shortvec.size > 0):
        order_throughs2.append(shortvec[numpy.argmin(meanvec.take(shortvec))])

# The following is fancy, but it does not work since derivative is put to
# zero at last pixels and hence it cannot be used to find peaks or troughs.
#
#    (inds,) = numpy.where(short_dd > -max_gradient)
#    if inds.size == 0: inds = short_dd.size
#    min_ind = numpy.min(inds)
#    max_ind = short_dd.size
#
#    for j in numpy.arange(min_ind, max_ind - min_ind):
#      order_throughs2.append(shortvec[j])
#      nfound = nfound + 1
#    if nfound == 0:
#      order_throughs2.append(shortvec[numpy.argmin(meanvec.take(shortvec))])



    # Then loop over orders and find the troughs between the orders
    for xpix in order_throughs:
      shortvec = numpy.arange(11) - 5 + xpix
      shortvec = numpy.extract(shortvec > 1,	   shortvec)
      shortvec = numpy.extract(shortvec < xsize-1, shortvec)
      short_dd = d_meanvec.take(shortvec)

      # Use gradient to find region between peaks
      (inds,) = numpy.where(short_dd < -max_gradient)
      if inds.size == 0: inds = 0
      min_ind = numpy.max(inds)
      (inds,) = numpy.where(short_dd >  max_gradient)
      if inds.size == 0: inds = short_dd.size
      max_ind = numpy.min(inds)

      # Add the found region to the array of troughs
      nfound = 0
      for j in numpy.arange(min_ind, max_ind - min_ind):
	order_throughs2.append(shortvec[j])
	nfound = nfound + 1
      if nfound == 0:
        # But, if no through found, try to take minimum value of meanvec at position of trough
	try: order_throughs2.append(shortvec[numpy.argmin(meanvec.take(shortvec))])
	except: pass

        # Old solution - middle point between the order peaks
	# Does not work well because of non-monotonous order spacing
	# order_throughs2.append(xpix)

      # Safety catch: remove any incorrectly selected order peaks...
      try: order_throughs2.remove(shortvec[j])
      except: pass



    # Finally, find lowest point after last order
    shortvec = numpy.arange(50) + order_peaks.max()
    shortvec = numpy.extract(shortvec < xsize-1, shortvec)
    short_dd = d_meanvec.take(shortvec)

    if shortvec.size > 0:
      order_throughs2.append(shortvec[numpy.argmin(meanvec.take(shortvec))])


    # Finally, make sure each point is only selected once
    order_throughs = numpy.unique(order_throughs2)


    niter = 0
    # Perform fitting with sigma-clipping
    while 1:

      coefs = numpy.polyfit(order_throughs - xx_mean, meanvec.take(order_throughs),
                            poly_order_x)
      xfit_poly = numpy.poly1d(coefs)
      xfit = xfit_poly(order_throughs - xx_mean)

      sigma = numpy.abs(meanvec.take(order_throughs) - xfit) / numpy.std(meanvec.take(order_throughs) - xfit)
      rejected = numpy.extract(sigma > 3, order_throughs)
      order_throughs = numpy.extract(sigma < 3, order_throughs)
      
      niter = niter + 1
      if niter == 5 or rejected.size == 0: break
    
    xfit = xfit_poly(xx - xx_mean)
    xfitarr[ycount, :] = xfit

    ycount = ycount + 1


    # Debugging plot in x-direction (across the orders)
    if 0:
    #if ycount % 10 == 0:

      import biggles
      biggles.configure('screen', 'width',  900)
      biggles.configure('screen', 'height', 450)
      fr = biggles.FramedPlot()
      fr.yrange = [-50, meanvec.take(order_throughs).max()+50]
      fr.add(biggles.Curve(xx, meanvec, color='green'))
      fr.add(biggles.Curve(xx, xfit, color='blue'))
      fr.add(biggles.Points(order_throughs, meanvec.take(order_throughs)))
      fr.add(biggles.Points(order_peaks, meanvec.take(order_peaks), color='red'))
      fr.title = str(yind)
      fr.show()


  # Now fit in the y-direction
  for xind in numpy.arange(xsize):

    # Perform fitting with sigma-clipping
    niter = 0
    goodind = numpy.arange(nsteps)

    while 1:

      coefs = numpy.polyfit(yvals.take(goodind) - yy_mean, xfitarr[goodind, xind], poly_order_y)

      yfit_poly = numpy.poly1d(coefs)
      yfit = yfit_poly(yvals.take(goodind) - yy_mean)

      sigma = (xfitarr[goodind, xind] - yfit) / numpy.std(xfitarr[goodind, xind] - yfit)
      rejected = numpy.extract(sigma > 3, goodind)
      goodind  = numpy.extract(sigma < 3, goodind)

      niter = niter + 1
      if niter == 3 or rejected.size == 0 or goodind.size == 0: break

    if goodind.size == 0: 
      print "Error: no points left when y-fitting the background"
      coefs=numpy.polyfit(xfitarr[:, xind])
    bgim[:, xind] = yfit_poly(yy - yy_mean)


    # Debugging plot in y-direction (along the orders)
    if 0:
    #if xind % 250 == 0:

      import biggles
      biggles.configure('screen', 'width',  900)
      biggles.configure('screen', 'height', 450)
      fr = biggles.FramedPlot()
      fr.yrange = [bgim[:, xind].min()-50, bgim[:, xind].max()+50]
      fr.add(biggles.Curve(yy, bgim[:, xind], color='blue'))
      fr.add(biggles.Points(yvals, xfitarr[:, xind], color='red'))
      fr.add(biggles.Points(yvals.take(goodind), xfitarr[goodind, xind], color='green'))
      fr.title = str(xind)
      fr.show()


  frame[extension].data = frame[extension].data - bgim
Пример #40
0
    def test_pqr_shear_recovery(self,
                                smin,
                                smax,
                                nshear,
                                npair=10000,
                                h=1.e-6,
                                eps=None,
                                expand_shear=None):
        """
        Test how well we recover the shear with no noise.

        parameters
        ----------
        smin: float
            min shear to test
        smax: float
            max shear to test
        nshear:
            number of shear values to test
        npair: integer, optional
            Number of pairs to use at each shear test value
        """
        import lensing
        from .shape import Shape, shear_reduced

        shear1_true = numpy.linspace(smin, smax, nshear)
        shear2_true = numpy.zeros(nshear)

        shear1_meas = numpy.zeros(nshear)
        shear2_meas = numpy.zeros(nshear)

        # _te means expanded around truth
        shear1_meas_te = numpy.zeros(nshear)
        shear2_meas_te = numpy.zeros(nshear)

        theta = numpy.pi / 2.0
        twotheta = 2.0 * theta
        cos2angle = numpy.cos(twotheta)
        sin2angle = numpy.sin(twotheta)

        # extra dim because working in 2d
        samples = numpy.zeros((npair * 2, self.ndim + 1))
        g = numpy.zeros(npair)
        g1 = numpy.zeros(npair * 2)
        g2 = numpy.zeros(npair * 2)

        for ishear in xrange(nshear):
            s1 = shear1_true[ishear]
            s2 = shear2_true[ishear]

            tsamples = self.sample2d(npair)

            g1samp = tsamples[:, 0]
            g2samp = tsamples[:, 1]
            g1[0:npair] = g1samp
            g2[0:npair] = g2samp

            # ring test, rotated by pi/2
            g1[npair:] = g1samp * cos2angle + g2samp * sin2angle
            g2[npair:] = -g1samp * sin2angle + g2samp * cos2angle

            # now shear all
            g1s, g2s = shear_reduced(g1, g2, s1, s2)

            #g=numpy.sqrt(g1s**2 + g2s**2)
            #print("gmin:",g.min(),"gmax:",g.max())

            samples[:, 0] = g1s
            samples[:, 1] = g2s
            samples[0:npair, 2:] = tsamples[:, 2:]
            samples[npair:, 2:] = tsamples[:, 2:]

            P, Q, R = self.get_pqr_num(samples, h=h)

            if expand_shear is not None:
                s1expand = expand_shear[0]
                s2expand = expand_shear[1]
            else:
                s1expand = s1
                s2expand = s2
            P_te, Q_te, R_te = self.get_pqr_num(samples,
                                                s1=s1expand,
                                                s2=s2expand,
                                                h=h)

            g1g2, C = lensing.pqr.get_pqr_shear(P, Q, R)
            g1g2_te, C_te = lensing.pqr.get_pqr_shear(P_te, Q_te, R_te)

            #g1g2_te[0] += s1
            #g1g2_te[1] += s2

            shear1_meas[ishear] = g1g2[0]
            shear2_meas[ishear] = g1g2[1]

            shear1_meas_te[ishear] = g1g2_te[0]
            shear2_meas_te[ishear] = g1g2_te[1]

            mess = 'true: %.6f,%.6f meas: %.6f,%.6f expand true: %.6f,%.6f'
            print(mess % (s1, s2, g1g2[0], g1g2[1], g1g2_te[0], g1g2_te[1]))

        fracdiff = shear1_meas / shear1_true - 1
        fracdiff_te = shear1_meas_te / shear1_true - 1
        if eps:
            import biggles
            biggles.configure('default', 'fontsize_min', 3)
            plt = biggles.FramedPlot()
            #plt.xlabel=r'$\gamma_{true}$'
            #plt.ylabel=r'$\Delta \gamma/\gamma$'
            plt.xlabel = r'$g_{true}$'
            plt.ylabel = r'$\Delta g/g$'
            plt.aspect_ratio = 1.0

            plt.add(
                biggles.FillBetween([0.0, smax], [0.004, 0.004], [0.0, smax],
                                    [0.000, 0.000],
                                    color='grey90'))
            plt.add(
                biggles.FillBetween([0.0, smax], [0.002, 0.002], [0.0, smax],
                                    [0.000, 0.000],
                                    color='grey80'))

            psize = 2.25
            pts = biggles.Points(shear1_true,
                                 fracdiff,
                                 type='filled circle',
                                 size=psize,
                                 color='blue')
            pts.label = 'expand shear=0'
            plt.add(pts)

            pts_te = biggles.Points(shear1_true,
                                    fracdiff_te,
                                    type='filled diamond',
                                    size=psize,
                                    color='red')
            pts_te.label = 'expand shear=true'
            plt.add(pts_te)

            if nshear > 1:
                coeffs = numpy.polyfit(shear1_true, fracdiff, 2)
                poly = numpy.poly1d(coeffs)

                curve = biggles.Curve(shear1_true,
                                      poly(shear1_true),
                                      type='solid',
                                      color='black')
                #curve.label=r'$\Delta \gamma/\gamma~\propto~\gamma^2$'
                curve.label = r'$\Delta g/g = 1.9 g^2$'
                plt.add(curve)

                plt.add(
                    biggles.PlotKey(0.1,
                                    0.9, [pts, pts_te, curve],
                                    halign='left'))
                print(poly)

            print('writing:', eps)
            plt.write_eps(eps)
Пример #41
0
import cPickle
import biggles
from pfac import const
from pfac.table import *
from pfac.spm import *
from math import *

biggles.configure('fontsize_min', 1.0)
p = biggles.FramedPlot()
p.ylog = 1
p.ylabel = 'Abundance Ratio'
p.xlabel = 'Log Temperature (K)'
p.aspect_ratio = 0.7
(t, logt, abund) = get_tgrid(26, 6, amin=1E-10, limits=[5, 7.5])
nt = len(t)
for k in range(3, 12):
    y = []
    for i in range(nt):
        y.append(abund[i][k - 1] / abund[i][k])
    p.add(biggles.Curve(logt, y, linetype='solid', linewidth=2))

p.xrange = (6.3, 7.8)
p.yrange = (0.05, 200)
for k in [3, 5, 7, 9, 11]:
    (tmax, amax) = MaxAbund(26, k)
    tmax = log10(tmax / const.kb)
    x = [tmax, tmax]
    y = [0.1, 120]
    p.add(biggles.Curve(x, y, linetype='dashed', linewidth=2))
    p.add(biggles.Label(tmax, 140, '%d+' % (26 - k), size=0.5))
Пример #42
0
    def _setup_plotting(self):
        import biggles

        biggles.configure("screen", "width", 1100)
        biggles.configure("screen", "height", 1100)
Пример #43
0
def plot_pqr(gsigma=0.3, other=0.0):
    import biggles
    biggles.configure('default','fontsize_min',1.0)
    gp = GPriorBA(gsigma)

    n=100
    z=numpy.zeros(n) + other
    gmin=-1
    gmax=1
    g1=numpy.linspace(gmin,gmax,n)
    g2=numpy.linspace(gmin,gmax,n)

    P_g1,Q_g1,R_g1=gp.get_pqr(g1,z)
    P_g2,Q_g2,R_g2=gp.get_pqr(z,g2)

    tab=biggles.Table(3,2)

    plt_P_g1 = biggles.FramedPlot()
    pts_P_g1 = biggles.Points(g1, P_g1, type='filled circle')
    plt_P_g1.add(pts_P_g1)
    plt_P_g1.xlabel='g1'
    plt_P_g1.ylabel='P'

    plt_P_g2 = biggles.FramedPlot()
    pts_P_g2 = biggles.Points(g2, P_g1, type='filled circle')
    plt_P_g2.add(pts_P_g2)
    plt_P_g2.xlabel='g2'
    plt_P_g2.ylabel='P'


    plt_Q_g1 = biggles.FramedPlot()
    pts_Q1_g1 = biggles.Points(g1, Q_g1[:,0], type='filled circle', color='red')
    pts_Q2_g1 = biggles.Points(g1, Q_g1[:,1], type='filled circle', color='blue')
    pts_Q1_g1.label='Q1'
    pts_Q2_g1.label='Q2'

    Qkey_g1 = biggles.PlotKey(0.9,0.2,[pts_Q1_g1,pts_Q2_g1],halign='right')
    plt_Q_g1.add(pts_Q1_g1,pts_Q2_g1,Qkey_g1)
    plt_Q_g1.xlabel='g1'
    plt_Q_g1.ylabel='Q'


    plt_Q_g2 = biggles.FramedPlot()
    pts_Q1_g2 = biggles.Points(g2, Q_g2[:,0], type='filled circle', color='red')
    pts_Q2_g2 = biggles.Points(g2, Q_g2[:,1], type='filled circle', color='blue')
    pts_Q1_g2.label='Q1'
    pts_Q2_g2.label='Q2'

    Qkey_g2 = biggles.PlotKey(0.9,0.2,[pts_Q1_g2,pts_Q2_g2],halign='right')
    plt_Q_g2.add(pts_Q1_g2,pts_Q2_g2,Qkey_g2)
    plt_Q_g2.xlabel='g2'
    plt_Q_g2.ylabel='Q'

    
    plt_R_g1 = biggles.FramedPlot()
    pts_R11_g1 = biggles.Points(g1, R_g1[:,0,0], type='filled circle', color='red')
    pts_R12_g1 = biggles.Points(g1, R_g1[:,0,1], type='filled circle', color='darkgreen')
    pts_R22_g1 = biggles.Points(g1, R_g1[:,1,1], type='filled circle', color='blue')
    pts_R11_g1.label = 'R11'
    pts_R12_g1.label = 'R12'
    pts_R22_g1.label = 'R22'
    Rkey_g1 = biggles.PlotKey(0.9,0.2,[pts_R11_g1,pts_R12_g1,pts_R22_g1],halign='right')

    plt_R_g1.add(pts_R11_g1,pts_R12_g1,pts_R22_g1,Rkey_g1)
    plt_R_g1.xlabel='g1'
    plt_R_g1.ylabel='R'

    plt_R_g2 = biggles.FramedPlot()
    pts_R11_g2 = biggles.Points(g2, R_g2[:,0,0], type='filled circle', color='red')
    pts_R12_g2 = biggles.Points(g2, R_g2[:,0,1], type='filled circle', color='darkgreen')
    pts_R22_g2 = biggles.Points(g2, R_g2[:,1,1], type='filled circle', color='blue')

    pts_R11_g2.label = 'R11'
    pts_R12_g2.label = 'R12'
    pts_R22_g2.label = 'R22'
    Rkey_g2 = biggles.PlotKey(0.9,0.2,[pts_R11_g2,pts_R12_g2,pts_R22_g2],halign='right')

    plt_R_g2.add(pts_R11_g2,pts_R12_g2,pts_R22_g2,Rkey_g2)
    plt_R_g2.xlabel='g2'
    plt_R_g2.ylabel='R'
 
    tab[0,0] = plt_P_g1
    tab[1,0] = plt_Q_g1
    tab[2,0] = plt_R_g1

    tab[0,1] = plt_P_g2
    tab[1,1] = plt_Q_g2
    tab[2,1] = plt_R_g2

    tab.show()
Пример #44
0
def main():
    options,args = parser.parse_args(sys.argv[1:])

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

    lensrun=args[0]
    randrun=args[1]

    bintype=options.bintype

    minrad=float(options.minrad)
    subtract_rand = bool(options.subtract_rand)

    #if bintype is None or nbin is None:
    #    raise ValueError("currently demand some kind of binning")
    if bintype is None:
        raise ValueError("currently demand some kind of binning")

    if subtract_rand:
        print("Will subtract randoms")

    b = lensing.binning.instantiate_binner(bintype)
    nbin=b.get_nbin()

    binned_data = lensing.files.sample_read(type='binned', sample=lensrun, name=b.get_name())

    extra = 'randmatch-%s' % randrun


    allrand = lensing.files.sample_read(type='binned',
                                        sample=lensrun,
                                        name=b.get_name(),
                                        extra=extra)

    alldata = lensing.correct.correct(binned_data, allrand, 
                                      subtract_rand=subtract_rand,
                                      minrad=minrad)

    lensing.files.sample_write(data=alldata,
                               type='corrected',
                               sample=lensrun,
                               name=b.get_name(),
                               extra=extra) 



    # now some plots
    biggles.configure('screen','width', 1100)
    biggles.configure('screen','height', 1100)

    
    range4var = [0.1,100]
    for binnum in xrange(nbin):
        eps_corr_extra='correction-%02d' % binnum
        eps_corr=lensing.files.sample_file(type='corrected-plots',
                                           sample=lensrun,
                                           name=b.get_name(),
                                           extra=eps_corr_extra, ext='eps')

        eps_rand_extra='randcomp-%02d' % binnum
        eps_rand=lensing.files.sample_file(type='corrected-plots',
                                           sample=lensrun,
                                           name=b.get_name(),
                                           extra=eps_rand_extra, ext='eps')
        eps_rand_extra='randcomp-o-%02d' % binnum
        eps_orand=lensing.files.sample_file(type='corrected-plots',
                                            sample=lensrun,
                                            name=b.get_name(),
                                            extra=eps_rand_extra, ext='eps')


        eps_dsigcorr_extra='dsigcorr-%02d' % binnum
        eps_dsigcorr=lensing.files.sample_file(type='corrected-plots',
                                               sample=lensrun,
                                               name=b.get_name(),
                                               extra=eps_dsigcorr_extra, ext='eps')

        eps_all_extra='allcorr-%02d' % binnum
        eps_all=lensing.files.sample_file(type='corrected-plots',
                                          sample=lensrun,
                                          name=b.get_name(),
                                          extra=eps_all_extra, ext='eps')



        lensing.files.make_dir_from_path(eps_corr)

        data = alldata[binnum]
        rand = allrand[binnum]

        label=b.bin_label(binnum)

        tab=doplot(binned_data[binnum], data, rand, label, show=options.show)

        # the corr(r)-1 plot
        tab[0,1][0,0].write_eps(eps_corr)
        converter.convert(eps_corr, dpi=90, verbose=True)

        # the corr(r)-1 plot
        tab[0,1][1,0].write_eps(eps_dsigcorr)
        converter.convert(eps_dsigcorr, dpi=90, verbose=True)

        # the rand comparison plot
        tab[0,0].write_eps(eps_rand)
        converter.convert(eps_rand, dpi=120, verbose=True)

        # the rand comparison plot with ortho
        tab[1,0].write_eps(eps_orand)
        converter.convert(eps_orand, dpi=120, verbose=True)


        # all
        tab.write_eps(eps_all)
        converter.convert(eps_all, dpi=150, verbose=True)


        if options.prompt:
            key=raw_input("hit a key (q to quit): ")
            if key == 'q':
                return

    d=os.path.dirname(eps_corr)
    os.chdir(d)

    outfile = os.path.join('correction.html')
    pattern = eps_corr.replace('%02d.eps' % (nbin-1,), '*.png')
    pattern=os.path.basename(pattern)
    print("making correction html file:",outfile)
    os.system('im2html -p '+pattern+' > '+outfile)

    outfile = os.path.join('randcomp.html')
    pattern = eps_rand.replace('%02d.eps' % (nbin-1,), '*.png')
    pattern=os.path.basename(pattern)
    print("making rand compare html file:",outfile)
    os.system('im2html -p '+pattern+' > '+outfile)

    outfile = os.path.join('dsigcorr.html')
    pattern = eps_dsigcorr.replace('%02d.eps' % (nbin-1,), '*.png')
    pattern=os.path.basename(pattern)
    print("making disg corr html file:",outfile)
    os.system('im2html -p '+pattern+' > '+outfile)

    outfile = os.path.join('allcorr.html')
    pattern = eps_all.replace('%02d.eps' % (nbin-1,), '*.png')
    pattern=os.path.basename(pattern)
    print("making all corr html file:",outfile)
    os.system('im2html -p '+pattern+' > '+outfile)
Пример #45
0
    def plot_m_c_vs(self,
                    res,
                    name,
                    xlog=True,
                    show=False,
                    combine=False,
                    xrng=None):
        """
        result from fit_m_c_vs

        parameters
        ----------
        res: dict
            result from running fit_m_c_vs
        name: string
            Name for the variable binned against, e.g. s/n or whatever
            This is used for the x axis
        xlog: bool, optional
            If True, use a log x axis
        show: bool, optional
            If True, show the plot on the screen

        returns
        -------
        biggles plot object
        """

        import biggles
        biggles.configure('default', 'fontsize_min', 2.0)
        tab = biggles.Table(2, 1)

        xvals = res['mean']

        if xrng is None:
            if xlog:
                xrng = [0.5 * xvals.min(), 1.5 * xvals.max()]
            else:
                xrng = [0.9 * xvals.min(), 1.1 * xvals.max()]

        mplt = biggles.FramedPlot()
        mplt.xlabel = name
        mplt.ylabel = 'm'
        mplt.xrange = xrng
        mplt.yrange = [-0.01, 0.01]
        mplt.xlog = xlog

        cplt = biggles.FramedPlot()
        cplt.xlabel = name
        cplt.ylabel = 'c'
        cplt.xrange = xrng
        cplt.yrange = [-0.0015, 0.0015]
        cplt.xlog = xlog

        if combine:

            m = 0.5 * (res['m1'] + res['m2'])
            c = 0.5 * (res['c1'] + res['c2'])

            merr = array([
                min(m1err, m2err)
                for m1err, m2err in zip(res['m1err'], res['m2err'])
            ])
            cerr = array([
                min(c1err, c2err)
                for c1err, c2err in zip(res['c1err'], res['c2err'])
            ])

            merr /= sqrt(2)
            cerr /= sqrt(2)

            mc = biggles.Points(xvals, m, type='filled circle', color='blue')
            merrc = biggles.SymmetricErrorBarsY(xvals, m, merr, color='blue')

            cc = biggles.Points(xvals, c, type='filled circle', color='blue')
            cerrc = biggles.SymmetricErrorBarsY(xvals, c, cerr, color='blue')

            zc = biggles.Curve(xrng, [0, 0])

            mplt.add(zc, mc, merrc)
            cplt.add(zc, cc, cerrc)

        else:
            m1c = biggles.Points(xvals,
                                 res['m1'],
                                 type='filled circle',
                                 color='blue')
            m1c.label = 'm1'
            m1errc = biggles.SymmetricErrorBarsY(xvals,
                                                 res['m1'],
                                                 res['m1err'],
                                                 color='blue')

            m2c = biggles.Points(xvals,
                                 res['m2'],
                                 type='filled circle',
                                 color='red')
            m2c.label = 'm2'
            m2errc = biggles.SymmetricErrorBarsY(xvals,
                                                 res['m2'],
                                                 res['m2err'],
                                                 color='red')
            mkey = biggles.PlotKey(0.9, 0.9, [m1c, m2c], halign='right')

            c1c = biggles.Points(xvals,
                                 res['c1'],
                                 type='filled circle',
                                 color='blue')
            c1c.label = 'c1'
            c1errc = biggles.SymmetricErrorBarsY(xvals,
                                                 res['c1'],
                                                 res['c1err'],
                                                 color='blue')

            c2c = biggles.Points(xvals,
                                 res['c2'],
                                 type='filled circle',
                                 color='red')
            c2c.label = 'c2'
            c2errc = biggles.SymmetricErrorBarsY(xvals,
                                                 res['c2'],
                                                 res['c2err'],
                                                 color='red')
            ckey = biggles.PlotKey(0.9, 0.9, [c1c, c2c], halign='right')

            zc = biggles.Curve(xvals, xvals * 0)

            mplt.add(zc, m1c, m1errc, m2c, m2errc, mkey)

            cplt.add(zc, c1c, c1errc, c2c, c2errc, ckey)

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

        if show:
            tab.show()
        return tab