예제 #1
0
def draw_chart_forcast(time_arr, val_arr):
    # t = np.arange(0.0, 2.0, 0.01)
    # s = 1 + np.sin(2 * np.pi * t)
    #
    # fig, ax = plt.subplots()
    # ax.plot(t, s)
    #
    # ax.set(xlabel='time (s)', ylabel='voltage (mV)',
    #        title='About as simple as it gets, folks')
    # ax.grid()
    # plt.show()

    myfirstwindow = Gtk.Window()
    myfirstwindow.connect("delete-event", Gtk.main_quit)
    myfirstwindow.set_default_size(400, 400)

    fig = Figure(figsize=(5, 5), dpi=100)
    ax = fig.add_subplot(111)
    items = ax.plot(time_arr, val_arr)
    for tick in ax.get_xticklabels():
        tick.set_rotation(90)

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

    canvas = FigureCanvas(fig)
    canvas.set_size_request(400, 400)
    sw.add_with_viewport(canvas)
    myfirstwindow.show_all()
    Gtk.main()
예제 #2
0
    def __init__(self, city_name):
        Gtk.Window.__init__(self, title="Temparature Chart")
        filename = os.path.join(CSV_DRUMP_DIR, '%s.csv' % city_name)
        self.connect("destroy", self.on_destroy)

        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_border_width(10)
        self.set_size_request(800, 600)
        self.data = []
        self.date = []
        self.temperature = []
        with open(filename) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                self.data.append(row)
                self.date.append(row.get('dt'))
                self.temperature.append(row.get('temp'))
        fig = Figure(figsize=(5, 5), dpi=100)
        ax = fig.add_subplot(111)
        # ax.tick_params(axis='x', rotation=90)
        # plt.gcf().autofmt_xdate()
        ax.plot([date[5:16].replace(" ", "\n") for date in self.date[-15:]],
                [float(temp) for temp in self.temperature[-15:]])
        canvas = FigureCanvas(fig)
        canvas.set_size_request(400, 400)

        self.add(canvas)
        self.show_all()
예제 #3
0
파일: views.py 프로젝트: neo5g/gsrp5
	def draw(self):
		x = [5,8,10]
		y = [12,16,6]
		
		x2 = [6,9,11]
		y2 = [6,15,7]
		
		fig, ax = plt.subplots()		
		canvas = FigureCanvas(fig)
		canvas.set_size_request(600,600)
		canvas.set_parent(self._scrolledwindow)
		#self._scrolledwindow.add_with_viewport(canvas)
	
		ax.bar(x, y, align='center')
		
		ax.bar(x2, y2, color='y', align='center')
		
		ax.plot()
		
		plt.title('Epic Info')
		plt.ylabel('Y axis')
		plt.xlabel('X axis')

		#print(dir(fig.canvas))
		#plt.draw()
		plt.show(block=False)
예제 #4
0
파일: summary.py 프로젝트: ctjacobs/pyqso
    def __init__(self, application):
        """ Create a summary page containing various statistics such as the number of logs in the logbook, the logbook's modification date, etc.

        :arg application: The PyQSO application containing the main Gtk window, etc.
        """

        self.application = application
        self.logbook = self.application.logbook
        self.builder = self.application.builder
        glade_file_path = join(realpath(dirname(__file__)), "res", "pyqso.glade")
        self.builder.add_objects_from_file(glade_file_path, ("summary_page",))
        self.summary_page = self.builder.get_object("summary_page")

        self.items = {}

        # Database name in large font at the top of the summary page
        self.builder.get_object("database_name").set_markup("<span size=\"x-large\">%s</span>" % basename(self.logbook.path))
        self.items["LOG_COUNT"] = self.builder.get_object("log_count")
        self.items["QSO_COUNT"] = self.builder.get_object("qso_count")
        self.items["DATE_MODIFIED"] = self.builder.get_object("date_modified")

        # Yearly statistics
        config = configparser.ConfigParser()
        have_config = (config.read(expanduser('~/.config/pyqso/preferences.ini')) != [])
        (section, option) = ("general", "show_yearly_statistics")
        if(have_config and config.has_option(section, option)):
            if(config.getboolean("general", "show_yearly_statistics") and have_matplotlib):
                hbox = Gtk.HBox()
                label = Gtk.Label(label="Display statistics for year: ", halign=Gtk.Align.START)
                hbox.pack_start(label, False, False, 6)
                year_select = Gtk.ComboBoxText()
                min_year, max_year = self.get_year_bounds()
                if min_year and max_year:
                    for year in range(max_year, min_year-1, -1):
                        year_select.append_text(str(year))
                year_select.append_text("")
                year_select.connect("changed", self.on_year_changed)
                hbox.pack_start(year_select, False, False, 6)
                self.summary_page.pack_start(hbox, False, False, 4)

                self.items["YEARLY_STATISTICS"] = Figure()
                canvas = FigureCanvas(self.items["YEARLY_STATISTICS"])
                canvas.set_size_request(800, 175)
                canvas.show()
                self.summary_page.pack_start(canvas, True, True, 0)

        # Summary tab label and icon.
        tab = Gtk.HBox(homogeneous=False, spacing=0)
        label = Gtk.Label(label="Summary  ")
        icon = Gtk.Image.new_from_icon_name(Gtk.STOCK_INDEX, Gtk.IconSize.MENU)
        tab.pack_start(label, False, False, 0)
        tab.pack_start(icon, False, False, 0)
        tab.show_all()

        self.logbook.notebook.insert_page(self.summary_page, tab, 0)  # Append as a new tab
        self.logbook.notebook.show_all()

        return
예제 #5
0
class DonutChart():
    def __init__(self, *args):
        self.box = args[0]  # gtkBox from builder
        self.radius, self.width = args[1]  # donut radius and width
        self.getStat = args[2]  # function that returns stat
        self.supTitle = args[3]  # supertitle's title
        self.supXPos, self.supYPos = args[4]  # supertitle x and y pos
        self.stat = self.getStat()  # grabs current stat number
        self.old_stat = 0  # initialize a compare variable to avoid unnecessary redraws
        self.maxStat = args[5]  # max range of donut
        self.statType = args[6]  # type of stat (%, Mib, MHz, W)
        self.statFontSize, self.supFontSize = args[
            7]  # stat and supertitle font sizes
        self.cnvsHeight, self.cnvsWidth = args[8]  # canvas width and height
        self.a = plt.cm.Blues  # fill color
        self.b = plt.cm.Greys  # negative color
        self.fig, self.ax = plt.subplots(1)  # sets a single subsplot
        self.fig.patch.set_facecolor('white')  # sets background to white
        self.createDonut()  # creates donut chart
        self.createAxis()  # creates equal borders and sets title
        self.canvas = FigureCanvas(self.fig)  # attach fig to a canvas
        self.canvas.set_size_request(self.cnvsHeight,
                                     self.cnvsWidth)  # sets canvas size
        self.box.add(self.canvas)  # adds canvas to specified gtkBox
        self.anim = animation.FuncAnimation(
            self.fig, self.update, interval=1000,
            blit=True)  # runs animation to update stats

    def createDonut(self):
        self.donut, _ = self.ax.pie([self.stat, self.maxStat - self.stat],
                                    radius=self.radius,
                                    colors=[self.a(0.6),
                                            self.b(0.6)],
                                    counterclock=False,
                                    startangle=180)
        plt.setp(self.donut, width=0.2, edgecolor='white'
                 )  # sets the circle width and adds a white border color

    def createAxis(self):
        self.ax.axis('equal')  # sets donut to be even within frame
        self.ax.set_title("{0}{1}".format(self.stat, self.statType),
                          fontsize=self.statFontSize,
                          y=0.425)  # main chart title

    def update(self, i):
        self.stat = self.getStat()  # function that returns up-to-date stat
        if self.stat != self.old_stat:  # rerenders donut if the stat has changed, otherwise no update
            self.ax.clear(
            )  # clears donut before rerendering -- otherwise it builds layers indefinitely
            self.createAxis()  # recreate axis
            self.createDonut()  # create new donut with new stat
            self.fig.suptitle(self.supTitle,
                              fontsize=self.supFontSize,
                              x=self.supXPos,
                              y=self.supYPos)  # super chart title
            self.old_stat = self.stat  # updates old stat
예제 #6
0
 def __init__(self, date, temp):
     super(Gtk.ListBoxRow, self).__init__()
     fig = Figure(figsize=(5, 5), dpi=100)
     ax = fig.add_subplot(111)
     ax.ylabel = 'Temperature'
     ax.xmargin = 2
     # ax.tick_params(axis='x', rotation=90)
     # plt.gcf().autofmt_xdate()
     ax.plot(date, temp)
     canvas = FigureCanvas(fig)
     canvas.set_size_request(400, 400)
     self.add(canvas)
예제 #7
0
	def open_detatiled_station_window(self, station_name, x=0, y=0):
		latest_data = []
		station_url = ""

		#Find the correct link for the requested station
		for link in self.every_station_link:
			if link[0] == station_name:
				#Perform detailed scrape
				latest_data = detailed_station_scrape(link[1], station_name)
				station_url = link[1]

		csv_url = get_csv_link(station_url, station_name)
		
		# Build new window based on Glade file.
		builder = Gtk.Builder()
		builder.add_from_file("Station Window.glade")
		builder.connect_signals(Handler())

		builder.get_object("label1").set_text(station_name)
		builder.get_object("label7").set_text(latest_data[0])
		builder.get_object("label8").set_text(latest_data[1])
		builder.get_object("label9").set_text(latest_data[2])
		builder.get_object("label10").set_text(latest_data[3])
		builder.get_object("label11").set_text(latest_data[4])
		builder.get_object("label18").set_text(latest_data[5])
		builder.get_object("label19").set_text(latest_data[6])
		builder.get_object("label20").set_text(latest_data[7])
		builder.get_object("label21").set_text(latest_data[8])
		builder.get_object("label22").set_text(latest_data[9])
		builder.get_object("label26").set_text(latest_data[10])
		builder.get_object("label27").set_text(latest_data[11])
		builder.get_object("label28").set_text(latest_data[12])

		display_station_win = builder.get_object("window1")
		display_station_win.set_title(station_name)
		display_station_win.move(x,y)

		refresh_butt = builder.get_object("button1")
		refresh_butt.connect("clicked", self.on_refresh_clicked)

		display_station_win.connect("delete-event", self.close_window_and_remove_reference)
		self.list_of_current_windows.append(display_station_win)#Dogfood # Stores current window in array so they can be iterated through when saving

		# Graph
		if csv_url != "no data":
			temperature_data = csv_scrap(csv_url)
			fig = temperature_graph(temperature_data)
			scroll_win = builder.get_object("scrolledwindow1")
			canvas = FigureCanvas(fig)
			canvas.set_size_request(400,400)
			scroll_win.add_with_viewport(canvas)

		display_station_win.show_all()
예제 #8
0
파일: gat.py 프로젝트: FedorSarafanov/bin
class MyProgram():
    def __init__(self):
        #some_gtk_stuff
        self.builder = Gtk.Builder()
        self.builder.add_from_file("u.glade")
        self.window = self.builder.get_object("window1")
        # sw = builder.get_object("sw")
        # canvas = FigureCanvas(fig)
        # sw.add_with_viewport(canvas)
        self.signals = {
            'cos_clicked': self.create_plot,
            'sin_clicked': self.create_plot,
            'sq_clicked': self.create_plot,
            'on_window1_destroy': self.on_window1_destroy,
        }
        self.builder.connect_signals(self.signals)

        self.vbox = self.builder.get_object('vbox')

        self.figure = plt.figure(figsize=(1, 1), dpi=100)
        # self.axis = self.figure.add_subplot(111)
        # self.figure = Figure(figsize=(1,1), dpi=100)
        self.ax = self.figure.add_subplot(111)
        self.canvas = None

        self.window.set_size_request(700, 500)
        self.window.show_all()

    def create_plot(self, button):
        self.ani = animation.FuncAnimation(self.figure,
                                           self.update_plot,
                                           interval=1000)

    def on_window1_destroy(self, *args):
        Gtk.main_quit(*args)

    def update_plot(self, i):
        #read SampleData from txt File
        x = []
        y = []
        with open('s.dat') as f:
            x_raw, y_raw = f.readline().strip().split(',')
            x.append(int(x_raw))
            y.append(int(y_raw))

        self.axis.plot(x, y)

        if not self.canvas:
            self.canvas = FigureCanvas(self.figure)
            self.vbox.pack_start(self.canvas)
            self.canvas.show()

        self.canvas.draw()
예제 #9
0
def plot_test_cost(test_cost, num_epochs, test_cost_xmin, vbox):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(np.arange(test_cost_xmin, num_epochs),
            test_cost[test_cost_xmin:num_epochs],
            color='#2A6EA6')
    ax.set_xlim([test_cost_xmin, num_epochs])
    ax.grid(True)
    ax.set_xlabel('Epoch')
    ax.set_title('Cost on the test data')
    canvas = FigureCanvas(fig)
    canvas.set_size_request(1400, 600)
    vbox.pack_start(canvas, True, True, 0)
    def __init__(self, ylim_correct=[-50, 16], ylim_wrong=[-50, 2]):
        scale = 3

        myfirstwindow = Gtk.Window()
        myfirstwindow.connect("delete-event", Gtk.main_quit)
        myfirstwindow.connect('destroy', lambda win: Gtk.main_quit())
        myfirstwindow.set_default_size(800, 600)

        self.updated_correct_values_cnt = 0
        self.updated_wrong_values_cnt = 0

        self.figure = plt.figure(figsize=(4 * scale, 3 * scale))
        self.figure.suptitle("SenSys'17 - Packetized-LTE PHY", fontsize=16)
        self.ax1 = self.figure.add_subplot(2, 1, 1)
        plt.grid(True)
        self.ax2 = self.figure.add_subplot(2, 1, 2)
        plt.grid(True)
        # draw and show it
        self.ax1.set_title("Successful Statistics")
        self.line1_correct, = self.ax1.plot(self.correct_rssi_vector,
                                            visible=True,
                                            label='RSSI [dBm]')
        self.line2_correct, = self.ax1.plot(self.correct_cqi_vector,
                                            visible=True,
                                            label='CQI')
        self.line3_correct, = self.ax1.plot(self.correct_noise_vector,
                                            visible=True,
                                            label='Noise [dBm]')
        self.ax1.legend()
        self.ax1.set_ylim(ylim_correct)
        self.ax2.set_title("Unsuccessful Statistics")
        self.line1_wrong, = self.ax2.plot(self.error_rssi_vector,
                                          visible=True,
                                          label='RSSI [dBm]')
        self.line2_wrong, = self.ax2.plot(self.error_noise_vector,
                                          visible=True,
                                          label='Noise [dBm]')
        self.ax2.legend()
        self.ax2.set_ylim(ylim_wrong)
        self.figure.canvas.draw()
        plt.ion()

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

        canvas = FigureCanvas(self.figure)
        canvas.set_size_request(1600, 1200)
        sw.add_with_viewport(canvas)

        myfirstwindow.show_all()
        Gtk.main()
예제 #11
0
파일: Plot.py 프로젝트: zhouyaoji/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.widget.set_size_request(width, height)
        self.widget.show_all()

    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)
예제 #12
0
파일: Plot.py 프로젝트: naojsoft/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.widget.set_size_request(width, height)
        self.widget.show_all()

    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)
예제 #13
0
def plot_test_accuracy(test_accuracy, num_epochs, test_accuracy_xmin, vbox):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(np.arange(test_accuracy_xmin, num_epochs), [
        accuracy / 100.0
        for accuracy in test_accuracy[test_accuracy_xmin:num_epochs]
    ],
            color='#2A6EA6')
    ax.set_xlim([test_accuracy_xmin, num_epochs])
    ax.grid(True)
    ax.set_xlabel('Epoch')
    ax.set_title('Accuracy (%) on the test data')
    canvas = FigureCanvas(fig)
    canvas.set_size_request(1400, 600)
    vbox.pack_start(canvas, True, True, 0)
