def main():
    # get Dimensions of the 2D grid.
    OptDB = PETSc.Options()

    n = OptDB.getInt('n', 33)
    nx = OptDB.getInt('nx', n)
    ny = OptDB.getInt('ny', n)

    # run solution
    pde, time = solvePoisson(nx, ny)

    # Plot solution
    show_solution = OptDB.getBool('plot_solution', 0)
    if show_solution:
        pylab.figure()
        pylab.contourf(pde.da.getVecArray(pde.x)[:])
        pylab.colorbar()

    # plot convergence behavior
    pylab.figure()
    rh = pde.ksp.getConvergenceHistory()
    pylab.semilogy(range(len(rh)), rh, 'b-o')
    pylab.xlabel('Iterations')
    pylab.ylabel('||r||_2')
    pylab.title('Convergence Behavior {0}, time={1:8.6f} s'.format(
        pde.solver_name, time))
    pylab.grid()
    pylab.show()
def plottingTimeConsumptions(titleString, trialedFuncs, timesToPlot):
    """ titleString...String to be displayed in Title
    trialedFuncs...list of the strings of the trialed functions
    timesToPlot...dim [numberTrials, numberFunctions]
    """
    #    plt.figure()
    for cnt in range(len(trialedFuncs)):
        if 'vectorized' in trialedFuncs[cnt]:
            lineStyle = '--'
        elif 'faverage' in trialedFuncs[cnt]:
            lineStyle = '--'
        else:
            lineStyle = '-'
        plt.semilogy(timesToPlot[cnt],
                     label=trialedFuncs[cnt],
                     linestyle=lineStyle,
                     marker='o')
    plt.xticks(range(len(timesToPlot[1])))
    plt.xlabel('trials [1]')
    plt.ylabel('Time per Trial [s]')
    plt.grid(which='major')
    plt.grid(which='minor', linestyle='--')
    plt.title(titleString)
    yMin, yMax = plt.ylim()
    newYMin = 10**np.floor(np.log10(yMin))
    plt.ylim(newYMin, yMax)
    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
    plt.show()
def plot_solution(sets, xkey, ykey, name):
    '''
    Plot x vs u for different data sets
    '''
    # Plot
    plt.figure()
    fig, ax = plt.subplots()
    ax.spines['right'].set_visible(True)
    ax.spines['top'].set_visible(True)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    #ax.annotate('192,000 dof', xy=(4, 500))
    #ax.annotate('2 million dof', xy=(25, 10000))
    #plt.axis([5, 45, -.1, 1.0])
    #plt.xticks(np.arange(5, 50, step=5))

    # plot solutions on same graph
    keys = sets.keys()
    cidx = 0
    for key in keys:
        cidx += 2
        data = sets[key]
        plt.semilogy(data[xkey], data[ykey], '-', lw=3, mec='black', label=key)

    # Axis formatting
    plt.legend(loc='upper right')
    plt.xlabel(xkey)
    plt.ylabel(ykey)

    plt.savefig(name, bbox_inches='tight', pad_inches=0.05)

    return
def plot_results(xdata, ydata, labels, xlabel='', ylabel='', title='', linestyles=None, logy=False, logx=False, legend_loc=0, ylim=None, save_plot=False, filename=''):

    for x, y, linestyle in zip(xdata, ydata, linestyles):
        if logy and not logx:

            plt.semilogy(np.transpose(xdata), np.transpose(ydata))

        elif logx and not logy:

            plt.semilogx(np.transpose(xdata), np.transpose(ydata))

        elif logy and logx:

            plt.loglog(np.transpose(xdata), np.transpose(ydata))

        else:

            plt.plot(x, y, linestyle=linestyle)

    plt.legend(labels=labels, loc=legend_loc, frameon=False)

    if ylim is None:
        ylim = [np.min(ydata), np.max(ydata)]
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.ylim(ylim)

    if save_plot:
        plt.savefig(filename, transparent=True)

    plt.show()

    return
def plot(coefs_files, digit=0, mixture=0, axis=0):
    import numpy as np
    import matplotlib.pylab as plt
    import amitgroup as ag

    for coefs_file in coefs_files:
        coefs_data = np.load(coefs_file)
        var = coefs_data['prior_var']
        samples = coefs_data['samples']
        llh_var = coefs_data['llh_var']

        var_flat = ag.util.wavelet.smart_flatten(var[digit,mixture,axis])
        last_i = len(var_flat)-1
        plt.xlim((0, last_i))

        #imdef = ag.util.DisplacementFieldWavelet((32, 32), 'db4', penalty=100

        if len(coefs_files) == 1:
            add = ""
        else:   
            add = " ({0})".format(coefs_file.name)

        plt.subplot(121)
        plt.semilogy(1/var_flat, label="ML"+add)
        plt.legend(loc=0)
        plt.xlabel('Coefficient')
        plt.ylabel('Precision $\lambda$')
        plt.xlim((0, 63))

        plt.subplot(122)
        plt.imshow(1/llh_var[digit,mixture], interpolation='nearest')
        plt.xlabel("Likelihood precision $\lambda'$")
        plt.colorbar()
    plt.show()
Beispiel #6
0
def plotHousing(impression):
    """
    生成房价随时间变化的图标
    """
    f = open("midWestHousingPrices.txt", 'r')
    #文件每一行是年季度价格
    labels, prices = [], []
    for line in f:
        year, quarter, price = line.split()
        label = year[2:4] + "\n Q" + quarter[1]
        labels.append(label)
        prices.append(float(price)/1000)
    #柱的X坐标
    quarters = np.arange(len(labels))
    #柱宽
    width = 0.5
    if impression == 'flat':
        plt.semilogy()
    plt.bar(quarters, prices, width, color='r')
    plt.xticks(quarters + width / 2.0, labels)
    plt.title("美国中西部各州房价")
    plt.xlabel("季度")
    plt.ylabel("平均价格($1000)")

    if impression == 'flat':
        plt.ylim(10, 10**3)
    elif impression == "volatile":
        plt.ylim(180, 220)
    elif impression == "fair":
        plt.ylim(150, 250)
    else:
        raise ValueError("Invalid input.")
Beispiel #7
0
    def plotFittingResults(self):
        """
        Plot results of Rmax optimization procedure and best fit of the experimental data
        """
        _listFitQ = [tmp.getValue() for tmp in self.getDataOutput().getScatteringFitQ()]
        _listFitValues = [tmp.getValue() for tmp in self.getDataOutput().getScatteringFitValues()]
        _listExpQ = [tmp.getValue() for tmp in self.getDataInput().getExperimentalDataQ()]
        _listExpValues = [tmp.getValue() for tmp in self.getDataInput().getExperimentalDataValues()]

        #_listExpStdDev = None
        #if self.getDataInput().getExperimentalDataStdDev():
        #    _listExpStdDev = [tmp.getValue() for tmp in self.getDataInput().getExperimentalDataStdDev()]
        #if _listExpStdDev:
        #    pylab.errorbar(_listExpQ, _listExpValues, yerr=_listExpStdDev, linestyle='None', marker='o', markersize=1,  label="Experimental Data")
        #    pylab.gca().set_yscale("log", nonposy='clip')
        #else:         
        #    pylab.semilogy(_listExpQ, _listExpValues, linestyle='None', marker='o', markersize=5,  label="Experimental Data")

        pylab.semilogy(_listExpQ, _listExpValues, linestyle='None', marker='o', markersize=5, label="Experimental Data")
        pylab.semilogy(_listFitQ, _listFitValues, label="Fitting curve")
        pylab.xlabel('q')
        pylab.ylabel('I(q)')
        pylab.suptitle("RMax : %3.2f. Fit quality : %1.3f" % (self.getDataInput().getRMax().getValue(), self.getDataOutput().getFitQuality().getValue()))
        pylab.legend()
        pylab.savefig(os.path.join(self.getWorkingDirectory(), "gnomFittingResults.png"))
        pylab.clf()
