def create_figure(self):
        self.fig = fig = Figure(figsize=(5, 4), dpi=100)
        self.axes_left = a = fig.add_subplot(111)
        canvas = FigureCanvas(fig)
        canvas.set_size_request(800, 600)
        self.plot_hbox.add(canvas)
        #plt.subplots_adjust(left=0.25, bottom=0.25)

        sound_line, = a.plot(self.t, self.feature, color='red')

        # draw threshold line
        self.threshold_line, = a.plot([self.t[0], self.t[-1]], [threshold] * 2)

        # calculate specgram (spectrogram)
        self.spec_fig = Figure(figsize=(5, 4), dpi=100)
        self.axes_right = a_specgram = self.spec_fig.add_subplot(111)
        a_specgram.specgram(samples_raw, NFFT=1024, Fs=sample_freq, noverlap=900)
        canvas_specgram = FigureCanvas(self.spec_fig)
        canvas_specgram.set_size_request(800, 600)
        self.plot_hbox.add(canvas_specgram)

        self.create_time_bars()
Beispiel #2
0
    def __init__(self, input_directory_path):

        super(BenchmarkPlotsContainer,
              self).__init__(orientation=gtk.Orientation.VERTICAL, spacing=6)

        self.input_directory_path = input_directory_path
        self.current_file_path = None

        # Plot options ################

        self.plot_histogram = False
        self.plot_log_scale = False
        self.plot_ellipse_shower = False
        self.show_scores = True
        self.plot_perpendicular_hit_distribution = None
        self.kill_isolated_pixels_on_ref = False
        self.use_ref_angle_for_perpendicular_hit_distribution = False

        # Wavelets options ############

        self.kill_isolated_pixels = False
        self.offset_after_calibration = None
        self.input_image_scale = 'linear'

        # Box attributes ##############

        self.set_border_width(18)

        # Matplotlib ##################

        self.fig = plt.figure()

        self.color_map = DEFAULT_COLOR_MAP
        self.color_map.set_bad(
            color='black'
        )  # Set to black pixels with value <= 0 in log scale (by default it's white). See http://stackoverflow.com/questions/22548813/python-color-map-but-with-all-zero-values-mapped-to-black

        self.show_color_bar = True

        # Plot histogram ##############

        self.plot_histogram_switch = gtk.Switch()
        self.plot_histogram_switch.connect("notify::active",
                                           self.plot_histogram_switch_callback)
        self.plot_histogram_switch.set_active(False)

        plot_histogram_label = gtk.Label(label="Plot histograms")

        # Plot log scale ##############

        self.plot_log_scale_switch = gtk.Switch()
        self.plot_log_scale_switch.connect("notify::active",
                                           self.plot_log_scale_switch_callback)
        self.plot_log_scale_switch.set_active(False)

        plot_log_scale_label = gtk.Label(label="Plot log scale")

        # Plot ellipse shower #########

        self.plot_ellipse_shower_switch = gtk.Switch()
        self.plot_ellipse_shower_switch.connect(
            "notify::active", self.plot_ellipse_shower_switch_callback)
        self.plot_ellipse_shower_switch.set_active(False)

        plot_ellipse_shower_label = gtk.Label(label="Plot ellipse shower")

        # Plot perpendicular hit distribution

        self.plot_perpendicular_hit_distribution_switch = gtk.Switch()
        self.plot_perpendicular_hit_distribution_switch.connect(
            "notify::active",
            self.plot_perpendicular_hit_distribution_switch_callback)
        self.plot_perpendicular_hit_distribution_switch.set_active(False)

        plot_perpendicular_hit_distribution_label = gtk.Label(label="Plot PHD")

        # Kill isolated pixels on ref #

        self.kill_isolated_pixels_on_ref_switch = gtk.Switch()
        self.kill_isolated_pixels_on_ref_switch.connect(
            "notify::active", self.kill_isolated_pixels_on_ref_switch_callback)
        self.kill_isolated_pixels_on_ref_switch.set_active(False)

        kill_isolated_pixels_on_ref_label = gtk.Label(
            label="Kill isolated pixels on ref.")

        # Use reference angle for perpendicular hit distribution

        self.use_ref_angle_for_perpendicular_hit_distribution_switch = gtk.Switch(
        )
        self.use_ref_angle_for_perpendicular_hit_distribution_switch.connect(
            "notify::active", self.
            use_ref_angle_for_perpendicular_hit_distribution_switch_callback)
        self.use_ref_angle_for_perpendicular_hit_distribution_switch.set_active(
            False)

        use_ref_angle_for_perpendicular_hit_distribution_label = gtk.Label(
            label="Ref. angle for PHD")

        # Save plots ##################

        self.save_plots_button = gtk.Button(label="Save")
        self.save_plots_button.connect("clicked",
                                       self.save_plots_button_callback)

        # Wavelets options entry ######

        self.wavelets_options_entry = gtk.Entry()
        self.wavelets_options_entry.set_text("-K -k -C1 -m3 -s3 -n4")
        self.wavelets_options_entry.connect(
            "activate", self.update_plots
        )  # call "print_text()" function when the "Enter" key is pressed in the entry

        # Kill isolated pixels ########

        self.kill_isolated_pixels_switch = gtk.Switch()
        self.kill_isolated_pixels_switch.connect(
            "notify::active", self.kill_isolated_pixels_switch_callback)
        self.kill_isolated_pixels_switch.set_active(False)

        kill_isolated_pixels_label = gtk.Label(label="Kill isolated pixels")

        # Log image ###################

        self.log_image_switch = gtk.Switch()
        self.log_image_switch.connect("notify::active",
                                      self.log_image_switch_callback)
        self.log_image_switch.set_active(False)

        log_image_label = gtk.Label(label="Log image")

        # Fill the box container ######

        # Plot options box
        plot_options_horizontal_box = gtk.Box(
            orientation=gtk.Orientation.HORIZONTAL,
            spacing=6)  # 6 pixels are placed between children

        plot_options_horizontal_box.pack_start(plot_histogram_label,
                                               expand=False,
                                               fill=False,
                                               padding=0)
        plot_options_horizontal_box.pack_start(self.plot_histogram_switch,
                                               expand=False,
                                               fill=False,
                                               padding=0)

        plot_options_horizontal_box.pack_start(plot_log_scale_label,
                                               expand=False,
                                               fill=False,
                                               padding=0)
        plot_options_horizontal_box.pack_start(self.plot_log_scale_switch,
                                               expand=False,
                                               fill=False,
                                               padding=0)

        plot_options_horizontal_box.pack_start(plot_ellipse_shower_label,
                                               expand=False,
                                               fill=False,
                                               padding=0)
        plot_options_horizontal_box.pack_start(self.plot_ellipse_shower_switch,
                                               expand=False,
                                               fill=False,
                                               padding=0)

        plot_options_horizontal_box.pack_start(
            plot_perpendicular_hit_distribution_label,
            expand=False,
            fill=False,
            padding=0)
        plot_options_horizontal_box.pack_start(
            self.plot_perpendicular_hit_distribution_switch,
            expand=False,
            fill=False,
            padding=0)

        plot_options_horizontal_box.pack_start(
            kill_isolated_pixels_on_ref_label,
            expand=False,
            fill=False,
            padding=0)
        plot_options_horizontal_box.pack_start(
            self.kill_isolated_pixels_on_ref_switch,
            expand=False,
            fill=False,
            padding=0)

        plot_options_horizontal_box.pack_start(
            use_ref_angle_for_perpendicular_hit_distribution_label,
            expand=False,
            fill=False,
            padding=0)
        plot_options_horizontal_box.pack_start(
            self.use_ref_angle_for_perpendicular_hit_distribution_switch,
            expand=False,
            fill=False,
            padding=0)

        plot_options_horizontal_box.pack_start(self.save_plots_button,
                                               expand=False,
                                               fill=False,
                                               padding=0)

        # Wavelet options box
        wavelets_options_horizontal_box = gtk.Box(
            orientation=gtk.Orientation.HORIZONTAL,
            spacing=6)  # 6 pixels are placed between children

        wavelets_options_horizontal_box.pack_start(self.wavelets_options_entry,
                                                   expand=True,
                                                   fill=True,
                                                   padding=0)

        wavelets_options_horizontal_box.pack_start(kill_isolated_pixels_label,
                                                   expand=False,
                                                   fill=False,
                                                   padding=0)
        wavelets_options_horizontal_box.pack_start(
            self.kill_isolated_pixels_switch,
            expand=False,
            fill=False,
            padding=0)

        wavelets_options_horizontal_box.pack_start(log_image_label,
                                                   expand=False,
                                                   fill=False,
                                                   padding=0)
        wavelets_options_horizontal_box.pack_start(self.log_image_switch,
                                                   expand=False,
                                                   fill=False,
                                                   padding=0)

        ###
        canvas = FigureCanvas(self.fig)

        self.pack_start(canvas, expand=True, fill=True, padding=0)
        self.pack_start(plot_options_horizontal_box,
                        expand=False,
                        fill=False,
                        padding=0)
        self.pack_start(wavelets_options_horizontal_box,
                        expand=False,
                        fill=False,
                        padding=0)