예제 #14
0
    def update_torch_data(self, str_txt):

        self.torch_lock.acquire()
        input_data = self.torch_show_data["torch_in"]
        fulconv_data = self.torch_show_data["torch_out"]
        self.torch_show_data.clear()
        self.torch_lock.release()

        self.torch_busy = 0

        strbuf = Gtk.TextBuffer()
        strbuf.set_text("")
        self.show_text_view.set_buffer(strbuf)

        fig = Figure(figsize=(5, 4), dpi=80)

        ax01 = fig.add_subplot(2, 2, 1)
        ax01.set_title(self.str_img_fn)
        ax01.imshow(input_data, cmap='gray', origin='lower')
        #ax01.axis('off')

        ax02 = fig.add_subplot(2, 2, 2)

        np_weight = self.np_convs_weights[0]
        wpe = np_weight.shape
        draw_conv = draw_data(
            np_weight.reshape(wpe[0] * wpe[1], wpe[2], wpe[3]))
        #draw_conv = draw_data(np_weight.reshape(wpe[0],wpe[1],wpe[2]) )
        ax02.imshow(draw_conv, cmap='gray', origin='lower')
        ax02.set_title("conv_weight")

        ax03 = fig.add_subplot(2, 2, 3)
        ax03.set_title(self.str_labels[0])
        ax03.imshow(fulconv_data[0][0], cmap='hot', origin='lower')

        ax04 = fig.add_subplot(2, 2, 4)

        ax04.imshow(fulconv_data[0][1], cmap='cool', origin='lower')
        ax04.set_title(self.str_labels[1])

        canvas = FigureCanvas(fig)  # a Gtk.DrawingArea
        canvas.set_size_request(800, 620)
        self.show_win.remove(self.show_view)
        self.show_win.add(canvas)
        self.show_win.show_all()
        self.show_view = canvas

        return False
예제 #15
0
	def __init__(self, application, size_request=None, style_context=None):
		"""
		:param tuple size_request: The size to set for the canvas.
		"""
		self.application = application
		self.style_context = style_context
		self.config = application.config
		"""A reference to the King Phisher client configuration."""
		self.figure, _ = pyplot.subplots()
		self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE))
		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.application.get_active_window())
		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._menu_item_show_toolbar = menu_item
		self.popup_menu.append(menu_item)
		self.popup_menu.show_all()
		self.navigation_toolbar.hide()
		self._legend = None
예제 #16
0
    def create_ui(self):
        self.fig = Figure(figsize=(8, 8), dpi=100)
        self.axes = []

        sw = Gtk.ScrolledWindow()

        plot_box = Gtk.VBox()
        sw.add_with_viewport(plot_box)

        canvas = FigureCanvas(self.fig)
        canvas.set_size_request(500, 600)
        plot_box.pack_start(canvas, True, True, 0)

        toolbar = NavigationToolbar2(canvas, sw)
        self.widget.pack_start(toolbar, False, False, 0)
        self.widget.add(sw)
예제 #17
0
    def __init__(self, workdir, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.workdir = workdir

        # main containers
        scr_win = Gtk.ScrolledWindow(visible=True)
        pad_box = Gtk.Box(visible=True)
        pad_box.pack_start(scr_win, True, True, 20)

        main_box = Gtk.Box(visible=True, orientation=Gtk.Orientation.VERTICAL)
        scr_win.add_with_viewport(main_box)

        # content
        lbl_head = '<span font="36.0"><b>Project Stats</b></span>'
        heading = Gtk.Label(label=lbl_head, expand=True, visible=True)
        heading.set_use_markup(True)
        main_box.pack_start(heading, False, False, 0)
        line = Gtk.Separator(visible=True)
        main_box.pack_start(line, False, False, 0)

        self.fig = Figure(facecolor='none')
        self.ax = self.fig.add_subplot(111, axisbg='#ffffff')
        self.canvas = FigCanvas(self.fig)
        self.canvas.set_size_request(800, 600)
        self.canvas.draw()
        self.canvas.show()
        main_box.pack_start(self.canvas, True, True, 0)

        self.add(pad_box)
        self.titlebar = Ide.WorkbenchHeaderBar(visible=True)

         # Gather stats
        thread = threading.Thread(target=self.gather_stats)
        thread.daemon = True
        thread.start()
예제 #18
0
    def __init__(self, builder, GPUs, maxpoints, precision, linux_kernelmain,
                 linux_kernelsub):
        # Can used for kernel specific workarounds
        self.linux_kernelmain = linux_kernelmain
        self.linux_kernelsub = linux_kernelsub

        self.precision = precision
        self.builder = builder
        self.GPUs = GPUs
        self.GPU = GPUs[0]
        self.maxpoints = maxpoints
        self.fig = Figure(figsize=(1000, 150), dpi=100, facecolor="#00000000")
        self.fig.set_tight_layout(True)
        self.ax = self.fig.add_subplot(111)
        # enable, name, unit, mean, max, current
        self.signalstore = Gtk.ListStore(bool, bool, bool, str, str, str, str,
                                         str, str, str)
        self.Plotsignals = self.init_signals(self.GPU)

        # Set top panel height in accordance to number of signals (with saturation)
        height_top_panel = len(self.Plotsignals) * 32.5
        if height_top_panel < 150:
            self.builder.get_object("MainPane").set_position(150)
        elif height_top_panel > 235:
            self.builder.get_object("MainPane").set_position(235)
        else:
            self.builder.get_object("MainPane").set_position(height_top_panel)

        self.init_treeview()
        self.update_signals()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(1000, 150)
        self.object = self.builder.get_object("matplot")
        self.object.add(self.canvas)
        self.object.show_all()
예제 #19
0
	def __init__(self, application, size_request=None):
		"""
		:param tuple size_request: The size to set for the canvas.
		"""
		self.application = application
		self.config = application.config
		"""A reference to the King Phisher client configuration."""
		self.figure, _ = 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.application.get_active_window())
		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._menu_item_show_toolbar = menu_item
		self.popup_menu.append(menu_item)
		self.popup_menu.show_all()
		self.navigation_toolbar.hide()
예제 #20
0
    def __init__(self, interval=100, view=20, keep=None, linewidth=1):
        super().__init__()
        self.fig = Figure(dpi=72)
        self.canvas = FigureCanvas(self.fig)
        self.pack_start(self.canvas, True, True, 0)

        self.data = {}
        self.plots = {}
        self.info = {}
        self.alternates = set()
        self.active = None

        self.axes = []
        self.axes.append(self.fig.add_subplot(111))
        self.fig.subplots_adjust(left=0.12, right=0.88)

        self.axes[0].set_xlabel('seconds ago')
        self.interval = interval  # milliseconds
        self.view_range = view  # seconds

        self.keep_range = keep or (view * 4)  # seconds
        self.linewidth = linewidth

        self.keep_size = int(self.keep_range * 1000 / self.interval)
        self.view_step = view // 2
        self.deviation = 10

        self.view_time = time.time()
        self.add_data('time')
        self.paused = False
        self.show_all()
예제 #21
0
    def create_ui(self):
        self.fig = Figure(figsize=(8, 8), dpi=100)
        self.axes = []

        sw = Gtk.ScrolledWindow()

        plot_box = Gtk.VBox()
        sw.add_with_viewport(plot_box)

        canvas = FigureCanvas(self.fig)
        canvas.set_size_request(500, 600)
        plot_box.pack_start(canvas, True, True, 0)

        toolbar = NavigationToolbar2(canvas, sw)
        self.widget.pack_start(toolbar, False, False, 0)
        self.widget.add(sw)
예제 #22
0
    def __init__(self, workdir, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.workdir = workdir

        # main containers
        scr_win = Gtk.ScrolledWindow(visible=True)
        pad_box = Gtk.Box(visible=True)
        pad_box.pack_start(scr_win, True, True, 20)

        main_box = Gtk.Box(visible=True, orientation=Gtk.Orientation.VERTICAL)
        scr_win.add_with_viewport(main_box)

        # content
        lbl_head = '<span font="36.0"><b>Project Stats</b></span>'
        heading = Gtk.Label(label=lbl_head, expand=True, visible=True)
        heading.set_use_markup(True)
        main_box.pack_start(heading, False, False, 0)
        line = Gtk.Separator(visible=True)
        main_box.pack_start(line, False, False, 0)

        self.fig = Figure(facecolor='none')
        self.ax = self.fig.add_subplot(111, axisbg='#ffffff')
        self.canvas = FigCanvas(self.fig)
        self.canvas.set_size_request(800, 600)
        self.canvas.draw()
        self.canvas.show()
        main_box.pack_start(self.canvas, True, True, 0)

        self.add(pad_box)
        self.titlebar = Ide.WorkbenchHeaderBar(visible=True)

        # Gather stats
        thread = threading.Thread(target=self.gather_stats)
        thread.daemon = True
        thread.start()
예제 #23
0
 def __init__(self, *args):
     self.box = args[0]  # gtkBox from builder
     self.radius, self.width = args[1]  # donut radius and width
     self.getStat = args[2]  # function that returns stat
     self.supTitle = args[3]  # supertitle's title
     self.supXPos, self.supYPos = args[4]  # supertitle x and y pos
     self.stat = self.getStat()  # grabs current stat number
     self.old_stat = 0  # initialize a compare variable to avoid unnecessary redraws
     self.maxStat = args[5]  # max range of donut
     self.statType = args[6]  # type of stat (%, Mib, MHz, W)
     self.statFontSize, self.supFontSize = args[
         7]  # stat and supertitle font sizes
     self.cnvsHeight, self.cnvsWidth = args[8]  # canvas width and height
     self.a = plt.cm.Blues  # fill color
     self.b = plt.cm.Greys  # negative color
     self.fig, self.ax = plt.subplots(1)  # sets a single subsplot
     self.fig.patch.set_facecolor('white')  # sets background to white
     self.createDonut()  # creates donut chart
     self.createAxis()  # creates equal borders and sets title
     self.canvas = FigureCanvas(self.fig)  # attach fig to a canvas
     self.canvas.set_size_request(self.cnvsHeight,
                                  self.cnvsWidth)  # sets canvas size
     self.box.add(self.canvas)  # adds canvas to specified gtkBox
     self.anim = animation.FuncAnimation(
         self.fig, self.update, interval=1000,
         blit=True)  # runs animation to update stats
    def update_torch_data(self, str_txt):

        self.torch_lock.acquire()
        np_imgs = self.torch_show_data["np_imgs"]
        np_mask_imgs = self.torch_show_data["np_mask_imgs"]
        np_decoded = self.torch_show_data["np_decoded"]
        self.torch_lock.release()

        np_imgs = np_imgs.transpose((0, 2, 3, 1))

        self.sw.remove(self.canvas)

        axs = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

        fig = Figure(figsize=(8, 8), dpi=80)

        for n in range(3):
            for i in range(self.n_test_imgs):
                axs[n][i] = fig.add_subplot(3, self.n_test_imgs,
                                            n * self.n_test_imgs + i + 1)

        for i in range(self.n_test_imgs):
            axs[0][i].imshow(np_imgs[i] * 0.5 + 0.5, cmap='gray')
            axs[1][i].imshow(np_mask_imgs[i][0], cmap='gray')
            axs[2][i].imshow(np_decoded[i][0], cmap='gray')

        self.canvas = FigureCanvas(fig)
        self.canvas.set_size_request(1000, 600)
        self.sw.add(self.canvas)
        self.sw.show_all()
예제 #25
0
	def __init__(self, application, size_request=None, style_context=None):
		"""
		:param tuple size_request: The size to set for the canvas.
		"""
		self.application = application
		self.style_context = style_context
		self.config = application.config
		"""A reference to the King Phisher client configuration."""
		self.figure, _ = pyplot.subplots()
		self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE))
		self.axes = self.figure.get_axes()
		self.canvas = FigureCanvas(self.figure)
		self.manager = None
		self.minimum_size = (380, 200)
		"""An absolute minimum size for the canvas."""
		if size_request is not None:
			self.resize(*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.application.get_active_window())

		self.popup_menu = managers.MenuManager()
		self.popup_menu.append('Export', self.signal_activate_popup_menu_export)
		self.popup_menu.append('Refresh', self.signal_activate_popup_refresh)

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

		self.navigation_toolbar.hide()
		self._legend = None
예제 #26
0
파일: Plot.py 프로젝트: zhouyaoji/ginga
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

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

        self.widget.set_size_request(width, height)
        self.widget.show_all()
예제 #27
0
파일: Plot.py 프로젝트: naojsoft/ginga
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

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

        self.widget.set_size_request(width, height)
        self.widget.show_all()
    def __init__(self):
        imgs_dir = "./imgs_comp_box"
        imgs_mask_dir = "./imgs_mask_box"

        self.str_imgs_fns = []
        self.str_mask_fns = []

        dirs = []

        for parent, dirnames, filenames in os.walk(imgs_mask_dir):
            for dirname in dirnames:
                dirs.append(dirname)

        for str_dir in dirs:
            str_dir_path = imgs_mask_dir + "/" + str_dir
            for parent, dirnames, filenames in os.walk(str_dir_path):
                for filename in filenames:
                    str_path = str_dir_path + "/" + filename
                    self.str_mask_fns.append(str_path)
                    idx = filename.find(".png")
                    str_img_path = imgs_dir + "/" + str_dir + "/" + filename[:
                                                                             idx] + ".png"
                    self.str_imgs_fns.append(str_img_path)

        self.autoencoder = AutoEncoder()

        self.win = Gtk.Window()
        self.win.connect("delete-event", self.win_quit)
        self.win.set_default_size(1000, 600)
        self.win.set_title("show imgs")

        self.sw = Gtk.ScrolledWindow()
        self.win.add(self.sw)
        self.sw.set_border_width(2)

        fig = Figure(figsize=(8, 8), dpi=80)
        self.canvas = FigureCanvas(fig)
        self.canvas.set_size_request(1000, 600)
        self.sw.add(self.canvas)
        self.win.show_all()

        self.torch_lock = threading.Lock()
        self.torch_show_data = {}
        self.n_test_imgs = 5
        self.torch_show_data["mess_quit"] = False

        thread_torch = Encoder_Thread(self.update_torch_data,
                                      self.torch_lock,
                                      self.autoencoder,
                                      self.str_imgs_fns,
                                      self.str_mask_fns,
                                      self.torch_show_data,
                                      wh=97,
                                      max_n_loop=1,
                                      n_loop=0,
                                      idx_segment=0)

        thread_torch.start()
