예제 #1
0
파일: Qbit.py 프로젝트: BogoslovskiyDA/QBit
    def draw_graph_first(self):
        # Создание кубита. Рисование сферы и осей
        plt.close()
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.plot_wireframe(self.x, self.y, self.z, color="black", lw=0.5)
        frame1 = plt.gca()
        frame1.axes.xaxis.set_ticklabels([])
        frame1.axes.yaxis.set_ticklabels([])
        frame1.axes.zaxis.set_ticklabels([])
        x, y, z = self.convert_3d_plot_first(0, 0, 1)
        ax.quiver(0, 0, 0, x, y, z, length=1.0, color='red', lw=4)

        ax.quiver(0, 0, 0, 0, 0, 1.7, length=1.0, color='green', lw=1)
        ax.text(0, 0, 1.8, 'Z', rotation=38, fontsize=10)
        ax.text(0, 0, 1.2, '|0>', rotation=38, fontsize=13, color='red')
        ax.text(0, 0, -1.2, '|1>', rotation=38, fontsize=13, color='red')

        ax.quiver(0, 0, 0, 0, -1.7, 0, length=1.0, color='green', lw=1)
        ax.text(0, -1.8, 0, 'X', rotation=38, fontsize=10)

        ax.quiver(0, 0, 0, 1.7, 0, 0, length=1.0, color='green', lw=1)
        ax.text(1.8, 0, 0, 'Y', rotation=38, fontsize=10)

        ax.view_init(elev=self.Alpha3D, azim=self.Beta3D)
        ax.dist = 9
        ax.grid(False)
        scene = QGraphicsScene(self)
        scene.setSceneRect(100, 100, 300, 300)
        canvas = FigureCanvas(fig)
        canvas.setGeometry(0, 0, 500, 500)
        scene.addWidget(canvas)
        self.graphicsView.setScene(scene)
class Ui_MetawearApp(object):
    def setupUi(self, MetawearApp):
        MetawearApp.setObjectName("MetawearApp")
        MetawearApp.resize(428, 247)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setGeometry(QtCore.QRect(0, 0, 428, 247))
        self.buttonConnect = QtWidgets.QPushButton(MetawearApp)
        self.buttonConnect.setGeometry(QtCore.QRect(100, 50, 121, 31))
        self.buttonConnect.setObjectName("buttonConnect")
        self.labelConnect = QtWidgets.QLabel(MetawearApp)
        self.labelConnect.setGeometry(QtCore.QRect(230, 60, 181, 17))
        self.labelConnect.setObjectName("labelConnect")
        self.buttonGatherData = QtWidgets.QPushButton(MetawearApp)
        self.buttonGatherData.setGeometry(QtCore.QRect(100, 90, 121, 31))
        self.buttonGatherData.setObjectName("buttonGatherData")
        self.labelGatherData = QtWidgets.QLabel(MetawearApp)
        self.labelGatherData.setGeometry(QtCore.QRect(230, 100, 171, 17))
        self.labelGatherData.setObjectName("labelGatherData")
        self.buttonExit = QtWidgets.QPushButton(MetawearApp)
        self.buttonExit.setGeometry(QtCore.QRect(60, 200, 97, 27))
        self.buttonExit.setObjectName("buttonExit")
        self.secondsSpin = QtWidgets.QSpinBox(MetawearApp)
        self.secondsSpin.setGeometry(QtCore.QRect(30, 90, 60, 27))
        self.secondsSpin.setMinimum(1)
        self.secondsSpin.setObjectName("secondsSpin")
        self.label = QtWidgets.QLabel(MetawearApp)
        self.label.setGeometry(QtCore.QRect(30, 120, 66, 17))
        self.label.setObjectName("label")
        self.buttonDownloadData = QtWidgets.QPushButton(MetawearApp)
        self.buttonDownloadData.setGeometry(QtCore.QRect(100, 130, 121, 31))
        self.buttonDownloadData.setObjectName("buttonDownloadData")
        self.labelDownloadData = QtWidgets.QLabel(MetawearApp)
        self.labelDownloadData.setGeometry(QtCore.QRect(230, 140, 181, 17))
        self.labelDownloadData.setObjectName("labelDownloadData")
        self.nameText = QtWidgets.QLineEdit(MetawearApp)
        self.nameText.setGeometry(QtCore.QRect(100, 10, 301, 27))
        self.nameText.setObjectName("nameText")
        self.label_2 = QtWidgets.QLabel(MetawearApp)
        self.label_2.setGeometry(QtCore.QRect(50, 10, 41, 20))
        self.label_2.setObjectName("label_2")

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

    def retranslateUi(self, MetawearApp):
        _translate = QtCore.QCoreApplication.translate
        MetawearApp.setWindowTitle(_translate("MetawearApp", "Metawear App"))
        self.buttonConnect.setText(_translate("MetawearApp", "Connect"))
        self.labelConnect.setText(_translate("MetawearApp", "..."))
        self.buttonGatherData.setText(_translate("MetawearApp", "Gather Data"))
        self.labelGatherData.setText(_translate("MetawearApp", "..."))
        self.buttonExit.setText(_translate("MetawearApp", "Exit"))
        self.label.setText(_translate("MetawearApp", "seconds"))
        self.buttonDownloadData.setText(
            _translate("MetawearApp", "Download Data"))
        self.labelDownloadData.setText(_translate("MetawearApp", "..."))
        self.label_2.setText(_translate("MetawearApp", "Name"))
예제 #3
0
 def histogram(self, data):
     print('test')
     window = QtGui.QMainWindow(self)
     window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     window.setWindowTitle(self.tr('Histogram'))
     window.setFixedSize(600, 600)
     figure = Figure()  #Create fig
     canvas = FigureCanvasQTAgg(figure)
     canvas.setParent(window)
     canvas.setGeometry(10, 10, 580, 580)
     ax = figure.add_subplot(111)
     ax.hist(data, 100)
     canvas.draw()
     window.show()
예제 #4
0
    def bruteplot(self, data):

        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        window.setWindowTitle(self.tr('Best Moving Average'))
        window.setFixedSize(1000, 600)
        figure = Figure()  #Create fig
        canvas = FigureCanvasQTAgg(figure)
        canvas.setParent(window)
        canvas.setGeometry(10, 10, 980, 580)
        ax = figure.add_subplot(111)
        ax.plot(data)
        canvas.draw()
        window.show()
예제 #5
0
파일: mainwindow.py 프로젝트: SMLMS/Colibri
 def plotBFP(self):
     r=self.settings[0].__getitem__('radius')
     e=self.settings[0].__getitem__('ellipticity')
     p=self.settings[0].__getitem__('phase')
     dx=self.settings[0].__getitem__('x_shift')
     dy=self.settings[0].__getitem__('y_shift')
     self.bfp.setValues(r, e, p, dx, dy)
     self.bfp.funcMirror()
     figure=self.bfp.definePlot()
     scene = QtGui.QGraphicsScene()
     canvas = FigureCanvas(figure)
     canvas.setGeometry(0, 0, 189, 189)
     scene.addWidget(canvas)
     self.ui.graphicsView.setScene(scene)
     self.ui.graphicsView.show()
예제 #6
0
    def __init__(self):
        QtWidgets.QGraphicsView.__init__(self)

        scene = QtWidgets.QGraphicsScene(self)
        self.scene = scene

        figure = Figure()
        axes = figure.gca()
        axes.set_title("title")
        axes.plot(plt.contourf(xx, yy, Z,cmap=plt.cm.autumn, alpha=0.8))
        canvas = FigureCanvas(figure)
        canvas.setGeometry(0, 0, 500, 500)
        scene.addWidget(canvas)

        self.setScene(scene)
예제 #7
0
    def __init__(self):
        super(MPLPlot, self).__init__()

        figure = Figure()
        axes = figure.gca()
        axes.set_title("Use the mouse wheel to zoom")
        axes.plot(np.random.rand(5))
        canvas = FigureCanvas(figure)
        canvas.setGeometry(0, 0, 500, 500)

        imgdata = StringIO.StringIO()
        figure.savefig(imgdata, format='svg')
        imgdata.seek(0)
        xmlreader = QtCore.QXmlStreamReader(imgdata.getvalue())
        self.renderer = QtSvg.QSvgRenderer(xmlreader)
예제 #8
0
파일: Qbit.py 프로젝트: BogoslovskiyDA/QBit
    def draw_move_2(self):
        if (self.my_counter == 200):
            self.my_counter = 0

        self.my_counter += 1

        self.moveTeta = self.my_counter * np.pi / 100
        self.movePhi = np.pi + self.Hook*self.moveTeta*0.5

        #Создание кубита. Рисование сферы и осей
        plt.close()
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.plot_wireframe(self.x, self.y, self.z, color="black", lw=0.5)
        frame1 = plt.gca()
        frame1.axes.xaxis.set_ticklabels([])
        frame1.axes.yaxis.set_ticklabels([])
        frame1.axes.zaxis.set_ticklabels([])
        x, y, z = self.convert_3d_plot_move(0, 0, 1)
        ax.quiver(0, 0, 0, x, y, z, length=1.0, color='red', lw=4)

        ax.quiver(0, 0, 0, 0, 0, 1.7, length=1.0, color='green', lw=1)
        ax.text(0, 0, 1.8, 'Z', rotation=38, fontsize=10)
        ax.text(0, 0, 1.2, '|0>', rotation=38, fontsize=13, color='red')
        ax.text(0, 0, -1.2, '|1>', rotation=38, fontsize=13, color='red')

        ax.quiver(0, 0, 0, 0, -1.7, 0, length=1.0, color='green', lw=1)
        ax.text(0, -1.8, 0, 'X', rotation=38, fontsize=10)

        ax.quiver(0, 0, 0, 1.7, 0, 0, length=1.0, color='green', lw=1)
        ax.text(1.8, 0, 0, 'Y', rotation=38, fontsize=10)

        ax.view_init(elev=self.moveAlpha3D, azim=self.moveBeta3D)
        ax.dist = 9
        ax.grid(False)
        scene = QGraphicsScene(self)
        scene.setSceneRect(100, 100, 300, 300)
        canvas = FigureCanvas(fig)
        canvas.setGeometry(0, 0, 500, 500)
        scene.addWidget(canvas)
        self.graphicsView_2.setScene(scene)
        self.label_3.setText(f'{round(np.cos(self.moveTeta/2) ** 2, 4)}')
        self.label_4.setText(f'{round(np.sin(self.moveTeta/2) ** 2, 4)}')
