Example #1
0
def plot_part2(filename):
	"""
	Plots the result of count ones test
	"""
	fig1 = pl.figure()
	iterations, runtimes, fvals = extract(filename)
	algos = ["SA", "GA", "MIMIC"]
	iters_sa, iters_ga, iters_mimic = [np.array(iterations[a]) for a in algos]
	runtime_sa, runtime_ga, runtime_mimic = [np.array(runtimes[a]) for a in algos]
	fvals_sa, fvals_ga, fvals_mimic = [np.array(fvals[a]) for a in algos]

	plotfunc = getattr(pl, "loglog")
	plotfunc(runtime_sa, fvals_sa, "bs", mew=0)
	plotfunc(runtime_ga, fvals_ga, "gs", mew=0)
	plotfunc(runtime_mimic, fvals_mimic, "rs", mew=0)

	# plotfunc(iters_sa, fvals_sa/(runtime_sa * iters_sa), "bs", mew=0)
	# plotfunc(iters_ga, fvals_ga/(runtime_ga * iters_ga), "gs", mew=0)
	# plotfunc(iters_mimic, fvals_mimic/(runtime_mimic * iters_mimic), "rs", mew=0)

	pl.xlabel("Runtime (seconds)")
	pl.ylabel("Objective function value")
	pl.ylim([min(fvals_sa) / 2, max(fvals_mimic) * 2])
	pl.legend(["SA", "GA", "MIMIC"], loc=4)

	pl.savefig(filename.replace(".csv", ".png"), bbox_inches="tight") 
Example #2
0
    def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'):
        outdir = self.set_dir(outdir)
        p = 64
        if F is None: F=self.calc_F(u,v)

        plt.close('all')
        plt.figure()
        #fig, axes = plt.subplots(nrows=1)
        if contour:
            plt.hold(True)
            plt.contourf(x,y,F)
        if plot=='quiver':
            plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1)
        
        if plot=='pcolor':
            plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1)
            plt.colorbar()

        if plot=='stream':
            speed = F[::16]
            plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k')

        plt.xlabel('$x$ (a.u.)')
        plt.ylabel('$y$ (a.u.)')
        
        plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight')
        plt.close()
Example #3
0
def plot_feat_hist(data_name_list, filename=None):
    if len(data_name_list)>1:
        assert filename is not None

    pylab.figure(num=None, figsize=(8, 6))
    num_rows = 1 + (len(data_name_list) - 1) / 2
    num_cols = 1 if len(data_name_list) == 1 else 2
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Fraction')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, facecolor='blue', alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name.replace(" ", "_")

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #4
0
    def check_models(self):
        plt.figure('Bandgap narrowing')
        Na = np.logspace(12, 20)
        Nd = 0.
        dn = 1e14
        temp = 300.

        for author in self.available_models():
            BGN = self.update(Na=Na, Nd=Nd, nxc=dn,
                              author=author,
                              temp=temp)

            if not np.all(BGN == 0):
                plt.plot(Na, BGN, label=author)

        test_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'Si', 'check data', 'Bgn.csv')

        data = np.genfromtxt(test_file, delimiter=',', names=True)

        for name in data.dtype.names[1:]:
            plt.plot(
                data['N'], data[name], 'r--',
                label='PV-lighthouse\'s: ' + name)

        plt.semilogx()
        plt.xlabel('Doping (cm$^{-3}$)')
        plt.ylabel('Bandgap narrowing (K)')

        plt.legend(loc=0)
Example #5
0
 def plot_bernoulli_matrix(self, show_npfs=False):
   """
   Plot the heatmap of the Bernoulli matrix 
   @self
   @show_npfs - Highlight NPFS detections [Boolean] 
   """
   matrix = self.Bernoulli_matrix
   if show_npfs == False:
     plot = plt.imshow(matrix)
     plot.set_cmap('hot')
     plt.colorbar()
     plt.xlabel("Bootstraps")
     plt.ylabel("Feature")
     plt.show()
   else:
     for i in self.selected_features:
       for k in range(len(matrix[i])):
         matrix[i,k] = .5
     plot = plt.imshow(matrix)
     plot.set_cmap('hot')
     plt.xlabel("Bootstraps")
     plt.ylabel("Feature")
     plt.colorbar()
     plt.show()
   return None
Example #6
0
def study_sdss_density(hemi='south'):
    grid = grid3d(hemi=hemi)
    n_data = num_sdss_data_both_catalogs(hemi, grid)
    n_rand, weight = num_sdss_rand_both_catalogs(hemi, grid)
    n_rand *= ((n_data*weight).sum() / (n_rand*weight).sum())
    delta = (n_data - n_rand) / n_rand
    delta[weight==0]=0.
    fdelta = np.fft.fftn(delta*weight)
    power = np.abs(fdelta)**2.
    ks = get_wavenumbers(delta.shape, grid.reso_mpc)
    kmag = ks[3]
    kbin = np.arange(0,0.06,0.002)
    ind = np.digitize(kmag.ravel(), kbin)
    power_ravel = power.ravel()
    power_bin = np.zeros_like(kbin)
    for i in range(len(kbin)):
        print i
        wh = np.where(ind==i)[0]
        power_bin[i] = power_ravel[wh].mean()
    #pl.clf()
    #pl.plot(kbin, power_bin)
    from cosmolopy import perturbation
    pk = perturbation.power_spectrum(kbin, 0.4, **cosmo)
    pl.clf(); pl.plot(kbin, power_bin/pk, 'b')
    pl.plot(kbin, power_bin/pk, 'bo')    
    pl.xlabel('k (1/Mpc)',fontsize=16)
    pl.ylabel('P(k) ratio, DATA/THEORY [arb. norm.]',fontsize=16)
    ipdb.set_trace()
Example #7
0
def make_corr1d_fig(dosave=False):
    corr = make_corr_both_hemi()
    lw=2; fs=16
    pl.figure(1)#, figsize=(8, 7))
    pl.clf()
    pl.xlim(4,300)
    pl.ylim(-400,+500)    
    lambda_titles = [r'$20 < \lambda < 30$',
                     r'$30 < \lambda < 40$',
                     r'$\lambda > 40$']
    colors = ['blue','green','red']
    for i in range(3):
        corr1d, rcen = corr_1d_from_2d(corr[i])
        ipdb.set_trace()
        pl.semilogx(rcen, corr1d*rcen**2, lw=lw, color=colors[i])
        #pl.semilogx(rcen, corr1d*rcen**2, 'o', lw=lw, color=colors[i])
    pl.xlabel(r'$s (Mpc)$',fontsize=fs)
    pl.ylabel(r'$s^2 \xi_0(s)$', fontsize=fs)    
    pl.legend(lambda_titles, 'lower left', fontsize=fs+3)
    pl.plot([.1,10000],[0,0],'k--')
    s_bao = 149.28
    pl.plot([s_bao, s_bao],[-9e9,+9e9],'k--')
    pl.text(s_bao*1.03, 420, 'BAO scale')
    pl.text(s_bao*1.03, 370, '%0.1f Mpc'%s_bao)
    if dosave: pl.savefig('xi1d_3bin.pdf')
Example #8
0
    def bar(self, key_word_sep = " ", title=None, **kwargs):
        """Generates a pylab bar plot from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        The last quantitative column is taken as the Y values;
        all other columns are combined to label the X axis.

        Parameters
        ----------
        title: Plot title, defaults to names of Y value columns
        key_word_sep: string used to separate column values
                      from each other in labels

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.bar``.
        """
        import matplotlib.pylab as plt
        self.guess_pie_columns(xlabel_sep=key_word_sep)
        plot = plt.bar(range(len(self.ys[0])), self.ys[0], **kwargs)
        if self.xlabels:
            plt.xticks(range(len(self.xlabels)), self.xlabels,
                       rotation=45)
        plt.xlabel(self.xlabel)
        plt.ylabel(self.ys[0].name)
        return plot
Example #9
0
def study_redmapper_2d():
    # I just want to know the typical angular separation for RM clusters.
    # I'm going to do this in a lazy way.
    hemi = 'north'
    rm = load_redmapper(hemi=hemi)
    ra = rm['ra']
    dec = rm['dec']
    ncl = len(ra)
    dist = np.zeros((ncl, ncl))
    for i in range(ncl):
        this_ra = ra[i]
        this_dec = dec[i]
        dra = this_ra-ra
        ddec = this_dec-dec
        dxdec = dra*np.cos(this_dec*np.pi/180.)
        dd = np.sqrt(dxdec**2. + ddec**2.)
        dist[i,:] = dd
        dist[i,i] = 99999999.
    d_near_arcmin = dist.min(0)*60.
    pl.clf(); pl.hist(d_near_arcmin, bins=100)
    pl.title('Distance to Nearest Neighbor for RM clusters')
    pl.xlabel('Distance (arcmin)')
    pl.ylabel('N')
    fwhm_planck_217 = 5.5 # arcmin
    sigma = fwhm_planck_217/2.355
    frac_2sigma = 1.*len(np.where(d_near_arcmin>2.*sigma)[0])/len(d_near_arcmin)
    frac_3sigma = 1.*len(np.where(d_near_arcmin>3.*sigma)[0])/len(d_near_arcmin)
    print '%0.3f percent of RM clusters are separated by 2-sigma_planck_beam'%(100.*frac_2sigma)
    print '%0.3f percent of RM clusters are separated by 3-sigma_planck_beam'%(100.*frac_3sigma)    
    ipdb.set_trace()
    def check_models(self):
        '''
        Displays a plot of the models against that taken from a
        respected website (https://www.pvlighthouse.com.au/)
        '''
        plt.figure('Intrinsic bandgap')
        t = np.linspace(1, 500)

        for author in self.available_models():

            Eg = self.update(temp=t, author=author, multiplier=1.0)
            plt.plot(t, Eg, label=author)

        test_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'Si', 'check data', 'iBg.csv')

        data = np.genfromtxt(test_file, delimiter=',', names=True)

        for temp, name in zip(data.dtype.names[0::2], data.dtype.names[1::2]):
            plt.plot(
                data[temp], data[name], '--', label=name)

        plt.xlabel('Temperature (K)')
        plt.ylabel('Intrinsic Bandgap (eV)')

        plt.legend(loc=0)
        self.update(temp=0, author=author, multiplier=1.01)