def testPlotFrequencyDomain():
	filename = baseFilename % 0
	
	rawData = dataImport.readADSFile(filename)
	rawSps = 32000
	downSampled = _downSample(rawData, rawSps)
	downSampledLinear = _downSampleLinearInterpolate(rawData, rawSps)
	rawTimes = range(len(rawData))
	times = [float(x) * rawSps / samplesPerSecond for x in range(len(downSampled))]
	
	#pylab.plot(times, downSampled)
	#pylab.plot(rawTimes, rawData)
	#pylab.plot(times, downSampledLinear)
	pylab.show()
	
	index = 0
	fdat = applyTransformsToWindows(getFFTWindows(downSampled), True)[index]
	fdatLin = applyTransformsToWindows(getFFTWindows(downSampledLinear), True)[index]
	#print [str(x) for x in zip(fdat, fdatLin)]
	
	frequencies = [i * samplesPerSecond / windowSize for i in range(len(fdat))]
	
	pylab.semilogy(frequencies, fdat)
	pylab.semilogy(frequencies, fdatLin)
	pylab.grid(True)
	pylab.show()
Beispiel #9
0
def CCDF(G,
         gType='loglog',
         fmt='',
         xlabel='Degree, k',
         ylabel='Pr(K>=k)',
         title=None,
         **kwargs):
    degs = nx.degree(G)
    kmax = 0
    karr = []
    for _, k in degs:
        karr.append(k)
        if (k > kmax):
            kmax = k
    c, b = np.histogram(karr, bins=[i for i in range(kmax + 2)], density=True)
    a = np.cumsum(c)
    a = np.insert(a, 0, 0)
    if (gType == 'loglog'):
        plt.loglog(b[1:-1], 1 - a[1:-1], fmt, **kwargs)
    elif (gType == 'semilogx'):
        plt.semilogx(b[1:-1], 1 - a[1:-1], fmt, **kwargs)
    elif (gType == 'semilogy'):
        plt.semilogy(b[1:-1], 1 - a[1:-1], fmt, **kwargs)
    elif (gType == 'linear'):
        plt.plot(b[1:-1], 1 - a[1:-1], fmt, **kwargs)
    else:
        raise Exception(
            'gType was specified incorrectly. Please specify loglog, semilogx, semilogy, or linear.'
        )
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.show()
    return
Beispiel #10
0
def flip_plot(min_exp, max_exp):
    """Assumes min_exp and max_exp positive integers; min_exp < max_exp
    Plots results of 2**min_exp to 2**max_exp coin flips"""
    ratios = []
    diffs = []
    xAxis = []
    for exp in range(min_exp, max_exp + 1):
        xAxis.append(2 ** exp)
    for flip_count in xAxis:
        head_count = 0
        for _ in range(flip_count):
            if random.random() < 0.5:
                head_count += 1
        tail_count = flip_count - head_count
        ratios.append(head_count / float(tail_count))
        diffs.append(abs(head_count - tail_count))

    pylab.title('Difference Between Heads and Tails')
    pylab.xlabel('Number of Flips')
    pylab.ylabel('Abs(#Heads - #Tails)')
    pylab.rcParams['lines.markersize'] = 10
    pylab.semilogx()
    pylab.semilogy()
    pylab.plot(xAxis, diffs, 'bo')
    pylab.figure()
    pylab.title('Heads/Tails Ratios')
    pylab.xlabel('Number of Flips')
    pylab.ylabel('Heads/Tails')
    pylab.plot(xAxis, ratios)
Beispiel #11
0
def demo():
    '''
    Load and plot a few CIB spectra.
    '''

    # define ell array.
    l = np.arange(100,4000)

    # get dictionary of CIBxCIB spectra.
    cl_cibcib = get_cl_cibcib(l)

    # plot
    import matplotlib.pylab as pl
    pl.ion()
    lw=2
    fs=18
    leg = []
    pl.clf()
    for band in ['857','545','353']:
        pl.semilogy(l, cl_cibcib['545',band],linewidth=lw)
        leg.append('545 x '+band)
    pl.xlabel(r'$\ell$',fontsize=fs)
    pl.ylabel(r'$C_\ell^{TT, CIB} [\mu K^2]$',fontsize=fs)
    pl.ylim(5e-2,6e3)
    pl.legend(leg, fontsize=fs)
Beispiel #12
0
def plottingTimeConsumptions(titleString, trialedFuncs, timesToPlot):
    """ titleString...String to be displayed in Title
    trialedFuncs...list of the strings of the trialed functions
    timesToPlot...dim [numberTrials, numberFunctions]
    """
#    plt.figure()
    for cnt in range(len(trialedFuncs)):
        if 'vectorized' in trialedFuncs[cnt]:
            lineStyle = '--'
        elif 'faverage' in trialedFuncs[cnt]:
            lineStyle = '--'
        else:
            lineStyle = '-'
        plt.semilogy(timesToPlot[cnt], label=trialedFuncs[cnt], linestyle=lineStyle, marker='o')
    plt.xticks(range(len(timesToPlot[1])))
    plt.xlabel('trials [1]')
    plt.ylabel('Time per Trial [s]')
    plt.grid(which='major')
    plt.grid(which='minor', linestyle='--')
    plt.title(titleString)
    yMin, yMax = plt.ylim()
    newYMin = 10 ** np.floor(np.log10(yMin))
    plt.ylim(newYMin, yMax)
    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
    plt.show()
Beispiel #13
0
def plot_misfit_curves(items, threshold, threshold_is_upper_limit,
                       logarithmic, component, pretty_misfit_name, filename):
    plt.close()

    crossing_periods = []
    crossing_values = []

    for item in items:
        if logarithmic:
            plt.semilogy(item["periods"], item["misfit_values"])
        else:
            plt.plot(item["periods"], item["misfit_values"])

        # Find the threshold.
        point = rightmost_threshold_crossing(
            item["periods"], item["misfit_values"], threshold,
            threshold_is_upper_limit)
        crossing_periods.append(point[0])
        crossing_values.append(point[1])

    plt.title("%s misfit curves for component %s" % (
        pretty_misfit_name, component))
    plt.xlabel("Lowpass Period [s]")
    plt.ylabel("%s" % pretty_misfit_name)

    x = items[0]["periods"][0] - 0.5, items[0]["periods"][-1] + 0.5

    plt.hlines(threshold, x[0], x[1],
               linestyle="--", color="0.5")
    plt.scatter(crossing_periods, crossing_values, color="0.2", s=10,
                zorder=5)
    plt.xlim(*x)

    plt.savefig(filename)
def plot(coefs_files, digit=0, mixture=0, axis=0):
    import numpy as np
    import matplotlib.pylab as plt
    import amitgroup as ag

    for coefs_file in coefs_files:
        coefs_data = np.load(coefs_file)
        var = coefs_data['prior_var']
        samples = coefs_data['samples']
        llh_var = coefs_data['llh_var']

        var_flat = ag.util.wavelet.smart_flatten(var[digit, mixture, axis])
        last_i = len(var_flat) - 1
        plt.xlim((0, last_i))

        #imdef = ag.util.DisplacementFieldWavelet((32, 32), 'db4', penalty=100

        if len(coefs_files) == 1:
            add = ""
        else:
            add = " ({0})".format(coefs_file.name)

        plt.subplot(121)
        plt.semilogy(1 / var_flat, label="ML" + add)
        plt.legend(loc=0)
        plt.xlabel('Coefficient')
        plt.ylabel('Precision $\lambda$')
        plt.xlim((0, 63))

        plt.subplot(122)
        plt.imshow(1 / llh_var[digit, mixture], interpolation='nearest')
        plt.xlabel("Likelihood precision $\lambda'$")
        plt.colorbar()
    plt.show()
