Example #1
0
def plot_results(training_details, validation_details, note=None):
    """
    Generates a combined training/validation graph.
    """
    print "\tPlotting results..."
    fig, ax1 = plt.subplots()
    ax1.plot(training_details["iters"], training_details["loss"], "b-")
    ax1.set_xlabel("Iterations")
    ax1.set_ylabel("Training Loss", color="b")
    for tl in ax1.get_yticklabels():
        tl.set_color("b")

    ax2 = ax1.twinx()
    ax2.plot(validation_details["iters"], validation_details["loss"], "r-")
    ax2.set_ylabel("Validation Loss", color="r")
    for tl in ax2.get_yticklabels():
        tl.set_color("r")

    legend_font = FontProperties()
    legend_font.set_size("small")
    blue_line = mpatches.Patch(color="blue", label="Training Loss")
    red_line = mpatches.Patch(color="red", label="Validation Loss")
    plt.legend(handles=[blue_line, red_line], prop=legend_font, loc="lower right")

    plt.suptitle("Iterations vs. Training/Validation Loss", fontsize=14)
    plt.title(get_hyperparameter_details(note), style="italic", fontsize=12)

    plt.savefig(constants.OUTPUT_GRAPH_PATH)
    print("\t\tGraph saved to %s" % constants.OUTPUT_GRAPH_PATH)
Example #2
0
def make_overview_plot(filename, title, noip_arrs, ip_arrs):
    plt.title("Inner parallelism - " + title)

    
    plt.ylabel('Time (ms)', fontsize=12)

    x = 0
    barwidth = 0.5
    bargroupspacing = 1.5

    for z in zip(noip_arrs, ip_arrs):
        noip,ip = z
        noip_mean,noip_conf = conf_stats(noip)
        ip_mean,ip_conf = conf_stats(ip)

        b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7)
        x += barwidth

        b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7)
        x += bargroupspacing

    plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal')

    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_noip, b_ip], \
        ('no inner parallelism', 'inner parallelism'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
   
    plt.ylim([0,62000])
    plt.savefig(output_file(filename))
    plt.clf()
Example #3
0
def frequency_plots(filename, xs_list, normalize=False, color='b', labels=['Plot1'], title=None, ylim=None, xlim=None, xlabel=None, ylabel=None):
  '''Take lists of lists of values, create multiple frequency tables and plot multiple lines'''
  ccolors = colors(len(xs_list))
  plt.clf()
  plt.figure().set_size_inches(25,15)
  ax = plt.subplot(111)
  for i, xs in enumerate(xs_list):
    dik = Counter(xs)
    if normalize:
      diksum = sum(dik.values())
      dik = {k:float(v)/diksum for k,v in dik.iteritems()}
    dicty = zip(*sorted(dik.iteritems()))
    ax.plot(dicty[0], dicty[1], color=ccolors[i], label=labels[i])
    ax.scatter(max(dik, key=dik.get), dik[max(dik, key=dik.get)], color=ccolors[i])
  if xlabel:
    ax.xlabel(xlabel)
  if ylabel:
    ax.ylabel(ylabel)
  if ylim:
    plt.ylim(ylim)
  else:
    plt.ylim(ymin=0)
  if xlim:
    plt.xlim(xlim)
  if title:
    plt.title(title)
  box = ax.get_position()
  ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])  
  from matplotlib.font_manager import FontProperties
  fontP = FontProperties()
  fontP.set_size('small')
  ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), prop=fontP)
  plt.savefig('%s' % filename)
Example #4
0
def legend(labels, ax=None, im=None, handles=None, bbox=None,
    loc='upper center', ncol=None):
    """Adds legend to plot.

    """
    if ax == None:
        ax = pylab.gca()

    fontP = FontProperties()
    fontP.set_size('small')
    #
    if bbox == None:
        bbox = (0.5, -0.05)
    if ncol == None:
        ncol = int(round(len(labels)/2))
    if im == None:
        if handles == None:
            ax.legend(labels, loc=loc, bbox_to_anchor=bbox,
                ncol=ncol, prop=fontP)
        else:
            ax.legend(handles, labels, loc=loc, bbox_to_anchor=bbox,
                ncol=ncol, prop=fontP)
    else:
        _proxy, _legend = [], []
        for lc, pc in zip(labels, im.collections):
            if lc != None:
                _proxy.append(pylab.Rectangle((0, 0), 1, 1,
                    fc=pc.get_facecolor()[0], hatch=pc.get_hatch()))
                _legend.append(lc)
        ax.legend(_proxy, _legend, loc='upper center',
            bbox_to_anchor=bbox, ncol=int(round(len(labels)/2)),
            prop=fontP)
    #
    return
	def plot_np_simple(x_labels, x_values_np, y_values_np, x_label, y_label, title, nb_x_labels, style):
		x = np.arange(len(y_values_np))
		
		fig, ax = plt.subplots()
		if style != None:
			ax.plot(x_values_np, y_values_np, style)
		else:
			ax.plot(x_values_np, y_values_np)
		
		
		
			
		
		
		plt.xlabel(x_label)
		plt.ylabel(y_label)
		plt.title(title)
		fontP = FontProperties()
		fontP.set_size('small')
		plt.legend(loc='lower right', prop=fontP)
		
		if x_labels != None:
			labels = np.array(x_labels)
			jump_step = len(labels)/nb_x_labels

			
			label_indexes = np.arange(1,len(labels),jump_step)
			
			for (X, Z) in zip(x[label_indexes], labels[label_indexes]):
				ax.annotate('{}'.format(Z), xy=(X,0), xytext=(X, (-0.1*y_max)), rotation=90, ha='center', size=10,
							textcoords='data')
		
		fig.tight_layout(pad=4)
		plt.draw()
Example #6
0
def make_legend(labels, colors, output_file):
    """ Hack to generate a legend as a separate image.  A dummy plot
        is created in one figure, and its legend gets saved to an
        output file.

        Inputs:
        labels - text labels for the legend
        colors - list of colors for the legend (same length as labels)
        output_file - filename for the resulting output figure

        Outputs:
        (None - output figure is written to output_file)

    """
    if len(labels) != len(colors):
        raise ValueError("Lists of labels and colors "
                         " should have the same length")
    fig = plt.figure()
    font_prop = FontProperties()
    font_prop.set_size('xx-large')
    font_prop.set_family('sans-serif')
    seperate_legend = plt.figure(figsize=(5, 3.5))
    ax = fig.add_subplot(111)
    N = len(labels)
    # Make a dummy pie chart so we can steal its legend
    wedges, texts = ax.pie([100/N]*N, colors=colors)
    seperate_legend.legend(wedges, labels, 'center',
                           prop=font_prop, frameon=False)
    seperate_legend.savefig(output_file)
Example #7
0
def plot_all(wells, errors=None, do_legend=True, legend_position=0.8):
    """Plots all of the timecourses in the dict.

    Parameters
    ----------
    wells : dict of timecourse data of the type returned by read_wallac.
    """
    for wellname, wellval in wells.iteritems():
        if errors is None:
            plot(wellval[TIME], wellval[VALUE], label=wellname)
        else:
            errorbar(wellval[TIME], wellval[VALUE],
                    yerr=errors[wellname][VALUE], label=wellname)

    # Label the axes and add a legend
    xlabel('Time') # TODO: automatically determine seconds or minutes, etc.
    ylabel('Value')

    if do_legend:
        fontP = FontProperties()
        fontP.set_size('small')
        ax = gca()
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * legend_position,
                         box.height])
        legend(loc='upper left', prop=fontP, ncol=1, bbox_to_anchor=(1, 1),
             fancybox=True, shadow=True)
def grafico(dicionario, info):
    fontP = FontProperties()
    fontP.set_size("small")
    marcadores = ["+", ".", "o", "*", "p", "s", "x", "D", "h"]
    eixo_y = []
    eixo_x = range(1, 9)
    nome_bairro = []
    legendas = []

    for i in dicionario.items():
        eixo_y.append(i[1])
        nome_bairro.append(i[0])

    for i in nome_bairro:
        legendas.append(info[i[6:]])

    for i in range(len(eixo_x)):
        plt.plot(eixo_x, eixo_y[i], label=legendas[i])

    plt.ylabel("numero de roubos")
    plt.xlabel("meses")
    art = []
    lgd = plt.legend(loc=9, bbox_to_anchor=(0.5, -0.1), ncol=2, prop=fontP)
    art.append(lgd)
    plt.savefig("grafico_roubos2015.png", additional_artists=art, bbox_inches="tight")
def plot_gradient_over_time(points, get_grad_over_time):
    fig = plt.figure(figsize=(6.5, 4))
    # Remove the plot frame lines. They are unnecessary chartjunk.    
    ax = plt.subplot(111)    
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    # ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
    # ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    # ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
    # ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    # ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
    # ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
    # ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')
    # ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')
    ax.grid(b=True, which='major', linewidth=0.75, linestyle=':', color='0.75')
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_ticks_position('none')
    for wx, wRec, c in points:
        grad_over_time = get_grad_over_time(wx, wRec)
        x = np.arange(1, grad_over_time.shape[1]+1, 1)
        plt.plot(x, np.sum(grad_over_time, axis=0), c+'.-', label='({0}, {1})'.format(wx, wRec), linewidth=1, markersize=8)
    plt.xlim(1, grad_over_time.shape[1])
    plt.xticks(x)
    plt.gca().invert_xaxis()
    plt.yscale('symlog')
    plt.yticks([10**8, 10**6, 10**4, 10**2, 0, -10**2, -10**4, -10**6, -10**8])
    plt.xlabel('time k')
    plt.ylabel('gradient ')
    plt.title('Unstability of gradient in backward propagation.\n(backpropagate from left to right)')
    leg = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False, numpoints=1)
    leg_font = FontProperties()
    leg_font.set_size('x-large')
    leg.set_title('$(w_x, w_{rec})$', prop=leg_font)
Example #10
0
    def _get_3d_plot(self, label_stable=True):
        """
        Shows the plot using pylab.  Usually I won"t do imports in methods,
        but since plotting is a fairly expensive library to load and not all
        machines have matplotlib installed, I have done it this way.
        """
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d.axes3d as p3
        from matplotlib.font_manager import FontProperties

        fig = plt.figure()
        ax = p3.Axes3D(fig)
        font = FontProperties()
        font.set_weight("bold")
        font.set_size(20)
        (lines, labels, unstable) = self.pd_plot_data
        count = 1
        newlabels = list()
        for x, y, z in lines:
            ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10)
        for coords in sorted(labels.keys()):
            entry = labels[coords]
            label = entry.name
            if label_stable:
                if len(entry.composition.elements) == 1:
                    ax.text(coords[0], coords[1], coords[2], label)
                else:
                    ax.text(coords[0], coords[1], coords[2], str(count))
                    newlabels.append("{} : {}".format(count, latexify(label)))
                    count += 1
        plt.figtext(0.01, 0.01, "\n".join(newlabels))
        ax.axis("off")
        return plt
Example #11
0
 def _show_3d_plot(self):
     '''
     Shows the plot using pylab.  Usually I won't do imports in methods,
     but since plotting is a fairly expensive library to load and not all 
     machines have matplotlib installed, I have done it this way.
     '''
     import matplotlib.pyplot as plt
     import mpl_toolkits.mplot3d.axes3d as p3
     from matplotlib.font_manager import FontProperties
     fig = plt.figure()
     ax = p3.Axes3D(fig)
     font = FontProperties()
     font.set_weight('bold')
     font.set_size(20)
     (lines, labels, unstable) = self.pd_plot_data
     count = 1
     newlabels = list()
     for x, y, z in lines:
         ax.plot(x, y, z, 'bo-', linewidth=3, markeredgecolor='b', markerfacecolor='r', markersize=10)
     for coords in sorted(labels.keys()):
         entry = labels[coords]
         label = entry.name
         if len(entry.composition.elements) == 1:
             # commented out options are only for matplotlib 1.0.  Removed them so that most ppl can use this class.
             ax.text(coords[0], coords[1], coords[2], label)#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
         else:
             ax.text(coords[0], coords[1], coords[2], str(count))#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
             newlabels.append(str(count) + " : " + label)
             count += 1
     plt.figtext(0.01, 0.01, '\n'.join(newlabels))
     ax.axis('off')
     plt.show()
 def bargraph(self):
     ind = np.arange(int(self.count))
     width = 0.25
     data = reportDB().selectSql(self.LATE_FIVE_SQL)
     errorsList = tuple(error[0] for error in data)[::-1]
     passedList = tuple(right[1] for right in data)[::-1]
     failedList = tuple(fail[2] for fail in data)[::-1]
     startTime = tuple(runtime[3] for runtime in data)[::-1]
     fig, ax = plt.subplots()
     ax.set_ylabel(u'个数')
     ax.set_title(u'最近%s次测试结果柱状图' % self.count)
     ax.set_xticks(ind+width)
     ax.set_xticklabels(startTime,rotation=18, fontsize='small')
     rectError = ax.bar(ind, errorsList, width, color='r')
     rectFail = ax.bar(ind+width, failedList, width, color='y')
     rectPass = ax.bar(ind+2*width, passedList, width, color='g')
     fontP = FontProperties()
     fontP.set_size('small')
     for e_rect in rectError:
         height = e_rect.get_height()
         ax.text(e_rect.get_x()+e_rect.get_width()/2., 1.05*height, '%d'%int(height),
                 ha='center', va='bottom')
     for f_rect in rectFail:
         height = f_rect.get_height()
         ax.text(f_rect.get_x()+f_rect.get_width()/2., 1.05*height, '%d'%int(height),
                 ha='center', va='bottom')
     for p_rect in rectPass:
         height = p_rect.get_height()
         ax.text(p_rect.get_x()+p_rect.get_width()/2., 0.8*height, '%d'%int(height),
                 ha='center', va='bottom')
     ax.legend( (rectError[0], rectPass[0], rectFail[0]), (u'错误', u'通过', u'失败'),prop = fontP)
     plt.savefig('E:\\apk\huodong\\tr\\pic\\bargraph')
Example #13
0
def create_plot(plot_title, datasets, offset, count, output_path):
    x = 0

    for dataset_path in datasets:

        first,average,conf = statistics(dataset_path, offset, count)

        b_first = plt.bar(x, first, 0.5, color='b')
        x += 0.5

        b_average = plt.bar(x, average, 0.5, color='r', yerr=conf, ecolor='black')
        x += 1.5

    plt.title("benchmark: " + plot_title)

    plt.xlabel('Dataset', fontsize=12)
    plt.ylabel('Time', fontsize=12)

    plt.xticks([0.5, 2.5, 4.5, 6.5, 8.5], ['10', '100', '1000', '10000', '100000'], rotation='horizontal')

    # Create graph legend
    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_first, b_average], \
        ('first query time', 'average time of other queries'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
    
    # Plot to file
    plt.savefig(output_path)
    plt.clf()
Example #14
0
    def initGraph(self):
        """ initalize graph to draw spans """

        self.trial = 1
        self.sbs = {}
        self.sbs['Lever'] = ScatterBrain('Lever','#3399FF','o')
        self.sbs['Mark'] = ScatterBrain('Mark','#000000','x')
        for i in range(0,5):
            name = 'aTaste%d'%i
            self.sbs[name] = ScatterBrain(name,uv.TasteColors[i],'s')
            name2 = 'mTaste%d'%i
            self.sbs[name2] = ScatterBrain(name2,uv.TasteColors[i],'s',False)
        
        self.figure = Figure(dpi=100,figsize=(5,5.5))
        self.axes = self.figure.add_subplot(111)
        print 'X.trial', X.trialDuration
        self.axes.axis([0,X.trialDuration,0,1.5])
        self.axes.set_xlabel('time (s)')
        
        self.drawSpans(True)
        
        LText = FontProperties()
        LText.set_size("small")
        
        
        self.axes.legend((self.sbs['Lever'].getPlot(self.axes),self.sbs['Mark'].getPlot(self.axes),
                          self.sbs['aTaste1'].getPlot(self.axes),self.sbs['mTaste1'].getPlot(self.axes)),
                         ("Lever Press","Time Marked", "Reward","Manual Reward"),
                         prop=LText, fancybox=True, bbox_to_anchor=(0., 1.02, 1., .102), loc=1, ncol=2, mode="expand", borderaxespad=0)
        
        self.canvas = FigureCanvas(self, -1, self.figure)
def plotProfile(plotname, data):
    ''' Plot a profile of the colors'''
    dtc=None
    if args.window:
        dt=numpy.transpose(data)
        for i in range(dt.shape[0]):
            dt[i]=movingAverage(dt[i], args.window)

        dtc=numpy.transpose(dt)
    else:
        dtc=data

    fontP = FontProperties()
    fontP.set_size('small')
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.plot(dtc)
    #ax.set_xticklabels(xlabels, rotation=45, fontproperties=fontP)
    #ax.set_xlabel('Image number in the series')
    ax.set_ylabel('Reef colors')
    box = ax.get_position()
    #ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    #ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height])
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height *0.85])
    header=["blue", "green", "red"]

    ax.legend((header), loc='upper center', bbox_to_anchor=(0.5, -0.10), ncol=4, prop=fontP)
    fig.savefig(plotname)
Example #16
0
File: utils.py Project: meyyar/WoC
    def add_plot(title, plots, min_class_label, max_class_label):
        colors = ["r", "y"]
        place = [0, 0.35]

        Utils.subplot += 1
        # fig = .figure()
        ax = Utils.figure.add_subplot(Utils.subplot)

        Utils.figure.subplots_adjust(hspace=0.75, wspace=0.5)
        ax.set_title(title)
        ax.set_xticks(np.arange(8))
        for i in xrange(len(plots)):
            item = plots[i]
            if item["xlim"] != None:
                ax.set_xlim(item["xlim"])
            if item["ylim"] != None:
                ax.set_ylim(item["ylim"])
            ax.set_xlabel(item["xlabel"])
            ax.set_ylabel(item["ylabel"])
            ax.bar(
                np.arange(min_class_label, max_class_label + 1) + place[i],
                item["y_values"],
                0.35,
                color=colors[i],
                label=item["label"],
            )

        handles, labels = ax.get_legend_handles_labels()
        fontP = FontProperties()
        fontP.set_size("small")
        Utils.figure.legend(handles, labels, loc="upper right", prop=fontP)
Example #17
0
def plot_markers(data, x_base, name, map, xoff_sgn, width, off_fac,
                 markersize):
    maxD = 0
    ds = {}
    used = []
    font = FontProperties()
    font.set_family('sans-serif')
    font.set_size(10)
    for (kind, subkind, dimval) in data:
        try:
            symb, lab = map[kind][subkind]
        except KeyError:
            raise KeyError("Invalid key for %s symbols"%name)
        used.append((kind, subkind))
        try:
            ds[dimval] += 1
            x_off = xoff_sgn*width*off_fac*(ds[dimval]-1)
        except KeyError:
            ds[dimval] = 1
            x_off = 0
        plot([x_base+x_off], [dimval], symb, markersize=markersize)
        # hack tweaks
    ##            if lab=='C':
    ##                x_off -= width/15
        if lab=='A':
            x_off += width/30
        text(x_base+x_off-width*.15, dimval-width*2., lab,
             fontproperties=font)
        if dimval > maxD:
            maxD = dimval
    return ds, maxD, used
Example #18
0
def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times legends 
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
    font.set_name('Script MT')
    font.set_family('serif')
    font.set_style('normal')
#    font.set_size('small')
    font.set_size('large')
    font.set_variant('normal')
    font.set_weight('medium')
    
    if xlim != None and ylim != None:
        axes.axis([0, xlim, 0., ylim], fontproperties=font)

    # format ticks for plot
    #
    locs, labels = axes.xticks()
    axes.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.xlabel(xlabel, fontproperties=font)

    locs, labels = axes.yticks()
    axes.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.ylabel(ylabel, fontproperties=font)
Example #19
0
def PlotSensitivityAndPPVGraphs(sensitivityDict, ppvDict, graphTitle, xAxisTitle, index, graphFileName):
	
	sensDremeMeanValues, sensDremeErrorValues, sensKspectrumMeanValues, sensKspectrumErrorValues, labels = parseResults.GetMeanAndStdErrorValues(sensitivityDict, index);
	ppvDremeMeanValues, ppvDremeErrorValues, ppvKspectrumMeanValues, ppvKspectrumErrorValues, labels = parseResults.GetMeanAndStdErrorValues(ppvDict, index);

	import matplotlib
	matplotlib.use('Agg')
	
	from matplotlib import pyplot as plt	
	matplotlib.rcParams.update({'font.size': 8})

	#Two subplots, the axes array is 1-d
	fig, (ax1, ax2) = plt.subplots(nrows=2)
	eb1, eb2, eb3, eb4 = sensitivity_ppv_plot(ax1, graphTitle + " on Sensitivity", sensDremeMeanValues, sensDremeErrorValues, sensKspectrumMeanValues, sensKspectrumErrorValues, labels, xAxisTitle, "Sensitivity");
	eb1, eb2, eb3, eb4= sensitivity_ppv_plot(ax2, graphTitle + " on PPV", ppvDremeMeanValues, ppvDremeErrorValues, ppvKspectrumMeanValues, ppvKspectrumErrorValues, labels, xAxisTitle, "PPV");	

	#ax2.set_xlabel(xAxisTitle)

	handles_ax1, labels_ax1 = ax1.get_legend_handles_labels();
	handles_ax1 = [h[0] for h in handles_ax1];

	from matplotlib.font_manager import FontProperties
	fontP = FontProperties();
	fontP.set_size('small');
	#fig.legend([eb1, eb2, eb3, eb4], ["DREME", "k-spectrum-25", "k-spectrum-50", "k-spectrum-100"], prop = fontP)
	fig.legend(handles_ax1, labels_ax1, loc = 'upper right')
	plt.savefig(graphFileName);
	plt.close(fig)
def plot_benchmarks(runs, out_file="output.eps", dpi=1200):
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties

    fontP = FontProperties()
    fontP.set_size("small")

    lines, densities = regroup_runs(runs)

    for line in lines:
        method = line["method"]
        condensation = line["2x2"]
        ys = [line[x] for x in densities]

        plt.plot(
            densities,
            ys,
            METHOD_SHAPE[method] + COND_SHAPE[condensation],
            color=METHOD_COLOR[method],
            label=method + COND_LEGEND[condensation],
        )

    plt.xlabel("density, %")
    plt.ylabel("CPU time, ms")

    if "2000" not in out_file:
        lgd = plt.legend(loc=2, prop=fontP)
    else:
        lgd = plt.legend(loc=2, bbox_to_anchor=(1, 1), prop=fontP)
    plt.grid(True)
    plt.savefig(out_file, bbox_extra_artists=(lgd,), bbox_inches="tight", format=out_file[-3:], dpi=dpi)
Example #21
0
def basic_skysurvey_plot_setup(from_plane=ephem.degrees('0')):
    # # EmulateApJ columnwidth=245.26 pts
    # fig_width_pt = 246.0
    # inches_per_pt = 1.0 / 72.27
    # golden_mean = (sqrt(5.) - 1.0) / 2.0
    # fig_width = fig_width_pt * inches_per_pt
    # fig_height = fig_width * golden_mean * 1.5
    # fig_size = [fig_width, fig_height]

    fig = plt.figure()
    ax = fig.add_subplot(111)  # , aspect="equal")

    handles = []  # this handles the creation of the legend properly at the end of plotting
    labels = []
    handles, labels = plot_galactic_plane(handles, labels)
    # handles, labels = plot_ecliptic_plane(handles, labels)
    handles, labels = plot_invariable_plane(handles, labels, from_plane)

    fontP = FontProperties()
    fontP.set_size('small')  # make the fonts smaller
    plt.xlabel('RA (deg)')
    plt.ylabel('Declination (deg)')
    plt.grid(True, which='both')
    # plot_fanciness.remove_border(ax)

    return handles, labels, ax, fontP
