예제 #1
0
class MatplotlibPlot:
    """ Class encapsulating a matplotlib plot"""

    def __init__(self, parent = None, dpi = 100, size = (5,5)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(size, dpi = self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

        # Reset the plot landscape
        self.figure.clear()

    def plotMultiPixel(self, info, data):
        """ Generate multi-pixel plot """

        # Tabula Rasa
        self.figure.clear()
        rows = math.ceil(math.sqrt(info['nbeams']))

	    # Display a subplot per beam (randomly for now)
        for i in range(info['nbeams']):
            ax = self.figure.add_subplot(rows, rows, i)
            ax.plot(data[:,512,i])
            
        

    def updatePlot(self):
        self.canvas.draw()
예제 #2
0
class GraphView(qg.QWidget):
    def __init__(self, name='Name', title='Title', graph_title='Graph Title', parent = None):
        super(GraphView, self).__init__(parent)

        self.name = name
        self.graph_title = graph_title

        self.dpi = 100
        self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
        self.axes = self.fig.add_subplot(111)
        
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas,self)
        self.layout = qg.QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.canvas.show()

    def clear(self):
        self.axes.clear()
    def plot(self,*args,**kwargs):
        self.axes.plot(*args,**kwargs)
    def draw(self):
        self.canvas.draw()
    def add_patch(self,patch):
        self.axes.add_patch(patch)
    def scatter(self,*args,**kwargs):
        self.axes.scatter(*args,**kwargs)
    def text(self,*args,**kwargs):
        self.axes.text(*args,**kwargs)
예제 #3
0
class GraphView(qg.QWidget):
    def __init__(self, name='Name', title='Title', graph_title='Graph Title', parent = None):
        super(GraphView, self).__init__(parent)

        self.name = name
        self.graph_title = graph_title

        self.dpi = 100
        self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
        self.axes = self.fig.add_subplot(111)
        
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas,self)
        self.layout = qg.QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.canvas.show()

    def clear(self):
        self.axes.clear()
    def plot(self,*args,**kwargs):
        self.axes.plot(*args,**kwargs)
    def draw(self):
        self.canvas.draw()
    def add_patch(self,patch):
        self.axes.add_patch(patch)
    def scatter(self,*args,**kwargs):
        self.axes.scatter(*args,**kwargs)
    def text(self,*args,**kwargs):
        self.axes.text(*args,**kwargs)
예제 #4
0
 def plot_image(self, img):
     cv = FigureCanvas(plt.figure(figsize=(5, 3)))
     cv.setWindowTitle(self.filename)
     plt.imshow(img)
     plt.title(self.filename)
     plt.gca().axis('off')
     cv.show()
예제 #5
0
class LiveGraphQt4(Backend):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def show(self, delay=50):
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.show()

        self.timer = QtCore.QTimer(self.canvas)
        self.timer.timeout.connect(self.run)

        super().show(delay)
예제 #6
0
class LiveGraphQt4(Backend):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def show(self, delay=50):
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.show()

        self.timer = QtCore.QTimer(self.canvas)
        self.timer.timeout.connect(self.run)

        super().show(delay)
예제 #7
0
 def __graph(self, processFunc):
     function = ProcessFun(processFunc).process()
     self.__a.clear()
     X = np.arange(float(self.__leftBoundE.get()),
                   float(self.__rightBoundE.get()), np.pi / 24)
     y = eval(function)
     self.__a.plot(X, y)
     pyplot.xlabel("x")
     pyplot.ylabel("y")
     self.__a.grid(True)
     canvas = FigureCanvasQTAgg(self.__f)
     canvas.show()
예제 #8
0
class MatplotlibPlot:
    """ Class encapsulating an matplotlib plot"""
    def __init__(self, parent=None, dpi=100, size=(5, 4)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(size, dpi=self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

    def plotCurve(self,
                  data,
                  xAxisRange=None,
                  yAxisRange=None,
                  xLabel="",
                  yLabel=""):
        """ Plot the data as a curve"""

        # clear the axes and redraw the plot anew
        self.figure.clear()
        self.axes = self.figure.add_subplot(111)
        self.axes.grid(True)
        self.axes.plot(range(np.size(data)), data)

        if xAxisRange is not None:
            self.xAxisRange = xAxisRange
            self.axes.xaxis.set_major_formatter(
                ticker.FuncFormatter(
                    lambda x, pos=None: '%.2f' % self.xAxisRange[x]
                    if 0 <= x < len(xAxisRange) else ''))
            for tick in self.axes.xaxis.get_ticklabels():
                tick.set_rotation(15)

        if yAxisRange is not None:
            self.yAxisRange = yAxisRange
            self.axes.xaxis.set_major_formatter(
                ticker.FuncFormatter(
                    lambda x, pos=None: '%.1f' % self.yAxisRange[y]
                    if 0 <= y < len(yAxisRange) else ''))
            for tick in self.axes.yaxis.get_ticklabels():
                tick.set_rotation(15)

        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.canvas.draw()
예제 #9
0
def _show(fig):
    """
    show image on canvas
    :param fig: matplotlib.figure.Figure instance
    :return: matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg instance
    """

    w = FigureCanvas(fig)

    # store instance to prevent garbage collection
    # otherwise widget is not sticking
    WIDGETS.append(w)

    # show the widget
    w.show()

    return w
예제 #10
0
class Grafica(QWidget):

    valores = (20, 35, 30, 35, 27) # valores de ejemplo


    def __init__(self, parent=None):
        super(Grafica, self).__init__()

        # FIGUREANDO
        self.ordenadas = np.arange(5)
        self.width = 1       # the width of the bars
        self.figure, self.ax = plt.subplots()
        #self.figure = plt.figure()
        self.line = self.ax.bar(self.ordenadas, self.valores, self.width, color='g')
        #self.line, = plt.plot(self.data)
        plt.ion() # animate

        N = 10
        self.xs = collections.deque(maxlen=N)
        self.ys = collections.deque(maxlen=N)
        self.xs.append(0)
        self.ys.append(0)

        self.ax = self.figure.add_subplot(111)
        self.ax.hold(False)
        self.ax.set_ylim([0, 360])

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.toolbar.hide()
        self.canvas.show()

        # set the layout
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.setLayout(self.layout)


    def add_sample(self, valores):
        self.valores = valores
        self.line = self.ax.bar(self.ordenadas, self.valores, self.width, color='g')
        self.canvas.draw()  # update the plot
예제 #11
0
class MatplotlibPlot:
    """ Class encapsulating an matplotlib plot"""
    def __init__(self, parent = None, dpi = 100, size = (5,4)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(size, dpi = self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

    def plotCurve(self, data, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = ""):
        """ Plot the data as a curve"""

        # clear the axes and redraw the plot anew
        self.figure.clear()
        self.axes = self.figure.add_subplot(111)        
        self.axes.grid(True)
        self.axes.plot(range(np.size(data)), data)

        if xAxisRange is not None:        
            self.xAxisRange = xAxisRange
            self.axes.xaxis.set_major_formatter(ticker.FuncFormatter(
                       lambda x, pos=None: '%.2f' % self.xAxisRange[x] if 0 <= x < len(xAxisRange) else ''))
            for tick in self.axes.xaxis.get_ticklabels():
                  tick.set_rotation(15)

        if yAxisRange is not None:        
            self.yAxisRange = yAxisRange
            self.axes.xaxis.set_major_formatter(ticker.FuncFormatter(
                       lambda x, pos=None: '%.1f' % self.yAxisRange[y] if 0 <= y < len(yAxisRange) else ''))
            for tick in self.axes.yaxis.get_ticklabels():
                  tick.set_rotation(15)

        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.canvas.draw()
예제 #12
0
class MatplotlibPlot:
    """ Class encapsulating a matplotlib plot"""
    def __init__(self, parent = None, dpi = 100, size = (5,5)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(size, dpi = self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

        # Reset the plot landscape
        self.figure.clear()
        self.nSubplot=0

    def resetSubplots(self):
        self.nSubplot=0

    def plotCurve(self, data, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = "", title="", label="", plotLog=False, nSubplots=1, hold=False):
        """ Plot the data as a curve"""

        if len(data) != 0:
            # Plan what dimensions the grid will have if there are to be subplots
            # Attempt to be roughly square but give preference to vertical stacking
            nSubplots_v = np.ceil(np.sqrt(nSubplots))
            nSubplots_h = np.ceil(float(nSubplots)/nSubplots_v)

            yAxisRange=np.array(yAxisRange)
            if yAxisRange is not None:
                auto_scale_y = False
                if plotLog:
                    data[data==0] = 1
                    yAxisRange[yAxisRange==0] = 1
                    data= 10*np.log(data)
                    yAxisRange = 10*np.log(yAxisRange)
            else:
                auto_scale_y = True

            # draw the new plot
            if self.nSubplot < nSubplots:
                self.axes = self.figure.add_subplot(nSubplots_v, nSubplots_h, self.nSubplot+1, label=label, title=title, ylim=yAxisRange) #subplots start from 1        
                self.axes.grid(True)
            #if plotLog:
            #    self.axes.semilogy(range(np.size(data)), data, scaley=auto_scale_y)
            #else:
            #    self.axes.plot(range(np.size(data)), data, scaley=auto_scale_y)
            self.axes.plot(range(np.size(data)), data, scaley=auto_scale_y)

            #if xAxisRange is not None:        
            #    self.xAxisRange = xAxisRange
            #    self.axes.xaxis.set_major_formatter(ticker.FuncFormatter(
            #               lambda x, pos=None: '%.2f' % self.xAxisRange[x] if 0 <= x < len(xAxisRange) else ''))
            #    for tick in self.axes.xaxis.get_ticklabels():
            #          tick.set_rotation(15)

            #if yAxisRange is not None:        
            #    self.yAxisRange = yAxisRange
            #    self.axes.xaxis.set_major_formatter(ticker.FuncFormatter(
            #               lambda x, pos=None: '%.1f' % self.yAxisRange[y] if 0 <= y < len(yAxisRange) else ''))
            #    for tick in self.axes.yaxis.get_ticklabels():
            #          tick.set_rotation(15)

            self.axes.xaxis.set_label_text(xLabel)
            self.axes.yaxis.set_label_text(yLabel)

            # Increment the subplot number ready for the plot method to be called again.
            # Count modulo number of subplots so that nSubplots=1 is the same as having a
            # single shared axis.
            # Skip this step if hold is set, in which case the next plot will be overlaid with the current one
            if not hold:
                self.nSubplot = (self.nSubplot + 1)

    def plotNewCurve(self, data, xAxisRange=None, yAxisRange=None, xLabel="", yLabel="", plotLog=False):
        # Clear the plot
        self.figure.clear()
        # Start from a new set of subplots
        self.nSubplot = 0
        self.plotCurve(self, data, xAxisRange=xAxisRange, yAxisRange=yAxisRange, xLabel=xLabel, yLabel=yLabel, plotLog=plotLog)

    def updatePlot(self):
        self.canvas.draw()
예제 #13
0
class BottleWindow(QtGui.QWidget):
    "Document window for displaying a particular bottle"

    def __init__(self, bottle):
        super(BottleWindow, self).__init__(None)
        self.ui = uic.loadUi(get_ui_file('bottle_window.ui'), self)
        self.ui.readings_view.setModel(BottleModel(DataAnalyzer(bottle, delta=True)))
        for col in range(self.ui.readings_view.model().columnCount()):
            self.ui.readings_view.resizeColumnToContents(col)
        self.exporter = BottleExporter(self)
        if matplotlib:
            self.figure = Figure(figsize=(5.0, 5.0), facecolor='w', edgecolor='w')
            self.canvas = FigureCanvas(self.figure)
            self.axes = self.figure.add_subplot(111)
            self.ui.splitter.addWidget(self.canvas)
            self.redraw_timer = QtCore.QTimer()
            self.redraw_timer.setInterval(200) # msecs
            self.redraw_timer.timeout.connect(self.redraw_timeout)
            self.ui.splitter.splitterMoved.connect(self.splitter_moved)
        self.refresh_edits()
        self.setWindowTitle('Bottle %s' % bottle.serial)
        self.ui.absolute_check.toggled.connect(self.absolute_toggled)
        self.ui.points_spin.valueChanged.connect(self.points_changed)

    @property
    def model(self):
        return self.ui.readings_view.model()

    @property
    def bottle(self):
        return self.model.analyzer.bottle

    def refresh_window(self):
        "Forces the list to be re-read from the data logger"
        self.model.beginResetModel()
        self.model.analyzer.refresh()
        self.refresh_edits()
        self.model.endResetModel()

    def refresh_edits(self):
        "Refresh all the edit controls from the bottle"
        bottle = self.model.analyzer.bottle
        self.ui.bottle_serial_edit.setText(bottle.serial)
        self.ui.bottle_id_edit.setText(str(bottle.id))
        self.ui.measurement_mode_edit.setText(bottle.mode_string)
        self.ui.bottle_volume_spin.setValue(bottle.bottle_volume)
        self.ui.sample_volume_spin.setValue(bottle.sample_volume)
        self.ui.dilution_spin.setValue(bottle.dilution)
        self.ui.start_timestamp_edit.setText(bottle.start.strftime('%c'))
        self.ui.finish_timestamp_edit.setText(bottle.finish.strftime('%c'))
        self.ui.measurement_complete_edit.setText(bottle.completed)
        self.ui.desired_values_edit.setText(str(bottle.expected_measurements))
        self.ui.actual_values_edit.setText(str(bottle.actual_measurements))
        self.ui.points_spin.setMaximum(
            max(1, bottle.actual_measurements - (
                1 if bottle.actual_measurements % 2 == 0 else 0)))
        self.ui.points_spin.setEnabled(bottle.actual_measurements > 1)
        self.ui.absolute_check.setEnabled(bottle.actual_measurements > 1)
        if bottle.actual_measurements > 1:
            self.canvas.show()
            self.invalidate_graph()
        else:
            self.canvas.hide()

    def export_file(self):
        "Export the readings to a user-specified filename"
        self.exporter.export_file()

    def absolute_toggled(self, checked):
        "Handler for the toggled signal of the absolute_check control"
        self.model.delta = not checked
        if matplotlib:
            self.invalidate_graph()

    def points_changed(self, value):
        "Handler for the valueChanged signal of the points_spin control"
        self.model.points = value
        if matplotlib:
            self.invalidate_graph()

    def splitter_moved(self, pos, index):
        "Handler for the moved signal of the splitter control"
        self.invalidate_graph()

    def invalidate_graph(self):
        "Invalidate the matplotlib graph on a timer"
        if self.redraw_timer.isActive():
            self.redraw_timer.stop()
        self.redraw_timer.start()

    def redraw_timeout(self):
        "Handler for the redraw_timer's timeout event"
        self.redraw_timer.stop()
        self.redraw_figure()

    def redraw_figure(self):
        "Called to redraw the channel image"
        # Configure the x and y axes appearance
        self.axes.clear()
        self.axes.set_frame_on(True)
        self.axes.set_axis_on()
        self.axes.grid(True)
        self.axes.set_xlabel(self.tr('Time'))
        if self.ui.absolute_check.isChecked():
            self.axes.set_ylabel(self.tr('Pressure (hPa)'))
        else:
            self.axes.set_ylabel(self.tr('Delta Pressure (hPa)'))
        m = self.ui.points_spin.value()
        for head_ix, head in enumerate(self.model.analyzer.heads):
            self.axes.plot_date(
                x=self.model.analyzer.timestamps,
                y=head,
                fmt='%s-' % matplotlib.rcParams['axes.color_cycle'][
                    head_ix % len(matplotlib.rcParams['axes.color_cycle'])]
                )
        self.axes.xaxis.set_major_formatter(DateFormatter('%d %b'))
        self.axes.autoscale_view()
        self.canvas.draw()
class AdminWindow(QWidget):

    def __init__(self, db_connection):
        super().__init__()
        self.db_connection = db_connection
        self.create_window()

    def create_window(self):
        self.setGeometry(300, 300, 900, 450) #x, y, w, h
        self.setWindowTitle('3D Printers DB - Administrator ')

        self.main_layout = QHBoxLayout(self)

        self.create_menu()
        self.menu_spacer = QSpacerItem(40, 10)
        self.main_layout.addItem(self.menu_spacer)

        self.create_welcome_message_layout()
        self.create_assign_print_layout()
        self.create_what_is_printed_layout()
        self.create_finish_print_layout()
        self.create_customer_leaderboards_layout()
        self.create_earnings_statistics_layout()

    def create_menu(self):
        self.menu = QVBoxLayout(self)

        self.menu_description = QLabel('Administrator Window', self)
        font = QFont()
        font.setPixelSize(20)
        font.setBold(True)
        self.menu_description.setFont(font)

        self.finish_print_btn = QPushButton('Finish print', self)
        self.customer_leaderboards_btn = QPushButton('Customer leaderboards', self)
        self.assign_print_btn = QPushButton('Assign print', self)
        self.what_is_printed_btn = QPushButton('What is printed?', self)
        self.earnings_statisctics_btn = QPushButton('Earnings Statisctics', self)
        self.logout_btn = QPushButton('Logout and exit', self)

        #self.make_order_btn.clicked.connect(self.make_oder_button_trigger)
        #self.order_history_btn.clicked.connect(self.order_history_button_trigger)
        #self.profile_btn.clicked.connect(self.profile_button_trigger)
        self.logout_btn.clicked.connect(self.logout_button_trigger)
        self.assign_print_btn.clicked.connect(self.assign_print_button_trigger)
        self.what_is_printed_btn.clicked.connect(self.what_is_printed_button_trigger)
        self.finish_print_btn.clicked.connect(self.finish_print_button_trigger)
        self.customer_leaderboards_btn.clicked.connect(self.customer_leaderboards_button_trigger)
        self.earnings_statisctics_btn.clicked.connect(self.earnings_statistics_button_trigger)


        self.menu.addWidget(self.menu_description)
        self.menu.addWidget(self.what_is_printed_btn)
        self.menu.addWidget(self.assign_print_btn)
        self.menu.addWidget(self.finish_print_btn)
        self.menu.addWidget(self.customer_leaderboards_btn)
        self.menu.addWidget(self.earnings_statisctics_btn)
        self.menu.addWidget(self.logout_btn)
        self.menu.addStretch()
        self.main_layout.addLayout(self.menu)

    def create_welcome_message_layout(self):
        self.welcome_message_layout = QVBoxLayout(self)

        self.welcome_message_font = QFont()
        self.welcome_message_font.setPixelSize(12)
        self.welcome_message_text = 'Welcome in Printer DB application in admin mode.\nUse menu ' \
                                    'located on the left site of window for navigation.'
        self.welcome_message = QLabel(self.welcome_message_text)
        self.welcome_message.setFont(self.welcome_message_font)
        self.welcome_message_layout.addWidget(self.welcome_message)
        self.welcome_message_layout.addStretch()
        self.main_layout.addLayout(self.welcome_message_layout)

    def hide_welcome_message_layout(self):
        self.welcome_message.hide()

    def show_welcome_message_layout(self):
        self.welcome_message.show()

    def fill_print(self):
        self.print_field.clear()
        SQL_command = "SELECT id, stl_filename, due_date, filament_type, filament_color, \
         estimated_printing_time FROM print_3d \
         WHERE completion_date IS NULL \
         AND printer_id IS NULL \
         ORDER BY due_date;"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        self.prints_to_do = []
        res = cursor.fetchone()
        while res is not None:
            self.prints_to_do.append(res)
            self.print_field.addItem(str(res.id) + ', ' + res.stl_filename + ', ' + str(res.due_date)[0:9] +', ' + res.filament_type+', ' + res.filament_color)
            res = cursor.fetchone()

    def fill_printers(self):
        self.printer_field.clear()
        SQL_command = "SELECT printer_3d.id, manufacturer, model \
                    FROM printer_3d \
                    JOIN print_3d on printer_3d.id = print_3d.printer_id \
                    WHERE completion_date IS NULL"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        self.busy_printers = []

        while res is not None:
            self.busy_printers.append(res)
            res = cursor.fetchone()

        SQL_command = "SELECT printer_3d.id, manufacturer, model \
                            FROM printer_3d"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        self.all_printers = []
        while res is not None:
            self.all_printers.append(res)
            res = cursor.fetchone()

        free_printers = []
        for i in self.all_printers:
            if i not in self.busy_printers:
               free_printers.append(i)
               self.printer_field.addItem(str(i.id)  + ', ' + i.manufacturer + ' ' + i.model)

    def create_assign_print_layout(self):
        self.assign_print_layout = QVBoxLayout(self)
        self.assign_print_grid = QGridLayout()

        self.assign_print_info = QLabel('Assign print: ', self)
        self.assign_print_info_font = QFont()
        self.assign_print_info_font.setPixelSize(16)
        self.assign_print_info_font.setBold(True)

        self.assign_print_info.setFont(self.assign_print_info_font)
        self.assign_print_layout.addWidget(self.assign_print_info)

        self.printer_label = QLabel('Printer:', self)
        self.printer_field = QListWidget(self)

        self.print_label = QLabel('Print: ', self)
        self.print_field = QListWidget(self)

        self.assign_print_apply_button = QPushButton('Assign', self)
        self.assign_print_apply_button.clicked.connect(self.print_apply_button_trigger)

        self.assign_print_grid.addWidget(self.printer_label, 0, 0)
        self.assign_print_grid.addWidget(self.printer_field, 0, 1)
        self.assign_print_grid.addWidget(self.print_label, 1, 0)
        self.assign_print_grid.addWidget(self.print_field, 1, 1)
        self.assign_print_grid.addWidget(self.assign_print_apply_button, 2, 1)

        self.assign_print_layout.addLayout(self.assign_print_grid)
        self.assign_print_layout.addStretch()
        self.main_layout.addLayout(self.assign_print_layout)
        self.hide_assign_print_layout()

    def hide_assign_print_layout(self):
        self.assign_print_info.hide()
        self.printer_label.hide()
        self.printer_field.hide()
        self.print_label.hide()
        self.print_field.hide()
        self.assign_print_apply_button.hide()

    def show_assign_print_layout(self):
        self.fill_printers()
        self.fill_print()
        self.assign_print_info.show()
        self.printer_label.show()
        self.printer_field.show()
        self.print_label.show()
        self.print_field.show()
        self.assign_print_apply_button.show()

    def create_what_is_printed_layout(self):
        self.what_is_printed_layout = QVBoxLayout(self)
        self.what_is_printed_info = QLabel('What is currently printed: ', self)
        self.what_is_printed_info_font = QFont()
        self.what_is_printed_info_font.setPixelSize(16)
        self.what_is_printed_info_font.setBold(True)

        self.what_is_printed_info.setFont(self.what_is_printed_info_font)
        self.what_is_printed_layout.addWidget(self.what_is_printed_info)

        self.what_is_printed_table = QTableWidget(self)
        self.what_is_printed_layout.addWidget(self.what_is_printed_table)
        self.main_layout.addLayout(self.what_is_printed_layout)
        self.what_is_printed_table.setColumnCount(3)
        self.what_is_printed_table.setHorizontalHeaderLabels(['Printer', 'Filename', 'Customer name'])
        self.what_is_printed_layout.addWidget(self.what_is_printed_table)
        self.hide_what_is_printed_layout()

    def update_what_is_printed_layout(self):
        SQL_command = "SELECT printer_3d.id, manufacturer, model, stl_filename, customer_username \
                    FROM printer_3d \
                    JOIN print_3d on printer_3d.id = print_3d.printer_id \
                    WHERE completion_date IS NULL"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        self.busy_printers = []

        while res is not None:
            self.busy_printers.append(res)
            res = cursor.fetchone()
        self.what_is_printed_table.setRowCount(len(self.busy_printers))
        for i in range(0, len(self.busy_printers)):
            self.what_is_printed_table.setItem(i, 0, QTableWidgetItem(str(self.busy_printers[i].id) + ' ' +\
                                                                    self.busy_printers[i].manufacturer + ' ' + \
                                                                    self.busy_printers[i].model))
            self.what_is_printed_table.setItem(i, 1, QTableWidgetItem(self.busy_printers[i].stl_filename))
            self.what_is_printed_table.setItem(i, 2, QTableWidgetItem(self.busy_printers[i].customer_username))

    def show_what_is_printed_layout(self):
        self.update_what_is_printed_layout()
        self.what_is_printed_info.show()
        self.what_is_printed_table.show()

    def hide_what_is_printed_layout(self):
        self.what_is_printed_info.hide()
        self.what_is_printed_table.hide()

    def create_finish_print_layout(self):
        self.finish_print_layout = QVBoxLayout(self)

        self.finish_print_info = QLabel('Finish print: ', self)
        self.finish_print_info_font = QFont()
        self.finish_print_info_font.setPixelSize(16)
        self.finish_print_info_font.setBold(True)

        self.finish_print_info.setFont(self.finish_print_info_font)
        self.finish_print_layout.addWidget(self.finish_print_info)

        self.busy_printers_field = QListWidget(self)
        self.finish_print_layout.addWidget(self.busy_printers_field)
        self.finish_print_apply_button = QPushButton('Finish print', self)
        self.finish_print_apply_button.clicked.connect(self.finish_print_apply_button_trigger)


        self.finish_print_filo_layout = QHBoxLayout(self)
        self.finish_print_filo_layout_descriptions = QVBoxLayout(self)
        self.finish_print_filo_layout_select = QVBoxLayout(self)
        self.finish_print_filo_layout.addLayout(self.finish_print_filo_layout_descriptions)
        self.finish_print_filo_layout.addLayout(self.finish_print_filo_layout_select)

        self.finish_print_filo_manufacturer_description = QLabel('Filament manufacturer: ', self)
        self.finish_print_filo_diameter_description = QLabel('Filament diameter: ', self)
        self.finish_print_filo_type_description = QLabel('Filament type: ', self)
        self.finish_print_filo_color_description = QLabel('Filament color: ', self)
        self.finish_print_filo_amount_description = QLabel('Amount [gram]: ', self)


        self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_manufacturer_description)
        self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_diameter_description)
        self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_type_description)
        self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_color_description)
        self.finish_print_filo_layout_descriptions.addWidget(self.finish_print_filo_amount_description)

        self.finish_print_filo_manufacturer_select = QComboBox(self)
        self.finish_print_filo_diameter_select = QComboBox(self)
        self.finish_print_filo_type_select = QComboBox(self)
        self.finish_print_filo_color_select = QComboBox(self)
        self.finish_print_filo_amount_select = QLineEdit(self)

        self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_manufacturer_select)
        self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_diameter_select)
        self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_type_select)
        self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_color_select)
        self.finish_print_filo_layout_select.addWidget(self.finish_print_filo_amount_select)

        self.finish_print_layout.addLayout(self.finish_print_filo_layout)
        self.finish_print_layout.addWidget(self.finish_print_apply_button)
        self.main_layout.addLayout(self.finish_print_layout)

        self.hide_finish_print_layout()

    def find_filament_id(self, manufacturer, diameter, type, color):
        SQL_command = "select id FROM filament WHERE " + \
                    "manufacturer = '" + manufacturer +  "' AND " + \
                    "diameter = " + diameter +  " AND " + \
                    "color = '" + color + "' AND " + \
                    "type = '" + type + "'"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        if res is not None:
            return res.id
        else:
            return -1



    def update_finish_print_layout(self):
        self.busy_printers_field.clear()
        SQL_command = "SELECT printer_3d.id, manufacturer, model \
                            FROM printer_3d \
                            JOIN print_3d on printer_3d.id = print_3d.printer_id \
                            WHERE completion_date IS NULL AND printer_id IS NOT NULL"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()

        while res is not None:
            self.busy_printers_field.addItem(str(res.id) + ', ' + res.manufacturer + ' ' + res.model)
            res = cursor.fetchone()

        #clearing all fields
        self.finish_print_filo_manufacturer_select.clear()
        self.finish_print_filo_diameter_select.clear()
        self.finish_print_filo_type_select.clear()
        self.finish_print_filo_color_select.clear()
        self.finish_print_filo_amount_select.clear()

        SQL_command = "SELECT DISTINCT manufacturer FROM filament"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()

        while res is not None:
            self.finish_print_filo_manufacturer_select.addItem(res.manufacturer)
            res = cursor.fetchone()

        SQL_command = "SELECT DISTINCT diameter FROM filament"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()

        while res is not None:
            self.finish_print_filo_diameter_select.addItem(str(res.diameter))
            res = cursor.fetchone()

        SQL_command = "SELECT DISTINCT type FROM filament"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()

        while res is not None:
            self.finish_print_filo_type_select.addItem(res.type)
            res = cursor.fetchone()

        SQL_command = "SELECT DISTINCT color FROM filament"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()

        while res is not None:
            self.finish_print_filo_color_select.addItem(res.color)
            res = cursor.fetchone()


    def show_finish_print_layout(self):
        self.update_finish_print_layout()
        self.busy_printers_field.show()
        self.finish_print_info.show()
        self.finish_print_apply_button.show()
        self.finish_print_filo_manufacturer_description.show()
        self.finish_print_filo_diameter_description.show()
        self.finish_print_filo_type_description.show()
        self.finish_print_filo_color_description.show()
        self.finish_print_filo_manufacturer_select.show()
        self.finish_print_filo_diameter_select.show()
        self.finish_print_filo_type_select.show()
        self.finish_print_filo_color_select.show()
        self.finish_print_filo_amount_description.show()
        self.finish_print_filo_amount_select.show()


    def hide_finish_print_layout(self):
        self.busy_printers_field.hide()
        self.finish_print_info.hide()
        self.finish_print_apply_button.hide()
        self.finish_print_filo_manufacturer_description.hide()
        self.finish_print_filo_diameter_description.hide()
        self.finish_print_filo_type_description.hide()
        self.finish_print_filo_color_description.hide()
        self.finish_print_filo_manufacturer_select.hide()
        self.finish_print_filo_diameter_select.hide()
        self.finish_print_filo_type_select.hide()
        self.finish_print_filo_color_select.hide()
        self.finish_print_filo_amount_description.hide()
        self.finish_print_filo_amount_select.hide()


    def create_customer_leaderboards_layout(self):
        self.customer_leaderboards_layout = QVBoxLayout(self)
        self.customer_leaderboards_info = QLabel('Customer leaderboards: ', self)
        self.customer_leaderboards_info_font = QFont()
        self.customer_leaderboards_info_font.setPixelSize(16)
        self.customer_leaderboards_info_font.setBold(True)

        self.customer_leaderboards_info.setFont(self.customer_leaderboards_info_font)
        self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_info)

        self.customer_leaderboards_table = QTableWidget(self)
        self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_table)
        self.main_layout.addLayout(self.customer_leaderboards_layout)
        self.customer_leaderboards_table.setColumnCount(4)
        self.customer_leaderboards_table.setHorizontalHeaderLabels(['Username', 'First name', 'Last name', 'Loyalty points'])
        self.customer_leaderboards_layout.addWidget(self.customer_leaderboards_table)
        self.hide_customer_leaderboards_layout()

    def update_customer_leaderboards_layout(self):
        self.busy_printers_field.clear()
        SQL_command = "SELECT TOP 3 username, first_name, last_name, loyalty_points from customer order by loyalty_points DESC"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        customers = []
        while res is not None:
            customers.append(res)
            res = cursor.fetchone()
        self.customer_leaderboards_table.setRowCount(len(customers))
        for i in range(0, len(customers)):
            self.customer_leaderboards_table.setItem(i, 0, QTableWidgetItem(customers[i].username))
            self.customer_leaderboards_table.setItem(i, 1, QTableWidgetItem(customers[i].first_name))
            self.customer_leaderboards_table.setItem(i, 2, QTableWidgetItem(customers[i].last_name))
            self.customer_leaderboards_table.setItem(i, 3, QTableWidgetItem(str(customers[i].loyalty_points)))

    def show_customer_leaderboards_layout(self):
        self.update_customer_leaderboards_layout()
        self.customer_leaderboards_info.show()
        self.customer_leaderboards_table.show()

    def hide_customer_leaderboards_layout(self):
        self.customer_leaderboards_info.hide()
        self.customer_leaderboards_table.hide()

    def hide_all(self):
        self.hide_assign_print_layout()
        self.hide_what_is_printed_layout()
        self.hide_welcome_message_layout()
        self.hide_finish_print_layout()
        self.hide_customer_leaderboards_layout()
        self.hide_earnings_statistics_layout()

    def create_earnings_statistics_layout(self):
        self.earnings_statistics_layout = QVBoxLayout(self)

        self.main_layout.addLayout(self.earnings_statistics_layout)

        self.earnings_statistics_info = QLabel('Earnings Statistics: ', self)
        self.earnings_statistics_info_font = QFont()
        self.earnings_statistics_info_font.setPixelSize(16)
        self.earnings_statistics_info_font.setBold(True)
        self.earnings_statistics_info.setFont(self.earnings_statistics_info_font)
        self.earnings_statistics_layout.addWidget(self.earnings_statistics_info)

        self.earnings_statistics_selection_layout = QHBoxLayout(self)

        self.earnings_statistics_layout.addLayout(self.earnings_statistics_selection_layout)

        self.earnings_statistics_duration_info = QLabel('Statistics duration: ', self)
        self.earnings_statistics_duration_field = QComboBox(self)
        self.earnings_statistics_duration_field.addItem('1 Week')
        self.earnings_statistics_duration_field.addItem('1 Month')
        self.earnings_statistics_duration_field.addItem('1 Year')

        self.earnings_statistics_duration_field.currentIndexChanged.connect(self.update_earnings_plot)
        self.earnings_statistics_selection_layout.addWidget(self.earnings_statistics_duration_info)
        self.earnings_statistics_selection_layout.addWidget(self.earnings_statistics_duration_field)

        self.earnings_statistics_figure = Figure()
        self.earnings_statistics_canvas = FigureCanvas(self.earnings_statistics_figure)
        self.earnings_statistics_layout.addWidget(self.earnings_statistics_canvas)
        self.update_earnings_plot()

        self.hide_earnings_statistics_layout()

    def get_earnings_data_week(self):
        d = datetime.datetime.now()
        delta = datetime.timedelta(days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
        dates = []
        earnings = []
        xlabels = []

        for i in range(0, 7):
            dates.append(str(d).split('.')[0])
            d = d - delta
            xlabels.append(-i-1)

        for d in dates:
            SQL_command =  "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';"
            cursor = self.db_connection.cursor()
            cursor.execute(SQL_command)
            res = cursor.fetchone()
            if res is not None:
                if res[0] is not None:
                    earnings.append(res[0])
                else:
                    earnings.append(Decimal(0))
        return xlabels, earnings

    def get_earnings_data_month(self):
        d = datetime.datetime.now()
        delta = datetime.timedelta(days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
        dates = []
        earnings = []
        xlabels = []

        for i in range(0, 31):
            dates.append(str(d).split('.')[0])
            d = d - delta
            xlabels.append(-i-1)

        for d in dates:
            SQL_command = "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';"
            cursor = self.db_connection.cursor()
            cursor.execute(SQL_command)
            res = cursor.fetchone()
            if res is not None:
                if res[0] is not None:
                    earnings.append(res[0])
                else:
                    earnings.append(Decimal(0))
        return xlabels, earnings

    def get_earnings_data_year(self):
        d = datetime.datetime.now()
        delta = relativedelta(months=1)
        dates = []
        earnings = []
        xlabels = []

        for i in range(0, 12):
            dates.append(str(d).split('.')[0])
            d = d - delta
            xlabels.append(-i-1)

        for d in dates:
            SQL_command = "SELECT SUM(cost) FROM print_3d WHERE completion_date < '" + d + "';"
            cursor = self.db_connection.cursor()
            cursor.execute(SQL_command)
            res = cursor.fetchone()
            if res is not None:
                if res[0] is not None:
                    earnings.append(res[0])
                else:
                    earnings.append(Decimal(0))
        return xlabels, earnings

    def update_earnings_plot(self):
        if (str(self.earnings_statistics_duration_field.currentText())) == '1 Week':
            ''' plot some random stuff '''
            print('week')
            datax, datay = self.get_earnings_data_week()

            self.earnings_statistics_figure.clear()

            self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111)
            self.earnings_statiscitcs_subplot.clear()
            self.earnings_statiscitcs_subplot.grid(True)
            self.earnings_statiscitcs_subplot.set_xlabel('Day (from now)')
            self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]')

            self.earnings_statiscitcs_subplot.plot(datax, datay, '*-')
            self.earnings_statistics_canvas.draw()

        if (str(self.earnings_statistics_duration_field.currentText())) == '1 Month':
            ''' plot some random stuff '''

            print('month')
            # random data
            datax, datay = self.get_earnings_data_month()

            self.earnings_statistics_figure.clear()

            self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111)
            self.earnings_statiscitcs_subplot.clear()
            self.earnings_statiscitcs_subplot.grid(True)
            self.earnings_statiscitcs_subplot.set_xlabel('Day (from now)')
            self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]')

            self.earnings_statiscitcs_subplot.plot(datax, datay, '*-')
            self.earnings_statistics_canvas.draw()
        if (str(self.earnings_statistics_duration_field.currentText())) == '1 Year':
            ''' plot some random stuff '''

            datax, datay = self.get_earnings_data_year()

            self.earnings_statistics_figure.clear()

            self.earnings_statiscitcs_subplot = self.earnings_statistics_figure.add_subplot(111)
            self.earnings_statiscitcs_subplot.clear()
            self.earnings_statiscitcs_subplot.grid(True)
            self.earnings_statiscitcs_subplot.set_xlabel('Month (from now)')
            self.earnings_statiscitcs_subplot.set_ylabel('Earnings [zl]')
            print(self.earnings_statiscitcs_subplot.get_ylabel())

            self.earnings_statiscitcs_subplot.plot(datax, datay, '*-')
            self.earnings_statistics_canvas.draw()


    def show_earnings_statistics_layout(self):
        self.earnings_statistics_info.show()
        self.earnings_statistics_duration_info.show()
        self.earnings_statistics_duration_field.show()
        self.earnings_statistics_canvas.show()

    def hide_earnings_statistics_layout(self):
        self.earnings_statistics_info.hide()
        self.earnings_statistics_duration_info.hide()
        self.earnings_statistics_duration_field.hide()
        self.earnings_statistics_canvas.hide()

    def earnings_statistics_button_trigger(self):
        self.hide_all()
        self.show_earnings_statistics_layout()

    def print_apply_button_trigger(self):
        if self.printer_field.currentItem() is not None:
            printer_id = self.printer_field.currentItem().text().split(',')[0]
            if self.print_field.currentItem() is not None:
                print_id = self.print_field.currentItem().text().split(',')[0]
                SQL_command = "UPDATE print_3d SET printer_id = " + \
                                printer_id + " WHERE print_3d.id = " + \
                                print_id
                cursor = self.db_connection.cursor()
                cursor.execute(SQL_command)
                cursor.commit()
                self.hide_assign_print_layout()
                self.show_assign_print_layout()
                popup = QMessageBox()
                popup.setIcon(QMessageBox.Information)
                popup.setText("Successfully assigned print to printer")
                popup.setWindowTitle("Assigned print to printer")
                popup.exec_()
            else:
                popup = QMessageBox()
                popup.setIcon(QMessageBox.Critical)
                popup.setText("Select print")
                popup.setWindowTitle("Error - print not selected")
                popup.exec_()

        else:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Select printer")
            popup.setWindowTitle("Error - printer not selected")
            popup.exec_()

    def assign_print_button_trigger(self):
        self.hide_all()
        self.show_assign_print_layout()

    def what_is_printed_button_trigger(self):
        self.hide_all()
        self.show_what_is_printed_layout()

    def finish_print_button_trigger(self):
        self.hide_all()
        self.show_finish_print_layout()

    def finish_print_apply_button_trigger(self):

        manufacturer = str(self.finish_print_filo_manufacturer_select.currentText())
        diameter = str(self.finish_print_filo_diameter_select.currentText())
        type = str(self.finish_print_filo_type_select.currentText())
        color = str(self.finish_print_filo_color_select.currentText())

        amount = str(self.finish_print_filo_amount_select.text())
        if len(amount) != 0:
            amount = str((float(amount)) / 1000)
        filament_id = str(self.find_filament_id(manufacturer, diameter, type, color))
        if filament_id == '-1':
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("There is no such filament")
            popup.setWindowTitle("No filament")
            popup.exec_()
            return

        date = str(datetime.datetime.now()).split('.')[0]

        if len(amount) == 0:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Please set amount of used filament")
            popup.setWindowTitle("No filament amount error")
            popup.exec_()
            return


        if self.busy_printers_field.currentItem() is not None:
            now = datetime.datetime.now()

            print_id = self.busy_printers_field.currentItem().text().split(',')[0]
            SQL_command = "UPDATE print_3d SET completion_date = '" + \
                                str(now)[0:10] + "' WHERE printer_id = " + \
                                print_id + "AND completion_date IS NULL"
            cursor = self.db_connection.cursor()
            cursor.execute(SQL_command)
            cursor.commit()
            self.hide_finish_print_layout()
            self.show_finish_print_layout()
        else:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Please select a printer")
            popup.setWindowTitle("No printer selected")
            popup.exec_()
            return

        SQL_command = "INSERT INTO filament_history (filament_id, order_date, delivered_date, added_amount) VALUES (" \
                      + filament_id + ", '" + date + "', '" + date + "', -" + amount + ')'
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        cursor.commit()

        popup = QMessageBox()
        popup.setIcon(QMessageBox.Information)
        popup.setText("Successfully finished print")
        popup.setWindowTitle("Finished print")
        popup.exec_()

    def customer_leaderboards_button_trigger(self):
        self.hide_all()
        self.show_customer_leaderboards_layout()

    def logout_button_trigger(self):
        self.destroy()
        exit(0)
