예제 #1
0
def plot_autocorr(trials, window=100, show=False, **kw):
    import biggles
    import emcee

    arr = biggles.FramedArray(trials.shape[1], 1)
    arr.uniform_limits = True

    func = emcee.autocorr.function(trials)
    tau2 = emcee.autocorr.integrated_time(trials, window=window)

    xvals = numpy.arange(func.shape[0])
    zc = biggles.Curve([0, func.shape[0] - 1], [0, 0])

    for i in xrange(trials.shape[1]):
        pts = biggles.Curve(xvals, func[:, i], color='blue')

        lab = biggles.PlotLabel(0.9,
                                0.9,
                                r'$%s tau\times 2: %s$' % (i, tau2[i]),
                                halign='right')
        arr[i, 0].add(pts, zc, lab)

    if show:
        arr.show(**kw)

    return arr
예제 #2
0
def plot_stats(stats, name=""):
    ''' 
    Plots the population's average and best fitness. 
    Lisa Meeden added a name parameter for handling multiple visualizations
    in co-evolution.
    '''
    if has_biggles:
        generation = [i for i in xrange(len(stats[0]))]

        fitness = [fit for fit in stats[0]]
        avg_pop = [avg for avg in stats[1]]

        plot = biggles.FramedPlot()
        plot.title = "Population's average and best fitness"
        plot.xlabel = r"Generations"
        plot.ylabel = r"Fitness"

        plot.add(biggles.Curve(generation, fitness, color="red"))
        plot.add(biggles.Curve(generation, avg_pop, color="blue"))

        #plot.show() # X11
        plot.write_img(600, 300, name+'avg_fitness.svg')
        # width and height doesn't seem to affect the output! 
    else:
        print 'You dot not have the Biggles package.'
def plot_species(species_log, name=""):
    ''' 
    Visualizes speciation throughout evolution. 
    Lisa Meeden added a name parameter for handling multiple visualizations
    in co-evolution.
    '''
    plot = biggles.FramedPlot()
    plot.title = "Speciation"
    plot.ylabel = r"Size per Species"
    plot.xlabel = r"Generations"
    generation = [i for i in range(len(species_log))]

    species = []
    curves = []

    for gen in range(len(generation)):
        for j in range(len(species_log), 0, -1):
            try:
                species.append(species_log[-j][gen] + sum(species_log[-j][:gen]))
            except IndexError:
                species.append(sum(species_log[-j][:gen]))
        curves.append(species)
        species = []

    s1 = biggles.Curve(generation, curves[0])

    plot.add(s1)
    plot.add(biggles.FillBetween(generation, [0]*len(generation), generation, curves[0], color=random.randint(0,90000)))

    for i in range(1, len(curves)):
        c = biggles.Curve(generation, curves[i])
        plot.add(c)
        plot.add(biggles.FillBetween(generation, curves[i-1], generation, curves[i], color=random.randint(0,90000)))
    plot.write_img(1024, 800, name+'speciation.svg')
예제 #4
0
    def test_example6(self):
        x = numpy.arange(1 * numpy.pi, 3 * numpy.pi, numpy.pi / 30)
        c = numpy.cos(x)
        s = numpy.sin(x)

        p = biggles.FramedPlot()
        p.aspect_ratio = 1
        p.frame1.draw_grid = 1
        p.frame1.tickdir = 1

        p.x1.label = "bottom"
        p.x1.subticks = 1

        p.y1.label = "left"
        p.y1.draw_spine = 0

        p.x2.label = "top"
        p.x2.range = 10, 1000
        p.x2.log = 1

        p.y2.label = "right"
        p.y2.draw_ticks = 0
        p.y2.ticklabels = ["-1", "-1/2", "0", "1/2", "1"]

        p.add(biggles.Curve(x, c, type='dash'))
        p.add(biggles.Curve(x, s))

        _write_example(6, p)