Beispiel #3
0
grid = Gtk.Grid()
window.add(grid)

min_inicial = [-10, -10, -10, -10, -10, -10]
max_inicial = [10, 10, 10, 10, 10, 10]
for i in range(6):
    adj = Gtk.Adjustment(0, min_inicial[i], max_inicial[i], 1, 10, 0)
    adj.tipo = i
    adj.connect("value-changed", replot)
    scale = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj)
    scale.set_size_request(100, 20)

    scale.set_value_pos(Gtk.PositionType.BOTTOM)
    grid.attach(scale, 0, i, 2, 1)

sw = Gtk.ScrolledWindow()
grid.attach(sw, 3, 0, 1, 8)
fig, ax = ci.create_figure()
ci.plot_plataforma(ax, ci.A0, ci.V0)

canvas = FigureCanvas(fig)
canvas.set_size_request(400, 400)
sw.add_with_viewport(canvas)
sw.set_vexpand(True)
sw.set_hexpand(True)

window.show_all()

Gtk.main()
Beispiel #4
0
    def __init__(self, device):
        super(Plot, self).__init__()
        self.device = device
        self.set_hexpand(True)
        self.set_vexpand(True)

        fig = Figure()
        fig.subplots_adjust(top=1,
                            bottom=0.09,
                            right=1,
                            left=0.065,
                            hspace=0.2,
                            wspace=0.2)

        self.ax = fig.add_subplot(111, fc='black')
        self._def_axis(self.ax)

        canvas = FigureCanvas(fig)

        canvas.set_size_request(600, 600)
        self.add(canvas)

        parent_conn, self.child_conn = Pipe(
            duplex=False)  # Pipe to pump the label data through

        def update_self(source, condition):
            """
            watches pipe and when data changes, changes the label
            """
            print('source = ', source, 'condition = ', condition)
            assert parent_conn.poll()
            data = parent_conn.recv()

            samples = data['values']

            ys = []
            tmp = 0

            sample_time = 1 / device.get_sampling_speed()

            val = 0
            vals = ['S', 'mS', 'uS', 'nS', 'pS']
            for val in range(0, len(vals)):
                if sample_time > 10:
                    break
                sample_time = sample_time * 1000

            print('scaled and vals set to ', vals[val])

            tmp = 0
            for y in range(len(samples)):
                ys.append(tmp)
                tmp = tmp + 1 / sample_time

            self._def_axis(self.ax)
            self.ax.set_xlabel('Time [%s]' % vals[val])
            self.ax.plot(ys, samples, **self.graph_properties)

            if data['trig_low'] is not None:
                self.ax.axhline(y=data['trig_low'], color='b', linestyle=':')
            if data['trig_up'] is not None:
                self.ax.axhline(y=data['trig_up'], color='b', linestyle=':')
            if data['trig_place'] is not None:
                self.ax.axvline(x=data['trig_place'] * sample_time,
                                color='r',
                                linestyle=':')

            self.queue_draw()
            return True

        GObject.io_add_watch(parent_conn.fileno(), GObject.IO_IN, update_self)