def main():
    t1 = time()
    assert 0, "This example needs easily accessible I and F"

    imdef, info = ag.stats.bernoulli_model(F, I, stepsize_scale_factor=1.0, penalty=0.1, rho=1.0, last_level=4, tol=0.001, \
                                  start_level=2, wavelet='db2')
    Fdef = imdef.deform(F)
    t2 = time()

    print "Time:", t2-t1

    PLOT = True
    if PLOT:
        import matplotlib.pylab as plt
        x, y = imdef.meshgrid()
        Ux, Uy = imdef.deform_map(x, y) 

        ag.plot.deformation(F, I, imdef)

        #Also print some info before showing
        print "Iterations (per level):", info['iterations_per_level'] 
        
        plt.show()

        # Print 
        plt.semilogy(info['costs'])
        plt.show()
Beispiel #16
0
def plot_cifar10():

    with open("log/boomnet_log_cifar100.json", "r") as f:
        d = json.load(f)

    fig = plt.figure()

    train_erro = 1 - np.array(d["train_loss"])[:, 1]
    test_erro = 1 - np.array(d["test_loss"])[:, 1]
    
    train_loss = np.array(d["train_loss"])[:, 0]
    test_loss = np.array(d["test_loss"])[:, 0]

    ax1 = fig.add_subplot(111)
    plt.plot(100*train_erro, color="lightsalmon", linewidth=1,label='train erro(%)')
    plt.plot(100*test_erro, color="lightskyblue", linewidth=1,label='test erro(%)')
    plt.ylim(0,50)
    ax1.set_ylabel('erro rate(%)')
    

    ax2 = ax1.twinx()
    plt.semilogy(train_loss,'--', color="salmon", linewidth=1,label='train logloss')
    plt.semilogy(test_loss, '--',color="skyblue", linewidth=1,label='test logloss')
    plt.ylim(0.01,10)
    ax2.set_ylabel('logloss')
    lines,labels = ax1.get_legend_handles_labels()
    lines2,labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines+lines2,labels+labels2,loc=0)



    plt.grid()
    plt.show()
    plt.clf()
    plt.close()
def plot_nh_s(chosen_top_k,
              datasets,
              input_folder,
              output_folder,
              fig_width=6.5,
              fig_height=6.0):

    plt_helper = PlotHelper(plt, fig_width, fig_height)
    plt_helper.plot_subplots_adjust(top_space=0.8, hspace=0.37)

    method = 'NH_LCCS_Sampling'

    for di, dataset in enumerate(datasets):
        ax = plt.subplot(1, len(datasets), di + 1)
        ax.set_xlabel(r'Recall (%)')
        if di == 0:
            ax.set_ylabel(r'Query Time (ms)')
        ax.set_title('%s' % dataset_labels_map[dataset])

        # get file name for this method on this dataset
        filename = get_filename(input_folder, dataset, method)
        print(filename, method, dataset)

        fix_m = 256
        data = []
        for record in parse_res(filename, chosen_top_k):
            # print(record)
            m = get_m(record)
            s = get_s(record)
            cand = get_cand(record)
            time = get_time(record)
            recall = get_recall(record)

            if m == fix_m:
                print(m, s, cand, time, recall)
                data += [[m, s, cand, time, recall]]
        data = np.array(data)

        ss = [1, 2, 4, 8]
        maxy = -1e9
        miny = 1e9
        for color, marker, s in zip(method_colors, method_markers, ss):
            data_mp = data[data[:, 1] == s]
            # print(m, data_mp)

            plt.semilogy(data_mp[:, -1],
                         data_mp[:, -2],
                         marker=marker,
                         label='$\lambda=%d d$' % (s) if di == 0 else "",
                         c=color,
                         markerfacecolor='none',
                         markersize=7)
            miny = min(miny, np.min(data_mp[:, -2]))
            maxy = max(maxy, np.max(data_mp[:, -2]))
        plt.xlim(0, 100)
        # print(dataset, distance, miny, maxy)
        plt_helper.set_y_axis_log10(ax, miny, maxy)

    plt_helper.plot_fig_legend(ncol=4)
    plt_helper.plot_and_save(output_folder, 'varying_nh_s')
Beispiel #18
0
def unteraufgabe_d():
    n = np.arange(2,21,2)
    xs = [x02,x04,x06,x08,x10,x12,x14,x16,x18,x20]
    f = lambda x: np.sin(10*x*np.cos(x))

    residuals = np.zeros_like(n,dtype=np.floating)
    condition = np.ones_like(n,dtype=np.floating)

    for i, x in enumerate(xs):
        b = f(x)
        A = interp_monom(x)
        alpha = solve(A,b)
        residuals[i] = norm(np.dot(A,alpha) - b)
        condition[i] = cond(A)

    plt.figure()
    plt.plot(n,residuals,"-o")
    plt.grid(True)
    plt.xlabel(r"$n$")
    plt.ylabel(r"$\|A \alpha - b\|_2$")
    plt.savefig("residuals.eps")

    plt.figure()
    plt.semilogy(n,condition,"-o")
    plt.grid(True)
    plt.xlabel(r"$n$")
    plt.ylabel(r"$\log(\mathrm{cond}(A))$")
    plt.savefig("condition.eps")
Beispiel #19
0
def demo():
    '''
    Load and plot a few CIB spectra.
    '''

    # define ell array.
    l = np.arange(100, 4000)

    # get dictionary of CIBxCIB spectra.
    cl_cibcib = get_cl_cibcib(l)

    # plot
    import matplotlib.pylab as pl
    pl.ion()
    lw = 2
    fs = 18
    leg = []
    pl.clf()
    for band in ['857', '545', '353']:
        pl.semilogy(l, cl_cibcib['545', band], linewidth=lw)
        leg.append('545 x ' + band)
    pl.xlabel(r'$\ell$', fontsize=fs)
    pl.ylabel(r'$C_\ell^{TT, CIB} [\mu K^2]$', fontsize=fs)
    pl.ylim(5e-2, 6e3)
    pl.legend(leg, fontsize=fs)
Beispiel #20
0
def unteraufgabe_g():
    # Sampling punkte
    x = np.linspace(0.0,1.0,1000)
    N = np.arange(2,16)

    LU = np.ones_like(N,dtype=np.floating)
    LT = np.ones_like(N,dtype=np.floating)

    # Approximiere Lebesgue-Konstante
    for i,n in enumerate(N):
        ################################################################
        #
        # xU = np.linspace(0.0,1.0,n)
        #
        # LU[i] = ...
        #
        # j = np.arange(n+1)
        # xT = 0.5*(np.cos((2.0*j+1.0)/(2.0*(n+1.0))*np.pi) + 1.0)
        #
        # LT[i] = ...
        #
        ################################################################
        continue

    # Plot
    plt.figure()
    plt.semilogy(N,LU,"-ob",label=r"Aequidistante Punkte")
    plt.semilogy(N,LT,"-og",label=r"Chebyshev Punkte")
    plt.grid(True)
    plt.xlim(N.min(),N.max())
    plt.xlabel(r"$n$")
    plt.ylabel(r"$\Lambda^{(n)}$")
    plt.legend(loc="upper left")
    plt.savefig("lebesgue.eps")