def plot_stats_biggles(stats, candidate_util, dest_dir='.'):
    if HAS_BIGGLES:
        generation = [i for i in range(len(stats[0]))]

        fitness = [candidate_util.get_candidate_fitness(c) \
                    if candidate_util.get_candidate_fitness(c) is not None \
                    else 0 for c in stats[0]]
        avg_pop = [avg if avg is not None else 0 for avg in stats[1]]

        plot = biggles.FramedPlot()
        plot.title = "Population's average and best fitness"
        plot.xlabel = r"Generations"
        plot.ylabel = r"Fitness"

        plot.add(biggles.Curve(generation, fitness, color="red"))
        plot.add(biggles.Curve(generation, avg_pop, color="blue"))

        # plot.show() # X11
        try:
            plot.write_img(1300, 800, os.path.join(dest_dir,
                                                   'avg_fitness.png'))
        except Exception:
            print(traceback.format_exc())
        # width and height doesn't seem to affect the output!
    else:
        print('You do not have the Biggles package.')
예제 #6
0
    def test_ColorSpectrum( self ):
        """ColorSpectrum test"""
        try:
            import biskit.tools as T
            import biggles as B
        except:
            B = 0
        
        c_grey    = ColorSpectrum( 'grey', 0, 100 )
        c_sausage = ColorSpectrum( 'sausage', 0, 100 )
        c_plasma  = ColorSpectrum( 'plasma', 0, 100 )
        c_plasma2 = ColorSpectrum( 'plasma2', 0, 100 )

        if B:
            self.p = B.FramedPlot()

##        old_spectrum = T.colorSpectrum( 100 )
        
        self.result = []
        for i in range( -1, 100 ):

            x = (i, i+1 )

            if B:
                self.result += [ c_grey.color( i ) ]
    
                self.p.add( B.FillBelow( x, (1., 1.),
                                         color = c_grey.color( i ) ) )
                
                self.p.add( B.FillBelow( x, (0.75, 0.75),
                                         color = c_sausage.color( i ) ) )
                self.p.add( B.FillBelow( x, (0.5, 0.5),
                                         color = c_plasma.color( i ) ) )
                self.p.add( B.FillBelow( x, (0.25, 0.25),
                                         color = c_plasma2.color( i ) ) )

##                self.p.add( B.FillBelow( x, (0., 0.),
##                                      color = old_spectrum[i] ))

        if B:
            self.p.add( B.Curve( (0,100), (1.,1.)) )
            self.p.add( B.Curve( (0,100), (.75,.75)) )
            self.p.add( B.Curve( (0,100), (.5,.5) ))
            self.p.add( B.Curve( (0,100), (0.25, 0.25)) )
            self.p.add( B.Curve( (0,100), (0.0, 0.0)) )
    
            self.p.add( B.PlotLabel(  0.5 ,0.9, 'grey') )
            self.p.add( B.PlotLabel(  0.5 ,0.65, 'sausage') )
            self.p.add( B.PlotLabel(  0.5 ,0.4, 'plasma') )
            self.p.add( B.PlotLabel(  0.5 ,0.15, 'plasma2') )

        if (self.local or self.VERBOSITY > 2) and B:
            self.p.show()
            
        ##self.assertEqual(self.result, self.EXPECTED)
        ## tolerate two differences to account for Python 3 result
        a = N0.array(self.result)
        b = N0.array(self.EXPECTED)
        self.assert_(N0.count_nonzero(a-b)<3)
예제 #7
0
def draw(t, in_, out):

    import biggles

    p = biggles.FramedPlot()
    p.add(biggles.Curve(t, out, color='blue'))
    p.add(biggles.Curve(t, in_, color='red'))
    p.add(biggles.Slope(0, color='green'))
    p.show()
