Ejemplo n.º 1
0
    def __init__(self, fsize, axrect, figure, axes):
        """Initialize PlotMPL class"""
        import matplotlib.figure

        self._plot_valid = True
        if figure is None:
            if not iterable(fsize):
                fsize = (fsize, fsize)
            self.figure = matplotlib.figure.Figure(figsize=fsize, frameon=True)
        else:
            figure.set_size_inches(fsize)
            self.figure = figure
        if axes is None:
            self._create_axes(axrect)
        else:
            axes.cla()
            axes.set_position(axrect)
            self.axes = axes
        canvas_classes = self._set_canvas()
        self.canvas = canvas_classes[0](self.figure)
        if len(canvas_classes) > 1:
            self.manager = canvas_classes[1](self.canvas, 1)
        for which in ["major", "minor"]:
            for axis in "xy":
                self.axes.tick_params(which=which,
                                      axis=axis,
                                      direction="in",
                                      top=True,
                                      right=True)
Ejemplo n.º 2
0
def setup_viz(state):
    """Setup visualization."""

    import matplotlib
    import matplotlib.figure
    import matplotlib.backends.backend_tkagg
    import Tkinter
    import threading

    viz = {}

    # Initialise Tk ...
    figure = matplotlib.figure.Figure()
    figure.set_size_inches((8, 6))

    viz['axes1'] = figure.add_subplot(311)
    viz['axes2'] = figure.add_subplot(312)
    viz['axes3'] = figure.add_subplot(313)

    viz['tk'] = Tkinter.Tk()
    viz['canvas'] = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(
        figure, master=viz['tk'])
    viz['canvas'].get_tk_widget().pack(expand=True, fill=Tkinter.BOTH)

    return viz
Ejemplo n.º 3
0
    def __init__(self, fsize, axrect, figure, axes):
        """Initialize PlotMPL class"""
        import matplotlib.figure

        self._plot_valid = True
        if figure is None:
            if not is_sequence(fsize):
                fsize = (fsize, fsize)
            self.figure = matplotlib.figure.Figure(figsize=fsize, frameon=True)
        else:
            figure.set_size_inches(fsize)
            self.figure = figure
        if axes is None:
            self._create_axes(axrect)
        else:
            axes.cla()
            axes.set_position(axrect)
            self.axes = axes
        self.interactivity = get_interactivity()

        figure_canvas, figure_manager = self._get_canvas_classes()
        self.canvas = figure_canvas(self.figure)
        if figure_manager is not None:
            self.manager = figure_manager(self.canvas, 1)

        self.axes.tick_params(which="both",
                              axis="both",
                              direction="in",
                              top=True,
                              right=True)
Ejemplo n.º 4
0
def changeSize(figure, factor):
    global canvas, mplCanvas, interior, interior_id, frame, cwid
    oldSize = figure.get_size_inches()
    print("old size is", oldSize)
    figure.set_size_inches([factor * s for s in oldSize])
    wi, hi = [i * figure.dpi for i in figure.get_size_inches()]
    print("new size is", figure.get_size_inches())
    print("new size pixels: ", wi, hi)
    mplCanvas.config(width=wi, height=hi)
    canvas.itemconfigure(cwid, width=wi, height=hi)
    canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),
                  width=200,
                  height=200)

    #figure.tight_layout() # matplotlib > 1.1.1
    #figure.subplots_adjust(left=0.2, bottom=0.15, top=0.86)
    figure.canvas.draw()
	def __init__(self, 
			figure = None, 
			left = 0.2, bottom = 0.2, width = 0.6, height = 0.6,
			axes = None,
			polar = None,
			autoscaling = None):
		"""FIGURE is the matplotlib.figure.Figure instance where to act on.
		AXES is optionally an existing axes instance.  If AXES is not given,
		a new axes instance will be created, either a cartesian, or a polar if
		POLAR is True.  Autoscaling will be turned on by default, if not
		overridded by AUTOSCALING.  If FIGURE is not given, it will be created
		and be initialised to be held and of size (1, 1) inches."""
	
		if autoscaling is None:
			autoscaling = True

		if figure is None:
			figure = matplotlib.figure.Figure(frameon = False)
			figure.hold(True)
			figure.set_size_inches(1, 1)

		# Initialise attributes ...

		self.layers = []
		self.drawn_layers = []
		self.needs_reset = False

		self.figure = figure
		
		if axes is None:
			# Create a new axes instance.
			self.axes = self.figure.add_axes(
					(left, bottom, width, height),
					polar = polar)

		else:
			# Take over the axes.
			self.axes = axes

		# Initialise the title etc. to some values.
		self.title = None
		self.xlabel = None
		self.ylabel = None
		
		# Turn autoscaling on.
		self.set_autoscale_on(autoscaling)