Beispiel #21
0
def main():
    t1 = time()
    assert 0, "This example needs easily accessible I and F"

    imdef, info = ag.stats.bernoulli_model(F, I, stepsize_scale_factor=1.0, penalty=0.1, rho=1.0, last_level=4, tol=0.001, \
                                  start_level=2, wavelet='db2')
    Fdef = imdef.deform(F)
    t2 = time()

    print "Time:", t2 - t1

    PLOT = True
    if PLOT:
        import matplotlib.pylab as plt
        x, y = imdef.meshgrid()
        Ux, Uy = imdef.deform_map(x, y)

        ag.plot.deformation(F, I, imdef)

        #Also print some info before showing
        print "Iterations (per level):", info['iterations_per_level']

        plt.show()

        # Print
        plt.semilogy(info['costs'])
        plt.show()
Beispiel #22
0
def plotAnimProfil(args):

    field = "field.d"

    args.folder = "../krusty/Quartz/data/"
    data = profile.readAllProfil(folder="%sprofile/%s/" % (args.folder, field))
    t = amr.gettmap(folder=args.folder)
    unit = physique.Cell2Meter(args) / 1000

    args.folder = "../data/strom_2e6_SN/"
    data2 = profile.readAllProfil(folder="%sprofile/%s/" %
                                  (args.folder, field))
    t2 = amr.gettmap(folder=args.folder)
    unit2 = physique.Cell2Meter(args) / 1000

    i = 0
    folder_out = 'img/'
    for i in range(len(data)):
        plt.clf()

        plt.semilogy(np.multiply(data[i][0], unit),
                     data[i][1],
                     label="with SN")
        plt.semilogy(np.multiply(data2[i][0], unit2),
                     data2[i][1],
                     label="without SN")

        plt.ylabel(r'delta rho')
        plt.xlabel(r'R (kpc)')
        plt.title("%s Myr" % "{:.2f}".format(t[i]))

        plt.ylim(1e-1, 3)
        plt.legend()
        plt.savefig(folder_out + str(i))
Beispiel #23
0
	def POD_energy(self):
		snaps = np.append(self.snap_Q,self.snap_P,0)
		print(snaps.shape)
		snaps = self.X*snaps;

		U,s,V = np.linalg.svd(snaps, full_matrices=True)
		plt.semilogy(s)
		plt.show()
Beispiel #24
0
def PlotFit(traj_diff, p):
    """
    Given a trajectory difference and p=(lyapExponent, lyapPrefactor),
    plot |traj_diff| and the fit on a semilog y axis.
    """
    
    pylab.plot(scipy.fabs(traj_diff), 'b-', linewidth=4)
    fit = scipy.exp(p[1] + p[0] * scipy.arange(len(traj_diff)))
    pylab.semilogy(fit, 'r-', linewidth=2)
    pylab.show()
Beispiel #25
0
def pp_ps(d, title=""):
    fig=mkfig()
    ax=fig.add_subplot(111)
    xvar = numpy.arange(d.shape[0])-(d.shape[0]+1)/2
    pylab.semilogy(xvar,d)
    ax.set_xlabel("Delay ( %f ns)" % (1e9/(100e6/1024) / 128,))
    ax.set_ylabel("Absolute mean cross-spectral power density ")
    ax.set_title("PowerSpectrum "+title )
    ax.xaxis.set_ticks_position('bottom')
    ax.grid()
def kmeans_graph(k, newClusters):
    plt.figure()
    plt.title('Clustering Result, k = %i'%(k+1))
    plt.xlabel('Number of counties in cluster')
    plt.ylabel('Population Count')
    plt.semilogy()
    colors = ['ro', 'bo', 'go', 'yo', 'r^', 'b^']
    for i, v in enumerate(newClusters):
        print i, v
        plt.plot(v, colors[i])
Beispiel #27
0
    def viz(self, names, title=None, lw=None, save=False, savename=None):
        '''
        NAMES can be
        a name: 'mary'
        space-separated names: 'mary james', or
        a list of names: ['mary','james'].
        Any capitalization works.
        '''
        pl.clf()
        leg = []
        colors = colorz()
        if isinstance(names, basestring):
            names = names.split()
        if lw is None: lw = 4.0 - 0.3 * np.log(len(names))
        for iname, name_ in enumerate(names):
            name = name_.lower().capitalize()
            if name not in self.data:
                print '%s is not in database.' % name
                return
            leg.append(name)
            v = self.data[name]
            years = np.sort(v.keys())
            rank = np.array([v[year]['rank'] for year in years])
            cnt = np.array([v[year]['cnt'] for year in years])

            # rank
            pl.subplot(1, 2, 1)
            pl.semilogy(years, rank, '-', linewidth=lw, color=colors[iname])
            pl.ylabel('Rank')
            pl.ylim(1e5, 1)
            pl.grid('on')

            # percentage
            pl.subplot(1, 2, 2)
            pl.semilogy(years,
                        cnt * 100,
                        '-',
                        linewidth=lw,
                        color=colors[iname])
            pl.ylabel('Share (%)')
            pl.ylim(1e-4, 10)
            pl.grid('on')

        # legend & title
        for i in [1, 2]:
            pl.subplot(1, 2, i)
            pl.legend(leg, loc='lower left', fontsize=11, framealpha=0.9)
            if title is not None:
                pl.title(title)
        pl.show()
        if save:
            if savename is None:
                savename = '%s.png' % ('_'.join(names))
            print 'saving %s' % savename
            pl.savefig(savename)
Beispiel #28
0
def contagion_analysis(path):

    figs = []

    #[x_init_m,x_final_m,t_converge,x_init_m_ER,x_final_m_ER,t_converge_ER,rhos,networks,mu0s] = load_data(paths)
    [
        x_init_m, x_final_m, t_converge, x_init_m_ER, x_final_m_ER,
        t_converge_ER, rhos, networks, mu0s
    ] = load_data_new(paths)

    rho_m = np.around(np.mean(rhos), decimals=2)
    rho_std = np.around(np.std(rhos), decimals=3)

    #pl.rc('text', usetex=True)

    ER_label = 'ER:'  # '+ r"$\rho = $" + str(rho_m)+r"$ \pm$ " + str(rho_std)

    f = make_hist(x_final_m[:, 0], x_final_m_ER[:, 0], 'Average final action',
                  ER_label)
    figs.append(f)
    f = make_hist(t_converge[:, 0], t_converge_ER[:, 0], 'Convergence time',
                  ER_label)
    figs.append(f)

    [contagion_frq, cond_contagion_frq_low,
     cond_contagion_frq_high] = calc_prob_contagion(x_final_m[:, 1:],
                                                    x_init_m[:, 1:])
    [contagion_frq_ER, cond_contagion_frq_low_ER,
     cond_contagion_frq_high_ER] = calc_prob_contagion(x_final_m_ER[:, 1:],
                                                       x_init_m_ER[:, 1:])

    #contagion_prob = compute_contagion(x_final_m[:,0])
    #contagion_prob_ER = compute_contagion(x_final_m_ER[:,0])

    xinits = x_init_m[1, 1:]

    f = pl.figure()
    pl.plot(xinits, contagion_frq, '-bo', label='endogenous')
    pl.plot(xinits, contagion_frq_ER, '--rD', label=ER_label)
    leg = pl.legend(loc=2, fancybox=True)
    leg.get_frame().set_alpha(0.5)
    pl.xlabel('average initial action')
    pl.ylabel('Probability of contagion')
    figs.append(f)

    f = pl.figure()
    pl.semilogy(xinits, contagion_frq, '-bo', label='endogenous')
    pl.semilogy(xinits, contagion_frq_ER, '--rD', label=ER_label)
    leg = pl.legend(loc=2, fancybox=True)
    leg.get_frame().set_alpha(0.5)
    pl.xlabel('average initial action')
    pl.ylabel('Probability of contagion')
    figs.append(f)

    return figs
