def __init__(self): # Explaining super is out of the scope of this article # So please google it if you're not familar with it # Simple reason why we use it here is that it allows us to # access variables, methods etc in the design.py file super(self.__class__, self).__init__() # konfiguriram PyQtGraph pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') # This is defined in GUI_design.py file automatically # It sets up layout and widgets that are defined self.setupUi(self) self.setWindowTitle("SAPF DLOG") self.setWindowIcon(QtGui.QIcon(resource_path("Logo_LRTME.png"))) # crte na grafu self.main_plot = self.PlotWidget.plotItem self.text = pg.LabelItem() self.text.setParentItem(self.main_plot.graphicsItem()) # pripravim vse elemente self.plot_ch1 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('r', width=3)) self.plot_ch2 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('g', width=3)) self.plot_ch3 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('b', width=3)) self.plot_ch4 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('c', width=3)) self.plot_ch5 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('m', width=3)) self.plot_ch6 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen('k', width=3)) self.plot_ch7 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen(0.25, width=3)) self.plot_ch8 = self.main_plot.plot(np.array([0.0]), np.array([0.0]), pen=pg.mkPen(0.5, width=3)) # ampak jih vecino odstranim self.main_plot.removeItem(self.plot_ch1) self.main_plot.removeItem(self.plot_ch2) self.main_plot.removeItem(self.plot_ch3) self.main_plot.removeItem(self.plot_ch4) self.main_plot.removeItem(self.plot_ch5) self.main_plot.removeItem(self.plot_ch6) self.main_plot.removeItem(self.plot_ch7) self.main_plot.removeItem(self.plot_ch8) self.main_plot.showGrid(True, True) self.vb = self.main_plot.vb self.mouse_point = QtCore.QPoint(0.0, 0.0) """ connect """ # registriram rx handlerje self.commonitor.connect_rx_handler(0x0901, self.on_received_ch1) self.commonitor.connect_rx_handler(0x0902, self.on_received_ch2) self.commonitor.connect_rx_handler(0x0903, self.on_received_ch3) self.commonitor.connect_rx_handler(0x0904, self.on_received_ch4) self.commonitor.connect_rx_handler(0x0905, self.on_received_ch5) self.commonitor.connect_rx_handler(0x0906, self.on_received_ch6) self.commonitor.connect_rx_handler(0x0907, self.on_received_ch7) self.commonitor.connect_rx_handler(0x0908, self.on_received_ch8) self.commonitor.connect_rx_handler(0x090A, self.on_dlog_params_received) self.commonitor.connect_rx_handler(0x0B0A, self.on_ref_params_received) # povezem signal z handlerjem signala self.commonitor.connect_crc_handler(self.crc_event_print) # se meni-quit self.actionQuit.triggered.connect(QtWidgets.qApp.quit) # se meni "connect" self.actionConnect_Disconnect.triggered.connect(self.com_meni_clicked) # pripravim dialoga self.com_dialog = COM_settings_dialog.ComDialog(self) self.com_dialog.try_connect_at_startup(serial_number=com_serial_number) self.com_stat_dialog = COM_statistics_dialog.ComStat(self) # se meni "com statistics" self.actionCom_statistics.triggered.connect( self.com_statistics_clicked) # kontorlni elementi za graf self.ch1_chkbox.stateChanged.connect(self.ch1_state_changed) self.ch2_chkbox.stateChanged.connect(self.ch2_state_changed) self.ch3_chkbox.stateChanged.connect(self.ch3_state_changed) self.ch4_chkbox.stateChanged.connect(self.ch4_state_changed) self.ch5_chkbox.stateChanged.connect(self.ch5_state_changed) self.ch6_chkbox.stateChanged.connect(self.ch6_state_changed) self.ch7_chkbox.stateChanged.connect(self.ch7_state_changed) self.ch8_chkbox.stateChanged.connect(self.ch8_state_changed) # za prescalar self.prescalar_spin.setOpts(value=1, dec=True, step=1, minStep=1, int=True) self.prescalar_spin.setMinimum(1) self.prescalar_spin.setMaximum(100) self.prescalar_spin.valueChanged.connect(self.prescaler_changed) # za nacin delovanja self.sld_amplituda.valueChanged[int].connect(self.ref_amp_changed) self.sld_amplituda.sliderReleased.connect(self.request_ref_params) self.ctrl_type.currentIndexChanged.connect(self.ctrl_type_changed) self.ctrl_dc_mode.currentIndexChanged.connect( self.ctrl_dc_mode_changed) self.amp_control.stateChanged.connect(self.amp_control_changed) # za filtriranje self.u_out_thd_f = 0.0 self.u_out_rms_f = 0.0 self.u_in_thd_f = 0.0 self.u_in_rms_f = 0.0 self.i_out_thd_f = 0.0 self.i_out_rms_f = 0.0 self.alpha = 0.1
def tab1UI(self): layout = QtGui.QGridLayout() layout.setHorizontalSpacing(2) """Layout widget definition""" self.win = pg.GraphicsLayoutWidget() self.label = pg.LabelItem(justify='right') self.win.addItem(self.label) self.tab1.setLayout(layout) """generate Components""" self.comboBoxCOM = QtGui.QComboBox() self.comboBoxCOM.addItems(bs_machine_bitlink.findBS()) self.comboBoxCOM.setStyleSheet( 'QComboBox {background-color: white; color:black;}') self.btnRunning = QtGui.QPushButton("", self) self.btnRunning.setCheckable(True) self.btnRunning.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnRunning.setStyleSheet('QPushButton {background: transparent}') self.btnRunning.setIcon(QtGui.QIcon('./Images/ledOFF.jpeg')) self.btnRunning.clicked.connect(self.running) # mode (do not change names) self.comboBoxMode = QtGui.QComboBox() self.comboBoxMode.addItem("Please Select") self.comboBoxMode.addItems( ["Dual", "Mixed", "SingleFast", "SingleMacro", "DualMacro"]) self.comboBoxMode.setStyleSheet('QComboBox {background-color: white}') self.comboBoxMode.currentIndexChanged.connect(self.modebtnPressed) # CHA and CHB self.btnChA = QtGui.QPushButton("CHA", self) self.btnChA.setStyleSheet( 'QPushButton {background-color: yellow; color:black;}') self.btnChA.setCheckable(True) self.btnChA.setEnabled(False) self.btnChA.clicked[bool].connect(self.btnChAPressed) self.btnChB = QtGui.QPushButton("CHB", self) self.btnChB.setStyleSheet( 'QPushButton {background-color: green; color:white}') self.btnChB.setCheckable(True) self.btnChB.setEnabled(False) self.btnChB.setChecked(False) self.btnChB.clicked[bool].connect(self.btnChBPressed) # Logic: Forget about iteration.. what's 'for'? self.btnL0 = QtGui.QPushButton("L0", self) self.btnL1 = QtGui.QPushButton("L1", self) self.btnL2 = QtGui.QPushButton("L2", self) self.btnL3 = QtGui.QPushButton("L3", self) self.btnL4 = QtGui.QPushButton("L4", self) self.btnL5 = QtGui.QPushButton("L5", self) self.btnL6 = QtGui.QPushButton("L6", self) self.btnL7 = QtGui.QPushButton("L7", self) # too many logic buttons self.btnL0.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL1.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL2.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL3.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL4.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL5.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL6.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL7.setFixedWidth(int(config['DEFAULT']['LogicBtnWidth'])) self.btnL0.setCheckable(True) self.btnL0.toggle() self.btnL0.setChecked(False) self.btnL0.setEnabled(False) self.btnL0.clicked.connect(self.buttonPressed) self.btnL1.setCheckable(True) self.btnL1.toggle() self.btnL1.setChecked(False) self.btnL1.setEnabled(False) self.btnL1.clicked.connect(self.buttonPressed) self.btnL2.setCheckable(True) self.btnL2.toggle() self.btnL2.setChecked(False) self.btnL2.setEnabled(False) self.btnL2.clicked.connect(self.buttonPressed) self.btnL3.setCheckable(True) self.btnL3.toggle() self.btnL3.setChecked(False) self.btnL3.setEnabled(False) self.btnL3.clicked.connect(self.buttonPressed) self.btnL4.setCheckable(True) self.btnL4.toggle() self.btnL4.setChecked(False) self.btnL4.setEnabled(False) self.btnL4.clicked.connect(self.buttonPressed) self.btnL5.setCheckable(True) self.btnL5.toggle() self.btnL5.setChecked(False) self.btnL5.setEnabled(False) self.btnL5.clicked.connect(self.buttonPressed) self.btnL6.setCheckable(True) self.btnL6.toggle() self.btnL6.setChecked(False) self.btnL6.setEnabled(False) self.btnL6.clicked.connect(self.buttonPressed) self.btnL7.setCheckable(True) self.btnL7.toggle() self.btnL7.setChecked(False) self.btnL7.setEnabled(False) self.btnL7.clicked.connect(self.buttonPressed) self.btnL0.setStyleSheet( 'QPushButton {background-color: purple; color:white}') self.btnL1.setStyleSheet( 'QPushButton {background-color: blue; color:white}') self.btnL2.setStyleSheet( 'QPushButton {background-color: cyan; color:black}') self.btnL3.setStyleSheet( 'QPushButton {background-color: magenta; color:black}') self.btnL4.setStyleSheet( 'QPushButton {background-color: orange; color:black}') self.btnL5.setStyleSheet( 'QPushButton {background-color: red; color:black}') self.btnL6.setStyleSheet( 'QPushButton {background-color: brown; color:black}') self.btnL7.setStyleSheet( 'QPushButton {background-color: grey; color:black}') #Sample rate self.samplerateLabel = QtGui.QLabel(" Clock setting", self) self.dialSR = QtGui.QDial(self) self.dialSR.setNotchesVisible(True) self.dialSR.setMinimum(int(config['DEFAULT']['SampleRateMin'])) self.dialSR.setMaximum(int(config['DEFAULT']['SampleRateMax'])) self.spinSR = QtGui.QSpinBox() self.spinSR.setMinimum(int(config['DEFAULT']['SampleRateMin'])) self.spinSR.setMaximum(int(config['DEFAULT']['SampleRateMax'])) self.dialSR.valueChanged.connect(self.spinSR.setValue) self.spinSR.valueChanged.connect(self.dialSR.setValue) self.spinSR.valueChanged.connect(self.buttonPressed) #Duration self.durationLabel = QtGui.QLabel(" Duration [sec]", self) self.dialDuration = QtGui.QDial() self.dialDuration.setNotchesVisible(True) self.spinDuration = QtGui.QSpinBox() self.dialDuration.setMinimum(int(config['DEFAULT']['DurationMin'])) self.dialDuration.setMaximum(int(config['DEFAULT']['DurationMax'])) self.spinDuration.setMinimum(int(config['DEFAULT']['DurationMin'])) self.spinDuration.setMaximum(int(config['DEFAULT']['DurationMax'])) self.dialDuration.valueChanged.connect(self.spinDuration.setValue) self.spinDuration.valueChanged.connect(self.dialDuration.setValue) self.spinDuration.valueChanged.connect(self.buttonPressed) self.spinDuration.setMinimum(int(config['DEFAULT']['DurationMin'])) self.spinDuration.setMaximum(int(config['DEFAULT']['DurationMax'])) #Buttons self.btnTest = QtGui.QPushButton("STOP", self) self.btnTest.setCheckable(True) self.btnTest.toggle() self.btnTest.setEnabled(True) self.btnTest.clicked.connect(self.stopTest) # Start,Stop,Reset self.btnStart = QtGui.QPushButton("START", self) self.btnStart.setEnabled(False) self.btnStart.clicked[bool].connect(self.startBtnPressed) self.btnFrameUpdate = QtGui.QPushButton("CONT_ON", self) self.btnFrameUpdate.setCheckable(True) self.btnFrameUpdate.setEnabled(False) self.btnFrameUpdate.clicked[bool].connect(self.timerToggle) self.btnRst = QtGui.QPushButton("RESET", self) self.btnRst.setCheckable(True) self.btnRst.setEnabled(False) self.btnRst.clicked[bool].connect(self.resetAll) self.btnUpdate = QtGui.QPushButton("UPDATE", self) self.btnUpdate.setEnabled(False) self.btnUpdate.setCheckable(True) self.btnUpdate.clicked.connect(self.updatePlot) # Toggle, Quit self.btnToggle = QtGui.QPushButton("TOGGLE", self) self.btnToggle.setCheckable(True) self.btnToggle.setEnabled(False) self.btnToggle.clicked.connect(self.buttonToggle) self.btnQuit = QtGui.QPushButton("QUIT", self) self.btnQuit.clicked.connect(QtCore.QCoreApplication.instance().quit) self.status = QtGui.QListWidget() self.status.setStyleSheet('QListWidget {font-size: 10px}') self.progressBar = QtGui.QProgressBar(self) self.progressBar.setStyleSheet( 'QProgressBar::chunk {background-color: #7799AA}') # Layout management #COMport and Macro layout.addWidget(self.comboBoxMode, 1, 2, 1, 7) layout.addWidget(self.btnRunning, 1, 1, 1, 1) layout.addWidget(self.comboBoxCOM, 2, 1, 1, 4) #Mode layout.addWidget(self.btnTest, 2, 5, 1, 4) #Row3: CHA and CHB layout.addWidget(self.btnChA, 3, 1, 1, 4) layout.addWidget(self.btnChB, 3, 5, 1, 4) #Logic layout.addWidget(self.btnL0, 4, 1, 1, 1) layout.addWidget(self.btnL1, 4, 2, 1, 1) layout.addWidget(self.btnL2, 4, 3, 1, 1) layout.addWidget(self.btnL3, 4, 4, 1, 1) layout.addWidget(self.btnL4, 4, 5, 1, 1) layout.addWidget(self.btnL5, 4, 6, 1, 1) layout.addWidget(self.btnL6, 4, 7, 1, 1) layout.addWidget(self.btnL7, 4, 8, 1, 1) #dials: Sample rate and buffer size Display layout.addWidget(self.samplerateLabel, 5, 1, 1, 4) layout.addWidget(self.durationLabel, 5, 5, 1, 4) #Sample rate and BufferSize layout.addWidget(self.dialSR, 6, 1, 1, 4) layout.addWidget(self.dialDuration, 6, 5, 1, 4) layout.addWidget(self.spinSR, 7, 1, 1, 4) layout.addWidget(self.spinDuration, 7, 5, 1, 4) #START, STOP, RESET layout.addWidget(self.btnStart, 8, 1, 1, 4) layout.addWidget(self.btnFrameUpdate, 8, 5, 1, 4) layout.addWidget(self.btnRst, 9, 1, 1, 4) layout.addWidget(self.btnUpdate, 9, 5, 1, 4) layout.addWidget(self.btnToggle, 10, 1, 1, 4) layout.addWidget(self.btnQuit, 10, 5, 1, 4) layout.addWidget(self.status, 11, 1, 2, 8) layout.addWidget(self.win, 1, 0, 12, 1) layout.addWidget(self.progressBar, 13, 0, 1, 9)
def __init__(self, topics=None, terms=None, addr=None, uiTemplate=None, parent=None, **kwargs): super().__init__(parent) self.node = kwargs.get("node", None) self.units = kwargs.get("units", {}) self.fetcher = None if addr: self.fetcher = AsyncFetcher(topics, terms, addr) self.plot_view = self.addPlot() if self.node: # node is passed in on subprocess self.viewbox_proxy = pg.SignalProxy( self.plot_view.vb.sigStateChanged, delay=1, slot=lambda args: self.node.sigStateChanged.emit(self.node), ) self.plot_view.showGrid(True, True) ax = self.plot_view.getAxis("bottom") ax.enableAutoSIPrefix(enable=bool(self.units)) ax.setZValue(100) ay = self.plot_view.getAxis("left") ay.enableAutoSIPrefix(enable=bool(self.units)) ay.setZValue(100) self.plot_view.setMenuEnabled(False) self.configure_btn = pg.ButtonItem(pg.pixmaps.getPixmap("ctrl"), 14, parentItem=self.plot_view) self.configure_btn.clicked.connect(self.configure_plot) self.configure_btn.show() self.plot = {} # { name : PlotDataItem } self.trace_ids = {} # { trace_idx : name } self.trace_attrs = {} self.legend_editors = {} self.annotation_editors = {} self.annotation_traces = {} self.terms = terms self.last_updated = pg.LabelItem(parent=self.plot_view) self.pixel_value = pg.LabelItem(parent=self.plot_view) self.hover_proxy = pg.SignalProxy(self.sceneObj.sigMouseMoved, rateLimit=30, slot=self.cursor_hover_evt) if uiTemplate is None: uiTemplate = [ ("Title", "text"), ("Show Grid", "check", { "checked": True }), ("Auto Range", "check", { "checked": True }), # x axis ("Label", "text", { "group": "X Axis" }), ("Log Scale", "check", { "group": "X Axis", "checked": False }), # y axis ("Label", "text", { "group": "Y Axis" }), ("Log Scale", "check", { "group": "Y Axis", "checked": False }), ] self.uiTemplate = uiTemplate self.ui, self.stateGroup, self.ctrls, self.plot_attrs = generateUi( self.uiTemplate) if self.stateGroup: self.stateGroup.sigChanged.connect(self.state_changed) ctrl_layout = self.ui.layout() self.legend = None if kwargs.get("legend", True): self.legend = self.plot_view.addLegend() self.legend_layout = QtGui.QFormLayout() self.legend_groupbox = QtWidgets.QGroupBox() self.legend_groupbox.setTitle("Legend") self.legend_groupbox.setLayout(self.legend_layout) ctrl_layout.addWidget(self.legend_groupbox) self.ctrls["Legend"] = self.legend_groupbox self.annotation_layout = QtGui.QFormLayout() self.annotation_groupbox = QtWidgets.QGroupBox() self.annotation_groupbox.setTitle("Annotations") self.annotation_groupbox.setLayout(self.annotation_layout) ctrl_layout.addWidget(self.annotation_groupbox) self.ctrls["Annotations"] = self.annotation_groupbox self.annotation_type = QtGui.QComboBox(parent=self.annotation_groupbox) self.annotation_type.addItem("Line", LineEditor) self.annotation_type.addItem("Circle", CircleEditor) self.annotation_type.addItem("Rect", RectEditor) self.annotation_layout.addWidget(self.annotation_type) self.add_annotation_btn = QtWidgets.QPushButton( "Add", self.annotation_groupbox) self.add_annotation_btn.clicked.connect(self.add_annotation) self.annotation_layout.addWidget(self.add_annotation_btn) self.apply_btn = QtWidgets.QPushButton("Apply", self.ui) self.apply_btn.clicked.connect(self.apply_clicked) ctrl_layout.addWidget(self.apply_btn) self.win = QtGui.QMainWindow() scrollArea = QtWidgets.QScrollArea(parent=self.win) scrollArea.setWidgetResizable(True) scrollArea.setWidget(self.ui) self.win.setCentralWidget(scrollArea) if self.node: self.win.setWindowTitle(self.node.name() + " configuration")
def home(self): # defines the home function (the main window) self.loaded_data = {} # ------ buttons + widgets ----------------------------- self.graph_settings_btn = QtWidgets.QPushButton("Graph Settings", self) self.graph_settings_btn.setToolTip( "Click if you want to add/remove waveforms, and edit the graph") self.score_btn = QtWidgets.QPushButton("Score", self) self.score_btn.setToolTip("Click if you want to score the EEG file") quit_btn = QtWidgets.QPushButton("Quit", self) quit_btn.clicked.connect(self.close_app) quit_btn.setShortcut("Ctrl+Q") quit_btn.setToolTip('Click to quit (or press Ctrl+Q)') self.TF_btn = QtWidgets.QPushButton("T-F Plots", self) self.TF_btn.setToolTip( "Click to open a window showing the Time-Frequency plots (Stockwell)" ) btn_layout = QtWidgets.QHBoxLayout() button_order = [ self.graph_settings_btn, self.score_btn, self.TF_btn, quit_btn ] for button in button_order: btn_layout.addWidget(button) # Version information ------------------------------------------- if getattr(sys, 'frozen', False): mod_date = time.ctime(os.path.getmtime( sys.executable)) # finds the modification date of the program vers_label = QtWidgets.QLabel( os.path.splitext(os.path.basename(sys.executable))[0] + " V1.1 - Last Updated: " + mod_date) else: mod_date = time.ctime(os.path.getmtime( __file__)) # finds the modification date of the program vers_label = QtWidgets.QLabel( os.path.splitext(os.path.basename(__file__))[0] + " V1.1 - Last Updated: " + mod_date) # ------------- grid layout ------------------------ self.main_window_parameters = [ 'Import Set', 'Set Filename:', '', '', '', '', '', ] self.main_window_fields = {} self.main_window_field_positions = {} positions = [(i, j) for i in range(2) for j in range(7)] self.main_window_layout = QtWidgets.QGridLayout() for (i, j), parameter in zip(positions, self.main_window_parameters): if parameter == '': continue else: self.main_window_field_positions[parameter] = (i, j) if 'Import' in parameter: self.main_window_fields[i, j] = QtWidgets.QPushButton( parameter, self) self.main_window_layout.addWidget( self.main_window_fields[i, j], *(i, j)) elif 'Set Filename' in parameter: self.main_window_fields[i, j] = QtWidgets.QLabel(parameter) self.main_window_fields[i, j].setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) self.main_window_fields[i, j + 1] = QtWidgets.QLineEdit() self.main_window_fields[i, j + 1].setAlignment( QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.main_window_fields[i, j + 1].setText('Import a Set file!') filename_layout = QtWidgets.QHBoxLayout() filename_layout.addWidget(self.main_window_fields[i, j]) filename_layout.addWidget(self.main_window_fields[i, j + 1]) self.main_window_layout.addLayout(filename_layout, i, j, 1, 3) # ------------------- setting the graph ----------------------- self.GraphLoaded = False self.graphics_window = pg.GraphicsWindow() self.Graph_label = pg.LabelItem( justify='right' ) # adds the Label that will be used for mouse interactions self.graphics_window.addItem(self.Graph_label) # adds the axis with custom viewbox to override the right click self.Graph_axis = self.graphics_window.addPlot( row=1, col=0, viewBox=CustomViewBox(self, self.graphics_window)) self.Graph_axis.hideButtons() self.vb = self.Graph_axis.vb self.Graph_axis.setMouseEnabled( x=False, y=False) # disables the mouse interactions self.Graph_axis.setLabel('bottom', "Time", units='ms') # adds the x label self.GraphLayout = QtWidgets.QVBoxLayout() self.GraphLayout.addLayout(self.main_window_layout) self.GraphLayout.addWidget(self.graphics_window) self.scrollbar = QtWidgets.QScrollBar(QtCore.Qt.Horizontal) self.scrollbar.actionTriggered.connect( functools.partial(self.changeCurrentGraph, 'scroll')) self.GraphLayout.addWidget(self.scrollbar) self.current_time = [] # -------------- graph settigns ------------------------------- self.graph_parameters = [ 'Window Size(ms):', '', 'Current Time(ms):', '', 'Start Time(ms):', '', 'Stop Time(ms):', '', 'Plot Spikes', '' ] self.graph_parameter_fields = {} self.graph_parameter_field_positions = {} positions = [(i, j) for i in range(1) for j in range(10)] self.graph_parameter_layout = QtWidgets.QGridLayout() for (i, j), parameter in zip(positions, self.graph_parameters): if parameter == '': continue else: self.graph_parameter_field_positions[parameter] = (i, j) if 'Plot' in parameter: self.graph_parameter_fields[ i, j + 1] = QtWidgets.QCheckBox(parameter) self.graph_parameter_layout.addWidget( self.graph_parameter_fields[i, j + 1], i, j + 1) else: self.graph_parameter_fields[i, j] = QtWidgets.QLabel( parameter) self.graph_parameter_layout.addWidget( self.graph_parameter_fields[i, j], *(i, j)) self.graph_parameter_fields[i, j + 1] = QtWidgets.QLineEdit() self.graph_parameter_fields[i, j + 1].setAlignment( QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.graph_parameter_layout.addWidget( self.graph_parameter_fields[i, j + 1], i, j + 1) if 'Window Size' in parameter: self.i_windowsize, self.j_windowsize = (i, j) self.graph_parameter_fields[i, j + 1].textChanged.connect( self.ChangeWindowSize) elif 'Amplitude' in parameter: pass elif 'Current Time' in parameter: self.i_current_time, self.j_current_time = (i, j) self.graph_parameter_fields[ i, j + 1].textChanged.connect( functools.partial(self.changeCurrentGraph, 'text')) elif 'Start Time' in parameter or 'Stop Time' in parameter: self.graph_parameter_fields[i, j + 1].textChanged.connect( self.changeEventTimes) # ------------- layout ------------------------------ layout = QtWidgets.QVBoxLayout() layout_order = [ self.GraphLayout, self.graph_parameter_layout, btn_layout ] for order in layout_order: if 'Layout' in order.__str__(): layout.addLayout(order) layout.addStretch(1) else: layout.addWidget(order, 0, QtCore.Qt.AlignCenter) layout.addStretch(1) layout.addStretch( 1) # adds stretch to put the version info at the buttom layout.addWidget( vers_label) # adds the date modification/version number self.setLayout(layout) center(self) self.show() self.set_parameters('Default')
def initplotTick(self): """""" global chan chan = Chan([], [], [], [], [], []) for index in range(0, len(self.listBar)): chan.append(self.listOpen[index], self.listHigh[index], self.listLow[index], self.listClose[index], self.listOpenInterest[index], self.listTimes[index]) if (chan.length > 26): chan.barsMerge() chan.findFenxing() chan.findBi() chan.findLines() chan.findZhongshus() chan.calculate_ta() chan.findBiZhongshus() chan.macdSeparate() chan.findTrendLines() chan.decisionBi() win = pg.GraphicsWindow() win.setWindowTitle('行情+缠论') label = pg.LabelItem(justify="center") win.addItem(label) axis = self.DateAxis(self.listTimes, orientation='bottom') p1 = win.addPlot(row=1, col=0, axisItems={'bottom': axis}) p2 = win.addPlot(row=2, col=0, axisItems={'bottom': axis}) p2.setXLink(p1) p2.plot(x=list(range(len(self.listBar))), y=chan.diff, pen='w') p2.plot(x=list(range(len(self.listBar))), y=chan.dea, pen='y') hLine = pg.InfiniteLine(angle=0, movable=False) hLine.setPos(0) p2.addItem(hLine, ignoreBounds=True) macdPositive = [] macdNegetive = [] for i in chan.macd: if i >= 0: macdPositive.append(i) macdNegetive.append(0) else: macdPositive.append(0) macdNegetive.append(i) self.curve0 = p2.plot(x=list(range(len(self.listBar))), y=np.zeros(len(self.listBar))) self.curve1 = p2.plot(x=list(range(len(self.listBar))), y=macdPositive, pen='w') self.curve2 = p2.plot(x=list(range(len(self.listBar))), y=macdNegetive, pen='w') self.itemFill1 = pg.FillBetweenItem(self.curve0, self.curve1, pg.mkBrush('r')) self.itemFill2 = pg.FillBetweenItem(self.curve0, self.curve2, pg.mkBrush('g')) p2.addItem(self.itemFill1) p2.addItem(self.itemFill2) self.itemK = self.CandlestickItem() self.itemK.set_data(self.listBar) self.itemBi = self.BisItem() self.itemBi.set_data(chan.bis) self.itemLine = self.LinesItem() self.itemLine.set_data(chan.lines) self.itemZhongshu = self.ZhongshusItem() #itemZhongshu.set_data(chan.zhongshus) self.itemZhongshu.set_data(chan.biZhongshus) # self.itemDiBeiChi = self.BeiChiItem() # self.itemDiBeiChi.set_data(chan.dibeichi) # self.itemDingBeiChi = self.BeiChiItem() # self.itemDingBeiChi.set_data(chan.dingbeichiLine) # self.itemTrendDiBeiChi = self.BeiChiItem() # self.itemTrendDiBeiChi.set_data(chan.trendDibeichi) # self.itemTrendDingBeiChi = self.BeiChiItem() # self.itemTrendDingBeiChi.set_data(chan.trendDingbeichi) p1.plot() p1.addItem(self.itemK) p1.addItem(self.itemBi) p1.addItem(self.itemLine) p1.addItem(self.itemZhongshu) # p1.addItem(self.itemDiBeiChi) # p1.addItem(self.itemDingBeiChi) # p1.addItem(self.itemTrendDiBeiChi) # p1.addItem(self.itemTrendDingBeiChi) p1.showGrid(x=True, y=True) #p1.setWindowTitle('pyqtgraph example: customGraphicsItem') # cross hair vLine = pg.InfiniteLine(angle=90, movable=False) hLine = pg.InfiniteLine(angle=0, movable=False) p1.addItem(vLine, ignoreBounds=True) p1.addItem(hLine, ignoreBounds=True) vb1 = p1.vb vb2 = p2.vb def mouseMoved(evt): pos = evt[ 0] # using signal proxy turns original arguments into a tuple if p1.sceneBoundingRect().contains(pos): mousePoint = vb1.mapSceneToView(pos) index = int(mousePoint.x()) if index > 0 and index < len(self.listBar): label.setText( "<span style='font-size: 12pt'>date=%d, <span style='color: red'>open=%0.01f</span>, <span style='color: green'>close=%0.01f\n, high = %0.01f, low = %0.01f</span>" % (self.listTimes[index], self.listBar[index][1], self.listBar[index][2], self.listBar[index][3], self.listBar[index][4])) vLine.setPos(mousePoint.x()) hLine.setPos(mousePoint.y()) setYRange() def setYRange(): r = vb1.viewRange() xmin = math.floor(r[0][0]) xmax = math.ceil(r[0][1]) #fix index <0 bug xmax = max(0, xmax - xmin) xmin = max(0, xmin) xmin = min(xmin, len(self.listBar)) xmax = min(xmax, len(self.listBar)) xmax = max(xmin, xmax) if (xmin == xmax): return if (len(self.listBar)): highBound1 = max(self.listHigh[xmin:xmax]) lowBound1 = min(self.listLow[xmin:xmax]) p1.setRange(yRange=(lowBound1, highBound1)) if (len(self.chan.diff)): highBound2 = max(self.chan.diff[xmin:xmax]) lowBound2 = min(self.chan.diff[xmin:xmax]) p2.setRange(yRange=(lowBound2, highBound2)) self.proxy = pg.SignalProxy(p1.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved) self.win = win self.p1 = p1 self.p2 = p2 self.chan = chan self.axis = axis
def __init__(self, tvar_name, show_xaxis=False, mouse_function=None): self.tvar_name = tvar_name self.show_xaxis = show_xaxis self.crosshair = pytplot.tplot_opt_glob['crosshair'] # Sets up the layout of the Tplot Object pg.GraphicsLayout.__init__(self) self.layout.setHorizontalSpacing(50) self.layout.setContentsMargins(0, 0, 0, 0) # Set up the x axis self.xaxis = pg.AxisItem(orientation='bottom') self.xaxis.setHeight(35) self.xaxis.enableAutoSIPrefix(enable=False) # Set up the y axis self.yaxis = AxisItem("left") self.yaxis.setWidth(100) vb = NoPaddingPlot() self.plotwindow = self.addPlot(row=0, col=0, axisItems={ 'bottom': self.xaxis, 'left': self.yaxis }, viewBox=vb) self.plotwindow.vb.setLimits(xMin=0, xMax=360, yMin=-90, yMax=90) # Set up the view box needed for the legends self.legendvb = pg.ViewBox(enableMouse=False) self.legendvb.setMaximumWidth(100) self.legendvb.setXRange(0, 1, padding=0) self.legendvb.setYRange(0, 1, padding=0) self.addItem(self.legendvb, 0, 1) self.curves = [] self.colors = self._setcolors() self.colormap = self._setcolormap() self.labelStyle = { 'font-size': str(pytplot.data_quants[self.tvar_name].extras['char_size']) + 'pt' } if show_xaxis: self.plotwindow.showAxis('bottom') else: self.plotwindow.hideAxis('bottom') self._mouseMovedFunction = mouse_function self.label = pg.LabelItem(justify='left') self.addItem(self.label, row=1, col=0) # Set legend options self.hoverlegend = CustomLegendItem(offset=(0, 0)) self.hoverlegend.setItem("Date: ", "0") self.hoverlegend.setItem("Time: ", "0") self.hoverlegend.setItem("Latitude:", "0") self.hoverlegend.setItem("Longitude:", "0") self.hoverlegend.setVisible(False) self.hoverlegend.setParentItem(self.plotwindow.vb)
if qc_sweeps > sweep_threshold: avg_first_pulse = trace_avg(qc_list) avg_first_pulse.t0 = 0 if plot_sweeps is True: for current_sweep in qc_list: current_sweep.t0 = 0 bsub_trace = bsub(current_sweep) trace_plot(bsub_trace, sweep_color, plot=grid[row, 0], x_range=[-2e-3, 27e-3]) trace_plot(avg_first_pulse, avg_color, plot=grid[row, 0], x_range=[-2e-3, 27e-3]) label = pg.LabelItem('%s, n = %d' % (connection_type, qc_sweeps)) label.setParentItem(grid[row, 0].vb) label.setPos(50, 0) maxYpulse.append((row, grid[row, 0].getAxis('left').range[1])) grid[row, 0].hideAxis('bottom') _, _, _, peak_t = get_amplitude(qc_list) all_amps = np.asarray(fail_rate(qc_list, sign=sign, peak_t=peak_t)) # y = pg.pseudoScatter(all_amps, spacing=0.15) # test[row, 0].plot(all_amps, y, pen=None, symbol='o', symbolSize=8, symbolPen=(255, 255, 255, 200), symbolBrush=(0, 0, 255, 150)) y, x = np.histogram(all_amps, bins=np.linspace(0, 2e-3, 40)) test[row, 0].plot(x, y, stepMode=True, fillLevel=0, brush='k') test[row, 0].setLabels(bottom=('Vm', 'V')) test[row, 0].setXRange(0, 2e-3) else: print("%s -> %s not enough sweeps for first pulse" %
def add(self, plots): # e.g.: plots.add(exp.enumerate_plots()) plotsize = None for plot in plots: # check if panel exists. there's a different panel for each x coordinate (e.g. iterations, time) panel_id = (plot['panel'], plot['x']) if panel_id not in self.panels: # create new panel to contain plot. # if title not defined, use the panel ID (e.g. stat name) title = str(plot.get('title', plot['panel'])) plot_widget = create_plot_widget(title) panel = self.window.add_panel(plot_widget, title) panel.plots_dict = {} # set up mouse move event plot_widget.mouseMoveEvent = partial(mouse_move, panel=panel) plot_widget.leaveEvent = partial(mouse_leave, panel=panel) # mouse cursor (vertical line) vline = pg.InfiniteLine(angle=90, pen="#B0B0B0") vline.setVisible(False) plot_widget.getPlotItem().addItem( vline, ignoreBounds=True) # ensure it doesn't mess autorange panel.cursor_vline = vline # mouse cursor text label = pg.LabelItem(justify='left') label.setParentItem(plot_widget.getPlotItem().getViewBox()) label.anchor(itemPos=(0, 0), parentPos=(0, 0)) panel.cursor_label = label self.panels[panel_id] = panel else: panel = self.panels[panel_id] # reuse existing panel # get data points exp = plot['exp'] (xs, ys) = (exp.data[exp.names.index(plot['x'])], exp.data[exp.names.index(plot['y'])]) # allow overriding the style style = exp.style if 'color' in plot: style['color'] = plot['color'] if 'width' in plot: style['width'] = plot['width'] if 'dash' in plot and plot['dash'] in dashes_by_name: style['style'] = dashes_by_name[plot['dash']] try: pen = pg.mkPen(style) except: # if the style is malformed, use the default style pen = pg.mkPen(exp.style) # check if plot line already exists if plot['line'] not in panel.plots_dict: # create new line line = panel.plot_widget.getPlotItem().plot(xs, ys, pen=pen) line.curve.setClickable(True, 8) # size of hover region line.mouse_over = False panel.plots_dict[plot['line']] = line else: # update existing one line = panel.plots_dict[plot['line']] line.setData(xs, ys) line.setPen(pen)
def init_figures(self): """ Create all figures that will be added to the GUI """ # Figures to show ephys data # 2D scatter/ image plot self.fig_img = pg.PlotItem() self.fig_img.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.fig_img.addLine(y=self.probe_tip, pen=self.kpen_dot, z=50) self.fig_img.addLine(y=self.probe_top, pen=self.kpen_dot, z=50) self.set_axis(self.fig_img, 'bottom') self.fig_data_ax = self.set_axis(self.fig_img, 'left', label='Distance from probe tip (uV)') self.fig_img_cb = pg.PlotItem() self.fig_img_cb.setMaximumHeight(70) self.fig_img_cb.setMouseEnabled(x=False, y=False) self.set_axis(self.fig_img_cb, 'bottom', show=False) self.set_axis(self.fig_img_cb, 'left', pen='w') self.set_axis(self.fig_img_cb, 'top', pen='w') # 1D line plot self.fig_line = pg.PlotItem() self.fig_line.setMouseEnabled(x=False, y=False) self.fig_line.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.fig_line.addLine(y=self.probe_tip, pen=self.kpen_dot, z=50) self.fig_line.addLine(y=self.probe_top, pen=self.kpen_dot, z=50) self.set_axis(self.fig_line, 'bottom') self.set_axis(self.fig_line, 'left', show=False) # 2D probe plot self.fig_probe = pg.PlotItem() self.fig_probe.setMouseEnabled(x=False, y=False) self.fig_probe.setMaximumWidth(50) self.fig_probe.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.fig_probe.addLine(y=self.probe_tip, pen=self.kpen_dot, z=50) self.fig_probe.addLine(y=self.probe_top, pen=self.kpen_dot, z=50) self.set_axis(self.fig_probe, 'bottom', pen='w') self.set_axis(self.fig_probe, 'left', show=False) self.fig_probe_cb = pg.PlotItem() self.fig_probe_cb.setMouseEnabled(x=False, y=False) self.fig_probe_cb.setMaximumHeight(70) self.set_axis(self.fig_probe_cb, 'bottom', show=False) self.set_axis(self.fig_probe_cb, 'left', show=False) self.set_axis(self.fig_probe_cb, 'top', pen='w') # Add img plot, line plot, probe plot, img colourbar and probe colourbar to a graphics # layout widget so plots can be arranged and moved easily self.fig_data_area = pg.GraphicsLayoutWidget() self.fig_data_area.scene().sigMouseClicked.connect(self.on_mouse_double_clicked) self.fig_data_area.scene().sigMouseHover.connect(self.on_mouse_hover) self.fig_data_layout = pg.GraphicsLayout() self.fig_data_layout.addItem(self.fig_img_cb, 0, 0) self.fig_data_layout.addItem(self.fig_probe_cb, 0, 1, 1, 2) self.fig_data_layout.addItem(self.fig_img, 1, 0) self.fig_data_layout.addItem(self.fig_line, 1, 1) self.fig_data_layout.addItem(self.fig_probe, 1, 2) self.fig_data_layout.layout.setColumnStretchFactor(0, 6) self.fig_data_layout.layout.setColumnStretchFactor(1, 2) self.fig_data_layout.layout.setColumnStretchFactor(2, 1) self.fig_data_layout.layout.setRowStretchFactor(0, 1) self.fig_data_layout.layout.setRowStretchFactor(1, 10) self.fig_data_area.addItem(self.fig_data_layout) # Figures to show histology data # Histology figure that will be updated with user input self.fig_hist = pg.PlotItem() self.fig_hist.setContentsMargins(0, 0, 0, 0) self.fig_hist.setMouseEnabled(x=False) self.fig_hist.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.set_axis(self.fig_hist, 'bottom', pen='w', ticks=False) self.ax_hist = self.set_axis(self.fig_hist, 'left', pen=None) self.ax_hist.setWidth(0) self.ax_hist.setStyle(tickTextOffset=-70) self.fig_scale = pg.PlotItem() self.fig_scale.setMaximumWidth(50) self.fig_scale.setMouseEnabled(x=False) self.scale_label = pg.LabelItem(color='k') self.set_axis(self.fig_scale, 'bottom', pen='w', ticks=False) self.set_axis(self.fig_scale, 'left', show=False) (self.fig_scale).setYLink(self.fig_hist) # Figure that will show scale factor of histology boundaries self.fig_scale_cb = pg.PlotItem() self.fig_scale_cb.setMouseEnabled(x=False, y=False) self.fig_scale_cb.setMaximumHeight(70) self.set_axis(self.fig_scale_cb, 'bottom', show=False) self.set_axis(self.fig_scale_cb, 'left', show=False) self.fig_scale_ax = self.set_axis(self.fig_scale_cb, 'top', pen='w') self.set_axis(self.fig_scale_cb, 'right', show=False) # Histology figure that will remain at initial state for reference self.fig_hist_ref = pg.PlotItem() self.fig_hist_ref.setMouseEnabled(x=False) self.fig_hist_ref.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.set_axis(self.fig_hist_ref, 'bottom', pen='w') self.set_axis(self.fig_hist_ref, 'left', show=False) self.ax_hist_ref = self.set_axis(self.fig_hist_ref, 'right', pen=None) self.ax_hist_ref.setWidth(0) self.ax_hist_ref.setStyle(tickTextOffset=-70) self.fig_hist_area = pg.GraphicsLayoutWidget() self.fig_hist_area.setMouseTracking(True) self.fig_hist_area.scene().sigMouseClicked.connect(self.on_mouse_double_clicked) self.fig_hist_area.scene().sigMouseHover.connect(self.on_mouse_hover) self.fig_hist_extra_yaxis = pg.PlotItem() self.fig_hist_extra_yaxis.setMouseEnabled(x=False, y=False) self.fig_hist_extra_yaxis.setMaximumWidth(2) self.fig_hist_extra_yaxis.setYRange(min=self.probe_tip - self.probe_extra, max=self.probe_top + self.probe_extra, padding=self.pad) self.set_axis(self.fig_hist_extra_yaxis, 'bottom', pen='w') self.ax_hist2 = self.set_axis(self.fig_hist_extra_yaxis, 'left', pen=None) self.ax_hist2.setWidth(10) self.fig_hist_layout = pg.GraphicsLayout() self.fig_hist_layout.addItem(self.fig_scale_cb, 0, 0, 1, 4) self.fig_hist_layout.addItem(self.fig_hist_extra_yaxis, 1, 0) self.fig_hist_layout.addItem(self.fig_hist, 1, 1) self.fig_hist_layout.addItem(self.fig_scale, 1, 2) self.fig_hist_layout.addItem(self.fig_hist_ref, 1, 3) self.fig_hist_layout.layout.setColumnStretchFactor(0, 1) self.fig_hist_layout.layout.setColumnStretchFactor(1, 4) self.fig_hist_layout.layout.setColumnStretchFactor(2, 1) self.fig_hist_layout.layout.setColumnStretchFactor(3, 4) self.fig_hist_layout.layout.setRowStretchFactor(0, 1) self.fig_hist_layout.layout.setRowStretchFactor(1, 10) self.fig_hist_area.addItem(self.fig_hist_layout) # Figure to show coronal slice through the brain self.fig_slice_area = pg.GraphicsLayoutWidget() self.fig_slice_layout = pg.GraphicsLayout() self.fig_slice_hist_alt = pg.ViewBox() self.fig_slice = pg.ViewBox() self.fig_slice_layout.addItem(self.fig_slice, 0, 0) self.fig_slice_layout.addItem(self.fig_slice_hist_alt, 0, 1) self.fig_slice_layout.layout.setColumnStretchFactor(0, 3) self.fig_slice_layout.layout.setColumnStretchFactor(1, 1) self.fig_slice_area.addItem(self.fig_slice_layout) self.slice_item = self.fig_slice_hist_alt # Figure to show fit and offset applied by user self.fig_fit = pg.PlotWidget(background='w') self.fig_fit.setMouseEnabled(x=False, y=False) self.fig_fit_exporter = pg.exporters.ImageExporter(self.fig_fit.plotItem) self.fig_fit.sigDeviceRangeChanged.connect(self.on_fig_size_changed) self.fig_fit.setXRange(min=self.view_total[0], max=self.view_total[1]) self.fig_fit.setYRange(min=self.view_total[0], max=self.view_total[1]) self.set_axis(self.fig_fit, 'bottom', label='Original coordinates (um)') self.set_axis(self.fig_fit, 'left', label='New coordinates (um)') plot = pg.PlotCurveItem() plot.setData(x=self.depth, y=self.depth, pen=self.kpen_dot) self.fit_plot = pg.PlotCurveItem(pen=self.bpen_solid) self.fit_scatter = pg.ScatterPlotItem(size=7, symbol='o', brush='w', pen='b') self.fit_plot_lin = pg.PlotCurveItem(pen=self.rpen_dot) self.fig_fit.addItem(plot) self.fig_fit.addItem(self.fit_plot) self.fig_fit.addItem(self.fit_plot_lin) self.fig_fit.addItem(self.fit_scatter) self.lin_fit_option = QtGui.QCheckBox('Linear fit', self.fig_fit) self.lin_fit_option.setChecked(True) self.lin_fit_option.stateChanged.connect(self.lin_fit_option_changed) self.on_fig_size_changed()
quiets = [ categorized_series_from_file(f"data/{datadir}/{f}.q", 1, [int], 0, [1]) for f in tqdm(range(n_files)) ] # Close spectral density analysis plot crit_freq_plot.close() # Add new plots, reset counter and rebind buttons dur_a_plot = LinearRegionPlot(2, title="durations v area") q_pdf_plot = LinearRegionPlot(6, title="pdf of quiet-times") dur_pdf_plot = LinearRegionPlot(6, title="pdf of durations") a_pdf_plot = LinearRegionPlot(6, title="pdf of areas") btn_runfile = Button("Lock and finish for current file") text = pg.LabelItem() win.removeItem(crit_freq_plot) win.removeItem(btn_next) win.removeItem(btn_run) btn_next.sigPressed.disconnect() btn_run.sigPressed.disconnect() counter = 1 win.addItem(text, row=0, col=0, colspan=3) win.addItem(btn_next, row=3, col=0, colspan=3) win.addItem(btn_run, row=5, col=0, colspan=3) win.addItem(btn_runfile, row=4, col=0, colspan=3) win.addItem(a_pdf_plot, row=1, col=0) win.addItem(dur_pdf_plot, row=1, col=1)
def initUI(self): pg.setConfigOption('background', 'w') self.actual_dir = os.getcwd() self.lblTit = pg.LabelItem(justify='right') # self.lblTit.setText("Hola") #Variables self.data_dir = '' self.result_dir = '' self.nom_dir = [] self.nom_arch = [] self.nom_facil = [] self.sizes = np.asarray([120, 60, 30, 15, 7.5, 3.75, 1.875, 0.9375]) buttons = QHBoxLayout() datos = QVBoxLayout() contain = QSplitter(Qt.Horizontal) ima = QVBoxLayout() self.glw = pg.GraphicsLayoutWidget(border=(100, 100, 100)) self.glw.useOpenGL(True) self.glw.addItem(self.lblTit, col=1, colspan=4) self.glw.nextRow() self.glw.addLabel('Canales', angle=-90, rowspan=3) vtick = QPainterPath() vtick.moveTo(0, -0.5) vtick.lineTo(0, 0.5) vtick.addRect(0, 0.5, 1, 1) s1 = pg.ScatterPlotItem(pxMode=False) s1.setSymbol(vtick) s1.setSize(1) s2 = pg.ScatterPlotItem(pxMode=False) s2.setSymbol(vtick) s2.setSize(1) s3 = pg.ScatterPlotItem(pxMode=False) s3.setSymbol(vtick) s3.setSize(1) # s3.setPen=(QColor(*np.random.randint(0, 255 + 1, 3).tolist())) s4 = pg.ScatterPlotItem(pxMode=False) s4.setSymbol(vtick) s4.setSize(1) s5 = pg.ScatterPlotItem(pxMode=False) s5.setSymbol(vtick) s5.setSize(1) s6 = pg.ScatterPlotItem(pxMode=False) s6.setSymbol(vtick) s6.setSize(1) s7 = pg.ScatterPlotItem(pxMode=False) s7.setSymbol(vtick) s7.setSize(1) s8 = pg.ScatterPlotItem(pxMode=False) s8.setSymbol(vtick) s8.setSize(1) s9 = pg.ScatterPlotItem(pxMode=False) s9.setSymbol(vtick) s9.setSize(1) s10 = pg.ScatterPlotItem(pxMode=False) s10.setSymbol(vtick) s10.setSize(1) s11 = pg.ScatterPlotItem(pxMode=False) s11.setSymbol(vtick) s11.setSize(1) s12 = pg.ScatterPlotItem(pxMode=False) s12.setSymbol(vtick) s12.setSize(1) s13 = pg.ScatterPlotItem(pxMode=False) s13.setSymbol(vtick) s13.setSize(1) s14 = pg.ScatterPlotItem(pxMode=False) s14.setSymbol(vtick) s14.setSize(1) s15 = pg.ScatterPlotItem(pxMode=False) s15.setSymbol(vtick) s15.setSize(1) s16 = pg.ScatterPlotItem(pxMode=False) s16.setSymbol(vtick) s16.setSize(1) s17 = pg.ScatterPlotItem(pxMode=False) s17.setSymbol(vtick) s17.setSize(1) s18 = pg.ScatterPlotItem(pxMode=False) s18.setSymbol(vtick) s18.setSize(1) s19 = pg.ScatterPlotItem(pxMode=False) s19.setSymbol(vtick) s19.setSize(1) s20 = pg.ScatterPlotItem(pxMode=False) s20.setSymbol(vtick) s20.setSize(1) s21 = pg.ScatterPlotItem(pxMode=False) s21.setSymbol(vtick) s21.setSize(1) s22 = pg.ScatterPlotItem(pxMode=False) s22.setSymbol(vtick) s22.setSize(1) y = [ '0', 'EMG', 'ROG', 'LOG', 'T6', 'T5', 'T4', 'T3', 'PZ', 'P4', 'P3', 'O2', 'O1', 'FZ', 'FP2', 'FP1', 'F8', 'F7', 'F4', 'F3', 'CZ', 'C4', 'C3' ] ydict = dict(enumerate(y)) stringaxis = pg.AxisItem(orientation='left') stringaxis.setTicks([ydict.items()]) self.p1 = self.glw.addPlot(axisItems={'left': stringaxis}, row=1, col=1) # self.p2 = self.glw.addPlot(col=0) # self.p1.setYRange(-0.5, 26.5, padding=0) self.p1.setLimits(yMin=-0.5) self.p1.setLimits(yMax=26.5) self.p1.addItem(s1) self.p1.addItem(s2) self.p1.addItem(s3) self.p1.addItem(s4) self.p1.addItem(s5) self.p1.addItem(s6) self.p1.addItem(s7) self.p1.addItem(s8) self.p1.addItem(s9) self.p1.addItem(s10) self.p1.addItem(s11) self.p1.addItem(s12) self.p1.addItem(s13) self.p1.addItem(s14) self.p1.addItem(s15) self.p1.addItem(s16) self.p1.addItem(s17) self.p1.addItem(s18) self.p1.addItem(s19) self.p1.addItem(s20) self.p1.addItem(s21) self.p1.addItem(s22) self.spis = [ s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22 ] self.lytEpoch = QFormLayout() self.cmbEpoch = QComboBox() self.cmbEpoch.addItem("120") self.cmbEpoch.addItem("60") self.cmbEpoch.addItem("30") self.cmbEpoch.addItem("15") self.cmbEpoch.addItem("7.5") self.cmbEpoch.addItem("3.75") self.cmbEpoch.addItem("1.875") self.cmbEpoch.addItem("0.9375") self.lytEpoch.addRow("Epoch size: ", self.cmbEpoch) btn_data_dir = QPushButton('Load Files') btn_data_dir.clicked.connect(lambda: self.openFiles(1)) btn_result_dir = QPushButton('Save Results') btn_result_dir.clicked.connect(lambda: self.openFiles(2)) btn_do = QPushButton('Do') btn_do.clicked.connect(self.llenarTabla) self.table = QTableWidget() btn_make = QPushButton('Processing') btn_make.clicked.connect(self.showDialog) btn_showSujeto = QPushButton('Sujeto') btn_showSujeto.clicked.connect(self.recuperaSujeto) datos.addLayout(self.lytEpoch) buttons.addWidget(btn_data_dir) buttons.addWidget(btn_result_dir) buttons.addWidget(btn_do) datos.addLayout(buttons) datos.addWidget(self.table) datos.addWidget(btn_make) datos.addWidget(btn_showSujeto) ima.addWidget(self.glw) bot = QWidget() bot.setLayout(datos) gra = QWidget() gra.setLayout(ima) contain.addWidget(bot) contain.addWidget(gra) self.addWidget(contain)
def __init__(self, tvar_name, show_xaxis=False, mouse_function=None): self.tvar_name = tvar_name self.show_xaxis = show_xaxis self.crosshair = pytplot.tplot_opt_glob['crosshair'] # Sets up the layout of the Tplot Object pg.GraphicsLayout.__init__(self) self.layout.setHorizontalSpacing(50) self.layout.setContentsMargins(0, 0, 0, 0) # Set up the x axis self.xaxis = pg.AxisItem(orientation='bottom') self.xaxis.setHeight(35) self.xaxis.enableAutoSIPrefix(enable=False) # Set up the y axis self.yaxis = AxisItem("left") self.yaxis.setWidth(100) vb = NoPaddingPlot() self.plotwindow = self.addPlot(row=0, col=0, axisItems={ 'bottom': self.xaxis, 'left': self.yaxis }, viewBox=vb) # Set up the view box needed for the legends self.legendvb = pg.ViewBox(enableMouse=False) self.legendvb.setMaximumWidth(100) self.legendvb.setXRange(0, 1, padding=0) self.legendvb.setYRange(0, 1, padding=0) self.addItem(self.legendvb, 0, 1) self.curves = [] self.colors = self._setcolors() self.colormap = self._setcolormap() if pytplot.tplot_opt_glob['black_background']: self.labelStyle = { 'font-size': str(pytplot.data_quants[self.tvar_name].attrs['plot_options'] ['extras']['char_size']) + 'pt', 'color': '#FFF' } else: self.labelStyle = { 'font-size': str(pytplot.data_quants[self.tvar_name].attrs['plot_options'] ['extras']['char_size']) + 'pt', 'color': '#000' } if show_xaxis: self.plotwindow.showAxis('bottom') else: self.plotwindow.hideAxis('bottom') self._mouseMovedFunction = mouse_function self.vLine = pg.InfiniteLine(angle=90, movable=False, pen=pg.mkPen('k')) self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('k')) self.plotwindow.addItem(self.vLine, ignoreBounds=True) self.plotwindow.addItem(self.hLine, ignoreBounds=True) self.vLine.setVisible(False) self.hLine.setVisible(False) self.label = pg.LabelItem(justify='left') self.addItem(self.label, row=1, col=0) # Set legend options self.hoverlegend = CustomLegendItem(offset=(0, 0)) # Allow the user to set x-axis(time) and y-axis data names in crosshairs self.hoverlegend.setItem( pytplot.data_quants[self.tvar_name].attrs['plot_options'] ['xaxis_opt']['crosshair'] + ':', "0") self.hoverlegend.setItem( pytplot.data_quants[self.tvar_name].attrs['plot_options'] ['yaxis_opt']['crosshair'] + ':', "0") self.hoverlegend.setVisible(False) self.hoverlegend.setParentItem(self.plotwindow.vb)
def __init__(self, collector, parent=None): """ Constructor. See AbstractInspector constructor for parameters. """ super(PgImagePlot2d, self).__init__(collector, parent=parent) # The sliced array is kept in memory. This may be different per inspector, e.g. 3D # inspectors may decide that this uses to much memory. The slice is therefor not stored # in the collector. self.slicedArray = None self.titleLabel = pg.LabelItem('title goes here...') # The image item self.imagePlotItem = ArgosPgPlotItem() self.viewBox = self.imagePlotItem.getViewBox() self.viewBox.disableAutoRange(BOTH_AXES) self.imageItem = pg.ImageItem() self.imageItem.setPos( -0.5, -0.5) # Center on pixels (see pg.ImageView.setImage source code) self.imagePlotItem.addItem(self.imageItem) self.histLutItem = HistogramLUTItem() # what about GradientLegend? # self.histLutItem.region.setBrush("#FF006632") # for line in self.histLutItem.region.lines: # line.setPen(color=("#FF0066")) self.histLutItem.setImageItem(self.imageItem) self.histLutItem.vb.setMenuEnabled(False) self.histLutItem.setHistogramRange(0, 100) # Disables autoscaling # Probe and cross hair plots self.crossPlotRow = None # the row coordinate of the cross hair. None if no cross hair. self.crossPlotCol = None # the col coordinate of the cross hair. None if no cross hair. self.horCrossPlotItem = ArgosPgPlotItem() self.verCrossPlotItem = ArgosPgPlotItem() self.horCrossPlotItem.setXLink(self.imagePlotItem) self.verCrossPlotItem.setYLink(self.imagePlotItem) self.horCrossPlotItem.setLabel('left', ' ') self.verCrossPlotItem.setLabel('bottom', ' ') self.horCrossPlotItem.showAxis('top', True) self.horCrossPlotItem.showAxis('bottom', False) self.verCrossPlotItem.showAxis('right', True) self.verCrossPlotItem.showAxis('left', False) self.crossPen = pg.mkPen("#BFBFBF") self.crossShadowPen = pg.mkPen([0, 0, 0, 100], width=3) self.crossLineHorShadow = pg.InfiniteLine(angle=0, movable=False, pen=self.crossShadowPen) self.crossLineVerShadow = pg.InfiniteLine(angle=90, movable=False, pen=self.crossShadowPen) self.crossLineHorizontal = pg.InfiniteLine(angle=0, movable=False, pen=self.crossPen) self.crossLineVertical = pg.InfiniteLine(angle=90, movable=False, pen=self.crossPen) self.imagePlotItem.addItem(self.crossLineVerShadow, ignoreBounds=True) self.imagePlotItem.addItem(self.crossLineHorShadow, ignoreBounds=True) self.imagePlotItem.addItem(self.crossLineVertical, ignoreBounds=True) self.imagePlotItem.addItem(self.crossLineHorizontal, ignoreBounds=True) self.probeLabel = pg.LabelItem('', justify='left') # Layout # Hiding the horCrossPlotItem and horCrossPlotItem will still leave some space in the # grid layout. We therefore remove them from the layout instead. We need to know if they # are already added. self.horPlotAdded = False self.verPlotAdded = False self.graphicsLayoutWidget = pg.GraphicsLayoutWidget() self.contentsLayout.addWidget(self.graphicsLayoutWidget) self.graphicsLayoutWidget.addItem(self.titleLabel, ROW_TITLE, COL_TITLE, colspan=3) self.graphicsLayoutWidget.addItem(self.histLutItem, ROW_COLOR, COL_COLOR, rowspan=2) self.graphicsLayoutWidget.addItem(self.imagePlotItem, ROW_IMAGE, COL_IMAGE) self.graphicsLayoutWidget.addItem(self.probeLabel, ROW_PROBE, COL_PROBE, colspan=3) gridLayout = self.graphicsLayoutWidget.ci.layout # A QGraphicsGridLayout gridLayout.setHorizontalSpacing(10) gridLayout.setVerticalSpacing(10) #gridLayout.setRowSpacing(ROW_PROBE, 40) gridLayout.setRowStretchFactor(ROW_HOR_LINE, 1) gridLayout.setRowStretchFactor(ROW_IMAGE, 2) gridLayout.setColumnStretchFactor(COL_IMAGE, 2) gridLayout.setColumnStretchFactor(COL_VER_LINE, 1) # Configuration tree self._config = PgImagePlot2dCti(pgImagePlot2d=self, nodeName='2D image plot') # Connect signals # Based mouseMoved on crosshair.py from the PyQtGraph examples directory. # I did not use the SignalProxy because I did not see any difference. self.imagePlotItem.scene().sigMouseMoved.connect(self.mouseMoved)
def setupUi(self, MainWindow): super().setupUi(MainWindow) #### self.visualizerGView = pg.GraphicsView(self.visualizerTab) self.visualizerGView.setObjectName(_fromUtf8("visualizerGView")) self.visualizerVLayout.addWidget(self.visualizerGView) self.layout = pg.GraphicsLayout(border=(100, 100, 100)) self.visualizerGView.setCentralItem(self.layout) #### # Mel filterbank plot self.fft_plot = self.layout.addPlot(title='Filterbank Output', colspan=3) self.fft_plot.setRange(yRange=[-0.1, 1.2]) self.fft_plot.disableAutoRange(axis=pg.ViewBox.YAxis) self.x_data = np.array(range(1, config.N_FFT_BINS + 1)) self.mel_curve = pg.PlotCurveItem() self.mel_curve.setData(x=self.x_data, y=self.x_data * 0) self.fft_plot.addItem(self.mel_curve) # Visualization plot self.layout.nextRow() self.led_plot = self.layout.addPlot(title='Visualization Output', colspan=3) self.led_plot.setRange(yRange=[-5, 260]) self.led_plot.disableAutoRange(axis=pg.ViewBox.YAxis) # Pen for each of the color channel curves self.r_pen = pg.mkPen((255, 30, 30, 200), width=4) self.g_pen = pg.mkPen((30, 255, 30, 200), width=4) self.b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves self.r_curve = pg.PlotCurveItem(pen=self.r_pen) self.g_curve = pg.PlotCurveItem(pen=self.g_pen) self.b_curve = pg.PlotCurveItem(pen=self.b_pen) # Define x data self.x_data = np.array(range(1, config.N_PIXELS + 1)) self.r_curve.setData(x=self.x_data, y=self.x_data * 0) self.g_curve.setData(x=self.x_data, y=self.x_data * 0) self.b_curve.setData(x=self.x_data, y=self.x_data * 0) # Add curves to plot self.led_plot.addItem(self.r_curve) self.led_plot.addItem(self.g_curve) self.led_plot.addItem(self.b_curve) # Frequency range label self.freq_label = pg.LabelItem('') # Frequency slider self.freq_slider = pg.TickSliderItem(orientation='bottom', allowAdd=False) self.freq_slider.addTick( (config.MIN_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) self.freq_slider.addTick( (config.MAX_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) self.freq_slider.tickMoveFinished = self.freq_slider_change self.freq_label.setText('Frequency range: {} - {} Hz'.format( config.MIN_FREQUENCY, config.MAX_FREQUENCY)) # Create effect "buttons" (labels with click event) self.energy_label = pg.LabelItem('Energy') self.scroll_label = pg.LabelItem('Scroll') self.spectrum_label = pg.LabelItem('Spectrum') self.energy_label.mousePressEvent = self.energy_click self.scroll_label.mousePressEvent = self.scroll_click self.spectrum_label.mousePressEvent = self.spectrum_click self.energy_click(0) # Layout self.layout.nextRow() self.layout.addItem(self.freq_label, colspan=3) self.layout.nextRow() self.layout.addItem(self.freq_slider, colspan=3) self.layout.nextRow() self.layout.addItem(self.energy_label) self.layout.addItem(self.scroll_label) self.layout.addItem(self.spectrum_label) # Fix secondTab self.tabWidget.setTabText(self.tabWidget.indexOf(self.visualizerTab), _translate("MainWindow", "Visualizer", None)) #SIGNALS AND CONNECTORS self.visualizerStartBtn.clicked.connect(self.start_visualizer_click) self.visualizerStopBtn.clicked.connect(self.stop_visualizer_click) self.parent_app.aboutToQuit.connect(self.closeEvent) # AUDIO INPUT DEVICES self.getaudiodevices() self.soundDeviceSelectBox.currentIndexChanged.connect( self.inputDeviceChanged)
def add_plot(self): gui_index = self.parent.ui.get_style_name_index() if "standard" in self.parent.gui_styles[gui_index]: pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') single_pen = pg.mkPen("k") else: single_pen = pg.mkPen("w") win = pg.GraphicsLayoutWidget() # justify='right',, self.label = pg.LabelItem(justify='left', row=0, col=0) win.addItem(self.label) # self.plot1 = win.addPlot(row=0, col=0) self.plot1 = win.addPlot(row=1, col=0) self.label2 = pg.LabelItem(justify='right') win.addItem(self.label2, row=0, col=0) self.plot1.setLabel('left', "A", units='au') self.plot1.setLabel('bottom', "", units='n shots') self.plot1.showGrid(1, 1, 1) self.plot1.getAxis('left').enableAutoSIPrefix( enable=False) # stop the auto unit scaling on y axes layout = QtGui.QGridLayout() self.ui.widget_log.setLayout(layout) layout.addWidget(win, 0, 0) self.plot1.setAutoVisible(y=True) self.plot1.addLegend() self.single = pg.PlotCurveItem(pen=single_pen, name='single') self.plot1.addItem(self.single) pen = pg.mkPen((51, 255, 51), width=2) pen = pg.mkPen((255, 0, 0), width=3) # self.average = pg.PlotCurveItem(x=[], y=[], pen=pen, name='average') self.average = pg.PlotCurveItem(pen=pen, name='average') self.plot1.addItem(self.average) pen = pg.mkPen((0, 255, 255), width=2) self.fit_func = pg.PlotCurveItem(pen=pen, name='Gauss Fit') # self.plot1.addItem(self.fit_func) # self.plot1.enableAutoRange(False) # self.textItem = pg.TextItem(text="", border='w', fill=(0, 0, 0)) # self.textItem.setPos(10, 10) pen = pg.mkPen((0, 100, 0), width=1) # self.average = pg.PlotCurveItem(x=[], y=[], pen=pen, name='average') self.back_plot = pg.PlotCurveItem(pen=pen, name='background') # self.plot1.addItem(self.back_plot) ##################################### SS removed, as typically we don;t need it once start pySpectrometer # cross hair self.vLine = pg.InfiniteLine(angle=90, movable=False) self.hLine = pg.InfiniteLine(angle=0, movable=False) self.plot1.addItem(self.vLine, ignoreBounds=True) self.plot1.addItem(self.hLine, ignoreBounds=True)
def __init__(self, parent=None, name="ImageView", view=None, imageItem=None, *args): pg.setConfigOptions(imageAxisOrder='row-major') addNewGradientFromMatplotlib("jet") addNewGradientFromMatplotlib("viridis") addNewGradientFromMatplotlib("plasma") addNewGradientFromMatplotlib("inferno") addNewGradientFromMatplotlib("magma") addNewGradientFromMatplotlib("cividis") grayclip = pg.graphicsItems.GradientEditorItem.Gradients["greyclip"] pg.graphicsItems.GradientEditorItem.Gradients["segmentation"] = { 'ticks': [(0.0, (0, 0, 0, 255)), (1.0 - np.finfo(float).eps, (255, 255, 255, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'rgb' } super().__init__(parent, name, view, imageItem, *args) self.imageItem.getHistogram = self.getImageItemHistogram self.imageItem.mouseClickEvent = self.mouseClickEventImageItem self.imageItem.mouseDragEvent = self.mouseClickEventImageItem self.timeLine.setPen('g') self.ui.histogram.sigLevelsChanged.connect(self.levelsChanged) self.ui.histogram.gradient.loadPreset("viridis") self.gradient = self.ui.histogram.gradient.colorMap() self.ui.histogram.gradient.updateGradient() self.ui.histogram.gradientChanged() self.ui.normAutoRadio = QtGui.QRadioButton(self.ui.normGroup) self.ui.normAutoRadio.setObjectName("normAutoRadio") self.ui.roiGroup = QtGui.QButtonGroup(self.ui.normGroup) self.ui.normRadioGroup = QtGui.QButtonGroup(self.ui.normGroup) self.ui.label_roi = QtGui.QLabel(self.ui.normGroup) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.ui.label_roi.setFont(font) self.ui.label_roi.setText( QtGui.QApplication.translate("Form", "ROI:", None)) self.ui.roiSquareRadio = QtGui.QRadioButton(self.ui.normGroup) self.ui.roiSquareRadio.setText( QtGui.QApplication.translate("Form", "Square", None)) self.ui.roiCircleRadio = QtGui.QRadioButton(self.ui.normGroup) self.ui.roiCircleRadio.setText( QtGui.QApplication.translate("Form", "Circle", None)) self.ui.roiGroup.addButton(self.ui.roiSquareRadio) self.ui.roiGroup.addButton(self.ui.roiCircleRadio) self.ui.normAutoRadio.setText( QtGui.QApplication.translate("Form", "Stack", None)) self.ui.normOffRadio.setText( QtGui.QApplication.translate("Form", "Manual", None)) self.ui.normTimeRangeCheck.setText( QtGui.QApplication.translate("Form", "Slice range", None)) self.ui.normDivideRadio.setText( QtGui.QApplication.translate("Form", "Auto", None)) self.ui.label_5.setText( QtGui.QApplication.translate("Form", "Type:", None)) self.ui.roiSquareRadio.clicked.connect(self.roiRadioChanged) self.ui.roiCircleRadio.clicked.connect(self.roiRadioChanged) self.ui.normAutoRadio.clicked.connect(self.normRadioChanged) self.ui.normRadioGroup.addButton(self.ui.normDivideRadio) self.ui.normRadioGroup.addButton(self.ui.normOffRadio) self.ui.roiSquareRadio.setChecked(True) self.ui.normDivideRadio.setChecked(True) self.hide_partial() for i in reversed(range(self.ui.gridLayout_2.count())): self.ui.gridLayout_2.itemAt(i).widget().setParent(None) self.ui.gridLayout_2.addWidget(self.ui.label_roi, 0, 0, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.roiSquareRadio, 0, 1, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.roiCircleRadio, 0, 2, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.label_5, 1, 0, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.normDivideRadio, 1, 1, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.normOffRadio, 1, 2, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.normFrameCheck, 2, 1, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.label_3, 2, 0, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.normROICheck, 2, 1, 1, 1) self.ui.gridLayout_2.addWidget(self.ui.normTimeRangeCheck, 2, 2, 1, 1) self.label = pg.LabelItem(justify='right') self.scene.addItem(self.label) self.scene.sigMouseMoved.connect(self.on_hover_image) self.threads = [] self.mouse_x = 0 self.mouse_y = 0 self.is_clickable = False self.is_drawable = False self.pen_size = 1 self.imageCopy = None self.imageItem.drawAt = self.drawAt self.levelMin, self.levelMax = None, None self.isNewImage = False self.isNewNorm = False self.normDivideRadioChecked = False self.ui.histogram.setHistogramRange = lambda mn, mx, padding=0.1: setHistogramRange( self.ui.histogram, mn, mx, padding)
def add(self, plots): # e.g.: plots.add(exp.enumerate_plots()) plotsize = None for plot in plots: # check if panel exists. there's a different panel for each x coordinate (e.g. iterations, time) panel_id = (plot['panel'], plot['x']) if panel_id not in self.panels: # create new panel widget = create_plot_widget() # set size based on size slider if plotsize is None: plotsize = self.window.size_slider.value() widget.setFixedWidth(plotsize) widget.setFixedHeight(plotsize) self.window.flow_layout.addWidget( widget) # add to window's flow layout # if title not defined, use the panel ID (e.g. stat name) widget.setTitle(str(plot.get('title', plot['panel']))) widget.plots_dict = {} # set up mouse move event widget.mouseMoveEvent = partial(mouse_move, widget=widget) widget.leaveEvent = partial(mouse_leave, widget=widget) # mouse cursor (vertical line) vline = pg.InfiniteLine(angle=90, pen="#B0B0B0") vline.setVisible(False) widget.getPlotItem().addItem( vline, ignoreBounds=True) # ensure it doesn't mess autorange widget.cursor_vline = vline # mouse cursor text label = pg.LabelItem(justify='left') label.setParentItem(widget.getPlotItem().getViewBox()) label.anchor(itemPos=(0, 0), parentPos=(0, 0)) widget.cursor_label = label self.panels[panel_id] = widget else: widget = self.panels[panel_id] # reuse existing panel # get data points exp = plot['exp'] (xs, ys) = (exp.data[exp.names.index(plot['x'])], exp.data[exp.names.index(plot['y'])]) # get the plot style associated with this experiment if len(exp.style) == 0: (exp.style_order, exp.style) = next(self.style_generator) # get a new style style = exp.style # allow overriding the style if 'color' in plots: style['color'] = plots['color'] if 'width' in plots: style['width'] = plots['width'] if 'dash' in plots and plots['dash'] in dashes_by_name: style['style'] = dashes_by_name[plots['dash']] try: pen = pg.mkPen(style) except: # if the style is malformed, use the default style pen = pg.mkPen(exp.style) # check if plot line already exists if plot['line'] not in widget.plots_dict: # create new line line = widget.getPlotItem().plot(xs, ys, pen=pen) line.curve.setClickable(True, 8) # size of hover region line.mouse_over = False widget.plots_dict[plot['line']] = line exp._plots.append( line) # register in experiment (to toggle visibility) else: # update existing one line = widget.plots_dict[plot['line']] line.setData(xs, ys) line.setPen(pen)
def display(self): logging.debug("setting up plot window for display") # create the plot window and set it's title self.plotwin = pg.GraphicsWindow() self.plotwin.setWindowTitle("Temperature Logs") # add items to window. # put a label at the top to display coordinates self.zCoordsLabel = pg.LabelItem(justify='right') self.zCoordsLabel.setText("(0,0)", row=0, col=0) # add plots to the window self.plotwin.addItem(self.zCoordsLabel) # zoom window self.zplot = self.plotwin.addPlot(row=1, col=0) self.zplot.addLegend() # region window self.rplot = self.plotwin.addPlot(row=3, col=0) # configure the axises (labels and tics) axis = self.zplot.getAxis('bottom') axis.setLabel("time") # swap out the bottom axis tickStrings function so it will display the date corrrectly def dateTickStrings(self, values, scale, spacing): # PySide's QTime() initialiser fails miserably and dismisses args/kwargs # times will be in number of seconds since... # need to convert this to a tuple, create a datetime object, and output it in the correct format return [fmtEpoch(value, TempPlotter.timefmt) for value in values] axis.tickStrings = types.MethodType(dateTickStrings, axis) axis = self.zplot.getAxis('left') axis.setLabel("temperature (%s)" % self.config.get("temperature/units")) axis = self.rplot.getAxis('bottom') axis.setLabel("time") axis.tickStrings = types.MethodType(dateTickStrings, axis) axis = self.rplot.getAxis('left') axis.setLabel("temperature (%s)" % self.config.get("temperature/units")) # ad a text item to display current temperatures text = self.config.get("temperature/display/template") self.tempDisp = pg.TextItem(html=text, anchor=(1, 0)) self.rplot.addItem(self.tempDisp) # add cross hair to the zoom plot self.crosshair = dict() self.crosshair['v'] = pg.InfiniteLine(angle=90, movable=False) self.crosshair['h'] = pg.InfiniteLine(angle=0, movable=False) self.zplot.addItem(self.crosshair['v'], ignoreBounds=True) self.zplot.addItem(self.crosshair['h'], ignoreBounds=True) def mouseMoved(evt): # slot to update the crosshairs pos = evt if self.zplot.sceneBoundingRect().contains(pos): mousePoint = self.zplot.vb.mapSceneToView(pos) index = int(mousePoint.x()) self.zCoordsLabel.setText( "(%(x)s, %(y).1f)" % { 'x': fmtEpoch(mousePoint.x(), self.timefmt), 'y': mousePoint.y() }) self.crosshair['v'].setPos(mousePoint.x()) self.crosshair['h'].setPos(mousePoint.y()) # add region to the region plot self.plotregion = pg.LinearRegionItem() self.plotregion.setZValue( 100) # make sure region gets displayed on top self.rplot.addItem(self.plotregion, ignoreBounds=True) self.rplot.setAutoVisible(y=True) self.plotregion.setRegion([self.getMinTime(), self.getMaxTime()]) def updateZoomPlot(): # slot to update zoom plot range when region is changed self.plotregion.setZValue(100) mint, maxt = self.plotregion.getRegion() self.zplot.setXRange(mint, maxt, padding=0) def updateRegion(wind, viewRange): # slot to update the region when zoom plot range changes self.plotregion.setRegion(viewRange[0]) # initialize the list of plot curves (actually, it is a dict) self.plotcurves = {} # connect signals self.zplot.scene().sigMouseMoved.connect(mouseMoved) self.data_changed.connect(self.plot) self.plotregion.sigRegionChanged.connect(updateZoomPlot) self.zplot.sigRangeChanged.connect(updateRegion) self.rplot.sigRangeChanged.connect(self.displayCurrentTemps) # emit signal that will cause plot to update self.data_changed.emit()
b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves r_curve = pg.PlotCurveItem(pen=r_pen) g_curve = pg.PlotCurveItem(pen=g_pen) b_curve = pg.PlotCurveItem(pen=b_pen) # Define x data x_data = np.array(range(1, config.N_PIXELS + 1)) r_curve.setData(x=x_data, y=x_data * 0) g_curve.setData(x=x_data, y=x_data * 0) b_curve.setData(x=x_data, y=x_data * 0) # Add curves to plot led_plot.addItem(r_curve) led_plot.addItem(g_curve) led_plot.addItem(b_curve) # Frequency range label freq_label = pg.LabelItem('') # Frequency slider def freq_slider_change(tick): minf = freq_slider.tickValue(0)**2.0 * (config.MIC_RATE / 2.0) maxf = freq_slider.tickValue(1)**2.0 * (config.MIC_RATE / 2.0) t = 'Frequency range: {:.0f} - {:.0f} Hz'.format(minf, maxf) freq_label.setText(t) config.MIN_FREQUENCY = minf config.MAX_FREQUENCY = maxf dsp.create_mel_bank() freq_slider = pg.TickSliderItem(orientation='bottom', allowAdd=False) freq_slider.addTick( (config.MIN_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) freq_slider.addTick(
def initUI(self): # Set the color scheme def updateStyle(self): r = '2px' if self.dim: fg = color.unselectedFG bg = color.unselectedBG border = color.unselectedBorder else: fg = color.selectedFG bg = color.selectedBG border = color.selectedBorder if self.orientation == 'vertical': self.vStyle = """DockLabel { background-color : %s; color : %s; border-top-right-radius: 0px; border-top-left-radius: %s; border-bottom-right-radius: 0px; border-bottom-left-radius: %s; border-top: 1px solid %s; border-left: 1px solid %s; border-right: 1px solid %s; border-width: 1px; border-right: 2px solid %s; padding-top: 3px; padding-bottom: 3px; font-size: 18px; }""" % (bg, fg, r, r, border, fg, fg, fg) self.setStyleSheet(self.vStyle) else: if self.dim: # unselected, decrease font size self.hStyle = """DockLabel { background-color : %s; color : %s; border-top-right-radius: %s; border-top-left-radius: %s; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; border-width: 1px; border-bottom: 2px solid %s; border-top: 1px solid %s; border-left: 1px solid %s; border-right: 1px solid %s; padding-left: 13px; padding-right: 13px; font-size: 16px }""" % (bg, fg, r, r, border, fg, fg, fg) else: # selected self.hStyle = """DockLabel { background-color : %s; color : %s; border-top-right-radius: %s; border-top-left-radius: %s; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; border-width: 1px; border-bottom: 2px solid %s; border-top: 1px solid %s; border-left: 1px solid %s; border-right: 1px solid %s; padding-left: 13px; padding-right: 13px; font-size: 18px }""" % (bg, fg, r, r, border, fg, fg, fg) self.setStyleSheet(self.hStyle) DockLabel.updateStyle = updateStyle if args.mode == 'sfx': self.area.addDock(self.mouse.dock, 'left') self.area.addDock(self.img.dock, 'bottom', self.mouse.dock) self.area.addDock(self.stack.dock, 'bottom', self.mouse.dock) self.area.moveDock( self.img.dock, 'above', self.stack.dock) ## move imagePanel on top of imageStack self.area.addDock(self.exp.dock, 'right') self.area.addDock(self.geom.dock, 'right') self.area.addDock(self.roi.dock, 'right') self.area.moveDock(self.geom.dock, 'above', self.roi.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.exp.dock, 'above', self.geom.dock) self.area.addDock(self.pk.dock, 'bottom', self.exp.dock) self.area.addDock(self.index.dock, 'bottom', self.exp.dock) self.area.addDock(self.mk.dock, 'bottom', self.exp.dock) self.area.moveDock(self.index.dock, 'above', self.mk.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.pk.dock, 'above', self.index.dock) self.area.addDock(self.small.dock, 'right') self.area.addDock(self.control.dock, 'right') self.area.moveDock(self.small.dock, 'top', self.control.dock) elif args.mode == 'spi': self.area.addDock(self.mouse.dock, 'left') self.area.addDock(self.img.dock, 'bottom', self.mouse.dock) self.area.addDock(self.stack.dock, 'bottom', self.mouse.dock) self.area.moveDock( self.img.dock, 'above', self.stack.dock) ## move imagePanel on top of imageStack self.area.addDock(self.exp.dock, 'right') self.area.addDock(self.geom.dock, 'right') self.area.addDock(self.roi.dock, 'right') self.area.moveDock(self.geom.dock, 'above', self.roi.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.exp.dock, 'above', self.geom.dock) self.area.addDock(self.hf.dock, 'bottom', self.exp.dock) self.area.addDock(self.index.dock, 'bottom', self.exp.dock) self.area.addDock(self.mk.dock, 'bottom', self.exp.dock) self.area.moveDock(self.index.dock, 'above', self.mk.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.hf.dock, 'above', self.index.dock) self.area.addDock(self.small.dock, 'right') self.area.addDock(self.control.dock, 'right') self.area.moveDock(self.small.dock, 'top', self.control.dock) elif args.mode == 'all': self.area.addDock(self.mouse.dock, 'left') self.area.addDock(self.img.dock, 'bottom', self.mouse.dock) self.area.addDock(self.stack.dock, 'bottom', self.mouse.dock) self.area.moveDock( self.img.dock, 'above', self.stack.dock) ## move imagePanel on top of imageStack self.area.addDock(self.exp.dock, 'right') self.area.addDock(self.geom.dock, 'right') self.area.addDock(self.roi.dock, 'right') self.area.moveDock(self.geom.dock, 'above', self.roi.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.exp.dock, 'above', self.geom.dock) self.area.addDock(self.hf.dock, 'bottom', self.exp.dock) self.area.addDock(self.pk.dock, 'bottom', self.exp.dock) self.area.addDock(self.index.dock, 'bottom', self.exp.dock) self.area.addDock(self.mk.dock, 'bottom', self.exp.dock) self.area.moveDock(self.index.dock, 'above', self.mk.dock) ## move d6 to stack on top of d4 self.area.moveDock(self.pk.dock, 'above', self.index.dock) self.area.moveDock(self.hf.dock, 'above', self.pk.dock) self.area.addDock(self.small.dock, 'right') self.area.addDock(self.control.dock, 'right') self.area.moveDock(self.small.dock, 'top', self.control.dock) else: self.area.addDock(self.mouse.dock, 'left') self.area.addDock(self.img.dock, 'bottom', self.mouse.dock) self.area.addDock(self.stack.dock, 'bottom', self.mouse.dock) self.area.addDock(self.control.dock, 'left') self.area.moveDock(self.control.dock, 'bottom', self.stack.dock) self.area.moveDock( self.img.dock, 'above', self.stack.dock) ## move imagePanel on top of imageStack self.area.addDock(self.exp.dock, 'right') self.area.addDock(self.roi.dock, 'right') self.area.moveDock(self.exp.dock, 'above', self.roi.dock) ## move d6 to stack on top of d4 self.area.addDock(self.pk.dock, 'bottom', self.exp.dock) self.area.addDock(self.mk.dock, 'bottom', self.exp.dock) self.area.moveDock(self.pk.dock, 'above', self.mk.dock) ## move d6 to stack on top of d4 ############### ### Threads ### ############### # Making powder patterns self.thread = [] self.threadCounter = 0 # Initial setup of input parameters if self.experimentName is not "": self.exp.p.param(self.exp.exp_grp, self.exp.exp_name_str).setValue( self.experimentName) self.exp.updateExpName(self.experimentName) if self.runNumber is not 0: self.exp.p.param(self.exp.exp_grp, self.exp.exp_run_str).setValue(self.runNumber) self.exp.updateRunNumber(self.runNumber) if self.detInfo is not "": self.exp.p.param(self.exp.exp_grp, self.exp.exp_detInfo_str).setValue(self.detInfo) self.exp.updateDetInfo(self.detInfo) self.exp.p.param(self.exp.exp_grp, self.exp.exp_evt_str).setValue(self.eventNumber) self.exp.updateEventNumber(self.eventNumber) if self.exp.hasExpRunInfo(): # Setup elog self.exp.setupRunTable() self.exp.getDatasource() self.exp.setupRunDir() self.exp.setupTotalEvents() self.exp.printDetectorNames() # Update paths in all the panels self.exp.updatePanels() self.exp.setupPsocake() # Update hidden CrystFEL files self.exp.updateHiddenCrystfelFiles(self.facility) # Optionally use local calib directory self.exp.setupLocalCalib() # Launch e-log crawler self.exp.setupCrawler() if self.exp.hasExpRunDetInfo(): self.exp.setupDetGeom() self.img.updateDetectorCentre(self.facility) self.exp.getEventAndDisplay() # Indicate centre of detector self.geom.drawCentre() self.doneInit = True # Try mouse over crosshair self.xhair = self.img.win.getView() self.vLine = pg.InfiniteLine(angle=90, movable=False) self.hLine = pg.InfiniteLine(angle=0, movable=False) self.xhair.addItem(self.vLine, ignoreBounds=True) self.xhair.addItem(self.hLine, ignoreBounds=True) self.vb = self.xhair.vb self.label = pg.LabelItem() self.mouse.win.addItem(self.label) def mouseMoved(evt): pos = evt[ 0] ## using signal proxy turns original arguments into a tuple if self.xhair.sceneBoundingRect().contains(pos): mousePoint = self.vb.mapSceneToView(pos) indexX = int(mousePoint.x()) indexY = int(mousePoint.y()) # update crosshair position self.vLine.setPos(mousePoint.x()) self.hLine.setPos(mousePoint.y()) # get pixel value, if data exists if self.data is not None: if indexX >= 0 and indexX < self.data.shape[0] \ and indexY >= 0 and indexY < self.data.shape[1]: if self.mk.maskingMode > 0: modeInfo = self.mk.masking_mode_message else: modeInfo = "" pixelInfo = "<span style='color: " + color.pixelInfo + "; font-size: 24pt;'>x=%0.1f y=%0.1f I=%0.1f </span>" self.label.setText(modeInfo + pixelInfo % (mousePoint.x(), mousePoint.y(), self.data[indexX, indexY])) def mouseClicked(evt): mousePoint = self.vb.mapSceneToView(evt[0].scenePos()) indexX = int(mousePoint.x()) indexY = int(mousePoint.y()) if self.data is not None: # Mouse click if indexX >= 0 and indexX < self.data.shape[0] \ and indexY >= 0 and indexY < self.data.shape[1]: print "mouse clicked: ", mousePoint.x(), mousePoint.y( ), self.data[indexX, indexY] if self.mk.maskingMode > 0: self.initMask() if self.mk.maskingMode == 1: # masking mode self.mk.userMaskAssem[indexX, indexY] = 0 elif self.mk.maskingMode == 2: # unmasking mode self.mk.userMaskAssem[indexX, indexY] = 1 elif self.mk.maskingMode == 3: # toggle mode self.mk.userMaskAssem[indexX, indexY] = ( 1 - self.mk.userMaskAssem[indexX, indexY]) self.displayMask() self.mk.userMask = self.det.ndarray_from_image( self.evt, self.mk.userMaskAssem, pix_scale_size_um=None, xy0_off_pix=None) self.algInitDone = False self.parent.pk.updateClassification() # Signal proxy self.proxy_move = pg.SignalProxy(self.xhair.scene().sigMouseMoved, rateLimit=30, slot=mouseMoved) self.proxy_click = pg.SignalProxy(self.xhair.scene().sigMouseClicked, slot=mouseClicked)
# col, rowspan, colspan) import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtGui #generate layout app = QtGui.QApplication([]) win = pg.GraphicsWindow() win.setWindowTitle('pyqtgraph example: crosshair') # Add the label to show the 'y' position on the plot at the 'x' value of the cross hair label = pg.LabelItem(justify='right') win.addItem(label) # Instanciate the plot containing the crosshair crosshair_plot = win.addPlot(row=0, col=0) # Instanciate the plot containing all the data all_data_plot = win.addPlot(row=0, col=1) # Region of selection in the 'all_data_plot' region = pg.LinearRegionItem() # Tell the ViewBox to exclude this item when doing auto-range calculations. all_data_plot.addItem(region, ignoreBounds=True) crosshair_plot.setAutoVisible(y=True) # Create data
avg_spike = TraceList(sweep_list['spike']).mean() avg_spike.t0 = 0 grid[row[1], 0].setLabels(left=('Vm', 'V')) grid[row[1], 0].setLabels(bottom=('t', 's')) grid[row[1], 0].setXRange(-2e-3, 27e-3) grid[row[1], 0].plot(avg_first_pulse.time_values, avg_first_pulse.data, pen={ 'color': (255, 0, 255), 'width': 2 }) grid[row[0], 0].setLabels(left=('Vm', 'V')) sweep_list['spike'][0].t0 = 0 grid[row[0], 0].plot(avg_spike.time_values, avg_spike.data, pen='k') grid[row[0], 0].setXLink(grid[row[1], 0]) label = pg.LabelItem('%s, n = %d' % (connection_type, n)) label.setParentItem(grid[row[1], 0].vb) label.setPos(50, 0) holding_label = pg.LabelItem('%d mV' % (sum(holding) / len(holding))) holding_label.setParentItem(grid[row[1], 0].vb) holding_label.setPos(50, 100) grid[row[1], 0].label = label maxYpulse.append((row[1], grid[row[1], 0].getAxis('left').range[1])) else: print("%s not enough sweeps for first pulse" % connection_type) if plot_trains is True: train_responses = analyzer.train_responses for i, stim_params in enumerate(train_responses.keys()): if stim_params[0] == 50: if len(train_responses[stim_params][0]) != 0: ind_group = train_responses[stim_params][0]
def __init__(self, tvar_name, show_xaxis=False): self.tvar_name = tvar_name self.show_xaxis = show_xaxis self.crosshair = pytplot.tplot_opt_glob['crosshair'] # Sets up the layout of the Tplot Object pg.GraphicsLayout.__init__(self) self.layout.setHorizontalSpacing(50) self.layout.setContentsMargins(0, 0, 0, 0) # Set up the x axis self.xaxis = pg.AxisItem(orientation='bottom') self.xaxis.setHeight(35) self.xaxis.enableAutoSIPrefix(enable=False) # Set up the y axis self.yaxis = AxisItem("left") self.yaxis.setWidth(100) # Creating axes to bound the plots with lines self.xaxis2 = pg.AxisItem(orientation='top') self.xaxis2.setHeight(0) self.yaxis2 = AxisItem("right") self.yaxis2.setWidth(0) vb = NoPaddingPlot() self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis, 'left': self.yaxis, "right": self.yaxis2, "top": self.xaxis2}, viewBox=vb) self.plotwindow.vb.setLimits(xMin=0, xMax=360, yMin=-90, yMax=90) if pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['border']: self.plotwindow.showAxis("top") self.plotwindow.showAxis("right") # Set up the view box needed for the legends self.legendvb = pg.ViewBox(enableMouse=False) self.legendvb.setMaximumWidth(100) self.legendvb.setXRange(0, 1, padding=0) self.legendvb.setYRange(0, 1, padding=0) self.addItem(self.legendvb, 0, 1) self.curves = [] self.colors = self._setcolors() self.colormap = self._setcolormap() if pytplot.tplot_opt_glob['black_background']: self.labelStyle = {'font-size': str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size']) + 'pt', 'color': '#FFF'} else: self.labelStyle = {'font-size': str(pytplot.data_quants[self.tvar_name].attrs['plot_options']['extras']['char_size']) + 'pt', 'color': '#000'} # Set the font size of the axes font = QtGui.QFont() font.setPixelSize(pytplot.tplot_opt_glob['axis_font_size']) self.xaxis.tickFont = font self.yaxis.tickFont = font if show_xaxis: self.plotwindow.showAxis('bottom') else: self.plotwindow.hideAxis('bottom') self.label = pg.LabelItem(justify='left') self.addItem(self.label, row=1, col=0) # Set legend options self.hoverlegend = CustomLegendItem(offset=(0, 0)) self.hoverlegend.setItem("Date: ", "0") self.hoverlegend.setItem("Time: ", "0") self.hoverlegend.setItem("Latitude:", "0") self.hoverlegend.setItem("Longitude:", "0") self.hoverlegend.setVisible(False) self.hoverlegend.setParentItem(self.plotwindow.vb)
def __init__(self, broker_addr="", profile_addr="", graph_name="graph", loop=None): super().__init__() if loop is None: self.app = QtGui.QApplication([]) loop = QEventLoop(self.app) asyncio.set_event_loop(loop) self.ctx = zmq.asyncio.Context() if broker_addr: self.broker = self.ctx.socket(zmq.SUB) self.broker.setsockopt_string(zmq.SUBSCRIBE, 'profiler') self.broker.connect(broker_addr) else: self.broker = None self.graph_name = graph_name self.profile_addr = profile_addr self.profile = self.ctx.socket(zmq.SUB) self.profile.setsockopt_string(zmq.SUBSCRIBE, self.graph_name) self.task = None self.deserializer = Deserializer() self.current_version = 0 self.metadata = {} # {version : metadata} self.parents = set() self.heartbeat_data = {} self.widget = QtWidgets.QWidget() self.layout = QtGui.QGridLayout(self.widget) self.widget.setLayout(self.layout) self.enabled_nodes = {} self.trace_layout = QtGui.QFormLayout(self.widget) hbox = QtWidgets.QHBoxLayout(self.widget) selectAll = QtWidgets.QPushButton("Select All", self.widget) selectAll.clicked.connect(self.selectAll) unselectAll = QtWidgets.QPushButton("Unselect All", self.widget) unselectAll.clicked.connect(self.unselectAll) hbox.addWidget(selectAll) hbox.addWidget(unselectAll) self.trace_layout.addRow(hbox) self.trace_group = WidgetGroup() self.trace_group.sigChanged.connect(self.state_changed) self.layout.addLayout(self.trace_layout, 0, 0, -1, 1) self.graphicsLayoutWidget = pg.GraphicsLayoutWidget() self.layout.addWidget(self.graphicsLayoutWidget, 0, 1, -1, -1) self.time_per_heartbeat = self.graphicsLayoutWidget.addPlot(row=0, col=0) self.time_per_heartbeat.showGrid(True, True) self.time_per_heartbeat.setLabel('bottom', "Heartbeat") self.time_per_heartbeat.setLabel('left', "Time (Sec)") self.time_per_heartbeat_data = collections.defaultdict( lambda: np.array([np.nan] * 100)) self.time_per_heartbeat_traces = {} self.time_per_heartbeat_legend = self.time_per_heartbeat.addLegend() self.heartbeats_per_second = self.graphicsLayoutWidget.addPlot(row=0, col=1) self.heartbeats_per_second.showGrid(True, True) self.heartbeats_per_second.setLabel('bottom', "Heartbeat") self.heartbeats_per_second.setLabel('left', "Heartbeats/Second") self.heartbeats_per_second_data = np.array([np.nan] * 100) self.heartbeats_per_second_trace = None self.percent_per_heartbeat = self.graphicsLayoutWidget.addPlot( row=1, col=0, rowspan=1, colspan=2) self.percent_per_heartbeat.showGrid(True, True) self.percent_per_heartbeat_trace = None self.last_updated = pg.LabelItem( parent=self.time_per_heartbeat.getViewBox()) self.total_heartbeat_time = pg.LabelItem( parent=self.percent_per_heartbeat.getViewBox()) self.heartbeat_per_second = pg.LabelItem( parent=self.heartbeats_per_second.getViewBox()) self.win = ProfilerWindow(self) self.win.setWindowTitle('Profiler') self.win.setCentralWidget(self.widget) self.win.show() with loop: loop.run_until_complete( asyncio.gather(self.process_broker_message(), self.monitor()))
def initUI(self): # pg.setConfigOption('background', 'w') self.lblTit = pg.LabelItem(justify='right') #Variables self.data_dir='' self.nom_dir = [] self.numEp=1 self.grafi=[] self.tam=0 self.puntos=0 self.sizes = np.asarray([120, 60, 30, 15]) datos = QVBoxLayout() contain=QSplitter(Qt.Horizontal) ima = QVBoxLayout() self.glw = pg.PlotWidget() btn_data_dir = QPushButton('Load Files') btn_data_dir.clicked.connect(self.openFile) self.lblDataDir=QLabel('') self.lytEpoch = QFormLayout() self.cmbEpoch = QComboBox() self.cmbEpoch.addItem("120") self.cmbEpoch.addItem("60") self.cmbEpoch.addItem("30") self.cmbEpoch.addItem("15") self.lytEpoch.addRow("Epoch size: ", self.cmbEpoch) self.lytFrec = QFormLayout() self.txtFrec = QLineEdit('200') self.lytFrec.addRow("Frecuencia: ",self.txtFrec) btn_do = QPushButton('DO') btn_do.clicked.connect(self.showDialog) self.lytEpo = QFormLayout() self.cmbEpo = QComboBox() self.cmbEpo.setCurrentIndex=1 self.cmbEpo.activated[str].connect(self.graficaX) self.lytEpo.addRow("Número de época: ", self.cmbEpo) datos.addWidget(btn_data_dir) datos.addWidget(self.lblDataDir) datos.addLayout(self.lytEpoch) datos.addLayout(self.lytFrec) datos.addWidget(btn_do) ima.addWidget(self.glw) ima.addLayout(self.lytEpo) bot = QWidget() bot.setLayout(datos) gra = QWidget() gra.setLayout(ima) contain.addWidget(bot) contain.addWidget(gra) self.addWidget(contain)
def __init__(self, display_name, gui): self.connected = False self._gui = gui self.display_name = display_name self.laser = gui.config["display_names"][display_name] self.server = "" self.wake_loop = asyncio.Event() self.dock = dock.Dock(self.display_name, autoOrientation=False) self.layout = pg.GraphicsLayoutWidget(border=(80, 80, 80)) # create widgets self.colour = "ffffff" # will be set later depending on laser colour self.detuning = pg.LabelItem("") self.detuning.setText("-", color="ffffff", size="64pt") self.frequency = pg.LabelItem("") self.frequency.setText("-", color="ffffff", size="12pt") self.name = pg.LabelItem("") self.name.setText(display_name, color="ffffff", size="32pt") self.osa = pg.PlotItem() self.osa.hideAxis('bottom') self.osa.showGrid(y=True) self.osa_curve = self.osa.plot(pen='y', color=self.colour) self.fast_mode = QtGui.QCheckBox("Fast mode") self.auto_exposure = QtGui.QCheckBox("Auto expose") self.exposure = [QtGui.QSpinBox() for _ in range(2)] for idx in range(2): self.exposure[idx].setSuffix(" ms") self.exposure[idx].setRange(0, 0) self.laser_status = QtGui.QLineEdit() self.laser_status.setReadOnly(True) self.f_ref = QtGui.QDoubleSpinBox() self.f_ref.setSuffix(" THz") self.f_ref.setDecimals(7) self.f_ref.setSingleStep(1e-6) self.f_ref.setRange(0., 1000.) # context menu self.menu = QtGui.QMenu() self.ref_editable = QtGui.QAction("Enable reference changes", self.dock) self.ref_editable.setCheckable(True) self.menu.addAction(self.ref_editable) for label in [self.detuning, self.name, self.frequency, self.f_ref]: label.contextMenuEvent = lambda ev: self.menu.popup( QtGui.QCursor.pos()) label.mouseReleaseEvent = lambda ev: None # layout GUI self.layout.addItem(self.osa, colspan=2) self.layout.nextRow() self.layout.addItem(self.detuning, colspan=2) self.layout.nextRow() self.layout.addItem(self.name) self.layout.addItem(self.frequency) self.dock.addWidget(self.layout, colspan=7) self.dock.addWidget(self.fast_mode, row=1, col=1) self.dock.addWidget(self.auto_exposure, row=2, col=1) self.dock.addWidget(QtGui.QLabel("Reference"), row=1, col=2) self.dock.addWidget(QtGui.QLabel("Exp 0"), row=1, col=3) self.dock.addWidget(QtGui.QLabel("Exp 1"), row=1, col=4) self.dock.addWidget(QtGui.QLabel("Status"), row=1, col=5) self.dock.addWidget(self.f_ref, row=2, col=2) self.dock.addWidget(self.exposure[0], row=2, col=3) self.dock.addWidget(self.exposure[1], row=2, col=4) self.dock.addWidget(self.laser_status, row=2, col=5) # Sort the layout to make the most of available space self.layout.ci.setSpacing(4) self.layout.ci.setContentsMargins(2, 2, 2, 2) self.dock.layout.setContentsMargins(0, 0, 0, 4) for i in [0, 6]: self.dock.layout.setColumnMinimumWidth(i, 4) for i in [2, 5]: self.dock.layout.setColumnStretch(i, 2) for i in [1, 3, 4]: self.dock.layout.setColumnStretch(i, 1) self.cb_queue = [] def add_async_cb(data): self.cb_queue.append(data) self.wake_loop.set() self.ref_editable.triggered.connect(self.ref_editable_cb) self.fast_mode.clicked.connect(functools.partial(add_async_cb, ("fast_mode",))) self.auto_exposure.clicked.connect(functools.partial(add_async_cb, ("auto_expose",))) self.f_ref.valueChanged.connect(functools.partial(add_async_cb, ("f_ref",))) for ccd, exp in enumerate(self.exposure): exp.valueChanged.connect(functools.partial(add_async_cb, ("exposure", ccd))) self.fut = asyncio.ensure_future(self.loop()) self._gui.loop.run_until_complete(self.setConnected(False))
for plt in mouse_conn_plot, human_conn_plot: plt.setFixedWidth(220) plt.setYRange(0, 0.3) plt.getAxis('left').setStyle(tickLength=0) plt.getAxis('bottom').setStyle(tickLength=0) plt.getAxis('left').setScale(100) # set up distance plots mouse_dist_plots = [] mouse_hist_plots = [] human_dist_plots = [] human_hist_plots = [] for row, plots in enumerate([(mouse_hist_plots, mouse_dist_plots), (human_hist_plots, human_dist_plots)]): hist_plots, dist_plots = plots xlabel = pg.LabelItem(u'distance (µm)') xlabel.setFixedHeight(20) win.addItem(xlabel, row=row * 3 + 2, col=1, colspan=5) for i in range(5): hist_plot = win.addPlot(row * 3, i + 1) dist_plot = win.addPlot(row * 3 + 1, i + 1) hist_plots.append(hist_plot) dist_plots.append(dist_plot) hist_plot.setMaximumHeight(40) dist_plot.setXLink(hist_plot) hist_plot.getAxis('bottom').hide() dist_plot.getAxis('bottom').setScale(1e6) dist_plot.getAxis('left').setScale(100) hist_plot.setXLink(mouse_hist_plots[0])
w.show() w.resize(600, 600) w.setWindowTitle('pyqtgraph example: Draw') view = pg.ViewBox(enableMouse=True) w.setCentralItem(view) ## lock the aspect ratio view.setAspectLocked(True) view.invertY() ## Create image item imgitem = pg.ImageItem(axisOrder='row-major') view.addItem(imgitem) labelitem = pg.LabelItem() view.addItem(labelitem) img = data.astronaut() # img = np.rot90(data.astronaut(), k=-1, axes=(0,1)) print('img is', img.shape) imgitem.setImage(img) view.autoRange(padding=0) labelitem.setText("hej", color='CCFF00') ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
def __init__(self): QtWidgets.QMainWindow.__init__(self) # This is the top level widget self.centralWidget = QtWidgets.QWidget() # Make grid layout and add button + graph into it self.layout = QtWidgets.QGridLayout() # Add a grid inside the QGridLayout self.centralWidget.setLayout(self.layout) self.setCentralWidget(self.centralWidget) self.setWindowTitle('Picoscope Spectrum Analyzer') # Make a control panel widget that holds all buttons and such. #self.controlPanel = QtWidgets.QWidget() self.controlPanelLayout = QtWidgets.QGridLayout() #self.controlPanel.setLayout(self.controlPanelLayout) # Button for restarting average self.restartAvgBtn = QtWidgets.QPushButton("Restart average") self.restartAvgBtn.clicked.connect(self.restartAvg) # Label for showing the number of averaged traces self.avg_iter = 1 self.avg_iter_label = QtWidgets.QLabel('Average of: ' + str(self.avg_iter)) # Combobox for choosing how to average self.avgComboBox = QtWidgets.QComboBox() self.avgComboBox.addItems( ["Average", "Exponential Rolling Average", "Continuous"]) self.avgComboBox.currentIndexChanged[str].connect(self.setAvgType) self.avgType = "Average" self.numAvgSpinBox = QtWidgets.QSpinBox() self.numAvgSpinBox.setRange(1, 10000) self.numAvgSpinBox.setValue(10) self.avgAlpha = 2 / (self.numAvgSpinBox.value() + 1) # Choose number of points to do in rolling average self.numAvgSpinBoxLabel = QtWidgets.QLabel( 'Number of exponential averages') self.numAvgSpinBox.valueChanged.connect(self.setNumAvg) # Choose number of samples self.nSamplesList = [1 << i for i in range(8, 21)] self.nSamplesListLabels = [f'{i:.3e}' for i in self.nSamplesList] self.nSamplesComboBox = QtWidgets.QComboBox() self.nSamplesComboBox.addItems(self.nSamplesListLabels) self.nSamplesComboBox.currentIndexChanged.connect(self.setNSamples) self.nSamples = 1 << 12 self.nSamplesLabel = QtWidgets.QLabel('Number of samples') # Add window funtions self.wfComboBox = QtWidgets.QComboBox() self.wfComboBox.addItems([ 'hamming', 'boxcar', 'blackman', 'bartlett', 'hanning', ]) self.wfComboBoxLabel = QtWidgets.QLabel('Window Function') self.wfComboBox.currentIndexChanged[str].connect(self.changeWF) self.window = np.hamming(self.nSamples) # Stop button self.stopButton = QtWidgets.QPushButton('Stop averaging') self.stopButton.clicked.connect(self.stopAvg) self.avg = True # Max hold buttons self.maxHoldWidget = QtWidgets.QWidget() self.maxHoldLayout = QtWidgets.QHBoxLayout() # self.maxHoldWidget.setLayout(self.maxHoldLayout) self.maxHoldButtonGreen = QtWidgets.QPushButton('Max Hold') self.maxHoldButtonGreen.setStyleSheet("background-color: green") self.maxHoldButtonGreen.clicked.connect(lambda: self.setMaxHold('g')) self.maxHoldButtonBlue = QtWidgets.QPushButton('Max Hold') self.maxHoldButtonBlue.setStyleSheet("background-color: blue") self.maxHoldButtonBlue.clicked.connect(lambda: self.setMaxHold('b')) self.maxHoldButtonRed = QtWidgets.QPushButton('Max Hold') self.maxHoldButtonRed.setStyleSheet("background-color: red") self.maxHoldButtonRed.clicked.connect(lambda: self.setMaxHold('r')) self.resetMaxHoldButton = QtWidgets.QPushButton('Reset max hold') self.resetMaxHoldButton.clicked.connect(self.resetMaxHold) self.maxHoldLayout.addWidget(self.maxHoldButtonGreen, ) self.maxHoldLayout.addWidget(self.maxHoldButtonBlue) self.maxHoldLayout.addWidget(self.maxHoldButtonRed) self.maxHoldList = { 'r': np.array([]), 'g': np.array([]), 'b': np.array([]) } self.colorPens = { 'r': (200, 0, 0, 180), 'g': (0, 200, 0, 180), 'b': (0, 0, 200, 180) } # Add save button self.saveButton = QtWidgets.QPushButton('Save trace') self.saveButton.clicked.connect(self.saveFile) # Add info label box self.infoLabel = QtWidgets.QLabel() self.infoLabel.setText(f'RBW: {10e6/self.nSamples:.1f} Hz') # Select Channel combobox self.channelComboBox = QtWidgets.QComboBox() self.channelLabel = QtWidgets.QLabel('Channel: ') self.channelComboBox.addItems(['A', 'B']) self.channelComboBox.currentIndexChanged.connect(self.changeChannel) self.channel = 0 # Add widgets to layout self.controlPanelLayout.addWidget(self.channelComboBox, 0, 1, 1, 1) self.controlPanelLayout.addWidget(self.channelLabel, 0, 0, 1, 1) # Add combobox for choosng type of average self.controlPanelLayout.addWidget(self.avgComboBox, 1, 0, 1, 1) # Add Stop-button self.controlPanelLayout.addWidget(self.stopButton, 1, 1, 1, 1) # Add button to restart average self.controlPanelLayout.addWidget( self.restartAvgBtn, 2, 1, ) self.controlPanelLayout.addWidget(self.avg_iter_label, 2, 0) # Add spinbox for choosing number of exponential averages self.controlPanelLayout.addWidget(self.numAvgSpinBoxLabel, 3, 0) self.controlPanelLayout.addWidget(self.numAvgSpinBox, 3, 1) # Add sample size function self.controlPanelLayout.addWidget(self.nSamplesLabel, 0, 2) self.controlPanelLayout.addWidget(self.nSamplesComboBox, 0, 3) # Add window function stuff to control panel self.controlPanelLayout.addWidget(self.wfComboBoxLabel, 1, 2) self.controlPanelLayout.addWidget(self.wfComboBox, 1, 3) # Add max-hold buttons self.controlPanelLayout.addLayout(self.maxHoldLayout, 2, 2, 1, 2) self.controlPanelLayout.addWidget(self.resetMaxHoldButton, 3, 2, 1, 2) # Save Button self.controlPanelLayout.addWidget(self.saveButton, 0, 4, 1, 2) self.controlPanelLayout.addWidget(self.infoLabel, 2, 4, 1, 2) # spacer = QtWidgets.QSpacerItem( # 1, 1, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) # self.controlPanelLayout.addItem(spacer, 20, 0) # Add control panel to grid. self.layout.addLayout(self.controlPanelLayout, 4, 0, 1, 1) # Add plot to grid self.plotWidget = pg.GraphicsLayoutWidget() self.xLabel = pg.LabelItem(justify='left') self.layout.addWidget(self.plotWidget, 0, 0, 4, 1) self.plotWidget.addItem(self.xLabel, row=1) self.specPlot = self.plotWidget.addPlot( row=0, col=0, labels={ 'bottom': ('Frequency', 'Hz'), 'left': '<font>V<sup>2</sup>/Hz<\font>' }) self.specPlot.setLogMode(y=True) self.specPlot.showGrid(x=True, y=True, alpha=0.15) self.resize(1400, 800) self.show() # [self.scope, self.rate] = setupScope(self.nSamples) # self.scopeRunning = False self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(50) self.prevSpec = 0 self.lastValue = None self.lastData = None self.lastUpdate = None self.vb = self.specPlot.vb self._proxy = pg.SignalProxy(self.specPlot.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
def configure_gui(): import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore #Define global variables global mel_curve global led_plot global r_pen global g_pen global b_pen global r_curve global g_curve global b_curve global x_data global app # Create GUI window app = QtGui.QApplication([]) view = pg.GraphicsView() layout = pg.GraphicsLayout(border=(100, 100, 100)) view.setCentralItem(layout) view.show() view.setWindowTitle('Visualization') view.resize(800, 600) # Mel filterbank plot fft_plot = layout.addPlot(title='Filterbank Output', colspan=4) fft_plot.setRange(yRange=[-0.1, 1.2]) fft_plot.disableAutoRange(axis=pg.ViewBox.YAxis) x_data = np.array(range(1, config.N_FFT_BINS + 1)) mel_curve = pg.PlotCurveItem() mel_curve.setData(x=x_data, y=x_data * 0) fft_plot.addItem(mel_curve) # Visualization plot layout.nextRow() led_plot = layout.addPlot(title='Visualization Output', colspan=4) led_plot.setRange(yRange=[-5, 260]) led_plot.disableAutoRange(axis=pg.ViewBox.YAxis) # Pen for each of the color channel curves r_pen = pg.mkPen((255, 30, 30, 200), width=4) g_pen = pg.mkPen((30, 255, 30, 200), width=4) b_pen = pg.mkPen((30, 30, 255, 200), width=4) # Color channel curves r_curve = pg.PlotCurveItem(pen=r_pen) g_curve = pg.PlotCurveItem(pen=g_pen) b_curve = pg.PlotCurveItem(pen=b_pen) # Define x data x_data = np.array(range(1, config.N_PIXELS + 1)) r_curve.setData(x=x_data, y=x_data * 0) g_curve.setData(x=x_data, y=x_data * 0) b_curve.setData(x=x_data, y=x_data * 0) # Add curves to plot led_plot.addItem(r_curve) led_plot.addItem(g_curve) led_plot.addItem(b_curve) # Frequency range label freq_label = pg.LabelItem('') # Frequency slider def freq_slider_change(tick): minf = freq_slider.tickValue(0)**2.0 * (config.MIC_RATE / 2.0) maxf = freq_slider.tickValue(1)**2.0 * (config.MIC_RATE / 2.0) t = 'Frequency range: {:.0f} - {:.0f} Hz'.format(minf, maxf) freq_label.setText(t) config.MIN_FREQUENCY = minf config.MAX_FREQUENCY = maxf dsp.create_mel_bank() freq_slider = pg.TickSliderItem(orientation='bottom', allowAdd=False) freq_slider.addTick((config.MIN_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) freq_slider.addTick((config.MAX_FREQUENCY / (config.MIC_RATE / 2.0))**0.5) freq_slider.tickMoveFinished = freq_slider_change freq_label.setText('Frequency range: {} - {} Hz'.format( config.MIN_FREQUENCY, config.MAX_FREQUENCY)) # Effect selection active_color = '#16dbeb' inactive_color = '#FFFFFF' def energy_click(x): global visualization_effect visualization_effect = visualize_energy energy_label.setText('Energy', color=active_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=inactive_color) def energy_spectrum_click(x): global visualization_effect visualization_effect = visualize_energy_spectrum energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=active_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=inactive_color) def scroll_click(x): global visualization_effect visualization_effect = visualize_scroll energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=active_color) spectrum_label.setText('Spectrum', color=inactive_color) def spectrum_click(x): global visualization_effect visualization_effect = visualize_spectrum energy_label.setText('Energy', color=inactive_color) energy_spectr_label.setText('Energy spectr', color=inactive_color) scroll_label.setText('Scroll', color=inactive_color) spectrum_label.setText('Spectrum', color=active_color) # Create effect "buttons" (labels with click event) energy_label = pg.LabelItem('Energy') energy_spectr_label = pg.LabelItem('Energy Spectr') scroll_label = pg.LabelItem('Scroll') spectrum_label = pg.LabelItem('Spectrum') energy_label.mousePressEvent = energy_click energy_spectr_label.mousePressEvent = energy_spectrum_click scroll_label.mousePressEvent = scroll_click spectrum_label.mousePressEvent = spectrum_click energy_click(0) # Layout layout.nextRow() layout.addItem(freq_label, colspan=4) layout.nextRow() layout.addItem(freq_slider, colspan=4) layout.nextRow() layout.addItem(energy_label) layout.addItem(scroll_label) layout.addItem(spectrum_label) layout.addItem(energy_spectr_label)