Ejemplo n.º 6
0
 def __init__(self, fsize, axrect, figure, axes):
     """Initialize PlotMPL class"""
     import matplotlib.figure
     from ._mpl_imports import FigureCanvasAgg
     self._plot_valid = True
     if figure is None:
         self.figure = matplotlib.figure.Figure(figsize=fsize, frameon=True)
     else:
         figure.set_size_inches(fsize)
         self.figure = figure
     if axes is None:
         self.axes = self.figure.add_axes(axrect)
     else:
         axes.cla()
         axes.set_position(axrect)
         self.axes = axes
     self.canvas = FigureCanvasAgg(self.figure)
     for which in ['major', 'minor']:
         for axis in 'xy':
             self.axes.tick_params(which=which,
                                   axis=axis,
                                   direction='in',
                                   top=True,
                                   right=True)
Ejemplo n.º 7
0
def drawSVMParaFirgure(xList, yList):
	'''
	#here's our data to plot, all normal Python lists
	x = [1, 2, 3, 4, 5]
	y = [0.1, 0.2, 0.3, 0.4, 0.5]

	intensity = [5, 10, 15, 20, 25,30, 35, 40, 45, 50,55, 60, 65, 70, 75,80, 85, 90, 95, 100,105, .01, 115, 120, 125]

	#setup the 2D grid with Numpy
	x, y = np.meshgrid(x, y)

	#convert intensity (list of lists) to a numpy array for plotting
	intensity = np.array(intensity).reshape((5, 5))
	print(intensity)

	#now just plug the data into pcolormesh, it's that easy!
	plt.pcolormesh(x, y, intensity)
	plt.colorbar() #need a colorbar to show the intensity scale
	plt.show() #boom	
	'''
	gamma = 1e-9*4.5
	gammaList = [ gamma*(10**powE) for powE in range(10)]
	
	C = 0.00001
	CList = [ C*(10**powE) for powE in range(10)]
	
	print(gammaList)
	print(CList)
	
	resultList = []
	scoreList = []
	decision_function = 'ovr'
	for C in CList:
		for gamma in gammaList:
			clf_rbf = svm.SVC(decision_function_shape=decision_function, 	C=C, kernel='rbf',  			gamma=gamma)

			#cross validation 
			#print("rbf cross validation")
			score_rbf = cross_validation.cross_val_score(clf_rbf, xList, yList, cv=3)
			mean = score_rbf.mean()	
			resultList.append({'C':C, 'gamme':gamma, 'score':mean})
			scoreList.append(mean)
	scoreList = np.array(scoreList)
	
	maxScore = 0
	maxResult = []
	for result in resultList:
		score = result['score']
		if maxScore < score:
			maxScore = score
			maxResult = result
	print (maxScore, maxResult)
	
	x = gammaList
	y = CList
	
	x = range(len(gammaList)+1)
	y = range(len(CList)+1)
	intensity = scoreList.reshape((len(gammaList), len(CList)))
	
	#print(x)
	#print(y)
	#print(intensity)
	
	#f1 = scoreList.reshape((6, 6))
	#setup the 2D grid with Numpy
	x, y = np.meshgrid(x, y)

	plt.pcolormesh(x, y, intensity)
	plt.colorbar() #need a colorbar to show the intensity scale
	#plt.show() #boom	
	
	fig = matplotlib.pyplot.gcf()
	fig.set_size_inches(10.5, 8.5)
	fig.savefig("SVM_C_gamma.png", dpi=100)
