def plotAllData( self, allData, particleSize, room ):
        dates = allData['Time']
        print 'Plotting and saving averages'
        for shift in ['Day Shift','Night Shift','Empty Lab']:
            pyplot.figure(num=None, figsize=(16,9), dpi=100, facecolor='w', edgecolor='k')
            pyplot.plot_date(dates,allData[shift + ' Avg'], 'b-')
            pyplot.xlabel( 'Date (MT) ')
            pyplot.ylabel( 'Average Count' )
            pyplot.title( room + ' ' + shift + ' Averages for ' + particleSize + ' um Counts' )
            pyplot.savefig( room + particleSize + 'Avg' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title( room + ' ' + shift + ' Averages for ' + particleSize + ' um Counts Log Scale' )
            pyplot.savefig( room + particleSize + 'Avg' + shift[:-6] + '.png')

        print 'Plotting and saving baselines'   
        for shift in ['Day Shift','Night Shift','Empty Lab']:
            pyplot.figure(num=None, figsize=(16,9), dpi=100, facecolor='w', edgecolor='k')
            pyplot.plot_date(dates,allData[shift + ' Base'], 'b-')
            pyplot.xlabel( 'Date (MT)' )
            pyplot.ylabel( 'Baseline' )
            pyplot.title( room + ' ' + shift + ' Baselines for ' + particleSize + ' um Counts' )
            pyplot.savefig( room + particleSize + 'Base' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title( room + ' ' + shift + ' Baselines for ' + particleSize + ' um Counts Log Scale' )
            pyplot.savefig( room + particleSize + 'Base' + shift[:-6] + '.png')
Example #2
0
def save_solutions(deps, s, trun_indx):
    np.savetxt("solution.dat", deps)
    np.savetxt("singular_values.dat", s)
    np.savetxt("truncation_index.dat", trun_indx)
    plt.plot(np.arange(np.shape(s)[0]), s, markerstyle="o", linewidth=2)
    plt.title("Singular Values", fontsize=20)
    plt.set_yscale("log")
    plt.xlabel("index", fontsize=20)
    plt.ylabel("Value", fontsize=20)
def save_solutions(deps, s, trun_indx):
    np.savetxt("solution.dat", deps)
    np.savetxt("singular_values.dat", s)
    np.savetxt("truncation_index.dat", trun_indx)
    plt.plot(np.arange(np.shape(s)[0]), s, markerstyle="o", linewidth=2)
    plt.title("Singular Values", fontsize=20)
    plt.set_yscale("log")
    plt.xlabel("index", fontsize=20)
    plt.ylabel("Value", fontsize=20)
Example #4
0
 def plot_metrics(self, plt, logarithmic, differences=False):
     metrics = list(zip(*self.metric_history))[1:]
     if len(metrics[0]) > 3:
         for m in metrics[1:-2]:
             if differences:
                 plt.plot(self.time_history[1:], list(np.diff(m)))
                 plt.set_ylabel('Daily change')
             else:
                 plt.plot(self.time_history, m)
                 plt.set_ylabel('Cumulative')
         if logarithmic:
             plt.set_yscale('log')
         labels = list(STATE_DESCRIPTIONS.values())[1:-2]
         if differences:
             labels = ['net newly ' + lb for lb in labels]
         plt.legend(labels)
         plt.set_xlabel('Days since first ' + str(self.params['geometry']['i']) + ' infections.')
Example #5
0
def plot_many_curves(data, parameters=None, fname=None):
    """
    Plot many curve on the given axis with the given parameters
    
    """

    params = process_parameters(parameters)

    plt.rc('font', **params['font'])
    fig = plt.figure(num=None, figsize=params['size'], dpi=params['dpi'])

    fig.clf()

    axis = plt.subplot(111)

    for d in data:
        plt.plot(d[0], d[1], lw=1, label=d[2])

    plt.grid(axis='y', color="0.9", linestyle='-', linewidth=1)
    axis.spines['top'].set_visible(False)
    axis.spines['right'].set_visible(False)
    axis.spines['left'].set_visible(False)

    axis.get_xaxis().tick_bottom()
    axis.get_yaxis().tick_left()
    axis.tick_params(axis='x', direction='out')
    axis.tick_params(axis='y', length=0)
    for spine in axis.spines.values():
        spine.set_position(('outward', 5))
    axis.set_axisbelow(True)
    axis.set_xlabel(params['xlabel'])
    axis.set_ylabel(params['ylabel'])

    if params['logscale'] == 'y':
        plt.set_yscale('log')
    if params['logscale'] == 'x':
        plt.set_xscale('log')

    plt.legend(loc='upper right', frameon=False)

    # draw & show / save image
    if fname is None:
        plt.draw()
        plt.show()
    else:
        plt.savefig(fname)
    def graphDataDictionary( self, dataDictionary, particleSize, room ):
        dayShiftDates = dataDictionary['Day Shift']['Time']
        dayShiftCounts = dataDictionary['Day Shift']['Count']
        nightShiftDates = dataDictionary['Night Shift']['Time']
        nightShiftCounts = dataDictionary['Night Shift']['Count']
        emptyLabDates = dataDictionary['Empty Lab']['Time']
        emptyLabCounts = dataDictionary['Empty Lab']['Count']

        pyplot.figure(num=None, figsize=(16,9), dpi=100, facecolor='w', edgecolor='k')
        pyplot.plot_date(date2num(dayShiftDates),dayShiftCounts, 'r-')
        pyplot.plot_date(date2num(nightShiftDates),nightShiftCounts, 'g-')
        pyplot.plot_date(date2num(emptyLabDates),emptyLabCounts, 'b-')
        pyplot.xlabel( 'Date/Time (MT)' )
        pyplot.ylabel( 'Count' )
        pyplot.title( room + ' ' + particleSize + ' um Counts' )
        pyplot.savefig( room + particleSize + 'Plot.png' )
        
        pyplot.set_yscale('log')
        pyplot.title( room + ' ' + particleSize + ' um Counts Log Scale' )
        pyplot.savefig( room + particleSize + 'PlotLog.png' )
Example #7
0
    def plotAllData(self, allData, particleSize, room):
        dates = allData['Time']
        print 'Plotting and saving averages'
        for shift in ['Day Shift', 'Night Shift', 'Empty Lab']:
            pyplot.figure(num=None,
                          figsize=(16, 9),
                          dpi=100,
                          facecolor='w',
                          edgecolor='k')
            pyplot.plot_date(dates, allData[shift + ' Avg'], 'b-')
            pyplot.xlabel('Date (MT) ')
            pyplot.ylabel('Average Count')
            pyplot.title(room + ' ' + shift + ' Averages for ' + particleSize +
                         ' um Counts')
            pyplot.savefig(room + particleSize + 'Avg' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title(room + ' ' + shift + ' Averages for ' + particleSize +
                         ' um Counts Log Scale')
            pyplot.savefig(room + particleSize + 'Avg' + shift[:-6] + '.png')

        print 'Plotting and saving baselines'
        for shift in ['Day Shift', 'Night Shift', 'Empty Lab']:
            pyplot.figure(num=None,
                          figsize=(16, 9),
                          dpi=100,
                          facecolor='w',
                          edgecolor='k')
            pyplot.plot_date(dates, allData[shift + ' Base'], 'b-')
            pyplot.xlabel('Date (MT)')
            pyplot.ylabel('Baseline')
            pyplot.title(room + ' ' + shift + ' Baselines for ' +
                         particleSize + ' um Counts')
            pyplot.savefig(room + particleSize + 'Base' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title(room + ' ' + shift + ' Baselines for ' +
                         particleSize + ' um Counts Log Scale')
            pyplot.savefig(room + particleSize + 'Base' + shift[:-6] + '.png')
Example #8
0
    def graphDataDictionary(self, dataDictionary, particleSize, room):
        dayShiftDates = dataDictionary['Day Shift']['Time']
        dayShiftCounts = dataDictionary['Day Shift']['Count']
        nightShiftDates = dataDictionary['Night Shift']['Time']
        nightShiftCounts = dataDictionary['Night Shift']['Count']
        emptyLabDates = dataDictionary['Empty Lab']['Time']
        emptyLabCounts = dataDictionary['Empty Lab']['Count']

        pyplot.figure(num=None,
                      figsize=(16, 9),
                      dpi=100,
                      facecolor='w',
                      edgecolor='k')
        pyplot.plot_date(date2num(dayShiftDates), dayShiftCounts, 'r-')
        pyplot.plot_date(date2num(nightShiftDates), nightShiftCounts, 'g-')
        pyplot.plot_date(date2num(emptyLabDates), emptyLabCounts, 'b-')
        pyplot.xlabel('Date/Time (MT)')
        pyplot.ylabel('Count')
        pyplot.title(room + ' ' + particleSize + ' um Counts')
        pyplot.savefig(room + particleSize + 'Plot.png')

        pyplot.set_yscale('log')
        pyplot.title(room + ' ' + particleSize + ' um Counts Log Scale')
        pyplot.savefig(room + particleSize + 'PlotLog.png')
Example #9
0
grp3, bin3 = np.histogram(h3, bins=range(0, max(h3) + 1), density=False)
grp4, bin4 = np.histogram(h4, bins=range(0, max(h4) + 1), density=False)

hist1, bin1 = np.histogram(h1, bins=range(0, max(h1) + 1), density=True)
hist2, bin2 = np.histogram(h2, bins=range(0, max(h2) + 1), density=True)
hist3, bin3 = np.histogram(h3, bins=range(0, max(h3) + 1), density=True)
hist4, bin4 = np.histogram(h4, bins=range(0, max(h4) + 1), density=True)

# # PDF plot in log-log scale
# l1, = plt.loglog(range(1, max(h1)+1), hist1, '-o')
# l2, = plt.loglog(range(1, max(h2)+1), hist2, '-o')
# l3, = plt.loglog(range(1, max(h3)+1), hist3, '-o')
# l4, = plt.loglog(range(1, max(h4)+1), hist4, '-o')

cs1 = np.cumsum(grp1) / float(len(h1))
cs2 = np.cumsum(grp2) / float(len(h2))
cs3 = np.cumsum(grp3) / float(len(h3))
cs4 = np.cumsum(grp4) / float(len(h4))

# ECDF plot
l1, = plt.plot(range(0, max(h1)), cs1, '-o', sety)
l2, = plt.plot(range(0, max(h2)), cs2, '--')
l3, = plt.plot(range(0, max(h3)), cs3, '-')
l4, = plt.plot(range(0, max(h4)), cs4)

plt.legend((l1, l2, l3, l4), ('GOOD', 'VF', 'SH', 'ALL'), loc='lower right')
plt.xlim(0, 3000)
plt.set_yscale('log')
# plt.ylim(0, 0.002)
plt.show()
Example #10
0
def density_profile(sim, linestyle=False, center=True, clear=True, fit=False,in_units=None,
                    filename=None, fit_factor=0.02, axes=False, **kwargs):
    '''

    3d density profile

    **Options:**

    *filename* (None):  name of file to which to save output

    **Usage:**

    >>> import pynbody.plot as pp
    >>> h = s.halos()
    >>> pp.density_profile(h[1],linestyle='dashed',color='k')


    '''
    if axes: plt = axes
    else: import matplotlib.pyplot as plt

    global config

    logger.info("Centering...")
    if center:
        halo.center(sim, mode='ssc')

    logger.info("Creating profile...")

    if 'min' in kwargs:
        ps = profile.Profile(
            sim, ndim=3, type='log', nbins=40, min=kwargs['min'])
        del kwargs['min']
    else:
        ps = profile.Profile(sim, ndim=3, type='log', nbins=40)

    if clear and not axes:
        plt.clf()
    critden = (units.Unit('100 km s^-1 Mpc^-1')
               * sim.properties['h']) ** 2 / 8.0 / np.pi / units.G
    r = ps['rbins'].in_units('kpc')
    if in_units is None:
        den = ps['density'].in_units(critden)
    else:
        den = ps['density'].in_units(in_units)

    if linestyle:
        plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']),
                     linestyle=linestyle, **kwargs)
    else:
        plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']),
                     fmt='o', **kwargs)

    if in_units is None:
        ylabel=r'$\rho / \rho_{cr}$'  # +den.units.latex()+'$]')
    else:
        ylabel=r'$\rho / '+den.units.latex()+'$'
    if axes:
        plt.set_yscale('log')
        plt.set_xscale('log')
        plt.set_xlabel('r [kpc]')
        plt.set_ylabel(ylabel) #r'$\rho / \rho_{cr}$')  # +den.units.latex()+'$]')
    else:
        plt.yscale('log')
        plt.xscale('log')
        plt.xlabel('r [kpc]')
        plt.ylabel(ylabel) #r'$\rho / \rho_{cr}$')  # +den.units.latex()+'$]')


    if (filename):
        logger.info("Saving %s", filename)
        plt.savefig(filename)

    if fit:
        fit_inds = np.where(r < fit_factor*sim['r'].max())
        alphfit = np.polyfit(np.log10(r[fit_inds]),
                             np.log10(den[fit_inds]), 1)
        
#        print "alpha: ", alphfit[0], "  norm:", alphfit[1]
        
        fit = np.poly1d(alphfit)
        plt.plot(r[fit_inds], 10**fit(np.log10(r[fit_inds])), 
                 color='k',linestyle='dashed',
                 label=r'$\alpha$=%.1f'%alphfit[0])
        plt.legend(loc=3)

        return alphfit[0]
Example #11
0
def plot_shaded_plot(x, y, parameters=None, fname=None):
    """

    Plot boxplot for set of data (median and shaded quartiles)
    where data is a list of lists of values 
    
    data = [ [...] , ... , [...] ] 
    
    """

    params = process_parameters(parameters)

    plt.rc('font', **params['font'])

    perc_05, perc_25, med, perc_75, perc_95 = percentiles(y)

    fig = plt.figure(num=None, figsize=params['size'], dpi=params['dpi'])
    axis = plt.subplot(111)

    plt.clf()
    if params['quartiles']:
        plt.fill_between(x,
                         perc_25,
                         perc_75,
                         alpha=0.5,
                         linewidth=0.1,
                         color=params['quart-color'])

        plt.fill_between(x,
                         perc_75,
                         perc_95,
                         alpha=0.25,
                         linewidth=0.1,
                         color=params['quart-color'])

        plt.fill_between(x,
                         perc_05,
                         perc_25,
                         alpha=0.25,
                         linewidth=0.1,
                         color=params['quart-color'])

    plt.plot(x,
             med,
             lw=1,
             alpha=1.0,
             label=params['label'],
             color=params['quart-color'])

    plt.grid(axis='y', color="0.9", linestyle='-', linewidth=1)
    axis.spines['top'].set_visible(False)
    axis.spines['right'].set_visible(False)
    axis.spines['left'].set_visible(False)
    axis.get_xaxis().tick_bottom()
    axis.get_yaxis().tick_left()
    axis.tick_params(axis='x', direction='out')
    axis.tick_params(axis='y', length=0)
    for spine in axis.spines.values():
        spine.set_position(('outward', 5))
    axis.set_axisbelow(True)
    axis.set_xlabel(params['xlabel'])
    axis.set_ylabel(params['ylabel'])

    if params['logscale'] == 'y':
        plt.set_yscale('log')
    if params['logscale'] == 'x':
        plt.set_xscale('log')

    # draw & show / save image
    if fname is None:
        plt.draw()
        plt.show()
    else:
        plt.savefig(fname)
Example #12
0
	fig = 0
	for h in histograms:
		fig += 1
		if plotallhistos or h.title.find(opts.SINGLETITLE)>-1:
			centers = []
			widths = []
			sumw = []
			sumw2 = []
			for bin in h:
				centers.append(bin.midpoint)
				widths.append(bin.width)
				sumw.append(bin.sumW)
				sumw2.append(bin.sumW2) 
			yerr = map(lambda x: math.sqrt(x), sumw2)
			if opts.LOGY:
				plt.set_yscale("log")
			if opts.LOGX:
				plt.set_xscale("log")
			thislegend = Legend(h.title,h.title,"green")
			if opts.LEGEND!="":
				leg = readLegend(opts.LEGEND)
				for l in leg:
					if l.title==h.title:
						thislegend=l
			#ax.errorbar(centers, sumw, yerr=yerr, xerr=widths, fmt='o')
			plt.figure(fig)
			plt.hist(centers,bins=len(centers),weights=sumw,normed=opts.NORM,facecolor=thislegend.color,alpha=0.5)
			plt.title(thislegend.nicename)

	
	plt.show()
# title += "capacity = " + str(config.capacity) + ", n = " + str(config.n_atoms)
# title += "<br>w<sub>c</sub> = " + wc_str(config.wc)
# title += "<br>w<sub>a</sub> = " + \
#     "[" + ", ".join([wa_str(i) for i in config.wa]) + "]"
# title += "<br>g = " + "[" + ", ".join([g_str(i) for i in config.g]) + "]"
# title += "<br>t = " + T_str(config.T)
# title += "<br>l = " + wc_str(config.l)
title += "</b>"

plt.set_title(title)

plt.set_xaxis("states")
plt.set_yaxis("time, " + T_str_mark(config.T))
plt.set_zaxis("prob.")

plt.set_yscale(y_scale)

plt.set_width(900)
plt.set_height(650)

plt.plot(
    x_csv=config.x_csv,
    y_csv=config.path + "/" + "t.csv",
    z_csv=config.path + "/" + "z.csv",
    # t_coeff=20000 / 1000 * (config.T / 1e-6),
    online=False,
    path=config.path,
    filename="BipartiteGeneralLindblad",
)
# ---------------------------------------------------------------------------------------------------------------------
Example #14
0
def plot(title,
         label,
         train_results,
         test_results,
         ax=None,
         yscale='linear',
         save_path=None,
         extra_pt=None,
         extra_pt_label=None):
    """Plot learning curves.

    Args:
        title (str): Title of plot
        label (str): x-axis label
        train_results (list): Results vector of training of length of number
            of epochs trained. Could be loss or accuracy.
        val_results (list): Results vector of validation of length of number
            of epochs. Could be loss or accuracy.
        yscale (str, optional): Matplotlib.pyplot.yscale parameter. 
            Defaults to 'linear'.
        save_path (str, optional): If passed, figure will be saved at this path.
            Defaults to None.
        extra_pt (tuple, optional): Tuple of length 2, defining x and y coordinate
            of where an additional black dot will be plotted. Defaults to None.
        extra_pt_label (str, optional): Legend label of extra point. Defaults to None.
    """

    epoch_array = np.arange(len(train_results)) + 1
    train_label, test_label = "Training " + label.lower(
    ), "Test " + label.lower()

    sns.set(style='ticks')

    #if ax is not None:
    #    plt = ax

    plt.plot(epoch_array,
             train_results,
             epoch_array,
             test_results,
             linestyle='dashed',
             marker='o')
    legend = ['Train results', 'Test results']

    if extra_pt:
        ####################
        ## YOUR CODE HERE ##
        ####################
        plt.scatter(extra_pt[0] + 1, extra_pt[1], c='black', zorder=9999)

        # END OF YOUR CODE #

    plt.legend(legend)
    if ax is not None:
        plt.set_xlabel('Epoch')
        plt.set_ylabel(label)
        plt.set_yscale(yscale)
        sns.despine(trim=True, offset=5)
        plt.set_title(title, fontsize=15)
    else:
        plt.xlabel('Epoch')
        plt.ylabel(label)
        plt.yscale(yscale)
        sns.despine(trim=True, offset=5)
        plt.title(title, fontsize=15)

    if save_path:
        plt.savefig(str(save_path), bbox_inches='tight')

    if ax is None:
        plt.show()