예제 #8
0
def logPlot(data, lenZeros, colorDic, ref=None, ave=None):
    """
    log(fraction of solutions) vs. fraction of native contacts (sorted)
    data - 3D matrix (rec * lig * soln)
    lenZeros - integer, the lowest number of zeros on any rec-lig pair
    ref - tuple, position of reference
    -> list of plot objects
    """
    ## data dimensions
    rec, lig, soln = shape(data)

    ## y data range (removing all zeros region)
    y = arange(soln - (lenZeros), 0, -1, 'f') / soln

    plots = []

    if type(colorDic) == str:
        colorDic = {'a': colorDic}

    ## collect all
    for r in range(rec):
        for l in range(lig):
            dt = data[r][l][-(soln - lenZeros):]
            if ave:
                dt = mathUtils.runningAverage(dt, ave, 1)
            plots += [biggles.Curve(dt, y, color=colorDic['a'])]

    if ref:
        nr = ref[0] - 1
        nl = ref[1] - 1
        ## contains x-ray rec
        for l in range(lig):
            dt = data[nr][l][-(soln - lenZeros):]
            if ave:
                dt = mathUtils.runningAverage(dt, ave, 1)
            plots += [biggles.Curve(dt, y, color=colorDic['r'])]

        ## contains x-ray lig
        for r in range(rec):
            dt = data[r][nl][-(soln - lenZeros):]
            if ave:
                dt = mathUtils.runningAverage(dt, ave, 1)
            plots += [biggles.Curve(dt, y, color=colorDic['l'])]

        ## add ref in other color
        dt = data[nr][nl][-(soln - lenZeros):]
        if ave:
            dt = mathUtils.runningAverage(dt, ave, 1)
        plots += [biggles.Curve(dt, y, color=colorDic['x'], width=4)]

        ## labels
        plots += [biggles.PlotLabel(.8, .95, 'Xray rec', color=colorDic['r'])]
        plots += [biggles.PlotLabel(.8, .90, 'Xray lig', color=colorDic['l'])]
        plots += [biggles.PlotLabel(.8, .85, 'Xray', color=colorDic['x'])]

    return plots
예제 #9
0
def main(argv):
    (t, d, v, a, j) = accel_plot(prt_berth_advance_trajectory)
    p = biggles.FramedPlot()
    p.title = 'Acceleration Profile'
    p.xlabel = 'Time'
    p.add(biggles.Curve(t, d, color='red'))
    p.add(biggles.Curve(t, v, color='yellow'))
    p.add(biggles.Curve(t, a, color='blue'))
    p.add(biggles.Curve(t, j, color='green'))
    p.show()
예제 #10
0
    def test_ColorSpectrum( self ):
        """ColorSpectrum test"""
        try:
            import biggles as B
        except:
            B = 0
        
        c_grey    = ColorSpectrum( 'grey', 0, 100 )
        c_sausage = ColorSpectrum( 'sausage', 0, 100 )
        c_plasma  = ColorSpectrum( 'plasma', 0, 100 )
        c_plasma2 = ColorSpectrum( 'plasma2', 0, 100 )

        if B:
            self.p = B.FramedPlot()

##         old_spectrum = tools.colorSpectrum( 100 )
        
        self.result = []
        for i in range( -1, 100 ):

            x = (i, i+1 )

            if B:
                self.result += [ c_grey.color( i ) ]
    
                self.p.add( B.FillBelow( x, (1., 1.),
                                         color = c_grey.color( i ) ) )
                
                self.p.add( B.FillBelow( x, (0.75, 0.75),
                                         color = c_sausage.color( i ) ) )
                self.p.add( B.FillBelow( x, (0.5, 0.5),
                                         color = c_plasma.color( i ) ) )
                self.p.add( B.FillBelow( x, (0.25, 0.25),
                                         color = c_plasma2.color( i ) ) )

##             self.p.add( B.FillBelow( x, (0., 0.),
##                                   color = old_spectrum[i] ))

        if B:
            self.p.add( B.Curve( (0,100), (1.,1.)) )
            self.p.add( B.Curve( (0,100), (.75,.75)) )
            self.p.add( B.Curve( (0,100), (.5,.5) ))
            self.p.add( B.Curve( (0,100), (0.25, 0.25)) )
            self.p.add( B.Curve( (0,100), (0.0, 0.0)) )
    
            self.p.add( B.PlotLabel(  0.5 ,0.9, 'grey') )
            self.p.add( B.PlotLabel(  0.5 ,0.65, 'sausage') )
            self.p.add( B.PlotLabel(  0.5 ,0.4, 'plasma') )
            self.p.add( B.PlotLabel(  0.5 ,0.15, 'plasma2') )

        if (self.local or self.VERBOSITY > 2) and B:
            self.p.show()
            
        self.assertEqual(self.result, self.EXPECTED)