Ejemplo n.º 8
0
def plot_path(path, path2=None, path3=None, title="", reward=None, x_label=None, y_label=None, waypoint_centers=(),
              highlight_waypoint_index=None, radii=(0, 0), linewidth=3):
    assert len(path[0]) == 2

    if reward is not None:
        title += " | Total Reward: {0:.2f}".format(reward)
    title += " | Steps: " + str(len(path) - 1)

    # get x's and y's
    x = [s[0] for s in path]
    y = [s[1] for s in path]
    # color map variables to configure a gradient along the trajectory
    color_num_scale = np.linspace(0, len(path), len(path))
    cmap = truncate_colormap(plt.get_cmap('gnuplot2_r'), minval=.1, maxval=.9)
    norm = plt.Normalize(0, len(path))
    # draw trajectory
    line_collection = make_line_collection(x, y, color_num_scale, cmap=cmap, norm=norm, linewidth=linewidth)
    line_collection2 = None
    line_collection3 = None
    cmap2 = None
    norm2 = None
    if path2:
        # get x's and y's
        x2 = [s[0] for s in path2]
        y2 = [s[1] for s in path2]
        # color map variables to configure a gradient along the trajectory
        color_num_scale2 = np.linspace(0, len(path2), len(path2))
        cmap2 = truncate_colormap(plt.get_cmap('cubehelix_r'), minval=.1, maxval=.8)
        norm2 = plt.Normalize(0, len(path2))
        # draw trajectory
        line_collection2 = make_line_collection(x2, y2, color_num_scale2, cmap=cmap2, norm=norm2, linewidth=linewidth)
        x += x2
        y += y2

        figure, (axis0, axis1, axis2) = plt.subplots(1, 3, gridspec_kw={
            'width_ratios': [24, 1,
                             1]})  # type: (matplotlib.figure.Figure, (matplotlib.axes.Axes, matplotlib.axes.Axes))
        cb2 = matplotlib.colorbar.ColorbarBase(axis2, cmap=cmap2,
                                               norm=norm2,
                                               orientation='vertical')
        cb2.set_label('Step')
        figure.set_size_inches(7.5, 5.15, forward=True)
    else:
        figure, (axis0, axis1) = plt.subplots(1, 2, gridspec_kw={
            'width_ratios': [12, 1]})  # type: (object, (matplotlib.axes.Axes, matplotlib.axes.Axes))

    if path3 is not None:
        # get x's and y's
        x3 = [s[0] for s in path3]
        y3 = [s[1] for s in path3]
        # color map variables to configure a gradient along the trajectory
        color_num_scale3 = np.linspace(0, len(path3), len(path3))
        cmap3 = truncate_colormap(plt.get_cmap('copper_r'), minval=.05, maxval=.5)
        norm3 = plt.Normalize(0, len(path3))
        # draw trajectory
        line_collection3 = make_line_collection(x3, y3, color_num_scale3, cmap=cmap3, norm=norm3, linewidth=linewidth)

    # maybe draw waypoints along trajectory
    if waypoint_centers is not None:
        waypoint_cmap = plt.get_cmap('binary')
        waypoint_color_num_scale = np.linspace(.2, .6, len(waypoint_centers))
        waypoint_norm = plt.Normalize(0, 1.0)
        waypoint_collection = make_ellipse_collection(waypoint_centers, waypoint_color_num_scale,
                                                      x_radius=radii[0], y_radius=radii[1],
                                                      cmap=waypoint_cmap, norm=waypoint_norm)
        axis0.add_collection(waypoint_collection)

    highlight = None
    if highlight_waypoint_index is not None:
        highlight_point = waypoint_centers[highlight_waypoint_index]
        highlight = Ellipse((highlight_point[0], highlight_point[1]), radii[0] * 2, radii[1] * 2, 0,
                            color="#ff8080")
        axis0.add_patch(highlight)

    axis0.set_title(title)  # labels/titles
    axis0.set_xlabel(x_label)
    axis0.set_ylabel(y_label)
    if path2:
        axis0.add_collection(line_collection2)
    if path3 is not None:
        axis0.add_collection(line_collection3)
    axis0.add_collection(line_collection)  # add main path
    axis0.set_xlim(min(x) - radii[0], max(x) + radii[0])  # set graph view cropping thingy
    axis0.set_ylim(min(y) - radii[1], max(y) + radii[1])
    cb1 = matplotlib.colorbar.ColorbarBase(axis1, cmap=cmap,  # color bar
                                           norm=norm,
                                           orientation='vertical')
    cb1.set_label('Step')
    plt.tight_layout()

    return axis0, line_collection, line_collection2, line_collection3, highlight
