예제 #1
0
 def __init__(self, *args):
     QwtPlot.__init__(self, *args)
     self.setTitle('Cartesian Coordinate System Demo')
     # create a plot with a white canvas
     self.setCanvasBackground(Qt.white)
     # set plot layout
     self.plotLayout().setCanvasMargin(0)
     self.plotLayout().setAlignCanvasToScales(True)
     # attach a grid
     grid = QwtPlotGrid()
     grid.attach(self)
     grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
     # attach a x-axis
     xaxis = CartesianAxis(QwtPlot.xBottom, QwtPlot.yLeft)
     xaxis.attach(self)
     self.enableAxis(QwtPlot.xBottom, False)
     # attach a y-axis
     yaxis = CartesianAxis(QwtPlot.yLeft, QwtPlot.xBottom)
     yaxis.attach(self)
     self.enableAxis(QwtPlot.yLeft, False)
     # calculate 3 NumPy arrays
     x = np.arange(-2*np.pi, 2*np.pi, 0.01)
     y = np.pi*np.sin(x)
     z = 4*np.pi*np.cos(x)*np.cos(x)*np.sin(x)
     # attach a curve
     curve = QwtPlotCurve('y = pi*sin(x)')
     curve.attach(self)
     curve.setPen(QPen(Qt.green, 2))
     curve.setData(x, y)
     # attach another curve
     curve = QwtPlotCurve('y = 4*pi*sin(x)*cos(x)**2')
     curve.attach(self)
     curve.setPen(QPen(Qt.black, 2))
     curve.setData(x, z)
     self.replot()
예제 #2
0
    def __init__(self, *args):
        QFrame.__init__(self, *args)

        self.xMap = QwtScaleMap()
        self.xMap.setScaleInterval(-0.5, 10.5)
        self.yMap = QwtScaleMap()
        self.yMap.setScaleInterval(-1.1, 1.1)

        # frame style
        self.setFrameStyle(QFrame.Box | QFrame.Raised)
        self.setLineWidth(2)
        self.setMidLineWidth(3)

        # calculate values
        self.x = np.arange(0, 10.0, 10.0/27)
        self.y = np.sin(self.x)*np.cos(2*self.x)

        # make curves with different styles
        self.curves = []
        self.titles = []

        # curve 2
        self.titles.append('Style: Lines, Symbol: None')
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkBlue))
        curve.setStyle(QwtPlotCurve.Lines)
        self.curves.append(curve)

        # attach data, using Numeric
        for curve in self.curves:
            curve.setData(self.x, self.y)
예제 #3
0
    def __init__(self, *args):
        QFrame.__init__(self, *args)

        self.xMap = QwtScaleMap()
        self.xMap.setScaleInterval(-0.5, 10.5)
        self.yMap = QwtScaleMap()
        self.yMap.setScaleInterval(-1.1, 1.1)

        # frame style
        self.setFrameStyle(QFrame.Box | QFrame.Raised)
        self.setLineWidth(2)
        self.setMidLineWidth(3)

        # calculate values
        self.x = np.arange(0, 10.0, 10.0 / 27)
        self.y = np.sin(self.x) * np.cos(2 * self.x)

        # make curves with different styles
        self.curves = []
        self.titles = []
        # curve 1
        self.titles.append("Style: Sticks, Symbol: Ellipse")
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.red))
        curve.setStyle(QwtPlotCurve.Sticks)
        curve.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.yellow), QPen(Qt.blue),
                      QSize(5, 5)))
        self.curves.append(curve)
        # curve 2
        self.titles.append("Style: Lines, Symbol: None")
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkBlue))
        curve.setStyle(QwtPlotCurve.Lines)
        self.curves.append(curve)
        # curve 3
        self.titles.append("Style: Lines, Symbol: None, Antialiased")
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkBlue))
        curve.setStyle(QwtPlotCurve.Lines)
        curve.setRenderHint(QwtPlotItem.RenderAntialiased)
        self.curves.append(curve)
        # curve 4
        self.titles.append("Style: Steps, Symbol: None")
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkCyan))
        curve.setStyle(QwtPlotCurve.Steps)
        self.curves.append(curve)
        # curve 5
        self.titles.append("Style: NoCurve, Symbol: XCross")
        curve = QwtPlotCurve()
        curve.setStyle(QwtPlotCurve.NoCurve)
        curve.setSymbol(
            QwtSymbol(QwtSymbol.XCross, QBrush(), QPen(Qt.darkMagenta),
                      QSize(5, 5)))
        self.curves.append(curve)

        # attach data, using Numeric
        for curve in self.curves:
            curve.setData(self.x, self.y)
예제 #4
0
class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

        self.current_y = 0

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_plot)
        self.timer.setInterval(1000 / FREQ)
        self.timer.start()

    def initUI(self):

        self.setGeometry(300, 300, 1000, 1000)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QtGui.QIcon('web.png'))
        self.plot = QwtPlot("Test", self)
        self.plot.resize(900, 900)
        self.curve = QwtPlotCurve("Curve 1")
        self.curve.attach(self.plot)
        self.show()

    def update_plot(self):
        self.curve.setData(x, ys[self.current_y])
        self.current_y = (self.current_y + 1) % YS
예제 #5
0
 def __init__(self, *args):
     QwtPlot.__init__(self, *args)
     self.setTitle("Cartesian Coordinate System Demo")
     # create a plot with a white canvas
     self.setCanvasBackground(Qt.white)
     # set plot layout
     self.plotLayout().setCanvasMargin(0)
     self.plotLayout().setAlignCanvasToScales(True)
     # attach a grid
     grid = QwtPlotGrid()
     grid.attach(self)
     grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
     # attach a x-axis
     xaxis = CartesianAxis(QwtPlot.xBottom, QwtPlot.yLeft)
     xaxis.attach(self)
     self.enableAxis(QwtPlot.xBottom, False)
     # attach a y-axis
     yaxis = CartesianAxis(QwtPlot.yLeft, QwtPlot.xBottom)
     yaxis.attach(self)
     self.enableAxis(QwtPlot.yLeft, False)
     # calculate 3 NumPy arrays
     x = np.arange(-2 * np.pi, 2 * np.pi, 0.01)
     y = np.pi * np.sin(x)
     z = 4 * np.pi * np.cos(x) * np.cos(x) * np.sin(x)
     # attach a curve
     curve = QwtPlotCurve("y = pi*sin(x)")
     curve.attach(self)
     curve.setPen(QPen(Qt.green, 2))
     curve.setData(x, y)
     # attach another curve
     curve = QwtPlotCurve("y = 4*pi*sin(x)*cos(x)**2")
     curve.attach(self)
     curve.setPen(QPen(Qt.black, 2))
     curve.setData(x, z)
     self.replot()
예제 #6
0
class MyWindow(QtGui.QMainWindow):
    """
    This class implements a derivative of
    PyQt4.QtGui.QMainWindow, a complete application
    window, which can feature menus, submenus,
    status bar, etc. In this example, it uses
    few of those features.
    """

    def __init__(self, parent=None):
        """
        Constructor: creates an instance of MyWindow
        """
        #########################################
        # Necessary actions, which must be done #
        # for any project                       #
        #########################################
        # first, calling the ancestor's creator
        QtGui.QMainWindow.__init__(self, parent)
        # get the User Interface from the module UI_p1
        self.ui=Ui_MainWindow()
        # initialize the user interface
        self.ui.setupUi(self)
        #########################################
        # Custom actions, which can be written  #
        # in other ways for other projects.     #
        #########################################
        # aliases for some parts of the user interface
        self.plotWidget    = self.ui.qwtPlot
        self.measureButton = self.ui.measureButton
        self.closeButton   = self.ui.closeButton
        # connect methods to buttons' click signals
        self.measureButton.clicked.connect(self.measure)
        self.closeButton.clicked.connect(self.close)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.plotWidget)
        return

    def measure(self):
        """
        This is a custom method to connect to the
        button for measurements.
        There is no need for another custom method,
        since the method "close" is already inherited
        from the ancestor class.
        """
        # create data for a curve with some fixed
        # and some random features
        import random
        x=np.arange(0,8,1e-2)      # abscissa: [0, 0.01, 0.02, ... 7.99]
        r=random.random()
        y=np.sin(x)+r*np.sin(3*x)  # calculated ordinate
        # feed new data into the curve
        self.curve.setData(x,y,len(x))
        # change the title of the plot on the fly
        self.plotWidget.setTitle("sin(x) + {} sin(3x)".format(r))
        # display the result
        self.plotWidget.replot()
        return
예제 #7
0
class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()        
        self.initUI()


        self.current_y = 0

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_plot)
        self.timer.setInterval(1000/FREQ)
        self.timer.start()
        
        
    def initUI(self):
        
        self.setGeometry(300, 300, 1000, 1000)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QtGui.QIcon('web.png'))
        self.plot = QwtPlot("Test", self)
        self.plot.resize(900, 900)
        self.curve = QwtPlotCurve("Curve 1")
        self.curve.attach(self.plot)
        self.show()

    def update_plot(self):
        self.curve.setData(x, ys[self.current_y])
        self.current_y = (self.current_y + 1) % YS
예제 #8
0
    def pbServerClicked(self):
        if self.ServerActive == 0:
            self.N = self.sbNsig.value()
            self.Hist = int(self.edHist.text().__str__())
            self.pbStartServer.setText('Stop Server')
            self.ServerActive = 1

            self.plot = dataPlot(self.N)
            self.plot.resize(800, 500)
            self.plot.show()

            self.timebase = []
            self.x = []
            self.c = []
            for n in range(0, self.N):
                self.x.append([])
                cv = QwtPlotCurve()
                pen = QPen(QColor(self.colors[n % 8]))
                pen.setWidth(WIDTH)
                cv.setPen(pen)
                cv.setData([], [])
                self.c.append(cv)
                self.c[n].attach(self.plot)

            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.pltRefresh)
            refTimer = self.sbRefT.value()
            self.timer.start(refTimer)
            self.th = rcvServer(self)
            self.th.start()
        else:
            self.pbStartServer.setText('Start Server')
            self.ServerActive = 0
            self.stopServer()
    def createCurve(self, x, y, colour):

        curve = QwtPlotCurve()
        colour = QColor(colour)
        curve.setPen(colour)
        curve.setData(x, y)
        curve.attach(self.plot)
        #self.plot.replot()
        self.curves.append(curve)
예제 #10
0
class MyWindow(QtGui.QMainWindow):
    """
    This class implements a derivative of
    PyQt4.QtGui.QMainWindow, a complete application
    window, which can feature menus, submenus,
    status bar, etc. In this example, it uses
    few of those features.
    """

    def __init__(self, parent=None):
        """
        Constructor: creates an instance of MyWindow
        """
        #########################################
        # Necessary actions, which must be done #
        # for any project                       #
        #########################################
        # first, calling the ancestor's creator
        QtGui.QMainWindow.__init__(self, parent)
        # get the User Interface from the module UI_p1
        self.ui=Ui_MainWindow()
        # initialize the user interface
        self.ui.setupUi(self)
        #########################################
        # Custom actions, which can be written  #
        # in other ways for other projects.     #
        #########################################
        # aliases for some parts of the user interface
        self.plotWidget    = self.ui.qwtPlot
        self.measureButton = self.ui.measureButton
        self.closeButton   = self.ui.closeButton
        # connect methods to buttons' click signals
        self.measureButton.clicked.connect(self.measure)
        self.closeButton.clicked.connect(self.close)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.plotWidget)
        # initialize the driver for expEYES Junior
        self.p             = ej.open()
        return

    def measure(self):
        """
        This is a custom method to connect to the
        button for measurements.
        There is no need for another custom method,
        since the method "close" is already inherited
        from the ancestor class.
        """
        t,v = self.p.capture(1,1000,200)
        self.curve.setData(t,v,len(t))
        # display the result
        self.plotWidget.replot()
        return
예제 #11
0
 def __insertCurve(self, orientation, color, base):
     curve = QwtPlotCurve()
     curve.attach(self)
     curve.setPen(QPen(color))
     curve.setSymbol(QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.gray), QPen(color), QSize(8, 8)))
     fixed = base * np.ones(10, np.float)
     changing = np.arange(0, 95.0, 10.0, np.float) + 5.0
     if orientation == Qt.Horizontal:
         curve.setData(changing, fixed)
     else:
         curve.setData(fixed, changing)
예제 #12
0
 def __insertCurve(self, orientation, color, base):
     curve = QwtPlotCurve()
     curve.attach(self)
     curve.setPen(QPen(color))
     curve.setSymbol(
         QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.gray), QPen(color), QSize(8, 8))
     )
     fixed = base * np.ones(10, np.float)
     changing = np.arange(0, 95.0, 10.0, np.float) + 5.0
     if orientation == Qt.Horizontal:
         curve.setData(changing, fixed)
     else:
         curve.setData(fixed, changing)
예제 #13
0
    def setData(self, *args):
        """Set x versus y data with error bars in dx and dy.

        Horizontal error bars are plotted if dx is not None.
        Vertical error bars are plotted if dy is not None.

        x and y must be sequences with a shape (N,) and dx and dy must be
        sequences (if not None) with a shape (), (N,), or (2, N):
        - if dx or dy has a shape () or (N,), the error bars are given by
          (x-dx, x+dx) or (y-dy, y+dy),
        - if dx or dy has a shape (2, N), the error bars are given by
          (x-dx[0], x+dx[1]) or (y-dy[0], y+dy[1]).
        """
        if len(args) == 1:
            QwtPlotCurve.setData(self, *args)
            return

        dx = None
        dy = None
        x, y = args[:2]
        if len(args) > 2:
            dx = args[2]
            if len(args) > 3:
                dy = args[3]

        self.__x = np.asarray(x, np.float)
        if len(self.__x.shape) != 1:
            raise RuntimeError('len(asarray(x).shape) != 1')

        self.__y = np.asarray(y, np.float)
        if len(self.__y.shape) != 1:
            raise RuntimeError('len(asarray(y).shape) != 1')
        if len(self.__x) != len(self.__y):
            raise RuntimeError('len(asarray(x)) != len(asarray(y))')

        if dx is None:
            self.__dx = None
        else:
            self.__dx = np.asarray(dx, np.float)
        if len(self.__dx.shape) not in [0, 1, 2]:
            raise RuntimeError('len(asarray(dx).shape) not in [0, 1, 2]')

        if dy is None:
            self.__dy = dy
        else:
            self.__dy = np.asarray(dy, np.float)
        if len(self.__dy.shape) not in [0, 1, 2]:
            raise RuntimeError('len(asarray(dy).shape) not in [0, 1, 2]')

        QwtPlotCurve.setData(self, self.__x, self.__y)