Example #22
0
def graph(fil):
    heap, time , free = np.loadtxt(fil, delimiter=',', unpack=True)

    fig,ax1 = plt.subplots(dpi=120, figsize=(7,7))
    ax2 = plt.twinx()

    ax1.set_ylabel("Allocation time ($ms$)",color = 'blue')
    ax1.set_xlabel("Initial heap size ($MB$)")

    ax2.set_ylabel("Free space on heap ($MB$)",color = 'green')
    ax2.set_xlabel("Initial heap size ($MB$)")


    p1,= ax1.plot(heap,time, label='Time taken to allocate large array')
    p2,= ax2.plot(heap,free , label='Free space on heap' ,color = 'green')


    plt.title('Scala Fragmentation tolerance')

    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')


    lines =[p1,p2]

    plt.legend(lines, [l.get_label() for l in lines],prop = fontP ,loc =9)

    name =  fil.split('.')[0]
    name = name +".png"

    plt.savefig(name)
def make_cross_plot(wac_df, clm_df):
    '''
    x = 320/415
    y = 950/750
    '''

    for index_name in wac_df.index:
        roi_name = index_name[:-4]
        x = wac_df.loc[index_name].values
        y = clm_df.loc[roi_name+'_clm'].values
        x_data = np.ma.masked_array(x[0],np.isnan(x[0]))
        y_data = np.ma.masked_array(y[0],np.isnan(y[0]))
        print roi_name, np.mean(x_data), np.mean(y_data), np.std(x_data), np.std(y_data)
        plt.errorbar(np.mean(x_data), np.mean(y_data), xerr=np.std(x_data),
            yerr=np.std(y_data), marker='o', label=(roi_name), 
            c=colorloop.next())

    rois_rough = pd.read_csv('/home/sbraden/imps_ratio_rough.csv', index_col=0)
    rois_mare = pd.read_csv('/home/sbraden/imps_ratio_mare.csv', index_col=0)

    for roi_name in rois_rough.index:
        ratio = rois_rough.loc[roi_name].values
        plt.scatter(ratio[1], ratio[0], marker='s', c='blue')
    
    for roi_name in rois_mare.index:
        ratio = rois_mare.loc[roi_name].values
        plt.scatter(ratio[1], ratio[0], marker='s', c='red')

    fontP = FontProperties()
    fontP.set_size('small')
    plt.legend(loc='lower right', prop=fontP, numpoints=1)
    plt.xlabel('320/415 nm WAC ratio', fontsize=14)
    plt.ylabel('950/750 nm CLEM ratio', fontsize=14)
    plt.savefig('lunar_roi_cross_plot.png', dpi=300)
    plt.close()
Example #24
0
def compile_scatter_plot_3d(args):
    bytes = args['tp_sizes'][0]
    tracers = args['tracers']
    res_dir = '/home/mogeb/git/benchtrace/trace-client/'
    values = defaultdict(list)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    fname = res_dir + 'none_' + str(bytes) + 'bytes_1process.hist'
    with open(fname, 'r') as f:
        legend = f.readline()
    legend = legend.split(',')
    i = 0
    for tracer in tracers:
        fname = res_dir + tracer + '_' + str(bytes) + 'bytes_1process.hist'
        values[tracer] = np.genfromtxt(fname, delimiter=',', skip_header=1, names=legend,
                                       dtype=None)

    fontP = FontProperties()
    fontP.set_size('small')

    for tracer in tracers:
        ax.scatter(values[tracer]['cache_misses'], values[tracer]['Instructions'],
                   values[tracer]['latency'])
    plt.title('Latency according to cache_misses and instructions')
    ax.set_xlabel('cache_misses')
    ax.set_ylabel('Instructions')
    ax.set_zlabel('latency')
    plt.legend(prop=fontP)
    plt.show()
def main():

    # Write a part to put image directories into "groups"
    source_dirs = [
        '/home/sbraden/400mpp_15x15_clm_wac/mare/',
        '/home/sbraden/400mpp_15x15_clm_wac/pyro/',
        '/home/sbraden/400mpp_15x15_clm_wac/imps/',
        '/home/sbraden/400mpp_15x15_clm_wac/mare_immature/'
        ]

    for directory in source_dirs:
        
        print directory
        groupname = os.path.split(os.path.dirname(directory))[1]
        print groupname
        # read in LROC WAC images
        wac_img_list = iglob(directory+'*_wac.cub')
        # read in Clementine images
        clm_img_list = iglob(directory+'*_clm.cub')

        make_cloud_plot(wac_img_list, colorloop.next(), groupname)

    fontP = FontProperties()
    fontP.set_size('small')
    #plt.legend(loc='upper left', fancybox=True, prop=fontP, scatterpoints=1)
    #plt.axis([0.70, 0.86, 0.90, 1.15],fontsize=14)
    plt.axis([0.60, 0.90, 0.90, 1.20],fontsize=14)
    plt.axes().set_aspect('equal')
    # THIS next line does not get called:
    plt.margins(0.20) # 4% add "padding" to the data limits before they're autoscaled
    plt.xlabel('WAC 320/415 nm', fontsize=14)
    plt.ylabel('CLM 950/750 nm', fontsize=14)
    plt.savefig('lunar_roi_cloud_plot.png', dpi=300)
    plt.close()
Example #26
0
def compile_scatter_plot_ICL(args):
    bytes = args['tp_sizes'][0]
    tracers = args['tracers']
    res_dir = '/home/mogeb/git/benchtrace/trace-client/'
    values = defaultdict(list)
    cpi = defaultdict(list)

    fname = res_dir + 'none_' + str(bytes) + 'bytes_1process.hist'

    with open(fname, 'r') as f:
        legend = f.readline()
    legend = legend.split(',')

    for tracer in tracers:
        fname = res_dir + tracer + '_' + str(bytes) + 'bytes_1process.hist'
        values[tracer] = np.genfromtxt(fname, delimiter=',', skip_header=1, names=legend, dtype=int)

    for tracer in tracers:
        for i in range(0, len(values[tracer])):
            cpi[tracer].append(values[tracer]['CPU_cycles'][i] / values[tracer]['Instructions'][i])

    for tracer in tracers:
        plt.scatter(values[tracer]['L1_misses'], cpi[tracer], s=values[tracer]['latency']*0.8,
                    color=tracers_colors[tracer], alpha=0.3, label=tracer)

    fontP = FontProperties()
    fontP.set_size('small')
    plt.title('Latency according to CPI and L1 misses')
    plt.xlabel('L1_misses')
    plt.ylabel('CPI')
    plt.legend(prop=fontP)
    plt.show()
Example #27
0
def compile_lttng_subbuf(args):
    res_dir = '/home/mogeb/git/benchtrace/trace-client/'
    tp_sizes = args['tp_sizes']
    nprocesses = args['nprocesses']
    tracer = 'lttng'
    buf_sizes_kb = args['buf_sizes_kb']
    perc = 0.90

    for tp_size in tp_sizes:
        percentiles = []
        for buf_size_kb in buf_sizes_kb:
            for tp_size in tp_sizes:
                # fname = res_dir + tracer + '_' + str(byte_size) + 'bytes_' + nprocess + 'process.hist'
                fname = tracer + '_' + str(tp_size) + 'bytes_' + buf_size_kb\
                        + 'kbsubbuf_1_process.hist'
                with open(fname, 'r') as f:
                    legend = f.readline()
                legend = legend.split(',')
                values = np.genfromtxt(fname, delimiter=',', skip_header=1, names=legend, dtype=None,
                                       invalid_raise=False)
                # percentiles.append(np.percentile(values['latency'], perc))
                percentiles.append(np.average(values['latency']))
        plt.plot(buf_sizes_kb, percentiles, 'o-', label=tracer, color=tracers_colors[tracer])

        plt.title(str(int(perc * 100)) + 'th percentiles for the cost of a tracepoint according to'
                                         'payload size')
        plt.xlabel('Subbuffer size in kb')
        plt.ylabel('Time in ns')
        fontP = FontProperties()
        fontP.set_size('small')

        # imgname = 'pertp/90th_' + nprocess + 'proc_' + str(args['buf_size_kb']) + 'subbuf_kb'
        plt.legend()
        plt.show()
Example #28
0
def topic_distribution(name = None, study = None, order = None, **options):
    '''Given a model p_z,p_w_z,p_d_z, we can plot the document's distribution
    using p(z|d) = normalized((p(d|z)*p(z))) '''
    
    m = microbplsa.MicrobPLSA()
    m.open_model(name = name, study = study, **options) #get model from the results file
    #return document's distribution
    p_z_d = m.model.document_topics()
    
    Z,N =p_z_d.shape #number of samples
    if order is not None:
        p_z_d = p_z_d[:,order]
    n = np.arange(N)
    width = 25.0/float(N) #scale width of bars by number of samples
    p = [] #list of plots
    colors = plt.cm.rainbow(np.linspace(0, 1, Z))    
    
    Lab = Labelling(m, ignore_continuous = False)
    Lab.metadata(non_labels = ['BarcodeSequence'])
    R = Lab.correlate()
    labels_r = Lab.assignlabels(R,num_labels = 1)
    labels, r = zip(*labels_r)
    labels = [l.replace('(','\n(') for l in labels]
    
    #sort and organize labels and topics so they are always plotted in the same order
    labelsUnsorted = zipper(labels,range(0,Z))
    labelsUnsorted.sort()
    labels, Zrange = zip(*labelsUnsorted)
    Zrange = list(Zrange)
    p.append(plt.bar(n, p_z_d[Zrange[0],:], width, color=colors[0], linewidth = 0))
    height = p_z_d[Zrange[0],:]
    for i,z in enumerate(Zrange[1:]):
        p.append(plt.bar(n, p_z_d[z,:], width, color=colors[i+1], bottom=height, linewidth = 0))
        height += p_z_d[z,:]
    
    
    plt.ylabel('Probability P(z|d)')
    plt.xlabel('Sample')
    plt.title('Sample\'s topic distribution')
    #plt.xticks(np.arange(0,width/2.0,N*width), ['S'+str(n) for n in range(1,N)])

    topiclegend = ['Topic' + str(Zrange[labels.index(l)]+1) + ': '+ l + '\n ('+ str(r[Zrange[labels.index(l)]]) + ')' for l in labels]
    fontP = FontProperties()
    if N >60:
        fontP.set_size('xx-small')
    else: fontP.set_size('small')
    ax = plt.subplot(111)
    ratio = float(N)*0.5
    ax.set_aspect(ratio)
    ax.tick_params(axis = 'x', colors='w') #remove tick labels by setting them the same color as background
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, 0.5, box.height])

    if order is not None:
        plt.xticks(n, order, size = 'xx-small')
    if Z > 12: 
        columns = 2
    else: columns = 1
    plt.legend(p, topiclegend, prop = fontP, title = 'Topic Label', loc='center left', bbox_to_anchor=(1, 0.5), ncol = columns)
    return plt
Example #29
0
def plot(X, Y, Graphs, Type, State_State):
	colors = iter(cm.rainbow(np.linspace(0, 1, len(Graphs))))
	if Type == 1:
		XTitle = 'delta'

	elif Type == 2:
		XTitle = 'epsilon'
		Y = Y.T
	else:
		print "Incorrect plot type, correct plottypes are 1 for row by columns and 2 for columns by rows."
		exit()

	Title = "Plot of rate " + str(State_State) + " for different values of " + XTitle

	#not sure if this works
	plt.figure(Title)

	for x in range(len(Graphs)):
		plt.plot(X, Y[x], label= str(Graphs[x]), color=next(colors))
	plt.ylabel('rate')
	plt.xlabel(XTitle)
	plt.grid(True)
	plt.title(Title)
	fontP = FontProperties()
	fontP.set_size('small')
	plt.legend(bbox_to_anchor=(1.01, 1), loc='upper left', borderaxespad=0., prop = fontP)
	FileName = 'rate_' + str(State_State) + '_' + XTitle +'.png'
	plt.savefig(FileName)
def save_graph(go_dict, chart_type, level, parser):
	fontP = FontProperties()
	fontP.set_size('small')
	# The slices will be ordered and plotted counter-clockwise.
	figure = plt.figure(figsize=(10,10))
	
	labels = go_dict.keys()
	sizes = [parser.go_term_by_name_dict.get(x)[0].encountered_count for x in go_dict]
	#sizes = go_dict.values() 	
	#print (chart_type)
	#print (zip(labels, sizes))
	#print (sum(sizes))
	plt.title('Graph Level %s Pie Chart [%s]' % (level, chart_type))
	total = sum(sizes)
	
	labels = [l+" "+str(float(s)/total * 100)[0:4]+"%  ("+ str(s) + ")" for l,s in zip(labels, sizes)]

	patches, texts = plt.pie(sizes, startangle=90)
	plt.legend(patches, labels, prop = fontP, loc="best")
	# Set aspect ratio to be equal so that pie is drawn as a circle.
	plt.axis('equal')
	#plt.tight_layout()
	#plt.show()



	print (chart_type)
	out = [str(x) + "\t" + str(parser.go_term_by_name_dict.get(x)[0].encountered_count) for x in go_dict]

	for x in out:
		print (x)
	print ("\n")	


	figure.savefig(chart_type+"_level_"+level+'.png',aspect='auto',dpi=100)
Example #31
0
lw = 2.3
args = [fp_range, fp_range_val, take_log, ax1, ax2, ax3, ax4]
l1 = plot(root_path + 'olta0', args, PL1, 's', PL1, lw, '-', oluct_lo_mea)
if discrete:
    l2 = plot(root_path + 'olta1', args, PL2, 's', PL2, lw, '-', oluct_lo_mea)
l3 = plot(root_path + 'olta2', args, PL3, '^', 'none', lw, '-.', oluct_lo_mea)
l4 = plot(root_path + 'olta3', args, PL4, 'o', 'none', lw, '--', oluct_lo_mea)
l5 = plot(root_path + 'olta4', args, PL5, 's', 'none', lw, '-', oluct_lo_mea)
l0 = plot(root_path + 'oluct', args, PL0, 'o', PL0, lw, '-', oluct_lo_mea)

# Label ------------------------------------------------------------------------

font = FontProperties()
font.set_family('serif')
font.set_style('normal')
font.set_size('x-large')
font.set_weight('light')

labsz = 13
xlab = 'Transition misstep probability'
ylab1 = 'Loss (time steps\nto reach all the\nwaypoints)'
ylab2 = 'Mean loss\nrelatively to\nOLUCT loss'
ylab3 = 'Computational\ncost (ms)'
ylab4 = 'Number of\ncalls'

apply_label(ax1, xlab, ylab1, font, False)
apply_label(ax2, xlab, ylab2, font, True)
apply_label(ax3, xlab, ylab3, font, False)
apply_label(ax4, xlab, ylab4, font, False)

# Legend -----------------------------------------------------------------------
Example #32
0
def SEAMO2(transportNetwork, problem):
    '''
    The main algorithm - detailed description in Paper
    '''
    population_size, generation_count = problem.initial, problem.generations
    population = generate_initial_population(transportNetwork, problem)
    #objectives = ["passengers", "operator"]
    objectives = ["passengers"]

    gen_stats = []

    best_objective = min(population, key = lambda x: x.get_scores("passengers"))
    for generation in range(generation_count):
        gen_stats.append(GenStat(generation, population_size))
        print "new generation", generation
        for parent1_index in range(population_size):
            # select parent 1
            parent1 = population[parent1_index]
            gen_stats[-1].all_scores.append(parent1.get_scores("passengers"))
            # select parent 2
            parent2_index = random.randint(0, population_size - 1)
            parent2 = population[parent2_index]
            # generate an offspring
            offspring = crossover(parent1, parent2, transportNetwork, problem)

            # repair the offspring - this shouldn't be necessary
            repair(offspring, transportNetwork, problem.max, problem.min)

            # apply mutation - gamma ray radiation
            mutate(offspring, problem.busses, problem.max, problem.min)
            if len(offspring.covered) < len(offspring.transportNetwork.nodes()):
                gen_stats[-1].offs_bad += 1
                continue
            # this is a heavy function
            offspring.calc_scores()

            # insert offspring into population
            if offspring in population:
                continue
            # if offspring dominates best so far objective
            if offspring.get_scores("passengers") < best_objective.get_scores("passengers"):
                gen_stats[-1].offs_best_news += 1
                best_objective = offspring
                population[random.choice([parent1_index, parent2_index])] = offspring
            # if offspring dominates either parent
            elif offspring.dominates(parent1):
                #print "offspring dominates parent 1"
                gen_stats[-1].offs_dominates_parent += 1
                population[parent1_index] = offspring
            elif offspring.dominates(parent2):
                #print "offspring dominates parent 2"
                gen_stats[-1].offs_dominates_parent += 1
                population[parent2_index] = offspring
            # mutual non domination
            elif not parent1.dominates(offspring) and not parent2.dominates(offspring):
                for ind in range(population_size):
                    if offspring.dominates(population[ind]):
                        gen_stats[-1].offs_replace_other += 1
                        population[ind] = offspring
                        break
            # just delete offspring
            else:
                gen_stats[-1].offs_thrown_away += 1
                continue
        gen_stats[-1].finalize()

    datas = zip(*[stat.get_params() for stat in gen_stats])
    labels = gen_stats[0].property_names
    for i, data in enumerate(datas):
        plt.plot(range(len(data)), data, label = labels[i], marker = 'o', linestyle = 'None')
    plt.legend()
    fontP = FontProperties()
    fontP.set_size('small')
    plt.legend(prop = fontP, bbox_to_anchor=(0.95, 1), loc='upper right', ncol=1)
    plt.title('Map %s - Population size: %d, Generations: %d' % (problem.graph, population_size, generation_count))
    plt.savefig(os.path.join('generating','stats.png'))
    plt.clf()

    return best_objective, gen_stats