Beispiel #5
0
    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)

        #str_pth_fn = "./models/bpcv_encoder_06000.pth"
        str_pth_fn = "./models/bpcv_encoder_12000.pth"

        self.autoencoder = AutoEncoder()

        bpcv_dict = torch.load(str_pth_fn)
        self.autoencoder.load_state_dict(bpcv_dict["net_state"])

        print("continue: ...  n_loop: {0:0>5d}  idx_loop: {1:0>5d}".format(
            bpcv_dict["n_loop"], bpcv_dict["idx_loop"]))
        print(
            ".............................................................................."
        )

        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=3,
                                      n_loop=bpcv_dict["n_loop"],
                                      idx_segment=bpcv_dict["idx_loop"])

        thread_torch.start()
Beispiel #6
0
    def add_data(self):
        try:
            usage = TodayUsage()
        except Exception:
            self.parent.add(create_error_bar("Could not read screen time log"))
            return
        self.time_label = create_usage_detail(
            "Screen time", format_time(usage.get_total_time()))
        self.add(self.time_label)
        print(usage.sessions)
        self.longest_session_label = create_usage_detail(
            "Longest session",
            format_time(max([d.get_length() for d in usage.sessions])))
        self.add(self.longest_session_label)

        self.unlocks_label = create_usage_detail("Unlocks",
                                                 usage.get_unlocks())
        self.add(self.unlocks_label)

        fig, ax = plt.subplots()

        times = get_chart_times(usage.sessions)

        last = []

        on = False

        plt.xlim(right=60 * 24)

        index = [1]

        for t in times:

            color = self.bar_color if on else self.background_color

            item = np.array([t])

            if len(last):
                plt.barh(index,
                         item,
                         left=sum(last),
                         color=color,
                         edgecolor=color,
                         linewidth=0)
            else:
                plt.barh(index,
                         item,
                         color=color,
                         edgecolor=color,
                         linewidth=0)
            last.append(item)

            on = not on

        [i.set_linewidth(0) for i in ax.spines.values()]

        ax.get_yaxis().set_visible(False)
        ax.get_xaxis().set_visible(True)
        ax.tick_params(axis='x', colors=LABEL_COLOR)
        plt.xticks(range(0, 24 * 60 + 1, 60), [
            "12A", "", "", "3A", "", "", "6A", "", "", "9A", "", "", "12P", "",
            "", "3P", "", "", "6P", "", "", "9P", "", "", "12A"
        ])
        ax.set_facecolor(BACKGROUND_COLOR)
        fig.set_facecolor(BACKGROUND_COLOR)
        plt.subplots_adjust(left=0.02, right=0.98)

        plt.plot()

        self.chart = FigureCanvas(fig)
        self.chart.set_size_request(768, 200)

        self.add(self.chart)
    def __init__(self):  #{{{
        self.lockTreeViewEvents = False
        np.seterr(all='ignore')

        ## Plotting initialization
        self.fig = matplotlib.figure.Figure(figsize=(8, 8),
                                            dpi=96,
                                            facecolor='#eeeeee',
                                            tight_layout=1)
        # (figure is static, axes clear on every replot)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(300, 300)
        self.toolbar = matplotlib.backends.backend_gtk3.NavigationToolbar2GTK3(
            self.canvas,
            w('box4').get_parent_window())

        self.xlim, self.ylim = None, None
        self.sw = Gtk.ScrolledWindow()
        self.sw.add_with_viewport(self.canvas)
        w('box4').pack_start(self.toolbar, False, True, 0)

        #self.toolbar.append_item(Gtk.Button('tetet'))
        ## TODO find out how to modify the NavigationToolbar...
        w('box4').pack_start(self.sw, True, True, 0)
        self.toolbar.pan()
        #TODO - define global shortcuts as a superset of the Matplotlib-GUI's internal, include also:
        #toolbar.zoom() #toolbar.home() #toolbar.back() #toolbar.forward() #toolbar.save_figure(toolbar)
        #TODO http://stackoverflow.com/questions/26433169/personalize-matplotlib-toolbar-with-log-feature
        #TODO http://dalelane.co.uk/blog/?p=778

        self.opj_file_cache = {}

        ## TreeStore and ListStore initialization
        self.tsFiles = Gtk.TreeStore(str, Pixbuf, str, Pixbuf, int, int, str)
        self.treeStoreColumns = {
            'filepath': 0,
            'icon': 1,
            'name': 2,
            'plotstyleicon': 3,
            'column': 4,
            'spreadsheet': 5,
            'rowtype': 6
        }
        self.dummy_treestore_row = [None for x in self.treeStoreColumns.keys()]

        treeViewCol0 = Gtk.TreeViewColumn("Plot")  # Create a TreeViewColumn
        colCellPlot = Gtk.CellRendererPixbuf(
        )  # Create a column cell to display text
        treeViewCol0.pack_start(colCellPlot, expand=True)
        treeViewCol0.add_attribute(colCellPlot, "pixbuf",
                                   3)  # set params for icon
        w('treeview1').append_column(
            treeViewCol0)  # Append the columns to the TreeView

        treeViewCol = Gtk.TreeViewColumn("File")  # Create a TreeViewColumn
        colCellImg = Gtk.CellRendererPixbuf(
        )  # Create a column cell to display an image
        colCellText = Gtk.CellRendererText(
        )  # Create a column cell to display text
        treeViewCol.pack_start(colCellImg,
                               expand=False)  # Add the cells to the column
        treeViewCol.pack_start(colCellText, expand=True)
        treeViewCol.add_attribute(
            colCellImg, "pixbuf",
            1)  # Bind the image cell to column 1 of the tree's model
        treeViewCol.add_attribute(
            colCellText, "text",
            2)  # Bind the text cell to column 0 of the tree's model
        w('treeview1').append_column(
            treeViewCol)  # Append the columns to the TreeView
        w('treeview1').set_expander_column(treeViewCol)
        w('treeview1').set_model(
            self.tsFiles)  # Append the columns to the TreeView
        w('treeview1').get_selection().set_select_function(
            self.treeview1_selectmethod, data=None)  # , full=True

        ## TODO: If files are specified as arguments, select these at start, and plot them at once

        ## If a directory is specified, just set it as the root of the file list. If none, use current working dir.
        self.populateTreeStore(
            self.tsFiles,
            reset_path=os.getcwd() if len(sys.argv) <= 1 else sys.argv[1])
        self.plot_reset()
        self.plot_all_sel_records()

        ## Initialize the default plotting commands
        w('txt_rc').get_buffer().set_text(line_plot_command)
        w('txt_rc').modify_font(Pango.FontDescription("monospace 10"))
