コード例 #1
0
ファイル: unittest_IBO.py プロジェクト: johnchia/IBO
    def test2DpyEI(self):
        
        f = lambda x: sum(sin(x))
        bounds = [[0., 5.], [0., 5.]]
        X = lhcSample(bounds, 5, seed=24)
        Y = [f(x) for x in X]

        kernel = GaussianKernel_ard(array([1.0, 1.0]))
        GP = GaussianProcess(kernel, X, Y)

        maxei = maximizeEI(GP, bounds)
        
        if False:
            figure(1)
            c0 = [(i/50.)*(bounds[0][1]-bounds[0][0])+bounds[0][0] for i in xrange(51)]
            c1 = [(i/50.)*(bounds[1][1]-bounds[1][0])+bounds[1][0] for i in xrange(51)]
            z = array([[GP.ei(array([i, j])) for i in c0] for j in c1])

            ax = plt.subplot(111)
            cs = ax.contour(c0, c1, z, 10, alpha=0.5, cmap=cm.Blues_r)
            plot([x[0] for x in X], [x[1] for x in X], 'ro')
            for i in xrange(len(X)):
                annotate('%2f'%Y[i], X[i])
            plot(maxei[1][0], maxei[1][1], 'ko')
            show()
コード例 #2
0
    def write_plots(self, take_every=1, show=False):
        pre = self.get_path_prefix()
        x, y, slope, yint = self.get_flux_xy(take_every)

        defaults = {'markersize':1, 'linewidth':0.1}
        fig = pl.figure()

        pl.plot(x, y, 'o',
                color='black', **defaults)

        fit_xs = np.array(pl.xlim())
        pl.plot(fit_xs, slope * fit_xs + yint,
                color='black', alpha=0.3, linewidth=1)

        pl.ylabel('Cumulative grains through aperture')
        pl.xlabel('Time')
        pl.title('Accumulation of grains vs time')

        pl.annotate('$Slope={:.1f}$'.format(slope),
            xy=(0.05, 0.95), xycoords='axes fraction', ha='left', va='top'
            , fontsize=14)
##        # Sim info:
##        pl.ylim(ymin=-2)  # make room for it
##        pl.annotate(info_for_naming, xy=(0.01, 0.03), xycoords='axes fraction', fontsize=12)
        pl.savefig('{}flux.png'.format(pre))
        pl.savefig('{}flux.svg'.format(pre))  # can take a while if complex plot
        if show:
            pl.show()
        else:
            pl.close()
コード例 #3
0
ファイル: malis_show.py プロジェクト: muqiao0626/znn-release
def disk_plot(e, D, DrTh, color='g'):
    # plot disk to illustrate the weight strength
    if np.all(e==0):
        return
    # rescale to 0-1
    re = rescale(e) * D
    y,x = np.nonzero(re)
    r = re[(y,x)]
    # sort the disk from small to large
    locs = np.argsort( r )
    y = y[ locs ]
    x = x[ locs ]
    r = r[ locs ]
    # eleminate the small disks
    y = y[ r > DrTh ]
    x = x[ r > DrTh ]
    r = r[ r > DrTh ]
    plt.scatter(x,y,r, c=color, alpha=0.6, linewidths=0)

    # print the maximum value
    dev = max(x.max(), y.max()) * 0.07
    plt.annotate("%d" % e.max(), xy=(x[-1],y[-1]),
                xytext=(x[-1]+dev, y[-1]+dev),
                color = 'white',
                arrowprops=dict(color='white',
                arrowstyle="->"))
コード例 #4
0
ファイル: image.py プロジェクト: rfahed/extProcess
def measure_psf(vignet, pixscale=1., show=False, mask_value=None):
    y, x = np.mgrid[-vignet.shape[0]/2:vignet.shape[0]/2, -vignet.shape[1]/2:vignet.shape[1]/2]*pixscale
    if mask_value :
        vignet = ma.masked_values(vignet, mask_value).filled(0)
    # Fit the data using astropy.modeling
    p_init=models.Gaussian2D(amplitude=vignet.max(), x_mean=0., y_mean=0.,
        x_stddev=2*pixscale, y_stddev=2*pixscale, theta=0, cov_matrix=None)
    fit_p = fitting.LevMarLSQFitter()

    p = fit_p(p_init, x, y, vignet)
    barycenter=measure_barycenter(vignet, pixscale=pixscale)
    
    # Plot the data with the best-fit model
    P.figure(figsize=(8, 2.5))
    P.subplot(1, 3, 1)
    P.imshow(vignet, origin='lower', interpolation='nearest', vmin=vignet.min(), vmax=vignet.max())
    P.title("Data")
    P.subplot(1, 3, 2)
    P.imshow(p(x, y), origin='lower', interpolation='nearest', vmin=vignet.min(), vmax=vignet.max())
    P.scatter(vignet.shape[0]/2, vignet.shape[1]/2,marker="+")
    P.annotate("({:.3f},{:.3f})".format(*barycenter), (vignet.shape[0]/3, vignet.shape[1]/3))
    P.title("Model - psf = {:.2f}".format(2.3548*np.mean([p.x_stddev.value, p.y_stddev.value])))
    P.subplot(1, 3, 3)
    P.imshow(vignet - p(x, y), origin='lower', interpolation='nearest', vmin=-vignet.max()/10,vmax=vignet.max()/10)
    P.title("Residual")
    P.tight_layout()
    if show :
        P.show()
    
    return p
コード例 #5
0
ファイル: Tri3.py プロジェクト: dengchangtao/ProyectoFEM
def Plot2DQuadGeometry(xyz,IEN,nodeId,elemId):
    for i in np.arange(IEN.shape[0]):
        x = np.zeros(4)
        y = np.zeros(4)
        index = IEN[i,0]
        x[0] = xyz[index-1,0]
        y[0] = xyz[index-1,1]
        index = IEN[i,1]
        x[1] = xyz[index-1,0]
        y[1] = xyz[index-1,1] 
        index = IEN[i,2]
        x[2] = xyz[index-1,0]
        y[2] = xyz[index-1,1]
        x_mean = np.mean(x[0:3])
        y_mean = np.mean(y[0:3])
        x[3] = x[0]
        y[3] = y[0]
        plt.plot(x,y,color='black')
        if elemId == True:
            plt.annotate(str(i+1),(x_mean,y_mean))
    for i in np.arange(xyz.shape[0]):
        if nodeId == True:
            plt.plot(xyz[:,0],xyz[:,1],'go')
            plt.annotate(str(i+1),(xyz[i,0],xyz[i,1]))
            for i in np.arange(xyz.shape[0]):
                x = xyz[i,0]
                y = xyz[i,1]        
