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
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
class DataPlot(QwtPlot): def __init__(self, *args): QwtPlot.__init__(self, *args) self.setCanvasBackground(Qt.white) curva = QwtPlotCurve('Altitud') self.phase=0 ################################################## # Initialize data self.x = [0] self.y = [0] # Title of the graph self.g1title = "Altitude= " + str(self.x[0]) self.insertLegend(QwtLegend(), QwtPlot.BottomLegend); self.curveR = QwtPlotCurve("Altitude") self.curveR.attach(self) self.curveR.setPen(QPen(Qt.blue)) self.setAxisTitle(QwtPlot.xBottom, "Time (seconds)") self.setAxisTitle(QwtPlot.yLeft, "Altitude(m)") self.setAxisScale(QwtPlot.xBottom, 0.0, 20) self.setAxisScale(QwtPlot.yLeft, 0.0, 20) self.pal = QPalette() #####palette for background self.pal.setColor(QPalette.Text, Qt.white) self.pal.setColor(QPalette.Foreground, Qt.white) self.setPalette(self.pal) self.counter=0 ###counter for actualize data, is the same for all of the graphs/data grid = QwtPlotGrid() grid.attach(self) grid.setPen(QPen(Qt.black, 0, Qt.DotLine))
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()
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
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()
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()
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)
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)
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
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)
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 4 empty curves for the plot widget self.curves=[] colors=[ QtGui.QColor("#000000"), #black QtGui.QColor("#ff0000"), #red QtGui.QColor("#0000ff"), #blue QtGui.QColor("#00cc00"), #dark green ] for i in range(4): c=QwtPlotCurve() c.setPen(colors[i]) self.curves.append(c) c.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 __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()
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
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
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()
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()
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
def __init__(self, *args): QwtPlot.__init__(self, *args) global x, y, lineL, lineH, curveTemp HISTORY = 300 x = 0.1 * np.arange(0, -HISTORY, -1) y = np.zeros(HISTORY, np.float) self.setAxisScale(QwtPlot.yLeft, 0, 100) lineL = QwtPlotMarker() lineL.setLinePen(QtGui.QPen(QtCore.Qt.blue)) lineL.setLabelAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom) lineL.setLineStyle(QwtPlotMarker.HLine) lineL.setYValue(0) lineL.attach(self) lineH = QwtPlotMarker() lineH.setLinePen(QtGui.QPen(QtCore.Qt.red)) lineH.setLabelAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) lineH.setLineStyle(QwtPlotMarker.HLine) lineH.setYValue(100) lineH.attach(self) curveTemp = QwtPlotCurve("实时温度") curveTemp.attach(self)
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()
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()
def main(args): app = QApplication(args) demo = QwtPlot() grid = QwtPlotGrid() grid.attach(demo) grid.setPen(QPen(Qt.black, 0, Qt.DotLine)) grid.enableX(True) grid.enableY(True) complex_divider = 50.0 myXScale = ComplexScaleDraw(start_value=0.0, end_value=complex_divider) #print('myXScale', myXScale) demo.setAxisScaleDraw(QwtPlot.xBottom, myXScale) m = QwtPlotMarker() m.attach(demo) m.setValue(complex_divider, 0.0) m.setLineStyle(QwtPlotMarker.VLine) m.setLabelAlignment(Qt.AlignRight | Qt.AlignBottom) m.setLinePen(QPen(Qt.black, 2, Qt.SolidLine)) vector_array = numpy.zeros((100, ), numpy.float32) for i in range(100): vector_array[i] = i curve = QwtPlotCurve('example data') curve.attach(demo) x_array = numpy.zeros(100, numpy.float32) y_array = numpy.zeros(100, numpy.float32) for i in range(100): x_array[i] = 1.0 * i y_array[i] = 2.0 * i curve.setSamples(x_array, y_array) demo.resize(600, 400) demo.replot() demo.show() # app.setMainWidget(demo) app.exec_()
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()
class TabGraph(QWidget): _logname = 'TabGraph' _log = logging.getLogger(f'{_logname}') ##TabGraph constructor # #Create the graph and accompanying buttons def __init__(self, db, parent=None): super().__init__(parent) # self.LOGIN = LOGIN # self.db = dataBase(self.LOGIN, "Brewing") self.db = db self.dataY = np.zeros(0) self.dataX = np.linspace(0, len(self.dataY), len(self.dataY)) self.count = 0 self.timeLabel = QLabel("Timer:") self.timeLabel.setAlignment(QtCore.Qt.AlignRight) self.tempLabel = QLabel("Temp:") self.tempLabel.setAlignment(QtCore.Qt.AlignRight) self.targetTemp = QLabel("Set Temp:") self.targetTime = QLabel("Set Time:") self.targetTimeLabel = QLabel("Target: ") self.targetTimeLabel.setAlignment(QtCore.Qt.AlignRight) self.targetTempLabel = QLabel("Target: ") self.targetTempLabel.setAlignment(QtCore.Qt.AlignRight) self.startButton = QPushButton() self.stopButton = QPushButton() self.plot = QwtPlot() self.curve = QwtPlotCurve() self.curve.attach(self.plot) self.plot.resize(1000, 1000) self.plot.replot() self.plot.show() 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) yTitle = QwtText() yTitle.setText(f"Temperature {DEGREESC}") yTitle.setFont(axisFont) self.plot.setAxisTitle(self.plot.yLeft, yTitle) self.tempStatusLED = QLed(self, onColour=QLed.Green, offColour=QLed.Red, shape=QLed.Circle) self.tempStatusLED.value = False self.tempStatusLED.setMaximumSize(25, 25) self.timeStatusLED = QLed(self, onColour=QLed.Green, offColour=QLed.Red, shape=QLed.Circle) self.timeStatusLED.value = False self.timeStatusLED.setMaximumSize(25, 25) self.recipeGrid = QGridLayout() self.recipeGrid.addWidget(QLabel(f"Recipe:"), 0, 0) self.recipeGrid.addWidget(QLabel(f"{self.recipedata['recipeName']}"), 0, 1) self.recipeGrid.addWidget(QHLine(), 1, 0, 1, 2) self.recipeGrid.addWidget(self.targetTemp) self.recipeGrid.addWidget(self.targetTempLabel) self.recipeGrid.addWidget(self.targetTime) self.recipeGrid.addWidget(self.targetTimeLabel) self.recipeGrid.addWidget(QHLine(), 4, 0, 1, 2) self.tempLayout = QHBoxLayout() # self.tempLayout.addWidget(self.targetTempLabel) # self.tempLayout.addStretch(10) self.tempLayout.addWidget(self.tempLabel) # self.tempLayout.addStretch(10) self.tempLayout.addWidget(self.tempStatusLED) self.tempLayout.addStretch(10) self.timeLayout = QHBoxLayout() # self.timeLayout.addWidget(self.targetTimeLabel) # self.timeLayout.addStretch(10) self.timeLayout.addWidget(self.timeLabel) # self.timeLayout.addStretch(10) self.timeLayout.addWidget(self.timeStatusLED) self.timeLayout.addStretch(10) self.plotLayout = QVBoxLayout() self.plotLayout.addLayout(self.timeLayout) # self.plotLayout.addStretch(10) self.plotLayout.addLayout(self.tempLayout) # self.plotLayout.addStretch(10) self.plotLayout.addWidget(self.plot) self.buttonLayout = QVBoxLayout() self.buttonLayout.addWidget(self.startButton) self.buttonLayout.addWidget(self.stopButton) self.buttonLayout.addLayout(self.recipeGrid) self.buttonLayout.addStretch(100) mainLayout = QHBoxLayout() mainLayout.addLayout(self.buttonLayout) mainLayout.addLayout(self.plotLayout) vLayout = QVBoxLayout(self) vLayout.addLayout(mainLayout) self.minuteTimer = QTimer(self) self.minuteTimer.timeout.connect(lambda: self.addTimer(60)) ##Keep track of the timer def addTimer(self, seconds): self.count += seconds ##convery the time from seconds to hours/minutes def display_time(self, seconds, granularity=2): result = [] for name, count in TIME_INTERVALS: value = seconds // count if value: seconds -= value * count if value == 1: name = name.rstrip('s') result.append("{} {}".format(value, name)) return ', '.join(result[:granularity])
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)
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()
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
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 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
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) # 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()
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
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()
# -*- 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))
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)
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()
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
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}")
class QwtImagePlot(QwtPlot): def __init__(self, *args): QwtPlot.__init__(self, *args) # make a QwtPlot widget self.plotLayout().setCanvasMargin(0) self.plotLayout().setAlignCanvasToScales(1) self.setTitle('QwtImagePlot: (un)zoom & (un)hide') # set axis titles self.setAxisTitle(QwtPlot.xBottom, 'time (s)') self.setAxisTitle(QwtPlot.yLeft, 'frequency (Hz)') # insert a few curves self.cSin = QwtPlotCurve('y = pi*sin(x)') self.cCos = QwtPlotCurve('y = 4*pi*sin(x)*cos(x)**2') self.cSin.attach(self) self.cCos.attach(self) # set curve styles self.cSin.setPen(QPen(Qt.green, 2)) self.cCos.setPen(QPen(Qt.black, 2)) self.xzoom_loc = None self.yzoom_loc = None self.xpos = None self.ypos = None # attach a grid grid = QwtPlotGrid() grid.attach(self) grid.setPen(Qt.black, 0, Qt.DotLine) # create zoom curve self.zoom_outline = QwtPlotCurve() self.zoom_outline.setStyle(QwtPlotCurve.Lines) # create and initialize an image display self.plotImage = QwtPlotImage(self) self.plotImage.attach(self) self.gain = 2.0 self.updateDisplay() self.zoomStack = [] self.spy = Spy(self.canvas()) self.prev_xpos = None self.prev_ypos = None # self.connect(self, Qt.SIGNAL("legendClicked(QwtPlotItem*)"), # self.toggleVisibility) self.spy.MouseMove.connect(self.onmouseMoveEvent) self.spy.MousePress.connect(self.onmousePressEvent) self.spy.MouseRelease.connect(self.onmouseReleaseEvent) # __init__() def toggleVisibility(self, plotItem): """Toggle the visibility of a plot item """ plotItem.setVisible(not plotItem.isVisible()) self.replot() # showCoordinates() def updateDisplay(self): offset = 3 # calculate 3 NumPy arrays x = numpy.arange(-1.0 * self.gain*math.pi, self.gain*math.pi, 0.01) y = math.pi*numpy.sin(x) + offset z = self.gain * self.gain*math.pi*numpy.cos(x)*numpy.cos(x)*numpy.sin(x) + offset # copy the data self.cSin.setSamples(x, y) self.cCos.setSamples(x, z) # image test_image = sinx_image(8,16,offset) self.plotImage.setData(test_image) # self.plotImage.setData( # square(512,-1.0 * self.gain*math.pi, self.gain*math.pi), (-1.0*self.gain*math.pi, self.gain*math.pi), (-1.0*self.gain*math.pi, self.gain*math.pi)) def updateBarDisplay(self): self.min = 0.0 self.max = 256.0 self.bar_array = numpy.reshape(numpy.arange(self.max), (1,256)) self.y_scale = (self.min, self.max) self.plotImage.setData(self.bar_array, None, self.y_scale) def start_timer(self, time): """ start a timer going to update the image every 1/10 sec """ self.timer = QTimer(self) self.timer.timeout.connect(self.testEvent) self.timer.start(time) def testEvent(self): """ change the gain factor and recalculate the image """ self.gain = self.gain + 1.0 self.updateDisplay() self.updateBarDisplay() self.replot() def mouseCatch(self,x,y,z): print('in mouseCatch') print('caught', x,y, z) def onmouseMoveEvent(self,event): position = event.pos() x = position.x() y = position.y() button = event.button() if not self.xpos is None: self.xpos = self.invTransform(QwtPlot.xBottom, x) self.ypos = self.invTransform(QwtPlot.yLeft, y) if not self.xzoom_loc is None: self.xzoom_loc = [self.press_xpos, self.press_xpos, self.xpos, self.xpos,self.press_xpos] self.yzoom_loc = [self.press_ypos, self.ypos, self.ypos, self.press_ypos,self.press_ypos] self.zoom_outline.setSamples(self.xzoom_loc,self.yzoom_loc) self.replot() def onmousePressEvent(self,event): position = event.pos() x = position.x() y = position.y() button = event.button() if Qt.LeftButton == button: if self.xpos is None: self.xpos = self.invTransform(QwtPlot.xBottom, x) self.ypos = self.invTransform(QwtPlot.yLeft, y) # Python semantics: self.pos = e.pos() does not work; force a copy self.press_xpos = self.xpos self.press_ypos = self.ypos self.xzoom_loc = [self.press_xpos] self.yzoom_loc = [self.press_ypos] self.zoom_outline.attach(self) self.zooming = 1 if self.zoomStack == []: try: self.zoomState = ( self.axisScaleDiv(QwtPlot.xBottom).lBound(), self.axisScaleDiv(QwtPlot.xBottom).hBound(), self.axisScaleDiv(QwtPlot.yLeft).lBound(), self.axisScaleDiv(QwtPlot.yLeft).hBound(), ) except: self.zoomState = ( self.axisScaleDiv(QwtPlot.xBottom).lowerBound(), self.axisScaleDiv(QwtPlot.xBottom).upperBound(), self.axisScaleDiv(QwtPlot.yLeft).lowerBound(), self.axisScaleDiv(QwtPlot.yLeft).upperBound(), ) elif Qt.RightButton == button: self.zooming = 0 # mousePressEvent() def onmouseReleaseEvent(self,event): position = event.pos() x = position.x() y = position.y() button = event.button() if Qt.LeftButton == button: xmin = min(self.xpos, self.press_xpos) xmax = max(self.xpos, self.press_xpos) ymin = min(self.ypos, self.press_ypos) ymax = max(self.ypos, self.press_ypos) if not self.xzoom_loc is None: self.zoom_outline.detach() self.xzoom_loc = None self.yzoom_loc = None if xmin == xmax or ymin == ymax: return self.zoomStack.append(self.zoomState) self.zoomState = (xmin, xmax, ymin, ymax) elif Qt.RightButton == button: # we back up the zoom stack if len(self.zoomStack): xmin, xmax, ymin, ymax = self.zoomStack.pop() else: return if button != Qt.MidButton: self.setAxisScale(QwtPlot.xBottom, xmin, xmax) self.setAxisScale(QwtPlot.yLeft, ymin, ymax) self.plotImage.update_xMap_draw(xmin,xmax) self.plotImage.update_yMap_draw(ymin,ymax) self.replot() # mouseReleaseEvent() def toggleCurve(self, key): curve = self.curve(key) if curve: curve.setEnabled(not curve.enabled()) self.replot()
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()
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()
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
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
class QwtColorBar(QwtPlot): menu_table = { 'unzoom intensity range': 200, 'lock colorbar scale': 201, 'unlock colorbar scale': 202, } set_image_range = pyqtSignal(int, int, int, int) def __init__(self, colorbar_number=0, parent=None): QwtPlot.__init__(self, parent) self._mainwin = parent and parent.topLevelWidget() self.colorbar_number = colorbar_number # create copy of standard application font.. font = QFont() fi = QFontInfo(font) # and scale it down to 70% font.setPointSize(fi.pointSize() * 0.7) # apply font to QwtPlot # self.setTitleFont(font); for axis in range(0, 4): self.setAxisFont(axis, font) # self.setAxisTitleFont(axis,font); # make a QwtPlot widget self.plotLayout().setCanvasMargin(0) self.plotLayout().setAlignCanvasToScales(1) # set axis parameters self.enableAxis(QwtPlot.yLeft) self.enableAxis(QwtPlot.xBottom, False) self.setAxisLabelRotation(QwtPlot.yLeft, 270) self.setAxisLabelAlignment(QwtPlot.yLeft, Qt.AlignTop) # default color bar self.plotImage = QwtPlotImage(self) self.plotImage.attach(self) self.updateDisplay() self.min = 0.0 self.max = 256.0 self.is_active = False self.log_scale = False self.ampl_phase = False self.bar_array = numpy.reshape(numpy.arange(self.max), (1, 256)) self.y_scale = (self.min, self.max) self.plotImage.setData(self.bar_array, None, self.y_scale) # Over-ride default QWT Plot size policy of MinimumExpanding # Otherwise minimum size of plots is too large when embedded in a # QGridlayout self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # width limits - the following seem reasonable # we don't want the bar to resize itself freely - it becomes too big! # self.setMaximumWidth(self.sizeHint().width() * 2.5) self.setMaximumWidth(self.sizeHint().width() * 1.5) self.spy = Spy(self.canvas()) self.spy.MouseMove.connect(self.MouseMoveEvent) self.spy.MousePress.connect(self.MousePressEvent) self.spy.MouseRelease.connect(self.MouseReleaseEvent) self.zoomStack = [] self.xzoom_loc = None self.yzoom_loc = None self.prev_xpos = None self.prev_ypos = None self.raw_image_min = None self.raw_image_max = None # create zoom curve self.zoom_outline = QwtPlotCurve() self.setMouseTracking(True) self.installEventFilter(self) # add intructions on how to use self.setWhatsThis(colorbar_instructions) # create pull_down menu and add menu components if self._mainwin: self._menu = QMenu(self._mainwin) else: self._menu = QMenu(None) self._unzoom_action = QAction('unzoom intensity range', self) self._menu.addAction(self._unzoom_action) self._unzoom_action.setVisible(False) self._unzoom_action.triggered.connect(self.unzoom) self._lock_colorbar = QAction('lock colorbar scale', self) self._menu.addAction(self._lock_colorbar) self._lock_colorbar.triggered.connect(self.lock_colorbar) self._unlock_colorbar = QAction('unlock colorbar scale', self) self._menu.addAction(self._unlock_colorbar) self._unlock_colorbar.setVisible(False) self._unlock_colorbar.triggered.connect(self.unlock_colorbar) self._lock_bar = False # for drag & drop stuff ... self.setAcceptDrops(True) self.yhb = 0 self.ylb = 0 self.xhb = 0 self.xlb = 0 # __init__() def lock_colorbar(self): self._lock_colorbar.setVisible(False) self._unlock_colorbar.setVisible(True) if len(self.zoomStack): self._unzoom_action.setVisible(False) self._lock_bar = True self.emit_range() def unlock_colorbar(self): self._lock_colorbar.setVisible(True) self._unlock_colorbar.setVisible(False) if len(self.zoomStack): self._unzoom_action.setVisible(True) self._lock_bar = False self.emit_range() def get_data_range(self): """ returns range of this widget when called by 'foreign' widget on which we have done a drop event """ rng = (self.min, self.max, self.colorbar_number, self.ampl_phase) return rng def dragEnterEvent(self, event): """ drag & drop event callback entered when we move out of or in to a widget """ try: if event.mimeData().hasText(): event.acceptProposedAction() except: pass def dropEvent(self, event): """ callback that handles a drop event from drag & drop """ if event.source() == self: return if event.mimeData().hasText(): command_str = str(event.mimeData().text()) if command_str.find('copyColorRange') > -1: components = event.source().get_data_range() min = components[0] max = components[1] colorbar = components[2] amp_phas = components[3] if self.colorbar_number == colorbar and not self._lock_bar: self.zoomStack == [] try: self.zoomState = ( self.axisScaleDiv(QwtPlot.yLeft).lBound(), self.axisScaleDiv(QwtPlot.yLeft).hBound(), ) except: self.zoomState = ( self.axisScaleDiv(QwtPlot.yLeft).lowerBound(), self.axisScaleDiv(QwtPlot.yLeft).upperBound(), ) self.zoomStack.append(self.zoomState) self._unzoom_action.setVisible(True) self.setRange(min, max, colorbar, amp_phas) else: message = 'QwtColorBar dropEvent decode failure' mb_reporter = QMessageBox.information(self, "QwtColorBar", message) event.acceptProposedAction() def startDrag(self, event): """ operations done when we start a drag event """ drag = Qt.QDrag(self) mimedata = Qt.QMimeData() passed_string = 'copyColorRange' mimedata.setText(passed_string) drag.setMimeData(mimedata) drag.exec_() event.accept() def setRange(self, min, max, colorbar_number=0, ampl_phase=False): """ sets display range for this colorbar and emits signal to associated display to set corresponding range """ if ampl_phase != self.ampl_phase: return if colorbar_number == self.colorbar_number: if min > max: temp = max max = min min = temp if abs(max - min) < 2.0e-8: if max == 0.0 or min == 0.0: min = -0.1 max = 0.1 else: min = 0.9 * min max = 1.1 * max self.min = min * 1.0 self.max = max * 1.0 # send event to display_image.py that range has changed self.emit_range() if self.log_scale: max = log(self.max) min = log(self.min) delta = (max - min) / 255.0 for i in range(256): self.bar_array[0, i] = exp(min + i * delta) else: delta = (self.max - self.min) / 255.0 for i in range(256): self.bar_array[0, i] = self.min + i * delta self.y_scale = (self.min, self.max) self.plotImage.setData(self.bar_array, None, self.y_scale) self.show() self.replot() # set Range() def getTransformOffset(self): """ get the offset value for a plot with a log scale """ return self.plotImage.getTransformOffset() def setScales(self): self.plotImage.setLogScale(self.log_scale) self.plotImage.setLogYScale(self.log_scale) self.setAxisAutoScale(QwtPlot.yLeft) if self.log_scale: self.setAxisScaleEngine(QwtPlot.yLeft, QwtLogScaleEngine()) else: self.setAxisScaleEngine(QwtPlot.yLeft, QwtLinearScaleEngine()) def handleRangeParms(self, limits, colorbar_number, log_scale, ampl_phase): if ampl_phase is None: ampl_phase = False self.setMaxRange(limits, colorbar_number, log_scale, ampl_phase) def setMaxRange(self, limits, colorbar_number=0, log_scale=False, ampl_phase=False): """ sets maximum range parameters for this colorbar """ # print('in colorbar setMaxRange : colorbar numbers ',colorbar_number,self.colorbar_number) if colorbar_number == self.colorbar_number: self.ampl_phase = ampl_phase if self.ampl_phase is None: self.ampl_phase = False self.log_scale = log_scale self.setScales() min = limits[0] max = limits[1] try: self.raw_image_min = limits[2] self.raw_image_max = limits[3] except: pass if min > max: temp = max max = min min = temp # if abs(max - min) < 0.00005: if abs(max - min) < 2.0e-8: if max == 0.0 or min == 0.0: min = -0.1 max = 0.1 else: min = 0.9 * min max = 1.1 * max if not self._lock_bar: self.image_min = min * 1.0 self.image_max = max * 1.0 self.min = self.image_min self.max = self.image_max if self.log_scale: if self.min <= 0.0: offset = -1.0 * self.min + 0.001 self.min = self.min + offset self.max = self.max + offset self.image_min = self.min self.image_max = self.max max = log(self.max) min = log(self.min) delta = (max - min) / 255.0 for i in range(256): self.bar_array[0, i] = exp(min + i * delta) if HAS_TIMBA: _dprint(3, 'log bar array is ', self.bar_array) else: delta = (self.max - self.min) / 255.0 for i in range(256): self.bar_array[0, i] = self.min + i * delta if not self._lock_bar: self.y_scale = (self.min, self.max) self.plotImage.setData(self.bar_array, None, self.y_scale) self.show() self.replot() # setMaxRange() def showDisplay(self, show_self, colorbar_number=0): """ callback to show or hide this colorbar """ # print('in colorbar show display with self.colorbar_number', self.colorbar_number) if colorbar_number == self.colorbar_number: self.is_active = True if show_self > 0: self.show() # print('should show') else: self.hide() # print('should hide') self.replot() # showDisplay def unHide(self): """ callback to show this colorbar """ if self.is_active: self.show() def emit_range(self): # print('emitting range') self.set_image_range.emit(self.min, self.max, self.colorbar_number, self._lock_bar) def setBarLock(self, set_lock=False): self._lock_bar = set_lock if self._lock_bar: toggle_id = self.menu_table['lock colorbar scale'] self._menu.setItemVisible(toggle_id, False) toggle_id = self.menu_table['unlock colorbar scale'] self._menu.setItemVisible(toggle_id, True) else: toggle_id == self.menu_table['unlock colorbar scale'] self._menu.setItemVisible(toggle_id, False) toggle_id = self.menu_table['lock colorbar scale'] self._menu.setItemVisible(toggle_id, True) self.emit_range() def unzoom(self): """ callback to set range of this colorbar back to default """ if len(self.zoomStack): while len(self.zoomStack): ymin, ymax = self.zoomStack.pop() self._unzoom_action.setVisible(False) if not self.raw_image_min is None: self.image_min = self.raw_image_min self.image_max = self.raw_image_max self.setAxisScale(QwtPlot.yLeft, self.image_min, self.image_max) if self.image_min > self.image_max: temp = self.image_max self.image_max = self.image_min self.image_min = temp self.setRange(self.image_min, self.image_max, self.colorbar_number, self.ampl_phase) # set the type of colorbar display, can be one of "hippo", "grayscale" # or "brentjens" def setDisplayType(self, display_type): self.plotImage.setDisplayType(display_type) self.plotImage.setData(self.bar_array, None, self.y_scale) self.replot() # setDisplayType() def drawCanvasItems(self, painter, rectangle, maps, filter): self.plotImage.drawImage(painter, maps[QwtPlot.xBottom], maps[QwtPlot.yLeft]) QwtPlot.drawCanvasItems(self, painter, rectangle, maps, filter) # drawCanvasItems() def MouseMoveEvent(self, e): """ callback to handle mouse moved event """ # print('in mouse move event') position = e.pos() xPos = position.x() yPos = position.y() self.xpos = self.invTransform(QwtPlot.xBottom, xPos) self.ypos = self.invTransform(QwtPlot.yLeft, yPos) if not self.xzoom_loc is None: self.xzoom_loc = [ self.press_xpos, self.press_xpos, self.xpos, self.xpos, self.press_xpos ] self.yzoom_loc = [ self.press_ypos, self.ypos, self.ypos, self.press_ypos, self.press_ypos ] if self.zoom_outline is None: self.zoom_outline = QwtPlotCurve() self.zoom_outline.setSamples(self.xzoom_loc, self.yzoom_loc) self.replot() # Test if mouse has moved outside the plot. If yes, we're # starting a drag. if xPos < self.xlb - 10 or xPos > self.xhb + 10 or yPos > self.ylb + 10 or yPos < self.yhb - 10: if not self.xzoom_loc is None: self.zoom_outline.detach() self.xzoom_loc = None self.yzoom_loc = None self.replot() self.startDrag(e) # onMouseMoved() def MousePressEvent(self, e): """ callback to handle mouse pressed event """ if Qt.LeftButton == e.button(): # get bounds of plot. Keep them around for later test if # we're initiating a drag operation try: self.yhb = self.transform( QwtPlot.yLeft, self.axisScaleDiv(QwtPlot.yLeft).hBound()) self.ylb = self.transform( QwtPlot.yLeft, self.axisScaleDiv(QwtPlot.yLeft).lBound()) self.xhb = self.transform( QwtPlot.xBottom, self.axisScaleDiv(QwtPlot.xBottom).hBound()) self.xlb = self.transform( QwtPlot.xBottom, self.axisScaleDiv(QwtPlot.xBottom).lBound()) except: self.yhb = self.transform( QwtPlot.yLeft, self.axisScaleDiv(QwtPlot.yLeft).upperBound()) self.ylb = self.transform( QwtPlot.yLeft, self.axisScaleDiv(QwtPlot.yLeft).lowerBound()) self.xhb = self.transform( QwtPlot.xBottom, self.axisScaleDiv(QwtPlot.xBottom).upperBound()) self.xlb = self.transform( QwtPlot.xBottom, self.axisScaleDiv(QwtPlot.xBottom).lowerBound()) # Python semantics: self.pos = e.pos() does not work; force a copy if HAS_TIMBA: _dprint(3, 'e.pos() ', e.pos()) self.press_xpos = self.xpos self.press_ypos = self.ypos if HAS_TIMBA: _dprint(3, 'self.xpos self.ypos ', self.xpos, ' ', self.ypos) if not self._lock_bar: self.xzoom_loc = [self.press_xpos] self.yzoom_loc = [self.press_ypos] self.zoom_outline.attach(self) if self.zoomStack == []: try: self.zoomState = ( self.axisScaleDiv(QwtPlot.yLeft).lBound(), self.axisScaleDiv(QwtPlot.yLeft).hBound(), ) except: self.zoomState = ( self.axisScaleDiv(QwtPlot.yLeft).lowerBound(), self.axisScaleDiv(QwtPlot.yLeft).upperBound(), ) # fake a mouse move to show the cursor position # self.onMouseMoved(e) elif Qt.RightButton == e.button(): e.accept() self._menu.popup(e.globalPos()) # onMousePressed() def MouseReleaseEvent(self, e): """ handles mouse release event if we're not doing a drop """ # if color bar is locked, do nothing if self._lock_bar: return if Qt.LeftButton == e.button(): xmin = min(self.xpos, self.press_xpos) xmax = max(self.xpos, self.press_xpos) ymin = min(self.ypos, self.press_ypos) ymax = max(self.ypos, self.press_ypos) if not self.xzoom_loc is None: self.zoom_outline.detach() self.xzoom_loc = None self.yzoom_loc = None if xmin == xmax or ymin == ymax: return self.zoomStack.append(self.zoomState) # print('self.zoomsSack', self.zoomStack) self.zoomState = (ymin, ymax) if len(self.zoomStack): self._unzoom_action.setVisible(True) elif Qt.RightButton == e.button(): if len(self.zoomStack): ymin, ymax = self.zoomStack.pop() else: return self.setAxisScale(QwtPlot.yLeft, ymin, ymax) if ymin > ymax: temp = ymax ymax = ymin ymin = temp self.setRange(ymin, ymax, self.colorbar_number, self.ampl_phase) self.replot() # onMouseReleased() def updateDisplay(self): # calculate 3 NumPy arrays self.gain = 1.0 # image self.plotImage.setData( square(512, -1.0 * self.gain * pi, self.gain * pi), (-1.0 * self.gain * pi, self.gain * pi), (-1.0 * self.gain * pi, self.gain * pi))
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_()
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()
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()
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()
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()