Beispiel #8
0
    def __init__(self, parent):
        self.appWindow = parent.appWindow  # an instance of appWindow
        self.disableAppButtons = parent.disable_app_buttons  # an instance of disable_all_buttons
        self.plt = plt  # instance of plt
        self.chartActions = ChartActionController(
            self)  # an instance of chart actions
        self.x_values, self.y_values = self.chartActions.initChartValues(
        )  # intialize x and y curve values

        self.fig = self.plt.figure(
            num="Fan Controller", figsize=(12, 9),
            facecolor='white')  # add plt.figure instance
        self.fig.subplots_adjust(left=0.11,
                                 bottom=0.15,
                                 right=0.94,
                                 top=0.89,
                                 wspace=0.2,
                                 hspace=0)  # adjusts Chart's window
        self.axes = self.fig.add_subplot(
            111)  # add a subplot instance to the figure
        self.canvas = FigureCanvas(
            self.fig)  # add fig instance to a figure canvas
        self.canvas.set_size_request(
            800,
            700)  # set default canvas height (req'd for displaying the chart)

        # appends the figure => to the graphBox => to the notebook
        parent.graph.add(self.canvas)

        # updates chart with GPU stats every 1000ms
        self.anim = animation.FuncAnimation(self.fig,
                                            self.updateLabelStats,
                                            interval=1000)

        # chart min/max values for the background grid layout
        self.ticks = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
        self.axes.set_xlim(-5, 105)  # x-axis min/max values
        self.axes.set_ylim(0, 105)  # y-axis min/max values
        self.axes.set_xticks(self.ticks)  # x-axis ticks
        self.axes.set_yticks(self.ticks)  # y-axis ticks
        self.axes.tick_params(colors='0.7', which='both', labelsize=12)
        self.axes.grid(linestyle='-', linewidth='0.1',
                       color='grey')  # background lines (thin and grey)

        # misc. chart configurations
        self.axes.axhline(
            y=10, xmin=0, xmax=1, linewidth=1,
            color='red')  # red line to represent lowest value (10,0)
        self.axes.set_title("Fan Controller", fontsize=16)  # Chart's title
        for axis in ['bottom', 'left', 'top', 'right']:
            self.axes.spines[axis].set_color(
                '0.1')  # adds spines to x and y axes
        self.plt.setp(self.axes.spines.values(),
                      linewidth=0.2)  # sets both spines' line widths

        # creates curve w/ options: color=blue, s=squares, picker=max distance for selection
        self.line, = self.axes.plot(self.x_values,
                                    self.y_values,
                                    linestyle='-',
                                    marker='s',
                                    markersize=4.5,
                                    color='b',
                                    picker=5,
                                    linewidth=1.5)

        # drag handler and curve instances
        self.dragHandler = DragHandler(
            self, self.appWindow)  # handles the mouse clicks on the curve
        self.dataController = DataController(
            self.appWindow, self.x_values,
            self.y_values)  # handles updating curve data

        # initializes and starts a stoppable thread (loop that looks for temp changes and updates accordingly)
        self.fanController = FanController(self.x_values, self.y_values)
        self.fanController.start()