Example #33
0
class Legend(Artist):
    """
    Place a legend on the axes at location loc.  Labels are a
    sequence of strings and loc can be a string or an integer
    specifying the legend location

    The location codes are::

      'best'         : 0, (only implemented for axis legends)
      '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,

    loc can be a tuple of the noramilzed coordinate values with
    respect its parent.

    Return value is a sequence of text, line instances that make
    up the legend
    """

    codes = {
        'best': 0,  # only implemented for axis legends
        '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,
    }

    zorder = 5

    def __str__(self):
        return "Legend"

    def __init__(
            self,
            parent,
            handles,
            labels,
            loc=None,
            numpoints=None,  # the number of points in the legend line
            markerscale=None,  # the relative size of legend markers vs. original
            scatterpoints=3,  # TODO: may be an rcParam
            scatteryoffsets=None,
            prop=None,  # properties for the legend texts

            # the following dimensions are in axes coords
        pad=None,  # deprecated; use borderpad
            labelsep=None,  # deprecated; use labelspacing
            handlelen=None,  # deprecated; use handlelength
            handletextsep=None,  # deprecated; use handletextpad
            axespad=None,  # deprecated; use borderaxespad

            # spacing & pad defined as a fraction of the font-size
        borderpad=None,  # the whitespace inside the legend border
            labelspacing=None,  #the vertical space between the legend entries
            handlelength=None,  # the length of the legend handles
            handletextpad=None,  # the pad between the legend handle and text
            borderaxespad=None,  # the pad between the axes and legend border
            columnspacing=None,  # spacing between columns
            ncol=1,  # number of columns
            mode=None,  # mode for horizontal distribution of columns. None, "expand"
            fancybox=None,  # True use a fancy box, false use a rounded box, none use rc
            shadow=None,
            title=None,  # set a title for the legend
            bbox_to_anchor=None,  # bbox that the legend will be anchored.
            bbox_transform=None,  # transform for the bbox
            frameon=True,  # draw frame
    ):
        """
        - *parent* : the artist that contains the legend
        - *handles* : a list of artists (lines, patches) to add to the legend
        - *labels* : a list of strings to label the legend

        Optional keyword arguments:

        ================   ==================================================================
        Keyword            Description
        ================   ==================================================================
        loc                a location code
        prop               the font property
        markerscale        the relative size of legend markers vs. original
        numpoints          the number of points in the legend for line
        scatterpoints      the number of points in the legend for scatter plot
        scatteryoffsets    a list of yoffsets for scatter symbols in legend
        frameon            if True, draw a frame (default is True)
        fancybox           if True, draw a frame with a round fancybox.  If None, use rc
        shadow             if True, draw a shadow behind legend
        ncol               number of columns
        borderpad          the fractional whitespace inside the legend border
        labelspacing       the vertical space between the legend entries
        handlelength       the length of the legend handles
        handletextpad      the pad between the legend handle and text
        borderaxespad      the pad between the axes and legend border
        columnspacing      the spacing between columns
        title              the legend title
        bbox_to_anchor     the bbox that the legend will be anchored.
        bbox_transform     the transform for the bbox. transAxes if None.
        ================   ==================================================================


The pad and spacing parameters are measure in font-size units.  E.g.,
a fontsize of 10 points and a handlelength=5 implies a handlelength of
50 points.  Values from rcParams will be used if None.

Users can specify any arbitrary location for the legend using the
*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
See :meth:`set_bbox_to_anchor` for more detail.

The legend location can be specified by setting *loc* with a tuple of
2 floats, which is interpreted as the lower-left corner of the legend
in the normalized axes coordinate.
        """
        from matplotlib.axes import Axes  # local import only to avoid circularity
        from matplotlib.figure import Figure  # local import only to avoid circularity

        Artist.__init__(self)

        if prop is None:
            self.prop = FontProperties(size=rcParams["legend.fontsize"])
        elif isinstance(prop, dict):
            self.prop = FontProperties(**prop)
            if "size" not in prop:
                self.prop.set_size(rcParams["legend.fontsize"])
        else:
            self.prop = prop

        self._fontsize = self.prop.get_size_in_points()

        propnames = [
            'numpoints', 'markerscale', 'shadow', "columnspacing",
            "scatterpoints"
        ]

        self.texts = []
        self.legendHandles = []
        self._legend_title_box = None

        localdict = locals()

        for name in propnames:
            if localdict[name] is None:
                value = rcParams["legend." + name]
            else:
                value = localdict[name]
            setattr(self, name, value)

        # Take care the deprecated keywords
        deprecated_kwds = {
            "pad": "borderpad",
            "labelsep": "labelspacing",
            "handlelen": "handlelength",
            "handletextsep": "handletextpad",
            "axespad": "borderaxespad"
        }

        # convert values of deprecated keywords (ginve in axes coords)
        # to new vaules in a fraction of the font size

        # conversion factor
        bbox = parent.bbox
        axessize_fontsize = min(bbox.width, bbox.height) / self._fontsize

        for k, v in deprecated_kwds.items():
            # use deprecated value if not None and if their newer
            # counter part is None.
            if localdict[k] is not None and localdict[v] is None:
                warnings.warn("Use '%s' instead of '%s'." % (v, k),
                              DeprecationWarning)
                setattr(self, v, localdict[k] * axessize_fontsize)
                continue

            # Otherwise, use new keywords
            if localdict[v] is None:
                setattr(self, v, rcParams["legend." + v])
            else:
                setattr(self, v, localdict[v])

        del localdict

        handles = list(handles)
        if len(handles) < 2:
            ncol = 1
        self._ncol = ncol

        if self.numpoints <= 0:
            raise ValueError("numpoints must be >= 0; it was %d" % numpoints)

        # introduce y-offset for handles of the scatter plot
        if scatteryoffsets is None:
            self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
        else:
            self._scatteryoffsets = np.asarray(scatteryoffsets)
        reps = int(self.scatterpoints / len(self._scatteryoffsets)) + 1
        self._scatteryoffsets = np.tile(self._scatteryoffsets,
                                        reps)[:self.scatterpoints]

        # _legend_box is an OffsetBox instance that contains all
        # legend items and will be initialized from _init_legend_box()
        # method.
        self._legend_box = None

        if isinstance(parent, Axes):
            self.isaxes = True
            self.set_axes(parent)
            self.set_figure(parent.figure)
        elif isinstance(parent, Figure):
            self.isaxes = False
            self.set_figure(parent)
        else:
            raise TypeError("Legend needs either Axes or Figure as parent")
        self.parent = parent

        if loc is None:
            loc = rcParams["legend.loc"]
            if not self.isaxes and loc in [0, 'best']:
                loc = 'upper right'
        if is_string_like(loc):
            if loc not in self.codes:
                if self.isaxes:
                    warnings.warn(
                        'Unrecognized location "%s". Falling back on "best"; '
                        'valid locations are\n\t%s\n' %
                        (loc, '\n\t'.join(self.codes.keys())))
                    loc = 0
                else:
                    warnings.warn(
                        'Unrecognized location "%s". Falling back on "upper right"; '
                        'valid locations are\n\t%s\n' %
                        (loc, '\n\t'.join(self.codes.keys())))
                    loc = 1
            else:
                loc = self.codes[loc]
        if not self.isaxes and loc == 0:
            warnings.warn(
                'Automatic legend placement (loc="best") not implemented for figure legend. '
                'Falling back on "upper right".')
            loc = 1

        self._mode = mode
        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)

        # We use FancyBboxPatch to draw a legend frame. The location
        # and size of the box will be updated during the drawing time.

        self.legendPatch = FancyBboxPatch(xy=(0.0, 0.0),
                                          width=1.,
                                          height=1.,
                                          facecolor=rcParams["axes.facecolor"],
                                          edgecolor=rcParams["axes.edgecolor"],
                                          mutation_scale=self._fontsize,
                                          snap=True)

        # The width and height of the legendPatch will be set (in the
        # draw()) to the length that includes the padding. Thus we set
        # pad=0 here.
        if fancybox is None:
            fancybox = rcParams["legend.fancybox"]

        if fancybox == True:
            self.legendPatch.set_boxstyle("round", pad=0, rounding_size=0.2)
        else:
            self.legendPatch.set_boxstyle("square", pad=0)

        self._set_artist_props(self.legendPatch)

        self._drawFrame = frameon

        # init with null renderer
        self._init_legend_box(handles, labels)

        self._loc = loc

        self.set_title(title)

        self._last_fontsize_points = self._fontsize

        self._draggable = None

    def _set_artist_props(self, a):
        """
        set the boilerplate props for artists added to axes
        """
        a.set_figure(self.figure)
        if self.isaxes:
            a.set_axes(self.axes)
        a.set_transform(self.get_transform())

    def _set_loc(self, loc):
        # find_offset function will be provided to _legend_box and
        # _legend_box will draw itself at the location of the return
        # value of the find_offset.
        self._loc_real = loc
        if loc == 0:
            _findoffset = self._findoffset_best
        else:
            _findoffset = self._findoffset_loc

        #def findoffset(width, height, xdescent, ydescent):
        #    return _findoffset(width, height, xdescent, ydescent, renderer)

        self._legend_box.set_offset(_findoffset)

        self._loc_real = loc

    def _get_loc(self):
        return self._loc_real

    _loc = property(_get_loc, _set_loc)

    def _findoffset_best(self, width, height, xdescent, ydescent, renderer):
        "Helper function to locate the legend at its best position"
        ox, oy = self._find_best_position(width, height, renderer)
        return ox + xdescent, oy + ydescent

    def _findoffset_loc(self, width, height, xdescent, ydescent, renderer):
        "Heper function to locate the legend using the location code"

        if iterable(self._loc) and len(self._loc) == 2:
            # when loc is a tuple of axes(or figure) coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
        else:
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(), renderer)

        return x + xdescent, y + ydescent

    @allow_rasterization
    def draw(self, renderer):
        "Draw everything that belongs to the legend"
        if not self.get_visible(): return

        renderer.open_group('legend')

        fontsize = renderer.points_to_pixels(self._fontsize)

        # if mode == fill, set the width of the legend_box to the
        # width of the paret (minus pads)
        if self._mode in ["expand"]:
            pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
            self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)

        if self._drawFrame:
            # update the location and size of the legend
            bbox = self._legend_box.get_window_extent(renderer)
            self.legendPatch.set_bounds(bbox.x0, bbox.y0, bbox.width,
                                        bbox.height)

            self.legendPatch.set_mutation_scale(fontsize)

            if self.shadow:
                shadow = Shadow(self.legendPatch, 2, -2)
                shadow.draw(renderer)

            self.legendPatch.draw(renderer)

        self._legend_box.draw(renderer)

        renderer.close_group('legend')

    def _approx_text_height(self, renderer=None):
        """
        Return the approximate height of the text. This is used to place
        the legend handle.
        """
        if renderer is None:
            return self._fontsize
        else:
            return renderer.points_to_pixels(self._fontsize)

    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self._fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.

        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(
            verticalalignment='baseline',
            horizontalalignment='left',
            fontproperties=self.prop,
        )

        labelboxes = []
        handleboxes = []

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        height = self._approx_text_height() * 0.7
        descent = 0.

        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their corrdinates should
        # be given in the display coordinates.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not uses its
        # default trasnform (eg, Collections), you need to
        # manually set their transform to the self.get_transform().

        for handle, lab in zip(handles, labels):
            if isinstance(handle, RegularPolyCollection) or \
                   isinstance(handle, CircleCollection):
                npoints = self.scatterpoints
            else:
                npoints = self.numpoints
            if npoints > 1:
                # we put some pad here to compensate the size of the
                # marker
                xdata = np.linspace(0.3 * fontsize,
                                    (self.handlelength - 0.3) * fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength * fontsize, 2)
                xdata_marker = [0.5 * self.handlelength * fontsize]

            if isinstance(handle, Line2D):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)

                legline.update_from(handle)
                self._set_artist_props(legline)  # after update
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                legline.set_drawstyle('default')
                legline.set_marker('None')

                handle_list.append(legline)

                legline_marker = Line2D(xdata_marker,
                                        ydata[:len(xdata_marker)])
                legline_marker.update_from(handle)
                self._set_artist_props(legline_marker)
                legline_marker.set_clip_box(None)
                legline_marker.set_clip_path(None)
                legline_marker.set_linestyle('None')
                if self.markerscale != 1:
                    newsz = legline_marker.get_markersize() * self.markerscale
                    legline_marker.set_markersize(newsz)
                # we don't want to add this to the return list because
                # the texts and handles are assumed to be in one-to-one
                # correpondence.
                legline._legmarker = legline_marker

            elif isinstance(handle, Patch):
                p = Rectangle(
                    xy=(0., 0.),
                    width=self.handlelength * fontsize,
                    height=(height - descent),
                )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            elif isinstance(handle, LineCollection):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                if dashes[0] is not None:  # dashed line
                    legline.set_dashes(dashes[1])
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                #ydata = self._scatteryoffsets
                ydata = height * self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                if self.scatterpoints < 4:
                    sizes = [.5 * (size_max + size_min), size_max, size_min]
                else:
                    sizes = (size_max - size_min) * np.linspace(
                        0, 1, self.scatterpoints) + size_min

                p = type(handle)(
                    handle.get_numsides(),
                    rotation=handle.get_rotation(),
                    sizes=sizes,
                    offsets=zip(xdata_marker, ydata),
                    transOffset=self.get_transform(),
                )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)

            elif isinstance(handle, CircleCollection):

                ydata = height * self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                if self.scatterpoints < 4:
                    sizes = [.5 * (size_max + size_min), size_max, size_min]
                else:
                    sizes = (size_max - size_min) * np.linspace(
                        0, 1, self.scatterpoints) + size_min

                p = type(handle)(
                    sizes,
                    offsets=zip(xdata_marker, ydata),
                    transOffset=self.get_transform(),
                )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            else:
                handle_type = type(handle)
                warnings.warn(
                    "Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n"
                    % (str(handle_type), ))
                handle_list.append(None)

            handle = handle_list[-1]
            if handle is not None:  # handle is None is the artist is not supproted
                textbox = TextArea(lab,
                                   textprops=label_prop,
                                   multilinebaseline=True,
                                   minimumdescent=True)
                text_list.append(textbox._text)

                labelboxes.append(textbox)

                handlebox = DrawingArea(width=self.handlelength * fontsize,
                                        height=height,
                                        xdescent=0.,
                                        ydescent=descent)

                handlebox.add_artist(handle)

                # special case for collection instances
                if isinstance(handle, RegularPolyCollection) or \
                       isinstance(handle, CircleCollection):
                    handle._transOffset = handlebox.get_transform()
                    handle.set_transform(None)

                if hasattr(handle, "_legmarker"):
                    handlebox.add_artist(handle._legmarker)
                handleboxes.append(handlebox)

        if len(handleboxes) > 0:

            # We calculate number of lows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaing
            # (num_smallcol) columns will have (nrows) rows.
            ncol = min(self._ncol, len(handleboxes))
            nrows, num_largecol = divmod(len(handleboxes), ncol)
            num_smallcol = ncol - num_largecol

            # starting index of each column and number of rows in it.
            largecol = safezip(
                range(0, num_largecol * (nrows + 1), (nrows + 1)),
                [nrows + 1] * num_largecol)
            smallcol = safezip(
                range(num_largecol * (nrows + 1), len(handleboxes), nrows),
                [nrows] * num_smallcol)
        else:
            largecol, smallcol = [], []

        handle_label = safezip(handleboxes, labelboxes)
        columnbox = []
        for i0, di in largecol + smallcol:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [
                HPacker(pad=0,
                        sep=self.handletextpad * fontsize,
                        children=[h, t],
                        align="baseline") for h, t in handle_label[i0:i0 + di]
            ]
            # minimumdescent=False for the text of the last row of the column
            itemBoxes[-1].get_children()[1].set_minimumdescent(False)

            # pack columnBox
            columnbox.append(
                VPacker(pad=0,
                        sep=self.labelspacing * fontsize,
                        align="baseline",
                        children=itemBoxes))

        if self._mode == "expand":
            mode = "expand"
        else:
            mode = "fixed"

        sep = self.columnspacing * fontsize

        self._legend_handle_box = HPacker(pad=0,
                                          sep=sep,
                                          align="baseline",
                                          mode=mode,
                                          children=columnbox)

        self._legend_title_box = TextArea("")

        self._legend_box = VPacker(
            pad=self.borderpad * fontsize,
            sep=self.labelspacing * fontsize,
            align="center",
            children=[self._legend_title_box, self._legend_handle_box])

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list

    def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """

        assert self.isaxes  # should always hold because function is only called internally

        ax = self.parent
        vertices = []
        bboxes = []
        lines = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        return [vertices, bboxes, lines]

    def draw_frame(self, b):
        'b is a boolean.  Set draw frame to b'
        self.set_frame_on(b)

    def get_children(self):
        'return a list of child artists'
        children = []
        if self._legend_box:
            children.append(self._legend_box)
        children.extend(self.get_lines())
        children.extend(self.get_patches())
        children.extend(self.get_texts())
        children.append(self.get_frame())

        if self._legend_title_box:
            children.append(self.get_title())
        return children

    def get_frame(self):
        'return the Rectangle instance used to frame the legend'
        return self.legendPatch

    def get_lines(self):
        'return a list of lines.Line2D instances in the legend'
        return [h for h in self.legendHandles if isinstance(h, Line2D)]

    def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list(
            'Patch', [h for h in self.legendHandles if isinstance(h, Patch)])

    def get_texts(self):
        'return a list of text.Text instance in the legend'
        return silent_list('Text', self.texts)

    def set_title(self, title):
        'set the legend title'
        self._legend_title_box._text.set_text(title)

        if title:
            self._legend_title_box.set_visible(True)
        else:
            self._legend_title_box.set_visible(False)

    def get_title(self):
        'return Text instance for the legend title'
        return self._legend_title_box._text

    def get_window_extent(self):
        'return a extent of the the legend'
        return self.legendPatch.get_window_extent()

    def get_frame_on(self):
        """
        Get whether the legend box patch is drawn
        """
        return self._drawFrame

    def set_frame_on(self, b):
        """
        Set whether the legend box patch is drawn

        ACCEPTS: [ *True* | *False* ]
        """
        self._drawFrame = b

    def get_bbox_to_anchor(self):
        """
        return the bbox that the legend will be anchored
        """
        if self._bbox_to_anchor is None:
            return self.parent.bbox
        else:
            return self._bbox_to_anchor

    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        set the bbox that the legend will be anchored.

        *bbox* can be a BboxBase instance, a tuple of [left, bottom,
        width, height] in the given transform (normalized axes
        coordinate if None), or a tuple of [left, bottom] where the
        width and height will be assumed to be zero.
        """
        if bbox is None:
            self._bbox_to_anchor = None
            return
        elif isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError:
                raise ValueError("Invalid argument for bbox : %s" % str(bbox))

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        if transform is None:
            transform = BboxTransformTo(self.parent.bbox)

        self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor, transform)

    def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
        """
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x,y) coordinate of the bbox.

        - loc: a location code in range(1, 11).
          This corresponds to the possible values for self._loc, excluding "best".

        - bbox: bbox to be placed, display coodinate units.
        - parentbbox: a parent box which will contain the bbox. In
            display coordinates.
        """
        assert loc in range(1, 11)  # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)

        anchor_coefs = {
            UR: "NE",
            UL: "NW",
            LL: "SW",
            LR: "SE",
            R: "E",
            CL: "W",
            CR: "E",
            LC: "S",
            UC: "N",
            C: "C"
        }

        c = anchor_coefs[loc]

        fontsize = renderer.points_to_pixels(self._fontsize)
        container = parentbbox.padded(-(self.borderaxespad) * fontsize)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0

    def _find_best_position(self, width, height, renderer, consider=None):
        """
        Determine the best location to place the legend.

        `consider` is a list of (x, y) pairs to consider as a potential
        lower-left corner of the legend. All are display coords.
        """

        assert self.isaxes  # should always hold because function is only called internally

        verts, bboxes, lines = self._auto_legend_data()

        bbox = Bbox.from_bounds(0, 0, width, height)
        consider = [
            self._get_anchored_bbox(x, bbox, self.get_bbox_to_anchor(),
                                    renderer)
            for x in range(1, len(self.codes))
        ]

        #tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y()

        candidates = []
        for l, b in consider:
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            badness = legendBox.count_contains(verts)
            badness += legendBox.count_overlaps(bboxes)
            for line in lines:
                if line.intersects_bbox(legendBox):
                    badness += 1

            ox, oy = l, b
            if badness == 0:
                return ox, oy

            candidates.append((badness, (l, b)))

        # rather than use min() or list.sort(), do this so that we are assured
        # that in the case of two equal badnesses, the one first considered is
        # returned.
        # NOTE: list.sort() is stable.But leave as it is for now. -JJL
        minCandidate = candidates[0]
        for candidate in candidates:
            if candidate[0] < minCandidate[0]:
                minCandidate = candidate

        ox, oy = minCandidate[1]

        return ox, oy

    def draggable(self, state=None, use_blit=False):
        """
        Set the draggable state -- if state is

          * None : toggle the current state

          * True : turn draggable on

          * False : turn draggable off

        If draggable is on, you can drag the legend on the canvas with
        the mouse.  The DraggableLegend helper instance is returned if
        draggable is on.
        """
        is_draggable = self._draggable is not None

        # if state is None we'll toggle
        if state is None:
            state = not is_draggable

        if state:
            if self._draggable is None:
                self._draggable = DraggableLegend(self, use_blit)
        else:
            if self._draggable is not None:
                self._draggable.disconnect()
            self._draggable = None

        return self._draggable