예제 #15
0
class GraphView(QtGui.QWidget):
    def __init__(self, pymol, pmap, parent=None):
        super(GraphView, self).__init__(parent)
        self.pymol = pymol
        self.dpi = 300
        self.pmap = pmap
        self.fig = Figure((4.5, 4.5), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.mpl_connect("button_press_event", self._onpick)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        if self.pmap.use_ca:
            self.xcoor = self.pmap.residue_numbers_ca[self.pmap.parent.current_model]
        else:
            self.xcoor = self.pmap.residue_numbers_cb[self.pmap.parent.current_model]
        self.ycoor = self.pmap.histogram_maps[self.pmap.parent.current_model]
        self.bar = self.axes.bar(self.xcoor, self.ycoor, width=1.0, linewidth=0)
        self.canvas.show()
        self.set_parameters()

    def _get_clicked_residues(self, event):
        xmin, xmax = self.axes.get_xlim()
        return int(math.ceil(event.xdata - xmin)) - 1

    def _onpick(self, event):
        if self.pmap.use_ca:
            atom = "CA"
            chains = self.pmap.chain_names_ca[self.pmap.parent.current_model]
            residue_numbers = self.pmap.residue_numbers_ca[self.pmap.parent.current_model]
        else:
            atom = "CB"
            chains = self.pmap.chain_names_cb[self.pmap.parent.current_model]
            residue_numbers = self.pmap.residue_numbers_cb[self.pmap.parent.current_model]

        index = self._get_clicked_residues(event)
        self.pymol.select_density(residue_numbers[index], atom, self.pmap.cutoff, chains[index])

    def set_parameters(self):
        self.axes.tick_params(axis=u"both", which=u"both", length=0)
        self.axes.set_xlim(min(self.xcoor), max(self.xcoor))
        self.axes.set_ylim(0, max(self.ycoor) + 1)
        self.axes.set_xlabel("Residue Number")
        self.axes.set_ylabel("Contact Counts")
        fractions = self.ycoor / max(self.ycoor)
        normalized_colors = colors.Normalize(fractions.min(), fractions.max())
        count = 0
        for rect in self.bar:
            c = cm.jet(normalized_colors(fractions[count]))
            rect.set_facecolor(c)
            count += 1
        self.fig.patch.set_facecolor((0.886, 0.886, 0.886))
        ticks_font = mpl.font_manager.FontProperties(
            family="times new roman", style="normal", size=12, weight="normal", stretch="normal"
        )
        labels = [self.axes.title, self.axes.xaxis.label, self.axes.yaxis.label]
        labels += self.axes.get_xticklabels() + self.axes.get_yticklabels()
        for item in labels:
            item.set_fontproperties(ticks_font)
            item.set_fontsize(4)

    def update_graph(self):
        self.axes.clear()
        if self.pmap.use_ca:
            self.xcoor = self.pmap.residue_numbers_ca[self.pmap.parent.current_model]
        else:
            self.xcoor = self.pmap.residue_numbers_cb[self.pmap.parent.current_model]
        self.ycoor = self.pmap.histogram_maps[self.pmap.parent.current_model]
        self.bar = self.axes.bar(self.xcoor, self.ycoor, width=1.0, linewidth=0)
        self.set_parameters()
        self.canvas.draw()
예제 #16
0
class SelectZoneWidget(QtGui.QWidget):

    _imageChanged = pyqtSignal(np.ndarray)
    _imageReset = pyqtSignal()
    _homographyChanged = pyqtSignal(list)

    def __init__(self, hWidget, parent=None):
        super(SelectZoneWidget, self).__init__(parent)
        self._hWidget = hWidget
        self._imageChanged.connect(self._hWidget.setImage)
        self._homographyChanged.connect(self._hWidget.setHomography)
        self._imageReset.connect(self._hWidget.reset)
        self._initUI()

    # Initialize the UI
    def _initUI(self):
        # Widget parameters
        self.setMinimumWidth(300)

        # Create the figure
        self._fig = Figure()

        # Canvas configuration
        self._canvas = FigureCanvas(self._fig)
        self._canvas.setParent(self)
        self._canvas.mpl_connect('button_press_event', self._onPick)

        # Plot configuration
        self._plt = self._fig.add_subplot(111)
        self._plt.xaxis.set_visible(False)
        self._plt.yaxis.set_visible(False)

        # Finalize figure
        self._fig.subplots_adjust(wspace=0, hspace=0)

        # Reset the variables
        self.reset()

        # Create the layout
        vbox = QtGui.QVBoxLayout()

        # Add Canvas to the layout
        vbox.addWidget(self._canvas)

        # Set the layout
        self.setLayout(vbox)

        zp = ZoomPan()
        figZoom = zp.zoom_factory(self._plt)
        figPan = zp.pan_factory(self._plt)


    # Reset the variables to original state
    def reset(self):
        self._canvas.hide()
        self._image = None
        self._points = []
        self._imageReset.emit()

    # Set an image to the widget
    def setImage(self, image):
        self.reset()
        self._image = image
        self._redraw()
        self._canvas.show()
        self._imageChanged.emit(image)

    # Get the image of the widget
    def getImage(self):
        pass

    # Redraw the image and points
    def _redraw(self):
        # Clear the canvas
        self._plt.clear()

        # Plot the image
        if self._image is not None:
            self._plt.autoscale(True)
            self._plt.imshow(self._image)
            self._plt.autoscale(False)

        # Plot the points
        if len(self._points) > 0:
            xs = [x for (x, _) in self._points]
            ys = [y for (_, y) in self._points]
            self._plt.plot(xs + [xs[0]], ys + [ys[0]], '-', color='red')
            self._plt.plot(xs + [xs[0]], ys + [ys[0]], 'o', color='blue')

        # Draw the canvas
        self._canvas.draw()

    # Handle click events
    def _onPick(self, event):

        if event.button == 3:
            self._redraw()
        elif event.button != 1:
            return

        # Get point position
        x = event.xdata
        y = event.ydata

        if x is None or y is None:
            return

        # For each existing points
        for px, py in self._points:

            # Compute distance to current point
            dst = np.sqrt((px - x) ** 2 + (py - y) ** 2)

            # If the distance is small remove it
            if dst < 10:
                self._removePoint(px, py)
                self._redraw()
                return

        # Delegate to add the point
        self._addPoint(x, y)

        # Redraw the image
        self._redraw()

    # Add a new point
    def _addPoint(self, x, y):
        # Count points
        n = len(self._points)

        # If less than 3 points just add it
        if n < 3:
            self._points.append((x, y))
            return

        # If already 4 points, ignore it
        if n >= 4:
            return

        # Else a verification must be done
        if self._validPoint(x, y):
            # Add the point
            self._points.append((x, y))

            # Reorder points to have consistant rectangle when drawing
            self._reorderPoints()

            # Lunch the homography
            self._homographyChanged.emit(self._points)

    # Remove an existing point
    def _removePoint(self, x, y):
        # Reset homograpy if we remove the 4th point
        if len(self._points) == 4:
            self._imageChanged.emit(self._image)

        # Remove the point
        self._points = list(filter(lambda v: v != (x, y), self._points))

    # Reorder points to have a planar graph (meaning no line crossing)
    def _reorderPoints(self):
        # List of reordoned points
        ordPoints = [self._points[0]]

        # List of selectionnable points
        others = self._points[1:]

        # Fill reordoned points
        while len(ordPoints) < 4:
            # Previous point
            p = ordPoints[-1]

            # Test other points
            for pn in others:
                # Points to verify side
                verify = list(filter(lambda v: v != pn and v != p,
                                     self._points))

                # Verify side
                if allSameSide(p, pn, verify):
                    ordPoints.append(pn)
                    others = list(filter(lambda v: v != pn, others))
                    break

        # Set the reordoned points
        self._points = ordPoints

    def _validPoint(self, x, y):
        a = [p for p in self._points] + [(x, y)]
        triangles = [[a[0], a[1], a[2]], [a[0], a[1], a[3]],
                     [a[0], a[2], a[3]], [a[1], a[2], a[3]]]
        points = [a[3], a[2], a[1], a[0]]

        for triangle, point in zip(triangles, points):
            px, py = point
            if lieIntoTriangle(triangle, px, py):
                return False

        return True
예제 #17
0
class View(QtGui.QWidget):
    def __init__(self,
                 parent=None,
                 width=5,
                 height=4,
                 dpi=80,
                 filename=None,
                 model=None,
                 plot_type='Image',
                 trace_num=None,
                 region=[]):
        # plot paramters #
        self.t_num = trace_num
        self.region = region

        # connect model signal #
        self.model = model
        self.model.dataChanged.connect(self.update_views)

        # create a dictionary of views
        self.view_options = {
            'Image': self.view_image,
            'TracePlot': self.view_trace,
            'PSD': self.view_psd,
            'Surface': self.view_surface
        }
        super(View, self).__init__(parent)

        # make the figure
        self.figure = Figure((width, height), dpi)
        fig_color = (1.0, 1.0, 1.0, 1.0)
        self.figure.set_facecolor(fig_color)
        # create the canvas
        self.canvas = Canvas(self.figure)
        self.canvas.setParent(self)

        # create the toolbar and tie it to the canvas
        self.toolbar = Toolbar(self.canvas, self)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.setLayout(self.layout)
        if filename:
            self.setWindowTitle(plot_type + ': ' + filename)

        if plot_type == 'Surface':
            self.axes = self.figure.gca(projection='3d')
        else:
            self.axes = self.figure.add_subplot(111)

        self.axes.hold(False)

        self.view_options[plot_type]()
        self.canvas.show()

    def view_image(self):
        self.axes.imshow(self.model.get_agc_data(), cmap=cm.coolwarm)
        self.axes.set_xticklabels([])
        self.axes.set_yticklabels([])
        self.axes.set_xticks([])
        self.axes.set_yticks([])
        self.axes.set_xlabel('source channel')
        self.axes.set_ylabel('time')

    def view_trace(self):
        print self.t_num
        y = self.model.getTrace(self.t_num)
        x = np.arange(len(y))
        self.axes.fill(x, y, 'r', linewidth=0)
        self.axes.set_xlabel('time')
        self.axes.set_ylabel('amplitude')
        self.axes.set_xlim(0, len(x))
        self.axes.grid(True)

    def view_surface(self):

        #x = np.arange(self.model.getNTraces())
        #y = np.arange(self.model.getTLength())
        y = np.arange(self.region[1] - self.region[0])
        x = np.arange(self.region[3] - self.region[2])
        x, y = np.meshgrid(x, y)
        z = self.model.get_agc_data()
        z = z[self.region[0]:self.region[1], self.region[2]:self.region[3]]
        print self.model.getTLength()
        self.axes.plot_surface(x,
                               y,
                               z,
                               rstride=1,
                               cstride=1,
                               cmap=cm.coolwarm,
                               linewidth=0,
                               antialiased=False)

    def view_psd(self):
        y = self.model.get_psd_of_trace(self.t_num)
        x = np.arange(-len(y) / 2, len(y) / 2)
        print x.shape
        print y.shape
        self.axes.semilogy(x, y, 'r', linewidth=1)
        self.axes.set_xlabel('frequency')
        self.axes.set_ylabel('spectral density')
        self.axes.set_xlim(-len(x) / 2, len(x) / 2)
        self.axes.grid(True)

    def update_views(self):
        print "updating views"
예제 #18
0
class GraphView(QtGui.QWidget):
    def __init__(self, image, aa, pymol, pmap, parent=None):
        super(GraphView, self).__init__(parent)
        self.aa = aa
        self.pymol = pymol
        self.dpi = 300
        self.pmap = pmap
        self.fig = Figure((4.5, 4.5), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.mpl_connect('button_press_event', self._onpick)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.dmap = self.cmap_discretize(cm.spectral, 10)
        self.image = image
        self.map = self.axes.imshow(self.image, interpolation='nearest', cmap=self.dmap, aspect='equal', origin='lower')
        self.canvas.show()
        self.set_parameters()

    def cmap_discretize(self, cmap, N):
        """Return a discrete colormap from the continuous colormap cmap.

            cmap: colormap instance, eg. cm.jet.
            N: number of colors.

        Example
            x = resize(arange(100), (5,100))
            djet = cmap_discretize(cm.jet, 5)
            imshow(x, cmap=djet)
        """
        if type(cmap) == str:
            cmap = cm.get_cmap(cmap)
        colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.)))
        colors_rgba = cmap(colors_i)
        indices = np.linspace(0, 1., N + 1)
        cdict = {}
        for ki, key in enumerate(('red', 'green', 'blue')):
            cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in xrange(N + 1)]
        # Return colormap object.
        return colors.LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)

    def _get_clicked_residues(self, event):
        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        return(int(math.ceil(event.xdata - xmin))-1, int(math.ceil(event.ydata - ymin))-1)

    def _onpick(self, event):
        if self.pmap.use_ca:
            atom = 'CA'
        else:
            atom = 'CB'

        index1, index2 = self._get_clicked_residues(event)
        if self.image[index1][index2] > 0:
            self.pymol.select_aminoacids(self.aa[index1], self.aa[index2], atom, self.pmap.cutoff)

    def set_parameters(self):
        cbar_ax = self.fig.add_axes([0.12, 0.94, 0.75, 0.03])
        cbar_ax.xaxis.labelpad = 3.0
        cbar_ax.tick_params(length=2.0, direction='out', pad=0.0)
        cbar = self.fig.colorbar(self.map, cax=cbar_ax, orientation='horizontal', drawedges=False)
        cbar_ax.xaxis.set_ticks_position('top')
        cbar_ax.xaxis.set_label_position('bottom')
        cbar_ax.xaxis.set_label_text('Contact Counts')
        self.axes.tick_params(axis=u'both', which=u'both', length=0)
        self.axes.xaxis.set_ticks(range(0, len(self.aa), 1))
        self.axes.yaxis.set_ticks(range(0, len(self.aa), 1))
        self.axes.set_xticklabels(self.aa, rotation=90)
        self.axes.set_yticklabels(self.aa)
        self.fig.patch.set_facecolor((0.886, 0.886, 0.886))
        ticks_font = mpl.font_manager.FontProperties(family='times new roman', style='normal', size=12, weight='normal',
                                                     stretch='normal')
        labels = [self.axes.title, self.axes.xaxis.label, self.axes.yaxis.label, cbar.ax.xaxis.label]
        labels += self.axes.get_xticklabels() + self.axes.get_yticklabels() + cbar.ax.get_xticklabels()
        for item in labels:
            item.set_fontproperties(ticks_font)
            item.set_fontsize(4)

    def update_graph(self, image):
        self.axes.clear()
        self.image = image
        self.map = self.axes.imshow(self.image, interpolation='nearest', cmap=self.dmap, aspect='equal', origin='lower')
        self.set_parameters()
        self.canvas.draw()
예제 #19
0
파일: Plot.py 프로젝트: astrofrog/ginga
class Plot(Callback.Callbacks):
    def __init__(self, logger):
        Callback.Callbacks.__init__(self)

        self.logger = logger

        # For callbacks
        for name in ('close', ):
            self.enable_callback(name)

        self.fig = matplotlib.figure.Figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_xlabel('X values')
        self.ax.set_ylabel('Y values')
        self.ax.set_title('')
        self.ax.grid(True)
        self.canvas = FigureCanvas(self.fig)

    def get_widget(self):
        return self.canvas

    def _sanity_check_window(self):
        pass

    def set_titles(self, xtitle=None, ytitle=None, title=None, rtitle=None):
        self._sanity_check_window()
        if xtitle != None:
            self.ax.set_xlabel(xtitle)
        if ytitle != None:
            self.ax.set_ylabel(ytitle)
        if title != None:
            self.ax.set_title(title)
        if rtitle != None:
            pass

    def clear(self):
        self._sanity_check_window()
        self.logger.debug('clearing canvas...')
        self.ax.cla()

    def show(self):
        self._sanity_check_window()
        self.logger.debug('raising window...')
        self.canvas.show()

    def hide(self):
        self._sanity_check_window()
        self.logger.debug('hiding window...')
        pass

    def close(self):
        self.logger.debug('closing window....')
        self.canvas.destroy()

        self.make_callback('close')
        return False

    def _draw(self):
        self.fig.canvas.draw()

    def plot(self,
             xarr,
             yarr,
             xtitle=None,
             ytitle=None,
             title=None,
             rtitle=None,
             color=None,
             alpha=1.0):
        self.set_titles(xtitle=xtitle,
                        ytitle=ytitle,
                        title=title,
                        rtitle=rtitle)
        if not color:
            self.ax.plot(xarr, yarr, linewidth=1.0, alpha=alpha, linestyle='-')
        else:
            self.ax.plot(xarr,
                         yarr,
                         linewidth=1.0,
                         color=color,
                         alpha=alpha,
                         linestyle='-')
        self.ax.grid(True)
        self._draw()
