def main():
    builder = Gtk.Builder()
    builder.add_objects_from_file(os.path.join(os.path.dirname(__file__),
                                               "mpl_with_glade3.glade"),
                                  ("window1", ""))
    builder.connect_signals(Window1Signals())
    window = builder.get_object("window1")
    sw = builder.get_object("scrolledwindow1")

    # Start of Matplotlib specific code
    figure = Figure(figsize=(8, 6), dpi=71)
    axis = figure.add_subplot(111)
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2*np.pi*t)
    axis.plot(t, s)

    axis.set_xlabel('time [s]')
    axis.set_ylabel('voltage [V]')

    canvas = FigureCanvas(figure)  # a Gtk.DrawingArea
    canvas.set_size_request(800, 600)
    sw.add_with_viewport(canvas)
    # End of Matplotlib specific code

    window.show_all()
    Gtk.main()
示例#2
0
文件: ui.py 项目: drmaas/embedded
 def on_clicked(self, widget, title, wid, workload):
     # run schedule
     wm = WorkloadManager(wid, workload)
     fig = wm.runAll()
     
     # create window
     win = gtk.Window()
     win.set_default_size(1024,768)
     win.set_title(title)
     
     # setup drawing area
     #sw = gtk.ScrolledWindow()
     canvas = FigureCanvas(fig)  # a Gtk.DrawingArea
     canvas.set_size_request(1024,768)
     #sw.add_with_viewport(canvas)
     vbox = gtk.VBox()
     win.add(vbox)
     #win.add(sw)
     #sw.set_border_width(10)
     vbox.pack_start(canvas, True, True, 0)
     
     # Create toolbar
     toolbar = NavigationToolbar(canvas, win)
     vbox.pack_start(toolbar, False, False, 0)
     
     win.show_all()
示例#3
0
def main():
    window = gtk.Window()
    window.set_default_size(800, 600)

    # matplotlib
    x_vec = np.arange(-10, 10, 0.01)
    y_vec = np.sin(2 * 2 * np.pi * x_vec) * 1/np.sqrt(2*np.pi) * np.exp(-(x_vec**2)/2)

    #fig = plt.figure(figsize=(8.0, 6.0), dpi=100)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x_vec, y_vec)

    # add the image to the window
    scrolled_window = gtk.ScrolledWindow()
    window.add(scrolled_window)

    canvas = FigureCanvas(fig)
    canvas.set_size_request(800, 600)             # optional...
    scrolled_window.add_with_viewport(canvas)

    # main
    window.connect("delete-event", gtk.main_quit) # ask to quit the application when the close button is clicked
    window.show_all()                             # display the window
    gtk.main()                                    # GTK+ main loop
示例#4
0
class PriceChart:
    def __init__(self, data):

        fig, axes = plt.subplots(nrows=2, ncols=1)

        data["Close"].plot(ax=axes[0])
        data["Volume"].plot(ax=axes[1])

        self.canvas = FigureCanvas(fig)
        self.canvas.set_size_request(400, 300)
示例#5
0
    def run(self):
        win = Gtk.Window()
        win.connect("delete-event", Gtk.main_quit)
        win.set_default_size(600, 400)
        win.set_title("GPlot via MatPlotLib in GTK")

        f = Figure(figsize=(6, 6), dpi=100)
        # f.add_axes([-1, -1, 2, 2])
        a = f.add_subplot(111)

        xs = []
        ys = []
        for line in self.lines:
            x = list(map(lambda i: line[i], range(0, len(line), 2)))
            y = list(map(lambda i: line[i], range(1, len(line), 2)))
            xs.extend(x)
            ys.extend(y)
            a.plot(x, y)

        for poly in self.polys:
            x = list(map(lambda i: poly[i], range(0, len(poly), 2)))
            y = list(map(lambda i: poly[i], range(1, len(poly), 2)))
            xs.extend(x)
            ys.extend(y)
            xy = []
            for i in range(len(poly) / 2):
                xy.append((poly[2 * i], poly[2 * i + 1]))
            gpoly = Polygon(xy, color=rand_color())
            a.add_patch(gpoly)

        for (x, y, r) in self.circles:
            circle = Circle((x, y), r, fill=False)
            xs.append(x - r)
            xs.append(x + r)
            ys.append(y - r)
            ys.append(y + r)
            a.add_patch(circle)

        if self.bbox is None:
            self.set_bbox(xs, ys)
        a.set_xlim(self.bbox[0:2])
        a.set_ylim(self.bbox[2:4])

        sw = Gtk.ScrolledWindow()
        win.add(sw)
        # A scrolled window border goes outside the scrollbars and viewport
        sw.set_border_width(10)

        canvas = FigureCanvas(f)  # a Gtk.DrawingArea
        canvas.set_size_request(800, 800)
        sw.add_with_viewport(canvas)
        # f.add_axes([-1, -1, 2, 2])

        win.show_all()
        Gtk.main()
示例#6
0
								class plot2d:
									def __init__(self, time, data, name):
										fig = Figure()
										self.ax = fig.gca()
										self.ax.plot(data)
										self.ax.set_title("%s vs. Time" %name)
										self.ax.set_xlabel("Time (s)")
										self.ax.set_ylabel(name)

										self.canvas = FigureCanvas(fig)
										self.canvas.set_size_request(800, 800)
示例#7
0
 def create_plot(self, yLabel, ydata):
     f = Figure(figsize=(5, 4), dpi=100)
     canvas = FigureCanvas(f)
     a = f.add_subplot(111)
     a.set_title(yLabel + ' Graph Report')
     a.set_xlabel('Day Number')
     a.set_ylabel(yLabel)
     t = np.arange(1, 9, 1)
     s = ydata
     a.plot(t, s)
     canvas.set_size_request(700, 500)
     self.graphReport.pack_start(canvas, True, True, 3)
示例#8
0
 def __init__(self):
     self.fig = Figure(figsize=(5, 4), dpi=100)
     FigureCanvas.__init__(self, self.fig)
     self.data = None  # данные графика
     self.cursor = None  # курсор
     self.plot = None  # график
     self.__markerStyle = dict(linestyle=':',
                               color='0.4',
                               markersize=10,
                               mfc="C0",
                               mec="C0")
     self.__markersDict = {}
示例#9
0
 def __init__(self, controller, plot_interval_ms=30):
     # microphone monitor
     self.controller = controller
     self.fig, self.ax, self.lines, self.data = self.prepare_monitor_fig()
     FigureCanvas.__init__(self, self.fig)  # a Gtk.DrawingArea
     self.set_size_request(100, 50)
     self.monitor_animation = FuncAnimation(self.fig,
                                            self.update_mic_monitor,
                                            interval=plot_interval_ms,
                                            blit=True)
     self.is_recording = False
     self.controller.signal_sender.connect('recording_state_changed',
                                           self.change_recording_state)
示例#10
0
    def get_plot(self, num):

        x = np.linspace(0, 5, 11)
        y = x**num

        fig = plt.figure()
        axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])

        axes.plot(x, y, color="red")

        canvas = FigureCanvas(fig)
        canvas.set_size_request(400, 300)
        return canvas
class Plot(Gtk.Frame):
    def __init__(self, sp, refs):
        Gtk.Frame.__init__(self)
        self.f = Figure()
        self.canvas = FigureCanvas(self.f)
        self.add(self.canvas)
        self.set_size_request(1024, 600)
        self.f.subplots_adjust(left=0.07, right=0.98, bottom=0.05, top=0.95,
                               hspace=0.2, wspace=0.2)
        # self.buffer = self.canvas.get_snapshot()

    def decorate(self, axis, title=None, ylab=None, legend=None):
        # font_prop = fm.FontProperties(fname='Humor-Sans-1.0.ttf', size=14)
        if title is not None:
            axis.set_title(title)  # , fontproperties=font_prop)
        if ylab is not None:
            axis.yaxis.set_label_text(ylab)  # , fontproperties=font_prop)
        if legend is not None:
            axis.legend(legend)  # , prop=font_prop)
        axis.xaxis.grid(color='k', linestyle='-', linewidth=0.2)
        axis.yaxis.grid(color='k', linestyle='-', linewidth=0.2)

    def update(self, sp, refs):
        title = [r'$\phi$', r'$\theta$', r'$\psi$']
        legend = ['Ref1', 'Ref2', 'Setpoint']
        for i in range(0, 3):
            axis = self.f.add_subplot(331 + i)
            axis.clear()
            for ref in refs:
                axis.plot(sp.time, pu.deg_of_rad(ref.euler[:, i]))
            axis.plot(sp.time, pu.deg_of_rad(sp.euler[:, i]))
            self.decorate(axis, title[i], *(('deg', legend) if i == 0 else (None, None)))

        title = [r'$p$', r'$q$', r'$r$']
        for i in range(0, 3):
            axis = self.f.add_subplot(334 + i)
            axis.clear()
            for ref in refs:
                axis.plot(sp.time, pu.deg_of_rad(ref.vel[:, i]))
            self.decorate(axis, title[i], 'deg/s' if i == 0 else None)

        title = [r'$\dot{p}$', r'$\dot{q}$', r'$\dot{r}$']
        for i in range(0, 3):
            axis = self.f.add_subplot(337 + i)
            axis.clear()
            for ref in refs:
                axis.plot(sp.time, pu.deg_of_rad(ref.accel[:, i]))
            self.decorate(axis, title[i], 'deg/s2' if i == 0 else None)

        self.canvas.draw()
示例#12
0
    def __init__(self, parent_window, dev_args, *args, **kwargs):
        super(Device, self).__init__(*args, **kwargs)

        self.btn_toggle_standby.connect('toggled', self.event_toggle_standby)
        self.btn_send_configuration.connect('clicked',
                                            self.event_send_configuration)

        self.parent_window = parent_window
        self.serial_port = dev_args['port']
        self.serial = serial.Serial(self.serial_port,
                                    baudrate=115200,
                                    timeout=0)

        self.connection_datetime = dt.datetime.now()

        self.axis_y_pressure = []
        self.axis_y_volume = []
        self.axis_x_time = []

        plt.style.use('seaborn')
        plot_figure, (ax_pressure, ax_volume) = plt.subplots(nrows=2,
                                                             ncols=1,
                                                             sharex=True)

        self.plot_figure = plot_figure
        self.plot_ax_pressure = ax_pressure
        self.plot_ax_volume = ax_volume

        self.plot_ax_volume.title.set_text('Volume (mL)')
        self.plot_ax_pressure.title.set_text('Pressure (mbars)')

        # A scrolled window border goes outside the scrollbars and viewport
        self.draw_surface.set_border_width(10)

        canvas = FigureCanvas(plot_figure)  # a Gtk.DrawingArea

        self.plot_animation = animation.FuncAnimation(
            self.plot_figure,
            func=self.loop_plot_update,
            interval=self.cte_interval_animation)

        self.draw_surface.add_with_viewport(canvas)
        self.parent_window.show_all()
        canvas.show()

        self.thread_serial_port = threading.Thread(
            target=self.loop_serial_read)
        self.thread_serial_port.daemon = True
        self.thread_serial_port.start()