class Legend(Artist):
    """
    Place a legend on the axes at location loc.

    """
    codes = {'best':         0,  # only implemented for axes legends
             '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,
             }

    zorder = 5

    def __str__(self):
        return "Legend"

    @docstring.dedent_interpd
    def __init__(self, parent, handles, labels,
                 loc=None,
                 numpoints=None,    # the number of points in the legend line
                 markerscale=None,  # the relative size of legend markers
                                    # vs. original
                 markerfirst=True,  # controls ordering (left-to-right) of
                                    # legend marker and label
                 scatterpoints=None,    # number of scatter points
                 scatteryoffsets=None,
                 prop=None,          # properties for the legend texts
                 fontsize=None,      # keyword to set font size directly
                 labelcolor=None,    # keyword to set the text color

                 # spacing & pad defined as a fraction of the font-size
                 borderpad=None,      # the whitespace inside the legend border
                 labelspacing=None,   # the vertical space between the legend
                                      # entries
                 handlelength=None,   # the length of the legend handles
                 handleheight=None,   # the height of the legend handles
                 handletextpad=None,  # the pad between the legend handle
                                      # and text
                 borderaxespad=None,  # the pad between the axes and legend
                                      # border
                 columnspacing=None,  # spacing between columns

                 ncol=1,     # number of columns
                 mode=None,  # mode for horizontal distribution of columns.
                             # None, "expand"

                 fancybox=None,  # True use a fancy box, false use a rounded
                                 # box, none use rc
                 shadow=None,
                 title=None,  # set a title for the legend
                 title_fontsize=None,  # the font size for the title
                 framealpha=None,  # set frame alpha
                 edgecolor=None,  # frame patch edgecolor
                 facecolor=None,  # frame patch facecolor

                 bbox_to_anchor=None,  # bbox that the legend will be anchored.
                 bbox_transform=None,  # transform for the bbox
                 frameon=None,  # draw frame
                 handler_map=None,
                 ):
        """
        Parameters
        ----------
        parent : `~matplotlib.axes.Axes` or `.Figure`
            The artist that contains the legend.

        handles : list of `.Artist`
            A list of Artists (lines, patches) to be added to the legend.

        labels : list of str
            A list of labels to show next to the artists. The length of handles
            and labels should be the same. If they are not, they are truncated
            to the smaller of both lengths.

        Other Parameters
        ----------------
        %(_legend_kw_doc)s

        Notes
        -----
        Users can specify any arbitrary location for the legend using the
        *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a
        `.BboxBase` (or derived therefrom) or a tuple of 2 or 4 floats.
        See `set_bbox_to_anchor` for more detail.

        The legend location can be specified by setting *loc* with a tuple of
        2 floats, which is interpreted as the lower-left corner of the legend
        in the normalized axes coordinate.
        """
        # local import only to avoid circularity
        from matplotlib.axes import Axes
        from matplotlib.figure import Figure

        Artist.__init__(self)

        if prop is None:
            if fontsize is not None:
                self.prop = FontProperties(size=fontsize)
            else:
                self.prop = FontProperties(
                    size=mpl.rcParams["legend.fontsize"])
        else:
            self.prop = FontProperties._from_any(prop)
            if isinstance(prop, dict) and "size" not in prop:
                self.prop.set_size(mpl.rcParams["legend.fontsize"])

        self._fontsize = self.prop.get_size_in_points()

        self.texts = []
        self.legendHandles = []
        self._legend_title_box = None

        #: A dictionary with the extra handler mappings for this Legend
        #: instance.
        self._custom_handler_map = handler_map

        locals_view = locals()
        for name in ["numpoints", "markerscale", "shadow", "columnspacing",
                     "scatterpoints", "handleheight", 'borderpad',
                     'labelspacing', 'handlelength', 'handletextpad',
                     'borderaxespad']:
            if locals_view[name] is None:
                value = mpl.rcParams["legend." + name]
            else:
                value = locals_view[name]
            setattr(self, name, value)
        del locals_view
        # trim handles and labels if illegal label...
        _lab, _hand = [], []
        for label, handle in zip(labels, handles):
            if isinstance(label, str) and label.startswith('_'):
                cbook._warn_external('The handle {!r} has a label of {!r} '
                                     'which cannot be automatically added to'
                                     ' the legend.'.format(handle, label))
            else:
                _lab.append(label)
                _hand.append(handle)
        labels, handles = _lab, _hand

        handles = list(handles)
        if len(handles) < 2:
            ncol = 1
        self._ncol = ncol

        if self.numpoints <= 0:
            raise ValueError("numpoints must be > 0; it was %d" % numpoints)

        # introduce y-offset for handles of the scatter plot
        if scatteryoffsets is None:
            self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
        else:
            self._scatteryoffsets = np.asarray(scatteryoffsets)
        reps = self.scatterpoints // len(self._scatteryoffsets) + 1
        self._scatteryoffsets = np.tile(self._scatteryoffsets,
                                        reps)[:self.scatterpoints]

        # _legend_box is a VPacker instance that contains all
        # legend items and will be initialized from _init_legend_box()
        # method.
        self._legend_box = None

        if isinstance(parent, Axes):
            self.isaxes = True
            self.axes = parent
            self.set_figure(parent.figure)
        elif isinstance(parent, Figure):
            self.isaxes = False
            self.set_figure(parent)
        else:
            raise TypeError("Legend needs either Axes or Figure as parent")
        self.parent = parent

        self._loc_used_default = loc is None
        if loc is None:
            loc = mpl.rcParams["legend.loc"]
            if not self.isaxes and loc in [0, 'best']:
                loc = 'upper right'
        if isinstance(loc, str):
            if loc not in self.codes:
                raise ValueError(
                    "Unrecognized location {!r}. Valid locations are\n\t{}\n"
                    .format(loc, '\n\t'.join(self.codes)))
            else:
                loc = self.codes[loc]
        if not self.isaxes and loc == 0:
            raise ValueError(
                "Automatic legend placement (loc='best') not implemented for "
                "figure legend.")

        self._mode = mode
        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)

        # We use FancyBboxPatch to draw a legend frame. The location
        # and size of the box will be updated during the drawing time.

        if facecolor is None:
            facecolor = mpl.rcParams["legend.facecolor"]
        if facecolor == 'inherit':
            facecolor = mpl.rcParams["axes.facecolor"]

        if edgecolor is None:
            edgecolor = mpl.rcParams["legend.edgecolor"]
        if edgecolor == 'inherit':
            edgecolor = mpl.rcParams["axes.edgecolor"]

        if fancybox is None:
            fancybox = mpl.rcParams["legend.fancybox"]

        self.legendPatch = FancyBboxPatch(
            xy=(0, 0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            # If shadow is used, default to alpha=1 (#8943).
            alpha=(framealpha if framealpha is not None
                   else 1 if shadow
                   else mpl.rcParams["legend.framealpha"]),
            # The width and height of the legendPatch will be set (in draw())
            # to the length that includes the padding. Thus we set pad=0 here.
            boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
                      else "square,pad=0"),
            mutation_scale=self._fontsize,
            snap=True,
            visible=(frameon if frameon is not None
                     else mpl.rcParams["legend.frameon"])
        )
        self._set_artist_props(self.legendPatch)

        # init with null renderer
        self._init_legend_box(handles, labels, markerfirst)

        tmp = self._loc_used_default
        self._set_loc(loc)
        self._loc_used_default = tmp  # ignore changes done by _set_loc

        # figure out title fontsize:
        if title_fontsize is None:
            title_fontsize = mpl.rcParams['legend.title_fontsize']
        tprop = FontProperties(size=title_fontsize)
        self.set_title(title, prop=tprop)
        self._draggable = None

        # set the text color

        color_getters = {  # getter function depends on line or patch
            'linecolor':       ['get_color',           'get_facecolor'],
            'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
            'mfc':             ['get_markerfacecolor', 'get_facecolor'],
            'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
            'mec':             ['get_markeredgecolor', 'get_edgecolor'],
        }
        if labelcolor is None:
            pass
        elif isinstance(labelcolor, str) and labelcolor in color_getters:
            getter_names = color_getters[labelcolor]
            for handle, text in zip(self.legendHandles, self.texts):
                for getter_name in getter_names:
                    try:
                        color = getattr(handle, getter_name)()
                        text.set_color(color)
                        break
                    except AttributeError:
                        pass
        elif np.iterable(labelcolor):
            for text, color in zip(self.texts,
                                   itertools.cycle(
                                       colors.to_rgba_array(labelcolor))):
                text.set_color(color)
        else:
            raise ValueError("Invalid argument for labelcolor : %s" %
                             str(labelcolor))

    def _set_artist_props(self, a):
        """
        Set the boilerplate props for artists added to axes.
        """
        a.set_figure(self.figure)
        if self.isaxes:
            # a.set_axes(self.axes)
            a.axes = self.axes

        a.set_transform(self.get_transform())

    def _set_loc(self, loc):
        # find_offset function will be provided to _legend_box and
        # _legend_box will draw itself at the location of the return
        # value of the find_offset.
        self._loc_used_default = False
        self._loc_real = loc
        self.stale = True
        self._legend_box.set_offset(self._findoffset)

    def _get_loc(self):
        return self._loc_real

    _loc = property(_get_loc, _set_loc)

    def _findoffset(self, width, height, xdescent, ydescent, renderer):
        """Helper function to locate the legend."""

        if self._loc == 0:  # "best".
            x, y = self._find_best_position(width, height, renderer)
        elif self._loc in Legend.codes.values():  # Fixed location.
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(),
                                           renderer)
        else:  # Axes or figure coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy

        return x + xdescent, y + ydescent

    @allow_rasterization
    def draw(self, renderer):
        # docstring inherited
        if not self.get_visible():
            return

        renderer.open_group('legend', gid=self.get_gid())

        fontsize = renderer.points_to_pixels(self._fontsize)

        # if mode == fill, set the width of the legend_box to the
        # width of the parent (minus pads)
        if self._mode in ["expand"]:
            pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
            self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)

        # update the location and size of the legend. This needs to
        # be done in any case to clip the figure right.
        bbox = self._legend_box.get_window_extent(renderer)
        self.legendPatch.set_bounds(bbox.x0, bbox.y0, bbox.width, bbox.height)
        self.legendPatch.set_mutation_scale(fontsize)

        if self.shadow:
            Shadow(self.legendPatch, 2, -2).draw(renderer)

        self.legendPatch.draw(renderer)
        self._legend_box.draw(renderer)

        renderer.close_group('legend')
        self.stale = False

    # _default_handler_map defines the default mapping between plot
    # elements and the legend handlers.

    _default_handler_map = {
        StemContainer: legend_handler.HandlerStem(),
        ErrorbarContainer: legend_handler.HandlerErrorbar(),
        Line2D: legend_handler.HandlerLine2D(),
        Patch: legend_handler.HandlerPatch(),
        LineCollection: legend_handler.HandlerLineCollection(),
        RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
        CircleCollection: legend_handler.HandlerCircleCollection(),
        BarContainer: legend_handler.HandlerPatch(
            update_func=legend_handler.update_from_first_child),
        tuple: legend_handler.HandlerTuple(),
        PathCollection: legend_handler.HandlerPathCollection(),
        PolyCollection: legend_handler.HandlerPolyCollection()
        }

    # (get|set|update)_default_handler_maps are public interfaces to
    # modify the default handler map.

    @classmethod
    def get_default_handler_map(cls):
        """
        A class method that returns the default handler map.
        """
        return cls._default_handler_map

    @classmethod
    def set_default_handler_map(cls, handler_map):
        """
        A class method to set the default handler map.
        """
        cls._default_handler_map = handler_map

    @classmethod
    def update_default_handler_map(cls, handler_map):
        """
        A class method to update the default handler map.
        """
        cls._default_handler_map.update(handler_map)

    def get_legend_handler_map(self):
        """
        Return the handler map.
        """

        default_handler_map = self.get_default_handler_map()

        if self._custom_handler_map:
            hm = default_handler_map.copy()
            hm.update(self._custom_handler_map)
            return hm
        else:
            return default_handler_map

    @staticmethod
    def get_legend_handler(legend_handler_map, orig_handle):
        """
        Return a legend handler from *legend_handler_map* that
        corresponds to *orig_handler*.

        *legend_handler_map* should be a dictionary object (that is
        returned by the get_legend_handler_map method).

        It first checks if the *orig_handle* itself is a key in the
        *legend_handler_map* and return the associated value.
        Otherwise, it checks for each of the classes in its
        method-resolution-order. If no matching key is found, it
        returns ``None``.
        """
        try:
            return legend_handler_map[orig_handle]
        except (TypeError, KeyError):  # TypeError if unhashable.
            pass
        for handle_type in type(orig_handle).mro():
            try:
                return legend_handler_map[handle_type]
            except KeyError:
                pass
        return None

    def _init_legend_box(self, handles, labels, markerfirst=True):
        """
        Initialize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self._fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.

        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances
        handles_and_labels = []

        label_prop = dict(verticalalignment='baseline',
                          horizontalalignment='left',
                          fontproperties=self.prop,
                          )

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        descent = 0.35 * fontsize * (self.handleheight - 0.7)
        # 0.35 and 0.7 are just heuristic numbers and may need to be improved.
        height = fontsize * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates should
        # be given in the display coordinates.

        # The transformation of each handle will be automatically set
        # to self.get_transform(). If the artist does not use its
        # default transform (e.g., Collections), you need to
        # manually set their transform to the self.get_transform().
        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, lab in zip(handles, labels):
            handler = self.get_legend_handler(legend_handler_map, orig_handle)
            if handler is None:
                cbook._warn_external(
                    "Legend does not support {!r} instances.\nA proxy artist "
                    "may be used instead.\nSee: "
                    "https://matplotlib.org/users/legend_guide.html"
                    "#creating-artists-specifically-for-adding-to-the-legend-"
                    "aka-proxy-artists".format(orig_handle))
                # We don't have a handle for this artist, so we just defer
                # to None.
                handle_list.append(None)
            else:
                textbox = TextArea(lab, textprops=label_prop,
                                   multilinebaseline=True,
                                   minimumdescent=True)
                handlebox = DrawingArea(width=self.handlelength * fontsize,
                                        height=height,
                                        xdescent=0., ydescent=descent)

                text_list.append(textbox._text)
                # Create the artist for the legend which represents the
                # original artist/handle.
                handle_list.append(handler.legend_artist(self, orig_handle,
                                                         fontsize, handlebox))
                handles_and_labels.append((handlebox, textbox))

        if handles_and_labels:
            # We calculate number of rows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaining
            # (num_smallcol) columns will have (nrows) rows.
            ncol = min(self._ncol, len(handles_and_labels))
            nrows, num_largecol = divmod(len(handles_and_labels), ncol)
            num_smallcol = ncol - num_largecol
            # starting index of each column and number of rows in it.
            rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol
            start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]])
            cols = zip(start_idxs, rows_per_col)
        else:
            cols = []

        columnbox = []
        for i0, di in cols:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [HPacker(pad=0,
                                 sep=self.handletextpad * fontsize,
                                 children=[h, t] if markerfirst else [t, h],
                                 align="baseline")
                         for h, t in handles_and_labels[i0:i0 + di]]
            # minimumdescent=False for the text of the last row of the column
            if markerfirst:
                itemBoxes[-1].get_children()[1].set_minimumdescent(False)
            else:
                itemBoxes[-1].get_children()[0].set_minimumdescent(False)

            # pack columnBox
            alignment = "baseline" if markerfirst else "right"
            columnbox.append(VPacker(pad=0,
                                     sep=self.labelspacing * fontsize,
                                     align=alignment,
                                     children=itemBoxes))

        mode = "expand" if self._mode == "expand" else "fixed"
        sep = self.columnspacing * fontsize
        self._legend_handle_box = HPacker(pad=0,
                                          sep=sep, align="baseline",
                                          mode=mode,
                                          children=columnbox)
        self._legend_title_box = TextArea("")
        self._legend_box = VPacker(pad=self.borderpad * fontsize,
                                   sep=self.labelspacing * fontsize,
                                   align="center",
                                   children=[self._legend_title_box,
                                             self._legend_handle_box])
        self._legend_box.set_figure(self.figure)
        self.texts = text_list
        self.legendHandles = handle_list

    def _auto_legend_data(self):
        """
        Return display coordinates for hit testing for "best" positioning.

        Returns
        -------
        bboxes
            List of bounding boxes of all patches.
        lines
            List of `.Path` corresponding to each line.
        offsets
            List of (x, y) offsets of all collection.
        """
        assert self.isaxes  # always holds, as this is only called internally
        ax = self.parent
        lines = [line.get_transform().transform_path(line.get_path())
                 for line in ax.lines]
        bboxes = [patch.get_bbox().transformed(patch.get_data_transform())
                  if isinstance(patch, Rectangle) else
                  patch.get_path().get_extents(patch.get_transform())
                  for patch in ax.patches]
        offsets = []
        for handle in ax.collections:
            _, transOffset, hoffsets, _ = handle._prepare_points()
            for offset in transOffset.transform(hoffsets):
                offsets.append(offset)
        return bboxes, lines, offsets

    def get_children(self):
        # docstring inherited
        return [self._legend_box, self.get_frame()]

    def get_frame(self):
        """Return the `~.patches.Rectangle` used to frame the legend."""
        return self.legendPatch

    def get_lines(self):
        r"""Return the list of `~.lines.Line2D`\s in the legend."""
        return [h for h in self.legendHandles if isinstance(h, Line2D)]

    def get_patches(self):
        r"""Return the list of `~.patches.Patch`\s in the legend."""
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)])

    def get_texts(self):
        r"""Return the list of `~.text.Text`\s in the legend."""
        return silent_list('Text', self.texts)

    def set_title(self, title, prop=None):
        """
        Set the legend title. Fontproperties can be optionally set
        with *prop* parameter.
        """
        self._legend_title_box._text.set_text(title)
        if title:
            self._legend_title_box._text.set_visible(True)
            self._legend_title_box.set_visible(True)
        else:
            self._legend_title_box._text.set_visible(False)
            self._legend_title_box.set_visible(False)

        if prop is not None:
            self._legend_title_box._text.set_fontproperties(prop)

        self.stale = True

    def get_title(self):
        """Return the `.Text` instance for the legend title."""
        return self._legend_title_box._text

    def get_window_extent(self, renderer=None):
        # docstring inherited
        if renderer is None:
            renderer = self.figure._cachedRenderer
        return self._legend_box.get_window_extent(renderer=renderer)

    def get_tightbbox(self, renderer):
        """
        Like `.Legend.get_window_extent`, but uses the box for the legend.

        Parameters
        ----------
        renderer : `.RendererBase` subclass
            renderer that will be used to draw the figures (i.e.
            ``fig.canvas.get_renderer()``)

        Returns
        -------
        `.BboxBase`
            The bounding box in figure pixel coordinates.
        """
        return self._legend_box.get_window_extent(renderer)

    def get_frame_on(self):
        """Get whether the legend box patch is drawn."""
        return self.legendPatch.get_visible()

    def set_frame_on(self, b):
        """
        Set whether the legend box patch is drawn.

        Parameters
        ----------
        b : bool
        """
        self.legendPatch.set_visible(b)
        self.stale = True

    draw_frame = set_frame_on  # Backcompat alias.

    def get_bbox_to_anchor(self):
        """Return the bbox that the legend will be anchored to."""
        if self._bbox_to_anchor is None:
            return self.parent.bbox
        else:
            return self._bbox_to_anchor

    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        Set the bbox that the legend will be anchored to.

        *bbox* can be

        - A `.BboxBase` instance
        - A tuple of ``(left, bottom, width, height)`` in the given transform
          (normalized axes coordinate if None)
        - A tuple of ``(left, bottom)`` where the width and height will be
          assumed to be zero.
        """
        if bbox is None:
            self._bbox_to_anchor = None
            return
        elif isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError as err:
                raise ValueError("Invalid argument for bbox : %s" %
                                 str(bbox)) from err

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        if transform is None:
            transform = BboxTransformTo(self.parent.bbox)

        self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
                                               transform)
        self.stale = True

    def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
        """
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x, y) coordinate of the bbox.

        - loc: a location code in range(1, 11).
          This corresponds to the possible values for self._loc, excluding
          "best".

        - bbox: bbox to be placed, display coordinate units.
        - parentbbox: a parent box which will contain the bbox. In
            display coordinates.
        """
        assert loc in range(1, 11)  # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)

        anchor_coefs = {UR: "NE",
                        UL: "NW",
                        LL: "SW",
                        LR: "SE",
                        R: "E",
                        CL: "W",
                        CR: "E",
                        LC: "S",
                        UC: "N",
                        C: "C"}

        c = anchor_coefs[loc]

        fontsize = renderer.points_to_pixels(self._fontsize)
        container = parentbbox.padded(-self.borderaxespad * fontsize)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0

    def _find_best_position(self, width, height, renderer, consider=None):
        """
        Determine the best location to place the legend.

        *consider* is a list of ``(x, y)`` pairs to consider as a potential
        lower-left corner of the legend. All are display coords.
        """
        assert self.isaxes  # always holds, as this is only called internally

        start_time = time.perf_counter()

        bboxes, lines, offsets = self._auto_legend_data()

        bbox = Bbox.from_bounds(0, 0, width, height)
        if consider is None:
            consider = [self._get_anchored_bbox(x, bbox,
                                                self.get_bbox_to_anchor(),
                                                renderer)
                        for x in range(1, len(self.codes))]

        candidates = []
        for idx, (l, b) in enumerate(consider):
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            # XXX TODO: If markers are present, it would be good to take them
            # into account when checking vertex overlaps in the next line.
            badness = (sum(legendBox.count_contains(line.vertices)
                           for line in lines)
                       + legendBox.count_contains(offsets)
                       + legendBox.count_overlaps(bboxes)
                       + sum(line.intersects_bbox(legendBox, filled=False)
                             for line in lines))
            if badness == 0:
                return l, b
            # Include the index to favor lower codes in case of a tie.
            candidates.append((badness, idx, (l, b)))

        _, _, (l, b) = min(candidates)

        if self._loc_used_default and time.perf_counter() - start_time > 1:
            cbook._warn_external(
                'Creating legend with loc="best" can be slow with large '
                'amounts of data.')

        return l, b

    def contains(self, event):
        inside, info = self._default_contains(event)
        if inside is not None:
            return inside, info
        return self.legendPatch.contains(event)

    def set_draggable(self, state, use_blit=False, update='loc'):
        """
        Enable or disable mouse dragging support of the legend.

        Parameters
        ----------
        state : bool
            Whether mouse dragging is enabled.
        use_blit : bool, optional
            Use blitting for faster image composition. For details see
            :ref:`func-animation`.
        update : {'loc', 'bbox'}, optional
            The legend parameter to be changed when dragged:

            - 'loc': update the *loc* parameter of the legend
            - 'bbox': update the *bbox_to_anchor* parameter of the legend

        Returns
        -------
        If *state* is ``True`` this returns the `~.DraggableLegend` helper
        instance. Otherwise this returns ``None``.
        """
        if state:
            if self._draggable is None:
                self._draggable = DraggableLegend(self,
                                                  use_blit,
                                                  update=update)
        else:
            if self._draggable is not None:
                self._draggable.disconnect()
            self._draggable = None
        return self._draggable

    def get_draggable(self):
        """Return ``True`` if the legend is draggable, ``False`` otherwise."""
        return self._draggable is not None
Example #35
0
                 s=100)
p5 = plt.scatter(V_14,
                 E_14,
                 color='grey',
                 marker="^",
                 facecolors='none',
                 label='Calcite II',
                 s=100)

#p7 = plt.scatter(V_7, E_7, color='magenta', marker="^", facecolors='none', label='S.G. 7', s=100)

#p8 = plt.scatter(V_161, E_161, color='green', marker="^", facecolors='none', label='S.G. 161', s=100)

fontP = FontProperties()
#fontP.set_size('small')
fontP.set_size('15')

#plt.legend((p1, p2, p5, p6, p8, p161), ("Calcite I", "Cubic fit Calcite I", "Calcite II", 'Cubic fit Calcite II', "S.G. 161", "Cubic fit S.G. 161"), prop=fontP)
plt.legend(
    (p1, p2, p5, p6),
    ("Calcite I", "Cubic fit Calcite I", "Calcite II", 'Cubic fit Calcite II'),
    prop=fontP)

global V0, B0, B0_prime
E0 = popt_C_I[0]
V0 = popt_C_I[1]
B0 = popt_C_I[2]
B0_prime = popt_C_I[3]

pressures_per_F_unit_C_I = P(V_C_I, V0, B0, B0_prime)
print 'popt_C_I = ', popt_C_I
Example #36
0
import functools as ft
import numpy as np
from math import sqrt, pi
import matplotlib as mpl

mpl.rcParams['axes.labelsize'] = 'x-large'
mpl.rcParams['legend.fontsize'] = 'x-large'
mpl.rcParams['xtick.labelsize'] = 'x-large'
mpl.rcParams['ytick.labelsize'] = 'x-large'

output_dir = './plots/'
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('small')


def save_pic(renderer, fig, p, suffix):
    fh = renderer._get_figure(fig)
    plt.tight_layout()
    # tikz_save(f'{output_dir}/heatRate_{suffix}.tex', figureheight='\\figureheight', figurewidth='\\figurewidth')
    plt.savefig(f'{output_dir}/heatRate_{suffix}.eps')


def analytical_sol_xv(renderer, fig, p):

    save_pic(renderer, fig, p, 'icrm_traj')


def analytical_sol_u(renderer, fig, p):
Example #37
0
def plot_gat_duration_error(data_dict,
                            astar_data,
                            action_durations,
                            title="",
                            log10=True):
    markers = itertools.cycle(plot_markers)
    linestyles = itertools.cycle(plot_linestyles)

    handles = []
    astar_gat_per_duration = astar_data
    if not astar_gat_per_duration:  # empty
        print("No data for A*")
    # astar_gat_per_duration_means, astar_confidence_interval_low, astar_confidence_interval_high = \
    #     mean_confidence_intervals(astar_gat_per_duration)
    x = np.arange(1, len(action_durations) + 1)

    fig = plt.figure()
    ax = plt.subplot()
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.tick_params(direction='out')
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    # Plot for each provided algorithm
    color_index = 0
    for algorithm, algorithm_gat_per_duration in data_dict.items():
        if not algorithm_gat_per_duration:  # empty
            print("No data for " + algorithm)
            continue
        # print(algorithm_gat_per_duration)
        # if log10:
        #     algorithm_gat_per_duration = [np.log10(gat) for gat in algorithm_gat_per_duration]
        algorithm_gat_per_duration_mean, algorithm_confidence_interval_low, algorithm_confidence_interval_high = \
            mean_confidence_intervals(algorithm_gat_per_duration)
        data_mask = np.isfinite(algorithm_gat_per_duration_mean)

        masked_x = x[data_mask]
        masked_data = np.array(algorithm_gat_per_duration_mean)[data_mask]
        masked_confidence_low = algorithm_confidence_interval_low[data_mask]
        masked_confidence_high = algorithm_confidence_interval_high[data_mask]
        label = translate_algorithm_name(algorithm)

        handle = plt.errorbar(masked_x,
                              masked_data,
                              label=label,
                              color=tableau20[color_index],
                              markeredgecolor='none',
                              linestyle=next(linestyles),
                              marker=next(markers),
                              clip_on=False,
                              yerr=(masked_confidence_low,
                                    masked_confidence_high))
        handles.append((handle, label, masked_data.tolist()))
        color_index += 1

    # Set labels, sort legend by mean value
    handles = sorted(handles, key=lambda handle: handle[2], reverse=True)
    ordered_handles = [a[0] for a in handles]
    ordered_labels = [a[1] for a in handles]
    font_properties = FontProperties()
    font_properties.set_size('small')
    lgd = plt.legend(
        handles=ordered_handles,
        labels=ordered_labels,
        prop=font_properties,
        ncol=2,
        frameon=False,
        # loc="upper center",bbox_to_anchor=(0.5, -0.1)
        loc='best')
    plt.xticks(x, [
        duration if duration - int(duration) > 0 else int(duration)
        for duration in action_durations
    ])
    plt.title(title)
    if log10:
        plt.yscale('symlog', basey=10)
        # plt.yscale('log', basey=10, nonposy='clip')
        plt.ylabel("Goal Achievement Time log10")
    else:
        plt.ylabel("Goal Achievement Time (ms)")
    plt.xlabel("Action Duration (ms)")
    ax.autoscale(tight=True)

    plt.gcf().tight_layout()

    return lgd
Example #38
0
def plot_clusters(num_clusters,
                  feature_matrix,
                  cluster_data,
                  book_data,
                  plot_size=(16, 8)):
    # generate random color for clusters
    def generate_random_color():
        color = '#%06x' % random.randint(0, 0xFFFFFF)
        return color

    # define markers for clusters
    markers = ['o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd']
    # build cosine distance matrix
    cosine_distance = 1 - cosine_similarity(feature_matrix)
    # dimensionality reduction using MDS
    mds = MDS(n_components=2, dissimilarity="precomputed", random_state=1)
    # get coordinates of clusters in new low-dimensional space
    plot_positions = mds.fit_transform(cosine_distance)
    x_pos, y_pos = plot_positions[:, 0], plot_positions[:, 1]
    # build cluster plotting data
    cluster_color_map = {}
    cluster_name_map = {}
    for cluster_num, cluster_details in cluster_data[:].items():
        # assign cluster features to unique label
        cluster_color_map[cluster_num] = generate_random_color()
        cluster_name_map[cluster_num] = ', '.join(
            cluster_details['key_features'][:5]).strip()
    # map each unique cluster label with its coordinates and books
    cluster_plot_frame = pd.DataFrame({
        'x':
        x_pos,
        'y':
        y_pos,
        'label':
        book_data['Cluster'].values.tolist(),
        'title':
        book_data['title'].values.tolist()
    })
    grouped_plot_frame = cluster_plot_frame.groupby('label')
    # set plot figure size and axes
    fig, ax = plt.subplots(figsize=plot_size)
    ax.margins(0.05)
    # plot each cluster using co-ordinates and book titles
    for cluster_num, cluster_frame in grouped_plot_frame:
        marker = markers[cluster_num] if cluster_num < len(markers) \
            else np.random.choice(markers, size=1)[0]
        ax.plot(cluster_frame['x'],
                cluster_frame['y'],
                marker=marker,
                linestyle='',
                ms=12,
                label=cluster_name_map[cluster_num],
                color=cluster_color_map[cluster_num],
                mec='none')
        ax.set_aspect('auto')
        ax.tick_params(axis='x',
                       which='both',
                       bottom='off',
                       top='off',
                       labelbottom='off')
        ax.tick_params(axis='y',
                       which='both',
                       left='off',
                       top='off',
                       labelleft='off')
    fontP = FontProperties()
    fontP.set_size('small')
    ax.legend(loc='upper center',
              bbox_to_anchor=(0.5, -0.01),
              fancybox=True,
              shadow=True,
              ncol=5,
              numpoints=1,
              prop=fontP)
    # add labels as the film titles
    for index in range(len(cluster_plot_frame)):
        ax.text(cluster_plot_frame.ix[index]['x'],
                cluster_plot_frame.ix[index]['y'],
                cluster_plot_frame.ix[index]['title'],
                size=8)
        # show the plot
    plt.show()