예제 #29
0
    def __init__(self, main_window, settings, data, add_layer_dataset, add_feature, redraw_main):
        """
        Initializes the RotationDialog class.

        Requires the main_window object, the settings object (PlotSettings
        class) and the data rows to initialize. All the necessary widgets are
        loaded from the Glade file. A matplotlib figure is set up and added
        to the scrolledwindow. Two axes are set up that show the original and
        rotated data.
        """
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain(i18n().get_ts_domain())
        script_dir = os.path.dirname(__file__)
        rel_path = "gui_layout.glade"
        abs_path = os.path.join(script_dir, rel_path)
        self.builder.add_objects_from_file(abs_path,
            ("dialog_rotation", "adjustment_rotation_dipdir",
             "adjustment_rotation_dip", "adjustment_rotation_angle"))
        self.dialog = self.builder.get_object("dialog_rotation")
        self.dialog.set_transient_for(main_window)
        self.settings = settings
        self.data = data
        self.trans = self.settings.get_transform()
        self.add_layer_dataset = add_layer_dataset
        self.add_feature = add_feature
        self.redraw_main = redraw_main

        self.adjustment_rotation_dipdir = self.builder.get_object("adjustment_rotation_dipdir")
        self.adjustment_rotation_dip = self.builder.get_object("adjustment_rotation_dip")
        self.adjustment_rotation_angle = self.builder.get_object("adjustment_rotation_angle")

        self.spinbutton_rotation_dipdir = self.builder.get_object("spinbutton_rotation_dipdir")
        self.spinbutton_rotation_dip = self.builder.get_object("spinbutton_rotation_dip")
        self.spinbutton_rotation_angle = self.builder.get_object("spinbutton_rotation_angle")

        self.scrolledwindow_rotate = self.builder.get_object("scrolledwindow_rotate")

        self.fig = Figure(dpi=self.settings.get_pixel_density())
        self.canvas = FigureCanvas(self.fig)
        self.scrolledwindow_rotate.add_with_viewport(self.canvas)

        gridspec = GridSpec(1, 2)
        original_sp = gridspec.new_subplotspec((0, 0),
                                             rowspan=1, colspan=1)
        rotated_sp = gridspec.new_subplotspec((0, 1),
                                           rowspan=1, colspan=1)
        self.original_ax = self.fig.add_subplot(original_sp,
                                         projection=self.settings.get_projection())
        self.rotated_ax = self.fig.add_subplot(rotated_sp,
                                         projection=self.settings.get_projection())

        self.canvas.draw()
        self.redraw_plot()
        self.dialog.show_all()
        self.builder.connect_signals(self)
        if sys.platform == "win32":
            translate_gui(self.builder)
예제 #30
0
파일: app.py 프로젝트: Hillash/QuantPy
    def onGoPressed(self, button):
        symbol = self.symbol.get_text()
        asset = pd.io.data.DataReader(symbol, 'yahoo')

        figure = Figure(figsize=(5, 4), dpi=100, frameon=False)
        subplot = figure.add_subplot(1, 1, 1)
        subplot.plot(asset.index, asset['Adj Close'])
        subplot.autoscale_view(True, True, True)

        canvas = FigureCanvas(figure)
        canvas.set_size_request(500, 250)

        sw = self.app.builder.get_object('scrolledwindow1')
        # remove old children
        for child in sw.get_children():
            sw.remove(child)
        sw.add(canvas)
        sw.show_all()
예제 #31
0
    def init_gui(self):
        self.builder = Gtk.Builder()
        self.builder.add_from_file("finally.glade")

        self.builder.connect_signals( 
                                    {
                                      "window_destroy"  : self.window_destroy,
                                      "press_button"    : self.press_button,
                                      "clear_text"      : self.clear_text,
                                      "remove_last_char": self.remove_last_char,
                                      "calculate"       : self.calculate,
                                      "switch_page"     : self.switch_page,
                                      "num_base_change" : self.num_base_change,
                                      "fix_cursor"      : self.fix_cursor,
                                      "enable_textview" : self.enable_textview,
                                      "disable_textview": self.disable_textview,
                                      "prog_calc"       : self.prog_calc,
                                      "back_to_future"  : self.back_to_future,
                                      "plot"            : self.plot
                                    }
                                    )

        self.window = self.builder.get_object("main_window")
        self.window.set_size_request(250,305)
        self.window.set_title("The Calculator")
        self.window.set_icon_from_file("/usr/share/pixmaps/thecalculator-icon.png")
        self.text_buff = self.builder.get_object("class_17").get_buffer()  # Access buffer from TextView
        self.builder.get_object("class_17").grab_focus()
        self.builder.get_object("radiobutton3").set_active(True)
        self.num_base_change(self.builder.get_object("radiobutton3"))

        ############### PLOT FUNCTION ##############

        sw = self.builder.get_object("scrolledwindow1")
        sw2 = self.builder.get_object("scrolledwindow2")

        fig = Figure(figsize=(5,5),dpi=120)
        self.ax = fig.add_subplot(111)

        self.x = arange(-3.1415,3.1415,0.01)
        self.y = sin(self.x)

        self.ax.plot(self.x,self.y,label="sin(x)")
        self.ax.set_xlim(-3.2,3.2)
        self.ax.set_ylim(-1.2,1.2)
        self.ax.grid(True)

        fig.set_size_inches(9.5, 5.5, forward=True)

        fig.tight_layout()

        self.canvas = FigureCanvas(fig)
        sw.add_with_viewport(self.canvas)
        self.canvas.show()

        toolbar = NavigationToolbar(self.canvas, self.window)
        sw2.add_with_viewport(toolbar)
예제 #32
0
 def __init__(self, dark):
     self.figure = Figure(figsize=(0, 1000),
                          dpi=75,
                          facecolor='w',
                          edgecolor='k')
     self.axes = self.figure.add_axes([0.12, 0.08, 0.75, 0.90])
     self.figure.patch.set_alpha(0)
     self.axes.margins(0, 0.05)
     self.axes.ticklabel_format(useOffset=False)
     self.axes.xaxis.set_major_locator(
         MultipleLocatorWithMargin(600, 0, 0.03))
     self.axes.xaxis.set_major_formatter(
         ticker.FuncFormatter(lambda x, pos: "{}m".format(int(x / 60))))
     if dark:
         self.axes.patch.set_facecolor('black')
     FigureCanvas.__init__(self, self.figure)
     self.set_size_request(400, 300)
     self.lines = {}
     self.texts = {}
예제 #33
0
 def __init__(self):
     # ### Initialise les datas###
     self.array_size = 10
     self.nbr_dots = 1
     # ###########################
     self.builder = Gtk.Builder()  # voir commentaires lignes 21-25
     # self.builder = gtk.Builder()
     self.builder.add_from_file(
         os.path.join(os.getcwd(), 'TBench_GUI_gl3.ui'))
     self.window = self.builder.get_object('dialog1')
     self.aboutdialog = self.builder.get_object('aboutdialog1')
     self.assistant = self.builder.get_object('assistant1')
     self.textview = self.builder.get_object('textview1')
     self.textbuffer = self.builder.get_object('textbuffer1')
     self.bt_exit = self.builder.get_object('bt_exit')
     self.tbt_state0 = self.builder.get_object('tbt_state0')
     self.tbt_state1 = self.builder.get_object('tbt_state1')
     self.tbt_state2 = self.builder.get_object('tbt_state2')
     self.imagemenuitem5 = self.builder.get_object('imagemenuitem5')
     self.imagemenuitem10 = self.builder.get_object('imagemenuitem10')
     self.builder.connect_signals(self)
     self.bufsize = 10  # ajout 20.02
     self.databuffer = collections.deque([0.0] * self.bufsize,
                                         self.bufsize)  # ajout 20.02
     self.x = [1 * i for i in range(-self.bufsize + 1, 1)
               ]  # ajout 20.02(-self.bufsize+1,1)
     # Matplotlib trucs
     self.figure = Figure(figsize=(100, 100), dpi=100)
     self.ax = self.figure.add_subplot(111)
     self.canvas = FigureCanvas(self.figure)  # une gtk.DrawingArea
     self.line, = self.ax.plot(self.x, self.databuffer)
     # Gtk trucs
     self.canvas.show()
     self.graphview = self.builder.get_object("plot")
     self.graphview.pack_start(self.canvas, True, True, True)
     self.arrow = self.builder.get_object('arrow1')
     self.window.connect('delete-event', self.quit)
     self.tbt_state0.connect('toggled', self.on_button_toggled0)
     self.tbt_state1.connect('toggled', self.on_button_toggled1)
     self.tbt_state2.connect('toggled', self.on_button_toggled2)
     self.bt_exit.connect('clicked', self.quit)
     self.imagemenuitem5.connect('activate', self.quit)
     self.imagemenuitem10.connect('activate', self.show_aboutdialog)
     self.window.show()
     # ================= Recherche du port de l'arduino ====================
     self.sonde = arduino.search()
     if self.sonde == "impossible d'ouvrir un port série":
         info = (
             self.sonde + "!" + '\n' +
             "quitter cette session, vérifier la connexion avec le PLC, puis relancer le programme"
         )
         self.ajout_log_term("TB", info)
     else:
         self.ajout_log_term("PLC", self.sonde)
         self.init_arduino()  # initialise l'arduino
예제 #34
0
    def __init__(self, pid):
        Gtk.Window.__init__(self, title="Auto-tune")
        self.pid = pid
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        f = matplotlib.figure.Figure()
        self.axes = f.add_subplot(111)
        self.axes.set_xlabel('Time (sec.)')
        self.axes.set_ylabel('Temperature (C)')
        self.axes.autoscale()
        self.out_axes = self.axes.twinx()
        self.out_axes.set_ylabel('OUT (%)')
        self.out_axes.autoscale()
        self.axes.grid()
        self.pv_x = []
        self.pv_y = []
        self.sv_x = []
        self.sv_y = []
        self.out_x = []
        self.out_y = []
        self.pv_plot, = self.axes.plot(self.pv_x, self.pv_y, 'b--') #b
        self.sv_plot, = self.axes.plot(self.sv_x, self.sv_y, 'k-') #k
        self.out_plot, = self.out_axes.plot(self.out_x, self.out_y, 'r:') #r

        self.canvas = FigureCanvas(f)
        self.canvas.set_size_request(800,600)

        vbox.add(self.canvas)

        hbox = Gtk.Box()

        self.start = Gtk.Button('Start', Gtk.STOCK_EXECUTE)
        self.start.connect('clicked', self.on_start)
        self.start.set_sensitive(False)
        hbox.pack_start(self.start, False, False, 0)

        self.stop = Gtk.Button('Stop', Gtk.STOCK_STOP)
        self.stop.connect('clicked', self.on_stop)
        self.stop.set_sensitive(False)
        hbox.pack_start(self.stop, False, False, 0)

        button = Gtk.Button('Close', Gtk.STOCK_CLOSE)
        button.connect('clicked', self.on_close)
        hbox.pack_end(button, False, False, 0)

        vbox.add(hbox)

        self.add(vbox)
        self.run = True
        self.start_at = True
        self.stop_at = False
        self.d = self.loop()
        self.d.addErrback(lambda x: None)
        self.connect('delete-event', self.on_delete)
예제 #35
0
    def setup(self):
        fig = Figure(figsize=(10, 10), dpi=100, facecolor="white", edgecolor="white")
        self.ax = fig.add_subplot(111)
        fig.subplots_adjust(left=0.1, right=0.90, top=0.95, bottom=0.05)
        # ensure the pie is round
        self.ax.set_aspect('equal')

        matplotlib.rc('font', family="sans", weight="normal", size=9)

        self.plot = FigureCanvas(fig)
        self.pack_start(self.plot, True, True, 0)
예제 #36
0
 def run_inner(self, endog, exog, **kwargs ):
     
     signs = ['x', '+']
     colours = ['r', 'b']
             
     f = plt.figure()
     
     var_index = 0
     for var in exog.columns:
         sign = signs[var_index % len( signs )]
         colour = colours[var_index % len( colours )]
         plt.plot( endog, exog[var], colour+sign )
         var_index += 1
     
     canvas = FigureCanvas( f )
     
     self.ui.output_vbox.pack_start( canvas, True, True, 0 )
     canvas.show()
     self.ui.output_dialog.run()
     self.ui.output_dialog.hide()
예제 #37
0
class PlotterGUI:
    def __init__(self):
        self.builder = Gtk.Builder()
        self.builder.add_from_file("plotter.xml")
        self.window = self.builder.get_object("plotter_window")

        cdt = plotter.get_dict_from_file("data/test.txt")
        plt = plotter.get_plot_from_dict(cdt)
        plt.draw()

        self.canvas = FigureCanvas(plt.gcf())
        self.canvas.set_size_request(750, 550)
        self.builder.get_object("plotter_plot_scrollable").add_with_viewport(
            self.canvas)
        self.toolbar = NavigationToolbar(self.canvas, self.window)
        self.builder.get_object(
            "plotter_toolbar_scrollable").add_with_viewport(self.toolbar)
        self.window.show_all()

    def destroy(self):
        self.window.destroy()
예제 #38
0
    def setup_matplotlib_widget(self):
        self.figure = Figure(dpi=72)

        self.plot = self.figure.add_subplot(111)
        self.figure.subplots_adjust(bottom=0.20)

        self.matlib_canvas = FigureCanvasGTK(self.figure)

        self.plot.autoscale_view()

        self.graph_parent.add(self.matlib_canvas)
        self.graph_parent.show_all()
예제 #39
0
    def setup_matplotlib_widget(self):
        self.figure = Figure(dpi=72)

        self.plot = self.figure.add_subplot(111)
        self.figure.subplots_adjust(bottom=0.20)

        self.matlib_canvas = FigureCanvasGTK(self.figure)

        self.plot.autoscale_view()

        self.graph_parent.add(self.matlib_canvas)
        self.graph_parent.show_all()
예제 #40
0
def plot_overlay(test_accuracy, training_accuracy, num_epochs, xmin,
                 training_set_size, vbox):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(np.arange(xmin, num_epochs),
            [accuracy / 100.0 for accuracy in test_accuracy],
            color='#2A6EA6',
            label="Accuracy on the test data")
    ax.plot(np.arange(xmin, num_epochs), [
        accuracy * 100.0 / training_set_size for accuracy in training_accuracy
    ],
            color='#FFA933',
            label="Accuracy on the training data")
    ax.grid(True)
    ax.set_xlim([xmin, num_epochs])
    ax.set_xlabel('Epoch')
    ax.set_ylim([90, 100])
    plt.legend(loc="lower right")
    #plt.show()
    canvas = FigureCanvas(fig)
    canvas.set_size_request(1400, 600)
    vbox.pack_start(canvas, True, True, 0)
예제 #41
0
    def create_graph(self):
        fig = Figure()
        self.axTemperature = fig.add_subplot(111, xlabel="Temps [s]")
        self.axHumidity = self.axTemperature.twinx()
        self.set_graph_axis(TimeScale.SECONDS)

        sw = Gtk.ScrolledWindow()
        vbox_graph = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        vbox_graph.pack_start(sw, True, True, 10)
        self.plot_canvas = FigureCanvas(fig)
        self.plot_canvas.set_size_request(400, 400)
        sw.add_with_viewport(self.plot_canvas)
        self.hbox.pack_start(vbox_graph, True, True, 5)
예제 #42
0
    def __init__(self):
        uigtk.widgets.Grid.__init__(self)

        figure = Figure()
        axis = figure.add_subplot(1, 1, 1)
        axis.set_xlim(0, 46)
        axis.set_xlabel("Week")
        axis.set_ylim(0, 100)
        axis.set_ylabel("Percentage Rating")

        values = [0] * 46
        line, = axis.plot(values, label='Chairman')
        line, = axis.plot(values, label='Staff')
        line, = axis.plot(values, label='Fans')
        line, = axis.plot(values, label='Finances')
        line, = axis.plot(values, label='Media')
        axis.legend()

        figurecanvas = FigureCanvas(figure)
        figurecanvas.set_hexpand(True)
        figurecanvas.set_vexpand(True)
        self.add(figurecanvas)
예제 #43
0
class EditAtomTypeView(BaseView):
    builder = resource_filename(__name__, "glade/atoms.glade")
    top = "edit_atom_type"
    widget_format = "atom_%s"

    # ------------------------------------------------------------
    #      Initialisation and other internals
    # ------------------------------------------------------------
    def __init__(self, *args, **kwargs):
        BaseView.__init__(self, *args, **kwargs)

        self.graph_parent = self["view_graph"]
        self.setup_matplotlib_widget()

    def setup_matplotlib_widget(self):
        self.figure = Figure(dpi=72)

        self.plot = self.figure.add_subplot(111)
        self.figure.subplots_adjust(bottom=0.20)

        self.matlib_canvas = FigureCanvasGTK(self.figure)

        self.plot.autoscale_view()

        self.graph_parent.add(self.matlib_canvas)
        self.graph_parent.show_all()

    # ------------------------------------------------------------
    #      Methods & Functions
    # ------------------------------------------------------------
    def update_figure(self, x, y):
        self.plot.cla()
        self.plot.plot(x, y, 'k-', aa=True)
        self.plot.set_ylabel('Scattering factor', size=14, weight="heavy")
        self.plot.set_xlabel('2θ', size=14, weight="heavy")
        self.plot.autoscale_view()
        if self.matlib_canvas is not None:
            self.matlib_canvas.draw()