示例#13
0
    def drawZones(self,shape,xvalues,yvalues,xlabel,ylabel,title,color,zones=None):
        logging.debug('>>')
        logging.debug("Type: pie | title: %s | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        self.removeVboxChildren()
        figure = Figure()
        logging.debug("Figure: %s", figure)
        axis = figure.add_subplot(111)

        labels = [_("rest")]
        colors = ["#ffffff"]
        for zone in reversed(zones):
            labels.append(zone[3])
            colors.append(zone[2])

        zone_sum = [0]*6
        for value in yvalues[0]:
            # bisection, it's faster
            if value <= zones[2][1]:
                if value <= zones[4][1]:
                    if value <= zones[4][0]:
                        zone_sum[0] += 1
                    else:
                        zone_sum[1] += 1
                else:
                    if value <= zones[3][1]:
                        zone_sum[2] += 1
                    else:
                        zone_sum[3] += 1
            else:
                if value <= zones[1][1]:
                    zone_sum[4] += 1
                else:
                    zone_sum[5] += 1

        if shape == "pie":
            self._piePlot(axis, zone_sum, colors, labels)
        elif shape == "histogram":
            self._barPlot(axis, zone_sum, colors, labels)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        canvas.show()

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        self.vbox.pack_start(canvas, True, True, 0)
        logging.debug('<<')
示例#14
0
    def drawZones(self,shape,xvalues,yvalues,xlabel,ylabel,title,color,zones=None):
        logging.debug('>>')
        logging.debug("Type: pie | title: %s | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        self.removeVboxChildren()
        figure = Figure()
        logging.debug("Figure: %s", figure)
        axis = figure.add_subplot(111)

        labels = [_("rest")]
        colors = ["#ffffff"]
        for zone in reversed(zones):
            labels.append(zone[3])
            colors.append(zone[2])

        zone_sum = [0]*6
        for value in yvalues[0]:
            # bisection, it's faster
            if value <= zones[2][1]:
                if value <= zones[4][1]:
                    if value <= zones[4][0]:
                        zone_sum[0] += 1
                    else:
                        zone_sum[1] += 1
                else:
                    if value <= zones[3][1]:
                        zone_sum[2] += 1
                    else:
                        zone_sum[3] += 1
            else:
                if value <= zones[1][1]:
                    zone_sum[4] += 1
                else:
                    zone_sum[5] += 1

        if shape == "pie":
            self._piePlot(axis, zone_sum, colors, labels)
        elif shape == "histogram":
            self._barPlot(axis, zone_sum, colors, labels)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        canvas.show()

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        self.vbox.pack_start(canvas, True, True, 0)
        logging.debug('<<')
示例#15
0
	def __init__(self, xdata, ydata, xlabel, ylabel, title):
		self.popupwin=Gtk.Window()
		self.popupwin.set_size_request(600,550)
		self.popupwin.set_position(Gtk.WindowPosition.CENTER)
		self.popupwin.set_border_width(10)
		self.xdata = xdata
		self.ydata = ydata
		vbox = Gtk.VBox()
		self.fig=Figure(dpi=100)
		self.ax  = self.fig.add_subplot(111)
		self.canvas  = FigureCanvas(self.fig)
		self.main_figure_navBar = NavigationToolbar(self.canvas, self)
		self.cursor = Cursor(self.ax, color='k', linewidth=1, useblit=True)
		self.canvas.mpl_connect("button_press_event",self.on_press)
		self.ax.set_xlabel(xlabel, fontsize = 18)
		self.ax.set_ylabel(ylabel, fontsize = 18)
		self.ax.set_title(title, fontsize = 18)
		self.ax.plot(self.xdata, self.ydata, 'b-', lw=2)
		
		self.textes = []
		self.plots  = []
		vbox.pack_start(self.main_figure_navBar, False, False, 0)
		vbox.pack_start(self.canvas, True, True, 2)
		self.popupwin.add(vbox)
		self.popupwin.connect("destroy", self.dest)
		self.popupwin.show_all()
示例#16
0
    def _createPlot(self):
        self.fig = plt.Figure(figsize=(5, 4), dpi=100)
        self.ax = self.fig.add_subplot()

        self.canvas = FigureCanvas(self.fig)  # a Gtk.DrawingArea
        self.canvas.set_size_request(800, 600)
        self.left.add(self.canvas)
示例#17
0
    def final_clicked(self, widget):

        self.grid.remove(self.label7)
        self.grid.remove(self.label8)
        self.grid.remove(self.canvas)
        f = Figure()
        ax = f.add_subplot(111)

        ax.scatter(np.arange(1,
                             len(self.gensel.scores_best) + 1, 1),
                   self.gensel.scores_best,
                   label='Best')
        ax.plot(np.arange(1,
                          len(self.gensel.scores_best) + 1, 1),
                self.gensel.scores_avg,
                label='Average')

        self.canvas = FigureCanvas(f)  # a Gtk.DrawingArea
        self.canvas.set_size_request(800, 600)
        self.grid.attach(self.canvas, 4, 0, 4, 4)

        self.gensel.scores_best.sort(reverse=True)

        self.label7 = Gtk.Label()
        self.label7.set_text("Accuracy after feature selection: {0}".format(
            self.gensel.scores_best[0]))
        self.grid.attach(self.label7, 4, 4, 4, 1)

        self.label8 = Gtk.Label()
        self.label8.set_text("Feature Subset selected: {0}".format(
            self.gensel.chromosomes_best[0]))
        self.grid.attach(self.label8, 4, 5, 4, 1)

        self.show_all()
示例#18
0
文件: img.py 项目: ke8ctn/gtknodes
    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)

        self.set_label("Image Plot")
        self.connect("node_func_clicked", self.remove)

        # create input socket
        lbl = Gtk.Label.new("Input")
        lbl.set_xalign(0.0)
        node_socket_input = self.item_add(lbl, GtkNodes.NodeSocketIO.SINK)
        node_socket_input.connect("socket_incoming", self.node_socket_incoming)

        # the compatibility key
        node_socket_input.set_key(1234)
        node_socket_input.set_rgba(get_rgba('darkturquoise'))

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(111)

        sw = Gtk.ScrolledWindow()
        sw.set_border_width(10)

        self.canvas = FigureCanvas(f)
        sw.add(self.canvas)
        sw.set_size_request(200, 200)

        self.item_add(sw, GtkNodes.NodeSocketIO.DISABLE)
        self.set_child_packing(sw, True, True, 0, Gtk.PackType.END)
示例#19
0
    def __init__(self):

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain(LANG_DOM)
        self.builder.add_from_file(UI_FILE)
        self.builder.connect_signals(self)
        self.win=self.builder.get_object('window1')
        self.graf_box=self.builder.get_object('graf_box')
        self.statusbar = self.builder.get_object('statusbar')
        self.statusbar.push(1,_('Last access: '))
        self.ui_label={}
        for label in labels:
            self.ui_label[label]=self.builder.get_object(label)

        fig = Figure()
        self.plot1 = fig.add_subplot(111)
        self.plot2 = fig.add_subplot(212)
        self.plot3 = fig.add_subplot(313)
        self.plot3.set_position([0.055,0.06,0.93,0.24])
        self.plot2.set_position([0.055,0.38,0.93,0.24])
        self.plot1.set_position([0.055,0.69,0.93,0.24])
        self.canvas = FigureCanvas(fig)
        self.graf_box.pack_start(self.canvas,True,True,0)

        self.win.show_all()
        if self.get_params():
            self.update_ui()
            GObject.timeout_add_seconds(180,self.update_ui)
示例#20
0
    def __init__(self, data, toplevel):
        """
        *Initialize with:*

        Args:
            data (GlobalData Object): Source of Data
        """
        super(PlotArea, self).__init__()
        self.toplevel = toplevel
        # GlobalData
        self.data = data
        # look_at_head: index-_bufsize:index -> the data you gonna display
        self.look_at_head = 0
        # look at present?
        self.look_at_present = True
        # number of points in buffer
        self._bufsize = int(100)
        # scrol Window Adjustments
        self.adj_scroll_hist = None
        self.axisequal = False
        #
        self.BufSizeSpinnBtn = None

        # MPL:
        # create figure
        self.figure = Figure()
        # create axes
        self.axx = self.figure.add_subplot(111)
        # set grid
        self.axx.grid(True)
        # set equal scale
        self.axx.set_aspect('auto')
        # set dynamic canvas to GTK3AGG backend
        self.canvas = FigureCanvasGTK3Agg(self.figure)
        # init plots
        self.points = {}
        self.nartist = 16
        self.nMarkers = 7
        # set the first 7 artists as Markers instead of lines
        for artist in range(self.nMarkers):
            self.points[artist] = self.axx.plot(nan, nan, 'ko')[0]
        for artist in range(self.nMarkers, self.nartist):
            self.points[artist] = self.axx.plot(nan, nan, '-')[0]

        # GTK:
        vbox = Gtk.VBox(False, 3)
        self.add(vbox)
        # Get PlotWindow and connect to figure
        self.plot_win = Gtk.Viewport()
        self.plot_win.add(self.canvas)

        self.buffer_win = Gtk.Viewport()
        vbox.pack_start(self.plot_win, True, True, 0)
        vbox.pack_start(self.buffer_win, False, True, 1)
        self._init_buffer_box()

        # ######
        # finally show
        self.canvas.show()
        self.show_all()
示例#21
0
    def __init__(self, viewport):
        self._viewport = viewport

        figure = Figure()
        self._canvas = FigureCanvas(figure)
        self._viewport.add(self._canvas)
        self._viewport.show_all()
示例#22
0
									def __init__(self, lat, lon, alt, data, name):
										fig = Figure()
										self.ax = fig.gca(projection='3d')
										s = False
										for i in range(len(sys.argv)):
											if (sys.argv[i] == "-l"):
												try:
													self.ax.plot3D(latitude, longitude, altitude, sys.argv[i+1])
												except ValueError:
													print("Colour not recognized")
												except IndexError:
													print("Please input a colour")
											elif (sys.argv[i] == "-s"):
												s = True;
												try:
													self.ax.scatter(latitude, longitude, altitude, c=data, s=int(sys.argv[i+1]))
												except IndexError:
													print("Please input a point size")
										if (s != True):
											self.ax.scatter(latitude, longitude, altitude, c=data, s=1)
										self.ax.set_title("%s Heatmap" %name)
										self.ax.set_xlabel("x (m)")
										self.ax.set_ylabel("y (m)")
										self.ax.set_zlabel("altitude (m)")
										self.ax.view_init(30, 45)

										self.canvas = FigureCanvas(fig)
										self.canvas.set_size_request(800, 800)
示例#23
0
 def __init__(self):
     self.win = Gtk.Window()
     self.win.connect("delete-event", Gtk.main_quit)
     self.win.set_default_size(720, 480)
     self.fig = Figure(figsize=(10, 10), dpi=100)
     self.ax = self.fig.add_subplot()
     self.canvas = FigureCanvas(self.fig)
     sw = Gtk.ScrolledWindow()
     sw.set_border_width(10)
     sw.add(self.canvas)
     upperside = Gtk.ButtonBox(orientation=Gtk.Orientation.VERTICAL)
     self.fill_btnbox(upperside, TIMINGS)
     lowerside = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
     self.spin = Gtk.SpinButton()
     self.spin.set_range(1,
                         2**16)  #TODO: find out how to remove upper bound
     self.spin.set_increments(1, 10)
     self.spin.set_value(self.iterc)
     self.spin.connect("value-changed", self._on_spin)
     lowerside.pack_end(self.spin, False, True, 0)
     lowerside.pack_end(Gtk.Label.new("↓Iterations↓"), False, True, 0)
     self.progr2 = Gtk.ProgressBar()
     lowerside.pack_end(self.progr2, False, True, 2)
     self.progr1 = Gtk.ProgressBar()
     lowerside.pack_end(self.progr1, False, True, 2)
     sidebar = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
     sidebar.pack_start(upperside, False, True, 10)
     sidebar.pack_start(lowerside, True, True, 2)
     self.box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
     self.box.pack_start(sidebar, False, True, 2)
     self.box.pack_start(sw, True, True, 0)
     self.win.add(self.box)
     self.win.show_all()
     self.progr1.set_opacity(0)
     self.progr2.set_opacity(0)
示例#24
0
    def __init__(self):
        super(PlotWindow, self).__init__()
        self.connect('destroy', Gtk.main_quit)

        self.box = Gtk.Box(spacing=6, orientation=Gtk.Orientation(1))
        self.add(self.box)

        self.switch = Gtk.Switch()
        self.switch.connect("notify::active", self.on_switch_toggled)
        self.switch.set_active(False)
        self.box.pack_start(self.switch, True, True, 0)

        self.progress = Gtk.ProgressBar(show_text=True)
        self.box.pack_start(self.progress, True, True, 0)

        # global line, ax, canvas
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_xlim(0, 30)
        self.ax.set_ylim([0, 255])
        self.ax.set_autoscale_on(False)
        self.data = []
        self.l_data, = self.ax.plot([], self.data, label='MagY')
        self.ax.legend()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(800, 600)
        self.canvas.show()
        self.box.pack_start(self.canvas, True, True, 0)
        # self.line, = self.ax.plot([1, 2, 3], [1, 2, 10])

        port = '/dev/ttyACM0'
        baud = 9600
        self.arduino = ArdTest(self, port, baud)
示例#25
0
 def __init__(self, profile):
     self.profile = profile
     self.builder = Gtk.Builder()
     prog_path = Path(__file__).parent
     self.builder.add_from_file(str(prog_path / 'ui.glade'))
     self.builder.connect_signals(self)
     for obj in self.builder.get_objects():
         try:
             setattr(self, Gtk.Buildable.get_name(obj), obj)
         except:
             pass
     self.f = Figure()
     self.canvas = FigureCanvas(self.f)
     self.figure_holder.pack_start(self.canvas, True, True, 5)
     self.profile_data_x = [0]
     self.profile_data_y = [25]
     for (rate, target, time) in self.profile:
         t = (target - self.profile_data_y[-1]) / rate
         self.profile_data_x.append(self.profile_data_x[-1] + t)
         self.profile_data_y.append(target)
         self.profile_data_x.append(self.profile_data_x[-1] + time)
         self.profile_data_y.append(target)
     self.recorded_data_x = [0]
     self.recorded_data_y = [25]
     self.replot()
     self.stop_button.set_sensitive(False)
     self.start_button.set_sensitive(False)
     print(self.connect_button.get_label())
     self.main_window.show_all()
     self.oven = None
     self.running = False
     self.start_t = None
     GLib.idle_add(lambda: self.idle())
	def __init__(self, config, parent, size_request=None):
		self.config = config
		self.parent = parent
		self.figure, ax = pyplot.subplots()
		self.axes = self.figure.get_axes()
		self.canvas = FigureCanvas(self.figure)
		self.manager = None
		if size_request:
			self.canvas.set_size_request(*size_request)
		self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed)
		self.canvas.show()
		self.navigation_toolbar = NavigationToolbar(self.canvas, self.parent)
		self.navigation_toolbar.hide()
		self.popup_menu = Gtk.Menu.new()

		menu_item = Gtk.MenuItem.new_with_label('Export')
		menu_item.connect('activate', self.signal_activate_popup_menu_export)
		self.popup_menu.append(menu_item)

		menu_item = Gtk.MenuItem.new_with_label('Refresh')
		menu_item.connect('activate', lambda action: self.refresh())
		self.popup_menu.append(menu_item)

		menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar')
		menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar)
		self.popup_menu.append(menu_item)
		self.popup_menu.show_all()