def drawSVMParaFirgure(xList, yList):
    '''
	#here's our data to plot, all normal Python lists
	x = [1, 2, 3, 4, 5]
	y = [0.1, 0.2, 0.3, 0.4, 0.5]

	intensity = [5, 10, 15, 20, 25,30, 35, 40, 45, 50,55, 60, 65, 70, 75,80, 85, 90, 95, 100,105, .01, 115, 120, 125]

	#setup the 2D grid with Numpy
	x, y = np.meshgrid(x, y)

	#convert intensity (list of lists) to a numpy array for plotting
	intensity = np.array(intensity).reshape((5, 5))
	print(intensity)

	#now just plug the data into pcolormesh, it's that easy!
	plt.pcolormesh(x, y, intensity)
	plt.colorbar() #need a colorbar to show the intensity scale
	plt.show() #boom	
	'''
    gamma = 1e-9 * 4.5
    gammaList = [gamma * (10**powE) for powE in range(10)]

    C = 0.00001
    CList = [C * (10**powE) for powE in range(10)]

    print(gammaList)
    print(CList)

    resultList = []
    scoreList = []
    decision_function = 'ovr'
    for C in CList:
        for gamma in gammaList:
            clf_rbf = svm.SVC(decision_function_shape=decision_function,
                              C=C,
                              kernel='rbf',
                              gamma=gamma)

            #cross validation
            #print("rbf cross validation")
            score_rbf = cross_validation.cross_val_score(clf_rbf,
                                                         xList,
                                                         yList,
                                                         cv=3)
            mean = score_rbf.mean()
            resultList.append({'C': C, 'gamme': gamma, 'score': mean})
            scoreList.append(mean)
    scoreList = np.array(scoreList)

    maxScore = 0
    maxResult = []
    for result in resultList:
        score = result['score']
        if maxScore < score:
            maxScore = score
            maxResult = result
    print(maxScore, maxResult)

    x = gammaList
    y = CList

    x = range(len(gammaList) + 1)
    y = range(len(CList) + 1)
    intensity = scoreList.reshape((len(gammaList), len(CList)))

    #print(x)
    #print(y)
    #print(intensity)

    #f1 = scoreList.reshape((6, 6))
    #setup the 2D grid with Numpy
    x, y = np.meshgrid(x, y)

    plt.pcolormesh(x, y, intensity)
    plt.colorbar()  #need a colorbar to show the intensity scale
    #plt.show() #boom

    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(10.5, 8.5)
    fig.savefig("SVM_C_gamma.png", dpi=100)
Ejemplo n.º 10
0
    axis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda tick, position: tick / 10.0 ** scale))
    axis.labelpad -= matplotlib.rcParams["font.size"] * 0.25

def scaleLabel(label, scale):
    return "{0} / ($10^{{{1}}}$)".format(label, scale)

def nudge(text, x, y):
    text.set_transform(text.get_transform() + matplotlib.transforms.Affine2D().translate(x, y))

if __name__ == "__main__":
    
    # Pre-configure plot
    plot = Plot()
    figure = matplotlib.pyplot.figure()
    if plot.sig:
        figure.set_size_inches(plot.args.size, plot.args.size)
        grid = matplotlib.gridspec.GridSpec(4, 1)
        axes1 = figure.add_subplot(grid[0:-1, :])
        axes2 = figure.add_subplot(grid[-1, :])
    else:
        figure.set_size_inches(plot.args.size, SIZE_FACTOR * plot.args.size)
        axes1 = figure.gca()
    if plot.args.logx:
        axes1.semilogx()
    elif plot.args.logy:
        axes1.semilogy()
    elif plot.args.logxy:
        axes1.loglog()
    
    # Iterate runs
    driven = {}