Example #11
0
    def plot(self, title=None, **kwargs):
        """Generates a pylab plot from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        The first and last columns are taken as the X and Y
        values.  Any columns between are ignored.

        Parameters
        ----------
        title: Plot title, defaults to names of Y value columns

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.plot``.
        """
        import matplotlib.pylab as plt
        self.guess_plot_columns()
        self.x = self.x or range(len(self.ys[0]))
        coords = reduce(operator.add, [(self.x, y) for y in self.ys])
        plot = plt.plot(*coords, **kwargs)
        if hasattr(self.x, 'name'):
            plt.xlabel(self.x.name)
        ylabel = ", ".join(y.name for y in self.ys)
        plt.title(title or ylabel)
        plt.ylabel(ylabel)
        return plot
 def plot_values(self, TITLE, SAVE):
     plot(self.list_of_densities, self.list_of_pressures)
     title(TITLE)
     xlabel("Densities")
     ylabel("Pressure")
     savefig(SAVE)
     show()
Example #13
0
 def test_simple_gen(self):
     self_con = .8
     other_con = 0.05
     g = self.gen.gen_stoch_blockmodel(min_degree=1, blocks=5, self_con=self_con, other_con=other_con,
                                       powerlaw_exp=2.1, degree_seq='powerlaw', num_nodes=1000, num_links=3000)
     deg_hist = vertex_hist(g, 'total')
     res = fit_powerlaw.Fit(g.degree_property_map('total').a, discrete=True)
     print 'powerlaw alpha:', res.power_law.alpha
     print 'powerlaw xmin:', res.power_law.xmin
     if len(deg_hist[0]) != len(deg_hist[1]):
         deg_hist[1] = deg_hist[1][:len(deg_hist[0])]
     print 'plot degree dist'
     plt.plot(deg_hist[1], deg_hist[0])
     plt.xscale('log')
     plt.xlabel('degree')
     plt.ylabel('#nodes')
     plt.yscale('log')
     plt.savefig('deg_dist_test.png')
     plt.close('all')
     print 'plot graph'
     pos = sfdp_layout(g, groups=g.vp['com'], mu=3)
     graph_draw(g, pos=pos, output='graph.png', output_size=(800, 800),
                vertex_size=prop_to_size(g.degree_property_map('total'), mi=2, ma=30), vertex_color=[0., 0., 0., 1.],
                vertex_fill_color=g.vp['com'],
                bg_color=[1., 1., 1., 1.])
     plt.close('all')
     print 'init:', self_con / (self_con + other_con), other_con / (self_con + other_con)
     print 'real:', gt_tools.get_graph_com_connectivity(g, 'com')
Example #14
0
   def __call__(self, **params):

       p = ParamOverrides(self, params)
       fig = plt.figure(figsize=(5, 5))

       # This one-liner works in Octave, but in matplotlib it
       # results in lines that are all connected across rows and columns,
       # so here we plot each line separately:
       #   plt.plot(x,y,"k-",transpose(x),transpose(y),"k-")
       # Here, the "k-" means plot in black using solid lines;
       # see matplotlib for more info.
       isint = plt.isinteractive() # Temporarily make non-interactive for
       # plotting
       plt.ioff()
       for r, c in zip(p.y[::p.skip], p.x[::p.skip]):
           plt.plot(c, r, "k-")
       for r, c in zip(np.transpose(p.y)[::p.skip],np.transpose(p.x)[::p.skip]):
           plt.plot(c, r, "k-")

       # Force last line avoid leaving cells open
       if p.skip != 1:
           plt.plot(p.x[-1], p.y[-1], "k-")
           plt.plot(np.transpose(p.x)[-1], np.transpose(p.y)[-1], "k-")

       plt.xlabel('x')
       plt.ylabel('y')
       # Currently sets the input range arbitrarily; should presumably figure out
       # what the actual possible range is for this simulation (which would presumably
       # be the maximum size of any GeneratorSheet?).
       plt.axis(p.axis)

       if isint: plt.ion()
       self._generate_figure(p)
       return fig
Example #15
0
def plot_confusion_matrix(cm, title='', cmap=plt.cm.Blues):
    #print cm
    #display vehicle, idle, walking accuracy respectively
    #display overall accuracy
    print type(cm)
   # plt.figure(index
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    #plt.figure("")
    plt.title("Confusion Matrix")
    plt.colorbar()
    tick_marks = [0,1,2]
    target_name = ["driving","idling","walking"]


    plt.xticks(tick_marks,target_name,rotation=45)

    plt.yticks(tick_marks,target_name,rotation=45)
    print len(cm[0])

    for i in range(0,3):
        for j in range(0,3):
         plt.text(i,j,str(cm[i,j]))
    plt.tight_layout()
    plt.ylabel("Actual Value")
    plt.xlabel("Predicted Outcome")
Example #16
0
    def visualization2(self, sp_to_vis=None):
        if sp_to_vis:
            species_ready = list(set(sp_to_vis).intersection(self.all_sp_signatures.keys()))
        else:
            raise Exception('list of driver species must be defined')

        if not species_ready:
            raise Exception('None of the input species is a driver')

        for sp in species_ready:
            # Setting up figure
            plt.figure()
            plt.subplot(313)

            mon_val = OrderedDict()
            signature = self.all_sp_signatures[sp]
            for idx, mon in enumerate(list(set(signature))):
                if mon[0] == 'C':
                    mon_val[self.all_comb[sp][mon] + (-1,)] = idx
                else:
                    mon_val[self.all_comb[sp][mon]] = idx

            mon_rep = [0] * len(signature)
            for i, m in enumerate(signature):
                if m[0] == 'C':
                    mon_rep[i] = mon_val[self.all_comb[sp][m] + (-1,)]
                else:
                    mon_rep[i] = mon_val[self.all_comb[sp][m]]
            # mon_rep = [mon_val[self.all_comb[sp][m]] for m in signature]

            y_pos = numpy.arange(len(mon_val.keys()))
            plt.scatter(self.tspan[1:], mon_rep)
            plt.yticks(y_pos, mon_val.keys())
            plt.ylabel('Monomials', fontsize=16)
            plt.xlabel('Time(s)', fontsize=16)
            plt.xlim(0, self.tspan[-1])
            plt.ylim(0, max(y_pos))

            plt.subplot(312)

            for name in self.model.odes[sp].as_coefficients_dict():
                mon = name
                mon = mon.subs(self.param_values)
                var_to_study = [atom for atom in mon.atoms(sympy.Symbol)]
                arg_f1 = [numpy.maximum(self.mach_eps, self.y[str(va)][1:]) for va in var_to_study]
                f1 = sympy.lambdify(var_to_study, mon)
                mon_values = f1(*arg_f1)
                mon_name = str(name).partition('__')[2]
                plt.plot(self.tspan[1:], mon_values, label=mon_name)
            plt.ylabel('Rate(m/sec)', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.1, 0.85), loc='upper right', ncol=1)

            plt.subplot(311)
            plt.plot(self.tspan[1:], self.y['__s%d' % sp][1:], label=parse_name(self.model.species[sp]))
            plt.ylabel('Molecules', fontsize=16)
            plt.legend(bbox_to_anchor=(-0.15, 0.85), loc='upper right', ncol=1)
            plt.suptitle('Tropicalization' + ' ' + str(self.model.species[sp]))

            # plt.show()
            plt.savefig('s%d' % sp + '.png', bbox_inches='tight', dpi=400)
Example #17
0
def cdf(x,colsym="",lab="",lw=4):
    """ plot the cumulative density function

    Parameters
    ----------

    x : np.array()
    colsym : string
    lab : string
    lw : int
        linewidth

    Examples
    --------

    >>> import numpy as np

    """
    rcParams['legend.fontsize']=20
    rcParams['font.size']=20

    x  = np.sort(x)
    n  = len(x)
    x2 = np.repeat(x, 2)
    y2 = np.hstack([0.0, repeat(np.arange(1,n) / float(n), 2), 1.0])
    plt.plot(x2,y2,colsym,label=lab,linewidth=lw)
    plt.grid('on')
    plt.legend(loc=2)
    plt.xlabel('Ranging Error[m]')
    plt.ylabel('Cumulative Probability')