Beispiel #9
0
    def after_view_init(self) -> None:
        figure = Figure(tight_layout=False)
        self.figure = figure

        self.figure_canvas = FigureCanvas(figure)
        self.figure_canvas.props.hexpand = True
        self.figure_canvas.props.vexpand = True
        self.figure_canvas.props.visible = True
        self.figure_container.add(self.figure_canvas)

        self.figure_canvas_mapped = False

        self.figure_canvas.connect('map', self.hdl_canvas_map)
        self.figure_canvas.connect('unmap', self.hdl_canvas_unmap)
        self.figure_canvas.connect('size-allocate',
                                   self.hdl_canvas_size_allocate)

        self.ift_axes, volume_axes, surface_area_axes = figure.subplots(
            3, 1, sharex='col')
        self.ift_axes.set_ylabel('IFT [mN/m]')
        self.ift_axes.tick_params(axis='x', direction='inout')
        volume_axes.xaxis.set_ticks_position('both')
        volume_axes.tick_params(axis='x', direction='inout')
        volume_axes.set_ylabel('V [mm³]')
        surface_area_axes.xaxis.set_ticks_position('both')
        surface_area_axes.tick_params(axis='x', direction='inout')
        surface_area_axes.set_ylabel('SA [mm²]')

        self.ift_axes.tick_params(axis='y',
                                  left=False,
                                  labelleft=False,
                                  right=True,
                                  labelright=True)
        volume_axes.tick_params(axis='y',
                                left=False,
                                labelleft=False,
                                right=True,
                                labelright=True)
        surface_area_axes.tick_params(axis='y',
                                      left=False,
                                      labelleft=False,
                                      right=True,
                                      labelright=True)

        self.ift_axes.grid(axis='x', linestyle='--', color="#dddddd")
        volume_axes.grid(axis='x', linestyle='--', color="#dddddd")
        surface_area_axes.grid(axis='x', linestyle='--', color="#dddddd")

        self.ift_axes.grid(axis='y', linestyle='-', color="#dddddd")
        volume_axes.grid(axis='y', linestyle='-', color="#dddddd")
        surface_area_axes.grid(axis='y', linestyle='-', color="#dddddd")

        # Format the labels to scale to the right units.
        self.ift_axes.get_yaxis().set_major_formatter(
            ticker.FuncFormatter(lambda x, pos: '{:.4g}'.format(x * 1e3)))
        volume_axes.get_yaxis().set_major_formatter(
            ticker.FuncFormatter(lambda x, pos: '{:.4g}'.format(x * 1e9)))
        surface_area_axes.get_yaxis().set_major_formatter(
            ticker.FuncFormatter(lambda x, pos: '{:.4g}'.format(x * 1e6)))

        self.ift_line = self.ift_axes.plot([], marker='o', color='red')[0]
        self.volume_line = volume_axes.plot([], marker='o', color='blue')[0]
        self.surface_area_line = surface_area_axes.plot([],
                                                        marker='o',
                                                        color='green')[0]

        self.graphs_service.connect('notify::ift', self.hdl_model_data_changed)
        self.graphs_service.connect('notify::volume',
                                    self.hdl_model_data_changed)
        self.graphs_service.connect('notify::surface-area',
                                    self.hdl_model_data_changed)

        self.hdl_model_data_changed()