コード例 #6
0
def plot_trajectory(mu_vector):
    data0 = mu_vector[:, 0]
    data1 = mu_vector[:, 1]
    labels = ["{0}".format(i) for i in xrange(len(mu_vector))]
    plt.scatter(data0[:, 0], data0[:, 1], color="red")
    plt.scatter(data1[:, 0], data1[:, 1], color="blue")
    for i in xrange(len(mu_vector)):
        plt.annotate(
            labels[i],
            (data0[i, 0], data0[i, 1]),
            fontsize=5,
            xytext=(-10, 20),
            textcoords="offset points",
            ha="right",
            va="bottom",
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
        plt.annotate(
            labels[i],
            (data1[i, 0], data1[i, 1]),
            fontsize=5,
            xytext=(-10, 20),
            textcoords="offset points",
            ha="right",
            va="bottom",
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
    plt.savefig("Mean_Trajectory.png")
    plt.show()
コード例 #7
0
ファイル: SciencePlots.py プロジェクト: ComPair/python
def nova_plot():

	erg2mev=624151.

	fig=plot.figure()
	yrange = [1e-6,2e-4]
	xrange = [1e-1,1e5]
	plot.fill_between([0.2,10e3],[yrange[1],yrange[1]],[yrange[0],yrange[0]],facecolor='yellow',interpolate=True,color='yellow',alpha=0.5)
	plot.annotate('AMEGO',xy=(3,9e-5),xycoords='data',fontsize=26,color='black')

	lat=ascii.read("data/NMon2012.LAT.dat",names=['energy','en_low','en_high','flux','flux_err','tmp'])
	plot.scatter(lat['energy'],lat['flux']*erg2mev,color='red')
	plot.errorbar(lat['energy'],lat['flux']*erg2mev,xerr=[lat['en_low'],lat['en_high']],yerr=lat['flux_err']*erg2mev,ecolor='red',capsize=0,fmt='none')
	latul=ascii.read("data/NMon2012.LAT.limits.dat",names=['energy','en_low','en_high','flux','tmp1','tmp2','tmp3','tmp4'])
	plot.errorbar(latul['energy'],latul['flux']*erg2mev,xerr=[latul['en_low'],latul['en_high']],yerr=0.5*latul['flux']*erg2mev,uplims=True,ecolor='red',capsize=0,fmt='none')
	plot.scatter(latul['energy'],latul['flux']*erg2mev,color='red')

	leptonic=ascii.read("data/sp-NMon12-IC-best-fit-1MeV-30GeV.txt",names=['energy','flux'],data_start=1)
	hadronic=ascii.read("data/sp-NMon12-pi0-and-secondaries.txt",names=['energy','flux1','flux2'],data_start=1)	

	plot.plot(leptonic['energy'],leptonic['flux']*erg2mev,'r--',color='black',lw=2,label='Leptonic')
	plot.plot(hadronic['energy'],hadronic['flux2']*erg2mev,color='black',lw=2,label='Hadronic+Secondary Leptons')

	plot.legend(loc='upper right',fontsize='small',frameon=False,framealpha=0.5)
	plot.xscale('log')
	plot.yscale('log')
	plot.ylim(yrange)
	plot.xlim(xrange)
	plot.xlabel(r'Energy (MeV)')
	plot.ylabel(r'Energy$^2 \times $ Flux (Energy) (erg cm$^{-2}$ s$^{-1}$)')
	plot.title('Nova V339 Del 2013')
	plot.savefig('Nova_SED.png', bbox_inches='tight')
	plot.savefig('Nova_SED.eps', bbox_inches='tight')
	plot.show()
	plot.close()
コード例 #8
0
def plot_prob_effector(sens, fpr, xmax=1, baserate=0.1):
    """Plots a line graph of P(effector|positive test) against
    the baserate of effectors in the input set to the classifier.
        
    The baserate argument draws an annotation arrow
    indicating P(pos|+ve) at that baserate
    """
    assert 0.1 <= xmax <= 1, "Max x axis value must be in range [0,1]"
    assert 0.01 <= baserate <= 1, "Baserate annotation must be in range [0,1]"
    baserates = pylab.arange(0, 1.05, xmax * 0.005)  
    probs = [p_correct_given_pos(sens, fpr, b) for b in baserates]
    pylab.plot(baserates, probs, 'r')
    pylab.title("P(eff|pos) vs baserate; sens: %.2f, fpr: %.2f" % (sens, fpr))
    pylab.ylabel("P(effector|positive)")
    pylab.xlabel("effector baserate")
    pylab.xlim(0, xmax)
    pylab.ylim(0, 1)
    # Add annotation arrow
    xpos, ypos = (baserate, p_correct_given_pos(sens, fpr, baserate))
    if baserate < xmax:
        if xpos > 0.7 * xmax:
            xtextpos = 0.05 * xmax
        else:
            xtextpos = xpos + (xmax-xpos)/5.
        if ypos > 0.5:
            ytextpos = ypos - 0.05
        else:
            ytextpos = ypos + 0.05
        pylab.annotate('baserate: %.2f, P(pos|+ve): %.3f' % (xpos, ypos), 
                       xy=(xpos, ypos), 
                       xytext=(xtextpos, ytextpos),
                       arrowprops=dict(facecolor='black', shrink=0.05))
    else:
        pylab.text(0.05 * xmax, 0.95, 'baserate: %.2f, P(pos|+ve): %.3f' %
                   (xpos, ypos))
コード例 #9
0
ファイル: fancy_dendrogram.py プロジェクト: getsmarter/bda
def fancy_dendrogram(*args, **kwargs):
    '''
    Source: https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/
    '''
    from scipy.cluster import hierarchy
    import matplotlib.pylab as plt
    
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)

    ddata = hierarchy.dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        plt.title('Hierarchical Clustering Dendrogram (truncated)')
        plt.xlabel('sample index or (cluster size)')
        plt.ylabel('distance')
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, 'o', c=c)
                plt.annotate("%.3g" % y, (x, y), xytext=(0, -5),
                             textcoords='offset points',
                             va='top', ha='center')
        if max_d:
            plt.axhline(y=max_d, c='k')
    return ddata
コード例 #10
0
ファイル: word2vec.py プロジェクト: MrH2S/py
def plot(embeddings,labels):
    assert embeddings.shape[0] >= len(labels) , 'More labels than embeddings'
    pylab.figure(figsize=(15,15)) #in inches
    for i, label in enumerate(labels):
        x,y = embeddings[i,:]
        pylab.scatter(x,y)
        pylab.annotate(label,xy=(x,y),xytext=(5,2),textcoords='offset points',ha='right',va='bottom')
    pylab.show()
コード例 #11
0
ファイル: infer.py プロジェクト: FoxxyMoxxy/Vision
def plot(embeddings, labels, out):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    pylab.figure(figsize=(15,15))
    for i, label in enumerate(labels):
        x, y = embeddings[i,:]
        pylab.scatter(x, y)
        pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                       ha='right', va='bottom')
    pylab.savefig(out)
    print('Saved plot to {}'.format(out))