예제 #14
0
    def setData(self, *args):
        """Set x versus y data with error bars in dx and dy.

        Horizontal error bars are plotted if dx is not None.
        Vertical error bars are plotted if dy is not None.

        x and y must be sequences with a shape (N,) and dx and dy must be
        sequences (if not None) with a shape (), (N,), or (2, N):
        - if dx or dy has a shape () or (N,), the error bars are given by
          (x-dx, x+dx) or (y-dy, y+dy),
        - if dx or dy has a shape (2, N), the error bars are given by
          (x-dx[0], x+dx[1]) or (y-dy[0], y+dy[1]).
        """
        if len(args) == 1:
            QwtPlotCurve.setData(self, *args)
            return
            
        dx = None
        dy = None
        x, y = args[:2]
        if len(args) > 2:
            dx = args[2]
            if len(args) > 3:
                dy = args[3]
        
        self.__x = np.asarray(x, np.float)
        if len(self.__x.shape) != 1:
            raise RuntimeError('len(asarray(x).shape) != 1')

        self.__y = np.asarray(y, np.float)
        if len(self.__y.shape) != 1:
            raise RuntimeError('len(asarray(y).shape) != 1')
        if len(self.__x) != len(self.__y):
            raise RuntimeError('len(asarray(x)) != len(asarray(y))')

        if dx is None:
            self.__dx = None
        else:
            self.__dx = np.asarray(dx, np.float)
        if len(self.__dx.shape) not in [0, 1, 2]:
            raise RuntimeError('len(asarray(dx).shape) not in [0, 1, 2]')
            
        if dy is None:
            self.__dy = dy
        else:
            self.__dy = np.asarray(dy, np.float)
        if len(self.__dy.shape) not in [0, 1, 2]:
            raise RuntimeError('len(asarray(dy).shape) not in [0, 1, 2]')
        
        QwtPlotCurve.setData(self, self.__x, self.__y)
예제 #15
0
class AlphaEpsilonPlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)
        self.enableAxis(self.xBottom)

        # insert a few curves
        self.Alpha = QwtPlotCurve('Alpha')
        self.Alpha.setPen(QPen(Qt.red))
        self.Alpha.attach(self)
        self.Epsilon = QwtPlotCurve('Epsilon')
        self.Epsilon.setPen(QPen(Qt.blue))
        self.Epsilon.attach(self)

        # initialize the data
        self.Alpha.setData([0], [0])
        self.Epsilon.setData([0], [0])

        # replot
        self.replot()

    def newData(self, Alpha, Epsilon):
        self.Alpha.setData(list(range(len(Alpha))), Alpha)
        self.Epsilon.setData(list(range(len(Epsilon))), Epsilon)
        # replot
        self.replot()
예제 #16
0
 def __init__(self, title, xdata, ydata, style, symbol=None, *args):
     super(BMPlot, self).__init__(*args)
     self.setMinimumSize(200, 200)
     self.setTitle(title)
     self.setAxisTitle(QwtPlot.xBottom, 'x')
     self.setAxisTitle(QwtPlot.yLeft, 'y')
     curve = QwtPlotCurve()
     curve.setPen(QPen(get_curve_color()))
     curve.setStyle(style)
     curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
     if symbol is not None:
         curve.setSymbol(symbol)
     curve.attach(self)
     curve.setData(xdata, ydata)
     self.replot()
예제 #17
0
def create_log_plot():
    plot = QwtPlot('LogCurveDemo.py (or how to handle -inf values)')
    plot.enableAxis(QwtPlot.xBottom)
    plot.setAxisScaleEngine(QwtPlot.yLeft, QwtLogScaleEngine())
    curve = QwtPlotCurve()
    curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
    pen = QPen(Qt.magenta)
    pen.setWidth(1.5)
    curve.setPen(pen)
    curve.attach(plot)
    x = np.arange(0.0, 10.0, 0.1)
    y = 10*np.cos(x)**2-.1
    print("y<=0:", y<=0)
    curve.setData(x, y)
    plot.replot()
    return plot
예제 #18
0
def create_log_plot():
    plot = QwtPlot('LogCurveDemo.py (or how to handle -inf values)')
    plot.enableAxis(QwtPlot.xBottom)
    plot.setAxisScaleEngine(QwtPlot.yLeft, QwtLogScaleEngine())
    curve = QwtPlotCurve()
    curve.setRenderHint(QwtPlotCurve.RenderAntialiased)
    pen = QPen(Qt.magenta)
    pen.setWidth(1.5)
    curve.setPen(pen)
    curve.attach(plot)
    x = np.arange(0.0, 10.0, 0.1)
    y = 10 * np.cos(x)**2 - .1
    print("y<=0:", y <= 0)
    curve.setData(x, y)
    plot.replot()
    return plot
예제 #19
0
    def setData(self, *args):
        if len(args) == 1:
            QwtPlotCurve.setData(self, *args)
            return
        x, y = args[:2]
        if len(args) > 2:
            self.symbolSizes = args[2]

        self.__x = numpy.asarray(x, numpy.float)
        if len(self.__x.shape) != 1:
            raise RuntimeError('len(asarray(x).shape) != 1')
        self.__y = numpy.asarray(y, numpy.float)
        if len(self.__y.shape) != 1:
            raise RuntimeError('len(asarray(y).shape) != 1')
        if len(self.__x) != len(self.__y):
            raise RuntimeError('len(asarray(x)) != len(asarray(y))')
        QwtPlotCurve.setData(self, self.__x, self.__y)
예제 #20
0
class DataPlot(QwtPlot):

    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.setCanvasBackground(Qt.white)

        # Initialize data
        self.x = [0]
        self.y = [0]

        self.setTitle("A Moving QwtPlot Demonstration")
        self.insertLegend(QwtLegend(), QwtPlot.BottomLegend);

        self.curveR = QwtPlotCurve("Data Moving Right")
        self.curveR.attach(self)
       
        self.curveR.setPen(QPen(Qt.red))

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "Values")
    
        self.startTimer(400)
        self.phase = 0.0
        #self.setAlignCanvasToScales(0.5,0.2)
    
    def timerEvent(self, e):
        if self.phase > np.pi - 0.0001:
            self.phase = 0.0

        # y moves from left to right:
        # shift y array right and assign new value y[0]
        self.y.append(self.phase+5*random.random())
        self.x.append(self.phase*3+0.4*random.random())
        # z moves from right to left:
        # Shift z array left and assign new value to z[n-1].
        self.curveR.setData(self.x, self.y)


        self.replot()
        self.phase += np.pi*0.0
예제 #21
0
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        self.setTitle('ReallySimpleDemo.py')
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)
        self.setAxisTitle(QwtPlot.xBottom, 'x -->')
        self.setAxisTitle(QwtPlot.yLeft, 'y -->')
        self.enableAxis(self.xBottom)

        # insert a few curves
        cSin = QwtPlotCurve('y = sin(x)')
        cSin.setPen(QPen(Qt.red))
        cSin.attach(self)
        cCos = QwtPlotCurve('y = cos(x)')
        cCos.setPen(QPen(Qt.blue))
        cCos.attach(self)
        
        # make a Numeric array for the horizontal data
        x = np.arange(0.0, 10.0, 0.1)

        # initialize the data
        cSin.setData(x, np.sin(x))
        cCos.setData(x, np.cos(x))

        # insert a horizontal marker at y = 0
        mY = QwtPlotMarker()
        mY.setLabel(QwtText('y = 0'))
        mY.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mY.setLineStyle(QwtPlotMarker.HLine)
        mY.setYValue(0.0)
        mY.attach(self)

        # insert a vertical marker at x = 2 pi
        mX = QwtPlotMarker()
        mX.setLabel(QwtText('x = 2 pi'))
        mX.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mX.setLineStyle(QwtPlotMarker.VLine)
        mX.setXValue(2*np.pi)
        mX.attach(self)

        # replot
        self.replot()
예제 #22
0
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        self.setTitle('ReallySimpleDemo.py')
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)
        self.setAxisTitle(QwtPlot.xBottom, 'x -->')
        self.setAxisTitle(QwtPlot.yLeft, 'y -->')
        self.enableAxis(self.xBottom)

        # insert a few curves
        cSin = QwtPlotCurve('y = sin(x)')
        cSin.setPen(QPen(Qt.red))
        cSin.attach(self)
        cCos = QwtPlotCurve('y = cos(x)')
        cCos.setPen(QPen(Qt.blue))
        cCos.attach(self)

        # make a Numeric array for the horizontal data
        x = np.arange(0.0, 10.0, 0.1)

        # initialize the data
        cSin.setData(x, np.sin(x))
        cCos.setData(x, np.cos(x))

        # insert a horizontal marker at y = 0
        mY = QwtPlotMarker()
        mY.setLabel(QwtText('y = 0'))
        mY.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mY.setLineStyle(QwtPlotMarker.HLine)
        mY.setYValue(0.0)
        mY.attach(self)

        # insert a vertical marker at x = 2 pi
        mX = QwtPlotMarker()
        mX.setLabel(QwtText('x = 2 pi'))
        mX.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mX.setLineStyle(QwtPlotMarker.VLine)
        mX.setXValue(2 * np.pi)
        mX.attach(self)

        # replot
        self.replot()
예제 #23
0
class RewardPlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)
        self.enableAxis(self.xBottom)

        # insert a few curves
        self.Reward = QwtPlotCurve('Reward')
        self.Reward.setPen(QPen(Qt.darkGreen))
        self.Reward.attach(self)

        # initialize the data
        self.Reward.setData([0], [0])

        # replot
        self.replot()

    def newData(self, Reward):
        self.Reward.setData(list(range(len(Reward))), Reward)
        # replot
        self.replot()
예제 #24
0
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        layout = QGridLayout(self)        
        # try to create a plot for SciPy arrays

        # make a curve and copy the data
        numpy_curve = QwtPlotCurve('y = lorentzian(x)')
        x = np.arange(0.0, 10.0, 0.01)
        y = lorentzian(x)
        numpy_curve.setData(x, y)
        # here, we know we can plot NumPy arrays
        numpy_plot = QwtPlot(self)
        numpy_plot.setTitle('numpy array')
        numpy_plot.setCanvasBackground(Qt.white)
        numpy_plot.plotLayout().setCanvasMargin(0)
        numpy_plot.plotLayout().setAlignCanvasToScales(True)
        # insert a curve and make it red
        numpy_curve.attach(numpy_plot)
        numpy_curve.setPen(QPen(Qt.red))
        layout.addWidget(numpy_plot, 0, 0)
        numpy_plot.replot()

        # create a plot widget for lists of Python floats
        list_plot = QwtPlot(self)
        list_plot.setTitle('Python list')
        list_plot.setCanvasBackground(Qt.white)
        list_plot.plotLayout().setCanvasMargin(0)
        list_plot.plotLayout().setAlignCanvasToScales(True)
        x = drange(0.0, 10.0, 0.01)
        y = [lorentzian(item) for item in x]
        # insert a curve, make it red and copy the lists
        list_curve = QwtPlotCurve('y = lorentzian(x)')
        list_curve.attach(list_plot)
        list_curve.setPen(QPen(Qt.red))
        list_curve.setData(x, y)
        layout.addWidget(list_plot, 0, 1)
        layout.addWidget(DataPlot(self),1,1)
        layout.addWidget(3dstl(self), 1, 0)
        list_plot.replot()
예제 #25
0
    def pbServerClicked(self):
        if self.ServerActive == 0:
            self.N = self.sbNsig.value()
            self.Hist = int(self.edHist.text().__str__())
            self.pbStartServer.setText('Stop Server')
            self.ServerActive = 1

            self.plot = dataPlot(self.N)
            self.plot.resize(800, 800)
            self.plot.show()

            self.x = []
            self.c = []
            for n in range(0, self.N):
                self.x.append([])

            for n in range(0, int(self.N / 2)):
                cv = QwtPlotCurve()
                pen = QPen(QColor(self.colors[n]))
                cv.setPen(pen)
                cv.setData([], [])
                self.c.append(cv)
                self.c[n].attach(self.plot)
            if not (self.ckAutoscale.isChecked()):
                self.xmin = float(self.edXmin.text().__str__())
                self.xmax = float(self.edXmax.text().__str__())
                self.ymin = float(self.edYmin.text().__str__())
                self.ymax = float(self.edYmax.text().__str__())
            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.pltRefresh)
            refTimer = self.sbRefT.value()
            self.timer.start(refTimer)
            self.th = rcvServer(self)
            self.th.start()
        else:
            self.pbStartServer.setText('Start Server')
            self.ServerActive = 0
            self.stopServer()
예제 #26
0
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        layout = QGridLayout(self)        
        # try to create a plot for SciPy arrays

        # make a curve and copy the data
        numpy_curve = QwtPlotCurve('y = lorentzian(x)')
        x = np.arange(0.0, 10.0, 0.01)
        y = lorentzian(x)
        numpy_curve.setData(x, y)
        # here, we know we can plot NumPy arrays
        numpy_plot = QwtPlot(self)
        numpy_plot.setTitle('numpy array')
        numpy_plot.setCanvasBackground(Qt.white)
        numpy_plot.plotLayout().setCanvasMargin(0)
        numpy_plot.plotLayout().setAlignCanvasToScales(True)
        # insert a curve and make it red
        numpy_curve.attach(numpy_plot)
        numpy_curve.setPen(QPen(Qt.red))
        layout.addWidget(numpy_plot, 0, 0)
        numpy_plot.replot()

        # create a plot widget for lists of Python floats
        list_plot = QwtPlot(self)
        list_plot.setTitle('Python list')
        list_plot.setCanvasBackground(Qt.white)
        list_plot.plotLayout().setCanvasMargin(0)
        list_plot.plotLayout().setAlignCanvasToScales(True)
        x = drange(0.0, 10.0, 0.01)
        y = [lorentzian(item) for item in x]
        # insert a curve, make it red and copy the lists
        list_curve = QwtPlotCurve('y = lorentzian(x)')
        list_curve.attach(list_plot)
        list_curve.setPen(QPen(Qt.red))
        list_curve.setData(x, y)
        layout.addWidget(list_plot, 0, 1)
        list_plot.replot()
예제 #27
0
class FermentGraph(QWidget):
    _logname = 'FermentGraphGeneric'
    _log = logging.getLogger(f'{_logname}')

    def __init__(self, database, parent=None):
        super().__init__(parent)
        self.db = database
        self.updateTimer = QTimer(self)
        self.updateTimer.start(5000)

        self.plot = QwtPlot()
        self.curve = QwtPlotCurve()
        self.curve.attach(self.plot)
        self.plot.resize(1000, 1000)
        self.plot.show()
        self.plot.setAxisScaleDraw(QwtPlot.xBottom, DateTimeTimeScaleDraw())

        axisFont = QFont("Helvetica", 11, QFont.Bold)
        titleFont = QFont("Helvetica", 12, QFont.Bold)

        xTitle = QwtText()
        xTitle.setText("Time")
        xTitle.setFont(axisFont)
        self.plot.setAxisTitle(self.plot.xBottom, xTitle)

        self.yTitle = QwtText()
        self.yTitle.setFont(axisFont)
        self.plot.setAxisTitle(self.plot.yLeft, self.yTitle)

        self.titleText = QwtText()
        self.titleText.setFont(titleFont)
        self.plot.setTitle(self.titleText)

        mainLayout = QHBoxLayout()
        mainLayout.addWidget(self.plot)
        self.setLayout(mainLayout)

        self.plot.show()
        self.results = []
        self.batchID = None

    def updatePlot(self, variable):
        if self.batchID is not None:
            self.db.flushTables()
            sql = f"SELECT TimeStamp, {variable} FROM Ferment WHERE BatchID = '{self.batchID}'"

            timestamps = []
            self.results = []
            for data in self.db.custom(sql)[1:]:
                timestamps.append(data[0])
                self.results.append(data[1])

            startTime = timestamps[0]
            for i in range(len(timestamps)):
                timestamps[i] = (timestamps[i] - startTime).seconds

            # self.plot.setAxisScaleDraw(QwtPlot.xBottom, TimeScaleDraw())

            self.curve.setData(timestamps, self.results)
            self.plot.replot()
            self.plot.show()

    def changeTank(self, tankID):
        self.titleText.setText(f"Fermentation Tank: {tankID}")