Beispiel #29
0
def p1():
    from scipy.sparse import diags

    Nv = 2**np.arange(3, 17)

    for n in Nv:
        h = 2 * pi / n
        x = -pi + h * np.arange(n)
        u = np.exp(np.sin(x))
        uprime = np.cos(x) * u  #du/dx

        d1 = np.array([2 / 3.])
        d2 = 1 / 12. + np.zeros(2)
        d3 = 1 / 12. + np.zeros(n - 2)
        d4 = 2 / 3. + np.zeros(n - 1)
        D=diags([d1,-d2,d3,-d4,d4,-d3,d2,-d1],\
                [-n+1,-n+2,-2,-1,1,2,n-2,n-1])
        #print np.round(D.toarray(),decimals=2)

        D = D / h

        error = np.linalg.norm(D * u - uprime)
        pl.loglog(n, error, 'o', c='#1f77b4')

        d1 = np.array([0.5])
        d2 = 0.5 + np.zeros(n - 1)
        D = diags([d1, -d2, d2, -d1], [-n + 1, -1, 1, n - 1])

        D = D / h

        error = np.linalg.norm(D * u - uprime)
        pl.loglog(n, error, 'o', c='#2ca02c')

        #d=[np.zeros(n-i-1)+1./(i+1) for i in range(n-1)]
        #diag=[d1 if i%2 else -d1 for i, d1 in enumerate(reversed(d))]+\
        #     [-d1 if i%2 else d1 for i, d1 in enumerate(d)]
        #loc=[-i for i in range(n-1,0,-1)]+range(1,n)
        #D=diags(diag,loc).toarray()
        #if n==16: print np.round(D.toarray(), decimals=3)

        #D=D/h

        #error=np.linalg.norm(np.dot(D,u)-uprime)
        #pl.loglog(n,error,'o',c='#bcbd22')

    pl.semilogy(Nv, 1. / Nv**4, '--', c='#1f77b4')
    pl.semilogy(Nv, 1. / Nv**2, '--', c='#2ca02c')
    pl.title('Convergence of  2- & 4-th order finite differences')
    pl.xlabel('N')
    pl.grid(ls='--', which='both')
    pl.text(20, 5e-8, r'N$^{-4}$', fontsize=14)
    pl.text(2000, 1e-6, r'N$^{-2}$', fontsize=14)
    pl.ylabel('error')
    pl.show()
def testFreeFreeEnsembleSpectrumTemperature():
    T = numpy.array([1, 10, 100.0])
    energies = numpy.linspace(1, 10, 10)
    for t in T:

        spectrum = freeFreeThermalSpectrum(1.0, t, energies)

        pylab.semilogy(energies, spectrum, label='T = %.2f' % t)

    pylab.legend(loc=1)
    pylab.show()
def makePlot(xVals, yVals, title, xLabel, yLabel, style, logX=False, logY=False):
    """用给定的标题和标签绘制xVals和yVals
    """
    plt.figure()
    plt.title(title)
    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.plot(xVals, yVals, style)
    if logX:
        plt.semilogx()
    if logY:
        plt.semilogy()
Beispiel #32
0
def make_plot(x_vals, yVals, title, xLabel, yLabel, style, newFig=False, logX=False, logY=False):
    """Plots x_vals vs. yVals with supplied titles and labels."""
    if newFig:
        pylab.figure()
    pylab.title(title)
    pylab.xlabel(xLabel)
    pylab.ylabel(yLabel)
    pylab.plot(x_vals, yVals, style)
    if logX:
        pylab.semilogx()
    if logY:
        pylab.semilogy()
Beispiel #33
0
def plot_misfit_curves(items, threshold, threshold_is_upper_limit,
                       logarithmic, component, pretty_misfit_name, filename):
    plt.close()

    crossing_periods = []
    crossing_values = []
    
    misfit_all = []
    for item in items:
        if logarithmic:
            plt.semilogy(item["periods"], item["misfit_values"])
        else:
            plt.plot(item["periods"], item["misfit_values"], color="blue", 
                     alpha=0.15, lw = 3)

        # Find the threshold.
        point = rightmost_threshold_crossing(
            item["periods"], item["misfit_values"], threshold,
            threshold_is_upper_limit)
        crossing_periods.append(point[0])
        crossing_values.append(point[1])

        misfit_all.append(item['misfit_values'])

    # compute mean and median of misfit for all stations at each filter period
    misfit_all= np.asarray(misfit_all)
    misfit_mean = misfit_all.mean(axis=0)
    misfit_std = misfit_all.std(axis=0)
    misfit_median = np.median(misfit_all, axis=0)
 
    plt.plot(np.asarray(items[0]["periods"]), misfit_mean, color="red", 
             lw = 2, label='mean')
    # Standard deviation doesn't make sense for a non-normal distribution
    #plt.errorbar(np.asarray(items[0]["periods"]), misfit_mean, misfit_std,
    #         lw = 2, zorder=3)
    plt.plot(np.asarray(items[0]["periods"]), misfit_median, color="Chartreuse", 
             lw = 2, label='median', linestyle="--")

    plt.title("%s misfit curves for component %s" % (
        pretty_misfit_name, component))
    plt.xlabel("Lowpass Period [s]")
    plt.ylabel("%s" % pretty_misfit_name)

    x = items[0]["periods"][0] - 0.5, items[0]["periods"][-1] + 0.5

    plt.hlines(threshold, x[0], x[1],
               linestyle="--", color="0.5")
    plt.scatter(crossing_periods, crossing_values, color="orange", s=10,
                zorder=5, alpha=0.3)
    plt.xlim(*x)

    plt.savefig(filename)
Beispiel #34
0
def plotFreq(data_samples,
             xlabel_str,
             ylabel_str,
             fig_name='cdf.pdf',
             xais_range=None,
             yaxis_range=None,
             xtick_gap=None,
             ytick_gap=None,
             shrinkScale=None,
             N=1000,
             yaxis_log=False):
    # this create the kernel, given an array it will estimate the probability over that values
    # kde = gaussian_kde( data_samples )
    # these are the values over wich your kernel will be evaluated
    # dist_space = np.linspace( min(data_samples), max(data_samples), N )
    # cdf=np.cumsum(kde(dist_space))
    # cdf/=cdf[-1] #normalized
    # print(min(data_samples),max(data_samples))
    # plot the results
    data_samples = np.array(data_samples)
    sample_bins = np.arange(
        np.amin(data_samples) - 0.5,
        np.amax(data_samples) + 0.5, 1)
    data_hist, data_bin = np.histogram(data_samples, sample_bins)
    # shrinkscale: make the y num become small, for example: 50000->500
    if shrinkScale is not None:
        data_hist /= shrinkScale
    fig = plt.figure(figsize=(8, 6))
    # plt.plot(dist_space, cdf,markersize=0)  #pdf line with no markers
    if yaxis_log:
        plt.semilogy(data_bin[0:len(data_bin) - 1] + 0.5, data_hist, lw=2)
    else:
        plt.plot(data_bin[0:len(data_bin) - 1] + 0.5,
                 data_hist,
                 lw=2,
                 color='b')
    plt.xlabel(xlabel_str)
    plt.ylabel(ylabel_str)
    if xais_range is not None:
        plt.xlim(xais_range[0], xais_range[1])
    if yaxis_range is not None:
        plt.ylim(yaxis_range[0], yaxis_range[1])
    if xtick_gap is not None:
        x_tick = np.arange(xais_range[0], xais_range[1] + xtick_gap, xtick_gap)
        plt.xticks(x_tick)
    if ytick_gap is not None:
        y_tick = np.arange(yaxis_range[0], yaxis_range[1] + ytick_gap,
                           ytick_gap)
        plt.yticks(y_tick)
    plt.savefig(join(WORK_PATH, fig_name))
    # plt.savefig(fig_name)
    plt.close(fig)