Beispiel #10
0
    def __init__(self):

        #Janela
        Gtk.Window.__init__(self, title="Testando")
        self.set_resizable(False)
        self.set_size_request(600, 600)
        self.set_position(Gtk.WindowPosition.CENTER)

        self.set_border_width(10)

        principal = Gtk.Box(spacing=10)
        principal.set_homogeneous(False)

        vbox_left = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox_left.set_homogeneous(False)
        vbox_right = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox_right.set_homogeneous(False)

        ### Boxes que ficarão dentro da vbox_left ###
        hbox_MDIST = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_MDIST.set_homogeneous(False)
        hbox_labels = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_labels.set_homogeneous(False)
        hbox_RDIST = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_RDIST.set_homogeneous(True)
        hbox_TOTEX = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_TOTEX.set_homogeneous(True)
        hbox_MVELO = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_MVELO.set_homogeneous(True)

        #criando os elementos das boxes Mdist, Labels, Rdist, TOTEX, Mvelo
        ##MDIST##
        label_Mdist = Gtk.Label('MDIST')
        self.entry_Mdist = Gtk.Entry()
        self.entry_Mdist.set_editable(False)
        self.entry_Mdist.set_max_length(max=8)
        ##LABELS##
        label_vazia = Gtk.Label('     ')
        label_AP = Gtk.Label('AP')
        label_ML = Gtk.Label('ML')
        label_TOTAL = Gtk.Label('TOTAL')
        ##RDIST##
        label_Rdist = Gtk.Label('RDIST')
        self.entry_Rdist_AP = Gtk.Entry()
        self.entry_Rdist_AP.set_editable(False)
        self.entry_Rdist_AP.set_max_length(max=8)
        self.entry_Rdist_ML = Gtk.Entry()
        self.entry_Rdist_ML.set_editable(False)
        self.entry_Rdist_ML.set_max_length(max=8)
        self.entry_Rdist_TOTAL = Gtk.Entry()
        self.entry_Rdist_TOTAL.set_editable(False)
        self.entry_Rdist_TOTAL.set_max_length(max=8)
        ##TOTEX##
        label_TOTEX = Gtk.Label('TOTEX')
        self.entry_TOTEX_AP = Gtk.Entry()
        self.entry_TOTEX_AP.set_editable(False)
        self.entry_TOTEX_AP.set_max_length(max=8)
        self.entry_TOTEX_ML = Gtk.Entry()
        self.entry_TOTEX_ML.set_editable(False)
        self.entry_TOTEX_ML.set_max_length(max=8)
        self.entry_TOTEX_TOTAL = Gtk.Entry()
        self.entry_TOTEX_TOTAL.set_editable(False)
        self.entry_TOTEX_TOTAL.set_max_length(max=8)
        ##MVELO##
        label_MVELO = Gtk.Label('MVELO')
        self.entry_MVELO_AP = Gtk.Entry()
        self.entry_MVELO_AP.set_editable(False)
        self.entry_MVELO_AP.set_max_length(max=8)
        self.entry_MVELO_ML = Gtk.Entry()
        self.entry_MVELO_ML.set_editable(False)
        self.entry_MVELO_ML.set_max_length(max=8)
        self.entry_MVELO_TOTAL = Gtk.Entry()
        self.entry_MVELO_TOTAL.set_editable(False)
        self.entry_MVELO_TOTAL.set_max_length(max=8)

        #colocando cada elemento dentro da sua box
        hbox_MDIST.pack_start(label_Mdist, True, True, 0)
        hbox_MDIST.pack_start(self.entry_Mdist, True, True, 0)

        hbox_labels.pack_start(label_vazia, True, True, 0)
        hbox_labels.pack_start(label_AP, True, True, 0)
        hbox_labels.pack_start(label_ML, True, True, 0)
        hbox_labels.pack_start(label_TOTAL, True, True, 0)

        hbox_RDIST.pack_start(label_Rdist, True, True, 0)
        hbox_RDIST.pack_start(self.entry_Rdist_AP, True, True, 0)
        hbox_RDIST.pack_start(self.entry_Rdist_ML, True, True, 0)
        hbox_RDIST.pack_start(self.entry_Rdist_TOTAL, True, True, 0)

        hbox_TOTEX.pack_start(label_TOTEX, True, True, 0)
        hbox_TOTEX.pack_start(self.entry_TOTEX_AP, True, True, 0)
        hbox_TOTEX.pack_start(self.entry_TOTEX_ML, True, True, 0)
        hbox_TOTEX.pack_start(self.entry_TOTEX_TOTAL, True, True, 0)

        hbox_MVELO.pack_start(label_MVELO, True, True, 0)
        hbox_MVELO.pack_start(self.entry_MVELO_AP, True, True, 0)
        hbox_MVELO.pack_start(self.entry_MVELO_ML, True, True, 0)
        hbox_MVELO.pack_start(self.entry_MVELO_TOTAL, True, True, 0)

        #colocando as boxes pequenas dentro das box vbox_left
        vbox_left.pack_start(hbox_MDIST, True, True, 0)
        vbox_left.pack_start(hbox_labels, True, True, 0)
        vbox_left.pack_start(hbox_RDIST, True, True, 0)
        vbox_left.pack_start(hbox_TOTEX, True, True, 0)
        vbox_left.pack_start(hbox_MVELO, True, True, 0)

        #elementos da vbox_right)
        #Notebook
        self.notebook = Gtk.Notebook()
        self.fig = plt.figure()

        self.axis = self.fig.add_subplot(111)
        self.axis.set_ylabel('ML')
        self.axis.set_xlabel('AP')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(500, 500)

        self.page1 = Gtk.Box()
        self.page1.set_border_width(10)
        self.page1.add(self.canvas)
        self.notebook.append_page(self.page1, Gtk.Label('Gráfico do CoP'))

        ##aqui fica a segunda janela do notebook
        self.fig2 = plt.figure()
        self.axis2 = self.fig2.add_subplot(111)
        self.axis2.set_ylabel('ML')
        self.axis2.set_xlabel('AP')
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.set_size_request(500, 500)

        self.page2 = Gtk.Box()
        self.page2.set_border_width(10)
        self.page2.add(self.canvas2)
        self.notebook.append_page(self.page2,
                                  Gtk.Label('Gráfico na frequência'))

        #criando os botoes
        hbox_botoes = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_botoes.set_homogeneous(True)

        self.button1 = Gtk.Button(label="Capturar")
        self.button1.connect("clicked", self.on_button1_clicked)

        self.button2 = Gtk.Button(label="Processar")
        self.button2.connect("clicked", self.on_button2_clicked)
        #self.set_resizable(True
        #colocando os botoes nas boxes
        hbox_botoes.pack_start(self.button1, True, True, 0)
        hbox_botoes.pack_start(self.button2, True, True, 0)

        vbox_right.pack_start(self.notebook, True, True, 0)
        vbox_right.pack_start(hbox_botoes, True, True, 0)
        # colocando as boxes verticais dentro da box principal
        principal.pack_start(vbox_left, True, True, 0)
        principal.pack_start(vbox_right, True, True, 0)

        #Adicionano os elementos na box exterior
        self.add(principal)