コード例 #12
0
ファイル: aisreview.py プロジェクト: irbdavid/mex
    def plot_frequency_altitude(self, f=2.0, ax=None, median_filter=False,
        vmin=None, vmax=None, altitude_range=(-99.9, 399.9), colorbar=False, return_image=False, annotate=True):

        if vmin is None:
            vmin = self.vmin

        if vmax is None:
            vmax = self.vmax

        if ax is None:
            ax = plt.gca()

        plt.sca(ax)
        plt.cla()
        freq_extent = (self.extent[0], self.extent[1],
            altitude_range[1], altitude_range[0])

        i = self.ionogram_list[0]
        inx = 1.0E6* (i.frequencies.shape[0] * f) / (i.frequencies[-1] - i.frequencies[0])
        img = self.tser_arr_all[:,int(inx),:]

        new_altitudes = np.arange(altitude_range[0], altitude_range[1], 14.)
        new_img = np.zeros((new_altitudes.shape[0], img.shape[1])) + np.nan

        for i in self.ionogram_list:
            e = int( round((i.time - self.extent[0]) / ais_code.ais_spacing_seconds ))

            pos = mex.iau_r_lat_lon_position(float(i.time))
            altitudes = pos[0] - ais_code.speed_of_light_kms * ais_code.ais_delays * 0.5 - mex.mars_mean_radius_km
            s = np.argsort(altitudes)
            new_img[:, e] = np.interp(new_altitudes, altitudes[s], img[s,e], left=np.nan, right=np.nan)

        plt.imshow(new_img, vmin=vmin, vmax=vmax,
            interpolation='Nearest', extent=freq_extent, origin='upper', aspect='auto')

        plt.xlim(freq_extent[0], freq_extent[1])
        plt.ylim(*altitude_range)

        ax.set_xlim(self.extent[0], self.extent[1])
        ax.xaxis.set_major_locator(celsius.SpiceetLocator())

        celsius.ylabel(r'Alt./km')
        if annotate:
            plt.annotate('f = %.1f MHz' % f, (0.02, 0.9),
                    xycoords='axes fraction', color='cyan', verticalalignment='top', fontsize='small')

        if colorbar:
            old_ax = plt.gca()
            plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$")
            plt.sca(old_ax)

        if return_image:
            return new_img, freq_extent, new_altitudes
コード例 #13
0
ファイル: stations.py プロジェクト: iceseismic/sito
 def plot(self, basemap, annotate=True, lsize='small', kwargs_an=None, **kwargs_in):
     kwargs = dict(marker='o')
     kwargs.update(kwargs_in)
     if kwargs_an is None:
         kwargs_an = {}
     for key, val in self.items():
         x, y = basemap(val.longitude, val.latitude)
         basemap.plot((x,), (y,), **kwargs)
         if annotate:
             import matplotlib.pylab as plt
             plt.annotate(key, (x, y), xytext=(3, 3),
                          textcoords='offset points', size=lsize, **kwargs_an)
コード例 #14
0
ファイル: interface_reactions.py プロジェクト: zclpf/pymatgen
    def plot(self):
        """
        Plots reaction energy as a function of mixing ratio x in
        self.c1 - self.c2 tie line using pylab.

        Returns:
            Pylab object that plots reaction energy as a function of
            mixing ratio x.
        """
        plt.rcParams['xtick.major.pad'] = '6'
        plt.rcParams['ytick.major.pad'] = '6'
        plt.rcParams['axes.linewidth'] = 2
        npoint = 1000
        xs = np.linspace(0, 1, npoint)

        # Converts sampling points in self.c1 - self.c2 tie line to those in
        # self.comp1 - self.comp2 tie line.
        xs_reverse_converted = InterfacialReactivity._reverse_convert(
            xs, self.factor1, self.factor2)
        energies = [self._get_energy(x) for x in xs_reverse_converted]
        plt.plot(xs, energies, 'k-')

        # Marks kinks and minimum energy point.
        kinks = self.get_kinks()
        _, x_kink, energy_kink, _, _ = zip(*kinks)
        plt.scatter(x_kink, energy_kink, marker='o', c='blue', s=20)
        plt.scatter(self.minimum()[0],
                    self.minimum()[1],
                    marker='*',
                    c='red',
                    s=300)

        # Labels kinks with indices. Labels are made draggable
        # in case of overlapping.
        for index, x, energy, _, _ in kinks:
            plt.annotate(
                index,
                xy=(x, energy),
                xytext=(5, 30),
                textcoords='offset points',
                ha='right',
                va='bottom',
                arrowprops=dict(arrowstyle='->',
                                connectionstyle='arc3,rad=0')).draggable()
        plt.xlim([-0.05, 1.05])
        if self.norm:
            plt.ylabel('Energy (eV/atom)')
        else:
            plt.ylabel('Energy (eV/f.u.)')
        plt.xlabel('$x$ in $x$ {} + $(1-x)$ {}'.format(
            self.c1.reduced_formula, self.c2.reduced_formula))
        return plt
コード例 #15
0
def plot(words):
    %matplotlib inline
    embeddings = [model[w] for w in words]

    pca = PCA(n_components=2)  
    two_d_embeddings = pca.fit_transform(embeddings)

    pylab.figure(figsize=(5,5))  # in inches
    for i, label in enumerate(words):
        x, y = two_d_embeddings[i,:]
        pylab.scatter(x, y)
        pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom')
    pylab.show()
コード例 #16
0
 def plot(self):
     fm = font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc')
     
     num_points = 500
     tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=10000)
     two_d_embeddings = tsne.fit_transform(self.final_embeddings[1:num_points, :])
     labels = [self.parser.reversed_recipe_dictionary[i] for i in range(1, num_points)]
     pylab.figure(figsize=(15,15))
     for i, label in enumerate(labels):
         x, y = two_d_embeddings[i, :]
         pylab.scatter(x, y)
         pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom', fontproperties=fm)
     pylab.savefig('recipes2vec.png')
コード例 #17
0
ファイル: utils.py プロジェクト: flovouin/tensorflow-udacity
def plot_embedding(embeddings, labels):
    """Applies non-linear dimensionalty reduction using tSNE and plots
    the words."""
    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
    two_d_embeddings = tsne.fit_transform(embeddings)

    pylab.figure(figsize=(15,15))  # in inches
    for i, label in enumerate(labels):
        x, y = two_d_embeddings[i,:]
        pylab.scatter(x, y)
        pylab.annotate(label, xy=(x, y), xytext=(5, 2),
            textcoords='offset points', ha='right', va='bottom')
    pylab.show()
コード例 #18
0
def plot(embeddings, labels):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    pylab.figure(figsize=(15, 15))  # in inches
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.show()
コード例 #19
0
ファイル: train_cbow.py プロジェクト: warchildmd/game2vec
def plot(embeddings, labels):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    pylab.figure(figsize=(64, 64))  # in inches
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.savefig('visuals/tsne_cbow.png', bbox_inches='tight')
コード例 #20
0
def plot(words):
    embeddings = [model[w] for w in words]

    pca = PCA(n_components = 2)
    two_d_embeddings = pca.fit_transform(embeddings)

    pylab.figure(figsize=(5,5))
    for i, label in enumerate(words):
        x, y = two_d_embeddings[i,:]
        pylab.scatter(x,y)
        pylab.annotate(label, xy=(x,y), xytext=(28, 2), 
            textcoords = 'offset points', ha='right', va='bottom')
    pylab.savefig('testplot19.png')