예제 #44
0
class EditAtomTypeView(BaseView):
    builder = resource_filename(__name__, "glade/atoms.glade")
    top = "edit_atom_type"
    widget_format = "atom_%s"

    # ------------------------------------------------------------
    #      Initialisation and other internals
    # ------------------------------------------------------------
    def __init__(self, *args, **kwargs):
        BaseView.__init__(self, *args, **kwargs)

        self.graph_parent = self["view_graph"]
        self.setup_matplotlib_widget()

    def setup_matplotlib_widget(self):
        self.figure = Figure(dpi=72)

        self.plot = self.figure.add_subplot(111)
        self.figure.subplots_adjust(bottom=0.20)

        self.matlib_canvas = FigureCanvasGTK(self.figure)

        self.plot.autoscale_view()

        self.graph_parent.add(self.matlib_canvas)
        self.graph_parent.show_all()

    # ------------------------------------------------------------
    #      Methods & Functions
    # ------------------------------------------------------------
    def update_figure(self, x, y):
        self.plot.cla()
        self.plot.plot(x, y, 'k-', aa=True)
        self.plot.set_ylabel('Scattering factor', size=14, weight="heavy")
        self.plot.set_xlabel('2θ', size=14, weight="heavy")
        self.plot.autoscale_view()
        if self.matlib_canvas is not None:
            self.matlib_canvas.draw()
예제 #45
0
 def __init__(self):
     # ### Initialise les datas###
     self.array_size = 10
     self.nbr_dots = 1
     # ###########################
     self.builder = Gtk.Builder()  # voir commentaires lignes 21-25
     # self.builder = gtk.Builder()
     self.builder.add_from_file(os.path.join(os.getcwd(), 'TBench_GUI_gl3.ui'))
     self.window = self.builder.get_object('dialog1')
     self.aboutdialog = self.builder.get_object('aboutdialog1')
     self.assistant = self.builder.get_object('assistant1')
     self.textview = self.builder.get_object('textview1')
     self.textbuffer = self.builder.get_object('textbuffer1')
     self.bt_exit = self.builder.get_object('bt_exit')
     self.tbt_state0 = self.builder.get_object('tbt_state0')
     self.tbt_state1 = self.builder.get_object('tbt_state1')
     self.tbt_state2 = self.builder.get_object('tbt_state2')
     self.imagemenuitem5 = self.builder.get_object('imagemenuitem5')
     self.imagemenuitem10 = self.builder.get_object('imagemenuitem10')
     self.builder.connect_signals(self)
     self.bufsize = 10  # ajout 20.02
     self.databuffer = collections.deque([0.0] * self.bufsize, self.bufsize)  # ajout 20.02
     self.x = [1 * i for i in range(-self.bufsize + 1, 1)]  # ajout 20.02(-self.bufsize+1,1)
     # Matplotlib trucs
     self.figure = Figure(figsize=(100, 100), dpi=100)
     self.ax = self.figure.add_subplot(111)
     self.canvas = FigureCanvas(self.figure)  # une gtk.DrawingArea
     self.line, = self.ax.plot(self.x, self.databuffer)
     # Gtk trucs
     self.canvas.show()
     self.graphview = self.builder.get_object("plot")
     self.graphview.pack_start(self.canvas, True, True, True)
     self.arrow = self.builder.get_object('arrow1')
     self.window.connect('delete-event', self.quit)
     self.tbt_state0.connect('toggled', self.on_button_toggled0)
     self.tbt_state1.connect('toggled', self.on_button_toggled1)
     self.tbt_state2.connect('toggled', self.on_button_toggled2)
     self.bt_exit.connect('clicked', self.quit)
     self.imagemenuitem5.connect('activate', self.quit)
     self.imagemenuitem10.connect('activate', self.show_aboutdialog)
     self.window.show()
     # ================= Recherche du port de l'arduino ====================
     self.sonde = arduino.search()
     if self.sonde == "impossible d'ouvrir un port série":
         info = (self.sonde + "!" + '\n' +
                 "quitter cette session, vérifier la connexion avec le PLC, puis relancer le programme")
         self.ajout_log_term("TB", info)
     else:
         self.ajout_log_term("PLC", self.sonde)
         self.init_arduino()  # initialise l'arduino
예제 #46
0
파일: views.py 프로젝트: fbocches/PyXRD
    def setup_matplotlib_widget(self):
        #style = Gtk.Style()
        self.figure = Figure(
            dpi=72)  #, edgecolor=str(style.bg[2]), facecolor=str(style.bg[2]))

        self.plot = self.figure.add_subplot(111)
        self.figure.subplots_adjust(bottom=0.20)

        self.matlib_canvas = FigureCanvasGTK(self.figure)

        self.plot.autoscale_view()

        self.graph_parent.add(self.matlib_canvas)
        self.graph_parent.show_all()
    def __init__(self):
        Gtk.Window.__init__(self, title="ADC View Window")

        self.set_default_size(800, 800)

        self.figure = Figure(figsize=(8, 8), dpi=100)

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

        canvas = FigureCanvas(self.figure)  # a Gtk.DrawingArea
        canvas.set_size_request(750, 750)
        sw.add_with_viewport(canvas)

        self.show_all()

        self.sw = sw
        self.canvas = canvas

        self.femb = None
        self.reset()
예제 #48
0
    def __init__(self):
        self.interface = Gtk.Builder()
        self.interface.add_from_file('UI.glade')
        self.interface.connect_signals(self)
        self.window = self.interface.get_object('Main')

        # first
        self.sw1 = self.interface.get_object('firstScrolled')
        self.fig1 = Figure()
        self.a1 = self.fig1.add_subplot(111)
        self.a1.plot(self.x1, self.y1)
        self.canvas1 = FigureCanvas(self.fig1)
        self.sw1.add_with_viewport(self.canvas1)

        # second
        self.sw2 = self.interface.get_object('secondScrolled')
        self.fig2 = Figure(figsize=(5, 5), dpi=100)
        self.a2 = self.fig2.add_subplot(111)
        self.a2.plot(self.x2, self.y2)
        self.canvas2 = FigureCanvas(self.fig2)
        self.sw2.add_with_viewport(self.canvas2)

        self.window.show_all()
예제 #49
0
class Pie(ChartBase):

    def setup(self):
        fig = Figure(figsize=(10, 10), dpi=100, facecolor="white", edgecolor="white")
        self.ax = fig.add_subplot(111)
        fig.subplots_adjust(left=0.1, right=0.90, top=0.95, bottom=0.05)
        # ensure the pie is round
        self.ax.set_aspect('equal')

        matplotlib.rc('font', family="sans", weight="normal", size=9)

        self.plot = FigureCanvas(fig)
        self.pack_start(self.plot, True, True, 0)

    def draw_plot(self):
        self.ax.clear()
        self.ax.pie(self.controller.values.values(),
                    labels=self.controller.values.keys(),
                    autopct='%1.1f%%',
                    colors=self.colors
                    )
        # show pie
        self.spinner.hide()
        self.plot.show()
예제 #50
0
 def setup_image_box(self):
     
     xx = self.xsize / float(self.dpi)    # inches
     yy = self.ysize / float(self.dpi)    # inches
     
     # TODO: make it resizable
     self.fig = Figure(figsize=(xx, yy), dpi=self.dpi)
     self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea 
     
     # setup drawing canvas
     self.canvas.set_size_request(self.xsize, self.ysize) 
     self.canvas.connect('button-press-event'  , self.on_canvas_button_press)
     self.canvas.connect('button-release-event', self.on_canvas_button_release)
     self.canvas.connect('motion-notify-event' , self.on_canvas_motion_notify)
     self.image_box.add(self.canvas)  
    def __init__(self):
        # Gets all the objects of interest: windows, list boxes, graphviews etc
        self.builder = Gtk.Builder()
        self.builder.add_from_file('gui/igl-app-window.glade')
        self.builder.connect_signals(self)

        self.window = self.builder.get_object('window1')

        self.sw = self.builder.get_object('graphscrollwindow')
        self.sw2 = self.builder.get_object('graphtools')

        self.gtbrevealer = self.builder.get_object('graphtoolsrevealer')
        self.m1revealer = self.builder.get_object('method1revealer')
        self.m2revealer = self.builder.get_object('method2revealer')

        self.fnbox = self.builder.get_object('functioncbtext')
        self.aentry = self.builder.get_object('aentry')
        self.bentry = self.builder.get_object('bentry')

        # Use Headerbar for inputs

        self.hb = Gtk.HeaderBar()
        self.hb.set_show_close_button(True)
        self.hb.set_custom_title(self.builder.get_object('titlebox'))

        self.window.set_titlebar(self.hb)

        # Adds widgets that change the view as per method

        self.m1box = guisetup.MethodDetailsBox()
        self.m2box = guisetup.MethodDetailsBox()
        self.m1revealer.add(self.m1box)
        self.m2revealer.add(self.m2box)
        self.m1box.mc = self
        self.m2box.mc = self
        
        # TODO: Plot as per the defaults to get started

        self.fig = Figure(figsize=(5,5), dpi=80)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.sw.add_with_viewport(self.canvas)

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

        self.on_params_changed(None)
예제 #52
0
    def __init__(self, main_controller):
        """ Initializes figure. Sets a default alpha. Initializes
        configuration dictionary. Initializes context menu. Connects
        button release event on canvas.
        """
        self.main_controller = main_controller
        self.figure = Figure()
        self.figure.patch.set_alpha(0.0)
        self.canvas = FigureCanvas(self.figure)

        self.customize_window = None
        self.config = OrderedDict()

        self._context_menu = gtk.Menu()
        self._build_context_menu()
        self.canvas.connect("button_release_event", self.on_button_release,
                            self.canvas)
예제 #53
0
    def setup(self):
        fig = Figure(figsize=(5, 5), dpi=100, facecolor="white", edgecolor="white")
        self.ax = fig.add_subplot(111)

        fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.2)

        # font
        matplotlib.rc('font', family="sans", weight="normal", size=9)

        # frame
        self.ax.set_frame_on(False)

        # pack fig
        self.plot = FigureCanvas(fig)
        self.pack_start(self.plot, True, True, 0)

        # connect events
        fig.canvas.mpl_connect('motion_notify_event', self.on_move)
예제 #54
0
    def setup(self):
        fig = Figure(dpi=100, facecolor="white", edgecolor="white")
        self.ax = ax = fig.add_subplot(111)
        fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)

        # gridlines
        ax.yaxis.grid(color='gray')
        ax.xaxis.grid(color='gray')

        # background
        # ax.patch.set_alpha(1)

        # font
        matplotlib.rc('font', family="sans", weight="normal", size=9)

        # frame
        ax.set_frame_on(False)

        # formatter
        formatter = FuncFormatter(gui_utils.get_currency_format_from_float)
        ax.yaxis.set_major_formatter(formatter)
        formatter = FuncFormatter(self.x_formatter)
        ax.xaxis.set_major_formatter(formatter)

        self.ax.autoscale(enable=True, axis='both', tight=True)

        # annotation
        self.annotation = ax.annotate("foo",
                xy=(0.0, 0.0), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                color='white',
                bbox=dict(boxstyle='round,pad=0.5', color=self.colors[0]),
                # arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
                )
        self.annotation.set_visible(False)

        # pack
        self.plot = FigureCanvas(fig)
        self.pack_start(self.plot, True, True, 0)

        # connect events
        fig.canvas.mpl_connect('motion_notify_event', self.on_move)