Example #18
0
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
Example #19
0
def plot_feat_hist(data_name_list, filename=None):
    pylab.clf()
    # import pdb;pdb.set_trace()
    num_rows = 1 + (len(data_name_list) - 1) / 2
    num_cols = 1 if len(data_name_list) == 1 else 2
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Density')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, facecolor='green', alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
Example #20
0
	def plot_cell(self,cell_number=0,label='insert_label'):

		current_cell = self.cell_list[cell_number]
		temp = current_cell.temp
		cd_signal = current_cell.cd_signal
		cd_calc = current_cell.cd_calc()
		
		ax = pylab.gca()

		pylab.plot(temp,cd_signal,'o',color='black')
                pylab.plot(temp,cd_calc,color='black')
		pylab.xlabel(r'Temperature ($^{\circ}$C)')
		pylab.ylabel('mdeg')
		pylab.ylim([-25,-4])
		dH = numpy.round(current_cell.dH, decimals=1)
		Tm = numpy.round(current_cell.Tm-273.15, decimals=1)
		nf = current_cell.nf
		nu = current_cell.nu
		textstr_dH = '${\Delta}H_{m}$ = %.1f kcal/mol' %dH
		textstr_Tm ='$T_{m}$ = %.1f $^{\circ}$C' %Tm
		textstr_nf ='$N_{folded}$ = %d' %nf
		textstr_nu ='$N_{unfolded}$ = %d'%nu
		ax.text(8,-6,textstr_dH, fontsize=16,ha='left',va='top')
		ax.text(8,-7.5,textstr_Tm, fontsize=16,ha='left',va='top')
		ax.text(8,-9,textstr_nf, fontsize=16,ha='left',va='top')
		ax.text(8,-10.5,textstr_nu, fontsize=16,ha='left',va='top')
		pylab.title(label)		
		pylab.show()

		return
Example #21
0
def plot_peaks(spectra, ref, zl, pl, filename=''):
  plt.figure();
  plt.title("Debug: Peak fitting for '%s'" % filename);
  plt.xlabel("y-position [px]");
  plt.ylabel("Intensity");

  Nspectra, Npx = spectra.shape;

  for s in xrange(Nspectra):
    scale = 1./spectra.max();
    offset= -s*0.1;

    # plot data
    plt.plot(spectra[s]*scale + offset,'k',linewidth=2);

    # plot first peak
    p,A,w = zl[s];
    x = np.arange(-2*w, 2*w) + p;
    plt.plot(x,gauss(x,*zl[s])*scale + offset,'r');
  
    # plot second peak
    if ref is not None:
      p,A   = pl[s];
      x = np.arange(len(ref)) - len(ref)/2 + p;
      plt.plot(x,ref/ref.max()*A*scale + offset,'g');
Example #22
0
def set_axis_0():
    pylab.xlabel('time (days)')
    pylab.gcf().subplots_adjust(top=1.0-0.13, bottom=0.2, right=1-0.02,
                                left=0.2)
    a = list(pylab.axis())
    na = [a[0], a[1], 0, a[3]*1.05]
    pylab.axis(na)
    def handle(self, *args, **options):
        try:
            from matplotlib import pylab as pl
            import numpy as np
        except ImportError:
            raise Exception('Be sure to install requirements_scipy.txt before running this.')

        all_names_and_counts = RawCommitteeTransactions.objects.all().values('attest_by_name').annotate(total=Count('attest_by_name')).order_by('-total')
        all_names_and_counts_as_tuple_and_sorted = sorted([(row['attest_by_name'], row['total']) for row in all_names_and_counts], key=lambda row: row[1])
        print "top ten attestors:  (name, number of transactions they attest for)"
        for row in all_names_and_counts_as_tuple_and_sorted[-10:]:
            print row

        n_bins = 100
        filename = 'attestor_participation_distribution.png'

        x_max = all_names_and_counts_as_tuple_and_sorted[-31][1]  # eliminate top outliers from hist
        x_min = all_names_and_counts_as_tuple_and_sorted[0][1]

        counts = [row['total'] for row in all_names_and_counts]
        pl.figure(1, figsize=(18, 6))
        pl.hist(counts, bins=np.arange(x_min, x_max, (float(x_max)-x_min)/100) )
        pl.title('Histogram of Attestor Participation in RawCommitteeTransactions')
        pl.xlabel('Number of transactions a person attested for')
        pl.ylabel('Number of people')
        pl.savefig(filename)
def flipPlot(minExp, maxExp):
    """假定minEXPy和maxExp是正整数且minExp<maxExp
    绘制出2**minExp到2**maxExp次抛硬币的结果
    """
    ratios = []
    diffs = []
    aAxis = []
    for i in range(minExp, maxExp+1):
        aAxis.append(2**i)
    for numFlips in aAxis:
        numHeads = 0
        for n in range(numFlips):
            if random.random() < 0.5:
                numHeads += 1
        numTails = numFlips - numHeads
        ratios.append(numHeads/numFlips)
        diffs.append(abs(numHeads-numTails))
    plt.figure()
    ax1 = plt.subplot(121)
    plt.title("Difference Between Heads and Tails")
    plt.xlabel('Number of Flips')
    plt.ylabel('Abs(#Heads - #Tails)')
    ax1.semilogx(aAxis, diffs, 'bo')
    ax2 = plt.subplot(122)
    plt.title("Heads/Tails Ratios")
    plt.xlabel('Number of Flips')
    plt.ylabel("#Heads/#Tails")
    ax2.semilogx(aAxis, ratios, 'bo')
    plt.show()
Example #25
0
def plot_q(model='cem', r_min=0.0, r_max=6371.0, dr=1.0):
    """
    Plot a radiallysymmetric Q model.

    plot_q(model='cem', r_min=0.0, r_max=6371.0, dr=1.0):

    r_min=minimum radius [km], r_max=maximum radius [km], dr=radius
    increment [km]

    Currently available models (model): cem, prem, ql6
    """
    import matplotlib.pylab as plt

    r = np.arange(r_min, r_max + dr, dr)
    q = np.zeros(len(r))

    for k in range(len(r)):

        if model == 'cem':
            q[k] = q_cem(r[k])
        elif model == 'ql6':
            q[k] = q_ql6(r[k])
        elif model == 'prem':
            q[k] = q_prem(r[k])

    plt.plot(r, q, 'k')
    plt.xlim((0.0, r_max))
    plt.xlabel('radius [km]')
    plt.ylabel('Q')
    plt.show()
Example #26
0
def plotMassFunction(im, pm, outbase, mmin=9, mmax=13, mstep=0.05):
    """
    Make a comparison plot between the input mass function and the 
    predicted projected correlation function
    """
    plt.clf()

    nmbins = ( mmax - mmin ) / mstep
    mbins = np.logspace( mmin, mmax, nmbins )
    mcen = ( mbins[:-1] + mbins[1:] ) /2
    
    plt.xscale( 'log', nonposx = 'clip' )
    plt.yscale( 'log', nonposy = 'clip' )
    
    ic, e, p = plt.hist( im, mbins, label='Original Halos', alpha=0.5, normed = True)
    pc, e, p = plt.hist( pm, mbins, label='Added Halos', alpha=0.5, normed = True)
    
    plt.legend()
    plt.xlabel( r'$M_{vir}$' )
    plt.ylabel( r'$\frac{dN}{dM}$' )
    #plt.tight_layout()
    plt.savefig( outbase+'_mfcn.png' )
    
    mdtype = np.dtype( [ ('mcen', float), ('imcounts', float), ('pmcounts', float) ] )
    mf = np.ndarray( len(mcen), dtype = mdtype )
    mf[ 'mcen' ] = mcen
    mf[ 'imcounts' ] = ic
    mf[ 'pmcounts' ] = pc

    fitsio.write( outbase+'_mfcn.fit', mf )
Example #27
0
def plot_runtime_results(results):
    plt.rcParams["figure.figsize"] = 7,7
    plt.rcParams["font.size"] = 22
    matplotlib.rc("xtick", labelsize=24)
    matplotlib.rc("ytick", labelsize=24)

    params = {"text.fontsize" : 32,
              "font.size" : 32,
              "legend.fontsize" : 30,
              "axes.labelsize" : 32,
              "text.usetex" : False
              }
    plt.rcParams.update(params)
    
    #plt.semilogx(results[:,0], results[:,3], 'r-x', lw=3)
    #plt.semilogx(results[:,0], results[:,1], 'g-D', lw=3)
    #plt.semilogx(results[:,0], results[:,2], 'b-s', lw=3)

    plt.plot(results[:,0], results[:,3], 'r-x', lw=3, ms=10)
    plt.plot(results[:,0], results[:,1], 'g-D', lw=3, ms=10)
    plt.plot(results[:,0], results[:,2], 'b-s', lw=3, ms=10)

    plt.legend(["Chain", "Tree", "FFT Tree"], loc="upper left")
    plt.xticks([1e5, 2e5, 3e5])
    plt.yticks([0, 60, 120, 180])

    plt.xlabel("Problem Size")
    plt.ylabel("Runtime (sec)")
    return results