示例#27
0
									def __init__(self, data, name):
										fig = Figure()
										self.ax = fig.gca()
										self.ax.boxplot(data)
										self.ax.set_title("%s" %name)

										self.canvas = FigureCanvas(fig)
										self.canvas.set_size_request(800, 800)
 def __init__(self, sp, refs):
     Gtk.Frame.__init__(self)
     self.f = Figure()
     self.canvas = FigureCanvas(self.f)
     self.add(self.canvas)
     self.set_size_request(1024, 600)
     self.f.subplots_adjust(left=0.07, right=0.98, bottom=0.05, top=0.95,
                            hspace=0.2, wspace=0.2)
示例#29
0
文件: Plot.py 项目: mkb0517/ginga
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

        self.widget = FigureCanvas(plot.get_figure())
        self.plot = plot
        self.logger = plot.logger

        self.widget.set_size_request(width, height)
        self.widget.show_all()
示例#30
0
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

        self.widget = FigureCanvas(plot.get_figure())
        self.plot = plot
        self.logger = plot.logger

        self.widget.set_size_request(width, height)
        self.widget.show_all()
示例#31
0
    def __init__(self):
        self.last_dir = os.getcwd()
        self.b = Gtk.Builder()
        gui_xml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_blob_detector_gui.xml')
        self.b.add_from_file(gui_xml_path)
        self.window = self.b.get_object("window")
        self.window.set_title('BlobDetector')

        self.f = matplotlib.figure.Figure()
        self.ax = self.f.add_subplot(111)
        self.f.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, hspace=0, wspace=0)

        self.canvas = FigureCanvas(self.f)
        self.b.get_object("alignment_img").add(self.canvas)

        grid = self.b.get_object("grid_params")

        j = 0
        self.detector_params_toggle_buttons = {}
        self.detector_params_entries = {}
        for p in detector_params_desc:
            if isinstance(p, dict):
                button = Gtk.CheckButton(label=p['name'])
                grid.attach(button, 0, j, 1, 1)
                self.detector_params_toggle_buttons[p['name']]= button
                j+=1
                for sp in p['params']:
                    label = Gtk.Label(label='{}'.format(sp))
                    label.set_justify(Gtk.Justification.LEFT)
                    grid.attach(label, 0, j, 1, 1)
                    if 0:
                        adj = Gtk.Adjustment(0, 0, 100, 5, 10, 0)
                        scale = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj)
                        grid.attach(scale, 1, j, 2, 1)
                    else:
                        entry = Gtk.Entry()
                        grid.attach(entry, 1, j, 2, 1)
                        self.detector_params_entries[sp] = entry
                    #print sp
                    j+=1
            else:
                label = Gtk.Label(label=f'{p}')  
                label.set_justify(Gtk.Justification.LEFT)
                grid.attach(label, 0, j, 1, 1)
                entry = Gtk.Entry()
                grid.attach(entry, 1, j, 2, 1)
                self.detector_params_entries[p] = entry
                j+=1

        scale = self.b.get_object("scale_gamma")
        adj_args = {'value':1, 'lower':0.1, 'upper':2., 'step_increment':0.05, 'page_increment':0.1, 'page_size':0}
        adj = Gtk.Adjustment(**adj_args)
        scale.set_adjustment(adj)

        self.image_display_mode = 'Original'
                
        self.window.show_all()
示例#32
0
文件: view.py 项目: Raiu/gkraken
def init_plot_chart(scrolled_window: Gtk.ScrolledWindow,
                    figure: Figure,
                    canvas: FigureCanvas,
                    axis: Axes) -> Any:
    axis.grid(True, linestyle=':')
    axis.margins(x=0, y=0.05)
    axis.set_facecolor('#00000000')
    axis.set_xlabel('Liquid temperature [°C]')
    axis.set_ylabel('Duty [%]')
    figure.subplots_adjust(top=1)
    canvas.set_size_request(400, 300)
    scrolled_window.add_with_viewport(canvas)
    # Returns a tuple of line objects, thus the comma
    lines = axis.plot([], [], 'o-', linewidth=3.0, markersize=10, antialiased=True)
    axis.set_ybound(lower=0, upper=105)
    axis.set_xbound(MIN_TEMP, MAX_TEMP)
    figure.canvas.draw()
    return lines
示例#33
0
	def plotOffHours(self):
		'''
		Returns a FigureCanvasGTK3Agg object that displays a graphical representation
		of self._offHours
		'''
		(t, val) = self.orderDict(self._offHours)
		t = np.array(t)
		val = np.array(val)
		
		val = val/self._STD_DAY
		
		#plt.xkcd(scale=1, length=100, randomness=2)
		f = plt.figure(figsize=(6,4), dpi=100)
		a = f.add_subplot(111)
		z = np.zeros(len(t))
		a.fill_between(t, z, val, val > 0.0, color='green', alpha=.25, interpolate=True)
		a.fill_between(t, z, val, val < 0.0, color='red', alpha=.25, interpolate=True)
		a.grid(True)
		f.autofmt_xdate()
		
		# Generate X ticks
		xticks = list()
		xtick_labels = list()
		xticks.append(t[0])
		xtick_labels.append(dt.strftime(t[0], "%b %y").decode("utf-8"))	# avoids problems with the accentuated months
		
		curr_month = t[0].month
		for d in t:
			if d.month != curr_month :
				curr_month = d.month
				xticks.append(dt(day=1,month=curr_month, year=d.year))
				xtick_labels.append(dt.strftime(d, "%b %y").decode("utf-8"))
		
		a.set_xticks(xticks)
		a.set_xticklabels(xtick_labels, fontsize=8)
		
		# Generate Y ticks
		yticks = np.arange(min(val), max(val), 2.5)
		a.set_yticks(yticks)
		
		canvas = FigureCanvas(f)  # a gtk.DrawingArea
		canvas.show()
		
		return canvas
示例#34
0
    def __init__(self, single_day_mode: bool = False):
        """
        Initialises charting and summary.

        :param single_day_mode: Set to true to render
        summary of single item(used in historic view).
        """
        self.single_day_mode = single_day_mode
        self.chart_data = []
        self.view = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.chart = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.summary = Gtk.Box(spacing=10)
        self.label = Gtk.Label()
        self.label.set_name('f_temp')

        # Dynamically create widgets.
        self.items = []
        for _ in range(1) if single_day_mode else range(5):
            item = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
            temperature = Gtk.Label()
            time = Gtk.Label()
            status = Gtk.Image()
            temperature.set_name("f_temp")
            time.set_name("f_time")

            item.pack_start(temperature, False, False, 0)
            item.pack_start(status, False, False, 0)
            item.pack_start(time, False, False, 0)
            self.items.append([status, temperature, time])
            self.summary.pack_start(item, True, True, 10)

        # Initializing and Formatting Charts
        self.fig = Figure(figsize=(5, 1), dpi=100)
        self.axis = self.fig.add_subplot(111)

        self.fig.patch.set_facecolor("None")
        self.axis.patch.set_visible(False)
        self.axis.spines['top'].set_visible(False)
        self.axis.spines['right'].set_visible(False)
        self.axis.spines['bottom'].set_visible(False)
        self.axis.spines['left'].set_visible(False)
        self.axis.get_xaxis().set_ticks([])
        self.axis.tick_params(axis='y', colors='white')

        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(500, 100)

        self.canvas.mpl_connect('motion_notify_event', self.hover)
        self.canvas.mpl_connect('axes_leave_event', self.hide_label)
        self.chart.pack_start(self.label, True, True, 0)
        self.chart.pack_start(self.canvas, True, True, 0)

        self.view.pack_start(self.chart, False, False, 20)
        self.view.pack_start(self.summary, False, False, 15)

        self._store = DataStore()
 def _init_plot_charts(self, ) -> None:
     self._chart_figure = Figure(figsize=(8, 6), dpi=72, facecolor='#00000000')
     self._chart_canvas = FigureCanvas(self._chart_figure)  # a Gtk.DrawingArea+
     self._chart_axis = self._chart_figure.add_subplot(111)
     self._chart_line, = init_plot_chart(
         self._builder.get_object('scrolled_window'),
         self._chart_figure,
         self._chart_canvas,
         self._chart_axis
     )
    def __init__(self, app):

        Gtk.Window.__init__(self, application=app)
        self.set_default_size(1200, 600)

        # ------------------------------------------------------------------

        df = pd.read_csv("TSLA.csv")

        fig = plt.figure()
        axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])

        df.plot.line(x="date", y="close", figsize=(20, 5), ax=axes)

        # ------------------------------------------------------------------
        canvas = FigureCanvas(fig)
        canvas.set_size_request(400, 300)

        self.add(canvas)
示例#37
0
 def _init_plot_charts(self,
                       fan_scrolled_window: Gtk.ScrolledWindow) -> None:
     self._fan_figure = Figure(figsize=(8, 6),
                               dpi=72,
                               facecolor='#00000000')
     self._fan_canvas = FigureCanvas(self._fan_figure)  # a Gtk.DrawingArea+
     self._fan_axis = self._fan_figure.add_subplot(111)
     self._fan_line, = init_plot_chart(fan_scrolled_window,
                                       self._fan_figure, self._fan_canvas,
                                       self._fan_axis)
示例#38
0
文件: Plot.py 项目: mkb0517/ginga
class PlotWidget(Widgets.WidgetBase):
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

        self.widget = FigureCanvas(plot.get_figure())
        self.plot = plot
        self.logger = plot.logger

        self.widget.set_size_request(width, height)
        self.widget.show_all()

    def set_plot(self, plot):
        self.plot = plot
        self.logger = plot.logger
        self.logger.debug("set_plot called")

    def configure_window(self, wd, ht):
        self.logger.debug("canvas resized to %dx%d" % (wd, ht))
        fig = self.plot.get_figure()
        fig.set_size_inches(float(wd) / fig.dpi, float(ht) / fig.dpi)
示例#39
0
    def __init__(self, model=None, parent=None):
        #View.__init__(self, model=model, parent=parent)
        if mdli.IProject.providedBy(model):
            model=None
        View.__init__(self, model=model, parent=parent)
        self.plot_options={'show-lines':True}
        self.set_axis_labels()
        #self.ui=rakeviews.Ui()
        self.ui.win=Gtk.Frame()

        #parent_ui= ui = parent.ui #gsm().getUtility(rakeints.IApplication).ui
        parent_ui= ui = gsm().getUtility(rakeints.IApplication).ui

        local=rakeviews.Ui()
        self.local=local

        self.ui.main_frame = win = self.ui.win
        win.set_shadow_type(Gtk.ShadowType.NONE)

        vbox = Gtk.VBox()
        win.add(vbox)

        fig = Figure(figsize=(5,4), dpi=120,
            subplotpars=matplotlib.figure.SubplotParams(left=0.03, right=0.96, bottom=0.03, top=0.96)
         )
        self.ui.fig = fig
        self.ui.ax = fig.add_subplot(111)
        #self.ui.ax2=self.ui.ax.twinx()
        #self.ui.ay2=self.ui.ax.twiny()

        canvas = FigureCanvas(fig)  # a Gtk.DrawingArea
        self.ui.canvas = canvas
        canvas.set_size_request(600, 400)
        vbox.pack_start(canvas, True, True, 0)
        toolbar_ = TXRFNavigationToolbar(canvas, self)

        self.ui.sb=ui.statusbar
        local.msg_id=None
        local.ctx_id=self.ui.sb.get_context_id("plotting")

        self.ui.cid = canvas.mpl_connect('button_press_event', self.on_click)
示例#40
0
 def drawDefault(self):
     logging.debug('>>')
     self.axis=self.figure.add_subplot(111)
     self.axis.set_xlabel('Yepper')
     self.axis.set_ylabel('Flabber')
     self.axis.set_title('An Empty Graph')
     self.axis.grid(True)
     self.canvas.destroy()
     self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea
     self.canvas.show()
     self.vbox.pack_start(self.canvas, True, True, 0)
     logging.debug('<<')
示例#41
0
 def drawDefault(self):
     logging.debug('>>')
     self.axis = self.figure.add_subplot(111)
     self.axis.set_xlabel('Yepper')
     self.axis.set_ylabel('Flabber')
     self.axis.set_title('An Empty Graph')
     self.axis.grid(True)
     self.canvas.destroy()
     self.canvas = FigureCanvasGTK(self.figure)  # a gtk.DrawingArea
     self.canvas.show()
     self.vbox.pack_start(self.canvas, True, True, 0)
     logging.debug('<<')