예제 #55
0
class StatPerspective(Gtk.Box, Ide.Perspective):

    """
    Sets up the stats perspective and handles the signals.

    This class sets up the containers of the perspective
    and the matplotlib figure and canvas. An asynchronous
    method iterates over the project and gathers the data
    for the plot.
    """

    def __init__(self, workdir, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.workdir = workdir

        # main containers
        scr_win = Gtk.ScrolledWindow(visible=True)
        pad_box = Gtk.Box(visible=True)
        pad_box.pack_start(scr_win, True, True, 20)

        main_box = Gtk.Box(visible=True, orientation=Gtk.Orientation.VERTICAL)
        scr_win.add_with_viewport(main_box)

        # content
        lbl_head = '<span font="36.0"><b>Project Stats</b></span>'
        heading = Gtk.Label(label=lbl_head, expand=True, visible=True)
        heading.set_use_markup(True)
        main_box.pack_start(heading, False, False, 0)
        line = Gtk.Separator(visible=True)
        main_box.pack_start(line, False, False, 0)

        self.fig = Figure(facecolor='none')
        self.ax = self.fig.add_subplot(111, axisbg='#ffffff')
        self.canvas = FigCanvas(self.fig)
        self.canvas.set_size_request(800, 600)
        self.canvas.draw()
        self.canvas.show()
        main_box.pack_start(self.canvas, True, True, 0)

        self.add(pad_box)
        self.titlebar = Ide.WorkbenchHeaderBar(visible=True)

         # Gather stats
        thread = threading.Thread(target=self.gather_stats)
        thread.daemon = True
        thread.start()

    def gather_stats(self):
        file_types = {}

        for root, subfolders, files in os.walk(self.workdir):
            for file in files:
                try:
                    with open(root + "/" + file) as fl:
                        line_count = 0
                        for line in fl:
                            line_count += 1

                        splt_str = file.split(".")
                        if len(splt_str) > 1:
                            file_ext = splt_str[-1]
                        else:
                            continue
                        if file_ext in file_types:
                            # key exists, add line count
                            file_types[file_ext] = file_types[file_ext] + line_count
                        else:
                            # key doesn't exist, create new key
                            file_types[file_ext] = line_count
                except:
                    continue

        keys = []
        values = []

        for key, value in file_types.items():
            keys.append(key)
            values.append(value)

        key_ar = np.array(keys)
        val_ar = np.array(values).astype(int)

        ar = np.vstack((key_ar, val_ar)).T
        ar = ar[ar[:,1].astype(int).argsort()]
        rows = ar.shape[0]
        val_pos = np.arange(1, ar.shape[0]+1)

        self.ax.barh(val_pos, ar[:,1].astype(int), 0.8, align="center")
        # facecolor='yellow'
        self.ax.set_yticks(val_pos)
        self.ax.tick_params(axis="both", which="major", pad=15)
        self.ax.set_yticklabels(ar[:,0], fontsize="16", weight="bold")
        self.ax.tick_params(axis="x", which="major", labelsize="16")

        self.canvas.set_size_request(800, (rows * 20 + 50))
        self.canvas.draw()

    def do_get_id(self):
        return 'hello-world2'

    def do_get_title(self):
        return 'Hello'

    def do_get_priority(self):
        return 10000

    def do_get_icon_name(self):
        return "utilities-system-monitor-symbolic"

    def do_get_titlebar(self):
        return self.titlebar
예제 #56
0
class GraphBase(object):
	"""
	A basic graph provider for using :py:mod:`matplotlib` to create graph
	representations of campaign data. This class is meant to be subclassed
	by real providers.
	"""
	name = 'Unknown'
	"""The name of the graph provider."""
	name_human = 'Unknown'
	"""The human readable name of the graph provider used for UI identification."""
	graph_title = 'Unknown'
	"""The title that will be given to the graph."""
	is_available = True
	def __init__(self, application, size_request=None, style_context=None):
		"""
		:param tuple size_request: The size to set for the canvas.
		"""
		self.application = application
		self.style_context = style_context
		self.config = application.config
		"""A reference to the King Phisher client configuration."""
		self.figure, _ = pyplot.subplots()
		self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE))
		self.axes = self.figure.get_axes()
		self.canvas = FigureCanvas(self.figure)
		self.manager = None
		self.minimum_size = (380, 200)
		"""An absolute minimum size for the canvas."""
		if size_request is not None:
			self.resize(*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.application.get_active_window())

		self.popup_menu = managers.MenuManager()
		self.popup_menu.append('Export', self.signal_activate_popup_menu_export)
		self.popup_menu.append('Refresh', self.signal_activate_popup_refresh)

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

		self.navigation_toolbar.hide()
		self._legend = None

	@property
	def rpc(self):
		return self.application.rpc

	@staticmethod
	def _ax_hide_ticks(ax):
		for tick in ax.yaxis.get_major_ticks():
			tick.tick1On = False
			tick.tick2On = False

	@staticmethod
	def _ax_set_spine_color(ax, spine_color):
		for pos in ('top', 'right', 'bottom', 'left'):
			ax.spines[pos].set_color(spine_color)

	def add_legend_patch(self, legend_rows, fontsize=None):
		if self._legend is not None:
			self._legend.remove()
			self._legend = None
		fontsize = fontsize or self.fontsize_scale
		legend_bbox = self.figure.legend(
			tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows),
			tuple(label for _, label in legend_rows),
			borderaxespad=1.25,
			fontsize=fontsize,
			frameon=True,
			handlelength=1.5,
			handletextpad=0.75,
			labelspacing=0.3,
			loc='lower right'
		)
		legend_bbox.legendPatch.set_linewidth(0)
		self._legend = legend_bbox

	def get_color(self, color_name, default):
		"""
		Get a color by its style name such as 'fg' for foreground. If the
		specified color does not exist, default will be returned. The underlying
		logic for this function is provided by
		:py:func:`~.gui_utilities.gtk_style_context_get_color`.

		:param str color_name: The style name of the color.
		:param default: The default color to return if the specified one was not found.
		:return: The desired color if it was found.
		:rtype: tuple
		"""
		color_name = 'theme_color_graph_' + color_name
		sc_color = gui_utilities.gtk_style_context_get_color(self.style_context, color_name, default)
		return (sc_color.red, sc_color.green, sc_color.blue)

	def make_window(self):
		"""
		Create a window from the figure manager.

		:return: The graph in a new, dedicated window.
		:rtype: :py:class:`Gtk.Window`
		"""
		if self.manager is None:
			self.manager = FigureManager(self.canvas, 0)
		self.navigation_toolbar.destroy()
		self.navigation_toolbar = self.manager.toolbar
		self._menu_item_show_toolbar.set_active(True)
		window = self.manager.window
		window.set_transient_for(self.application.get_active_window())
		window.set_title(self.graph_title)
		return window

	@property
	def fontsize_scale(self):
		scale = self.markersize_scale
		if scale < 5:
			fontsize = 'xx-small'
		elif scale < 7:
			fontsize = 'x-small'
		elif scale < 9:
			fontsize = 'small'
		else:
			fontsize = 'medium'
		return fontsize

	@property
	def markersize_scale(self):
		bbox = self.axes[0].get_window_extent().transformed(self.figure.dpi_scale_trans.inverted())
		return bbox.width * self.figure.dpi * 0.01

	def mpl_signal_canvas_button_pressed(self, event):
		if event.button != 3:
			return
		self.popup_menu.menu.popup(None, None, None, None, event.button, Gtk.get_current_event_time())
		return True

	def signal_activate_popup_menu_export(self, action):
		dialog = extras.FileChooserDialog('Export Graph', self.application.get_active_window())
		file_name = self.config['campaign_name'] + '.png'
		response = dialog.run_quick_save(file_name)
		dialog.destroy()
		if not response:
			return
		destination_file = response['target_path']
		self.figure.savefig(destination_file, dpi=200, facecolor=self.figure.get_facecolor(), format='png')

	def signal_activate_popup_refresh(self, event):
		self.refresh()

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

	def resize(self, width=0, height=0):
		"""
		Attempt to resize the canvas. Regardless of the parameters the canvas
		will never be resized to be smaller than :py:attr:`.minimum_size`.

		:param int width: The desired width of the canvas.
		:param int height: The desired height of the canvas.
		"""
		min_width, min_height = self.minimum_size
		width = max(width, min_width)
		height = max(height, min_height)
		self.canvas.set_size_request(width, height)
예제 #57
0
파일: hp8903.py 프로젝트: cosmonaut/hp8903
    def __init__(self):
        Gtk.Window.__init__(self, title="HP 8903B Control")

        # Serial connection!
        self.ser = None
        self.gpib_dev = None
        self.devices = list_ports.comports()
        
        # Menu Bar junk!
        action_group = Gtk.ActionGroup("my_actions")
        action_filemenu = Gtk.Action("FileMenu", "File", None, None)
        action_group.add_action(action_filemenu)
        self.action_filesave = Gtk.Action("FileSave", "Save Data", None, None)
        
        action_filequit = Gtk.Action("FileQuit", None, None, Gtk.STOCK_QUIT)
        action_filequit.connect("activate", self.on_menu_file_quit)
        action_group.add_action(self.action_filesave)
        action_group.add_action(action_filequit)
        self.action_filesave.set_sensitive(False)
        self.action_filesave.connect('activate', self.save_data)

        
        uimanager = self.create_ui_manager()
        uimanager.insert_action_group(action_group)

        menubar = uimanager.get_widget("/MenuBar")

        self.status_bar = Gtk.Statusbar()
        self.status_bar.push(0, "HP 8903 Audio Analyzer Control")
        
        self.master_vbox = Gtk.Box(False, spacing = 2, orientation = 'vertical')
        self.master_vbox.pack_start(menubar, False, False, 0)
        master_hsep = Gtk.HSeparator()
        self.master_vbox.pack_start(master_hsep, False, False, 0)
        self.add(self.master_vbox)

        self.hbox = Gtk.Box(spacing = 2)
        self.master_vbox.pack_start(self.hbox, True, True, 0)

        self.master_vbox.pack_start(self.status_bar, False, False, 0)

        # Begin controls
        bframe = Gtk.Frame(label = "Control")
        left_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        self.box = Gtk.Box(spacing = 2)

        bframe.add(left_vbox)

        # GPIB device selector
        gpib_frame = Gtk.Frame(label = "GPIB Communication Device")
        self.gpib_big_box = Gtk.Box(spacing = 2)
        gpib_frame.add(self.gpib_big_box)
        self.gpib_box = Gtk.Box(spacing = 2)
        self.gpib_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        gpib_label = Gtk.Label("GPIB Device: ")
        self.gpib_box.pack_start(gpib_label, False, False, 0)

        gpib_store = Gtk.ListStore(int, str)
        for n, g_dev in enumerate(HP8903_GPIB_devices):
            gpib_store.append([n, g_dev[1]])
        self.gpib_combo = Gtk.ComboBox.new_with_model_and_entry(gpib_store)
        self.gpib_combo.set_entry_text_column(1)
        self.gpib_combo.set_active(0)

        self.gpib_box.pack_start(self.gpib_combo, False, False, 0)

        gpib_addr_box = Gtk.Box(spacing = 2)

        self.gpib_addr = Gtk.SpinButton()
        self.gpib_addr.set_range(0, 30)
        self.gpib_addr.set_digits(0)
        self.gpib_addr.set_value(0)
        self.gpib_addr.set_increments(1.0, 1.0)


        gpib_addr_label = Gtk.Label("GPIB Address: ")
        gpib_addr_box.pack_start(gpib_addr_label, False, False, 0)
        gpib_addr_box.pack_start(self.gpib_addr, False, False, 0)

        self.gpib_vbox.pack_start(self.gpib_box, False, False, 0)
        self.gpib_vbox.pack_start(gpib_addr_box, False, False, 0)

        self.gpib_big_box.pack_start(self.gpib_vbox, False, False, 0)

        left_vbox.pack_start(gpib_frame, False, False, 0)

        # Device items
        left_vbox.pack_start(self.box, False, False, 0)

        self.hbox.pack_start(bframe, False, False, 0)

        con_hbox = Gtk.Box(spacing = 2)
        self.con_button = Gtk.Button(label = "Connect")
        self.dcon_button = Gtk.Button(label = "Disconnect")

        self.con_button.connect("clicked", self.setup_gpib)
        self.dcon_button.connect("clicked", self.close_gpib)
        
        con_hbox.pack_start(self.con_button, False, False, 0)
        con_hbox.pack_start(self.dcon_button, False, False, 0)

        left_vbox.pack_start(con_hbox, False, False, 0)
        
        device_store = Gtk.ListStore(int, str)

        for i, dev in enumerate(self.devices):
            device_store.append([i, dev[0]])
        self.device_combo = Gtk.ComboBox.new_with_model_and_entry(device_store)
        self.device_combo.set_entry_text_column(1)
        self.device_combo.set_active(0)

        device_label = Gtk.Label("Device: ")
        
        self.box.pack_start(device_label, False, False, 0)
        self.box.pack_start(self.device_combo, False, False, 0)

        hsep0 = Gtk.HSeparator()
        left_vbox.pack_start(hsep0, False, False, 2)

        # Measurement Selection
        mframe = Gtk.Frame(label = "Measurement Selection")
        meas_box = Gtk.Box(spacing = 2)
        meas_vbox = Gtk.Box(spacing = 2)

        mframe.add(meas_box)
        meas_box.pack_start(meas_vbox, False, False, 0)

        meas_store = Gtk.ListStore(int, str)
        meas_dict = {0: "THD+n",
                     1:"Frequency Response",
                     2: "THD+n (Ratio)",
                     3: "Frequency Response (Ratio)",
                     4: "Ouput Level"}
        for k, v in meas_dict.iteritems():
            meas_store.append([k, v])
        self.meas_combo = Gtk.ComboBox.new_with_model_and_entry(meas_store)
        self.meas_combo.set_entry_text_column(1)
        self.meas_combo.set_active(0)

        self.meas_combo.connect("changed", self.meas_changed)
        
        meas_vbox.pack_start(self.meas_combo, False, False, 0)
        left_vbox.pack_start(mframe, False, False, 0)


        units_frame = Gtk.Frame(label = "Units")
        units_box = Gtk.Box(spacing = 2)
        units_vbox = Gtk.Box(spacing = 2)

        units_frame.add(units_box)
        units_box.pack_start(units_vbox, False, False, 0)

        self.thd_units_store = Gtk.ListStore(int, str)
        self.ampl_units_store = Gtk.ListStore(int, str)
        self.thdr_units_store = Gtk.ListStore(int, str)
        self.amplr_units_store = Gtk.ListStore(int, str)
        self.optlvl_units_store = Gtk.ListStore(int, str)
        thd_units_dict = {0: "%", 1: "dB"}
        ampl_units_dict = {0: "V", 1: "dBm"}
        thdr_units_dict = {0: "%", 1: "dB"}
        amplr_units_dict = {0: "%", 1:"dB"}
        optlvl_units_dict = {0: "V"}

        for k, v in thd_units_dict.iteritems():
            self.thd_units_store.append([k, v])
        for k, v in ampl_units_dict.iteritems():
            self.ampl_units_store.append([k, v])
        for k, v in thdr_units_dict.iteritems():
            self.thdr_units_store.append([k, v])
        for k, v in amplr_units_dict.iteritems():
            self.amplr_units_store.append([k, v])
        for k, v in optlvl_units_dict.iteritems():
            self.optlvl_units_store.append([k, v])

            
        self.units_combo = Gtk.ComboBox.new_with_model_and_entry(self.thd_units_store)
        self.units_combo.set_entry_text_column(1)
        self.units_combo.set_active(0)

        self.units_combo.connect("changed", self.units_changed)
        
        units_vbox.pack_start(self.units_combo, False, False, 0)
        left_vbox.pack_start(units_frame, False, False, 0)
        
        # units_combo.set_model(ampl_units_store)
        # units_combo.set_active(0)
        #left_vbox.pack_start(units_combo, False, False, 0)
        
        
        
        hsep1 = Gtk.HSeparator()
        left_vbox.pack_start(hsep1, False, False, 2)

        # Frequency Sweep Control
        #side_filler = Gtk.Box(spacing = 2, orientation = 'vertical')
        swconf = Gtk.Frame(label = "Frequency Sweep Control")
        swhbox = Gtk.Box(spacing = 2)
        swbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        swconf.add(swhbox)
        swhbox.pack_start(swbox, False, False, 0)
        
        left_vbox.pack_start(swconf, False, False, 0)
        
        startf = Gtk.Frame(label = "Start Frequency (Hz)")
        
        self.start_freq = Gtk.SpinButton()
        self.start_freq.set_range(20.0, 100000.0)
        self.start_freq.set_digits(5)
        self.start_freq.set_value(20.0)
        self.start_freq.set_increments(100.0, 1000.0)

        startf.add(self.start_freq)
        #left_vbox.pack_start(startf, False, False, 0)
        swbox.pack_start(startf, False, False, 0)
        self.start_freq.connect("value_changed", self.freq_callback)
        
        stopf = Gtk.Frame(label = "Stop Frequency (Hz)")
        
        self.stop_freq = Gtk.SpinButton()
        self.stop_freq.set_range(20.0, 100000.0)
        self.stop_freq.set_digits(5)
        self.stop_freq.set_value(30000.0)
        self.stop_freq.set_increments(100.0, 1000.0)

        stopf.add(self.stop_freq)
        #left_vbox.pack_start(stopf, False, False, 0)
        swbox.pack_start(stopf, False, False, 0)
        self.stop_freq.connect("value_changed", self.freq_callback)

        stepsf = Gtk.Frame(label = "Steps per Decade")
        
        self.steps = Gtk.SpinButton()
        self.steps.set_range(1.0, 1000.0)
        self.steps.set_digits(1)
        self.steps.set_value(10.0)
        self.steps.set_increments(1.0, 10.0)

        stepsf.add(self.steps)
        swbox.pack_start(stepsf, False, False, 0)
        #left_vbox.pack_start(stepsf, False, False, 0)

        hsep2 = Gtk.HSeparator()
        left_vbox.pack_start(hsep2, False, False, 2)

        # Freq Control

        freqf = Gtk.Frame(label = "Frequency")
        freqbox = Gtk.Box(spacing = 2)
        freqhbox = Gtk.Box(spacing = 2, orientation = 'vertical')

        freqf.add(freqhbox)
        freqhbox.pack_start(freqbox, False, False, 0)

        self.freq = Gtk.SpinButton()
        self.freq.set_range(20.0, 100000.0)
        self.freq.set_digits(5)
        self.freq.set_value(1000.0)
        self.freq.set_increments(100.0, 1000.0)

        self.freq.set_sensitive(False)
        
        freqbox.pack_start(self.freq, False, False, 0)
        left_vbox.pack_start(freqf, False, False, 0)

        freqhsep = Gtk.HSeparator()
        left_vbox.pack_start(freqhsep, False, False, 2)
        
        # Source Control
        sourcef = Gtk.Frame(label = "Source Control (V RMS)")
        source_box = Gtk.Box(spacing = 2)
        sourcef.add(source_box)
        
        self.source = Gtk.SpinButton()
        self.source.set_range(0.0006, 6.0)
        self.source.set_digits(4)
        self.source.set_value(0.5)
        self.source.set_increments(0.5, 1.0)
        source_box.pack_start(self.source, False, False, 0)
        left_vbox.pack_start(sourcef, False, False, 0)

        hsep3 = Gtk.HSeparator()
        left_vbox.pack_start(hsep3, False, False, 2)


        vswconf = Gtk.Frame(label = "Voltage Sweep Control")
        vswhbox = Gtk.Box(spacing = 2)
        vswbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        vswconf.add(vswhbox)
        vswhbox.pack_start(vswbox, False, False, 0)
        
        left_vbox.pack_start(vswconf, False, False, 0)
        
        startv = Gtk.Frame(label = "Start Voltage (V)")
        
        self.start_v = Gtk.SpinButton()
        self.start_v.set_range(0.0006, 6.0)
        self.start_v.set_digits(5)
        self.start_v.set_value(0.1)
        self.start_v.set_increments(0.1, 1)

        startv.add(self.start_v)
        #left_vbox.pack_start(startf, False, False, 0)
        vswbox.pack_start(startv, False, False, 0)
        self.start_v.connect("value_changed", self.volt_callback)
        
        stopv = Gtk.Frame(label = "Stop Voltage (V)")
        
        self.stop_v = Gtk.SpinButton()
        self.stop_v.set_range(0.0006, 6.0)
        self.stop_v.set_digits(5)
        self.stop_v.set_value(1.0)
        self.stop_v.set_increments(0.1, 1.0)

        stopv.add(self.stop_v)
        #left_vbox.pack_start(stopf, False, False, 0)
        vswbox.pack_start(stopv, False, False, 0)
        self.stop_v.connect("value_changed", self.volt_callback)

        stepsv = Gtk.Frame(label = "Total Samples")
        
        self.stepsv = Gtk.SpinButton()
        self.stepsv.set_range(1.0, 1000.0)
        self.stepsv.set_digits(1)
        self.stepsv.set_value(10.0)
        self.stepsv.set_increments(1.0, 10.0)

        stepsv.add(self.stepsv)
        vswbox.pack_start(stepsv, False, False, 0)
        #left_vbox.pack_start(stepsf, False, False, 0)

        hsepsv = Gtk.HSeparator()
        left_vbox.pack_start(hsepsv, False, False, 2)



        
        filterf = Gtk.Frame(label = "Filters")
        filterb = Gtk.Box(spacing = 2)
        filtervb = Gtk.Box(spacing = 2, orientation = 'vertical')
        filterf.add(filterb)
        filterb.pack_start(filtervb, False, False, 0)

        self.f30k = Gtk.CheckButton("30 kHz LP")
        self.f80k = Gtk.CheckButton("80 kHz LP")

        self.lpi = Gtk.CheckButton("Left Plug-in filter")
        self.rpi = Gtk.CheckButton("Right Plug-in filter")

        self.f30k.connect("toggled", self.filter1_callback)
        self.f80k.connect("toggled", self.filter1_callback)

        self.lpi.connect("toggled", self.filter2_callback)
        self.rpi.connect("toggled", self.filter2_callback)
        
        filtervb.pack_start(self.f30k, False, False, 0)
        filtervb.pack_start(self.f80k, False, False, 0)
        filtervb.pack_start(self.lpi, False, False, 0)
        filtervb.pack_start(self.rpi, False, False, 0)

        left_vbox.pack_start(filterf, False, False, 0)
        
        hsep = Gtk.HSeparator()
        left_vbox.pack_start(hsep, False, False, 2)
        
        self.run_button = Gtk.Button(label = "Start Sequence")
        self.run_button.set_sensitive(False)
        left_vbox.pack_start(self.run_button, False, False, 0)
        self.run_button.connect("clicked", self.run_test)
        
        
        self.f = Figure(figsize=(5,4), dpi=100)
        self.a = self.f.add_subplot(111)
        #self.plt = self.a.plot(20,-90, marker = 'x')
        self.plt = self.a.plot(marker = 'x')
        self.a.grid(True)
        self.a.set_xscale('log')
        self.a.set_xlim((10.0, 30000.0))
        self.a.set_ylim((0.0005, 0.01))
        self.a.set_xlabel("Frequency (Hz)")
        self.a.set_ylabel("THD+n (%)")
        
        self.canvas = FigureCanvas(self.f)

        toolbar = NavigationToolbar(self.canvas, self)

        plot_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        plot_vbox.pack_start(self.canvas, True, True, 0)
        plot_vbox.pack_start(toolbar, False, False, 0)
        
        #self.hbox.pack_start(self.canvas, True, True, 0)
        self.hbox.pack_start(plot_vbox, True, True, 0)

        # Groups of widgets
        self.measurement_widgets = [self.meas_combo, self.units_combo]
        self.freq_sweep_widgets = [self.start_freq, self.stop_freq, self.steps]
        self.source_widgets = [self.source]
        self.filter_widgets = [self.f30k, self.f80k, self.lpi, self.rpi]
        self.vsweep_widgets = [self.start_v, self.stop_v, self.stepsv]
        
        for w in self.measurement_widgets:
            w.set_sensitive(False)
        for w in self.freq_sweep_widgets:
            w.set_sensitive(False)
        for w in self.source_widgets:
            w.set_sensitive(False)
        for w in self.filter_widgets:
            w.set_sensitive(False)
        for w in self.vsweep_widgets:
            w.set_sensitive(False)

        
        self.meas_string = "THD+n (%)"
        self.units_string = "%"
        self.measurements = None