Example #28
0
def fdr(p_values=None, verbose=0):
    """Returns the FDR associated with each p value

    Parameters
    -----------
    p_values : ndarray of shape (n)
        The samples p-value

    Returns
    -------
    q : array of shape(n)
        The corresponding fdr values
    """
    p_values = check_p_values(p_values)
    n_samples = p_values.size
    order = p_values.argsort()
    sp_values = p_values[order]

    # compute q while in ascending order
    q = np.minimum(1, n_samples * sp_values / np.arange(1, n_samples + 1))
    for i in range(n_samples - 1, 0, - 1):
        q[i - 1] = min(q[i], q[i - 1])

    # reorder the results
    inverse_order = np.arange(n_samples)
    inverse_order[order] = np.arange(n_samples)
    q = q[inverse_order]

    if verbose:
        import matplotlib.pylab as mp
        mp.figure()
        mp.xlabel('Input p-value')
        mp.plot(p_values, q, '.')
        mp.ylabel('Associated fdr')
    return q
Example #29
0
def plotFeaturePDF(ift, pft, outbase, fmin=0.0, fmax=1.0, fstep=0.01):
    """
    Plot a comparison between the input feature distribution and the 
    feature distribution of the predicted halos
    """
    plt.clf()
    nfbins = ( fmax - fmin ) / fstep
    fbins = np.logspace( fmin, fmax, nfbins )
    fcen = ( fbins[:-1] + fbins[1:] ) / 2

    plt.xscale( 'log', nonposx='clip' )
    plt.yscale( 'log', nonposy='clip' )
    
    ic, e, p = plt.hist( ift, fbins, label='Original Halos', alpha=0.5, normed=True )
    pc, e, p = plt.hist( pft, fbins, label='Added Halos', alpha=0.5, normed=True )

    plt.legend()
    plt.xlabel( r'$\delta$' )
    plt.savefig( outbase+'_fpdf.png' )

    fdtype = np.dtype( [ ('fcen', float), ('ifcounts', float), ('pfcounts', float) ] )
    fd = np.ndarray( len(fcen), dtype = fdtype )
    fd[ 'mcen' ] = fcen
    fd[ 'imcounts' ] = ic
    fd[ 'pmcounts' ] = pc

    fitsio.write( outbase+'_fpdf.fit', fd )
Example #30
0
    def plot_corner_posteriors(self, savefile=None, labels=["T1", "R1", "Av", "T2", "R2"]):
        '''
        Plots the corner plot of the MCMC results.
        '''
        ndim = len(self.sampler.flatchain[0,:])
        chain = self.sampler
        samples = chain.flatchain
        
        samples = samples[:,0:ndim]  
        plt.figure(figsize=(8,8))
        fig = corner.corner(samples, labels=labels[0:ndim])
        plt.title("MJD: %.2f"%self.mjd)
        name = self._get_save_path(savefile, "mcmc_posteriors")
        plt.savefig(name)
        plt.close("all")
        

        plt.figure(figsize=(8,ndim*3))
        for n in range(ndim):
            plt.subplot(ndim,1,n+1)
            chain = self.sampler.chain[:,:,n]
            nwalk, nit = chain.shape
            
            for i in np.arange(nwalk):
                plt.plot(chain[i], lw=0.1)
                plt.ylabel(labels[n])
                plt.xlabel("Iteration")
        name_walkers = self._get_save_path(savefile, "mcmc_walkers")
        plt.tight_layout()
        plt.savefig(name_walkers)
        plt.close("all")  
filename = 'beta_alpha.dat'

# import data
data = np.loadtxt(filename)

# initial size of plot window
plt.figure(figsize=(8, 6))

x = np.linspace(0, len(data), len(data))
# plot
plt.plot(data[:, 0], '-', label=r'$\beta=$' + str(0.51))
for i in range(1, 6):
    plt.plot(data[:, i], '-', label=r'$\beta=$' + str(0.5 + i / 10))

# labels
plt.xlabel('# gradient steps', fontsize=20)
plt.ylabel(r'$\alpha$', fontsize=20)

# legend
plt.legend(loc='upper right')
leg = plt.gca().get_legend()
ltext = leg.get_texts()
plt.setp(ltext, fontsize=12)

# axis limits)
plt.ylim(0.05, 0.25)
# tick fontsize
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.title('Convergence of ' + r'$\alpha$' + ' for different ' + r'$\beta$' '')
plt.savefig('4_alpha_convergence.png')
Example #32
0
plt.rc('ytick',labelsize=0.5)

#RESID = RESID1
import seaborn as sns

def create_dataset(dataset, look_back):
	dataX, dataY = [], []
	for i in range(len(dataset)-look_back):
		a = dataset[i:(i+look_back)]
		dataX.append(a)
		dataY.append(dataset[i + look_back])
	return np.array(dataX), np.array(dataY)
 
x,y =  create_dataset(DATA[:,1],4)
sns.distplot(RESID[k])
plt.xlabel('Residual size',fontsize = 13)
plt.ylabel('Residual counts',fontsize = 13)
    
plt.plot(RESID[k])
plt.ylabel('Residual amplitude',fontsize = 13)
plt.xlabel('Week',fontsize = 13)

import statsmodels.api as sm
sm.graphics.tsa.plot_acf(RESID[k],lags=25)
np.array(abs(RESID[k])).sum()/(len(RESID[k]))

from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.diagnostic import het_white

df_resid = pd.DataFrame(RESID[k],columns = ['resid'])
X= np.concatenate((np.ones(30).reshape(-1,1),x[-30:,:]),axis = 1)
Created on Sun May 16 13:33:21 2021