map2.drawcoastlines()
map2.drawlsmask(ocean_color="aqua")

# For each group the obtained by grouping the dataset by Cities, one city (the first occurrence),
# is selected to represent the city and it is plotted to have a reference of the precise location
# of this city and compare the result with the clustering algorithm
for i, cluster_row in sorted_cities.iterrows():
    rgb = [rd.random(), rd.random(), rd.random()]
    clusteri = df[df.City == cluster_row['City']]
    reference = clusteri.iloc[0]
    x, y = map2(reference['Longitude'], reference['Latitude'])
    map2.plot(x,
              y,
              marker='o',
              markersize=10,
              label=reference['City'],
              color=rgb)

fontP = FontProperties()
fontP.set_size('xx-small')
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1), prop=fontP)
plt.show()
# %%
# As can be inspected, 10 out of 20 of the total clusters match, that is, a 50%.
# There are some cases in which to cities are merged in one cluster, that is the case of San Diego
# and Los Angeles or Columbia and Atlanta. This happen because this cities are closed to each other
# and the zip codes are located uniformly throughout the cities.
# On the other hand, large cities may have the zip codes sparsely located and they are not correctly
# clustered.
# %%
Example #40
0
class AnchoredOffsetbox(OffsetBox):
    """
    An offset box placed according to the legend location
    loc. AnchoredOffsetbox has a single child. When multiple children
    is needed, use other OffsetBox class to enlose them.  By default,
    the offset box is anchored against its parent axes. You may
    explicitly specify the bbox_to_anchor.
    """

    zorder = 5  # zorder of the legend

    def __init__(self,
                 loc,
                 pad=0.4,
                 borderpad=0.5,
                 child=None,
                 prop=None,
                 frameon=True,
                 bbox_to_anchor=None,
                 bbox_transform=None,
                 **kwargs):
        """
        loc is a string or an integer specifying the legend location.
        The valid  location codes are::

        '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,

        pad : pad around the child for drawing a frame. given in
          fraction of fontsize.

        borderpad : pad between offsetbox frame and the bbox_to_anchor,

        child : OffsetBox instance that will be anchored.

        prop : font property. This is only used as a reference for paddings.

        frameon : draw a frame box if True.

        bbox_to_anchor : bbox to anchor. Use self.axes.bbox if None.

        bbox_transform : with which the bbox_to_anchor will be transformed.

        """

        super(AnchoredOffsetbox, self).__init__(**kwargs)

        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
        self.set_child(child)

        self.loc = loc
        self.borderpad = borderpad
        self.pad = pad

        if prop is None:
            self.prop = FontProperties(size=rcParams["legend.fontsize"])
        elif isinstance(prop, dict):
            self.prop = FontProperties(**prop)
            if "size" not in prop:
                self.prop.set_size(rcParams["legend.fontsize"])
        else:
            self.prop = prop

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0),
            width=1.,
            height=1.,
            facecolor='w',
            edgecolor='k',
            mutation_scale=self.prop.get_size_in_points(),
            snap=True)
        self.patch.set_boxstyle("square", pad=0)
        self._drawFrame = frameon

    def set_child(self, child):
        "set the child to be anchored"
        self._child = child

    def get_child(self):
        "return the child"
        return self._child

    def get_children(self):
        "return the list of children"
        return [self._child]

    def get_extent(self, renderer):
        """
        return the extent of the artist. The extent of the child
        added with the pad is returned
        """
        w, h, xd, yd = self.get_child().get_extent(renderer)
        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        pad = self.pad * fontsize

        return w + 2 * pad, h + 2 * pad, xd + pad, yd + pad

    def get_bbox_to_anchor(self):
        """
        return the bbox that the legend will be anchored
        """
        if self._bbox_to_anchor is None:
            return self.axes.bbox
        else:
            transform = self._bbox_to_anchor_transform
            if transform is None:
                return self._bbox_to_anchor
            else:
                return TransformedBbox(self._bbox_to_anchor, transform)

    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        set the bbox that the child will be anchored.

        *bbox* can be a Bbox instance, a list of [left, bottom, width,
        height], or a list of [left, bottom] where the width and
        height will be assumed to be zero. The bbox will be
        transformed to display coordinate by the given transform.
        """
        if bbox is None or isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError:
                raise ValueError("Invalid argument for bbox : %s" % str(bbox))

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        self._bbox_to_anchor_transform = transform

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        self._update_offset_func(renderer)
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset(w, h, xd, yd, renderer)
        return Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def _update_offset_func(self, renderer, fontsize=None):
        """
        Update the offset func which depends on the dpi of the
        renderer (because of the padding).
        """
        if fontsize is None:
            fontsize = renderer.points_to_pixels(
                self.prop.get_size_in_points())

        def _offset(w, h, xd, yd, renderer, fontsize=fontsize, self=self):
            bbox = Bbox.from_bounds(0, 0, w, h)
            borderpad = self.borderpad * fontsize
            bbox_to_anchor = self.get_bbox_to_anchor()

            x0, y0 = self._get_anchored_bbox(self.loc, bbox, bbox_to_anchor,
                                             borderpad)
            return x0 + xd, y0 + yd

        self.set_offset(_offset)

    def update_frame(self, bbox, fontsize=None):
        self.patch.set_bounds(bbox.x0, bbox.y0, bbox.width, bbox.height)

        if fontsize:
            self.patch.set_mutation_scale(fontsize)

    def draw(self, renderer):
        "draw the artist"

        if not self.get_visible(): return

        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        self._update_offset_func(renderer, fontsize)

        if self._drawFrame:
            # update the location and size of the legend
            bbox = self.get_window_extent(renderer)
            self.update_frame(bbox, fontsize)
            self.patch.draw(renderer)

        width, height, xdescent, ydescent = self.get_extent(renderer)

        px, py = self.get_offset(width, height, xdescent, ydescent, renderer)

        self.get_child().set_offset((px, py))
        self.get_child().draw(renderer)

    def _get_anchored_bbox(self, loc, bbox, parentbbox, borderpad):
        """
        return the position of the bbox anchored at the parentbbox
        with the loc code, with the borderpad.
        """
        assert loc in range(1, 11)  # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)

        anchor_coefs = {
            UR: "NE",
            UL: "NW",
            LL: "SW",
            LR: "SE",
            R: "E",
            CL: "W",
            CR: "E",
            LC: "S",
            UC: "N",
            C: "C"
        }

        c = anchor_coefs[loc]

        container = parentbbox.padded(-borderpad)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0
Example #41
0
class AnimatedSpins(object):
    def __init__(self, l, J, B, Ramp,
                 simul_step):  #, spins, singweight, spinup, simul_step):
        """
        Class for Ising 2D lattice animation
        constructor takes as arguments                                                              
        -- l: the lattice size                                                        
        -- J: coupling constant
        -- B: field
        -- Ramp: speed at which J is increased/decreased
        -- simul_step: routine which performs the update
        """
        self.l = l
        self.J = J
        self.B = B
        self.Ramp = Ramp
        self.spins = np.ones((self.l, self.l), dtype=int)
        self.spins[0, 0] = -1
        self.singweight = np.exp(-2 * self.J * np.arange(-4, 5, 2))
        self.spinup = np.exp(-2 * self.B * np.arange(-1, 2, 2))
        self.xdata = [J]
        self.MagPoint = np.sum(self.spins) / (self.l)**2
        self.ydata = [self.MagPoint]
        self.iter = 0
        self.suspend = False

        self.stream = self.data_stream()
        self.simul_step = simul_step
        self.fig, self.ax = plt.subplots(figsize=(10, 10))
        plt.axis('off')
        self.gs = gridspec.GridSpec(2,
                                    2,
                                    width_ratios=[1, 25],
                                    height_ratios=[2, 1])
        self.font = FontProperties()
        self.font.set_size(20)
        self.ax1 = self.fig.add_subplot(self.gs[0])
        self.ax1.set_ylim(-1.0, 1.0)
        self.ax1.tick_params(axis='x',
                             which='both',
                             bottom='off',
                             top='off',
                             labelbottom='off')
        self.ax2 = self.fig.add_subplot(self.gs[1])
        self.ax2.set_axis_off()
        self.ax3 = self.fig.add_subplot(self.gs[3])
        self.ax3.set_ylim(-1.0, 1.0)
        self.ax3.set_xlim(0.0, 1.0)
        self.ax3.set_xlabel('J', fontproperties=self.font)
        self.ax3.set_ylabel('<s>', fontproperties=self.font)
        self.ax3.axhline(color='red')
        self.ax3.axvline(x=0.44, color='red')
        self.line, = self.ax3.plot(self.xdata, self.ydata, lw=2)
        plt.subplots_adjust(left=0.05, bottom=0.30)
        axcolor = 'lightgoldenrodyellow'
        self.axg = plt.axes([0.15, 0.05, 0.65, 0.03])  #, axisbg=axcolor)
        self.axt = plt.axes([0.15, 0.10, 0.65, 0.03])  #, axisbg=axcolor)
        self.axr = plt.axes([0.15, 0.15, 0.65, 0.03])  #, axisbg=axcolor)
        self.axl = plt.axes([0.15, 0.20, 0.65, 0.03])  #, axisbg=axcolor)
        self.Jslider = Slider(self.axg, 'J', 0.1, 1.0, valinit=0.3)
        self.Bslider = Slider(self.axt, 'B', -0.5, 0.5, valinit=0.0)
        self.Rslider = Slider(self.axr,
                              'Ramp',
                              -0.01,
                              0.01,
                              valinit=0.0,
                              valfmt=u'%1.5f')
        self.Lslider = Slider(self.axl,
                              'L',
                              1,
                              200,
                              valinit=self.l,
                              valfmt=u'%3.0f')
        self.im1 = self.ax1.add_patch(patches.Rectangle(
            (0.0, 0.0),
            1.0,
            0.0,
        ))
        self.im1.set_height(0.0)
        self.im2 = self.ax2.imshow(0.5 * (self.spins + 1),
                                   cmap='YlGn',
                                   interpolation='nearest')
        self.ani = animation.FuncAnimation(self.fig,
                                           self.display,
                                           self.simul_step(
                                               self.l, self.spins,
                                               self.singweight, self.spinup),
                                           interval=40)
        self.Jslider.on_changed(self.update)
        self.Bslider.on_changed(self.update)
        self.Rslider.on_changed(self.update)
        self.Lslider.on_changed(self.update)
        self.rar = plt.axes([0.78, 0.75, 0.15, 0.15])  #, axisbg=axcolor)
        self.radio_reset = RadioButtons(self.rar, ('$T=0$', '$T=\infty$'))
        self.radio_reset.on_clicked(self.reset_spins)
        self.susb = plt.axes([0.78, 0.65, 0.15, 0.05])  #, axisbg=axcolor)
        self.suspend_button = Button(self.susb,
                                     "Click to suspend",
                                     color=axcolor,
                                     hovercolor='white')
        self.suspend_button.on_clicked(self.suspend_MC)
        self.resb = plt.axes([0.78, 0.55, 0.15, 0.05])  #, axisbg=axcolor)
        self.reset_mag_button = Button(self.resb,
                                       "Clear mag plot",
                                       color=axcolor,
                                       hovercolor='white')
        self.reset_mag_button.on_clicked(self.reset_magplot)

    def update(self, val):
        """ This function is called whenever a slider has been changed """
        self.J = self.Jslider.val
        self.B = self.Bslider.val
        self.Ramp = self.Rslider.val
        self.singweight = np.exp(-2 * self.J * np.arange(-4, 5, 2))
        self.spinup = np.exp(-2 * self.B * np.arange(-1, 2, 2))
        OldL = self.l
        self.l = np.int(self.Lslider.val / 2)
        self.l = self.l * 2
        if OldL != self.l:
            self.reset_spins("T=0")
        self.fig.canvas.draw()
        self.Switch = True

    def reset_spins(self, label):
        """ Resets the spin to either the T=0 (ordered) or T=infty (disordered) configuration """
        if label == '$T=0$':
            self.spins = np.ones((self.l, self.l), dtype=int)
        else:
            self.spins = rand.random_integers(0, 1, (self.l, self.l))
            self.spins = 2 * self.spins - 1

    def suspend_MC(self, label):
        """ MC simulation is suspended / resumed """
        self.suspend = not (self.suspend)
        if self.suspend:
            self.suspend_button.label.set_text('Click to resume')
        else:
            self.suspend_button.label.set_text('Click to suspend')

    def reset_magplot(self, label):
        """ Resets the plot of the magnetization """
        self.xdata = []
        self.ydata = []

    def data_stream(self):
        """ 
           Calls spin update routine, copies it to the relevant section of the 'data' array which 
           is then yielded
        """
        self.spins = self.simul_step(self.l, self.spins, self.singweight,
                                     self.spinup)
        data = self.spins
        while True:
            if not (self.suspend):
                if (self.Ramp != 0):
                    self.J = self.J + self.Ramp
                    self.J = np.minimum(self.J, MaxJ)
                    self.J = np.maximum(self.J, MinJ)
                    self.singweight = np.exp(-2 * self.J * np.arange(-4, 5, 2))
                    self.spinup = np.exp(-2 * self.B * np.arange(-1, 2, 2))
                self.spins = self.simul_step(self.l, self.spins,
                                             self.singweight, self.spinup)
            data = self.spins
            yield data

    def display(
        self, i
    ):  # , simul_step, l, spins, J, B, Ramp, singweight, spinup, xdata, ydata):
        """ function called by FuncAnimation. Plots all graphs """

        if (self.iter % 10) == 0:
            self.Jslider.set_val(self.J)
        self.iter = self.iter + 1
        data = next(self.stream)
        self.im2.set_data((data + 1) / 2)
        self.im1.set_height(np.sum(data) / (self.l)**2)
        self.MagPoint = np.sum(data) / (self.l)**2
        self.xdata.append(self.J)
        self.ydata.append(self.MagPoint)
        self.line.set_data(self.xdata, self.ydata)
        plt.draw()
        return self.im1, self.im2, self.line, self.xdata, self.ydata

    def show(self):
        plt.show()
Example #42
0
from __future__ import division, print_function
import sys, os, re, matplotlib
import numpy as np
import matplotlib.pyplot as plt
import numericalunits, colors

matplotlib.rcParams['text.usetex'] = True

from matplotlib.font_manager import FontProperties

small_font = FontProperties()
small_font.set_size('small')

matplotlib.rcParams['text.usetex'] = True
matplotlib.rc('font', family='serif')
"""
Create deliverable capacity and density plots from NIST Thermophysical fluid
data generated with isothermal-save-gas-csv.py using Python 3

Copyright (c) 2019 - 2020 Jordan K. Pommerenck

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Example #43
0
def test_plots2pdf(chnf,figNo,subplotNo,outfilename,pp,primaryAxisChs,secondaryAxisChs,layout,Primary2Ylabel):
    # # this function is called for each OUT file, for each PDF

    #if wanting to save iamges, check image outputs directory exists, and create if not:
    # if SAVE_IMAGES and not os.path.exists(IMAGEDIR):
        # os.makedirs(IMAGEDIR)

    # # matplotlib general settings
    fontP = FontProperties()
    fontP.set_size('x-small') #will be used on legends
    font = {'size': 8}
    matplotlib.rc('font', **font) #set all matplotlib items to font size specified
    matplotlib.rcParams['axes.linewidth'] = 0.1

    # # extract channel file object data
    sh_ttl, ch_id, ch_data = chnf.get_data()
    sh_ttl, ch_id = chnf.get_id()
    ch_range = chnf.get_range()

    figNo2SubNo2Chs={}
    sNo = subplotNo #sNo starts from subplotNo
    fNo = figNo #fNo starts from figNo
    for i in range(1,len(primaryAxisChs)+1):
        if fNo not in figNo2SubNo2Chs.keys():
            figNo2SubNo2Chs[fNo]={}
        figNo2SubNo2Chs[fNo][sNo]=findChs(primaryAxisChs[i-1],ch_id)
        sNo = sNo+1
        if sNo > int(layout[0])*int(layout[1]):
            sNo = 1
            fNo = fNo+1
    # subplotNo=sNo
    # figNo=fNo
    numRow = int(layout[0])
    numCol = int(layout[1])
    k = 0
    for fNo in figNo2SubNo2Chs.keys():
        """matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
           fig_kw : Dict with keywords passed to the figure() call. Note that all keywords not recognized above will be automatically included here."""
        fig_kw = {'num': fNo}
        f, axarr = plt.subplots(figsize=(11.7,8.3), nrows=int(layout[0]),ncols=int(layout[1]), **fig_kw)
        f.suptitle(outfilename[:-4],fontsize = 10)
        for sNo in figNo2SubNo2Chs[fNo].keys():
            plt.subplot(int(layout+str(sNo)))
            for i in figNo2SubNo2Chs[fNo][sNo]:
                plt.plot(ch_data['time'], ch_data[i], label=ch_id[i])
                #plt.autoscale(enable=True, axis='both', tight=False)
                plt.autoscale(enable=True, axis='both', tight=False)
            # BP added following to reset ylim if abs(ymax-ymin)<0.01-------------------
            ymin, ymax = plt.ylim()
            if abs(ymax-ymin) < 0.01:
                yminnew = ymin-(0.01-abs(ymax-ymin))/2
                ymaxnew = ymax+(0.01-abs(ymax-ymin))/2
                plt.ylim(yminnew,ymaxnew)
            # --------------------------------------------------------------------------

            i = int(math.ceil(float(sNo)/float(numCol))) - 1 ######################
            j = ((sNo) % numCol) - 1
            if j < 0: #only true if nth subplot is at the end of a row
                j = numCol - 1

            ax = plt.subplot(int(layout[0]), int(layout[1]), int(layout[1]) * i + j + 1)
            ax.get_xaxis().get_major_formatter().set_useOffset(False)
            ax.get_yaxis().get_major_formatter().set_useOffset(False)

            #---------------------------------------------------------------------------
            #BP added follwoing, this code rely on numbering of output ch in dynamic sim
            #Plotting reactive current
            if secondaryAxisChs[k]=="Iq":
                #ch_data[1] = INV1_Voltage, ch_data[3] = INV1_Qelec
                num_UUT = 0
                num_UUT2 = 0
                chan_UUT_vol_id = 4
                chan_UUT_Q_id = 6
                # id_indx = 0
                # for id_val_1 in ch_id:
                    # if "UUT_Voltage" in str(ch_id[id_val_1]):
                        # num_UUT = num_UUT + 1
                        # if num_UUT == 1:
                            # chan_UUT_vol_id = idIndx
                    # if "UUT_Qelec" in str(ch_id[id_val_1]):
                        # num_UUT2 = num_UUT2 + 1
                        # if num_UUT2 == 1:
                            # chan_UUT_Q_id = idIndx
                    # id_indx = id_indx + 1
                Iq_Calc(outfilename,ch_data['time'],ch_data[chan_UUT_vol_id],ch_data[chan_UUT_Q_id])
            #---------------------------------------------------------------------------
            #---------------------------------------------------------------------------
            #BP added follwoing, this code rely on numbering of output ch in dynamic sim
            #Plotting reactive current
            if secondaryAxisChs[k]=="Ip":
                #ch_data[1] = INV1_Voltage, ch_data[3] = INV1_Qelec
                P_Recovery_Calc(outfilename,ch_data['time'],ch_data[2])
            #---------------------------------------------------------------------------

            # # try to plot on secondary axis
            ax2 = ax.twinx()
            ChsS=[]

            #---------------------------------------------------------------------------
            #BP added follwoing, this code rely on numbering of output ch in dynamic sim
            #Calculating rise time and settling time
            if secondaryAxisChs[k]=="Rise time and settling time calc":
                #ch_data[3] = INV1_Qelec
                rise_settle_TimeCalc(ch_data['time'],ch_data[6])
            #---------------------------------------------------------------------------

            elif secondaryAxisChs[k]!="":
                ChsS=findChs(secondaryAxisChs[k],ch_id)
                for ch in ChsS:
                    ax2.plot(ch_data['time'],ch_data[ch],':',label=ch_id[ch])
                    ax2.autoscale(enable=True, axis='x', tight=True)

            ax.grid(b=True, which='both', color='gray',linestyle=':')
            ax.set_xlim(xmin=round(ch_range['time']['min']),xmax=round(ch_range['time']['max']))
            primaryAxisChs[sNo-subplotNo] in Primary2Ylabel.keys()
            if primaryAxisChs[sNo-subplotNo] in Primary2Ylabel.keys():
                #if user has defined a specific y label for this set of primary axis content (e.g. VARS->Q)
                ax.set_ylabel(Primary2Ylabel[primaryAxisChs[k]])
            else:
                #otherwise set y label to primary axis content
                ax.set_ylabel(primaryAxisChs[k])
            # # Shrink current axis's height by 10% on the bottom
            box = axarr[i,j].get_position()
            ax.set_position([box.x0, box.y0 + box.height * 0.1,box.width, box.height * 0.9])
            # # Put a legend below current axis
            if int(matplotlib.__version__.split('.')[0]) >= 2:
                ax.legend(loc='center left', bbox_to_anchor=(0, -0.125), ncol=3, fontsize='x-small', frameon=False)
            else:
                ax.legend(loc='center left', bbox_to_anchor=(0, -0.125), ncol=3, prop=fontP, frameon=False)
            if ENABLE_TITLE:
                ax.set_title(primaryAxisChs[k])
            #secondary axis labelling
            if secondaryAxisChs[k] in Primary2Ylabel.keys():
                ax2.set_ylabel(Primary2Ylabel[secondaryAxisChs[k]])
            else:
                ax2.set_ylabel(secondaryAxisChs[k])
            if int(matplotlib.__version__.split('.')[0]) >= 2:
                ax2.legend(loc='center right', bbox_to_anchor=(1, -0.125), ncol=3, fontsize='x-small', frameon=False)
            else:
                ax2.legend(loc='center right', bbox_to_anchor=(1, -0.125), ncol=3, prop=fontP, frameon=False)
            k = k+1
        if sNo == int(layout[0])*int(layout[1]):
            plt.tight_layout(pad=5.0,w_pad=5.0, h_pad=7.0)
            plt.savefig(pp, format='pdf') #bbox_inches='tight' #TM: added 29/07/2016
            # if SAVE_IMAGES:
                # plt.savefig(IMAGEDIR+outfilename+'_'+str(fNo)+'.png')
                # print IMAGEDIR+outfilename+'_'+str(fNo)+'.png saved'
        plt.close(f)    # Added by BP to address python crashing issue experienced when plotting a large number of .out files
    sNo = sNo+1
    if sNo > int(layout[0])*int(layout[1]):
        sNo = 1
        fNo = fNo+1
    subplotNo=sNo
    figNo=fNo
    return figNo,subplotNo