示例#42
0
class PlotWidget(Widgets.WidgetBase):

    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

        self.widget = FigureCanvas(plot.get_figure())
        self.plot = plot
        self.logger = plot.logger

        self.widget.set_size_request(width, height)
        self.widget.show_all()

    def set_plot(self, plot):
        self.plot = plot
        self.logger = plot.logger
        self.logger.debug("set_plot called")

    def configure_window(self, wd, ht):
        self.logger.debug("canvas resized to %dx%d" % (wd, ht))
        fig = self.plot.get_figure()
        fig.set_size_inches(float(wd) / fig.dpi, float(ht) / fig.dpi)
示例#43
0
    def __init__(self, model=None, parent=None):
        """
        """
        View.__init__(self, model=model, parent=parent)
        self.parent_ui=pui=gsm().getUtility(
            icc.rake.views.interfaces.IApplication
        )

        # self.ui.graph_image.clear()

        self.add_actions_to_toolbar(self.ui.ag_simulation, important_only=False)
        self.add_actions_to_menu(self.ui.ag_simulation, label="Simulation")

        frame=self.get_main_frame()
        vbox=self.ui.sim_box

        fig = Figure(figsize=(5,4), dpi=120,
            subplotpars=matplotlib.figure.SubplotParams(
                left=0.1,
                right=0.96,
                bottom=0.1,
                top=0.96)
        )

        self.ui.fig = fig
        #self.ui.ax = fig.add_subplot(111)

        canvas=FigureCanvas(fig)
        self.ui.canvas=canvas
        canvas.set_size_request(600,400)
        vbox.pack_start(canvas, True, True, 0)
        toolbar=DMENavigatorToolbar(canvas, self)

        parent.connect("project-open", self.on_project_open)
        parent.connect("project-save", self.on_project_save)

        dot_widget=self.ui.dot_widget = xdot.DotWidget()
        self.ui.graph_viewport.add(dot_widget)
        xdot_setup=xdot.DotWindowSetup(pui.ui.window, dot_widget)
        xdot_setup()
示例#44
0
class OdPredictorGui(Gtk.HBox):

    def __init__(self):
        super().__init__()
        self.controls = ControlPanel()
        self.controls.connect('new-params', self.on_new_params)

        self.fig = Figure(facecolor='#e9e9e9')
        self.axes = self.fig.add_subplot(1, 1, 1)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(300, 300)

        self.pack_start(self.controls, False, False, 0)
        self.pack_start(self.canvas, True, True, 0)

        self.on_new_params()

    def on_new_params(self, *args):
        predictor = self.controls.get_params()
        predictor.plot_time_estimate(self.axes)
        self.fig.tight_layout(pad=1.0)
        self.canvas.draw()
示例#45
0
    def testGtk(self):
        from gi.repository import Gtk

        from matplotlib.figure import Figure
        from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

        win = Gtk.Window()
        win.connect("delete-event", Gtk.main_quit )
        win.set_default_size(800,600)
        win.set_title("Embedding in GTK")

        p = Plot(self.schedule, self.executions, 300, 10, "Workoad 2")
        p.addScheduleBar()
        p.addTaskBars()
        p.addLegend()
        p.addMiscInfo()
        f = p.getFigure()

        sw = Gtk.ScrolledWindow()
        win.add (sw)

        # A scrolled window border goes outside the scrollbars and viewport
        sw.set_border_width (10)

        canvas = FigureCanvas(f)  # a Gtk.DrawingArea
        canvas.set_size_request(800,600)
        sw.add_with_viewport (canvas)
        
        win.show_all()
        Gtk.main()
        
        win2 = Gtk.Window()
        win2.connect("delete-event", Gtk.main_quit )
        win2.set_default_size(800,600)
        win2.set_title("Embedding in GTK 2")
        
        win2.show_all()
        Gtk.main()        
示例#46
0
    def __init__(self):
        super().__init__()
        self.controls = ControlPanel()
        self.controls.connect('new-params', self.on_new_params)

        self.fig = Figure(facecolor='#e9e9e9')
        self.axes = self.fig.add_subplot(1, 1, 1)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(300, 300)

        self.pack_start(self.controls, False, False, 0)
        self.pack_start(self.canvas, True, True, 0)

        self.on_new_params()
示例#47
0
文件: main.py 项目: sacovo/fraktale
    def __init__(self):
        builder = Gtk.Builder()
        builder.add_from_string(resource_string(__name__, 'gui.glade').decode())
        builder.connect_signals(self)

        self.window = builder.get_object("window")
        
        self.figure = Figure(figsize=(100,250), dpi=75)
        self.axis = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)

        self.toolbar = NavigationToolbar(self.canvas, self.window)

        imbox = builder.get_object("image_box")
        imbox.pack_start(self.toolbar, False, False, 1)
        imbox.pack_start(self.canvas, True, True, 1)
        self.progress = builder.get_object("progressbar")
        self.builder = builder
        self.exit_thread = False
        self.pen = None

        self.notebook = builder.get_object("notebook")
示例#48
0
    def __init__(self, debugger):
        """
        @type debugger: debugger.Debugger
        """
        Gtk.ScrolledWindow.__init__(self)
        self.debugger = debugger
        self.debugger.heap_manager.on_heap_change.subscribe(
            lambda heap: self._handle_heap_change(heap))
        self.debugger.on_process_state_changed.subscribe(
            lambda state, data: self._handle_process_change(state))
        self.sizes = []
        self.times = []

        figure = Figure()
        self.axis = figure.add_subplot(111)

        figure.subplots_adjust(bottom=0.3)

        self.canvas = Canvas(figure)
        self.add_with_viewport(self.canvas)

        self.heap_size = 0
        self.start_time = 0
示例#49
0
class HeapGraph(Gtk.ScrolledWindow):
    def __init__(self, debugger):
        """
        @type debugger: debugger.Debugger
        """
        Gtk.ScrolledWindow.__init__(self)
        self.debugger = debugger
        self.debugger.heap_manager.on_heap_change.subscribe(
            lambda heap: self._handle_heap_change(heap))
        self.debugger.on_process_state_changed.subscribe(
            lambda state, data: self._handle_process_change(state))
        self.sizes = []
        self.times = []

        figure = Figure()
        self.axis = figure.add_subplot(111)

        figure.subplots_adjust(bottom=0.3)

        self.canvas = Canvas(figure)
        self.add_with_viewport(self.canvas)

        self.heap_size = 0
        self.start_time = 0

    def redraw(self):
        self.axis.set_xlabel('time [s]')
        self.axis.set_ylabel('heap size [MiB]')
        self.axis.plot(self.times, self.sizes, "r")
        self.canvas.queue_draw()

    def _reset(self):
        self.sizes = []
        self.times = []
        self.heap_size = 0
        self.start_time = time.time()
        self.axis.cla()

    def _handle_process_change(self, state):
        """
        @type state: enums.ProcessState
        """
        if state == ProcessState.Launching:
            self._reset()
            self.redraw()
        elif state == ProcessState.Running:
            self._schedule_refresh()

    def _timer_tick(self):
        self.sizes.append(self.heap_size)
        self.times.append(time.time() - self.start_time)
        self.redraw()
        return self.debugger.process_state == ProcessState.Running

    def _schedule_refresh(self):
        GObject.timeout_add(1000,
                            self._timer_tick)

    def _handle_heap_change(self, heap):
        """
        @type heap: list of debugee.HeapBlock
        """
        size = 0
        for block in heap:
            size += block.size

        self.heap_size = size / 1024.0  # size in MiBs
示例#50
0
    def drawStackedBars(self,xvalues,yvalues,ylabel,title, valuesAreTime=False, colors={}):
        '''function to draw stacked bars
            xvalues needs to be a list of lists of strings, e.g. [0]["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
            yvalues needs to be a list of dicts e.g. [0]{'Kayak': {'Tue': 10.08, 'Fri': 17.579999999999998, 'Thu': 15.66, 'Sat': 30.619999999999997}, {'Run': {'Mon': 9.65, 'Sun': 15.59}}
        '''
        #TODO tidy
        logging.debug('>>')
        logging.debug("Title: %s", title)
        logging.debug("X values received: %s", xvalues)
        logging.debug("Y values received: %s", yvalues)
        self.removeVboxChildren()

        #Check how many axes to draw
        if len(xvalues) == 1: #One axis
            barWidth = 0.8
            barOffset = 0.1
        elif len(xvalues) == 2: #Twin axes
            barWidth = 0.4
            barOffset = 0.1
        else: #Error
            return

        keys = list(yvalues[0].keys()) # days of the week
        numRows = len(keys)
        numCols = len(xvalues[0])
        if numRows == 0:
            return
        width = .8
        #figure = plt.figure(figsize=(6,4), dpi=72)
        figure = plt.figure()
        logging.debug("Figure: %s", figure)
        axis = plt.subplot(111)

        ybottoms = [0] * numCols
        yheights = [0] * numCols
        inds = range(0, numCols)
        xvals = [x+barOffset for x in range(0, numCols)]
        cellText = []
        self.showGraph=False

        for k in colors:
            if colors[k]==None: colors[k]=''

        #Display first axis
        xticks = []
        for key in keys:
            logging.debug("Day of the week: %s", key)
            for ind in inds:
                ybottoms[ind] += yheights[ind]
                yheights[ind] = 0 #Zero heights
            color = "#"+colors.get(key, '')
            if len(color)<2:
                color = self.getColor(keys.index(key))
            for xvalue in xvalues[0]:
                index = xvalues[0].index(xvalue)
                if xvalue in yvalues[0][key]:
                    height = yvalues[0][key][xvalue]
                    if float(height) > 0.0:
                        self.showGraph=True
                else:
                    height = self.NEARLY_ZERO
                yheights[index] = height
            cellText.append([self.fmtTableText(x, valuesAreTime[0]) for x in yheights])
            if self.showGraph:
                axis.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color,  align='edge', label=key)
            else:   #Only zero results
                pass
        axis.set_xticklabels('' * len(xvalues[0]))
        axis.set_ylabel(ylabel[0])
        if len(xvalues) == 1:
            plt.title(title[0])
            axis.legend(loc=0)

        axis.set_xlim(0,numCols)

        logging.debug("X values first axis: %s", xvals)
        logging.debug("Y values first axis: %s", yheights)

        #Display twin axis
        if len(xvalues) == 2:
            self.showGraph=False
            ax2 = axis.twinx()
            keys = list(yvalues[1].keys())
            ybottoms = [0] * numCols
            yheights = [self.NEARLY_ZERO] * numCols
            for key in keys:
                for ind in inds:
                    ybottoms[ind] += yheights[ind]
                    yheights[ind] = 0.0 #Zero heights
                color = "#"+colors.get(key, '')
                if len(color)<2:
                    color = self.getColor(keys.index(key))
                for xvalue in xvalues[0]:
                    index = xvalues[0].index(xvalue)
                    if xvalue in yvalues[1][key]:
                        height = yvalues[1][key][xvalue]
                        if float(height) > 0.0:
                            self.showGraph=True
                    else:
                        height = self.NEARLY_ZERO
                    yheights[index] = height
                    textToAdd = self.fmtTableText(height, valuesAreTime[1])
                    if textToAdd is not ' ':
                        row = keys.index(key)
                        col = index
                        cellText[row][col] += " | %s" % (self.fmtTableText(height, valuesAreTime[1]))
                        #print "Would add %s to %s %s" % (self.fmtTableText(height, valuesAreTime[1]), index, keys.index(key))
                if self.showGraph:
                    xvals = [x+barOffset+barWidth for x in range(0, numCols)]
                    #print "ax2", xvals, yheights, ybottoms
                    ax2.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color,  align='edge', label=key)
                else:   #Only zero results
                    ax2.bar(xvals, [0]*numCols, bottom=[0]*numCols, width=barWidth, color=color,  align='edge', label=key)
                    pass
            ax2.set_xticklabels('' * len(xvalues[1]))
            ax2.set_xlim(0,numCols)
            ax2.set_ylabel(ylabel[1])
            ax2.legend(loc=0)
            plt.title("%s vs %s" %(title[0],title[1]))

        ## try to do some table stuff
        colLabels = xvalues[0]
        rowLabels = keys
        axis.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, colLabels=colLabels, loc='bottom')
        plt.subplots_adjust(left=0.15,bottom=0.08+(0.03*numRows))
        axis.grid(True)
        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        #toolbar = NavigationToolbar(canvas, self.window)
        #self.vbox.pack_start(toolbar, False, False)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')
示例#51
0
a3 = a.twinx()
a2.spines["right"].set_position(("axes", 1.2))

a2.set_ylim(-10, 80)
a3.set_ylim(-10, 80)



a2.set_ylabel('Flow rate (Q lit/min)')
a3.set_ylabel('Eng Values')
a.set_ylabel('Pump Out: P (bar) and Q (lit/min)')