@author: Dhiraj Wagh
"""

#Importing the Libraries.
import numpy as np
import pandas as pd
import matplotlib.pylab as plt

dataset = pd.read_csv('Ads_CTR_Optimisation.csv')

# IMPLEMENTING THE ALGORITHM RANDEM SELECTION
import random
N = 10000
d = 10
ads_selected = []
total_reward = 0
for n in range(0, N):
    ad = random.randrange(d)
    ads_selected.append(ad)
    reward = dataset.values[n, ad]
    total_reward = total_reward + reward

#Visualizing the results - Histogram
plt.hist(ads_selected)
plt.title('Histogram of ads selections')
plt.xlabel('Ads')
plt.ylabel('Number of times each ad was selected')
plt.show()
Example #34
0
# set the inital conditions for the two populations
R0 = 10
C0 = 5
RC0 = sc.array([R0, C0])

# now, numerically integrate this system forwards from these conditions
pops, infodict = intergrate.odeint(dCR_dt, RC0, t, full_output=True)

# plot it
f1 = p.figure()
p.plot(t, pops[:, 0], 'g-', label='Resource density')  # Plot
p.plot(t, pops[:, 1], 'b-', label='Consumer density')
p.grid()
p.legend(loc='best')
p.xlabel('Time')
p.ylabel('Population density')
p.title('Consumer-Resource population dynamics')

# add the parameter values to the plot. Currently in the plot but for
# multiple plots as part of a pipeline this should be substituted for
# something outside the plot grid.
p.text(6, 15, "r = {}, a = {}, z = {}, e = {}, K = {}".format(r, a, z, e, K))

# save the figure as a pdf`
f1.savefig('../Results/Plots/LV2_model.pdf')

# plot the second circular figure. this just has the values from above as axis
f2 = p.figure()
p.plot(pops[:, 0], pops[:, 1], 'r-')  # Plot
p.grid()
    return 0.01 * x ** 2 + 0.1 * x

def function_2(x):
    return x[0] ** 2 + x[1] ** 2

print(numerical_gradient(function_2, np.array([3.0, 4.0])))
print(numerical_gradient(function_2, np.array([0.0, 2.0])))
print(numerical_gradient(function_2, np.array([3.0, 0.0])))

init_x = np.array([-3.0, 4.0])
t = gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100)
print(t)



'''
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.plot(x, y)

k1 = numerical_diff(function_1, 5)
y1 = k1 * x + (function_1(5) - k1 * 5)
plt.plot(x, y1)

k2 = numerical_diff(function_1, 15)
y2 = k2 * x + (function_1(15) - k2 * 15)
plt.plot(x, y2)

plt.show()
nwalk = 10000
nstep = 100
x = np.zeros(nwalk)
y = np.zeros(nwalk)
r2 = np.zeros(nwalk)
sum_walk = np.zeros(nstep)

for iwalk in range(nwalk):
    random.seed(None)
    x[iwalk] = 0
    y[iwalk] = 0
    r2[iwalk] = 0
    for istep in range(nstep):
        dx = 2*random.random()-1
        dy = 2*random.random()-1
        dr = np.sqrt(dx**2+dy**2)
        x[iwalk] = x[iwalk] + dx/dr
        y[iwalk] = y[iwalk] + dy/dr
        r2[iwalk] = x[iwalk]**2 + y[iwalk]**2
        sum_walk[istep] = sum_walk[istep] + r2[iwalk]
for istep in range(nstep):
    sum_walk[istep] = sum_walk[istep]/nwalk

time = np.arange(nstep)
pl.plot(time, sum_walk, 'r-', label='distribution',linewidth=1.0)
pl.xlim(0,100)
pl.ylim(0,120)
pl.xlabel(r'walk steps', fontsize=20)
pl.ylabel(r'<r2>', fontsize=20)
pl.show()
Example #37
0
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pylab as plt
import numpy as np
import sympy as sym
import time
sym.init_printing(use_unicode=True)


# In[2]:


H = [20,25,30,35,40,45,50]
f = [101,115, 92,64,60,50,49]

plt.scatter(H,f)
plt.xlabel('Hormone Level')
plt.ylabel('Fatalities')
f = np.matrix(f).T


# We want to determine a line that is expressed by the following equation 
# 
# $$f = aH + b,$$
# 
# to approximate the connection between Hormone dosage ($H$) and Fatalities $f$. 
# That is, we want to find $a$ (slope) and $b$ (y-intercept) for this line. First we define the variable $ 
# x = \left[
# \begin{matrix}
#     a  \\
#     b  
# \end{matrix}
from statsmodels.tsa.seasonal import seasonal_decompose

'''Decomposiçãp da série temporal para o produção total onshore de gás natural'''

#Preparação do dataframe para a decomposição temporal
dateparse = lambda dates: pd.datetime.strptime(dates, '%Y')
data = pd.read_csv('Produção_gas_natural_total_onshore_serie_temporal.csv',
                   parse_dates = ['Ano'], index_col = 'Ano', date_parser = dateparse)

data = data.drop('Unnamed: 0', axis = 1)

#Visualização do gráfico da série temporal
ts = data['Produção de gás natural (m³)']

plt.figure(figsize = (10, 5))
plt.xlabel('Anos')
plt.ylabel('Produção de gás natural (m³)')
plt.plot(ts)

#Aplicação da decomposição da série temporal
decomposicao = seasonal_decompose(ts)
tendencia = decomposicao.trend
sazonal = decomposicao.seasonal
residuo = decomposicao.resid

plt.plot(tendencia)
plt.plot(sazonal)
plt.plot(residuo)

plt.figure(figsize = (10, 5))
plt.subplot(4, 1, 1)
Example #39
0
#!/usr/bin/python3
import numpy as np
import matplotlib.pylab as plt
from scipy.stats import linregress

data = np.loadtxt("ns_128.txt")
y, x = np.histogram(data, bins=200, range=[0, 200])
x = x[:200]
x = np.log10(x)
y = np.log10(y)
mask = np.isfinite(x) & np.isfinite(y)
slope, intercept, r_value, p_value, std_err = linregress(x[mask], y[mask])
# Tengo errores de division por cero
# Hay que eliminar los ceros primero
# Puedo usar menos bins
# Ademas para el ajuste necesito quedarme solo
# con la parte lineal, eso hay que hacerlo a mano
plt.plot(x[mask], y[mask], 'ro')
plt.plot(x[mask], slope * x[mask] + intercept, 'b')
plt.ylabel(r'$n_{s}(p_c)$ (log)')
plt.xlabel(r'Tamaño de cluster s (log)')
plt.savefig('nspctau.png')
print("Tau: ", -slope)
plt.show()
solver_params['collision_model']='srt'
solver_params['phrqc_flags']={}
solver_params['phrqc_flags']['only_interface']=True
#solver_params['phrqc_flags']['smart_run']=True
#solver_params['phrqc_smart_run_tol']=1e-8
rt= yantra.PhrqcReactiveTransport('AdvectionDiffusion', domain,
                                  domain_params,{},solver_params)
#%%run model
time=[]
AvgCa =[]
iters = 2
while rt.iters < iters: #rt.time<=1:#20
    rt.advance()
    AvgCa.append(np.sum(rt.fluid.Ca.c)/np.sum(rt.fluid.Ca.nodetype<=0)) 
    time.append(rt.time)
        
#%%plot results
plt.figure()
plt.plot(time,AvgCa)
plt.xlabel('Time [s]')
plt.ylabel('Avg. Ca conc in aqeuous phase [mM]')
plt.show()

plt.figure()
plt.imshow(rt.fluid.Ca.c)
plt.colorbar()
plt.title('Ca concentarion [mol/l]')
plt.show()

print(rt.fluid.Ca._ss[3:8,3:8] + rt.fluid.Ca._c[3:8,3:8])
print(rt.solid.portlandite.c[5,5])
Example #41
0
# specify the lasso regression model
model = LassoLarsCV(cv=10, precompute=False).fit(pred_train, tar_train)

# print variable names and regression coefficients
print(dict(zip(predictors.columns, model.coef_)))

# plot coefficient progression
m_log_alphas = -np.log10(model.alphas_)
ax = plt.gca()
plt.plot(m_log_alphas, model.coef_path_.T)
plt.axvline(-np.log10(model.alpha_),
            linestyle='--',
            color='k',
            label='alpha CV')
plt.ylabel('Regression Coefficients')
plt.xlabel('-log(alpha)')
plt.title('Regression Coefficients Progression for Lasso Paths')

# plot mean square error for each fold
m_log_alphascv = -np.log10(model.cv_alphas_)
plt.figure()
plt.plot(m_log_alphascv, model.mse_path_, ':')
plt.plot(m_log_alphascv,
         model.mse_path_.mean(axis=-1),
         'k',
         label='Average across the folds',
         linewidth=2)
plt.axvline(-np.log10(model.alpha_),
            linestyle='--',
            color='k',
            label='alpha CV')
Example #42
0
####output
f = open('workfile','w')
f.write("r1\ttheta\tsexp\tstheo\tmiller\ta\n")
for i in range(0,len(a1)):
	f.write(str(round(r1_mess[i],2))+ "\t" + str( round(theta1[i],2)) + "\t" +  str( round(s_exp1[i],2)) +  "\t" + str(round(s_theo1[i],2)) +  "\t" + str(h1[i])+str(k1[i])+str(l1[i]) +str("\t") + str(round(a1[i],2)))
	f.write("\n")

f.write("\n\n\n")
f.write("r2\ttheta\tsexp\tstheo\tmiller\ta\n")
for i in range(0,len(a2)):
	f.write(str(round(r2_mess[i],2))+ "\t" + str( round(theta2[i],2)) + "\t" +  str( round(s_exp2[i],2)) +  "\t" + str(round(s_theo2[i],2)) +  "\t" + str(h2[i])+str(k2[i])+str(l2[i]) +str("\t")+ str(round(a2[i],2)))
	f.write("\n")

f.close()

plt.plot(x,fit1)
plt.xlim((0,1))
plt.title("Korrektur zum Gitterparameter der ersten Probe")
plt.xlabel(r"cos$^2 (\theta)$")
plt.ylabel("Gitterparameter $a$")
#plt.legend(loc=2)
#plt.plot(x,fit2)
ax.scatter(cosSquare1, a1)
#plt.savefig("a1",dpi=100)

#ax.scatter(cosSquare2, a2)
#plt.savefig("a2",dpi=100)
plt.show()

Example #43
0
def df(x):
    return 0.02 * x + 0.1


def analyticLine(f, x):
    a = df(x)
    b = f(x) - a * x
    return lambda t: a * t + b


def numLine(f, x):
    a = numericalDifferentiation(f, x)
    b = f(x) - a * x
    return lambda t: a * t + b


x = np.arange(0.0, 20.0, 0.1)
#x = np.arange(0.0, 100.0, 0.1)

plt.xlabel('x')
plt.ylabel('f(x)')
plt.plot(x, f(x))
plt.plot(x, analyticLine(f, 5)(x))
plt.plot(x, analyticLine(f, 10)(x))
plt.plot(x, numLine(f, 5)(x), linestyle='--')
plt.plot(x, numLine(f, 10)(x), linestyle='--')
#for i in range(1, 100):
#	plt.plot(x, numLine(f, i)(x))
plt.show()
Example #44
0
# mean_auc = auc(mean_fpr, mean_tpr)
# std_auc = np.std(aucs)
# plt.plot(mean_fpr, mean_tpr, color='b',
#          label=r'Mean ROC (AUC = %0.3f $\pm$ %0.3f)' % (mean_auc, std_auc),
#          lw=2, alpha=.8)

# std_tpr = np.std(tprs, axis=0)
# tprs_upper = np.minimum(mean_tpr + 3*std_tpr, 1)
# tprs_lower = np.maximum(mean_tpr - 3*std_tpr, 0)
# plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.5,
#                  label=r'$\pm$ 3 std. dev.')

plt.xlim([0, 1])
plt.ylim([0, 1])
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")



epochs_list = range(1, epochs+1)


plt.figure(2)
for i in range(nb_K_Fold-1):
    plt.plot(epochs_list, acc_list[i], 'blue', label='Training acc')
    plt.plot(epochs_list, val_acc_list[i], 'red', label='Validation acc')

plt.figure(3)
Example #45
0
def plot_table(*positional_parameters,
               errorbars=None,
               xrange=None,
               yrange=None,
               title="",
               xtitle="",
               ytitle="",
               show=1,
               legend=None,
               legend_position=None,
               color=None,
               xlog=False,
               ylog=False):

    n_arguments = len(positional_parameters)
    if n_arguments == 0:
        return

    fig = plt.figure()

    if n_arguments == 1:
        y = positional_parameters[0]
        x = np.arange(y.size)
        plt.plot(x, y, label=legend)
    elif n_arguments == 2:
        x = positional_parameters[0]
        y = positional_parameters[1]

        if len(y.shape) == 1:
            y = np.reshape(y, (1, y.size))
            if isinstance(legend, str):
                legend = [legend]
            if isinstance(color, str):
                color = [color]

        for i in range(y.shape[0]):
            if legend is None:
                ilegend = None
            else:
                ilegend = legend[i]

            if color is None:
                icolor = None
            else:
                icolor = color[i]

            if errorbars is None:
                plt.plot(x, y[i], label=ilegend, color=icolor)
            else:
                plt.errorbar(x,
                             y[i],
                             yerr=errorbars[i],
                             label=ilegend,
                             color=icolor)
    else:
        raise Exception("Incorrect number of arguments")

    ax = plt.subplot(111)

    if xlog:
        ax.set_xscale("log")

    if ylog:
        ax.set_yscale("log")

    if legend is not None:
        if legend_position is None:
            legend_position = (1.1, 1.05)
        ax.legend(bbox_to_anchor=legend_position)

    plt.xlim(xrange)
    plt.ylim(yrange)

    plt.title(title)
    plt.xlabel(xtitle)
    plt.ylabel(ytitle)

    if show:
        plt.show()

    return fig
Example #46
0
import numpy as np
import matplotlib.pylab as plt
from p47_ステップ関数のグラフ import step_function
from p48_シグモイド関数 import sigmoid

if __name__ == '__main__':
    x = np.arange(-5.0, 5.0, 0.1)
    y1 = step_function(x)
    y2 = sigmoid(x)
    plt.plot(x, y1, label="step")
    plt.plot(x, y2, linestyle="--", label="sigmoid")  # 破線で描画
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("step & sigmoid")
    plt.legend(
    )  # plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=0, fontsize=18)
    plt.ylim(-0.1, 1.1)
    plt.show()
    # 1エポックごとに認識精度算出
    if i % iter_per_epoch == 0:
        train_acc = network.accuracy(x_train, t_train)
        test_acc = network.accuracy(x_test, t_test)
        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)

        # 経過表示
        print(f"[更新数]{i: >4} [損失関数の値]{loss:.4f} "
              f"[訓練データの認識精度]{train_acc:.4f} [テストデータの認識精度]{test_acc:.4f}")

#! 損失関数の値の推移を描画
x = np.arange(len(train_loss_list))
plt.plot(x, train_loss_list, label='loss')
plt.xlabel("iteration")
plt.ylabel("loss")
plt.xlim(left=0)
plt.ylim(bottom=0)
plt.show()

#! 訓練データとテストデータの認識制度の推移を描画
x2 = np.arange(len(train_acc_list))
plt.plot(x2, train_acc_list, label='train acc')
plt.plot(x2, test_acc_list, label='test acc', linestyle='--')
plt.xlabel("epochs")  #?エポック数:一つの訓練データを何回繰り返して学習させるか
plt.ylabel("accuracy")
plt.xlim(left=0)
plt.ylim(0, 1.0)
plt.legend(loc='lower right')  #?アンカーの位置(loc)を右下にする
plt.show()
Example #48
0
def plot(*positional_parameters,
         title="",
         xtitle="",
         ytitle="",
         xrange=None,
         yrange=None,
         show=1,
         legend=None,
         legend_position=None,
         color=None,
         marker=None,
         linestyle=None,
         xlog=False,
         ylog=False):

    if isinstance(positional_parameters, tuple):
        if len(positional_parameters
               ) == 1:  # in the cvase that input is a tuple with all curves
            positional_parameters = positional_parameters[0]

    n_arguments = len(positional_parameters)
    if n_arguments == 0:
        return

    fig = plt.figure()
    if n_arguments == 1:
        y = positional_parameters[0]
        x = np.arange(y.size)
        if linestyle == None:
            linestyle = '-'
        plt.plot(x,
                 y,
                 label=legend,
                 marker=marker,
                 color=color,
                 linestyle=linestyle)
    elif n_arguments == 2:
        x = positional_parameters[0]
        y = positional_parameters[1]
        if linestyle == None:
            linestyle = '-'
        plt.plot(x,
                 y,
                 label=legend,
                 color=color,
                 marker=marker,
                 linestyle=linestyle)
    elif n_arguments == 4:
        x1 = positional_parameters[0]
        y1 = positional_parameters[1]
        x2 = positional_parameters[2]
        y2 = positional_parameters[3]
        if legend is None:
            legend1 = None
            legend2 = None
        else:
            legend1 = legend[0]
            legend2 = legend[1]

        if color is None:
            color1 = None
            color2 = None
        else:
            color1 = color[0]
            color2 = color[1]

        if marker is None:
            marker1 = None
            marker2 = None
        else:
            marker1 = marker[0]
            marker2 = marker[1]

        if linestyle is None:
            linestyle1 = '-'
            linestyle2 = '-'
        else:
            linestyle1 = linestyle[0]
            linestyle2 = linestyle[1]

        plt.plot(x1,
                 y1,
                 label=legend1,
                 marker=marker1,
                 linestyle=linestyle1,
                 color=color1)
        plt.plot(x2,
                 y2,
                 label=legend2,
                 marker=marker2,
                 linestyle=linestyle2,
                 color=color2)
    elif n_arguments == 6:
        x1 = positional_parameters[0]
        y1 = positional_parameters[1]
        x2 = positional_parameters[2]
        y2 = positional_parameters[3]
        x3 = positional_parameters[4]
        y3 = positional_parameters[5]
        if legend is None:
            legend1 = None
            legend2 = None
            legend3 = None
        else:
            legend1 = legend[0]
            legend2 = legend[1]
            legend3 = legend[2]

        if color is None:
            color1 = None
            color2 = None
            color3 = None
        else:
            color1 = color[0]
            color2 = color[1]
            color3 = color[2]

        if marker is None:
            marker1 = None
            marker2 = None
            marker3 = None
        else:
            marker1 = marker[0]
            marker2 = marker[1]
            marker3 = marker[2]

        if linestyle is None:
            linestyle1 = '-'
            linestyle2 = '-'
            linestyle3 = '-'
        else:
            linestyle1 = linestyle[0]
            linestyle2 = linestyle[1]
            linestyle3 = linestyle[2]

        plt.plot(x1,
                 y1,
                 label=legend1,
                 marker=marker1,
                 linestyle=linestyle1,
                 color=color1)
        plt.plot(x2,
                 y2,
                 label=legend2,
                 marker=marker2,
                 linestyle=linestyle2,
                 color=color2)
        plt.plot(x3,
                 y3,
                 label=legend3,
                 marker=marker3,
                 linestyle=linestyle3,
                 color=color3)
    elif n_arguments == 8:
        x1 = positional_parameters[0]
        y1 = positional_parameters[1]
        x2 = positional_parameters[2]
        y2 = positional_parameters[3]
        x3 = positional_parameters[4]
        y3 = positional_parameters[5]
        x4 = positional_parameters[6]
        y4 = positional_parameters[7]
        if legend is None:
            legend1 = None
            legend2 = None
            legend3 = None
            legend4 = None
        else:
            legend1 = legend[0]
            legend2 = legend[1]
            legend3 = legend[2]
            legend4 = legend[3]
        if color is None:
            color1 = None
            color2 = None
            color3 = None
            color4 = None
        else:
            color1 = color[0]
            color2 = color[1]
            color3 = color[2]
            color4 = color[3]

        if marker is None:
            marker1 = None
            marker2 = None
            marker3 = None
            marker4 = None
        else:
            marker1 = marker[0]
            marker2 = marker[1]
            marker3 = marker[2]
            marker4 = marker[3]

        if linestyle is None:
            linestyle1 = '-'
            linestyle2 = '-'
            linestyle3 = '-'
            linestyle4 = '-'
        else:
            linestyle1 = linestyle[0]
            linestyle2 = linestyle[1]
            linestyle3 = linestyle[2]
            linestyle4 = linestyle[3]

        plt.plot(x1,
                 y1,
                 label=legend1,
                 marker=marker1,
                 linestyle=linestyle1,
                 color=color1)
        plt.plot(x2,
                 y2,
                 label=legend2,
                 marker=marker2,
                 linestyle=linestyle2,
                 color=color2)
        plt.plot(x3,
                 y3,
                 label=legend3,
                 marker=marker3,
                 linestyle=linestyle3,
                 color=color3)
        plt.plot(x4,
                 y4,
                 label=legend4,
                 marker=marker4,
                 linestyle=linestyle4,
                 color=color4)
    else:
        raise Exception("Incorrect number of arguments, maximum 4 data sets")
        # x = positional_parameters[0]
        # y = positional_parameters[1]
        # plt.plot(x,y,label=legend)

    ax = plt.subplot(111)
    if legend is not None:
        ax.legend(bbox_to_anchor=legend_position)

    if xlog:
        ax.set_xscale("log")

    if ylog:
        ax.set_yscale("log")

    plt.xlim(xrange)
    plt.ylim(yrange)

    plt.title(title)
    plt.xlabel(xtitle)
    plt.ylabel(ytitle)

    if show:
        plt.show()

    return fig
    plt.figure(figsize=(10, 7.5))    

    # Remove the plot frame lines.
    ax = plt.subplot(111)    
    ax.spines["top"].set_visible(False)    
    ax.spines["bottom"].set_visible(False)    
    ax.spines["right"].set_visible(False)    
    ax.spines["left"].set_visible(False)    
    ax.get_xaxis().tick_bottom()    
    ax.get_yaxis().tick_left()    

    plt.ylabel("Bikes in use", fontsize=15)  
    plt.title("DublinBikes average weekday usage", fontsize=22)  

    plt.xlabel("\nData source: CityBikes http://api.citybik.es/ | " 
           "Author: James Lawlor @lawlorino", fontsize=10)


    ax.plot(ts, df['mean'], color='black')
    ax.fill_between(ts, df['mean'] - df['std'], df['mean'] + df['std'], facecolor='blue', alpha=0.1)
#    ax.grid()
    plt.xlim(ts[0],ts[-1])
   # plt.ylim(0, np.max(df['mean'] + df['std']) + 100)
    ax.set_ylim(bottom = 0) 
    ax.xaxis.set_major_locator(dates.HourLocator(interval=2))
    hfmt = dates.DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(hfmt)

plt.show()

Example #50
0
#        
#np.savetxt('results/data/rho_norm_x001.out', rho_norm) 

plot1 =plt.plot( rho_norm/sqrt(len(rho_norm)))

ax=plt.subplot(111)
ax.set_xlim(1, 100)



plt.annotate(r'$ \Delta x_{PDE} = \Delta x_{SDE} = 0.005$', xy=(60, 0.15), xytext=(55, 0.20), fontsize=13)
plt.annotate(r'$ N=10000$', xy=(60, 0.15), xytext=(55, 0.18), fontsize=13)
#plt.xscale('log')
#plt.yscale('log')
#pl.ylabel(r'$T^*$', fontsize = 20)
plt.xlabel('m', fontsize = 16)
#plt.ylabel(r'$||\mathbb{E}(\mathbf{J}(\mathbf{U}_{SDE}) \cdot \mathbf{V})||_2 - ||\mathbf{J}(\mathbf{U}_{FP}) \cdot \mathbf{V})||_2 $', fontsize = 20)
#plt.ylabel(r'$||\mathbb{E}\left[\mathbf{J}(\mathbf{U}_{SDE}) \cdot \mathbf{V} \right]- \mathbf{J}(\mathbf{U}_{FP}) \cdot \mathbf{V}  )||_2 $', fontsize = 20)
plt.ylabel(r'$\frac{||\mathbb{E}[\mathbf{\rho}_{SDE}(m)  - \mathbf{\rho}_{FP}] ||_2 } {|| \mathbf{1}||_2}    $', fontsize = 20)
#plt.legend([plot1, plot2], loc='best') #, ['x=0.05', 'x=0.01']) #, loc='best') #, numpoints=1)
#pl.legend([line1, line2, line3],  'best')
#pl.legend( loc='best', numpoints = 1 )
#first_legend = pl.legend([line1], loc=1)
#plt.legend(bbox_to_anchor=(1, 1), numpoints = 1 )
#pl.legend([line3], bbox_to_anchor=(0.3, 0.6))
#ax = pl.gca().add_artist(first_legend)
#plt.savefig("results/Jve_sde-Jv_pde_compare.pdf")



plt.show()
Example #51
0
def sub_seek_dist(lists_cmd, options):
    ''' 
  seek_dist_record=sub_seek_dist(lists_cmd,options)
  seek distance calcuation
 
  inputs
    lists_cmd: n samples x 3 for LBA, size, flags
    options: control parameters
        plot_fontsize: the figure's font size
        plot_figure: >=1: plot the figure; otherwise not; default 1
        save_figure: >=1: save the figures
        export_report: >=1: export the figure/data into a ppt
        report_name: report name
        output_foldername: the output folder name for figures and report; default =''
        offset_time:  some trace is not started from zone. in this case. need to find the starting time of first event.
        spec_stack=[10,20,30];  % a vector specify the stack distance, for which we can collect the statistical value and output to the ppt file. for very large dataset ; otherwise specify some small numbers
  outputs
    seek_dist_record: structure for statistics of seek distance
 
  Author: [email protected]
  '''

    if hasattr(options, 'plot_fontsize'):
        plot_fontsize = options.plot_fontsize
    else:
        plot_fontsize = 10

    if hasattr(options, 'save_figure'):
        save_figure = options.save_figure
    else:
        save_figure = 1

    if hasattr(options, 'plot_figure'):
        plot_figure = options.plot_figure
    else:
        plot_figure = 1

    if hasattr(options, 'queue_len_setting'):
        queue_len_setting = options.queue_len_setting
    else:
        queue_len_setting = 2**(arange(0, 8, 1))

    num_queue_setting = shape(queue_len_setting)[0]

    if hasattr(options, 'plot_flags'):
        plot_flags = options.plot_flags
    else:
        plot_flags = [
            'r', 'k--', 'b-.', 'b:', 'y--', 'r:', 'y:', 'r-.', 'k-.', 'y', 'g:'
        ]

    if len(plot_flags) < num_queue_setting:
        print('Error! The figure flags for legend is smaller than required')
        return

    seek_write_only = zeros((num_queue_setting, 10))
    # 1 total R/W IO number, 2 sequnce number, 3 mean, 4 mean abs, 5 median, 6 mode, 7 mode couter, 8 min abs, 9 max abs, 10 std abs
    seek_read_only = zeros((num_queue_setting, 10))
    seek_all = zeros((num_queue_setting, 10))

    for queue_id in arange(0, num_queue_setting):
        print('Now check queue ID = ' + str(queue_id))
        # write
        seq_cmd_count, write_cmd_count, total_cmd, queued_lba_distance = seek_distance_stack(
            queue_len_setting[queue_id], lists_cmd, 0, 0)
        if write_cmd_count > 0:
            x, xi = mode(queued_lba_distance)
            seek_write_only[queue_id, :] = [
                total_cmd - write_cmd_count, seq_cmd_count,
                mean(queued_lba_distance),
                mean(abs(queued_lba_distance)),
                median(queued_lba_distance), x, xi,
                min(abs(queued_lba_distance)),
                max(abs(queued_lba_distance)),
                std(abs(queued_lba_distance))
            ]
        # read
        seq_cmd_count, read_cmd_count, total_cmd, queued_lba_distance = seek_distance_stack(
            queue_len_setting[queue_id], lists_cmd, 1, 0)
        if read_cmd_count > 0:
            x, xi = mode(queued_lba_distance)
            seek_read_only[queue_id, :] = [
                total_cmd - read_cmd_count, seq_cmd_count,
                mean(queued_lba_distance),
                mean(abs(queued_lba_distance)),
                median(queued_lba_distance), x, xi,
                min(abs(queued_lba_distance)),
                max(abs(queued_lba_distance)),
                std(abs(queued_lba_distance))
            ]
        # combined
        seq_cmd_count, all_cmd_count, total_cmd, queued_lba_distance = seek_distance_stack(
            queue_len_setting[queue_id], lists_cmd, 2, 0)
        if all_cmd_count:
            x, xi = mode(queued_lba_distance)
            # write command number, sequential command number, average queue LBA distance, average absolute queue LBA distance, median, mode value,mode frequency,min, max, std
            seek_all[queue_id, :] = [
                total_cmd - all_cmd_count, seq_cmd_count,
                mean(queued_lba_distance),
                mean(abs(queued_lba_distance)),
                median(queued_lba_distance), x, xi,
                min(abs(queued_lba_distance)),
                max(abs(queued_lba_distance)),
                std(abs(queued_lba_distance))
            ]

    seek_dist_record = []
    seek_dist_record = seek_dist_record_class(queue_len_setting, seek_all,
                                              seek_write_only, seek_read_only)

    if plot_figure == 1:

        figure()
        # hold(True)
        plot(transpose(queue_len_setting), seek_write_only[:, 6], 'b-')
        plot(transpose(queue_len_setting), seek_read_only[:, 6], 'r:')
        plot(transpose(queue_len_setting), seek_all[:, 6], 'k-.')
        xlabel('Queue length ')
        ylabel('Frequency')
        title('Mode Counter')
        legend(['write', 'read', 'combined'])
        savefig('sk_mode.eps')
        savefig('sk_mode.png')

        figure()
        # hold(True)
        plot(transpose(queue_len_setting), seek_write_only[:, 2], 'b-')
        plot(transpose(queue_len_setting), seek_read_only[:, 2], 'r:')
        plot(transpose(queue_len_setting), seek_all[:, 2], 'k-.')
        xlabel('Queue length ')
        ylabel('Value')
        title('Mean Value')
        legend(['write', 'read', 'combined'])
        savefig('sk_mean.eps')
        savefig('sk_mean.png')

        figure()
        # hold(True)
        plot(transpose(queue_len_setting), seek_write_only[:, 3], 'b-')
        plot(transpose(queue_len_setting), seek_read_only[:, 3], 'r:')
        plot(transpose(queue_len_setting), seek_all[:, 3], 'k-.')
        xlabel('Queue length ')
        ylabel('Value')
        title('Mean Absolute Value')
        legend(['write', 'read', 'combined'])
        savefig('sk_abs_mean.eps')
        savefig('sk_abs_mean.png')

        figure()
        # hold(True)
        plot(transpose(queue_len_setting), seek_write_only[:, 8], 'b-')
        plot(transpose(queue_len_setting), seek_read_only[:, 8], 'r:')
        plot(transpose(queue_len_setting), seek_all[:, 8], 'k-.')
        xlabel('Queue length ')
        ylabel('Value')
        title('Maximum Seek Distance')
        legend(['write', 'read', 'combined'])
        savefig('sk_max.eps')
        savefig('sk_max.png')

#    if options.export_report:
#        options.section_name='Seek Distance'
#        generate_ppt(options)
#
#        string0=string_generate([queue_len_setting';seek_write_only(:,6)],20);
#        string0=['Mode value (write)=',string0];
#        saveppt2(options.report_name,'f',0,'t',string0);
#
#        string0=string_generate([queue_len_setting';seek_write_only(:,7)],20);
#        string0=['Mode count (write)=',string0];
#        saveppt2(options.report_name,'f',0,'t',string0);
#
#        string0=string_generate([queue_len_setting';seek_read_only(:,6)],20);
#        string0=['Mode value (read)=',string0];
#        saveppt2(options.report_name,'f',0,'t',string0);
#
#        string0=string_generate([queue_len_setting';seek_read_only(:,7)],20);
#        string0=['Mode count (read)=',string0];
#        saveppt2(options.report_name,'f',0,'t',string0);

    return seek_dist_record
numImages = tiffStack.shape[0]

# get first image
zeroImage = tiffStack[0, :, :]

# calculate threshold value
adjImage = adjust(tiffStack[23, :, :], zeroImage)
thresh = skf.threshold_triangle(adjImage)

intensityArray = []
timeArray = []
timeMinutes = 0

for i in range(5, numImages, 6):
    iImage = tiffStack[i, :, :]
    adjImage = adjust(iImage, zeroImage)
    binaryImage = adjImage > thresh
    intensityTotal = np.sum(adjImage[binaryImage])

    intensityArray.append(intensityTotal)
    timeArray.append(timeMinutes)
    timeMinutes = timeMinutes + 30
    outFile.write('%8.2f\t%8.4e\n' % (timeMinutes, intensityTotal))

outFile.close()
plt.plot(timeArray, intensityArray, linestyle='', marker='o')
plt.xlabel('t [min]')
plt.ylabel('N [rel]')
plt.savefig(graphFileName, dpi=300)
plt.show()
		print(y_test.shape)
		model.eval()
		z = model(x_test)
		_,yhat = torch.max(z.data,1)
		correct += (yhat == y_test).sum().item()

	accuracy = correct/n_test
	print(accuracy)
	accuracy_list.append(accuracy)

torch.save(model.state_dict(), "")

x = np.arange(len(loss_list))
plt.plot(x,loss_list)
plt.title('Average Loss per Epoch vs epoch')
plt.xlabel('Epoch')
plt.ylabel('Average loss per epoch')
plt.show()

x = np.arange(N_EPOCHS)
plt.plot(x,accuracy_list)
plt.title('Accuracy per Epoch vs epoch')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()

#Testing
look_up = {0: 'predicted: $5'
		   , 1: 'predicted: $10'
		   , 2: 'predicted: $20'
		   , 3: 'predicted: $50'
Example #54
0
    count = 1
    for avg_index in range(N_avg):

        for noise in noises:

            print('working on run {} of {}'.format(count, N_avg*N_noise))
            print('    noise = {}'.format(noise))

            count += 1

            log_stream.flush()

            # run the demo on company          
            metric_list = run_demo('company', noise=noise)
            for i, e in enumerate(cases):
                f1s[e][avg_index].append(metric_list[-4+i]['f1'])

    for case, f1_list in f1s.items():

        # compute the average over all runs for each noise level        
        f1s_T = list(map(list, zip(*f1_list)))
        avgs = [sum(f)/N_avg for f in f1s_T]

        plt.plot(noises, avgs)

    plt.legend(cases)
    plt.xlabel('noise')
    plt.ylabel('f1s')
    plt.show()

import sklearn
# print(sklearn.metrics.accuracy_score(label_test,prediction))


print('f1: '+str(sklearn.metrics.f1_score(label_test,prediction,average='weighted'))) #weighted #macro #binary

import matplotlib.pyplot as plt

plt.plot()
plt.scatter(feature_test['length'][np.bitwise_and(label_test == prediction,label_test=='car')],
            feature_test['width'][np.bitwise_and(label_test== prediction,label_test=='car')],color='g')
plt.scatter(feature_test['length'][np.bitwise_and(label_test == prediction,label_test=='truck')],
            feature_test['width'][np.bitwise_and(label_test== prediction,label_test=='truck')],color='r')
plt.scatter(feature_test['length'][label_test!=prediction],feature_test['width'][label_test!=prediction],color='k')
plt.title('car_truck_classification_result')#显示图表标题
plt.xlabel('length')#x轴名称
plt.ylabel('width')#y轴名称
plt.legend(['car','truck','wrong'])
# plt.grid(True)#显示网格线
plt.show()










Example #56
0
from matplotlib import pylab

# tripolar to uniform 2560 x 5120

nprocs = [
    1,
    2,
    4,
    8,
    16,
]
times = [2.12e3, 1.18e3, 637, 368, 203]

pylab.plot(nprocs, [times[0] / t for t in times], 'ko', nprocs,
           [times[0] / t for t in times], 'b-')
pylab.title('ESMF conserve tripolar to uniform 2560x5120')
pylab.plot(nprocs, nprocs, 'k--')
pylab.xlabel('number of procs')
pylab.ylabel('speedup')
pylab.show()
import matplotlib.pylab as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

# mp.rc('font', family = 'serif', serif = 'cmr10')
mp.rcParams['mathtext.fontset'] = 'cm'
mp.rcParams.update({'font.size': 16})

n=3
α = np.array([0.8,1.0,1.2])
X = np.array([8/15,5/15,2/15])
with PdfPages('water_filling_plot.pdf') as pdf:
	axis = np.arange(0.5,n+1.5,1)
	index = axis+0.5
	# X = np.asarray(x).flatten()
	Y = α + X

	# to include the last data point as a step, we need to repeat it
	A = np.concatenate((α,[α[-1]]))
	X = np.concatenate((X,[X[-1]]))
	Y = np.concatenate((Y,[Y[-1]]))

	plt.xticks(index)
	plt.xlim(0.5,n+0.5)
	plt.ylim(0,1.5)
	plt.step(axis,A,where='post',label =r'$\alpha$',lw=2)
	plt.step(axis,Y,where='post',label=r'$\alpha + x$',lw=2)
	plt.legend(loc='lower right')
	plt.xlabel('channel number')
	plt.ylabel('power level')
	pdf.savefig(bbox_inches='tight')
Example #58
0
laynames = record_all.Layer.unique()
layermap = {nm: i for i, nm in enumerate(laynames)}
layermap_inall = {'conv1':0,'conv2':1,'conv3':2,'conv4':3,'conv5':4,'conv6':5,'conv7':6,'conv8':7,'conv9':8,\
                  'conv10':9,'conv11':10,'conv12':11,'conv13':12,'fc1':13,'fc2':14,'fc3':15}

#%%
ax = plt.subplot()
plt.scatter(
    record_all.manifMax.apply(lambda a: a[0]),
    record_all.manifMax_rf.apply(lambda a: a[0]),
    alpha=0.3,
    c=record_all.Layer.map(layermap_inall),
)
plt.ylabel("Resized to match RF")
plt.xlabel("Full size")
addDiagonal(ax)
ax.set_aspect(1)
plt.title("Comparison of Max Score in Manifold Full vs Resized")
plt.savefig(join(sumdir, "xscatter_MaxScore_cmp.png"))
plt.savefig(join(sumdir, "xscatter_MaxScore_cmp.pdf"))
plt.show()


#%%
def pairedJitter(ax, tab, varlist, jitter=True, xoffset=0, xsigma=0.25):
    if jitter:
        xjit = np.random.randn(tab.shape[0]) * xsigma
    else:
        xjit = np.zeros(tab.shape[0])
    for i, varnm in enumerate(varlist):
Example #59
0
File: pew.py Project: iamjakob/Lab
1. Read in GDP per capita
"""
from pandas.io import wb