コード例 #21
0
def plotSamples(samples, marker):
    '''
    绘制样本
    '''
    xVals = []
    yVals = []
    for s in samples:
        x = s.getFeatures()[0]
        y = s.getFeatures()[1]
        plt.annotate(s.getName(), xy=(x,y), xytext=(x+0.13, y-0.07), fontsize='x-large')
        xVals.append(x)
        yVals.append(y)
    plt.plot(xVals, yVals, marker)
コード例 #22
0
def plot(embeddings, WORDS):
    assert len(embeddings) >= len(WORDS)
    pylab.figure(figsize=(15, 15))  # 15 inches
    for i, label in enumerate(WORDS):
        x, y = embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=[x, y],
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')

    pylab.show()
コード例 #23
0
def check_psp_fitting():
    """Plots the results of the current fitting with the save fits and denotes 
    when there is a change. 
    """
    plotting=True # specifies whether to make plots of fitting results
        
    test_data_files=[os.path.join(test_data_dir,f) for f in os.listdir(test_data_dir)] #list of test files
    for file in sorted(test_data_files):
#    for file in ['test_psp_fit/1492546902.92_2_6stacked.json']: order of parameters affects this fit
        print 'file', file
        test_dict=json.load(open(file)) # load test data
        avg_trace=neuroanalysis.data.Trace(data=np.array(test_dict['input']['data']), dt=test_dict['input']['dt']) # create Trace object
        psp_fits = fit_psp(avg_trace, 
                           sign=test_dict['input']['amp_sign'], 
                           stacked=test_dict['input']['stacked'] 
                            )                        
        
        change_flag=False
        if test_dict['out']['best_values']!=psp_fits.best_values:     
            print '  the best values dont match'
            print '\tsaved', test_dict['out']['best_values']
            print '\tobtained', psp_fits.best_values
            change_flag=True
            
        if test_dict['out']['best_fit']!=psp_fits.best_fit.tolist():
            print '  the best fit traces dont match'
            print '\tsaved', test_dict['out']['best_fit']
            print '\tobtained', psp_fits.best_fit.tolist()
            change_flag=True
        
        if test_dict['out']['nrmse']!=float(psp_fits.nrmse()):
            print '  the nrmse doesnt match'
            print '\tsaved', test_dict['out']['nrmse']
            print '\tobtained', float(psp_fits.nrmse())
            change_flag=True
            
        if plotting:
            import matplotlib.pylab as mplt
            fig=mplt.figure(figsize=(20,8))
            ax=fig.add_subplot(1,1,1)
            ax2=ax.twinx()
            ax.plot(avg_trace.time_values, psp_fits.data*1.e3, 'b', label='data')
            ax.plot(avg_trace.time_values, psp_fits.best_fit*1.e3, 'g', lw=5, label='current best fit')
            ax2.plot(avg_trace.time_values, test_dict['input']['weight'], 'r', label='weighting')
            if change_flag is True:
                ax.plot(avg_trace.time_values, np.array(test_dict['out']['best_fit'])*1.e3, 'k--', lw=5, label='original best fit')
                mplt.annotate('CHANGE', xy=(.5, .5), xycoords='figure fraction', fontsize=40)
            ax.legend()
            mplt.title(file + ', nrmse =' + str(psp_fits.nrmse()))
            mplt.show()
コード例 #24
0
def plot(embeddings, labels, out):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    pylab.figure(figsize=(15, 15))
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.savefig(out)
    print('Saved plot to {}'.format(out))
コード例 #25
0
def ps_plot(date, annotate=[], **kwargs):
    with open(f"../data/{event_name}/interpolate/{date}.csv", 'r', encoding='utf-8') as f:
        rdr = csv.reader(f)
        x, y = list(zip(*rdr))
        x = [int(n) for n in x]
        y = [int(n) for n in y]
    plt.plot(x, y, **kwargs)

    for i in annotate:
        if i == 0:
            text = f"{y[i]}점\n100등"
        else:
            text = f"{PER_INFO.get(i, '')}{y[i]}점\n{i}%"
        plt.annotate(text, xy=(i + 2, y[i] + 5000))
コード例 #26
0
def plot_word_embedding(plt, table, labels=None, title='', num=1):
    import numpy as np
    plt.figure(num)
    vectors = np.matrix(table).tolist()
    words = list(table.index)

    import matplotlib
    if(type(labels) == type(None)):
        None
        colors = None
    else:
        label_set = list(set(list(labels.values.transpose().tolist())[0]))

        def get_spaced_colors(n):
            max_value = 16581375  # 255**3
            interval = int(max_value / n)
            colors = [hex(I)[2:].zfill(6)
                      for I in range(0, max_value, interval)]

            return [(int(i[:2], 16), int(i[2:4], 16), int(i[4:], 16)) for i in colors]
        colors = get_spaced_colors(len(label_set))

    for i in range(len(words)):
        point = vectors[i]
        word = words[i]
        # plot points
        plt.scatter(point[0], point[1])
        # plot word annotations
        if(type(labels) == type(None)):

            plt.annotate(
                word,
                xy=(point[0], point[1]),
                size="x-small"
            )
        else:
            label_index = label_set.index(
                list(labels.values.transpose().tolist())[0][i])
            plt.annotate(
                word,
                xy=(point[0], point[1]),
                color='#' +
                "".join(list(map(lambda x: format(x, '#04x')
                                 [2:], colors[label_index]))).upper(),
                size="x-small"
            )

    plt.tight_layout()
    plt.title(title)
コード例 #27
0
ファイル: plot.py プロジェクト: paullianyang/SimPol
def pkmean(kmean, X, label_centers=True, save_loc=False):
    '''
    INPUT: fitted kmean model,
           1-dimensional array of x,y tuples,
           True/False to include centroid labels,
           save location
    OUTPUT: None

    Create and show a scatterplot color points by cluster
    and plot the cluster centers in black.

    You can choose to save the plot if
    file location is specified for save_loc
    '''
    centers = kmean.cluster_centers_
    colors = plt.cm.Spectral(np.linspace(0, 1, len(centers)))
    labels = np.arange(len(centers))
    # plot and color points by cluster
    for label, col in zip(labels, colors):
        label_indices = np.where(kmean.labels_ == label)
        x = X[:, 0][label_indices]
        y = X[:, 1][label_indices]

        plt.plot(x, y, '.',
                 markerfacecolor=col,
                 alpha=0.1)
        plt.axis('off')

    # add labels to centers
    if label_centers:
        center_x = centers[:, 0]
        center_y = centers[:, 1]
        # plot cluster centers in black
        plt.plot(center_x, center_y, '.',
                 markerfacecolor='k')

        for label, x, y in zip(labels, center_x, center_y):
            plt.annotate(
                label,
                xy=(x, y), xytext = (-20, 20),
                textcoords = 'offset points', ha = 'right', va = 'bottom',
                bbox = dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops = dict(arrowstyle='->',
                                  connectionstyle='arc3,rad=0'))

    if save_loc:
        plt.savefig(save_loc)
    else:
        plt.show()
