Exemple #1
0
    def test_example2(self):
        p = biggles.FramedPlot()
        p.xrange = 0, 100
        p.yrange = 0, 100
        p.aspect_ratio = 1

        x = numpy.arange(0, 100, 5)
        yA = numpy.random.normal(40, 10, size=len(x))
        yB = x + numpy.random.normal(0, 5, size=len(x))

        a = biggles.Points(x, yA, type="circle")
        a.label = "a points"

        b = biggles.Points(x, yB)
        b.label = "b points"
        b.style(type="filled circle")

        l = biggles.Slope(1, type="dotted")
        l.label = "slope"

        k = biggles.PlotKey(.1, .9)
        k += a
        k += b, l

        p.add(l, a, b, k)

        _write_example(2, p)
Exemple #2
0
def plot( delta_scores_1, delta_rms_1, delta_scores_2, delta_rms_2,
          feps ):
    """
    """
    p = B.FramedPlot()
    p.xlabel = r"Interface rmsd to bound relative to free"
    p.ylabel = r"Docking performance relative to free"
    
    points_1 = B.Points( delta_rms_1, delta_scores_1, type='circle',
                         symbolsize=1)
    points_1.label = 'MD'
    
    points_2 = B.Points( delta_rms_2, delta_scores_2, type='diamond',
                         symbolsize=1)
    points_2.label = 'PCR-MD'

    a = concatenate( (delta_rms_1, delta_rms_2) )
    h = density( a, 20 )
    scale = max( h[:,1] ) / max( a )
    histogram = B.Curve( h[:,0], h[:,1] * scale )
    histogram.label = "distribution"
    
    p.add( points_1 )
    p.add( points_2 )
    p.add( histogram )
    p.add( B.PlotKey( 0.73, 0.95, [ points_1, points_2, histogram ] ) )

    p.show()
    p.write_eps( feps )
Exemple #3
0
def _plot_single(data, samples, comps, do_ylog=False):
    import biggles
    import esutil as eu
    import pcolors

    valmin=data.min()
    valmax=data.max()

    std = data.std()
    binsize=0.05*std

    ph,be,harr = biggles.make_histc(data, min=valmin, max=valmax,
                                    binsize=binsize,
                                    ylog=do_ylog, norm=1,
                                    get_hdata=True)
    sample_ph,sbe,sharr= biggles.make_histc(samples, min=valmin, max=valmax,
                                            binsize=binsize, color='red', ylog=do_ylog, norm=1,
                                            get_hdata=True)

    ph.label='data'
    sample_ph.label='fit'

    key = biggles.PlotKey(0.1, 0.9, [ph, sample_ph], halign='left')
    plt = biggles.FramedPlot()
    plt.add( ph, sample_ph, key )

    w,=where( (harr > 0) & (sharr > 0) )
    yrange=[min(harr[w].min(), sharr[w].min()),
            1.1*max(harr[w].max(), sharr[w].max())]

    if do_ylog:
        plt.ylog=True

    # now add the components
    h,rev=eu.stat.histogram(comps, rev=True)
    print(h)
    w,=where(h > 0)
    ncolors = w.size

    colors=pcolors.rainbow(ncolors)

    icolor=0
    for i in xrange(h.size):
        if rev[i] != rev[i+1]:
            w=rev[ rev[i]:rev[i+1] ]

            frac=float(w.size)/comps.size

            ph = biggles.make_histc(samples[w],
                                    #min=valmin, max=valmax,
                                    binsize=binsize,
                                    color=colors[icolor],
                                    ylog=do_ylog,
                                    norm=frac)
            plt.add(ph)
            icolor += 1

    plt.yrange=yrange
    return plt
Exemple #4
0
    def test_example10(self):
        from numpy import log10, logspace, random

        # 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)
        epts = biggles.SymmetricErrorBarsY(x, y, yerr, color=color)

        pts.label = 'data'
        mcurve.label = '1/x'

        key = biggles.PlotKey(0.9, 0.9, [pts, mcurve], halign='right')

        a[0, 0] += pts, epts, mcurve, key
        a[0, 0].ytitle = r'$\Delta\Sigma  [M_{\odot} pc^{-2}]$'
        a[0, 0].yrange = [0.05, 20.0]
        a[0, 0].xrange = [0.05, 20.0]
        a[0, 0].ylog = True  # log y axis only for the top plot

        a[1, 0] += biggles.Points(x, yratio, type=sym, color=color, size=3)
        a[1, 0] += biggles.SymmetricErrorBarsY(x,
                                               yratio,
                                               yratio_err,
                                               color=color)
        a[1, 0] += biggles.Curve(x, x * 0 + 1)
        a[1, 0].ytitle = r'$ratio$'
        a[1, 0].yrange = [0.5, 1.5]

        _write_example(10, a)