scrolledwindow1.set_border_width(5)
samples_no = 1
canvas = FigureCanvas(f)  # a Gtk.DrawingArea
canvas.set_size_request(800, 450)
scrolledwindow1.add_with_viewport(canvas)
canvas.show()
if len(cfgItems) > 0:
    samples_no = smtConfig.getint('General', 'samples_no')
    if smtConfig.has_option('Output', 'folder'):
        output_folder = smtConfig.get('Output', 'folder')    
    if smtConfig.has_option('Manifold_1', 'host') and smtConfig.has_option('Manifold_1', 'port'):
        manifold_host_1 = smtConfig.get('Manifold_1', 'host')
        manifold_port_1 = smtConfig.get('Manifold_1', 'port')   
        a_low= smtConfig.getint('Manifold_1', 'low')
        a_high=smtConfig.getint('Manifold_1', 'high')
        p_low=smtConfig.getint('Manifold_1', 'p_low')
        p_high=smtConfig.getint('Manifold_1', 'p_high')
        q_low=smtConfig.getint('Manifold_1', 'q_low')
示例#52
0
class DrawArea:
    def __init__(self, vbox = None, window = None):
        logging.debug('>>')
        #self.figure = Figure(figsize=(6,4), dpi=72)
        #self.axis = self.figure.add_subplot(111)
        self.vbox = vbox
        self.window = window
        #self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea
        #self.drawDefault()
        self.NEARLY_ZERO = 0.0000000000000000000001
        logging.debug('<<')

    def stadistics(self,type,xvalues,yvalues,xlabel,ylabel,title,color=None,zones=None):
        logging.debug('>>')
        if len(xvalues[0]) < 1:
            #self.drawDefault()
            return False
        #logging.debug('xvalues: '+str(xvalues))
        #logging.debug('yvalues: '+str(yvalues))
        #logging.debug("Type: "+type+" | title: "+str(title)+" | col: "+str(color)+" | xlabel: "+str(xlabel)+" | ylabel: "+str(ylabel))
        if type == "bars":
            self.drawBars(xvalues,yvalues,xlabel,ylabel,title,color)
        elif type == "plot":
            self.drawPlot(xvalues,yvalues,xlabel,ylabel,title,color,zones)
        elif type == "pie" or type == "histogram":
            self.drawZones(type,xvalues,yvalues,xlabel,ylabel,title,color,zones)
        logging.debug('<<')

    def drawBars(self,xvalues,yvalues,xlabel,ylabel,title,color):
        logging.debug('>>')
        logging.debug("Type: bars | title: %s"" | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        self.removeVboxChildren()
        #figure = Figure(figsize=(6,4), dpi=72)
        figure = plt.figure()
        logging.debug("Figure: %s", figure)
        numCols=len(xvalues[0])
        xmod = 0.4
        self.showGraph=False
        axis = figure.add_subplot(111)
        logging.debug("Axis: %s", axis)

        if len(xvalues) == 1: #One axis
            barWidth = 0.8
            barOffset = 0.1
            logging.debug("One axis, barWidth %f, barOffset %f", barWidth, barOffset)
        elif len(xvalues) == 2: #Twin axes
            barWidth = 0.4
            barOffset = 0.1
            logging.debug("Twin axes, barWidth %f, barOffset %f", barWidth, barOffset)
        else: #Error
            logging.debug("Error: invalid number of axes" )
            return

        axis.set_xlabel(xlabel[0])
        axis.set_ylabel(ylabel[0])
        logging.debug("Labels set x: %s, y: %s", xlabel[0], ylabel[0])
        xvals = [x+barOffset for x in range(0, numCols)]
        yvals = [0] * numCols
        for i in range(0, numCols):
            yval = yvalues[0][i]
            if float(yval) > 0.0:
                self.showGraph=True
            else:
                yval = self.NEARLY_ZERO
            yvals[i] = yval
        if self.showGraph:
            logging.debug("Drawing bars")
            axis.bar(xvals, yvals, barWidth, color=color[0], align='edge')
        else:   #Only zero results
            logging.debug("No results to draw")
            pass

        axis.grid(True)
        axis.set_title("%s" %(title[0]))
        logging.debug("Setting title to: %s", title[0])
        for tl in axis.get_yticklabels():
            logging.debug("Setting ticklabel color %s", color[0])
            tl.set_color('%s' %color[0])

        if len(xvalues) == 2: #Display twin axis
            ax2 = axis.twinx()
            logging.debug("Axis 2: Twin axis: %s", ax2)
            xvals = [x+barOffset+barWidth for x in range(0, numCols)]
            for i in range(0, numCols):
                yval = yvalues[1][i]
                if float(yval) > 0.0:
                    self.showGraph=True
                else:
                    yval = self.NEARLY_ZERO
                yvals[i] = yval
            if self.showGraph:
                logging.debug("Axis 2: Drawing bars")
                ax2.bar(xvals, yvals, barWidth, color=color[1], align='edge')
                logging.debug("Axis 2: Label set y: %s", ylabel[1])
                ax2.set_ylabel(ylabel[1])
            else:   #Only zero results
                logging.debug("Axis 2: No results to draw")
                pass
            for tl in ax2.get_yticklabels():
                tl.set_color('%s' %color[1])
                logging.debug("Axis 2: Setting ticklabel color %s", color[1])
            _title = "%s vs %s" %(title[0],title[1])
            logging.debug("Axis 2: Setting title to: %s", _title)
            axis.set_title(_title)

        logging.debug("Setting x ticks")
        tickLocations = [x+0.5 for x in range(0, numCols)]
        axis.set_xticks(tickLocations)
        axis.set_xticklabels(xvalues[0])
        logging.debug("Setting x limits")
        axis.set_xlim(0, numCols)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        logging.debug("Got canvas: %s", canvas)
        canvas.show()
        logging.debug("Adding canvas to vbox")
        self.vbox.pack_start(canvas, True, True, 0)
        #toolbar = NavigationToolbar(canvas, self.window)
        #self.vbox.pack_start(toolbar, False, False)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')

    def getColor(self, x):
        colors=["b","g","r","c","m","y","k", "w"]
        if x >= len(colors):
            x = x % len(colors)
        return colors[x]

    def fmtTableText(self, x, valuesAreTime):
        if x <= 0.0001:
            return ' '
        elif valuesAreTime:
            hour = int(x)
            minutes = int((x-hour)*60)
            hourLabel = _("h")
            minLabel = _("min")
            if hour > 0:
                return "%d%s %02d%s" % (hour, hourLabel, minutes, minLabel)
            else:
                return "%02d%s" % (minutes, minLabel)
        else:
            return '%1.1f' % x

    def drawStackedBars(self,xvalues,yvalues,ylabel,title, valuesAreTime=False, colors={}):
        '''function to draw stacked bars
            xvalues needs to be a list of lists of strings, e.g. [0]["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
            yvalues needs to be a list of dicts e.g. [0]{'Kayak': {'Tue': 10.08, 'Fri': 17.579999999999998, 'Thu': 15.66, 'Sat': 30.619999999999997}, {'Run': {'Mon': 9.65, 'Sun': 15.59}}
        '''
        #TODO tidy
        logging.debug('>>')
        logging.debug("Title: %s", title)
        logging.debug("X values received: %s", xvalues)
        logging.debug("Y values received: %s", yvalues)
        self.removeVboxChildren()

        #Check how many axes to draw
        if len(xvalues) == 1: #One axis
            barWidth = 0.8
            barOffset = 0.1
        elif len(xvalues) == 2: #Twin axes
            barWidth = 0.4
            barOffset = 0.1
        else: #Error
            return

        keys = list(yvalues[0].keys()) # days of the week
        numRows = len(keys)
        numCols = len(xvalues[0])
        if numRows == 0:
            return
        width = .8
        #figure = plt.figure(figsize=(6,4), dpi=72)
        figure = plt.figure()
        logging.debug("Figure: %s", figure)
        axis = plt.subplot(111)

        ybottoms = [0] * numCols
        yheights = [0] * numCols
        inds = range(0, numCols)
        xvals = [x+barOffset for x in range(0, numCols)]
        cellText = []
        self.showGraph=False

        for k in colors:
            if colors[k]==None: colors[k]=''

        #Display first axis
        xticks = []
        for key in keys:
            logging.debug("Day of the week: %s", key)
            for ind in inds:
                ybottoms[ind] += yheights[ind]
                yheights[ind] = 0 #Zero heights
            color = "#"+colors.get(key, '')
            if len(color)<2:
                color = self.getColor(keys.index(key))
            for xvalue in xvalues[0]:
                index = xvalues[0].index(xvalue)
                if xvalue in yvalues[0][key]:
                    height = yvalues[0][key][xvalue]
                    if float(height) > 0.0:
                        self.showGraph=True
                else:
                    height = self.NEARLY_ZERO
                yheights[index] = height
            cellText.append([self.fmtTableText(x, valuesAreTime[0]) for x in yheights])
            if self.showGraph:
                axis.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color,  align='edge', label=key)
            else:   #Only zero results
                pass
        axis.set_xticklabels('' * len(xvalues[0]))
        axis.set_ylabel(ylabel[0])
        if len(xvalues) == 1:
            plt.title(title[0])
            axis.legend(loc=0)

        axis.set_xlim(0,numCols)

        logging.debug("X values first axis: %s", xvals)
        logging.debug("Y values first axis: %s", yheights)

        #Display twin axis
        if len(xvalues) == 2:
            self.showGraph=False
            ax2 = axis.twinx()
            keys = list(yvalues[1].keys())
            ybottoms = [0] * numCols
            yheights = [self.NEARLY_ZERO] * numCols
            for key in keys:
                for ind in inds:
                    ybottoms[ind] += yheights[ind]
                    yheights[ind] = 0.0 #Zero heights
                color = "#"+colors.get(key, '')
                if len(color)<2:
                    color = self.getColor(keys.index(key))
                for xvalue in xvalues[0]:
                    index = xvalues[0].index(xvalue)
                    if xvalue in yvalues[1][key]:
                        height = yvalues[1][key][xvalue]
                        if float(height) > 0.0:
                            self.showGraph=True
                    else:
                        height = self.NEARLY_ZERO
                    yheights[index] = height
                    textToAdd = self.fmtTableText(height, valuesAreTime[1])
                    if textToAdd is not ' ':
                        row = keys.index(key)
                        col = index
                        cellText[row][col] += " | %s" % (self.fmtTableText(height, valuesAreTime[1]))
                        #print "Would add %s to %s %s" % (self.fmtTableText(height, valuesAreTime[1]), index, keys.index(key))
                if self.showGraph:
                    xvals = [x+barOffset+barWidth for x in range(0, numCols)]
                    #print "ax2", xvals, yheights, ybottoms
                    ax2.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color,  align='edge', label=key)
                else:   #Only zero results
                    ax2.bar(xvals, [0]*numCols, bottom=[0]*numCols, width=barWidth, color=color,  align='edge', label=key)
                    pass
            ax2.set_xticklabels('' * len(xvalues[1]))
            ax2.set_xlim(0,numCols)
            ax2.set_ylabel(ylabel[1])
            ax2.legend(loc=0)
            plt.title("%s vs %s" %(title[0],title[1]))

        ## try to do some table stuff
        colLabels = xvalues[0]
        rowLabels = keys
        axis.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, colLabels=colLabels, loc='bottom')
        plt.subplots_adjust(left=0.15,bottom=0.08+(0.03*numRows))
        axis.grid(True)
        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        #toolbar = NavigationToolbar(canvas, self.window)
        #self.vbox.pack_start(toolbar, False, False)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')

    def drawPlot(self,xvalues,yvalues,xlabel,ylabel,title,color,zones=None,xzones=None, ylimits=None, y1_linewidth=None):
        logging.debug('>>')
        logging.debug("Type: plot | title: %s | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        logging.debug('xlabel: %s | ylabel: %s | title: %s', xlabel, ylabel, title)
        self.removeVboxChildren()
        figure = plt.Figure()
        logging.debug("Figure: %s", figure)
        #figure.clf()
        i = 0
        for value in xvalues:
            if i<1:
                logging.debug("i: %d, value: (%s) %s %s", i, value, xvalues, yvalues)
                axis = figure.add_subplot(111)
                logging.debug("Axis: %s", axis)
                line = axis.plot(xvalues[i],yvalues[i], color=color[i])
                logging.debug("Axis plotted, Line: %s", line)
                if y1_linewidth is not None:
                    line[0].set_linewidth(y1_linewidth)
                linewidth = line[0].get_linewidth()

                axis.grid(True)
                logging.debug("Axis grid on" )
                for tl in axis.get_yticklabels():
                    tl.set_color('%s' %color[i])
                logging.debug("Ticklabels color set" )
                #Draw zones on graph, eg for each lap
                if xzones is not None:
                    logging.debug("Setting xzones" )
                    for xzone in xzones:
                        if xzones.index(xzone) % 2:
                            zonecolor='b'
                        else:
                            zonecolor='g'
                        axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor)
                maxX = max(xvalues[i])
            if i>=1:
                ax2 = axis.twinx()
                logging.debug("Axis2: Axis: %s", ax2)
                ax2.plot(xvalues[i], yvalues[i], color=color[i])
                logging.debug("Axis2: plotted" )
                for tl in ax2.get_yticklabels():
                    tl.set_color('%s' %color[i])
                logging.debug("Axis2: Ticklabels color set" )
                maxXt = max(xvalues[i])
                if maxXt > maxX:
                    maxX = maxXt
            axis.set_xlabel(xlabel[i])
            logging.debug("X label set" )
            i+=1
        axis.set_xlim(0, maxX)

        if (len(xvalues)>1):
            axis.set_title("%s vs %s" %(ylabel[0],ylabel[1]))
        else:
            axis.set_title("%s" %(ylabel[0]))

        ylim_min, ylim_max = axis.get_ylim()
        if ylimits is not None:
            logging.debug("Using ylimits: %s", ylimits)
            if ylimits[0] is not None:
                ylim_min = ylimits[0]
            if ylimits[1] is not None:
                ylim_max = ylimits[1]
            axis.set_ylim(ylim_min, ylim_max)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        logging.debug("Canvas: %s", canvas)
        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        toolbar = NavigationToolbar(canvas, self.window)
        self.vbox.pack_start(toolbar, False, False, 0)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')
        return {'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth}

    def drawZones(self,shape,xvalues,yvalues,xlabel,ylabel,title,color,zones=None):
        logging.debug('>>')
        logging.debug("Type: pie | title: %s | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        self.removeVboxChildren()
        figure = Figure()
        logging.debug("Figure: %s", figure)
        axis = figure.add_subplot(111)

        labels = [_("rest")]
        colors = ["#ffffff"]
        for zone in reversed(zones):
            labels.append(zone[3])
            colors.append(zone[2])

        zone_sum = [0]*6
        for value in yvalues[0]:
            # bisection, it's faster
            if value <= zones[2][1]:
                if value <= zones[4][1]:
                    if value <= zones[4][0]:
                        zone_sum[0] += 1
                    else:
                        zone_sum[1] += 1
                else:
                    if value <= zones[3][1]:
                        zone_sum[2] += 1
                    else:
                        zone_sum[3] += 1
            else:
                if value <= zones[1][1]:
                    zone_sum[4] += 1
                else:
                    zone_sum[5] += 1

        if shape == "pie":
            self._piePlot(axis, zone_sum, colors, labels)
        elif shape == "histogram":
            self._barPlot(axis, zone_sum, colors, labels)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        canvas.show()

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        self.vbox.pack_start(canvas, True, True, 0)
        logging.debug('<<')

    def _barPlot(self, axis, zone_sum, colors, labels):
        invtotal = 100.0/sum(zone_sum)
        fracs = [i*invtotal for i in zone_sum]
        xticks = list(range(len(fracs)))

        axis.bar(xticks, fracs, color=colors, align="center")
        axis.set_xticks(xticks)
        axis.set_xticklabels(labels)
        axis.set_ylabel(_("Time in zone [%]"))

    def _piePlot(self, axis, zone_sum, colors, labels):
        labels_trunc = [l for z,l in zip(zone_sum, labels) if z > 0]
        colors_trunc = [c for z,c in zip(zone_sum, colors) if z > 0]
        zone_trunc   = [z for z in zone_sum if z > 0]
        explode      = [0]*len(zone_trunc)
        axis.pie(zone_trunc, explode=explode, labels=labels_trunc, colors=colors_trunc, autopct='%1.1f%%', shadow=True)

    def drawDefault(self):
        logging.debug('>>')
        self.axis=self.figure.add_subplot(111)
        self.axis.set_xlabel('Yepper')
        self.axis.set_ylabel('Flabber')
        self.axis.set_title('An Empty Graph')
        self.axis.grid(True)
        self.canvas.destroy()
        self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea
        self.canvas.show()
        self.vbox.pack_start(self.canvas, True, True, 0)
        logging.debug('<<')

    def fill_over(self, ax, x, y, val, color, over=True):
        """
        Plot filled x,y for all y over val
        if over = False, fill all areas < val
        """
        logging.debug('>>')
        ybase = asarray(y)-val
        crossings = nonzero(less(ybase[:-1] * ybase[1:],0))

        if ybase[0]>=0:
            fillon = over
        else:
            fillon = not over
        indLast = 0
        for ind in crossings:
            if fillon:
                thisX = x[indLast:ind+1]
                thisY = y[indLast:ind+1]
                thisY[0] = val
                thisY[-1] = val
                ax.fill(thisX, thisY, color)
            fillon = not fillon
            indLast = ind
        logging.debug('<<')

    def removeVboxChildren(self):
        ''' function to delete vbox children so that multiple graphs do not appear
            there must a better way to do this - pyplot?
        '''
        logging.debug('>>')
        #Tidy up draw areas
        vboxChildren = self.vbox.get_children()
        logging.debug('Vbox has %d children %s', len(vboxChildren), vboxChildren)
        # ToDo: check why vertical container is shared
        for child in vboxChildren:
            #Remove all FigureCanvasGTK and NavigationToolbar2GTKAgg to stop double ups of graphs
            if isinstance(child, FigureCanvasGTK) or isinstance(child, NavigationToolbar):
                logging.debug('Removing child: %s', child)
                self.vbox.remove(child)
        logging.debug('<<')
示例#53
0
文件: gui.py 项目: edumur/paramp
    def __init__(self):


        self.builder = Gtk.Builder()
        self.builder.add_from_file('gui.glade')
        self.window = self.builder.get_object('window1')
        self.builder.connect_signals(self)
        figure_box = self.builder.get_object('scrolledwindow1')

        self.builder.get_object('spinbuttonphi_s').set_increments(0.005, 0.1)
        self.builder.get_object('spinbuttonphi_p').set_increments(0.005, 0.1)
        self.builder.get_object('spinbuttonL_b').set_increments(0.001, 0.1)
        self.simple_ext = False
        self.freeze_plot = False

        self.paramp = LJPA(I_c=self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                           phi_dc=self.builder.get_object('spinbuttonphi_dc').get_value(),
                           phi_ac=self.builder.get_object('spinbuttonphi_p').get_value(),
                           phi_s=self.builder.get_object('spinbuttonphi_s').get_value(),
                           theta_p=self.builder.get_object('spinbuttontheta_p').get_value(),
                           C=self.builder.get_object('spinbuttonC').get_value()*1e-12,
                           L_s=self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                           f_p=self.builder.get_object('spinbuttonf_p').get_value()*1e9)

        self.parameters = {'I_c' : self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                           'phi_dc' : self.builder.get_object('spinbuttonphi_dc').get_value(),
                           'phi_ac' : self.builder.get_object('spinbuttonphi_p').get_value(),
                           'phi_s' : self.builder.get_object('spinbuttonphi_s').get_value(),
                           'theta_p' : self.builder.get_object('spinbuttontheta_p').get_value(),
                           'C' : self.builder.get_object('spinbuttonC').get_value()*1e-12,
                           'L_s' : self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                           'f_p' : self.builder.get_object('spinbuttonf_p').get_value()*1e9}

        self.builder.get_object('entry1').set_text(str(self.parameters))

        # Start of Matplotlib specific code
        self.fig, (self.ax1, self.ax2, self.ax3, self.ax4) = plt.subplots(4, 1, sharex=True)
        # figure = Figure()#figsize=(8, 6), dpi=71)
        # self.ax = figure.add_subplot(111)

        f = self.get_frequency()
        z = self.get_impedance(f)
        re = np.real(z)
        im = np.imag(z)
        r = 20.*np.log10(abs((z - 50.)/(z + 50.)))

        self.line_r,  = self.ax1.plot(f/1e9, r)
        self.line_20, = self.ax1.plot([f[0]/1e9, f[-1.]/1e9], [20., 20.], 'r--')

        self.line_re, = self.ax2.plot(f/1e9, re)
        self.line_50, = self.ax2.plot([f[0]/1e9, f[-1.]/1e9], [-50., -50.], 'r--')

        self.line_im, = self.ax3.plot(f/1e9, im)
        self.line_0, = self.ax3.plot([f[0]/1e9, f[-1.]/1e9], [0., 0.], 'r--')

        self.line_abs, = self.ax4.plot(f/1e9, abs(z))
        self.line_00, = self.ax4.plot([f[0]/1e9, f[-1.]/1e9], [0., 0.], 'r--')

        self.ax1.set_ylabel('Gain [dB]')
        self.ax2.set_ylabel('Re(Z)')
        self.ax3.set_ylabel('Im(Z)')
        self.ax4.set_ylabel('|Z|')

        self.ax4.set_xlabel('Frequency [GHz]')

        self.canvas = FigureCanvas(self.fig)

        self.canvas.set_size_request(800, 600)
        figure_box.add_with_viewport(self.canvas)

        toolbar_box = self.builder.get_object('scrolledwindow2')
        toolbar = NavigationToolbar(self.canvas, self.window)
        toolbar_box.add_with_viewport(toolbar)

        self.window.show_all()

        Gtk.main()
示例#54
0
文件: gui.py 项目: edumur/paramp
class Window(object):

    def __init__(self):


        self.builder = Gtk.Builder()
        self.builder.add_from_file('gui.glade')
        self.window = self.builder.get_object('window1')
        self.builder.connect_signals(self)
        figure_box = self.builder.get_object('scrolledwindow1')

        self.builder.get_object('spinbuttonphi_s').set_increments(0.005, 0.1)
        self.builder.get_object('spinbuttonphi_p').set_increments(0.005, 0.1)
        self.builder.get_object('spinbuttonL_b').set_increments(0.001, 0.1)
        self.simple_ext = False
        self.freeze_plot = False

        self.paramp = LJPA(I_c=self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                           phi_dc=self.builder.get_object('spinbuttonphi_dc').get_value(),
                           phi_ac=self.builder.get_object('spinbuttonphi_p').get_value(),
                           phi_s=self.builder.get_object('spinbuttonphi_s').get_value(),
                           theta_p=self.builder.get_object('spinbuttontheta_p').get_value(),
                           C=self.builder.get_object('spinbuttonC').get_value()*1e-12,
                           L_s=self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                           f_p=self.builder.get_object('spinbuttonf_p').get_value()*1e9)

        self.parameters = {'I_c' : self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                           'phi_dc' : self.builder.get_object('spinbuttonphi_dc').get_value(),
                           'phi_ac' : self.builder.get_object('spinbuttonphi_p').get_value(),
                           'phi_s' : self.builder.get_object('spinbuttonphi_s').get_value(),
                           'theta_p' : self.builder.get_object('spinbuttontheta_p').get_value(),
                           'C' : self.builder.get_object('spinbuttonC').get_value()*1e-12,
                           'L_s' : self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                           'f_p' : self.builder.get_object('spinbuttonf_p').get_value()*1e9}

        self.builder.get_object('entry1').set_text(str(self.parameters))

        # Start of Matplotlib specific code
        self.fig, (self.ax1, self.ax2, self.ax3, self.ax4) = plt.subplots(4, 1, sharex=True)
        # figure = Figure()#figsize=(8, 6), dpi=71)
        # self.ax = figure.add_subplot(111)

        f = self.get_frequency()
        z = self.get_impedance(f)
        re = np.real(z)
        im = np.imag(z)
        r = 20.*np.log10(abs((z - 50.)/(z + 50.)))

        self.line_r,  = self.ax1.plot(f/1e9, r)
        self.line_20, = self.ax1.plot([f[0]/1e9, f[-1.]/1e9], [20., 20.], 'r--')

        self.line_re, = self.ax2.plot(f/1e9, re)
        self.line_50, = self.ax2.plot([f[0]/1e9, f[-1.]/1e9], [-50., -50.], 'r--')

        self.line_im, = self.ax3.plot(f/1e9, im)
        self.line_0, = self.ax3.plot([f[0]/1e9, f[-1.]/1e9], [0., 0.], 'r--')

        self.line_abs, = self.ax4.plot(f/1e9, abs(z))
        self.line_00, = self.ax4.plot([f[0]/1e9, f[-1.]/1e9], [0., 0.], 'r--')

        self.ax1.set_ylabel('Gain [dB]')
        self.ax2.set_ylabel('Re(Z)')
        self.ax3.set_ylabel('Im(Z)')
        self.ax4.set_ylabel('|Z|')

        self.ax4.set_xlabel('Frequency [GHz]')

        self.canvas = FigureCanvas(self.fig)

        self.canvas.set_size_request(800, 600)
        figure_box.add_with_viewport(self.canvas)

        toolbar_box = self.builder.get_object('scrolledwindow2')
        toolbar = NavigationToolbar(self.canvas, self.window)
        toolbar_box.add_with_viewport(toolbar)

        self.window.show_all()

        Gtk.main()



    def get_frequency(self):

        return np.linspace(self.builder.get_object('spinbuttonf_s_start').get_value(),
                           self.builder.get_object('spinbuttonf_s_stop').get_value(),
                           self.builder.get_object('spinbuttonf_s_nb_point').get_value())*1e9


    def get_impedance(self, f):

        if self.builder.get_object('checkbutton3').get_active():

            return self.paramp.impedance(f, simple_ext=self.simple_ext)
        else:

            return self.paramp.impedance(f)


    def checkbutton1_toggled(self, checkbutton):

        if checkbutton.get_active():
            self.builder.get_object('box11').set_sensitive(True)
            self.builder.get_object('box20').set_sensitive(False)
            self.paramp.f_p = self.builder.get_object('spinbuttonf_p').get_value()*1e9
        else:
            self.builder.get_object('box11').set_sensitive(False)
            self.builder.get_object('box20').set_sensitive(True)
            self.paramp.f_p = None

        self.update_plot()



    def checkbutton3_toggled(self, checkbutton):

        if checkbutton.get_active():
            self.simple_ext = True
        else:
            self.simple_ext = False

        self.update_plot()



    def checkbutton2_toggled(self, checkbutton):

        if checkbutton.get_active():

            self.builder.get_object('box21').set_sensitive(True)
            self.builder.get_object('box25').set_sensitive(True)
            self.builder.get_object('box26').set_sensitive(True)
            self.builder.get_object('box27').set_sensitive(True)
            self.builder.get_object('checkbutton3').set_sensitive(True)
            self.builder.get_object('box31').set_sensitive(True)
            self.builder.get_object('box30').set_sensitive(True)
            self.builder.get_object('box29').set_sensitive(True)
            self.builder.get_object('box28').set_sensitive(True)
            self.builder.get_object('box13').set_sensitive(True)
            self.builder.get_object('box8').set_sensitive(True)
            self.builder.get_object('label35').set_sensitive(True)
            self.builder.get_object('label31').set_sensitive(True)
            self.builder.get_object('button1').set_sensitive(True)

            self.paramp = KLJPA(I_c=self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                               phi_dc=self.builder.get_object('spinbuttonphi_dc').get_value(),
                               phi_ac=self.builder.get_object('spinbuttonphi_p').get_value(),
                               phi_s=self.builder.get_object('spinbuttonphi_s').get_value(),
                               theta_p=self.builder.get_object('spinbuttontheta_p').get_value(),
                               C=self.builder.get_object('spinbuttonC').get_value()*1e-12,
                               L_s=self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                               f_p=self.builder.get_object('spinbuttonf_p').get_value()*1e9,
                                Z_l=self.builder.get_object('spinbuttonz_l').get_value(),
                                l=self.builder.get_object('spinbuttonl').get_value()*1e-2,
                                g_m=self.builder.get_object('spinbuttong_m').get_value(),
                                C_l=1.66e-10,
                                L_l=4.21e-7,
                                L_b=self.builder.get_object('spinbuttonL_b').get_value()*1e-9)

            self.builder.get_object('entry1').set_text(str(self.parameters))

        else:

            self.builder.get_object('box21').set_sensitive(False)
            self.builder.get_object('box25').set_sensitive(False)
            self.builder.get_object('box26').set_sensitive(False)
            self.builder.get_object('box27').set_sensitive(False)
            self.builder.get_object('checkbutton3').set_sensitive(False)
            self.builder.get_object('box31').set_sensitive(False)
            self.builder.get_object('box30').set_sensitive(False)
            self.builder.get_object('box29').set_sensitive(False)
            self.builder.get_object('box28').set_sensitive(False)
            self.builder.get_object('box13').set_sensitive(False)
            self.builder.get_object('box8').set_sensitive(False)
            self.builder.get_object('label35').set_sensitive(False)
            self.builder.get_object('label31').set_sensitive(False)
            self.builder.get_object('button1').set_sensitive(False)

            self.paramp = LJPA(I_c=self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                               phi_dc=self.builder.get_object('spinbuttonphi_dc').get_value(),
                               phi_ac=self.builder.get_object('spinbuttonphi_p').get_value(),
                               phi_s=self.builder.get_object('spinbuttonphi_s').get_value(),
                               theta_p=self.builder.get_object('spinbuttontheta_p').get_value(),
                               C=self.builder.get_object('spinbuttonC').get_value()*1e-12,
                               L_s=self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                               f_p=self.builder.get_object('spinbuttonf_p').get_value()*1e9)

        self.update_plot()


    def button2_clicked(self, button):

        p = eval(self.builder.get_object('entry1').get_text())

        self.freeze_plot = True
        self.builder.get_object('spinbuttonI_c').set_value(p['I_c']*1e6)
        self.builder.get_object('spinbuttonphi_dc').set_value(p['phi_dc'])
        self.builder.get_object('spinbuttonphi_p').set_value(p['phi_ac'])
        self.builder.get_object('spinbuttonphi_s').set_value(p['phi_s'])
        self.builder.get_object('spinbuttontheta_p').set_value(p['theta_p'])
        self.builder.get_object('spinbuttonC').set_value(p['C']*1e12)
        self.builder.get_object('spinbuttonL_s').set_value(p['L_s']*1e12)
        self.builder.get_object('spinbuttonf_p').set_value(p['f_p']*1e-9)
        self.builder.get_object('spinbuttonz_l').set_value(p['Z_l'])
        self.builder.get_object('spinbuttonl').set_value(p['l']*1e2)
        self.builder.get_object('spinbuttong_m').set_value(p['g_m'])
        self.builder.get_object('spinbuttonL_b').set_value(p['L_b']*1e9)
        self.freeze_plot = False

        self.update_plot()


    def spinbuttonC_changed(self, spinbutton):

        self.paramp.C = spinbutton.get_value()*1e-12

        self.update_plot()



    def spinbuttonI_c_changed(self, spinbutton):

        self.paramp.I_c = spinbutton.get_value()*1e-6

        self.update_plot()



    def spinbuttonL_s_changed(self, spinbutton):

        self.paramp.L_s = spinbutton.get_value()*1e-12

        self.update_plot()



    def spinbuttonf_p_changed(self, spinbutton):

        self.paramp.f_p = spinbutton.get_value()*1e9

        self.update_plot()



    def spinbuttonphi_p_changed(self, spinbutton):

        self.paramp.phi_ac = spinbutton.get_value()

        self.update_plot()



    def spinbuttontheta_p_changed(self, spinbutton):

        self.paramp.theta_p = spinbutton.get_value()

        self.update_plot()



    def spinbuttonphi_s_changed(self, spinbutton):

        self.paramp.phi_s = spinbutton.get_value()*1e-3

        self.update_plot()



    def spinbuttonphi_dc_changed(self, spinbutton):

        self.paramp.phi_dc = spinbutton.get_value()

        self.update_plot()



    def spinbuttonl_changed(self, spinbutton):

        self.paramp.l = spinbutton.get_value()*1e-2

        self.update_plot()



    def spinbuttonz_l_changed(self, spinbutton):

        self.paramp.zl = spinbutton.get_value()

        self.update_plot()



    def spinbuttong_m_changed(self, spinbutton):

        self.paramp.gm = spinbutton.get_value()

        self.update_plot()



    def spinbuttonL_b_changed(self, spinbutton):

        self.paramp.L_b = spinbutton.get_value()*1e-9

        self.update_plot()



    def spinbuttonf_s_nb_point_changed(self, spinbutton):

        self.update_plot()



    def spinbuttonf_s_start_changed(self, spinbutton):

        self.update_plot()



    def spinbuttonf_s_stop_changed(self, spinbutton):

        self.update_plot()



    def update_plot(self, x=None, y=None):

        if not self.freeze_plot:

            if x is not None and y is not None:
                f = x
                z = y
            else:
                f = self.get_frequency()
                z = self.get_impedance(f)

            re = np.real(z)
            im = np.imag(z)
            r = 20.*np.log10(abs((z - 50.)/(z + 50.)))

            self.line_r.set_data(f/1e9, r)
            self.line_20.set_data(f/1e9, r)

            self.line_re.set_data(f/1e9, re)
            self.line_50.set_data([f[0]/1e9, f[-1.]/1e9], [-50., -50.])

            self.line_im.set_data(f/1e9, im)
            self.line_0.set_data([f[0]/1e9, f[-1.]/1e9], [0., 0.])

            self.line_abs.set_data(f/1e9, abs(z))
            self.line_00.set_data([f[0]/1e9, f[-1.]/1e9], [0., 0.])

            for ax in (self.ax1, self.ax2, self.ax3, self.ax4):

                ax.relim()
                ax.autoscale_view()

            self.line_20.set_data([f[0]/1e9, f[-1.]/1e9], [20., 20.])
            self.canvas.draw()

        if self.builder.get_object('checkbutton2').get_active():

            self.parameters = {'I_c' : self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                               'phi_dc' : self.builder.get_object('spinbuttonphi_dc').get_value(),
                               'phi_ac' : self.builder.get_object('spinbuttonphi_p').get_value(),
                               'phi_s' : self.builder.get_object('spinbuttonphi_s').get_value(),
                               'theta_p' : self.builder.get_object('spinbuttontheta_p').get_value(),
                               'C' : self.builder.get_object('spinbuttonC').get_value()*1e-12,
                               'L_s' : self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                               'f_p' : self.builder.get_object('spinbuttonf_p').get_value()*1e9,
                               'Z_l' : self.builder.get_object('spinbuttonz_l').get_value(),
                               'l' : self.builder.get_object('spinbuttonl').get_value()*1e-2,
                               'g_m' : self.builder.get_object('spinbuttong_m').get_value(),
                               'C_l' : 1.66e-10,
                               'L_l' : 4.21e-7,
                               'L_b' : self.builder.get_object('spinbuttonL_b').get_value()*1e-9}
        else:

            self.parameters = {'I_c' : self.builder.get_object('spinbuttonI_c').get_value()*1e-6,
                               'phi_dc' : self.builder.get_object('spinbuttonphi_dc').get_value(),
                               'phi_ac' : self.builder.get_object('spinbuttonphi_p').get_value(),
                               'phi_s' : self.builder.get_object('spinbuttonphi_s').get_value(),
                               'theta_p' : self.builder.get_object('spinbuttontheta_p').get_value(),
                               'C' : self.builder.get_object('spinbuttonC').get_value()*1e-12,
                               'L_s' : self.builder.get_object('spinbuttonL_s').get_value()*1e-12,
                               'f_p' : self.builder.get_object('spinbuttonf_p').get_value()*1e9}


        self.builder.get_object('entry1').set_text(str(self.parameters))


    def optimization(self, button):

        self.iteration = 0
        def func(x, names, f):

            x = abs(x)

            for value, name in zip(x, names):

                if name == 'c':
                    self.paramp.C = value*1e-12
                if name == 'Ic':
                    self.paramp.I_c = value*1e-6
                if name == 'Ls':
                    self.paramp.L_s = value*1e-12
                if name == 'l':
                    self.paramp.l = value*1e-2
                if name == 'zl':
                    self.paramp.zl = value
                if name == 'gm':
                    self.paramp.gm = value*1e-1
                if name == 'lb':
                    self.paramp.L_b = value*1e-1
                if name == 'fp':
                    self.paramp.f_p = value*1e9
                if name == 'phi_ac':
                    self.paramp.phi_ac = value*1e-1
                if name == 'phi_dc':
                    self.paramp.phi_dc = value*1e-1

            z = self.get_impedance(f)

            re = np.real(z)
            im = np.imag(z)

            re_condition = np.sum(((re + 50.)/re)**2.)
            im_condition = np.sum((im/100.)**2.)

            y =  np.sum(((re + 50.)/re)**2. + (im/100.)**2.)
            self.iteration += 1

            print ''
            print 'Iteration: ', self.iteration
            for value, name in zip(x, names):
                if name == 'c':
                    print 'C: '+str(round(self.paramp.C*1e12, 3))
                if name == 'Ic':
                    print 'Ic: '+str(round(self.paramp.I_c*1e6, 3))
                if name == 'Ls':
                    print 'L_s: '+str(round(self.paramp.L_s*1e12, 3))
                if name == 'l':
                    print 'l: '+str(round(self.paramp.l*1e2, 3))
                if name == 'zl':
                    print 'zl: '+str(round(self.paramp.zl, 3))
                if name == 'gm':
                    print 'gm: '+str(round(self.paramp.gm, 3))
                if name == 'lb':
                    print 'L_b: '+str(round(self.paramp.L_b*1e9, 3))
                if name == 'fp':
                    print 'f_p: '+str(round(self.paramp.f_p*1e-9, 3))
                if name == 'phi_ac':
                    print 'phi_ac: '+str(round(self.paramp.phi_ac, 3))
                if name == 'phi_dc':
                    print 'phi_dc: '+str(round(self.paramp.phi_dc, 3))
            print 'Real part: '+str(round(re_condition, 3))+', imaginary part: '+str(round(im_condition, 3))+', least square: '+str(round(y, 3))
            print ''

            return y


        names  = ['c', 'Ic', 'Ls', 'l', 'zl', 'gm', 'lb', 'fp', 'phi_ac', 'phi_dc']
        values = [self.builder.get_object('spinbuttonC').get_value(),
                  self.builder.get_object('spinbuttonI_c').get_value(),
                  self.builder.get_object('spinbuttonL_s').get_value(),
                  self.builder.get_object('spinbuttonl').get_value(),
                  self.builder.get_object('spinbuttonz_l').get_value(),
                  self.builder.get_object('spinbuttong_m').get_value()*10.,
                  self.builder.get_object('spinbuttonL_b').get_value()*10.,
                  self.builder.get_object('spinbuttonf_p').get_value(),
                  self.builder.get_object('spinbuttonphi_p').get_value()*10.,
                  self.builder.get_object('spinbuttonphi_dc').get_value()*10.]
        bounds = ((2., 8.),
                  (2., 6.),
                  (20., 30.),
                  (0.5, 4.),
                  (3., 20.),
                  (0.01, 5),
                  (0.01, 20.),
                  (5., 20.),
                  (0.1, 9.),
                  (1., 4.))


        variables = []
        if self.builder.get_object('checkbutton_optimized_c').get_active():
            variables.append('c')
        if self.builder.get_object('checkbutton_optimized_Ic').get_active():
            variables.append('Ic')
        if self.builder.get_object('checkbutton_optimized_ls').get_active():
            variables.append('Ls')
        if self.builder.get_object('checkbutton_optimized_l').get_active():
            variables.append('l')
        if self.builder.get_object('checkbutton_optimized_zl').get_active():
            variables.append('zl')
        if self.builder.get_object('checkbutton_optimized_gm').get_active():
            variables.append('gm')
        if self.builder.get_object('checkbutton_optimized_lb').get_active():
            variables.append('lb')
        if self.builder.get_object('checkbutton_optimized_fp').get_active():
            variables.append('fp')
        if self.builder.get_object('checkbutton_optimized_phi_ac').get_active():
            variables.append('phi_ac')
        if self.builder.get_object('checkbutton_optimized_phi_dc').get_active():
            variables.append('phi_dc')

        names_to_optimized  = []
        values_to_optimized = []
        bounds_to_optimized = []

        for name, value, bound in zip(names, values, bounds):
            if name in variables:
                names_to_optimized.append(name)
                values_to_optimized.append(value)
                bounds_to_optimized.append(bound)

        f = np.linspace(self.builder.get_object('spinbutton1').get_value(),
                        self.builder.get_object('spinbutton2').get_value(),
                        self.builder.get_object('spinbutton3').get_value())*1e9

        self.freeze_plot = True
        results = minimize(func,
                           values_to_optimized,
                           args=(names_to_optimized, f),
                        #    method='TNC',
                           method='SLSQP',
                        #    method='L-BFGS-B',
                           bounds=bounds_to_optimized)
        values_optimized = results.x

        self.freeze_plot = False

        for value, name in zip(values_optimized, names_to_optimized):
            if name == 'c':
                self.builder.get_object('spinbuttonC').set_value(value)
            if name == 'Ic':
                self.builder.get_object('spinbuttonI_c').set_value(value)
            if name == 'Ls':
                self.builder.get_object('spinbuttonL_s').set_value(value)
            if name == 'l':
                self.builder.get_object('spinbuttonl').set_value(value)
            if name == 'zl':
                self.builder.get_object('spinbuttonz_l').set_value(value)
            if name == 'gm':
                self.builder.get_object('spinbuttong_m').set_value(value/10.)
            if name == 'lb':
                self.builder.get_object('spinbuttonL_b').set_value(value/10.)
            if name == 'fp':
                self.builder.get_object('spinbuttonf_p').set_value(value)
            if name == 'phi_ac':
                self.builder.get_object('spinbuttonphi_p').set_value(value/10.)
            if name == 'phi_dc':
                self.builder.get_object('spinbuttonphi_dc').set_value(value/10.)

        self.update_plot()
        print 'Done'
        return True




    def quit(self, event):

        Gtk.main_quit()
示例#55
0
    def drawPlot(self,xvalues,yvalues,xlabel,ylabel,title,color,zones=None,xzones=None, ylimits=None, y1_linewidth=None):
        logging.debug('>>')
        logging.debug("Type: plot | title: %s | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        logging.debug('xlabel: %s | ylabel: %s | title: %s', xlabel, ylabel, title)
        self.removeVboxChildren()
        figure = plt.Figure()
        logging.debug("Figure: %s", figure)
        #figure.clf()
        i = 0
        for value in xvalues:
            if i<1:
                logging.debug("i: %d, value: (%s) %s %s", i, value, xvalues, yvalues)
                axis = figure.add_subplot(111)
                logging.debug("Axis: %s", axis)
                line = axis.plot(xvalues[i],yvalues[i], color=color[i])
                logging.debug("Axis plotted, Line: %s", line)
                if y1_linewidth is not None:
                    line[0].set_linewidth(y1_linewidth)
                linewidth = line[0].get_linewidth()

                axis.grid(True)
                logging.debug("Axis grid on" )
                for tl in axis.get_yticklabels():
                    tl.set_color('%s' %color[i])
                logging.debug("Ticklabels color set" )
                #Draw zones on graph, eg for each lap
                if xzones is not None:
                    logging.debug("Setting xzones" )
                    for xzone in xzones:
                        if xzones.index(xzone) % 2:
                            zonecolor='b'
                        else:
                            zonecolor='g'
                        axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor)
                maxX = max(xvalues[i])
            if i>=1:
                ax2 = axis.twinx()
                logging.debug("Axis2: Axis: %s", ax2)
                ax2.plot(xvalues[i], yvalues[i], color=color[i])
                logging.debug("Axis2: plotted" )
                for tl in ax2.get_yticklabels():
                    tl.set_color('%s' %color[i])
                logging.debug("Axis2: Ticklabels color set" )
                maxXt = max(xvalues[i])
                if maxXt > maxX:
                    maxX = maxXt
            axis.set_xlabel(xlabel[i])
            logging.debug("X label set" )
            i+=1
        axis.set_xlim(0, maxX)

        if (len(xvalues)>1):
            axis.set_title("%s vs %s" %(ylabel[0],ylabel[1]))
        else:
            axis.set_title("%s" %(ylabel[0]))

        ylim_min, ylim_max = axis.get_ylim()
        if ylimits is not None:
            logging.debug("Using ylimits: %s", ylimits)
            if ylimits[0] is not None:
                ylim_min = ylimits[0]
            if ylimits[1] is not None:
                ylim_max = ylimits[1]
            axis.set_ylim(ylim_min, ylim_max)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        logging.debug("Canvas: %s", canvas)
        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        toolbar = NavigationToolbar(canvas, self.window)
        self.vbox.pack_start(toolbar, False, False, 0)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')
        return {'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth}
class CampaignGraph(object):
	title = 'Unknown'
	_graph_id = None
	table_subscriptions = []
	def __init__(self, config, parent, size_request=None):
		self.config = config
		self.parent = parent
		self.figure, ax = pyplot.subplots()
		self.axes = self.figure.get_axes()
		self.canvas = FigureCanvas(self.figure)
		self.manager = None
		if size_request:
			self.canvas.set_size_request(*size_request)
		self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed)
		self.canvas.show()
		self.navigation_toolbar = NavigationToolbar(self.canvas, self.parent)
		self.navigation_toolbar.hide()
		self.popup_menu = Gtk.Menu.new()

		menu_item = Gtk.MenuItem.new_with_label('Export')
		menu_item.connect('activate', self.signal_activate_popup_menu_export)
		self.popup_menu.append(menu_item)

		menu_item = Gtk.MenuItem.new_with_label('Refresh')
		menu_item.connect('activate', lambda action: self.refresh())
		self.popup_menu.append(menu_item)

		menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar')
		menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar)
		self.popup_menu.append(menu_item)
		self.popup_menu.show_all()

	@classmethod
	def get_graph_id(klass):
		return klass._graph_id

	def make_window(self):
		if self.manager == None:
			self.manager = FigureManager(self.canvas, 0)
		window = self.manager.window
		window.set_transient_for(self.parent)
		window.set_title(self.title)
		return window

	def mpl_signal_canvas_button_pressed(self, event):
		if event.button != 3:
			return
		pos_func = lambda m, d: (event.x, event.y, True)
		self.popup_menu.popup(None, None, None, None, event.button, Gtk.get_current_event_time())
		return True

	def signal_activate_popup_menu_export(self, action):
		dialog = gui_utilities.UtilityFileChooser('Export Graph', self.parent)
		file_name = self.config['campaign_name'] + '.png'
		response = dialog.run_quick_save(file_name)
		dialog.destroy()
		if not response:
			return
		destination_file = response['target_filename']
		self.figure.savefig(destination_file, format='png')

	def signal_toggled_popup_menu_show_toolbar(self, widget):
		if widget.get_property('active'):
			self.navigation_toolbar.show()
		else:
			self.navigation_toolbar.hide()

	def load_graph(self):
		self.refresh()

	def refresh(self, info_cache=None):
		info_cache = (info_cache or {})
		if not self.parent.rpc:
			return info_cache
		for table in self.table_subscriptions:
			if not table in info_cache:
				info_cache[table] = list(self.parent.rpc.remote_table('campaign/' + table, self.config['campaign_id']))
		map(lambda ax: ax.clear(), self.axes)
		self._load_graph(info_cache)
		self.canvas.draw()
		return info_cache
示例#57
0
    def drawBars(self,xvalues,yvalues,xlabel,ylabel,title,color):
        logging.debug('>>')
        logging.debug("Type: bars | title: %s"" | col: %s | xlabel: %s | ylabel: %s",
                      title, color, xlabel, ylabel)
        self.removeVboxChildren()
        #figure = Figure(figsize=(6,4), dpi=72)
        figure = plt.figure()
        logging.debug("Figure: %s", figure)
        numCols=len(xvalues[0])
        xmod = 0.4
        self.showGraph=False
        axis = figure.add_subplot(111)
        logging.debug("Axis: %s", axis)

        if len(xvalues) == 1: #One axis
            barWidth = 0.8
            barOffset = 0.1
            logging.debug("One axis, barWidth %f, barOffset %f", barWidth, barOffset)
        elif len(xvalues) == 2: #Twin axes
            barWidth = 0.4
            barOffset = 0.1
            logging.debug("Twin axes, barWidth %f, barOffset %f", barWidth, barOffset)
        else: #Error
            logging.debug("Error: invalid number of axes" )
            return

        axis.set_xlabel(xlabel[0])
        axis.set_ylabel(ylabel[0])
        logging.debug("Labels set x: %s, y: %s", xlabel[0], ylabel[0])
        xvals = [x+barOffset for x in range(0, numCols)]
        yvals = [0] * numCols
        for i in range(0, numCols):
            yval = yvalues[0][i]
            if float(yval) > 0.0:
                self.showGraph=True
            else:
                yval = self.NEARLY_ZERO
            yvals[i] = yval
        if self.showGraph:
            logging.debug("Drawing bars")
            axis.bar(xvals, yvals, barWidth, color=color[0], align='edge')
        else:   #Only zero results
            logging.debug("No results to draw")
            pass

        axis.grid(True)
        axis.set_title("%s" %(title[0]))
        logging.debug("Setting title to: %s", title[0])
        for tl in axis.get_yticklabels():
            logging.debug("Setting ticklabel color %s", color[0])
            tl.set_color('%s' %color[0])

        if len(xvalues) == 2: #Display twin axis
            ax2 = axis.twinx()
            logging.debug("Axis 2: Twin axis: %s", ax2)
            xvals = [x+barOffset+barWidth for x in range(0, numCols)]
            for i in range(0, numCols):
                yval = yvalues[1][i]
                if float(yval) > 0.0:
                    self.showGraph=True
                else:
                    yval = self.NEARLY_ZERO
                yvals[i] = yval
            if self.showGraph:
                logging.debug("Axis 2: Drawing bars")
                ax2.bar(xvals, yvals, barWidth, color=color[1], align='edge')
                logging.debug("Axis 2: Label set y: %s", ylabel[1])
                ax2.set_ylabel(ylabel[1])
            else:   #Only zero results
                logging.debug("Axis 2: No results to draw")
                pass
            for tl in ax2.get_yticklabels():
                tl.set_color('%s' %color[1])
                logging.debug("Axis 2: Setting ticklabel color %s", color[1])
            _title = "%s vs %s" %(title[0],title[1])
            logging.debug("Axis 2: Setting title to: %s", _title)
            axis.set_title(_title)

        logging.debug("Setting x ticks")
        tickLocations = [x+0.5 for x in range(0, numCols)]
        axis.set_xticks(tickLocations)
        axis.set_xticklabels(xvalues[0])
        logging.debug("Setting x limits")
        axis.set_xlim(0, numCols)

        canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea
        logging.debug("Got canvas: %s", canvas)
        canvas.show()
        logging.debug("Adding canvas to vbox")
        self.vbox.pack_start(canvas, True, True, 0)
        #toolbar = NavigationToolbar(canvas, self.window)
        #self.vbox.pack_start(toolbar, False, False)

        for child in self.vbox.get_children():
            logging.debug('Child available: %s', child)

        logging.debug('<<')