コード例 #28
0
ファイル: main.py プロジェクト: shashi12533/Code-Exercises
def plot(embeddings, labels, drawn_vocabs):
    """
        Sử dụng thư viện matplotlib để biểu diễn từ lên mặt phẳng tọa độ
    """
    pylab.figure(figsize=(50,50)) 
    rcParams.update({'font.size': 40}) 
    for i, label in enumerate(labels):
        if label in drawn_vocabs:
            x, y = embeddings[i,:]
            pylab.scatter(x, y)
            xt = random.randint(0,200)
            yt = random.randint(0,200)
            pylab.annotate(label, xy=(x, y), xytext=(xt, yt), textcoords='offset points',
                       ha='right', va='bottom')
    pylab.show()
コード例 #29
0
ファイル: visualization.py プロジェクト: codeXiaoLi/word2vec
def plot(embeddings, labels, save_path):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    plt.figure(figsize=(16, 9))  # in inches
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        plt.scatter(x, y)
        plt.annotate(label,
                     xy=(x, y),
                     xytext=(5, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')
    plt.savefig(save_path)
    plt.show()
    plt.close()
コード例 #30
0
def plot(result=None,
         figname=None,
         datapoints=None,
         annotate=False,
         model=None):
    plt.figure(figsize=(12, 8), dpi=300)
    plt.scatter(result[:datapoints, 0], result[:datapoints, 1])
    if annotate == True:
        words = list(model.wv.vocab)[:datapoints]
        for i, word in enumerate(words):
            if i % 5 == 0:
                plt.annotate(word,
                             xy=(result[i, 0], result[i, 1]),
                             fontsize=10)
    plt.savefig('./results/{}.png'.format(figname))
コード例 #31
0
    def visualization(self):
        num_points = 100

        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
        two_d_embeddings = tsne.fit_transform(self.final_embeddings[1:num_points+1, :])

        labels = [ self.reverse_dictionary[i] for i in range(1, num_points+1) ]
        assert self.final_embeddings.shape[0] >= len(labels), 'More labels than embeddings'
        pylab.figure(figsize=(15,15))  # in inches
        for i, label in enumerate(labels):
            x, y = self.final_embeddings[i,:]
            pylab.scatter(x, y)
            pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                   ha='right', va='bottom')
        pylab.show()
コード例 #32
0
def plotting(test, book_title):
    xs, ys = zip(*test.values())
    labels = test.keys()

    plt.figure(figsize=(8, 10))
    plt.title("The closest books to: " + bold_title(book_title), fontsize=20)
    plt.scatter(xs, ys, marker='o')
    plt.axis('scaled')
    for label, x, y in zip(labels, xs, ys):
        plt.annotate(label, xy=(x, y), ha='center')
    # plt.axis('off')
    plt.xticks([])
    plt.yticks([])
    plt.tight_layout()
    plt.savefig('foo.png')
コード例 #33
0
def plot_words(model, words):
    words_vectors = []
    for word in words:
        words_vectors.append(model.wv[word])

    # transform word vectors to 2D using PCA
    pca = decomposition.PCA(n_components=2)
    pca.fit(words_vectors)
    reduced = pca.transform(words_vectors)

    for word, vec in zip(words, reduced):
        x, y = vec[0], vec[1]
        plt.plot(x, y, 'k.')
        plt.annotate(word, xy=(x, y))
    plt.show()
コード例 #34
0
def show_projection(a,b):
    plt.plot([0,a[0]], [0,a[1]], color='black')
    plt.annotate('b', b, 
            xytext=(0.9, 0.7), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='right', verticalalignment='top')
    plt.annotate('a', a, 
            xytext=(0.7, 0.95), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='right', verticalalignment='top')
    plt.plot([0,b[0]], [0,b[1]], color='black')
    
#Finish your code here

    plt.axis('equal')
コード例 #35
0
def plot(arg_embeddings, arg_labels, arg_file_name):
    assert arg_embeddings.shape[0] >= len(
        arg_labels), 'More labels than embeddings'
    pylab.figure(figsize=(18, 18))  # in inches
    for index, label in enumerate(arg_labels):
        x, y = arg_embeddings[index, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.savefig(arg_file_name + '.png')
    pylab.savefig(arg_file_name + '.pdf')
    pylab.show()
コード例 #36
0
 def plot(embeddings, labels, category):
     assert embeddings.shape[0] >= len(
         labels), 'More labels than embeddings'
     pylab.figure(figsize=(10, 10))  # in inches
     for i, label in enumerate(labels):
         x, y = embeddings[i, :]
         cat = category[i]
         pylab.scatter(x, y, color=col(cat))
         pylab.annotate(label,
                        xy=(x, y),
                        xytext=(5, 2),
                        textcoords='offset points',
                        ha='right',
                        va='bottom',
                        fontsize=7)
     pylab.show()
コード例 #37
0
ファイル: GeneralTools.py プロジェクト: irenge/RLPy
def fromAtoB(x1,y1,x2,y2,color = 'k', connectionstyle="arc3,rad=-0.4",shrinkA=10,shrinkB=10,arrowstyle="fancy",ax = None):
    #draw an arrow from point A=(x1,y1) to point B=(x2,y2)
    # ax is optional to specifify the axis used for drawing
    if ax is None:
        return pl.annotate("",
                xy=(x2,y2), xycoords='data',
                xytext=(x1,y1), textcoords='data',
                arrowprops=dict(arrowstyle=arrowstyle, #linestyle="dashed",
                                color= color,
                                shrinkA=shrinkA, shrinkB=shrinkB,
                                patchA=None,
                                patchB=None,
                                connectionstyle=connectionstyle),
                )
    else:
        return ax.annotate("",
                xy=(x2,y2), xycoords='data',
                xytext=(x1,y1), textcoords='data',
                arrowprops=dict(arrowstyle=arrowstyle, #linestyle="dashed",
                                color= color,
                                shrinkA=shrinkA, shrinkB=shrinkB,
                                patchA=None,
                                patchB=None,
                                connectionstyle=connectionstyle),
                )
コード例 #38
0
ファイル: fitting.py プロジェクト: hgrollnt/pyHegel
def plotResult(func,
               p,
               pe,
               extra={},
               signif=2,
               loc='upper right',
               ax=None,
               formats={}):
    """
    takes the fitting results and make a text box on the axis ax
    according to location loc (can be the same as for legend except for best(0) or
    a (x,y) tuple in axes fraction coordinate.
    It uses annotate, so you can override some of the settings with formats
    """
    res = '\n'.join(strResult(func, p, pe, extra, signif))
    kwarg = dict(family='monospace', size=14, xycoords='axes fraction')
    update = False
    if ax is None:
        ax = plt.gca()
        update = True
    bg = _get_axis_bgcolor(ax)
    kwarg['bbox'] = dict(boxstyle='round', fill=True, facecolor=bg, alpha=.6)
    codes = {
        'upper right': 1,
        'upper left': 2,
        'lower left': 3,
        'lower right': 4,
        'right': 5,
        'center left': 6,
        'center right': 7,
        'lower center': 8,
        'upper center': 9,
        'center': 10
    }
    UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(1, 11)
    loc_para = {
        UR: (.99, .99, 'right', 'top'),
        UL: (.01, .99, 'left', 'top'),
        LL: (.01, .01, 'left', 'bottom'),
        LR: (.99, .01, 'right', 'bottom'),
        R: (.99, .5, 'right', 'center'),
        CL: (.01, .5, 'left', 'center'),
        CR: (.99, .5, 'right', 'center'),
        LC: (.5, .01, 'center', 'bottom'),
        UC: (.5, .99, 'center', 'top'),
        C: (.5, .5, 'center', 'center')
    }
    if not isinstance(loc, tuple):
        if isinstance(loc, basestring):
            loc = codes[loc]
        x, y, ha, va = loc_para[loc]
        loc = x, y
        kwarg['horizontalalignment'] = ha
        kwarg['verticalalignment'] = va
    kwarg.update(formats)
    if update:
        a = plt.annotate(res, loc, **kwarg).draggable()
    else:
        a = ax.annotate(res, loc, **kwarg).draggable()
    return a
コード例 #39
0
def fromAtoB(x1, y1, x2, y2, color='k', connectionstyle="arc3,rad=-0.4",
             shrinkA=10, shrinkB=10, arrowstyle="fancy", ax=None):
    """
    Draws an arrow from point A=(x1,y1) to point B=(x2,y2) on the (optional)
    axis ``ax``.

    .. note::

        See matplotlib documentation.

    """
    if ax is None:
        return pl.annotate("",
                           xy=(x2, y2), xycoords='data',
                           xytext=(x1, y1), textcoords='data',
                           arrowprops=dict(
                               arrowstyle=arrowstyle,  # linestyle="dashed",
                               color=color,
                               shrinkA=shrinkA, shrinkB=shrinkB,
                               patchA=None,
                               patchB=None,
                               connectionstyle=connectionstyle),
                           )
    else:
        return ax.annotate("",
                           xy=(x2, y2), xycoords='data',
                           xytext=(x1, y1), textcoords='data',
                           arrowprops=dict(
                               arrowstyle=arrowstyle,  # linestyle="dashed",
                               color=color,
                               shrinkA=shrinkA, shrinkB=shrinkB,
                               patchA=None,
                               patchB=None,
                               connectionstyle=connectionstyle),
                           )
コード例 #40
0
def plot(embeddings, labels, save_to_pdf='embed.pdf'):
    assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
    pp = PdfPages(save_to_pdf)
    plt.figure(figsize=(15, 15))  # in inches
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        plt.scatter(x, y)
        plt.annotate(label,
                     xy=(x, y),
                     xytext=(5, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')
    plt.savefig(pp, format='pdf')
    plt.show()
    pp.close()
コード例 #41
0
def plotSamples(samples, marker):
    '''
    绘制样本
    '''
    xVals = []
    yVals = []
    for s in samples:
        x = s.getFeatures()[0]
        y = s.getFeatures()[1]
        plt.annotate(s.getName(),
                     xy=(x, y),
                     xytext=(x + 0.13, y - 0.07),
                     fontsize='x-large')
        xVals.append(x)
        yVals.append(y)
    plt.plot(xVals, yVals, marker)
コード例 #42
0
ファイル: F1Optimizer_.py プロジェクト: Jie-Yuan/tql-Python
def save_plot(P, filename='expected_f1.png'):
    E_F1 = pd.DataFrame(F1Optimizer.get_expectations(P).T, columns=["/w None", "/wo None"])
    best_k, _, max_f1 = F1Optimizer.maximize_expectation(P)

    plt.style.use('ggplot')
    plt.figure()
    E_F1.plot()
    plt.title('Expected F1-Score for \n {}'.format("P = [{}]".format(",".join(map(str, P)))), fontsize=12)
    plt.xlabel('k')
    plt.xticks(np.arange(0, len(P) + 1, 1.0))
    plt.ylabel('E[F1(P,k)]')
    plt.plot([best_k], [max_f1], 'o', color='#000000', markersize=4)
    plt.annotate('max E[F1(P,k)] = E[F1(P,{})] = {:.5f}'.format(best_k, max_f1), xy=(best_k, max_f1),
                 xytext=(best_k, max_f1 * 0.8), arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=7),
                 horizontalalignment='center', verticalalignment='top')
    plt.gcf().savefig(filename)
コード例 #43
0
ファイル: GeneralTools.py プロジェクト: epruesse/rlpy
def fromAtoB(x1, y1, x2, y2, color='k', connectionstyle="arc3,rad=-0.4",
             shrinkA=10, shrinkB=10, arrowstyle="fancy", ax=None):
    """
    Draws an arrow from point A=(x1,y1) to point B=(x2,y2) on the (optional)
    axis ``ax``.

    .. note::

        See matplotlib documentation.

    """
    if ax is None:
        return pl.annotate("",
                           xy=(x2, y2), xycoords='data',
                           xytext=(x1, y1), textcoords='data',
                           arrowprops=dict(
                               arrowstyle=arrowstyle,  # linestyle="dashed",
                               color=color,
                               shrinkA=shrinkA, shrinkB=shrinkB,
                               patchA=None,
                               patchB=None,
                               connectionstyle=connectionstyle),
                           )
    else:
        return ax.annotate("",
                           xy=(x2, y2), xycoords='data',
                           xytext=(x1, y1), textcoords='data',
                           arrowprops=dict(
                               arrowstyle=arrowstyle,  # linestyle="dashed",
                               color=color,
                               shrinkA=shrinkA, shrinkB=shrinkB,
                               patchA=None,
                               patchB=None,
                               connectionstyle=connectionstyle),
                           )
コード例 #44
0
def tsne_and_plot(num_points, final_embeddings, labels):
    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
    two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points +
                                                           1, :])
    assert two_d_embeddings.shape[0] >= len(
        labels), 'More labels than embeddings'
    pylab.figure(figsize=(15, 15))  # in inches
    for i, label in enumerate(labels):
        x, y = two_d_embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.show()
コード例 #45
0
ファイル: utils.py プロジェクト: sausax/tensorflow-udacity
def plot_embedding(embeddings, labels):
    """Applies non-linear dimensionalty reduction using tSNE and plots
    the words."""
    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
    two_d_embeddings = tsne.fit_transform(embeddings)

    pylab.figure(figsize=(15, 15))  # in inches
    for i, label in enumerate(labels):
        x, y = two_d_embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords='offset points',
                       ha='right',
                       va='bottom')
    pylab.show()