Example #44
0
def make_line_plot(dir_path,
                   data_file_link,
                   background_color,
                   label_color,
                   xy_coords,
                   props,
                   x_len=8,
                   y_len=4,
                   draw_axes=False,
                   generate_eps=True):
    """ Write a line plot

    xy_coords: a dict of form {series_label:([x data], [y data], point_marker, color)}

    (code adapted from Micah Hamady's code)
    """
    rc('font', size='8')
    rc('axes', linewidth=.5, edgecolor=label_color)
    rc('axes', labelsize=8)
    rc('xtick', labelsize=8)
    rc('ytick', labelsize=8)
    fig = figure(figsize=(x_len, y_len))
    mtitle = props.get("title", "Groups")
    x_label = props.get("xlabel", "X")
    y_label = props.get("ylabel", "Y")

    title('%s' % mtitle, fontsize='10', color=label_color)
    xlabel(x_label, fontsize='8', color=label_color)
    ylabel(y_label, fontsize='8', color=label_color)

    sorted_keys = sorted(xy_coords.keys())
    labels = []
    for s_label in sorted_keys:
        s_data = xy_coords[s_label]
        c = s_data[3]
        m = s_data[2]
        plot(s_data[0],
             s_data[1],
             c=c,
             marker=m,
             label=s_label,
             linewidth=.1,
             ms=5,
             alpha=1.0)

    fp = FontProperties()
    fp.set_size('8')
    legend(prop=fp, loc=0)

    show()

    img_name = 'scree_plot.png'
    savefig(os.path.join(dir_path, img_name),
            dpi=80,
            facecolor=background_color)

    # Create zipped eps files
    eps_link = ""
    if generate_eps:
        eps_img_name = str('scree_plot.eps')
        savefig(os.path.join(dir_path, eps_img_name), format='eps')
        out, err, retcode = qiime_system_call(
            "gzip -f " + os.path.join(dir_path, eps_img_name))
        eps_link = DOWNLOAD_LINK % (
            (os.path.join(data_file_link, eps_img_name) + ".gz"),
            "Download Figure")

    return os.path.join(data_file_link, img_name), eps_link
Example #45
0
             fontsize=10)

    #plot actual outputs
    i = ps_inputs.index(alt)
    ax2[(i - (i % 2)) / 2, i % 2].plot(output[0], output[1], '-r')
    exp_x = np.arange(0.9 * min(IND_asses), 1.1 * max(IND_asses),
                      (max(IND_asses) - min(IND_asses)) / 50.)
    exp_y = fuzz.trapmf(
        exp_x,
        [min(IND_asses),
         min(IND_asses),
         max(IND_asses),
         max(IND_asses)])
    ax2[(i - (i % 2)) / 2, i % 2].plot(exp_x, exp_y, '-b')

ax1.set_ylim([0, 11])
ax1.set_xlim([0.6, 1.0])
ax1.yaxis.grid(True)
ax1.set_yticks(range(1, 11))
ax1.set_yticklabels([alt[0] for alt in ps_inputs])
ax1.set_xlabel('System Propulsive Efficiency')

fontP = FontProperties()
fontP.set_size('medium')
ax1.legend(['Fuzzy System Output', 'Expert System Evaluations'],
           bbox_to_anchor=(1.0, 1.06),
           prop=fontP)

plt.draw()
plt.show()
Example #46
0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style
from matplotlib.font_manager import FontProperties

plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0.
plt.rcParams['axes.ymargin'] = 0.

fontP = FontProperties()
fontP.set_size('smaller')

fig1, ax1 = plt.subplots()

yref = 25
ax2 = ax1.twinx()
x, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17 = np.loadtxt(
    '07july2017_chambdata.csv', unpack=True, delimiter=',', skiprows=1)