class JouleBraytonDialog(QDialog, layout_cicloJouleBrayton.Ui_Dialog):

    # Estas lineas son medias magicas, pero siempre van:
    def __init__(self,parent=None):
        super(JouleBraytonDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle(__appName__)

        # Creo algunas variables que generales que luego voy a usar
        self.Q = []
        self.gamma_aire = 1.4
        self.R_aire = 287
        #Defino las formulas quimicas para selecionar en formulas_comboBox
        self.formulas = {"AvGas":{'c':7,'h':16,'o':0,'s':0.00},"Diesel":{'c':12,'h':21,'o':0,'s':0.00}}
        # Utilizo las 'keys' de self.formulas para cargar los items en la combobox
        for key in self.formulas.keys():
            self.formula_comboBox.addItem(key)

        self.actualizarFormula()

        # Generamos dos figuras, cada una luego asociada a un canvas, que a su vez tiene como padre una de las pestañas
        # self.tab -> contiene la pestaña titulada "Diagrama P-S"
        # self.tab_2 -> contiene la pestaña titulada "Diagrama T-S"
        self.fig1 = Figure(figsize=(4.8,3.4),dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
        self.axes1 = self.fig1.add_subplot(111)
        self.axes1.set_ylabel('p')
        self.axes1.set_xlabel('v')
        self.axes1.set_title('Ciclo Joule-Brayton')
        self.axes1.ticklabel_format(style="sci", scilimits=(0, 0), axis="both")  # , useOffset=True,useLocale=True)
        self.axes1.tick_params(axis="both", direction='in', length=6, width=2, labelsize="medium")
        self.fig2 = Figure(figsize=(4.8,3.4),dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
        self.axes2 = self.fig2.add_subplot(111)
        self.axes2.set_ylabel('T')
        self.axes2.ticklabel_format(style='sci', scilimits=(0, 0), axis="both")
        self.axes2.set_xlabel('S')
        self.axes2.set_title('Ciclo Joule-Brayton')
        # generate the canvas to display the plot
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setParent(self.tab)
        self.canvas1.show()
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.setParent(self.tab_2)
        self.canvas2.show()

#        Cambio los lineInput de HVS y HVI a "ReadOnly"
        self.HVS_lineEdit.setReadOnly(True)
        self.HVI_lineEdit.setReadOnly(True)

        #Inicializo la parte de la postcombustión como no habilitada.
        self.datoExtra_3.setDisabled(True)
        self.selecDatoExtra_3.setDisabled(True)
        self.theta1.setDisabled(True)

        #Seleccion de una formula en formula_comboBox
        self.connect(self.formula_comboBox,SIGNAL("currentIndexChanged(int)"),self.selecionFormula)

        #Acciones de actualización de la formula quimica para el calculo de Q
        # En este punto tengo que agregar la opción de que si Q surge como resultado
        # de otro parametros de entrada, la relación demezcla se tendrá que actualizar
        # para que la formula y la relación sean compatibles con el Q obtenido
        self.connect(self.formulaC,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaH,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaO,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaS,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.relacionMezcla,SIGNAL("valueChanged(double)"),self.actualizarFormula)
        self.connect(self.calcular,SIGNAL("clicked()"),self.Calculos)
        # Configurando el boton de check para la postcombustion
        self.connect(self.PostCombustion,SIGNAL("stateChanged(int)"),self.enable_PostCombustion)
        self.connect(self.selecDatoExtra_2,SIGNAL("currentIndexChanged(int)"),self.actualizarFormula)
        # Boton para mostrar matriz de resultados
        self.connect(self.matrixButton,SIGNAL("clicked()"),self.displayMatrix)
        #Boton para seleccionar P1 y T1 a partir de la altura:
        self.connect(self.Altura_Button,SIGNAL("clicked()"),self.seleccionAltura)

    def enable_PostCombustion(self):
        if self.PostCombustion.checkState():
            self.datoExtra_3.setEnabled(True)
            self.selecDatoExtra_3.setEnabled(True)
            self.theta1.setEnabled(True)
        else:
            self.datoExtra_3.setDisabled(True)
            self.selecDatoExtra_3.setDisabled(True)
            self.theta1.setDisabled(True)


    def selecionFormula(self):
        formula = self.formula_comboBox.currentText()
        if formula != 'Otra':
            self.formulaC.setText(str(self.formulas[formula]['c']))
            self.formulaH.setText(str(self.formulas[formula]['h']))
            self.formulaO.setText(str(self.formulas[formula]['o']))
            self.formulaS.setText(str(self.formulas[formula]['s']))
            self.actualizarFormula()

    def actualizarFormula(self):
        c = self.lecturadatos(self.formulaC,'int')
        h = self.lecturadatos(self.formulaH,'int')
        o = self.lecturadatos(self.formulaO,'int')
        s = self.lecturadatos(self.formulaS,'float')
        # si la formula ingresada coincide con alguna formula del comboBox
        # poner el comboBox en esa formula.
        indexName = 'Otra'
        for key in self.formulas.keys():
            if (self.formulas[key]['c'] == c) &  (self.formulas[key]['h'] == h) & (self.formulas[key]['o'] == o):
                indexName = key
        index = self.formula_comboBox.findText(indexName)
        self.formula_comboBox.setCurrentIndex(index)

        Fr = self.relacionMezcla.value()
        self.HVS, self.HVI, self.Q, self.lambda_s = PoderCalorifico.PoderCalorifico(c,h,o,s,Fr)
        self.HVS_lineEdit.setText('{:.1f}'.format(self.HVS))
        self.HVI_lineEdit.setText('{:.1f}'.format(self.HVI))
        self.calorQ.setText('{:.1f}'.format(self.Q))
        if self.selecDatoExtra_2.currentText().split("  ")[0] == 'Q':
            self.datoExtra_2.setText(str(self.Q))
            self.datoExtra_2.setReadOnly(True)
        else: self.datoExtra_2.setReadOnly(False)

    def seleccionAltura(self):
        p1 = str(self.presion1.text())
        t1 = str(self.temperatura1.text())
        dialogo = GUI_atmosfera_estandar.MainDialog(p1,t1)
        if dialogo.exec_():
            self.presion1.setText('{:.1f}'.format(dialogo.atmosfera['p']))
            self.temperatura1.setText('{:.1f}'.format(dialogo.atmosfera['t']))

    def lecturadatos(self,lineedit,type):
        try:
            aux = 0
            if type == 'int':
                aux = int(lineedit.text())
            if type == 'float':
                aux = float(lineedit.text())
            if aux < 0:
                raise NumeroNegativoError
            return aux
        except (TypeError, ValueError,NumeroNegativoError):
            QMessageBox.warning(self,"Error en los datos de entrada! ","Vuelva a ingresar los datos")
            lineedit.selectAll()
            lineedit.setFocus()
            raise

    # Genero ahora la función que va a realizar los calculos, es decir,
    # que va a llamar la función del ciclo.
    def Calculos(self):
        # Lectura de los datos de entrada con la función verificacion
        p1 = self.lecturadatos(self.presion1,'float')
        t1 = self.lecturadatos(self.temperatura1,'float')
        tb = self.lecturadatos(self.temperatura_base,'float')
        variableExtra1 = self.selecDatoExtra_1.currentText().split("  ")[0]
        datoExtra1 = self.lecturadatos(self.datoExtra_1,'float')
        variableExtra2 = self.selecDatoExtra_2.currentText().split("  ")[0]
        datoExtra2 = self.lecturadatos(self.datoExtra_2,'float')
        theta1 = self.lecturadatos(self.theta1,'float')
        variableExtra3 = self.selecDatoExtra_3.currentText().split()[0]
        datoExtra3 = self.lecturadatos(self.datoExtra_3,'float')
        try:
            #Procedo a calcular los parametros del ciclo, diferenciando entre el problema
            #con y sin post-combustión
            if self.PostCombustion.checkState()== Qt.CheckState.Checked:
                self.puntos, self.resultados = Ciclo_JouleBrayton.CicloJouleBraytonPostcombustion(p1,t1,tb,theta1,variableExtra1,datoExtra1,variableExtra2,datoExtra2,variableExtra3,datoExtra3)
            else:
                self.puntos, self.resultados = Ciclo_JouleBrayton.CicloJouleBraytonSimple(p1,t1,tb,variableExtra1,datoExtra1,variableExtra2,datoExtra2)

        except MayorAUnoError as e:
            QMessageBox.warning(self,"Error en los datos de entrada! ","La variable "+str(e.variableName)+" no puede ser menor a 1")
            if e.variableName == 'theta1':
                self.theta1.selectAll()
                self.theta1.setFocus()
            else:
                self.datoExtra_1.selectAll()
                self.datoExtra_1.setFocus()

        except TemperaturaIncompatibleError as e:
            QMessageBox.warning(self,"Error en los datos de entrada! ","La temperatura "+str(e.variableName)+" no puede ser menor a la "+
                                    "temepratura del estado anterior ("+str(e.value)+" K)")
            if e.variableName == 't3':
                self.datoExtra_2.selectAll()
                self.datoExtra_2.setFocus()
            else:
                self.datoExtra_3.selecAll()
                self.datoExtra_3.setFocus()

        else:
            #Grafico el resultado
            self.plotCiclo(self.puntos)

            # Muestro los resultados
            self.calor2.setText(str(self.resultados[1]))
            self.calorU.setText(str(self.resultados[2]))
            self.trabajoW.setText(str(self.resultados[3]))
            self.presionMedia.setText(str(self.resultados[4]))
            self.rendimiento.setText(str(self.resultados[5]))

            # En caso de que realice un calculo con "Temp. max" como parametro de
            #entrada, Q es resultado del calculo. Como la formula quimica del combustible
            # y por ende, su poder calorifico, no varian, debo cambiar la relación
            # de mezcla de entrada para que sea compatible con el nuevo calor calculado.
            self.Q = self.resultados[0]/1000
            if self.selecDatoExtra_2.currentText().split("  ")[0] == "Temp. max":
                self.calorQ.setText(str(self.Q))
                self.relacionMezcla.setValue(self.Q*self.lambda_s/self.HVI)

    def plotCiclo(self,puntos):
        presion = []
        temperatura = []
        densidad = []
        volumen = []
        entropia = []
        for punto in puntos:
            presion.append(punto[0])
            temperatura.append(punto[1])
            densidad.append(punto[2])
            volumen.append(punto[3])
            entropia.append(punto[4])

        v1 = np.append(np.arange(volumen[1],volumen[0],(volumen[0]-volumen[1])/100),volumen[0])
        v2 = np.append(np.arange(volumen[-2],volumen[-1],(volumen[-1]-volumen[-2])/100),volumen[-1])
        self.axes1.clear()
        self.axes1.plot(v1,presion[1]*volumen[1]**self.gamma_aire*(1/v1**self.gamma_aire),'r')
        self.axes1.plot(volumen[1:3],presion[1:3],'r')
        self.axes1.plot((volumen[0],volumen[-1]),(presion[0],presion[-1]),'r')
        self.axes1.plot(v2,presion[-2]*volumen[-2]**self.gamma_aire*(1/v2**self.gamma_aire),'r')
        if self.PostCombustion.checkState() == Qt.CheckState.Checked:
            self.axes1.plot((volumen[-3],volumen[-2]),(presion[-3],presion[-2]),'r')
            v3 = np.append(np.arange(volumen[2],volumen[3],(volumen[3]-volumen[2])/100),volumen[3])
            self.axes1.plot(v3,presion[2]*volumen[2]**self.gamma_aire*(1/v3**self.gamma_aire),'r')

        self.canvas1.draw()

        S1 = np.append(np.arange(entropia[1],entropia[2],(entropia[2]-entropia[1])/100),entropia[2])
        S2 = np.append(np.arange(entropia[0],entropia[-1],(entropia[-1]-entropia[0])/100),entropia[-1])

        self.axes2.clear()
        self.axes2.plot(entropia[0:2],temperatura[0:2],'r',entropia[-2::],temperatura[-2::],'r')
        self.axes2.plot(S1,temperatura[1]*np.exp((self.gamma_aire-1)*(S1-entropia[1])/(self.R_aire*self.gamma_aire)),'r')
        self.axes2.plot(S2,temperatura[0]*np.exp((self.gamma_aire-1)*(S2-entropia[0])/(self.R_aire*self.gamma_aire)),'r')
        if self.PostCombustion.checkState()==Qt.CheckState.Checked:
            S3 = np.append(np.arange(entropia[3],entropia[4],(entropia[4]-entropia[3])/100),entropia[4])
            self.axes2.plot(entropia[2:4],temperatura[2:4],'r')
            self.axes2.plot(S3,temperatura[3]*np.exp((self.gamma_aire-1)*(S3-entropia[3])/self.R_aire/self.gamma_aire),'r')
        self.canvas2.draw()


    def displayMatrix(self):
        matriz = MatrixDialog(self.puntos)
        matriz.exec_()
예제 #21
0
class mainWindow(QMainWindow):
    def __init__(self):
        super(mainWindow, self).__init__()

        self.full_filename_dict = {}  # {    full_filename:  group_name   }
        self.group_name_dict = {}  #group name dict, not necessary now?
        self.current_full_filename = None  #current selected full filename
        self.current_hdf5 = None  #open(  self.current_full_filename, r )
        self.current_hdf5_item = None
        self.current_group_name = None
        self.current_base_filename = ''  #current selected   base filename
        self.current_item_path = ''  #current item full path. /io/md/...
        self.current_item_name = ''  #current selected item name  md

        self.legend = None
        self.values = np.array([])
        self.logX_plot = False
        self.logY_plot = False

        self.X = None
        self.guiplot_count = 0
        self.testplot_count = 1
        self.image_plot_count = 0
        self.surface_plot_count = 0
        self.plot_type = 'curve'

        self.colormap_string = 'jet'
        self.colorscale_string = 'log'
        self.show_image_data = False
        self.rot_image_data = False
        self.attributes_flag = False
        self.current_selected_HDF = ''
        self.dataset_type_list = [
            'CFN',
            'LiX',
            'CHX',
        ]
        self.default_dataset_type = 'CFN'
        self.current_dataset_type = 'CFN'

        #########################Tobecleaned
        self.image_data_keys = [
            'avg_img', 'mask', 'pixel_mask', 'roi_mask', 'g12b'
        ]
        self.pds_keys = [
            'g2_fit_paras', 'g2b_fit_paras', 'spec_km_pds', 'spec_pds',
            'qr_1d_pds'
        ]
        #####################

        self.PWT = PlotWidget(self)
        self.MPWT = MATPlotWidget(self)
        self.initialise_user_interface()

        self.vstack_sampling = 20
        self.vstack_yshift = 10

    def initialise_user_interface(self):
        '''
        Initialises the main window. '''

        grid = QGridLayout()
        grid.setSpacing(10)
        self.grid = grid
        #self.file_items_list = ht.titledTree('File Tree')
        self.file_items_list = ht.tree()
        self.file_items_list_property = {}
        self.file_items_list.tree.itemClicked.connect(self.item_clicked)
        #self.file_items_list.tree.itemDoubleClicked.connect(self.item_double_clicked)
        self.guiplot_grid_fromRow = 5
        self.guiplot_grid_fromColumn = 1
        self.guiplot_grid_rowSpan = 5
        self.guiplot_grid_columnSpan = 8
        self.testplot_grid_fromRow = 6
        self.testplot_grid_fromColumn = 1
        self.testplot_grid_rowSpan = 4
        self.testplot_grid_columnSpan = 8
        self.plotLibrary = 'matplotlib'
        self.plot_buttons_array = []
        # Make dataset table
        self.dataset_table = ht.titledTable('Values')
        # Make attribute table
        self.attribute_table = ht.titledTable('Attribute')  # QTableWidget()
        self.attribute_table.table.setShowGrid(True)
        #dataset type to set buttons layout
        self.dataset_type_obj_string = self.default_dataset_type
        # Initialise all buttons
        self.open_button = self.add_open_button()
        self.remove_button = self.add_remove_button()
        self.create_button = self.add_create_button()
        self.dataset_type_box = self.add_dataset_type_box()
        self.add_all_plot_buttons()
        self.setX_button = self.add_setX_button()
        self.resetX_button = self.add_resetX_button()
        self.setlogX_box = self.add_setlogX_box()
        self.setlogY_box = self.add_setlogY_box()
        #self.clr_plot_checkbox = self.add_clr_plot_box()
        self.clr_plot_button = self.add_clr_plot_button()
        self.resizeEvent = self.onresize
        # Add 'extra' window components
        self.make_menu_bar()
        self.filename_label = QLabel('H5FileName')
        ## Add plot window
        self.guiplot = pg.PlotWidget()  ##using pg
        self.testplot = Figure()
        self.ax = self.testplot.add_subplot(111)
        self.canvas = FigureCanvas(self.testplot)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.cbWidget = None
        #self.guiplot = pg.ImageView()
        # Add the created layouts and widgets to the window
        grid.addLayout(self.open_button, 1, 0, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.remove_button, 6, 0, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.create_button, 7, 0, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.dataset_type_box, 1, 0, 1, 1, QtCore.Qt.AlignRight)
        grid.addLayout(self.clr_plot_button, 1, 4, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.setX_button, 1, 8, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.resetX_button, 2, 8, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.setlogX_box, 1, 7, 1, 1, QtCore.Qt.AlignLeft)
        grid.addLayout(self.setlogY_box, 2, 7, 1, 1, QtCore.Qt.AlignLeft)

        grid.addWidget(self.filename_label, 2, 0, 1, 1)
        #filename list
        #grid.addLayout(self.file_items_list.layout, 4, 0, 3, 1)
        grid.addLayout(self.file_items_list.datalayout, 4, 0, 2, 1)
        #data dataset table
        grid.addLayout(self.dataset_table.layout, 4, 1, 1, 8)
        # Add toolbar
        grid.addWidget(self.toolbar, 5, 1, 1, 7)
        ## Add guiplot window, it's not the default so hide
        grid.addWidget(self.guiplot, self.guiplot_grid_fromRow,
                       self.guiplot_grid_fromColumn, self.guiplot_grid_rowSpan,
                       self.guiplot_grid_columnSpan)
        self.guiplot.setWindowOpacity(0)
        self.guiplot.hide()
        grid.addWidget(self.canvas, self.testplot_grid_fromRow,
                       self.testplot_grid_fromColumn,
                       self.testplot_grid_rowSpan,
                       self.testplot_grid_columnSpan)
        # attribute tabel
        grid.addLayout(self.attribute_table.layout, 8, 0, 3, 1)
        #grid.addWidget(self.attribute_table, 7, 0, 2, 1 )
        self.dev_cur_layout(plot_type='curve')
        self.dev_cur_layout(plot_type='image')
        self.setCentralWidget(QWidget(self))
        self.centralWidget().setLayout(grid)
        # Other tweaks to the window such as icons etc
        self.setWindowTitle('XSH5View--Ver1')
        #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
        self.initialise_layout(
        )  #to add different type of layout based on self.dataset_type_obj_string

    ########Start Deal with layout
    def initialise_layout(self):
        if self.dataset_type_obj_string == 'CFN':
            self.delete_dataset_buttons('CHX')
            self.dev_dataset_buttons(self.dataset_type_obj_string)
        elif self.dataset_type_obj_string == 'LIX':
            self.delete_dataset_buttons('CHX')
        elif self.dataset_type_obj_string == 'CHX':
            self.dev_dataset_buttons(self.dataset_type_obj_string)
        else:
            pass

    def dev_cur_layout(self, plot_type):
        if plot_type in plot_curve_type:
            self.CurCrossHair = QLabel()
            self.CurCrossHair.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.grid.addWidget(self.CurCrossHair, 9, 2, 1, 1)
            self.CrossHair_type = 'curve'
        elif plot_type in plot_image_type:
            self.imageCrossHair = QLabel()
            self.imageCrossHair.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.grid.addWidget(self.imageCrossHair, 9, 1, 1, 1)
            self.CrossHair_type = 'image'
        else:
            self.CrossHair_type = 'None'

    def delete_cur_layout(self, plot_type):
        if plot_type in plot_curve_type:
            try:
                self.deleteLayout(self.imageCrossHair)
            except:
                pass
        elif plot_type in plot_image_type:
            try:
                self.deleteLayout(self.CurCrossHair)
            except:
                pass
        else:
            pass

    def dev_dataset_buttons(self, dataset_type):
        if dataset_type == 'CHX':
            self.plot_g2_button = self.add_plot_g2_button()
            self.plot_c12_button = self.add_plot_c12_button()
            self.q_box_input = self.add_q_box()
            self.plot_qiq_button = self.add_plot_qiq_button()
            self.grid.addLayout(self.plot_g2_button, 2, 1, 1, 1,
                                QtCore.Qt.AlignLeft)
            self.grid.addLayout(self.plot_c12_button, 2, 2, 1, 1,
                                QtCore.Qt.AlignLeft)
            self.grid.addLayout(self.plot_qiq_button, 2, 3, 1, 1,
                                QtCore.Qt.AlignLeft)
            self.grid.addLayout(self.q_box_input, 2, 6, 1, 1,
                                QtCore.Qt.AlignLeft)

        if dataset_type == 'CFN':
            self.rot_image_button = self.add_rot_image_button()
            self.grid.addLayout(self.rot_image_button, 2, 2, 1, 1,
                                QtCore.Qt.AlignLeft)
            self.stack_plot_button = self.add_stack_plot_button()
            self.grid.addLayout(self.stack_plot_button, 2, 1, 1, 1,
                                QtCore.Qt.AlignLeft)

    def add_rot_image_button(self):
        rot_image_button = QPushButton("rot image")
        rot_image_button.clicked.connect(self.rot_image)
        button_section = QHBoxLayout()
        button_section.addWidget(rot_image_button)
        return button_section

    def rot_image(self):
        #print('here')
        try:
            self.value = self.value.T
        except:
            pass

    def delete_dataset_buttons(self, dataset_type):
        if dataset_type == 'CHX' and self.current_dataset_type == 'CHX':
            self.deleteLayout(self.plot_g2_button)
            self.deleteLayout(self.plot_c12_button)
            self.deleteLayout(self.plot_qiq_button)
            self.deleteLayout(self.q_box_input)

    def deleteLayout(self, layout):
        for i in range(layout.count()):
            layout.itemAt(i).widget().close()

    ########End Deal with layout
    def onresize(self, event):
        #print('Here for resize')
        self.file_items_list.tree.setMaximumWidth(int(0.3 * self.width()))
        #self.dataset_table.table.setMinimumHeight(0.1*self.height())
        #self.dataset_table.table.setMaximumWidth( 0.3*self.height() )
        self.attribute_table.table.setMaximumWidth(int(0.3 * self.width()))
        #self.guiplot.setMinimumHeight( 0.6*self.height() )
        #self.guiplot.setMinimumHeight( 0.6*self.height() )
    def add_open_button(self):
        '''
        Initialises the buttons in the button bar at the top of the main window. '''
        open_file_btn = QPushButton('Open')
        open_file_btn.clicked.connect(self.choose_file)
        button_section = QHBoxLayout()
        button_section.addWidget(open_file_btn)
        #button_section.addStretch(0)
        return button_section

    def add_remove_button(self):
        remove_file_btn = QPushButton('Remove File')
        remove_file_btn.clicked.connect(self.remove_file)
        button_section = QHBoxLayout()
        button_section.addWidget(remove_file_btn)
        return button_section

    def add_create_button(self):
        create_file_btn = QPushButton('Create File')
        create_file_btn.clicked.connect(self.create_file)
        button_section = QHBoxLayout()
        button_section.addWidget(create_file_btn)
        return button_section

    def add_dataset_type_box(self):
        self.dataset_type_obj = QComboBox()
        self.dataset_type_obj.addItems(self.dataset_type_list)
        self.dataset_type_obj.currentIndexChanged.connect(
            self.dataset_type_selection_change)
        self.dataset_type_obj_string = self.dataset_type_obj.currentText()
        box_section = QHBoxLayout()
        box_section.addWidget(self.dataset_type_obj)
        return box_section

    def dataset_type_selection_change(self, i):
        self.dataset_type_obj_string = self.dataset_type_obj.currentText()
        self.initialise_layout()
        self.current_dataset_type = self.dataset_type_obj.currentText()
        #print( self.dataset_type_obj_string , self.dataset_type_obj.currentText() )

    def add_all_plot_buttons(self):
        self.plot_curve_button = self.add_plot_curve_button()
        self.plot_img_button = self.add_plot_img_button()
        if self.plotLibrary != 'matplotlib':
            self.plot_surface_button = self.add_plot_surface_button()
            self.grid.addLayout(self.plot_surface_button, 1, 3, 1, 1,
                                QtCore.Qt.AlignLeft)
        else:
            self.plot_acr_datasets_button = self.add_plot_acr_datasets_button()
            self.grid.addLayout(self.plot_acr_datasets_button, 2, 3, 1, 1,
                                QtCore.Qt.AlignLeft)
        self.grid.addLayout(self.plot_curve_button, 1, 1, 1, 1,
                            QtCore.Qt.AlignLeft)
        self.grid.addLayout(self.plot_img_button, 1, 2, 1, 1,
                            QtCore.Qt.AlignLeft)

    def add_stack_plot_button(self):
        return self.add_generic_plot_button(plot_type='plot_stack',
                                            button_name='Stack Plot')

    def add_plot_acr_datasets_button(self):
        return self.add_generic_plot_button(
            plot_type='stack_across', button_name='Stack Across Datasets')

    def add_plot_g2_button(self):
        return self.add_generic_plot_button(plot_type='g2',
                                            button_name='Plot_g2')

    def add_plot_c12_button(self):
        return self.add_generic_plot_button(plot_type='C12',
                                            button_name='Plot_TwoTime')

    def add_plot_curve_button(self):
        return self.add_generic_plot_button(plot_type='curve',
                                            button_name='Plot_Curve')

    def add_plot_qiq_button(self):
        return self.add_generic_plot_button(plot_type='qiq',
                                            button_name='Plot_qiq')

    def add_plot_img_button(self):
        return self.add_generic_plot_button(plot_type='image',
                                            button_name='Plot_Image')

    def add_plot_surface_button(self):
        return self.add_generic_plot_button(plot_type='surface',
                                            button_name='Plot_Surface')

    def add_generic_plot_button(self, plot_type, button_name):
        plot_btn = QPushButton(button_name)
        pg_plot_type_dict = {
            'curve': self.PWT.plot_curve,
            'g2': self.PWT.plot_g2,
            'qiq': self.PWT.plot_qiq,
            'surface': self.PWT.plot_surface,
            'image': self.PWT.plot_image,
            'C12': self.PWT.plot_C12,
            'plot_stack': self.PWT.plot_stack,
        }
        mat_plot_type_dict = {
            'curve': self.MPWT.plot_curve,
            'g2': self.PWT.plot_g2,
            'qiq': self.PWT.plot_qiq,
            'surface': self.MPWT.plot_surface,
            'image': self.MPWT.plot_image,
            'C12': self.PWT.plot_C12,
            'plot_stack': self.MPWT.plot_stack,
            'stack_across': self.MPWT.plot_across,
        }
        if self.plotLibrary == 'pyqtgraph':
            plot_btn.clicked.connect(pg_plot_type_dict[plot_type])
        if self.plotLibrary == 'matplotlib':
            plot_btn.clicked.connect(mat_plot_type_dict[plot_type])
        button_section = QHBoxLayout()
        button_section.addWidget(plot_btn)
        self.plot_buttons_array.append(plot_btn)
        return button_section

    def add_setlogX_box(self):
        self.setlogX_box_obj = QCheckBox("logX")
        self.setlogX_box_obj.stateChanged.connect(self.click_setlogX_box)
        button_section = QHBoxLayout()
        button_section.addWidget(self.setlogX_box_obj)
        return button_section

    def click_setlogX_box(self, state):
        if state == QtCore.Qt.Checked:
            self.logX_plot = True
        else:
            self.logX_plot = False
        try:
            self.guiplot.setLogMode(x=self.logX_plot, y=self.logY_plot)
        except:
            pass

    def add_setlogY_box(self):
        self.setlogY_box_obj = QCheckBox("logY")
        self.setlogY_box_obj.stateChanged.connect(self.click_setlogY_box)
        button_section = QHBoxLayout()
        button_section.addWidget(self.setlogY_box_obj)
        return button_section

    def click_setlogY_box(self, state):
        if state == QtCore.Qt.Checked:
            self.logY_plot = True
        else:
            self.logY_plot = False
        try:
            self.guiplot.setLogMode(x=self.logX_plot, y=self.logY_plot)
        except:
            pass

    def get_dict_from_qval_dict(self):
        l = list(self.current_hdf5['qval_dict'].attrs.items())
        dc = {int(i[0]): i[1] for i in l}
        return dc

    def add_setX_button(self):
        self.setX_btn = QPushButton('SetX')
        self.setX_btn.clicked.connect(self.setX)
        button_section = QHBoxLayout()
        button_section.addWidget(self.setX_btn)
        return button_section

    def add_resetX_button(self):
        self.resetX_btn = QPushButton('ReSetX')
        self.resetX_btn.clicked.connect(self.resetX)
        button_section = QHBoxLayout()
        button_section.addWidget(self.resetX_btn)
        return button_section

    def add_clr_plot_button(self):
        self.clr_plot_button = QPushButton("clear plot")
        self.clr_plot_button.clicked.connect(self.plot_clear)
        button_section = QHBoxLayout()
        button_section.addWidget(self.clr_plot_button)
        return button_section

    def plot_clear(self):
        if self.plotLibrary == 'matplotlib':
            if self.plot_type in plot_curve_type or self.plot_type in plot_image_type:
                if self.plot_type in plot_image_type:
                    self.grid.removeWidget(self.MPWT.cb)
                    self.MPWT.cb.setWindowOpacity(0)
                    self.MPWT.cb.hide()
                self.ax.clear()
                self.canvas.draw()
                self.canvas.hide()
                self.canvas.show()
                self.testplot_count = 0
        elif self.plotLibrary == 'pyqtgraph':
            self.guiplot.clear()
            #self.surface_plot_count = 0
            #self.grid.removeWidget(self.testplot)
            #self.guiplot.setWindowOpacity(0)
            #self.guiplot.hide()
        try:
            self.legend.scene().removeItem(self.legend)
        except:
            pass

    def add_q_box(self):
        # Create textbox
        self.q_box = QLineEdit(
            placeholderText="Please enter q-number (int) of two-time function."
        )
        button_section = QHBoxLayout()
        button_section.addWidget(self.q_box)
        return button_section

    def make_menu_bar(self):
        '''
        Initialises the menu bar at the top. '''
        menubar = self.menuBar()
        # Create a File menu and add an open button
        self.file_menu = menubar.addMenu('&File')
        open_action = QtGui.QAction('&Open', self)
        open_action.setShortcut('Ctrl+o')
        open_action.triggered.connect(self.choose_file)
        self.file_menu.addAction(open_action)
        # Add a shortcut to copy and paste data
        copy_data_action = QtGui.QAction('&Copy Data', self)
        copy_data_action.setShortcut('Ctrl+c')
        copy_data_action.triggered.connect(self.copy_data)
        self.file_menu.addAction(copy_data_action)
        paste_data_action = QtGui.QAction('&Paste Data', self)
        paste_data_action.setShortcut('Ctrl+v')
        paste_data_action.triggered.connect(self.paste_data)
        self.file_menu.addAction(paste_data_action)
        new_key_action = QtGui.QAction('&Add New Key', self)
        new_key_action.setShortcut('Ctrl+n')
        new_key_action.triggered.connect(self.create_key)
        self.file_menu.addAction(new_key_action)
        # Add an exit button to the file menu
        exit_action = QtGui.QAction('&Exit', self)
        exit_action.setShortcut('Ctrl+Z')
        exit_action.setStatusTip('Exit application')
        exit_action.triggered.connect(QtGui.qApp.quit)
        self.file_menu.addAction(exit_action)
        ## Create a view manu
        self.view_menu = menubar.addMenu('&View')
        #self.view_menu.setShortcut('Alt+v')
        self.plot_type_options_menu = self.view_menu.addMenu('&Plot Library')
        group = QActionGroup(self.plot_type_options_menu)
        texts = ["matplotlib", "pyqtgraph"]
        for text in texts:
            action = QAction(text,
                             self.plot_type_options_menu,
                             checkable=True,
                             checked=text == texts[0])
            self.plot_type_options_menu.addAction(action)
            group.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered_plotLibrary)

        self.image_plot_options_menu = self.view_menu.addMenu(
            '&Image Plot Options')
        self.colormap_options_menu = self.image_plot_options_menu.addMenu(
            '&Colormap')
        group = QActionGroup(self.colormap_options_menu)
        texts = image_colors
        for text in texts:
            action = QAction(text,
                             self.colormap_options_menu,
                             checkable=True,
                             checked=text == texts[0])
            self.colormap_options_menu.addAction(action)
            group.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered_colormap)
        self.colorscale_options_menu = self.image_plot_options_menu.addMenu(
            '&ColorScale')
        group = QActionGroup(self.colorscale_options_menu)
        texts = ["linear", "log"]
        for text in texts:
            action = QAction(text,
                             self.colormap_options_menu,
                             checkable=True,
                             checked=text == texts[1])
            self.colorscale_options_menu.addAction(action)
            group.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered_colorscale)
        self.display_image_data_options_menu = self.view_menu.addMenu(
            '&Display Image Data')
        show_image_data_action = QAction('show data',
                                         self,
                                         checkable=True,
                                         checked=False)
        show_image_data_action.triggered.connect(
            self.onTriggered_show_image_data)
        self.display_image_data_options_menu.addAction(show_image_data_action)

        self.stack_plot_options_menu = self.view_menu.addMenu(
            '&Stack Plot Options')
        set_stack_action = QtGui.QAction('Sampling and yshift', self)
        set_stack_action.triggered.connect(self.onTriggered_set_stack)
        self.stack_plot_options_menu.addAction(set_stack_action)

        # Create a Help menu and add an about button
        help_menu = menubar.addMenu('&Help')
        about_action = QtGui.QAction('About XSH5FView', self)
        about_action.setStatusTip('About this program')
        about_action.triggered.connect(self.show_about_menu)
        help_menu.addAction(about_action)

    def onTriggered_set_stack(self, action):
        print('set stack opt here.')
        i, okPressed = QInputDialog.getInt(self, "Set Sampling Number",
                                           "sampling:", self.vstack_sampling,
                                           0, 10000, 10)
        if okPressed:
            self.vstack_sampling = i
            print(i)
        d, okPressed = QInputDialog.getDouble(self, "Set yshift", "Value:",
                                              self.vstack_yshift, 0, 1e8, 2)
        if okPressed:
            self.vstack_yshift = d
            print(d)

    def onTriggered_show_image_data(self, action):
        #print(action.text())
        self.show_image_data = action  #.text()

    def onTriggered_colormap(self, action):
        #print(action.text())
        self.colormap_string = action.text()

    def onTriggered_colorscale(self, action):
        #print(action.text())
        self.colorscale_string = action.text()

    def onTriggered_plotLibrary(self, action):
        self.plotLibrary = action.text()
        for i in range(len(self.plot_buttons_array)):
            button_to_remove = self.plot_buttons_array.pop()
            self.grid.removeWidget(button_to_remove)
            button_to_remove.setWindowOpacity(0)
            button_to_remove.hide()
        if action.text() == 'matplotlib':
            self.toolbar.setWindowOpacity(100)
            self.toolbar.show()
            self.canvas.setWindowOpacity(100)
            self.canvas.show()
        else:
            self.toolbar.setWindowOpacity(0)
            self.toolbar.hide()
            self.canvas.setWindowOpacity(0)
            self.canvas.hide()
        if action.text() == 'pyqtgraph':
            self.guiplot.setWindowOpacity(100)
            self.guiplot.show()
        else:
            self.guiplot.setWindowOpacity(0)
            self.guiplot.hide()
        self.add_all_plot_buttons()
        self.initialise_layout()

    def show_about_menu(self):
        '''
        Shows the about menu by initialising an about_window object. This class is described in _window_classes.py '''
        self.about_window = ht.aboutWindow()
        self.about_window.show()

    def choose_file(self):
        '''
        Opens a QFileDialog window to allow the user to choose the hdf5 file they would like to view. '''
        filenames_list = QtGui.QFileDialog.getOpenFileNames(
            self,
            'Open file',
            '/home/yugang/Desktop/XPCS_GUI/TestData/test.h5',
            filter='*.hdf5 *.h5 *.lst')[0]
        for f in filenames_list:
            ext = f.split('/')[-1].split('.')[-1]
            if ext == 'lst':
                full_filename_list = np.loadtxt(
                    f,
                    dtype=object,
                )
                group_name = f.split('/')[-1]
                if group_name not in list(self.group_name_dict.keys()):
                    self.group_name_dict[group_name] = full_filename_list
                for fp in full_filename_list:
                    self.initiate_file_open(fp, group_name=group_name)
            else:
                self.initiate_file_open(f)

    def initiate_file_open(self, full_filename, group_name=None):
        base_filename = full_filename.split('/')[-1]
        self.full_filename_dict[full_filename] = group_name
        self.dataset_table.clear()
        self.attribute_table.clear()
        try:
            self.file_items_list.add_file(full_filename, group_name)
            if group_name is None:
                self.filename_label.setText(base_filename)
            else:
                self.filename_label.setText(group_name)
            self.setWindowTitle('XSH5View@CHX - ' + base_filename)
        except:
            self.filename = ''  # if it didn't work keep the old value
            self.filename_label.setText('')
            self.setWindowTitle('XSH5View@CHX')
            self.clear_file_items()
            self.dataset_table.clear()
            self.attribute_table.clear()
            print("Error opening file")

    def create_file(self):
        filename = self.file_items_list.create_file()
        self.initiate_file_open(filename)

    def remove_file(self, filename):
        self.file_items_list.remove_file()

    def clear_file_items(self):
        self.file_items_list.clear()

    def copy_data(self):
        self.file_items_list.copy_data()

    def paste_data(self):
        destination = self.file_items_list.tree.currentItem().text(1)
        item_path = self.file_items_list.tree.currentItem().text(2)
        #self.file_items_list.remove_file()
        self.file_items_list.paste_data(destination, item_path, self)
        #self.initiate_file_open(destination)

    def create_key(self):
        item = self.file_items_list.tree.currentItem()
        self.file_items_list.create_key(item.text(1), item.text(2), self)

    def get_selected_row_col(self):
        selected_items = self.dataset_table.table.selectedItems()
        shape = np.shape(self.value)
        Ns = len(shape)
        if len(selected_items) > 0:
            min_row = selected_items[0].row()
            max_row = selected_items[-1].row() + 1
            min_col = selected_items[0].column()
            max_col = selected_items[-1].column() + 1
            self.selected_flag = True
        else:
            if len(shape) == 1:
                max_col = 1
            else:
                max_col = shape[1]
            min_row = 0
            max_row = shape[0]
            min_col = 0
            self.selected_flag = False
        self.min_row, self.max_row, self.min_col, self.max_col = min_row, max_row, min_col, max_col

    def setX(self):
        self.get_selected_row_col()
        min_row, max_row, min_col, max_col = self.min_row, self.max_row, self.min_col, self.max_col
        if self.selected_flag:
            try:
                self.X = self.value[min_row:max_row, min_col]
            except:
                self.X = self.value[min_row:max_row]

    def resetX(self):
        self.X = None

    def get_filename_selected(self):
        self.dataset_table.clear()
        self.item = self.file_items_list.tree.currentItem()
        self.current_full_filename = self.item.text(1)
        self.current_group_name = self.full_filename_dict[
            self.current_full_filename]
        #print("in get filename selected:", self.current_full_filename)
        self.current_hdf5 = h5py.File(self.current_full_filename, 'r')
        self.current_base_filename = self.current_full_filename.split('/')[-1]
        self.current_item_path = self.item.text(2)
        if self.current_item_path == '':
            self.current_hdf5_item = self.current_hdf5
            self.current_item_name = self.item.text(2)
        else:
            self.current_hdf5_item = self.current_hdf5[self.current_item_path]
            self.current_item_name = self.item.text(2).split('/')[-1]

    def display_dataset(self):
        self.get_filename_selected()
        text = self.current_item_path  #self.item.text(2)
        if self.current_item_path != '':
            hdf5_file = self.current_hdf5_item
            if isinstance(hdf5_file, h5py.Dataset):
                #print( 'shows dataset-------------->')
                self.group_data = False
                #self.current_dataset = self.item_path.split('/')[-1]
                shape = hdf5_file.shape
                Ns = len(shape)
                if Ns == 0:
                    try:
                        self.value = bstring_to_string(hdf5_file)  #[0]
                    except:
                        self.value = np.array([hdf5_file])  #[0]
                    numrows = 1
                    numcols = 1
                elif Ns == 1:
                    numrows = shape[0]
                    numcols = 1
                    self.value = hdf5_file[:]
                elif Ns == 2:
                    numrows = shape[0]
                    numcols = shape[1]
                    self.value = hdf5_file[:]
                elif Ns >= 3:  #a 3D array, [x,y,z], show [x,y ]
                    if self.current_dataset_type == 'CHX':
                        numrows = shape[0]
                        numcols = shape[1]
                        try:
                            self.value = hdf5_file[:, :, self.qth]
                        except:
                            print('The max q-th is %s.' % shape[2])
                            self.value = hdf5_file[text][:, :, 0]
                    else:
                        numrows = shape[-2]
                        numcols = shape[-1]
                        try:
                            self.value = hdf5_file[self.qth, :, :]
                        except:
                            print('The max q-th is %s.' % shape[0])

            elif isinstance(hdf5_file, h5py.Group):
                print('display the group data here')
                if text in self.pds_keys:
                    d = pds.read_hdf(self.filename, key=text)  #[:]
                    self.value = np.array(d)
                    shape = self.value.shape
                    numrows = shape[0]
                    numcols = shape[1]
                    Ns = len(shape)
                    self.group_data_label = np.array(d.columns)[:]
                    self.group_data = True
                else:
                    self.dataset_table.clear()
                    self.value = np.array([])
                    self.plot_btn.hide()
            else:
                print('Other format!')
            try:
                self.dataset_table.table.setRowCount(numrows)
                self.dataset_table.table.setColumnCount(numcols)
                show_data_flag = True
                if not self.show_image_data:
                    if text in self.image_data_keys:
                        self.dataset_table.clear()
                        show_data_flag = False
                    try:
                        if self.value.shape[0] > 100 and self.value.shape[
                                1] > 100:
                            show_data_flag = False
                    except:
                        pass
                if show_data_flag:
                    if Ns != -1:
                        for i in range(numrows):
                            if numcols > 1:
                                for j in range(numcols):
                                    self.dataset_table.set_item(
                                        i, j, str(self.value[i, j]))
                            else:
                                self.dataset_table.set_item(
                                    i, 0, str(self.value[i]))
                #print( self.attributes_flag  )
                if not self.attributes_flag:
                    self.attribute_table.clear()
                    self.attribute_table.table.setRowCount(1)
                    self.attribute_table.table.setColumnCount(Ns + 1)
                    self.attribute_table.table.setItem(
                        0, 0, QTableWidgetItem('shape'))
                    for i, s in enumerate(shape):
                        self.attribute_table.table.setItem(
                            0, i + 1, QTableWidgetItem('%s' % s))
            except:
                pass
        self.current_hdf5.close()

    def display_attributes(self):
        # reset the value
        self.attribute_table.clear()
        self.get_filename_selected()
        if self.current_item_path != '':
            #print('Here shows the attributes')
            hdf5_file = self.current_hdf5_item
            try:
                attributes = list(hdf5_file.attrs.items())
                num_attributes = len(attributes)
                self.attribute_table.table.setRowCount(num_attributes)
                self.attribute_table.table.setColumnCount(0)
            except:
                num_attributes = 0

            if num_attributes > 0:
                self.attribute_table.table.setColumnCount(2)
                self.attributes_flag = True
            else:
                self.attributes_flag = False
            print(num_attributes, self.attributes_flag)
            # Populate the table
            for i in range(num_attributes):
                value = attributes[i][1]
                self.attribute_table.table.setItem(
                    i, 0, QTableWidgetItem(attributes[i][0]))
                if isinstance(value, np.ndarray):
                    N = len(value)
                    self.attribute_table.table.setColumnCount(N + 1)
                    j = 1
                    for v in value:
                        self.attribute_table.table.setItem(
                            i, j, QTableWidgetItem(str(v)))
                        #self.attribute_table.setItem(i, 1, QTableWidgetItem(str(value[0].decode())))
                        j += 1
                else:
                    self.attribute_table.table.setItem(
                        i, 1, QTableWidgetItem(str(value)))
        self.current_hdf5.close()

    def item_double_clicked(self):
        '''
        Responds to a double click on an item in the file_items_list.'''

        #self.display_attributes()
        try:
            self.display_attributes()
            #print('display attributes')
        except:
            pass

    def item_clicked(self):

        #############
        #self.display_dataset()
        #################3

        try:
            self.qth = int(self.q_box.text())
        except:
            self.qth = 0
        try:
            self.display_attributes()
            #print('display attributes')
        except:
            pass
        try:
            self.display_dataset()
        except:
            pass
        try:

            self.filename_label.setText(self.current_base_filename)
            self.setWindowTitle('XSH5View@CHX - ' + self.current_full_filename)
        except:
            pass