Beispiel #11
0
    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
 def __init__(self, scatterPoints):
     self.fig = Figure(dpi=50)
     self.ax = self.fig.add_subplot(111)
     self.canvas = FigureCanvas(self.fig)
     self.canvas.set_size_request(400, 337)
     self.scatterPoints = scatterPoints
Beispiel #13
0
"""

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

from matplotlib.figure import Figure
from numpy import arange, sin, pi

# uncomment to select /GTK/GTKAgg/GTKCairo, but only cairo works :|
from matplotlib.backends.backend_gtk3cairo import FigureCanvas
#from matplotlib.backends.backend_gtk3 import FigureCanvas
#from matplotlib.backends.backend_gtk3agg import FigureCanvas

win = Gtk.Window()
win.connect("destroy", lambda x: Gtk.main_quit())
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")

f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)
a.plot(t, s)

canvas = FigureCanvas(f)  # a gtk.DrawingArea
win.add(canvas)

win.show_all()
Gtk.main()
Beispiel #14
0
    def __init__(self, parent):
        Gtk.Grid.__init__(self)
        self.parent = parent

        self.fig = Figure( figsize=(6,6), dpi=65 )
        self.axis = self.fig.add_subplot( 111 )
        self.axis.grid( True )
        self.graph_count = 0

        self.set_border_width( WIDTH )
        self.set_column_homogeneous( 1 )
        self.set_row_spacing( WIDTH )
        self.set_column_spacing( WIDTH )

        #--ButtonGrid
        self.button_grid = Gtk.Grid()
        self.button_grid.set_border_width( WIDTH )
        self.button_grid.set_column_homogeneous( 1 )
        self.button_grid.set_row_spacing( WIDTH )
        self.button_grid.set_column_spacing( WIDTH )

        #--InputGrid
        self.txt_grid = Gtk.Grid()
        self.txt_grid.set_column_homogeneous( 1 )
        self.txt_grid.set_column_spacing( WIDTH )


        #--Buttons
        self.button_clear = Gtk.Button( 'Clear' )
        self.button_clear.connect( 'pressed', self.on_clear_press )
        self.button_add = Gtk.Button( 'Add' )
        self.button_add.connect( 'pressed', self.on_add_press )
        self.button_save = Gtk.Button( 'Save' )
        self.button_save.connect( 'pressed', self.on_save_press )
        self.button_snapshot = Gtk.Button( 'Snapshot' )
        self.button_snapshot.connect( 'pressed', self.on_snapshot_press )

        #--Text Input
        self.txt_eq = Gtk.Entry()
        self.txt_eq.set_placeholder_text('cos(var)...etc')
        self.lbl_eq = Gtk.Label( 'Equation:' )
        self.lbl_eq.set_justify( Gtk.Justification.LEFT )
        self.txt_var = Gtk.Entry()
        self.txt_var.set_placeholder_text('xc or x or y')
        self.lbl_var = Gtk.Label( 'Variables:' )
        self.lbl_var.set_justify( Gtk.Justification.LEFT )
        self.txt_ran = Gtk.Entry()
        self.txt_ran.set_placeholder_text('a,b')
        self.lbl_ran = Gtk.Label( 'Range:' )
        self.lbl_ran.set_justify( Gtk.Justification.LEFT )
        self.lbl_snapshot = Gtk.Label( 'Snapshot Taken' )
        self.lbl_snapshot.set_no_show_all( True )


        #--Graph added to canvas
        self.canvas = FigureCanvas( self.fig )
        self.canvas.set_size_request( 300, 300 )
        self.canvas.set_hexpand( True )
        self.canvas.set_vexpand( True )

        #--Button attachments
        self.button_grid.attach( self.txt_grid, 1,1,2,1 )
        self.button_grid.attach( self.button_add, 1,2,1,1 )
        self.button_grid.attach( self.button_clear, 2,2,1,1 )
        self.button_grid.attach( self.button_snapshot, 1,3,1,1 )
        self.button_grid.attach( self.button_save, 2,3,1,1 )
        self.button_grid.attach( self.lbl_snapshot, 1,4,2,1 )

        #--Entry attachments
        self.txt_grid.attach( self.lbl_var, 1,1,1,1 )
        self.txt_grid.attach( self.txt_var, 1,2,1,1 )
        self.txt_grid.attach( self.lbl_eq, 2,1,1,1 )
        self.txt_grid.attach( self.txt_eq, 2,2,1,1 )
        self.txt_grid.attach( self.lbl_ran, 3,1,1,1 )
        self.txt_grid.attach( self.txt_ran, 3,2,1,1 )

        #--Main Grid attachments
        self.attach( self.canvas, 1, 1, 1, 1 )
        self.attach( self.button_grid, 1, 2, 1, 1 )
Beispiel #15
0
    def get_canvas(self):
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

        ax1.title.set_text(_('Linear response test'))
        p11, = ax1.plot(*zip(*self.linear_chart.get_fixed_input_values()),
                        label=_('Input force'),
                        color='blue')
        p12, = ax1.plot(*zip(*self.linear_chart.get_linearity_values()),
                        label=_('Output force'),
                        color='purple')
        ax1.set_ylabel(_('Force level'))
        ax1.grid(True)

        ax2.axis('off')

        ax3b = ax3.twinx()
        ax3.title.set_text(_('Step test (angular velocity + position)'))
        p31, = ax3.step(*zip(*self.performance_chart.get_input_values()),
                        label=_('Input force'),
                        color='blue')
        p32, = ax3.step(*zip(*self.performance_chart.get_pos_values()),
                        label=_('Angular displacement (raw)'),
                        color='yellow')
        p33, = ax3.plot(
            *zip(*self.performance_chart.get_filtered_pos_values()),
            label=_('Angular displacement (smoothed)'),
            color='darkorange')
        p34, = ax3b.plot(*zip(*self.performance_chart.get_velocity_values()),
                         label=_('Angular velocity (raw)'),
                         color='lightgreen')
        p35, = ax3b.plot(
            *zip(*self.performance_chart.get_filtered_velocity_values()),
            label=_('Angular velocity (smoothed)'),
            color='green')
        ax3.set_xlabel(_('Time (s)'))
        ax3.set_ylabel(_('Position'))
        ax3b.set_ylabel(_('RPM'))
        ax3.tick_params(axis='y', labelcolor='gray')
        ax3b.tick_params(axis='y', labelcolor='green')
        ax3.grid(True)

        ax4b = ax4.twinx()
        ax4.title.set_text(_('Step test (angular acceleration)'))
        p41, = ax4.step(*zip(*self.performance_chart.get_input_values()),
                        label=_('Input Force'),
                        color='blue')
        p42, = ax4b.plot(*zip(*self.performance_chart.get_accel_values()),
                         label=_('Angular acceleration (raw)'),
                         color='orange')
        p43, = ax4b.plot(
            *zip(*self.performance_chart.get_filtered_accel_values()),
            label=_('Angular acceleration (smoothed)'),
            color='red')
        ax4.set_xlabel(_('Time (s)'))
        ax4b.set_ylabel(_('RPM/s'))
        ax4b.tick_params(axis='y', labelcolor='red')
        ax4.grid(True)

        props = dict(boxstyle='square', pad=1.5, facecolor='wheat', alpha=0.5)
        text = [
            _('Latency = {:.0f} ms'),
            _('Max. velocity = {:.0f} RPM'),
            _('Mean accel. = {:.0f} RPM/s'),
            _('Mean decel. = {:.0f} RPM/s'),
            _('Max. accel. = {:.0f} RPM/s'),
            _('Time max. accel. = {:.0f} ms'),
            _('Max. decel. = {:.0f} RPM/s'),
            _('Time max. decel. = {:.0f} ms'),
            _('Residual decel. = {:.0f} RPM/s'),
            _('Estimated SNR = {:.0f} dB'),
            _('Min. force level = {:.1f} %'),
        ]
        values = [
            self.performance_chart.get_latency() * 1000,
            self.performance_chart.get_max_velocity(),
            self.performance_chart.get_mean_accel(),
            self.performance_chart.get_mean_decel(),
            self.performance_chart.get_max_accel(),
            self.performance_chart.get_time_to_max_accel() * 1000,
            self.performance_chart.get_max_decel(),
            self.performance_chart.get_time_to_max_decel() * 1000,
            self.performance_chart.get_residual_decel(),
            self.performance_chart.get_estimated_snr(),
            self.linear_chart.get_minimum_level_percent(),
        ]
        ax2.text(0,
                 0.9,
                 '\n'.join(text).format(*values),
                 transform=ax2.transAxes,
                 fontsize=10,
                 verticalalignment='top',
                 bbox=props)
        fig.subplots_adjust(left=0.1, right=0.8)

        subplots = [p11, p12, p32, p33, p34, p35, p42, p43]
        plt.figlegend(subplots, [p.get_label() for p in subplots],
                      loc='upper center',
                      mode=None,
                      ncol=3)

        self.align_yaxis(ax3, 0, ax3b, 0)
        self.align_yaxis(ax4, 0, ax4b, 0)

        canvas = FigureCanvas(fig)

        return canvas