예제 #11
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)
예제 #12
0
    def _add_curve(self):

        plt = self.plt
        indices = self.indices
        if indices is None:
            plt.add(biggles.Curve(self.x, self.y, **self))
        else:
            x = self.x
            y = self.y
            for key, grps in itertools.groupby(enumerate(indices),
                                               lambda tup: tup[0] - tup[1]):
                wgrp = map(operator.itemgetter(1), grps)
                plt.add(biggles.Curve(x[wgrp], y[wgrp], **self))
예제 #13
0
    def test_example1(self):
        x = numpy.arange(0, 3 * numpy.pi, numpy.pi / 30)
        c = numpy.cos(x)
        s = numpy.sin(x)

        p = biggles.FramedPlot()
        p.title = "title"
        p.xlabel = r"$x$"
        p.ylabel = r"$\Theta$"

        p.add(biggles.FillBetween(x, c, x, s))
        p.add(biggles.Curve(x, c, color="red"))
        p.add(biggles.Curve(x, s, color="blue"))

        _write_example(1, p)
예제 #14
0
def main():
  ddin= genSignal()
  x = [i for i in range(len(ddin))]

  dv = Delay_Var()
  dv.convert()

  tbr = dv.tb(ddin, 4)
  sim = Simulation(tbr)
  sim.run()

  dv.ddout.append(0)
  p = biggles.FramedPlot()
  p.add( biggles.Curve(x, dv.ddout, color="red") )
  p.add( biggles.Curve(x, ddin, color="blue") )
  p.show()
예제 #15
0
def make_points(shears, biases, bias_errors, color, res):
    pts = biggles.Points(shears,
                         biases,
                         type='filled diamond',
                         color=color,
                         size=2.5)
    ptsc = biggles.Points(shears,
                          biases,
                          type='diamond',
                          color='black',
                          size=2.5)
    ptserr = biggles.SymmetricErrorBarsY(simshears,
                                         simbiases,
                                         simerrs,
                                         color=simcolor)

    if res is not None:
        xp = numpy.linspace(0, shears[-1])
        fitc = biggles.Curve(
            xp,
            res['m'] + res['alpha'] / units * xp**2,
            color=color,
        )

        fitc.label = r'$%.1f \gamma^2$' % res['alpha']
    else:
        fitc = None

    return pts, ptsc, ptserr, fitc
예제 #16
0
def main():
    # import pycat
    # model = pycat.Zilany2009
    # pars = { 'powerlaw_implnt':'approx',
    #          'with_ffGn':False }
    # fs = 100e3

    import cochlea
    model = cochlea.Sumner2003
    pars = {}
    fs = 100e3

    # import cochlea
    # model = cochlea.Holmberg2007
    # fs = 48000

    import traveling_waves as tw
    cf = tw.real_freq_map[68]

    # print _run_model( (model, cf, 48000, 3000, 50, {}) )
    # exit()

    rates = calc_isointensity_curves(model, cf, fs=fs, **pars)
    print rates

    import biggles
    p = biggles.FramedPlot()
    p.xlog = 1
    for dbspl in np.unique(rates['dbspl']):
        selected = rates[rates['dbspl'] == dbspl]
        p.add(biggles.Curve(selected['freq'], selected['hsr_rate']))

    p.show()
예제 #17
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 )
예제 #18
0
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)
    # diff plot
    x = range(1, soln - (zeros - 1))
    x.reverse()
    diff = (sorted_data - sorted_ref)[-(soln - zeros):]
    diff_p = biggles.Curve(x, cumsum(diff), color=color)
    # rank plot
    x = arange(1, soln + 1, 1, 'f') / soln
    rank_p = biggles.Curve(x, maxVal(data), color=color)
    return log_p, diff_p, rank_p