예제 #22
0
class GraphView(QtGui.QWidget):
    def __init__(self, pymol, pmap, parent=None):
        super(GraphView, self).__init__(parent)
        self.pymol = pymol
        self.dpi = 300
        self.pmap = pmap
        self.fig = Figure((4.5, 4.5), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.mpl_connect('button_press_event', self._onpick)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        if self.pmap.use_ca:
            self.xcoor = self.pmap.residue_numbers_ca[
                self.pmap.parent.current_model]
        else:
            self.xcoor = self.pmap.residue_numbers_cb[
                self.pmap.parent.current_model]
        self.ycoor = self.pmap.histogram_maps[self.pmap.parent.current_model]
        self.bar = self.axes.bar(self.xcoor,
                                 self.ycoor,
                                 width=1.0,
                                 linewidth=0)
        self.canvas.show()
        self.set_parameters()

    def _get_clicked_residues(self, event):
        xmin, xmax = self.axes.get_xlim()
        return (int(math.ceil(event.xdata - xmin)) - 1)

    def _onpick(self, event):
        if self.pmap.use_ca:
            atom = 'CA'
            chains = self.pmap.chain_names_ca[self.pmap.parent.current_model]
            residue_numbers = self.pmap.residue_numbers_ca[
                self.pmap.parent.current_model]
        else:
            atom = 'CB'
            chains = self.pmap.chain_names_cb[self.pmap.parent.current_model]
            residue_numbers = self.pmap.residue_numbers_cb[
                self.pmap.parent.current_model]

        index = self._get_clicked_residues(event)
        self.pymol.select_density(residue_numbers[index], atom,
                                  self.pmap.cutoff, chains[index])

    def set_parameters(self):
        self.axes.tick_params(axis=u'both', which=u'both', length=0)
        self.axes.set_xlim(min(self.xcoor), max(self.xcoor))
        self.axes.set_ylim(0, max(self.ycoor) + 1)
        self.axes.set_xlabel('Residue Number')
        self.axes.set_ylabel('Contact Counts')
        fractions = self.ycoor / max(self.ycoor)
        normalized_colors = colors.Normalize(fractions.min(), fractions.max())
        count = 0
        for rect in self.bar:
            c = cm.jet(normalized_colors(fractions[count]))
            rect.set_facecolor(c)
            count += 1
        self.fig.patch.set_facecolor((0.886, 0.886, 0.886))
        ticks_font = mpl.font_manager.FontProperties(family='times new roman',
                                                     style='normal',
                                                     size=12,
                                                     weight='normal',
                                                     stretch='normal')
        labels = [
            self.axes.title, self.axes.xaxis.label, self.axes.yaxis.label
        ]
        labels += self.axes.get_xticklabels() + self.axes.get_yticklabels()
        for item in labels:
            item.set_fontproperties(ticks_font)
            item.set_fontsize(4)

    def update_graph(self):
        self.axes.clear()
        if self.pmap.use_ca:
            self.xcoor = self.pmap.residue_numbers_ca[
                self.pmap.parent.current_model]
        else:
            self.xcoor = self.pmap.residue_numbers_cb[
                self.pmap.parent.current_model]
        self.ycoor = self.pmap.histogram_maps[self.pmap.parent.current_model]
        self.bar = self.axes.bar(self.xcoor,
                                 self.ycoor,
                                 width=1.0,
                                 linewidth=0)
        self.set_parameters()
        self.canvas.draw()
예제 #23
0
class GraphView(QtGui.QWidget):
    def __init__(self, filename, parent=None):
        super(GraphView, self).__init__(parent)
        self.dpi = 300
        self.filename = filename
        self.data = None
        self.fig = Figure((4.5, 4.5), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.mpl_connect('button_press_event', self._onpick)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.x = []
        self.y = []
        self.read_data()
        self.load_data()
        self.canvas.show()
        self.set_parameters()

    def read_data(self):
        fh = open(self.filename)
        for line in fh.readlines():
            if not re.match(r'[A-Za-z]', line):
                values = line.strip().split(',')
                try:
                    self.x.append(float(values[0]))
                    self.y.append(float(values[2]))
                except:
                    pass
        self.x = np.array(self.x)
        self.y = np.array(self.y)

    def load_data(self):
        self.bar = self.axes.plot(self.x, self.y, linewidth=1.0)

    def _get_clicked_residues(self, event):
        xmin, xmax = self.axes.get_xlim()
        return(int(math.ceil(event.xdata - xmin))-1)

    def _onpick(self, event):
        pass

    def set_parameters(self):
        self.axes.tick_params(axis=u'both', which=u'both', length=0)
        self.axes.set_xlim(min(self.x), max(self.x))
        self.axes.set_ylim(0, max(self.y) + 1)
        self.axes.set_xlabel('Threshold')
        self.axes.set_ylabel('Overdispersion')
        # fractions = self.y / max(self.y)
        # normalized_colors = colors.Normalize(fractions.min(), fractions.max())
        # count = 0
        # for rect in self.bar:
        #     c = cm.jet(normalized_colors(fractions[count]))
        #     rect.set_facecolor(c)
        #     count += 1
        # self.fig.patch.set_facecolor((0.886, 0.886, 0.886))
        ticks_font = mpl.font_manager.FontProperties(family='times new roman', style='normal', size=12,
                                                     weight='normal', stretch='normal')
        labels = [self.axes.title, self.axes.xaxis.label, self.axes.yaxis.label]
        labels += self.axes.get_xticklabels() + self.axes.get_yticklabels()
        for item in labels:
            item.set_fontproperties(ticks_font)
            item.set_fontsize(4)
        self.fig.set_size_inches(30, self.fig.get_figheight(), forward=True)
예제 #24
0
class BottleWindow(QtGui.QWidget):
    "Document window for displaying a particular bottle"

    def __init__(self, bottle):
        super(BottleWindow, self).__init__(None)
        self.ui = uic.loadUi(get_ui_file('bottle_window.ui'), self)
        self.ui.readings_view.setModel(
            BottleModel(DataAnalyzer(bottle, delta=True)))
        for col in range(self.ui.readings_view.model().columnCount()):
            self.ui.readings_view.resizeColumnToContents(col)
        self.exporter = BottleExporter(self)
        if matplotlib:
            self.figure = Figure(figsize=(5.0, 5.0),
                                 facecolor='w',
                                 edgecolor='w')
            self.canvas = FigureCanvas(self.figure)
            self.axes = self.figure.add_subplot(111)
            self.ui.splitter.addWidget(self.canvas)
            self.redraw_timer = QtCore.QTimer()
            self.redraw_timer.setInterval(200)  # msecs
            self.redraw_timer.timeout.connect(self.redraw_timeout)
            self.ui.splitter.splitterMoved.connect(self.splitter_moved)
        self.refresh_edits()
        self.setWindowTitle('Bottle %s' % bottle.serial)
        self.ui.absolute_check.toggled.connect(self.absolute_toggled)
        self.ui.points_spin.valueChanged.connect(self.points_changed)

    @property
    def model(self):
        return self.ui.readings_view.model()

    @property
    def bottle(self):
        return self.model.analyzer.bottle

    def refresh_window(self):
        "Forces the list to be re-read from the data logger"
        self.model.beginResetModel()
        self.model.analyzer.refresh()
        self.refresh_edits()
        self.model.endResetModel()

    def refresh_edits(self):
        "Refresh all the edit controls from the bottle"
        bottle = self.model.analyzer.bottle
        self.ui.bottle_serial_edit.setText(bottle.serial)
        self.ui.bottle_id_edit.setText(str(bottle.id))
        self.ui.measurement_mode_edit.setText(bottle.mode_string)
        self.ui.bottle_volume_spin.setValue(bottle.bottle_volume)
        self.ui.sample_volume_spin.setValue(bottle.sample_volume)
        self.ui.dilution_spin.setValue(bottle.dilution)
        self.ui.start_timestamp_edit.setText(bottle.start.strftime('%c'))
        self.ui.finish_timestamp_edit.setText(bottle.finish.strftime('%c'))
        self.ui.measurement_complete_edit.setText(bottle.completed)
        self.ui.desired_values_edit.setText(str(bottle.expected_measurements))
        self.ui.actual_values_edit.setText(str(bottle.actual_measurements))
        self.ui.points_spin.setMaximum(
            max(
                1, bottle.actual_measurements -
                (1 if bottle.actual_measurements % 2 == 0 else 0)))
        self.ui.points_spin.setEnabled(bottle.actual_measurements > 1)
        self.ui.absolute_check.setEnabled(bottle.actual_measurements > 1)
        if bottle.actual_measurements > 1:
            self.canvas.show()
            self.invalidate_graph()
        else:
            self.canvas.hide()

    def export_file(self):
        "Export the readings to a user-specified filename"
        self.exporter.export_file()

    def absolute_toggled(self, checked):
        "Handler for the toggled signal of the absolute_check control"
        self.model.delta = not checked
        if matplotlib:
            self.invalidate_graph()

    def points_changed(self, value):
        "Handler for the valueChanged signal of the points_spin control"
        self.model.points = value
        if matplotlib:
            self.invalidate_graph()

    def splitter_moved(self, pos, index):
        "Handler for the moved signal of the splitter control"
        self.invalidate_graph()

    def invalidate_graph(self):
        "Invalidate the matplotlib graph on a timer"
        if self.redraw_timer.isActive():
            self.redraw_timer.stop()
        self.redraw_timer.start()

    def redraw_timeout(self):
        "Handler for the redraw_timer's timeout event"
        self.redraw_timer.stop()
        self.redraw_figure()

    def redraw_figure(self):
        "Called to redraw the channel image"
        # Configure the x and y axes appearance
        self.axes.clear()
        self.axes.set_frame_on(True)
        self.axes.set_axis_on()
        self.axes.grid(True)
        self.axes.set_xlabel(self.tr('Time'))
        if self.ui.absolute_check.isChecked():
            self.axes.set_ylabel(self.tr('Pressure (hPa)'))
        else:
            self.axes.set_ylabel(self.tr('Delta Pressure (hPa)'))
        m = self.ui.points_spin.value()
        for head_ix, head in enumerate(self.model.analyzer.heads):
            self.axes.plot_date(
                x=self.model.analyzer.timestamps,
                y=head,
                fmt='%s-' %
                matplotlib.rcParams['axes.color_cycle'][head_ix % len(
                    matplotlib.rcParams['axes.color_cycle'])])
        self.axes.xaxis.set_major_formatter(DateFormatter('%d %b'))
        self.axes.autoscale_view()
        self.canvas.draw()
예제 #25
0
class PointsView(QtGui.QDialog, Ui_PointsView):
    """
    Window for exploring and delating points
    """
    def __init__(self, reac_data, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle("Points view")
        self.reac_data = deepcopy(reac_data)
        self.axes = None
        self.axes2 = None
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
        self.verticalLayout_3.addWidget(self.canvas)
        self.verticalLayout_3.addWidget(self.mpl_toolbar)

        # SS init
        if self.reac_data.is_single():
            self.label.hide()
            self.label_2.hide()
            self.VarBox.hide()
            self.SetBox.hide()
            self.qbox_level3()
        # DS init
        else:
            self.qbox_level1()

        # make change
        self.VarBox.activated.connect(self.qbox_level1)
        self.SetBox.activated.connect(self.qbox_level2)
        self.RepBox.activated.connect(self.qbox_level3)
        self.DelBut.clicked.connect(self.delete_points)

    def select_rep(self):
        """
        Returns you rep which should be bold
        """
        sel_set = self.SetBox.currentIndex()
        varsub = self.VarBox.currentIndex() == 0
        return [sel_set if varsub else -2, sel_set if not varsub else -2]

    def draw_plots(self):
        """
        Draw or re-draw plots
        """
        self.fig.clear()
        if self.reac_data.is_single():
            self.axes = self.fig.add_subplot(111)
            # Graph plot
            reaction_plots.plot_singlegraph(self.reac_data, self.axes, 0, pick=self.RepBox.currentIndex())
            self.canvas.draw()
            self.canvas.show()

        else:
            self.axes = self.fig.add_subplot(121)
            self.axes2 = self.fig.add_subplot(122)

            picks = self.select_rep()
            reaction_plots.plot_singlegraph(self.reac_data.get_repres(True), self.axes, 0, pick=picks[0], alpha1=0.75)
            reaction_plots.plot_singlegraph(self.reac_data.get_repres(False), self.axes2, 0, pick=picks[1], alpha1=0.75)

            # enhance single point
            sub_group = True if self.VarBox.currentIndex() == 0 else False
            plot_obj = self.axes if sub_group else self.axes2
            dat_set = self.SetBox.currentIndex()
            dat_rep = self.RepBox.currentIndex()
            # plot if possible
            try:
                plot_obj.plot(self.reac_data.AllVar[sub_group][dat_set][dat_rep],
                              self.reac_data.AllRates[sub_group][dat_set][dat_rep], 'o', color='red')
            except IndexError:
                pass
            self.canvas.draw()
            self.canvas.show()

    def qbox_level1(self):
        """
        Display changes stage 1
        """
        idx = self.VarBox.currentIndex()
        idx = 0 if idx == -1 else idx
        self.VarBox.clear()
        self.VarBox.addItems([self.reac_data.nameA, self.reac_data.nameB])
        self.VarBox.setCurrentIndex(idx)
        self.qbox_level2()

    def qbox_level2(self):
        """
        Display changes stage 2
        """
        idx = self.SetBox.currentIndex()
        idx = 0 if idx == -1 else idx
        self.SetBox.clear()
        subs_sel = True if self.VarBox.currentIndex() == 0 else False
        self.SetBox.addItems(['Set {}'.format(i + 1) for i in range(len(self.reac_data.AllVar[subs_sel]))])
        self.SetBox.setCurrentIndex(idx if idx < len(self.SetBox) else 0)
        self.qbox_level3()

    def qbox_level3(self):
        """
        Display changes stage 3
        """
        idx = self.RepBox.currentIndex()
        idx = 0 if idx == -1 else idx
        self.RepBox.clear()
        if self.reac_data.is_single():
            self.RepBox.addItems(['Replicate {}'.format(i + 1) for i in range(self.reac_data.replicates)])
            self.RepBox.setCurrentIndex(idx if idx < len(self.RepBox) else 0)
        else:
            subs_sel = True if self.VarBox.currentIndex() == 0 else False
            sub_set = self.SetBox.currentIndex()
            try:
                self.RepBox.addItems(['Replicate {}'.format(i + 1) for i in range(len(
                    self.reac_data.AllVar[subs_sel][sub_set]))])
                self.RepBox.setCurrentIndex(idx if idx < len(self.RepBox) else 0)
            except:
                WarningMessage('You have no replicates for selected substrate')
        self.draw_plots()

    def delete_points(self):
        """
        Deletes replicate points
        """
        # SS delete
        if self.reac_data.is_single():
            if self.reac_data.replicates > 0:
                posit = self.RepBox.currentIndex()
                self.reac_data.rates.pop(posit)
                self.reac_data.concentrations.pop(posit)
                self.reac_data.replicates -= 1
                self.qbox_level3()
            else:
                WarningMessage("No points to delete")
        # DS delete
        else:
            subs_sel = True if self.VarBox.currentIndex() == 0 else False
            set_pos = self.SetBox.currentIndex()
            rep_pos = self.RepBox.currentIndex()

            self.reac_data.AllVar[subs_sel][set_pos].pop(rep_pos)
            self.reac_data.AllRates[subs_sel][set_pos].pop(rep_pos)
            self.reac_data.AllConst[subs_sel][set_pos].pop(rep_pos)
            if not self.reac_data.AllVar[subs_sel][set_pos]:
                self.reac_data.AllVar[subs_sel].pop(set_pos)
                self.reac_data.AllRates[subs_sel].pop(set_pos)
                self.reac_data.AllConst[subs_sel].pop(set_pos)
            self.qbox_level1()
예제 #26
0
class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        QtCore.pyqtRemoveInputHook()
        self.mutex = QtCore.QMutex()
        self.initUI()

    def initUI(self):

        #### MSP CONNECTION CONFIG #########################
        self.mspConfigPortBox = QtGui.QLineEdit(self)
        if sys.platform == "win32":
            self.mspConfigPortBox.setText("COM1")
        else:
            self.mspConfigPortBox.setText("/dev/ttyUSB0")
        self.mspConfigBaudBox = QtGui.QLineEdit(self)
        self.mspConfigBaudBox.setText("9600")

        #### MSP COMMAND STUFF #############################
        self.btnMspConnect = QtGui.QPushButton("CONNECT")
        self.btnMspConnect.clicked.connect(self.mspConnect)

        self.btnSendCommand = QtGui.QPushButton("SEND")
        self.btnSendCommand.clicked.connect(self.mspSend)

        self.commandBox = QtGui.QLineEdit(self)
        self.commandBox.setText("CMD?")

        #### CURVE TRACE APP MAIN LAYOUT ###################
        vbox = QtGui.QVBoxLayout()

        #### CURVE TRACE APP CONNECTION ####################
        self.mspConnectGroup = QtGui.QGroupBox("Connection")
        self.mspConnectGroup.setFlat(False)
        # btnTest = QtGui.QPushButton("TEST")
        # btnTest.clicked.connect(self.tester)
        # btnTest.clicked.connect(self.sweepVoltageAction)
        gridConnect = QtGui.QGridLayout()
        gridConnect.addWidget(self.mspConfigPortBox, 0, 0)
        gridConnect.addWidget(self.mspConfigBaudBox, 0, 1)
        gridConnect.addWidget(self.btnMspConnect, 0, 2)

        self.mspConnectGroup.setLayout(gridConnect)

        #### CURVE TRACE APP COMMANDS ######################
        mspCommandGroup = QtGui.QGroupBox("Send Manual Command")
        mspCommandGroup.setFlat(False)
        gridCommand = QtGui.QGridLayout()
        gridCommand.addWidget(self.commandBox, 0, 0, 0, 1)
        gridCommand.addWidget(self.btnSendCommand, 0, 2)
        mspCommandGroup.setLayout(gridCommand)

        #### SWEEPER GROUP #################################
        self.groupSweeper = QtGui.QGroupBox("Sweeper Settings")
        gridSweeper = QtGui.QGridLayout()

        sweepVoltageMinLabel = QtGui.QLabel("Min Voltage (mV)")
        self.sweepVoltageMin = QtGui.QLineEdit(self)
        self.sweepVoltageMin.setMinimumWidth(50)
        self.sweepVoltageMin.setText("-1000")
        # self.sweepVoltageMin.setAlignment(QtCore.Qt.AlignCenter)

        sweepVoltageMaxLabel = QtGui.QLabel("Max Voltage (mV)")
        self.sweepVoltageMax = QtGui.QLineEdit(self)
        self.sweepVoltageMax.setText("1000")
        self.sweepVoltageMax.setMinimumWidth(50)

        sweepVoltageIncrLabel = QtGui.QLabel("Step Size (mV)")
        self.sweepVoltageIncr = QtGui.QLineEdit(self)
        self.sweepVoltageIncr.setText("10")
        self.sweepVoltageIncr.setMinimumWidth(40)

        self.btnSweepCommand = QtGui.QPushButton("SWEEP")
        self.btnSweepCommand.clicked.connect(self.sweepVoltageAction)
        self.btnSweepCommand.setFixedWidth(60)

        self.sweepSampleRateLabel = QtGui.QLabel("Sample Rate (x_)")
        self.sweepSampleRate = QtGui.QLineEdit(self)
        self.sweepSampleRate.setText("2")
        self.sweepSampleRate.setFixedWidth(60)

        self.vcc5VoltageLabel = QtGui.QLabel("5V Value (V)")
        self.vcc5Voltage = QtGui.QLineEdit(self)
        self.vcc5Voltage.setText("5.00")
        self.vcc5Voltage.setFixedWidth(50)

        self.vcc3VoltageLabel = QtGui.QLabel("3.3V Value (V)")
        self.vcc3Voltage = QtGui.QLineEdit(self)
        self.vcc3Voltage.setText("3.30")
        self.vcc3Voltage.setFixedWidth(50)

        self.currentGainLabel = QtGui.QLabel("Shunt Resistor Gain")
        self.currentGain = QtGui.QLineEdit(self)
        self.currentGain.setText("-50")
        self.currentGain.setFixedWidth(50)

        self.btnExportLog = QtGui.QPushButton("Export")
        self.btnExportLog.clicked.connect(self.btnExportLogAction)
        self.btnExportLog.setFixedWidth(60)
        self.btnExportLog.setEnabled(False)  # Cannot export log without a run

        # self.tempCheck = QtGui.QCheckBox()
        # self.tempCheckLabel = QtGui.QLabel("Temperature?")
        gridSweeper.addWidget(sweepVoltageMaxLabel, 0, 0)
        gridSweeper.addWidget(self.sweepVoltageMax, 0, 1)
        gridSweeper.addWidget(sweepVoltageMinLabel, 1, 0)
        gridSweeper.addWidget(self.sweepVoltageMin, 1, 1)
        gridSweeper.addWidget(self.vcc5VoltageLabel, 2, 0)
        gridSweeper.addWidget(self.vcc5Voltage, 2, 1)
        gridSweeper.addWidget(self.vcc3VoltageLabel, 3, 0)
        gridSweeper.addWidget(self.vcc3Voltage, 3, 1)
        gridSweeper.addWidget(self.currentGainLabel, 4, 0)
        gridSweeper.addWidget(self.currentGain, 4, 1)
        gridSweeper.addWidget(sweepVoltageIncrLabel, 0, 4)
        gridSweeper.addWidget(self.sweepVoltageIncr, 0, 5)
        gridSweeper.addWidget(self.sweepSampleRateLabel, 1, 4)
        gridSweeper.addWidget(self.sweepSampleRate, 1, 5)
        gridSweeper.addWidget(self.btnSweepCommand, 3, 6)
        gridSweeper.addWidget(self.btnExportLog, 4, 6)
        self.groupSweeper.setLayout(gridSweeper)

        #### STATUS GROUP ###################################
        self.groupStatus = QtGui.QGroupBox("Sweep Status")
        gridStatus = QtGui.QGridLayout()

        measuredVoltageLabel = QtGui.QLabel("Voltage [mV]")
        self.measuredVoltage = QtGui.QLineEdit(self)
        self.measuredVoltage.setReadOnly(True)

        measuredCurrentLabel = QtGui.QLabel("Current [mA]")
        self.measuredCurrent = QtGui.QLineEdit(self)
        self.measuredCurrent.setReadOnly(True)

        gridStatus.addWidget(measuredVoltageLabel, 0, 0)
        gridStatus.addWidget(self.measuredVoltage, 0, 1)
        gridStatus.addWidget(measuredCurrentLabel, 1, 0)
        gridStatus.addWidget(self.measuredCurrent, 1, 1)
        self.groupStatus.setLayout(gridStatus)

        #### VBOX LAYOUT
        vbox.addWidget(self.mspConnectGroup)
        vbox.addWidget(mspCommandGroup)
        vbox.addWidget(self.groupSweeper)
        vbox.addWidget(self.groupStatus)
        self.setLayout(vbox)
        self.show()

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Curve Tracer Prototype')

        self.toggleCommandField("OFF")
        self.toggleConnectField("ON")
        self.show()

    def mspConnect(self):
        source = self.sender()
        if source.text() == "CONNECT":
            port = self.mspConfigPortBox.text()
            rate = self.mspConfigBaudBox.text()
            self.mspInst = curveTracerSerial.Connection(port, rate)
            self.btnMspConnect.setText("DISCONNECT")
            self.toggleConnectField("OFF")
        elif source.text() == "DISCONNECT":
            self.mspInst.close()
            del self.mspInst
            self.btnMspConnect.setText("CONNECT")
            self.toggleConnectField("ON")

    def sweepVoltageAction(self):
        sender = self.sender()
        senderName = sender.text()
        if senderName == "SWEEP":
            maxV = self.sweepVoltageMax.text()
            minV = self.sweepVoltageMin.text()
            incr = self.sweepVoltageIncr.text()
            sampleRate = self.sweepSampleRate.text()
            vcc5Voltage = self.vcc5Voltage.text()
            vcc3Voltage = self.vcc3Voltage.text()
            currentGain = self.currentGain.text()
            try:
                self.c = cts.SweepThread(self.mutex, self.mspInst, minV, maxV,
                                         incr, sampleRate, vcc5Voltage,
                                         vcc3Voltage, currentGain)
                self.c.signalSweepDone.connect(self.sweepDoneAction)
                self.c.signalUpdateStats.connect(self.updateStats)
                self.c.begin()
            except:
                print("unable to start")
        elif senderName == "STOP":
            try:
                self.c.stopSweep()
                # del self.c
                self.toggleSweepField("ON")
                self.btnSweepCommand.setText("SWEEP")
            except:
                print("Could not kill process")

    def sweepDoneAction(self, check):
        if check is False:
            self.btnSweepCommand.setText("STOP")
            self.toggleSweepField("OFF")
        elif check is True:
            print("voltage", self.voltageArray)
            print("current", self.currentArray)
            self.toggleSweepField("ON")
            self.btnExportLog.setEnabled(True)
            self.btnSweepCommand.setText("SWEEP")

    def btnExportLogAction(self):
        csvFile = QtGui.QFileDialog.getSaveFileName(self, 'Open file', '.')
        print(csvFile)
        with open(csvFile, 'w', newline='') as fp:
            a = csv.writer(fp, delimiter=',')
            a.writerow(('VOLTAGE [mV]', 'CURRENT [mA]'))
            for i in range(len(self.voltageArray)):
                a.writerow((self.voltageArray[i], self.currentArray[i]))

    def updateStats(self, type, value):
        valueRounded = round(value, 4)
        if type == "VOLTAGE":
            self.measuredVoltage.setText(str(valueRounded) + " mV")
            self.voltageArray.append(value)
        elif type == "CURRENT":
            self.measuredCurrent.setText(str(valueRounded) + " mA")
            self.currentArray.append(value)
            for i in range(len(self.currentArray)):
                ax = self.figure.add_subplot(111)
                ax.hold(False)
                ax.plot(self.voltageArray[0:i], self.currentArray[0:i])
                ax.set_title('SOLAR CELL IV CURVE')
                ax.set_xlabel('VOLTAGE [mV]')
                ax.set_ylabel('CURRENT [mA]')
                self.canvas.draw()
        elif type == "SIZE":
            self.voltageArray = array.array('f')
            self.currentArray = array.array('f')
            self.figure = plt.figure()
            self.canvas = FigCanvas(self.figure)
            self.canvas.show()

    def mspSend(self):
        command = self.commandBox.text()
        self.mspInst.sendCommand(command)
        print(self.mspInst.read())

    def toggleConnectField(self, value):
        if value == "ON":
            self.mspConfigBaudBox.setEnabled(True)
            self.mspConfigPortBox.setEnabled(True)
            self.toggleCommandField("OFF")
        elif value == "OFF":
            self.toggleCommandField("ON")
            self.mspConfigBaudBox.setEnabled(False)
            self.mspConfigPortBox.setEnabled(False)

    def toggleCommandField(self, value):
        if value == "ON":
            self.btnSendCommand.setEnabled(True)
            self.commandBox.setEnabled(True)
            self.groupSweeper.setEnabled(True)
        elif value == "OFF":
            self.btnSendCommand.setEnabled(False)
            self.commandBox.setEnabled(False)
            self.groupSweeper.setEnabled(False)

    def toggleSweepField(self, value):
        if value == "ON":
            self.sweepVoltageMin.setEnabled(True)
            self.sweepVoltageMax.setEnabled(True)
        elif value == "OFF":
            self.sweepVoltageMin.setEnabled(False)
            self.sweepVoltageMax.setEnabled(False)
예제 #27
0
class GraphView(QtGui.QWidget):
    def __init__(self, image, aa, pymol, pmap, parent=None):
        super(GraphView, self).__init__(parent)
        self.aa = aa
        self.pymol = pymol
        self.dpi = 300
        self.pmap = pmap
        self.fig = Figure((4.5, 4.5), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.mpl_connect('button_press_event', self._onpick)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.dmap = self.cmap_discretize(cm.spectral, 10)
        self.image = image
        self.map = self.axes.imshow(self.image,
                                    interpolation='nearest',
                                    cmap=self.dmap,
                                    aspect='equal',
                                    origin='lower')
        self.canvas.show()
        self.set_parameters()

    def cmap_discretize(self, cmap, N):
        """Return a discrete colormap from the continuous colormap cmap.

            cmap: colormap instance, eg. cm.jet.
            N: number of colors.

        Example
            x = resize(arange(100), (5,100))
            djet = cmap_discretize(cm.jet, 5)
            imshow(x, cmap=djet)
        """
        if type(cmap) == str:
            cmap = cm.get_cmap(cmap)
        colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.)))
        colors_rgba = cmap(colors_i)
        indices = np.linspace(0, 1., N + 1)
        cdict = {}
        for ki, key in enumerate(('red', 'green', 'blue')):
            cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i,
                                                                           ki])
                          for i in xrange(N + 1)]
        # Return colormap object.
        return colors.LinearSegmentedColormap(cmap.name + "_%d" % N, cdict,
                                              1024)

    def _get_clicked_residues(self, event):
        xmin, xmax = self.axes.get_xlim()
        ymin, ymax = self.axes.get_ylim()
        return (int(math.ceil(event.xdata - xmin)) - 1,
                int(math.ceil(event.ydata - ymin)) - 1)

    def _onpick(self, event):
        if self.pmap.use_ca:
            atom = 'CA'
        else:
            atom = 'CB'

        index1, index2 = self._get_clicked_residues(event)
        if self.image[index1][index2] > 0:
            self.pymol.select_aminoacids(self.aa[index1], self.aa[index2],
                                         atom, self.pmap.cutoff)

    def set_parameters(self):
        cbar_ax = self.fig.add_axes([0.12, 0.94, 0.75, 0.03])
        cbar_ax.xaxis.labelpad = 3.0
        cbar_ax.tick_params(length=2.0, direction='out', pad=0.0)
        cbar = self.fig.colorbar(self.map,
                                 cax=cbar_ax,
                                 orientation='horizontal',
                                 drawedges=False)
        cbar_ax.xaxis.set_ticks_position('top')
        cbar_ax.xaxis.set_label_position('bottom')
        cbar_ax.xaxis.set_label_text('Contact Counts')
        self.axes.tick_params(axis=u'both', which=u'both', length=0)
        self.axes.xaxis.set_ticks(range(0, len(self.aa), 1))
        self.axes.yaxis.set_ticks(range(0, len(self.aa), 1))
        self.axes.set_xticklabels(self.aa, rotation=90)
        self.axes.set_yticklabels(self.aa)
        self.fig.patch.set_facecolor((0.886, 0.886, 0.886))
        ticks_font = mpl.font_manager.FontProperties(family='times new roman',
                                                     style='normal',
                                                     size=12,
                                                     weight='normal',
                                                     stretch='normal')
        labels = [
            self.axes.title, self.axes.xaxis.label, self.axes.yaxis.label,
            cbar.ax.xaxis.label
        ]
        labels += self.axes.get_xticklabels() + self.axes.get_yticklabels(
        ) + cbar.ax.get_xticklabels()
        for item in labels:
            item.set_fontproperties(ticks_font)
            item.set_fontsize(4)

    def update_graph(self, image):
        self.axes.clear()
        self.image = image
        self.map = self.axes.imshow(self.image,
                                    interpolation='nearest',
                                    cmap=self.dmap,
                                    aspect='equal',
                                    origin='lower')
        self.set_parameters()
        self.canvas.draw()
예제 #28
0
class PlotTab(QtGui.QWidget):
	delete_this_tab = QtCore.pyqtSignal()
	dataset = None

	def __init__(self, delete_plot_button=True, parent=None):
	    QtGui.QWidget.__init__(self, parent=parent)
	    self.layout = QtGui.QGridLayout()
	    self.setLayout(self.layout)

	    # Title lable and enter title name
	    plot_title_label = QtGui.QLabel("Title: ")
	    self.layout.addWidget(plot_title_label, 0, 0)
	    self.plot_title_edit = QtGui.QLineEdit()
	    self.layout.addWidget(self.plot_title_edit, 0, 1)

	    #make the axes config widget
	    axes_config_widget = QtGui.QWidget()
	    axes_config_widget_layout = QtGui.QHBoxLayout()
	    axes_config_widget.setLayout(axes_config_widget_layout)
	    self.layout.addWidget(axes_config_widget, 1, 0, 1, 2)

	    self.axes_config_struct = []
	    # this struct should contain axes config objects
	    #[ [ var, label, flatten, flatten, ...], [var, label, flatten, flatten, ...], ... ]
	    
	    #make the x axis config, setup
	    x_config_widget = QtGui.QWidget()
	    self.x_config_widget_layout = QtGui.QGridLayout()
	    x_config_widget.setLayout(self.x_config_widget_layout)
	    #label the seciton
	    x_config_widget_label = QtGui.QLabel("X Axis")
	    self.x_config_widget_layout.addWidget(x_config_widget_label, 0, 0)
	    #variable selection
	    x_config_var_label = QtGui.QLabel("Var: ")
	    self.x_config_widget_layout.addWidget(x_config_var_label, 1, 0)
	    self.x_config_var_select = QtGui.QComboBox()
	    self.x_config_var_select.currentIndexChanged.connect(self.x_var_selected)
	    self.x_config_widget_layout.addWidget(self.x_config_var_select, 1, 1)
	    #axis label config
	    x_config_axis_label_label = QtGui.QLabel("x axis label:")
	    self.x_config_widget_layout.addWidget(x_config_axis_label_label, 2, 0)
	    self.x_config_axis_label_edit = QtGui.QLineEdit()
	    self.x_config_widget_layout.addWidget(self.x_config_axis_label_edit, 2, 1)
	    axes_config_widget_layout.addWidget(x_config_widget, 0)

	    #make the y axis config stuff
	    y_config_widget = QtGui.QWidget()
	    self.y_config_widget_layout = QtGui.QGridLayout()
	    y_config_widget.setLayout(self.y_config_widget_layout)
	    #label the section
	    y_config_widget_label = QtGui.QLabel("Y Axis")
	    self.y_config_widget_layout.addWidget(y_config_widget_label, 0, 0)
	    #variable selection
	    y_config_var_label = QtGui.QLabel("Var: ")
	    self.y_config_widget_layout.addWidget(y_config_var_label, 1, 0)
	    self.y_config_var_select = QtGui.QComboBox()
	    self.y_config_var_select.currentIndexChanged.connect(self.y_var_selected)
	    self.y_config_widget_layout.addWidget(self.y_config_var_select, 1, 1)
	    #axis label config
	    y_config_axis_label_label = QtGui.QLabel("y axis label")
	    self.y_config_widget_layout.addWidget(y_config_axis_label_label, 2, 0)
	    self.y_config_axis_label_edit = QtGui.QLineEdit()
	    self.y_config_widget_layout.addWidget(self.y_config_axis_label_edit, 2, 1)
	    axes_config_widget_layout.addWidget(y_config_widget, 1)

	    #create buttons to perform certain actions
	    config_actions_widget = QtGui.QWidget()
	    config_actions_widget_layout = QtGui.QHBoxLayout()
	    config_actions_widget.setLayout(config_actions_widget_layout)
	    # should the widget have a delete plot button? make on if so
	    # The first tab should never have a delete button on it, 
	    # The interface should always have one tab besides the "+" tab
	    if delete_plot_button == True:
	        config_actions_widget_delete = QtGui.QPushButton("Delete plot")
		config_actions_widget_delete.clicked.connect(self.delete_clicked)
	        config_actions_widget_layout.addWidget(config_actions_widget_delete)
	    #button to click to import a variable from the console to be able to plot
	    config_actions_widget_importvar = QtGui.QPushButton("Import var from console")
	    config_actions_widget_importvar.clicked.connect(self.importvar_clicked)
	    config_actions_widget_layout.addWidget(config_actions_widget_importvar)
	    #button to click when they are done config and want to create the plot
	    config_actions_widget_plot = QtGui.QPushButton("Create Plot")
	    config_actions_widget_plot.clicked.connect(self.plot_clicked)
	    config_actions_widget_layout.addWidget(config_actions_widget_plot)
	    self.layout.addWidget(config_actions_widget, 2, 1)

	    # connect to the mainwindow dataset_imported fufn
	    self.window().dataset_imported.connect(self.dataset_imported)
	
	def x_var_selected(self):
	    xvar = self.x_config_var_select.currentText()
	    if self.x_config_widget_layout.itemAtPosition(3, 0):
	        oldcontaineritem = self.x_config_widget_layout.itemAtPosition(3, 0).widget()
	        self.x_config_widget_layout.removeWidget(oldcontaineritem)
	        oldcontaineritem.deleteLater()
	        oldcontaineritem = None
	        self.x_flatten = None
	    #if the variable is not flat, need to flatten it
	    if len(self.dataset.variables[xvar].shape)>1:
		container = QtGui.QWidget()
	        container_layout = QtGui.QGridLayout()
	        container.setLayout(container_layout)
	        message = QtGui.QLabel("not flat, select dims to flatten")
	        container_layout.addWidget(message, 0, 0, 1, 2)
	        #not flat! how to flatten?
	        self.x_flatten = []
	        for dim in self.dataset.variables[xvar].shape:
	            label = QtGui.QLabel("dim %s" % dim)
	            container_layout.addWidget(label)
	            options = QtGui.QComboBox()
	            options.dim = dim
	            options.addItem("all")
	            for i in range(dim):
	                options.addItem(str(i))
	            self.x_flatten.append(options)
	            container_layout.addWidget(options)
	        self.x_config_widget_layout.addWidget(container, 3, 0, 1, 2)
	    #if the variable has time in it, see if we prettify
	    if re.search("time", xvar):
	        container = QtGui.QWidget()
	        self.pretty_time_container_layout = QtGui.QGridLayout()
	        container.setLayout(self.pretty_time_container_layout)
 	        self.x_pretty_time_checkbox = QtGui.QCheckBox("Is this a time variable, make it pretty?")
	        self.x_pretty_time_checkbox.stateChanged.connect(self.make_time_pretty)
	        self.pretty_time_container_layout.addWidget(self.x_pretty_time_checkbox, 0, 0, 1, 2)
	        self.x_config_widget_layout.addWidget(container, 4, 0, 1, 2)
	        self.x_config_axis_label_edit.setText("time")
	    else:
	        units = self.dataset.variables[xvar].units
	        self.x_config_axis_label_edit.setText("%s [%s]" % (xvar, units))
	

	def y_var_selected(self):
	    yvar = self.y_config_var_select.currentText()
	    units = self.dataset.variables[yvar].units
	    self.y_config_axis_label_edit.setText("%s [%s]" % (yvar, units))
	    if self.y_config_widget_layout.itemAtPosition(3, 0):
	        oldcontaineritem = self.y_config_widget_layout.itemAtPosition(3, 0).widget()
	        self.y_config_widget_layout.removeWidget(oldcontaineritem)
	        oldcontaineritem.deleteLater()
	        oldcontaineritem = None
	        self.y_flatten = None
	    if len(self.dataset.variables[yvar].shape)>1:
		container = QtGui.QWidget()
	        container_layout = QtGui.QGridLayout()
	        container.setLayout(container_layout)
	        message = QtGui.QLabel("not flat, select dims to flatten")
	        container_layout.addWidget(message, 0, 0, 1, 2)
	        #not flat! how to flatten?
	        self.y_flatten = []
	        for dim in self.dataset.variables[yvar].shape:
	            label = QtGui.QLabel("dim %s" % dim)
	            container_layout.addWidget(label)
	            options = QtGui.QComboBox()
	            options.dim = dim
	            options.addItem("all")
	            for i in range(dim):
	                options.addItem(str(i))
	            self.y_flatten.append(options)
	            container_layout.addWidget(options)
	        self.y_config_widget_layout.addWidget(container, 3, 0, 1, 2)

	def make_time_pretty(self, state):
	    if state == QtCore.Qt.Checked:
	        # when the make time pretty checkbox is checked...
	        # make a container to put the parsing widget in
	        container = QtGui.QWidget()
	        container_layout = QtGui.QGridLayout()
	        container.setLayout(container_layout)
	        xvar = self.x_config_var_select.currentText()

	        # init variable as self so that can access from the plot clicked button,
	        # want to make sure we delete when the checkbox is unchecked
 	        self.x_pretty_time_epoch_type = QtGui.QComboBox()
	        for timetype in epoch2datetime.timetypes:
	            self.x_pretty_time_epoch_type.addItem(timetype)
	            # if the timetype shows up in the units of the variable, autoselect it
	            if re.search(timetype, self.dataset.variables[xvar].units):
	                i = self.x_pretty_time_epoch_type.findText(timetype)
	                self.x_pretty_time_epoch_type.setCurrentIndex(i)
	        since = QtGui.QLabel("since")
	        self.x_pretty_time_epoch_start = QtGui.QDateTimeEdit()
	        # search for the timestring in the units, should match something like 2015-03-20
	        tryparsetime = re.search("[0-9,:,/,-]+ [0-9,:,/,-]+", self.dataset.variables[xvar].units)
	        if tryparsetime: #otherwise user has to configure themselves
	            tryparsetime = dateutil.parser.parse(tryparsetime.group(0))
	            self.x_pretty_time_epoch_start.setDateTime(tryparsetime)

	        # put things in the container
	        container_layout.addWidget(self.x_pretty_time_epoch_type, 0, 0)
	        container_layout.addWidget(since, 0, 1)
	        container_layout.addWidget(self.x_pretty_time_epoch_start, 0, 2)

	        # add the container to the parent container
	        self.pretty_time_container_layout.addWidget(container, 1, 0, 1, 2)
	    else:
	        # all the stuff above (combobox since datetimedit) was put in one container
	        # fixed at (1, 0) in pretty_time_container_layout so get it and delete it if 
	        # the box was unchecked
	        container = self.pretty_time_container_layout.getItemAtPosition(1, 0).widget()
	        self.pretty_time_container_layout.removeWidget(container)
	        container.deleteLater()
	        self.x_pretty_time_epoch_type = None

	def delete_clicked(self):
	    #delete the tab when the delete button is clicked
	    self.delete_this_tab.emit()

	def importvar_clicked(self):
	    #TODO: how to pull a local variable from the scope of the console
	    #print self.window().console.kernel_manager.kernel.shell.__dict__
	    pass

	def plot_clicked(self):
	    xvar = self.x_config_var_select.currentText()
	    yvar = self.y_config_var_select.currentText()
	    self.fig = Figure(figsize=(5, 4), dpi=100)
	    axes = self.fig.add_subplot(111)
	    axes.hold(False)
	    x = self.dataset.variables[xvar][:]
	    y = self.dataset.variables[yvar][:]
	    if self.x_config_widget_layout.itemAtPosition(3, 0):
	        #flatten x
	        flattening = []
	        for widget in self.x_flatten:
	            dim = widget.currentText()
	            if dim == "all":
			flattening.append(slice(None))
	            else:
	                flattening.append(int(dim))
                x = x[flattening].flatten()
	    if re.search("time", xvar):
	        if self.x_pretty_time_checkbox.isChecked():
	            #if this is a time variable and the checkbox for pretty time is checked
	            # then we know we need to parse the x variable and turn it into a datetime
	            # object to pass to matplotlib
	            tmp_epochtypestr = self.x_pretty_time_epoch_type.currentText()
	            tmp_epochbegin = self.x_pretty_time_epoch_start.dateTime().toPyDateTime()
	            convertor = epoch2datetime.Epoch2Datetime(tmp_epochtypestr, tmp_epochbegin)
	            x = [convertor.int2datetime(tmp_epoch) for tmp_epoch in x]

	    if self.y_config_widget_layout.itemAtPosition(3, 0):
	        #flatten y
	        flattening = []
	        for widget in self.y_flatten:
	            dim = widget.currentText()
	            if dim == "all":
			flattening.append(slice(None))
	            else:
	                flattening.append(int(dim))
                y = y[flattening].flatten()
	    self.plotwidget = FigureCanvas(self.fig)
	    axes.plot(x, y)
	    axes.set_title(self.plot_title_edit.text())
	    axes.set_xlabel(self.x_config_axis_label_edit.text())
	    axes.set_ylabel(self.y_config_axis_label_edit.text())
	    self.fig.autofmt_xdate()
	    self.plotwidget.show()

	def dataset_imported(self, dataset):
	    self.dataset = dataset

	    # clear the comboboxes in case they are already populated
	    # ie. reimporting a dataset, also b/c this is called on new tab
	    self.x_config_var_select.clear()
	    self.y_config_var_select.clear()
	    self.plot_title_edit.setText(self.dataset.title)
	    for var in self.dataset.variables:
	        self.x_config_var_select.addItem(var)
	        self.y_config_var_select.addItem(var)
