コード例 #1
0
ファイル: setplot.py プロジェクト: clawpack/geoclaw_1d
    def fixticks(current_data):
        from pylab import ticklabel_format, plot,grid,ones,sqrt, \
            legend,title,ylabel,text
        ticklabel_format(useOffset=False)

        # to plot max elevation over entire computation:
        #if xmax is not None:
        #    plot(xmax, etamax, 'r')

        #grid(True)
        hl = 3200.
        hr = 200.
        greens = (hl / hr)**(0.25)
        print('greens = ', greens)
        #plot(current_data.x, greens*ones(current_data.x.shape),'g--')
        plot(xlimits, [greens, greens], 'g--', label='$C_g$, Greens Law')
        ctrans = 2 * sqrt(hl) / (sqrt(hl) + sqrt(hr))
        crefl = (sqrt(hl) - sqrt(hr)) / (sqrt(hl) + sqrt(hr))
        print('ctrans = ', ctrans)
        plot(xlimits, [ctrans, ctrans],
             'r--',
             label='$C_T$, Transmission coefficient')
        legend(loc='upper left')
        title('')
        ylabel('meters', fontsize=14)

        if current_data.frameno == 0:
            text(-80, -0.4, '$\longrightarrow$', fontsize=20)
            text(-80, -0.6, 'Incident')
        h = current_data.q[0, :]
        mx2 = int(round(len(h) / 2.))
        etamax2 = (h[:mx2] - hl).max()
        print('mx2 = %i, etamax2 = %g' % (mx2, etamax2))
コード例 #2
0
def plot_xy():
    plt.plot(x, y, 'bo')
    plt.ticklabel_format(useOffset=False)
    plt.xlabel('JD')
    plt.ylabel('Number of files')
    plt.title('Number of files with search string *xx*HH*uvc')
    plt.show()
コード例 #3
0
def plotCumulativeRegretsFromDump(names, envName, median, quantile1, quantile2,
                                  times, timeHorizon):
    nbFigure = pl.gcf().number + 1
    pl.figure(nbFigure)
    textfile = "results/Regret-"
    colors = [
        'black', 'blue', 'gray', 'green', 'red'
    ]  # ['black', 'purple', 'blue','cyan','yellow', 'orange', 'red', 'chocolate']

    style = ['o', 'v', 's', 'd', '<']
    for i in range(len(median)):
        pl.plot(times,
                median[i],
                style[i],
                label=names[i],
                color=colors[i % len(colors)],
                linewidth=2.0,
                linestyle='--',
                markevery=0.05)
        pl.plot(times,
                quantile1[i],
                color=colors[i % len(colors)],
                linestyle=':',
                linewidth=0.7)
        pl.plot(times,
                quantile2[i],
                color=colors[i % len(colors)],
                linestyle=':',
                linewidth=0.7)
        textfile += names[i] + "-"
        print(names[i], ' has regret ', median[i][-1], ' after ', timeHorizon,
              ' time steps with quantiles ', quantile1[i][-1], ' and ',
              quantile2[i][-1])

    textfile += "_" + str(timeHorizon) + "_" + envName
    pl.legend(loc=2)
    pl.xlabel("Time steps", fontsize=13, fontname="Arial")
    pl.ylabel("Regret", fontsize=13, fontname="Arial")
    #pl.xticks(times)
    pl.ticklabel_format(axis='both',
                        useMathText=True,
                        useOffset=True,
                        style='sci',
                        scilimits=(0, 0))
    pl.ylim(0)
    pl.savefig(textfile + '.png')
    pl.savefig(textfile + '.pdf')
    pl.xscale('log')
    pl.savefig(textfile + '_xlog.png')
    pl.savefig(textfile + '_xlog.pdf')
    pl.ylim(100)
    if (timeHorizon > 1000):
        pl.xlim(1000, timeHorizon)
    pl.xscale('linear')
    pl.yscale('log')
    pl.savefig(textfile + '_ylog.png')
    pl.savefig(textfile + '_ylog.pdf')
    pl.xscale('log')
    pl.savefig(textfile + '_loglog.png')
    pl.savefig(textfile + '_loglog.pdf')
コード例 #4
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, savefig
     title_hours(current_data)
     ticklabel_format(format='plain', useOffset=False)
     xticks(rotation=20)
     a = gca()
     a.set_aspect(1. / cos(46.349 * pi / 180.))
コード例 #5
0
def evaluate_models_on_testing(x, y, models):
    """
    For each regression model, compute the RMSE for this model and plot the
    test data along with the model’s estimation.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        RMSE of your model evaluated on the given data points. 

    Args:
        x: an 1-d pylab array with length N, representing the x-coordinates of
            the N sample points
        y: an 1-d pylab array with length N, representing the y-coordinates of
            the N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a pylab array storing the coefficients of
            a polynomial.

    Returns:
        None
    """
    for model in models:
        modeldata = pylab.polyval(model, x)

        pylab.plot(x, y, 'bo', label='Historical Data')
        pylab.plot(x, modeldata, 'r-', label='Prediction')
        pylab.xlabel('Year')
        pylab.ticklabel_format(useOffset=False)
        pylab.ylabel('Temp')

        pylab.show()
コード例 #6
0
ファイル: analyzeResults.py プロジェクト: brownhep/TCT
def plotResults(dataTCT, current, corr_curr):
    i = 0
    diff = []
    while i < len(current):
        diff.append(corr_curr[i] - current[i])
        i += 1
    fig = pylab.figure(1, (8, 7))
    pylab.plot(dataTCT.xdata[dataTCT.initPoint:dataTCT.endPoint - 700],
               current[0:len(current) - 700],
               "r",
               label="Current")
    pylab.plot(dataTCT.xdata[dataTCT.initPoint:dataTCT.endPoint - 700],
               corr_curr[0:len(corr_curr) - 700],
               "k",
               label="Corrected Current")
    pylab.plot(dataTCT.xdata[dataTCT.initPoint:dataTCT.endPoint - 700],
               diff[0:len(diff) - 700],
               "b",
               label="Difference")
    pylab.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
    pylab.legend(loc=0)
    pylab.grid(True)
    pylab.xlabel("Time(s)")
    pylab.ylabel("Voltage(V) ")
    pylab.tight_layout()
    pylab.savefig(dataTCT.filename.replace(".bin", ".png"))
    pylab.close()
コード例 #7
0
ファイル: analyzeResults.py プロジェクト: brownhep/TCT
def plotTotResults(
    filename_tot,
    xdata_tot,
    current_tot,
    init_tot,
    end_tot,
):
    fig = pylab.figure(1, (8, 7))
    n = 0
    voltage = []
    while n <= 100:
        voltage.append(n * 10)
        n += 1
    i = 1
    while i < len(current_tot):
        print str(init_tot[i] - end_tot[i])
        print len(current_tot[i])
        pylab.plot(xdata_tot[i][init_tot[i]:end_tot[i] - 800],
                   current_tot[i][0:len(current_tot[i]) - 800],
                   label=str(voltage[i]) + " V")
        i += 10
    pylab.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
    pylab.legend(loc=0)
    pylab.grid(True)
    pylab.xlabel("Time")
    pylab.ylabel("Current")
    pylab.tight_layout()
    pylab.savefig("CurrentCombine.png")
    pylab.close()
コード例 #8
0
def plotdata( xdata, ydata, cont ):
  pylab.plot( xdata, ydata, "-", label = "waveform" + str( cont ) )
  pylab.ticklabel_format( style = 'sci', scilimits = ( 0, 0 ) )
  pylab.xlabel( "Time [s]" )
  pylab.ylabel( "Signal [V]" )
  pylab.legend( loc = 1 )
  pylab.grid()
コード例 #9
0
def cpu(*F,N=(500,5000,500)):
    '''Mostra gráfico com o consumo de tempo das funções *F, para
       entradas com tamanho variando no intervalo N=(500,5000,500).
       Um parâmetro E = g define a função que gera as entradas'''
    C = ['r','b','g','c','m','y','k','w']
    M = ['o','s','p','h','+','x','v','^']
    X = []
    Y = [[] for _ in range(len(F))]
    print('n = ',end='')
    inicio = time()
    rodada = 1
    for n in range(N[0],N[1]+1,N[2]):
        print('%s ' % rodada,end='')
        X.append(n)
        v = sample(range(0,n),n)
        for i,f in enumerate(F):
            w = deepcopy(v)
            Y[i].append(tempo(f,w))
        rodada += 1
    print('\nTempo total: %.1fs' % (time()-inicio))
    xlabel('tamanho da entrada')
    ylabel('tempo de execução (s)')
    ticklabel_format(style='sci', axis='both', scilimits=(-3,+4))
    grid(True)
    for i,f in enumerate(F):
        plot(X,Y[i],color=C[i%len(C)],marker=M[i%len(M)],label=f.__name__)
    legend(loc='upper left')
    show()
コード例 #10
0
    def fixticks(current_data):
        from pylab import ticklabel_format, plot,grid,ones,sqrt,\
             where,tight_layout,legend,nan, title
        ticklabel_format(format='plain', useOffset=False)

        # to plot max elevation over entire computation:
        if xmax is not None:
            plot(xmax, etamax, 'r', label='wave height')

        grid(True)
        hl = 3000.
        hr = 100.
        greens = (hl / hr)**(0.25)
        print('greens = ', greens)
        z = current_data.q[0, :] - current_data.q[2, :]
        z = where(z > 10, z, 10.)
        xp = mapc2p(current_data.x)
        plot(xp, (hl / z)**(0.25), 'g--', label='CG')
        ctrans = 2 * sqrt(hl) / (sqrt(hl) + sqrt(hr))
        crefl = (sqrt(hl) - sqrt(hr)) / (sqrt(hl) + sqrt(hr))
        print('ctrans = ', ctrans)
        print('crefl = ', crefl)
        hm = 1400.
        ct12 = 2 * sqrt(hl) / (sqrt(hl) +
                               sqrt(hm)) * 2 * sqrt(hm) / (sqrt(hm) + sqrt(hr))
        plot([-60e3, 0], [ct12, ct12], 'r--', label='CT1*CT2')
        ctx = 2 * sqrt(hl) / (sqrt(hl) + sqrt(z))
        plot(xp, ctx, 'b--', label='CT')
        legend(loc='upper left', fontsize=8, framealpha=1)
        #tight_layout()
        timestr = timeformat(current_data.t)
        title('Surface displacement at time %s' % timestr)
