예제 #1
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()
예제 #2
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()
예제 #3
0
class Ui_LboardWindow(QtGui.QWidget):

    user_names = []
    learned_count = []
    #Quiztaken= []
    #avg_quiz_score= []
    cur = conn.cursor()
    uname = []
    name = ""
    total = 0

    def __init__(self, parent=None):
        super(Ui_LboardWindow, self).__init__()
        self.figure = plt.figure(figsize=(50, 20), facecolor="white")  #
        self.canvas = FigureCanvas(
            self.figure)  #create canvas that will hold our plot
        #self.toolbar = NavigationToolbar(self.canvas,self)

    def setupUi(self, LboardWindow, StatusWindow, username):

        self.lw = LboardWindow
        self.username = username
        self.sw = StatusWindow
        self.cur.execute("select count(*) from users")
        self.rcount = self.cur.fetchone()[0]

        LboardWindow.setObjectName(_fromUtf8("LboardWindow"))
        LboardWindow.resize(640, 480)
        LboardWindow.setGeometry(320, 100, 640, 480)
        LboardWindow.setMinimumSize(QtCore.QSize(640, 480))
        LboardWindow.setMaximumSize(QtCore.QSize(640, 480))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Ubuntu Condensed"))
        font.setPointSize(14)
        LboardWindow.setFont(font)
        LboardWindow.setStyleSheet(
            _fromUtf8("background-color: rgb(255, 255, 255);\n"
                      "color: rgb(0, 0, 0);"))
        self.gridLayoutWidget = QtGui.QWidget(LboardWindow)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(17, 141, 601, 311))
        self.gridLayoutWidget.setObjectName(_fromUtf8("gridLayoutWidget"))
        self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.labheader = QtGui.QLabel(LboardWindow)
        self.labheader.setGeometry(QtCore.QRect(18, 22, 601, 51))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Ubuntu Condensed"))
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.labheader.setFont(font)
        self.labheader.setStyleSheet(
            _fromUtf8("background-color: rgb(59, 89, 152);\n"
                      "color: rgb(255, 255, 255);"))
        self.labheader.setAlignment(QtCore.Qt.AlignCenter)
        self.labheader.setObjectName(_fromUtf8("labheader"))
        self.tableWidget = QtGui.QTableWidget(LboardWindow)
        self.tableWidget.setGeometry(QtCore.QRect(104, 207, 430, 210))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.tableWidget.sizePolicy().hasHeightForWidth())
        self.tableWidget.setSizePolicy(sizePolicy)
        #self.tableWidget.setMinimumSize(QtCore.QSize(600, 310))
        #self.tableWidget.setMaximumSize(QtCore.QSize(600, 310))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Ubuntu Condensed"))
        font.setPointSize(14)
        self.tableWidget.setFont(font)
        self.tableWidget.setFrameShadow(QtGui.QFrame.Plain)
        self.tableWidget.setEditTriggers(
            QtGui.QAbstractItemView.NoEditTriggers)
        self.tableWidget.setAlternatingRowColors(False)
        self.tableWidget.setShowGrid(True)
        self.tableWidget.setGridStyle(QtCore.Qt.SolidLine)

        self.tableWidget.setRowCount(self.rcount)

        self.tableWidget.setColumnCount(3)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(0, 0, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(0, 1, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(1, 0, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(1, 1, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(2, 0, item)
        item = QtGui.QTableWidgetItem()
        self.tableWidget.setItem(2, 1, item)

        self.btn_showgraph = QtGui.QPushButton(LboardWindow)
        self.btn_showgraph.setGeometry(QtCore.QRect(530, 130, 41, 41))
        self.btn_showgraph.setStyleSheet(
            _fromUtf8("background-color: rgb(59, 89, 152);"))
        self.btn_showgraph.setText(_fromUtf8(""))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("fwd.png")), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        self.btn_showgraph.setIcon(icon)
        self.btn_showgraph.setObjectName(_fromUtf8("btn_showgraph"))
        self.btn_showtable = QtGui.QPushButton(LboardWindow)
        self.btn_showtable.setGeometry(QtCore.QRect(470, 130, 41, 41))
        self.btn_showtable.setStyleSheet(
            _fromUtf8("background-color: rgb(59, 89, 152);"))
        self.btn_showtable.setText(_fromUtf8(""))
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(_fromUtf8("rewnd.png")),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_showtable.setIcon(icon1)
        self.btn_showtable.setObjectName(_fromUtf8("btn_showtable"))

        #self.tableWidget.setColumnWidth(1, 200)
        self.tableWidget.setColumnWidth(1, 150)
        self.tableWidget.setHorizontalHeaderLabels(('Rank', 'Name', 'Score'))
        self.tableWidget.horizontalHeader().setVisible(True)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.verticalHeader().setVisible(False)
        self.lab_headoftable = QtGui.QLabel(LboardWindow)
        self.lab_headoftable.setGeometry(QtCore.QRect(40, 140, 200, 21))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Ubuntu Condensed"))
        font.setPointSize(14)
        self.lab_headoftable.setFont(font)
        self.lab_headoftable.setAlignment(QtCore.Qt.AlignLeading
                                          | QtCore.Qt.AlignLeft
                                          | QtCore.Qt.AlignVCenter)
        self.lab_headoftable.setObjectName(_fromUtf8("lab_headoftable"))
        self.bck_btn = QtGui.QPushButton(LboardWindow)
        self.bck_btn.setGeometry(QtCore.QRect(18, 22, 51, 51))
        self.bck_btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.bck_btn.setStyleSheet(
            _fromUtf8("background-color: rgba(255, 255, 255, 0);"))
        self.bck_btn.setText(_fromUtf8(""))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("back.png")),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.bck_btn.setIcon(icon)
        self.bck_btn.setIconSize(QtCore.QSize(25, 25))
        self.bck_btn.setFlat(False)
        self.bck_btn.setObjectName(_fromUtf8("bck_btn"))

        self.btn_showgraph.clicked.connect(self.btnShowGraphClicked)
        self.btn_showtable.clicked.connect(self.btnShowTableClicked)
        self.bck_btn.clicked.connect(self.btnBKClicked)

        self.btn_showgraph.show()
        self.btn_showtable.hide()

        for i in range(self.rcount):
            self.newitem3 = QtGui.QTableWidgetItem(str(i + 1))
            self.newitem3.setTextAlignment(0x0004 | 0x0080)
            self.tableWidget.setItem(i, 0, self.newitem3)

        self.bck_btn.clicked.connect(self.btnBKClicked)

        fetch = self.cur.execute(
            "select username, score from users order by score desc")
        fetch = list(fetch)

        for i in range(self.rcount):
            self.newitem1 = QtGui.QTableWidgetItem(fetch[i][0])
            self.newitem2 = QtGui.QTableWidgetItem(str(fetch[i][1]))
            self.newitem1.setTextAlignment(0x0004 | 0x0080)
            self.newitem2.setTextAlignment(0x0004 | 0x0080)
            self.tableWidget.setItem(i, 1, self.newitem1)
            self.tableWidget.setItem(i, 2, self.newitem2)

        self.retranslateUi(LboardWindow)
        QtCore.QMetaObject.connectSlotsByName(LboardWindow)

    def retranslateUi(self, LboardWindow):
        LboardWindow.setWindowTitle(
            _translate("LboardWindow", "GRE Vocab Builder", None))
        self.labheader.setText(_translate("LboardWindow", "LeaderBoard", None))
        self.tableWidget.setSortingEnabled(False)
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.lab_headoftable.setText(
            _translate("LboardWindow", "Current LeaderBoard ", None))

    def btnShowTableClicked(self):
        self.lab_headoftable.setText("Current LeaderBoard ")
        self.btn_showgraph.show()
        self.btn_showtable.hide()
        self.canvas.hide()
        self.tableWidget.show()

    def btnShowGraphClicked(self):
        self.figure = plt.figure(figsize=(50, 20), facecolor="white")  #
        self.canvas = FigureCanvas(
            self.figure)  #create canvas that will hold our plot
        self.learned_count[:] = []
        self.uname[:] = []
        self.tableWidget.hide()
        self.btn_showgraph.hide()
        self.btn_showtable.show()
        self.gridLayout.addWidget(self.canvas, 1, 0, 1, 2)
        self.cur.execute("select count(username) from users")
        self.total = self.cur.fetchone()[0]

        self.cur1 = conn.execute("select username from users")
        for row in self.cur1:
            name = row[0]
            name = name.encode('utf-8')
            self.uname.append(name)

        for user in self.uname:

            self.cur.execute("select count(" + user +
                             ") from allwords where " + user + "=2 or " +
                             user + "=3")
            self.lCount = self.cur.fetchone()[0]
            self.learned_count.append(self.lCount)

        width = 0.2
        ind1 = np.arange(len(self.uname))
        plt.cla()
        ax = self.figure.add_subplot(111)

        rects1 = ax.bar(ind1 + width,
                        self.learned_count,
                        width,
                        color='blue',
                        error_kw=dict(elinewidth=2, ecolor='red'))
        ax.set_xticks(ind1 + 0.0 + width)
        ax.set_xticklabels(self.uname, rotation='vertical')
        ax.set_ylabel("Learned Words")
        ax.set_xlabel(" ")
        self.lab_headoftable.setText("Learned Words Comparision")
        plt.tight_layout(rect=[0.15, 0.20, 0.90, 0.85])
        #ax.set_title("Learning Stats for all users",fontsize = 20)
        #ax.legend((rects1[0],rects2[0]),('Learned','avg_score'))

    def btnBKClicked(self):
        self.lw.hide()
        self.sw.show()
예제 #4
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
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)
예제 #6
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
예제 #7
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
예제 #8
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]])
예제 #9
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()
예제 #10
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()
예제 #11
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()
예제 #12
-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()