コード例 #46
0
    def plot_transition_frequencies(self, transitions, frequencies, plot_single=False, plot_multiple=True, show_labels=True):

        txt = []
        x = []
        y = []
        for key in transitions:
            if key != 'UNKNOWN' and ((plot_single and len(key)==1) or (plot_multiple and len(key)>1)):
                txt.append(key)
                x.append(transitions[key])
                y.append(frequencies[key])
        plt.scatter(x, y)

        if show_labels:
            for txt,xv,yv in zip(txt,x,y):
                plt.annotate(txt.replace(' ','_'), (xv, yv))

        return np.array(x).astype(def_dtype), np.array(y).astype(def_dtype)
コード例 #47
0
def plot_alpha_beta():
    init = dict(year=2021, month=11, day=1)
    end = dict(year=2021, month=11, day=30)
    ww = get_words_date_range(init, end)
    beta = [heaps(*voc_tokens(w))[1] for w in ww]
    words = get_words()
    zipf_c = [zipf(d) for d in words]

    # plt.rcParams['text.usetex'] = True
    plt.plot([x for _, x in zipf_c], beta, 'o')
    for y, (_, x), country in zip(beta, zipf_c, COUNTRIES):
        plt.annotate(country, [x, y])
    plt.grid()
    plt.ylabel(r'$\beta$')
    plt.xlabel(r'$\alpha$')
    plt.tight_layout()
    plt.savefig('es_alpha_beta.png', dpi=300)