コード例 #11
0
ファイル: setplot.py プロジェクト: rjleveque/adjoint
 def aa_patches(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, yticks
     ticklabel_format(format='plain',useOffset=False)
     xticks([180, 200, 220, 240], rotation=20, fontsize = 28)
     yticks(fontsize = 28)
     a = gca()
     a.set_aspect(1./cos(41.75*pi/180.))
コード例 #12
0
def plotCumulativeRegrets(names,
                          cumulativerewards_,
                          timeHorizon,
                          testName="riverSwim",
                          semilog=False,
                          ysemilog=False):
    #print(len(cumulativerewards_[0]), len(cumulativerewards_))#[0])#print(len(cumulativerewards_[0]), cumulativerewards_[0])
    nbFigure = pl.gcf().number + 1
    pl.figure(nbFigure)
    cur_dir = os.path.abspath(os.path.curdir)
    output_path = os.path.join(cur_dir, 'results')
    textfile = output_path + "/Regret-"
    colors = [
        'black', 'blue', 'gray', 'green', 'red'
    ]  #['black', 'purple', 'blue','cyan','yellow', 'orange', 'red', 'chocolate']
    avgcum_rs = [
        np.mean(cumulativerewards_[-1], axis=0) -
        np.mean(cumulativerewards_[i], axis=0)
        for i in range(len(cumulativerewards_) - 1)
    ]
    std_cum_rs = [
        1.96 * np.std(cumulativerewards_[i], axis=0) /
        np.sqrt(len(cumulativerewards_[i]))
        for i in range(len(cumulativerewards_) - 1)
    ]
    for i in range(len(cumulativerewards_) - 1):
        pl.plot(avgcum_rs[i], label=names[i], color=colors[i % len(colors)])
        step = timeHorizon // 10
        pl.errorbar(np.arange(0, timeHorizon, step),
                    avgcum_rs[i][0:timeHorizon:step],
                    std_cum_rs[i][0:timeHorizon:step],
                    color=colors[i % len(colors)],
                    linestyle='None',
                    capsize=10)
        textfile += names[i] + "-"
        print(names[i], ' has regret ', avgcum_rs[i][-1], ' after ',
              len(avgcum_rs[i]), ' time steps with variance ',
              std_cum_rs[i][-1])
        #pl.show()
    pl.legend()
    pl.xlabel("Time steps", fontsize=13, fontname="Arial")
    pl.ylabel("Regret", fontsize=13, fontname="Arial")
    pl.ticklabel_format(axis='both',
                        useMathText=True,
                        useOffset=True,
                        style='sci',
                        scilimits=(0, 0))
    if semilog:
        pl.xscale('log')
        textfile += "_xsemilog"
    else:
        pl.xlim(0, timeHorizon)
    if ysemilog:
        pl.yscale('log')
        textfile += "_ysemilog"
        pl.ylim(100)
    else:
        pl.ylim(0)

    pl.savefig(textfile + testName + '.png')
コード例 #13
0
    def test_verify_AIS(self):
        model = oRBM(input_size=self.input_size,
                     hidden_size=self.hidden_size,
                     beta=self.beta)

        model.W.set_value(self.W)
        model.b.set_value(self.b)
        model.c.set_value(self.c)

        # Brute force
        print "Computing lnZ using brute force (i.e. summing the free energy of all posible $v$)..."
        V = theano.shared(
            value=cartesian([(0, 1)] * self.input_size, dtype=config.floatX))
        brute_force_lnZ = logsumexp(-model.free_energy(V), 0)
        f_brute_force_lnZ = theano.function([], brute_force_lnZ)

        params_bak = [param.get_value() for param in model.parameters]

        print "Approximating lnZ using AIS..."
        import time
        start = time.time()

        try:
            ais_working_dir = tempfile.mkdtemp()
            result = compute_AIS(model,
                                 M=self.nb_samples,
                                 betas=self.betas,
                                 seed=1234,
                                 ais_working_dir=ais_working_dir,
                                 force=True)
            logcummean_Z, logcumstd_Z_down, logcumstd_Z_up = result[
                'logcummean_Z'], result['logcumstd_Z_down'], result[
                    'logcumstd_Z_up']
            std_lnZ = result['std_lnZ']

            print "{0} sec".format(time.time() - start)

            import pylab as plt
            plt.gca().set_xmargin(0.1)
            plt.errorbar(range(1, self.nb_samples + 1),
                         logcummean_Z,
                         yerr=[std_lnZ, std_lnZ],
                         fmt='or')
            plt.errorbar(range(1, self.nb_samples + 1),
                         logcummean_Z,
                         yerr=[logcumstd_Z_down, logcumstd_Z_up],
                         fmt='ob')
            plt.plot([1, self.nb_samples], [f_brute_force_lnZ()] * 2, '--g')
            plt.ticklabel_format(useOffset=False, axis='y')
            plt.show()
            AIS_logZ = logcummean_Z[-1]

            assert_array_equal(params_bak[0], model.W.get_value())
            assert_array_equal(params_bak[1], model.b.get_value())
            assert_array_equal(params_bak[2], model.c.get_value())

            print np.abs(AIS_logZ - f_brute_force_lnZ())
            assert_almost_equal(AIS_logZ, f_brute_force_lnZ(), decimal=2)
        finally:
            shutil.rmtree(ais_working_dir)
コード例 #14
0
ファイル: NicePlot.py プロジェクト: j2duffy/JGF
def X1plot():
    sns.set(font_scale=1.5)

    pl.figure(figsize=(12, 6))

    pl.subplot(1, 2, 1)
    w, X = np.loadtxt("X1DZ1re.dat").T
    pl.plot(w, X)
    w, X = np.loadtxt("X1DZ1im.dat").T
    pl.plot(w, X)
    pl.xlim([0.85e-3, 1.1e-3])

    pl.xlabel(r"$\omega$")
    pl.ylabel(r"$\chi(\omega)$")

    pl.ticklabel_format(style='sci', scilimits=(0, 0))

    pl.subplot(1, 2, 2)
    w, X = np.loadtxt("X1DZ3re.dat").T
    pl.plot(w, X)
    w, X = np.loadtxt("X1DZ3im.dat").T
    pl.plot(w, X)
    pl.xlim([9.694658e-4, 9.694661e-4])

    pl.xlabel(r"$\omega$")
    pl.ylabel(r"$\chi(\omega)$")

    pl.ticklabel_format(style='sci', scilimits=(0, 0))

    pl.tight_layout()
    pl.savefig("X1.pdf")
    pl.show()
コード例 #15
0
 def plotraw(self):
     """quickly plots the raw isotope pattern (with mass defects preserved)"""
     import pylab as pl
     pl.bar(self.rawip[0], self.rawip[1], width=0.0001)
     pl.xlabel('m/z', style='italic')
     pl.ylabel('normalized intensity')
     pl.ticklabel_format(useOffset=False)
     pl.show()
コード例 #16
0
def plot_I(susceptible, infected, Title):
    pl.figure(figsize=(5,3))
    pl.plot(time, infected,label="Infected", color=(0.8666666666666667, 0.5176470588235295, 0.3215686274509804))
    pl.fill_between(time, infected, 0, alpha=0.30, color=(0.8666666666666667, 0.5176470588235295, 0.3215686274509804))
    pl.ticklabel_format(axis="y", style="sci", scilimits=(0,0))
    pl.xlabel('Time in days', fontsize=14)
    pl.ylabel('Infected individuals', fontsize=14)
    pl.title(Title)
コード例 #17
0
 def plotraw(self):
     """quickly plots the raw isotope pattern (with mass defects preserved)"""
     import pylab as pl
     pl.bar(self.rawip[0],self.rawip[1],width=0.0001)
     pl.xlabel('m/z', style='italic')
     pl.ylabel('normalized intensity')
     pl.ticklabel_format(useOffset=False)
     pl.show()
コード例 #18
0
ファイル: setplot.py プロジェクト: clawpack/csdms
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi
     plotcc(current_data)
     title_hours(current_data)
     ticklabel_format(format='plain',useOffset=False)
     xticks(rotation=20)
     a = gca()
     a.set_aspect(1./cos(41.75*pi/180.))
コード例 #19
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
    def aa(current_data):
        from pylab import ticklabel_format, xticks, gca, cos, pi, savefig

        title_hours(current_data)
        ticklabel_format(format="plain", useOffset=False)
        xticks(rotation=20)
        a = gca()
        a.set_aspect(1.0 / cos(46.349 * pi / 180.0))
コード例 #20
0
 def plotbar(self):
     """quickly plots a bar plot of the isotope bar pattern"""
     import pylab as pl
     fwhm = self.em / self.ks['res']
     pl.bar(self.barip[0], self.barip[1], width=fwhm, align='center')
     pl.xlabel('m/z', style='italic')
     pl.ylabel('normalized intensity')
     pl.ticklabel_format(useOffset=False)
     pl.show()
コード例 #21
0
 def fixup(current_data):
     import pylab
     #addgauges(current_data)
     t = current_data.t
     t = t / 3600.  # hours
     pylab.title('Surface at %4.2f hours' % t, fontsize=20)
     pylab.ticklabel_format(format='plain',useOffset=False)
     mean_lat = 19.7
     pylab.gca().set_aspect(1.0 / pylab.cos(pylab.pi / 180.0 * mean_lat))
コード例 #22
0
 def plotbar(self):
     """quickly plots a bar plot of the isotope bar pattern"""
     import pylab as pl
     fwhm = self.em/self.ks['res']
     pl.bar(self.barip[0], self.barip[1], width=fwhm, align='center')
     pl.xlabel('m/z', style='italic')
     pl.ylabel('normalized intensity')
     pl.ticklabel_format(useOffset=False)
     pl.show()
コード例 #23
0
 def fixticks(current_data):
     from pylab import ticklabel_format, plot,grid,gca
     ticklabel_format(useOffset=False)
     if xmax is not None:
         plot(xmax, etamax, 'r')
     xlimits = gca().get_xlim()
     print('+++ xlimits = ',xlimits)
     import pdb; pdb.set_trace()
     grid(True)
コード例 #24
0
ファイル: setplot.py プロジェクト: rjleveque/adjoint
 def aa_innerprod(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, yticks
     plotcc(current_data)
     title_innerproduct(current_data)
     ticklabel_format(format='plain',useOffset=False)
     xticks([180, 200, 220, 240], rotation=20, fontsize = 28)
     pylab.tick_params(axis='y', labelleft='off')
     a = gca()
     a.set_aspect(1./cos(41.75*pi/180.))
コード例 #25
0
ファイル: setplot.py プロジェクト: ortegagingrich/adjoint
 def aa_innerprod(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, yticks
     plotcc(current_data)
     title_innerproduct(current_data)
     ticklabel_format(format='plain',useOffset=False)
     xticks([180, 200, 220, 240], rotation=20, fontsize = 28)
     pylab.tick_params(axis='y', labelleft='off')
     a = gca()
     a.set_aspect(1./cos(41.75*pi/180.))
コード例 #26
0
ファイル: setplot.py プロジェクト: ortegagingrich/adjoint
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, yticks
     plotcc(current_data)
     title(current_data)
     ticklabel_format(format='plain',useOffset=False)
     xticks([180, 200, 220, 240], rotation=20, fontsize = 28)
     yticks(fontsize = 28)
     a = gca()
     a.set_aspect(1./cos(41.75*pi/180.))
コード例 #27
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, imshow, savefig
     addgauges(current_data)
     title_hours(current_data)
     ticklabel_format(format='plain', useOffset=False)
     xticks(rotation=20)
     #extent = (235.8756, 235.9116, 46.854, 46.8756)
     #imshow(OcostaGE,extent=extent, alpha=0.5)
     a = gca()
     a.set_aspect(1. / cos(46.86 * pi / 180.))
コード例 #28
0
ファイル: setplot.py プロジェクト: rjleveque/adjoint
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, yticks, grid
     plotcc(current_data)
     title_hours(current_data)
     ticklabel_format(format='plain', useOffset=False)
     xticks(rotation=20, fontsize=10)
     yticks(fontsize=10)
     a = gca()
     a.set_aspect(1. / cos(41.75 * pi / 180.))
     grid(True)
コード例 #29
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
    def aa(current_data):
        from pylab import ticklabel_format, xticks, gca, cos, pi, imshow, savefig

        addgauges(current_data)
        title_hours(current_data)
        ticklabel_format(format="plain", useOffset=False)
        xticks(rotation=20)
        # extent = (235.8756, 235.9116, 46.854, 46.8756)
        # imshow(OcostaGE,extent=extent, alpha=0.5)
        a = gca()
        a.set_aspect(1.0 / cos(46.86 * pi / 180.0))
コード例 #30
0
 def aa_patches(current_data):
     import pylab
     pylab.ticklabel_format(format='plain', useOffset=False)
     pylab.xticks([180, 200, 220, 240], rotation=20, fontsize=28)
     pylab.yticks(fontsize=28)
     t = current_data.t
     t = t / 3600.  # hours
     pylab.title('Grids patches at %4.2f hours' % t, fontsize=20)
     a = pylab.gca()
     a.set_aspect(1. / pylab.cos(41.75 * pylab.pi / 180.))
     pylab.grid(True)
コード例 #31
0
def plot_SandI(susceptible, infected, Title):
    pl.figure(figsize=(5,3))
    pl.plot(time, susceptible,label="Susceptible")
    pl.fill_between(time, susceptible, 0, alpha=0.30)
    pl.plot(time, infected,label="Infected")
    pl.fill_between(time, infected, 0, alpha=0.30)
    pl.ticklabel_format(axis="y", style="sci", scilimits=(0,0))
    pl.xlabel('Time in days', fontsize=14)
    pl.ylabel('Individuals', fontsize=14)
    pl.title(Title)
    pl.legend()
コード例 #32
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
    def aa(current_data):
        from pylab import ticklabel_format, xticks, gca, cos, pi, imshow, savefig, plot
        from pyclaw.plotters.plottools import plotbox

        # addgauges(current_data)
        title_hours(current_data)
        ticklabel_format(format="plain", useOffset=False)
        xticks(rotation=20)
        a = gca()
        # a.set_aspect(1./cos(46.86*pi/180.))
        a.set_aspect(1.0 / cos(46.349 * pi / 180.0))
        plot([235.9499], [46.3490], "wo")
コード例 #33
0
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, imshow, savefig
     from clawpack.visclaw.plottools import plotbox
     #addgauges(current_data)
     title_hours(current_data)
     ticklabel_format(useOffset=False)
     xticks(rotation=20)
     a = gca()
     a.set_aspect(1./cos(46.86*pi/180.))
     if current_data.t > 40*60.:
         extent = (235.8756, 235.9116, 46.854, 46.8756)
         plotbox(extent)
コード例 #34
0
ファイル: setplot.py プロジェクト: dlgeorge/geoclawapps
 def aa(current_data):
     from pylab import ticklabel_format, xticks, gca, cos, pi, imshow, \
                 savefig, plot
     from pyclaw.plotters.plottools import plotbox
     #addgauges(current_data)
     title_hours(current_data)
     ticklabel_format(format='plain', useOffset=False)
     xticks(rotation=20)
     a = gca()
     #a.set_aspect(1./cos(46.86*pi/180.))
     a.set_aspect(1. / cos(46.349 * pi / 180.))
     plot([235.9499], [46.3490], 'wo')
コード例 #35
0
def plotdata(noiselessData):
    aD.plot_parameters()
    fig = pylab.figure(1, (7, 5))
    fig.add_subplot(111)
    for noiseless in noiselessData:
        pylab.plot(noiseless.noiselessData, label=noiseless.voltage)
    pylab.ticklabel_format(style='sci', scilimits=(0, 0))
    pylab.xlabel("Time [s]")
    pylab.ylabel("Voltage [V]")
    pylab.legend(loc=4, ncol=5)
    pylab.grid()
    pylab.tight_layout()
    pylab.show()
コード例 #36
0
def plotResults(results):
    fig = pylab.figure(20, (7, 5))
    fig.add_subplot(111)
    pylab.plot(results["Voltage"], results["MIPs"], "ko", fillstyle="none")
    pylab.ticklabel_format(axis="x", style='sci', scilimits=(-1, 4))
    pylab.ticklabel_format(axis="y", style='sci', scilimits=(0, 2))
    pylab.ylabel("MIPs")
    pylab.xlabel("Voltage [V]")
    pylab.legend(loc=4, ncol=5)
    pylab.grid()
    pylab.tight_layout()
    pylab.savefig("mipsVsVoltage.png")
    pylab.close()
コード例 #37
0
def mostrar_gráfico(X, Y, F):
    C = ['r', 'b', 'g', 'c', 'm', 'y', 'k', 'w']
    M = ['o', 's', 'p', 'h', '+', 'x', 'v', '^']
    xlabel('tamanho da entrada')
    ylabel('tempo de execução (s)')
    ticklabel_format(style='sci', axis='both', scilimits=(-3, +4))
    grid(True)
    for i, f in enumerate(F):
        plot(X,
             Y[i],
             color=C[i % len(C)],
             marker=M[i % len(M)],
             label=f.__name__)
    legend(loc='upper left')
    show()
コード例 #38
0
def run():
    x = []
    y = []

    for i in range(1, 1001):
        x.append(i / 100.0)
        y.append((planckFunction(i * 10**-8, 2850.0)))

    pylab.ticklabel_format(axis='y', style='sci',
                           scilimits=(-3, 4))  # label in scientific notation
    pylab.plot(x, y, linewidth='2.5', label='2850 K')
    pylab.xlabel('Wavelength (µm)')
    pylab.ylabel('Spectral radiance (W m$^{−2}$ µm$^{−1}$ sr$^{−1}$)')
    pylab.legend()
    pylab.show()
コード例 #39
0
ファイル: plot.py プロジェクト: jakob-ifgt/trunk
		def createLines(pStrip,ySpecs,isY1=True,y2Exists=False):
			'''Create data lines from specifications; this code is common for y1 and y2 axes;
			it handles y-data specified as callables, which might create additional lines when updated with liveUpdate.
			'''
			# save the original specifications; they will be smuggled into the axes object
			# the live updated will run yNameFuncs to see if there are new lines to be added
			# and will add them if necessary
			yNameFuncs=set([d[0] for d in ySpecs if callable(d[0])]) | set([d[0].keys for d in ySpecs if hasattr(d[0],'keys')])
			yNames=set()
			ySpecs2=[]
			for ys in ySpecs:
				# ys[0]() must return list of strings, which are added to ySpecs2; line specifier is synthesized by tuplifyYAxis and cannot be specified by the user
				if callable(ys[0]): ySpecs2+=[(ret,ys[1]) for ret in ys[0]()]
				elif hasattr(ys[0],'keys'): ySpecs2+=[(yy,'') for yy in ys[0].keys()]
				else: ySpecs2.append(ys)
			if len(ySpecs2)==0:
				print 'yade.plot: creating fake plot, since there are no y-data yet'
				line,=pylab.plot([nan],[nan])
				line2,=pylab.plot([nan],[nan])
				currLineRefs.append(LineRef(line,None,line2,[nan],[nan]))
			# set different color series for y1 and y2 so that they are recognizable
			if pylab.rcParams.has_key('axes.color_cycle'): pylab.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
			for d in ySpecs2:
				yNames.add(d)
				line,=pylab.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0]))
				line2,=pylab.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha)
				# use (0,0) if there are no data yet
				scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
				# if current value is NaN, use zero instead
				scatter=pylab.scatter(scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0,s=scatterSize,color=line.get_color(),**scatterMarkerKw)
				currLineRefs.append(LineRef(line,scatter,line2,data[pStrip],data[d[0]]))
			axes=line.get_axes()
			labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
			l=pylab.legend(loc=labelLoc)
			if hasattr(l,'draggable'): l.draggable(True)
			if scientific:
				pylab.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
				# fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
				if not isY1: axes.yaxis.set_offset_position('right')
			if isY1:
				pylab.ylabel((', '.join([xlateLabel(_p[0]) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
				pylab.xlabel(xlateLabel(pStrip) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
			else:
				pylab.ylabel((', '.join([xlateLabel(_p[0]) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
			# if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
			if yNameFuncs:
				axes.yadeYNames,axes.yadeYFuncs,axes.yadeXName,axes.yadeLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend yade to avoid clashes
コード例 #40
0
ファイル: test_irbm.py プロジェクト: MarcCote/iRBM
    def test_verify_AIS(self):
        model = iRBM(input_size=self.input_size,
                     hidden_size=self.hidden_size,
                     beta=self.beta)

        model.W.set_value(self.W)
        model.b.set_value(self.b)
        model.c.set_value(self.c)

        # Brute force
        print "Computing lnZ using brute force (i.e. summing the free energy of all posible $v$)..."
        V = theano.shared(value=cartesian([(0, 1)] * self.input_size, dtype=config.floatX))
        brute_force_lnZ = logsumexp(-model.free_energy(V), 0)
        f_brute_force_lnZ = theano.function([], brute_force_lnZ)

        params_bak = [param.get_value() for param in model.parameters]

        print "Approximating lnZ using AIS..."
        import time
        start = time.time()

        try:
            ais_working_dir = tempfile.mkdtemp()
            result = compute_AIS(model, M=self.nb_samples, betas=self.betas, seed=1234, ais_working_dir=ais_working_dir, force=True)
            logcummean_Z, logcumstd_Z_down, logcumstd_Z_up = result['logcummean_Z'], result['logcumstd_Z_down'], result['logcumstd_Z_up']
            std_lnZ = result['std_lnZ']

            print "{0} sec".format(time.time() - start)

            import pylab as plt
            plt.gca().set_xmargin(0.1)
            plt.errorbar(range(1, self.nb_samples+1), logcummean_Z, yerr=[std_lnZ, std_lnZ], fmt='or')
            plt.errorbar(range(1, self.nb_samples+1), logcummean_Z, yerr=[logcumstd_Z_down, logcumstd_Z_up], fmt='ob')
            plt.plot([1, self.nb_samples], [f_brute_force_lnZ()]*2, '--g')
            plt.ticklabel_format(useOffset=False, axis='y')
            plt.show()
            AIS_logZ = logcummean_Z[-1]

            assert_array_equal(params_bak[0], model.W.get_value())
            assert_array_equal(params_bak[1], model.b.get_value())
            assert_array_equal(params_bak[2], model.c.get_value())

            print np.abs(AIS_logZ - f_brute_force_lnZ())
            assert_almost_equal(AIS_logZ, f_brute_force_lnZ(), decimal=2)
        finally:
            shutil.rmtree(ais_working_dir)
コード例 #41
0
ファイル: plots.py プロジェクト: fmihpc/analysator
def plot_from_list( list_of_coordinates, fitfunction="nullfit", cubicspline=True, xticks=-1, yticks=-1 ):
   '''Plots the given list. The list should be in the following format:
      [[x1,y1], [x2,y2], [x3,y3], [x4,y4], .. ]
      :param list_of_coordinates    List of coordinates to be plotted
   '''
   index = 1
   fig = pl.figure()
   for i in list_of_coordinates:
      #title="(" + i[2] + "," + i[3] + ")"
      pl.subplot(len(list_of_coordinates), 1, index)
      #ax = fig.add_subplot(len(list_of_coordinates), 1, index)
      x = i[0]
      y = i[1]
      pl.xlabel(i[2])
      pl.ylabel(i[3])
      xlength = max(x) - min(x)
      ylength = max(y) - min(y)
      pl.xlim([min(x) - 0.01*xlength, max(x) + 0.01*xlength])
      pl.ylim([min(y) - 0.05*ylength, max(y) + 0.05*ylength])
      plot_variables(x,y,False,fitfunction,cubicspline=cubicspline)
      pl.ticklabel_format(style='sci', axis='y', scilimits=(-3,3))
      # Set y ticks
      if yticks > 0 and len(i) == 4:
         ticks = min(y) + np.arange(yticks + 1) / (float)(yticks)*ylength
         print len(i)
         from decimal import *
         getcontext().prec = 2
         # Get two decimals
         ticks = [float(Decimal(j)/Decimal(1)) for j in ticks]
         pl.yticks(ticks)
         print ticks
      # Set x ticks
      if xticks > 0 and len(i) == 4:
         ticks = min(x) + np.arange(xticks + 1) / (float)(xticks)*xlength
         from decimal import *
         getcontext().prec = 2
         # Get two decimals
         ticks = [float(Decimal(j)/Decimal(1)) for j in ticks]
         pl.xticks(ticks)
      index = index + 1
   #pl.tight_layout()
   pl.ion()
   pl.show()
コード例 #42
0
ファイル: SamplingTimes.py プロジェクト: airanmehr/bio
def plotDepth():
    d = pd.read_pickle(utl.outpath + 'real/D.F59.df').replace({0: 1})

    z = pd.Series(np.ndarray.flatten(d.values))
    plt.figure(figsize=(8, 8), dpi=100);
    plt.subplot(2, 1, 1);
    sns.distplot(z, bins=180, norm_hist=False, kde=False);
    plt.xlim([0, 200]);
    plt.xlabel('Depth');
    plt.ylabel('Number of Measurments' + ' (out of {:.1f}M)'.format(z.shape[0] / 1e6));
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    plt.subplot(2, 1, 2);
    sns.distplot(d.min(1), bins=50, norm_hist=False, kde=False);
    plt.xlim([0, 200]);
    plt.xlabel('Minimum Depth of each Site');
    plt.ylabel('Number of Sites' + ' (out of {:.1f}M)'.format(d.shape[0] / 1e6));

    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    plt.savefig(utl.paperFiguresPath + 'depth.pdf')
コード例 #43
0
ファイル: Depth.py プロジェクト: airanmehr/bio
def plotDepth():
    sns.set_style("whitegrid", {"grid.color": "1", 'axes.linewidth': .5, "grid.linewidth": ".09"})
    sns.set_context("notebook", font_scale=1.4, rc={"lines.linewidth": 2.5})
    d = pd.read_pickle(utl.outpath + 'real/CD.F59.df').xs('D', level='READ', axis=1)
    (d.min(1) > 50).sum()

    (d > 50).sum().sum()

    z = pd.Series(np.ndarray.flatten(d.values))
    fontsize = 6
    mpl.rcParams.update({'font.size': fontsize})
    plt.figure(figsize=(6, 4), dpi=300);
    plt.subplot(2, 2, 1);
    z.value_counts().sort_index().plot()
    plt.xlim([0, 200]);
    plt.xlabel('Depth');
    plt.ylabel('Number of Measurments' + '\n (out of {:.1f}M)'.format(z.shape[0] / 1e6));
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    plt.title('Scaled PDF')
    pplt.annotate('(A)', xpad=0.85, ypad=0.45, fontsize=fontsize)
    plt.axvline(50, linestyle='--', linewidth=1, color='k')
    pplt.setSize(plt.gca(), fontsize)
    plt.subplot(2, 2, 2);

    z.value_counts().sort_index().cumsum().plot()
    plt.xlim([0, 200])
    plt.ylim([-3e5, 2.05 * 1e7])
    plt.xlabel('Depth');
    plt.title('Scaled CDF')
    pplt.annotate('(B)', xpad=0.85, ypad=0.45, fontsize=fontsize)
    plt.axvline(50, linestyle='--', linewidth=1, color='k')
    pplt.setSize(plt.gca(), fontsize)
    plt.subplot(2, 2, 3);
    d.min(1).value_counts().sort_index().plot()
    plt.xlim([0, 100]);
    plt.xlabel('Minimum Depth of each Variant');
    plt.ylabel('Number of Variants' + '\n (out of {:.1f}M)'.format(d.shape[0] / 1e6));
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    plt.rc('font', size=fontsize)
    pplt.annotate('(C)', xpad=0.85, ypad=0.45, fontsize=fontsize)
    plt.axvline(50, linestyle='--', linewidth=1, color='k')
    pplt.setSize(plt.gca(), fontsize)
    plt.subplot(2, 2, 4);
    d.min(1).value_counts().sort_index().cumsum().plot()
    plt.xlim([0, 60])
    plt.ylim([0.25 * -1e5, plt.ylim()[1]])
    plt.xlabel('Minimum Depth of each Variant');
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    pplt.annotate('(D)', xpad=0.85, ypad=0.45, fontsize=fontsize)
    plt.axvline(50, linestyle='--', linewidth=1, color='k')
    pplt.setSize(plt.gca(), fontsize)
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.gcf().tight_layout(h_pad=0.1)
    fontsize = 6
    mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': fontsize});
    mpl.rc('text', usetex=True)
    mpl.rcParams.update({'font.size': 1})

    pplt.savefig('depth', 300)
    plt.show()
コード例 #44
0
 def plotgaus(self,exp=None):
     """quickly plots the simulated gaussian isotope pattern"""
     import pylab as pl
     try:
         pl.plot(self.gausip[0],self.gausip[1],linewidth=1)
     except AttributeError:
         self.gausip = self.gaussianisotopepattern()
         pl.plot(self.gausip[0],self.gausip[1],linewidth=1)
     if exp is not None: # plots experimental if supplied
         y = []
         maxy = max(exp[1])
         for val in exp[1]: # normalize
             y.append(val/maxy*100)
         comp = self.compare(exp)
         pl.plot(exp[0],exp[1])
         pl.text(max(exp[0]),95,'SER: '+`comp`)
         #pl.fill_between(x,self.gausip[1],exp[1],where= exp[1] =< self.gausip[1],interpolate=True, facecolor='red')
     pl.fill(self.gausip[0],self.gausip[1],facecolor='blue',alpha=0.25)
     pl.xlabel('m/z', style='italic')
     pl.ylabel('normalized intensity')
     pl.ticklabel_format(useOffset=False)
     pl.show()
コード例 #45
0
def P_AP(folder,keys):
  
  for f in folder:
    
    
    a=Analysis.AnalyseFile()
    a.add_column(f.column('Current'),'Current')
    a.add_column(f.column('Mean'),'NLV')
    
    fit, fitVar= a.curve_fit(quad,'Current','NLV',bounds=lambda x,y:abs(x)>200e-6,result=True,header='Fit') 
    
    plt.title(r'')
    plt.xlabel(r'Temperature (K)')
    plt.ylabel(r'$\beta$ (V/A$^2$)')
    plt.ticklabel_format(style='plain', scilimits=(3 ,3))
    plt.hold(True)
    
    '''
    if f['IVtemp'] == 5:
      plt.plot(a.column('Current'),a.column('NLV'),'b')
      plt.plot(a.column('Current'),a.column('Fit'),'k')
      
    '''
    print f['state'],f['IVtemp']
    
    if f['state'] == 'P':
      #plt.plot(f['IVtemp'],fit[0],'ro')
      print fitVar
      plt.errorbar(f['IVtemp'],fit[0],numpy.sqrt(fitVar[0,0]),ecolor='k',marker='o',mfc='red', mec='k',ms=15.0)
      print 'p'
    if f['state'] == 'AP':
      print 'ap'
      plt.errorbar(f['IVtemp'],fit[0],numpy.sqrt(fitVar[0,0]),ecolor='k',marker='o',mfc='blue', mec='k',ms=15.0)
      #plt.plot(f['IVtemp'],fit[0],'bx')
  #plt.legend()
  plt.savefig('/Users/Joe/PhD/Talks/MMM13/beta.eps', bbox_inches=0)
  plt.show()
コード例 #46
0
ファイル: load.py プロジェクト: PragyaJaiswal/Benchmarking
def plot_stat_without_eq(dictionary, file, location=None):
	fig = pylab.figure()
	count = 0
	print(type(dictionary))
	lis = sorted(dictionary.keys())

	for key in lis:
		count+=1
		axes = dictionary.get(key)

		filename = str(file) + '.png'
		
		fig.add_subplot(4, 2, (count))
		pylab.ticklabel_format(style='sci', axis = 'both', scilimits=(0,0))
		pylab.plot(axes.get('x'), axes.get('y'), str(1), color='0.4', marker='o', markeredgecolor='0.4')
		pylab.xlabel('iTRAQAnalyzer')
		pylab.ylabel('Protein Pilot')
		pylab.rc('font', size=5.5)

		# z[0] denotes slope, z[1] denotes the intercept
		z = np.polyfit(axes.get('x'), axes.get('y'), 1)
		p = np.poly1d(z)
		coeff = np.corrcoef(axes.get('x'), axes.get('y'))

		pylab.plot(axes.get('x'), p(axes.get('x')), "r-", color='0')
		print "y=%.6fx+(%.6f)"%(z[0],z[1])
		# pylab.text(0.1, 0.3, "y=%.6fx+(%.6f)"%(z[0],z[1]))
		print str(coeff[0][1])
		pylab.title(str(key))
		pylab.tight_layout()

		graph = pylab.gcf()
		graph.canvas.set_window_title(str(filename))

	graph.savefig(location + '/' + filename)
	pylab.close()
コード例 #47
0
ファイル: pgrot.py プロジェクト: thibaultmerle/formato
        pl.xticks(pl.arange(len(terms))+1, (terms))
    #ax1.set_xticks(pl.arange(len(terms))[::2]+1)
    #ax1.set_xticklabels(terms[::2])ls
    #ax2.set_xticks(pl.arange(len(terms))[::2]+1.5)
    #ax2.set_xticklabels(terms[1:len(terms)-1:2])
    #ax1.tick_params(axis='x', which='major', labelsize=10)   
    pl.xlim(0.5, len(terms)+0.5)
    if levels[0].e/EV_TO_CM == 0:
        pl.ylim((levels[0].e/EV_TO_CM-0.2), round(ION.e/EV_TO_CM+0.5))
        #pl.ylim((levels[0].e/EV_TO_CM-0.2), round(levels[-1].e/EV_TO_CM+0.5))

    if not IL:
        pl.ylim(-0.2, round(max(levels).e/EV_TO_CM+0.5))

    try:
        pl.ticklabel_format(useOffset=False)
    except AttributeError:
        pass

# Plot collision transitions

    if CT_THEO:
        for i, llev in enumerate(fl+ml+sl+hl):
            for j, ulev in enumerate((fl+ml+sl+hl)[i+1:]):
                term_l = llev.remove_label_term(llev.term)
                term_u = ulev.remove_label_term(ulev.term)
                e_l = llev.e/EV_TO_CM
                e_u = ulev.e/EV_TO_CM                
                #print(terms.index(term_l)+1, terms.index(term_u)+1, [e_l, e_u])
                try:
                    ct_theo_line, = pl.plot([terms.index(term_l)+1, terms.index(term_u)+1], [e_l, e_u], 'k-')
コード例 #48
0
def plot_mass_spectrum(realspec, simdict={}, **kwargs):
    """
    Plots and saves a publication quality mass spectrum with optional overlaid isotope patterns

    **Parameters**

    realspec: *list*
        A paired list of x and y values of the form ``[[x values],[y values]]``

    simdict: *dictionary* or *list* or *string*, optional
        This can either be a molecular formula to predict the isotope pattern of (string),
        a list of formulae, or a dictionary of the form
        ``simdict = {'formula1':{'colour':<hex or name or RGB tuple>, 'alpha':float}, ...}``.
        If this is dictionary is left empty, no isotope patterns will be overlaid on the output
        spectrum.


    **Returns**

    returns: ``None``
        This function has not pythonic output.


    **\*\*kwargs**

    annotations: None
        Annotations for the spectrum in dictionary form: ``{'thing to print':[x,y],}``. Options: dictionary or ``None``

    axwidth: 1.5
        Line width for the axes and tick marks. Options: float.

    bw: 'auto'
        The width of the bar in *m/z* for bar isotope patterns. Options: 'auto' or float
        This only has an affect if *simtype* is 'bar'.
        Auto make the bars equal to 2 times the full width at half max of the peak they are simulating.

    delta: False
        Whether to calculate and output the mass delta between the exact mass predicted by the isotope pattern
        simulation and the location of the maximum intensity within the bounds specified by *normwindow*.
        Options: bool.

    dpiout: 300
        The dots per inch for the output figure. Options: integer.

    exten: 'png'
        The file extension for the output figure. Options: 'png', 'svg', or other supported by matplotlib.

    fs: 16
        Font size to use for labels. Options: integer or float.

    lw: 1.5
        Line width for the plotted spectrum. Options: float.

    maxy: 'max'
        The maximum y value for the spectrum. Options: 'max' or specify a value

    mz: 'auto'
        The *m/z* bounds for the output spectrum. Default: 'auto', but can be supplied
        with a tuple or list of length 2 of the form ``[x start, x end]``.

    norm: True
        Normalize the spectrum. Options: bool

    normwindow: 'fwhm'
        The *m/z* window width within with too look for a maximum intensity value.
        This will only have an effect if *delta* is ``True``.
        Options: 'fwhm' for full width at half max or float.

    offsetx: True
        Whether to offset the x-axis slightly. Options: bool.
        Enabling this shows makes it easier to see low intensity peaks.

    outname: 'spectrum'
        Name of the file to be saved.

    output: 'save'
        Save ('save') or show ('show') the figure.

    padding: 'auto'
        This allows the user to specify the subplot padding of the output figure.
        Options: 'auto' or list of the form ``[left,right,bottom,top]`` scalars.

    res_label: False
        Whether to output the resolution of the spectrum onto the figure. Options: bool.

    resolution:
        Override the auto-resolution calculation with a specified instrument resolution

    showx: True
        Whether to show the x-axis line. Options: bool.

    showy: True
        Whether to show the y-axis line. Options: bool.

    simlabels: False
        Whether to show the names of the simulated isotope patterns. Options: bool.
        The names will be exactly as supplied in ``simdict``.

    simnorm: 'spec'
        Normalize the isotope pattern simulations to what value. Options: 'top', 'spec', or specify a value.
        Top will normalize the patterns to ``maxy``, and will only function if maxy is not 'max'.
        Spec will normalize the patterns to the maximum spectrum y value within the x bounds of the
        simulated pattern.
        Specifying a value will normalize all isotope patterns to that value.
    
    simtype: 'bar'
        The type for the isotope pattern simulation overlay. Options: 'bar' or 'gaussian'.
    
    size: [7.87,4.87]
        The size in inches for the output figure. This must be a list of length 2 of the form
        ``[width,height]``.

    speccolour: 'k'
        The colour for the real spectrum , # colour for the spectrum to be plotted

    specfont: 'Arial'
        The font to use for text in the plot. The specified font must be accepted by matplotlib.

    spectype: 'continuum'
        The type of spectrum being handed to the function. Options: 'continuum' or 'centroid'.

    stats: False
        Whether to calculate and output the goodness of fit between the predicted isotope pattern and
        the supplied spectrum. This functionality is still a work in progress. Options: bool.

    verbose: True
        Verbose option for the script. Options: bool.

    xlabel: True
        Whether to show the label for the *m/z* axis. Options: bool.

    xvalues: True
        Whether to show the values of the x-axis. Options: bool.

    ylabel: True
        Whether to show the y-axis label. Options: bool.

    yvalues: True
        Whether to show the values of the y-axis. Options: bool.

    """
    def checksimdict(dct):
        """
        checks the type of simdict, converting to dictionary if necessary
        also checks for alpha and colour keys and adds them if necessary (defaulting to key @ 0.5)
        """
        if type(dct) is not dict:
            if type(dct) is str:
                dct = {dct: {}}
            elif type(dct) is list or type(dct) is tuple:
                tdct = {}
                for i in dct:
                    tdct[i] = {}
                dct = tdct
        for species in dct:
            if 'colour' not in dct[species]:
                dct[species]['colour'] = 'k'
            if 'alpha' not in dct[species]:
                dct[species]['alpha'] = 0.5
        return dct

    settings = {  # default settings
        'mz': 'auto',  # m/z bounds for the output spectrum
        'outname': 'spectrum',  # name for the output file
        'output': 'save',  # 'save' or 'show' the figure
        'simtype': 'bar',  # simulation overlay type ('bar' or 'gaussian')
        'spectype': 'continuum',  # spectrum type ('continuum' or 'centroid')
        'maxy': 'max',  # max or value
        'norm': True,  # True or False
        'simnorm': 'spec',  # top, spec, or value
        'xlabel': True,  # show x label
        'ylabel': True,  # show y label
        'xvalues': True,  # show x values
        'yvalues': True,  # show y values
        'showx': True,  # show x axis
        'showy': True,  # how y axis
        'offsetx': True,  # offset x axis (shows low intensity species better)
        'fs': 16,  # font size
        'lw': 1.5,  # line width for the plotted spectrum
        'axwidth': 1.5,  # axis width
        'simlabels': False,  # show labels isotope for patterns
        'bw': 'auto',  # bar width for isotope patterns (auto does 2*fwhm)
        'specfont': 'Arial',  # the font for text in the plot
        'size': [7.87, 4.87],  # size in inches for the figure
        'dpiout': 300,  # dpi for the output figure
        'exten': 'png',  # extension for the output figure
        'resolution': None,  # resolution to use for simulations (if not specified, automatically calculates)
        'res_label': False,  # output the resolution of the spectrum
        'delta': False,  # output the mass delta between the spectrum and the isotope patterns
        'stats': False,  # output the goodness of match between the spectrum and the predicted isotope patterns,
        'speccolour': 'k',  # colour for the spectrum to be plotted
        'padding': 'auto',  # padding for the output plot
        'verbose': True,  # verbose setting
        'normwindow': 'fwhm',
    # the width of the window to look for a maximal value around the expected exact mass for a peak
        'annotations': None,  # annotations for the spectrum in dictionary form {'thing to print':[x,y],}
        'normrel': 100.,  # the maximum value for normalization
        'ipmol_kwargs': {},  # IPMolecule keyword arguments
    }

    if set(kwargs.keys()) - set(settings.keys()):  # check for invalid keyword arguments
        string = ''
        for i in set(kwargs.keys()) - set(settings.keys()):
            string += ' %s' % i
        raise KeyError('Unsupported keyword argument(s): %s' % string)

    settings.update(kwargs)  # update settings from keyword arguments

    if settings['resolution'] is None:
        if settings['spectype'] != 'centroid':
            res = autoresolution(realspec[0], realspec[1])  # calculate resolution
        else:
            res = 5000
    else:
        res = settings['resolution']

    simdict = checksimdict(simdict)  # checks the simulation dictionary
    for species in simdict:  # generate Molecule object and set x and y lists
        simdict[species]['colour'] = Colour(simdict[species]['colour'])
        simdict[species]['mol'] = IPMolecule(species, resolution=res, **kwargs['ipmol_kwargs'])
        # simdict[species]['mol'] = Molecule(species, res=res, dropmethod='threshold')
        if settings['simtype'] == 'bar':
            simdict[species]['x'], simdict[species]['y'] = simdict[species]['mol'].barip
        if settings['simtype'] == 'gaussian':
            simdict[species]['x'], simdict[species]['y'] = simdict[species]['mol'].gausip

    if settings['mz'] == 'auto':  # automatically determine m/z range
        if settings['verbose'] is True:
            sys.stdout.write('Automatically determining m/z window')
        mz = [10000000, 0]
        for species in simdict:
            simdict[species]['bounds'] = simdict[species]['mol'].bounds  # calculate bounds
            if simdict[species]['bounds'][0] < mz[0]:
                mz[0] = simdict[species]['bounds'][0] - 1
            if simdict[species]['bounds'][1] > mz[1]:
                mz[1] = simdict[species]['bounds'][1] + 1
        if mz == [10000000, 0]:
            mz = [min(realspec[0]), max(realspec[0])]
        settings['mz'] = mz
        if settings['verbose'] is True:
            sys.stdout.write(': %i - %i\n' % (int(mz[0]), int(mz[1])))
            sys.stdout.flush()
    else:  # catch for user specified m/z bounds
        mz = settings['mz']

    realspec[0], realspec[1] = trimspectrum(realspec[0], realspec[1], settings['mz'][0] - 1,
                                            settings['mz'][1] + 1)  # trim real spectrum for efficiency

    if len(realspec[0]) == 0:  # catch for empty spectrum post-trim (usually user error)
        raise ValueError(f'There are no spectral values in the specified m/z bounds ({mz[0]}-{mz[1]}). Common causes: '
                         f'no values in the loaded spectrum within the window of interest, an error in specifying the '
                         f'molecule(s) to simulate')

    if settings['norm'] is True:  # normalize spectrum
        realspec[1] = normalize(realspec[1], settings['normrel'])

    for species in simdict:  # normalize simulations
        if settings['simnorm'] == 'spec':  # normalize to maximum around exact mass
            if settings['normwindow'] == 'fwhm':  # if default, look within the full width at half max
                window = simdict[species]['mol'].fwhm
            else:  # otherwise look within the specified value
                window = settings['normwindow']
            simdict[species]['y'] = normalize(
                simdict[species]['y'],
                localmax(
                    realspec[0],
                    realspec[1],
                    simdict[species]['mol'].estimated_exact_mass,
                    window
                )
            )
        elif settings['simnorm'] == 'top':  # normalize to top of the y value
            if settings['maxy'] == 'max':
                raise ValueError('Simulations con only be normalized to the top of the spectrum when the maxy setting '
                                 'is a specific value')
            simdict[species]['y'] = normalize(simdict[species]['y'], settings['maxy'])
        elif type(settings['simnorm']) is int or type(settings['simnorm']) is float:  # normalize to specified value
            simdict[species]['y'] = normalize(simdict[species]['y'], settings['simnorm'])
        if settings['delta'] is True:
            if settings['normwindow'] == 'fwhm':  # if default, look within the full width at half max
                window = simdict[species]['mol'].fwhm
            else:  # otherwise look within the specified value
                window = settings['normwindow']
            est = estimated_exact_mass(  # try to calculate exact mass
                realspec[0],
                realspec[1],
                simdict[species]['mol'].estimated_exact_mass,
                simmin=simdict[species]['mol'].estimated_exact_mass,
                simmax=simdict[species]['mol'].estimated_exact_mass,
                lookwithin=window,
                # min(simdict[species]['x']),
                # max(simdict[species]['x'])
            )
            if type(est) is float:
                simdict[species]['delta'] = '%.3f (%.1f ppm)' % (
                simdict[species]['mol'].estimated_exact_mass - est, simdict[species]['mol'].compare_exact_mass(est))
            else:
                simdict[species]['delta'] = est

    pl.clf()  # clear and close figure if open
    pl.close()
    fig = pl.figure(figsize=tuple(settings['size']))
    ax = fig.add_subplot(111)

    ax.spines["right"].set_visible(False)  # hide right and top spines
    ax.spines["top"].set_visible(False)

    if settings['showx'] is False:
        ax.spines["bottom"].set_visible(False)  # hide bottom axis
    if settings['showy'] is False:
        ax.spines["left"].set_visible(False)  # hide left axis

    for axis in ["top", "bottom", "left", "right"]:
        ax.spines[axis].set_linewidth(settings['axwidth'])

    if settings['offsetx'] is True:  # offset x axis
        ax.spines["bottom"].set_position(('axes', -0.01))

    font = {'fontname': settings['specfont'], 'fontsize': settings['fs']}  # font parameters for axis/text labels
    tickfont = pl.matplotlib.font_manager.FontProperties(  # font parameters for axis ticks
        family=settings['specfont'],
        size=settings['fs']
    )

    ax.set_xlim(settings['mz'])  # set x bounds

    if settings['maxy'] == 'max':  # set y bounds
        ax.set_ylim(0., max(realspec[1]))
        top = max(realspec[1])
    elif type(settings['maxy']) is int or type(settings['maxy']) is float:
        ax.set_ylim(0., settings['maxy'])
        top = settings['maxy']

    if settings[
        'simtype'] == 'bar':  # generates zeros for bottom of bars (assumes m/z spacing is equal between patterns)
        for species in simdict:
            simdict[species]['zero'] = []
            for i in simdict[species]['x']:
                simdict[species]['zero'].append(0.)
        for species in simdict:  # for each species
            for subsp in simdict:  # look at all the species
                if subsp != species:  # if it is not itself
                    ins = bisect_left(simdict[subsp]['x'], simdict[species]['x'][-1])  # look for insertion point
                    if 0 < ins < len(simdict[subsp]['x']):  # if species highest m/z is inside subsp list
                        for i in range(ins):  # add intensity of species to subsp zeros
                            # used -ins+i-1 to fix an error, with any luck this won't break it next time
                            simdict[subsp]['zero'][i] += simdict[species]['y'][-ins + i]
    # include resolution if specified (and spectrum is not centroid)
    if settings['res_label'] is True and settings['spectype'] != 'centroid':
        ax.text(
            mz[1],
            top * 0.95,
            f'resolution: {str(round(res))}',
            horizontalalignment='right',
            **font
        )

    for species in simdict:  # plot and label bars
        if settings['simtype'] == 'bar':
            if settings['bw'] == 'auto':
                bw = simdict[species]['mol'].fwhm * 2
            else:
                bw = settings['bw']
            ax.bar(
                simdict[species]['x'],
                simdict[species]['y'],
                bw,
                alpha=simdict[species]['alpha'],
                color=simdict[species]['colour'].mpl,
                linewidth=0,
                align='center',
                bottom=simdict[species]['zero']
            )
        elif settings['simtype'] == 'gaussian':
            ax.plot(
                simdict[species]['x'],
                simdict[species]['y'],
                alpha=simdict[species]['alpha'],
                color=simdict[species]['colour'].mpl,
                linewidth=settings['lw']
            )
            ax.fill_between(
                simdict[species]['x'],
                0,
                simdict[species]['y'],
                alpha=simdict[species]['alpha'],
                color=simdict[species]['colour'].mpl,
                linewidth=0
            )
        # if any labels are to be shown
        if settings['simlabels'] is True or settings['stats'] is True or settings['delta'] is True:
            string = ''
            bpi = simdict[species]['y'].index(max(simdict[species]['y']))  # index of base peak
            if settings['simlabels'] is True:  # species name
                string += species
                if settings['stats'] is True or settings['delta'] is True:  # add return if SER or delta is called for
                    string += '\n'
            if settings['stats'] is True:  # standard error of regression
                string += f'SER: {simdict[species]["mol"].compare(realspec)} '
            if settings['delta'] is True:  # mass delta
                string += f'mass delta: {simdict[species]["delta"]}'
            ax.text(
                simdict[species]['x'][bpi],
                top * 1.01,
                string,
                color=simdict[species]['colour'].mpl,
                horizontalalignment='center',
                **font
            )

    if settings['spectype'] == 'continuum':
        ax.plot(
            realspec[0],
            realspec[1],
            linewidth=settings['lw'],
            color=Colour(settings['speccolour']).mpl
        )
    elif settings['spectype'] == 'centroid':
        dist = []
        for ind, val in enumerate(realspec[0]):  # find distance between all adjacent m/z values
            if ind == 0:
                continue
            dist.append(realspec[0][ind] - realspec[0][ind - 1])
        dist = sum(dist) / len(dist)  # average distance
        ax.bar(
            realspec[0],
            realspec[1],
            dist * 0.75,
            linewidth=0,
            color=Colour(settings['speccolour']).mpl,
            align='center',
            alpha=0.8
        )

    if settings['annotations'] is not None:
        for label in settings['annotations']:
            ax.text(
                settings['annotations'][label][0],
                settings['annotations'][label][1],
                label,
                horizontalalignment='center',
                **font
            )

            # show or hide axis values/labels as specified
    if settings['yvalues'] is False:  # y tick marks and values
        ax.tick_params(axis='y', labelleft='off', length=0)
    if settings['yvalues'] is True:  # y value labels
        ax.tick_params(
            axis='y',
            length=settings['axwidth'] * 3,
            width=settings['axwidth'],
            direction='out',
            right='off'
        )
        for label in ax.get_yticklabels():
            label.set_fontproperties(tickfont)
    if settings['ylabel'] is True:  # y unit
        if top == 100:  # normalized
            ax.set_ylabel('relative intensity', **font)
        else:  # set to counts
            ax.set_ylabel('intensity (counts)', **font)

    if settings['xvalues'] is False:  # x tick marks and values
        ax.tick_params(axis='x', labelbottom='off', length=0)
    if settings['xvalues'] is True:  # x value labels
        ax.tick_params(
            axis='x',
            length=settings['axwidth'] * 3,
            width=settings['axwidth'],
            direction='out',
            top='off'
        )
        for label in ax.get_xticklabels():
            label.set_fontproperties(tickfont)
    if settings['xlabel'] is True:  # x unit
        ax.set_xlabel('m/z', style='italic', **font)

    pl.ticklabel_format(useOffset=False)  # don't use the stupid shorthand thing
    if settings['padding'] == 'auto':
        pl.tight_layout(pad=0.5)  # adjust subplots
        if settings['simlabels'] is True or settings['stats'] is True or settings['delta'] is True:
            pl.subplots_adjust(top=0.90)  # lower top if details are called for
    elif type(settings['padding']) is list and len(settings['padding']) == 4:
        pl.subplots_adjust(
            left=settings['padding'][0],
            right=settings['padding'][1],
            bottom=settings['padding'][2],
            top=settings['padding'][3]
        )

    if settings['output'] == 'save':  # save figure
        outname = ''  # generate tag for filenaming
        for species in simdict:
            outname += ' ' + species
        outname = settings['outname'] + outname + '.' + settings['exten']
        pl.savefig(
            outname,
            dpi=settings['dpiout'],
            format=settings['exten'],
            transparent=True
        )
        if settings['verbose'] is True:
            sys.stdout.write('Saved figure as:\n"%s"\nin the working directory' % outname)

    elif settings['output'] == 'show':  # show figure
        pl.show()
コード例 #49
0

        
コード例 #50
0
ファイル: rosalib.py プロジェクト: ziyang/rosalib
def draw_RA(ROSAs, title=''):
    '''
    Draw RA figure
    ROSAs: a dict of several ROSA results
           Every ROSA result is also a dict.
    title='': title of the figure
    '''
    keys = ROSAs.keys()
    xsize, ysize = 6, 6

    #draw RA figure
    max_r = 3.
    RA_fig = pylab.figure(figsize=(xsize, ysize))
    ax2 = RA_fig.add_subplot(111)
    ax2.plot(0, 0, 'ks')
    ax2.axvline(x=0, color='k', linestyle=':')
    ax2.axhline(y=0, color='k', linestyle=':')
    X, Y = [], []
    U, V = [], []
    rs, thetas = [], []
    for k in keys:
        x = ROSAs[k]['r_rate']
        X.append(x)
        y = ROSAs[k]['Hu_dist']
        Y.append(y)
        ax2.plot(x, y, 'ko')
    Xlim = ax2.get_xlim()
    lx = 0.2/xsize * (Xlim[1]-Xlim[0])
    Ylim = ax2.get_ylim()
    ly = 0.2/ysize * (Ylim[1]-Ylim[0])
    ax2.set_xlim(Xlim[0]-2*lx, Xlim[1]+2*lx)
    ax2.set_ylim(Ylim[0]-2*ly, Ylim[1]+2*ly)
    Xlim = ax2.get_xlim()
    lx = 0.2/xsize * (Xlim[1]-Xlim[0])
    Ylim = ax2.get_ylim()
    ly = 0.2/ysize * (Ylim[1]-Ylim[0])
    for k in keys:
        r = ROSAs[k]['ecc']
        rs.append(r)
        theta = ROSAs[k]['angle'] * numpy.pi/180.
        thetas.append(theta)
        u = r * numpy.cos(theta)
        U.append(u)
        v = r * numpy.sin(theta)
        V.append(v)
    ll = min(lx, ly)
    for i, k in enumerate(keys):
        x = X[i]
        y = Y[i]
        ax2.text(x+0.5*lx, y+0.5*ly, k, color='k')
        u = U[i]
        v = V[i]
        theta = thetas[i]
        delta_x = numpy.cos(theta)
        delta_y = numpy.sin(theta)
    U = numpy.array(U)
    V = numpy.array(V)
    N_uv = numpy.sqrt(U**2 + V**2)

    #U1 = 0.15 * U/N_uv
    #V1 = 0.15 * V/N_uv
    U1 = []
    V1 = []
    for i in range(len(U)):
        if N_uv[i] != 0:
            U1.append(0.15 * U[i]/N_uv[i])
            V1.append(0.15 * V[i]/N_uv[i])
        else:
            U1.append(0.)
            V1.append(0.)
    U1 = numpy.array(U1)
    V1 = numpy.array(V1)

    ax2.quiver(X, Y, U, V, scale_units='inches', scale=0.254, width=0.004)

    ax2.quiver(X, Y, U1, V1, scale_units='inches', scale=0.254, width=0.00001, headwidth=1, linestyle='dotted', facecolor='none', linewidth=0.5)  #dotted line
    ax2.set_title(r'%s RA figure' % title)
    ax2.set_xlabel(r'Relative bias of amount $R$', labelpad=12)
    ax2.set_ylabel(r"Bias of Hu's moments $S_{HU}$", labelpad=0)
    for tick in ax2.xaxis.get_major_ticks():
        tick.label.set_fontsize('x-small')
    for tick in ax2.yaxis.get_major_ticks():
        tick.label.set_fontsize('x-small')
    pylab.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    RA_fig.savefig('%s-RA.pdf' % title)
    pylab.close()

    return RA_fig
コード例 #51
0
ファイル: IV_plotandfit.py プロジェクト: joebatley/PythonCode
print a.column(1)
fit, fitVar = a.curve_fit(lin, 1, 0)

print fit, fitVar
error = numpy.sqrt(fitVar[0, 0])
print error
t = 96e-9
w = 1130e-9
l = 30e-6

print fit[0] * t * w / l

alpha = 1e6
beta = 1

# plt.title(a['Sample ID'] + ' - ' + a['Notes'] + ' at ' + str.format("{0:.1f}",a['Sample Temp']) + ' K')
plt.xlabel(r"Current ($\mu$A)")
plt.ylabel(r"Voltage (V)")
plt.ticklabel_format(style="sci", useOffset=False)
plt.tick_params(axis="both", which="minor")
plt.plot(
    a.column("1"),
    a.column("0"),
    "-o",
    label="R = " + str.format("{0:.2f}", fit[0]) + r"$\pm$" + str.format("{0:.2f}", error) + r" $\Omega$",
)
plt.plot(a.column("1"), (fit[1] + (a.column("1") * fit[0])), "-r", label="Fit")
plt.legend(loc=2)
plt.tight_layout()
plt.show()
コード例 #52
0
ファイル: chapman.py プロジェクト: butala/pyrsss
    dt = datetime(2000, 1, 1)
    lat = 0
    lon = 0

    iri_ne = []
    for alt_i in alt:
        point = Point(dt, lat, lon, alt_i)
        point.run_iri()
        iri_ne.append(point.ne)

    Nm_star, Hm_star, H_O_star = chapman_fit(alt, iri_ne, verbose=True)

    chapman_ne = [chapman(z, Nm_star, Hm_star, H_O_star) for z in alt]

    fig = PL.figure(figsize=(6,10))
    PL.plot(iri_ne,
            alt,
            color='b',
            label='IRI')
    PL.plot(chapman_ne,
            alt,
            color='g',
            label='Chapman fit')
    PL.legend()
    PL.xlabel('Electron density [cm$^{-3}$]')
    PL.ylabel('Height [km]')
    PL.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
    PL.axis('tight')

    PL.show()
コード例 #53
0
ファイル: mixture.py プロジェクト: appcoreopc/thesis
a[1] = xt[-1]
a[2] = yt[0]
a[3] = yt[-1]
pylab.axis(a)
pylab.savefig('../figs/%spermutations.pdf' % prefix)

pylab.figure(8, figsize=figsize)
pylab.clf()
u = np.random.random(10**6)
pylab.subplot(2,1,1)
pylab.hist(np.log(u), 100)
pylab.text(-15.5, 10**5, '$N$ = 1,000,000\n100 bins', fontsize=fs-2)
pylab.xticks(fontsize=fs)
(a, b) = pylab.yticks()
pylab.yticks(a[:-1:2])
pylab.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
pylab.yticks(fontsize=fs)
pylab.rc('font', **{'size':fs})
pylab.ylabel('count', fontsize=fs)
pylab.title('Histograms of $\\log$ $u$, $u$ ~ Unif(0, 1)', fontsize=fs)
pylab.subplot(2,1,2)
pylab.hist(np.log(u), 100, log=True)
pylab.ylabel('count (log scale)', fontsize=fs)
pylab.xticks(fontsize=fs)
pylab.yticks(fontsize=fs)
(a, b) = pylab.yticks()
pylab.yticks(a[2:-1:2])
pylab.xlabel('$\\log$ $u$\n', fontsize=fs)
pylab.savefig('../figs/%suniform.pdf' % prefix)

pylab.figure(6, figsize=figsize)
コード例 #54
0
AP = a.mean('Rs',bounds = lambda x: x<Ref)
DeltaR = P-AP

print DeltaR

Perr = (numpy.std(a.search('Rs',lambda x,y:x>Ref,'Rs')))/numpy.sqrt(len(a.search('Rs',lambda x,y:x>Ref,'Rs'))) # error in average value for P state
APerr = (numpy.std(a.search('Rs',lambda x,y:x<Ref,'Rs')))/numpy.sqrt(len(a.search('Rs',lambda x,y:x<Ref,'Rs')))
DeltaRerr = numpy.sqrt((Perr*Perr)+(APerr*APerr)) #calculate error in Delta R in micro Ohms

print DeltaRerr


plt.title()
plt.xlabel('B (T)')
plt.ylabel(r'R$_s$ ($\mu$V/A)')
plt.ticklabel_format(style = 'sci', useOffset = False)
plt.tick_params(axis='both', which='minor')
plt.plot(data.column('Field'),data.column('Rs (microOhms)'),'-ob')
#matplotlib.pyplot.grid(False)
#plt.show()

b=Analysis.AnalyseFile()

for f in folder:
    
    Rmax = numpy.max(f.column('Resistance'))
    Rmin = numpy.min(f.column('Resistance'))    
    offset = ((Rmax-Rmin)/2)+Rmin        
    
    for i in range(0,len(f.column('Res'))-1,1):
        if f.column('Resistance')[i]>offset and  f.column('Resistance')[i+1]<offset:                       
コード例 #55
0
folder = DataFolder('/Users/Joe/PhD/Measurements/RN0151_4T/NLIVvsT/Both/',pattern = pattern)
folder.group(['state','IVtemp'])

folder.walk_groups(IV_group_Avg,group=True,replace_terminal=True)

folder.walk_groups(P_AP_col,group=True,replace_terminal=True)

print folder['AP']
  
for f in folder:
  
  for column in f.column_headers:
    plt.title(r'NL IV offset vs Temperature for Parallel (red) and Antiparallel (blue) State')
    plt.xlabel(r'Temperature (K)')
    plt.ylabel(r'$\alpha$ ($\mu$V/A) ')
    plt.ticklabel_format(style='plain', scilimits=(3 ,3))
    plt.hold(True)
    plt.grid(True)
    
    if folder['state'] == 'P':
        plt.errorbar(folder['IVtemp'],folder['P'].column('Mean Coef')[1],folder['P'].column('Err Coef')[1],ecolor='k',marker='o',mfc='red', mec='red')
    else:
        plt.errorbar(folder['IVtemp'],folder['AP'].column('Mean Coef')[1],folder['AP'].column('Err Coef')[1],ecolor='k',marker='o',mfc='blue', mec='blue')
  
#plt.legend()
plt.show()




コード例 #56
0
	else:
	
		plt.errorbar(axisrange, params[0][x], xerr = params[1][x], \
						marker='.', color = 'red', \
							ecolor = 'grey', linestyle = 'none',capsize = 0)

	if log == True:

		ax.set_yscale('log')
		ax.set_xscale('log')
		ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())

	else:

		plt.ticklabel_format(style='sci', scilimits=(0,0))

	if labels:

		for index in range(len(params[0][0])):
			plt.annotate(index +1, 
					xy = (params[0][x][index], params[0][y][index]), 
					xytext = (-20,20),
					textcoords = 'offset points', ha = 'right', va = 'bottom',
					bbox = dict(boxstyle = 'round,pad=0.5', fc = 'blue', alpha = 0.5),
					arrowprops = dict(arrowstyle = '->', 
					connectionstyle = 'arc3,rad=0'))


	#plt.ylim([-2.7,1.95])
	#plt.xlim([0.0,0.015])
コード例 #57
0
ファイル: setplot.py プロジェクト: cjvogl/seismic
 def fixticks1(current_data):
     from pylab import ticklabel_format
     ticklabel_format(format='plain',useOffset=False)
コード例 #58
0
ファイル: setplot.py プロジェクト: cjvogl/seismic
 def fixticks(current_data):
     from pylab import ticklabel_format, plot
     ticklabel_format(format='plain',useOffset=False)
     if xmax is not None:
         plot(xmax, etamax, 'r')
コード例 #59
0
import Stoner
from Stoner.Folders import DataFolder

# from pylab import arange,pi,sin,cos,sqrt


################ READ FILE INFO ########################

# filename = tkFileDialog.askopenfilename(message = 'Pick first file', title = 'Pick file ')
# workingpath = filename.rpartition('/')[0]

####### IMPORT DATA ######

folder = DataFolder(False, pattern="*.txt")

for f in folder:
    Ref = ((max(f.Resistance) - min(f.Resistance)) / 2) + min(f.Resistance)

    Field = f.column("Control:Magnet Output")

    plt.title("NL dc R vs H for different Temp")
    plt.xlabel(r"Field (T)")
    plt.ylabel(r"Resistance ($\mu$R)")
    plt.ticklabel_format(style="plain", scilimits=(3, 3))
    plt.hold(True)
    plt.plot(Field, f.column("Resistance") * 1e6, label=str(f.metadata["Sample Temp"]))
    plt.grid(True)

plt.legend()
plt.show()