예제 #9
0
파일: main.py 프로젝트: Akashi23/Qt_tests
    def compute(self):
        self.listWidget.clear()

        if self.comboBox.currentText() == 'xgboost':
            lis = self.calc.xgboosting()
            figure = self.calc.plot_pred(self.calc.predicts)
            scene = QGraphicsScene()
            canvas = FigureCanvas(figure)
            canvas.setGeometry(0, 0, 650, 650)
            scene.addWidget(canvas)

            self.graphicsView.setScene(scene)
            self.graphicsView.show()

            for result_name in lis:
                self.listWidget.addItem(result_name)

        elif self.comboBox.currentText() == 'naive_bayes':
            lis = self.calc.naive_bayes_calc()
            figure = self.calc.plot_pred(self.calc.predicts)
            scene = QGraphicsScene()
            canvas = FigureCanvas(figure)
            canvas.setGeometry(0, 0, 650, 650)
            scene.addWidget(canvas)

            self.graphicsView.setScene(scene)
            self.graphicsView.show()
            for result_name in lis:
                self.listWidget.addItem(result_name)

        elif self.comboBox.currentText() == 'kmeans':
            figure1, figure2 = self.calc.kmeans_plot()
            scene = QGraphicsScene()
            canvas = FigureCanvas(figure1)
            canvas.setGeometry(0, 0, 650, 650)
            scene.addWidget(canvas)

            self.graphicsView.setScene(scene)
            self.graphicsView.show()

            scene = QGraphicsScene()
            canvas = FigureCanvas(figure2)
            canvas.setGeometry(0, 0, 650, 650)
            scene.addWidget(canvas)

            self.graphicsView_2.setScene(scene)
            self.graphicsView_2.show()
예제 #10
0
class PlotInitWidget(CoreWidget):
    def __init__(self,
                 *args,
                 b_x_start=75,
                 b_height=30,
                 b_space=10,
                 b_width=None,
                 f_left=0.04,
                 f_top=0.98,
                 f_bottom=0.17,
                 f_height=350,
                 f_width=1600,
                 f_start_y=30,
                 g_width=1900,
                 g_height=None,
                 canvas_geom=None,
                 draw_h_line=False,
                 language="EN",
                 **kwargs):

        super(PlotInitWidget, self).__init__(*args,
                                             language=language,
                                             **kwargs)

        self.draw_h_line = draw_h_line
        self.canvas_geom = canvas_geom
        self.f_start_y = f_start_y
        self.f_left, = f_left,
        self.f_right = 1 - self.f_left
        self.f_top, self.f_bottom, self.f_height, self.f_width = f_top, f_bottom, f_height, f_width
        self.b_x_start, self.b_height, self.b_space = b_x_start, b_height, b_space
        self.g_height, self.g_width = g_height, g_width

        if self.g_height is None and not self.draw_h_line:
            self.g_height = self.f_height + 3 * self.b_height + 4 * self.b_space

        if self.g_height is None and self.draw_h_line:
            self.g_height = self.f_height + 4 * self.b_height + 5 * self.b_space

        self.b_width = b_width
        if self.b_width is None:
            self.b_width = int((self.f_width - 2 * self.b_x_start -
                                (self.b_num - 1) * self.b_space) / self.b_num)

        self.set_b_coord(
            item={
                "x_s": self.b_x_start,
                "y_s": self.f_height + self.b_space,
                "w": self.b_width,
                "h": self.b_height,
                "s": self.b_space
            })
        self.set_global_geom(item=(0, 0, self.g_width, self.g_height))

        self.InitCoreUi()

    def HistUiCall(self):
        self.set_canvas_geom()
        self.init_HistUi()
        self.figure.subplots_adjust(left=self.f_left,
                                    right=self.f_right,
                                    top=self.f_top,
                                    bottom=self.f_bottom)

    def set_canvas_geom(self, item=None):
        if self.canvas_geom is None:
            self.canvas_geom = self.calc_canvas_geom()
        if item is not None:
            self.canvas_geom = item

    def calc_canvas_geom(self):
        x_axis_length = (self.b_num) * self.b_width + (
            self.b_num) * self.b_space
        tot_f_length = x_axis_length * 1 / (1 -
                                            (1 - self.f_right) - self.f_left)
        return (self.b_x_start - tot_f_length * self.f_left, self.f_start_y,
                tot_f_length, self.f_height - self.f_start_y)

    def init_HistUi(self):
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.figure.set_facecolor("none")
        self.canvas.setParent(self)
        self.canvas_geom = tuple(int(it) for it in self.canvas_geom)
        self.canvas.setGeometry(QtCore.QRect(*self.canvas_geom))
    def plot_dataXY(self, MainWindow):

        counter = 0
        Position = np.array([0, 0, 0])
        ScatterX = []
        ScatterY = []
        ScatterAmp = []
        RangeXY = []
        DopplerXY = []
        rangeArray = []
        dopplerArray = []
        rangeDoppler = [[]]
        scene = QGraphicsScene()
        self.PlotXY.setScene(scene)
        figure = Figure()
        axes = figure.gca()
        scene1 = QGraphicsScene()
        self.Plot_RangeDoppler.setScene(scene1)
        figure1 = Figure()
        axes1 = figure1.gca()

        print(self.fileName)
        print(self.fin)
        for i in range(164):

            try:

                ScatterX, ScatterY, ScatterZ, ScatterAmp, RangeXY, DopplerXY, rangeArray, dopplerArray, rangeDoppler = processing(
                    self.fin, counter, Position)

                #axes.clf()

                #plt.style.use('dark_background')
                plt.clf()
                ax = plt.gca()
                #axes.clear()
                lines = axes.scatter(ScatterX,
                                     ScatterY,
                                     c=ScatterAmp,
                                     cmap=cm.rainbow)
                axes.set_title("Range Doppler")
                axes.set_xlim(xmin=-8, xmax=8)
                axes.set_ylim(ymin=0, ymax=8)
                axes.set_xlabel('left', text='X Position (m)')
                axes.set_ylabel('bottom', text='Y position (m)')
                #axes.grid()

                #mplcursors.cursor(lines)
                cursor = Cursor(axes,
                                horizOn=True,
                                vertOn=True,
                                color='green',
                                linewidth=2.0)

                #fig.canvas.mpl_connect('button_press_event',onclick)

                # ********************************************************************
                #axes1.clear()
                #axes1.imshow(rangeDoppler)
                axes1.imshow(rangeDoppler,
                             interpolation='nearest',
                             aspect='auto',
                             extent=[
                                 np.min(rangeArray),
                                 np.max(rangeArray),
                                 np.min(dopplerArray), -np.min(dopplerArray)
                             ])

                #axes1.grid()
                #axes.scatter(RangeXY,Doppler_Value)
                plt.draw()
                plt.pause(0.1)
                canvas = FigureCanvas(figure)

                canvas1 = FigureCanvas(figure1)

                canvas.setGeometry(QRect(10, 240, 331, 251))
                canvas1.setGeometry(QRect(850, 130, 481, 191))
                scene.addWidget(canvas)
                scene1.addWidget(canvas1)
            except BaseException:
                print("File no Traitable!!!")
    def update(self, MainWindow):
        dataOk = 0
        global detObj
        rangeDoppler = [[]]
        rangeArray = []
        dopplerArray = []
        x = []
        y = []
        rangeVal = []
        dopplerVal = []
        peakVal = []

        # Read and parse the received data
        #configParameters = parseConfigFile(configFileName)

        dataOk, frameNumber, detObj, rangeDoppler, rangeArray, dopplerArray = readAndParseData16xx(
            self.port1)
        print(rangeDoppler)

        if dataOk and len(detObj["x"]) > 0:

            # print(detObj)

            scene = QGraphicsScene()
            scene1 = QGraphicsScene()
            self.Plot_BitFreq_Pow.setScene(scene)
            self.Plot_RangeDoppler.setScene(scene1)
            figure = Figure()
            figure1 = Figure()
            axes = figure.gca()
            axes1 = figure1.gca()

            for i in range(1600):
                try:

                    #configParameters = parseConfigFile(configFileName)
                    dataOk, frameNumber, detObj, rangeDoppler, rangeArray, dopplerArray = readAndParseData16xx(
                        self.port1)
                    longitud = detObj["x"]
                    lateral = -detObj["y"]
                    rangeVal = detObj["RangeXY"]
                    dopplerVal = detObj["dopplerVal"]
                    peakVal = detObj["peakVal"]
                    print(detObj["x"])

                    # lateral,longitud,peakVal,rangeVal,dopplerVal = filtrer(dopplerVal,rangeVal,peakVal,20,longitud,lateral)
                    # filtrage
                    Longitude = []
                    Laterale = []
                    Portee = []
                    Velocity = []
                    Power = []
                    for ii in range(len(rangeVal)):
                        if rangeVal[ii] <= 20:
                            Longitude.append(longitud[ii])
                            Laterale.append(lateral[ii])
                            Portee.append(rangeVal[ii])
                            Velocity.append(dopplerVal[ii])
                            Power.append(peakVal[ii])

                    axes1.set_title("Range Doppler")

                    axes.set_title("Plot X and Y")
                    axes.set_xlim(xmin=-20, xmax=20)
                    axes.set_ylim(ymin=0, ymax=20)
                    axes.set_xlabel('left', text='X Position (m)')
                    axes.set_ylabel('bottom', text='Y Position (m)')

                    #print(i)
                    if len(lateral) > 2:
                        plt.draw()
                        #plt.connect('motion_notify_event', mouse_move)
                        plt.pause(0.1)
                        axes.clear()
                        axes1.clear()
                        axes1.imshow(rangeDoppler,
                                     interpolation='nearest',
                                     aspect='auto',
                                     extent=[
                                         np.min(rangeArray),
                                         np.max(rangeArray),
                                         np.min(dopplerArray),
                                         -np.min(dopplerArray)
                                     ])
                        axes.scatter(Laterale,
                                     Longitude,
                                     c=Power,
                                     cmap=cm.rainbow)
                        datacursor(display='multiple', draggable=True)
                        canvas = FigureCanvas(figure)
                        canvas1 = FigureCanvas(figure1)
                        canvas.setGeometry(QRect(850, 390, 491, 291))
                        canvas1.setGeometry(QRect(850, 130, 491, 221))
                        scene.addWidget(canvas)
                        scene1.addWidget(canvas1)

                except BaseException:
                    print("File no Traitable!!!")

        return dataOk