コード例 #48
0
ファイル: nets.py プロジェクト: adesam01/FEMTools
 def plot(self, **kwds):
     ''' Plots geometry '''
     fig = plt.figure()
     ax = fig.add_axes()
     plt.grid()
     cn = self.corner_nodes
     k = concatenate([linspace(cn[cni][0],cn[(cni+1)%len(cn)][0]) for cni in xrange(len(cn))])
     e = concatenate([linspace(cn[cni][1],cn[(cni+1)%len(cn)][1]) for cni in xrange(len(cn))])
     plt.plot(self.x(k,e),self.y(k,e))
     plt.scatter(self.xcoords,self.ycoords,marker='o',c='b',s=10)
     for (xi,yi,i) in zip(self.xcoords,self.ycoords,range(len(self.xcoords))):
         plt.annotate('%d'%(i+1), xy=(xi,yi), xytext=(0,10), 
         textcoords='offset points', ha='right', va='bottom',
         bbox=dict(boxstyle='round,pad=0.5', fc='blue', alpha=0.2))
     if kwds.has_key('filename'):
         plt.savefig(**kwds)
     return fig,ax
コード例 #49
0
ファイル: roc.py プロジェクト: lvxingvir/template
def plot_crosshair(coordinates, ax=None, **kwargs):
    """
    Plot crosshair at target cordinate
    Args:
        coordinates: the x, y coordinates of the point to be plotted
    Return:
        crosshair_handles: handles to crosshair lines
    """
    x, y = coordinates
    if ax is None:
        ax = plt.gca()
    horiz = ax.axhline(y, **kwargs)
    vert = ax.axvline(x, **kwargs)
    annotation = '({:.2f},{:.2f})'.format(x, y)
    plt.annotate(annotation, (x + 0.01, y - 0.04), color=kwargs['color'])
    crosshair_handles = horiz, vert
    return crosshair_handles
コード例 #50
0
 def plot(embeddings, labels):
     assert embeddings.shape[0] >= len(
         labels), 'More labels than embeddings'
     pylab.figure(figsize=(15, 15))  # in inches
     for i, label in enumerate(labels):
         x, y = embeddings[i, :]
         pylab.scatter(x, y)
         pylab.annotate(label,
                        xy=(x, y),
                        xytext=(5, 2),
                        textcoords='offset points',
                        ha='right',
                        va='bottom')
     # pylab.show()
     pylab.savefig(
         os.path.join(preprocessing_photos.DATA_HOUSE_PATH,
                      'embedding-pca.jpg'))
コード例 #51
0
    def plot(self):
        """
        Plots reaction energy as a function of mixing ratio x in
        self.c1 - self.c2 tie line using pylab.

        Returns:
            Pylab object that plots reaction energy as a function of
            mixing ratio x.
        """
        plt.rcParams['xtick.major.pad'] = '6'
        plt.rcParams['ytick.major.pad'] = '6'
        plt.rcParams['axes.linewidth'] = 2
        npoint = 1000
        xs = np.linspace(0, 1, npoint)

        # Converts sampling points in self.c1 - self.c2 tie line to those in
        # self.comp1 - self.comp2 tie line.
        xs_reverse_converted = self._reverse_convert(xs, self.factor1,
                                                     self.factor2)
        energies = [self._get_energy(x) for x in xs_reverse_converted]
        plt.plot(xs, energies, 'k-')

        # Marks kinks and minimum energy point.
        kinks = self.get_kinks()
        _, x_kink, energy_kink, _, = zip(*kinks)
        plt.scatter(x_kink, energy_kink, marker='o', c='blue', s=20)
        plt.scatter(self.minimum()[0], self.minimum()[1], marker='*',
                    c='red', s=300)

        # Labels kinks with indices. Labels are made draggable
        # in case of overlapping.
        for index, x, energy, reaction in kinks:
            plt.annotate(
                index,
                xy=(x, energy), xytext=(5, 30),
                textcoords='offset points', ha='right', va='bottom',
                arrowprops=dict(arrowstyle='->',
                                connectionstyle='arc3,rad=0')).draggable()
        plt.xlim([-0.05, 1.05])
        if self.norm:
            plt.ylabel('Energy (eV/atom)')
        else:
            plt.ylabel('Energy (eV/f.u.)')
        plt.xlabel('$x$ in $x$ {} + $(1-x)$ {}'.format(
            self.c1.reduced_formula, self.c2.reduced_formula))
        return plt