#ax1.plot(x,y1,label="101_Temp")
#ax1.plot(x,y2,label="102_Temp")
#ax1.plot(x,y3,label="103_Temp")
#ax1.plot(x,y4,label="104_Temp")
#ax1.plot(x,y5,label="105_Temp")
#ax1.plot(x,y6,label="106_Temp")
#ax1.plot(x,y7,label="107_Temp")
#ax1.plot(x,y8,label="108_Temp")
#ax1.plot(x,y9,label="109_Temp")
#ax1.plot(x,y10,label="110_Temp")
#ax1.plot(x,y11,label="111_Temp")
#ax1.plot(x,y12,label="112_Temp")
#ax1.plot(x,y13,label="113_Temp")
Example #47
0
class Legend(Artist):
    """
    Place a legend on the axes at location loc.  Labels are a
    sequence of strings and loc can be a string or an integer
    specifying the legend location

    The location codes are::

      'best'         : 0, (only implemented for axes legends)
      'upper right'  : 1,
      'upper left'   : 2,
      'lower left'   : 3,
      'lower right'  : 4,
      'right'        : 5, (same as 'center right', for back-compatibility)
      'center left'  : 6,
      'center right' : 7,
      'lower center' : 8,
      'upper center' : 9,
      'center'       : 10,

    loc can be a tuple of the normalized coordinate values with
    respect its parent.

    """
    codes = {
        'best': 0,  # only implemented for axes legends
        '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,
    }

    zorder = 5

    def __str__(self):
        return "Legend"

    def __init__(
        self,
        parent,
        handles,
        labels,
        loc=None,
        numpoints=None,  # the number of points in the legend line
        markerscale=None,  # the relative size of legend markers
        # vs. original
        markerfirst=True,  # controls ordering (left-to-right) of
        # legend marker and label
        scatterpoints=None,  # number of scatter points
        scatteryoffsets=None,
        prop=None,  # properties for the legend texts
        fontsize=None,  # keyword to set font size directly

        # spacing & pad defined as a fraction of the font-size
        borderpad=None,  # the whitespace inside the legend border
        labelspacing=None,  # the vertical space between the legend
        # entries
        handlelength=None,  # the length of the legend handles
        handleheight=None,  # the height of the legend handles
        handletextpad=None,  # the pad between the legend handle
        # and text
        borderaxespad=None,  # the pad between the axes and legend
        # border
        columnspacing=None,  # spacing between columns
        ncol=1,  # number of columns
        mode=None,  # mode for horizontal distribution of columns.
        # None, "expand"
        fancybox=None,  # True use a fancy box, false use a rounded
        # box, none use rc
        shadow=None,
        title=None,  # set a title for the legend
        framealpha=None,  # set frame alpha
        edgecolor=None,  # frame patch edgecolor
        facecolor=None,  # frame patch facecolor
        bbox_to_anchor=None,  # bbox that the legend will be anchored.
        bbox_transform=None,  # transform for the bbox
        frameon=None,  # draw frame
        handler_map=None,
    ):
        """
        - *parent*: the artist that contains the legend
        - *handles*: a list of artists (lines, patches) to be added to the
                      legend
        - *labels*: a list of strings to label the legend

        Optional keyword arguments:

        ================   ====================================================
        Keyword            Description
        ================   ====================================================
        loc                Location code string, or tuple (see below).
        prop               the font property
        fontsize           the font size (used only if prop is not specified)
        markerscale        the relative size of legend markers vs. original
        markerfirst        If True (default), marker is to left of the label.
        numpoints          the number of points in the legend for line
        scatterpoints      the number of points in the legend for scatter plot
        scatteryoffsets    a list of yoffsets for scatter symbols in legend
        frameon            If True, draw the legend on a patch (frame).
        fancybox           If True, draw the frame with a round fancybox.
        shadow             If True, draw a shadow behind legend.
        framealpha         Transparency of the frame.
        edgecolor          Frame edgecolor.
        facecolor          Frame facecolor.
        ncol               number of columns
        borderpad          the fractional whitespace inside the legend border
        labelspacing       the vertical space between the legend entries
        handlelength       the length of the legend handles
        handleheight       the height of the legend handles
        handletextpad      the pad between the legend handle and text
        borderaxespad      the pad between the axes and legend border
        columnspacing      the spacing between columns
        title              the legend title
        bbox_to_anchor     the bbox that the legend will be anchored.
        bbox_transform     the transform for the bbox. transAxes if None.
        ================   ====================================================


        The pad and spacing parameters are measured in font-size units.  e.g.,
        a fontsize of 10 points and a handlelength=5 implies a handlelength of
        50 points.  Values from rcParams will be used if None.

        Users can specify any arbitrary location for the legend using the
        *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
        of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
        See :meth:`set_bbox_to_anchor` for more detail.

        The legend location can be specified by setting *loc* with a tuple of
        2 floats, which is interpreted as the lower-left corner of the legend
        in the normalized axes coordinate.
        """
        # local import only to avoid circularity
        from matplotlib.axes import Axes
        from matplotlib.figure import Figure

        Artist.__init__(self)

        if prop is None:
            if fontsize is not None:
                self.prop = FontProperties(size=fontsize)
            else:
                self.prop = FontProperties(size=rcParams["legend.fontsize"])
        elif isinstance(prop, dict):
            self.prop = FontProperties(**prop)
            if "size" not in prop:
                self.prop.set_size(rcParams["legend.fontsize"])
        else:
            self.prop = prop

        self._fontsize = self.prop.get_size_in_points()

        self.texts = []
        self.legendHandles = []
        self._legend_title_box = None

        #: A dictionary with the extra handler mappings for this Legend
        #: instance.
        self._custom_handler_map = handler_map

        locals_view = locals()
        for name in [
                "numpoints", "markerscale", "shadow", "columnspacing",
                "scatterpoints", "handleheight", 'borderpad', 'labelspacing',
                'handlelength', 'handletextpad', 'borderaxespad'
        ]:
            if locals_view[name] is None:
                value = rcParams["legend." + name]
            else:
                value = locals_view[name]
            setattr(self, name, value)
        del locals_view

        handles = list(handles)
        if len(handles) < 2:
            ncol = 1
        self._ncol = ncol

        if self.numpoints <= 0:
            raise ValueError("numpoints must be > 0; it was %d" % numpoints)

        # introduce y-offset for handles of the scatter plot
        if scatteryoffsets is None:
            self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
        else:
            self._scatteryoffsets = np.asarray(scatteryoffsets)
        reps = self.scatterpoints // len(self._scatteryoffsets) + 1
        self._scatteryoffsets = np.tile(self._scatteryoffsets,
                                        reps)[:self.scatterpoints]

        # _legend_box is an OffsetBox instance that contains all
        # legend items and will be initialized from _init_legend_box()
        # method.
        self._legend_box = None

        if isinstance(parent, Axes):
            self.isaxes = True
            self.axes = parent
            self.set_figure(parent.figure)
        elif isinstance(parent, Figure):
            self.isaxes = False
            self.set_figure(parent)
        else:
            raise TypeError("Legend needs either Axes or Figure as parent")
        self.parent = parent

        if loc is None:
            loc = rcParams["legend.loc"]
            if not self.isaxes and loc in [0, 'best']:
                loc = 'upper right'
        if isinstance(loc, six.string_types):
            if loc not in self.codes:
                if self.isaxes:
                    warnings.warn('Unrecognized location "%s". Falling back '
                                  'on "best"; valid locations are\n\t%s\n' %
                                  (loc, '\n\t'.join(self.codes)))
                    loc = 0
                else:
                    warnings.warn('Unrecognized location "%s". Falling back '
                                  'on "upper right"; '
                                  'valid locations are\n\t%s\n' %
                                  (loc, '\n\t'.join(self.codes)))
                    loc = 1
            else:
                loc = self.codes[loc]
        if not self.isaxes and loc == 0:
            warnings.warn('Automatic legend placement (loc="best") not '
                          'implemented for figure legend. '
                          'Falling back on "upper right".')
            loc = 1

        self._mode = mode
        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)

        # We use FancyBboxPatch to draw a legend frame. The location
        # and size of the box will be updated during the drawing time.

        if facecolor is None:
            facecolor = rcParams["legend.facecolor"]
        if facecolor == 'inherit':
            facecolor = rcParams["axes.facecolor"]

        if edgecolor is None:
            edgecolor = rcParams["legend.edgecolor"]
        if edgecolor == 'inherit':
            edgecolor = rcParams["axes.edgecolor"]

        self.legendPatch = FancyBboxPatch(xy=(0.0, 0.0),
                                          width=1.,
                                          height=1.,
                                          facecolor=facecolor,
                                          edgecolor=edgecolor,
                                          mutation_scale=self._fontsize,
                                          snap=True)

        # The width and height of the legendPatch will be set (in the
        # draw()) to the length that includes the padding. Thus we set
        # pad=0 here.
        if fancybox is None:
            fancybox = rcParams["legend.fancybox"]

        if fancybox:
            self.legendPatch.set_boxstyle("round", pad=0, rounding_size=0.2)
        else:
            self.legendPatch.set_boxstyle("square", pad=0)

        self._set_artist_props(self.legendPatch)

        self._drawFrame = frameon
        if frameon is None:
            self._drawFrame = rcParams["legend.frameon"]

        # init with null renderer
        self._init_legend_box(handles, labels, markerfirst)

        # If shadow is activated use framealpha if not
        # explicitly passed. See Issue 8943
        if framealpha is None:
            if shadow:
                self.get_frame().set_alpha(1)
            else:
                self.get_frame().set_alpha(rcParams["legend.framealpha"])
        else:
            self.get_frame().set_alpha(framealpha)

        self._loc = loc
        self.set_title(title)
        self._last_fontsize_points = self._fontsize
        self._draggable = None

    def _set_artist_props(self, a):
        """
        set the boilerplate props for artists added to axes
        """
        a.set_figure(self.figure)
        if self.isaxes:
            # a.set_axes(self.axes)
            a.axes = self.axes

        a.set_transform(self.get_transform())

    def _set_loc(self, loc):
        # find_offset function will be provided to _legend_box and
        # _legend_box will draw itself at the location of the return
        # value of the find_offset.
        self._loc_real = loc
        self.stale = True

    def _get_loc(self):
        return self._loc_real

    _loc = property(_get_loc, _set_loc)

    def _findoffset(self, width, height, xdescent, ydescent, renderer):
        "Helper function to locate the legend"

        if self._loc == 0:  # "best".
            x, y = self._find_best_position(width, height, renderer)
        elif self._loc in Legend.codes.values():  # Fixed location.
            bbox = Bbox.from_bounds(0, 0, width, height)
            x, y = self._get_anchored_bbox(self._loc, bbox,
                                           self.get_bbox_to_anchor(), renderer)
        else:  # Axes or figure coordinates.
            fx, fy = self._loc
            bbox = self.get_bbox_to_anchor()
            x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy

        return x + xdescent, y + ydescent

    @allow_rasterization
    def draw(self, renderer):
        "Draw everything that belongs to the legend"
        if not self.get_visible():
            return

        renderer.open_group('legend')

        fontsize = renderer.points_to_pixels(self._fontsize)

        # if mode == fill, set the width of the legend_box to the
        # width of the paret (minus pads)
        if self._mode in ["expand"]:
            pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
            self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)

        # update the location and size of the legend. This needs to
        # be done in any case to clip the figure right.
        bbox = self._legend_box.get_window_extent(renderer)
        self.legendPatch.set_bounds(bbox.x0, bbox.y0, bbox.width, bbox.height)
        self.legendPatch.set_mutation_scale(fontsize)

        if self._drawFrame:
            if self.shadow:
                shadow = Shadow(self.legendPatch, 2, -2)
                shadow.draw(renderer)

            self.legendPatch.draw(renderer)

        self._legend_box.draw(renderer)

        renderer.close_group('legend')
        self.stale = False

    def _approx_text_height(self, renderer=None):
        """
        Return the approximate height of the text. This is used to place
        the legend handle.
        """
        if renderer is None:
            return self._fontsize
        else:
            return renderer.points_to_pixels(self._fontsize)

    # _default_handler_map defines the default mapping between plot
    # elements and the legend handlers.

    _default_handler_map = {
        StemContainer:
        legend_handler.HandlerStem(),
        ErrorbarContainer:
        legend_handler.HandlerErrorbar(),
        Line2D:
        legend_handler.HandlerLine2D(),
        Patch:
        legend_handler.HandlerPatch(),
        LineCollection:
        legend_handler.HandlerLineCollection(),
        RegularPolyCollection:
        legend_handler.HandlerRegularPolyCollection(),
        CircleCollection:
        legend_handler.HandlerCircleCollection(),
        BarContainer:
        legend_handler.HandlerPatch(
            update_func=legend_handler.update_from_first_child),
        tuple:
        legend_handler.HandlerTuple(),
        PathCollection:
        legend_handler.HandlerPathCollection(),
        PolyCollection:
        legend_handler.HandlerPolyCollection()
    }

    # (get|set|update)_default_handler_maps are public interfaces to
    # modify the default handler map.

    @classmethod
    def get_default_handler_map(cls):
        """
        A class method that returns the default handler map.
        """
        return cls._default_handler_map

    @classmethod
    def set_default_handler_map(cls, handler_map):
        """
        A class method to set the default handler map.
        """
        cls._default_handler_map = handler_map

    @classmethod
    def update_default_handler_map(cls, handler_map):
        """
        A class method to update the default handler map.
        """
        cls._default_handler_map.update(handler_map)

    def get_legend_handler_map(self):
        """
        return the handler map.
        """

        default_handler_map = self.get_default_handler_map()

        if self._custom_handler_map:
            hm = default_handler_map.copy()
            hm.update(self._custom_handler_map)
            return hm
        else:
            return default_handler_map

    @staticmethod
    def get_legend_handler(legend_handler_map, orig_handle):
        """
        return a legend handler from *legend_handler_map* that
        corresponds to *orig_handler*.

        *legend_handler_map* should be a dictionary object (that is
        returned by the get_legend_handler_map method).

        It first checks if the *orig_handle* itself is a key in the
        *legend_hanler_map* and return the associated value.
        Otherwise, it checks for each of the classes in its
        method-resolution-order. If no matching key is found, it
        returns None.
        """
        if is_hashable(orig_handle):
            try:
                return legend_handler_map[orig_handle]
            except KeyError:
                pass

        for handle_type in type(orig_handle).mro():
            try:
                return legend_handler_map[handle_type]
            except KeyError:
                pass

        return None

    def _init_legend_box(self, handles, labels, markerfirst=True):
        """
        Initialize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self._fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.

        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(
            verticalalignment='baseline',
            horizontalalignment='left',
            fontproperties=self.prop,
        )

        labelboxes = []
        handleboxes = []

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
        # 0.35 and 0.7 are just heuristic numbers and may need to be improved.
        height = self._approx_text_height() * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates should
        # be given in the display coordinates.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not use its
        # default transform (e.g., Collections), you need to
        # manually set their transform to the self.get_transform().
        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, lab in zip(handles, labels):
            handler = self.get_legend_handler(legend_handler_map, orig_handle)
            if handler is None:
                warnings.warn(
                    "Legend does not support {!r} instances.\nA proxy artist "
                    "may be used instead.\nSee: "
                    "http://matplotlib.org/users/legend_guide.html"
                    "#creating-artists-specifically-for-adding-to-the-legend-"
                    "aka-proxy-artists".format(orig_handle))
                # We don't have a handle for this artist, so we just defer
                # to None.
                handle_list.append(None)
            else:
                textbox = TextArea(lab,
                                   textprops=label_prop,
                                   multilinebaseline=True,
                                   minimumdescent=True)
                text_list.append(textbox._text)

                labelboxes.append(textbox)

                handlebox = DrawingArea(width=self.handlelength * fontsize,
                                        height=height,
                                        xdescent=0.,
                                        ydescent=descent)
                handleboxes.append(handlebox)

                # Create the artist for the legend which represents the
                # original artist/handle.
                handle_list.append(
                    handler.legend_artist(self, orig_handle, fontsize,
                                          handlebox))

        if handleboxes:
            # We calculate number of rows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaining
            # (num_smallcol) columns will have (nrows) rows.
            ncol = min(self._ncol, len(handleboxes))
            nrows, num_largecol = divmod(len(handleboxes), ncol)
            num_smallcol = ncol - num_largecol
            # starting index of each column and number of rows in it.
            rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol
            start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]])
            cols = zip(start_idxs, rows_per_col)
        else:
            cols = []

        handle_label = list(zip(handleboxes, labelboxes))
        columnbox = []
        for i0, di in cols:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [
                HPacker(pad=0,
                        sep=self.handletextpad * fontsize,
                        children=[h, t] if markerfirst else [t, h],
                        align="baseline") for h, t in handle_label[i0:i0 + di]
            ]
            # minimumdescent=False for the text of the last row of the column
            if markerfirst:
                itemBoxes[-1].get_children()[1].set_minimumdescent(False)
            else:
                itemBoxes[-1].get_children()[0].set_minimumdescent(False)

            # pack columnBox
            alignment = "baseline" if markerfirst else "right"
            columnbox.append(
                VPacker(pad=0,
                        sep=self.labelspacing * fontsize,
                        align=alignment,
                        children=itemBoxes))

        mode = "expand" if self._mode == "expand" else "fixed"
        sep = self.columnspacing * fontsize
        self._legend_handle_box = HPacker(pad=0,
                                          sep=sep,
                                          align="baseline",
                                          mode=mode,
                                          children=columnbox)
        self._legend_title_box = TextArea("")
        self._legend_box = VPacker(
            pad=self.borderpad * fontsize,
            sep=self.labelspacing * fontsize,
            align="center",
            children=[self._legend_title_box, self._legend_handle_box])
        self._legend_box.set_figure(self.figure)
        self._legend_box.set_offset(self._findoffset)
        self.texts = text_list
        self.legendHandles = handle_list

    def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets]

    def draw_frame(self, b):
        'b is a boolean.  Set draw frame to b'
        self.set_frame_on(b)

    def get_children(self):
        'return a list of child artists'
        children = []
        if self._legend_box:
            children.append(self._legend_box)
        children.append(self.get_frame())

        return children

    def get_frame(self):
        'return the Rectangle instance used to frame the legend'
        return self.legendPatch

    def get_lines(self):
        'return a list of lines.Line2D instances in the legend'
        return [h for h in self.legendHandles if isinstance(h, Line2D)]

    def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list(
            'Patch', [h for h in self.legendHandles if isinstance(h, Patch)])

    def get_texts(self):
        'return a list of text.Text instance in the legend'
        return silent_list('Text', self.texts)

    def set_title(self, title, prop=None):
        """
        set the legend title. Fontproperties can be optionally set
        with *prop* parameter.
        """
        self._legend_title_box._text.set_text(title)

        if prop is not None:
            if isinstance(prop, dict):
                prop = FontProperties(**prop)
            self._legend_title_box._text.set_fontproperties(prop)

        if title:
            self._legend_title_box.set_visible(True)
        else:
            self._legend_title_box.set_visible(False)
        self.stale = True

    def get_title(self):
        'return Text instance for the legend title'
        return self._legend_title_box._text

    def get_window_extent(self, *args, **kwargs):
        'return a extent of the legend'
        return self.legendPatch.get_window_extent(*args, **kwargs)

    def get_frame_on(self):
        """
        Get whether the legend box patch is drawn
        """
        return self._drawFrame

    def set_frame_on(self, b):
        """
        Set whether the legend box patch is drawn

        ACCEPTS: [ *True* | *False* ]
        """
        self._drawFrame = b
        self.stale = True

    def get_bbox_to_anchor(self):
        """
        return the bbox that the legend will be anchored
        """
        if self._bbox_to_anchor is None:
            return self.parent.bbox
        else:
            return self._bbox_to_anchor

    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        set the bbox that the legend will be anchored.

        *bbox* can be a BboxBase instance, a tuple of [left, bottom,
        width, height] in the given transform (normalized axes
        coordinate if None), or a tuple of [left, bottom] where the
        width and height will be assumed to be zero.
        """
        if bbox is None:
            self._bbox_to_anchor = None
            return
        elif isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError:
                raise ValueError("Invalid argument for bbox : %s" % str(bbox))

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        if transform is None:
            transform = BboxTransformTo(self.parent.bbox)

        self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor, transform)
        self.stale = True

    def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
        """
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x,y) coordinate of the bbox.

        - loc: a location code in range(1, 11).
          This corresponds to the possible values for self._loc, excluding
          "best".

        - bbox: bbox to be placed, display coodinate units.
        - parentbbox: a parent box which will contain the bbox. In
            display coordinates.
        """
        assert loc in range(1, 11)  # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))

        anchor_coefs = {
            UR: "NE",
            UL: "NW",
            LL: "SW",
            LR: "SE",
            R: "E",
            CL: "W",
            CR: "E",
            LC: "S",
            UC: "N",
            C: "C"
        }

        c = anchor_coefs[loc]

        fontsize = renderer.points_to_pixels(self._fontsize)
        container = parentbbox.padded(-(self.borderaxespad) * fontsize)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0

    def _find_best_position(self, width, height, renderer, consider=None):
        """
        Determine the best location to place the legend.

        `consider` is a list of (x, y) pairs to consider as a potential
        lower-left corner of the legend. All are display coords.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        verts, bboxes, lines, offsets = self._auto_legend_data()

        bbox = Bbox.from_bounds(0, 0, width, height)
        if consider is None:
            consider = [
                self._get_anchored_bbox(x, bbox, self.get_bbox_to_anchor(),
                                        renderer)
                for x in range(1, len(self.codes))
            ]

        candidates = []
        for idx, (l, b) in enumerate(consider):
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            # XXX TODO: If markers are present, it would be good to
            # take them into account when checking vertex overlaps in
            # the next line.
            badness = (legendBox.count_contains(verts) +
                       legendBox.count_contains(offsets) +
                       legendBox.count_overlaps(bboxes) + sum(
                           line.intersects_bbox(legendBox, filled=False)
                           for line in lines))
            if badness == 0:
                return l, b
            # Include the index to favor lower codes in case of a tie.
            candidates.append((badness, idx, (l, b)))

        _, _, (l, b) = min(candidates)
        return l, b

    def contains(self, event):
        return self.legendPatch.contains(event)

    def draggable(self, state=None, use_blit=False, update="loc"):
        """
        Set the draggable state -- if state is

          * None : toggle the current state

          * True : turn draggable on

          * False : turn draggable off

        If draggable is on, you can drag the legend on the canvas with
        the mouse.  The DraggableLegend helper instance is returned if
        draggable is on.

        The update parameter control which parameter of the legend changes
        when dragged. If update is "loc", the *loc* parameter of the legend
        is changed. If "bbox", the *bbox_to_anchor* parameter is changed.
        """
        is_draggable = self._draggable is not None

        # if state is None we'll toggle
        if state is None:
            state = not is_draggable

        if state:
            if self._draggable is None:
                self._draggable = DraggableLegend(self,
                                                  use_blit,
                                                  update=update)
        else:
            if self._draggable is not None:
                self._draggable.disconnect()
            self._draggable = None

        return self._draggable
def create_benchmark_plot(train_X,
                          train_y,
                          test_X,
                          test_y,
                          clf,
                          splits=20,
                          plot_outfile=None,
                          y_ticks=0.025,
                          min_y_lim=0.4):
    """
    This method creates a benchmark plot.

    :param train_X:
    :param train_y:
    :param test_X:
    :param test_y:
    :param clf:
    :param splits:
    :param plot_outfile:
    :param y_ticks:
    :param min_y_lim:
    :return:
    """

    results = {'train_size': [], 'on_test': [], 'on_train': []}

    # splitting the train X in n (almost) equal splits)
    train_x_splits = np.array_split(ary=train_X,
                                    indices_or_sections=splits,
                                    axis=0)

    # splitting the train y in the same splits as the train X
    train_y_splits = np.array_split(ary=train_y,
                                    indices_or_sections=splits,
                                    axis=0)

    # setting parameters for the graph.
    font_p = FontProperties()

    font_p.set_size('small')

    fig = plt.figure()
    fig.suptitle('Learning Curves', fontsize=20)

    ax = fig.add_subplot(111)
    ax.axis(xmin=0, xmax=train_X.shape[0] * 1.05, ymin=0, ymax=1.1)

    plt.xlabel('N. of training instances', fontsize=18)
    plt.ylabel('Accuracy', fontsize=16)

    plt.grid(True)

    plt.axvline(x=int(train_X.shape[0] * 0.3))
    plt.yticks(np.arange(0, 1.025, 0.025))

    if y_ticks == 0.05:
        plt.yticks(np.arange(0, 1.025, 0.05))

    elif y_ticks == 0.025:
        plt.yticks(np.arange(0, 1.025, 0.025))

    plt.ylim([min_y_lim, 1.025])

    # each time adds up one split and refits the model.
    for i in range(1, splits + 1):
        train_x_part = np.concatenate(train_x_splits[:i])
        train_y_part = np.concatenate(train_y_splits[:i])

        print(20 * '*')
        print('Split {} size: {}'.format(i, train_x_part.shape))

        results['train_size'].append(train_x_part.shape[0])

        result_on_test = benchmark(clf=clf,
                                   train_X=train_x_part,
                                   train_y=train_y_part,
                                   test_X=test_X,
                                   test_y=test_y)

        # calculates each time the metrics also on the test.
        results['on_test'].append(result_on_test['accuracy'])

        # calculates the metrics for the given training part
        result_on_train_part = benchmark(clf=clf,
                                         train_X=train_x_part,
                                         train_y=train_y_part,
                                         test_X=train_x_part,
                                         test_y=train_y_part)

        results['on_train'].append(result_on_train_part['accuracy'])

        line_up, = ax.plot(results['train_size'],
                           results['on_train'],
                           'o-',
                           label='Accuracy on Train')

        line_down, = ax.plot(results['train_size'],
                             results['on_test'],
                             'o-',
                             label='Accuracy on Test')

        plt.legend([line_up, line_down],
                   ['Accuracy on Train', 'Accuracy on Test'],
                   prop=font_p)

    if plot_outfile:
        fig.savefig(plot_outfile)

    plt.show()

    return results
Example #49
0
def full_matrix_hnn():

    m_encoder = scalar_sdr(40,22,-0.25,0.25,(6,12))
    b_encoder = scalar_sdr(460,200,0.0,1.0)
    # calculate number of nodes
    nodes = m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape) + b_encoder.n
    # initialize hopfield net
    hnn = Hopfield_Neural_Network(nodes)

    # store data in hnn i.e. brain_id -- matrix[brain_id] pairs
    for id_ in brain_id:
        data = np.array([])
        matrix = matrices[id_]
        matrix = m_encoder.encode_ndarray(matrix)
        data = np.append(data,matrix.flatten())

        brain_sig = brain_id[id_]
        brain_sig = b_encoder.encode(brain_sig)
        data = np.append(data,brain_sig)

        hnn.store(data)

    durations = []
    diffs = []
    samples = 10
    for i in range(samples):
        for id_ in matrices:
            # setup input with complete brain_id signal
            data = np.zeros(m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape))-1
            brain_sig = brain_id[id_]
            brain_sig = b_encoder.encode(brain_sig)
            data = np.append(data,brain_sig)
        
            # set number of iterations -- proportional to number of nodes (i.e. 300*72 = 21600)
            hnn.setIter(21600)

            # recall matrix value
            t0 = time.time()
            mem = hnn.recall(data)
            duration = time.time()-t0
            durations.append(duration)

            # decode recalled matrix
            mem_decoded = m_encoder.decode_ndarray(mem[0:m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape)])

            # calculate recall error
            matrix_decoded = m_encoder.decode_ndarray(m_encoder.encode_ndarray(matrices[id_]).flatten())
            diff = mem_decoded-matrix_decoded
            diffs.append(abs(np.array(diff)))

    # print meta data
    print "mean: ", np.mean(np.array(diffs).flatten())
    print "max: ", np.max(np.array(diffs).flatten())
    print "std: ", np.std(np.array(diffs).flatten())
    print "duration: ", np.mean(durations)

    # Bar graph plot
    # plotting constants 
    max_ = 0.5
    bars = 40

    # calculate category indices
    categories = []
    for i in range(bars):
        categories.append(i*max_/bars)
    width = categories[1]

    # tally number of instances for each category
    values = np.zeros(bars)
    for diff in np.array(diffs).flatten():
        i = int(diff/(max_+0.0000001)*bars)
        values[i] += 1
    # divide by number of samples to obtain normalized score
    values /= samples
    values /= 288.

    # plot bar graph
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    plt.figure(1)
    plt.title("Average error distribution across 10 samples")
    plt.bar(categories, values, width, align='center')
    plt.xlabel("Error bars - width = %0.4f" %(max_/bars))
    plt.ylabel("Proportion")
    plt.show()
    # print number of values that fall into first category (good approximation of how well the memory does)
    print "Values[0]: ", values[0]
Example #50
0
def visualize():
    def load(lib):
        batch = np.loadtxt("results-batch-size-%s.csv" % lib, delimiter=",")
        nfeat = np.loadtxt("results-nfeat-%s.csv" % lib, delimiter=",")
        return batch, nfeat

    fig, axes = plt.subplots(nrows=2, ncols=2)
    sns.despine()
    # sns.set_context("poster")
    fig.set_figheight(6)
    fig.set_figwidth(9)

    names = [f[f.index('size-') + 5:-4] for f in glob('*size*.csv')]

    for name in names:
        batch_res, nfeat_res = load(name)
        axes[0, 0].plot(batch_res[:, 0], batch_res[:, 1], label=name)
        axes[0, 1].plot(nfeat_res[:, 0], nfeat_res[:, 1], label=name)
    # pytorch_batch, pytorch_nfeat = load("pytorch")
    # spflow_batch, spflow_nfeat = load("spflow")
    # tf_batch, tf_nfeat = load("spflow-tf")
    # spflow_layers_batch, spflow_layers_nfeat = load("spflow-layer")

    # Plot absolute values
    #axes[0, 0].plot(spflow_batch[:, 0], spflow_batch[:, 1], label="SPFlow")
    #axes[0, 0].plot(tf_batch[:, 0], tf_batch[:, 1], label="SPFlow-TF")
    #axes[0, 0].plot(pytorch_batch[:, 0], pytorch_batch[:, 1], label="Layerwise PyTorch")
    #axes[0, 0].plot(spflow_layers_batch[:, 0], spflow_layers_batch[:, 1], label="SPFlow Layers")

    #axes[0, 1].plot(spflow_nfeat[:, 0], spflow_nfeat[:, 1], label="SPFlow")
    #axes[0, 1].plot(tf_nfeat[:, 0], tf_nfeat[:, 1], label="SPFlow-TF")
    #axes[0, 1].plot(pytorch_nfeat[:, 0], pytorch_nfeat[:, 1], label="Layerwise PyTorch")
    #axes[0, 1].plot(spflow_layers_nfeat[:, 0], spflow_layers_nfeat[:, 1], label="SPFlow Layers")

    fontP = FontProperties()
    fontP.set_size("small")
    axes[0, 1].legend(loc="upper left",
                      fancybox=True,
                      framealpha=0.5,
                      prop=fontP)

    axes[0, 0].set_xscale("log", basex=2)
    axes[0, 0].set_yscale("log", basey=10)
    axes[0, 1].set_xscale("log", basex=2)
    axes[0, 1].set_yscale("log", basey=10)

    # Plot relative improvements
    # axes[1, 0].plot(
    #     spflow_batch[:, 0],
    #     spflow_batch[:, 1] / pytorch_batch[:, 1],
    #     label="SPFlow/Layerwise PyTorch",
    # )
    # axes[1, 0].plot(
    #     tf_batch[:, 0],
    #     tf_batch[:, 1] / pytorch_batch[:, 1],
    #     label="SPFlow-TF/Layerwise PyTorch",
    # )
    # axes[1, 1].plot(
    #     spflow_nfeat[:, 0],
    #     spflow_nfeat[:, 1] / pytorch_nfeat[:, 1],
    #     label="SPFlow/Layerwise PyTorch",
    # )
    # axes[1, 1].plot(
    #     tf_nfeat[:, 0],
    #     tf_nfeat[:, 1] / pytorch_nfeat[:, 1],
    #     label="SPFlow-TF/Layerwise PyTorch",
    # )

    axes[1, 0].set_xscale("log", basex=2)
    # axes[1, 0].set_yscale("log", basey=10)
    axes[1, 1].set_xscale("log", basex=2)
    # axes[1, 1].set_yscale("log", basey=10)
    axes[0, 0].set_ylabel("Avg Time (s) over 100 Runs")
    axes[0, 1].set_ylabel("Avg Time (s) over 100 Runs")
    axes[1, 0].set_ylabel(r"Relative Time $\frac{t_x}{t_{PyTorch}}$")
    axes[1, 1].set_ylabel(r"Relative Time $\frac{t_x}{t_{PyTorch}}$")
    axes[0, 0].set_xlabel("Batch Size")
    axes[0, 1].set_xlabel("Features")
    axes[1, 0].set_xlabel("Batch Size")
    axes[1, 1].set_xlabel("Features")
    axes[1, 1].legend(loc="upper left",
                      fancybox=True,
                      framealpha=0.5,
                      prop=fontP)

    # Titles
    title = "vs".join(
        names
    ) + " SPN Forward"  #"SPFlow vs SPFlow-TF vs PyTorch: SPN Forward Pass"
    fig.suptitle(title)
    plt.savefig("benchmark.png", dpi=300)  # , bbox_inches="tight")
Example #51
0
def plotter(fdict):
    """ Go """
    font0 = FontProperties()
    font0.set_family('monospace')
    font0.set_size(16)

    pgconn = get_dbconn('asos')
    ctx = get_autoplot_context(fdict, get_description())
    varname = ctx['var']
    month = ctx['month']
    network = ctx['network']
    station = ctx['zstation']
    hour = ctx['hour']
    nt = NetworkTable(network)

    if month == 'all':
        months = range(1, 13)
    elif month == 'fall':
        months = [9, 10, 11]
    elif month == 'winter':
        months = [12, 1, 2]
    elif month == 'spring':
        months = [3, 4, 5]
    elif month == 'summer':
        months = [6, 7, 8]
    elif month == 'gs':
        months = [5, 6, 7, 8, 9]
    else:
        ts = datetime.datetime.strptime("2000-"+month+"-01", '%Y-%b-%d')
        # make sure it is length two for the trick below in SQL
        months = [ts.month]

    df = read_sql("""
    WITH obs as (
        SELECT (valid + '10 minutes'::interval) at time zone %s as ts,
        tmpf::int as itmpf, dwpf::int as idwpf from alldata
        where station = %s and tmpf is not null
        and dwpf is not null and
        extract(month from valid at time zone %s) in %s),
    agg1 as (
        SELECT date_trunc('hour', ts) as hts, avg(itmpf) as avg_itmpf,
        avg(idwpf) as avg_idwpf from obs
        WHERE extract(hour from ts) = %s GROUP by hts)

    SELECT extract(year from hts)::int as year, avg(avg_itmpf) as avg_tmpf,
    count(*) as cnt
    from agg1 GROUP by year ORDER by year ASC
    """, pgconn, params=(nt.sts[station]['tzname'], station,
                         nt.sts[station]['tzname'], tuple(months), hour),
                  index_col='year')
    minfreq = len(months) * 30 * 0.8
    df2 = df[df['cnt'] > minfreq]

    (fig, ax) = plt.subplots(1, 1)
    ax.bar(df2.index.values, df2[varname], align='center', ec='b', fc='b')
    m = df2[varname].mean()
    ax.axhline(m, lw=2, zorder=5, color='k')
    slp, intercept, r, _, _ = stats.linregress(df2.index.values,
                                               df2[varname].values)
    ax.plot(df2.index.values, intercept + (df2.index.values * slp), color='r',
            lw=2, zorder=6)
    ax.text(0.02, 0.92,
            r"$\frac{^\circ}{decade} = %.2f,R^2=%.2f, avg = %.1f$" % (
                    slp * 10.0, r ** 2, m), va='bottom',
            transform=ax.transAxes, bbox=dict(color='white'))

    ax.set_ylim([df2[varname].min() - 5,
                 df2[varname].max() + 5])
    ax.grid(True)
    lts = datetime.datetime(2000, 1, 1, int(hour), 0)
    fig.text(0.5, 0.91, ("%s [%s] %s Local %s-%s\n"
                         "%s [%s]"
                         ) % (nt.sts[station]['name'], station,
                              lts.strftime("%-I %p"),
                              df2.index.min(),
                              df2.index.max(),
                              PDICT[varname],
                              MDICT[month]), ha='center')

    return fig, df
Example #52
0
def full_matrix_lam():
    matrix_shape = matrices["zero"].shape
    m_encoder = scalar_sdr(100,21,-0.25,0.25,matrix_shape,neg=False)
    b_encoder = scalar_sdr(100,21,0.0,1.0,neg=False)

    shape = (b_encoder.n,m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape))

    lma = LAM(shape)
    for id_ in brain_id:
        data = np.array([])
        matrix = matrices[id_]
        matrix = m_encoder.encode_ndarray(matrix)

        data = np.append(data,matrix.flatten())

        brain_sig = brain_id[id_]
        brain_sig = b_encoder.encode(brain_sig)

        data = np.append(data,brain_sig)

        lma.store(brain_sig,matrix)

    diffs = []
    durations = []
    for i in range(1):
        for id_ in brain_id:
            brain_sig = brain_id[id_]
            brain_sig = b_encoder.encode(brain_sig)

            t0 = time.time()
            mem = lma.recall(np.array(brain_sig))
            duration = time.time()-t0
            durations.append(duration)

            matrix_decoded = m_encoder.decode_ndarray(np.array(mem).reshape((reduce(lambda x, y: x*y, m_encoder.ndarray_shape)*m_encoder.n,)))
            diff = m_encoder.decode_ndarray(np.array(m_encoder.encode_ndarray(matrices[id_])).reshape((reduce(lambda x, y: x*y, m_encoder.ndarray_shape)*m_encoder.n,)))-matrix_decoded
            diffs.append(diff)

    # print meta data
    print "mean: ", np.mean(np.array(diffs).flatten())
    print "max: ", np.max(np.array(diffs).flatten())
    print "std: ", np.std(np.array(diffs).flatten())
    print "duration: ", np.mean(durations)

    # Bar graph plot
    # plotting constants 
    max_ = 0.5
    bars = 40

    # calculate category indices
    categories = []
    for i in range(bars):
        categories.append(i*max_/bars)
    width = categories[1]

    # tally number of instances for each category
    values = np.zeros(bars)
    for diff in np.array(diffs).flatten():
        i = int(diff/(max_+0.0000001)*bars)
        values[i] += 1

    values /= 288.

    # plot bar graph
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    plt.figure(1)
    plt.title("Average error distribution across 10 samples")
    plt.bar(categories, values, width, align='center')
    plt.xlabel("Error bars - width = %0.4f" %(max_/bars))
    plt.ylabel("Proportion")
    plt.show()
    # print number of values that fall into first category (good approximation of how well the memory does)
    print "Values[0]: ", values[0]
Example #53
0
# save new clusters for chart
y_km = kmeans.fit_predict(points)

#k means ++ plot
plt.scatter(points[y_km == 0, 0], points[y_km == 0, 1], s=100, c='red')
plt.scatter(points[y_km == 1, 0], points[y_km == 1, 1], s=100, c='black')
plt.scatter(points[y_km == 2, 0], points[y_km == 2, 1], s=100, c='blue')
plt.scatter(points[y_km == 3, 0], points[y_km == 3, 1], s=100, c='cyan')
plt.xlim(-6, 6)
plt.ylim(-8, 6)
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.title('K-means++ wine clustering')
plt.grid(color='lightgray', linestyle='--', linewidth=0.5)
fontpar = FontProperties()
fontpar.set_size('small')
plt.legend(['C1', 'C2', 'C3', 'C4'],
           loc=2,
           prop=fontpar,
           bbox_to_anchor=(-0.01, 1.15),
           ncol=4)
plt.savefig('K-means-clusters-wine-data-4.png', dpi=250)
plt.clf()

print('4 clusters computed')

# create kmeans object
kmeans5 = KMeans(n_clusters=5)
# fit kmeans object to data
kmeans5.fit(points)
# print location of clusters learned by kmeans object
Example #54
0
def single_cell_hnn():
    matrix_shape = (1,)
    m_encoder = scalar_sdr(40,22,-0.25,0.25,matrix_shape)
    b_encoder = scalar_sdr(46,20,0.0,1.0)
    # Calculate number of nodes of hopfield net
    nodes = m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape) + b_encoder.n
    # i) Initialize hopfield network for each matrix value
    # ii) Store data for each brain_id+matrix[brain_id] for given matrix index
    nns = {}
    for index in np.ndindex(matrices["zero"].shape):
        hnn = Hopfield_Neural_Network(nodes)
        for id_ in brain_id:
            data = np.array([])
            matrix = matrices[id_][index].reshape(matrix_shape)
            matrix = m_encoder.encode_ndarray(matrix)
            data = np.append(data,matrix.flatten())
            brain_sig = brain_id[id_]
            brain_sig = b_encoder.encode(brain_sig)
            data = np.append(data,brain_sig)
            hnn.store(data)
        nns[index] = hnn
    # Recall matrix values from brain_id
    # setup some arrays to hold data
    nans_avg = []
    diffs = []
    durations = []
    # run recall fo network 'samples' number of times
    samples = 10
    for i in range(samples):
        nans = 0
        diffs_m = []
        # for each index in the DEP matrix
        for index in np.ndindex(matrices["zero"].shape):

            # for each brain id
            for id_ in brain_id:

                # generate data
                data = np.zeros(nodes)-1
                brain_sig = brain_id[id_]
                brain_sig = b_encoder.encode(brain_sig)
                data[-b_encoder.n:] = brain_sig

                # set iteration number
                nns[index].setIter(300)

                # recall matrix value
                t0 = time.time()
                mem = nns[index].recall(data,(0,m_encoder.n))
                duration = time.time()-t0
                durations.append(duration)

                # decode matrix value
                matrix_out = mem[0:m_encoder.n*reduce(lambda x, y: x*y, m_encoder.ndarray_shape)]

                # calculate error of recalled matrix value
                matrix_decoded = m_encoder.decode_ndarray(matrix_out)
                diff_m = m_encoder.decode_ndarray(m_encoder.encode_ndarray(matrices[id_][index].reshape(matrix_shape)).flatten())-matrix_decoded

                if np.isnan(diff_m):
                    nans += 1
                diffs_m.append(diff_m)
        nans_avg.append(nans)
        diffs.append(abs(np.array(diffs_m)))
    # print meta data
    print "nans: ", np.max(nans_avg)
    print "mean: ", np.mean(np.array(diffs).flatten())
    print "max: ", np.max(np.array(diffs).flatten())
    print "std: ", np.std(np.array(diffs).flatten())
    print "duration: ", np.mean(durations)
    # Bar graph plot
    # plotting constants 
    max_ = 0.5
    bars = 40
    # calculate category indices
    categories = []
    for i in range(bars):
        categories.append(i*max_/bars)
    
    width = categories[1]
    # tally number of instances for each category
    values = np.zeros(bars)
    for diff in np.array(diffs).flatten():
        i = int(diff/(max_+0.0000001)*bars)
        values[i] += 1
    # divide by number of samples to obtain normalized score
    values /= samples
    values /= 288.0
    # plot bar graph
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    plt.figure(1)
    plt.title("Average error distribution across 10 samples")
    plt.bar(categories, values, width, align='center')
    plt.xlabel("Error bars - width = %0.4f" %(max_/bars))
    plt.ylabel("Proportion")
    plt.show()
    # print number of values that fall into first category (good approximation of how well the memory does)
    print "Values[0]: ", values[0]
Example #55
0
#!/usr/local/bin/python3

import os, sys, json
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties

matplotlib.rcParams["pdf.fonttype"] = 42
matplotlib.rcParams["ps.fonttype"] = 42
matplotlib.rcParams["font.size"] = 8
font = FontProperties()
font.set_size(8)
font2 = FontProperties()
font2.set_size(8)
font2.set_weight("bold")
font3 = FontProperties()
font3.set_size(7)


# get label from string
def get_label(x):
    x = x.split("_")[0]
    return x.upper() if len(x) <= 2 else x.capitalize()


# get browser from string
def get_browser(x):
    x = "".join([l for l in x if l.isalpha()])
Example #56
0
def make_bench_plot(x,
                    ys,
                    y_errors,
                    labels,
                    title,
                    ylabel,
                    poly,
                    deg,
                    output_fp,
                    scale=1):
    """Generates a plot with the benchmark results

    Parameters
    ----------
    x : list
        The values for the x axis
    ys : list of lists
        Each element of the list a series of data to plot
    y_errors : list of lists
        Values of the errorbars for each data series
    labels : list of strings
        Data series names
    title : string
        The plot title
    ylabel : string
        The y axis label
    poly : array
        Polynomial that fits the dataseries
    deg : integer
        Degree of the polynomial
    output_fp : string
        The path to the output figure
    scale : number, optional
        Value used to scale the y values (default: 1, no scale is performed)

    Raises
    ------
    ValueError
        If scale is <= 0
    """
    if scale <= 0:
        raise ValueError("Scale should be an integer greater than 0")
    # Check if the x axis is numerical
    x_ticks = x
    try:
        x = np.asarray(x, dtype=np.float64)
    except ValueError:
        x = np.arange(len(x))
    # For the function resulted from curve fitting, we use an extended x axis,
    # so the trend line is more clear
    interval = x[1] - x[0]
    x2 = np.arange(x[0] - interval, x[-1] + 2 * interval)
    # Generate plot
    # First plot the fitted curve
    y2 = np.polyval(poly, x2)
    # Scale the y2 value
    y2 = y2 / scale
    figure = plt.figure()
    ax = figure.add_subplot(111)
    ax.plot(x2, y2, 'k', label=generate_poly_label(poly, deg))
    # Plot the benchmark data
    for label, y, y_err in izip(labels, ys, y_errors):
        y = np.array(y) / scale
        y_err = np.array(y_err) / scale
        ax.errorbar(x, y, yerr=y_err, label=label)
    figure.suptitle(title)
    ax.set_xlabel("Input file")
    ax.set_ylabel(ylabel)
    fontP = FontProperties()
    fontP.set_size('small')
    ax.legend(loc='best', prop=fontP, fancybox=True).get_frame().set_alpha(0.2)
    ax.set_xticks(x)
    ax.set_xticklabels(x_ticks)
    figure.savefig(output_fp)
Example #57
0
def plotBand(self, gs_main, pos=0, band='K', cutoff=3., 
            pstamp=None, pstamp_hdr=None, tdhst_cat=None, tdhst_vers=None):
            
            
    gs = gridspec.GridSpecFromSubplotSpec(2,2, 
              subplot_spec = gs_main[pos],
              width_ratios = [7,1], 
              height_ratios = [1,1],
              hspace=0.2,
              wspace=0.01)
    

    # Set Default Font properties
    font_header = FontProperties()
    font_header.set_size(8.)
    font_axes = FontProperties()
    font_axes.set_size(6.5)
    tick_fontsize = 6.5
    labelpad = -1
    

    # &&&&&&&&&&&&&&&&&&&&
    # SPEC2D plot prep:
    
            
    # Add 2D spectrum axis:
    ax2 = self.fig.add_subplot(gs[1,0])
    ax2.set_axis_off()
    
    # Read in data from files
    spec2d, spec2d_hdr = read_spec2d(self.query_info['spec2d_file_'+band.lower()])
    
    
    lamdelt = spec2d_hdr['cdelt1']
    lam0 = spec2d_hdr['crval1'] - ((spec2d_hdr['crpix1']-1)*spec2d_hdr['cdelt1'])
    lamend = lam0+lamdelt*(np.shape(spec2d)[1]-1)
    spec2d_x = np.linspace(lam0, lamend, num=np.shape(spec2d)[1])/1.e4   # plotting um
              
    # In the interest of plotting, trim all ranges where the columns are full 
    #   of nans, or are all zero.
    # Need to check left and right
    left_inds = np.array([0,0])
    right_inds = np.array([np.shape(spec2d)[1]-1, np.shape(spec2d)[1]-1])
    
    # Keep columns left_inds[1] to right_inds[0]-1, 
    #   ie index as [left_inds[1], right_inds[0]]
    
    l_flag, r_flag = 0, 0
    li, ri = 0, np.shape(spec2d)[1]-1
    
    while l_flag == 0:
        # Check finite:
        if (np.all(np.isfinite(spec2d[:,li])) == False) or \
            (spec2d[:,li].min() == 0 and spec2d[:,li].max() == 0):
            li += 1
        else:
            left_inds[1] = li
            l_flag = 1
            
    while r_flag == 0:
        # Check finite:
        if (np.all(np.isfinite(spec2d[:,ri])) == False) or \
            (spec2d[:,ri].min() == 0 and spec2d[:,ri].max() == 0):
            ri -= 1
        else:
            right_inds[0] = ri+1
            r_flag = 1
            
    spec2d = spec2d[:,left_inds[1]:right_inds[0]]
    spec2d_x = spec2d_x[left_inds[1]:right_inds[0]]
    
    
    # &&&&&&&&&&&&&&&&&&&&
    # SPEC1D plot:
  
    # Add 1D spectrum axis:
    ax, spec1d_flux, spec1d_hdr, spec1d_light_profile = plot_1d(self, gs, band, 
                    font_header, font_axes, 
                    labelpad, tick_fontsize,
                    left_inds, right_inds,
                    cutoff=cutoff)
    


    # &&&&&&&&&&&&&&&&&&&&
    # SPEC2D plot:
    
    if spec2d is not None:
        range_spec = spec2d[np.isfinite(spec2d)].copy()
        range_spec.sort()
        ax2.imshow(spec2d, cmap=cm.gray, \
              vmin = range_spec[np.int(np.round(frac_spec*len(range_spec)))], \
              vmax = range_spec[np.int(np.round((1.-frac_spec)*len(range_spec)))], \
              interpolation='None', origin='lower')
              
        ax2.format_coord = make_format_ax2(ax2, spec2d_hdr, left_inds[1])
      
        xlim = ax2.get_xlim()
        ylim = ax2.get_ylim()

        plot_lines(ax2, self.z, 
                np.array(range(np.shape(spec2d)[1])), spec2d_x, 
                ls='-', flag_2d=True, quiescent_lines=self.quilines_cb.isChecked())

                
        if spec1d_hdr is not None:        
            plot_spatial_pos(ax2, spec1d_hdr['ypos'], ls='-', length=0.08)

        ax2.set_xlim(xlim)
        ax2.set_ylim(ylim)

        range_spec = None

    ## spec2d_hdr contains PA, position offset, pix_scale, etc etc!!!


    # &&&&&&&&&&&&&&&&&&&&
    # Thumbnail + slit plot:
    ax3 = self.fig.add_subplot(gs[0,1])
    ax3.set_axis_off()
    
    
    # WFC3 pixel scale is ~0.06"/pix
    
    if pstamp is not None:
        range_spec = pstamp[np.isfinite(pstamp)].copy()
        range_spec.sort()
        ax3.imshow(pstamp, cmap=cm.gray, \
                vmin = range_spec[np.int(np.round(frac_pstamp*len(range_spec)))], \
                vmax = range_spec[np.int(np.round((1.-frac_pstamp)*len(range_spec)))], \
                interpolation='None', origin='lower')
            
        # Angle btween 3DHST and MOSFIRE slit PA- 
        angle = angle_offset(self.maskname, self.obj_id, 
                    field=self.field, 
                    mask_PA=spec2d_hdr['PA'], 
                    pstamp_hdr=pstamp_hdr, vers=tdhst_vers)   # Decimal_degrees
        
        if message:        
            print('Mask PA={}'.format(spec2d_hdr['PA'])) 
            print(angle)
          
        # Setup values     
        # Assume angle already is slit angle 
        slit_angle = angle    # PA for MOSFIRE slits
        sci_angle = angle -4. + 0.22   # PA for MOSFIRE science detector, not to slit.
        d2r = np.pi/180.            
        slit_len = np.shape(spec2d)[0]*spec2d_hdr['pscale']   # arcsec
        slit_wid = 0.7      # arcsec -- can you get this from the headers?
    
        pscale_3dhst = 0.06  # arcsec -- taken from Brammer+11
        pscale_mosfire = spec2d_hdr['pscale']
        
        xlim = ax3.get_xlim()
        ylim = ax3.get_ylim()
        x0 = np.average(xlim)
        y0 = np.average(ylim)
        
        
        # Offset in slit coords
        try:
            y0_off = spec2d_hdr['c_offset']/pscale_3dhst
        except:
            # Someone doesn't have the updated header version of 2D: fall back to 
            #   raw data offset.
            y0_off = spec2d_hdr['offset']/pscale_3dhst
        
        y0 -= y0_off
        
        
        ##############
        # Corner coords: slit rectangle
        off_angle = 4.-0.22   # exaggerate for test. really: 4.-0.22
        y_shear = slit_wid/pscale_3dhst*np.tan(off_angle*d2r)
        
        pos_11 = np.array([x0-0.5*slit_wid/pscale_3dhst, y0-0.5*slit_len/pscale_3dhst])
        pos_12 = np.array([x0-0.5*slit_wid/pscale_3dhst, y0+0.5*slit_len/pscale_3dhst])
        pos_21 = np.array([x0+0.5*slit_wid/pscale_3dhst, y0-0.5*slit_len/pscale_3dhst])
        pos_22 = np.array([x0+0.5*slit_wid/pscale_3dhst, y0+0.5*slit_len/pscale_3dhst])
        
        # Modify BL, TR corner y coords: shear
        pos_11[1] += y_shear
        pos_22[1] -= y_shear
        
        rect_sci_x, rect_sci_y = rot_corner_coords([pos_11,pos_21,pos_22,pos_12,pos_11], 
                slit_angle*d2r, x0=x0, y0=y0+y0_off)
                
        ax3.plot(rect_sci_x, rect_sci_y, lw=1, ls='-', c='lime')        
        ############
                
        ###################################################################
        # Overplot circles for objects within the field of view:
        
        # If the tdhst_cat is found:
        if tdhst_cat is not None:
            pad_arcsec = 1. # 2.
            # Define region with 1" padding around slit area, for plotting object IDs.
            rect_padded_x, rect_padded_y = padded_region([pos_11,pos_21,pos_22,pos_12,pos_11], 
                    slit_angle*d2r, x0=x0, y0=y0+y0_off, pad=pad_arcsec, pscale_3dhst=pscale_3dhst)
        
            # Get info for primary object, if the 1D spectra exist:
            try:
                prim_y_pos = get_primary_y_pos(self, band)
                main_y_pos = spec1d_hdr['ypos']
            except:
                prim_y_pos = -1
                main_y_pos = -1
        
            w = WCS(pstamp_hdr)
            
            
            main_id = self.obj_id
        
            plot_detections_in_stamp(self, ax3, ax2, tdhst_cat, w, 
                         main_id, main_y_pos, prim_y_pos, slit_angle, 
                        pscale_ratio=pscale_mosfire/pscale_3dhst, 
                        x0=x0, y0=y0+y0_off, 
                        rect_pad_x=rect_padded_x, rect_pad_y=rect_padded_y,
                        band=band)
        ###################################################################
        
        ax3.set_xlim(xlim)
        ax3.set_ylim(ylim)
        ##########
    

    # &&&&&&&&&&&&&&&&&&&&
    # Spatial profile plot:
    if spec1d_flux is not None:
        ax4 = self.fig.add_subplot(gs[1,1])
    
        # Light profile in spec1d_light_profile
        #Get spec2d aspect ratio:
        h_2d, w_2d = np.shape(spec2d)
        ax_ratio = np.float(h_2d)/np.float(w_2d)
            
        ax2_pos = ax2.get_position()
        ax3_pos = ax3.get_position()
        ax2_ratio = np.float(ax2_pos.bounds[3])/np.float(ax2_pos.bounds[2])
            
        scale = ax_ratio/ax2_ratio*1.35 #*1.15  #*1.65
        diff = (ax2_pos.bounds[3]*(1-scale))
            
        rect = [ax3_pos.bounds[0], ax2_pos.bounds[1]+diff/2., 
                ax3_pos.bounds[2], ax2_pos.bounds[3]*scale]
            
            
        ax4.set_position(rect)
        
        spatial_y = np.array(range(len(spec1d_light_profile)))  
        profile = spec1d_light_profile.copy()
        ax4.plot(profile, spatial_y, 'b-')
        ax4.set_ylim([spatial_y.min(), spatial_y.max()])
    
        ax4.get_xaxis().set_ticks([])
        ax4.get_yaxis().set_ticks([])
        
    
    return None
Example #58
0
    def plot(self) -> matplotlib.figure.Figure:
        """Plot temperature history of adaptive simulated annealing."""
        # Code adjusted based on:
        #    https://matplotlib.org/3.1.1/gallery/ticks_and_spines/multiple_yaxis_with_spines.html

        if self._temperature_history is None:
            raise NoHistoryKept("No history datapoints kept")

        x = [i for i in range(len(self._temperature_history))]
        # Top rated candidate was chosen.
        y1 = [i[0] if i[1] is True else None for i in self._temperature_history]
        # A neighbour candidate was chosen.
        y2 = [i[0] if i[1] is False else None for i in self._temperature_history]
        # Acceptance probability - as the probability in 0 - 1, lets make it larger - scale to temperature size.
        y3 = [i[2] for i in self._temperature_history]
        # Number of products.
        y4 = [i[3] for i in self._temperature_history]

        fig, host = plt.subplots()
        fig.subplots_adjust(right=0.75)

        par1 = host.twinx()
        par2 = host.twinx()

        # Offset the right spine of par1 and par2. The ticks and label have already been
        # placed on the right by twinx above.
        par1.spines["right"].set_position(("axes", 1.050))
        par2.spines["right"].set_position(("axes", 1.225))

        # Having been created by twinx, par1 par2 have their frame off, so the line of its
        # detached spine is invisible. First, activate the frame but make the patch
        # and spines invisible.
        self._make_patch_spines_invisible(par1)
        self._make_patch_spines_invisible(par2)

        # Second, show the right spine.
        par1.spines["right"].set_visible(True)
        par2.spines["right"].set_visible(True)
        host.spines["right"].set_visible(False)
        host.spines["top"].set_visible(False)

        host.plot(x, y1, ".g", label="Expansion of a highest rated candidate")
        host.plot(x, y2, ",r", label="Expansion of a neighbour candidate")
        (p3,) = par1.plot(x, y3, ",b", label="Acceptance probability for a neighbour candidate")
        (p4,) = par2.plot(x, y4, ",y", label="Number of products produced in the pipeline")

        host.set_xlabel("iteration")
        host.set_ylabel("temperature")
        par1.set_ylabel("acceptance probability")
        par2.set_ylabel("product count")

        host.yaxis.label.set_color("black")
        par1.yaxis.label.set_color(p3.get_color())
        par2.yaxis.label.set_color(p4.get_color())

        tkw = dict(size=4, width=1.5)
        host.tick_params(axis="y", colors="black", **tkw)
        par1.tick_params(axis="y", colors=p3.get_color(), **tkw)
        par2.tick_params(axis="y", colors=p4.get_color(), **tkw)
        host.tick_params(axis="x", **tkw)

        font_prop = FontProperties()
        font_prop.set_size("small")
        fig.legend(
            loc="upper center",
            bbox_to_anchor=(0.50, 1.00),
            ncol=2,
            fancybox=True,
            shadow=True,
            prop=font_prop,
        )
        return fig
def main(training_conf_dir):
    with open(join(training_conf_dir, "conf.yaml")) as f:
        conf = yaml.safe_load(f)
    training_dir = conf["training_dir"]
    color = None
    for hue_bin in conf["hue_bins"]:
        name = hue_bin["name"]
        if color != None:
            print ("Number of colors has to be 1 in this experiment. Exiting")
            exit(1)
        color = []
        for r in hue_bin["ranges"]:
            color.append((r["start"], r["end"]))

    executor = ProcessPoolExecutor(max_workers=8)
    obj_frames = {}
    vids = [d for d in listdir(training_dir) if isdir(join(training_dir, d))]
    futures = []
    for vid in vids:
        vid_dir = join(training_dir, vid)
        bin_file = [join(vid_dir, f) for f in listdir(vid_dir) if isfile(join(vid_dir, f)) and f.endswith(".bin")][0]

        future = executor.submit(extract_per_vid_hfs, bin_file, color, vid)

        futures.append(future)

        uniq_obj_file = join(join(training_dir, vid), "unique_objs_per_frame.txt")
        if not isfile(uniq_obj_file):
            continue
        obj_frames[vid] = object_based_metrics_calc.get_obj_frames(uniq_obj_file)

    dfs = []
    hf_map = {}
    max_hf = None
    for f in futures:
        df, hfs, vid = f.result()
        hf_map[vid] = hfs
        dfs.append(df)
        M = max([hf for (hf, l) in hfs])
        if max_hf == None or M> max_hf:
            max_hf= M

    df = pd.concat(dfs, ignore_index=True)

    fontsize=20
    fontP = FontProperties()
    fontP.set_size(fontsize)

    df.loc[df.label == False, "label"] = "-ve"
    df.loc[df.label == True, "label"] = "+ve"
    num_vids = len(df["vid"].unique())

    plt.close()
    fig, ax = plt.subplots(figsize=(8,4))
    sns.stripplot(data=df, x="vid", y="hf", hue="label", dodge=True, ax=ax)
    ax.set_xlabel("Video file")
    ax.set_ylabel("Hue Fraction")
    ax.grid()
    fig.savefig("hf_stripplot.png", bbox_inches="tight")
    plt.close()
    fig, ax = plt.subplots(figsize=(8,4))
    sns.boxplot(data=df, x="vid", y="hf", hue="label", ax=ax)
    ax.set_xlabel("Video File", fontsize=fontsize)
    ax.set_ylabel("Hue Fraction", fontsize=fontsize)
    ax.grid()
    ax.set_xticklabels(range(1, num_vids+1))
    ax.tick_params(axis='both', which='major', labelsize=fontsize)
    legend = ax.legend(fancybox=True,shadow=False,title='Frame label', prop=fontP, ncol=2)
    plt.setp(legend.get_title(),fontsize=fontsize)
    fig.savefig("hf_catplot.png", bbox_inches="tight")
    
    num_points = 100
    step = max_hf/num_points
    X = []
    FP = []
    FN = []

    obj_det_rates = []
    qors = []
    frame_drops = []

    for idx in range(num_points):
        hf_threshold = idx*step
        #fp, fn = compute_fp_fn(hf_map, hf_threshold)
        obj_det_rate, frame_drop_rate, qor = compute_qor(hf_map, obj_frames, hf_threshold)
        X.append(hf_threshold)
        #FP.append(fp)
        #FN.append(fn)
        frame_drops.append(frame_drop_rate)
        qors.append(qor)
        obj_det_rates.append(obj_det_rate)
    plt.close()
    fig, ax = plt.subplots(figsize=(8,4))
    #ax.plot(X, FP, label="FP")
    #ax.plot(X, FN, label="FN")
    #ax.plot(X, obj_det_rates, label="Obj. Detn. Rate")
    ax.plot(X, qors, label="Per-Object QoR")
    ax.plot(X, frame_drops, label="Frame Drop Rate")
    ax.set_xlabel("Hue Fraction threshold", fontsize=fontsize)
    ax.tick_params(axis='both', which='major', labelsize=fontsize)
    legend = ax.legend(fancybox=True,shadow=False, prop=fontP)

    ax.grid()
    fig.savefig("hue_fp_np.png", bbox_inches="tight")
                meas[run].mean_veh[k], 2)
            error_distance[k][run] = np.sum(error_square[k][run], axis=0)
    for l in range(n_v):
        error[l] = np.mean(error_square[l], axis=0)
        error_mean_norm[l] = np.sqrt(np.mean(error_distance[l], axis=0))

    with open(
            '/home/tomek/TheTitans/ICP/Pickles/errorKalman' + str(n_v) + '_' +
            str(n_f) + '_' + str(meas[0].vehicle(0, 0).get_cov()[0, 0]) + '_' +
            str(meas[0].vehicle(1, 0).get_cov()[0, 0]) + '_' +
            str(meas[0].feature(0, 0, 0).get_cov()[0, 0]) + '_' + str(runs) +
            '.pickle', 'wb') as output:
        pickle.dump(error_mean_norm, output)

    fontprop = FontProperties()
    fontprop.set_size('small')

    plt.figure(1, figsize=(9, 5))
    err1 = plt.subplot(211)
    plt.plot(error[0][0, :], label='Square error in x')
    plt.plot(error[0][1, :], label='Square error in y')
    plt.plot(error_mean_norm[0], label='Mean distance error')
    plt.title('The RMSE for vehicle 1')
    plt.xlabel('Time')
    plt.ylabel('RMSE [m]')
    plt.subplots_adjust(hspace=0.36)
    err1.legend(ncol=3, prop=fontprop)
    err1.set_ylim([
        err1.get_ylim()[0],
        err1.get_ylim()[0] + (err1.get_ylim()[1] - err1.get_ylim()[0]) * 1.15
    ])