예제 #29
0
class mywidget(QWidget):
    def __init__(self, Parent=None):
        super(mywidget, self).__init__(Parent)
        self.figure = plt.figure(figsize=(15, 25), facecolor='w', dpi=50)
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(1, 100)
        self.slider.setValue(5)
        self.slider.valueChanged[int].connect(self.changeValue)
        self.label = QLabel('Taxa de amostragem 50 Hz')
        self.spinbox = QSpinBox()
        self.spinbox.setValue(5)
        self.spinbox.valueChanged.connect(self.sliderchange)
        self.spinbox.setRange(1, 100)
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.slider)
        layout.addWidget(self.spinbox)
        layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.changeValue)
        self.setLayout(layout)
        self.plot()
        #self.changeValue(5)

    def sliderchange(self, value):
        self.slider.setValue(value)

    def plot(self):
        self.amostrasporseg = 15 * 5  #samples/sec
        frequenciasinal = 5  #Hz
        omega = frequenciasinal
        self.z = 2 * np.pi * np.arange(0, 2 * np.pi, 1 / self.amostrasporseg)
        y = np.sin(self.z * omega)
        k = y * signal.hann(len(y))

        ylinha = 20 * np.log10(abs(np.fft.fft(k, 2048)))
        ylinha = np.tile(ylinha, 3)

        zlinha = np.linspace(-2, 4, len(ylinha))
        self.figure.subplots_adjust(bottom=.75)
        gs = gridspec.GridSpec(5, 1, height_ratios=[0.2, 1, 0.25, 1, 0.2])
        ax = self.figure.add_subplot(gs[1])
        self.plot2, = plt.plot(zlinha, ylinha)
        plt.title('Espectro do sinal')
        plt.xlabel(r'$\omega$')
        plt.ylabel(r'|X($\omega$)|')

        plt.xticks((-2, -1, 0, 1, 2, 3, 4), [
            r'$-2\pi$', r'$-\pi$', '0', r'$\pi$', r'$2\pi$', r'$3\pi$',
            r'$4\pi$'
        ])
        #ax.set_xticks([-0.0442,0.0442], minor=True)
        ax.xaxis.grid(True,
                      which='major',
                      linewidth=0.75,
                      color='k',
                      linestyle='--')
        self.beta = self.figure.add_subplot(gs[3])
        self.plot3, = plt.plot(self.z, y, label='Amostragem Correta')
        plt.plot(self.z, y, 'o', label='Amostragem Fixa')
        plt.legend(loc='upper right')
        self.beta.set_xlabel(r't')
        self.beta.set_ylabel(r'x(t)')
        self.beta.set_xlim([0, 2 * np.pi])
        self.figure.tight_layout()

    def changeValue(self, value):
        self.spinbox.setValue(value)
        freq = value
        znovo = np.arange(0, 2 * np.pi, 0.001)
        omega = freq
        omeganovo = freq
        y = np.sin(self.z * omega)
        yf = np.sin(znovo * omeganovo)
        k = y * signal.hann(len(y))
        ylinha = np.fft.fft(k, 2048)
        ylinha = np.tile(ylinha, 3)
        self.beta.clear()
        self.beta.plot(znovo, yf, label='Amostragem Correta')
        self.beta.plot(self.z, y, 'o-', lw=2, label='Amostragem Fixa')
        plt.legend(loc='upper right')
        self.beta.set_xlim([0, 2 * np.pi])
        self.beta.set_xlabel(r't')
        self.beta.set_ylabel(r'x(t)')
        self.beta.set_title(
            'Sinal com amostragem correta x Sinal com amostragem fixa')
        self.plot2.set_ydata(20 * np.log10(abs(ylinha)))
        self.canvas.draw()
        self.canvas.show()
예제 #30
0
파일: Spectro.py 프로젝트: chaxor/Spectro
class Spectra_Tab(QtGui.QTabWidget):
	start_comp = QtCore.pyqtSignal()
	kill_thread = QtCore.pyqtSignal()
	def __init__(self, parent, temp_spectra):
		self.parent = parent
		QtGui.QTabWidget.__init__(self, parent)
		self.temp_spectra = temp_spectra
		self.top_layer_grid = QtGui.QGridLayout(self)
		
		self.canvas_frame = QtGui.QFrame(self)
		self.canvas_frame.setFrameShape(QtGui.QFrame.StyledPanel)
		self.results_frame = QtGui.QFrame(self)
		self.results_frame.setFrameShape(QtGui.QFrame.StyledPanel)
		
		self.top_layer_grid.addWidget(self.canvas_frame)
		self.top_layer_grid.addWidget(self.results_frame)

		self.canvas_grid = QtGui.QGridLayout(self.canvas_frame)
	
		self.top_left_frame = QtGui.QFrame(self.canvas_frame)
		self.top_left_frame.setFrameShape(QtGui.QFrame.StyledPanel)
		self.canvas_grid.addWidget(self.top_left_frame)
	
		self.bottom_canvas_frame = QtGui.QFrame(self.canvas_frame)
		self.bottom_canvas_frame.setFrameShape(QtGui.QFrame.StyledPanel)
		self.canvas_grid.addWidget(self.bottom_canvas_frame)
	
		vertical_splitter = QtGui.QSplitter(QtCore.Qt.Vertical)
		vertical_splitter.addWidget(self.top_left_frame)
		vertical_splitter.addWidget(self.bottom_canvas_frame)
		self.canvas_grid.addWidget(vertical_splitter)

		self.results_grid = QtGui.QGridLayout(self.results_frame)
		self.treeWidget = QtGui.QTreeWidget(self.results_frame)
		self.treeWidget.setFocusPolicy(QtCore.Qt.WheelFocus)
		self.treeWidget.setAutoFillBackground(True)
		self.treeWidget.setAlternatingRowColors(True)
		self.treeWidget.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
		self.treeWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
		self.treeWidget.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerItem)
		self.treeWidget.setAutoExpandDelay(-1)
		self.treeWidget.setHeaderLabels(["(n,m)/Property","%, [value]"])
		self.other_properties = QtGui.QTreeWidgetItem(self.treeWidget, ["Properties"])
		self.nm_species = QtGui.QTreeWidgetItem(self.treeWidget, ["(n,m)"])
		self.semiconducting = QtGui.QTreeWidgetItem(self.other_properties, ["Semiconducting %"])
		self.metallic = QtGui.QTreeWidgetItem(self.other_properties, ["Metallic %"])
		self.avg_diameter = QtGui.QTreeWidgetItem(self.other_properties, ["Average Diameter"])
		self.step_in_tree = QtGui.QTreeWidgetItem(self.other_properties, ["Iteration #"])
		self.dict_of_nm_tree = {}
		for swcnt in temp_spectra.SWCNT_list:
			self.dict_of_nm_tree[swcnt] = QtGui.QTreeWidgetItem(self.nm_species, [swcnt.strNM()])
		self.results_grid.addWidget(self.treeWidget)

		graph_results_splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
		graph_results_splitter.addWidget(self.canvas_frame)
		graph_results_splitter.addWidget(self.results_frame)
		self.top_layer_grid.addWidget(graph_results_splitter)

		policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Preferred)
		policy.setHorizontalStretch(8)
		self.canvas_frame.setSizePolicy(policy)

		# Make figure for original line, background line, and total fit line
		self.top_left_fig = matplotlib.figure.Figure()
		self.top_left_plot = self.top_left_fig.add_subplot(111)
		self.top_left_plot.set_ylabel('Absorbance [a.u.]')
		self.top_left_plot.set_xlabel('Photon Energy [eV]')
		self.top_left_plot.set_title('Total Absorbance Fit')
		init_values = np.zeros(len(self.temp_spectra.X))
		self.top_left_line, = self.top_left_plot.plot(self.temp_spectra.X, self.temp_spectra.Y, 'r-')
		self.top_left_background_line, self.top_left_total_fit_line, = self.top_left_plot.plot(self.temp_spectra.X, init_values, 'k-', self.temp_spectra.X, init_values, 'b-', animated=True)
		self.top_left_canvas = FigureCanvas(self.top_left_fig)
		plotLayout = QtGui.QVBoxLayout()
		plotLayout.addWidget(self.top_left_canvas)
		self.top_left_frame.setLayout(plotLayout)	   
		self.top_left_canvas.show()
		self.top_left_canvas.draw()
		self.top_left_canvas_BBox = self.top_left_plot.figure.canvas.copy_from_bbox(self.top_left_plot.bbox)
		self.ax1 = self.top_left_plot.figure.axes[0]
		self.ax1.set_xlim(self.temp_spectra.X.min(), self.temp_spectra.X.max())
		self.ax1.set_ylim(0, self.temp_spectra.Y.max() + .05*self.temp_spectra.Y.max())
		self.top_left_plot_old_size = self.top_left_plot.bbox.width, self.top_left_plot.bbox.height

		# Make bottom figure
		self.bottom_fig = matplotlib.figure.Figure()
		self.bottom_plot = self.bottom_fig.add_subplot(111)
		self.bottom_plot.set_ylabel('Absorbance [a.u.]')
		self.bottom_plot.set_xlabel('Photon Energy [eV]')
		self.bottom_plot.set_title('Background Subtracted Fit')
		self.bottom_line_original_without_background, = self.bottom_plot.plot(self.temp_spectra.X, self.temp_spectra.Y, 'r-', linewidth=3, animated=True)
		self.bottom_line, = self.bottom_plot.plot(self.temp_spectra.X, init_values, 'b-', linewidth=3, animated=True)
		self.swcnt_line_dict = {}
		for swcnt in temp_spectra.SWCNT_list:
			self.swcnt_line_dict[swcnt], = self.bottom_plot.plot(self.temp_spectra.X, swcnt.line, animated=True)
		self.bottom_canvas = FigureCanvas(self.bottom_fig)
		bottomplotLayout = QtGui.QVBoxLayout()
		bottomplotLayout.addWidget(self.bottom_canvas)
		self.bottom_canvas_frame.setLayout(bottomplotLayout)
		self.bottom_canvas.show()
		self.bottom_canvas.draw()
		self.bottom_canvas_BBox = self.bottom_plot.figure.canvas.copy_from_bbox(self.bottom_plot.bbox)
		self.bottom_ax1 = self.bottom_plot.figure.axes[0]
		self.bottom_ax1.set_xlim(self.temp_spectra.X.min(), self.temp_spectra.X.max())
		self.bottom_ax1.set_ylim(0, self.temp_spectra.Y.max() + .05*self.temp_spectra.Y.max())
		self.bottom_plot_old_size = self.bottom_plot.bbox.width, self.bottom_plot.bbox.height
		
		# Make Thread associated with the tab
		thread = QtCore.QThread(parent=self)
		self.worker = self.temp_spectra
		self.worker.moveToThread(thread)
		self.worker.update_signal.connect(self.update_GUI)
		self.worker.done_signal.connect(self.closeEvent)
		self.start_comp.connect(self.worker.deconvolute)
		self.kill_thread.connect(thread.quit)
		thread.start()
		
	@QtCore.pyqtSlot(Spectra)
	def update_GUI(self, tmp_spectra):
		# change the GUI to reflect changes made to Spectra
		# Get the first background of the plots to blits lines to
		if(tmp_spectra.step==1):
			self.top_left_canvas_BBox = self.top_left_plot.figure.canvas.copy_from_bbox(self.top_left_plot.bbox)
			self.bottom_canvas_BBox = self.bottom_plot.figure.canvas.copy_from_bbox(self.bottom_plot.bbox)
		# If the size of the box changes, get that background instead
		top_left_plot_current_size = self.top_left_plot.bbox.width, self.top_left_plot.bbox.height
		bottom_plot_current_size = self.bottom_plot.bbox.width, self.bottom_plot.bbox.height
		if( self.top_left_plot_old_size != top_left_plot_current_size or self.bottom_plot_old_size != bottom_plot_current_size):
			self.top_left_plot_old_size = top_left_plot_current_size
			self.top_left_plot.clear()
			self.top_left_canvas.draw()
			self.top_left_canvas_BBox = self.top_left_plot.figure.canvas.copy_from_bbox(self.top_left_plot.bbox)
			self.top_left_plot.set_ylabel('Absorbance [a.u.]')
			self.top_left_plot.set_xlabel('Photon Energy [eV]')
			self.top_left_plot.set_title('Total Absorbance Fit')
			self.bottom_plot_old_size = bottom_plot_current_size
			self.bottom_plot.clear()
			self.bottom_canvas.draw()
			self.bottom_canvas_BBox = self.bottom_plot.figure.canvas.copy_from_bbox(self.bottom_plot.bbox)
			self.bottom_plot.set_ylabel('Absorbance [a.u.]')
			self.bottom_plot.set_xlabel('Photon Energy [eV]')
			self.bottom_plot.set_title('Background Subtracted Fit')
		
		# Write to the Top Left Plot with original data, background data, and total fit
		self.top_left_background_line.set_ydata(tmp_spectra.background_model)
		self.top_left_total_fit_line.set_ydata(tmp_spectra.model)
		self.top_left_plot.figure.canvas.restore_region(self.top_left_canvas_BBox)
		if( tmp_spectra.background_model.max() > tmp_spectra.Y.max()):
			self.ax1.set_ylim(0, 1.05*tmp_spectra.background_model.max())
		elif(tmp_spectra.model.max() > tmp_spectra.Y.max()):
			self.ax1.set_ylim(0, 1.05*tmp_spectra.model.max())
		else:
			self.ax1.set_ylim(0, 1.05*tmp_spectra.Y.max())
		self.top_left_plot.draw_artist(self.top_left_line)
		self.top_left_plot.draw_artist(self.top_left_background_line)
		self.top_left_plot.draw_artist(self.top_left_total_fit_line)
		self.top_left_plot.figure.canvas.blit(self.top_left_plot.bbox)

		# Write to the Bottom Plot with each nanotube peak
		self.bottom_line_original_without_background.set_ydata(tmp_spectra.Y-tmp_spectra.background_model)
		self.bottom_line.set_ydata(tmp_spectra.model_without_background)
		try:
			for swcnt in self.dict_of_nm_tree:
				self.swcnt_line_dict[swcnt].set_ydata(swcnt.line)
				self.swcnt_line_dict[swcnt].set_linewidth(1)
			current_swcnt = None
			for swcnt in self.dict_of_nm_tree:
				if(self.dict_of_nm_tree[swcnt] == self.treeWidget.currentItem()):
					current_swcnt = swcnt
					break
			self.swcnt_line_dict[current_swcnt].set_linewidth(4)
		except KeyError:
			pass
		self.bottom_plot.figure.canvas.restore_region(self.bottom_canvas_BBox)
		if( np.amax(tmp_spectra.Y-tmp_spectra.background_model) > np.amax(tmp_spectra.model_without_background) ):
			self.bottom_ax1.set_ylim(0, 1.05*np.amax(tmp_spectra.Y-tmp_spectra.background_model))
		if( np.amax(tmp_spectra.model_without_background) < 0.05):
			self.bottom_ax1.set_ylim(0, 0.05)
		else:
			self.bottom_ax1.set_ylim(0, 1.05*np.amax(tmp_spectra.model_without_background))
		self.bottom_plot.draw_artist(self.bottom_line_original_without_background)
		self.bottom_plot.draw_artist(self.bottom_line)
		for swcnt in tmp_spectra.SWCNT_list:
			self.bottom_plot.draw_artist(self.swcnt_line_dict[swcnt])
		self.bottom_plot.figure.canvas.blit(self.bottom_plot.bbox)

		# Show percentage of species on the side bar
		try:
			percent_dict = tmp_spectra.species_percentage_dictionary
			percent_error_dict = tmp_spectra.species_percentage_error_dictionary
			for swcnt in tmp_spectra.SWCNT_list:
				self.dict_of_nm_tree[swcnt].setText(1, str(round(percent_dict[swcnt], 0)).rstrip('0') + ' % +-' + str(round(percent_error_dict[swcnt], 1)))
			self.semiconducting.setText(1, str(round(100.-tmp_spectra.metallic_percentage, 0)).rstrip('0') + ' %')
			self.metallic.setText(1, str(round(tmp_spectra.metallic_percentage, 0)).rstrip('0') + ' %')
			self.avg_diameter.setText(1, str(round(tmp_spectra.mean_diameter,2)) + ' nm')
			self.step_in_tree.setText(1, str(tmp_spectra.step))
		except KeyError:
			pass


	def output_results(self):
		print "Making Excel Workbook..."

		date_time = datetime.datetime.now().strftime("%Y-%m-%d(%H-%M-%S)")
		name = str(self.temp_spectra.spectra_name)
		book = xlsxwriter.Workbook(name + ' -- ' + date_time +'_OA_Results.xlsx')
		OA_sheet_name = "Optical Absorption Data"
		Results_sheet_name = "Results"
		Other_params_name = "Other Parameters"
		OA_sheet = book.add_worksheet(OA_sheet_name)
		Results_sheet = book.add_worksheet(Results_sheet_name)
		Other_params_sheet = book.add_worksheet(Other_params_name)

		# Write x, y data for main and all species
		OA_sheet.write('A1', "Energy (eV)")
		OA_sheet.write_column('A2', self.temp_spectra.X)
		OA_sheet.write('B1', name )
		OA_sheet.write_column('B2', self.temp_spectra.Y)
		OA_sheet.write('C1', "Model")
		OA_sheet.write_column('C2', self.temp_spectra.model)
		OA_sheet.write('D1', "Background")
		OA_sheet.write_column('D2', self.temp_spectra.background_model)
		for i, swcnt in enumerate(self.temp_spectra.SWCNT_list):
			OA_sheet.write(0, 3+i, swcnt.strNM())
			OA_sheet.write_column(1, 3+i, swcnt.line)

		Results_sheet.write('A1', "(n,m)")
		Results_sheet.write('B1', "%")
		quant_dict = self.temp_spectra.species_percentage_dictionary.iteritems()
		for i, (swcnt, amount) in enumerate(sorted(quant_dict)):
			Results_sheet.write(i+1, 0, swcnt.strNM())
			Results_sheet.write(i+1, 1, round(amount,1))
		Results_sheet.write('D1', "Semiconducting %")
		Results_sheet.write('D2', "Metallic %")
		Results_sheet.write('E1', round(100-self.temp_spectra.calc_metallic_percentage(),1))
		Results_sheet.write('E2', round(self.temp_spectra.calc_metallic_percentage(),1))


		Other_params_sheet.write("A1", "(n,m)")
		Other_params_sheet.write_column("A2", [swcnt.strNM() for swcnt in self.temp_spectra.SWCNT_list])
		Other_params_sheet.write("B1", "SWCNT Solution Vector")
		Other_params_sheet.write_column("B2", self.temp_spectra.swcnts_soln)

		book.close()
		print "Excel Workbook Made."
			


	def start_computation(self):
		self.start_comp.emit()
		return
		
	def closeEvent(self):
		print 'done with processing'
		self.kill_thread.emit()