Exemple #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!
    """
    import biggles
    tab = biggles.Table(2, 1)
    pltbig = biggles.FramedPlot()
    pltzoom = biggles.FramedPlot()

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

    lin = Linear()
    r = 10.0**np.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 = lin.xi(r, nplk=nplk)

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

        plist.append(climxi)

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

    key = biggles.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()
    def plot_ens(self, keys, member=None, firstBold=0, yrange=None):
        """
        Plot the different entropy components versus variable parameter.
        keys   - [str], keys from R.calculate()
        member - int OR None, member index or None for ensemble
        """
        colors = ['black', 'red', 'blue', 'green', 'cyan', 'grey54', 'brown']
        colors.reverse()

        ## axis dimensions and labels
        p = B.FramedPlot()
        p.xlabel = self.var
        p.ylabel = 'bound-free entropy [cal/(mol K)]'

        if yrange: p.yrange = yrange

        d = self.calculate(member)

        sz = firstBold * 3 or 1
        curves = []
        points = []

        for k in keys:
            c = colors.pop()
            curve = B.Curve(self.vrange, d[k], color=c, width=sz)
            curve.label = k
            pts = B.Points(self.vrange, d[k], color=c, type='filled circle')

            curves.append(curve)
            points.append(pts)

            sz = 1

        ## add first item last (to have it on top)
        curves.reverse()
        points.reverse()
        for i in range(len(curves)):
            p.add(curves[i])
            p.add(points[i])

        ## Legend
        curves.reverse()
        p.add(B.PlotKey(.70, .85, curves))

        return p
Exemple #7
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
Exemple #8
0
    def doplot(self, show=False):
        """
        plot m,c vs s2n
        """
        import biggles

        xrng = [0.5 * self.s2n.min(), 1.5 * self.s2n.max()]
        mplt = biggles.FramedPlot()
        cplt = biggles.FramedPlot()

        mplt.xlabel = 'S/N'
        mplt.ylabel = 'm'
        mplt.xlog = True
        mplt.xrange = xrng

        cplt.xlabel = 'S/N'
        cplt.ylabel = 'c'
        cplt.xlog = True
        cplt.xrange = xrng

        color1 = 'blue'
        color2 = 'red'

        mcurve1 = biggles.Curve(self.s2n,
                                self.m[:, 0],
                                type='solid',
                                color=color1)
        merr1 = biggles.SymmetricErrorBarsY(self.s2n,
                                            self.m[:, 0],
                                            self.merr[:, 0],
                                            color=color1)
        mcurve2 = biggles.Curve(self.s2n,
                                self.m[:, 1],
                                type='dashed',
                                color=color2)
        merr2 = biggles.SymmetricErrorBarsY(self.s2n,
                                            self.m[:, 1],
                                            self.merr[:, 1],
                                            color=color2)

        ccurve1 = biggles.Curve(self.s2n,
                                self.c[:, 0],
                                type='solid',
                                color=color1)
        cerr1 = biggles.SymmetricErrorBarsY(self.s2n,
                                            self.c[:, 0],
                                            self.cerr[:, 0],
                                            color=color1)
        ccurve2 = biggles.Curve(self.s2n,
                                self.c[:, 1],
                                type='dashed',
                                color=color2)
        cerr2 = biggles.SymmetricErrorBarsY(self.s2n,
                                            self.c[:, 1],
                                            self.cerr[:, 1],
                                            color=color2)

        key = biggles.PlotKey(0.1, 0.9, [mcurve1, mcurve2], halign='left')

        mcurve1.label = r'$g_1$'
        mcurve2.label = r'$g_2$'
        ccurve1.label = r'$g_1$'
        ccurve2.label = r'$g_2$'

        zc = biggles.Curve(self.s2n, self.s2n * 0)

        mplt.add(mcurve1, merr1, mcurve2, merr2, zc, key)
        cplt.add(ccurve1, cerr1, ccurve2, cerr2, zc, key)

        if show:
            mplt.show()
            cplt.show()
        return mplt, cplt
Exemple #9
0
ncpts, ncptsc, ncerr, ncfitc = make_points(
    ncshears,
    ncbiases,
    ncerrs,
    nccolor,
    ncres,
)
ncpts.label = 'no coadd'
#ncres = run_fitter(ncshears, ncbiases*units, ncerrs*units)
#ncres['type']='no coadd'
#print_res(ncres)

key = biggles.PlotKey(
    0.1,
    0.9,
    [simpts, fitc, ncpts],
    halign='left',
)

ax = numpy.array([-0.1, 0.2])
z = biggles.Curve(ax, ax * 0)

allowed = biggles.FillBetween(ax, [-1.0e-3 / units] * 2,
                              ax, [1.0e-3 / units] * 2,
                              color='gray90')

plt.add(
    allowed,
    z,
    simpts,
    simerr,
Exemple #10
0
                                   symbolsize=psize[i])
            if (i == 0):
                b0.label = labels[j]
                bp[2+j] = b0
            if (j == 1):
                b1.label = shells[i]
                bp[i] = b1
            p.add(b0)
            p.add(b1)
            if (k == 10 and j == n-1):
                continue
            ym = max(y)
            if (ymax < ym):
                ymax = ym
            ym = min(y)
            if (ymin > ym):
                ymin = ym
    p.yrange = (ymin*0.85, ymax*1.25)
    x0 = 0.15
    if (k < 10):
        y0 = 0.3
    else:
        y0 = 0.25
    p.add(biggles.PlotKey(x0, y0, bp[:3]))
    x0 = 0.7
    y0 = 0.85
    p.add(biggles.PlotKey(x0, y0, bp[3:]))
    p.write_eps('rates%02d.eps'%k)
        
            
Exemple #11
0
tmp1 = biggles.Points(u1gg, ggrange, size=1.5, type="filled circle")
p.add(tmp1)
p.add(biggles.SymmetricErrorBarsX(u1gg, ggrange, u1gg_err))
tmp2 = biggles.Points(u1inee, ineerange, size=2, type="triangle")
p.add(tmp2)
p.add(biggles.SymmetricErrorBarsX(u1inee, ineerange, u1inee_err))
tmp3 = biggles.Points(u1outee,
                      outeerange,
                      size=2,
                      type="filled inverted triangle")
p.add(tmp3)
p.add(biggles.SymmetricErrorBarsX(u1outee, outeerange, u1outee_err))
tmp1.label = r"$\gamma\gamma$ luminosity"
tmp2.label = r"inner $e^+e^-$"
tmp3.label = r"outer $e^+e^-$"
p.add(biggles.PlotKey(0.6, 0.7, [tmp1, tmp2, tmp3]))
p.yrange = -len(names1), 1
p.y.ticks = ineerange
p.y.ticklabels = names1
p.y1.draw_subticks = 0
p.y.draw_ticks = 0
p.y2.draw_ticklabels = 0
p.xrange = -0.2, 1.2
p.x1.label = r"$M_{PDG} - M_{measured}$ for $\Upsilon(1S)$"
p.aspect_ratio = 11. / 8.5
p.show()
p.write_eps("/home/mccann/antithesis/plots/bhabhafits_shifts1.eps")

ggrange = Numeric.array(range(0, -len(names2), -1)) + 0.2
ineerange = Numeric.array(range(0, -len(names2), -1))
outeerange = Numeric.array(range(0, -len(names2), -1)) - 0.2
Exemple #12
0
        y = [2e-1,2.71e-1,2.87e-1,2.78e-1,2.6e-1,2.4e-1,2.2e-1,
             2.01e-1,1.84e-1,9.02e-2,5.48e-2,3.76e-2,2.78e-2,2.16e-2]
        y1 = [9.86e-2,6.41e-2,4.56e-2,3.44e-2,2.71e-2,2.21e-2,1.84e-2,
              1.57e-2,1.36e-2,5.06e-3,2.8e-3,1.84e-3,1.32e-3,1.01e-3]
        y = map(lambda a,b:a+b, y, y1)
        x = map(lambda a:log10(a*1e3/const.kb), x)
        c = biggles.Points(x[:-5], y[:-5],
                           symboltype='filled circle',symbolsize=1.5)
        p.add(c)
        c.label = 'Roszman87a'
        b.append(c)
    if (k == 8):
        x = [0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,2.0,3.0,4.0,5.0]
        y = [1.1e-1,1.84e-1,2.14e-1,2.19e-1,2.11e-1,1.99e-1,1.86e-1,
             1.72e-1,1.60e-1,8.15e-2,5.02e-2,3.47e-2,2.58e-2]
        y1 = [1.52e-1,9.57e-2,6.7e-2,5.01e-2,3.93e-2,3.19e-2,2.65e-2,
             2.25e-2,1.94e-2,7.18e-3,3.97e-3,2.60e-3,1.87e-3]
        y = map(lambda a,b:a+b, y, y1)
        x = map(lambda a:log10(a*1e3/const.kb), x)
        c = biggles.Points(x[:-3], y[:-3],
                           symboltype='filled circle',symbolsize=1.5)
        p.add(c)
        c.label = 'Roszman87b'
        b.append(c)
        
    p.add(biggles.PlotKey(0.3, 0.2, b))
    
    p.write_eps('trates%02d.eps'%(k))
        
tbl.close()
Exemple #13
0
def compare_hist(data1,
                 data2,
                 names=None,
                 dataset_names=None,
                 nsig=10.0,
                 **kw):
    """
    Compare the normalized histograms for the two data sets.  Make a grid of
    plots if the data are multi-dimensional

    parameters
    ----------
    data1: array
        a [N] or [N,dim] array
    data2: array
        a [M] or [M,dim] array
    names: list, optional
        Optional list of names for each dimension
    dataset_names: list, optional
        Optional list of names for each dataset
    nsig: float, optional
        Optional number of standard deviations to clip histograms,
        default 10.0
    """
    import biggles
    from numpy import newaxis
    from .stat import sigma_clip

    if len(data1.shape) == 1:
        data1 = data1[:, newaxis]
    if len(data2.shape) == 1:
        data2 = data2[:, newaxis]

    n1, d1 = data1.shape
    n2, d2 = data2.shape

    if d1 != d2:
        raise ValueError("data must have same number of dims. "
                         "got %d and %d" % (d1, d2))

    if names is not None:
        if len(names) != d1:
            raise ValueError("names must have len equal to number of dims. "
                             " in data, got %d and %d" % (d1, len(names)))

    else:
        names = ['par%d' % i for i in xrange(d1)]
    if dataset_names is not None:
        if len(dataset_names) != 2:
            raise ValueError("dataset_names must be len 2, "
                             "got %d" % len(dataset_names))
    else:
        dataset_names = ['dataset1', 'dataset2']

    if nsig is None:
        nsig = 100.0

    grid = Grid(d1)
    tab = biggles.Table(grid.nrow, grid.ncol)

    pkw = {}
    pkw.update(kw)
    for dkeys in ['width', 'height']:
        del pkw[dkeys]

    pkw['visible'] = False
    for i in xrange(d1):
        mn1, st1, ind1 = sigma_clip(data1[:, i], nsig=nsig, get_indices=True)
        mn2, st2, ind2 = sigma_clip(data2[:, i], nsig=nsig, get_indices=True)

        use_std = max(st1, st2)
        binsize = 0.2 * use_std

        plt = biggles.FramedPlot()
        plt.xlabel = names[i]

        pkw['binsize'] = binsize
        pkw['color'] = 'blue'
        h1 = biggles.make_histc(data1[ind1, i], **pkw)
        pkw['color'] = 'red'
        h2 = biggles.make_histc(data2[ind2, i], **pkw)

        plt.add(h1, h2)

        if i == 0:
            h1.label = dataset_names[0]
            h2.label = dataset_names[1]
            key = biggles.PlotKey(0.9, 0.9, [h1, h2], halign='right')
            plt.add(key)

        row, col = grid(i)
        tab[row, col] = plt

    if 'show' in kw:
        show = kw['show']
    elif 'visible' in kw:
        show = kw['visible']
    else:
        show = True

    tab.aspect_ratio = kw.get('aspect_ratio', float(grid.nrow) / grid.ncol)
    if show:
        width = kw.get('width', 1000)
        height = kw.get('height', 1000)
        tab.show(width=width, height=height)

    return tab
Exemple #14
0
    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)
epts = biggles.SymmetricErrorBarsY(x, y, yerr, color=color)

pts.label = 'data'
mcurve.label = '1/x'

key = biggles.PlotKey(0.9, 0.9, [pts, mcurve], halign='right')
a[0, 0] += pts, epts, mcurve, key
a[0, 0].ytitle = r'$\Delta\Sigma  [M_{\odot} pc^{-2}]$'
a[0, 0].yrange = [0.05, 20.0]
a[0, 0].xrange = [0.05, 20.0]
a[0, 0].ylog = True  # log y axis only for the top plot

a[1, 0] += biggles.Points(x, yratio, type=sym, color=color, size=3)
a[1, 0] += biggles.SymmetricErrorBarsY(x, yratio, yratio_err, color=color)
a[1, 0] += biggles.Curve(x, x * 0 + 1)
a[1, 0].ytitle = r'$ratio$'
a[1, 0].yrange = [0.5, 1.5]

a.write("example10.png", dpi=55)
a.write("example10.eps")
a.write("example10.pdf")
Exemple #15
0
def compare_hist(
    data1,
    data2,
    names=None,
    dataset_names=None,
    nsig=10.0,
    **kw,
):
    """
    Compare the normalized histograms for the two data sets.  Make a grid of
    plots if the data are multi-dimensional

    parameters
    ----------
    data1: array
        a [N] or [N,dim] array
    data2: array
        a [M] or [M,dim] array
    names: list, optional
        Optional list of names for each dimension
    dataset_names: list, optional
        Optional list of names for each dataset
    nsig: float, optional
        Optional number of standard deviations to clip histograms,
        default 10.0
    """
    import biggles
    from numpy import newaxis
    from .stat import sigma_clip

    if len(data1.shape) == 1:
        data1 = data1[:, newaxis]
    if len(data2.shape) == 1:
        data2 = data2[:, newaxis]

    n1, d1 = data1.shape
    n2, d2 = data2.shape

    if d1 != d2:
        raise ValueError("data must have same number of dims. "
                         "got %d and %d" % (d1, d2))

    if names is not None:
        if len(names) != d1:
            raise ValueError("names must have len equal to number of dims. "
                             " in data, got %d and %d" % (d1, len(names)))

    else:
        names = ["par%d" % i for i in range(d1)]
    if dataset_names is not None:
        if len(dataset_names) != 2:
            raise ValueError("dataset_names must be len 2, "
                             "got %d" % len(dataset_names))
    else:
        dataset_names = ["dataset1", "dataset2"]

    if nsig is None:
        nsig = 100.0

    grid = Grid(d1)
    tab = biggles.Table(grid.nrow, grid.ncol)

    pkw = {}
    pkw.update(kw)
    for dkey in ["width", "height"]:
        pkw.pop(dkey, None)

    pkw["visible"] = False
    pkw["norm"] = 1
    if "nbin" not in pkw and 'binsize' not in pkw:
        get_binsize = True
    else:
        get_binsize = False

    for i in range(d1):

        mn1, st1, ind1 = sigma_clip(data1[:, i], nsig=nsig, get_indices=True)
        mn2, st2, ind2 = sigma_clip(data2[:, i], nsig=nsig, get_indices=True)
        if get_binsize:
            use_std = max(st1, st2)
            pkw["binsize"] = 0.2 * use_std

        plt = biggles.FramedPlot()
        plt.xlabel = names[i]

        pkw["color"] = "blue"
        h1 = biggles.make_histc(data1[ind1, i], **pkw)
        pkw["color"] = "red"
        h2 = biggles.make_histc(data2[ind2, i], **pkw)

        plt.add(h1, h2)

        if i == 0:
            h1.label = dataset_names[0]
            h2.label = dataset_names[1]
            key = biggles.PlotKey(0.9, 0.9, [h1, h2], halign="right")
            plt.add(key)

        row, col = grid(i)
        tab[row, col] = plt

    if "show" in kw:
        show = kw["show"]
    elif "visible" in kw:
        show = kw["visible"]
    else:
        show = True

    tab.aspect_ratio = kw.get("aspect_ratio", float(grid.nrow) / grid.ncol)
    if show:
        width = kw.get("width", 1000)
        height = kw.get("height", 1000)
        tab.show(width=width, height=height)

    return tab
Exemple #16
0
p = biggles.FramedPlot()
p.xrange = 0, 100
p.yrange = 0, 100
p.aspect_ratio = 1

x = numpy.arange(0, 100, 5)
yA = numpy.random.normal(40, 10, (len(x),))
yB = x + numpy.random.normal(0, 5, (len(x),))

a = biggles.Points(x, yA, type="circle")
a.label = "a points"

b = biggles.Points(x, yB)
b.label = "b points"
b.style(type="filled circle")

l = biggles.Slope(1, type="dotted")
l.label = "slope"

k = biggles.PlotKey(.1, .9)
k += a
k += b, l

p.add(l, a, b, k)

p.write("example2.png", dpi=55)
p.write("example2.eps")
p.write("example2.pdf")
p.show()
print("sim m: %g +/- %g alpha: %g +/- %g" %
      (sim_m, sim_merr, sim_alpha, sim_alphaerr))

simpts.label = 'image simulation'

#perr = biggles.SymmetricErrorBarsY(shears, m, merr)

#c = biggles.Curve(xp,fitter(xp),color='blue')
c = biggles.Curve(xp, xp**2 / units, color=mcolor, type='shortdashed')
#c.label=r'$%.2f + %.2f*g^2$' % (fm, falpha)
c.label = r'$1.0 \gamma^2$'

simc = biggles.Curve(xp, sim_m + sim_alpha / units * xp**2, color=simcolor)
#c.label=r'$%.2f + %.2f*g^2$' % (fm, falpha)
simc.label = r'$%.1f \gamma^2$' % sim_alpha

key = biggles.PlotKey(0.1, 0.9, [pts, c, simpts, simc], halign='left')

ax = numpy.array([-0.1, 0.2])
z = biggles.Curve(ax, ax * 0)

allowed = biggles.FillBetween(ax, [-1.0e-3 / units] * 2,
                              ax, [1.0e-3 / units] * 2,
                              color='gray90')

plt.add(allowed, z, c, simc, pts, ptsc, simpts, simerr, simptsc, key)

#plt.show()

plt.write_eps('results-noise0-m0.6.eps')
Exemple #18
0
disk2015p = biggles.Points([2015],
                           disk2015,
                           type='filled diamond',
                           color='red')
disk2015p.label = 'extrap 2015'

cpu2016p = biggles.Points([2016], cpu2016, type='filled circle', color='red')
cpu2016p.label = 'extrap 2016'
disk2016p = biggles.Points([2016],
                           disk2016,
                           type='filled diamond',
                           color='red')
disk2016p.label = 'extrap 2016'

key = biggles.PlotKey(0.9,
                      0.9,
                      [cpup, cpu2015p, cpu2016p, diskp, disk2015p, disk2016p],
                      halign='right')

plt.add(cpup, cpu2015p, cpu2016p, diskp, disk2015p, disk2016p, key)
plt.show()

print year
print diskcost, disk2015[0], disk2016[0]
print cpucost, cpu2015[0], cpu2016[0]

for i in xrange(year.size):
    print '%d %d %d' % (year[i], diskcost[i], cpucost[i])
print '-' * 70
print '%d %d %d' % (2015, disk2015[0], cpu2015[0])
print '%d %d %d' % (2016, disk2016[0], cpu2016[0])
Exemple #19
0
class TestStatsReporter:
    """
    The TestStatsReporter class is used to report statistics
    generated in testing a code.  There are two main modes
    of use: reading data from a previous run stored in file
    or adding new data.
    """
    def __init__(self, filesToReadFrom=[]):
        """
        __init__(self,filesToReadFrom=[]):
        Reads data from the files specified in filesToReadFrom.
        Note that each element in the list filesToReadFrom must
        be a file which can be imported into python via import,
        i.e., each element must a file of the form <name>.py
        which is in sys.path.
        """
        self.iterationsNeeded = []
        self.flips = []
        self.N = []
        self.K = []
        self.names = []

        for file in filesToReadFrom:
            self.GetStatsFromFile(file)

    def AddStats(self, N, K, name, iterationsNeeded, flips):
        """
        AddStats(self,N,K,name,iterationsNeeded,flips):
        
        Add results for running a test of an (N,K) quantization code
        resulting in flips unmatched bits for 
        the number of iterations required given by iterationsNeeded.
        """
        self.N.append(N)
        self.K.append(K)
        self.names.append(name)
        self.iterationsNeeded.append(iterationsNeeded)
        self.flips.append(flips)

    def GetStatsFromFile(self, file):
        """
        GetStatsFromFile(self,file):

        Read stats from file and add them to this object.
        See comments in the __init__ function for constrains on file.
        """
        fileData = __import__(file)
        Nlist = fileData.Nlist
        Klist = fileData.Klist
        nElist = fileData.nElist
        nameList = fileData.nameList
        iterNeeded = fileData.iterationsNeeded
        fl = fileData.flips

        self.N = self.N + Nlist
        self.K = self.K + Klist
        self.names = self.names + nameList
        self.iterationsNeeded = self.iterationsNeeded + iterNeeded
        self.flips = self.flips + fl

    def WriteInternalsToFD(self, fd):
        """
        WriteInternalsToFD(self,fd):

        Write internal representation of data to the file descriptor
        fd.  This allows a later TestStatsReporter object to read
        in the data using the GetStatsFromFile function.
        """
        fd.write('Nlist = ' + ` self.N ` + '\n')
        fd.write('Klist = ' + ` self.K ` + '\n')
        fd.write('nameList = ' + ` self.names ` + '\n')
        fd.write('iterationsNeeded = ' + ` self.iterationsNeeded ` + '\n')
        fd.write('flips = ' + ` self.flips ` + '\n')

    def Report(self, title='No title given', file=None):
        """
        Report(self,title='No title given',file=None):

        Report data for all tests using the given title and write
        the data to the given file name.  If file==None, then data
        is printed to the screen but not written to file.

        Note that if you want to be able to read the data back into
        a TestStatsReporter object in the future then file should
        end in .py and satisfy the other constrains listed in the
        comment for the __init__ function.
        """
        if (file == None):
            fd = sys.stdout
        else:
            fd = open(file, 'w')

        for codeIndex in range(len(self.names)):
            self.WriteFlipStatsToFD(codeIndex, title, fd)

        if (file != None):
            self.WriteInternalsToFD(fd)
            fd.close()
            print 'Data written to file ' + file

    def WriteFlipStatsToFD(self, codeIndex, title, fd):
        tries = reduce(lambda x, y: x + y, self.iterationsNeeded[codeIndex])
        sumFlips = reduce(
            lambda a, b: a + b,
            map(lambda k, v: k * v, self.flips[codeIndex].keys(),
                self.flips[codeIndex].values()))
        sumSqFlips = reduce(
            lambda a, b: a + b,
            map(lambda k, v: (k**2) * v, self.flips[codeIndex].keys(),
                self.flips[codeIndex].values()))
        mean = float(sumFlips) / float(tries)
        print '-->', tries, sumFlips, sumSqFlips, mean
        var = float(sumSqFlips) / float(tries) - mean**2
        fd.write('# ' + title + '\n')
        fd.write('# mean flips = ' + ` mean ` + '\n')
        fd.write('# variance   = ' + ` var ` + '\n')

    def MakePlot(self, file):
        """
        MakePlot(self,file):

        If file==None then do nothing.  Otherwise use biggles
        to create a plot of the test results and write them in
        Encapsulated PostScript format to file.

        Note that you must have biggles and Numeric installed
        for this function to work.
        """
        if (None == file):
            return None

        try:
            import biggles, Numeric
        except Exception, e:
            print 'Received exception "' + ` e ` + '" in import biggles,Numeric.'
            print 'No plot will be made.  Please install biggles and'
            print 'Numeric if you want plotting capability.'
            return

        p = biggles.FramedPlot()
        p.title = 'Length ' + ` self.N ` + ' code'
        p.xlabel = '% flipped'
        p.ylabel = 'prob'
        types = [
            'solid', 'dotted', 'dotdashed', 'longdashed', 'shortdashed',
            'dotdotdashed', 'dotdotdotdashed'
        ]
        curves = [0] * len(self.names)
        tries = [0] * len(self.names)
        for i in range(len(self.names)):
            keys = self.flips[i].keys()
            keys.sort()
            tries[i] = reduce(lambda x, y: x + y, self.iterationsNeeded[i])
            pFlipped = Numeric.array(
                map(lambda x: float(x) / float(self.N[i]), keys))
            prob = Numeric.array(
                map(lambda x: float(self.flips[i][x]) / tries[i], keys))

            curves[i] = biggles.Curve(pFlipped,
                                      prob,
                                      type=types[i % len(types)])
            curves[i].label = self.names[i]
            p.add(curves[i])
        plotKey = biggles.PlotKey(.1, .9, curves)
        p.add(plotKey)

        if (file):
            p.write_eps(file)
            print 'Plot written to file ', file

        return p
p4a.add(p4a_me)
p4a.add(
    biggles.SymmetricErrorBarsY(recont3,
                                fudge_factor * Numeric.array(hadxs_rec3lum),
                                fudge_factor *
                                Numeric.array(hadxs_rec3lumerr)))
p4a_gg = biggles.Points(Numeric.array(recont3) + 0.1,
                        hadxs_rerigglum,
                        symboltype="diamond",
                        symbolsize=2)
p4a_gg.label = r"from RunInfo's $\gamma\gamma$ luminosity"
p4a.add(p4a_gg)
p4a.add(
    biggles.SymmetricErrorBarsY(
        Numeric.array(recont3) + 0.1, hadxs_rerigglum, hadxs_rerigglumerr))
p4a_bb = biggles.Points(Numeric.array(recont3) + 0.2,
                        hadxs_reribblum,
                        symboltype="triangle",
                        symbolsize=2)
p4a_bb.label = r"from RunInfo's $e^+e^-$ luminosity"
p4a.add(p4a_bb)
p4a.add(
    biggles.SymmetricErrorBarsY(
        Numeric.array(recont3) + 0.2, hadxs_reribblum, hadxs_reribblumerr))
p4a.add(biggles.PlotKey(0.1, 0.2, [p4a_me, p4a_gg, p4a_bb]))
p4a.xrange = 0.5, 7.5
p4a.yrange = 5, 6
p4a.y1.label = r"below $\Upsilon(3S)$ hadronic $\sigma$, runinfo's units"
p4a.show()
p4a.write_eps("plottrig3_p4a.eps")
    def compare(self, run):
        import biggles
        import pcolors

        pdata, mdata = self.load_data(run)
        if len(pdata) == 0:
            print("no princeton data found")
            return
        if len(mdata) == 0:
            print("no my data found")
            return

        tab = biggles.Table(2, 2)

        pcos_plt = biggles.FramedPlot()
        psin_plt = biggles.FramedPlot()
        mcos_plt = biggles.FramedPlot()
        msin_plt = biggles.FramedPlot()

        pcos_plots = []
        psin_plots = []
        mcos_plots = []
        msin_plots = []

        colors = pcolors.rainbow(6, 'hex')

        for camcol in xrange(1, 6 + 1):
            # first princeton
            wp = where1(pdata['camcol'] == camcol)

            bcos = eu.stat.Binner(pdata['field'][wp],
                                  cos(2 * pdata['phi_offset'][wp]))
            bcos.dohist(binsize=1.0)
            bcos.calc_stats()

            wgood_cos = where1(bcos['hist'] > 0)
            pcos = biggles.Curve(bcos['xmean'][wgood_cos],
                                 bcos['ymean'][wgood_cos],
                                 color=colors[camcol - 1])
            pcos.label = 'princ camcol %s' % camcol

            pcos_plt.add(pcos)
            pcos_plots.append(pcos)

            bsin = eu.stat.Binner(pdata['field'][wp],
                                  sin(2 * pdata['phi_offset'][wp]))
            bsin.dohist(binsize=1.0)
            bsin.calc_stats()

            wgood_sin = where1(bsin['hist'] > 0)
            psin = biggles.Curve(bsin['xmean'][wgood_sin],
                                 bsin['ymean'][wgood_sin],
                                 color=colors[camcol - 1])
            psin.label = 'princ camcol %s' % camcol

            psin_plt.add(psin)
            psin_plots.append(psin)

            # now mine
            wm = where1(mdata['camcol'] == camcol)
            mpcos = biggles.Curve(mdata['field'][wm],
                                  cos(2 * mdata['angle'][wm, 2]),
                                  color=colors[camcol - 1])
            mpcos.label = 'mine camcol %s' % camcol
            mcos_plt.add(mpcos)
            mcos_plots.append(mpcos)

            wm = where1(mdata['camcol'] == camcol)
            mpsin = biggles.Curve(mdata['field'][wm],
                                  sin(2 * mdata['angle'][wm, 2]),
                                  color=colors[camcol - 1])
            mpsin.label = 'mine camcol %s' % camcol
            msin_plt.add(mpsin)
            msin_plots.append(mpsin)

        # princeton stuff
        pcos_key = biggles.PlotKey(0.1, 0.9, pcos_plots)
        pcos_plt.add(pcos_key)

        pcos_plt.xlabel = 'Field'
        pcos_plt.title = 'Run: %s' % run
        pcos_plt.ylabel = 'cos(2*angle)'

        psin_key = biggles.PlotKey(0.1, 0.9, psin_plots)
        psin_plt.add(psin_key)

        psin_plt.xlabel = 'Field'
        psin_plt.title = 'Run: %s' % run
        psin_plt.ylabel = 'sin(2*angle)'

        tab[0, 0] = pcos_plt
        tab[0, 1] = psin_plt

        # my stuff
        mcos_key = biggles.PlotKey(0.1, 0.9, mcos_plots)
        mcos_plt.add(mcos_key)

        mcos_plt.xlabel = 'Field'
        mcos_plt.title = 'Run: %s' % run
        mcos_plt.ylabel = 'cos(2*angle)'

        msin_key = biggles.PlotKey(0.1, 0.9, msin_plots)
        msin_plt.add(msin_key)

        msin_plt.xlabel = 'Field'
        msin_plt.title = 'Run: %s' % run
        msin_plt.ylabel = 'sin(2*angle)'

        tab[1, 0] = mcos_plt
        tab[1, 1] = msin_plt

        tab.show()
Exemple #22
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)
Exemple #23
0
import biggles
import numpy
import numpy.random

p = biggles.FramedPlot()
p.xrange = 0, 100
p.yrange = 0, 100
p.aspect_ratio = 1

x = numpy.arange( 0, 100, 5 )
yA = numpy.random.normal( 40, 10, (len(x),) )
yB = x + numpy.random.normal( 0, 5, (len(x),) )

a = biggles.Points( x, yA, type="circle" )
a.label = "a points"

b = biggles.Points( x, yB )
b.label = "b points"
b.style( type="filled circle" )

l = biggles.Slope( 1, type="dotted" )
l.label = "slope"

k = biggles.PlotKey( .1, .9, [a,b,l] )

p.add( l, a, b, k )

#p.write_img( 400, 400, "example2.png" )
#p.write_eps( "example2.eps" )
p.show()
Exemple #24
0
class TestStatsReporter:
    """
    The TestStatsReporter class is used to report statistics
    generated in testing a code.  There are two main modes
    of use: reading data from a previous run stored in file
    or adding new data.
    """
    def __init__(self, filesToReadFrom=[]):
        """
        __init__(self,filesToReadFrom=[]):
        Reads data from the files specified in filesToReadFrom.
        Note that each element in the list filesToReadFrom must
        be a file which can be imported into python via import,
        i.e., each element must a file of the form <name>.py
        which is in sys.path.

        For example, if you have previously generated the files
        test_a.py and test_b.py you can read them in using
        t = TestStatsReporter(['test_a','test_b'])
        """
        self.numSuccesses = []
        self.numTrials = []
        self.N = []
        self.K = []
        self.names = []
        self.noiseType = ''
        self.noiseLevels = []

        for file in filesToReadFrom:
            self.GetStatsFromFile(file)

    def AddStats(self, N, K, noiseType, noiseLevels, name, numSuccesses,
                 numTrials):
        """
        AddStats(self,N,K,noiseType,noiseLevels,name,numSuccesses,numTrials):
        
        Add results for running a test of an (N,K) code with the given
        parameters.
        """
        self.N.append(N)
        self.K.append(K)
        self.noiseLevels.append(noiseLevels)
        self.names.append(name)
        self.numSuccesses.append(numSuccesses)
        self.numTrials.append(numTrials)
        if (self.noiseType and self.noiseType != noiseType):
            raise Exception, ('Data noise types differ:', self.noiseType,
                              noiseType)
        else:
            self.noiseType = noiseType

    def GetStatsFromFile(self, file):
        """
        GetStatsFromFile(self,file):

        Read stats from file and add them to this object.
        See comments in the __init__ function for constrains on file.
        """
        fileData = __import__(file)
        Nlist = fileData.Nlist
        Klist = fileData.Klist
        nLList = fileData.nLList
        noiseType = fileData.noiseType
        nameList = fileData.nameList
        numSuccesses = fileData.numSuccesses
        numTrials = fileData.numTrials

        self.N = self.N + Nlist
        self.K = self.K + Klist
        self.noiseLevels = self.noiseLevels + nLList
        if (self.noiseType and self.noiseType != noiseType):
            raise Exception, ('Data noise types differ:', self.noiseType,
                              noiseType)
        else:
            self.noiseType = noiseType

        self.names = self.names + nameList
        self.numSuccesses = self.numSuccesses + numSuccesses
        self.numTrials = self.numTrials + numTrials

    def WriteInternalsToFD(self, fd):
        """
        WriteInternalsToFD(self,fd):

        Write internal representation of data to the file descriptor
        fd.  This allows a later TestStatsReporter object to read
        in the data using the GetStatsFromFile function.
        """
        fd.write('Nlist = ' + ` self.N ` + '\n')
        fd.write('Klist = ' + ` self.K ` + '\n')
        fd.write('nLList = ' + ` self.noiseLevels ` + '\n')
        fd.write('noiseType = ' + ` self.noiseType ` + '\n')
        fd.write('nameList = ' + ` self.names ` + '\n')
        fd.write('numSuccesses = ' + ` self.numSuccesses ` + '\n')
        fd.write('numTrials = ' + ` self.numTrials ` + '\n')

    def WriteStatsToFD(self, codeIndex, title, fd):
        """
        WriteStatsToFD(self,codeIndex,title,fd):

        Write the results for test number codeIndex with the given
        title to file descriptor fd.
        """
        fd.write('# ' + title + '\n')
        fd.write('# ' + 'code title = ' + self.names[codeIndex] + '\n')

    def Report(self, title='No title given', file=None):
        """
        Report(self,title='No title given',file=None):

        Report data for all tests using the given title and write
        the data to the given file name.  If file==None, then data
        is printed to the screen but not written to file.

        Note that if you want to be able to read the data back into
        a TestStatsReporter object in the future then file should
        end in .py and satisfy the other constrains listed in the
        comment for the __init__ function.
        """
        if (file == None):
            fd = sys.stdout
        else:
            fd = open(file, 'w')

        for codeIndex in range(len(self.names)):
            self.WriteStatsToFD(codeIndex, title, fd)

        if (file != None):
            self.WriteInternalsToFD(fd)
            fd.close()
            print 'Data written to file ' + file

    def MakePlot(self, file=None, title=None, xrange=None):
        """
        MakePlot(self,file=None,title=None,xrange=None):

        If file==None then do nothing.  Otherwise use biggles
        to create a plot of the test results and write them in
        Encapsulated PostScript format to file.

        Note that you must have biggles and Numeric installed
        for this function to work.
        """
        if (None == file):
            return None
        if (None == title):
            title = 'Length ' + ` self.N ` + ' codes'

        try:
            import biggles, Numeric
        except Exception, e:
            print 'Received exception "' + ` e ` + '" in import biggles,Numeric.'
            print 'No plot will be made.  Please install biggles and'
            print 'Numeric if you want plotting capability.'
            return

        p = biggles.FramedPlot()
        if (None != xrange):
            p.xrange = xrange
        p.title = title
        p.xlabel = self.noiseType
        p.ylabel = 'failure probability'
        types = [
            'solid', 'dotted', 'dotdashed', 'longdashed', 'shortdashed',
            'dotdotdashed', 'dotdotdotdashed'
        ]
        curves = [0] * len(self.names)

        for i in range(len(self.names)):
            noiseLevels = Numeric.array(self.noiseLevels[i])
            failProbs = Numeric.array(
                map(lambda x, y: 1 - (float(x) / float(y)),
                    self.numSuccesses[i], self.numTrials[i]))
            curves[i] = biggles.Curve(noiseLevels, failProbs, type=types[i])
            curves[i].label = self.names[i]
            p.add(curves[i])

        plotKey = biggles.PlotKey(.1, .9, curves)
        p.add(plotKey)

        if (file):
            p.write_eps(file)
            print 'Plot written to file ', file

        return p
Exemple #25
0
    def test_labels(self):
        import numpy
        from numpy import linspace

        key = biggles.PlotKey(0.1, 0.9, halign='left')

        plt = biggles.FramedPlot(key=key, aspect_ratio=1)

        err = 0.1
        x = numpy.arange(10)
        y = numpy.arange(10)**2

        err = numpy.zeros(x.size) + 2
        ydata = y + numpy.random.normal(size=x.size) * err

        color = 'red'
        pts = biggles.Points(x,
                             ydata,
                             color=color,
                             type='filled diamond',
                             label='data')
        errpts = biggles.SymmetricErrorBarsY(x,
                                             ydata,
                                             err,
                                             color=color,
                                             label='data')

        model = biggles.Curve(x, y, label='model')

        plt += biggles.Polygon([0, 8, 4], [0, 0, 30],
                               color='grey20',
                               label='triangle')

        plt += [model, pts, errpts]

        plt += biggles.Point(4,
                             4,
                             type='filled circle',
                             color='cyan',
                             label='other')

        # Go from light blue to intense red.
        np = 30
        xp = linspace(0.5, 4, np)
        yp = 20 + 5 * xp.copy()
        minColor = [0.6, 0.9, 1.0]
        maxColor = [1.0, 0.2, 0.2]

        colors = numpy.zeros((np, 3))
        colors[:, 0] = numpy.interp(xp, xp,
                                    linspace(minColor[0], maxColor[0], np))
        colors[:, 1] = numpy.interp(xp, xp,
                                    linspace(minColor[1], maxColor[1], np))
        colors[:, 2] = numpy.interp(xp, xp,
                                    linspace(minColor[2], maxColor[2], np))

        plt += biggles.ColoredPoints(
            xp,
            yp,
            colors,
            type='cross',
            size=1,
            label='grad',
        )

        plt += biggles.LineX(5, color='green', label='lineY')
        plt += biggles.LineY(5, color='magenta', type='dashed', label='lineX')

        plt += biggles.Slope(-3, (0, 40), color='Hot Pink', label='slope')

        plt += biggles.DataBox([5.5, 70], [6.5, 80],
                               color='Dodger Blue',
                               label='box')

        # label doesn't work, nor does ellipses.  fundamental perhaps
        #plt += Circle(6.0, 75.0, 1,  color='yellow', label='circle')

        # not even sure how DataArc works
        #plt += DataArc(6.0, 75.0, 1,  color='yellow', label='circle')

        _write_example('labels', plt)
Exemple #26
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
Exemple #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
                                    Numeric.array(hadgroup_err) /
                                    center_of_groups,
                                    color=color))
    p.add(biggles.LineY(1., type="longdashed"))
    return tmp


q = biggles.FramedPlot()
q_one = addtogroupsplot(q, cs_oldhadronalloldgam, -0.15, "black",
                        "filled circle")
q_one.label = "Old hadron cuts, Gamgam cut at 0.9 eBeam"
q_two = addtogroupsplot(q, cs_oldhadronall, 0., "red", "filled square")
q_two.label = "Old hadron cuts, Gamgam cut at 0.7 eBeam"
q_three = addtogroupsplot(q, cross_section, 0.15, "blue", "filled diamond")
q_three.label = "New hadron cuts, Gamgam cut at 0.7 eBeam"
q.add(biggles.PlotKey(0.1, 0.25, [q_one, q_two, q_three]))
q.yrange = 0.92, 1.06
q.xrange = 0.5, 9.5
q.x1.ticks = range(1, 10)
q.x1.subticks_size = 0
q.x2.ticks_size = 0
q.x2.subticks_size = 0
q.ylabel = "Normalized hadronic cross-section"
q.xlabel = "Continuum running period"
q.aspect_ratio = 8.5 / 11. / 1.5
# q.show()
q.write_eps("ptatalk/prepforpta4.eps")

r = biggles.FramedPlot()
r_one = addtogroupsplot(r, cs_oldhadronalloldgam, -0.15, "black",
                        "filled circle")