wb.search('gdp.*capita.*const').iloc[:,:2]
dat = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'],
                  start=2005, end=2008)
dat['NY.GDP.PCAP.KD'].groupby(level=0).mean()

wb.search('cell.*%').iloc[:,:2]
ind = ['NY.GDP.PCAP.KD', 'IT.MOB.COV.ZS']
dat = wb.download(indicator=ind, country='all', start=2011, end=2011).dropna()
dat.columns = ['gdp', 'cellphone']

"""
2. Read in complete csv (see Sargent-Stachurski)
"""


#%%
# OLD PLOTS FROM ANOTHER PROGRAM
plt.plot(calls_strikes, calls_mid, 'r', lw=2, label='calls')
#plt.plot(calls_strikes, calls_ask, 'r', lw=2, label='calls ask')
plt.plot(puts_strikes, puts_mid, 'b', lw=2, label='puts')
plt.axis([120, 250, 0, 50])
plt.axvline(x=atm, color='k', linestyle='--', lw=2, label='atm')
plt.xlabel('Strike')
plt.ylabel('Option Price')
plt.legend(loc='upperleft')

Example #60
0
import matplotlib.pylab as plt

days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]

plt.plot([], [], color='red', label=sleeping, linewidth=5)
plt.plot([], [], color='blue', label=eating, linewidth=5)
plt.plot([], [], color='green', label=working, linewidth=5)
plt.plot([], [], color='black', label=playing, linewidth=5)

plt.stackplot(days,
              sleeping,
              eating,
              working,
              playing,
              colors=['red', 'blue', 'green', 'black'])

plt.xlabel('X')
plt.ylabel('Y')

plt.legend()

plt.title('Intresting Graph\nCheck it Out')
plt.show()