예제 #31
0
class mGraph(QtGui.QWidget):
    def __init__(self, device, parent=None):
        QtGui.QWidget.__init__(self, parent)
        # Create a matplotlib figure
        self.figure = plt.figure()
        self.figure.set_facecolor("r")
        # Create a QFrame to house the plot. This is not necessary, just makes it look nice
        self.matframe = QtGui.QFrame()
        self.matLayout = QtGui.QVBoxLayout()
        self.matLayout.setSpacing(0)
        self.matframe.setLayout(self.matLayout)
        self.matframe.setFrameShape(QtGui.QFrame.Panel)
        self.matframe.setFrameShadow(QtGui.QFrame.Plain)
        self.matframe.setStyleSheet("background-color: rgb(70,80,88); margin:0px; border:2px solid rgb(0, 0, 0); ")
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        # This is the device we want to use
        self.device = device
        # This sets up axis on which to plot
        self.ax = self.figure.add_subplot(111, axisbg=(189.0 / 255, 195.0 / 255, 199.0 / 255))
        # Add the matplotlib canvas to the QFrame
        self.matLayout.addWidget(self.canvas)
        # The following lines set up all the colors, makes it look nice. The code to do it is
        # far from pretty and I am planning on cleaning this up a bit.
        self.figure.patch.set_color((70.0 / 255, 80.0 / 255, 88.0 / 255))
        self.figure.patch.set_edgecolor((70.0 / 255, 80.0 / 255, 88.0 / 255))
        self.ax.spines["bottom"].set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.spines["top"].set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.spines["right"].set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.spines["left"].set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.tick_params(axis="x", colors=(189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.tick_params(axis="y", colors=(189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.title.set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.yaxis.label.set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.xaxis.label.set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.xaxis.get_offset_text().set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        self.ax.yaxis.get_offset_text().set_color((189.0 / 255, 195.0 / 255, 199.0 / 255))
        # This is an array of all the lines on the plot. A line for every parameter
        self.line = []
        # Each element of line holds a plot, to be combined onto the same graph
        self.line.append(self.ax.plot(1, 1, label="Getting Data...")[0])
        # This is the ONLY time canvas.draw is called. It should NOT be called anywhere else if
        # the graphing speed is to be fast.
        self.canvas.draw()
        # In order to handle interactivity, I had to do some odd stuff with the
        # toolbar buttons. Self.home holds the original function called when the home button on the toolbar
        # is clicked.
        self.home = NavigationToolbar.home
        # We now change the function that is called when the toolbar is clicked.
        NavigationToolbar.home = self.enableAutoScaling
        self.toolbar = NavigationToolbar(self.canvas, self)
        # print [item for item in dir(self.toolbar) if type(item) == QtGui.QDialog]
        self.cid = self.canvas.mpl_connect("button_press_event", self.disableAutoScaling)
        self.setStyleSheet(
            "QPushButton{\
                    color:rgb(189,195, 199); \
                    background:rgb(70, 80, 88)}"
        )
        self.toolbarFrame = QtGui.QFrame()
        toolbarFrameLayout = QtGui.QVBoxLayout()
        toolbarFrameLayout.addWidget(self.toolbar)
        self.toolbar.setParent(None)
        self.toolbarFrame.setLayout(toolbarFrameLayout)
        self.toolbarFrame.setStyleSheet(
            "\
                    border:2px solid rgb(0,0,0);\
                    color:rgb(189,195,199); \
                    background:rgb(70, 80, 88);\
                    "
        )
        self.toolbar.setStyleSheet(
            "\
                    border:0px solid rgb(0,0,0);\
                    QDialog{background:rgb(250, 80, 88)}\
                    "
        )
        # print dir(self.toolbar)
        # print self.toolbar.children()
        # print self.toolbar.setPalette
        self.matPlotInfo = QtGui.QLabel()
        self.alertFont = QtGui.QFont()
        self.alertFont.setPointSize(12)
        self.matPlotInfo.setStyleSheet("color:rgb(200, 69, 50);")
        self.matPlotInfo.setText("Auto refresh disabled, click HOME button to enable.")
        self.matPlotInfo.setFont(self.alertFont)

        self.refreshRateSec = device.getFrame().getPlotRefreshRate()
        self.timer = QtCore.QTimer(self)

        self.hidden = True
        self.home = True
        self.currTimeRange = 120
        self.plot(self.currTimeRange)

        self.timer.timeout.connect(partial(self.plot, self.currTimeRange))
        self.timer.start(self.refreshRateSec * 1000)
        # did it store data?
        self.dataOk = True
        self.hideButton = QtGui.QPushButton("Show Plot")
        self.hideButton.clicked.connect(self.togglePlot)
        self.thrtysecButton = QtGui.QPushButton("30 Sec")
        self.thrtysecButton.clicked.connect(partial(self.plot, 30))
        self.twoMinButton = QtGui.QPushButton("2 Min")
        self.twoMinButton.clicked.connect(partial(self.plot, 120))
        self.fiveMinButton = QtGui.QPushButton("5 Min")
        self.fiveMinButton.clicked.connect(partial(self.plot, 300))
        self.thrtyMinButton = QtGui.QPushButton("30 Min")
        self.thrtyMinButton.clicked.connect(partial(self.plot, 1800))
        self.twoHrButton = QtGui.QPushButton("2 Hr")
        self.twoHrButton.clicked.connect(partial(self.plot, 7200))
        self.tenHrButton = QtGui.QPushButton("10 Hr")
        self.tenHrButton.clicked.connect(partial(self.plot, 36000))
        self.oneDayButton = QtGui.QPushButton("24 Hr")
        self.oneDayButton.clicked.connect(partial(self.plot, 86400))
        self.oneWkButton = QtGui.QPushButton("1 Wk")
        self.oneWkButton.clicked.connect(partial(self.plot, 604800))
        self.twoWkButton = QtGui.QPushButton("2 Wk")
        self.twoWkButton.clicked.connect(partial(self.plot, 1209600))
        self.allButton = QtGui.QPushButton("All Time")
        self.allButton.clicked.connect(partial(self.plot, None))
        self.canvas.hide()
        self.toolbar.hide()

        # set the layout

        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.hideButton)
        buttonLayout.addStretch(0)
        buttonLayout2 = QtGui.QHBoxLayout()

        buttonLayout3 = QtGui.QHBoxLayout()

        buttonLayout2.addWidget(self.thrtysecButton)
        buttonLayout2.addWidget(self.twoMinButton)
        buttonLayout2.addWidget(self.fiveMinButton)
        buttonLayout2.addWidget(self.thrtyMinButton)
        buttonLayout2.addWidget(self.twoHrButton)
        buttonLayout2.addStretch(0)
        buttonLayout3.addWidget(self.tenHrButton)
        buttonLayout3.addWidget(self.oneDayButton)
        buttonLayout3.addWidget(self.oneWkButton)
        buttonLayout3.addWidget(self.twoWkButton)
        buttonLayout3.addWidget(self.allButton)
        buttonLayout3.addStretch(0)
        self.thrtysecButton.hide()
        self.twoMinButton.hide()
        self.fiveMinButton.hide()
        self.thrtyMinButton.hide()
        self.twoHrButton.hide()
        self.tenHrButton.hide()
        self.oneDayButton.hide()
        self.oneWkButton.hide()
        self.twoWkButton.hide()
        self.allButton.hide()
        self.matframe.hide()
        self.matPlotInfo.hide()
        self.toolbarFrame.hide()

        layout = QtGui.QVBoxLayout()
        layout.addLayout(buttonLayout)
        layout.addLayout(buttonLayout2)
        layout.addLayout(buttonLayout3)
        layout.addWidget(self.matPlotInfo)
        layout.addWidget(self.matframe)
        layout.addWidget(self.toolbarFrame)

        self.setLayout(layout)

    def enableAutoScaling(self):
        self.timer.start(self.refreshRateSec * 1000)
        # self.canvas.mpl_disconnect(self.cid)
        # self.cid = self.canvas.mpl_connect('button_press_event', self.disableAutoScaling)
        self.home = True
        self.matPlotInfo.hide()
        # self.deviceThread = threading.Thread(target =
        # self.plot, args=[self.currTimeRange])
        # If the main thread stops, stop the child thread
        # self.deviceThread.daemon = True
        # Start the thread
        # self.deviceThread.start()

        self.plot(self.currTimeRange)

    def disableAutoScaling(self, event):
        self.home = False
        self.matPlotInfo.show()
        self.canvas.update()
        # plt.show()
        # print event.name
        # self.canvas.mpl_disconnect(self.cid)
        # self.cid = self.canvas.mpl_connect('button_press_event', self.enableAutoScaling)
        self.timer.stop()
        # self.zoom(self.toolbar)

    def togglePlot(self):

        if not self.hidden:
            self.canvas.hide()
            self.toolbar.hide()
            self.thrtysecButton.hide()
            self.twoMinButton.hide()
            self.fiveMinButton.hide()
            self.thrtyMinButton.hide()
            self.twoHrButton.hide()
            self.tenHrButton.hide()
            self.oneDayButton.hide()
            self.oneWkButton.hide()
            self.twoWkButton.hide()
            self.allButton.hide()
            self.matPlotInfo.hide()
            self.matframe.hide()
            self.toolbarFrame.hide()
            self.timer.stop()
            self.hideButton.setText("Show Plot")
            self.hidden = True

        elif self.hidden:
            self.canvas.show()
            self.toolbar.show()
            self.thrtysecButton.show()
            self.twoMinButton.show()
            self.fiveMinButton.show()
            self.thrtyMinButton.show()
            self.twoHrButton.show()
            self.tenHrButton.show()
            self.oneDayButton.show()
            self.oneWkButton.show()
            self.twoWkButton.show()
            self.allButton.show()
            self.plot(self.currTimeRange)
            self.matframe.show()
            self.toolbarFrame.show()
            self.timer.start(self.refreshRateSec * 1000)
            self.hideButton.setText("Hide Plot")
            self.enableAutoScaling()
            self.hidden = False

    def plot(self, timeRange):
        if not self.hidden:
            if timeRange != self.currTimeRange:
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(lambda: self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)
            if self.refreshRateSec != self.device.getFrame().getPlotRefreshRate():
                # print "New plot refresh rate: ", self.device.getFrame().getPlotRefreshRate()
                self.refreshRateSec = self.device.getFrame().getPlotRefreshRate()
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(lambda: self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)
            dataSet = self.device.getFrame().getDataSet()
            # If the dataset exists
            if dataSet is not None:
                # Get all data from the dataset
                data = dataSet.getData()
                self.ax.hold(False)
                try:
                    # for each entry in the dataset [[time], [[data], [data], [data...]]]
                    # print data
                    # Get the corresponding times that the values were recorded

                    for i in range(1, len(data[-1])):
                        # Get colum. aka all values from parameter i over time
                        column = [row[i] for row in data]

                        # print times
                        # If the there is  no defined a time range
                        if self.currTimeRange is None:
                            times = [datetime.datetime.fromtimestamp(row[0]) for row in data]
                            # Plot all of the data (columns) vs time
                            # self.ax.plot_date(times, column, label =
                            # dataSet.getVariables()[1][i-1][0])
                            pass
                        else:
                            # Otherwise, if the user PREVIOUSLY defined a time range,
                            # we need to look for the beginning of it.
                            # Start by getting the current time
                            dstamp = dateStamp()
                            # The dataset should be from now to -timerange
                            # time(now)-time(range)
                            startTime = dstamp.utcNowFloat() - self.currTimeRange
                            # If timeRange is not None, then we know we need
                            # to display only a certain range of values
                            # However, if the starttime defined is less than the lowest time, we
                            # do not have enough data to display the whole thing, so we must
                            # display all that we have instead. We do this by setting
                            # currTimeRange = 0.
                            if timeRange is not None and startTime < float(data[0][0]):
                                self.currTimeRange = None
                            # For all entries in data
                            for y in range(len(data)):
                                # We are searching backwards through the dataset to find a time
                                # just before the time range specified
                                if data[len(data) - y - 1][0] < startTime:
                                    # once we find it, we know the beginning index of the data to be
                                    # displayed
                                    index = y
                                    # Get the times and datafrom the index and columns to the end of the dataset
                                    times = [datetime.datetime.fromtimestamp(row[0]) for row in data[-index:]]
                                    # print times[0]
                                    column = [row[i] for row in data[-index:]]
                                    # Exit the loop
                                    break

                        try:
                            while len(self.line) <= i:
                                self.line.append(self.ax.plot(1, 1, label=dataSet.getVariables()[1][i - 1][0])[0])

                            self.line[i].set_data(times, column)
                            self.ax.legend(loc="upper left", shadow=True, fancybox=True)
                            # maxi = max(column)
                            # mini = min(column)
                            # newMax = max(column)
                            # newMini = min(column)
                            # if(newMax>maxi)
                            # maxi=newMax
                            # self.ax.set_ylim(mini-mini/2, maxi+maxi/2)
                            # if(newMini<mini)
                            # self.ax.set_ylim(mini-mini/2, maxi+maxi/2)
                            # maxi = max(column)
                            # mini = min(column)

                            # self.ax.set_ylim(mini-mini/2, maxi+maxi/2)
                            # self.ax.set_xlim(min(times), max(times))
                            # self.ax.draw_artist(self.line[i])
                        except:

                            traceback.print_exc()

                            # print "Failed to log data"
                        # Add a legend
                        legend = self.ax.legend(loc="upper left")
                        self.ax.set_title(
                            self.device.getFrame().getTitle(), color=(189.0 / 255, 195.0 / 255, 199.0 / 255)
                        )

                        if (
                            self.device.getFrame().getYLabel() is not None
                            and len(self.device.getFrame().getCustomUnits()) is not 0
                        ):
                            self.ax.set_ylabel(
                                self.device.getFrame().getYLabel()
                                + " ("
                                + self.device.getFrame().getCustomUnits()
                                + ")"
                            )
                        elif (
                            self.device.getFrame().getYLabel() is not None
                            and len(self.device.getFrame().getUnits()[i - 1]) is not 0
                        ):

                            self.ax.set_ylabel(
                                self.device.getFrame().getYLabel()
                                + " ("
                                + self.device.getFrame().getUnits()[i - 1]
                                + ")"
                            )

                        self.ax.set_xlabel("Time")

                        self.ax.hold(True)
                        # locator = AutoDateLocator()
                        # self.ax.fmt_xdata = AutoDateFormatter()
                        # self.ax.xaxis.set_major_locator(locator)
                        # self.ax.xaxis.set_major_locator(locator)
                        # self.ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))

                        # self.ax.fmt_xdata = mdates.DateFormatter('%m/%d %H:%M:%S')
                        # print "type: ", type(times[-1])
                        # print "time[-1]: ",times[-1]
                        # self.ax.set_ylim(bottom = 733681, top = 733682)

                        # self.figure.tight_layout()
                        self.ax.grid(True)

                except Exception as e:
                    print "Error"
                try:

                    self.ax.grid(True)
                    # self.ax.clear(self.ax.yaxis)
                    # self.ax.cla()

                    if self.home:
                        self.ax.set_xlim(times[0], times[-1])
                        self.ax.relim()
                        self.ax.autoscale()

                    # print self.ax.get_data_interval()
                    self.ax.draw_artist(self.figure)
                    self.ax.draw_artist(self.ax.patch)

                    locator = AutoDateLocator()

                    self.ax.xaxis.set_major_locator(locator)
                    self.ax.xaxis.set_major_formatter(DateFormatter("%m/%d %H:%M:%S"))
                    self.figure.autofmt_xdate()
                    # print [time.toordinal() for time in times]
                    self.ax.draw_artist(self.ax.yaxis)
                    self.ax.draw_artist(self.ax.xaxis)

                    for line in self.line:
                        self.ax.draw_artist(line)

                    # self.ax.axis('off')

                    self.ax.draw_artist(legend)

                    self.canvas.update()

                    self.canvas.flush_events()

                except:
                    times = [datetime.datetime.fromtimestamp(row[0]) for row in data]
                    traceback.print_exc()
                    self.ax.set_xlim(times[0], times[-1])
                    self.ax.relim()
                    self.ax.autoscale()
                    # print self.ax.get_data_interval()
                    pass
예제 #32
0
class SabatheDialog(QDialog, CicloSabatheGUI.Ui_Dialog):

    def __init__(self, parent=None):
        super(SabatheDialog, self).__init__(parent)
        self.setWindowTitle(__appName__)
        self.setupUi(self)
        self.Q = []
        #Defino las formulas quimicas para selecionar en formulas_comboBox
        self.formulas = {"AvGas":{'c':7,'h':16,'o':0,'s':0.00},"Diesel":{'c':12,'h':21,'o':0,'s':0.00}}
        # Utilizo las 'keys' de self.formulas para cargar los items en la combobox
        for key in self.formulas.keys():
            self.formula_comboBox.addItem(key)

        # Generamos dos figuras, cada una luego asociada a un canvas, que a su vez tiene como padre una de las pestañas
        # self.tab -> contiene la pestaña titulada "Diagrama P-S"
        # self.tab_2 -> contiene la pestaña titulada "Diagrama T-S"
        self.fig1 = Figure(figsize=(4.8,3.4),dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
        self.axes1 = self.fig1.add_subplot(111)
        self.axes1.set_ylabel('p')
        self.axes1.set_xlabel('v')
        self.axes1.set_title('Ciclo Sabathe')
        self.fig2 = Figure(figsize=(4.8,3.4),dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
        self.axes2 = self.fig2.add_subplot(111)
        self.axes2.set_ylabel('T')
        self.axes2.set_xlabel('S')
        self.axes2.set_title('Ciclo Sabathe')
        # generate the canvas to display the plot
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setParent(self.tab)
        self.canvas1.show()
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.setParent(self.tab_2)
        self.canvas2.show()
        self.gamma_aire = 1.4
        self.R_aire = 287
        self.actualizarFormula()

        #Cambio los lineInput de HVS y HVI a "ReadOnly"
        self.HVS_lineEdit.setReadOnly(True)
        self.HVI_lineEdit.setReadOnly(True)

        #Seleccion de una formula en formula_comboBox
        self.connect(self.formula_comboBox,SIGNAL("currentIndexChanged(int)"),self.selecionFormula)


        # Acciones de actualización de la formula quimica para el calculo de Q
        self.connect(self.formulaC,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaH,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaO,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.formulaS,SIGNAL("textEdited(const QString&)"),self.actualizarFormula)
        self.connect(self.relacionMezcla,SIGNAL("valueChanged(double)"),self.actualizarFormula)
        self.connect(self.calcular,SIGNAL("clicked()"),self.Calculos)
        # Boton para mostrar matriz de resultados
        self.connect(self.matrixButton,SIGNAL("clicked()"),self.displayMatrix)
        #Boton para seleccionar P1 y T1 a partir de la altura:
        self.connect(self.Altura_Button,SIGNAL("clicked()"),self.seleccionAltura)

    def selecionFormula(self):
        formula = self.formula_comboBox.currentText()
        if formula != 'Otra':
            self.formulaC.setText(str(self.formulas[formula]['c']))
            self.formulaH.setText(str(self.formulas[formula]['h']))
            self.formulaO.setText(str(self.formulas[formula]['o']))
            self.formulaS.setText(str(self.formulas[formula]['s']))
            self.actualizarFormula()

    def actualizarFormula(self):
        try:
            c = self.lecturadatos(self.formulaC, 'int')
            h = self.lecturadatos(self.formulaH, 'int')
            o = self.lecturadatos(self.formulaO, 'int')
            s = self.lecturadatos(self.formulaS, 'float')
        except: pass
        else:
            # si la formula ingresada coincide con alguna formula del comboBox
            # poner el comboBox en esa formula.
            indexName = 'Otra'
            for key in self.formulas.keys():
                if (self.formulas[key]['c'] == c) &  (self.formulas[key]['h'] == h) & (self.formulas[key]['o'] == o):
                    indexName = key
            index = self.formula_comboBox.findText(indexName)
            self.formula_comboBox.setCurrentIndex(index)

            Fr = self.relacionMezcla.value()
            HVS, HVI, self.Q, self.lambda_s = PoderCalorifico.PoderCalorifico(c,h,o,s,Fr)
            self.HVS_lineEdit.setText('{:.1f}'.format(HVS))
            self.HVI_lineEdit.setText('{:.1f}'.format(HVS))
            self.calorQ.setText('{:.1f}'.format(self.Q))

    def seleccionAltura(self):
        p1 = str(self.presion1.text())
        t1 = str(self.temperatura1.text())
        dialogo = GUI_atmosfera_estandar.MainDialog(p1,t1)
        if dialogo.exec_():
            self.presion1.setText('{:.1f}'.format(dialogo.atmosfera['p']))
            self.temperatura1.setText('{:.1f}'.format(dialogo.atmosfera['t']))

# Genero ahora la función que va a realizar los calculos, es decir,
    # que va a llamar la función del ciclo. A esta le agrego una subclase de
    # Exception para capturar los valores de entrada negativos.
    class NumeroNegativo(Exception): pass

    def lecturadatos(self, lineedit, type):
        try:
            aux = 0
            if type == 'int':
                aux = int(lineedit.text())
            if type == 'float':
                aux = float(lineedit.text())
            if aux < 0:
                raise NumeroNegativoError
            return aux
        except (TypeError, ValueError, NumeroNegativoError):
            QMessageBox.warning(self,"Error en los datos de entrada! ","Vuelva a ingresar los datos")
            lineedit.selectAll()
            lineedit.setFocus()
            raise

    def Calculos(self):
        Q = self.Q
        # Lectura de los datos de entrada con la función verificacion
        try:
            p1 = self.lecturadatos(self.presion1, 'float')
            t1 = self.lecturadatos(self.temperatura1, 'float')
            variableExtra1 = self.selecDatoExtra1.currentText().split("  ")[0]
            datoExtra1 = self.lecturadatos(self.datoExtra1, 'float')
            variableExtra2 = self.selecDatoExtra2.currentText().split("  ")[0]
            datoExtra2 = self.lecturadatos(self.datoExtra2, 'float')
            self.puntos, resultados = ciclo_sabathe.CicloSabathe(p1, t1, Q * 1000, variableExtra1, datoExtra1,
                                                                 variableExtra2, datoExtra2)

        except MayorAUnoError as e:
            QMessageBox.warning(self, "Error en los datos de entrada! ",
                                "La variable " + str(e.variableName) + " no puede ser menor a 1")
            if e.variableName == 'r_comp':
                self.datoExtra1.selectAll()
                self.datoExtra1.setFocus()
            elif e.variableName == 'Alpha':
                self.datoExtra2.selectAll()
                self.datoExtra2.setFocus()
            else:
                pass

        except TemperaturaIncompatibleError as e:
            QMessageBox.warning(self, "Error en los datos de entrada! ",
                                "La temperatura " + str(e.variableName) + " no puede ser menor a la " + \
                                "temepratura del estado anterior (" + str(e.value) + " K)")
            self.datoExtra1.selectAll()
            self.datoExtra1.setFocus()

        except Var2IncompatibleError as e:
            QMessageBox.warning(self, "Error en los datos de entrada!",
                                e.varname + " no puede ser mayor a " + str(e.value1) + \
                                ", ni menor a = " + str(e.value2))
            self.datoExtra2.selectAll()
            self.datoExtra2.setFocus()





        else:
            self.plotCiclo(self.puntos)

            self.calor2.setText(str(resultados[0]))
            self.calorU.setText(str(resultados[1]))
            self.trabajoW.setText(str(resultados[2]))
            self.presionMedia.setText(str(resultados[3]))
            self.rendimiento.setText(str(resultados[4]))

    def plotCiclo(self,puntos):
        presion = []
        temperatura = []
        densidad = []
        volumen = []
        entropia = []
        for punto in puntos:
            presion.append(punto[0])
            temperatura.append(punto[1])
            densidad.append(punto[2])
            volumen.append(punto[3])
            entropia.append(punto[4])

        v1 = np.append(np.arange(volumen[1],volumen[0],(volumen[0]-volumen[1])/100),volumen[0])
        v2 = np.append(np.arange(volumen[3],volumen[4],(volumen[4]-volumen[3])/100),volumen[4])
        self.axes1.clear()
        self.axes1.plot(v1,presion[1]*volumen[1]**self.gamma_aire*(1/v1**self.gamma_aire),'r')
        self.axes1.plot(volumen[1:4],presion[1:4],'r',(volumen[4],volumen[0]),(presion[4],presion[0]),'r')
        self.axes1.plot(v2,presion[3]*volumen[3]**self.gamma_aire*(1/v2**self.gamma_aire),'r')
        self.canvas1.draw()

        S1 = np.append(np.arange(entropia[1],entropia[2],(entropia[2]-entropia[1])/100),entropia[2])
        S2 = np.append(np.arange(entropia[2],entropia[3],(entropia[3]-entropia[2])/100),entropia[3])
        S3 = np.append(np.arange(entropia[4],entropia[0],(entropia[0]-entropia[4])/100),entropia[0])

        self.axes2.clear()
        self.axes2.plot(S1,temperatura[1]*np.exp((self.gamma_aire-1)*(S1-entropia[1])/self.R_aire),'r')
        self.axes2.plot(S2,temperatura[2]*np.exp((self.gamma_aire-1)*(S2-entropia[2])/self.R_aire/self.gamma_aire),'r')
        self.axes2.plot(entropia[0:2],temperatura[0:2],'r',entropia[3::],temperatura[3::],'r')
        self.axes2.plot(S3,temperatura[4]*np.exp((self.gamma_aire-1)*(S3-entropia[4])/self.R_aire),'r')
        self.canvas2.draw()

    def displayMatrix(self):
        matriz = MatrixDialog(self.puntos)
        matriz.exec_()
예제 #33
0
class MatplotlibPlot:
    """ Class encapsulating an matplotlib plot """

    def __init__(self, parent = None, dpi = 100, size = (5,4)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(dpi = self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

    def plotCurve(self, data, numCurves = 1, labels = None, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = ""):
        """ Normal plots """

        self.figure.clear()
        self.axes = self.figure.add_subplot(111)        
        self.axes.grid(True)

        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        # Place all plots in axes
        for i in range(numCurves):
            self.axes.plot(data[:,i], label=labels[i])
            self.axes.set_xlim((0, len(data[:,i])))

        # Final touches
        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.canvas.draw()

    def subplotCurve(self, data, numPlots = 1, labels = None, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = ""):
        """ Subplot mode """

        self.figure.clear()
  
        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        if numPlots == 1:
            ax = self.figure.add_subplot(111)
            ax.plot(data[:])
            ax.set_xlabel(xLabel)
            ax.set_ylabel(yLabel)
            ax.set_title(labels[0])   
            ax.grid(True)         
        else:
            # Plot each image
            num_rows = ceil(sqrt(numPlots))
            for i in range(numPlots):
                ax = self.figure.add_subplot(num_rows, num_rows, i + 1)
                ax.plot(data[:,i])
                ax.set_xlim((0, len(data[:,i])))
                ax.set_xlabel(xLabel)
                ax.set_ylabel(yLabel)
                ax.set_title(labels[i])
                ax.grid(True)

        # Final touches
        self.figure.tight_layout()
        self.canvas.draw()


    def plotImage(self, data, numImages = 1, labels = None, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = ""):
        """ Image plot """

        self.figure.clear()
        self.axes = self.figure.add_subplot(111)        

        # Show image
        im = self.axes.imshow(data, origin='lower', aspect='auto')
    
        # Final touches
        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.figure.colorbar(im)
        self.canvas.draw()

    def subplotImage(self, data, numImages = 1, labels = None, xAxisRange = None, yAxisRange = None, xLabel = "", yLabel = ""):
        """ Image subplot """

        # Clear figure
        self.figure.clear()

        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        # Plot each image
        num_rows = ceil(sqrt(numImages))
        for i in range(numImages):
            ax = self.figure.add_subplot(num_rows, num_rows, i + 1)        
            im = ax.imshow(data[:,:,i],  origin='lower', aspect='auto')            
            ax.set_xlabel(xLabel)
            ax.set_ylabel(yLabel)
            ax.set_title(labels[i])

        # Final touches
        self.figure.tight_layout()
        self.canvas.draw()
class Window(QtGui.QDialog):
    def __init__(self, parent=None):

        super(Window, self).__init__(parent)

        #self.setGeometry(300, 100, 800, 600)
        # distance from sx, from top, length, heigth

        self.showMaximized()

        self.figure, ((self.ax1, self.ax2), (self.ax3,
                                             self.ax4)) = plt.subplots(2, 2)

        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.button = QtGui.QPushButton('Browse')
        self.button.clicked.connect(self.browse)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)
        #self.ax = self.figure.add_subplot(111)

        self.span1 = SpanSelector(self.ax1,
                                  self.extremes1,
                                  'horizontal',
                                  useblit=True,
                                  rectprops=dict(alpha=0.5, facecolor='green'))

        self.span2 = SpanSelector(self.ax2,
                                  self.extremes2,
                                  'horizontal',
                                  useblit=True,
                                  rectprops=dict(alpha=0.5, facecolor='green'))

        self.span3 = SpanSelector(self.ax3,
                                  self.extremes3,
                                  'horizontal',
                                  useblit=True,
                                  rectprops=dict(alpha=0.5, facecolor='green'))

        self.span4 = SpanSelector(self.ax4,
                                  self.extremes4,
                                  'horizontal',
                                  useblit=True,
                                  rectprops=dict(alpha=0.5, facecolor='green'))

    def extremes1(self, xmin, xmax):

        return xmin, xmax

    def extremes2(self, xmin, xmax):

        return xmin, xmax

    def extremes3(self, xmin, xmax):

        return xmin, xmax

    def extremes4(self, xmin, xmax):

        return xmin, xmax

    def browse(self):

        fName = QtGui.QFileDialog.getOpenFileName(
            self, 'Browse file', "Open new file",
            self.tr("All Files (*);;Text Files (*txt)"))

        if fName.isEmpty() == False:
            self.fileLocation = fName

            self.ax1.clear()
            self.ax2.clear()
            self.ax3.clear()
            self.ax4.clear()

            self.printSig()

    def printSig(self):

        import Signals as ss
        import PreAllinea

        segnali = ss.Signals(str(self.fileLocation))
        lista_segnali = []
        shift = PreAllinea.getShift()

        for i in range(24):

            if i < 8:

                segnale = segnali.SigData(i)
                lista_segnali.append(segnale)
                lista_segnali[i].SigShift(shift[i])
                self.ax1.plot(segnale.x, segnale.SigFir(10))
                self.ax1.set_xlim(1000, 2300)
                self.ax1.set_ylim(1e-1, 100000)

            elif (i > 7 and i < 16):

                segnale = segnali.SigData(i)
                lista_segnali.append(segnale)
                lista_segnali[i].SigShift(shift[i])
                self.ax2.plot(segnale.x, segnale.SigFir(10))
                self.ax2.set_xlim(1000, 2300)
                self.ax2.set_ylim(1e-1, 100000)

            elif (i > 15 and i < 24):

                segnale = segnali.SigData(i)
                lista_segnali.append(segnale)
                lista_segnali[i].SigShift(shift[i])
                self.ax3.plot(segnale.x, segnale.SigFir(10))
                self.ax3.set_xlim(1000, 2300)
                self.ax3.set_ylim(1e-1, 100000)

            else:

                segnale = segnali.SigData(i)
                lista_segnali.append(segnale)
                lista_segnali[i].SigShift(shift[i])
                self.ax4.plot(segnale.x, segnale.SigFir(10))
                self.ax4.set_xlim(1000, 2300)
                self.ax4.set_ylim(1e-1, 100000)

        self.ax1.semilogy()
        self.ax2.semilogy()
        self.ax3.semilogy()
        self.ax4.semilogy()

        self.canvas.show()
예제 #35
0
class MainDialog(QDialog, layout.Ui_Dialog):

    def __init__(self, parent=None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)
        self.AIRFOIL_DATA = None

        # Generamos dos figuras, cada una luego asociada a un canvas, que a su vez tiene como padre una de las pestanias
        # self.tab -> contiene la pestania titulada "Diagrama P-S"
        # self.tab_2 -> contiene la pestania titulada "Diagrama T-S"
        self.fig1 = Figure(figsize=(4.8, 3.4), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.axes1 = self.fig1.add_subplot(111)
        self.axes1.set_ylabel('Cl')
        self.axes1.set_xlabel('AoA')
        self.fig2 = Figure(figsize=(4.8, 3.4), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.axes2 = self.fig2.add_subplot(111)
        self.axes2.set_ylabel('Cd')
        self.axes2.set_xlabel('Cl')
        # generate the canvas to display the plot
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setParent(self.frame_ClAlpha)
        self.canvas1.show()
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.setParent(self.frame_CdCl)
        self.canvas2.show()
        #Ponemos el primer checkbox en "checked"
        self.checkBox_Re3.setCheckState(Qt.Checked)
        # Cargamos los numeros de Reynolds
        self.Reynolds = ['Re_3', 'Re_6', 'Re_9', 'Re_std']
        # Cargamos los parametros caracteristicos del perfil
        self.vHeader = ['CL_max', 'beta_max',
                    'CL_betamax', 'alpha_betamax', 'dbeta_dalpha', 'b_max',
                    'CD_min', 'CL_CD_max', 'cuspide', 'CM0']
        # Cargamos el formato en que se deben mostrar cada parametro caracteristico
        self.HeadersFormat = ['{:.2f}', '{:.1f}', '{:.2f}', '{:.1f}', '{:.3f}', '{:.1f}',
                              '{:.5f}', '{:.1f}', str, '{:.2}']
        self.tableDatos.setVerticalHeaderLabels(self.vHeader)
        self.tableDatos.setHorizontalHeaderLabels(self.Reynolds)


        self.connect(self.openButton, SIGNAL("clicked()"), self.Open)
        self.connect(self.okButton, SIGNAL("clicked()"), self, SLOT('accept()'))
        self.connect(self.cancelButton, SIGNAL("clicked()"), self, SLOT('reject()'))
        self.connect(self.checkBox_Re3, SIGNAL("toggled(bool)"), self.plotGraph)
        self.connect(self.checkBox_Re6, SIGNAL("toggled(bool)"), self.plotGraph)
        self.connect(self.checkBox_Re9, SIGNAL("toggled(bool)"), self.plotGraph)
        self.connect(self.checkBox_SR, SIGNAL("toggled(bool)"), self.plotGraph)

    def Open(self):
        dir = '.'
        fileAdress = QFileDialog.getOpenFileName(self,"Selecionar Perfil",dir,filter="Text File (*.txt)")
        self.AIRFOIL_DATA = profile.lectura_perfiles(fileAdress[0])
        #print self.AIRFOIL_DATA

        for j in range(len(self.Reynolds)):
            for i in range(len(self.vHeader)):
                if self.vHeader[i] in self.AIRFOIL_DATA[self.Reynolds[j]].keys():
                    item = QTableWidgetItem(self.HeadersFormat[i].format(self.AIRFOIL_DATA[self.Reynolds[j]][self.vHeader[i]]))
                    self.tableDatos.setItem(i, j, item)
        nombrePerfil = fileAdress[0].split('/')[-1].split('.')[0]
        #print nombrePerfil
        self.labelPerfil.setText('Datos Perfil:  NACA '+nombrePerfil)
        self.plotGraph()

    def plotGraph(self):
        self.axes1.clear()
        self.axes2.clear()

        if self.checkBox_Re3.isChecked():
            self.plotReynolds('Re_3', 'b')

        if self.checkBox_Re6.isChecked():
            self.plotReynolds('Re_6', 'r')

        if self.checkBox_Re9.isChecked():
            self.plotReynolds('Re_9', 'g')

        if self.checkBox_SR.isChecked():
            self.plotReynolds('Re_std', 'y')

        self.canvas1.draw()
        self.canvas2.draw()

    def plotReynolds(self, reynolds, color):
        x1 = [value[0] for value in self.AIRFOIL_DATA[reynolds]['AoA_Cl']]
        y1 = [value[1] for value in self.AIRFOIL_DATA[reynolds]['AoA_Cl']]
        x2 = [value[0] for value in self.AIRFOIL_DATA[reynolds]['Cl_Cd']]
        y2 = [value[1] for value in self.AIRFOIL_DATA[reynolds]['Cl_Cd']]
        self.axes1.plot(x1, y1, color)
        self.axes2.plot(x2, y2, color)
예제 #36
0
파일: Plot.py 프로젝트: PaulPrice/ginga
class Plot(Callback.Callbacks):

    def __init__(self, logger):
        Callback.Callbacks.__init__(self)

        self.logger = logger

        # For callbacks
        for name in ('close', ):
            self.enable_callback(name)

        self.fig = matplotlib.figure.Figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_xlabel('X values')
        self.ax.set_ylabel('Y values')
        self.ax.set_title('')
        self.ax.grid(True)
        self.canvas = FigureCanvas(self.fig)

    def get_widget(self):
        return self.canvas
    
    def _sanity_check_window(self):
        pass

    def set_titles(self, xtitle=None, ytitle=None, title=None,
                   rtitle=None):
        self._sanity_check_window()
        if xtitle != None:
            self.ax.set_xlabel(xtitle)
        if ytitle != None:
            self.ax.set_ylabel(ytitle)
        if title != None:
            self.ax.set_title(title)
        if rtitle != None:
            pass

    def clear(self):
        self._sanity_check_window()
        self.logger.debug('clearing canvas...')
        self.ax.cla()

    def show(self):
        self._sanity_check_window()
        self.logger.debug('raising window...')
        self.canvas.show()

    def hide(self):
        self._sanity_check_window()
        self.logger.debug('hiding window...')
        pass

    def close(self):
        self.logger.debug('closing window....')
        self.canvas.destroy()

        self.make_callback('close')
        return False

    def _draw(self):
        self.fig.canvas.draw()

    def plot(self, xarr, yarr, xtitle=None, ytitle=None, title=None,
             rtitle=None, **kwdargs):
        self.set_titles(xtitle=xtitle, ytitle=ytitle, title=title,
                        rtitle=rtitle)
        self.ax.plot(xarr, yarr, **kwdargs)
        self.ax.grid(True)
        self._draw()
예제 #37
0
class mGraph(QtGui.QWidget):
    def __init__(self, device, parent=None):
        QtGui.QWidget.__init__(self, parent)
        # Create a matplotlib figure.
        self.figure = plt.figure()
        self.figure.set_facecolor('r')
        # Create a QFrame to house the plot. This is not necessary,
        # just makes it look nice.
        self.matframe = QtGui.QFrame()
        self.matLayout = QtGui.QVBoxLayout()
        self.matLayout.setSpacing(0)
        self.matframe.setLayout(self.matLayout)
        self.matframe.setFrameShape(QtGui.QFrame.Panel)
        self.matframe.setFrameShadow(QtGui.QFrame.Plain)
        self.matframe.setStyleSheet(
            "background-color: rgb(70,80,88); "
            "margin:0px; border:2px solid rgb(0, 0, 0); ")
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                  QtGui.QSizePolicy.Preferred)
        # This is the device we want to use.
        self.device = device
        # This sets up axis on which to plot.
        color = (189. / 255, 195. / 255, 199. / 255)
        self.ax = self.figure.add_subplot(111, axisbg=color)
        ax = self.ax
        # Add the matplotlib canvas to the QFrame.
        self.matLayout.addWidget(self.canvas)
        # The following lines set up all the colors, makes it look nice.
        # The code to do it is far from pretty and I am planning
        # on cleaning this up a bit.
        self.figure.patch.set_color((70. / 255, 80. / 255, 88. / 255))
        self.figure.patch.set_edgecolor((70. / 255, 80. / 255, 88. / 255))
        ax.spines['bottom'].set_color(color)
        ax.spines['top'].set_color(color)
        ax.spines['right'].set_color(color)
        ax.spines['left'].set_color(color)
        ax.tick_params(axis='x', colors=color)
        ax.tick_params(axis='y', colors=color)
        ax.title.set_color(color)
        ax.yaxis.label.set_color(color)
        ax.xaxis.label.set_color(color)
        ax.xaxis.get_offset_text().set_color(color)
        ax.yaxis.get_offset_text().set_color(color)
        # This is an array of all the lines on the plot. A line for
        # every parameter.
        self.line = []
        self.mins = 0
        self.maxes = 1
        # Each element of line holds a plot, to be combined onto
        # the same graph.
        self.line.append(ax.plot(1, 1, label="Getting Data...")[0])

        # In order to handle interactivity, I had to do some odd stuff
        # with the toolbar buttons: self.home holds the original
        # function called when the home button on the toolbar
        # is clicked.
        self.home = NavigationToolbar.home
        # We now change the function that is called when the toolbar is
        # clicked.
        NavigationToolbar.home = self.enableAutoScaling
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.cid = self.canvas.mpl_connect('button_press_event',
                                           self.disableAutoScaling)
        self.setStyleSheet("QPushButton{\
                    color:rgb(189,195, 199); \
                    background:rgb(70, 80, 88)};")
        self.fullGraphBtn = QtGui.QPushButton("Show Interactive Graph")
        self.fullGraphBtn.clicked.connect(self.openFullGraphGui)
        self.toolbarFrame = QtGui.QFrame()
        toolbarFrameLayout = QtGui.QVBoxLayout()
        toolbarFrameLayout.addWidget(self.toolbar)
        self.toolbar.setParent(None)
        self.toolbarFrame.setLayout(toolbarFrameLayout)
        self.toolbarFrame.setStyleSheet("\
                   border:2px solid rgb(0,0,0);\
                   color:rgb(189,195,199); \
                   background:rgb(70, 80, 88);")
        self.toolbar.setStyleSheet("\
                   border:0px solid rgb(0,0,0);\
                   QDialog{background:rgb(70, 80, 88)}")
        self.matPlotInfo = QtGui.QLabel()
        self.alertFont = QtGui.QFont()
        self.alertFont.setPointSize(12)
        self.matPlotInfo.setStyleSheet("color:rgb(200, 69, 50);")
        self.matPlotInfo.setText("Auto refresh disabled, "
                                 "click HOME button to enable.")
        self.matPlotInfo.setFont(self.alertFont)

        #self.refreshRateSec = device.getFrame().getPlotRefreshRate()
        self.refreshRateSec = device.getFrame().getPlotRefreshRate()
        self.timer = QtCore.QTimer(self)

        self.hidden = True
        self.home = True
        self.initialized = False
        self.currTimeRange = 120
        self.lineSelect = MCheckableComboBox()
        self.lineSelect.setSizeAdjustPolicy(0)
        self.lineSelect.setStyleSheet("\
                    background-color:rgb(70, 80, 88);\
                    color:rgb(189,195, 199);")
        self.plot(self.currTimeRange)

        self.timer.timeout.connect(partial(self.plot, self.currTimeRange))
        self.timer.start(self.refreshRateSec * 1000)

        # Did it store data?
        self.dataOk = True
        self.hideButton = QtGui.QPushButton("Show Plot")
        self.hideButton.clicked.connect(self.togglePlot)
        self.oneMinButton = QtGui.QPushButton("1 min")
        self.oneMinButton.clicked.connect(partial(self.plot, 60))
        self.tenMinButton = QtGui.QPushButton("10 min")
        self.tenMinButton.clicked.connect(partial(self.plot, 600))
        self.twoHrButton = QtGui.QPushButton("2 hr")
        self.twoHrButton.clicked.connect(partial(self.plot, 7200))
        self.twelveHrButton = QtGui.QPushButton("12 hr")
        self.twelveHrButton.clicked.connect(partial(self.plot, 43200))
        self.threeDayButton = QtGui.QPushButton("3 day")
        self.threeDayButton.clicked.connect(partial(self.plot, 259200))
        self.oneWkButton = QtGui.QPushButton("1 week")
        self.oneWkButton.clicked.connect(partial(self.plot, 604800))
        self.allButton = QtGui.QPushButton("All Time")
        self.allButton.clicked.connect(partial(self.plot, None))

        self.canvas.hide()
        self.toolbar.hide()

        # Set the layout.
        buttonLayout1 = QtGui.QHBoxLayout()
        buttonLayout1.addWidget(self.hideButton)
        buttonLayout1.addWidget(self.fullGraphBtn)
        buttonLayout1.addStretch(0)
        buttonLayout2 = QtGui.QHBoxLayout()
        settingsbuttons1 = QtGui.QHBoxLayout()

        buttonLayout2.addWidget(self.oneMinButton)
        buttonLayout2.addWidget(self.tenMinButton)
        buttonLayout2.addWidget(self.twoHrButton)
        buttonLayout2.addWidget(self.twelveHrButton)
        buttonLayout2.addWidget(self.threeDayButton)
        buttonLayout2.addWidget(self.oneWkButton)
        buttonLayout2.addWidget(self.allButton)
        buttonLayout2.addStretch(0)
        self.oneMinButton.hide()
        self.tenMinButton.hide()
        self.twoHrButton.hide()
        self.twelveHrButton.hide()
        self.threeDayButton.hide()
        self.oneWkButton.hide()
        self.allButton.hide()
        self.lineSelect.hide()
        self.matframe.hide()
        self.matPlotInfo.hide()
        self.toolbarFrame.hide()

        settingsbuttons1.addWidget(self.lineSelect)
        layout = QtGui.QVBoxLayout()
        allButtonsLayout = QtGui.QHBoxLayout()
        timeButtonsLayout = QtGui.QVBoxLayout()
        allButtonsLayout.addLayout(timeButtonsLayout)
        layout.addLayout(allButtonsLayout)
        allButtonsLayout.addLayout(settingsbuttons1)
        timeButtonsLayout.addLayout(buttonLayout1)
        timeButtonsLayout.addLayout(buttonLayout2)
        timeButtonsLayout.addWidget(self.matPlotInfo)
        layout.addWidget(self.matframe)
        layout.addWidget(self.toolbarFrame)

        self.setLayout(layout)

    def enableAutoScaling(self):
        self.timer.start(self.refreshRateSec * 1000)
        self.home = True
        self.matPlotInfo.hide()
        self.plot(self.currTimeRange)

    def disableAutoScaling(self, event):
        self.home = False
        self.matPlotInfo.show()
        self.canvas.update()
        self.timer.stop()

    def togglePlot(self):
        if not self.hidden:
            self.canvas.hide()
            self.toolbar.hide()
            self.oneMinButton.hide()
            self.tenMinButton.hide()
            self.twoHrButton.hide()
            self.twelveHrButton.hide()
            self.threeDayButton.hide()
            self.oneWkButton.hide()
            self.allButton.hide()
            self.matPlotInfo.hide()
            self.matframe.hide()
            self.lineSelect.hide()
            self.toolbarFrame.hide()
            self.timer.stop()
            self.hideButton.setText("Show Plot")
            self.hidden = True
        elif self.hidden:
            self.canvas.show()
            self.toolbar.show()
            self.oneMinButton.show()
            self.tenMinButton.show()
            self.twoHrButton.show()
            self.twelveHrButton.show()
            self.threeDayButton.show()
            self.oneWkButton.show()
            self.allButton.show()
            self.plot(self.currTimeRange)
            self.matframe.show()
            self.lineSelect.show()
            self.toolbarFrame.show()
            self.timer.start(self.refreshRateSec * 1000)
            self.hideButton.setText("Hide Plot")
            self.enableAutoScaling()
            self.hidden = False

    def initializePlot(self, dataSet):
        if dataSet:
            varNames = dataSet.getVariables()
            varNames = [varNames[1][i][0] for i in range(len(varNames[1]))]
            self.dropdownFont = QtGui.QFont()
            self.dropdownFont.setPointSize(12)
        if dataSet is not None:
            self.initialized = True
            self.line[0].remove()
            self.line = []

            for i in range(len(varNames)):
                self.line.append(self.ax.plot(1, 1, label=varNames[i])[0])
                text = QtCore.QString(varNames[i])
                self.lineSelect.addItem(text)
                self.lineSelect.setFont(self.dropdownFont)
                self.lineSelect.setChecked(i, True)

    def changeIndependenVarRange(self, timeRange):
        if not self.hidden:
            if timeRange != self.currTimeRange:
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(
                    lambda: self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)
            plotRefreshRate = self.device.getFrame().getPlotRefreshRate()
            if self.refreshRateSec != plotRefreshRate:
                self.refreshRateSec = plotRefreshRate
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(
                    lambda: self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)

    def getDataRangeFromDataSet(self, dataSet, time):
        if dataSet:
            data = dataSet.getData()
            i = len(data) - 1
            if time:
                while data[i][0] > (data[-1][0] - time):
                    i -= 1
                    if -1 * i > len(data):
                        return data
                data = data[i:-1]
            return data
        else:
            return None

    def openFullGraphGui(self):
        # print "opening full graph gui."
        dataSet = self.device.getFrame().getDataSet().getData()
        # print dataSet
        times = [dt.datetime.fromtimestamp(elem[0]) for elem in dataSet]
        vars = self.device.getFrame().getDataSet().getVariables()

        self.fullgraphcont = fullGraphContainer(times, vars, dataSet)
        self.fullgraphcont.show()

    def plot(self, time):
        times = None
        self.changeIndependenVarRange(time)
        dataSet = self.device.getFrame().getDataSet()

        if not self.initialized:
            self.initializePlot(dataSet)
            self.legend = self.ax.legend(loc='upper left')
            # This is the ONLY time canvas.draw is called. It should
            # NOT be called anywhere else if the graphing speed is
            # to be fast.
            self.canvas.draw()
        else:
            data = self.getDataRangeFromDataSet(dataSet, time)
            for i in range(len(data[0]) - 1):
                if self.lineSelect.isChecked(i):
                    times = [dt.datetime.fromtimestamp(row[0]) for row in data]
                    column = [row[i + 1] for row in data]
                    if not self.line[i].get_visible():
                        self.line[i].set_visible(True)
                    self.line[i].set_data(times, column)
                    self.legend = self.ax.legend(loc='upper left')
                    self.ax.grid(True)
                    self.ax.hold(True)
                else:
                    self.line[i].set_visible(False)
                pass
            self.ax.set_title(self.device.getFrame().getTitle(),
                              color=(189. / 255, 195. / 255, 199. / 255))
            if self.home and times:
                self.ax.set_xlim(times[0], times[-1])
                self.ax.relim(visible_only=True)
                self.ax.autoscale(axis='y')

            frame = self.device.getFrame()
            yLabel = frame.getYLabel()
            if yLabel is not None:
                if frame.getCustomUnits():
                    self.ax.set_ylabel("%s (%s)" %
                                       (yLabel, frame.getCustomUnits()))
                elif frame.getUnits()[i - 1]:
                    self.ax.set_ylabel("%s (%s)" %
                                       (yLabel, frame.getUnits()[i - 1]))

            locator = AutoDateLocator()

            self.ax.xaxis.set_major_locator(locator)
            self.ax.xaxis.set_major_formatter(DateFormatter('%m/%d %H:%M:%S'))
            self.figure.autofmt_xdate()
            self.ax.draw_artist(self.figure)
            self.ax.draw_artist(self.ax.patch)
            self.ax.draw_artist(self.ax.yaxis)
            self.ax.draw_artist(self.ax.xaxis)

            for i, line in enumerate(self.line):
                self.ax.draw_artist(line)

            self.ax.set_xlabel("Time")
            self.ax.draw_artist(self.legend)

            self.canvas.update()

            self.canvas.flush_events()
예제 #38
0
class Load_win_fn(QtGui.QWidget):
    """The class for loading and processing images"""
    def __init__(self,par_obj,win):
        super(Load_win_fn, self).__init__()
        #Vertical layout
        vbox = QtGui.QVBoxLayout()
        self.setLayout(vbox)
        hbox0 = QtGui.QHBoxLayout()
        vbox.addLayout(hbox0)

        #Load images button
        self.loadImages_button = QtGui.QPushButton("Load Images", self)
        hbox0.addWidget(self.loadImages_button)
        hbox0.addStretch()

        
        about_btn = QtGui.QPushButton('About')
        about_btn.clicked.connect(self.on_about)
        hbox0.addWidget(about_btn)

        #Load button.
        self.Text_CHopt = QtGui.QLabel()
        vbox.addWidget(self.Text_CHopt)
        self.ex = fileDialog(self)
        self.loadImages_button.clicked.connect(self.ex.showDialog)
        
        
        #SigmaData input field.
        self.feature_scale_input = QtGui.QLineEdit(str(par_obj.feature_scale))
        #SigmaData input Text.
        self.feature_scaleText = QtGui.QLabel()
        
        hbox1 = QtGui.QHBoxLayout()
        vbox.addWidget(self.feature_scaleText)
        vbox.addLayout(hbox1)
        
        
        self.feature_scaleText.resize(40,20)
        self.feature_scaleText.setText('Input sigma for feature calculation default (0.8):')
        self.feature_scaleText.hide()

        hbox1.addWidget(self.feature_scale_input)
        hbox1.addStretch()
        
        self.feature_scale_input.resize(10,10)
        self.feature_scale_input.textChanged[str].connect(self.feature_scale_change)
        self.feature_scale_input.hide()

        
        
        CH_pX = 0
        CH_pY = 50

        #Channel dialog generation.
        
        vbox.addWidget(self.Text_CHopt)
        self.Text_CHopt.setText('Please select which channels you want to include in the training:')
        self.Text_CHopt.resize(500,40)
        self.Text_CHopt.hide()

        
        hbox2 = QtGui.QHBoxLayout()           
        #Object factory for channel selection.
        for i in range(0,10):
            name = 'self.CH_cbx'+str(i+1)+'_txt = QtGui.QLabel()'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'_txt.setText(\'CH '+str(i+1)+':\')'
            exec(name)
            name = 'hbox2.addWidget(self.CH_cbx'+str(i+1)+'_txt)'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'_txt.hide()'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'= checkBoxCH()'
            exec(name)
            name = 'hbox2.addWidget(self.CH_cbx'+str(i+1)+')'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'.hide()'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'.setChecked(True)'
            exec(name)
            name = 'self.CH_cbx'+str(i+1)+'.type =\'feature_ch\''
            exec(name)
        hbox2.addStretch()
        vbox.addLayout(hbox2)


        self.figure1 = Figure(figsize=(2,2))
        self.canvas1 = FigureCanvas(self.figure1)
        

        #self.figure1.patch.set_facecolor('white')
        self.plt1 = self.figure1.add_subplot(1,1,1)
        self.resize(100,100)
        self.canvas1.hide()
        self.figure1.subplots_adjust(left=0.001, right=0.999, top=0.999, bottom=0.001)
        self.plt1.set_xticklabels([])
        self.plt1.set_yticklabels([])
        
        hbox3 = QtGui.QHBoxLayout()
        vbox.addLayout(hbox3)
        hbox3.addWidget(self.canvas1)
        hbox3.addStretch()

        #Channel dialog generation.
        self.Text_FrmOpt2 = QtGui.QLabel()
        vbox.addWidget(self.Text_FrmOpt2)
        self.Text_FrmOpt2.hide()

        #Image frames dialog.
        Text_FrmOpt1_panel = QtGui.QHBoxLayout()
        self.Text_FrmOpt1 = QtGui.QLabel()
        self.Text_FrmOpt1.setText('Please choose the frames you wish to use for training. Use either \',\' to separate individual frames or a \'-\' to indicate a range:')
        self.Text_FrmOpt1.hide()
        Text_FrmOpt1_panel.addWidget(self.Text_FrmOpt1)
        vbox.addLayout(Text_FrmOpt1_panel)

        #Image frames input.
        linEdit_Frm_panel = QtGui.QHBoxLayout()
        self.linEdit_Frm = QtGui.QLineEdit()
        self.linEdit_Frm.hide()
        linEdit_Frm_panel.addWidget(self.linEdit_Frm)
        linEdit_Frm_panel.addStretch()
        vbox.addLayout(linEdit_Frm_panel)
        

        #Feature calculation to perform:
        self.Text_Radio = QtGui.QLabel()
        vbox.addWidget(self.Text_Radio)
        self.Text_Radio.setText('Feature select which kind of feature detection you would like to use:')
        self.Text_Radio.resize(500,40)
        self.Text_Radio.hide()
        self.radio_group=QtGui.QButtonGroup(self) # Number 
        self.r0 = QtGui.QRadioButton("Basic",self)
        self.r1 = QtGui.QRadioButton("Fine",self)
        
        self.r1.setChecked(True)
        self.radio_group.addButton(self.r0)
        self.radio_group.addButton(self.r1)
        
        vbox.addWidget(self.r0)
        vbox.addWidget(self.r1)
        
        self.r0.hide()
        self.r1.hide()
        vbox.addStretch()
        #Green status text.
        
        #Load images button
        hbox1 = QtGui.QHBoxLayout()
        vbox.addLayout(hbox1)
        self.confirmImages_button = QtGui.QPushButton("Confirm Images")
        hbox1.addWidget(self.confirmImages_button)
        self.confirmImages_button.clicked.connect(self.processImgs)
        self.confirmImages_button.setEnabled(False)
        #Move to training button.
        self.selIntButton = QtGui.QPushButton("Goto Training")
        hbox1.addWidget(self.selIntButton)
        self.selIntButton.clicked.connect(win.loadTrainFn)
        self.selIntButton.setEnabled(False)

        self.image_status_text = QtGui.QStatusBar()
        self.image_status_text.setStyleSheet("QLabel {  color : green }")
        self.image_status_text.showMessage('Status: Highlight training images in folder. ')
        vbox.addWidget(self.image_status_text)
        
        
        hbox1.addStretch()

       
        #File browsing functions
        layout = QtGui.QVBoxLayout() 
    def on_about(self):
        self.about_win = QtGui.QWidget()
        self.about_win.setWindowTitle('About QuantiFly Software v2.0')
        
        license = return_license()
        #with open (sys.path[0]+'/GNU GENERAL PUBLIC LICENSE.txt', "r") as myfile:
        #    data=myfile.read().replace('\n', ' ')
        #    license.append(data)
        
        # And give it a layout
        layout = QtGui.QVBoxLayout()
        
        self.view = QtWebKit.QWebView()
        self.view.setHtml('''
          <html>
            
         
            <body>
              <form>
                <h1 >About</h1>
                
                <p>Software written by Dominic Waithe (c) 2015</p>
                '''+str(license)+'''
                
                
              </form>
            </body>
          </html>
        ''')
        layout.addWidget(self.view)
        self.about_win.setLayout(layout)
        self.about_win.show()
        self.about_win.raise_()   

    def feature_scale_change(self,text):
        """Updates on change of feature scale"""
        par_obj.feature_scale = float(text)

    def updateAfterImport(self):
        """Specific to ui updates"""

        if par_obj.file_ext == 'tif' or par_obj.file_ext == 'tiff':
            if par_obj.tiff_file.maxFrames >1:
                self.linEdit_Frm.setText('1-'+str(par_obj.uploadLimit))
                self.Text_FrmOpt2.setText('There are '+str(par_obj.tiff_file.maxFrames+1)+' frames in total.')
                self.Text_FrmOpt1.show()
                self.Text_FrmOpt2.show()
                self.linEdit_Frm.show()

        self.confirmImages_button.setEnabled(True)
        
        self.plt1.cla()
        self.plt1.imshow(255-par_obj.ex_img)
        self.plt1.set_xticklabels([])
        self.plt1.set_yticklabels([])
        self.canvas1.show()
        self.canvas1.draw()
       
        
        par_obj.ch_active =[];
        if par_obj.numCH> 2:
            self.Text_CHopt.show()
            for i in range(0,par_obj.numCH):
                name = 'self.CH_cbx'+str(i+1)+'.show()'
                exec(name)
                name = 'self.CH_cbx'+str(i+1)+'_txt.show()'
                exec(name)
                par_obj.ch_active.append(i)
        else:
            par_obj.ch_active.append(0)
        
        self.feature_scale_input.show()
        self.feature_scaleText.show()
        self.r0.show()
        self.r1.show()
        self.Text_Radio.show()
    def hyphen_range(self,s):
        """ yield each integer from a complex range string like "1-9,12, 15-20,23"

        >>> list(hyphen_range('1-9,12, 15-20,23'))
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]

        >>> list(hyphen_range('1-9,12, 15-20,2-3-4'))
        Traceback (most recent call last):
            ...
        ValueError: format error in 2-3-4
        """
        for x in s.split(','):
            elem = x.split('-')
            if len(elem) == 1: # a number
                yield int(elem[0])
            elif len(elem) == 2: # a range inclusive
                start, end = map(int, elem)
                for i in xrange(start, end+1):
                    yield i
            else: # more than one hyphen
                raise ValueError('format error in %s' % x)


    def processImgs(self):
        """Loads images and calculates the features."""
        #Resets everything should this be another patch of images loaded.
        imgs =[]
        gt_im_sing_chgs =[]
        fmStr = self.linEdit_Frm.text()
        par_obj.feat_arr ={}
        par_obj.pred_arr ={}
        par_obj.sum_pred ={}
        par_obj.frames_2_load ={}
        par_obj.left_2_calc =[]
        par_obj.saved_ROI =[]
        par_obj.saved_dots=[]
        par_obj.curr_img = 0
        par_obj.eval_load_im_win_eval = False

        if self.r0.isChecked():
            par_obj.feature_type = 'basic'
        if self.r1.isChecked():
            par_obj.feature_type = 'fine'
   
        #Now we commit our options to our imported files.
        if par_obj.file_ext == 'png':
            for i in range(0,par_obj.file_array.__len__()):
                par_obj.left_2_calc.append(i)
                par_obj.frames_2_load[i] = [0]
            self.image_status_text.showMessage('Status: Loading Images. Loading Image Num: '+str(par_obj.file_array.__len__()))
                
            v2.im_pred_inline_fn(par_obj, self)
        elif par_obj.file_ext =='tiff' or par_obj.file_ext =='tif':
            if par_obj.tiff_file.maxFrames>1:
                for i in range(0,par_obj.file_array.__len__()):
                    par_obj.left_2_calc.append(i)
                    try:
                        np.array(list(self.hyphen_range(fmStr)))-1
                        par_obj.frames_2_load[i] = np.array(list(self.hyphen_range(fmStr)))-1
                    except:
                        self.image_status_text.showMessage('Status: The supplied range of image frames is in the wrong format. Please correct and click confirm images.')
                        return
                self.image_status_text.showMessage('Status: Loading Images.')
                v2.im_pred_inline_fn(par_obj, self)
               
            else:
                for i in range(0,par_obj.file_array.__len__()):
                    par_obj.left_2_calc.append(i)
                    par_obj.frames_2_load[i] = [0]
                v2.im_pred_inline_fn(par_obj, self)
        count = 0
        for b in par_obj.left_2_calc:
            frames =par_obj.frames_2_load[b]
            for i in frames:
                count = count+1
                
        par_obj.test_im_start= 0
        par_obj.test_im_end= count
        
        
        for i in par_obj.left_2_calc:
            im_array = np.zeros((par_obj.height,par_obj.width))
            par_obj.dense_array[i]=im_array
        
        self.image_status_text.showMessage('Status: Images loaded. Click \'Goto Training\'')
        self.selIntButton.setEnabled(True)
        par_obj.imgs = imgs
    def report_progress(self,message):
        self.image_status_text.showMessage('Status: '+message)
        app.processEvents()
예제 #39
0
class MatplotlibPlot:
    """ Class encapsulating an matplotlib plot """
    def __init__(self, parent=None, dpi=100, size=(5, 4)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(dpi=self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

    def plotCurve(self,
                  data,
                  numCurves=1,
                  labels=None,
                  xAxisRange=None,
                  yAxisRange=None,
                  xLabel="",
                  yLabel=""):
        """ Normal plots """

        self.figure.clear()
        self.axes = self.figure.add_subplot(111)
        self.axes.grid(True)

        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        # Place all plots in axes
        for i in range(numCurves):
            self.axes.plot(data[:, i], label=labels[i])
            self.axes.set_xlim((0, len(data[:, i])))

        # Final touches
        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.canvas.draw()

    def subplotCurve(self,
                     data,
                     numPlots=1,
                     labels=None,
                     xAxisRange=None,
                     yAxisRange=None,
                     xLabel="",
                     yLabel=""):
        """ Subplot mode """

        self.figure.clear()

        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        if numPlots == 1:
            ax = self.figure.add_subplot(111)
            ax.plot(data[:])
            ax.set_xlabel(xLabel)
            ax.set_ylabel(yLabel)
            ax.set_title(labels[0])
            ax.grid(True)
        else:
            # Plot each image
            num_rows = ceil(sqrt(numPlots))
            for i in range(numPlots):
                ax = self.figure.add_subplot(num_rows, num_rows, i + 1)
                ax.plot(data[:, i])
                ax.set_xlim((0, len(data[:, i])))
                ax.set_xlabel(xLabel)
                ax.set_ylabel(yLabel)
                ax.set_title(labels[i])
                ax.grid(True)

        # Final touches
        self.figure.tight_layout()
        self.canvas.draw()

    def plotImage(self,
                  data,
                  numImages=1,
                  labels=None,
                  xAxisRange=None,
                  yAxisRange=None,
                  xLabel="",
                  yLabel=""):
        """ Image plot """

        self.figure.clear()
        self.axes = self.figure.add_subplot(111)

        # Show image
        im = self.axes.imshow(data, origin='lower', aspect='auto')

        # Final touches
        self.axes.xaxis.set_label_text(xLabel)
        self.axes.yaxis.set_label_text(yLabel)
        self.figure.colorbar(im)
        self.canvas.draw()

    def subplotImage(self,
                     data,
                     numImages=1,
                     labels=None,
                     xAxisRange=None,
                     yAxisRange=None,
                     xLabel="",
                     yLabel=""):
        """ Image subplot """

        # Clear figure
        self.figure.clear()

        # Set empty labels if non defined
        if labels is None:
            labels = ['' for i in range(numImages)]

        # Plot each image
        num_rows = ceil(sqrt(numImages))
        for i in range(numImages):
            ax = self.figure.add_subplot(num_rows, num_rows, i + 1)
            im = ax.imshow(data[:, :, i], origin='lower', aspect='auto')
            ax.set_xlabel(xLabel)
            ax.set_ylabel(yLabel)
            ax.set_title(labels[i])

        # Final touches
        self.figure.tight_layout()
        self.canvas.draw()
예제 #40
0
class HomographyWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(HomographyWidget, self).__init__(parent)
        self._initUI()

    # Initialize the UI
    def _initUI(self):
        # Widget parameters
        self.setMinimumWidth(300)

        # Create the figure
        self._fig = Figure()

        # Canvas configuration
        self._canvas = FigureCanvas(self._fig)
        self._canvas.setParent(self)
        self._canvas.mpl_connect('button_press_event', self._onPick)

        # Plot configuration
        self._plt = self._fig.add_subplot(111)
        self._plt.xaxis.set_visible(False)
        self._plt.yaxis.set_visible(False)

        # Finalize figure
        self._fig.subplots_adjust(wspace=0, hspace=0)

        # Reset the variables
        self.reset()

        # Create the layout
        vbox = QtGui.QVBoxLayout()

        # Add Canvas to the layout
        vbox.addWidget(self._canvas)

        # Set the layout
        self.setLayout(vbox)

        zp = ZoomPan()
        figZoom = zp.zoom_factory(self._plt)
        figPan = zp.pan_factory(self._plt)

    # Reset the variables to original state
    def reset(self):
        self._image = None
        self._render = None
        self._points = []
        self._lastPoints = []
        self._canvas.hide()

    # Set an image to the widget
    def setImage(self, image):
        self._image = image
        self._render = image
        self._canvas.show()
        self._redraw()

    # Get the image of the widget
    def getImage(self):
        pass

    def setHomography(self, points):
        # Save points
        self._lastPoints = points

        # Redraw canvas
        self._redraw()

    # Redraw the image and points
    def _redraw(self):
        # Clear the canvas
        self._plt.clear()

        if len(self._points) == 2 and len(self._lastPoints) == 4:
            # Get points
            src = self._pointsToVector(self._lastPoints)
            dest = self._pointsToVector(self._rectangle())

            # Compute Transformation
            self._projective = ProjectiveTransform()
            self._projective.estimate(src, dest)

            # Prepare output image
            self._render = warp(self._image, self._projective.inverse)

        # Plot the image
        if self._render is not None:
            self._plt.autoscale(True)
            self._plt.imshow(self._render)
            self._plt.autoscale(False)

        # Plot the points
        if len(self._points) > 0:
            xs = [x for (x, _) in self._rectangle()]
            ys = [y for (_, y) in self._rectangle()]
            self._plt.plot(xs + [xs[0]], ys + [ys[0]], '-', color='green')

            xs = [x for (x, _) in self._points]
            ys = [y for (_, y) in self._points]
            self._plt.plot(xs + [xs[0]], ys + [ys[0]], 'o', color='blue')

        # Draw the canvas
        self._canvas.draw()

    # Handle click events
    def _onPick(self, event):

        if event.button == 3:
            self._redraw()
        elif event.button != 1:
            return

        # Get point position
        x = event.xdata
        y = event.ydata

        if x is None or y is None:
            return

        # For each existing points
        for px, py in self._points:

            # Compute distance to current point
            dst = np.sqrt((px - x) ** 2 + (py - y) ** 2)

            # If the distance is small remove it
            if dst < 10:
                self._removePoint(px, py)
                self._redraw()
                return

        # Delegate to add the point
        self._addPoint(x, y)

        # Redraw the image
        self._redraw()

    # Add a new point
    def _addPoint(self, x, y):
        # Count points
        n = len(self._points)

        # If less than 3 points just add it
        if n < 2:
            self._points.append((x, y))
            return

    # Remove an existing point
    def _removePoint(self, x, y):
        # Remove the point
        self._points = list(filter(lambda v: v != (x, y), self._points))

    def _rectangle(self):
        # Get xs and ys
        xs = [x for (x, _) in self._points]
        ys = [y for (_, y) in self._points]

        # Compute ranges
        xmax = max(xs)
        xmin = min(xs)
        ymax = max(ys)
        ymin = min(ys)

        # Return rectangle
        return [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]

    def _pointsToVector(self, points):
        # Get points values
        x1, y1 = points[0]
        x2, y2 = points[1]
        x3, y3 = points[2]
        x4, y4 = points[3]

        # Return the vector
        return np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
예제 #41
0
class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.setGeometry(500, 300, 800, 600)

        self.setWindowTitle("PyQT Mappn!")
#_________________________________________________________________________
#(Menubah)


        self.myQMenuBar = QtGui.QMenuBar(self)

        FileMenu = self.myQMenuBar.addMenu('File')

        AboutMenu = self.myQMenuBar.addMenu('About')

        exchangeChoice = self.myQMenuBar.addMenu('Exchanges')

        dataTF = self.myQMenuBar.addMenu('Data Time')

        OHLCI = self.myQMenuBar.addMenu('OHLC Interval')

        topIndicator = self.myQMenuBar.addMenu('Top Indicator')

        middleIndicator = self.myQMenuBar.addMenu('Middle Indicator')
#______________


        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Quit Program')
        exitAction.triggered.connect(QtGui.qApp.quit)

        popupmsgAction = QtGui.QAction('Open', self)
        popupmsgAction.setStatusTip('Popup')
        popupmsgAction.triggered.connect(self.popupmsg)
#-----

        exchange2 = QtGui.QAction('BTC-E', self)
        exchange2.setStatusTip('BTC-E')
        exchange2.triggered.connect(self.btce)

        exchange1 = QtGui.QAction('BITFINEX', self)
        exchange1.setStatusTip('BITFINEX')
        exchange1.triggered.connect(self.bitfinex)

        exchange3 = QtGui.QAction('Bitstamp', self)
        exchange3.setStatusTip('bitstamp')
        exchange3.triggered.connect(self.bitstamp)

#_________
        tick = QtGui.QAction('Tick', self)
        tick.setStatusTip('Tick Data')
        tick.triggered.connect(self.btce)

        oned = QtGui.QAction('1 day', self)
        oned.setStatusTip('One Day')
        oned.triggered.connect(self.bitfinex)

        threed = QtGui.QAction('3 day', self)
        threed.setStatusTip('three day')
        threed.triggered.connect(self.bitstamp)

        sevend = QtGui.QAction('7 day', self)
        sevend.setStatusTip('seven day')
        sevend.triggered.connect(self.bitstamp)
#__________

        tick1 = QtGui.QAction('tick', self)
        tick1.setStatusTip('seven day')
        tick1.triggered.connect(self.bitstamp)

        onem = QtGui.QAction('1 minute',  self)
        onem.setStatusTip('seven day')
        onem.triggered.connect(self.bitstamp)


        fivem = QtGui.QAction('5 minute', self)
        fivem.setStatusTip('seven day')
        fivem.triggered.connect(self.bitstamp)

        fifteenm = QtGui.QAction('15 minute', self)
        fifteenm.setStatusTip('seven day')
        fifteenm.triggered.connect(self.bitstamp)

        thirtymin = QtGui.QAction('30 mins', self)
        thirtymin.setStatusTip('seven day')
        thirtymin.triggered.connect(self.bitstamp)

        oneh = QtGui.QAction('1 hour', self)
        oneh.setStatusTip('seven day')
        oneh.triggered.connect(self.bitstamp)

        threeh = QtGui.QAction('3 hour', self)
        threeh.setStatusTip('seven day')
        threeh.triggered.connect(self.bitstamp)

#------------Top indicator

        noner = QtGui.QAction('None', self)
        noner.setStatusTip('None')
        noner.triggered.connect(self.btce)

        sma = QtGui.QAction('EMA', self)
        sma.setStatusTip('EMA')
        sma.triggered.connect(self.addTopIndicator)

        ema = QtGui.QAction('SMA', self)
        ema.setStatusTip('SMA')
        ema.triggered.connect(self.bitstamp)

#------------Middle Indicator

        noner = QtGui.QAction('None', self)
        noner.setStatusTip('None')
        noner.triggered.connect(self.btce)

        rsi = QtGui.QAction('RSI', self)
        rsi.setStatusTip('RSI')
        rsi.triggered.connect(self.bitfinex)

        macd = QtGui.QAction('MACD', self)
        macd.setStatusTip('MACD')
        macd.triggered.connect(self.bitstamp)

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

        FileMenu.addAction(exitAction)


        AboutMenu.addAction(popupmsgAction)


        exchangeChoice.addAction(exchange1)
        exchangeChoice.addAction(exchange2)
        exchangeChoice.addAction(exchange3)

        dataTF.addAction(tick)
        dataTF.addAction(oned)
        dataTF.addAction(threed)
        dataTF.addAction(sevend)

        OHLCI.addAction(tick1)
        OHLCI.addAction(onem)
        OHLCI.addAction(fivem)
        OHLCI.addAction(fifteenm)
        OHLCI.addAction(thirtymin)
        OHLCI.addAction(oneh)
        OHLCI.addAction(threeh)


        topIndicator.addAction(noner)
        topIndicator.addAction(rsi)
        topIndicator.addAction(macd)


        middleIndicator.addAction(noner)
        middleIndicator.addAction(ema)
        middleIndicator.addAction(sma)




#_________________________________________________________________________
#

#Canvas------------------

        self.canvas = FigureCanvas(f)
        self.canvas.show()
        self.show()








#_________________________________________________________________________
#(down starting from top, from left, continuing, how many rows it spas across)
        grid = QtGui.QGridLayout()

        grid.addWidget(self.canvas, 0, 0, 2, 4)




        self.setLayout(grid)
#_________________________________________________________________________




#_________________________________________________________________________
#Functions--------------------------------------------------------------


    def close_application(self):
        print("whooaaaa so custom!!!")
        sys.exit()



    def popupmsg(self):
        msg = QtGui.QMessageBox.question(self, "Error!",
                                         "Not supported just yet..",
                                         QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if msg == QtGui.QMessageBox.Yes:
            print("Exiting!!!!")
            sys.exit()
        else:
            pass


        #Info------------

    def changeExchange(self, toWhat, pn):
        global exchange
        global DatCounter
        global programName

        exchange = toWhat
        programName=pn
        DatCounter=9000


    def btce(self):
        pass
    def bitfinex(self):
        pass
    def bitstamp(self):
        pass



    def changeTimeFrame(self, tf, popupmsg):
        global DatCounter
        global datapace

        if tf == "7 day" and resampleSize == "1 minute":
            popupmsg("Way to much data!")

        else:
            datapace = tf
            DatCounter = 9000

    def changeSampleSize(self, size, width, popupmsg):
        global resampleSize
        global DatCounter
        global candleWidth


        if datapace == "7 day" and resampleSize == "1 minute":
            popupmsg("Way to much data!")

        elif datapace == "tick":
            popupmsg("Your currently viewing ticking data")

        else:
            resampleSize = size
            DatCounter = 9000
            candleWidth = width




#-------Indicators
    def addTopIndicator(self):
        global topIndicator
        global DatCounter


        text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
            'Enter your name:')

        if ok:
            self.le.setText(str(text))
예제 #42
0
class mywidget(QWidget):
    def __init__(self,Parent=None):
        super(mywidget,self).__init__(Parent)
        self.figure=plt.figure(figsize=(15,25),facecolor='w',dpi=50)
        self.canvas=FigureCanvas(self.figure)
        self.toolbar=NavigationToolbar(self.canvas,self)
        self.slider=QSlider(Qt.Horizontal,self)
        self.slider.setRange(1, 100)
        self.slider.setValue(5)
        self.slider.valueChanged[int].connect(self.changeValue)
        self.label=QLabel('Taxa de amostragem 50 Hz')
        self.spinbox=QSpinBox()
        self.spinbox.setValue(5)
        self.spinbox.valueChanged.connect(self.sliderchange)
        self.spinbox.setRange(1,100)
        layout=QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.slider)
        layout.addWidget(self.spinbox)
        layout.addWidget(self.label)

        self.slider.valueChanged.connect(self.changeValue)
        self.setLayout(layout)
        self.plot()
        #self.changeValue(5)

    def sliderchange(self,value):
        self.slider.setValue(value)

    def plot(self):
        self.amostrasporseg=15*5 #samples/sec
        frequenciasinal=5 #Hz
        omega= frequenciasinal
        self.z=2*np.pi*np.arange(0,2*np.pi,1/self.amostrasporseg)
        y=np.sin(self.z*omega)
        k=y*signal.hann(len(y))

        ylinha= 20*np.log10(abs(np.fft.fft(k,2048)))
        ylinha=np.tile(ylinha,3)

        zlinha=np.linspace(-2,4,len(ylinha))
        self.figure.subplots_adjust(bottom=.75)
        gs = gridspec.GridSpec(5, 1,height_ratios=[0.2,1,0.25,1,0.2])
        ax =self.figure.add_subplot(gs[1])
        self.plot2,=plt.plot(zlinha,ylinha)
        plt.title('Espectro do sinal')
        plt.xlabel(r'$\omega$')
        plt.ylabel(r'|X($\omega$)|')

        plt.xticks((-2,-1,0,1,2,3,4),[r'$-2\pi$',r'$-\pi$','0',r'$\pi$',r'$2\pi$',r'$3\pi$',r'$4\pi$'])
        #ax.set_xticks([-0.0442,0.0442], minor=True)
        ax.xaxis.grid(True,which='major',linewidth=0.75,color='k',linestyle='--')
        self.beta=self.figure.add_subplot(gs[3])
        self.plot3,=plt.plot(self.z,y,label='Amostragem Correta')
        plt.plot(self.z,y,'o',label='Amostragem Fixa')
        plt.legend(loc='upper right')
        self.beta.set_xlabel(r't')
        self.beta.set_ylabel(r'x(t)')
        self.beta.set_xlim([0,2*np.pi])
        self.figure.tight_layout()

    def changeValue(self,value):
        self.spinbox.setValue(value)
        freq = value
        znovo=np.arange(0,2*np.pi,0.001)
        omega= freq
        omeganovo= freq
        y=np.sin(self.z*omega)
        yf=np.sin(znovo*omeganovo)
        k=y*signal.hann(len(y))
        ylinha=np.fft.fft(k,2048)
        ylinha=np.tile(ylinha,3)
        self.beta.clear()
        self.beta.plot(znovo,yf,label='Amostragem Correta')
        self.beta.plot(self.z,y,'o-',lw=2,label='Amostragem Fixa')
        plt.legend(loc='upper right')
        self.beta.set_xlim([0,2*np.pi])
        self.beta.set_xlabel(r't')
        self.beta.set_ylabel(r'x(t)')
        self.beta.set_title('Sinal com amostragem correta x Sinal com amostragem fixa')
        self.plot2.set_ydata(20*np.log10(abs(ylinha)))
        self.canvas.draw()
        self.canvas.show()
예제 #43
0
class View(QtGui.QWidget):


    def __init__(self, parent = None, width=5, height=4, dpi=80, filename = None, model = None,
                        plot_type = 'Image', trace_num = None, region = []):
        # plot paramters #                                        
        self.t_num = trace_num
        self.region = region

        # connect model signal #
        self.model = model
        self.model.dataChanged.connect(self.update_views)
        
        # create a dictionary of views 
        self.view_options = {'Image': self.view_image,
                             'TracePlot': self.view_trace,
                             'PSD': self.view_psd,
                             'Surface':self.view_surface}
        super(View,self).__init__(parent)
        
        # make the figure
        self.figure = Figure((width, height), dpi)
        fig_color = (1.0, 1.0, 1.0, 1.0)
        self.figure.set_facecolor(fig_color)
        # create the canvas
        self.canvas = Canvas(self.figure)
        self.canvas.setParent(self)
        
        # create the toolbar and tie it to the canvas
        self.toolbar = Toolbar(self.canvas, self)
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.setLayout(self.layout)
        if filename:
            self.setWindowTitle(plot_type+': '+filename) 

        if plot_type == 'Surface':
            self.axes = self.figure.gca(projection='3d')
        else:
            self.axes = self.figure.add_subplot(111)
            
        self.axes.hold(False)

        self.view_options[plot_type]()
        self.canvas.show()   

    def view_image(self):
        self.axes.imshow(self.model.get_agc_data(),cmap = cm.coolwarm)
        self.axes.set_xticklabels([])
        self.axes.set_yticklabels([])  
        self.axes.set_xticks([])
        self.axes.set_yticks([])        
        self.axes.set_xlabel('source channel')        
        self.axes.set_ylabel('time')        
            
        
    def view_trace(self):
        print self.t_num
        y = self.model.getTrace(self.t_num)
        x = np.arange(len(y))
        self.axes.fill(x,y,'r',linewidth = 0)
        self.axes.set_xlabel('time')        
        self.axes.set_ylabel('amplitude') 
        self.axes.set_xlim(0,len(x))   
        self.axes.grid(True)    
    
    def view_surface(self):
        
        #x = np.arange(self.model.getNTraces())
        #y = np.arange(self.model.getTLength())       
        y = np.arange(self.region[1]-self.region[0])
        x = np.arange(self.region[3]-self.region[2])       
        x, y = np.meshgrid(x, y)
        z = self.model.get_agc_data()
        z = z[self.region[0]:self.region[1], self.region[2]:self.region[3]]
        print self.model.getTLength()
        self.axes.plot_surface(x,y,z, rstride=1, cstride=1, cmap=cm.coolwarm,
                               linewidth=0, antialiased=False)

    def view_psd(self):
        y = self.model.get_psd_of_trace(self.t_num)
        x = np.arange(-len(y)/2,len(y)/2)
        print x.shape
        print y.shape
        self.axes.semilogy(x,y,'r', linewidth  = 1)
        self.axes.set_xlabel('frequency')        
        self.axes.set_ylabel('spectral density')        
        self.axes.set_xlim(-len(x)/2,len(x)/2)   
        self.axes.grid(True)            
       
   
    def update_views(self):
        print "updating views"
class DiagramaDeRafagasyManiobrasDialog(QFrame, layout_DiagramaDeRafagasyManiobras.Ui_Dialog):

    def __init__(self, parent=None):
        super(DiagramaDeRafagasyManiobrasDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle(__appName__)

        # Define input unit's label for SI and IM
        self.length_label = {'IM': 'ft', 'SI': 'm'}
        self.area_label = {'IM': 'ft^2', 'SI': 'm^2'}
        self.weight_label = {'IM': 'lb', 'SI': 'kg'}
        self.speed_label = {'IM': 'ft/s', 'SI': 'm/s'}
        self.den_label = {'IM': 'slug/ft^2', 'SI': 'kg/m^3'}

        self.ft2m = 0.3048
        self.lb2kg = 0.453592

        datos = {
            'CAM': {'SI': 2.461, 'IM': 2.461/self.ft2m},
            'sw': {'SI': 60, 'IM': 60 / self.ft2m / self.ft2m},
            'a3D': 5.0037,
            'MTOW': {'SI': 23000, 'IM': 23000 / self.lb2kg},
            'MLW': {'SI': 23000, 'IM': 23000 / self.lb2kg},
            'MZFW': {'SI': 16376.0, 'IM': 16376.0 / self.lb2kg},
            'Vc': {'SI': 151.93, 'IM': 151.93 / self.ft2m},
            'clmax': 1.2463,
            'clmax_flap': 1.499,
            'clmin': -0.75*1.2463,
            'Zmo': {'SI': 9999.2, 'IM': 9999.2 / self.ft2m}
        }
        w = {'SI': 20000, 'IM': 20000 / self.lb2kg}
        h = {'SI': 5000, 'IM': 5000 / self.ft2m}
        den = {'SI': 1.225, 'IM': 1.225 / self.lb2kg * self.ft2m**3}
        self.diagramas = Diagramas(datos, w, h, den, units='SI')
        self.update_units()
        self.atmosfera_estandar_dialog = AtmosferaEstandarDialog(unit=self.units)

        self.fig1 = Figure((5.0, 3.0), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.fig1.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.25)
        self.axes1 = self.fig1.add_subplot(111)
        self.axes1.set_ylabel('n')
        self.axes1.set_xlabel(self.speed_label[self.units])
        self.axes1.set_title('Diagrama de Maniobras')
        self.axes1.ticklabel_format(style="sci", scilimits=(0, 0), axis="both")  # , useOffset=True,useLocale=True)
        self.axes1.tick_params(axis="both", direction='in', length=6, width=2, labelsize="medium")

        self.fig2 = Figure(dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.fig2.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.25)
        self.axes2 = self.fig2.add_subplot(111)
        self.axes2.set_ylabel('n')
        self.axes2.ticklabel_format(style='sci', scilimits=(0, 0), axis="both")
        self.axes2.set_xlabel(self.speed_label[self.units])
        self.axes2.set_title('Diagrama de Rafagas')

        self.fig3 = Figure(dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.fig3.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.25)
        self.axes3 = self.fig3.add_subplot(111)
        self.axes3.set_ylabel('n')
        self.axes3.ticklabel_format(style='sci', scilimits=(0, 0), axis="both")
        self.axes3.set_xlabel(self.speed_label[self.units])
        self.axes3.set_title('Diagrama de Rafagas y maniobras')

        # generate the canvas to display the plot
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setParent(self.manoeuvre_tab)
        self.canvas1.show()
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.setParent(self.gust_tab)
        self.canvas2.show()
        self.canvas3 = FigureCanvas(self.fig3)
        self.canvas3.setParent(self.combined_tab)
        self.canvas3.show()

        # SIGNALS & SLOTS
        self.connect(self.IM_radioButton, SIGNAL("clicked()"), self.update_units)
        self.connect(self.SI_radioButton, SIGNAL("clicked()"), self.update_units)
        self.connect(self.Altura_Button, SIGNAL("clicked()"), self.seleccionAltura)
        self.connect(self.grafiacar_pushButton, SIGNAL("clicked()"), self.calculos())

        self.CAM_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.CAM, float(self.CAM_lineEdit.text()), self.ft2m))
        self.sw_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.sw, float(self.sw_lineEdit.text()), self.ft2m**2))
        self.MTOW_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.MTOW, float(self.MTOW_lineEdit.text()), self.lb2kg))
        self.MLW_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.MLW, float(self.MLW_lineEdit.text()), self.lb2kg))
        self.MZFW_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.MZFW, float(self.MZFW_lineEdit.text()), self.lb2kg))

        self.a3D_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.a3D, float(self.a3D_lineEdit.text())))
        self.clmax_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.clmax, float(self.clmax_lineEdit.text())))
        self.clmax_flap_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.clmax_flap, float(self.clmax_flap_lineEdit.text())))

        self.Zmo_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.Zmo, float(self.Zmo_lineEdit.text()), self.ft2m))
        self.Vc_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.Vc, float(self.Vc_lineEdit.text()), self.ft2m))

        self.W_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.W, float(self.W_lineEdit.text()), self.lb2kg))
        self.h_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.h, float(self.h_lineEdit.text()), self.ft2m))
        self.den_lineEdit.editingFinished.connect(lambda: self.lecturadatos(self.diagramas.den, float(self.den_lineEdit.text()), self.lb2kg / self.ft2m**3))

        self.grafiacar_pushButton.clicked.connect(self.calculos)

    def resizeEvent(self, event):
        self.canvas1.setGeometry(self.PlotArea.rect())
        self.canvas2.setGeometry(self.PlotArea.rect())
        self.canvas3.setGeometry(self.PlotArea.rect())

    def lecturadatos(self, variable, value, unit_converter = 1.0):
        logger.debug(value)
        if self.units == 'IM':
            variable['IM'] = value
            variable['SI'] = value*unit_converter
        else:
            variable['SI'] = value
            variable['IM'] = value/unit_converter

    def update_units(self):
        if self.IM_radioButton.isChecked():
            self.units = "IM"
            self.diagramas.units = "IM"
        elif self.SI_radioButton.isChecked():
            self.units = "SI"
            self.diagramas.units = "SI"
        else:
            return -1
        self.update_unitLabels()
        self.write_lineEdits()

    def calculos(self):
        self.print_input_variables()
        self.diagramas.calculos()
        self.plot_diagrams()

    def seleccionAltura(self):
        # TODO: actualizar atmosfera_estandar_dialog con los valores de diagramas.h y diagramas.den
        # update units
        self.atmosfera_estandar_dialog.units = self.units
        self.atmosfera_estandar_dialog.update_labels()
        self.atmosfera_estandar_dialog.atmosfera[self.units]['h'] = self.diagramas.h[self.units]
        self.atmosfera_estandar_dialog.write_lineEdits()
        self.atmosfera_estandar_dialog.actualizar('altura')
        self.atmosfera_estandar_dialog.actualizarRho(self.diagramas.den[self.units])
        if self.atmosfera_estandar_dialog.exec_():
            self.diagramas.h[self.units] = self.atmosfera_estandar_dialog.atmosfera[self.units]['h']
            self.diagramas.den[self.units] = self.atmosfera_estandar_dialog.atmosfera[self.units]['rho']
            self.write_lineEdits()

    def plot_diagrams(self):
        self.axes1.clear()
        self.diagramas.plot_diagrama_de_maniobras(self.axes1, 0.5)
        self.diagramas.plot_diagrama_de_maniobras_con_flap(self.axes1, 0.5)
        self.canvas1.draw()

        self.axes2.clear()
        self.diagramas.plot_diagrama_de_rafagas(self.axes2, 0.5)
        self.canvas2.draw()

        self.axes3.clear()
        self.diagramas.plot_diagrama_de_maniobras_y_rafagas(self.axes3, 0.5)
        self.canvas3.draw()

    def update_unitLabels(self):
        self.CAM_unitlabel.setText(self.length_label[self.units])
        self.sw_unitlabel.setText(self.area_label[self.units])
        self.MTOW_unitlabel.setText(self.weight_label[self.units])
        self.MLW_unitlabel.setText(self.weight_label[self.units])
        self.MZFW_unitlabel.setText(self.weight_label[self.units])
        self.W_unitlabel.setText(self.weight_label[self.units])
        self.Zmo_unitlabel.setText(self.length_label[self.units])
        self.h_unitlabel.setText(self.length_label[self.units])
        self.den_unitlabel.setText(self.den_label[self.units])
        self.Vc_unitlabel.setText(self.speed_label[self.units])

    def write_lineEdits(self):
        # TODO: set decimals to print
        self.CAM_lineEdit.setText(str(self.diagramas.CAM[self.units]))
        self.sw_lineEdit.setText(str(self.diagramas.sw[self.units]))
        self.MTOW_lineEdit.setText(str(self.diagramas.MTOW[self.units]))
        self.MLW_lineEdit.setText(str(self.diagramas.MLW[self.units]))
        self.MZFW_lineEdit.setText(str(self.diagramas.MZFW[self.units]))
        self.W_lineEdit.setText(str(self.diagramas.W[self.units]))
        self.Zmo_lineEdit.setText(str(self.diagramas.Zmo[self.units]))
        self.h_lineEdit.setText(str(self.diagramas.h[self.units]))
        self.den_lineEdit.setText(str(self.diagramas.den[self.units]))
        self.Vc_lineEdit.setText(str(self.diagramas.Vc[self.units]))
        self.a3D_lineEdit.setText(str(self.diagramas.a3D))
        self.clmax_lineEdit.setText(str(self.diagramas.clmax))
        self.clmax_flap_lineEdit.setText(str(self.diagramas.clmax_flap))
        self.clmin_lineEdit.setText(str(self.diagramas.clmin))

    def print_input_variables(self):
        logger.info("CAM = {}".format(self.diagramas.CAM[self.units]))
        logger.info("Sw = {}".format(self.diagramas.sw[self.units]))
        logger.info("MTOW = {}".format(self.diagramas.MTOW[self.units]))
        logger.info("MLW = {}".format(self.diagramas.MLW[self.units]))
        logger.info("MZFW = {}".format(self.diagramas.MZFW[self.units]))
        logger.info("a3D = {}".format(self.diagramas.a3D))
        logger.info("clmax = {}".format(self.diagramas.clmax))
        logger.info("clmax_flap = {}".format(self.diagramas.clmax_flap))
        logger.info("clmin = {}".format(self.diagramas.clmin))
        logger.info("Zmo = {}".format(self.diagramas.Zmo[self.units]))
        logger.info("Vc = {}".format(self.diagramas.Vc[self.units]))