예제 #28
0
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        # connect methods to buttons' click signals
        self.ui.wakeUpButton.clicked.connect(self.wakeUp)
        self.ui.stopButton.clicked.connect(self.stop)
        self.ui.closeButton.clicked.connect(self.close)
        self.ui.saveButton.clicked.connect(self.save)
        self.ui.immediateButton.clicked.connect(self.immediate)
        self.ui.finalButton.clicked.connect(self.final)
        self.ui.fitButton.clicked.connect(self.fit)
        self.ui.action_Save_Ctrl_S.triggered.connect(self.save)
        self.ui.action_Quit_Ctrl_Q.triggered.connect(self.close)
        self.ui.actionManual.triggered.connect(self.manual)
        self.ui.actionAbout.triggered.connect(self.about)
        self.ui.durationEdit.textChanged.connect(self.durationChanged)
        # create a timer
        self.stopTime=time.time()
        self.timer=QtCore.QTimer()
        # connect the timer to the "tick" callback method
        self.timer.timeout.connect(self.tick)
        # 20 times per second
        self.timer.start(50)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve0        = QwtPlotCurve()
        self.fitCurve1     = QwtPlotCurve()
        self.fitCurve2     = QwtPlotCurve()
        self.fitCurve3     = QwtPlotCurve()
        self.curve.attach(self.ui.qwtPlot)
        self.curve0.attach(self.ui.qwtPlot)
        self.fitCurve1.attach(self.ui.qwtPlot)
        self.fitCurve2.attach(self.ui.qwtPlot)
        self.fitCurve3.attach(self.ui.qwtPlot)
        # adjust the axis scales based on duration = 15 s
        self.durationChanged(15, ampl=5)
        # set the maxvalue for the threshold rate (in V/s)
        self.maxthreshold=150/15 # = 150/duration
        # expEYESdetection and initialization
        try:
            self.p             = ej.open()
            assert(self.p.fd)
            self.setWindowTitle("expEYES Junior found on port {}".format(
                self.p.fd.port
            ))
        except:
            self.setWindowTitle("ERROR: expEYES Junior NOT FOUND!")
            self.ui.wakeUpButton.setEnabled(False)
        # custom properties
        self.isImmediate=True
        return
        
    def durationChanged(self, value, ampl=0):
        """
        Callback function for changed in ui.durationEdit
        @param value the widget's value in case of an event
        @param ampl an amplitudes (defaults to 0)
        """
        try:
            duration=float(value)
        except:
            return
        # set the axis scales for the plot widget
        self.ui.qwtPlot.setAxisScale(QwtPlot.xBottom, 0, duration)
        # draw the "zero" line
        small=duration/1e6
        self.curve0.setData([0, small, 2*small, 3*small, duration],
                            [0, ampl,  -ampl,   0,       0], 5)
        # update the threshold rate 
        self.maxThreshold=150/duration
        self.ui.thresholdLabel.setText("{} V/s".format(self.maxThreshold))
        # erase fit curves
        self.fitCurve1.setData([],[],0)
        self.fitCurve2.setData([],[],0)
        self.fitCurve3.setData([],[],0)
        return
        
    def immediate(self):
        self.isImmediate=True
        return
        
    def final(self):
        self.isImmediate=False
        return
        
    def stop(self):
        # in "final" mode, this has no effect
        # in "immediate" mode, it forces the plot to
        # stop at the next tick call.
        self.stopTime=time.time()
        return

    def save(self):
        filename=self.ui.fileNameEdit.text()
        with open(filename,"w") as outfile:
            for i in range(len(self.t)):
                outfile.write("{} {}\n".format(
                   self.t[i], self.v[i]
                ))
        self.ui.statusbar.showMessage(
            "Saved data to {}".format(filename), 3000 # 3 seconds
        )
        return
        
    def waitForThreshold(self, threshold, duration, timeOut=None):
        """
        wait for the input to change quickly enough 
        @param threshold a minimal voltage slew rate (V/s)
        @param duration the duration of scheduled measurement series
        @param timeOut the longets wait time (defaults to None)
        """
        start=time.time()
        delay=int(duration/1000*1e6) # thousandth of duration, in µs
        if delay < 4:
            delay=4
        t, v = self.p.capture(1, 2, delay)
        slewRate=(v[1]-v[0])/(t[1]-t[0])*1000
        while abs(slewRate)<threshold:
            if timeOut != None and time.time()>start+timeOut:
                return
            t, v = self.p.capture(1, 2, delay)
            slewRate=(v[1]-v[0])/(t[1]-t[0])*1000
        return

    def wakeUp(self):
        # get the duration of the experiment in s
        duration = float(self.ui.durationEdit.text())
        self.durationChanged(duration)
        if duration < 0.5: # "final" mode is mandatory
            self.ui.finalButton.setChecked(True)
            self.isImmediate=False
        elif duration > 3.5: # "immediate" mode is mandatory
            self.ui.immediateButton.setChecked(True)
            self.isImmediate=True
        # wait until the slew rate is fast enough
        threshold = self.ui.thresholdSlider.value()*self.maxThreshold/100
        self.waitForThreshold(threshold, duration, timeOut=5)
        # start measuring
        if self.isImmediate:
            now=time.time()
            self.t=[]
            self.v=[]
            self.curve.setData([],[],0)
            self.startTime=now
            self.stopTime=now+duration
            # now the curve will grow until time.time >= self.stopTime
            # thanks to self.timer's timeout events
        else:
            samples  = 1800 # maximum sample number with 8 bit precision
            # ensure that samples * delay will be slightly bigger than duration
            delay=1+int(duration*1e6/1800)
            t, self.v = self.p.capture(1,samples, delay)
            self.t=[1e-3*date for date in t] # convert ms to s
            self.curve.setData(self.t, self.v, len(self.t))
        return

    def tick(self):
        """ Callback for the timeout events """
        t=time.time()
        if t < self.stopTime:
            v = self.p.get_voltage(1)
            self.t.append(time.time()-self.startTime)
            self.v.append(v)
            self.curve.setData(self.t, self.v, len(self.t))
        return
            
    
    def fit(self):
        """
        Fitting data in self.t, self.v with a damped oscillation model
        """
        # fitting is performed by eyemath (aka em) thanks to
        # scipy.optimize, and the error function defined by
        # the module eyemath (line 92):
        # p[0] * sin(2*pi*p[1]*x+p[2]) * exp(-p[4]*x) - p[3]
        # so the vector of parameters is:
        # amplitude, frequency, phase, DC average, damping factor.
        yfit, plsq = em.fit_dsine(self.t, self.v, mode="Hz")
        # display the fitting model
        msg="{0:4.2f}*sin(2*pi*{1:4.2f}*t+({2:3.1f}))*exp(-{4:4.2f}*t)+{3:3.1f}".format(
            *plsq
        )
        self.ui.fitEdit.setText(msg)
        # display three curves : model and model's envelopes
        t=np.array(self.t)
        f1=np.array(yfit)
        f2=plsq[0]*np.exp(-plsq[4]*t)
        f3=-1.0*f2
        average=plsq[3]*np.ones(len(t))
        red=QtGui.QColor("#ff0000")
        self.fitCurve1.setPen(red)
        self.fitCurve2.setPen(red)
        self.fitCurve3.setPen(red)
        self.fitCurve1.setData(t, f1, len(t))
        self.fitCurve2.setData(t, f2+average, len(t))
        self.fitCurve3.setData(t, f3+average, len(t))
        return
        
    def about(self):
        """
        show license stuff
        """
        with open("license.html","w") as licenseFile:
            licenseFile.write("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta  http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title> About ... </title>
</head>
<body>
""")
            licenseFile.write(license)
            licenseFile.write("</body></html>")
        self.aboutWidget=QtGui.QTextBrowser(self.parent())
        self.aboutWidget.resize(600,500)
        self.aboutWidget.show()
        self.aboutWidget.setOpenExternalLinks(True)
        self.aboutWidget.setSource(QtCore.QUrl("file:license.html"))
        self.aboutWidget.setWindowTitle("About oscill4.py")
        return
        
    def manual(self):
        """
        display the manual
        """
        self.manualWidget=QtGui.QTextBrowser(self.parent())
        self.manualWidget.resize(600,500)
        self.manualWidget.show()
        self.manualWidget.setOpenExternalLinks(True)
        self.manualWidget.setSource(QtCore.QUrl("file:oscill4.html"))
        self.manualWidget.setWindowTitle("User Manual of oscill4.py")
        return
        
    def notImplemented(self):
        msg=QtGui.QMessageBox(QtGui.QMessageBox.Warning,"Sorry",
                              "not yet implemented", )
        msg.exec_()
        return
예제 #29
0
class MyWindow(QtGui.QMainWindow):
    """
    This class implements a derivative of
    PyQt4.QtGui.QMainWindow, a complete application
    window, which can feature menus, submenus,
    status bar, etc. In this example, it uses
    few of those features.
    """

    def __init__(self, parent=None):
        """
        Constructor: creates an instance of MyWindow
        """
        #########################################
        # Necessary actions, which must be done #
        # for any project                       #
        #########################################
        # first, calling the ancestor's creator
        QtGui.QMainWindow.__init__(self, parent)
        # get the User Interface from the module UI_p1
        self.ui=Ui_MainWindow()
        # initialize the user interface
        self.ui.setupUi(self)
        #########################################
        # Custom actions, which can be written  #
        # in other ways for other projects.     #
        #########################################
        # aliases for some parts of the user interface
        self.plotWidget    = self.ui.qwtPlot
        self.measureButton = self.ui.measureButton
        self.closeButton   = self.ui.closeButton
        # connect methods to buttons' click signals
        self.measureButton.clicked.connect(self.measure)
        self.closeButton.clicked.connect(self.close)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.plotWidget)
        # initialize the driver for expEYES Junior
        # prevent an error if the box is not detected
        try:
            self.p             = ej.open()
            assert(self.p.fd)
            self.setWindowTitle("expEYES Junior found on port {}".format(
                self.p.fd.port
            ))
        except:
            self.setWindowTitle("ERROR: expEYES Junior NOT FOUND!")
            self.measureButton.setEnabled(False)
        return

    def measure(self):
        """
        This is a custom method to connect to the
        button for measurements.
        There is no need for another custom method,
        since the method "close" is already inherited
        from the ancestor class.
        """
        sample=int(self.ui.samplesEdit.text())
        delay=int(self.ui.delayEdit.text())
        channel=self.inputCode()
        duration=int(sample*delay/1000) # in ms
        self.ui.statusbar.showMessage(
            "Measuring data for {} seconds, please be patient...".format(duration/1000),
            duration
        )
        self.ui.statusbar.repaint() # immediately shows the status
        t,v = self.p.capture(channel, sample, delay)
        self.curve.setData(t,v,len(t))
        # display the result
        self.plotWidget.replot()
        return

    def inputCode(self):
        """
        considers the radio buttons
        @return the code for the selected input channel
        """
        value={
            "A1":  1,
            "A2":  2,
            "IN1": 3,
            "IN2": 4,
            "SEN": 5,
        }
        radios=[r for r in self.ui.groupBox.children()
                  if isinstance(r, QtGui.QRadioButton)]
        for r in radios:
            if r.isChecked():
                return value[r.text().strip()]
        return 0
예제 #30
0
class MapDemo(QMainWindow):
    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.plot = QwtPlot(self)
        self.plot.setTitle("A Simple Map Demonstration")
        self.plot.setCanvasBackground(Qt.white)
        self.plot.setAxisTitle(QwtPlot.xBottom, "x")
        self.plot.setAxisTitle(QwtPlot.yLeft, "y")
        self.plot.setAxisScale(QwtPlot.xBottom, 0.0, 1.0)
        self.plot.setAxisScale(QwtPlot.yLeft, 0.0, 1.0)
        self.setCentralWidget(self.plot)
        # Initialize map data
        self.count = self.i = 1000
        self.xs = np.zeros(self.count, np.float)
        self.ys = np.zeros(self.count, np.float)
        self.kappa = 0.2
        self.curve = QwtPlotCurve("Map")
        self.curve.attach(self.plot)
        self.curve.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.red), QPen(Qt.blue),
                      QSize(5, 5)))
        self.curve.setPen(QPen(Qt.cyan))
        toolBar = QToolBar(self)
        self.addToolBar(toolBar)
        # 1 tick = 1 ms, 10 ticks = 10 ms (Linux clock is 100 Hz)
        self.ticks = 10
        self.tid = self.startTimer(self.ticks)
        self.timer_tic = None
        self.user_tic = None
        self.system_tic = None
        self.plot.replot()

    def setTicks(self, ticks):
        self.i = self.count
        self.ticks = int(ticks)
        self.killTimer(self.tid)
        self.tid = self.startTimer(ticks)

    def resizeEvent(self, event):
        self.plot.resize(event.size())
        self.plot.move(0, 0)

    def moreData(self):
        if self.i == self.count:
            self.i = 0
            self.x = random.random()
            self.y = random.random()
            self.xs[self.i] = self.x
            self.ys[self.i] = self.y
            self.i += 1
            chunks = []
            self.timer_toc = time.time()
            if self.timer_tic:
                chunks.append("wall: %s s." %
                              (self.timer_toc - self.timer_tic))
                print(' '.join(chunks))
            self.timer_tic = self.timer_toc
        else:
            self.x, self.y = standard_map(self.x, self.y, self.kappa)
            self.xs[self.i] = self.x
            self.ys[self.i] = self.y
            self.i += 1

    def timerEvent(self, e):
        self.moreData()
        self.curve.setData(self.xs[:self.i], self.ys[:self.i])
        self.plot.replot()
예제 #31
0
from qwt.qt.QtGui import QApplication
from qwt import QwtPlot, QwtPlotCurve
import numpy as np

app = QApplication([])

x = np.linspace(-10, 10, 500)
y1, y2 = np.cos(x), np.sin(x)

my_plot = QwtPlot("Two curves")
curve1, curve2 = QwtPlotCurve("Curve 1"), QwtPlotCurve("Curve 2")
curve1.setData(x, y1)
curve2.setData(x, y2)
curve1.attach(my_plot)
curve2.attach(my_plot)
my_plot.resize(600, 300)
my_plot.replot()
my_plot.show()

app.exec_()
class DataPlot(QwtPlot):
    # signal define
    signal_showinfo = pyqtSignal(object)

    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.uut_dev = None
        self.timerId = None
        #self.interval = 250    # ms
        self.interval = config.interval  # ms

        fileTIME = datetime.datetime.now()
        File_timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
            fileTIME.year, fileTIME.month, fileTIME.day, fileTIME.hour,
            fileTIME.minute, fileTIME.second)

        self.fileNamme = '.\data\data_%s.txt' % File_timestamp
        print('Raw data record file name:%s' % self.fileNamme)
        # default parameters from config file
        self.x_ZERO = config.X_lower
        self.x_range = config.X_upper
        self.x_interval = config.X_grid_interval
        self.y_range_Upper = config.Y_upper
        self.y_range_Lower = config.Y_lower
        self.y_interval = config.Y_grid_interval
        self.unit = 'kPa'  # default value, will replaced by actual reading.
        #self.getReadingCommand = r"UPPER_VAL?\r\n"  # default pass and pac
        #self.getResp_rex = r'^[-]?([0-9]{1,}[.]?[0-9]*)'

        self.lenth = config.Slope_lenth  #  40 = 10s caculate the slowrate

        # QwtPlot property
        # Initialize 坐标轴
        self.setCanvasBackground(Qt.white)  #Qt.white
        self.alignScales()
        grid = QwtPlotGrid()
        grid.attach(self)
        grid.setMajorPen(QPen(Qt.black, 0, Qt.DotLine))

        # x Axis property
        #self.setAxisScaleDraw(QwtPlot.xBottom, TimeScaleDraw(self.cpuStat.upTime()))
        #timeScale = QwtDateScaleDraw(Qt.LocalTime)
        #print(timeScale)
        #self.setAxisScaleDraw(QwtPlot.xBottom, timeScale)

        self.setAxisScale(QwtPlot.xBottom, 0.0, self.x_range, self.x_interval)

        #self.setAxisAutoScale(QwtPlot.yLeft,True)
        #self.setAxisScale(QwtPlot.yLeft,99.99,100.0,0.0005)
        self.setAxisScale(QwtPlot.yLeft, self.y_range_Lower,
                          self.y_range_Upper, self.y_interval)
        self.setAxisLabelRotation(QwtPlot.xBottom, -45.0)

        self.x = np.arange(
            0.0, self.x_range + 1, 0.25
        )  #0.25 for ONE POINT, THIS SHOULD BE Align to the reading rate:250ms

        #self.z = np.zeros(len(self.x), np.float)
        list = []
        for i in range(len(self.x)):
            list.append(0.0)
        self.z = np.array(list)

        rlist = []

        for i in range(self.lenth):  # 10s
            rlist.append(0.0)
        self.RateList = np.array(rlist)

        self.setTitle("UUT Reading Monitor - OutPort(%s)\r\n" % (self.unit))
        #self.insertLegend(QwtLegend(), QwtPlot.RightLegend);

        self.curveL = QwtPlotCurve("UUT Reading")
        self.curveL.attach(self)
        pen = QPen(Qt.red)
        pen.setWidth(1.5)
        #pen.setWidth(1)
        self.curveL.setPen(pen)

        font = QFont()
        font.setFamily("Calibri")  #,Consolas
        font.setPointSize(16)

        # show the latest reading. line and point value
        self.peakMarker = m = QwtPlotMarker()
        m.setLineStyle(QwtPlotMarker.HLine)
        m.setLabelAlignment(Qt.AlignLeft | Qt.AlignTop)
        m.setLinePen(QPen(Qt.blue, 1.5, Qt.DashDotLine))

        text = QwtText('Reading: ----')
        text.setColor(Qt.red)
        text.setBackgroundBrush(QBrush(self.canvasBackground()))

        text.setFont(font)

        m.setLabel(text)
        # MarkPoint symbol
        m.setSymbol(
            QwtSymbol(QwtSymbol.Diamond, QBrush(Qt.blue), QPen(Qt.green),
                      QSize(7, 7)))
        m.attach(self)

        # text marker  , display slope rate
        self.txtMarker = m = QwtPlotMarker()
        m.setValue(self.x_range / 2,
                   self.y_range_Upper - self.y_interval / 2)  # show position
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        text = QwtText('Slope Rate: ----')
        text.setFont(font)
        text.setColor(Qt.white)
        text.setBackgroundBrush(QBrush(Qt.black))
        text.setBorderPen(QPen(Qt.red, 2))

        m.setLabel(text)
        m.attach(self)

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "UUT - Reading(%s)" % (self.unit))

        self.replot()

        #self.startTimer(250)#ms# FOR GET READING
        #self.starttime = time.clock();#unit: s    python2
        self.starttime = time.time()  # python3

        self.idx = 0
        self.readfmt = "%f"
        self.Saveinfo("Starting...")

    def setPara(
            self, y_lower, y_upper, y_interval, x_interval, x_upper,
            x_lower):  # y_lower,y_upper,y_interval,x_interval,X-Upper,x_lower
        self.y_range_Upper = y_upper
        self.y_range_Lower = y_lower
        self.x_interval = x_interval
        self.y_interval = y_interval
        self.x_range = x_upper
        self.x_ZERO = x_lower

        self.setAxisScale(QwtPlot.xBottom, self.x_ZERO, self.x_range,
                          self.x_interval)  # self.x_range
        #self.setAxisAutoScale(QwtPlot.yLeft,True)
        #self.setAxisScale(QwtPlot.yLeft,99.99,100.0,0.0005)
        self.setAxisScale(QwtPlot.yLeft, self.y_range_Lower,
                          self.y_range_Upper, self.y_interval)

        self.replot()

    def StartTimer(self):
        if not self.uut_dev:
            print(
                "Please connect the device first!\r\n**********************************************"
            )
            self.signal_showinfo.emit("Please connect the device first!")
            QMessageBox.warning(self, 'Warning',
                                'Please connect the device first!',
                                QMessageBox.Yes, QMessageBox.Yes)

        else:
            if not self.timerId:
                print(self.interval)
                self.timerId = self.startTimer(self.interval)
                self.signal_showinfo.emit("Timer Started!")

    def StopTimer(self):
        if self.timerId:
            if (QMessageBox.Yes == QMessageBox.warning(
                    self, 'Warning',
                    'Are you want to stop the refresh of the curve?',
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)):
                self.killTimer(self.timerId)
                self.timerId = None
                self.signal_showinfo.emit("Timmer stoped!")

    def Connect(self, COMPort, baudrate):
        if self.uut_dev is None:
            try:
                self.uut_dev = device_py3.SerialDevice(
                    False, False, port=COMPort,
                    baudrate=baudrate)  #'''args[0]'''
                self.signal_showinfo.emit('Device opened success!')

                # Do Configuration settings:
                for cmd in config.pre_cmd:
                    print(self.sendcmd(self.uut_dev, cmd + "\r\n"))
                    time.sleep(0.5)
                #print(self.sendcmd(self.uut_dev,"echo 0\r\n"))
                #print(self.sendcmd(self.uut_dev,"prompt off\r\n"))

            except Exception as e:
                print(e, '\r\nDevice opened failed!')
                self.signal_showinfo.emit(
                    'Device opened failed!\r\n**********************************************'
                )
                QMessageBox.warning(
                    self, 'Warning',
                    'Device opened failed! Please Check the COM port!!',
                    QMessageBox.Yes, QMessageBox.Yes)

        else:
            print("Device already opened!")
            self.signal_showinfo.emit("Device already opened!")
            QMessageBox.warning(self, 'Warning', 'Device has already opened!',
                                QMessageBox.Yes, QMessageBox.Yes)

    def DisConnect(self):
        self.StopTimer()
        if self.uut_dev:
            self.uut_dev.close()
            self.uut_dev = None
            print("Device disconnected! \r\n")
            self.signal_showinfo.emit("Device disconnected!")
            QMessageBox.warning(self, 'Warning', 'Device disconnected!',
                                QMessageBox.Yes, QMessageBox.Yes)

    def showPeak(self, x, amplitude):
        self.peakMarker.setValue(x, amplitude)  # position
        label = self.peakMarker.label()
        label.setText('Reading: %f %s' % (amplitude, self.unit))
        self.peakMarker.setLabel(label)

    def showTxtLabel(self, x, y, txt):
        self.txtMarker.setValue(x, y)
        label = self.txtMarker.label()
        label.setText(txt)
        self.txtMarker.setLabel(label)

    def alignScales(self):
        self.canvas().setFrameStyle(QFrame.Box | QFrame.Plain)
        self.canvas().setLineWidth(1)
        for i in range(QwtPlot.axisCnt):
            scaleWidget = self.axisWidget(i)
            if scaleWidget:
                scaleWidget.setMargin(0)
            scaleDraw = self.axisScaleDraw(i)
            if scaleDraw:
                scaleDraw.enableComponent(QwtAbstractScaleDraw.Backbone, False)

    def timerEvent(self, e):
        # send cmd and get readings, record times, X is second;
        # tfdata = self.uut_get_val(self.uut_dev, "VAL?\r")   #Wolf
        #tfdata = self.uut_get_val(self.uut_dev, "READ:VOLT:DC?\r")   # GW VOLT
        #ifdata = self.uut_get_val(self.uut_dev, "READ:CURR:DC?\r")   # GW CURRENT
        #tfdata = self.uut_get_val(self.uut_dev, "x?\r\n")   # 8508

        tfdata = self.uut_get_val(self.uut_dev, config.GetReadingCmd +
                                  "\r\n")  #"UPPER_VAL?\r\n")   # pass/pac

        self.showPeak(int(self.x_range), tfdata)
        #print(tfdata)  #, "\t"	, ifdata

        self.z = np.concatenate((self.z[1:], self.z[:1]), 0)
        if (tfdata < 99999999.0):
            self.z[-1] = tfdata
        else:
            self.z[-1] = 99999999.0

        # Rate
        self.RateList = np.concatenate((self.RateList[1:], self.RateList[:1]),
                                       0)
        self.RateList[-1] = tfdata
        self.showTxtLabel(
            self.x_ZERO, self.y_range_Upper,
            str('Slope Rate:%f %s/min' %
                ((self.RateList[-1] - self.RateList[0]) /
                 (self.lenth * 250.0 / 1000.0 / 60.0), self.unit)))

        self.curveL.setData(self.x, self.z)
        self.setTitle("Max:%f, min:%f, Peak2Peak:%f " %
                      (np.amax(self.z), np.amin(self.z), np.ptp(self.z)))
        self.setAxisTitle(QwtPlot.yLeft, "UUT - Reading(%s)" % (self.unit))
        self.replot()

        self.idx = self.idx + 1
        #Write file to txt log
        self.SaveData(tfdata)

        #now = time.clock();   # python 2
        now = time.time()
        # python 3
        if ((now - self.starttime) > int(self.x_range)):  #  points (seconds)

            #self.starttime = time.clock(); # reset start time  python 2
            self.starttime = time.time()
            # reset start time    python 3

            pngTIME = datetime.datetime.now()
            FILE_timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
                pngTIME.year, pngTIME.month, pngTIME.day, pngTIME.hour,
                pngTIME.minute, pngTIME.second)
            PNGFile = ('%s_%s' % (FILE_timestamp, '.png'))
            self.exportTo('.\pic\%s' % PNGFile,
                          size=(1920, 1080),
                          resolution=100)
            print(PNGFile, "The snaped curve picture has been created.")

    def uut_get_val(
        self,
        uut_dev_in,
        type="x?\r\n"
    ):  #[0-9]\d*\.\d+$    #r'[ -+]\d+\.\d+[Ee][-+][0-9]{2}'   #r'[-]?\d+\.\d+' 匹配正负小数
        cmd_encode = type.encode()

        m, self.unit = uut_dev_in.trx(
            cmd_encode, config.rsp_regular
        )  #r'^[-]?([0-9]{1,}[.]?[0-9]*)')   # ^[-]?([0-9]{1,}[.]?[0-9]*)$   - 匹配正负小数和整数

        if m:
            return float(m.group(0))
        else:
            return 7200.0  ##

    def sendcmd(self, uut_dev_in, cmd):
        cmd_encode = cmd.encode()
        uut_dev_in.write(cmd_encode)

        return cmd_encode

    def SaveData(self, tfdata):
        fh = open(self.fileNamme, "a")
        now = datetime.datetime.now()
        timestamp = "%02d:%02d:%02d.%03d" % (now.hour, now.minute, now.second,
                                             now.microsecond / 1000)

        rstr = "%s, %s, %s\n" % (self.idx, timestamp, tfdata)
        fh.write(rstr)
        fh.flush()

    def Saveinfo(self, info):
        fh = open(self.fileNamme, "a")
        now = datetime.datetime.now()
        timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
            now.year, now.month, now.day, now.hour, now.minute, now.second)
        title = "%s,   %s\n" % (timestamp, info)
        fh.write(title)
        fh.write("\nSN,TIME,SenseNiose\n")
        fh.flush()
예제 #33
0
    def __init__(self, parent=None):
        super(Mision, self).__init__(parent)
        layout = QGridLayout(self)
        layout.lb1 = QLabel(self)
        layout.IM1=QLabel(self)
        layout.IM2=QLabel(self)
        layout.IM3=QLabel(self)
        layout.IM4 = QLabel(self)
        layout.IM5 = QLabel(self)
        layout.IM1.setPixmap(QPixmap("ipn.png"))
        layout.IM1.setGeometry(1250, 0, 120, 90)
        layout.IM2.setPixmap(QPixmap("mexico.png"))
        layout.IM2.setGeometry(1160, 0, 120, 90)
        layout.IM3.setPixmap(QPixmap("upiita.png"))
        layout.IM3.setGeometry(80, 0, 120, 90)
        layout.IM4.setPixmap(QPixmap("CANSATCOMP.png"))
        layout.IM4.setGeometry(500, 30, 180, 90)
        layout.IM5.setPixmap(QPixmap("IPNUPIITA.png"))
        layout.IM5.setGeometry(700, 30, 180, 90)
        ###############
        layout.lb1.setPixmap(QPixmap("CANSAT_BKG.png"))
        layout.lb1.setGeometry(0, 0, 1500, 1000)

        ############################TITLE#############################
        titulo1=QLabel()
        teamthor = QPixmap("TEAM3.png")
        titulo1.setPixmap(teamthor)
        layout.addWidget(titulo1,0,1)
        #############################################################
        x = [1, 2]
        y = [1, 2]
        layout.addWidget(grap1, 1, 0)
 ##############################################################
        graph2 = QwtPlot()
        curva2 = QwtPlotCurve()
        curva3 = QwtPlotCurve()
        xcurva2 = [-800, 800]
        ycurva2 = [0, 0]
        xcurva3 = [0, 0]
        ycurva3 = [-800, 800]
        curva2.setData(xcurva2, ycurva2)
        curva2.setPen(QPen(Qt.black))
        curva2.attach(graph2)
        curva3.setData(xcurva3, ycurva3)
        curva3.setPen(QPen(Qt.black))
        curva3.attach(graph2)
        pal = QPalette();
        pal.setColor(QPalette.Text, Qt.white)
        pal.setColor(QPalette.Foreground, Qt.white)
        layout.addWidget(graph2, 2, 0)
        grid = QwtPlotGrid()
        grid.attach(graph2)
        grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
        graph2.replot()
        graph2.setAxisScale(QwtPlot.xBottom, -800, 800)
        graph2.setAxisScale(QwtPlot.yLeft, -800, 800)
        graph2.setPalette(pal)
#############################################################)
        layoutv = QGridLayout()
        layoutvN = QVBoxLayout()
        lb1 = QLabel(self)
        pixmap=QPixmap("DIAL4.png")
        pixmap = pixmap.scaledToWidth(220)
        lb1.setPixmap(pixmap)
        layoutv.addWidget(text_pressure,0,0)
        layoutv.addWidget(lb1,1,0)
        layoutv.addWidget(ql1,1,0,Qt.AlignCenter)
        frame5.setLayout(layoutv)
        layoutvN.addWidget(frame5)
        layout.addLayout(layoutvN, 1, 1)
#############################################################
        layoutvp = QGridLayout()
        layoutvNp = QVBoxLayout()
        lb1p = QLabel(self)
        pixmapp = QPixmap("DIAL4.png")
        pixmapp = pixmap.scaledToWidth(160)
        lb1p.setPixmap(pixmapp)
        layoutvp.addWidget(text_pitch, 0, 0)
        layoutvp.addWidget(text_roll, 1, 0)
        layoutvp.addWidget(text_bladespin, 2, 0)
        layoutvp.addWidget(lb1p, 3, 0 ,Qt.AlignCenter)
        layoutvp.addWidget(ql1p, 3, 0, Qt.AlignCenter)
        frame6.setLayout(layoutvp)
        layoutvNp.addWidget(frame6)
        layout.addLayout(layoutvNp, 2, 1)
############################################################
        layouth1 = QHBoxLayout()
        layouth2 = QHBoxLayout()
        layouth1.addWidget(volt_bar)
        layouth1.addWidget(text_volt)
        frame3.setLayout(layouth1)
        layouth2.addWidget(frame3)
        layout.addLayout(layouth2, 1, 2)
############################################################
        layoutG = QVBoxLayout()
        layoutG2 = QVBoxLayout()
        layoutG3 = QVBoxLayout()
        layoutG4 = QVBoxLayout()
        layoutG5 = QVBoxLayout()
        layoutG.addWidget(text_gps_time)
        layoutG.addWidget(text_gps_la)
        layoutG.addWidget(text_gps_lo)
        layoutG.addWidget(text_gps_al)
        layoutG.addWidget(text_gps_sats)
        layoutG3.addWidget(text_teamId)
        layoutG3.addWidget(text_mission_time)
        layoutG3.addWidget(text_Packet_count)
        frame2.setLayout(layoutG)
        frame7.setLayout(layoutG3)
        layoutG2.addWidget(frame2)
        layoutG4.addWidget(frame7)
        layoutG5.addLayout(layoutG2)
        layoutG5.addLayout(layoutG4)
        layout.addLayout(layoutG5, 2,2)
############################################################
        vboxj3 = QVBoxLayout()
        layoutG3 = QVBoxLayout()
        vboxj3.addWidget(text_sys)
        vboxj3.addWidget(text_elevation)
        vboxj3.addWidget(text_azimut)
        vboxj3.addWidget(text_gs_to_cansat)
        vboxj3.addWidget(text_space)
        frame1.setLayout(vboxj3)
        layoutG3.addWidget(frame1)
        layout.addLayout(layoutG3, 1, 3)
###########################################################
        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(30)
############################################################
        layouth3 = QHBoxLayout()
        layouth4 = QHBoxLayout()
        layouth3.addWidget(temp_bar)
        layouth3.addWidget(temp_text)
        frame4.setLayout(layouth3)
        layouth4.addWidget(frame4)
        layout.addLayout(layouth4, 2, 3)
        temp_bar.setStyleSheet('QProgressBar::chunk {background: rgb(255, 0, 0);}')
        temp_bar.setRange(0, 350)
        temp_bar.setFixedSize(50, 200)
############################################################
        self.setLayout(layout)
예제 #34
0
파일: BodeDemo.py 프로젝트: qinghhua/plotpy
class BodePlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.setTitle('Frequency Response of a 2<sup>nd</sup>-order System')
        self.setCanvasBackground(Qt.darkBlue)

        # legend
        legend = QwtLegend()
        legend.setFrameStyle(QFrame.Box | QFrame.Sunken)
        self.insertLegend(legend, QwtPlot.BottomLegend)

        # grid
        self.grid = QwtPlotGrid()
        self.grid.enableXMin(True)
        self.grid.attach(self)

        # axes
        self.enableAxis(QwtPlot.yRight)
        self.setAxisTitle(QwtPlot.xBottom, '\u03c9/\u03c9<sub>0</sub>')
        self.setAxisTitle(QwtPlot.yLeft, 'Amplitude [dB]')
        self.setAxisTitle(QwtPlot.yRight, 'Phase [\u00b0]')

        self.setAxisMaxMajor(QwtPlot.xBottom, 6)
        self.setAxisMaxMinor(QwtPlot.xBottom, 10)
        self.setAxisScaleEngine(QwtPlot.xBottom, QwtLogScaleEngine())

        # curves
        self.curve1 = QwtPlotCurve('Amplitude')
        self.curve1.setRenderHint(QwtPlotItem.RenderAntialiased)
        self.curve1.setPen(QPen(Qt.yellow))
        self.curve1.setYAxis(QwtPlot.yLeft)
        self.curve1.attach(self)

        self.curve2 = QwtPlotCurve('Phase')
        self.curve2.setRenderHint(QwtPlotItem.RenderAntialiased)
        self.curve2.setPen(QPen(Qt.cyan))
        self.curve2.setYAxis(QwtPlot.yRight)
        self.curve2.attach(self)

        # alias
        fn = self.fontInfo().family()

        # marker
        self.dB3Marker = m = QwtPlotMarker()
        m.setValue(0.0, 0.0)
        m.setLineStyle(QwtPlotMarker.VLine)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        m.setLinePen(QPen(Qt.green, 2, Qt.DashDotLine))
        text = QwtText('')
        text.setColor(Qt.green)
        text.setBackgroundBrush(Qt.red)
        text.setFont(QFont(fn, 12, QFont.Bold))
        m.setLabel(text)
        m.attach(self)

        self.peakMarker = m = QwtPlotMarker()
        m.setLineStyle(QwtPlotMarker.HLine)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        m.setLinePen(QPen(Qt.red, 2, Qt.DashDotLine))
        text = QwtText('')
        text.setColor(Qt.red)
        text.setBackgroundBrush(QBrush(self.canvasBackground()))
        text.setFont(QFont(fn, 12, QFont.Bold))

        m.setLabel(text)
        m.setSymbol(
            QwtSymbol(QwtSymbol.Diamond, QBrush(Qt.yellow), QPen(Qt.green),
                      QSize(7, 7)))
        m.attach(self)

        # text marker
        m = QwtPlotMarker()
        m.setValue(0.1, -20.0)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        text = QwtText('[1-(\u03c9/\u03c9<sub>0</sub>)<sup>2</sup>+2j\u03c9/Q]'
                       '<sup>-1</sup>')
        text.setFont(QFont(fn, 12, QFont.Bold))
        text.setColor(Qt.blue)
        text.setBackgroundBrush(QBrush(Qt.yellow))
        text.setBorderPen(QPen(Qt.red, 2))
        m.setLabel(text)
        m.attach(self)

        self.setDamp(0.01)

    def showData(self, frequency, amplitude, phase):
        self.curve1.setData(frequency, amplitude)
        self.curve2.setData(frequency, phase)

    def showPeak(self, frequency, amplitude):
        self.peakMarker.setValue(frequency, amplitude)
        label = self.peakMarker.label()
        label.setText('Peak: %4g dB' % amplitude)
        self.peakMarker.setLabel(label)

    def show3dB(self, frequency):
        self.dB3Marker.setValue(frequency, 0.0)
        label = self.dB3Marker.label()
        label.setText('-3dB at f = %4g' % frequency)
        self.dB3Marker.setLabel(label)

    def setDamp(self, d):
        self.damping = d
        # Numerical Python: f, g, a and p are NumPy arrays!
        f = np.exp(np.log(10.0) * np.arange(-2, 2.02, 0.04))
        g = 1.0 / (1.0 - f * f + 2j * self.damping * f)
        a = 20.0 * np.log10(abs(g))
        p = 180 * np.arctan2(g.imag, g.real) / np.pi
        # for show3dB
        i3 = np.argmax(np.where(np.less(a, -3.0), a, -100.0))
        f3 = f[i3] - (a[i3] + 3.0) * (f[i3] - f[i3 - 1]) / (a[i3] - a[i3 - 1])
        # for showPeak
        imax = np.argmax(a)

        self.showPeak(f[imax], a[imax])
        self.show3dB(f3)
        self.showData(f, a, p)

        self.replot()
예제 #35
0
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        # set plot title
        self.setTitle('ImagePlot')
        # set plot layout
        self.plotLayout().setCanvasMargin(0)
        self.plotLayout().setAlignCanvasToScales(True)
        # set legend
        legend = QwtLegend()
        legend.setDefaultItemMode(QwtLegendData.Clickable)
        self.insertLegend(legend, QwtPlot.RightLegend)
        # set axis titles
        self.setAxisTitle(QwtPlot.xBottom, 'time (s)')
        self.setAxisTitle(QwtPlot.yLeft, 'frequency (Hz)')

        colorMap = QwtLinearColorMap(Qt.blue, Qt.red)
        interval = QwtInterval(-1, 1)
        self.enableAxis(QwtPlot.yRight)
        self.setAxisScale(QwtPlot.yRight, -1, 1)
        self.axisWidget(QwtPlot.yRight).setColorBarEnabled(True)
        self.axisWidget(QwtPlot.yRight).setColorMap(interval, colorMap)

        # calculate 3 NumPy arrays
        x = np.arange(-2*np.pi, 2*np.pi, 0.01)
        y = np.pi*np.sin(x)
        z = 4*np.pi*np.cos(x)*np.cos(x)*np.sin(x)
        # attach a curve
        curve = QwtPlotCurve('y = pi*sin(x)')
        curve.attach(self)
        curve.setPen(QPen(Qt.green, 2))
        curve.setData(x, y)
        # attach another curve
        curve = QwtPlotCurve('y = 4*pi*sin(x)*cos(x)**2')
        curve.attach(self)
        curve.setPen(QPen(Qt.black, 2))
        curve.setData(x, z)
        # attach a grid
        grid = QwtPlotGrid()
        grid.attach(self)
        grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
        # attach a horizontal marker at y = 0
        marker = QwtPlotMarker()
        marker.attach(self)
        marker.setValue(0.0, 0.0)
        marker.setLineStyle(QwtPlotMarker.HLine)
        marker.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        marker.setLabel(QwtText('y = 0'))
        # attach a vertical marker at x = pi
        marker = QwtPlotMarker()
        marker.attach(self)
        marker.setValue(np.pi, 0.0)
        marker.setLineStyle(QwtPlotMarker.VLine)
        marker.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        marker.setLabel(QwtText('x = pi'))
        # attach a plot image
        plotImage = PlotImage('Image')
        plotImage.attach(self)
        plotImage.setData(square(512, -2*np.pi, 2*np.pi),
                          (-2*np.pi, 2*np.pi), (-2*np.pi, 2*np.pi))

        legend.SIG_CLICKED.connect(self.toggleVisibility)
        
        # replot
        self.replot()
예제 #36
0
class MyWindow(QtGui.QMainWindow):
    """
    This class implements a derivative of
    PyQt4.QtGui.QMainWindow, a complete application
    window, which can feature menus, submenus,
    status bar, etc. In this example, it uses
    few of those features.
    """

    def __init__(self, parent=None):
        """
        Constructor: creates an instance of MyWindow
        """
        #########################################
        # Necessary actions, which must be done #
        # for any project                       #
        #########################################
        # first, calling the ancestor's creator
        QtGui.QMainWindow.__init__(self, parent)
        # get the User Interface from the module UI_p1
        self.ui=Ui_MainWindow()
        # initialize the user interface
        self.ui.setupUi(self)
        #########################################
        # Custom actions, which can be written  #
        # in other ways for other projects.     #
        #########################################
        # aliases for some parts of the user interface
        self.plotWidget    = self.ui.qwtPlot
        self.measureButton = self.ui.measureButton
        self.closeButton   = self.ui.closeButton
        self.saveButton   = self.ui.saveButton
        # connect methods to buttons' click signals
        self.measureButton.clicked.connect(self.measure)
        self.closeButton.clicked.connect(self.close)
        self.saveButton.clicked.connect(self.save)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.plotWidget)
        # initialize the driver for expEYES Junior
        # prevent an error if the box is not detected
        try:
            self.p             = ej.open()
            assert(self.p.fd)
            self.setWindowTitle("expEYES Junior found on port {}".format(
                self.p.fd.port
            ))
        except:
            self.setWindowTitle("ERROR: expEYES Junior NOT FOUND!")
            self.measureButton.setEnabled(False)
        return

    def measure(self):
        """
        This is a custom method to connect to the
        button for measurements.
        There is no need for another custom method,
        since the method "close" is already inherited
        from the ancestor class.
        """
        self.t, self.v = self.p.capture(1,1000,200)
        self.curve.setData(self.t, self.v, len(self.t))
        # display the result
        self.plotWidget.replot()
        # activate the save widget
        self.saveButton.setEnabled(True)
        return
        
    def save(self):
        """
        save data into a file named "data.csv"
        """
        with open("data.csv", "w") as outfile:
           for i in range(len(self.t)):
               outfile.write("{} {}\n".format(self.t[i], self.v[i]))
        delay=2000 # 2000 ms = 2 seconds
        self.ui.statusbar.showMessage("saved data to file data.csv",delay)
        return
예제 #37
0
class DataPlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        # Initialize Decice address,
        #self.uut_dev = GPIBdevice.GPIBdevice(args[0])
        self.rm = visa.ResourceManager()
        print(self.rm.list_resources())
        self.uut_dev = self.rm.open_resource(args[0])

        print('open pass')
        # Initialize 坐标轴
        self.setCanvasBackground(Qt.white)
        self.alignScales()
        grid = QwtPlotGrid()
        grid.attach(self)
        grid.setMajorPen(QPen(Qt.black, 0, Qt.DotLine))

        self.setAxisScale(QwtPlot.xBottom, 0.0, 300.1, 10.0)
        self.setAxisAutoScale(QwtPlot.yLeft, True)
        #self.setAxisScale(QwtPlot.yLeft,4.0,20.0,2.0)

        self.x = np.arange(
            0.0, 300.1, 0.5
        )  #0.25 for ONE POINT, THIS SHOULD BE Align to the reading rate:250ms

        self.z = np.zeros(len(self.x), np.float)

        self.setTitle("UUT Reading Monitor")
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)

        self.curveL = QwtPlotCurve("UUT Reading")
        self.curveL.attach(self)

        self.curveL.setPen(QPen(Qt.red))

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "UUT - Reading")
        self.replot()

        self.startTimer(500)  #ms# FOR GET READING

        self.starttime = time.clock()
        #unit: s
        self.idx = 0
        self.readfmt = "%.8f"
        self.Saveinfo("Starting...")

        IDN = self.uut_get_val(self.uut_dev, "*IDN?\r")
        print IDN

        print "Starting..."

    def alignScales(self):
        self.canvas().setFrameStyle(QFrame.Box | QFrame.Plain)
        self.canvas().setLineWidth(1)
        for i in range(QwtPlot.axisCnt):
            scaleWidget = self.axisWidget(i)
            if scaleWidget:
                scaleWidget.setMargin(0)
            scaleDraw = self.axisScaleDraw(i)
            if scaleDraw:
                scaleDraw.enableComponent(QwtAbstractScaleDraw.Backbone, False)

    def timerEvent(self, e):
        # send cmd and get readings, record times, X is second;
        tfdata = self.uut_get_val(self.uut_dev, "x?\r")
        print tfdata

        self.z = np.concatenate((self.z[1:], self.z[:1]), 1)
        self.z[-1] = tfdata

        self.curveL.setData(self.x, self.z)
        self.replot()

        self.idx = self.idx + 1
        #Write file to txt log
        self.SaveData(tfdata)

        now = time.clock()
        if ((now - self.starttime) > 250):  # 250 point (seconds)
            self.starttime = time.clock()
            # reset start time

            pngTIME = datetime.datetime.now()
            FILE_timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
                pngTIME.year, pngTIME.month, pngTIME.day, pngTIME.hour,
                pngTIME.minute, pngTIME.second)
            PNGFile = ('%s_%s' % (FILE_timestamp, '.png'))
            self.exportTo(PNGFile, size=(1920, 1080), resolution=200)
            print PNGFile, "The snaped curve picture has been created."

    def uut_get_val(self, uut_dev_in, type="x?\r"):  #[0-9]\d*\.\d+$
        '''
        if type  == "*IDN?\r":
            uut_dev_in.write(type)
            line = ''
            m = None
            while True:
                line = line + uut_dev_in.read()
                if line.endswith('\r'):
                    return line
                    break
        else:
            m = uut_dev_in.trx(type,  r'-?\d+\.\d+[Ee][-+][0-9]{2}')
            print m.group(0);
            return float(m.group(0))
        '''
        reading = ''

        reading = uut_dev_in.query(type)  #u'+000.3272E-06\n'

        if type == "*IDN?\r":
            return reading

        return float(reading)

    def SaveData(self, tfdata):
        fh = open("data_8508.txt", "a")
        now = datetime.datetime.now()
        timestamp = "%02d:%02d:%02d.%03d" % (now.hour, now.minute, now.second,
                                             now.microsecond / 1000)
        fmtstr = "%s, %%s, %s\n" % (self.idx, self.readfmt)
        fh.write(fmtstr % (timestamp, tfdata))
        fh.flush()

    def Saveinfo(self, info):
        fh = open("data_8508.txt", "a")
        now = datetime.datetime.now()
        timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
            now.year, now.month, now.day, now.hour, now.minute, now.second)
        title = "%s,   %s\n" % (timestamp, info)
        fh.write(title)
        fh.flush()
예제 #38
0
pen.setJoinStyle(Qt.MiterJoin)

symbol = QwtSymbol()
symbol.setPen(pen)
symbol.setBrush(Qt.red)
symbol.setPath(path)
symbol.setPinPoint(QPointF(0.0, 0.0))
symbol.setSize(10, 14)

# --- Test it within a simple plot ---

curve = QwtPlotCurve()
curve_pen = QPen(Qt.blue)
curve_pen.setStyle(Qt.DotLine)
curve.setPen(curve_pen)
curve.setSymbol(symbol)
x = np.linspace(0, 10, 10)
curve.setData(x, np.sin(x))

plot = QwtPlot()
curve.attach(plot)
plot.resize(600, 300)
plot.replot()
plot.show()

plot.grab().save(
    osp.join(osp.abspath(osp.dirname(__file__)), "images",
             "symbol_path_example.png"))

app.exec_()
예제 #39
0
class MapDemo(QMainWindow):
    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.plot = QwtPlot(self)
        self.plot.setTitle("A Simple Map Demonstration")
        self.plot.setCanvasBackground(Qt.white)
        self.plot.setAxisTitle(QwtPlot.xBottom, "x")
        self.plot.setAxisTitle(QwtPlot.yLeft, "y")    
        self.plot.setAxisScale(QwtPlot.xBottom, 0.0, 1.0)
        self.plot.setAxisScale(QwtPlot.yLeft, 0.0, 1.0)
        self.setCentralWidget(self.plot)
        # Initialize map data
        self.count = self.i = 1000
        self.xs = np.zeros(self.count, np.float)
        self.ys = np.zeros(self.count, np.float)
        self.kappa = 0.2
        self.curve = QwtPlotCurve("Map")
        self.curve.attach(self.plot)
        self.curve.setSymbol(QwtSymbol(QwtSymbol.Ellipse,
                                           QBrush(Qt.red),
                                           QPen(Qt.blue),
                                           QSize(5, 5)))
        self.curve.setPen(QPen(Qt.cyan))
        toolBar = QToolBar(self)
        self.addToolBar(toolBar)
        # 1 tick = 1 ms, 10 ticks = 10 ms (Linux clock is 100 Hz)
        self.ticks = 10
        self.tid = self.startTimer(self.ticks)
        self.timer_tic = None
        self.user_tic = None
        self.system_tic = None    
        self.plot.replot()

    def setTicks(self, ticks):
        self.i = self.count
        self.ticks = int(ticks)
        self.killTimer(self.tid)
        self.tid = self.startTimer(ticks)
        
    def resizeEvent(self, event):
        self.plot.resize(event.size())
        self.plot.move(0, 0)

    def moreData(self):
        if self.i == self.count:
            self.i = 0
            self.x = random.random()
            self.y = random.random()
            self.xs[self.i] = self.x
            self.ys[self.i] = self.y
            self.i += 1
            chunks = []
            self.timer_toc = time.time()
            if self.timer_tic:
                chunks.append("wall: %s s." % (self.timer_toc-self.timer_tic))
                print(' '.join(chunks))
            self.timer_tic = self.timer_toc
        else:
            self.x, self.y = standard_map(self.x, self.y, self.kappa)
            self.xs[self.i] = self.x
            self.ys[self.i] = self.y
            self.i += 1
        
    def timerEvent(self, e):
        self.moreData()
        self.curve.setData(self.xs[:self.i], self.ys[:self.i])
        self.plot.replot()
예제 #40
0
파일: 25MAR.py 프로젝트: jessastrid9/QT
    def __init__(self, parent=None):
        super(Mision, self).__init__(parent)
        layout = QGridLayout(self)
        layout.lb1 = QLabel(self)
        x=0
        layout.lb1.setPixmap(QPixmap("CANSAT_BKG.png"))
        layout.lb1.setGeometry(0, 0, 1500, 1000)

        ############################TITLE#############################
        font = QFont("UKNumberPlate", 20, 10, 0)  #### FUENTE, TAMAÑO, GROSOR, ITALICA 0-F
        titulo1=QLabel()
        titulo1.setFont(font)
        titulo1.setStyleSheet('color: white')
        titulo1.setText('TEAM THOR')
        layout.addWidget(titulo1,0,1)
        #############################################################
        x = [1, 2]
        y = [1, 2]
        layout.addWidget(grap1, 1, 0)
 ##############################################################
        graph2 = QwtPlot()
        curva2 = QwtPlotCurve()
        curva3 = QwtPlotCurve()
        xcurva2 = [-800, 800]
        ycurva2 = [0, 0]
        xcurva3 = [0, 0]
        ycurva3 = [-800, 800]
        curva2.setData(xcurva2, ycurva2)
        curva2.setPen(QPen(Qt.black))
        curva2.attach(graph2)
        curva3.setData(xcurva3, ycurva3)
        curva3.setPen(QPen(Qt.black))
        curva3.attach(graph2)
        pal = QPalette();
        pal.setColor(QPalette.Text, Qt.white)
        pal.setColor(QPalette.Foreground, Qt.white)
        layout.addWidget(graph2, 2, 0)
        grid = QwtPlotGrid()
        grid.attach(graph2)
        grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
        graph2.replot()
        graph2.setAxisScale(QwtPlot.xBottom, -800, 800)
        graph2.setAxisScale(QwtPlot.yLeft, -800, 800)
        graph2.setPalette(pal)
#############################################################)
        layoutv = QVBoxLayout()
        layoutvN = QVBoxLayout()
        lb1 = QLabel(self)
        pixmap=QPixmap("DIAL4.png")
        pixmap2 = QPixmap("pointer.png")
        pixmap = pixmap.scaledToWidth(220)
        pixmap2 = pixmap2.scaledToWidth(20)
        lb1.setPixmap(pixmap)
        layoutv.addWidget(text_pressure)
        layoutv.addWidget(lb1)
        frame5.setLayout(layoutv)
        layoutvN.addWidget(frame5)
        layout.addLayout(layoutvN, 1, 1)
        ###
        self.lbN = QLabel(self)
        #x=50400
        press=0
        ang=(0.002685)*press-140
        if ang>=0:
            correctionx =  0
            correctiony=round(ang*0.2)
        else:
            correctiony = - round(ang * 0.2)
            if ang<=-105:
                correctionx = -round((((-ang-100)*0.07)**(2))-40)
            else:
                if ang>=-9.4:
                    correctionx = round(12 * (((-ang-1)/100) ** (1 / 4)))
                else:
                    correctionx = round(12 * (((-ang -9.5)) ** (1 / 4)))
        t = QTransform()
        t.rotate(ang)
        rotated_pixmap = pixmap2.transformed(t, Qt.SmoothTransformation)
        #lbN = QLabel(self)
        self.lbN.setPixmap(rotated_pixmap)
        self.lbN.setGeometry(619 - correctionx, 180 + correctiony, 70, 70)
        layout.lbN= self.lbN
        #layout.lbN.setPixmap(rotated_pixmap)
        #layout.lbN.setGeometry(619-correctionx, 180 + correctiony, 70, 70)
        #ang2.correctiony
#############################################################

############################################################
        layouth1 = QHBoxLayout()
        layouth2 = QHBoxLayout()
        layouth1.addWidget(volt_bar)
        layouth1.addWidget(text_volt)
        frame3.setLayout(layouth1)
        layouth2.addWidget(frame3)
        layout.addLayout(layouth2, 1, 2)
############################################################
        layoutG = QVBoxLayout()
        layoutG2 = QVBoxLayout()
        layoutG3 = QVBoxLayout()
        layoutG4 = QVBoxLayout()
        layoutG5 = QVBoxLayout()
        layoutG.addWidget(text_gps_time)
        layoutG.addWidget(text_gps_la)
        layoutG.addWidget(text_gps_lo)
        layoutG.addWidget(text_gps_al)
        layoutG.addWidget(text_gps_sats)
        layoutG3.addWidget(text_teamId)
        layoutG3.addWidget(text_mission_time)
        layoutG3.addWidget(text_Packet_count)
        frame2.setLayout(layoutG)
        frame7.setLayout(layoutG3)
        layoutG2.addWidget(frame2)
        layoutG4.addWidget(frame7)
        layoutG5.addLayout(layoutG2)
        layoutG5.addLayout(layoutG4)
        layout.addLayout(layoutG5, 2,2)
############################################################
        vboxj3 = QVBoxLayout()
        layoutG3 = QVBoxLayout()
        vboxj3.addWidget(text_sys)
        vboxj3.addWidget(text_elevation)
        vboxj3.addWidget(text_azimut)
        vboxj3.addWidget(text_gs_to_cansat)
        vboxj3.addWidget(text_space)
        frame1.setLayout(vboxj3)
        layoutG3.addWidget(frame1)
        layout.addLayout(layoutG3, 1, 3)
###########################################################
        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(40)
############################################################
        layouth3 = QVBoxLayout()
        layouth4 = QVBoxLayout()
        layouth3.addWidget(temp_text)
        layouth3.addWidget(temp_bar)
        frame4.setLayout(layouth3)
        layouth4.addWidget(frame4)
        layout.addLayout(layouth4, 2, 3)
        temp_bar.setStyleSheet('QProgressBar::chunk {background: rgb(255, 0, 0);}')
############################################################
        self.setLayout(layout)
예제 #41
0
class DataPlot(QwtPlot):

    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.setCanvasBackground(Qt.white)
        self.alignScales()

        # Initialize data
        self.x = np.arange(0.0, 100.1, 0.5)
        self.y = np.zeros(len(self.x), np.float)
        self.z = np.zeros(len(self.x), np.float)

        self.setTitle("A Moving QwtPlot Demonstration")
        self.insertLegend(QwtLegend(), QwtPlot.BottomLegend);

        self.curveR = QwtPlotCurve("Data Moving Right")
        self.curveR.attach(self)
        self.curveL = QwtPlotCurve("Data Moving Left")
        self.curveL.attach(self)

        self.curveL.setSymbol(QwtSymbol(QwtSymbol.Ellipse,
                                        QBrush(),
                                        QPen(Qt.yellow),
                                        QSize(7, 7)))

        self.curveR.setPen(QPen(Qt.red))
        self.curveL.setPen(QPen(Qt.blue))

        mY = QwtPlotMarker()
        mY.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mY.setLineStyle(QwtPlotMarker.HLine)
        mY.setYValue(0.0)
        mY.attach(self)

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "Values")
    
        self.startTimer(50)
        self.phase = 0.0

    def alignScales(self):
        self.canvas().setFrameStyle(QFrame.Box | QFrame.Plain)
        self.canvas().setLineWidth(1)
        for i in range(QwtPlot.axisCnt):
            scaleWidget = self.axisWidget(i)
            if scaleWidget:
                scaleWidget.setMargin(0)
            scaleDraw = self.axisScaleDraw(i)
            if scaleDraw:
                scaleDraw.enableComponent(QwtAbstractScaleDraw.Backbone, False)
    
    def timerEvent(self, e):
        if self.phase > np.pi - 0.0001:
            self.phase = 0.0

        # y moves from left to right:
        # shift y array right and assign new value y[0]
        self.y = np.concatenate((self.y[:1], self.y[:-1]), 1)
        self.y[0] = np.sin(self.phase) * (-1.0 + 2.0*random.random())
		
        # z moves from right to left:
        # Shift z array left and assign new value to z[n-1].
        self.z = np.concatenate((self.z[1:], self.z[:1]), 1)
        self.z[-1] = 0.8 - (2.0 * self.phase/np.pi) + 0.4*random.random()

        self.curveR.setData(self.x, self.y)
        self.curveL.setData(self.x, self.z)

        self.replot()
        self.phase += np.pi*0.02
예제 #42
0
    def __init__(self, *args):
        QFrame.__init__(self, *args)

        self.xMap = QwtScaleMap()
        self.xMap.setScaleInterval(-0.5, 10.5)
        self.yMap = QwtScaleMap()
        self.yMap.setScaleInterval(-1.1, 1.1)

        # frame style
        self.setFrameStyle(QFrame.Box | QFrame.Raised)
        self.setLineWidth(2)
        self.setMidLineWidth(3)

        # calculate values
        self.x = np.arange(0, 10.0, 10.0/27)
        self.y = np.sin(self.x)*np.cos(2*self.x)
        
        # make curves with different styles
        self.curves = []
        self.titles = []
        # curve 1
        self.titles.append('Style: Sticks, Symbol: Ellipse')
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.red))
        curve.setStyle(QwtPlotCurve.Sticks)
        curve.setSymbol(QwtSymbol(QwtSymbol.Ellipse,
                                      QBrush(Qt.yellow),
                                      QPen(Qt.blue),
                                      QSize(5, 5)))
        self.curves.append(curve)
        # curve 2
        self.titles.append('Style: Lines, Symbol: None')
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkBlue))
        curve.setStyle(QwtPlotCurve.Lines)
        self.curves.append(curve)
        # curve 3
        self.titles.append('Style: Lines, Symbol: None, Antialiased')
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkBlue))
        curve.setStyle(QwtPlotCurve.Lines)
        curve.setRenderHint(QwtPlotItem.RenderAntialiased)
        self.curves.append(curve)
        # curve 4
        self.titles.append('Style: Steps, Symbol: None')
        curve = QwtPlotCurve()
        curve.setPen(QPen(Qt.darkCyan))
        curve.setStyle(QwtPlotCurve.Steps)
        self.curves.append(curve)        
        # curve 5
        self.titles.append('Style: NoCurve, Symbol: XCross')
        curve = QwtPlotCurve()
        curve.setStyle(QwtPlotCurve.NoCurve)
        curve.setSymbol(QwtSymbol(QwtSymbol.XCross,
                                      QBrush(),
                                      QPen(Qt.darkMagenta),
                                      QSize(5, 5)))
        self.curves.append(curve)

        # attach data, using Numeric
        for curve in self.curves:
            curve.setData(self.x, self.y)
예제 #43
0
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        # connect methods to buttons' click signals
        self.ui.wakeUpButton.clicked.connect(self.wakeUp)
        self.ui.stopButton.clicked.connect(self.stop)
        self.ui.closeButton.clicked.connect(self.close)
        self.ui.saveButton.clicked.connect(self.save)
        self.ui.immediateButton.clicked.connect(self.immediate)
        self.ui.finalButton.clicked.connect(self.final)
        self.ui.fitButton.clicked.connect(self.fit)
        self.ui.action_Save_Ctrl_S.triggered.connect(self.save)
        self.ui.action_Quit_Ctrl_Q.triggered.connect(self.close)
        self.ui.actionManual.triggered.connect(self.manual)
        self.ui.actionAbout.triggered.connect(self.about)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.ui.qwtPlot)
        # expEYESdetection and initialization
        try:
            self.p             = ej.open()
            assert(self.p.fd)
            self.setWindowTitle("expEYES Junior found on port {}".format(
                self.p.fd.port
            ))
        except:
            self.setWindowTitle("ERROR: expEYES Junior NOT FOUND!")
            self.wakeUpButton.setEnabled(False)
        # custom properties
        self.isImmediate=True
        return
        
    def immediate(self):
        self.isImmediate=True
        return
        
    def final(self):
        self.isImmediate=False
        return

    def wakeUp(self):
        # get the duration of the experiment in µs
        duration = 1e6 * float(self.ui.durationEdit.text())
        samples  = 1800 # maximum sample number with 8 bit precision
        # ensure that samples * delay will be slightly bigger than duration
        delay=1+int(duration/1800)
        t,v = self.p.capture(1,samples, delay)
        self.curve.setData(t,v,len(t))
        # display the result
        self.ui.qwtPlot.replot()
        return

        
    def notImplemented(self):
        msg=QtGui.QMessageBox(QtGui.QMessageBox.Warning,"Sorry",
                              "not yet implemented", )
        msg.exec_()
        return

    stop=save=fit=manual=about=notImplemented
예제 #44
0
파일: temp.py 프로젝트: valeriy67/Cquality
# -*- coding: utf-8 -*-
__author__ = 'Valeriy'

from qwt.qt.QtGui import QApplication
from qwt import QwtPlot, QwtPlotCurve
import numpy as np

app = QApplication([])

# x = [1,2,3,4,5,6,7,8,9]
# y1 = [3.2, 5.1 ,7.0, 4.24, 4.41, 8.34, 2.21, 5.657, 6.1]


x = []
y1 = []


my_plot = QwtPlot("Two curves")
curve1 = QwtPlotCurve("Curve 1")
my_plot.resize(600, 300)

curve1.setData(x, y1)
curve1.attach(my_plot)
# my_plot.replot()
my_plot.show()

app.exec_()

# SELECT PrepData FROM= Pdata WHERE ((PNameId=2) AND (SNameId = 14) AND (YearId=2012))
예제 #45
0
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        # set plot title
        self.setTitle('ImagePlot')
        # set plot layout
        self.plotLayout().setCanvasMargin(0)
        self.plotLayout().setAlignCanvasToScales(True)
        # set legend
        legend = QwtLegend()
        legend.setDefaultItemMode(QwtLegendData.Clickable)
        self.insertLegend(legend, QwtPlot.RightLegend)
        # set axis titles
        self.setAxisTitle(QwtPlot.xBottom, 'time (s)')
        self.setAxisTitle(QwtPlot.yLeft, 'frequency (Hz)')

        colorMap = QwtLinearColorMap(Qt.blue, Qt.red)
        interval = QwtInterval(-1, 1)
        self.enableAxis(QwtPlot.yRight)
        self.setAxisScale(QwtPlot.yRight, -1, 1)
        self.axisWidget(QwtPlot.yRight).setColorBarEnabled(True)
        self.axisWidget(QwtPlot.yRight).setColorMap(interval, colorMap)

        # calculate 3 NumPy arrays
        x = np.arange(-2 * np.pi, 2 * np.pi, 0.01)
        y = np.pi * np.sin(x)
        z = 4 * np.pi * np.cos(x) * np.cos(x) * np.sin(x)
        # attach a curve
        curve = QwtPlotCurve('y = pi*sin(x)')
        curve.attach(self)
        curve.setPen(QPen(Qt.green, 2))
        curve.setData(x, y)
        # attach another curve
        curve = QwtPlotCurve('y = 4*pi*sin(x)*cos(x)**2')
        curve.attach(self)
        curve.setPen(QPen(Qt.black, 2))
        curve.setData(x, z)
        # attach a grid
        grid = QwtPlotGrid()
        grid.attach(self)
        grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
        # attach a horizontal marker at y = 0
        marker = QwtPlotMarker()
        marker.attach(self)
        marker.setValue(0.0, 0.0)
        marker.setLineStyle(QwtPlotMarker.HLine)
        marker.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        marker.setLabel(QwtText('y = 0'))
        # attach a vertical marker at x = pi
        marker = QwtPlotMarker()
        marker.attach(self)
        marker.setValue(np.pi, 0.0)
        marker.setLineStyle(QwtPlotMarker.VLine)
        marker.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        marker.setLabel(QwtText('x = pi'))
        # attach a plot image
        plotImage = PlotImage('Image')
        plotImage.attach(self)
        plotImage.setData(square(512, -2 * np.pi, 2 * np.pi),
                          (-2 * np.pi, 2 * np.pi), (-2 * np.pi, 2 * np.pi))

        legend.SIG_CLICKED.connect(self.toggleVisibility)

        # replot
        self.replot()
예제 #46
0
class BodePlot(QwtPlot):

    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.setTitle('Frequency Response of a 2<sup>nd</sup>-order System')
        self.setCanvasBackground(Qt.darkBlue)

        # legend
        legend = QwtLegend()
        legend.setFrameStyle(QFrame.Box | QFrame.Sunken)
        self.insertLegend(legend, QwtPlot.BottomLegend)

        # grid
        self.grid = QwtPlotGrid()
        self.grid.enableXMin(True)
        self.grid.attach(self)

        # axes
        self.enableAxis(QwtPlot.yRight)
        self.setAxisTitle(QwtPlot.xBottom, '\u03c9/\u03c9<sub>0</sub>')
        self.setAxisTitle(QwtPlot.yLeft, 'Amplitude [dB]')
        self.setAxisTitle(QwtPlot.yRight, 'Phase [\u00b0]')

        self.setAxisMaxMajor(QwtPlot.xBottom, 6)
        self.setAxisMaxMinor(QwtPlot.xBottom, 10)
        self.setAxisScaleEngine(QwtPlot.xBottom, QwtLogScaleEngine())

        # curves
        self.curve1 = QwtPlotCurve('Amplitude')
        self.curve1.setRenderHint(QwtPlotItem.RenderAntialiased);
        self.curve1.setPen(QPen(Qt.yellow))
        self.curve1.setYAxis(QwtPlot.yLeft)
        self.curve1.attach(self)
        
        self.curve2 = QwtPlotCurve('Phase')
        self.curve2.setRenderHint(QwtPlotItem.RenderAntialiased);
        self.curve2.setPen(QPen(Qt.cyan))
        self.curve2.setYAxis(QwtPlot.yRight)
        self.curve2.attach(self)

        # alias
        fn = self.fontInfo().family()

        # marker
        self.dB3Marker = m = QwtPlotMarker()
        m.setValue(0.0, 0.0)
        m.setLineStyle(QwtPlotMarker.VLine)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        m.setLinePen(QPen(Qt.green, 2, Qt.DashDotLine))
        text = QwtText('')
        text.setColor(Qt.green)
        text.setBackgroundBrush(Qt.red)
        text.setFont(QFont(fn, 12, QFont.Bold))
        m.setLabel(text)
        m.attach(self)

        self.peakMarker = m = QwtPlotMarker()
        m.setLineStyle(QwtPlotMarker.HLine)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        m.setLinePen(QPen(Qt.red, 2, Qt.DashDotLine))
        text = QwtText('')
        text.setColor(Qt.red)
        text.setBackgroundBrush(QBrush(self.canvasBackground()))
        text.setFont(QFont(fn, 12, QFont.Bold))
        
        m.setLabel(text)
        m.setSymbol(QwtSymbol(QwtSymbol.Diamond,
                              QBrush(Qt.yellow),
                              QPen(Qt.green),
                              QSize(7,7)))
        m.attach(self)

        # text marker
        m = QwtPlotMarker()
        m.setValue(0.1, -20.0)
        m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom)
        text = QwtText(
            '[1-(\u03c9/\u03c9<sub>0</sub>)<sup>2</sup>+2j\u03c9/Q]'
            '<sup>-1</sup>'
            )
        text.setFont(QFont(fn, 12, QFont.Bold))
        text.setColor(Qt.blue)
        text.setBackgroundBrush(QBrush(Qt.yellow))
        text.setBorderPen(QPen(Qt.red, 2))
        m.setLabel(text)
        m.attach(self)

        self.setDamp(0.01)

    def showData(self, frequency, amplitude, phase):
        self.curve1.setData(frequency, amplitude)
        self.curve2.setData(frequency, phase)

    def showPeak(self, frequency, amplitude):
        self.peakMarker.setValue(frequency, amplitude)
        label = self.peakMarker.label()
        label.setText('Peak: %4g dB' % amplitude)
        self.peakMarker.setLabel(label)

    def show3dB(self, frequency):
        self.dB3Marker.setValue(frequency, 0.0)
        label = self.dB3Marker.label()
        label.setText('-3dB at f = %4g' % frequency)
        self.dB3Marker.setLabel(label)

    def setDamp(self, d):
        self.damping = d
        # Numerical Python: f, g, a and p are NumPy arrays!
        f = np.exp(np.log(10.0)*np.arange(-2, 2.02, 0.04))
        g = 1.0/(1.0-f*f+2j*self.damping*f)
        a = 20.0*np.log10(abs(g))
        p = 180*np.arctan2(g.imag, g.real)/np.pi
        # for show3dB
        i3 = np.argmax(np.where(np.less(a, -3.0), a, -100.0))
        f3 = f[i3] - (a[i3]+3.0)*(f[i3]-f[i3-1])/(a[i3]-a[i3-1])
        # for showPeak
        imax = np.argmax(a)

        self.showPeak(f[imax], a[imax])
        self.show3dB(f3)
        self.showData(f, a, p)

        self.replot()
예제 #47
0
class DataPlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)

        self.setCanvasBackground(Qt.white)
        self.alignScales()

        # Initialize data
        self.x = np.arange(0.0, 100.1, 0.5)
        self.y = np.zeros(len(self.x), np.float)
        self.z = np.zeros(len(self.x), np.float)

        self.setTitle("A Moving QwtPlot Demonstration")
        self.insertLegend(QwtLegend(), QwtPlot.BottomLegend)

        self.curveR = QwtPlotCurve("Data Moving Right")
        self.curveR.attach(self)
        self.curveL = QwtPlotCurve("Data Moving Left")
        self.curveL.attach(self)

        self.curveL.setSymbol(
            QwtSymbol(QwtSymbol.Ellipse, QBrush(), QPen(Qt.yellow),
                      QSize(7, 7)))

        self.curveR.setPen(QPen(Qt.red))
        self.curveL.setPen(QPen(Qt.blue))

        mY = QwtPlotMarker()
        mY.setLabelAlignment(Qt.AlignRight | Qt.AlignTop)
        mY.setLineStyle(QwtPlotMarker.HLine)
        mY.setYValue(0.0)
        mY.attach(self)

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "Values")

        self.startTimer(50)
        self.phase = 0.0

    def alignScales(self):
        self.canvas().setFrameStyle(QFrame.Box | QFrame.Plain)
        self.canvas().setLineWidth(1)
        for i in range(QwtPlot.axisCnt):
            scaleWidget = self.axisWidget(i)
            if scaleWidget:
                scaleWidget.setMargin(0)
            scaleDraw = self.axisScaleDraw(i)
            if scaleDraw:
                scaleDraw.enableComponent(QwtAbstractScaleDraw.Backbone, False)

    def timerEvent(self, e):
        if self.phase > np.pi - 0.0001:
            self.phase = 0.0

        # y moves from left to right:
        # shift y array right and assign new value y[0]
        self.y = np.concatenate((self.y[:1], self.y[:-1]), 1)
        self.y[0] = np.sin(self.phase) * (-1.0 + 2.0 * random.random())

        # z moves from right to left:
        # Shift z array left and assign new value to z[n-1].
        self.z = np.concatenate((self.z[1:], self.z[:1]), 1)
        self.z[-1] = 0.8 - (2.0 * self.phase / np.pi) + 0.4 * random.random()

        self.curveR.setData(self.x, self.y)
        self.curveL.setData(self.x, self.z)

        self.replot()
        self.phase += np.pi * 0.02
예제 #48
0
class ZoomPopup(QWidget):

    winclosed = pyqtSignal(int)
    winpaused = pyqtSignal(int)
    save_zoom_display = pyqtSignal(str, int)
    image_auto_scale = pyqtSignal(int)
    image_scale_values = pyqtSignal(float, float)

    def __init__(self,
                 CurveNumber,
                 x_values,
                 y_values,
                 flags,
                 pen,
                 parent=None,
                 name=None):
        """ Initialises all the variables.  
        creates the main zoom plot
        connects the qt signals
    """

        QWidget.__init__(self, parent)
        self.setWindowTitle('Channel ' + str(CurveNumber))
        self._parent = parent
        self._d_zoomActive = self._d_zoom = False
        self._curve_number = CurveNumber
        self.curves = {}

        self._do_close = True  # enable closing by window manager
        self._do_pause = False  # pause mode is False at startup
        self._compare_max = False
        self._do_linear_scale = True  # linear Y axis scale by default
        self._do_fixed_scale = False  # auto scaling by default
        self._array_label = "Channel "

        #Create the plot for selected curve to zoom
        self._plotter = QwtImageDisplay(self)
        self._plotter.setZoomDisplay()

        self._zoom_plot_label = self._array_label + str(
            self._curve_number) + " Sequence (oldest to most recent)"

        self._max_crv = -1  # negative value used to indicate that this display
        self._min_crv = -1  # is not being used

        #####end of parameters set for the plot#######/

        # we seem to need a layout for PyQt
        box1 = QHBoxLayout(self)
        box1.addWidget(self._plotter)
        #   self.plotPrinter = plot_printer_qt5.plot_printer(self._plotter)

        self._plotter.winpaused.connect(self.Pausing)
        self._plotter.compare.connect(self.do_compare)
        #   self._plotter.do_print.connnect(self.plotPrinter.do_print)
        self._plotter.save_display.connect(self.handle_save_display)

        # insert flags ?
        self._plotter.initVellsContextMenu()
        self.update_plot(y_values, flags)
        self.show()

    def handle_save_display(self, title):
        self.save_zoom_display.emit(self._zoom_plot_label, self._curve_number)

    def do_compare_max(self, x_values):
        ### instantiate the envelop that will show min/max deviations
        self._max_envelop = self._y_values
        self._min_envelop = self._y_values
        self._max_crv = QwtPlotCurve('Zoomed max curve')
        self._max_crv.attach(self._plotter)
        self._min_crv = QwtPlotCurve('Zoomed min curve')
        self._min_crv.attach(self._plotter)
        self._max_crv.setData(x_values, self._max_envelop)
        self._min_crv.setData(x_values, self._min_envelop)
        self._compare_max = True

    def do_compare(self):
        print('in zoomwin do_compare')
        if self._compare_max:
            self.stop_compare_max()
            self._compare_max = False
        else:
            self._max_envelop = self._y_values
            self._min_envelop = self._y_values
            self._max_crv = QwtPlotCurve('Zoomed max curve')
            self._max_crv.attach(self._plotter)
            self._min_crv = QwtPlotCurve('Zoomed min curve')
            self._min_crv.attach(self._plotter)
            self._max_crv.setData(x_values, self._max_envelop)
            self._min_crv.setData(x_values, self._min_envelop)
            self._compare_max = True
        self.reset_max()

    def stop_compare_max(self):
        if self._compare_max:
            self._max_envelop = 0.0
            self._min_envelop = 0.0
            self._max_crv.detach()
            self._min_crv.detach()
            self._compare_max = False
            self._max_crv = -1
            self._min_crv = -1

    def get_max(self):
        if self._compare_max:
            self._max_envelop = self.max(self._max_envelop, self._y_values)
            self._min_envelop = self.min(self._min_envelop, self._y_values)

    def max(self, array1, array2):
        shape = array1.shape
        max_envelop = array1
        for i in range(shape[0]):
            if array2[i] > array1[i]:
                max_envelop[i] = array2[i]
        return max_envelop

    def min(self, array1, array2):
        shape = array1.shape
        min_envelop = array1
        for i in range(shape[0]):
            if array2[i] < array1[i]:
                min_envelop[i] = array2[i]
        return min_envelop

    def reset_max(self):
        if self._compare_max:
            self._max_envelop = self._y_values
            self._min_envelop = self._y_values

    def test_max(self):
        if self._compare_max:
            return True
        else:
            return False

    def pause_mode(self):
        if self._do_pause:
            return True
        else:
            return False

    def exec_close(self):
        self.close()

    def Pausing(self):
        self.winpaused.emit(self._curve_number)

    def change_scale_type(self):
        # click means change to fixed scale
        toggle_id = self.menu_table['Fixed Scale ']
        if self._do_fixed_scale:
            self._do_fixed_scale = False
            self._menu.changeItem(toggle_id, 'Fixed Scale')
            self._plotter.setAxisAutoScale(QwtPlot.yLeft)
            self.image_auto_scale.emit(0)
        else:
            self._do_fixed_scale = True
            self._menu.changeItem(toggle_id, 'Auto Scale')
            # find current data min and max
            scale_max = self._y_values.max()
            scale_min = self._y_values.min()

    def set_scale_values(self, max_value, min_value):
        if self._do_fixed_scale:
            self.image_scale_values.emit(max_value, min_value)
            self._plotter.setAxisScale(QwtPlot.yLeft, min_value, max_value)
            self._plotter.replot()

    def cancel_scale_request(self):
        if self._do_fixed_scale:
            toggle_id = self.menu_table['Fixed Scale ']
            self._menu.changeItem(toggle_id, 'Fixed Scale')
            self._plotter.setAxisAutoScale(QwtPlot.yLeft)
            self._do_fixed_scale = False

    def update_plot(self, y_values, flags):
        if not self._do_pause:
            self._plotter.unsetFlagsData()
            self._y_values = y_values
            abs_flags = numpy.absolute(flags)
            if abs_flags.max() > 0:
                if len(flags) == len(self._y_values):
                    self._plotter.setFlagsData(flags, flip_axes=True)
                    self._plotter.set_flag_toggles_active(True, False)
            else:
                self._plotter.set_flag_toggles_active(False, False)
            self._plotter.array_plot(incoming_plot_array=self._y_values,
                                     flip_axes=True)

            #     self.get_max()
            self._plotter.replot()

    def setDataLabel(self, data_label, array_label, is_array=False):
        self._data_label = data_label
        if array_label is None:
            self._array_label = 'Ch ' + str(self._curve_number)
        else:
            self._array_label = array_label
        if is_array:
            self._zoom_plot_label = self._data_label + ": " + self._array_label
        else:
            self._zoom_plot_label = self._data_label + ": " + self._array_label + " Sequence (oldest to most recent)"
        self._plotter.setAxisTitle(QwtPlot.xBottom, self._zoom_plot_label)
        self._plotter._x_title = self._zoom_plot_label
        self.setWindowTitle(self._zoom_plot_label)

    def plotMouseMoved(self, e):
        """	Gets x and y position of the mouse on the plot according to axis' value
        set right text on the button and underneath the plot
    """
        # (I) e (QMouseEvent) Mouse event
        lbl = QString("Event=")
        lbl2 = QString("")
        lbl2.setNum(self._plotter.invTransform(QwtPlot.xBottom,
                                               e.pos().x()), 'g', 3)
        lbl += lbl2 + ",  Signal="
        lbl2.setNum(self._plotter.invTransform(QwtPlot.yLeft,
                                               e.pos().y()), 'g', 3)
        lbl += lbl2


#   self._ControlFrame._lblInfo.setText(lbl)

    def closeEvent(self, ce):
        if self._do_close:
            self.winclosed.emit(self._curve_number)
            ce.accept()
        else:
            ce.ignore()
예제 #49
0
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        # connect methods to buttons' click signals
        self.ui.wakeUpButton.clicked.connect(self.wakeUp)
        self.ui.stopButton.clicked.connect(self.stop)
        self.ui.closeButton.clicked.connect(self.close)
        self.ui.saveButton.clicked.connect(self.save)
        self.ui.immediateButton.clicked.connect(self.immediate)
        self.ui.finalButton.clicked.connect(self.final)
        self.ui.fitButton.clicked.connect(self.fit)
        self.ui.action_Save_Ctrl_S.triggered.connect(self.save)
        self.ui.action_Quit_Ctrl_Q.triggered.connect(self.close)
        self.ui.actionManual.triggered.connect(self.manual)
        self.ui.actionAbout.triggered.connect(self.about)
        # create a timer
        self.stopTime=time.time()
        self.timer=QtCore.QTimer()
        # connect the timer to the "tick" callback method
        self.timer.timeout.connect(self.tick)
        # 20 times per second
        self.timer.start(50)
        # initialize an empty curve for the plot widget
        self.curve         = QwtPlotCurve()
        self.curve.attach(self.ui.qwtPlot)
        # expEYESdetection and initialization
        try:
            self.p             = ej.open()
            assert(self.p.fd)
            self.setWindowTitle("expEYES Junior found on port {}".format(
                self.p.fd.port
            ))
        except:
            self.setWindowTitle("ERROR: expEYES Junior NOT FOUND!")
            self.wakeUpButton.setEnabled(False)
        # custom properties
        self.isImmediate=True
        return
        
    def immediate(self):
        self.isImmediate=True
        return
        
    def final(self):
        self.isImmediate=False
        return

    def wakeUp(self):
        # get the duration of the experiment in s
        duration = float(self.ui.durationEdit.text())
        if duration < 0.5: # "final" mode is mandatory
            self.ui.finalButton.setChecked(True)
            self.isImmediate=False
        elif duration > 3.5: # "immediate" mode is mandatory
            self.ui.immediateButton.setChecked(True)
            self.isImmediate=True
        self.ui.qwtPlot.setAxisScale(QwtPlot.xBottom, 0, duration)
        if self.isImmediate:
            now=time.time()
            self.t=[]
            self.v=[]
            self.curve.setData([],[],0)
            self.startTime=now
            self.stopTime=now+duration
            # now the curve will grow until time.time >= self.stopTime
            # thanks to self.timer's timeout events
        else:
            samples  = 1800 # maximum sample number with 8 bit precision
            # ensure that samples * delay will be slightly bigger than duration
            delay=1+int(duration*1e6/1800)
            t, self.v = self.p.capture(1,samples, delay)
            self.t=[1e-3*date for date in t] # convert ms to s
            self.curve.setData(self.t, self.v, len(self.t))
        return

    def tick(self):
        """ Callback for the timeout events """
        t=time.time()
        if t < self.stopTime:
            v = self.p.get_voltage(1)
            self.t.append(time.time()-self.startTime)
            self.v.append(v)
            self.curve.setData(self.t, self.v, len(self.t))
        return
            
        
    def notImplemented(self):
        msg=QtGui.QMessageBox(QtGui.QMessageBox.Warning,"Sorry",
                              "not yet implemented", )
        msg.exec_()
        return

    stop=save=fit=manual=about=notImplemented
class DataPlot(QwtPlot):
    def __init__(self, *args):
        QwtPlot.__init__(self, *args)
        self.Dev_COM = None
        self.uut_dev = None
        print(args)
        if args:
            self.Dev_COM = args[0]
        if self.Dev_COM:
            # Initialize Decice COM,
            self.uut_dev = device.SerialDevice(False,
                                               False,
                                               port=self.Dev_COM,
                                               baudrate=9600)
        else:
            # Initial LAN device
            #UUT PORT(NOTE: PC need to config the same ip section)
            self.uut_Client_ip = '169.254.1.3'
            self.uut_lan_port = 3490  #
            self.uut_buf_size = 1024

            try:
                self.uut_dev = socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM)
                Addr = (self.uut_Client_ip, self.uut_lan_port)
                self.uut_dev.connect(Addr)
                print('Connectin created!')

            except Exception as e:  #
                raise Exception(e)
        #print(self.sendcmd('SYST:REM\r\n'))
        print(self.sendcmd('*CLS\r\n'))

        fileTIME = datetime.datetime.now()
        File_timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
            fileTIME.year, fileTIME.month, fileTIME.day, fileTIME.hour,
            fileTIME.minute, fileTIME.second)

        self.fileNamme = r'./data/data_%s.txt' % (File_timestamp)
        print(self.fileNamme)

        # Initialize 坐标轴
        self.setCanvasBackground(Qt.white)
        self.alignScales()
        grid = QwtPlotGrid()
        grid.attach(self)
        grid.setMajorPen(QPen(Qt.black, 0, Qt.DotLine))

        self.setAxisScale(QwtPlot.xBottom, 0.0, 300.1, 10.0)
        self.setAxisAutoScale(QwtPlot.yLeft, True)
        #self.setAxisScale(QwtPlot.yLeft,99.99,100.0,0.0005)

        self.x = np.arange(
            0.0, 300, 0.5
        )  #0.5 for ONE POINT, THIS SHOULD BE Align to the reading rate:250ms
        print(self.x)
        #self.z = np.zeros(len(self.x), np.float)
        list = []
        for i in range(len(self.x)):
            list.append(0)

        self.z = np.array(list)

        self.setTitle("UUT Reading Monitor -  (mA)")
        self.insertLegend(QwtLegend(), QwtPlot.RightLegend)

        self.curveL = QwtPlotCurve("UUT Reading")
        self.curveL.attach(self)

        self.curveL.setPen(QPen(Qt.red))

        self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)")
        self.setAxisTitle(QwtPlot.yLeft, "UUT - Reading(mA)")
        self.replot()

        self.startTimer(500)  # ms # FOR GET READING

        self.starttime = time.clock()
        #unit: s
        self.idx = 0
        self.readfmt = "%f"
        self.Saveinfo("Starting...")

    def alignScales(self):
        self.canvas().setFrameStyle(QFrame.Box | QFrame.Plain)
        self.canvas().setLineWidth(1)
        for i in range(QwtPlot.axisCnt):
            scaleWidget = self.axisWidget(i)
            if scaleWidget:
                scaleWidget.setMargin(0)
            scaleDraw = self.axisScaleDraw(i)
            if scaleDraw:
                scaleDraw.enableComponent(QwtAbstractScaleDraw.Backbone, False)

    def timerEvent(self, e):
        # send cmd and get readings, record times, X is second;
        if self.Dev_COM:  # SerialDevice
            # tfdata = self.uut_get_val(self.uut_dev, "VAL?\r")   #Wolf
            #tfdata = self.uut_get_val(self.uut_dev, "READ:VOLT:DC?\r")   # GW VOLT
            #ifdata = self.uut_get_val(self.uut_dev, "READ:CURR:DC?\r")   # GW CURRENT
            #tfdata = self.uut_get_val(self.uut_dev, "x?\r\n")   # 8508
            #print('Getting Serial data.........')
            tfdata = self.uut_get_val(self.uut_dev,
                                      "UPPER_VAL?\r\n")  # pass/pac
            #tfdata = 1000*self.uut_get_val(self.uut_dev, "CONF:CURR:DC +1.000000E-01,+1.000000E-07;:MEAS:CURR:DC?\r\n")   # 8846
        else:  # LanDevice
            print('Getting Serial data.........')
            tfdata = 1000.0 * float(
                self.Get_Lan_Response(
                    "CONF:CURR:DC +1.000000E-01,+1.000000E-07;:MEAS:CURR:DC?\r\n"
                ))  # 8846

        print(tfdata)  #, "\t"	, ifdata

        self.z = np.concatenate((self.z[1:], self.z[:1]), 0)
        self.z[-1] = tfdata

        self.curveL.setData(self.x, self.z)
        self.replot()

        self.idx = self.idx + 1
        #Write file to txt log
        self.SaveData(tfdata)

        now = time.clock()
        if ((now - self.starttime) > 250):  # 250 point (seconds)
            self.starttime = time.clock()
            # reset start time

            pngTIME = datetime.datetime.now()
            FILE_timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
                pngTIME.year, pngTIME.month, pngTIME.day, pngTIME.hour,
                pngTIME.minute, pngTIME.second)
            PNGFile = ('%s_%s' % (FILE_timestamp, '.png'))
            self.exportTo('.\pic\%s' % PNGFile,
                          size=(1920, 1080),
                          resolution=200)
            print PNGFile, "The snaped curve picture has been created."

    def sendcmd(self, cmd):
        cmd_encode = cmd.encode()
        if self.Dev_COM:
            self.uut_dev.write(cmd)
        else:
            self.uut_dev.send(cmd_encode)
        return cmd_encode

    # LAN Device   reaponse
    def Get_Lan_Response(self, cmd):
        self.sendcmd(cmd)
        Rsp = ''
        rtn = ''
        while (1):
            recv_data = self.uut_dev.recv(self.uut_buf_size)
            Rsp += recv_data.decode()
            #print(Rsp)

            if ('\n' or '\r') in Rsp:
                Rsp.strip()
                break
        return Rsp

    # Serial devie response
    def uut_get_val(self,
                    uut_dev_in,
                    type="x?\r\n"
                    ):  #[0-9]\d*\.\d+$    #r'[ -+]\d+\.\d+[Ee][-+][0-9]{2}'
        cmd_encode = type.encode()
        print(cmd_encode)
        uut_dev_in.flush()
        m = uut_dev_in.trx(type, r'[0-9]\d*\.\d+$')
        print m.group(0)
        return float(m.group(0))

    def SaveData(self, tfdata):
        fh = open(self.fileNamme, "a")
        now = datetime.datetime.now()
        timestamp = "%02d:%02d:%02d.%03d" % (now.hour, now.minute, now.second,
                                             now.microsecond / 1000)

        str = "%s, %s, %s\n" % (self.idx, timestamp, tfdata)
        fh.write(str)
        fh.flush()

    def Saveinfo(self, info):
        fh = open(self.fileNamme, "a")
        now = datetime.datetime.now()
        timestamp = "%04d-%02d-%02d_%02d%02d%02d" % (
            now.year, now.month, now.day, now.hour, now.minute, now.second)
        title = "%s,   %s\n" % (timestamp, info)
        fh.write(title)

        fh.write("\nSN,TIME,SenseNiose\n")

        fh.flush()