예제 #58
0
파일: hp8903.py 프로젝트: cosmonaut/hp8903
class HP8903BWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="HP 8903B Control")

        # Serial connection!
        self.ser = None
        self.gpib_dev = None
        self.devices = list_ports.comports()
        
        # Menu Bar junk!
        action_group = Gtk.ActionGroup("my_actions")
        action_filemenu = Gtk.Action("FileMenu", "File", None, None)
        action_group.add_action(action_filemenu)
        self.action_filesave = Gtk.Action("FileSave", "Save Data", None, None)
        
        action_filequit = Gtk.Action("FileQuit", None, None, Gtk.STOCK_QUIT)
        action_filequit.connect("activate", self.on_menu_file_quit)
        action_group.add_action(self.action_filesave)
        action_group.add_action(action_filequit)
        self.action_filesave.set_sensitive(False)
        self.action_filesave.connect('activate', self.save_data)

        
        uimanager = self.create_ui_manager()
        uimanager.insert_action_group(action_group)

        menubar = uimanager.get_widget("/MenuBar")

        self.status_bar = Gtk.Statusbar()
        self.status_bar.push(0, "HP 8903 Audio Analyzer Control")
        
        self.master_vbox = Gtk.Box(False, spacing = 2, orientation = 'vertical')
        self.master_vbox.pack_start(menubar, False, False, 0)
        master_hsep = Gtk.HSeparator()
        self.master_vbox.pack_start(master_hsep, False, False, 0)
        self.add(self.master_vbox)

        self.hbox = Gtk.Box(spacing = 2)
        self.master_vbox.pack_start(self.hbox, True, True, 0)

        self.master_vbox.pack_start(self.status_bar, False, False, 0)

        # Begin controls
        bframe = Gtk.Frame(label = "Control")
        left_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        self.box = Gtk.Box(spacing = 2)

        bframe.add(left_vbox)

        # GPIB device selector
        gpib_frame = Gtk.Frame(label = "GPIB Communication Device")
        self.gpib_big_box = Gtk.Box(spacing = 2)
        gpib_frame.add(self.gpib_big_box)
        self.gpib_box = Gtk.Box(spacing = 2)
        self.gpib_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        gpib_label = Gtk.Label("GPIB Device: ")
        self.gpib_box.pack_start(gpib_label, False, False, 0)

        gpib_store = Gtk.ListStore(int, str)
        for n, g_dev in enumerate(HP8903_GPIB_devices):
            gpib_store.append([n, g_dev[1]])
        self.gpib_combo = Gtk.ComboBox.new_with_model_and_entry(gpib_store)
        self.gpib_combo.set_entry_text_column(1)
        self.gpib_combo.set_active(0)

        self.gpib_box.pack_start(self.gpib_combo, False, False, 0)

        gpib_addr_box = Gtk.Box(spacing = 2)

        self.gpib_addr = Gtk.SpinButton()
        self.gpib_addr.set_range(0, 30)
        self.gpib_addr.set_digits(0)
        self.gpib_addr.set_value(0)
        self.gpib_addr.set_increments(1.0, 1.0)


        gpib_addr_label = Gtk.Label("GPIB Address: ")
        gpib_addr_box.pack_start(gpib_addr_label, False, False, 0)
        gpib_addr_box.pack_start(self.gpib_addr, False, False, 0)

        self.gpib_vbox.pack_start(self.gpib_box, False, False, 0)
        self.gpib_vbox.pack_start(gpib_addr_box, False, False, 0)

        self.gpib_big_box.pack_start(self.gpib_vbox, False, False, 0)

        left_vbox.pack_start(gpib_frame, False, False, 0)

        # Device items
        left_vbox.pack_start(self.box, False, False, 0)

        self.hbox.pack_start(bframe, False, False, 0)

        con_hbox = Gtk.Box(spacing = 2)
        self.con_button = Gtk.Button(label = "Connect")
        self.dcon_button = Gtk.Button(label = "Disconnect")

        self.con_button.connect("clicked", self.setup_gpib)
        self.dcon_button.connect("clicked", self.close_gpib)
        
        con_hbox.pack_start(self.con_button, False, False, 0)
        con_hbox.pack_start(self.dcon_button, False, False, 0)

        left_vbox.pack_start(con_hbox, False, False, 0)
        
        device_store = Gtk.ListStore(int, str)

        for i, dev in enumerate(self.devices):
            device_store.append([i, dev[0]])
        self.device_combo = Gtk.ComboBox.new_with_model_and_entry(device_store)
        self.device_combo.set_entry_text_column(1)
        self.device_combo.set_active(0)

        device_label = Gtk.Label("Device: ")
        
        self.box.pack_start(device_label, False, False, 0)
        self.box.pack_start(self.device_combo, False, False, 0)

        hsep0 = Gtk.HSeparator()
        left_vbox.pack_start(hsep0, False, False, 2)

        # Measurement Selection
        mframe = Gtk.Frame(label = "Measurement Selection")
        meas_box = Gtk.Box(spacing = 2)
        meas_vbox = Gtk.Box(spacing = 2)

        mframe.add(meas_box)
        meas_box.pack_start(meas_vbox, False, False, 0)

        meas_store = Gtk.ListStore(int, str)
        meas_dict = {0: "THD+n",
                     1:"Frequency Response",
                     2: "THD+n (Ratio)",
                     3: "Frequency Response (Ratio)",
                     4: "Ouput Level"}
        for k, v in meas_dict.iteritems():
            meas_store.append([k, v])
        self.meas_combo = Gtk.ComboBox.new_with_model_and_entry(meas_store)
        self.meas_combo.set_entry_text_column(1)
        self.meas_combo.set_active(0)

        self.meas_combo.connect("changed", self.meas_changed)
        
        meas_vbox.pack_start(self.meas_combo, False, False, 0)
        left_vbox.pack_start(mframe, False, False, 0)


        units_frame = Gtk.Frame(label = "Units")
        units_box = Gtk.Box(spacing = 2)
        units_vbox = Gtk.Box(spacing = 2)

        units_frame.add(units_box)
        units_box.pack_start(units_vbox, False, False, 0)

        self.thd_units_store = Gtk.ListStore(int, str)
        self.ampl_units_store = Gtk.ListStore(int, str)
        self.thdr_units_store = Gtk.ListStore(int, str)
        self.amplr_units_store = Gtk.ListStore(int, str)
        self.optlvl_units_store = Gtk.ListStore(int, str)
        thd_units_dict = {0: "%", 1: "dB"}
        ampl_units_dict = {0: "V", 1: "dBm"}
        thdr_units_dict = {0: "%", 1: "dB"}
        amplr_units_dict = {0: "%", 1:"dB"}
        optlvl_units_dict = {0: "V"}

        for k, v in thd_units_dict.iteritems():
            self.thd_units_store.append([k, v])
        for k, v in ampl_units_dict.iteritems():
            self.ampl_units_store.append([k, v])
        for k, v in thdr_units_dict.iteritems():
            self.thdr_units_store.append([k, v])
        for k, v in amplr_units_dict.iteritems():
            self.amplr_units_store.append([k, v])
        for k, v in optlvl_units_dict.iteritems():
            self.optlvl_units_store.append([k, v])

            
        self.units_combo = Gtk.ComboBox.new_with_model_and_entry(self.thd_units_store)
        self.units_combo.set_entry_text_column(1)
        self.units_combo.set_active(0)

        self.units_combo.connect("changed", self.units_changed)
        
        units_vbox.pack_start(self.units_combo, False, False, 0)
        left_vbox.pack_start(units_frame, False, False, 0)
        
        # units_combo.set_model(ampl_units_store)
        # units_combo.set_active(0)
        #left_vbox.pack_start(units_combo, False, False, 0)
        
        
        
        hsep1 = Gtk.HSeparator()
        left_vbox.pack_start(hsep1, False, False, 2)

        # Frequency Sweep Control
        #side_filler = Gtk.Box(spacing = 2, orientation = 'vertical')
        swconf = Gtk.Frame(label = "Frequency Sweep Control")
        swhbox = Gtk.Box(spacing = 2)
        swbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        swconf.add(swhbox)
        swhbox.pack_start(swbox, False, False, 0)
        
        left_vbox.pack_start(swconf, False, False, 0)
        
        startf = Gtk.Frame(label = "Start Frequency (Hz)")
        
        self.start_freq = Gtk.SpinButton()
        self.start_freq.set_range(20.0, 100000.0)
        self.start_freq.set_digits(5)
        self.start_freq.set_value(20.0)
        self.start_freq.set_increments(100.0, 1000.0)

        startf.add(self.start_freq)
        #left_vbox.pack_start(startf, False, False, 0)
        swbox.pack_start(startf, False, False, 0)
        self.start_freq.connect("value_changed", self.freq_callback)
        
        stopf = Gtk.Frame(label = "Stop Frequency (Hz)")
        
        self.stop_freq = Gtk.SpinButton()
        self.stop_freq.set_range(20.0, 100000.0)
        self.stop_freq.set_digits(5)
        self.stop_freq.set_value(30000.0)
        self.stop_freq.set_increments(100.0, 1000.0)

        stopf.add(self.stop_freq)
        #left_vbox.pack_start(stopf, False, False, 0)
        swbox.pack_start(stopf, False, False, 0)
        self.stop_freq.connect("value_changed", self.freq_callback)

        stepsf = Gtk.Frame(label = "Steps per Decade")
        
        self.steps = Gtk.SpinButton()
        self.steps.set_range(1.0, 1000.0)
        self.steps.set_digits(1)
        self.steps.set_value(10.0)
        self.steps.set_increments(1.0, 10.0)

        stepsf.add(self.steps)
        swbox.pack_start(stepsf, False, False, 0)
        #left_vbox.pack_start(stepsf, False, False, 0)

        hsep2 = Gtk.HSeparator()
        left_vbox.pack_start(hsep2, False, False, 2)

        # Freq Control

        freqf = Gtk.Frame(label = "Frequency")
        freqbox = Gtk.Box(spacing = 2)
        freqhbox = Gtk.Box(spacing = 2, orientation = 'vertical')

        freqf.add(freqhbox)
        freqhbox.pack_start(freqbox, False, False, 0)

        self.freq = Gtk.SpinButton()
        self.freq.set_range(20.0, 100000.0)
        self.freq.set_digits(5)
        self.freq.set_value(1000.0)
        self.freq.set_increments(100.0, 1000.0)

        self.freq.set_sensitive(False)
        
        freqbox.pack_start(self.freq, False, False, 0)
        left_vbox.pack_start(freqf, False, False, 0)

        freqhsep = Gtk.HSeparator()
        left_vbox.pack_start(freqhsep, False, False, 2)
        
        # Source Control
        sourcef = Gtk.Frame(label = "Source Control (V RMS)")
        source_box = Gtk.Box(spacing = 2)
        sourcef.add(source_box)
        
        self.source = Gtk.SpinButton()
        self.source.set_range(0.0006, 6.0)
        self.source.set_digits(4)
        self.source.set_value(0.5)
        self.source.set_increments(0.5, 1.0)
        source_box.pack_start(self.source, False, False, 0)
        left_vbox.pack_start(sourcef, False, False, 0)

        hsep3 = Gtk.HSeparator()
        left_vbox.pack_start(hsep3, False, False, 2)


        vswconf = Gtk.Frame(label = "Voltage Sweep Control")
        vswhbox = Gtk.Box(spacing = 2)
        vswbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        vswconf.add(vswhbox)
        vswhbox.pack_start(vswbox, False, False, 0)
        
        left_vbox.pack_start(vswconf, False, False, 0)
        
        startv = Gtk.Frame(label = "Start Voltage (V)")
        
        self.start_v = Gtk.SpinButton()
        self.start_v.set_range(0.0006, 6.0)
        self.start_v.set_digits(5)
        self.start_v.set_value(0.1)
        self.start_v.set_increments(0.1, 1)

        startv.add(self.start_v)
        #left_vbox.pack_start(startf, False, False, 0)
        vswbox.pack_start(startv, False, False, 0)
        self.start_v.connect("value_changed", self.volt_callback)
        
        stopv = Gtk.Frame(label = "Stop Voltage (V)")
        
        self.stop_v = Gtk.SpinButton()
        self.stop_v.set_range(0.0006, 6.0)
        self.stop_v.set_digits(5)
        self.stop_v.set_value(1.0)
        self.stop_v.set_increments(0.1, 1.0)

        stopv.add(self.stop_v)
        #left_vbox.pack_start(stopf, False, False, 0)
        vswbox.pack_start(stopv, False, False, 0)
        self.stop_v.connect("value_changed", self.volt_callback)

        stepsv = Gtk.Frame(label = "Total Samples")
        
        self.stepsv = Gtk.SpinButton()
        self.stepsv.set_range(1.0, 1000.0)
        self.stepsv.set_digits(1)
        self.stepsv.set_value(10.0)
        self.stepsv.set_increments(1.0, 10.0)

        stepsv.add(self.stepsv)
        vswbox.pack_start(stepsv, False, False, 0)
        #left_vbox.pack_start(stepsf, False, False, 0)

        hsepsv = Gtk.HSeparator()
        left_vbox.pack_start(hsepsv, False, False, 2)



        
        filterf = Gtk.Frame(label = "Filters")
        filterb = Gtk.Box(spacing = 2)
        filtervb = Gtk.Box(spacing = 2, orientation = 'vertical')
        filterf.add(filterb)
        filterb.pack_start(filtervb, False, False, 0)

        self.f30k = Gtk.CheckButton("30 kHz LP")
        self.f80k = Gtk.CheckButton("80 kHz LP")

        self.lpi = Gtk.CheckButton("Left Plug-in filter")
        self.rpi = Gtk.CheckButton("Right Plug-in filter")

        self.f30k.connect("toggled", self.filter1_callback)
        self.f80k.connect("toggled", self.filter1_callback)

        self.lpi.connect("toggled", self.filter2_callback)
        self.rpi.connect("toggled", self.filter2_callback)
        
        filtervb.pack_start(self.f30k, False, False, 0)
        filtervb.pack_start(self.f80k, False, False, 0)
        filtervb.pack_start(self.lpi, False, False, 0)
        filtervb.pack_start(self.rpi, False, False, 0)

        left_vbox.pack_start(filterf, False, False, 0)
        
        hsep = Gtk.HSeparator()
        left_vbox.pack_start(hsep, False, False, 2)
        
        self.run_button = Gtk.Button(label = "Start Sequence")
        self.run_button.set_sensitive(False)
        left_vbox.pack_start(self.run_button, False, False, 0)
        self.run_button.connect("clicked", self.run_test)
        
        
        self.f = Figure(figsize=(5,4), dpi=100)
        self.a = self.f.add_subplot(111)
        #self.plt = self.a.plot(20,-90, marker = 'x')
        self.plt = self.a.plot(marker = 'x')
        self.a.grid(True)
        self.a.set_xscale('log')
        self.a.set_xlim((10.0, 30000.0))
        self.a.set_ylim((0.0005, 0.01))
        self.a.set_xlabel("Frequency (Hz)")
        self.a.set_ylabel("THD+n (%)")
        
        self.canvas = FigureCanvas(self.f)

        toolbar = NavigationToolbar(self.canvas, self)

        plot_vbox = Gtk.Box(spacing = 2, orientation = 'vertical')
        plot_vbox.pack_start(self.canvas, True, True, 0)
        plot_vbox.pack_start(toolbar, False, False, 0)
        
        #self.hbox.pack_start(self.canvas, True, True, 0)
        self.hbox.pack_start(plot_vbox, True, True, 0)

        # Groups of widgets
        self.measurement_widgets = [self.meas_combo, self.units_combo]
        self.freq_sweep_widgets = [self.start_freq, self.stop_freq, self.steps]
        self.source_widgets = [self.source]
        self.filter_widgets = [self.f30k, self.f80k, self.lpi, self.rpi]
        self.vsweep_widgets = [self.start_v, self.stop_v, self.stepsv]
        
        for w in self.measurement_widgets:
            w.set_sensitive(False)
        for w in self.freq_sweep_widgets:
            w.set_sensitive(False)
        for w in self.source_widgets:
            w.set_sensitive(False)
        for w in self.filter_widgets:
            w.set_sensitive(False)
        for w in self.vsweep_widgets:
            w.set_sensitive(False)

        
        self.meas_string = "THD+n (%)"
        self.units_string = "%"
        self.measurements = None

    def setup_gpib(self, button):
        # Get GPIB info
        gpib_model = self.gpib_combo.get_model()
        gpib_tree_iter = self.gpib_combo.get_active_iter()

        # Get address
        gpib_addr = self.gpib_addr.get_value_as_int()

        # Instantiate GPIB Device class
        self.gpib_dev = HP8903_GPIB_devices[gpib_model[gpib_tree_iter][0]][0](gpib_addr = gpib_addr)
        print("Using GPIB Device: %s" % self.gpib_dev.name())
        print("Using GPIB Address: %s" % str(gpib_addr))

        if (not self.gpib_dev.implements_addr()):
            print("Warning: this GPIB communication device does not implement")
            print("    address setting, check your hardware's settings!")

        # Get device info
        model = self.device_combo.get_model()

        tree_iter = self.device_combo.get_active_iter()

        print("Device: %s" % model[tree_iter][1])
        dev_name = model[tree_iter][1]

        # Disable gpib and devices buttons
        self.con_button.set_sensitive(False)
        self.device_combo.set_sensitive(False)
        self.gpib_combo.set_sensitive(False)
        self.gpib_addr.set_sensitive(False)


        if(not self.gpib_dev.open(dev_name)):
            # Make into warning window?
            print("Failed to open GPIB Device: %s at %s" % (self.gpib_dev.name(), dev_name))
            print("Verify hardware setup and try to connect again")

            self.con_button.set_sensitive(True)
            self.device_combo.set_sensitive(True)
            self.gpib_combo.set_sensitive(True)
            self.gpib_addr.set_sensitive(True)

            return(False)

        # Do test?
        if (not self.gpib_dev.test()):
            print("GPIB device failed self test: %s at %s" % (self.gpib_dev.name(), dev_name))
            print("Verify hardware setup and try to connect again")

            self.con_button.set_sensitive(True)
            self.device_combo.set_sensitive(True)
            self.gpib_combo.set_sensitive(True)
            self.gpib_addr.set_sensitive(True)

            return(False)


        if (self.gpib_dev.is_open()):
            self.gpib_dev.flush_input()
            # Initialize the HP 8903
            status = self.init_hp8903()
            if (not status):
                print("Failed to initialize HP 8903")
                print("Verify hardware setup and try to connect again")

                self.gpib_dev.close()

                self.con_button.set_sensitive(True)
                self.device_combo.set_sensitive(True)
                self.gpib_combo.set_sensitive(True)
                self.gpib_addr.set_sensitive(True)

                return(False)

        else:
            print("Failed to use GPIB device")
            print("Verify hardware setup and try to connect again")

            self.gpib_dev.close()

            self.con_button.set_sensitive(True)
            self.device_combo.set_sensitive(True)
            self.gpib_combo.set_sensitive(True)
            self.gpib_addr.set_sensitive(True)

            return(False)

        # Enable measurement controls
        self.run_button.set_sensitive(True)
        for w in self.measurement_widgets:
            w.set_sensitive(True)
        for w in self.freq_sweep_widgets:
            w.set_sensitive(True)
        for w in self.source_widgets:
            w.set_sensitive(True)
        for w in self.filter_widgets:
            w.set_sensitive(True)
        for w in self.vsweep_widgets:
            w.set_sensitive(False)


        self.status_bar.push(0, "Connected to  HP 8903, ready for measurements")

    def close_gpib(self, button):
        if (self.gpib_dev):
            self.gpib_dev.close()

        # Activate device/connection buttons
        self.con_button.set_sensitive(True)
        self.device_combo.set_sensitive(True)
        self.gpib_combo.set_sensitive(True)
        self.gpib_addr.set_sensitive(True)

        # Disable measurement controls
        for w in self.measurement_widgets:
            w.set_sensitive(False)
        for w in self.freq_sweep_widgets:
            w.set_sensitive(False)
        for w in self.source_widgets:
            w.set_sensitive(False)
        for w in self.filter_widgets:
            w.set_sensitive(False)
        for w in self.vsweep_widgets:
            w.set_sensitive(False)

        self.freq.set_sensitive(False)

        self.run_button.set_sensitive(False)

    def run_test(self, button):
        # Disable all control widgets during sweep
        self.run_button.set_sensitive(False)
        self.action_filesave.set_sensitive(False)

        for w in self.measurement_widgets:
            w.set_sensitive(False)
        for w in self.freq_sweep_widgets:
            w.set_sensitive(False)
        for w in self.source_widgets:
            w.set_sensitive(False)
        for w in self.filter_widgets:
            w.set_sensitive(False)
        for w in self.vsweep_widgets:
            w.set_sensitive(False)

        self.freq.set_sensitive(False)

        
        self.x = []
        self.y = []
        
        # 30, 80, LPI, RPI
        filters = [False, False, False, False]
        filters[0] = self.f30k.get_active()
        filters[1] = self.f80k.get_active()
        filters[2] = self.lpi.get_active()
        filters[3] = self.rpi.get_active()
        #print(filters)

        amp = self.source.get_value()
        
        strtf = self.start_freq.get_value()
        stopf = self.stop_freq.get_value()
        
        num_steps = self.steps.get_value_as_int()
        step_size = 10**(1.0/num_steps)

        strt_dec = math.floor(math.log10(strtf))
        stop_dec = math.floor(math.log10(stopf))

        meas = self.meas_combo.get_active()
        units = self.units_combo.get_active()

        lsteps = []
        vsteps = []
        if ((meas < 4) and (meas >= 0)):
            decs = math.log10(stopf/strtf)
            npoints = int(decs*num_steps)

            for n in range(npoints + 1):
                lsteps.append(strtf*10.0**(float(n)/float(num_steps)))
                
            self.a.set_xlim((lsteps[0]*10**(-2.0/10.0), lsteps[-1]*10**(2.0/10.0)))
            self.a.set_xscale('log')
        elif (meas == 4):
            start_amp = self.start_v.get_value()
            stop_amp = self.stop_v.get_value()
            num_vsteps = self.stepsv.get_value()
            vsteps = np.linspace(start_amp, stop_amp, num_vsteps)
            amp_buf = ((stop_amp - start_amp)*0.1)/2.0
            print(amp_buf)
            self.a.set_xlim(((start_amp - amp_buf), (stop_amp + amp_buf)))
            self.a.set_xscale('linear')
            # print(start_amp)
            # print(stop_amp)
            # print(num_vsteps)


        center_freq = self.freq.get_value()
            
        # center freq...
        self.measurements = [amp, filters, meas, units, self.meas_string, self.units_string]
        
        if ((meas == 0) or (meas == 1)):
            #pass
            pt = self.send_measurement(meas, units, center_freq, amp, filters, ratio = 2)
        elif ((meas == 2) or (meas == 3)):
            pt = self.send_measurement(meas, units, center_freq, amp, filters)
            #print(pt)
            pt = self.send_measurement(meas, units, center_freq, amp, filters, ratio = 1)
            #print("PT: %s" % pt)
        elif (meas == 4):
            pt = self.send_measurement(meas, units, center_freq, start_amp, filters, ratio = 2)

        if ((meas < 4) and (meas >= 0)):
            for i in lsteps:
                meas_point = self.send_measurement(meas, units, i, amp, filters)
                self.x.append(float(i))
                self.y.append(float(meas_point))
                print(float(meas_point))
                self.update_plot(self.x, self.y)
                # plot new measures
                #print(meas_point)
        elif (meas == 4):
            #pass
            for v in vsteps:
                meas_point = self.send_measurement(meas, units, center_freq, v, filters)
                self.x.append(v)
                self.y.append(float(meas_point))
                print("in: %f, out %f" % (v, float(meas_point)))
                self.update_plot(self.x, self.y)
        

        for w in self.measurement_widgets:
            w.set_sensitive(True)
        for w in self.filter_widgets:
            w.set_sensitive(True)

        if ((meas < 4) and (meas >= 0)):
            for w in self.freq_sweep_widgets:
                w.set_sensitive(True)
            for w in self.source_widgets:
                w.set_sensitive(True)
        if (meas == 4):
            for w in self.vsweep_widgets:
                w.set_sensitive(True)

        if (meas > 1):
            self.freq.set_sensitive(True)

        self.run_button.set_sensitive(True)
        self.action_filesave.set_sensitive(True)

    def update_plot(self, x, y):
        if (len(self.plt) < 1):
            self.plt = self.a.plot(x, y, marker = 'x')
        self.plt[0].set_data(x, y)
        ymin = min(y)
        ymax = max(y)

        
        # if (ymin == 0.0):
        #     ymin = -0.01
        # if (ymax == 0.0):
        #     ymax = 0.01

        sep = abs(ymax - ymin)
        sep = sep/10.0

        if (sep == 0.0):
            sep = 0.01

        #self.a.set_ylim((ymin - abs(ymin*0.10), ymax + abs(ymax*0.10)))
        self.a.set_ylim((ymin - abs(sep), ymax + abs(sep)))
        self.canvas.draw()
            
    def init_hp8903(self):
        self.gpib_dev.flush_input()
        # Arbitrary but simple measurement to check device
        self.gpib_dev.write("FR1000.0HZAP0.100E+00VLM1LNL0LNT3")
        status, meas = self.gpib_dev.read(msg_len = 12, timeout = 5000)

        if (status):
            print(meas)
        else:
            print("Failed to initialize HP8903!")
            print(status, meas)
            return(False)

        return(True)
        
    def send_measurement(self, meas, unit, freq, amp, filters, ratio = 0):
        # Store parameters for saving after any measure
        #self.measurements = [amp, filters, meas, unit]
        measurement = ""
        meas_unit = ""
        
        if (filters[0]):
            fs1 = "L1"
        elif (filters[1]):
            fs1 = "L2"
        else:
            fs1 = "L0"

        if (filters[2]):
            fs2 = "H1"
        elif (filters[3]):
            fs2 = "H2"
        else:
            fs2 = "H0"

        if ((meas == 0) or (meas == 2)):
            measurement = "M3"
        elif ((meas == 1) or (meas == 3) or (meas == 4)):
            measurement = "M1"

        if (unit == 0):
            meas_unit = "LN"
        elif (unit == 1):
            meas_unit = "LG"
            
        source_freq = ("FR%.4EHZ" % freq)
        source_ampl = ("AP%.4EVL" % amp)
        filter_s = fs1 + fs2

        rat = ""
        if (ratio == 1):
            rat = "R1"
        elif (ratio == 2):
            rat = "R0"
        
        #payload = source_freq + source_ampl + "M3LN" + filter_s + "LNT3"
        payload = source_freq + source_ampl + measurement + filter_s + meas_unit + rat + "T3"
        #print(payload)
        #print("FR%.4EHZAP1VLM1LNL0LNT3" % freq)
        #print("FR%.4EHZAP%.4EVLM3LNL0LNT3" % (freq, amp))
        #self.ser.write(("FR%.4EHZAP%.4EVLM3LNL2LNT3" % (freq, amp)))

        # Send and read measurement via GPIB controller
        self.gpib_dev.write(payload)
        status, samp = self.gpib_dev.read(timeout = 2500)
        if (status):
            sampf = float(samp)
        else:
            sampf = np.NAN
            print("Failed to get sample")

        if (sampf > 4.0e9):
            print(("Error: %s" % samp[4:6]) + " " + HP8903_errors[int(samp[4:6])])
            samp = np.NAN

        self.status_bar.push(0, "Freq: %f, Amp: %f, Return: %f,    GPIB: %s" % (freq, amp, sampf, payload))
            
        return(samp)

    def save_data(self, button):
        fname = datetime.now().strftime("%Y-%m-%d-%H%M%S")
        fid = open(fname + '.txt', 'w')

        # Write source voltage info
        source_v = str(self.measurements[0])
        fid.write("# Measurement: " + self.measurements[4] + "\n")
        fid.write("# Source Voltage: " + source_v + " V RMS\n")
        # write filter info
        for n, f in enumerate(self.measurements[1]):
            if f:
                fid.write("# " + HP8903_filters[n] + " active\n")

        fid.write("# Frequency (Hz)    " + self.measurements[5] + "\n")
        n = np.array([np.array(self.x), np.array(self.y)])
        np.savetxt(fid, n.transpose(), fmt = ["%f", "%f"])
        fid.close()
        
        
    def freq_callback(self, spinb):
        if (self.start_freq.get_value() > self.stop_freq.get_value()):
            self.start_freq.set_value(self.stop_freq.get_value())

    def volt_callback(self, spinb):
        if (self.start_v.get_value() > self.stop_v.get_value()):
            self.start_v.set_value(self.stop_v.get_value())

    # 30k/80k toggle
    def filter1_callback(self, cb):
        if (cb.get_active()):
            if (cb.get_label() == "30 kHz LP"):
                self.f80k.set_active(False)
            elif (cb.get_label() == "80 kHz LP"):
                self.f30k.set_active(False)

    # left plugin/right plugin toggle
    def filter2_callback(self, cb):
        if (cb.get_active()):
            if (cb.get_label() == "Left Plug-in filter"):
                self.rpi.set_active(False)
            elif (cb.get_label() == "Right Plug-in filter"):
                self.lpi.set_active(False)

    def on_menu_file_quit(self, widget):
        if (self.gpib_dev):
            self.gpib_dev.close()
        Gtk.main_quit()

    def meas_changed(self, widget):
        meas_ind = self.meas_combo.get_active()
        if (meas_ind == 0):
            self.units_combo.set_model(self.thd_units_store)
            self.units_combo.set_active(0)
            self.a.set_ylabel("THD+n (%)")
            self.a.set_xlabel("Frequency (Hz)")            
            self.canvas.draw()
            self.freq.set_sensitive(False)
            self.source.set_sensitive(True)
            for w in self.freq_sweep_widgets:
                w.set_sensitive(True)
            for w in self.vsweep_widgets:
                w.set_sensitive(False)
        elif (meas_ind == 1):
            self.units_combo.set_model(self.ampl_units_store)
            self.units_combo.set_active(0)
            self.a.set_ylabel("AC Level (V RMS)")
            self.a.set_xlabel("Frequency (Hz)")            
            self.canvas.draw()
            self.freq.set_sensitive(False)
            self.source.set_sensitive(True)
            for w in self.freq_sweep_widgets:
                w.set_sensitive(True)
            for w in self.vsweep_widgets:
                w.set_sensitive(False)
        elif (meas_ind == 2):
            self.units_combo.set_model(self.thdr_units_store)
            self.units_combo.set_active(0)
            self.a.set_ylabel("THD+n Ratio (%)")
            self.a.set_xlabel("Frequency (Hz)")
            self.canvas.draw()
            self.freq.set_sensitive(True)
            self.source.set_sensitive(True)
            for w in self.freq_sweep_widgets:
                w.set_sensitive(True)
            for w in self.vsweep_widgets:
                w.set_sensitive(False)
        elif (meas_ind == 3):
            self.units_combo.set_model(self.amplr_units_store)
            self.units_combo.set_active(0)
            self.a.set_ylabel("AC Level Ratio (%)")
            self.a.set_xlabel("Frequency (Hz)")
            self.canvas.draw()
            self.freq.set_sensitive(True)
            self.source.set_sensitive(True)
            for w in self.freq_sweep_widgets:
                w.set_sensitive(True)
            for w in self.vsweep_widgets:
                w.set_sensitive(False)
        elif (meas_ind == 4):
            self.units_combo.set_model(self.optlvl_units_store)
            self.units_combo.set_active(0)
            self.a.set_ylabel("Output Level (V)")
            self.a.set_xlabel("Input Level (V)")
            self.canvas.draw()
            self.freq.set_sensitive(True)
            self.source.set_sensitive(False)
            for w in self.freq_sweep_widgets:
                w.set_sensitive(False)
            for w in self.vsweep_widgets:
                w.set_sensitive(True)


            


    def units_changed(self, widget):
        meas_ind = self.meas_combo.get_active()
        units_ind = self.units_combo.get_active()
        #print("meas ind: %d units ind: %d" % (meas_ind, units_ind))
        # Set units on plot
        meas = ""
        if (meas_ind == 0):
            meas = "THD+n "
            if (units_ind == 0):
                meas += "(%)"
                self.units_string = "%"
            elif (units_ind == 1):
                meas += "(dB)"
                self.units_string = "dB"
        elif (meas_ind == 1):
            meas = "AC Level "
            if (units_ind == 0):
                meas += "(V RMS)"
                self.units_string = "V RMS"
            elif (units_ind == 1):
                meas += "(dB V)"
                self.units_string = "dB V"
        elif (meas_ind == 2):
            meas = "THD+n (Ratio) "
            if (units_ind == 0):
                meas += "(%)"
                self.units_string = "%"
            elif (units_ind == 1):
                meas += "(dB)"
                self.units_string = "dB"
        elif (meas_ind == 3):
            meas = "AC Level (Ratio) "
            if (units_ind == 0):
                meas += "(%)"
                self.units_string = "%"
            elif (units_ind == 1):
                meas += "(dB)"
                self.units_string = "dB"

        # Save text info about units
        self.meas_string = meas
        # Updated plot
        self.a.set_ylabel(meas)
        self.canvas.draw()

    # menu bar junk
    def create_ui_manager(self):
        uimanager = Gtk.UIManager()

        # Throws exception if something went wrong
        uimanager.add_ui_from_string(UI_INFO)

        # Add the accelerator group to the toplevel window
        accelgroup = uimanager.get_accel_group()
        self.add_accel_group(accelgroup)
        return uimanager