Beispiel #35
0
def visualize_progress(arch,
                       performance,
                       patch_size,
                       camera_name,
                       out_directory,
                       plot=False,
                       sampling_rate=100):
    from helpers import utils

    v_range = np.arange(0, sampling_rate * len(performance['ssim']),
                        sampling_rate)

    plt.figure(figsize=(16, 6))
    plt.subplot(2, 2, 1)
    plt.semilogy(performance['train_loss'], alpha=0.15)
    plt.plot(
        utils.ma_conv(performance['train_loss'],
                      np.maximum(10,
                                 len(performance['train_loss']) // 25)))
    plt.plot(v_range, np.array(performance['loss']), '.-', alpha=0.5)
    plt.ylabel('Loss')
    plt.legend(['loss (batch)', 'mov. avg loss (batch)', 'loss (valid.)'])

    if len(performance['loss']) > 10:
        n_tail = 5
        current = np.mean(performance['loss'][-n_tail:-1])
        previous = np.mean(performance['loss'][-(n_tail + 1):-2])
        vloss_change = abs((current - previous) / previous)
        plt.title('Validation loss change: {:.6f}'.format(vloss_change))

    plt.subplot(2, 2, 2)
    plt.plot(v_range, performance['ssim'], '.-', alpha=0.5)
    plt.ylabel('SSIM')

    plt.subplot(2, 2, 3)
    plt.plot(v_range, np.array(performance['psnr']), '.-', alpha=0.5)
    plt.ylabel('PSNR')

    plt.subplot(2, 2, 4)
    plt.semilogy(v_range, np.array(performance['dmse']), '.-', alpha=0.5)
    plt.ylabel('$\Delta$ MSE from last')

    plt.suptitle('{} for {} ({}px): PSNR={:.1f}, SSIM={:.2f}'.format(
        arch, camera_name, patch_size, performance['psnr'][-1],
        performance['ssim'][-1]))
    if plot:
        plt.show()
    else:
        plt.savefig(os.path.join(out_directory, 'progress.png'),
                    bbox_inches='tight',
                    dpi=150)
        plt.close()
Beispiel #36
0
    def viz(self, names, title=None, lw=None,
            save=False, savename=None):
        '''
        NAMES can be
        a name: 'mary'
        space-separated names: 'mary james', or
        a list of names: ['mary','james'].
        Any capitalization works.
        '''
        pl.clf()
        leg = []
        colors = colorz()
        if isinstance(names, basestring):
            names = names.split()
        if lw is None: lw = 4.0 - 0.3*np.log(len(names))
        for iname,name_ in enumerate(names):
            name = name_.lower().capitalize()
            if name not in self.data:
                print '%s is not in database.'%name
                return
            leg.append(name)
            v = self.data[name]
            years = np.sort(v.keys())
            rank = np.array([v[year]['rank'] for year in years])
            cnt = np.array([v[year]['cnt'] for year in years])

            # rank
            pl.subplot(1,2,1)
            pl.semilogy(years, rank, '-', linewidth=lw, color=colors[iname])
            pl.ylabel('Rank')
            pl.ylim(1e5,1)
            pl.grid('on')

            # percentage
            pl.subplot(1,2,2)
            pl.semilogy(years, cnt*100, '-', linewidth=lw, color=colors[iname])
            pl.ylabel('Share (%)')
            pl.ylim(1e-4,10)
            pl.grid('on')

        # legend & title
        for i in [1,2]:
            pl.subplot(1,2,i)
            pl.legend(leg, loc='lower left', fontsize=11, framealpha=0.9)
            if title is not None:
                pl.title(title)
        pl.show()
        if save:
            if savename is None:
                savename = '%s.png'%('_'.join(names))
            print 'saving %s'%savename
            pl.savefig(savename)
Beispiel #37
0
def main():
    """
    NAME
        lowes.py
    DESCRIPTION
        Plots Lowes spectrum for input IGRF-like file
    SYNTAX
       lowes.py [options]

    OPTIONS:
       -h prints help message and quits
       -f FILE  specify file name with input data
       -d date specify desired date
       -r read desired dates from file
       -n normalize to dipole term
    INPUT FORMAT:
        l m g h
    """
    norm=0
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        data=np.loadtxt(file)
        dates=[2000]
    elif '-d' in sys.argv:
        ind=sys.argv.index('-d')
        dates=[float(sys.argv[ind+1])]
    elif '-r' in sys.argv:
        ind=sys.argv.index('-r')
        dates=np.loadtxt(sys.argv[ind+1])
    if '-n' in sys.argv: norm=1
    if len(sys.argv)!=0 and '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    plt.semilogy()
    plt.xlabel('Degree (l)')
    plt.ylabel('Power ($\mu$T$^2$)')
    labels=[]
    for date in dates:
        if date!=2000: 
            gh=pmag.doigrf(0,0,0,date,coeffs=1)
            data=pmag.unpack(gh)
            Ls,Rs=pmag.lowes(data)
            labels.append(str(date))
        print(date,Rs[0])
        if norm==1: 
            Rs=old_div(np.array(Rs),Rs[0])
        #plt.plot(Ls,Rs,'ro')
        plt.plot(Ls,Rs,linewidth=2)
        plt.legend(labels,'upper right')
        plt.draw()
    input()
def errorVsDegree(ndegrees, npts=40, filename=None, **kwargs):
    degrees = numpy.array(range(ndegrees),dtype=float)
    errs = numpy.zeros_like(degrees)
    ntrials=10
    for i, deg in enumerate(degrees):
        for trial in range(ntrials):
            p, x, y, err = noisyDataPolyFit(deg, returnError=True)
            errs[i] = errs[i] + err
        errs[i] = errs[i]/ntrials
    plt.semilogy(degrees,errs,'go-')
    plt.xlabel('Degree')
    plt.ylabel('Squared Error')
    outputPlot(filename)
Beispiel #39
0
 def brightness(self):
     ax = plt.subplot(1, 1, 1)
     plt.title('Brightness')
     if np.max(self.data['lx'] < 0):
         plt.semilogy(self.dates, self.data['lx'], 'k')
     else:
         plt.plot(self.dates, self.data['lx'], 'k')
     self.plot_bar(ax)
     self.plot_xticks()
     plt.grid()
     plt.ylabel('lux')
     plt.savefig(os.path.join(self.plotpath, 'brightness.svg'))
     plt.close()
Beispiel #40
0
 def dust(self):
     ax = plt.subplot(1, 1, 1)
     plt.title('Dust')
     if np.max(self.data['dust']) / np.min(self.data['dust']) > 10.0:
         plt.semilogy(self.dates, self.data['dust'], 'k', drawstyle='steps')
     else:
         plt.plot(self.dates, self.data['dust'], 'k', drawstyle='steps')
     self.plot_bar(ax)
     self.plot_xticks()
     plt.grid()
     plt.ylabel('dust')
     plt.savefig(os.path.join(self.plotpath, 'dust.svg'))
     plt.close()
Beispiel #41
0
def plot_profile_fit(filename, merger, rmin=3, rmax=6):

    s = pynbody.load(filename)
    faceon(s)
    if merger: s = s.s[np.where(s.s['mass'] > .1)[0]]
    p = Profile(s.s, min=0, max=15, nbins=30)
    fit, chsq = fit_profile(p, expo, [1e9, 3], 'Msol kpc^-2', rmin, rmax)

    plt.figure()
    plt.plot(p['rbins'], p['density'].in_units('Msol kpc^-2'))
    overplot_fit(fit, expo)
    print((fit, chsq))
    plt.semilogy()
def clear(n, p, steps):
    """假定n和steps是正整数,p是浮点数,
    n是分子的初始数量
    p是分子被清除的概率
    steps是模拟的时间
    """
    numRemaining = [n]
    for t in range(1, steps+1):
        numRemaining.append(numRemaining[-1]*(1-p))
    plt.plot(numRemaining)
    plt.xlabel('Time')
    plt.ylabel('Molecules Remianing')
    plt.title('Clearance of Drug')
    plt.semilogy()
def inSampleErrorVsDegree(ndegrees, npts=40, filename=None, **kwargs):
    degrees = numpy.array(range(ndegrees),dtype=float)
    errs = numpy.zeros_like(degrees)
    ntrials=10
    for i, deg in enumerate(degrees):
        for trial in range(ntrials):
            p, x, y = noisyDataPolyFit(deg)
            fitfun = numpy.poly1d(p)
            errs[i] = errs[i] + sum((fitfun(x)-y)**2)
        errs[i] = errs[i]/ntrials
    plt.semilogy(degrees,errs,'go-')
    plt.xlabel('Degree')
    plt.ylabel('In-Sample Squared Error')
    outputPlot(filename)
 def __plotRMaxSearchResults(self):
     """
     Plot results of Rmax optimization procedure and best fit of the experimental data
     """
     cm = matplotlib.cm.get_cmap('cool')
     #pylab.rcParams['figure.figsize'] = 6, 5
     for itr in range(self.__iNbGnomSeries):
         rMaxList = []
         fitQualityList = []
         for idx in range(self.__rMaxDivide + 1):
             rMaxList.append(self.__xsGnomPlugin[(itr,idx)].getDataInput().getRMax().getValue())
             fitQualityList.append(self.__xsGnomPlugin[(itr,idx)].getDataOutput().getFitQuality().getValue())
         
         #pylab.plot(fitQualityList, marker='o', color=cm(1.0*itr/(self.__iNbGnomSeries-1)), markersize=5,  label="Iteration # %d" % itr)
         pylab.figure(self.__iNbGnomSeries+1, figsize=(6,5))
         pylab.plot(rMaxList, fitQualityList, linestyle='None', marker='o', color=cm(1.0*(itr+1)/self.__iNbGnomSeries), markersize=5,  label="Iteration # %d" % itr)
         pylab.figure(itr+1, figsize=(6,5))
         pylab.plot(rMaxList, fitQualityList, linestyle='-', marker='o', markersize=5,  label="Iteration # %d" % itr)
         pylab.xlabel(u"Rmax / \u00c5")
         pylab.ylabel('Fit quality')
         pylab.legend(loc=4)
         pylab.savefig(os.path.join(self.getWorkingDirectory(),"rMaxSearchResults-%d.png" % (itr+1)))
         
     pylab.figure(self.__iNbGnomSeries+1, figsize=(6,5))
     pylab.xlabel(u"Rmax / \u00c5")
     pylab.ylabel('Fit quality')
     pylab.suptitle("Optimized value of RMax : %3.2f   Maximal fit quality : %1.3f" % (self.__edPluginExecGnom.getDataInput().getRMax().getValue(),self.__edPluginExecGnom.getDataOutput().getFitQuality().getValue()))
     pylab.legend(loc=4)
     pylab.savefig(os.path.join(self.getWorkingDirectory(),"rMaxSearchResults.png"))
     pylab.clf()
     
     
     _listFitQ = [tmp.getValue() for tmp in self.__edPluginExecGnom.getDataOutput().getScatteringFitQ()]
     _listFitValues = [tmp.getValue() for tmp in self.__edPluginExecGnom.getDataOutput().getScatteringFitValues()]
     _listExpQ = [tmp.getValue() for tmp in self.__edPluginExecGnom.getDataInput().getExperimentalDataQ()]
     _listExpValues = [tmp.getValue() for tmp in self.__edPluginExecGnom.getDataInput().getExperimentalDataValues()]
      
     pylab.semilogy(_listExpQ, _listExpValues, linestyle='None', marker='o', markersize=5,  label="Experimental Data")
     pylab.semilogy(_listFitQ, _listFitValues, label="Fitting curve")
     pylab.xlabel(u"q / \u00c5$^{-1}$")
     pylab.ylabel('I(q)')
     pylab.suptitle("RMax : %3.2f   Fit quality : %1.3f" % (self.__edPluginExecGnom.getDataInput().getRMax().getValue(),self.__edPluginExecGnom.getDataOutput().getFitQuality().getValue()))
     pylab.legend()
     pylab.savefig(os.path.join(self.getWorkingDirectory(),"gnomFittingResults.png"))
     pylab.clf()
     
     if self.__bPlotFit:
         for gnomJob in self.__xsGnomPlugin.itervalues():
             gnomJob.plotFittingResults()  
         self.__edPluginExecGnom.plotFittingResults()
Beispiel #45
0
def chisq(df, fig=None, columns=['teff','logg','fe'], **kwargs):
    """Make a multi-panel plot of chisq
    """
    ncols = len(columns)
    if fig is None:
        fig,axL = plt.subplots(ncols=ncols)
    else:
        axL = fig.get_axes()

    i = 0
    for col in columns:
        plt.sca(axL[i])
        plt.semilogy()
        plt.plot(df[col],df['chisq'],**kwargs)
        i+=1
def PlotTrajectoryDifference(g, x1, x2, N):
    """
    Calls TrajectoryDifference to find the difference, then plots the 
    absolute value of the difference using 
        pylab.semilogy(scipy.fabs(dx)).
    (Given just one array, pylab assumes the other axis is just the
    index into the array.)

    Notice that the differences stop growing when they become of order 
    one (naturally). Don't use such long trajectories to calculate the 
    Lyapunov exponents: it will bias the results downward.
    """
    dx = TrajectoryDifference(g, x1, x2, N)
    pylab.semilogy(scipy.fabs(dx))
    pylab.show()
Beispiel #47
0
    def plot_fourier_transform(self, trange=None, scale='log', **kwrds):
        '''
         scale = 'log' logarithmic scale
         scale = 'lin' linear scale
        '''

        if trange is None:
            tarr = np.linspace(-0.1 / self.frequency, 7 * np.pi / self.frequency, 100)
        else:
            tarr = trange

        Axfft, Ayfft = self.make_fourier_transform(tarr)
        #energy = 2. * np.pi / trange * 4.1357 * 10**(-15)

        n = tarr.size
        time_step = tarr[1]-tarr[0]

        energy = np.fft.fftfreq(n, d=time_step) * 4.1357 * 10**(-15) 

        max_en = max(energy)
        for i in xrange(0, len(energy)):
           if energy[i]<0:
              energy[i] += 2.*max_en

        plt.subplot(1,2,1)
        if scale=='lin':
           plt.plot(energy, abs(Axfft),label='Ax_fft', **kwrds)
        elif scale=='log':
           try:
               plt.semilogy(energy, abs(Axfft), label='Ax_fft', **kwrds)
           except:
               pass
        plt.ylabel('Ax_fft')
        plt.xlabel('energy (eV)')

        plt.subplot(1,2,2)
        if scale=='lin':
           plt.plot(energy, abs(Ayfft),label='Ay_fft', **kwrds)
        elif scale=='log':
           try:
               plt.semilogy(energy, abs(Ayfft), label='Ay_fft', **kwrds)
           except:
               pass
        plt.ylabel('Ay_fft')
        plt.xlabel('energy (eV)')
Beispiel #48
0
def compare_unbiased_spectra():
    bands = [100, 143, 217, 'mb']
    pl.clf()
    leg=[]

    l_theory, cl_mb = get_cl_theory('mb')
    bl, l_bl = load_planck_bl('mb')
    cl_mb /= (bl**2.)
    
    for band in bands:
        l_theory, this_cl_theory = get_cl_theory(band)
        bl, l_bl = load_planck_bl(band)
        this_cl_theory /= (bl**2.)
        #pl.plot(l_theory, this_cl_theory/cl_mb, lw=2)
        pl.semilogy(l_theory, this_cl_theory, lw=2)        
        leg.append(band)
    pl.ylim(8e-16,1e-14)
    #pl.ylim(.1,2)
    pl.legend(leg)
Beispiel #49
0
    def plot_data(self):
        """Make a plot of the open connections and files vs time"""
        import matplotlib
        matplotlib.use('agg')
        import matplotlib.pylab as plt 
        matplotlib.style.use('fivethirtyeight')
        
        times = self.times
        data = self.data
        pid = self.pid

        plt.plot([time - times[0] for time in times], data['connections'], label='connections')
        plt.plot([time - times[0] for time in times], data['files'], label='files')
        plt.semilogy()
        plt.xlabel('time (s)')
        plt.ylabel('N open files')
        plt.legend(fontsize='small')
        plt.tight_layout()
        plt.savefig('{pid}.png'.format(pid=pid))
def plot_PCA_residuals(data, D=None, newfig=True, marker='o'):
    if D is None:
        D = shape(data)[1]
    p=doPCA(data, D, D)
    spec=zeros((D,1),Float)
    for i in range(1,D):
        spec[i] = norm(p.d[:i])
    res = transpose(sqrt(spec[-1]**2-spec**2)/spec[-1])[0]
    print "2-norm of PCA spectrum =", spec[-1]
    if newfig:
        figure()
        style='k'+marker
    else:
        style=marker
    semilogy(res,style)
##    title('PCA residuals')
    xlabel(r'$\rm{Dimension}$',fontsize=20)
    ylabel(r'$\rm{PCA \ residual}$',fontsize=20)
    return p, res
    def B(self, nxc, doping, temp):
        if 'blow_model' in self.vals.keys():
            self.change_model(self.vals['blow_model'])
            B = getattr(radmdls, model)(vals, temp)
            temp_tt = np.array([77, 90, 112, 170, 195, 249, 300])
            plt.figure()
            B_tt = np.array(
                [8.01e-14, 4.57e-14, 2.14e-14, 8.84e-15, 7.35e-15, 5.48e-15, 4.73e-15])
            plt.semilogy()
            plt.plot(temp_tt, B_tt, 'o')
            plt.plot(temp, B)
            plt.plot()

            B = getattr(
                radmdls, self.model + '_B')(self.vals, nxc, doping, temp, B)

        else:
            B = self.vals['B']

        return B
Beispiel #52
0
def plottingTimeConsumptionOverSpecificOrdinate(dirName, ordinate='nMics'):
    listOfFiles = glob.glob(dirName + '/*.sav')
    helpText, daten = readingInSAVES(listOfFiles[0])
    arrayOrdinate = np.zeros(len(listOfFiles))
    arrayTimeConsump = np.zeros((len(listOfFiles), len(daten[6])))
    cnt = 0
    for currentfile in listOfFiles:
        helpText, daten = readingInSAVES(currentfile)
        if ordinate == 'nMics':
            arrayOrdinate[cnt] = daten[3]
        arrayTimeConsump[cnt, :] = daten[6]
        cnt += 1
    indSorted = np.argsort(arrayOrdinate)
    plt.semilogy(arrayOrdinate[indSorted], arrayTimeConsump[indSorted, :], marker='o')#, label=trialedFuncs[cnt], linestyle=lineStyle, marker='o')
    plt.legend(daten[0])
    plt.grid(which='major')
    plt.grid(which='minor', linestyle='--')
    plt.xlabel(ordinate)
    plt.ylabel('Mean of Time per Trial [s] (normalized to faverage)')
    plt.title('Mean of TimeConsumption over ' + ordinate + '\n asd')
    plt.xticks(arrayOrdinate)
Beispiel #53
0
def kepmag_to_npix(kepmag,plot=False):
    fn = 'optimal_aperture_sizes.csv'
    dirn = os.path.dirname( os.path.dirname( __file__ ) )
    fn = os.path.join( dirn, 'data/', fn )
    df = pd.read_csv(fn)
    df['lognpix'] = np.log10(df.npix)
    p1 = np.polyfit(df.kepmag,df.lognpix,1)
    npixfit = 10**np.polyval(p1,kepmag) 

    if plot:
        plt.semilogy()
        df['npixfit'] = 10**np.polyval(p1,df.kepmag)
        df['npixfit_upper'] = df['npixfit'] * npix_scan_fac
        df['npixfit_lower'] = df['npixfit'] / npix_scan_fac
        plt.plot(df.kepmag,df.npix,'.')
        plt.plot(df.kepmag,df.npixfit)
        plt.plot(df.kepmag,df.npixfit_lower)
        plt.plot(df.kepmag,df.npixfit_upper)


    return npixfit
Beispiel #54
0
def plot_all(X, Y, Xlabel, Ylabels, loglist):

  y_offset = 0.02 #0.01

  no_plots = np.shape(Y)[0]
  for i in range(no_plots):
    panel = plt.subplot(no_plots, 1, i+1)
    position = panel.get_position()
    pos = position.get_points()
    #pos[0][0] = 0.13
    pos[0][1] = pos[0][1] + y_offset
    position.set_points(pos)
    panel.set_position(position)

    if loglist[i]:
      plt.semilogy(X, Y[i], 'ko')
    else:
      plt.plot(X, Y[i], 'ko')
    plt.ylabel(Ylabels[i])
  plt.xlabel(Xlabel)
  plt.show()
  return 0
Beispiel #55
0
    def plot_imposed_trace(self, y, tspan, imp_trace_values, sp_idx, diff_trace_ode, epsilon):
        """

        :param y: Solution of the differential equations
        :param tspan: time span of the solution of the differential equations
        :param imp_trace_values: Imposed trace values
        :param sp_idx: Index of the molecular species to be plotted
        :param diff_trace_ode: Maxmimum difference between the dynamic and the imposed trace
        :param epsilon: Order of magnitude difference between solution of ODE and imposed trace to consider species as
        passenger
        :return: Plot of the imposed trace and the dnamic solution
        """
        plt.figure()
        plt.semilogy(tspan, imp_trace_values, 'r--', linewidth=5, label='imposed')
        plt.semilogy(tspan, y['__s{0}'.format(sp_idx)], label='full')
        plt.legend(loc=0)
        plt.xlabel('time', fontsize=20)
        plt.ylabel('population', fontsize=20)
        if max(diff_trace_ode) < epsilon:
            plt.title(str(self.model.species[sp_idx]) + 'passenger', fontsize=20)
        else:
            plt.title(self.model.species[sp_idx], fontsize=20)
        plt.savefig('s%d' % sp_idx + '_imposed_trace' + '.png', bbox_inches='tight', dpi=400)