예제 #13
0
class Ui_Monitor(object):
    def setupUi(self, Monitor):
        Monitor.setObjectName(_fromUtf8("Monitor"))
        Monitor.resize(1060, 680)
        self.setrunning(Monitor)
        self.setbutton(Monitor)
        self.setramprate(Monitor)

        # matplotlib canvas
        self._figVI = Figure(facecolor="whitesmoke")
        self.plotVI = FigureCanvas(self._figVI)
        self.plotVI.setGeometry(QtCore.QRect(380, 20, 640, 400))
        self.plotVI.setObjectName(_fromUtf8("VIshow"))
        self.plotVI.setParent(Monitor)

        self._fig_tI = Figure(facecolor="whitesmoke")
        self.plot_tI = FigureCanvas(self._fig_tI)
        self.plot_tI.setGeometry(QtCore.QRect(40, 450, 300, 200))
        self.plot_tI.setObjectName(_fromUtf8("tIshow"))
        self.plot_tI.setParent(Monitor)

        self._fig_tVp = Figure(facecolor="whitesmoke")
        self.plot_tVp = FigureCanvas(self._fig_tVp)
        self.plot_tVp.setGeometry(QtCore.QRect(380, 450, 300, 200))
        self.plot_tVp.setObjectName(_fromUtf8("tVpshow"))
        self.plot_tVp.setParent(Monitor)

        self._fig_tVh = Figure(facecolor="whitesmoke")
        self.plot_tVh = FigureCanvas(self._fig_tVh)
        self.plot_tVh.setGeometry(QtCore.QRect(720, 450, 300, 200))
        self.plot_tVh.setObjectName(_fromUtf8("tVhshow"))
        self.plot_tVh.setParent(Monitor)

        self.retranslateUi(Monitor)
        #QtCore.QObject.connect(self.exit_but, QtCore.SIGNAL(_fromUtf8("clicked()")), Monitor.close)
        QtCore.QMetaObject.connectSlotsByName(Monitor)

    def retranslateUi(self, Monitor):
        Monitor.setWindowTitle(_translate("Monitor", "Form", None))
        self.supply_dis.setText(
            _translate("Dialog", "Current Supply: OFF", None))
        self.I_on_but.setText(_translate("Dialog", "ON", None))
        self.I_up_but.setText(_translate("Dialog", "SET RAMP", None))
        self.I_off_but.setText(_translate("Dialog", "OFF", None))
        self.exit_but.setText(_translate("Dialog", "EXIT", None))
        self.meas_but.setText(_translate("Dialog", "MEASURE", None))
        self.ramp_lab.setText(_translate("Dialog", "Ramp Rate [A/sec]:", None))

    def setrunning(self, mainwin):
        self.supply_dis = QtGui.QLabel(mainwin)
        self.supply_dis.setGeometry(QtCore.QRect(30, 30, 310, 80))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Helvetica"))
        font.setPointSize(28)
        font.setBold(True)
        font.setWeight(75)
        self.supply_dis.setFont(font)
        self.supply_dis.setAlignment(QtCore.Qt.AlignCenter)
        self.supply_dis.setObjectName(_fromUtf8("supply_dis"))

    def setbutton(self, mainwin):
        self.I_on_but = QtGui.QPushButton(mainwin)
        self.I_on_but.setGeometry(QtCore.QRect(90, 200, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(17)
        font.setUnderline(True)
        self.I_on_but.setFont(font)
        self.I_on_but.setAutoFillBackground(False)
        self.I_on_but.setObjectName(_fromUtf8("I_on_but"))
        self.I_up_but = QtGui.QPushButton(mainwin)
        self.I_up_but.setGeometry(QtCore.QRect(90, 250, 200, 40))
        self.I_up_but.setFont(font)
        self.I_up_but.setObjectName(_fromUtf8("I_up_but"))
        self.I_off_but = QtGui.QPushButton(mainwin)
        self.I_off_but.setGeometry(QtCore.QRect(90, 300, 200, 40))
        self.I_off_but.setFont(font)
        self.I_off_but.setObjectName(_fromUtf8("I_off_but"))
        self.meas_but = QtGui.QPushButton(mainwin)
        self.meas_but.setGeometry(QtCore.QRect(90, 360, 200, 40))
        self.meas_but.setFont(font)
        self.meas_but.setObjectName(_fromUtf8("I_off_but"))
        self.exit_but = QtGui.QPushButton(mainwin)
        self.exit_but.setGeometry(QtCore.QRect(90, 410, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(True)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        self.exit_but.setFont(font)
        self.exit_but.setToolTip(_fromUtf8(""))
        self.exit_but.setObjectName(_fromUtf8("exit_but"))

    def setramprate(self, win):
        self.ramp_box = QtGui.QDoubleSpinBox(win)
        self.ramp_box.setEnabled(True)
        self.ramp_box.setGeometry(QtCore.QRect(180, 130, 120, 30))
        self.ramp_box.setProperty("value", 0.1)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.ramp_box.setFont(font)
        self.ramp_box.setAlignment(QtCore.Qt.AlignCenter)
        self.ramp_box.setDecimals(2)
        self.ramp_box.setMaximum(40.0)
        self.ramp_box.setObjectName(_fromUtf8("ramp_box"))
        self.ramp_lab = QtGui.QLabel(win)
        self.ramp_lab.setGeometry(QtCore.QRect(30, 130, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.ramp_lab.setFont(font)
        self.ramp_lab.setObjectName(_fromUtf8("ramp_lab"))
예제 #14
0
class GNSSAzEl_window(QtGui.QMainWindow, Ui_GNSSAzElWindow):
    def __init__(self):
        super(GNSSAzEl_window, self).__init__()
        self.setupUi(self)
        self.init_Ui()

    def init_Ui(self):

        self.create_menuActions()
        self.btn_close.clicked.connect(self.close)

        self.dpi = 100
        self.fig = Figure((6.6, 6.6), dpi=self.dpi)
        self.fig.patch.set_facecolor('none')
        self.canvas = FigureCanvas(self.fig)
        # Position as left, top, width, height
        self.canvas.setGeometry(QtCore.QRect(40, 60, 600, 600))
        self.canvas.setParent(self)
        self.drawAzElPlt()

        self.checkBoxGPS.clicked.connect(self.refreshAzElPlt)
        self.checkBoxGLONASS.clicked.connect(self.refreshAzElPlt)
        self.checkBoxGALILEO.clicked.connect(self.refreshAzElPlt)
        self.checkBoxBEIDOU.clicked.connect(self.refreshAzElPlt)

        self.refreshtimer = QtCore.QTimer()
        self.refreshtimer.start(5000)  #ms
        self.refreshtimer.timeout.connect(self.refreshAzElPlt)

        self.btn_close.clicked.connect(self.refreshtimer.stop)

    def drawAzElPlt(self):
        """
	Draws the GNSS Az-El plot.

	"""

        self.grid = rc('grid', color='green', linewidth=0.5, linestyle='-')
        self.grid = rc('xtick', labelsize=15)
        self.grid = rc('ytick', labelsize=10)

        self.ax = self.fig.add_axes([0.1, 0.1, 0.8, 0.8],
                                    projection='polar',
                                    axisbg='#d5de9c')
        self.ax.set_rmax(90)

        self.ax.set_rgrids([10, 20, 30, 40, 50, 60, 70, 80, 90], angle=0)
        self.ax.set_theta_offset(0.5 * math.pi)
        self.ax.set_theta_direction(-1)

        self.ax.set_title(
            "GNSS satellites on the local horizon",
            va='bottom',
        )
        self.ax.set_yticklabels(map(str, range(80, 0, -10)))
        self.ax.set_xticklabels(['N', '', 'E', '', 'S', '', 'W', ''])

        self.ax.set_autoscalex_on(False)
        self.ax.set_autoscaley_on(False)

        if self.checkBoxGPS.isChecked() == True:
            [GPSname, phi_GPS, r_GPS] = satellites.SatCompute(
                'visible', 'GPS')  # fills the list with all GPS satellites
            GPSname = [
                j.split()[-2].replace("(", "") +
                j.split()[-1].replace(")", "") for j in GPSname
            ]  # shortens the displayed satellites' names on the plot
            self.ax.plot(phi_GPS, r_GPS, 'ro', label='GPS')
            for i, txt in enumerate(GPSname):
                self.ax.annotate(txt, (phi_GPS[i], r_GPS[i]))

        if self.checkBoxGLONASS.isChecked() == True:
            [GLONASSname, phi_GLONASS, r_GLONASS] = satellites.SatCompute(
                'visible',
                'COSMOS')  # fills the list with all GLONASS satellites
            GLONASSname = [j[13:16] for j in GLONASSname]
            self.ax.plot(phi_GLONASS, r_GLONASS, 'bo', label='GLONASS')
            for i, txt in enumerate(GLONASSname):
                self.ax.annotate(txt, (phi_GLONASS[i], r_GLONASS[i]))

        if self.checkBoxGALILEO.isChecked() == True:
            [GALILEOname, phi_GALILEO, r_GALILEO] = satellites.SatCompute(
                'visible',
                'GSAT')  # fills the list with all GALILEO satellites
            GALILEOname = [
                j.split()[-2].replace("(", "") +
                j.split()[-1].replace(")", "") for j in GALILEOname
            ]
            self.ax.plot(phi_GALILEO, r_GALILEO, 'go', label='GALILEO')
            for i, txt in enumerate(GALILEOname):
                self.ax.annotate(txt, (phi_GALILEO[i], r_GALILEO[i]))
        if self.checkBoxBEIDOU.isChecked() == True:
            [BEIDOUname, phi_BEIDOU, r_BEIDOU] = satellites.SatCompute(
                'visible',
                'BEIDOU')  # fills the list with all BEIDOU satellites
            BEIDOUname = [j.split()[-1] for j in BEIDOUname]
            self.ax.plot(phi_BEIDOU, r_BEIDOU, 'ko', label='BEIDOU')
            for i, txt in enumerate(BEIDOUname):
                self.ax.annotate(txt, (phi_BEIDOU[i], r_BEIDOU[i]))

        self.canvas.draw()

    def refreshAzElPlt(self):
        """
	    Refreshes the drawn plot
	"""
        self.ax.clear()
        self.drawAzElPlt()

    def create_menuActions(self):
        """
        Creates actions for the menubar of the GNSS Az-El window.
        :return: Nothing
        """
        save_file_action = self.create_action(
            "&Save current view",
            shortcut="Ctrl+S",
            slot=self.save_AzElPlot,
            tip="Saves current Azimuth-Elevation view as an image.")

        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Closes current window")

        about_action = self.create_action(
            "&About",
            shortcut='F1',
            slot=self.on_about,
            tip='Displays additional information.')

        self.add_actions(self.file_menu, (save_file_action, None, quit_action))

        self.add_actions(self.help_menu, (about_action, ))

    def add_actions(self, target, actions):

        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):

        action = QtGui.QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, QtCore.SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action

    def save_AzElPlot(self):
        """
        Saves the current GNSS Az-El plot
        """
        file_choices = "PNG (*.png)|*.png"

        path = unicode(
            QtGui.QFileDialog.getSaveFileName(self, 'Save file', '',
                                              file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    def on_about(self):
        """
        A message of the help option
        """
        msg = """

        This window displays current positions of GNSS satellites on the local horizon. Positions computed using two-line element set (TLE) data.
        """
        QtGui.QMessageBox.about(self, "GNSS Az-El view", msg.strip())
예제 #15
0
파일: main.py 프로젝트: varenius/salsa
class GNSSAzEl_window(QtGui.QMainWindow, Ui_GNSSAzElWindow ):
    def __init__(self):
        super(GNSSAzEl_window, self).__init__()
        self.setupUi(self)
        self.init_Ui()
 
    def init_Ui(self):

        self.create_menuActions()
        self.btn_close.clicked.connect(self.close)

        self.dpi = 100
        self.fig = Figure((6.6, 6.6), dpi=self.dpi)
        self.fig.patch.set_facecolor('none')
        self.canvas = FigureCanvas(self.fig)
        # Position as left, top, width, height
        self.canvas.setGeometry(QtCore.QRect(40,60, 600, 600))  
        self.canvas.setParent(self)
        self.drawAzElPlt()

        self.checkBoxGPS.clicked.connect(self.refreshAzElPlt)
        self.checkBoxGLONASS.clicked.connect(self.refreshAzElPlt)
        self.checkBoxGALILEO.clicked.connect(self.refreshAzElPlt)
        self.checkBoxBEIDOU.clicked.connect(self.refreshAzElPlt)

        self.refreshtimer = QtCore.QTimer()
        self.refreshtimer.start(5000) #ms
        self.refreshtimer.timeout.connect(self.refreshAzElPlt)

        self.btn_close.clicked.connect(self.refreshtimer.stop)
            
    def drawAzElPlt(self):
	"""
	Draws the GNSS Az-El plot.

	"""
 
        self.grid=rc('grid', color='green', linewidth=0.5, linestyle='-')
        self.grid=rc('xtick', labelsize=15)
        self.grid=rc('ytick', labelsize=10)

        self.ax = self.fig.add_axes([0.1, 0.1, 0.8, 0.8], projection='polar', axisbg='#d5de9c')
        self.ax.set_rmax(90)

        self.ax.set_rgrids([10,20,30,40,50,60,70,80,90], angle=0)
        self.ax.set_theta_offset(0.5*math.pi)
        self.ax.set_theta_direction(-1)

        self.ax.set_title("GNSS satellites on the local horizon",va='bottom', )
        self.ax.set_yticklabels(map(str, range(80, 0, -10)))
        self.ax.set_xticklabels(['N', '', 'E', '', 'S', '', 'W', ''])

        self.ax.set_autoscalex_on(False)
        self.ax.set_autoscaley_on(False)

        if self.checkBoxGPS.isChecked() == True :
            [GPSname, phi_GPS, r_GPS] = satellites.SatCompute('visible', 'GPS')  # fills the list with all GPS satellites
            GPSname = [j.split()[-2].replace("(","" ) + j.split()[-1].replace(")" ,"") for j in GPSname] # shortens the displayed satellites' names on the plot
            self.ax.plot(phi_GPS,r_GPS, 'ro',label='GPS')
            for i,txt in enumerate(GPSname):
                self.ax.annotate(txt,(phi_GPS[i],r_GPS[i]))

        if self.checkBoxGLONASS.isChecked() == True:
            [GLONASSname, phi_GLONASS, r_GLONASS] = satellites.SatCompute('visible', 'COSMOS')  # fills the list with all GLONASS satellites
            GLONASSname = [j[13:16] for j in GLONASSname]
            self.ax.plot(phi_GLONASS, r_GLONASS, 'bo', label='GLONASS')
            for i, txt in enumerate(GLONASSname):
                self.ax.annotate(txt, (phi_GLONASS[i], r_GLONASS[i]))

        if self.checkBoxGALILEO.isChecked() == True:
            [GALILEOname, phi_GALILEO, r_GALILEO] = satellites.SatCompute('visible', 'GSAT')  # fills the list with all GALILEO satellites
            GALILEOname = [j.split()[-2].replace("(","" ) + j.split()[-1].replace(")" ,"") for j in GALILEOname]
            self.ax.plot(phi_GALILEO, r_GALILEO, 'go', label='GALILEO')
            for i, txt in enumerate(GALILEOname):
                self.ax.annotate(txt, (phi_GALILEO[i], r_GALILEO[i]))
        if self.checkBoxBEIDOU.isChecked() == True:
            [BEIDOUname, phi_BEIDOU, r_BEIDOU] = satellites.SatCompute('visible','BEIDOU')  # fills the list with all BEIDOU satellites
            BEIDOUname = [ j.split()[-1] for j in BEIDOUname]
            self.ax.plot(phi_BEIDOU, r_BEIDOU, 'ko', label='BEIDOU')
            for i, txt in enumerate(BEIDOUname):
                self.ax.annotate(txt, (phi_BEIDOU[i], r_BEIDOU[i]))

        self.canvas.draw()

    def refreshAzElPlt(self):
        """
	    Refreshes the drawn plot
	"""
        self.ax.clear()
        self.drawAzElPlt()

        
    def create_menuActions(self):
        """
        Creates actions for the menubar of the GNSS Az-El window.
        :return: Nothing
        """
        save_file_action = self.create_action("&Save current view",
            shortcut="Ctrl+S", slot=self.save_AzElPlot, 
            tip="Saves current Azimuth-Elevation view as an image.")

        quit_action = self.create_action("&Quit", slot=self.close, 
            shortcut="Ctrl+Q", tip="Closes current window")

        about_action = self.create_action("&About", 
            shortcut='F1', slot=self.on_about, 
            tip='Displays additional information.')

        self.add_actions(self.file_menu, 
            (save_file_action, None, quit_action))
        
        self.add_actions(self.help_menu, (about_action,))
        
    def add_actions(self, target, actions):

        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(  self, text, slot=None, shortcut=None, 
                        icon=None, tip=None, checkable=False, 
                        signal="triggered()"):

        action = QtGui.QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, QtCore.SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action

    def save_AzElPlot(self):
        """
        Saves the current GNSS Az-El plot
        """
        file_choices = "PNG (*.png)|*.png"

        path = unicode(QtGui.QFileDialog.getSaveFileName(self, 
                        'Save file', '', 
                        file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    def on_about(self):
        """
        A message of the help option
        """
        msg = """

        This window displays current positions of GNSS satellites on the local horizon. Positions computed using two-line element set (TLE) data.
        """
        QtGui.QMessageBox.about(self, "GNSS Az-El view", msg.strip())
class DiagramaDeRafagasyManiobrasDialog(QFrame, layout_DiagramaDeRafagasyManiobras.Ui_Dialog):

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

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

        self.ft2m = 0.3048
        self.lb2kg = 0.453592

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def print_input_variables(self):
        logger.info("CAM = {}".format(self.diagramas.CAM[self.units]))
        logger.info("Sw = {}".format(self.diagramas.sw[self.units]))
        logger.info("MTOW = {}".format(self.diagramas.MTOW[self.units]))
        logger.info("MLW = {}".format(self.diagramas.MLW[self.units]))
        logger.info("MZFW = {}".format(self.diagramas.MZFW[self.units]))
        logger.info("a3D = {}".format(self.diagramas.a3D))
        logger.info("clmax = {}".format(self.diagramas.clmax))
        logger.info("clmax_flap = {}".format(self.diagramas.clmax_flap))
        logger.info("clmin = {}".format(self.diagramas.clmin))
        logger.info("Zmo = {}".format(self.diagramas.Zmo[self.units]))
        logger.info("Vc = {}".format(self.diagramas.Vc[self.units]))
예제 #17
0
class MplGraphWidget(QtGui.QWidget):
    def __init__(self, parent=None, width=3, height=3, dpi=100):

        super(MplGraphWidget, self).__init__(parent)

        self._dataY = np.array([])
        self._dataX = np.array([])

        self._spCols = 1
        self._spRows = 1
        self.all_sp_axes = []
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.all_sp_axes.append(
            self.fig.add_subplot(self._spCols, self._spRows, 1))
        self.fig.set_frameon(False)
        self.fig.set_tight_layout(True)

        self.canvas = Canvas(self.fig)

        self._navBarOn = True
        self.mpl_toolbar = NavigationToolbar(self.canvas, parent)

        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('button_press_event', self.on_button_press)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()

        self.canvas.setParent(parent)
        self.canvas.clearMask()
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                  QtGui.QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        if self._navBarOn:
            vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)

    key_pressed = QtCore.pyqtSignal(object, name='keyPressed')

    def on_key_press(self, event):
        self.key_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    button_pressed = QtCore.pyqtSignal(object, name='buttonPressed')

    def on_button_press(self, event):
        self.button_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    mouse_move = QtCore.pyqtSignal(object, name='mouseMoved')

    def on_mouse_move(self, event):
        self.mouse_move.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    def get_icon(name):
        """Return Matplotlib icon *name*"""
        return QtGui.QIcon(osp.join(rcParams['datapath'], 'images', name))

    def generateNewAxes(self):
        for ax in self.all_sp_axes:
            self.fig.delaxes(ax)
        self.all_sp_axes = []
        numOfAxes = (self._spRows * self._spCols) + 1
        for i in np.arange(1, numOfAxes):
            self.all_sp_axes.append(
                self.fig.add_subplot(self._spRows, self._spCols, i))
        self.canvas.setGeometry(100, 100, 300,
                                300)  #Used to update the new number of axes
        self.canvas.updateGeometry(
        )  #This will bring the size of the canvas back to the original (defined by the vbox)

    spRowsChanged = QtCore.pyqtSignal(int)

    def getspRows(self):
        return self._spRows

    @QtCore.pyqtSlot(int)
    def setspRows(self, spRows):
        self._spRows = spRows
        self.generateNewAxes()
        self.spRowsChanged.emit(spRows)

    def resetspRows(self):
        self.setspRows(1)

    spRows = QtCore.pyqtProperty(int, getspRows, setspRows, resetspRows)

    spColsChanged = QtCore.pyqtSignal(int)

    def getspCols(self):
        return self._spCols

    @QtCore.pyqtSlot(int)
    def setspCols(self, spCols):
        self._spCols = spCols
        self.generateNewAxes()
        self.spRowsChanged.emit(spCols)

    def resetspCols(self):
        self.setspCols(1)

    spCols = QtCore.pyqtProperty(int, getspCols, setspCols, resetspCols)

    dataChanged = QtCore.pyqtSignal(bool)

    def get_Y_data(self):
        return self._dataY

    @QtCore.pyqtSlot(int)
    def set_Y_data(self, y_data):
        self._dataY = y_data
        self.dataChanged.emit(True)

    def plot(self, on_axes=0):
        if np.size(self._dataX) == 0:
            self.all_sp_axes[on_axes].plot(self._dataY)
        else:
            self.all_sp_axes[on_axes].plot(self._dataX, self._dataY)

    def getNavBarOn(self):
        return self._navBarOn

    def setNavBarOn(self, navBarOn):
        self._navBarOn = navBarOn
        if not navBarOn:
            self.mpl_toolbar.hide()
        else:
            self.mpl_toolbar.show()

    def resetNavBarOn(self):
        self._navBarOn = True

    navBarOn = QtCore.pyqtProperty(bool, getNavBarOn, setNavBarOn,
                                   resetNavBarOn)

    # def getautoscale(self):
    #     return self._autoscale
    #
    # def setautoscale(self, autoscale):
    #     self._autoscale = autoscale
    #     for axis in self.all_sp_axes:
    #         axis.set_autoscale(autoscale)
    #
    # def resetautoscale(self):
    #     self._autoscale = False
    #
    # autoscale = QtCore.pyqtProperty(bool, getautoscale, setautoscale, resetautoscale)

    @QtCore.pyqtSlot(bool)
    def set_autoscale(self, autoscale):
        for axis in self.all_sp_axes:
            axis.set_autoscale(autoscale)
예제 #18
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.init_UI()

    def init_UI(self):
        self.save_folder = ""
        self.box = ""
        self.all_data, self.curr_data = self.readfile()
        self.setFixedSize(1200, 950)
        self.dates()
        self.info()
        self.buttons()
        self.sim_list()
        self.curr_list()
        self.add_plot()
        self.log_flag = False
        self.setWindowTitle("SIMULATION TOOL")
        self.error = False
        self.error_box()


#    self.radio_buttons()

    """UI FUNCTIONS"""
    def paintEvent(self, event):
        lines = QtGui.QPainter(self)
        #    pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
        #    lines.setPen(pen)
        lines.begin(self)
        lines.drawRect(20, 20, 230, 110)
        lines.drawRect(250, 20, 340, 110)
        lines.drawRect(620, 20, 560, 110)
        lines.drawRect(10, 10, 1180, 930)
        lines.drawRect(10, 149, 1180, 701)
        lines.end()

    def info(self):  #Create a label where trades stats can be appended
        self.stats_info = QtGui.QLabel(self)
        self.stats_info.setGeometry(20, 860, 300, 80)
        self.stats_info.setText("")

        self.brute_lab = QtGui.QLabel(self)
        self.brute_lab.setGeometry(300, 870, 300, 60)
        self.brute_lab.setText("")

    def error_box(self):
        self.errb = QCheckBox("Error checking", self)
        self.errb.setGeometry(1080, 20, 100, 90)
        self.errb.setChecked(False)
        self.errb.stateChanged.connect(self.error_truth)

    def dates(self):  #Create date input boxes
        self.from_lab = QtGui.QLabel(self)
        self.from_lab.setGeometry(30, 30, 71, 16)
        self.from_lab.setText('Date from')
        self.from_edit = QtGui.QLineEdit(self)
        self.from_edit.setGeometry(30, 50, 61, 20)
        self.from_edit.setPlaceholderText('20170101')
        self.to_lab = QtGui.QLabel(self)
        self.to_lab.setGeometry(120, 30, 71, 16)
        self.to_lab.setText('Date to')
        self.to_edit = QtGui.QLineEdit(self)
        self.to_edit.setGeometry(120, 50, 61, 20)
        self.to_edit.setPlaceholderText('20170630')

    def sim_list(self):  #Create list of indices
        self.cb = QComboBox(self)
        self.cb.addItems(list(self.all_data.columns))
        self.cb.currentIndexChanged.connect(self.plot_chart)
        self.cb.setGeometry(140, 80, 100, 40)

    def curr_list(self):  #Create list of currrncies
        self.cl = QComboBox(self)
        self.cl.addItems(list(self.curr_data.columns))
        self.cl.setGeometry(30, 80, 100, 40)

    def buttons(self):  #Create all buttons and connect to appropiate functions

        #Row 1 starts

        self.a = QtGui.QPushButton('IMPLEMENT STRAT', self)
        self.a.clicked.connect(self.tester)
        self.a.setGeometry(260, 30, 100, 40)

        self.mov = QtGui.QPushButton('Derivative', self)
        self.mov.clicked.connect(self.deriv_strat)
        self.mov.setGeometry(370, 30, 100, 40)

        self.mov = QtGui.QPushButton('Moving Average', self)
        self.mov.clicked.connect(self.moving_average)
        self.mov.setGeometry(480, 30, 100, 40)

        #Row 2 strats

        self.b = QtGui.QPushButton('IMPLEMENT STRAT', self)
        self.b.clicked.connect(self.tester)
        self.b.setGeometry(260, 80, 100, 40)

        self.gc = QtGui.QPushButton('Golden Cross', self)
        self.gc.clicked.connect(self.gd)
        self.gc.setGeometry(370, 80, 100, 40)

        self.mr = QtGui.QPushButton('Mean Reversal', self)
        self.mr.clicked.connect(self.mean_reversion)
        self.mr.setGeometry(480, 80, 100, 40)

        #Row 1 funcs

        self.mavg = QtGui.QPushButton('Moving Average\nIndex', self)
        self.mavg.clicked.connect(self.plot_mov_avg)
        self.mavg.setGeometry(630, 30, 100, 40)

        self.log = QtGui.QPushButton('Scale', self)
        self.log.clicked.connect(self.log_scale)
        self.log.setGeometry(740, 30, 100, 40)

        self.repl = QtGui.QPushButton('Reset', self)
        self.repl.clicked.connect(self.plot_chart)
        self.repl.setGeometry(850, 30, 100, 40)

        self.sf = QtGui.QPushButton('Save Figure', self)
        self.sf.clicked.connect(self.save_fig)
        self.sf.setGeometry(960, 30, 100, 40)

        #Row 2 funcs

        self.opt = QtGui.QPushButton('Optimal\nMoving Average', self)
        self.opt.clicked.connect(self.brutefor)
        self.opt.setGeometry(630, 80, 100, 40)

        self.cur = QtGui.QPushButton('Currency\nPerformance', self)
        self.cur.clicked.connect(self.currperf)
        self.cur.setGeometry(740, 80, 100, 40)

        self.plot = QtGui.QPushButton('Plot', self)
        self.plot.clicked.connect(self.plot_chart_diff_curr)
        self.plot.setGeometry(850, 80, 100, 40)

        self.sf = QtGui.QPushButton('Save Folder', self)
        self.sf.clicked.connect(self.set_save_folder)
        self.sf.setGeometry(960, 80, 100, 40)

    """PLOTTING FUNCTIONS"""

    def plot_stats(self, ml):  #Fetch trade stats and write to UI
        print(ml)
        trades = int(ml[0])
        avg = int(ml[1])
        maxval = int(ml[2])
        minval = int(ml[3])
        med = int(ml[4])
        text = "Amount of trades: %.1f \nAverage amount of days between trades: %.1f \nMedian amount of days between trades: %.1f \nLongest period of days between trades: %.1f \nShortest amount of days between trades: %.1f" % (
            trades, med, avg, maxval, minval)
        print(self.error)
        if self.error:
            errnum = ml[5]
            text2 = "\nAmount of error trades: %d" % errnum
            text = text + text2
            print(text)
        self.stats_info.setText(text)

    def add_plot(self):  #Intialise matplotlib in the UI
        currency = self.cl.currentText()
        index = self.cb.currentText()
        self.figure = Figure()  #Create fig
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.setParent(self)
        self.canvas.setGeometry(11, 150, 1179, 700)
        self.axis = self.figure.add_subplot(111)
        self.axis.set_xlabel("")
        self.axis.legend(loc=2)
        to_plot = self.all_data[
            self.cb.currentText()]  #Plotting data is first item in list

        to_plot = self.reindex(to_plot)  #Plot from 100
        self.first_date = to_plot.index[
            0]  #Set universal variable for currency plotting

        text = index + " " + currency
        self.plotter(to_plot, text)  #Plot

    def plot_strat(self, to_plot,
                   name):  #Plot each individual strategy (E.g movin avg)
        currency = self.cl.currentText()
        to_plot = self.date_cut(to_plot)
        to_plot = self.to_series(to_plot)
        to_plot = self.reindex(to_plot)
        text = name + " " + currency
        self.plotter(to_plot, text)

    def plot_chart(self):  #Plot a new base chart and clear everything
        self.cl.setCurrentIndex(0)
        currency = self.cl.currentText()
        column = self.cb.currentText()
        all_curr_data = self.curr_data[currency]
        to_plot = self.all_data[column]
        to_plot = to_plot.dropna()

        to_plot = self.date_cut(to_plot)
        all_curr_data = self.date_cut(all_curr_data)

        to_plot = self.to_series(to_plot)
        all_curr_data = self.to_series(all_curr_data)
        to_plot = to_plot.div(all_curr_data)

        to_plot = self.reindex(to_plot)
        self.first_date = to_plot.index[0]

        self.axis.clear()
        text = column + " " + currency
        self.plotter(to_plot, text)
        self.stats_info.setText("")

    def plot_chart_diff_curr(self):  #Plot base chart in a different curenncy
        currency = self.cl.currentText()
        column = self.cb.currentText()
        all_curr_data = self.curr_data[currency]
        to_plot = self.all_data[column]
        to_plot = to_plot.dropna()
        to_plot = self.date_cut(to_plot)
        all_curr_data = self.date_cut(all_curr_data)
        to_plot = self.to_series(to_plot)
        all_curr_data = self.to_series(all_curr_data)

        to_plot = to_plot.div(all_curr_data)

        to_plot = self.reindex(to_plot)

        text = column + " " + currency
        self.plotter(to_plot, text)

    def currperf(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        to_plot = curr
        to_plot = self.date_cut(to_plot)
        to_plot = to_plot.truncate(before=self.first_date)
        to_plot = self.reindex(to_plot)
        text = "USD : " + currency
        self.plotter(to_plot, text)

    def plot_mov_avg(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        number = self.getint("Enter moving average")
        text = "%s %s %d Moving Average" % (column, currency, number)
        data = self.all_data[column]
        data = data.div(curr)
        data = data.dropna()
        to_plot = data.rolling(window=number).mean()

        if self.from_edit.text() != '' and self.from_edit.text() != '':
            to_plot = self.date_cut(to_plot)
        else:
            to_plot = to_plot.truncate(before=self.first_date)

        firstval = self.to_series(
            self.date_cut(self.all_data[column].div(curr))).dropna()[0]
        print(firstval)
        to_plot = self.to_series(to_plot)
        to_plot = to_plot / firstval * 100
        self.plotter(to_plot, text)

    def plotter(self, to_plot, text):  #Plots to_plot on plot
        self.axis.plot(to_plot, label=text)
        self.axis.legend(loc=2)
        self.canvas.draw()

    """Strategies"""

    def mean_reversion(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        func = mean_reversal
        nr_stdev = self.getfloat("Number of standard deviations")
        number = self.getint("Enter moving average")
        text = " " + str(nr_stdev) + " Deviation - Mean Reversion"
        data = self.all_data[column]
        signals, diffs = func(data, number, curr, nr_stdev)

        self.simulate(data, number, curr, text, signals, diffs)

    def moving_average(self):
        func = mov_avg
        self.strats(func)

    def gd(self):
        func = golden_cross
        text = ":50 GC"
        self.strats(func, text)

    def deriv_strat(self):
        func = derivative_strat
        text = ":200 Derivative"
        self.strats(func, text)

    def brutefor(self):  #Find the best moving avarge
        lower = self.getint("Enter lower bound")
        upper = self.getint("Enter upper bound")
        self.complaint_box("This might take a while...\n")
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        data = self.all_data[column]
        data = optimizer(column, currency, data, curr, lower, upper)
        print(data)
        self.bruteplot(data)

    def strats(self, func, text="", number=200):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        if number == 200:
            number = self.getint("Enter moving average")
        data = self.all_data[column]
        signals, diffs = func(data, number, curr)
        if self.error:
            self.error_checking(data, number, curr, text, signals, diffs)
        else:
            self.simulate(data, number, curr, text, signals, diffs)

    def simulate(self, data, number, curr, text, signals, diffs):
        if self.from_edit.text() != '' and self.from_edit.text() != '':
            signals = self.date_cut(signals)
        signals = self.to_series(signals)
        to_plot, masterlist = simulator(data, signals, diffs, curr)
        text = str(number) + text
        self.plot_strat(to_plot, text)
        self.plot_stats(masterlist)

    def error_checking(self, data, number, curr, text, signals, diffs):
        print("ERROR CHECK")
        if self.from_edit.text() != '' and self.from_edit.text() != '':
            signals = self.date_cut(signals)
        signals = self.to_series(signals)
        errnum = self.getint("Enter days for error check")
        to_plot, masterlist, days_between_trades = simulator_error_check(
            data, signals, diffs, curr, errnum)
        text = str(number) + text
        self.plot_strat(to_plot, text)
        self.plot_stats(masterlist)
        self.histogram(days_between_trades)

    """Underlying UI"""

    def histogram(self, data):
        print('test')
        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        window.setWindowTitle(self.tr('Histogram'))
        window.setFixedSize(600, 600)
        figure = Figure()  #Create fig
        canvas = FigureCanvasQTAgg(figure)
        canvas.setParent(window)
        canvas.setGeometry(10, 10, 580, 580)
        ax = figure.add_subplot(111)
        ax.hist(data, 100)
        canvas.draw()
        window.show()

    def bruteplot(self, data):

        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        window.setWindowTitle(self.tr('Best Moving Average'))
        window.setFixedSize(1000, 600)
        figure = Figure()  #Create fig
        canvas = FigureCanvasQTAgg(figure)
        canvas.setParent(window)
        canvas.setGeometry(10, 10, 980, 580)
        ax = figure.add_subplot(111)
        ax.plot(data)
        canvas.draw()
        window.show()

    def set_save_folder(self):
        self.save_folder = str(
            QtGui.QFileDialog.getExistingDirectory(self, "Select Directory"))
        return None

    def complaint_box(self, text):  #Create an angry box when users f**** up
        error_dialog = QtGui.QErrorMessage(self)
        error_dialog.setWindowModality(QtCore.Qt.WindowModal)
        error_dialog.showMessage(text)

    def getint(self, text):
        print(text)
        num, ok = QtGui.QInputDialog.getInt(self, "Integer Input", text)
        if ok:
            print(num)
            return num

    def getfloat(self, text):
        print(text)
        num, ok = QtGui.QInputDialog.getDouble(self, "Float Input", text)
        if ok:
            print(num)
            return num

    def save_fig(self):  #Save figure
        if self.save_folder != "":
            self.figure.savefig(self.save_folder + '/test.png')
            self.complaint_box('Figure saved in ' + self.save_folder)
        else:
            self.complaint_box('Choose a folder to save in')

    def log_scale(self):
        if self.log_flag:  #Change y-scale to linear
            self.axis.set_yscale('linear')
            self.log_flag = False
            self.canvas.draw()
        else:  #Change y-scale to log
            self.axis.set_yscale('log')

            self.log_flag = True
            self.canvas.draw()

    def error_truth(self):  #Inlcude error stats or not
        self.error = not self.error

    """Short data funtions"""

    def reindex(self, data):
        data = self.to_series(data)
        data = data.dropna()
        data = data / data[0] * 100
        return data

    def to_series(
            self, data
    ):  #If input is pandas DF, return series based on first columns.
        if isinstance(data, pd.DataFrame):
            data = data[data.columns[0]]
        return data

    def date_cut(self, data):  #Cut datframe to specified dates
        if self.from_edit.text() != '' and self.from_edit.text(
        ) != '':  #Check input boxes
            if not isinstance(
                    data,
                    pd.DataFrame):  #Make sire input actually is a dataframe
                data = data.to_frame()
            try:
                data.index = data.index.to_datetime()
                from_date = pd.to_datetime(str(self.from_edit.text()),
                                           format='%Y%m%d')
                to_date = pd.to_datetime(str(self.to_edit.text()),
                                         format='%Y%m%d')
                data = data.truncate(before=from_date, after=to_date)  #Cut
            except:
                err = sys.exc_info()[0]
                err2 = sys.exc_info()[1]
                print(err, err2)
                self.complaint_box(
                    "Invalid date, plotting all \n The index starts " +
                    data.index[0] + " and ends " + data.index[-1] + ".")
        return data

    def readfile(self):  #Read input data
        data = pd.read_excel("file path to index data")
        #    data.index = data.index.to_datetime()
        curr_data = pd.read_excel("file path to currency data")
        #    curr_data.index = data.index.to_datetime()
        return data, curr_data

    def tester(self):  #Test function for UI elemtents
        print("Something happens")
예제 #19
0
class Ui_Monitor(object):
    def setupUi(self, Monitor):
        Monitor.setObjectName(_fromUtf8("Monitor"))
        Monitor.resize(649, 388)
        self._plabel = []
        self._port = []
        self._display = []
        ## port
        self.SetPort(Monitor)
        # port label
        self.SetLabel(Monitor)
        # lcd number
        self.SetLcdDisplay(Monitor)

        font = QtGui.QFont()
        font.setPointSize(11)

        self._start = QtGui.QPushButton(Monitor)
        self._start.setGeometry(QtCore.QRect(10, 240, 91, 21))
        self._start.setFont(font)
        self._start.setObjectName(_fromUtf8("_start"))
        self._stop = QtGui.QPushButton(Monitor)
        self._stop.setGeometry(QtCore.QRect(10, 270, 91, 21))
        self._stop.setFont(font)
        self._stop.setObjectName(_fromUtf8("_stop"))
        self._quit = QtGui.QPushButton(Monitor)
        self._quit.setGeometry(QtCore.QRect(10, 300, 91, 21))
        self._quit.setFont(font)
        self._quit.setObjectName(_fromUtf8("_quit"))

        # matplotlib canvas
        self._fig = Figure(facecolor="whitesmoke")
        self.plot = FigureCanvas(self._fig)
        self.plot.setGeometry(QtCore.QRect(120, 10, 521, 371))
        self.plot.setObjectName(_fromUtf8("monitor"))
        self.plot.setParent(Monitor)

        self.retranslateUi(Monitor)
        QtCore.QObject.connect(self._quit, QtCore.SIGNAL(_fromUtf8("clicked()")), Monitor.close)
        QtCore.QMetaObject.connectSlotsByName(Monitor)

    def retranslateUi(self, Monitor):
        Monitor.setWindowTitle(_translate("Monitor", "Form", None))
        self._start.setText(_translate("Monitor", "Start", None))
        self._stop.setText(_translate("Monitor", "Stop", None))
        self._quit.setText(_translate("Monitor", "Quit", None))

    ## set port label
    def SetLabel(self, mainwin):
        numoflabel = 3
        font = QtGui.QFont()
        font.setPointSize(11)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)

        for i in range(numoflabel):
            self._plabel.append( QtGui.QLabel(mainwin) )
        self._plabel[0].setGeometry(QtCore.QRect(10, 30, 101, 21))
        self._plabel[1].setGeometry(QtCore.QRect(10, 70, 101, 21))
        self._plabel[2].setGeometry(QtCore.QRect(10, 110, 101, 21))

        for i in range(len(self._plabel)):
            self._plabel[i].setFont(font)
            self._plabel[i].setText(_fromUtf8( "Port %i" %(i+1) ))
            self._plabel[i].setTextFormat(QtCore.Qt.AutoText)
            self._plabel[i].setScaledContents(False)
            self._plabel[i].setAlignment(QtCore.Qt.AlignCenter)
            self._plabel[i].setWordWrap(False)
            self._plabel[i].setObjectName(_fromUtf8( "_pLabel%i" %(i+1) ))

    ## set port address
    def SetPort(self, mainwin):
        numofport = 3
        for i in range(numofport):
            self._port.append( QtGui.QSpinBox(mainwin) )

        self._port[0].setGeometry(QtCore.QRect(10, 10, 101, 21))
        self._port[0].setProperty("value", 20)
        self._port[1].setGeometry(QtCore.QRect(10, 50, 101, 21))
        self._port[1].setProperty("value", 6)
        self._port[2].setGeometry(QtCore.QRect(10, 90, 101, 21))
        self._port[2].setProperty("value", 12)
        for i in range(len(self._port)):
            self._port[i].setObjectName(_fromUtf8("_port%i" %(i+1)))


    ## set lcd display
    def SetLcdDisplay(self, mainwin):
        numoflcd = 3
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Symbol"))
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)

        for i in range(numoflcd):
            self._display.append( QtGui.QLCDNumber(mainwin) )

        self._display[0].setGeometry(QtCore.QRect(10, 140, 91, 16))
        self._display[1].setGeometry(QtCore.QRect(10, 160, 91, 16))
        self._display[2].setGeometry(QtCore.QRect(10, 180, 91, 16))

        for i in range(numoflcd):
            self._display[i].setFont(font)
            self._display[i].setSmallDecimalPoint(False)
            self._display[i].setNumDigits(14)
            self._display[i].setSegmentStyle(QtGui.QLCDNumber.Flat)
            self._display[i].setObjectName(_fromUtf8( "_num%i" %(i+1) ))
class MplGraphWidget(QtGui.QWidget):

    def __init__(self, parent=None, width=3, height=3, dpi=100):

        super(MplGraphWidget, self).__init__(parent)

        self._dataY = np.array([])
        self._dataX = np.array([])

        self._spCols = 1
        self._spRows = 1
        self.all_sp_axes = []
        self.fig = Figure(figsize=(width,height), dpi=dpi)
        self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
        self.fig.set_frameon(False)
        self.fig.set_tight_layout(True)

        self.canvas = Canvas(self.fig)

        self._navBarOn = True
        self.mpl_toolbar = NavigationToolbar(self.canvas, parent)

        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('button_press_event', self.on_button_press)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()

        self.canvas.setParent(parent)
        self.canvas.clearMask()
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        if self._navBarOn:
            vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)

    key_pressed = QtCore.pyqtSignal(object, name='keyPressed')

    def on_key_press(self, event):
        self.key_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    button_pressed = QtCore.pyqtSignal(object, name='buttonPressed')

    def on_button_press(self, event):
        self.button_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    mouse_move = QtCore.pyqtSignal(object, name='mouseMoved')

    def on_mouse_move(self, event):
        self.mouse_move.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    def get_icon(name):
        """Return Matplotlib icon *name*"""
        return QtGui.QIcon(osp.join(rcParams['datapath'], 'images', name))

    def generateNewAxes(self):
        for ax in self.all_sp_axes:
            self.fig.delaxes(ax)
        self.all_sp_axes = []
        numOfAxes = (self._spRows*self._spCols)+1
        for i in np.arange(1,numOfAxes):
            self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
        self.canvas.setGeometry(100, 100, 300, 300)  #Used to update the new number of axes
        self.canvas.updateGeometry()  #This will bring the size of the canvas back to the original (defined by the vbox)

    spRowsChanged = QtCore.pyqtSignal(int)

    def getspRows(self):
        return self._spRows

    @QtCore.pyqtSlot(int)
    def setspRows(self, spRows):
        self._spRows = spRows
        self.generateNewAxes()
        self.spRowsChanged.emit(spRows)

    def resetspRows(self):
        self.setspRows(1)

    spRows = QtCore.pyqtProperty(int, getspRows, setspRows, resetspRows)

    spColsChanged = QtCore.pyqtSignal(int)

    def getspCols(self):
        return self._spCols

    @QtCore.pyqtSlot(int)
    def setspCols(self, spCols):
        self._spCols = spCols
        self.generateNewAxes()
        self.spRowsChanged.emit(spCols)

    def resetspCols(self):
        self.setspCols(1)

    spCols = QtCore.pyqtProperty(int, getspCols, setspCols, resetspCols)

    dataChanged = QtCore.pyqtSignal(bool)

    def get_Y_data(self):
        return self._dataY

    @QtCore.pyqtSlot(int)
    def set_Y_data(self, y_data):
        self._dataY = y_data
        self.dataChanged.emit(True)


    def plot(self, on_axes=0):
        if np.size(self._dataX) == 0:
            self.all_sp_axes[on_axes].plot(self._dataY)
        else:
            self.all_sp_axes[on_axes].plot(self._dataX, self._dataY)

    def getNavBarOn(self):
        return self._navBarOn

    def setNavBarOn(self, navBarOn):
        self._navBarOn = navBarOn
        if not navBarOn:
            self.mpl_toolbar.hide()
        else:
            self.mpl_toolbar.show()

    def resetNavBarOn(self):
        self._navBarOn = True

    navBarOn = QtCore.pyqtProperty(bool, getNavBarOn, setNavBarOn, resetNavBarOn)


    # def getautoscale(self):
    #     return self._autoscale
    #
    # def setautoscale(self, autoscale):
    #     self._autoscale = autoscale
    #     for axis in self.all_sp_axes:
    #         axis.set_autoscale(autoscale)
    #
    # def resetautoscale(self):
    #     self._autoscale = False
    #
    # autoscale = QtCore.pyqtProperty(bool, getautoscale, setautoscale, resetautoscale)

    @QtCore.pyqtSlot(bool)
    def set_autoscale(self, autoscale):
        for axis in self.all_sp_axes:
            axis.set_autoscale(autoscale)
예제 #21
0
class MainWindow():
    def __init__(self):
        self.main_window = gui.QMainWindow()
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.init_gui()

    def init_gui(self):
        self.init_canvas()
        self.init_execution_parameters_frame()

        eval_type_frame = gui.QFrame(self.main_window)
        eval_type_frame.setFrameStyle(gui.QFrame.Box)
        eval_type_frame.setGeometry(800, 530, 200, 70)

        self.eval_type_group = gui.QButtonGroup(eval_type_frame)

        self.eval_type_sample = gui.QRadioButton('Sample', eval_type_frame)
        self.eval_type_sample.setGeometry(5, 5, 150, 30)
        self.eval_type_group.addButton(self.eval_type_sample)

        self.eval_type_direct = gui.QRadioButton('Direct', eval_type_frame)
        self.eval_type_direct.setGeometry(5, 35, 150, 30)
        self.eval_type_group.addButton(self.eval_type_direct)

        self.number_of_samples = NamedTextArea(self.main_window)
        self.number_of_samples.init_gui('No. of Samples', 800, 600, 110, 50)

        button = gui.QPushButton('Execute', self.main_window)
        button.clicked.connect(self.execute)
        button.setGeometry(800, 670, 100, 30)

        self.main_window.setGeometry(100, 100, 1024, 700)
        self.main_window.setFixedSize(1024, 768)
        self.main_window.setWindowTitle('Probabilistic Robotics')

        self.reset_canvas()

    def init_canvas(self):
        self.canvas.setParent(self.main_window)
        self.canvas.setGeometry(10, 10, 1000, 475)
        self.canvas.mpl_connect('button_press_event', self)

    def init_execution_parameters_frame(self):
        execution_parameters_frame = gui.QFrame(self.main_window)
        execution_parameters_frame.setGeometry(10, 500, 750, 200)

        self.tab_widget = gui.QTabWidget(execution_parameters_frame)
        self.tab_widget.setGeometry(0, 0, 750, 200)

        self.tab_widget.addTab(self.get_motion_model_tab(), 'Motion Model')
        self.tab_widget.addTab(self.get_sensor_model_tab(), 'Sensor Model')
        self.tab_widget.addTab(self.get_landmark_tab(), 'Landmarks')
        self.tab_widget.addTab(self.get_multirobot_tab(), 'Robots')

    def get_motion_model_tab(self):
        motion_model_parameters_frame = gui.QFrame()

        self.odometry_errors = [None] * 4
        for i in xrange(len(self.odometry_errors)):
            self.odometry_errors[i] = NamedSlider(
                motion_model_parameters_frame, 100)
            self.odometry_errors[i].init_gui('a' + str(i + 1), 10, i * 30, 30,
                                             150, 40)

        return motion_model_parameters_frame

    def get_sensor_model_tab(self):
        sensor_model_parameters_frame = gui.QFrame()

        self.sensing_distance = NamedTextArea(sensor_model_parameters_frame)
        self.sensing_distance.init_gui('Distance', 10, 10, 110, 40)

        self.laser_angle = NamedTextArea(sensor_model_parameters_frame)
        self.laser_angle.init_gui('Angle', 10, 40, 110, 40)

        self.sensing_distance_error = NamedSlider(
            sensor_model_parameters_frame, 100)
        self.sensing_distance_error.init_gui('Dist. error', 200, 10, 80, 150,
                                             40)

        self.sensing_theta_error = NamedSlider(sensor_model_parameters_frame,
                                               100)
        self.sensing_theta_error.init_gui('Theta error', 200, 40, 80, 150, 40)

        self.sensing_signature_error = NamedSlider(
            sensor_model_parameters_frame, 100)
        self.sensing_signature_error.init_gui('Sign. error', 200, 70, 80, 150,
                                              40)

        self.enable_sensors = gui.QCheckBox('Enable sensors',
                                            sensor_model_parameters_frame)
        self.enable_sensors.setGeometry(500, 10, 150, 20)

        return sensor_model_parameters_frame

    def get_landmark_tab(self):
        self.landmarks = list()

        landmark_frame = gui.QFrame()

        self.landmark_list = gui.QListWidget(landmark_frame)
        self.landmark_list.setGeometry(10, 10, 150, 145)

        remove_landmark_button = gui.QPushButton('-', landmark_frame)
        remove_landmark_button.setGeometry(170, 50, 30, 30)
        remove_landmark_button.clicked.connect(self.remove_selected_landmark)

        clear_landmarks_button = gui.QPushButton('Clear All', landmark_frame)
        clear_landmarks_button.setGeometry(300, 10, 150, 30)
        clear_landmarks_button.clicked.connect(self.remove_all_landmarks)

        return landmark_frame

    def get_multirobot_tab(self):
        multirobot_frame = gui.QFrame()

        robot_frame = gui.QFrame(multirobot_frame)
        robot_frame.setFrameStyle(gui.QFrame.Box)
        robot_frame.setGeometry(10, 10, 110, 150)

        self.robot_group = gui.QButtonGroup(multirobot_frame)

        self.robots = list()
        self.robot_points = list()

        for i in xrange(3):

            def make_lambda(index):
                return lambda: self.update_robot_list(index)

            robot = gui.QRadioButton('Robot - ' + str(i + 1), robot_frame)
            robot.setGeometry(5, 5 + i * 30, 100, 30)
            robot.clicked.connect(make_lambda(i))

            self.robots.append(robot)
            self.robot_group.addButton(robot)
            self.robot_points.append(list())

        self.robot_list = gui.QListWidget(multirobot_frame)
        self.robot_list.setGeometry(150, 10, 150, 145)

        remove_robot_point = gui.QPushButton('-', multirobot_frame)
        remove_robot_point.setGeometry(310, 50, 30, 30)
        remove_robot_point.clicked.connect(self.remove_selected_robot_point)

        clear_landmarks_button = gui.QPushButton('Clear All', multirobot_frame)
        clear_landmarks_button.setGeometry(350, 10, 150, 30)
        clear_landmarks_button.clicked.connect(self.remove_all_robot_points)

        self.enable_communication = gui.QCheckBox('Enable communication',
                                                  multirobot_frame)
        self.enable_communication.setGeometry(520, 10, 200, 20)

        self.enable_one_way_update = gui.QCheckBox('One way update',
                                                   multirobot_frame)
        self.enable_one_way_update.setGeometry(520, 40, 200, 20)

        self.communication_distance = NamedTextArea(multirobot_frame)
        self.communication_distance.init_gui('Comm. Distance', 520, 120, 150,
                                             40)

        return multirobot_frame

    def reset_canvas(self):
        ax = self.figure.gca()
        ax.cla()
        ax.set_ylim([0, 5])
        ax.set_xlim([0, 9])

        self.plot_landmarks()
        self.plot_robot_points()
        self.canvas.draw()

    def execute(self):
        a_values = list()
        for odometry_error in self.odometry_errors:
            a_values.append(odometry_error.get_value())

        ax = self.figure.gca()
        ax.cla()

        execution_parameters = dict()

        execution_parameters['points'] = self.get_robot_points()

        if len(execution_parameters['points']) == 0:
            show_error_box(self.main_window,
                           'En az 1 robot icin yol bilgisi girilmelidir')
            return

        execution_parameters[
            'use_communication'] = self.enable_communication.isChecked()
        execution_parameters[
            'one_way_update'] = self.enable_one_way_update.isChecked()
        execution_parameters['use_sensors'] = self.enable_sensors.isChecked()
        if execution_parameters['use_communication']:
            try:
                execution_parameters['comm_distance'] = float(
                    self.communication_distance.get_text())
            except Exception:
                show_error_box(self.main_window, 'Hatali iletisim uzakligi')
                return

        if self.enable_sensors.isChecked():
            try:
                execution_parameters['sensor_r'] = float(
                    self.sensing_distance.get_text())
            except Exception:
                show_error_box(self.main_window, 'Hatali sensor uzakligi')
                return

            try:
                execution_parameters['sensor_theta'] = float(
                    self.laser_angle.get_text())
            except Exception:
                show_error_box(self.main_window, 'Hatali sensor acisi')
                return

            execution_parameters['sensor_d_error'] = float(
                self.sensing_distance_error.get_value())
            execution_parameters['sensor_theta_error'] = float(
                self.sensing_theta_error.get_value())
            execution_parameters['sensor_s_error'] = float(
                self.sensing_signature_error.get_value())

        execution_parameters['landmarks'] = self.landmarks
        try:
            execution_parameters['no_of_samples'] = int(
                self.number_of_samples.get_text())
        except Exception:
            show_error_box(self.main_window, 'Hatali ornek sayisi')
            return

        execution_parameters['a'] = a_values
        execution_parameters['sample'] = (
            self.eval_type_group.checkedButton() == self.eval_type_sample)

        execute_simulation(ax, execution_parameters)

        self.canvas.draw()

    def get_robot_points(self):
        return [(i, robot_list)
                for i, robot_list in enumerate(self.robot_points)
                if len(robot_list) > 0]

    def show(self):
        self.main_window.show()

    def __call__(self, event):
        current_tab = self.tab_widget.currentIndex()
        if current_tab == 2:  #add landmarks
            self.add_landmark(event.xdata, event.ydata)
        elif current_tab == 3:  #add robot point
            self.add_robot_point(event.xdata, event.ydata)

    def update_robot_list(self, index):
        num_of_points = len(self.robot_points[index])
        self.refresh_robot_list(num_of_points)

    def remove_selected_landmark(self):
        selected_items = list(self.landmark_list.selectedItems())
        for selected_item in selected_items:
            self.landmark_list.takeItem(self.landmark_list.row(selected_item))
            current_item_id = int(str(selected_item.text()))
            self.landmarks = [
                landmark for landmark in self.landmarks
                if landmark[2] != current_item_id
            ]
        self.reset_canvas()

    def get_selected_robot_index(self):
        if self.robot_group.checkedButton() is None:
            return -1

        return [
            i for i in xrange(len(self.robot_points))
            if self.robots[i] == self.robot_group.checkedButton()
        ][0]

    def remove_selected_robot_point(self):
        current_robot_index = self.get_selected_robot_index()
        if current_robot_index == -1:
            return

        selected_items = [
            str(selected_item.text())
            for selected_item in self.robot_list.selectedItems()
        ]
        new_point_list = list()

        for i in xrange(len(self.robot_points[current_robot_index])):
            if str(i + 1) not in selected_items:
                new_point_list.append(
                    self.robot_points[current_robot_index][i])

        self.robot_points[current_robot_index] = new_point_list
        self.refresh_robot_list(len(new_point_list))
        self.reset_canvas()

    def remove_all_landmarks(self):
        self.landmark_list.clear()
        self.landmarks = list()
        self.reset_canvas()

    def remove_all_robot_points(self):
        self.robot_list.clear()
        self.robot_points = list()
        for robot_points in xrange(3):
            self.robot_points.append(list())
        self.reset_canvas()

    def add_landmark(self, x, y):
        landmark_id = 0 if len(self.landmarks) == 0 else max(
            [landmark[2] for landmark in self.landmarks]) + 1
        self.landmarks.append((x, y, landmark_id))
        self.landmark_list.addItem(str(landmark_id))
        self.reset_canvas()

    def add_robot_point(self, x, y):
        current_robot_index = self.get_selected_robot_index()
        if current_robot_index == -1:
            return

        self.robot_points[current_robot_index].append((x, y))
        self.refresh_robot_list(len(self.robot_points[current_robot_index]))
        self.reset_canvas()

    def refresh_robot_list(self, num_of_points):
        self.robot_list.clear()
        for i in xrange(1, num_of_points + 1):
            self.robot_list.addItem(str(i))

    def plot_landmarks(self):
        ax = self.figure.gca()
        for landmark in self.landmarks:
            ax.plot([landmark[0]], [landmark[1]], 'go')
            ax.annotate(str(landmark[2]),
                        xy=(landmark[0], landmark[1]),
                        textcoords='offset points')
        self.canvas.draw()

    def plot_robot_points(self):
        ax = self.figure.gca()
        for i in xrange(len(self.robots)):
            ax.plot([p[0] for p in self.robot_points[i]],
                    [p[1] for p in self.robot_points[i]],
                    robot_colors[i] + 's')
            ax.plot([p[0] for p in self.robot_points[i]],
                    [p[1] for p in self.robot_points[i]], robot_colors[i])