예제 #59
0
    def __init__(self, timeline, binding):
        figure = Figure()
        FigureCanvas.__init__(self, figure)
        Loggable.__init__(self)

        self.__timeline = timeline
        self.__source = binding.props.control_source
        self.__source.connect("value-added", self.__controlSourceChangedCb)
        self.__source.connect("value-removed", self.__controlSourceChangedCb)
        self.__source.connect("value-changed", self.__controlSourceChangedCb)
        self.__propertyName = binding.props.name
        self.__resetTooltip()
        self.get_style_context().add_class("KeyframeCurve")

        self.__ylim_min, self.__ylim_max = KeyframeCurve.YLIM_OVERRIDES.get(
            binding.pspec, (0.0, 1.0))

        # Curve values, basically separating source.get_values() timestamps
        # and values.
        self.__line_xs = []
        self.__line_ys = []

        # axisbg to None for transparency
        self.__ax = figure.add_axes([0, 0, 1, 1], axisbg='None')
        self.__ax.cla()

        # FIXME: drawing a grid and ticks would be nice, but
        # matplotlib is too slow for now.
        self.__ax.grid(False)

        self.__ax.tick_params(axis='both',
                              which='both',
                              bottom='off',
                              top='off',
                              right='off',
                              left='off')

        # This seems to also be necessary for transparency ..
        figure.patch.set_visible(False)

        # The actual Line2D object
        self.__line = None

        # The PathCollection as returned by scatter
        sizes = [50]
        self.__keyframes = self.__ax.scatter([], [], marker='D', s=sizes,
                                             c=KEYFRAME_NODE_COLOR, zorder=2)

        # matplotlib weirdness, simply here to avoid a warning ..
        self.__keyframes.set_picker(True)

        self.__line = self.__ax.plot([], [],
                                     alpha=KEYFRAME_LINE_ALPHA,
                                     c=KEYFRAME_LINE_COLOR,
                                     linewidth=KEYFRAME_LINE_HEIGHT, zorder=1)[0]
        self.__updatePlots()

        # Drag and drop logic
        self.__dragged = False
        self.__offset = None
        self.handling_motion = False

        self.__hovered = False

        self.connect("motion-notify-event", self.__gtkMotionEventCb)
        self.connect("event", self._eventCb)
        self.connect("notify::height-request", self.__heightRequestCb)

        self.mpl_connect('button_press_event', self.__mplButtonPressEventCb)
        self.mpl_connect('button_release_event', self.__mplButtonReleaseEventCb)
        self.mpl_connect('motion_notify_event', self.__mplMotionEventCb)