コード例 #52
0
ファイル: knee.py プロジェクト: orenlivne/euler
def plot_knee_point(x, y, knee, text_offset=(180, -20)):
    '''Generate a plot of the data y(x), and the knee point at knee (the index of that
    point in the x- and y-arrays).'''
    idx = np.argsort(x)
    fig = P.figure()
    P.clf()
    ax = fig.add_subplot(111)
    P.hold(True)
    ax.plot(x[idx], y[idx], 'bx-', label='Data')
    P.xlabel('x')
    P.ylabel('y')
    P.plot(x[knee], y[knee], 'ro', markersize=10)
    P.annotate('Knee Point (%.3f,%.3f)' % (x[knee], y[knee]), xy=(x[knee], y[knee]), xytext=text_offset,
               textcoords='offset points', ha='right', va='bottom',
               bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
               arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    P.title('Curve and Knee')
コード例 #53
0
def varianceDemo(degree, ntrials, filename=None, **kwargs):
    pts = numpy.linspace(MIN,MAX,100)
    zeropreds = numpy.zeros((ntrials))

    plt.subplot(2,1,1)
    for i in range(ntrials):
        p, x, y = noisyDataPolyFit(degree, **kwargs)
        fitf = numpy.poly1d(p)
        plt.plot(pts,fitf(pts),'g-',alpha=.5)
        zeropreds[i] = fitf(0.)
    plt.plot(x,y,'ro')
    plt.xlim([MIN,MAX])
    plt.ylim([-2.,2.])
    
    plt.subplot(2,1,2)
    x, y = noisyData(npts=3,noise_amp=0.,x_noise_amp=0.)
    zerotrue = y[1]
    n, bins, patches = plt.hist(zeropreds, ntrials/20)

    # draw line at true zero prediction
    lheight = max(n)*5/4
    line = plt.plot([zerotrue,zerotrue],[0,lheight],'r-')
    plt.setp(line,linewidth=2)

    mean    = numpy.mean(zeropreds)
    sd      = numpy.sqrt(numpy.var(zeropreds))
    datahi  = max(n)

    if mean < 0:
        txtpos = mean-2.4*sd
        balign = 'left'
        valign = 'right'
    else:
        txtpos = mean+2.4*sd
        balign = 'right'
        valign = 'left'

    plt.annotate('Bias', xy=(mean, 0.9*lheight), xytext=(0, 0.9*lheight), xycoords='data', 
            ha=balign, va='center', arrowprops={'facecolor':'red', 'shrink':0.05})
    line = plt.plot([mean-2*sd,mean+2*sd],[datahi/3.,datahi/3.],'g-')
    plt.setp(line,linewidth=7)
    plt.text(txtpos, datahi*9./24., 'Variance', ha=valign, va='bottom')
    plt.suptitle('Polynomial, degree '+str(degree))
    plt.xlim((-0.3,0.3))
    outputPlot(filename)
コード例 #54
0
def cbow_plot(embeddings, labels):
    """

    :param embeddings:
    :param labels:
    :return:
    """
    pylab.figure(figsize=(12, 12))
    for i, label in enumerate(labels):
        x, y = embeddings[i, :]
        pylab.scatter(x, y)
        pylab.annotate(label,
                       xy=(x, y),
                       xytext=(5, 2),
                       textcoords="offset points",
                       ha="right",
                       va="bottom")
    pylab.show()
コード例 #55
0
    def plot(self, num_words=100):
        from sklearn.manifold import TSNE
        from matplotlib import pylab
        tsne = TSNE()
        embedding_2d = tsne.fit_transform(self.final_embeddings[:num_words, :])

        words = [self.idx2word[i] for i in range(num_words)]
        pylab.figure(figsize=(15, 15))
        for i, label in enumerate(words):
            x, y = embedding_2d[i, :]
            pylab.scatter(x, y)
            pylab.annotate(label,
                           xy=(x, y),
                           xytext=(5, 2),
                           textcoords='offset points',
                           ha='right',
                           va='bottom')
        pylab.show()
コード例 #56
0
ファイル: __init__.py プロジェクト: jacksonloper/bardensr
    def go(r, c, a):

        m1s = bc.rolonies['m1'] - (m1 - radius)
        m2s = bc.rolonies['m2'] - (m2 - radius)
        goodies = (m1s >= 0) & (m2s >= 0) & (m1s < radius * 2) & (m2s <
                                                                  radius * 2)
        m1s = m1s[goodies]
        m2s = m2s[goodies]
        js = bc.rolonies['j'][goodies]
        for (mm1, mm2, j) in zip(m1s, m2s, js):
            if bc.codebook[r, c, j]:
                plt.annotate(str(j), [mm2, mm1],
                             color='white',
                             bbox=dict(fc="k", ec="b", lw=2, alpha=.4))
                plt.scatter([mm2], [mm1], color='red', marker='x')

        # if r==0 and c==0:
        # print(bc.rolonies[goodies].to_markdown())

        sub = rectangles.sliceit0(X[r, c, 0], [m1 - radius, m2 - radius],
                                  [m1 + radius + 1, m2 + radius + 1])
        plt.imshow(sub)
        plt.title(f'mx={sub.max():.2f}')
        if r == R - 1:
            plt.yticks([0, radius, radius * 2],
                       [str(m1 - radius),
                        str(m1), str(m1 + radius)])
            plt.gca().yaxis.tick_right()
        else:
            plt.yticks([])

        if c == C - 1:
            plt.xticks([0, radius, radius * 2],
                       [str(m2 - radius),
                        str(m2), str(m2 + radius)])
        else:
            plt.xticks([])

        plt.axhline(radius, color='green')
        plt.axvline(radius, color='green')

        if (code is not None) and code[r, c]:
            plt.axhline(radius, color='red')
            plt.axvline(radius, color='red')
コード例 #57
0
ファイル: SciencePlots.py プロジェクト: ComPair/python
def SMBH_mass(save=False):

	fig=plot.figure()

	#a=ascii.read('data/BHmass_dist.dat',names=['mass','N'],data_start=1)
	#mass=(np.round(a['mass']*100.)/100.)
	#N=np.array(np.round(a['N']*100),dtype=np.int64)

	high=ascii.read('data/BH_mass_High_z.txt',names=['mass'])
	low=ascii.read('data/BH_mass_Low_z.txt',names=['mass'])

	loghigh=np.log10(high['mass'])
	loglow=np.log10(low['mass'])
	#ind1=np.arange(0,13,1)
	#ind2=np.arange(13,len(mass),1)

	#m1=np.repeat(mass[ind1],N[ind1])
	#w1=np.repeat(np.repeat(1./max(N[ind1]),len(ind1)),N[ind1])
	#m2=np.repeat(mass[ind2],N[ind2])
	#w2=np.repeat(np.repeat(1./max(N[ind2]),len(ind2)),N[ind2])

	low_bin=np.logspace(np.min(loglow),np.max(loglow),num=14)
	plot.hist(low['mass'],bins=low_bin,color='blue',weights=np.repeat(1./28,len(low)))
	high_bin=np.logspace(np.min(loghigh),np.max(loghigh),num=10)
	plot.hist(high['mass'],bins=high_bin,color='red',alpha=0.7,weights=np.repeat(1./28,len(high)))

	plot.annotate('Low Redshift (z < 3) Blazars',xy=(1.5e9,0.8),xycoords='data',fontsize=14,color='blue')
	plot.annotate('High Redshift (z > 3) Blazars',xy=(1.5e9,0.5),xycoords='data',fontsize=14,color='red')

	plot.xlim([5e7,5e10])
	plot.ylim([0,1.05])
	plot.xscale('log')
#	plot.yscale('log')
	plot.xlabel(r'Black Hole Mass (M$_{\odot}$)')
	plot.ylabel('Fraction of Known Blazars')
#	plot.title('Supermassive Black Hole Mass Evolution')

	if save:
		plot.savefig('SMBH_mass.png', bbox_inches='tight')
		plot.savefig('SMBH_mass.eps', bbox_inches='tight')
	else:
		plot.show()

	return
コード例 #58
0
ファイル: plot.py プロジェクト: paullianyang/SimPol
def plotone(df, field, centers=None, figsize=(8, 5), save_loc=False):
    '''
    INPUT: dataframe, field to color by,
           cluster centers (optional),
           figure size tuple,
           local file path to save to (optional)
    OUTPUT: scatter plot

    Show scatterplot by dataframe field, and optional cluster centers
    if plotting predicted values
    '''
    regions = df[field].unique()
    colors = plt.cm.Spectral(np.linspace(0, 1, len(regions)))
    plt.figure(figsize=figsize)
    for r, col in zip(regions, colors):
        label_indices = df[field] == r
        x = df[label_indices]['X']
        y = df[label_indices]['Y']
        plt.plot(x, y, '.',
                 markerfacecolor=col,
                 alpha=0.1)
        plt.axis('off')

    if centers is not None:
        center_x = centers[:, 0]
        center_y = centers[:, 1]
        plt.plot(center_x, center_y, '.',
                 markerfacecolor='k')
        labels = np.arange(len(centers))

        for label, x, y in zip(labels, center_x, center_y):
            plt.annotate(
                label,
                xy=(x, y), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round, pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle='->',
                                connectionstyle='arc3, rad=0'))

    if save_loc:
        plt.savefig(save_loc)
    else:
        plt.show()