예제 #45
0
class RTWindowWidget(QtGui.QWidget):
    """Matplotlib wxFrame with animation effect"""
    ### connects widgets and signals ###
    def __init__(self, parent = None):
        super(RTWindowWidget, self).__init__(parent)

        # Matplotlib Figure
        self.fig = Figure((6, 4), 100)
        # bind the Figure to the backend specific canvas
        self.canvas = FigureCanvas(self.fig)
        # add a subplot
        self.ax = self.fig.add_subplot(111)

        # limit the X and Y axes dimensions
        # we prefer 2 separate functions for clarity
        self.ax.set_ylim([0, 100])
        self.ax.set_xlim([0, POINTS])
        # but we want a "frozen" window (defined by y/xlim functions)
        self.ax.set_autoscale_on(False)

        # we do not want ticks on X axis
        self.ax.set_xticks([])
        # we want a tick every 10 point on Y (101 is to have 100 too)
        self.ax.set_yticks(range(0, 101, 10))
        # disable autoscale, since we don't want the Axes to adapt
        # draw a grid (it will be only for Y)
        self.ax.grid(True)

        # generates first "empty" plots
        self.user = [None] * POINTS
        self.nice = [None] * POINTS
        self.sys  = [None] * POINTS
        self.idle = [None] * POINTS

        self.l_user, = self.ax.plot(range(POINTS), self.user, label='User %')
        self.l_nice, = self.ax.plot(range(POINTS), self.nice, label='Nice %')
        self.l_sys,  = self.ax.plot(range(POINTS),  self.sys,  label='Sys %')
        self.l_idle, = self.ax.plot(range(POINTS), self.idle, label='Idle %')

        # add the legend
        self.ax.legend(loc='upper center',
                           ncol=4,
                           prop=font_manager.FontProperties(size=10))

        # force a draw on the canvas()
        # trick to show the grid and the legend
        self.canvas.draw()

        # save the clean background - everything but the line
        # is drawn and saved in the pixel buffer background
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)

        # take a snapshot of CPU usage, needed for the update algorithm
        self.before = self.prepare_cpu_usage()


        # timerCallback = lambda: self.onTimer()
        myTimer = QtCore.QTimer()
        myTimer.timeout.connect(self.onTimer)
        myTimer.start(1000) #once a sec
        # print 1
        self.canvas.show()


    def prepare_cpu_usage(self):
        """helper function to return CPU usage info"""

        # get the CPU times using psutil module
        t = p.cpu_times()

        # return only the values we're interested in
        if hasattr(t, 'nice'):
            return [t.user, t.nice, t.system, t.idle]
        else:
            # special case for Windows, without 'nice' value
            return [t.user, 0, t.system, t.idle]


    def get_cpu_usage(self):
        """Compute CPU usage comparing previous and current measurements"""

        # take the current CPU usage information
        now = self.prepare_cpu_usage()
        # compute deltas between current and previous measurements
        delta = [now[i]-self.before[i] for i in range(len(now))]
        # compute the total (needed for percentages calculation)
        total = sum(delta)
        # save the current measurement to before object
        self.before = now
        # return the percentage of CPU usage for our 4 categories
        return [(100.0*dt)/total for dt in delta]


    def onTimer(self):
        """callback function for timer events"""

        print 1
        # get the CPU usage information
        tmp = self.get_cpu_usage()

        # restore the clean background, saved at the beginning
        self.canvas.restore_region(self.bg)

        # update the data
        self.user = self.user[1:] + [tmp[0]]
        self.nice = self.nice[1:] + [tmp[1]]
        self.sys  = self.sys[1:]  + [tmp[2]]
        self.idle = self.idle[1:] + [tmp[3]]

        # update the plot
        self.l_user.set_ydata(self.user)
        self.l_nice.set_ydata(self.nice)
        self.l_sys.set_ydata( self.sys)
        self.l_idle.set_ydata(self.idle)

        # just draw the "animated" objects
        self.ax.draw_artist(self.l_user)
        self.ax.draw_artist(self.l_nice)
        self.ax.draw_artist(self.l_sys)
        self.ax.draw_artist(self.l_idle)

        # "blit" the background with the animated lines
        self.canvas.blit(self.ax.bbox)