예제 #60
0
파일: gui.py 프로젝트: Quaaas/ODESolver
    def __init__(self):
        Gtk.Window.__init__(self, title="ODE Solver")
        
        #Main Box
        self.grid = Gtk.Grid(column_spacing=6)

        #Dopdown for kind of solver
        self.combo_solver = Gtk.ComboBoxText()
        self.combo_solver.set_entry_text_column(0)

        self.solvers = ["Euler explicit", "Heun explicit", "Runge-Kutta explicit","Midpoint implicit","Heun implicit"]

        for solver in self.solvers:
            self.combo_solver.append_text(solver)
      
        self.combo_solver.set_active(0)


        #Entrys
        self.function_entry = Gtk.Entry(text="test")
        self.x0_entry = Gtk.Entry(text="1,2")
        self.t0_entry = Gtk.Entry(text="0")
        self.T_entry = Gtk.Entry(text="5")
        self.N_entry = Gtk.Entry(text="100")
        self.eps_entry = Gtk.Entry(text="0.1")

        #Labels
        self.function_label = Gtk.Label("Function Name:")
        self.x0_label = Gtk.Label("Starting Point:")
        self.t0_label = Gtk.Label("Starting Time:")
        self.T_label = Gtk.Label("Ending Time:")
        self.N_label = Gtk.Label("Number of Steps:")
        self.eps_label = Gtk.Label("Stopping Criterium:")

        #Buttons
        self.plot_button = Gtk.Button(label="Plot")
        self.reset_plot_button = Gtk.Button(label="Reset Plot")
        
        self.plot_button.connect("clicked",self.on_plot_clicked)
        self.reset_plot_button.connect("clicked",self.reset)

        #Box on right side
        self.boxRight = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        
        #Plot 
        self.fig = Figure(figsize=(5,4), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.ax.plot()

        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(400,400)

        self.sw = Gtk.ScrolledWindow()
        self.sw.add_with_viewport(self.canvas)
        self.sw.set_min_content_width(500)
        self.sw.set_min_content_height(500)
        self.boxRight.pack_start(self.sw,True,True,0)
        
        self.toolbar = NavigationToolbar(self.canvas,self)
        self.boxRight.pack_start(self.toolbar,False,True,0)


        self.foo = Gtk.Label("")
        #Left Side
        self.gridLeft = Gtk.Grid(row_spacing=6)

        #Put it together
        self.gridLeft.attach(self.combo_solver,0,0,1,1)
        self.gridLeft.attach(self.foo,0,1,1,1)
        self.gridLeft.attach(self.function_label,0,2,1,1)
        self.gridLeft.attach(self.function_entry,0,3,1,1)
        self.gridLeft.attach(self.x0_label,0,4,1,1)
        self.gridLeft.attach(self.x0_entry,0,5,1,1)
        self.gridLeft.attach(self.t0_label,0,6,1,1)
        self.gridLeft.attach(self.t0_entry,0,7,1,1)
        self.gridLeft.attach(self.T_label,0,8,1,1)
        self.gridLeft.attach(self.T_entry,0,9,1,1)
        self.gridLeft.attach(self.N_label,0,10,1,1)
        self.gridLeft.attach(self.N_entry,0,11,1,1)
        self.gridLeft.attach(self.eps_label,0,12,1,1)
        self.gridLeft.attach(self.eps_entry,0,13,1,1)
        self.gridLeft.attach(self.plot_button,0,14,1,1)
        self.gridLeft.attach(self.reset_plot_button,0,15,1,1)
        


#        self.boxLeft.pack_start(self.function_entry,True,True,0)
#        self.boxLeft.pack_start(self.x0_entry,True,True,0)
#        self.boxLeft.pack_start(self.t0_entry,True,True,0)
#        self.boxLeft.pack_start(self.T_entry,True,True,0)
#        self.boxLeft.pack_start(self.N_entry,True,True,0)
#        self.boxLeft.pack_start(self.eps_entry,True,True,0)
#        self.boxLeft.pack_start(self.plot_button,True,True,0)
#        self.boxLeft.pack_start(self.reset_plot_button,True,True,0)
       

        self.grid.attach(self.gridLeft,0,0,2,6)
        self.grid.attach(self.boxRight,2,0,4,6)
        self.add(self.grid)


        #Definition of methods
        A_euler_explicit = np.array([0])
        b_euler_explicit = np.array([1])
        c_euler_explicit = np.array([0])
        self.euler_explicit = (A_euler_explicit,b_euler_explicit,c_euler_explicit)

    
        A_heun_explicit = np.array([[0,0],[1,0]])
        b_heun_explicit = np.array([0.5,0.5])
        c_heun_explicit = np.array([0,1])
        self.heun_explicit = (A_heun_explicit,b_heun_explicit,c_heun_explicit)


        A_rk_explicit = np.array([[0,0,0,0],[0.5,0,0,0],[0,0.5,0,0],[0,0,1,0]])
        b_rk_explicit = np.array([1/6,2/6,2/6,1/6])
        c_rk_explicit = np.array([0,0.5,0.5,1])
        self.rk_explicit = (A_rk_explicit,b_rk_explicit,c_rk_explicit)
       


        A_midpoint_implicit = np.array([[0.5]])
        b_midpoint_implicit = np.array([1])
        c_midpoint_implicit = np.array([0.5])
        self.midpoint_implicit = (A_midpoint_implicit,b_midpoint_implicit,c_midpoint_implicit)

        A_heun_implicit = np.array([[0,0],[0.5,0.5]])
        b_heun_implicit = np.array([0.5,0.5])
        c_heun_implicit = np.array([0,1])
        self.heun_implicit = (A_heun_implicit,b_heun_implicit,c_heun_implicit)

        
        self.methods = {}
        self.methods[self.solvers[0]] = self.euler_explicit
        self.methods[self.solvers[1]] = self.heun_explicit
        self.methods[self.solvers[2]] = self.rk_explicit
        self.methods[self.solvers[3]] = self.midpoint_implicit 
        self.methods[self.solvers[4]] = self.heun_implicit