예제 #19
0
def main10():
    amp = 16385
    Tao = 10E-6
    Ts = 1E-8
    m1 = 297
    m2 = 0.297  #0.0515
    noi = 0

    t, s = Signal(Ts, Tao, amp=amp)
    snoise = noise(s, noi)

    spz = poleZero(snoise, Tao, Ts)
    rn, sn = trapez(spz, m1, m2)
    max_ = PHA(sn)

    print np.floor(sn[0:100])

    print max_

    import biggles
    p = biggles.FramedPlot()
    p.add(biggles.Curve(np.arange(sn.shape[0])[20:70], sn[20:70],
                        color='blue'))
    p.add(biggles.Slope(0, color='green'))
    p.show()
예제 #20
0
    def plotHistogram( self, *name, **arg ):
        """
        @param bins: number of bins (10)
        @type  bins: int
        @param ynormalize: normalize histograms to area 1.0 (False)
        @type  ynormalize: bool
        @param xnormalize: adapt bin range to min and max of all profiles (True)
        @type  xnormalize: bool
        @param xrange: min and max of bin range (None)
        @type  xrange: (float, float)
        @param steps: draw histogram steps (True)
        @type  steps: bool
        """
        if not biggles:
            raise ImportError, 'module biggles could not be imported'

        plot = biggles.FramedArray( len(name),1 )

        if not 'size' in arg:
            arg['size'] = 1
        
        bins = arg.get('bins', 10)
        hist = arg.get('ynormalize', False)
        steps= arg.get('steps', 1)
        histrange= arg.get('xrange', None)
        autorange= arg.get('xnormalize', histrange is None)
        
        xkey = arg.get('xkey', None)
        if xkey:
            plot.xlabel = xkey

        if autorange:
            v = []
            for keys in name:
                if not type(keys) is tuple:
                    keys = ( keys, )
                for key in keys:
                    v += list(self[key])
            histrange = ( min( v ), max( v ) )
            
        for i, keys in enumerate(name):
            
            if not type(keys) is tuple:
                keys = ( keys, )
                
            for j, key in enumerate(keys):

                h = density( self[key], nBins=bins, steps=steps, hist=hist,
                             range=histrange )
                x = h[:,0]
                y = h[:,1]
                
                colors = [0] + T.colorSpectrum( len(keys) , '00FF00', 'FF00FF')

                plot[i,0].add( biggles.Curve( x, y, color=colors[j], **arg ) )
    
                plot[i,0].add( biggles.PlotLabel( 0.7, 0.95-j*0.1, key,
                                                  color=colors[j] ) )

        return plot
예제 #21
0
def plot_voltages(fs, vecs):
    import biggles

    all_values = np.concatenate( vecs )
    hi = all_values.max()
    lo = all_values.min()

    plot = biggles.Table(len(vecs), 1)
    plot.cellpadding = 0
    plot.cellspacing = 0
    for i,vec in enumerate(vecs):
        p = biggles.Plot()
        p.add( biggles.Curve(wv.t(fs, vec), vec) )
        p.yrange = (lo, hi)
        plot[i,0] = p


    p.add( biggles.LineX(0) )
    p.add( biggles.Label(0, (hi+lo)/2, "%.2f mV" % (hi-lo), halign='left') )

    p.add( biggles.LineY(lo) )
    p.add( biggles.Label((len(vec)/fs/2), lo, "%.1f ms" % (1000*len(vec)/fs), valign='bottom') )


    return plot
예제 #22
0
def main():
    pulse = GenPulse()
    pulse.setPmtComps()
    pulse.calcConstants()
    pulse.initLists()
    #pulse.calcPulseExp()
    pulse.calcPulseTri()
    pulse.calcPmtOut()
    time, out = pulse.calcADCOut(3)
    #pulse.differential()

    import copy
    tmp = copy.copy(pulse.pulseOut)

    #pulse.integra()
    pulse.amplifier(1.0 / 256.0)
    pulse.integra()
    tw = twc.TwoCompl(16)
    #twl = tw.toFile(pulse.pulseOut, "vector.tv")

    plt = biggles.FramedPlot()

    plt.add(biggles.Curve(time, pulse.expPulse, color="black"))

    plt.show()