예제 #46
0
def generate_est_png(tasks, number=10, display=False):
    if len(tasks) > 0 and mpl_available:
        # Allocate arrays
        N = len(tasks)
        x = numpy.arange(N)
        lbe = numpy.zeros(N)
        errors = numpy.zeros(N)
        average = numpy.zeros(N)
        sigma_minus = numpy.zeros(N)
        sigma_plus = numpy.zeros(N)
        colors = []
        
        # Plot properties
        M = max([0, N - number])  # index of first task to show
        w = 0.4  # width of the bars
        
        # Compute values
        for i, task in enumerate(tasks):
            lbe[i] = i - w/2
            errors[i] = (task.duration - task.estimate) / 60.0  # in minutes
            average[i] = numpy.average(errors[:i+1]) / (i + 1)
            sigma_minus[i] = average[i] - numpy.std(errors[:i+1])
            sigma_plus[i] = average[i] + numpy.std(errors[:i+1])
            if errors[i] <= 0:
                # Logged duration was less than estimate
                colors.append(GREEN)
            else:
                # Logged duration was more than estimate
                colors.append(RED)
        
        # Create plot
        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(1, 1, 1)
        ax.hold(True)
        ax.set_xlim(M-w/2, N-1+w/2)
        ax.set_xticks([])
        ax.set_xticklabels([])
        ax.set_ylim(min([-10, numpy.min(errors)-10]), max([180, numpy.max(errors)+10]))
        ax.set_ylabel('Estimation error [minutes]')
        ax.grid(axis='y')
        
        # Plot data
        ax.plot(x[M:], average[M:], color=DARK_BLUE)
        ax.plot(x[M:], sigma_minus[M:], color=LIGHT_BLUE)
        ax.plot(x[M:], sigma_plus[M:], color=LIGHT_BLUE)
        ax.fill_between(x[M:], y1=sigma_minus[M:], y2=sigma_plus[M:], color=LIGHT_BLUE)
        ax.bar(lbe[M:], errors[M:], w, color=colors[M:], alpha=0.4)
        
        # Create labels
        for x, task in enumerate(tasks[M:]):
            ax.text(x+M, 1, task.name, rotation=90, ha='center', va='bottom')
        
        # Output
        if not display:
            # Output as base64-encoded string
            im = sio.StringIO()
            fig.savefig(im, format='png')
            png = im.getvalue().encode('base64').strip()
            return png
        else:
            # Show on screen
            canvas.show()
            return None
    else:
        return None
예제 #47
0
파일: test_qt1.py 프로젝트: bat3/PiMeteo
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setGeometry(200,100,500,120)
        p = self.palette()
        p.setColor(self.backgroundRole(), QtGui.QColor(200,100,100))
        self.setPalette(p)
        # Supprime les bords de la fentre
        self.setWindowFlags( QtCore.Qt.FramelessWindowHint)

        tempLabel = QtGui.QLabel(self)
        # Pour ne pas avoir de probleme avec le °
        text = QtCore.QString.fromUtf8("Temperature\n125°C")
        tempLabel.setText(text)

        humLabel = QtGui.QLabel(self)
        text = QtCore.QString.fromUtf8("Humidité\n100%")
        humLabel.setText(text)

        self.heure = QtGui.QLabel()
        self.date = QtGui.QLabel()

        pathToImage = "/home/francois/Documents/test_git/PiMeteo/"
        # pathToImage = "/home/user/Documents/PiMeteo/"
        b1 = QtGui.QPushButton()
        b1.setMaximumSize(90,70)
        b1.setMinimumSize(90,70)
        image_temp = QtGui.QPixmap()
        image_temp.load(pathToImage+"image_temp.png")
        labelImage = QtGui.QLabel(b1)
        labelImage.setPixmap(image_temp)

        self.b2 = QtGui.QPushButton()
        self.b2.setMaximumSize(90,70)
        self.b2.setMinimumSize(90,70)
        image_hum = QtGui.QPixmap()
        image_hum.load(pathToImage+"image_hum.png")
        labelImage = QtGui.QLabel(self.b2)
        labelImage.setPixmap(image_hum)

        b3 = QtGui.QPushButton()
        b3.setMaximumSize(90,70)
        b3.setMinimumSize(90,70)

        self.b5 = QtGui.QListView()

        self.main_frame = QtGui.QWidget()
        self.main_frame.setGeometry(200,100,100,100)
        fig = Figure(figsize=None, dpi=None, facecolor=((0.78,0.39,0.39,1)))
        self.canvas = FigureCanvas(fig)
        self.canvas.setParent(self.main_frame)
        self.axes = fig.add_subplot(111)
        # axes.plot([1,2,3])
        self.axes.plot([3,2,1])
        self.canvas.draw()

        # connect the signals to the slots
        b1.clicked.connect(self.plot_1)
        self.b2.clicked.connect(self.plot_2)
        b3.clicked.connect(self.draw_infos)

        # set the layout_boutton
        self.layout_boutton = QtGui.QGridLayout()
        self.layout_boutton.addWidget(self.date,0,0)
        self.layout_boutton.addWidget(self.heure,0,1)
        self.layout_boutton.addWidget(tempLabel,1,0)
        self.layout_boutton.addWidget(b1,1,1)
        self.layout_boutton.addWidget(self.b2,2,1)
        self.layout_boutton.addWidget(b3,3,1)
        self.layout_boutton.addWidget(humLabel,2,0)

        # set the layout_window
        self.layout_window = QtGui.QGridLayout()
        self.layout_window.addLayout(self.layout_boutton,0,0)
        self.layout_window.addWidget(self.b5,0,1)
        self.setLayout(self.layout_window)

    def update_time(self,heure_courante):
        self.heure.setText(heure_courante)

    def update_date(self,date_courante):
        self.date.setText(date_courante)

    def plot_1(self):
        if -1 == self.layout_window.indexOf(self.canvas):
            self.layout_window.removeWidget(self.b5)
            self.b5.hide()
            self.layout_window.addWidget(self.canvas,0,1)
            self.canvas.show()
        # discards the old graph
        self.axes.hold(False)
        # plot data
        self.axes.plot([1,2,3])
        # refresh canvas
        self.canvas.draw()

    def plot_2(self):
        if -1 == self.layout_window.indexOf(self.canvas):
            self.layout_window.removeWidget(self.b5)
            self.b5.hide()
            self.layout_window.addWidget(self.canvas,0,1)
            self.canvas.show()
        # discards the old graph
        self.axes.hold(False)
        # plot data
        self.axes.plot([3,2,1])
        # refresh canvas
        self.canvas.draw()

    def draw_infos(self):
        if -1 == self.layout_window.indexOf(self.b5):
            self.layout_window.removeWidget(self.canvas)
            self.canvas.hide()
            self.layout_window.addWidget(self.b5,0,1)
            self.b5.show()
            for dr in range(ndir):
                rao[fr, dr, :] = MotionFreq(
                    self._data_h['m_m'] + self._data_h['m_add'][fr, :, :],
                    self._data_h['c_rad'][fr, :, :] +
                    self._data_p['c_pto'][te, hs, ang, :, :] +
                    self._data_p['c_fit'][te, hs, ang, :, :] +
                    self._data_p['c_ext'][te, hs, ang, :, :],
                    self._data_h['k_hst'] +
                    self._data_p['k_mooring'][te, hs, ang, :, :] +
                    self._data_p['k_fit'][te, hs, ang, :, :] +
                    self._data_p['k_ext'][te, hs, ang, :, :],
                    self._data_h['f_ex'][fr, dr].T, omeg[fr])

        return rao


if __name__ == "__main__":
    vi = Visualiser()
    data = {
        'periods': np.array([0, 1]),
        'f_ex': np.array([[[0, 1]]], dtype=complex).T,
        'c_rad': np.array([[[0, 1]]], 'f').T,
        'm_add': np.array([[[0, 1]]], 'f').T
    }
    figu = vi.show_diffraction_problem(0, 0)
    vi.set_hydrodynamic_data(data)
    figu = vi.show_radiation_problem(0, 0)
    canvas = FigureCanvas(figu)
    canvas.draw()
    canvas.show()
예제 #49
0
파일: Viewer.py 프로젝트: HenricusRex/TMV3
class MainForm(QtGui.QMainWindow):
    signalShowMessage = QtCore.pyqtSignal(str)
    signalGraphUpdate = QtCore.pyqtSignal()

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.config = configparser.ConfigParser()
        self.config.read('../Lib/TMV3.ini')
        self.ui = uic.loadUi("Viewer.ui", self)
        self.workBenchDB = self.config['DataBases']['workbench']
        self.figure_canvasReference = FigureCanvas(Figure())
        self.figure_canvasCurrent = FigureCanvas(Figure())
        self.plotsRef = []
        self.plotsRefPos = 0
        self.plotsCur = []
        self.plotsCurPos = 0
        self.mode = -1

        self.defBackground = 0
        self.ui.BtnCurrent.setChecked(False)
        self.ui.BtnReference.setChecked(False)

        self.ui.BtnLoadPlotsRef.clicked.connect(self.onBtnLoadRef)
        self.ui.BtnLoadPlotsCur.clicked.connect(self.onBtnLoadCur)
        self.ui.BtnSum.clicked.connect(self.onBtnApply)
        self.ui.BtnDiff.clicked.connect(self.onBtnApply)
        self.ui.BtnPrint.clicked.connect(self.onBtnApply)
        self.ui.BtnEditor.clicked.connect(self.onBtnApply)
        self.ui.BtnReference.clicked.connect(self.onBtnRefCur)
        self.ui.BtnCurrent.clicked.connect(self.onBtnRefCur)
        self.ui.BtnFRwd.clicked.connect(self.onBtnFRwd)
        self.ui.BtnRwd.clicked.connect(self.onBtnRwd)
        self.ui.BtnFwd.clicked.connect(self.onBtnFwd)
        self.ui.BtnFFwd.clicked.connect(self.onBtnFFwd)

        self.signalGraphUpdate.connect(self.onGraphUpdate)

        self.ui.BtnReference.setStyleSheet("QPushButton {background-color: lightGray}"
                                           "QPushButton:checked {background-color: yellow}")
        self.ui.BtnCurrent.setStyleSheet("QPushButton {background-color: lightGray}"
                                           "QPushButton:checked {background-color: green}")


        self.initGraph()

    def contextMenuEvent(self, event):
        self.menu = QtGui.QMenu(self)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)
        renameAction = QtGui.QAction('Rename', self)
        renameAction.triggered.connect(lambda: self.renameSlot(event))
        self.menu.addAction(renameAction)

        # add other required actions
        self.menu.popup(QtGui.QCursor.pos())

    def renameSlot(self,event):
        print('renameSlot')


    def onBtnFRwd(self):
        if self.mode == Ref:
            self.plotsRefPos = 0
            self.onShowPlot(self.plotsRef[0],Ref)
        if self.mode == Cur:
            self.plotsCurPos = 0
            self.onShowPlot(self.plotsCur[0],Cur)
        if self.mode == Both:
            self.plotsRefPos = 0
            self.plotsCurPos = 0
            self.onShowPlot(self.plotsRef[0],Ref)
            self.onShowPlot(self.plotsCur[0],Cur)
        pass
    def onBtnRwd(self):
        if self.mode == Ref:
            if self.plotsRefPos > 0:
                self.plotsRefPos -= 1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
        if self.mode == Cur:
            if self.plotsCurPos > 0:
                self.plotsCurPos -= 1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        if self.mode == Both:
            if self.plotsRefPos > 0:
                self.plotsRefPos -= 1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
            if self.plotsCurPos > 0:
                self.plotsCurPos -= 1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        pass
    def onBtnFwd(self):
        print ("FWD",self.mode)
        if self.mode == Ref:
            if self.plotsRefPos < len(self.plotsRef)-1:
                self.plotsRefPos += 1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
        if self.mode == Cur:
            if self.plotsCurPos < len(self.plotsCur)-1:
                self.plotsCurPos += 1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        if self.mode == Both:
            if self.plotsRefPos < len(self.plotsRef)-1:
                self.plotsRefPos += 1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
            if self.plotsCurPos < len(self.plotsCur)-1:
                self.plotsCurPos += 1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        pass
    def onBtnFFwd(self):
        if self.mode == Ref:
            self.plotsRefPos = len(self.plotsRef)-1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
        if self.mode == Cur:
            self.plotsCurPos = len(self.plotsCur)-1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        if self.mode == Both:
            self.plotsRefPos = len(self.plotsRef)-1
            self.onShowPlot(self.plotsRef[self.plotsRefPos],Ref)
            self.plotsCurPos = len(self.plotsCur)-1
            self.onShowPlot(self.plotsCur[self.plotsCurPos],Cur)
        pass
    def onBtnRefCur(self):
        if (self.ui.BtnCurrent.isChecked() and self.ui.BtnReference.isChecked()):
            self.mode = Both
            print (self.mode)
        elif (self.ui.BtnCurrent.isChecked() and not self.ui.BtnReference.isChecked()):
            self.mode = Cur
            print (self.mode)
        elif (not self.ui.BtnCurrent.isChecked() and self.ui.BtnReference.isChecked()):
            self.mode = Ref
            print (self.mode)
        else:
            self.mode = -1
            print (self.mode)
    def openSession(self):
        session = Session()
        session.exec()
        if session.ret:
            if session.new:
                self.onBtnLoadRef()
            else:
                print(session.sel)
    def onGraphUpdate(self):
        self.figure_canvas.draw()
    def onShowMessageB(self, text):
        self.addItem(text)
        pass

    def onShowMessageA(self, data):
        text = pickle.loads(data)
        #Message from foreign thread => access gui via qt-signal
        self.signalShowMessage.emit(text)
    def onBtnApply(self):
        pass
    def onBtnLoadRef(self):
        filter = Filter()
        filter.exec()
        if filter.ret:
            print(filter.sel)
            self.plotsRef = filter.sel


        pass
    def onBtnLoadCur(self):
        filter = Filter()
        filter.exec()
        if filter.ret:
            print(filter.sel)
            self.plotCur = filter.sel
        pass
    def onShowPlot(self, id, dest):
        print ("id, dest",id,dest)
        _Plot = Tpl3Plot(self.workBenchDB,id)
        if _Plot.read():
            self.onNewPlot(_Plot, dest)
            for _t in _Plot.traces:
                self.onNewTrace(_t, dest)

            #_lines = eval (data.lineObjects)
            for _line in _Plot.lineObjects:
                self.onNewLine(_line, dest)
            return True
        else:
            _err = "Error reading Plot {}".format(str(id))
            QtGui.QMessageBox.information(self, 'TMV3', _err, QtGui.QMessageBox.Ok)
            return False
    def onNewPlot(self, data, dest):
        if dest == Ref:
            self.axesR.set_xlim(data.x1,data.x2)
            self.axesR.set_ylim(data.y1,data.y2)
        if dest == Cur:
            self.axesC.set_xlim(data.x1,data.x2)
            self.axesC.set_ylim(data.y1,data.y2)
         #   self.signalShowTitle.emit(data.plot_title)
        self.signalGraphUpdate.emit()
        pass

    def onShowTitleRef(self,txt):
        #access to Gui only via signal
        self.setWindowTitle(txt)

    def onGraphUpdate(self):
        self.figure_canvasReference.draw()
        self.figure_canvasCurrent.draw()


    def onNewLine(self, data, dest):
        try:
          #  print ('Graph: new Line {0} {1} {2}'.format(data.type, str(data.line_id), str(len(data.data_xy))))
            _xyf = eval(data.data_xy)
          #  print(_xyf, type(_xyf))

            _xys = sorted(_xyf,key = lambda x: x[0])
            _x, _y = zip(*_xys)

            self.getDefaultLineStyle(data.type)
            _color = self.defaultColor
            _style = self.defaultStyle
            _width = self.defaultWidth
         #   print(data.color, data.style, data.width)
            if data.color == '': _color = self.defaultColor
            if data.style == '': style = self.defaultStyle
            if data.style == '0.0': _width = self.defaultWidth
            #if self.backgroundPlot == 'True':
            #    _color = 'grey'

          #  if dest == Ref:
            self.axesR.plot(_x, _y, picker=5, label=data.title, color=_color,ls=_style, lw=1)
           # else:
            #    self.axesC.plot(_x, _y, picker=5, label=data.title, color=_color,ls=_style, lw=1)

            if data.type == "Limit":
                _yTextPos = _y[-1]
                _xTextPos = self.axes.get_xlim()[1]
                _text = ' ' + data.title
                if dest == Ref:
                    self.axesR.text(_xTextPos,_yTextPos,_text)
                else:
                    self.axesC.text(_xTextPos,_yTextPos,_text)
                pass
            #self.figure_canvas.draw()
            self.signalGraphUpdate.emit()
        except Exception as _err:
            print("Graph: onNewLine: {0}".format(str(_err)))
            logging.exception(_err)

    def onNewTrace(self, data, dest):
        print('GRAPH NewTrace')
        _x = []
        _y = []
        try:
            _startFreq = data.x1
            _stopFreq = data.x2
            if data.data_xy_mode == 'Sweep':
                if type(data.data_y) == str:
                    _y = eval(data.data_y)
                else:
                    _y = data.data_y
                _stepFreq = (_stopFreq - _startFreq)/len(_y)
                _x = numpy.arange(_startFreq,_stopFreq,_stepFreq)
            else:
                pass

            self.getDefaultLineStyle('Trace')
            if data.hf_overload == True or data.if_overload == True:
                self.getDefaultLineStyle('TraceOverload')
            if data.uncal == True:
                self.getDefaultLineStyle('TraceUncal')
            _color = self.defaultColor
            _style = self.defaultStyle
            _width = self.defaultWidth
         #   if self.backgroundPlot == 'True': _color = 'grey'
            self.axesR.plot(_x, _y, picker=5,color=_color, ls=_style, lw=1)
            self.signalGraphUpdate.emit()
            pass
        except Exception as _err:
            print("Graph: onNewTrace: {0}".format(str(_err)))
            logging.exception(_err)
        pass

    def onResult(self,data):

        right = 0.9
        top = 0.9
        self.axes.text(right, top, data,
            horizontalalignment='right',
            verticalalignment='top',
            fontsize=20, color='red',
            transform=self.axes.transAxes)
        self.signalGraphUpdate.emit()

    def onNewAnnotation(self, data):
        print('GRAPH NewAnnotation')
        pass

    def onNewClassification(self, data):
        print('GRAPH NewClassification')
        pass

    def onNewDescription(self, data):
        print('GRAPH NewDescription')
        pass

    def onNewNumber(self, data):
        print('GRAPH NewNumber')
        pass

    def onPrint(self, data):
        print('GRAPH Print')
        pass

    def onStop(self, data):
        print('GRAPH Stop')
        self.Client.stop()
        pass

    def getDefaultLineStyle(self,type):
        if type == 'Limit':
            self.defaultColor = self.config['LineStyle']['limit_color']
            self.defaultStyle = self.config['LineStyle']['limit_style']
            self.defaultWidth = self.config['LineStyle']['limit_width']
        if type == 'Antenna':
            self.defaultColor = self.config['LineStyle']['antenna_color']
            self.defaultStyle = self.config['LineStyle']['antenna_style']
            self.defaultWidth = self.config['LineStyle']['antenna_width']
        if type == 'Cable':
            self.defaultColor = self.config['LineStyle']['cable_color']
            self.defaultStyle = self.config['LineStyle']['cable_style']
            self.defaultWidth = self.config['LineStyle']['cable_width']
        if type == 'Line':
            self.defaultColor = self.config['LineStyle']['line_color']
            self.defaultStyle = self.config['LineStyle']['line_style']
            self.defaultWidth = self.config['LineStyle']['line_width']
        if type == 'Trace':
            self.defaultColor = self.config['LineStyle']['trace_color']
            self.defaultStyle = self.config['LineStyle']['trace_style']
            self.defaultWidth = self.config['LineStyle']['trace_width']
        if type == 'TraceOverload':
            self.defaultColor = self.config['LineStyle']['trace_overload_color']
            self.defaultStyle = self.config['LineStyle']['trace_overload_style']
            self.defaultWidth = self.config['LineStyle']['trace_overload_width']
        if type == 'TraceUncal':
            self.defaultColor = self.config['LineStyle']['trace_uncal_color']
            self.defaultStyle = self.config['LineStyle']['trace_uncal_style']
            self.defaultWidth = self.config['LineStyle']['trace_uncal_width']
        if type == 'Analyse':
            self.defaultColor = self.config['LineStyle']['anaylse_color']
            self.defaultStyle = self.config['LineStyle']['anaylse_style']
            self.defaultWidth = self.config['LineStyle']['anaylse_width']
        pass

    def initGraph(self):
                # create a figure

        self.figure_canvasReference.setParent(self.ui.frame_3)
        layoutR = QtGui.QVBoxLayout()
        self.ui.frame_3.setLayout(layoutR)
        layoutR.addWidget(self.figure_canvasReference, 0)
        # and the axes for the figure
        self.axesR = self.figure_canvasReference.figure.add_subplot(111)
        self.axesR.set_ylabel('dBµV')
        self.axesR.set_xlabel('Hz')
        self.axesR.grid(True)
        self.axesR.set_xscale('log')
        formatterHZ = EngFormatter(unit = '',places=0)
        formatterDB = EngFormatter(unit = '',places=1)
        self.axesR.xaxis.set_major_formatter(formatterHZ)
        self.axesR.yaxis.set_major_formatter(formatterDB)
        self.axesR.xaxis.label.set_color('yellow')
        self.axesR.yaxis.label.set_color('yellow')
        self.axesR.title.set_color('yellow')
        self.axesR.title.set_text('Reference')
        self.figure_canvasReference.show()

        self.figure_canvasCurrent.setParent(self.ui.frame_4)
        layoutC = QtGui.QVBoxLayout()
        self.ui.frame_4.setLayout(layoutC)
        layoutC.addWidget(self.figure_canvasCurrent, 2)
        self.ui.frame_4.setLayout(layoutC)
        # and the axes for the figure
        self.axesC = self.figure_canvasCurrent.figure.add_subplot(111)
        self.axesC.set_ylabel('dBµV')
        self.axesC.set_xlabel('Hz')
        self.axesC.grid(True)
        self.axesC.set_xscale('log')
        formatterHZ = EngFormatter(unit = '',places=0)
        formatterDB = EngFormatter(unit = '',places=1)
        self.axesC.xaxis.set_major_formatter(formatterHZ)
        self.axesC.yaxis.set_major_formatter(formatterDB)
        self.axesC.xaxis.label.set_color('green')
        self.axesC.yaxis.label.set_color('green')
        self.axesC.title.set_color('green')
        self.axesC.title.set_text('Current')
        self.figure_canvasCurrent.show()
예제 #50
-1
파일: main.py 프로젝트: wimag/shtty-viewer
class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.shot = None  #opened shot
        self.folder_name = ''  #folder to search for shots
        self.current_num = 0  #current diagram
        self.currently_selected = None  #selected point plot
        self.selected_points = OrderedSet()  #point to be added
        self.current_point = None  #plot of current point
        self.overall_selected = None  #points added to selected list
        #super(Window, self).__init__(parent)
        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()
        self.canvas.setMinimumSize(500, 0)
        self.canvas.mpl_connect('pick_event', self.on_pick)
        self.canvas.mpl_connect('motion_notify_event', self.on_move)
        self.canvas.hide()

        # this is the Navigation widget
        # it takes the Canvas widget and a pa rent
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.toolbar.hide()

        # Show files widget
        self.files = QtGui.QListWidget()
        self.files.itemDoubleClicked.connect(self.select_file)
        self.files.setMaximumSize(200, 100000)
        self.files.setMinimumSize(100, 0)
        self.files.hide()

        # Show selected points
        self.points = ThumbListWidget(self)
        #self.points.itemDoubleClicked.connect(self.unselect_point)
        self.points.itemClicked.connect(self.points_clicked)
        self.points.itemDoubleClicked.connect(self.points_doubleclicked)
        self.points.setMaximumSize(200, 100000)
        self.points.setMinimumSize(100, 0)
        self.points.hide()

        #Show diagram widget
        self.diagrams = QtGui.QListWidget()
        self.diagrams.itemClicked.connect(self.select_item)
        self.diagrams.setMaximumSize(250, 100000)
        self.diagrams.setMinimumSize(190, 0)
        self.diagrams.hide()

        #save result button
        self.save_button = QtGui.QPushButton('Add time point', self)
        self.save_button.clicked.connect(self.add_time)
        self.save_button.hide()

        #filter menu
        self.filters_button = QtGui.QPushButton('Manage filters', self)
        self.filters_button.clicked.connect(self.show_filters)
        self.filters_button.hide()
        self.filters = OrderedDict
        self.read_filters()


        #diagramms
        self.bottom_layout = QtGui.QGridLayout()
        self.diagrams_figure = plt.figure()
        self.diagrams_canvas = FigureCanvas(self.diagrams_figure)
        self.diagrams_canvas.setParent(parent)
        self.diagrams_canvas.setMinimumSize(250, 250)
        self.diagrams_canvas.setMaximumSize(500, 500)
        self.diagrams_toolbar = NavigationToolbar(self.diagrams_canvas, self)
        self.diagrams_toolbar.setMaximumWidth(250)
        self.diagrams_ax = self.diagrams_figure.add_subplot(111)
        self.diagrams_ax.set_ylim(ymin=0)
        self.diagrams_ax.set_xlim(xmin=0)
        self.diagrams_canvas.draw()

        self.enlargre_button = QtGui.QPushButton('Enlarge diagram', self)
        self.enlargre_button.clicked.connect(self.enlarge_diagram)

        self.bottom_layout.addWidget(self.diagrams_toolbar, 0, 2)
        self.bottom_layout.addWidget(self.diagrams_canvas, 1, 2, QtCore.Qt.AlignRight)
        self.bottom_layout.addWidget(self.enlargre_button, 0, 1)

        # set the layout
        self.layout = QtGui.QGridLayout()
        self.layout.addWidget(self.filters_button, 0, 1)
        self.layout.addWidget(self.toolbar, 0, 2)
        self.layout.addWidget(self.canvas, 1, 2)
        self.layout.addWidget(self.diagrams, 1, 1)
        self.layout.addWidget(self.files, 1, 0)
        self.layout.addWidget(self.points, 1, 3)
        self.layout.addWidget(self.save_button, 0, 3)
        self.layout.addLayout(self.bottom_layout, 2, 2)
        self.setLayout(self.layout)


    def enlarge_diagram(self): #меняет местами диаграммы
        pass

    def points_doubleclicked(self):
        if self.points._mouse_button == 1:
            num = self.points.currentRow()
            point = list(self.selected_points)[num]
            diag = self.shot.get_diagram(self.current_num)

            xs = np.array(diag.x)
            ys = np.array(diag.y)

            idx = np.absolute(xs - point[0]).argmin()

            npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0])
            for point in list(self.selected_points):
                if point[2] == self.current_point[2] and point[3] == self.current_point[3]:
                    self.selected_points.remove(point)
            self.selected_points.add(npoint)
            self.refresh_points()


    def greenvald(self): #диаграмма хьюгилла #TODO - move to another file
        temp = {}
        names = self.shot.get_diagram_names()
        for x in self.selected_points:
            if x[3] not in temp:
                temp[x[3]] = {}
            tag = ""
            for name, value in self.filters.items():
                if re.compile(value).match(names[x[2]]):
                    tag = name
                    break
            if tag:
                temp[x[3]][tag] = x[0], x[1], x[3] #X, Y, Shot
        points = []
        for x in temp:
            if "Ip" in temp[x] and "neL" in temp[x] and "ITF" in temp[x]:
                a = 24
                R = 36
                k = 1.65

                #print("wololo")

                Ip = temp[x]["Ip"][1]/1000
                Itf = temp[x]["ITF"][1]/1000
                neL = temp[x]["neL"][1]
                Bt = Itf*0.001*100*16*0.2/R
                print(Ip)
                print(Itf)
                print(neL)
                print(Bt)
                qcyl = 5*a*a*0.01*0.01*Bt*100*1000/(R*Ip)
                print(qcyl)
                #print(temp[x])
                #print(Itf)
                #print(neL)

                rqcyl = 1/qcyl
                print(rqcyl)
                print("wololo")
                ne = neL*0.03/k
                BtrR = Bt*100/R
                print(ne)
                print(BtrR)
                neRrBt = ne/BtrR
                print(neRrBt)
                points.append(((neRrBt, rqcyl), temp[x]["Ip"][2]))
        return points

    def update_diagramms(self):
        points = self.greenvald()
        x = [tmp[0][0] for tmp in points]
        y = [tmp[0][1] for tmp in points]
        #self.diagrams_figure.clf()
        self.diagrams_ax.set_xlabel('neR/BT, 10^20/(T*m^2)')
        self.diagrams_ax.set_ylabel('1/qcyl')
        self.diagrams_ax.set_title("Greenwald")
        self.diagrams_ax.plot(x, y, 'bo', ms=5, alpha=0.8, markersize=5)
        self.diagrams_canvas.draw()
        print(points)

    def points_clicked(self):#один клик, правая кнопка - удалить точку, левая - подсветить
        if self.points._mouse_button == 1:
            num = self.points.currentRow()
            point = list(self.selected_points)[num]
            diag = self.shot.get_diagram(self.current_num)

            xs = np.array(diag.x)
            ys = np.array(diag.y)

            idx = np.absolute(xs - point[0]).argmin()

            self.highlight.set_xdata([xs[idx]])
            self.highlight.set_ydata([ys[idx]])
        else:
            self.unselect_point(None)


    def read_filters(self):
        with open("filters.conf") as inp:
            lines = inp.readlines()
        n = int(lines[0])
        mass = []
        for i in range(n):
            mass.append((lines[2*i+1].strip(), lines[2*(i+1)].strip()))
        self.filters = OrderedDict(mass)


    def show_filters(self):
        self.f = FiltersPopup(self.filters)
        self.f.setGeometry(100, 100, 400, 200)
        self.f.exec_()
        self.filters = self.f.getValues()
        self.show_diagrams()



    def add_time(self):
        time, ok = QtGui.QInputDialog.getText(self, 'Time point', 'enter time point in seconds(e.g. 0.123):')
        if ok:
            if time.isdigit:
                diag = self.shot.get_diagram(self.current_num)

                xs = np.array(diag.x)
                ys = np.array(diag.y)

                idx = np.absolute(xs - float(time)/1000).argmin()

                npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0])
                for point in list(self.selected_points):
                    if point[2] == self.current_point[2] and point[3] == self.current_point[3]:
                        print("wololololololo")
                        self.selected_points.remove(point)
                self.selected_points.add(npoint)
                self.refresh_points()

    def select_item(self, current):
        self.figure.clf()
        name = self.diagrams.currentItem().text()
        names = self.shot.get_diagram_names()
        if name in names:
            self.current_num = names.index(name)
        else:
            self.current_num = names.index("".join(name.split(':')[1:])[1:])
        self.plot(self.shot.get_diagram(self.current_num))

    def unselect_point(self, current):
        num = self.points.currentRow()
        self.selected_points.remove(list(self.selected_points)[num])
        self.refresh_points()

    def select_file(self, current):
        self.figure.clf()
        self.show_shot(Shot(join(self.folder_name, self.files.currentItem().text())))
        self.canvas.setFocus()

    def on_pick(self, event):
        print(self.selected_points)
        if self.current_point in self.selected_points:
            self.selected_points.remove(self.current_point)
        else:
            for point in list(self.selected_points):
                if point[2] == self.current_point[2] and point[3] == self.current_point[3]:
                    print("wololo")
                    self.selected_points.remove(point)
            self.selected_points.add(self.current_point)
        self.refresh_points()

    def refresh_points(self):
        self.update_diagramms()
        self.points.clear()
        self.points.addItems([str(x[0]) for x in self.selected_points])
        self.overall_selected.set_xdata(self.active_points[0])
        self.overall_selected.set_ydata(self.active_points[1])


    def on_move(self, event):
        # get the x and y pixel coords
        x, y = event.x, event.y

        if event.inaxes:
            ax = event.inaxes  # the axes instance
            diag = self.shot.get_diagram(self.current_num)

            xs = np.array(diag.x)
            ys = np.array(diag.y)

            idx = np.absolute(xs - event.xdata).argmin()
            self.currently_selected.set_xdata([diag.x[idx]])
            self.currently_selected.set_ydata([diag.y[idx]])
            self.current_point = (diag.x[idx], diag.y[idx], self.current_num, self.shot.file[0])
            self.canvas.draw()

    @property
    def active_points(self):
        x = [x[0] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]]
        y = [x[1] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]]
        return x, y

    def plot(self, diagram=None):
        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph


        #pridicted max value
        ind = np.argmax(np.array(diagram.y))
        # plot data
        if diagram:
            self.highlight, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'bo', ms=12, alpha=0.8, markersize=8)
            ax.plot(diagram.x, diagram.y, 'b-')
            self.currently_selected, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'yo', ms=12, alpha=0.6, markersize=6,
                                               picker=15)
            self.overall_selected, = ax.plot(self.active_points[0], self.active_points[1], 'ro', ms=12, alpha=0.9,
                                             markersize=4)
            ax.set_xlabel('t, sec')
            ax.set_ylabel(diagram.unit)
            ax.set_title(diagram.comment)
            self.figure.tight_layout()
        # refresh canvas
        self.canvas.draw()

    def show_diagrams(self):
        names = self.shot.get_diagram_names()
        self.diagrams.clear()
        res = set()
        for x in names:
            for name, reg in self.filters.items():
                try:
                    if re.compile(reg).match(x):
                        res.add(str(name) + ': ' + str(x))
                        break
                except:
                    pass
        #self.diagrams.addItems(list(names))
        self.diagrams.addItems(list(res))
        self.diagrams.show()

    def show_shot(self, shot):
        self.shot = shot
        self.show_diagrams()
        self.toolbar.show()
        self.canvas.show()
        self.files.show()
        self.points.show()
        self.save_button.show()
        self.filters_button.show()
        self.current_num = 0
        self.plot(self.shot.get_diagram(0))
        self.canvas.setFocus()