예제 #23
0
파일: linear.py 프로젝트: esheldon/dsfit
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()
예제 #24
0
def plotRanking(data, colorDic, ref=(1, 1)):
    """
    log(fraction of solutions) vs. fraction of native contacts (sorted)
    data - 3D matrix (rec * lig * soln)
    ref - tuple, position of reference
    -> list of plot objects
    """
    ## data dimensions
    rec, lig, soln = shape(data)

    ## y data range (removing all zeros region)
    x = arange(1, soln + 1, 1, 'f') / soln
    area = zeros((rec, lig), 'f')
    plots = []

    ## collect all
    ref_area = getArea(x, (maxVal(data[ref[0] - 1][ref[1] - 1])))
    for r in range(rec):
        for l in range(lig):
            d = maxVal(data[r][l])
            area[r][l] = getArea(x, d) - ref_area
            plots += [biggles.Curve(x, d, color=colorDic['a'])]

    if ref:
        nr = ref[0] - 1
        nl = ref[1] - 1
        ## contains x-ray rec
        for l in range(lig):
            plots += [
                biggles.Curve(x, maxVal(data[nr][l]), color=colorDic['r'])
            ]

        ## contains x-ray lig
        for r in range(rec):
            plots += [
                biggles.Curve(x, maxVal(data[r][nl]), color=colorDic['l'])
            ]

        ## add ref in other color
        plots += [biggles.Curve(x, maxVal(data[nr][nl]), color=colorDic['x'])]

        ## labels
        plots += [biggles.PlotLabel(.8, .95, 'Xray rec', color=colorDic['r'])]
        plots += [biggles.PlotLabel(.8, .90, 'Xray lig', color=colorDic['l'])]
        plots += [biggles.PlotLabel(.8, .85, 'Xray', color=colorDic['x'])]

    return plots, area
def plot_species_biggles(species_log, dest_dir='.'):
    if HAS_BIGGLES:
        plot = biggles.FramedPlot()
        plot.title = "Speciation"
        plot.ylabel = r"Size per Species"
        plot.xlabel = r"Generations"
        generation = [i for i in range(len(species_log))]

        species = []
        curves = []

        for gen in range(len(generation)):
            for j in range(len(species_log), 0, -1):
                try:
                    species.append(species_log[-j][gen] +
                                   sum(species_log[-j][:gen]))
                except IndexError:
                    species.append(sum(species_log[-j][:gen]))
            curves.append(species)
            species = []

        new_curve = biggles.Curve(generation, curves[0])
        plot.add(new_curve)
        plot.add(
            biggles.FillBetween(generation, [0] * len(generation),
                                generation,
                                curves[0],
                                color=random.randint(0, 90000)))

        for i in range(1, len(curves)):
            curve = biggles.Curve(generation, curves[i])
            plot.add(curve)
            plot.add(
                biggles.FillBetween(generation,
                                    curves[i - 1],
                                    generation,
                                    curves[i],
                                    color=random.randint(0, 90000)))

        try:
            plot.write_img(1300, 800, os.path.join(dest_dir, 'speciation.png'))
        except Exception:
            print(traceback.format_exc())

    else:
        print('You do not have the Biggles package.')
예제 #26
0
def main():

    disc = Delay()
    disc.convert()
    t, ddin = disc.genSignal(100, 10)

    tbr = disc.tb(ddin)
    sim = Simulation(tbr)
    sim.run()

    p = biggles.FramedPlot()
    p.yrange = -5, 5

    disc.ddout.append(0)
    p.add(biggles.Curve(t, ddin, color="blue"))
    p.add(biggles.Curve(t, disc.ddout, color="red"))
    p.show()
예제 #27
0
def pixfind(angdis, res, pixnum):
    #find the pixels around a pixel that are a given angular distance away.  To start, simply returns 10 pixels
    from math import pi, cos, sin
    b = 0
    try:
        import biggles
    except:
        b = 1

    (eta, lam) = pix2etalam(res, pixnum)
    out = []
    etal = []
    laml = []
    count = 0
    r = int(160. * angdis * res / 256.)
    for i in range(0, r / 2):
        ang = i * 2. * pi / float(r)
        eta1 = eta + angdis * cos(ang)
        etal.append(eta1)
        lam1 = lam + angdis * sin(ang)
        laml.append(lam1)
        pix = ang2pix(res, lam1, eta1)
        if count == 0:
            out.append(pix)
            count += 1
        else:
            if pix != out[count - 1]:
                out.append(pix)
                count += 1
            else:
                print('too many divisions')
                print(pix)
    peta = []
    plam = []
    for i in range(0, len(out)):
        (eta1, lam1) = pix2etalam(res, out[i])
        peta.append(eta1)
        plam.append(lam1)
    plot = biggles.FramedPlot()
    crv1 = biggles.Curve(laml, etal)
    crv2 = biggles.Curve(plam, peta)
    plot.add(crv1)
    plot.add(crv2)

    plot.show()
    return out
예제 #28
0
def plot(complex_lst):
    ## plot the cluster rmsd dist.
    plot = biggles.FramedPlot()
    inset = biggles.FramedPlot()

    ## plot title
    plot.title = '/'.join(string.split(absfile(options['o']), '/')[-5:-1])

    ## customize plot appearence
    plot.x1.label = 'cluster'
    plot.y2.label = 'size'
    plot.y1.label = 'rmsd'

    plot.x2.draw_ticks = 0
    plot.y2.draw_ticks = 0

    inset.frame.draw_ticks = 0
    inset.x1.draw_ticklabels = 0
    inset.y1.draw_ticklabels = 0
    inset.y2.draw_ticklabels = 1
    inset.y2.draw_ticks = 1
    inset.y2.ticks_style['color'] = 'red'

    ## get cluter and rmsd lists
    clst_list = []
    rms_list = []
    for compl in complex_lst:
        clst_list += [compl.info['hex_clst']]
        rms_list += [compl.info['rms']]

    ## get average, max, min and size of cluster
    data = []
    clst_range = range(1, max(clst_list) + 1)
    for clst in clst_range:
        rms = compress(equal(clst_list, clst), rms_list)
        data += [[average(rms), max(rms), min(rms), len(rms)]]
    data = transpose(data)

    ## Inset
    inset.add(biggles.Curve(clst_range, data[3], color='red'))

    ## Plot
    plot.add(biggles.ErrorBarsY(clst_range, data[1], data[2]))
    plot.add(biggles.Points(clst_range, data[0], type='cross', size=1))
    plot.add(biggles.Inset((0.0, 0.0), (1.0, 1.0), inset))
    plot.add(biggles.LineY(10, type='dot'))

    ## add label with info about 'good' solutions (average rmsd < 10A)
    good = []
    for clst in clst_range:
        if data[0][clst - 1] < 10:
            good += [clst]
    plot.add(biggles.PlotLabel(0.5, 0.98, 'Solutions with rmsd < 10A', size=1))
    plot.add(biggles.PlotLabel(0.5, 0.95, str(good), size=1))

    ## plot and save
    plot.show()
    plot.write_eps(string.split(options['o'], '.')[0] + '.eps')
예제 #29
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
예제 #30
0
def plot_species(species_log):
    ''' Visualizes speciation throughout evolution. '''
    if has_biggles:
        plot = biggles.FramedPlot()
        plot.title = "Speciation"
        plot.ylabel = r"Size per Species"
        plot.xlabel = r"Generations"
        generation = [i for i in xrange(len(species_log))]

        species = []
        curves = []

        for gen in xrange(len(generation)):
            for j in xrange(len(species_log), 0, -1):
                try:
                    species.append(species_log[-j][gen] +
                                   sum(species_log[-j][:gen]))
                except IndexError:
                    species.append(sum(species_log[-j][:gen]))
            curves.append(species)
            species = []

        s1 = biggles.Curve(generation, curves[0])

        plot.add(s1)
        plot.add(
            biggles.FillBetween(generation, [0] * len(generation),
                                generation,
                                curves[0],
                                color=random.randint(0, 90000)))

        for i in range(1, len(curves)):
            c = biggles.Curve(generation, curves[i])
            plot.add(c)
            plot.add(
                biggles.FillBetween(generation,
                                    curves[i - 1],
                                    generation,
                                    curves[i],
                                    color=random.randint(0, 90000)))

        plot.write_img(1024, 800, 'speciation.svg')

    else:
        print('You dot not have the Biggles package.')