def initUI(self, e=None): """ Definition, configuration and initialisation of the ODMR GUI. @param object e: Fysom.event object from Fysom class. An object created by the state machine module Fysom, which is connected to a specific event (have a look in the Base Class). This object contains the passed event, the state before the event happened and the destination of the state which should be reached after the event had happened. This init connects all the graphic modules, which were created in the *.ui file and configures the event handling between the modules. """ self._no_logic = self.get_in_connector('nuclearoperationslogic') self._save_logic = self.get_in_connector('savelogic') # Create the MainWindow to display the GUI self._mw = NuclearOperationsMainWindow() # Add save file tag input box self._mw.save_tag_LineEdit = QtWidgets.QLineEdit(self._mw) self._mw.save_tag_LineEdit.setMaximumWidth(200) self._mw.save_tag_LineEdit.setToolTip('Enter a nametag which will be\n' 'added to the filename.') self._mw.save_ToolBar.addWidget(self._mw.save_tag_LineEdit) # Set the values from the logic to the GUI: # Set the pulser parameter: self._mw.electron_rabi_periode_DSpinBox.setValue( self._no_logic.electron_rabi_periode * 1e9) self._mw.pulser_mw_freq_DSpinBox.setValue( self._no_logic.pulser_mw_freq / 1e6) self._mw.pulser_mw_amp_DSpinBox.setValue(self._no_logic.pulser_mw_amp) self._mw.pulser_mw_ch_SpinBox.setValue(self._no_logic.pulser_mw_ch) self._mw.nuclear_rabi_period0_DSpinBox.setValue( self._no_logic.nuclear_rabi_period0 * 1e6) self._mw.pulser_rf_freq0_DSpinBox.setValue( self._no_logic.pulser_rf_freq0 / 1e6) self._mw.pulser_rf_amp0_DSpinBox.setValue( self._no_logic.pulser_rf_amp0) self._mw.nuclear_rabi_period1_DSpinBox.setValue( self._no_logic.nuclear_rabi_period1 * 1e6) self._mw.pulser_rf_freq1_DSpinBox.setValue( self._no_logic.pulser_rf_freq1 / 1e6) self._mw.pulser_rf_amp1_DSpinBox.setValue( self._no_logic.pulser_rf_amp1) self._mw.pulser_rf_ch_SpinBox.setValue(self._no_logic.pulser_rf_ch) self._mw.pulser_laser_length_DSpinBox.setValue( self._no_logic.pulser_laser_length * 1e9) self._mw.pulser_laser_amp_DSpinBox.setValue( self._no_logic.pulser_laser_amp) self._mw.pulser_laser_ch_SpinBox.setValue( self._no_logic.pulser_laser_ch) self._mw.num_singleshot_readout_SpinBox.setValue( self._no_logic.num_singleshot_readout) self._mw.pulser_idle_time_DSpinBox.setValue( self._no_logic.pulser_idle_time * 1e9) self._mw.pulser_detect_ch_SpinBox.setValue( self._no_logic.pulser_detect_ch) # set the measurement parameter: self._mw.current_meas_asset_name_ComboBox.clear() self._mw.current_meas_asset_name_ComboBox.addItems( self._no_logic.get_meas_type_list()) if self._no_logic.current_meas_asset_name != '': index = self._mw.current_meas_asset_name_ComboBox.findText( self._no_logic.current_meas_asset_name, QtCore.Qt.MatchFixedString) if index >= 0: self._mw.current_meas_asset_name_ComboBox.setCurrentIndex( index) if self._no_logic.current_meas_asset_name == 'Nuclear_Frequency_Scan': self._mw.x_axis_start_DSpinBox.setValue( self._no_logic.x_axis_start / 1e6) self._mw.x_axis_step_DSpinBox.setValue(self._no_logic.x_axis_step / 1e6) elif self._no_logic.current_meas_asset_name in [ 'Nuclear_Rabi', 'QSD_-_Artificial_Drive', 'QSD_-_SWAP_FID', 'QSD_-_Entanglement_FID' ]: self._mw.x_axis_start_DSpinBox.setValue( self._no_logic.x_axis_start * 1e6) self._mw.x_axis_step_DSpinBox.setValue(self._no_logic.x_axis_step * 1e6) self._mw.x_axis_num_points_SpinBox.setValue( self._no_logic.x_axis_num_points) self._mw.num_of_meas_runs_SpinBox.setValue( self._no_logic.num_of_meas_runs) # set the optimize parameters: self._mw.optimize_period_odmr_SpinBox.setValue( self._no_logic.optimize_period_odmr) self._mw.optimize_period_confocal_SpinBox.setValue( self._no_logic.optimize_period_confocal) self._mw.odmr_meas_freq0_DSpinBox.setValue( self._no_logic.odmr_meas_freq0 / 1e6) self._mw.odmr_meas_freq1_DSpinBox.setValue( self._no_logic.odmr_meas_freq1 / 1e6) self._mw.odmr_meas_freq2_DSpinBox.setValue( self._no_logic.odmr_meas_freq2 / 1e6) self._mw.odmr_meas_runtime_DSpinBox.setValue( self._no_logic.odmr_meas_runtime) self._mw.odmr_meas_freq_range_DSpinBox.setValue( self._no_logic.odmr_meas_freq_range / 1e6) self._mw.odmr_meas_step_DSpinBox.setValue( self._no_logic.odmr_meas_step / 1e6) self._mw.odmr_meas_power_DSpinBox.setValue( self._no_logic.odmr_meas_power) # set the mw parameters for measurement self._mw.mw_cw_freq_DSpinBox.setValue(self._no_logic.mw_cw_freq / 1e6) self._mw.mw_cw_power_DSpinBox.setValue(self._no_logic.mw_cw_power) self._mw.mw_on_odmr_peak_ComboBox.clear() # convert on the fly the integer entries to str entries: self._mw.mw_on_odmr_peak_ComboBox.addItems( [str(elem) for elem in self._no_logic.get_available_odmr_peaks()]) # set gated counter parameters: self._mw.gc_number_of_samples_SpinBox.setValue( self._no_logic.gc_number_of_samples) self._mw.gc_samples_per_readout_SpinBox.setValue( self._no_logic.gc_samples_per_readout) # Create the graphic display for the measurement: self.nuclear_ops_graph = pg.PlotDataItem( self._no_logic.x_axis_list, self._no_logic.y_axis_list, pen=QtGui.QPen(QtGui.QColor(212, 85, 0, 255))) self._mw.nulcear_ops_GraphicsView.addItem(self.nuclear_ops_graph) # Set the proper initial display: self.current_meas_asset_name_changed() # Connect the signals: self._mw.current_meas_asset_name_ComboBox.currentIndexChanged.connect( self.current_meas_asset_name_changed) # adapt the unit according to the # Connect the start and stop signals: self._mw.action_run_stop.toggled.connect(self.start_stop_measurement) self._mw.action_continue.toggled.connect( self.continue_stop_measurement) self._mw.action_save.triggered.connect(self.save_measurement) self._no_logic.sigMeasurementStopped.connect( self._update_display_meas_stopped) # Connect graphic update: self._no_logic.sigCurrMeasPointUpdated.connect(self.update_meas_graph) self._no_logic.sigCurrMeasPointUpdated.connect( self.update_meas_parameter)
def show_data(self): f = open(self.myfile, 'r') lines = f.readlines() result = [] for x in lines: result.append(x.split('#')[0]) f.close() a = [x for x in result if x != ''] self.time = np.zeros(len(a)) self.counts1 = np.zeros(len(a)) self.error1 = np.zeros(len(a)) self.counts2 = np.zeros(len(a)) self.error2 = np.zeros(len(a)) self._mw.data_plot.clear() self._mw.processeddataplot.clear() for i in range(len(a)): self.time[i]=np.asarray(a[i].split(), dtype=np.float32)[0] self.counts1[i] = np.asarray(a[i].split(), dtype=np.float32)[1] self.error1[i] = np.asarray(a[i].split(), dtype=np.float32)[3] self.counts2[i] = np.asarray(a[i].split(), dtype=np.float32)[2] self.error2[i] = np.asarray(a[i].split(), dtype=np.float32)[4] #self.time = self.time[np.where(self.time >= 268*1e-9)] #self.counts1 = self.counts1[np.where(self.time >= 268*1e-9)] #self.counts2 = self.counts2[np.where(self.time >= 268*1e-9)] self.data_image1 = pg.PlotDataItem(self.time*1e+9, self.counts1, pen=pg.mkPen(palette.c1, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c1, symbolBrush=palette.c1, symbolSize=7) self._mw.data_plot.addItem(self.data_image1) self.data_image2 = pg.PlotDataItem(self.time * 1e+9, self.counts2, pen=pg.mkPen(palette.c3, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c3, symbolBrush=palette.c3, symbolSize=7) self._mw.data_plot.addItem(self.data_image2) self._mw.data_plot.setLabel(axis='left', text='Counts', units='Counts/s') self._mw.data_plot.setLabel(axis='bottom', text='time', units='ns') self._mw.data_plot.showGrid(x=True, y=True, alpha=0.8) self.baseline = np.sum(self.counts2+self.counts1)/len(self.counts2)/2 C0_up = self.baseline / (1 - 0.01 * self._mw.contrast.value() / 2) C0_down = C0_up * (1 - 0.01 * self._mw.contrast.value()) counts = self.counts2 - self.counts1 self.T = self.time * 16 * self._mw.sequence_order.value() self.normalized_counts = (counts) / (C0_up - C0_down) self.normalized_image = pg.PlotDataItem(self.time, self.normalized_counts, pen=pg.mkPen(palette.c2, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c2, symbolBrush=palette.c2, symbolSize=7) self._mw.processeddataplot.addItem(self.normalized_image) self._mw.processeddataplot.setLabel(axis='left', text='Counts', units='Counts/s') self._mw.processeddataplot.setLabel(axis='bottom', text='time', units='s') self._mw.processeddataplot.showGrid(x=True, y=True, alpha=0.8) self._filter_function_button_fired()
def __init__(self, parent, cmdp, statistics_font_resizer, marker_font_resizer, name, display_name=None, units=None, y_limit=None, y_log_min=None, y_range=None, **kwargs): QtCore.QObject.__init__(self, parent=parent) self._cmdp = cmdp self.text_item = None self.name = name self.log = logging.getLogger(__name__ + '.' + name) self.units = units self.config = { 'name': name, 'y-axis': { 'limit': y_limit, 'log_min': y_log_min, 'range': 'auto' if y_range is None else y_range, 'scale': 'linear', }, } self._statistics_font_resizer = statistics_font_resizer self.markers: Dict[str, Marker] = None # WARNING: for reference only self._marker_font_resizer = marker_font_resizer self._markers_single = {} self._markers_dual = {} self._is_min_max_active = False # when zoomed out enough to display min/max self._y_pan = None self.vb = SignalViewBox(name=self.name) if y_limit is not None: y_min, y_max = y_limit self.vb.setLimits(yMin=y_min, yMax=y_max) self.vb.setYRange(y_min, y_max, padding=0) self.y_axis = YAxis(name, cmdp, log_enable=y_log_min is not None) self.y_axis.linkToView(self.vb) self.y_axis.setGrid(128) self._y_range_now = [None, None] self._most_recent_data = None if display_name is None: display_name = name if display_name is not None: self.y_axis.setLabel(text=display_name, units=units) self.text_item = SignalStatistics(field=self.name, units=units, cmdp=cmdp) self.curve_mean = pg.PlotDataItem() self.curve_max = pg.PlotDataItem() self.curve_min = pg.PlotDataItem() self.curve_range = None self.vb.addItem(self.curve_max) self.vb.addItem(self.curve_min) self.vb.addItem(self.curve_mean) self.curve_max.hide() self.curve_min.hide() self.y_axis.sigConfigEvent.connect(self.y_axis_config_update) self.y_axis.sigWheelZoomYEvent.connect(self.on_wheelZoomY) self.y_axis.sigPanYEvent.connect(self.on_panY) self.y_axis.range_set(self.config['y-axis']['range']) self.vb.sigYRangeChanged.connect(self._on_y_range_changed) cmdp.subscribe('Widgets/Waveform/grid_y', self._on_grid_y, update_now=True) cmdp.subscribe('Widgets/Waveform/show_min_max', self._on_show_min_max, update_now=True) cmdp.subscribe('Widgets/Waveform/trace_width', self._on_colors, update_now=True) cmdp.subscribe('Appearance/__index__', self._on_colors, update_now=True)
def test_clear_in_step_mode(): w = pg.PlotWidget() c = pg.PlotDataItem([1, 4, 2, 3], [5, 7, 6], stepMode="center") w.addItem(c) c.clear()
# a standard pyqtgraph plot_item w = pg.PlotWidget() # add legend to the plot, for that we have to give a name to plot items w.addLegend() # add a Y2 axis from taurus.qt.qtgui.tpg import Y2ViewBox y2ViewBox = Y2ViewBox() y2ViewBox.attachToPlotItem(w.getPlotItem()) # adding a regular data item (non-taurus) c1 = pg.PlotDataItem( name="st plot", pen=dict(color="y", width=3, style=QtCore.Qt.DashLine), fillLevel=0.3, fillBrush="g", ) c1.setData(numpy.arange(300) / 300.0) w.addItem(c1) # adding a taurus data item c2 = TaurusPlotDataItem(name="st2 plot", pen="r", symbol="o", symbolSize=10) c2.setModel("sys/tg_test/1/wave") w.addItem(c2)
def peak_detection(blueThresh, redThresh, bluePeakThresh, redPeakThresh, image_plot, stack, czpro): markers = ['C', 'A', 'G', 'T'] colors = ['r', 'b'] score = ascore = gscore = tscore = spseries = pd.Series() df = pd.DataFrame({ "ident": [], 'stimes': [], 'etimes': [], 'maxes': [], 'mins': [] }) seqdf = pd.DataFrame({'base': [], 'times': []}) time1, intensity1 = image_plot.roiCurve1.getData() time2, intensity2 = image_plot.roiCurve2.getData() intensities = [intensity1, intensity2] # self.firingplotlist = [] peak_series = pd.Series() min_series = pd.Series() firing_plot_list = [] def threshold_data(data, threshold, noise, other_data): intensity_high_enough = data > thresh intensity_greater_than_other = data > other_data[idx - 1] firing_points = np.where(intensity_high_enough & intensity_greater_than_other)[0] boundary_points = np.diff(firing_points) boundary_idxs = list(np.concatenate(np.argwhere(boundary_points))) firing_bounds = list(zip(boundary_idxs[::2], boundary_idxs[1::2])) for start, end in firing_bounds: # sp = start_points[idx] # ep = end_points[idx] + 1 # end += 1 x_values = np.arange(start, end) intensities = intensity[start:end] curve_pen = pg.mkPen(colors[idx], width=2) curve = pg.PlotDataItem(x=x_values, y=intensities, pen=curve_pen) firing_plot_list.append(curve) # Plotting the curves highlighting each base image_plot.getRoiPlot().addItem(curve) try: peaks, mins = peakdet(v=intensities, delta=noise, x=x_values) if len(peaks) == 0 or len(mins) == 0: peaks = np.NAN substack = np.mean(stack[start:end], 0) call = get_call(substack, czpro, idx) seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [start] }), ignore_index=True) else: # point = pg.PlotDataItem(maxes, pen = None, symbol = 'o', symbolBrush = 'g') # self.p1.getRoiPlot().addItem(point) # self.firingplotlist.append(point) # point = pg.PlotDataItem(mins, pen = None, symbol = 'o', symbolBrush = 'r') # self.p1.getRoiPlot().addItem(point) # self.firingplotlist.append(point) for idx, x in enumerate(peaks): if idx == 0: ssp = start sep = int(mins[idx][0]) elif idx == len(peaks) - 1: ssp = int(mins[idx - 1][0]) sep = end else: ssp = int(mins[idx - 1][0]) sep = int(mins[idx][0]) substack = np.mean(stack[ssp:sep + 1], 0) call = get_call(substack, czpro, idx) seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [ssp] }), ignore_index=True) peak_series = peak_series.append(pd.Series([peaks])) min_series = min_series.append(pd.Series([mins])) except Exception as e: raise ValueError for idx, intensity in enumerate(intensities): if idx == 0: thresh = redThresh noise = redPeakThresh elif idx == 1: thresh = blueThresh noise = bluePeakThresh else: raise IndexError("Intensity index out of range") intensity_high_enough = intensity > thresh intensity_greater_than_other = intensity > intensities[idx - 1] firing_points = np.where(intensity_high_enough & intensity_greater_than_other)[0] boundary_points = np.diff(firing_points) boundary_idxs = np.concatenate([[0], np.concatenate( np.argwhere(boundary_points > 1)), [len(boundary_points)]]) # Skipping doesn't work for intervals of length 1 firing_bounds = list( zip(firing_points[boundary_idxs[::2]], firing_points[boundary_idxs[1::2]])) df = df.append(pd.DataFrame({ "ident": [idx] * len(firing_bounds), 'stimes': [x for x, _ in firing_bounds], 'etimes': [y for _, y in firing_bounds] }), ignore_index=True) # Check that length of start and end points is the same for start, end in firing_bounds: # sp = start_points[idx] # ep = end_points[idx] + 1 # end += 1 x_values = np.arange(start, end) intensities = intensity[start:end] curve_pen = pg.mkPen(colors[idx], width=2) curve = pg.PlotDataItem(x=x_values, y=intensities, pen=curve_pen) firing_plot_list.append(curve) # Plotting the curves highlighting each base image_plot.getRoiPlot().addItem(curve) try: maxes, mins = peakdet(v=intensities, delta=noise, x=x_values) if len(maxes) == 0 or len(mins) == 0: maxes = np.NAN substack = np.mean(stack[start:end], 0) call = get_call(substack, czpro, idx) seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [start] }), ignore_index=True) else: # point = pg.PlotDataItem(maxes, pen = None, symbol = 'o', symbolBrush = 'g') # self.p1.getRoiPlot().addItem(point) # self.firing_plot_list.append(point) # point = pg.PlotDataItem(mins, pen = None, symbol = 'o', symbolBrush = 'r') # self.p1.getRoiPlot().addItem(point) # self.firing_plot_list.append(point) for idx, x in enumerate(maxes): if idx == 0: ssp = start sep = int(mins[idx][0]) elif idx == len(maxes) - 1: ssp = int(mins[idx - 1][0]) sep = end else: ssp = int(mins[idx - 1][0]) sep = int(mins[idx][0]) substack = np.mean(stack[ssp:sep + 1], 0) call = get_call(substack, czpro, idx) seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [ssp] }), ignore_index=True) peak_series = peak_series.append(pd.Series([maxes])) min_series = min_series.append(pd.Series([mins])) except Exception as e: raise ValueError seqdf = seqdf.sort(['times', 'base']) base_colors = {'C': 'r', 'A': 'y', 'G': 'g', 'T': 'b'} seq_plot_list = [] for idx, x in enumerate(seqdf.index): base = seqdf.base[idx] color = base_colors.get(base) if base in ['C', 'A']: intensity = intensities[0][int(seqdf.times[idx])] else: intensity = intensities[1][int(seqdf.times[idx])] text = pg.TextItem(base, color=color) seqplot = image_plot.getRoiPlot().addItem(text) if idx == 0: seq_plot_list = [text] else: seq_plot_list.append(text) text.setPos(seqdf.times[idx], intensity) print(seqdf.base.str.cat()) return seqdf, firing_plot_list, seq_plot_list
def __init__(self): # use QMainWindow in this early version to benefit from menu, tool bar, etc. super(Window, self).__init__() self.setGeometry(100, 100, 1080, 720) self.setWindowTitle('RubyRead') self.setWindowIcon(QtGui.QIcon('ruby4.png')) # self.setStyleSheet('font-size: 10pt') # create the main window widget and make it central self.mw = QtGui.QWidget() self.setCentralWidget(self.mw) # now make and set layout for the mw (main window) self.mw_layout = QtGui.QVBoxLayout() self.mw.setLayout(self.mw_layout) self.my_thread = myThread(self) self.my_thread.start() self.my_thread.callBackSignal.connect(self.thread_callback) # TODO figure out menubar # ###''' # ###Menu bar # ###''' # ### # ###self.main_menu = self.menuBar() # ###self.file_menu = self.main_menu.addMenu('File') # ###self.options_menu = self.main_menu.addMenu('Options') # ### # ###''' # ###Options Tab # ###''' # ### # ###self.options_window = QtGui.QTabWidget() # ### # #### make p calibration tab and widgets # ###self.p_calibration_tab = QtGui.QWidget() # ###self.p_calibration_tab_layout = QtGui.QVBoxLayout() # ###self.p_calibration_tab.setLayout(self.p_calibration_tab_layout) # ### # #### lambda naught options # ###self.set_lambda_naught_gb = QtGui.QGroupBox() # ###self.p_calibration_tab_layout.addWidget(self.set_lambda_naught_gb) # ###self.set_lambda_naught_gb.setTitle(u'\u03BB' + '<sub>0</sub>' + '(295)') # ###self.set_lambda_naught_label = QtGui.QLabel('Define' + u'\u03BB' + '<sub>0</sub>(295) from:') # ###self.lambda_from_fit_btn = QtGui.QPushButton('Fit') # ###self.lambda_from_target_btn = QtGui.QPushButton('Target') # ### # #### connect signals # ###self.lambda_from_fit_btn.clicked.connect(lambda: self.set_lambda_naught('fit')) # ###self.lambda_from_target_btn.clicked.connect(lambda: self.set_lambda_naught('target')) # ### # #### add widgets to layout # ###self.set_lambda_naught_vb = QtGui.QVBoxLayout() # ###self.set_lambda_naught_gb.setLayout(self.set_lambda_naught_vb) # ###self.set_lambda_naught_vb.addWidget(self.set_lambda_naught_label) # ### # ###self.set_lambda_btns_layout = QtGui.QHBoxLayout() # ###self.set_lambda_btns_layout.addWidget(self.lambda_from_fit_btn) # ###self.set_lambda_btns_layout.addWidget(self.lambda_from_target_btn) # ###self.set_lambda_naught_vb.addLayout(self.set_lambda_btns_layout) # ### # ### # ### # ### # ### # ### # ### # ### # ###self.options_window.addTab(self.p_calibration_tab, 'P Calibration') # ### # ###self.options_window.show() ''' Custom Toolbar ''' # make custom toolbar for top of main window self.tb = QtGui.QWidget() self.tb_layout = QtGui.QHBoxLayout() self.tb_layout.setAlignment(QtCore.Qt.AlignLeft) self.tb.setLayout(self.tb_layout) # make custom toolbar widgets self.take_spec_label = QtGui.QLabel('Collect') self.take_one_spec_btn = QtGui.QPushButton('1') self.take_n_spec_btn = QtGui.QPushButton('n') self.take_n_spec_btn.setCheckable(True) self.fit_spec_label = QtGui.QLabel('Fit') self.fit_one_spec_btn = QtGui.QPushButton('1') self.fit_n_spec_btn = QtGui.QPushButton('n') self.fit_n_spec_btn.setCheckable(True) self.save_spec_label = QtGui.QLabel('Save') self.save_spec_data_btn = QtGui.QPushButton('Data') self.save_spec_plot_btn = QtGui.QPushButton('Plot') # connect custom toolbar signals self.take_one_spec_btn.clicked.connect(lambda: start_timer(1)) self.take_n_spec_btn.clicked.connect(lambda: start_timer(0)) self.fit_one_spec_btn.clicked.connect(fit_spectrum) # add custom toolbar widgets to toolbar layout self.tb_layout.addWidget(self.take_spec_label) self.tb_layout.addWidget(self.take_one_spec_btn) self.tb_layout.addWidget(self.take_n_spec_btn) self.tb_layout.addSpacing(20) self.tb_layout.addWidget(self.fit_spec_label) self.tb_layout.addWidget(self.fit_one_spec_btn) self.tb_layout.addWidget(self.fit_n_spec_btn) self.tb_layout.addSpacing(20) self.tb_layout.addWidget(self.save_spec_label) self.tb_layout.addWidget(self.save_spec_data_btn) self.tb_layout.addWidget(self.save_spec_plot_btn) # add custom toolbar to main window self.mw_layout.addWidget(self.tb) ''' Plot Window ''' # make the plot window for the left side of bottom layout self.pw = pg.PlotWidget(name='Plot1') # ###EXPERIMENT WITH STYLE### self.pw.setTitle('Spectrum', size='12pt') # label_style = {'color': '#808080', 'font-size': '11px'} self.pw.plotItem.getAxis('left').enableAutoSIPrefix(False) self.pw.setLabel('left', 'Intensity', units='counts') #, **label_style) self.pw.setLabel('bottom', 'Wavelength', units='nm') # create plot items (need to be added when necessary) self.raw_data = pg.PlotDataItem() self.fit_data = pg.PlotDataItem() self.r1_data = pg.PlotDataItem() self.r2_data = pg.PlotDataItem() self.bg_data = pg.PlotDataItem() # self.ref_data = pg.PlotDataItem() # self.target_data = pg.PlotDataItem() # stylize plot items self.fit_data.setPen(color='r', width=2) self.r1_data.setPen(color='g', style=QtCore.Qt.DashLine) self.r2_data.setPen(color='b', style=QtCore.Qt.DashLine) self.bg_data.setPen(color='c', style=QtCore.Qt.DashLine) line_dict = {'angle': 90, 'fill': 'k'} self.vline_press = pg.InfiniteLine(pos=694.260, angle=90.0, movable=False, pen='g', label='Fit', labelOpts=line_dict) self.vline_ref = pg.InfiniteLine(pos=694.260, angle=90.0, movable=False, pen='m', label='Reference', labelOpts=line_dict) self.vline_target = pg.InfiniteLine(pos=694.260, angle=90.0, movable=True, pen='y', label='Target', labelOpts=line_dict) # raw data is always visible, add rest when or as needed self.pw.addItem(self.raw_data) # create signal for target pressure line self.vline_target.sigPositionChanged.connect(self.target_line_moved) # ###LAYOUT MANAGEMENT### # make layout for plot window and control window and add to main window self.bottom_layout = QtGui.QHBoxLayout() self.mw_layout.addLayout(self.bottom_layout) # add plot widget to bottom layout self.bottom_layout.addWidget(self.pw) # make the control window for the right side and add it to main window layout self.cw = QtGui.QWidget() self.cw.setMaximumWidth(300) self.bottom_layout.addWidget(self.cw) # make the layout for the control widget self.cw_layout = QtGui.QVBoxLayout() self.cw_layout.setAlignment(QtCore.Qt.AlignTop) self.cw.setLayout(self.cw_layout) ''' Spectrum control window ''' # make top right widget for spectrometer control self.spec_control = QtGui.QGroupBox() self.spec_control.setTitle('Spectrum Control') self.cw_layout.addWidget(self.spec_control) self.cw_layout.addSpacing(10) # make and set layout to Spectrum Control QGroupBox self.spec_control_layout = QtGui.QVBoxLayout() self.spec_control_layout.setAlignment(QtCore.Qt.AlignTop) # ###self.spec_control_layout.setSpacing(10) self.spec_control.setLayout(self.spec_control_layout) # ###make individual widgets to spec control grid layout # create count time label self.count_time_label = QtGui.QLabel('Integration time (ms)') # create, configure count time input self.count_time_input = QtGui.QLineEdit('100') self.count_time_input.setValidator(QtGui.QIntValidator()) self.count_time_input.setMaxLength(4) # crate count time shortcut buttons self.count_less_button = QtGui.QPushButton('') self.count_less_button.setIcon(QtGui.QApplication.style().standardIcon( QtGui.QStyle.SP_ArrowLeft)) self.count_less_button.setMinimumWidth(70) self.count_more_button = QtGui.QPushButton('') self.count_more_button.setIcon(QtGui.QApplication.style().standardIcon( QtGui.QStyle.SP_ArrowRight)) self.count_more_button.setMinimumWidth(70) # create checkbox widget, create and configure spinbox widget self.average_spec_cbox = QtGui.QCheckBox('Average n spectra') self.average_spec_sbox = QtGui.QSpinBox() self.average_spec_sbox.setMaximumWidth(50) self.average_spec_sbox.setValue(1) self.average_spec_sbox.setMinimum(1) self.average_spec_sbox.setMaximum(10) # connect signals self.count_time_input.editingFinished.connect(self.update_count_time) self.count_less_button.clicked.connect( lambda: self.count_time_shortcut('down')) self.count_more_button.clicked.connect( lambda: self.count_time_shortcut('up')) # add widgets to layout self.spec_control_layout.addWidget(self.count_time_label) self.count_time_layout = QtGui.QHBoxLayout() self.count_time_layout.addWidget(self.count_less_button) self.count_time_layout.addWidget(self.count_time_input) self.count_time_layout.addWidget(self.count_more_button) self.spec_control_layout.addLayout(self.count_time_layout) self.spec_control_layout.addSpacing(10) self.average_spec_layout = QtGui.QHBoxLayout() self.average_spec_layout.setAlignment(QtCore.Qt.AlignLeft) self.average_spec_layout.addWidget(self.average_spec_cbox) self.average_spec_layout.addWidget(self.average_spec_sbox) self.spec_control_layout.addLayout(self.average_spec_layout) ''' Plot control window ''' # make middle-right widget for plot control self.plot_control = QtGui.QGroupBox() self.plot_control.setTitle('Plot Control') self.cw_layout.addWidget(self.plot_control) self.cw_layout.addSpacing(10) # make and set primary layout for Plot Control QGroupBox self.plot_control_layout = QtGui.QVBoxLayout() self.plot_control_layout.setAlignment(QtCore.Qt.AlignTop) self.plot_control.setLayout(self.plot_control_layout) # ### make and add individual widgets to plot control # create show curves label and checkboxes self.show_fits_label = QtGui.QLabel('Select fitted data to show') self.show_curve_cbox = QtGui.QCheckBox('Curve') self.show_r1r2_cbox = QtGui.QCheckBox('R1, R2') self.show_bg_cbox = QtGui.QCheckBox('Background') # create show reference lines labels, cboxes, data displays, data inputs self.show_refs_label = QtGui.QLabel('Select markers to show') self.markers_lambda_heading = QtGui.QLabel(u'\u03BB' + ' (nm)') self.markers_pressure_heading = QtGui.QLabel('P (GPa)') self.markers_delta_p_heading = QtGui.QLabel(u'\u0394' + 'P (GPa)') self.show_fit_p_cbox = QtGui.QCheckBox('P(fit)') self.show_reference_p_cbox = QtGui.QCheckBox('P(ref)') self.show_ref_p_lambda = QtGui.QLabel('694.260') self.show_ref_p_pressure = QtGui.QLabel('0.00') self.show_ref_p_delta = QtGui.QLabel('0.00') self.show_target_p_cbox = QtGui.QCheckBox('P(target)') self.show_target_p_lambda = QtGui.QLineEdit('694.260') self.show_target_p_pressure = QtGui.QLineEdit('0.00') self.show_target_p_delta = QtGui.QLineEdit('0.00') # create reference buttons self.set_ref_p_label = QtGui.QLabel('Select data to define P(ref)') self.set_ref_fit_btn = QtGui.QPushButton('Fit') self.set_ref_target_btn = QtGui.QPushButton('Target') # create zoom buttons self.zoom_full_btn = QtGui.QPushButton('Full spectrum') self.zoom_roi_btn = QtGui.QPushButton('Zoom ROI') self.autoscale_cbox = QtGui.QCheckBox('Autoscale') # connect plot control signals self.show_curve_cbox.stateChanged.connect(self.show_curve_cbox_changed) self.show_r1r2_cbox.stateChanged.connect(self.show_r1r2_cbox_changed) self.show_bg_cbox.stateChanged.connect(self.show_bg_cbox_changed) self.show_fit_p_cbox.stateChanged.connect(self.show_fit_p_cbox_changed) self.show_reference_p_cbox.stateChanged.connect( self.show_reference_p_cbox_changed) self.show_target_p_cbox.stateChanged.connect( self.show_target_p_cbox_changed) self.show_target_p_lambda.editingFinished.connect( self.show_target_p_lambda_changed) self.show_target_p_pressure.editingFinished.connect( self.show_target_p_pressure_changed) self.show_target_p_delta.editingFinished.connect( self.show_target_p_delta_changed) self.set_ref_fit_btn.clicked.connect(self.set_ref_from_fit) self.set_ref_target_btn.clicked.connect(self.set_ref_from_target) self.zoom_full_btn.clicked.connect(self.zoom_full) self.zoom_roi_btn.clicked.connect(self.zoom_roi) # add widgets to layout self.plot_control_layout.addWidget(self.show_fits_label) self.reference_curves_layout = QtGui.QHBoxLayout() self.reference_curves_layout.addWidget(self.show_curve_cbox) # self.reference_curves_layout.addWidget(self.show_fit_p_cbox) self.reference_curves_layout.addWidget(self.show_r1r2_cbox) self.reference_curves_layout.addWidget(self.show_bg_cbox) self.plot_control_layout.addLayout(self.reference_curves_layout) self.plot_control_layout.addSpacing(10) self.plot_control_layout.addWidget(self.show_refs_label) self.reference_lines_layout = QtGui.QGridLayout() # self.reference_lines_layout.addWidget(self.show_fitted_p_cbox, 0, 0) self.reference_lines_layout.addWidget(self.markers_lambda_heading, 1, 1) self.reference_lines_layout.addWidget(self.markers_pressure_heading, 1, 2) self.reference_lines_layout.addWidget(self.markers_delta_p_heading, 1, 3) self.reference_lines_layout.addWidget(self.show_fit_p_cbox, 1, 0) self.reference_lines_layout.addWidget(self.show_reference_p_cbox, 2, 0) self.reference_lines_layout.addWidget(self.show_ref_p_lambda, 2, 1) self.reference_lines_layout.addWidget(self.show_ref_p_pressure, 2, 2) self.reference_lines_layout.addWidget(self.show_ref_p_delta, 2, 3) self.reference_lines_layout.addWidget(self.show_target_p_cbox, 3, 0) self.reference_lines_layout.addWidget(self.show_target_p_lambda, 3, 1) self.reference_lines_layout.addWidget(self.show_target_p_pressure, 3, 2) self.reference_lines_layout.addWidget(self.show_target_p_delta, 3, 3) self.plot_control_layout.addLayout(self.reference_lines_layout) self.plot_control_layout.addSpacing(10) self.plot_control_layout.addWidget(self.set_ref_p_label) self.set_reference_layout = QtGui.QHBoxLayout() self.set_reference_layout.addWidget(self.set_ref_fit_btn) self.set_reference_layout.addWidget(self.set_ref_target_btn) self.plot_control_layout.addLayout(self.set_reference_layout) self.plot_control_layout.addSpacing(10) self.zoom_buttons_layout = QtGui.QHBoxLayout() self.zoom_buttons_layout.addWidget(self.zoom_full_btn) self.zoom_buttons_layout.addWidget(self.zoom_roi_btn) self.zoom_buttons_layout.addWidget(self.autoscale_cbox) self.plot_control_layout.addLayout(self.zoom_buttons_layout) ''' Pressure Control window ''' # make bottom right widget for Pressure control self.press_control = QtGui.QGroupBox() self.press_control.setTitle('Pressure Control') self.cw_layout.addWidget(self.press_control) # make and add primary layout to Pressure Control QGroupBox self.press_control_layout = QtGui.QGridLayout() self.press_control_layout.setAlignment(QtCore.Qt.AlignTop) self.press_control.setLayout(self.press_control_layout) # ###make and add individual widgets to press control layout # create pressure control widgets self.press_calibration_label = QtGui.QLabel('Calibration') self.press_calibration_display = QtGui.QLabel('Dorogokupets') self.lambda_naught_295_label = QtGui.QLabel(u'\u03BB' + '<sub>0</sub>' + '(295)' + ' (nm)') self.lambda_naught_295_display = QtGui.QLabel('694.260') self.lambda_naught_t_label = QtGui.QLabel(u'\u03BB' + '<sub>0</sub>' + '(T)' + ' (nm)') self.lambda_naught_t_display = QtGui.QLabel('694.260') self.lambda_r1_label = QtGui.QLabel(u'\u03BB' + '<sub>R1</sub>' + ' (nm)') self.lambda_r1_display = QtGui.QLabel('694.260') self.threshold_label = QtGui.QLabel('Fit threshold') self.threshold_min_input = QtGui.QSpinBox() self.threshold_min_input.setRange(0, 16000) self.threshold_min_input.setValue(200) self.threshold_min_input.setSingleStep(100) # self.threshold_min_input.setMaximumWidth(50) self.temperature_label = QtGui.QLabel('T(K)') self.temperature_label.setStyleSheet('QLabel {font: bold 18px}') self.temperature_input = QtGui.QSpinBox() self.temperature_input.setStyleSheet('QSpinBox {font: bold 24px}') self.temperature_input.setRange(4, 600) self.temperature_input.setValue(295) self.temperature_track_cbox = QtGui.QCheckBox('Track') self.temperature_track_cbox.setEnabled(False) self.pressure_fit_label = QtGui.QLabel('P(GPa)') self.pressure_fit_label.setStyleSheet('QLabel {font: bold 18px}') self.pressure_fit_display = QtGui.QLabel('0.00') self.pressure_fit_display.setMinimumWidth(100) self.pressure_fit_display.setStyleSheet('QLabel {font: bold 36px}') self.fit_warning_display = QtGui.QLabel('') # connect pressure control signals self.temperature_input.valueChanged.connect(self.calculate_lambda_0_t) # add pressure control widgets to pressure control layout self.press_control_layout.addWidget(self.press_calibration_label, 0, 0) self.press_control_layout.addWidget(self.press_calibration_display, 0, 1) self.press_control_layout.addWidget(self.lambda_naught_295_label, 1, 0) self.press_control_layout.addWidget(self.lambda_naught_295_display, 1, 1) self.press_control_layout.addWidget(self.lambda_naught_t_label, 2, 0) self.press_control_layout.addWidget(self.lambda_naught_t_display, 2, 1) self.press_control_layout.addWidget(self.lambda_r1_label, 3, 0) self.press_control_layout.addWidget(self.lambda_r1_display, 3, 1) self.press_control_layout.addWidget(self.threshold_label, 4, 0) self.press_control_layout.addWidget(self.threshold_min_input, 4, 1) self.press_control_layout.addWidget(self.temperature_label, 5, 0) self.press_control_layout.addWidget(self.temperature_input, 5, 1) self.press_control_layout.addWidget(self.temperature_track_cbox, 5, 2) self.press_control_layout.addWidget(self.pressure_fit_label, 6, 0) self.press_control_layout.addWidget(self.pressure_fit_display, 6, 1) self.press_control_layout.addWidget(self.fit_warning_display, 6, 2) ''' Options window ''' self.ow = QtGui.QTabWidget() # ###PRESSURE CALIBRATION### # make pressure calibration tab self.p_calibration_tab = QtGui.QWidget() self.p_calibration_tab_layout = QtGui.QVBoxLayout() self.p_calibration_tab.setLayout(self.p_calibration_tab_layout) # make Group Box for lambda naught self.set_lambda_naught_gb = QtGui.QGroupBox() self.set_lambda_naught_gb.setTitle('Reference wavelength') self.p_calibration_tab_layout.addWidget(self.set_lambda_naught_gb) self.set_lambda_naught_gb_layout = QtGui.QVBoxLayout() self.set_lambda_naught_gb.setLayout(self.set_lambda_naught_gb_layout) # make widgets for lambda naught self.manual_lambda_naught_label = QtGui.QLabel('Enter user-defined ' + u'\u03BB' + '<sub>0</sub>' + '(295) here') self.manual_lambda_naught_input = QtGui.QLineEdit('694.260') self.auto_lambda_naught_btn = QtGui.QPushButton('Get ' + u'\u03BB' + '(295) from fit') # connect signals self.manual_lambda_naught_input.returnPressed.connect( lambda: self.set_lambda_naught('manual')) self.auto_lambda_naught_btn.clicked.connect( lambda: self.set_lambda_naught('auto')) # add lambda naught widgets to set lambda naught gb layout self.manual_lambda_naught_layout = QtGui.QHBoxLayout() self.manual_lambda_naught_layout.addWidget( self.manual_lambda_naught_label) self.manual_lambda_naught_layout.addWidget( self.manual_lambda_naught_input) self.set_lambda_naught_gb_layout.addLayout( self.manual_lambda_naught_layout) self.set_lambda_naught_gb_layout.addWidget(self.auto_lambda_naught_btn) # make Group Box for Calibration selection self.set_p_calibration_gb = QtGui.QGroupBox() self.set_p_calibration_gb.setTitle('Pressure Calibration') self.p_calibration_tab_layout.addWidget(self.set_p_calibration_gb) self.set_p_calibration_gb_layout = QtGui.QVBoxLayout() self.set_p_calibration_gb.setLayout(self.set_p_calibration_gb_layout) # make widgets for calibration selection self.choose_calibration_drop = QtGui.QComboBox() self.choose_calibration_drop.addItems( ['Dorogokupets', 'Mao', 'Dewaele']) self.p_calibration_alpha_label = QtGui.QLabel(u'\u03B1') self.p_calibration_alpha_display = QtGui.QLabel('1885') self.p_calibration_beta_label = QtGui.QLabel(u'\u03B2') self.p_calibration_beta_display = QtGui.QLabel('11.0') self.calculation_label = QtGui.QLabel(u'\u03B1' + '/' + u'\u03B2') # connect signal self.choose_calibration_drop.currentIndexChanged.connect( self.set_new_p_calibration) # add widgets to layout self.set_p_calibration_gb_layout.addWidget( self.choose_calibration_drop) self.p_cal_constants_layout = QtGui.QHBoxLayout() self.p_cal_constants_layout.addWidget(self.p_calibration_alpha_label) self.p_cal_constants_layout.addWidget(self.p_calibration_alpha_display) self.p_cal_constants_layout.addWidget(self.p_calibration_beta_label) self.p_cal_constants_layout.addWidget(self.p_calibration_beta_display) self.set_p_calibration_gb_layout.addLayout(self.p_cal_constants_layout) self.set_p_calibration_gb_layout.addWidget(self.calculation_label) self.ow.addTab(self.p_calibration_tab, 'P Calibration') # self.ow.show() # from Clemens' Dioptas # file = open(os.path.join("stylesheet.qss")) # stylesheet = file.read() # self.setStyleSheet(stylesheet) # file.close() self.show()
def update_traceplot(self): self._tracesWidget.clear() for data in self._scope_logic.split_data: self._pw.addItem(pg.PlotDataItem(pen=pg.mkPen(data), symbol=None))
def on_activate(self): """ Definition and initialisation of the GUI plus staring the measurement. """ self._scope_logic = self.get_connector('scopelogic') self._mw = ScopeWindow() # Configuration of the trigger source comboWidget self._mw.trigger_source_comboBox.addItem('Channel 1') self._mw.trigger_source_comboBox.addItem('Channel 2') self._mw.trigger_source_comboBox.addItem('Channel 3') self._mw.trigger_source_comboBox.addItem('Channel 4') # Configuration of the channel 1 vertical scale comboWidget self._mw.channel1_vscale_comboBox.addItem('1e-3') self._mw.channel1_vscale_comboBox.addItem('2e-3') self._mw.channel1_vscale_comboBox.addItem('5e-3') self._mw.channel1_vscale_comboBox.addItem('1e-2') self._mw.channel1_vscale_comboBox.addItem('2e-2') self._mw.channel1_vscale_comboBox.addItem('5e-2') self._mw.channel1_vscale_comboBox.addItem('1e-1') self._mw.channel1_vscale_comboBox.addItem('2e-1') self._mw.channel1_vscale_comboBox.addItem('5e-1') self._mw.channel1_vscale_comboBox.addItem('1') self._mw.channel1_vscale_comboBox.addItem('2') self._mw.channel1_vscale_comboBox.addItem('5') # Configuration of the channel 2 vertical scale comboWidget self._mw.channel2_vscale_comboBox.addItem('1e-3') self._mw.channel2_vscale_comboBox.addItem('2e-3') self._mw.channel2_vscale_comboBox.addItem('5e-3') self._mw.channel2_vscale_comboBox.addItem('1e-2') self._mw.channel2_vscale_comboBox.addItem('2e-2') self._mw.channel2_vscale_comboBox.addItem('5e-2') self._mw.channel2_vscale_comboBox.addItem('1e-1') self._mw.channel2_vscale_comboBox.addItem('2e-1') self._mw.channel2_vscale_comboBox.addItem('5e-1') self._mw.channel2_vscale_comboBox.addItem('1') self._mw.channel2_vscale_comboBox.addItem('2') self._mw.channel2_vscale_comboBox.addItem('5') # Configuration of the channel 3 vertical scale comboWidget self._mw.channel3_vscale_comboBox.addItem('1e-3') self._mw.channel3_vscale_comboBox.addItem('2e-3') self._mw.channel3_vscale_comboBox.addItem('5e-3') self._mw.channel3_vscale_comboBox.addItem('1e-2') self._mw.channel3_vscale_comboBox.addItem('2e-2') self._mw.channel3_vscale_comboBox.addItem('5e-2') self._mw.channel3_vscale_comboBox.addItem('1e-1') self._mw.channel3_vscale_comboBox.addItem('2e-1') self._mw.channel3_vscale_comboBox.addItem('5e-1') self._mw.channel3_vscale_comboBox.addItem('1') self._mw.channel3_vscale_comboBox.addItem('2') self._mw.channel3_vscale_comboBox.addItem('5') # Configuration of the channel 4 vertical scale comboWidget self._mw.channel4_vscale_comboBox.addItem('1e-3') self._mw.channel4_vscale_comboBox.addItem('2e-3') self._mw.channel4_vscale_comboBox.addItem('5e-3') self._mw.channel4_vscale_comboBox.addItem('1e-2') self._mw.channel4_vscale_comboBox.addItem('2e-2') self._mw.channel4_vscale_comboBox.addItem('5e-2') self._mw.channel4_vscale_comboBox.addItem('1e-1') self._mw.channel4_vscale_comboBox.addItem('2e-1') self._mw.channel4_vscale_comboBox.addItem('5e-1') self._mw.channel4_vscale_comboBox.addItem('1') self._mw.channel4_vscale_comboBox.addItem('2') self._mw.channel4_vscale_comboBox.addItem('5') # Configuration of the channels RadioButton self._mw.channel1_display_radioButton.setChecked(True) self._mw.channel2_display_radioButton.setChecked(True) self._mw.channel3_display_radioButton.setChecked(True) self._mw.channel4_display_radioButton.setChecked(True) self._mw.channel1_DC_radioButton.setChecked(True) self._mw.channel2_DC_radioButton.setChecked(True) self._mw.channel3_DC_radioButton.setChecked(True) self._mw.channel4_DC_radioButton.setChecked(True) self._mw.channel1_impedance_input_radioButton.setChecked(True) self._mw.channel2_impedance_input_radioButton.setChecked(True) self._mw.channel3_impedance_input_radioButton.setChecked(True) self._mw.channel4_impedance_input_radioButton.setChecked(True) # Connections self._mw.run_pushButton.clicked.connect(self._scope_logic.run_continuous) self._mw.stop_pushButton.clicked.connect(self._scope_logic.stop_aq) self._mw.singlerun_pushButton.clicked.connect(self._scope_logic.single_aq) self._mw.getdata_pushButton.clicked.connect(self._scope_logic.get_data) self._mw.savedata_pushButton.clicked.connect(self._scope_logic.save_data) self._mw.autoscale_pushButton.clicked.connect(self._scope_logic.auto_scale) self._mw.aqcuire_mode_normal_radioButton.clicked.connect(self._scope_logic.acquire_mode_normal) self._mw.aqcuire_mode_highres_radioButton.clicked.connect(self._scope_logic.aqcuire_mode_highres) self._mw.aqcuire_mode_average_radioButton.clicked.connect(self._scope_logic.aqcuire_mode_average) self._mw.channel1_vscale_comboBox.currentIndexChanged.connect(self.change_channel1_vscale) self._mw.channel2_vscale_comboBox.currentIndexChanged.connect(self.change_channel2_vscale) self._mw.channel3_vscale_comboBox.currentIndexChanged.connect(self.change_channel3_vscale) self._mw.channel4_vscale_comboBox.currentIndexChanged.connect(self.change_channel4_vscale) self._mw.channel1_DC_radioButton.clicked.connect(self._scope_logic.set_channel1_DC_couling) self._mw.channel1_AC_radioButton.clicked.connect(self._scope_logic.set_channel1_AC_couling) self._mw.channel2_DC_radioButton.clicked.connect(self._scope_logic.set_channel2_DC_couling) self._mw.channel2_AC_radioButton.clicked.connect(self._scope_logic.set_channel2_AC_couling) self._mw.channel3_DC_radioButton.clicked.connect(self._scope_logic.set_channel3_DC_couling) self._mw.channel3_AC_radioButton.clicked.connect(self._scope_logic.set_channel3_AC_couling) self._mw.channel4_DC_radioButton.clicked.connect(self._scope_logic.set_channel4_DC_couling) self._mw.channel4_AC_radioButton.clicked.connect(self._scope_logic.set_channel4_AC_couling) self._mw.channel1_impedance_input_radioButton.clicked.connect(self.channel1_impedance_input) self._mw.channel2_impedance_input_radioButton.clicked.connect(self.channel2_impedance_input) self._mw.channel3_impedance_input_radioButton.clicked.connect(self.channel3_impedance_input) self._mw.channel4_impedance_input_radioButton.clicked.connect(self.channel4_impedance_input) self._mw.aqcuire_mode_peak_radioButton.clicked.connect(self._scope_logic.aqcuire_mode_peak) self._mw.trigger_EDGE_radioButton.clicked.connect(self._scope_logic.trigger_mode_EDGE) self._mw.channel1_display_radioButton.clicked.connect(self.channel1_state_chage) self._mw.channel2_display_radioButton.clicked.connect(self.channel2_state_chage) self._mw.channel3_display_radioButton.clicked.connect(self.channel3_state_chage) self._mw.channel4_display_radioButton.clicked.connect(self.channel4_state_chage) # Plot labels. self._pw = self._mw.scope_PlotWidget self._pw.setLabel('left', 'Voltage', units='V') self._pw.setLabel('bottom', 'Time', units='s') self.curves = [] self.colors = [palette.c1, palette.c5, palette.c6, palette.c4] for i, ch in enumerate(self._scope_logic.get_channels()): # Create an empty plot curve to be filled later, set its pen self.curves.append( pg.PlotDataItem(pen=pg.mkPen(self.colors[i]), symbol=None)) self._pw.addItem(self.curves[-1]) # setting the x axis length correctly self._pw.setXRange( 0, self._scope_logic.get_timescale()[-1] ) self._scope_logic.sigDataUpdated.connect(self.updateData) for ch in self._scope_logic.get_channels(): self._scope_logic.change_channel_state(channel=ch, state='ON')
x = np.arange(1000, dtype=float) y = np.random.normal(size=1000) y += 5 * np.sin(x / 100) win = pg.GraphicsWindow() win.setWindowTitle('pyqtgraph example: ____') win.resize(1000, 800) win.ci.setBorder((50, 50, 100)) sub1 = win.addLayout() sub1.addLabel( "<b>Standard mouse interaction:</b><br>left-drag to pan, right-drag to zoom." ) sub1.nextRow() v1 = sub1.addViewBox() l1 = pg.PlotDataItem(y) v1.addItem(l1) sub2 = win.addLayout() sub2.addLabel( "<b>One-button mouse interaction:</b><br>left-drag zoom to box, wheel to zoom out." ) sub2.nextRow() v2 = sub2.addViewBox() v2.setMouseMode(v2.RectMode) l2 = pg.PlotDataItem(y) v2.addItem(l2) win.nextRow() sub3 = win.addLayout()
def main(): global plotItem, viewBox, pw (xMin, xMax, xDelta) = (-5, 5, 0.1) x = np.arange(xMin, xMax, xDelta) mu = 0. sigma = 1. y = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 / (2 * sigma**2)) mu = 1.0 sigma = 0.7 y2 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 / (2 * sigma**2)) pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') app = pg.mkQApp() win = pg.GraphicsWindow(title="Overlay 2 plots") win.clear() win.addLabel("Second plot has log scale", row=1, col=1, colspan=10) win.addLabel("A comment", row=2, col=1, colspan=10) plotItem = win.addPlot(row=3, col=1) plotItem.setLabels(left='axis 1') plotItem.showAxis('top') plotItem.showAxis('right') plotItem.getAxis('right').style['showValues'] = False plotItem.getAxis('right').setLabel('axis2', color='#00ffff') plotItem.setLogMode(x=False, y=False) plotDataItem = plotItem.plot() plotDataItem.setData(x, y) ## create a new ViewBox, link the right axis to its coordinate system viewBox = pg.ViewBox() plotItem.scene().addItem(viewBox) # # Link this axis to a ViewBox, causing its displayed range to # match the visible range of the view. # plotItem.getAxis('right').linkToView(viewBox) # # link the views x-axis to another view # viewBox.setXLink(plotItem) vbDataItem = pg.PlotDataItem(x, y2, pen='#00ffff') vbDataItem.setLogMode(False, True) viewBox.addItem(vbDataItem) viewBox.enableAutoRange(x=True, y=True) #viewBox.setXRange( -5, 5) #viewBox.setYRange( -10, 1) updateViews() plotItem.vb.sigResized.connect(updateViews) app.processEvents() time.sleep(0.1) app.processEvents() print "Prtc ", sys.stdin.readline()
# a standard pyqtgraph plot_item w = pg.PlotWidget() #add legend to the plot, for that we have to give a name to plot items w.addLegend() # add a Y2 axis from taurus.qt.qtgui.tpg import Y2ViewBox y2ViewBox = Y2ViewBox() y2ViewBox.attachToPlotItem(w.getPlotItem()) # adding a regular data item (non-taurus) c1 = pg.PlotDataItem( name='st plot', pen=dict(color='y', width=3, style=QtCore.Qt.DashLine), fillLevel=0.3, fillBrush='g' ) c1.setData(numpy.arange(300)/300.) w.addItem(c1) # adding a taurus data item c2 = TaurusPlotDataItem(name='st2 plot', pen='r', symbol='o', symbolSize=10) c2.setModel('sys/tg_test/1/wave') w.addItem(c2) # attach tool to plot item of the PlotWidget tool = CurvesPropertiesTool()
"""
def configure_plot(self): """Configure data plots.""" self.pw_plot.clear() self.pw_plot.setLabel('bottom', self._bottom_axis_label) self.pw_plot.showGrid(x=True, y=True) # Configure left axis 1 self.pw_plot.setLabel('left', self._left_axis_1_label) colors = self._left_axis_1_data_colors data_labels = self._left_axis_1_data_labels if len(colors) != len(data_labels): colors = [(0, 0, 255)] * len(data_labels) for i, label in enumerate(data_labels): pen = colors[i] graph = self.pw_plot.plotItem.plot(_np.array([]), _np.array([]), pen=pen, symbol='o', symbolPen=pen, symbolSize=3, symbolBrush=pen) self._graphs[label] = graph # Configure right axis 1 data_labels = self._right_axis_1_data_labels colors = self._right_axis_1_data_colors if len(colors) != len(data_labels): colors = [(0, 0, 255)] * len(data_labels) if len(data_labels) != 0: self.right_axis_1 = _utils.plot_item_add_first_right_axis( self.pw_plot.plotItem) self.right_axis_1.setLabel(self._right_axis_1_label) self.right_axis_1.setStyle(showValues=True) for i, label in enumerate(data_labels): pen = colors[i] graph = _pyqtgraph.PlotDataItem(_np.array([]), _np.array([]), pen=pen, symbol='o', symbolPen=pen, symbolSize=3, symbolBrush=pen) self.right_axis_1.linkedView().addItem(graph) self._graphs[label] = graph # Configure right axis 2 data_labels = self._right_axis_2_data_labels colors = self._right_axis_2_data_colors if len(colors) != len(data_labels): colors = [(0, 0, 255)] * len(data_labels) if len(data_labels) != 0: self.right_axis_2 = _utils.plot_item_add_second_right_axis( self.pw_plot.plotItem) self.right_axis_2.setLabel(self._right_axis_2_label) self.right_axis_2.setStyle(showValues=True) for i, label in enumerate(data_labels): pen = colors[i] graph = _pyqtgraph.PlotDataItem(_np.array([]), _np.array([]), pen=pen, symbol='o', symbolPen=pen, symbolSize=3, symbolBrush=pen) self.right_axis_2.linkedView().addItem(graph) self._graphs[label] = graph # Update legend self.update_legend_items()
from taurus.qt.qtgui.application import TaurusApplication # from taurus.qt.qtgui.tpg import TaurusPlotDataItem from taurus.external.qt import Qt from taurus.qt.qtgui.tpg import TaurusModelChooserTool app = TaurusApplication() # a standard pyqtgraph plot_item w = pg.PlotWidget() # add legend to the plot, for that we have to give a name to plot items w.addLegend() # adding a regular data item (non-taurus) c1 = pg.PlotDataItem(name="st plot", pen="b", fillLevel=0, brush="c") c1.setData(numpy.arange(300) / 300.0) w.addItem(c1) pen = pg.mkPen(color="r", style=4) brush = pg.mkBrush(color="b") brush.setStyle(3) # adding a taurus data item # c2 = TaurusPlotDataItem(name='st2 plot', pen='r', symbol='o') c2 = TaurusPlotDataItem(pen=pen, name="foo") # c2 = TaurusPlotDataItem() # c2.loadConfigFile('tmp/conf.cfg') c2.setModel('eval:Quantity(rand(256),"m")')
def __init__(self, signals, with_dots, step_mode, *args, **kwargs): super(Plot, self).__init__(*args, **kwargs) self.xrange_changed.connect(self.xrange_changed_handle) self.with_dots = with_dots if self.with_dots: self.curvetype = pg.PlotDataItem else: self.curvetype = pg.PlotCurveItem self.step_mode = step_mode self.info = None self.standalone = kwargs.get("standalone", False) self.singleton = None self.region = None self.cursor1 = None self.cursor2 = None self.signals = signals self.disabled_keys = set() for sig in self.signals: if sig.samples.dtype.kind == "f": sig.stepmode = False sig.format = "{:.6f}" sig.texts = None else: if self.step_mode: sig.stepmode = True else: sig.stepmode = False sig.format = "phys" if sig.samples.dtype.kind in "SV": sig.texts = sig.original_texts = sig.samples sig.samples = np.zeros(len(sig.samples)) else: sig.texts = None sig.enable = True sig.original_samples = sig.samples sig.original_timestamps = sig.timestamps sig._stats = { "range": (0, -1), "range_stats": {}, "visible": (0, -1), "visible_stats": {}, } if self.signals: self.all_timebase = self.timebase = reduce( np.union1d, (sig.timestamps for sig in self.signals) ) else: self.all_timebase = self.timebase = None self.showGrid(x=True, y=True) self.plot_item = self.plotItem self.plot_item.hideAxis("left") self.layout = self.plot_item.layout self.scene_ = self.plot_item.scene() self.viewbox = self.plot_item.vb self.viewbox.sigResized.connect(self.update_views) self.viewbox.sigXRangeChanged.connect(self.xrange_changed.emit) self.viewbox.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True) self.curve = self.curvetype([], []) axis = self.layout.itemAt(2, 0) axis.setParent(None) self.axis = FormatedAxis("left") self.layout.removeItem(axis) self.layout.addItem(self.axis, 2, 0) self.axis.linkToView(axis.linkedView()) self.plot_item.axes["left"]["item"] = self.axis self.plot_item.hideAxis("left") self.viewbox.addItem(self.curve) self.cursor_hint = pg.PlotDataItem( [], [], pen="#000000", symbolBrush="#000000", symbolPen="w", symbol="s", symbolSize=8, ) self.viewbox.addItem(self.cursor_hint) self.view_boxes = [] self.curves = [] self.axes = [] for i, sig in enumerate(self.signals): color = COLORS[i % 10] sig.color = color if len(sig.samples): sig.min = np.amin(sig.samples) sig.max = np.amax(sig.samples) sig.empty = False else: sig.empty = True axis = FormatedAxis("right") axis.setPen(color) if sig.conversion and "text_0" in sig.conversion: axis.text_conversion = sig.conversion view_box = pg.ViewBox() view_box.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True) axis.linkToView(view_box) axis.setLabel(sig.name, sig.unit, color=color) self.layout.addItem(axis, 2, i + 2) self.scene_.addItem(view_box) if sig.stepmode: if len(sig.timestamps): to_append = sig.timestamps[-1] else: to_append = 0 t = np.append(sig.timestamps, to_append) else: t = sig.timestamps curve = self.curvetype( t, sig.samples, pen=color, symbolBrush=color, symbolPen=color, symbol="o", symbolSize=4, stepMode=sig.stepmode, # connect='pairs' ) # curve.setDownsampling(ds=100, auto=True, method='peak') view_box.addItem(curve) view_box.setXLink(self.viewbox) view_box.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True) view_box.sigResized.connect(self.update_views) self.view_boxes.append(view_box) self.curves.append(curve) self.axes.append(axis) axis.hide() if len(signals) == 1: self.setSignalEnable(0, 1) self.update_views() self.keyPressEvent(QKeyEvent(QEvent.KeyPress, Qt.Key_H, Qt.NoModifier)) self.resizeEvent = self._resizeEvent
def plot_raw_data(self,data): bins=np.linspace(1,len(data),len(data)) self._mw.raw_data_PlotWidget.clear() self._mw.raw_data_PlotWidget.addItem(pg.PlotDataItem(bins,data)) return
def cobweb_plot(plt, idx=-1, model=logistic_map, r=0, cobweb_x=0.5, function_n=1000, cobweb_n=100, num_discard=0, title='', filename='', show=True, save=True, start=0, end=1, figsize=(6, 6), diagonal_linewidth=1.35, cobweb_linewidth=1, function_linewidth=1.5, folder='images', dpi=300, bbox_inches='tight', pad=0.1): plt.clear() initial_pop = float(cobweb_x) stride_idx = (idx - 1) * 3 func_x_vals, func_y_vals = get_function_points(model=model, r=r, n=function_n, start=start, end=end) cobweb_x_vals, cobweb_y_vals = get_cobweb_points(model=model, r=r, x=cobweb_x, n=cobweb_n) cobweb_x_vals = cobweb_x_vals[:stride_idx] cobweb_y_vals = cobweb_y_vals[:stride_idx] plt.setTitle(f"Cobweb Plot") diagonal_line = plt.plot((0, 1), (0, 1)) diagonal_line.setPen(width=diagonal_linewidth) function_line = pg.PlotDataItem(x=func_x_vals, y=func_y_vals) function_line.setPen(color=colors['lomid'], width=3.0) function_line = plt.addItem(function_line) sizes = 1 / np.linspace(.1, 1, len(cobweb_x_vals)) sizes = np.maximum(5, sizes) cobweb_line = plt.plot(cobweb_x_vals, cobweb_y_vals, symbol='o', symbolSize=sizes) cobweb_line.setPen(color=colors['lomid'], width=cobweb_linewidth) cobweb_line.setSymbolPen(color=(1, 1, 1, 0), width=0.0) cobweb_line.setSymbolBrush(color=colors['himid']) xaxis = plt.getAxis("bottom") #xaxis.setTickSpacing(4,4) xaxis.tickFont = numfont xaxis.setStyle(tickTextOffset=20) yaxis = plt.getAxis("left") #yaxis.setTickSpacing(.2, .2) yaxis.resizeEvent = types.MethodType(custom_axis_item_resizeEvent, yaxis) yaxis.tickFont = numfont yaxis.setStyle(tickTextOffset=10, tickLength=10) xaxis.label.setFont(txtfont) yaxis.label.setFont(txtfont) plt.titleLabel.item.setFont(txtfont) return np.concatenate(([ initial_pop, ], np.array(cobweb_y_vals[1::3])))
def addToKline(self, line): curveOI1 = pg.PlotDataItem() curveOI1.setData(y=line) self.plotItem.addItem(curveOI1) return curveOI1
# use a standard Plot w = pg.PlotWidget() # add the XAutoPanTool autopan = XAutoPanTool() autopan.attachToPlotItem(w.getPlotItem()) # configure plot window w.setWindowIcon(QtGui.QIcon("icon-mongol.jpg")) # no icon?? w.showAxis('right') # set attributes of chart w.hideAxis('left') w.showGrid(x=True, y=True, alpha=1.0) # w.addLine(y=10) # add a curve that appends a new point every 500ms c = pg.PlotDataItem(symbol='x') idx = 40 max_points = 10000 xdata = np.arange(max_points) ydata = np.random.rand(max_points) c.setData(xdata[:idx], ydata[:idx]) def addPoint(): global idx idx += 1 c.setData(xdata[:idx], ydata[:idx]) print(autopan.isChecked(), idx) t = QtCore.QTimer() t.timeout.connect(addPoint) t.start(1000)
def on_activate(self): """ Definition and initialisation of the GUI. """ self._counting_logic = self.counterlogic1() ##################### # Configuring the dock widgets # Use the inherited class 'CounterMainWindow' to create the GUI window self._mw = CounterMainWindow() # Setup dock widgets self._mw.centralwidget.hide() self._mw.trace_selection_DockWidget.hide() self._mw.setDockNestingEnabled(True) # Plot labels. self._pw = self._mw.counter_trace_PlotWidget self._pw.setLabel('left', 'Fluorescence', units='counts/s') self._pw.setLabel('bottom', 'Time', units='s') self.curves = [] for i, ch in enumerate(self._counting_logic.get_channels()): if i % 2 == 0: # Create an empty plot curve to be filled later, set its pen self.curves.append( pg.PlotDataItem(pen=pg.mkPen(palette.c1), symbol=None)) self._pw.addItem(self.curves[-1]) self.curves.append( pg.PlotDataItem(pen=pg.mkPen(palette.c2, width=3), symbol=None)) self._pw.addItem(self.curves[-1]) else: self.curves.append( pg.PlotDataItem(pen=pg.mkPen(palette.c3, style=QtCore.Qt.DotLine), symbol='s', symbolPen=palette.c3, symbolBrush=palette.c3, symbolSize=5)) self._pw.addItem(self.curves[-1]) self.curves.append( pg.PlotDataItem(pen=pg.mkPen(palette.c4, width=3), symbol=None)) self._pw.addItem(self.curves[-1]) # setting the x axis length correctly self._pw.setXRange( 0, self._counting_logic.get_count_length() / self._counting_logic.get_count_frequency()) ##################### # Setting default parameters self._mw.count_length_SpinBox.setValue( self._counting_logic.get_count_length()) self._mw.count_freq_SpinBox.setValue( self._counting_logic.get_count_frequency()) self._mw.oversampling_SpinBox.setValue( self._counting_logic.get_counting_samples()) self._display_trace = 1 self._trace_selection = [True, True, True, True] ##################### # Connecting user interactions self._mw.start_counter_Action.triggered.connect(self.start_clicked) self._mw.record_counts_Action.triggered.connect(self.save_clicked) self._mw.count_length_SpinBox.valueChanged.connect( self.count_length_changed) self._mw.count_freq_SpinBox.valueChanged.connect( self.count_frequency_changed) self._mw.oversampling_SpinBox.valueChanged.connect( self.oversampling_changed) if len(self.curves) >= 2: self._mw.trace_1_checkbox.setChecked(True) else: self._mw.trace_1_checkbox.setEnabled(False) self._mw.trace_1_radiobutton.setEnabled(False) if len(self.curves) >= 4: self._mw.trace_2_checkbox.setChecked(True) else: self._mw.trace_2_checkbox.setEnabled(False) self._mw.trace_2_radiobutton.setEnabled(False) if len(self.curves) >= 6: self._mw.trace_3_checkbox.setChecked(True) else: self._mw.trace_3_checkbox.setEnabled(False) self._mw.trace_3_radiobutton.setEnabled(False) if len(self.curves) >= 8: self._mw.trace_4_checkbox.setChecked(True) else: self._mw.trace_4_checkbox.setEnabled(False) self._mw.trace_4_radiobutton.setEnabled(False) self._mw.trace_1_checkbox.stateChanged.connect( self.trace_selection_changed) self._mw.trace_2_checkbox.stateChanged.connect( self.trace_selection_changed) self._mw.trace_3_checkbox.stateChanged.connect( self.trace_selection_changed) self._mw.trace_4_checkbox.stateChanged.connect( self.trace_selection_changed) self._mw.trace_1_radiobutton.setChecked(True) self._mw.trace_1_radiobutton.released.connect( self.trace_display_changed) self._mw.trace_2_radiobutton.released.connect( self.trace_display_changed) self._mw.trace_3_radiobutton.released.connect( self.trace_display_changed) self._mw.trace_4_radiobutton.released.connect( self.trace_display_changed) # Connect the default view action self._mw.restore_default_view_Action.triggered.connect( self.restore_default_view) ##################### # starting the physical measurement self.sigStartCounter.connect(self._counting_logic.startCount) self.sigStopCounter.connect(self._counting_logic.stopCount) ################## # Handling signals from the logic self._counting_logic.sigCounterUpdated.connect(self.updateData) # ToDo: # self._counting_logic.sigCountContinuousNext.connect() # self._counting_logic.sigCountGatedNext.connect() # self._counting_logic.sigCountFiniteGatedNext.connect() # self._counting_logic.sigGatedCounterFinished.connect() # self._counting_logic.sigGatedCounterContinue.connect() self._counting_logic.sigCountingSamplesChanged.connect( self.update_oversampling_SpinBox) self._counting_logic.sigCountLengthChanged.connect( self.update_count_length_SpinBox) self._counting_logic.sigCountFrequencyChanged.connect( self.update_count_freq_SpinBox) self._counting_logic.sigSavingStatusChanged.connect( self.update_saving_Action) self._counting_logic.sigCountingModeChanged.connect( self.update_counting_mode_ComboBox) self._counting_logic.sigCountStatusChanged.connect( self.update_count_status_Action) # Throw a deprecation warning pop-up to encourage users to switch to # TimeSeriesGui/TimeSeriesReaderLogic # dialog = QtWidgets.QDialog(self._mw) # dialog.setWindowTitle('Deprecation warning') # label1 = QtWidgets.QLabel('Deprecation Warning:') # label1.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) # font = label1.font() # font.setPointSize(12) # label1.setFont(font) # label2 = QtWidgets.QLabel('The modules CounterGui, CounterLogic and ' # 'NationalInstrumentsXSeries are deprecated for time series ' # 'streaming (also called "slow counting") and will be removed in ' # 'the future.\nPlease consider switching to TimeSeriesGui, ' # 'TimeSeriesReaderLogic and NIXSeriesInStreamer.\nSee default.cfg ' # 'for a configuration template.') # label2.setAlignment(QtCore.Qt.AlignVCenter) # label2.setWordWrap(True) # button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) # button_box.setCenterButtons(True) # layout = QtWidgets.QVBoxLayout() # layout.addWidget(label1) # layout.addWidget(label2) # layout.addWidget(button_box) # button_box.accepted.connect(dialog.accept) # dialog.setLayout(layout) # dialog.exec() return 0
def __init__(self): QtGui.QWidget.__init__(self) self.cap = None self.filename=None self.magnification=1 font=QtGui.QFont() font.setBold(True) self.resize(500, 1000) self.setWindowTitle('Open Field analysis: Activity') layout = QtGui.QGridLayout(self) self.setLayout(layout) self.LableMag = QtGui.QLineEdit(self) self.LableMag.setEnabled(False) self.LableMag.setGeometry(QtCore.QRect(800, 30, 80, 20)) self.LableMag.setFrame(False) self.LableMag.setText("Video mag.:") self.videoSize = QtGui.QComboBox(self) self.videoSize.addItem("1X") self.videoSize.addItem("1.5X") self.videoSize.addItem("2X") self.videoSize.addItem("3X") self.videoSize.addItem("4X") self.videoSize.setCurrentIndex(0) self.videoSize.setEnabled(True) self.videoSize.activated.connect(self.magnific) self.videoSize.setGeometry(QtCore.QRect(675, 30, 50, 20)) self.LablePath = QtGui.QLineEdit(self) self.LablePath.setEnabled(False) self.LablePath.setGeometry(QtCore.QRect(90, 10, 641, 20)) self.LablePath.setFrame(False) self.open_button = QtGui.QPushButton(self) self.open_button.setText("Open Video") self.open_button.clicked.connect(self.getfile) self.open_button.setGeometry(QtCore.QRect(9, 9, 75, 23)) self.save_button = QtGui.QPushButton(self) self.save_button.setText("Save data") self.save_button.clicked.connect(self.handleSave) self.save_button.setGeometry(QtCore.QRect(850, 450, 80, 30)) self.save_button.setEnabled(False) self.play_button = QtGui.QPushButton(self) self.play_button.setText("Analyze") self.play_button.clicked.connect(self.AnalyzeBtn) self.play_button.setGeometry(QtCore.QRect(760, 450, 80, 30)) self.play_button.setEnabled(False) self.roi_button = QtGui.QPushButton(self) self.roi_button.setText("Save Roi") self.roi_button.clicked.connect(self.roi_box) self.roi_button.setGeometry(QtCore.QRect(670, 450, 80, 30)) self.pg2_label=QtGui.QLineEdit(self) self.pg2_label.setGeometry(QtCore.QRect(650, 10, 320, 20)) self.pg2_label.setFrame(False) self.pg2_label.setEnabled(False) self.pg2_label.setText("Tracking:") self.pg2_label.setFont(font) self.pg2 = pg.GraphicsLayoutWidget(self) self.pg2.setGeometry(QtCore.QRect(650, 40, 280, 200)) self.pg2.setBackground(None) self.roi2= pg.RectROI([200, 200], [200, 200], pen=(0,9), movable=False,centered=True, sideScalers=False) self.w1=self.pg2.addPlot() self.plot=pg.PlotDataItem(size=3,connect="all", symbolSize=3) self.w1.invertY() self.w1.addItem(self.plot) self.w1.addItem(self.roi2) self.roi3= pg.RectROI([200, 200], [200, 200], pen=(2,9), movable=False,centered=True, sideScalers=False) self.w1.addItem(self.roi3) self.Options_label=QtGui.QLineEdit(self) self.Options_label.setGeometry(QtCore.QRect(670, 270, 320, 20)) self.Options_label.setFrame(False) self.Options_label.setEnabled(False) self.Options_label.setText("Options:") self.Options_label.setFont(font) self.proBar_label=QtGui.QLineEdit(self) self.proBar_label.setGeometry(QtCore.QRect(670, 500, 320, 20)) self.proBar_label.setFrame(False) self.proBar_label.setEnabled(False) self.proBar_label.setText("Progress:") self.proBar=QtGui.QProgressBar(self) self.proBar.setGeometry(QtCore.QRect(670, 520, 280, 20)) self.sl = QtGui.QSlider(self) self.sl.setOrientation(QtCore.Qt.Horizontal) self.sl.setMinimum(0) self.sl.setMaximum(255) self.sl.setValue(200) self.sl.setTickPosition(QtGui.QSlider.TicksBelow) self.sl.setTickInterval(10) self.sl.setGeometry(QtCore.QRect(750, 340, 180, 20)) self.sl.valueChanged.connect(self.selectionchange) self.sl.setEnabled(False) self.sl_brigth = QtGui.QSlider(self) self.sl_brigth.setOrientation(QtCore.Qt.Horizontal) self.sl_brigth.setMinimum(0) self.sl_brigth.setMaximum(50) self.sl_brigth.setValue(10) self.sl_brigth.setTickPosition(QtGui.QSlider.TicksBelow) self.sl_brigth.setTickInterval(10) self.sl_brigth.valueChanged.connect(self.selectionchange) self.sl_brigth.setGeometry(QtCore.QRect(750, 370, 180, 20)) self.sl_rotation = QtGui.QSlider(self) self.sl_rotation.setOrientation(QtCore.Qt.Horizontal) self.sl_rotation.setMinimum(-180) self.sl_rotation.setMaximum(180) self.sl_rotation.setValue(0) self.sl_rotation.setTickPosition(QtGui.QSlider.TicksBelow) self.sl_rotation.setTickInterval(20) self.sl_rotation.valueChanged.connect(self.selectionchange) self.sl_rotation.setGeometry(QtCore.QRect(750, 400, 180, 20)) self.Inner_label = QtGui.QLineEdit(self) self.Inner_label.setEnabled(False) self.Inner_label.setGeometry(QtCore.QRect(670, 230, 80, 20)) self.Inner_label.setFrame(False) self.Inner_label.setText("Inner box (%):") self.Inner = QtGui.QLineEdit(self) self.Inner.setEnabled(True) self.Inner.setText("45") self.Inner.setGeometry(QtCore.QRect(760, 230, 40, 20)) self.Inner.setFrame(True) self.BoxW_label = QtGui.QLineEdit(self) self.BoxW_label.setEnabled(False) self.BoxW_label.setGeometry(QtCore.QRect(690, 290, 80, 20)) self.BoxW_label.setFrame(False) self.BoxW_label.setText("Width (cm):") self.BoxW = QtGui.QLineEdit(self) self.BoxW.setEnabled(True) self.BoxW.setText("80") self.BoxW.setGeometry(QtCore.QRect(760, 290, 40, 20)) self.BoxW.setFrame(True) self.BoxL_label = QtGui.QLineEdit(self) self.BoxL_label.setEnabled(False) self.BoxL_label.setGeometry(QtCore.QRect(830, 290, 80, 20)) self.BoxL_label.setFrame(False) self.BoxL_label.setText("Long (cm):") self.BoxL = QtGui.QLineEdit(self) self.BoxL.setEnabled(True) self.BoxL.setText("100") self.BoxL.setGeometry(QtCore.QRect(895, 290, 40, 20)) self.BoxL.setFrame(True) self.thresh_label = QtGui.QLineEdit(self) self.thresh_label.setEnabled(False) self.thresh_label.setGeometry(QtCore.QRect(670, 340, 80, 20)) self.thresh_label.setFrame(False) self.thresh_label.setText("Set threshold:") self.bright_label = QtGui.QLineEdit(self) self.bright_label.setEnabled(False) self.bright_label.setGeometry(QtCore.QRect(670, 370, 80, 20)) self.bright_label.setFrame(False) self.bright_label.setText("Set brightness:") self.rotation_label = QtGui.QLineEdit(self) self.rotation_label.setEnabled(False) self.rotation_label.setGeometry(QtCore.QRect(670, 400, 80, 20)) self.rotation_label.setFrame(False) self.rotation_label.setText("Rotate image:") self.btn_refresh= QtGui.QPushButton(self) self.btn_refresh.setText("Live") self.btn_refresh.clicked.connect(self.Live) self.btn_refresh.setGeometry(QtCore.QRect(850, 230, 80, 23)) layout.addWidget(self.open_button, 0,0) layout.addWidget(self.LableMag, 0,1) layout.addWidget(self.videoSize, 0,2) layout.addWidget(self.LablePath, 1,0) layout.addWidget(self.pg2_label, 2,0) layout.addWidget(self.pg2, 3,0,3,3) layout.addWidget(self.btn_refresh, 2,2) layout.addWidget(self.Options_label, 7,0) layout.addWidget(self.Inner_label, 8,1) layout.addWidget(self.Inner, 8,2) layout.addWidget(self.BoxW_label, 9,1) layout.addWidget(self.BoxW, 9,2) layout.addWidget(self.BoxL_label, 10,1) layout.addWidget(self.BoxL, 10,2) layout.addWidget(self.thresh_label, 12,0) layout.addWidget(self.sl, 12,1,1,2) layout.addWidget(self.bright_label, 13,0) layout.addWidget(self.sl_brigth, 13,1,1,2) layout.addWidget(self.rotation_label, 14,0) layout.addWidget(self.sl_rotation, 14,1,1,2) layout.addWidget(self.roi_button, 16,0) layout.addWidget(self.play_button, 16,1) layout.addWidget(self.save_button, 16,2) layout.addWidget(self.proBar_label, 18,0) layout.addWidget(self.proBar, 18,1,1,2) self.show()
def on_activate(self): """ Definition and initialisation of the GUI. """ self._wm_logger_logic = self.get_connector('wavemeterloggerlogic1') self._save_logic = self.get_connector('savelogic') # setting up the window self._mw = WavemeterLogWindow() ## giving the plots names allows us to link their axes together self._pw = self._mw.plotWidget # pg.PlotWidget(name='Counter1') self._plot_item = self._pw.plotItem ## create a new ViewBox, link the right axis to its coordinate system self._right_axis = pg.ViewBox() self._plot_item.showAxis('right') self._plot_item.scene().addItem(self._right_axis) self._plot_item.getAxis('right').linkToView(self._right_axis) self._right_axis.setXLink(self._plot_item) ## create a new ViewBox, link the right axis to its coordinate system self._top_axis = pg.ViewBox() self._plot_item.showAxis('top') self._plot_item.scene().addItem(self._top_axis) self._plot_item.getAxis('top').linkToView(self._top_axis) self._top_axis.setYLink(self._plot_item) self._top_axis.invertX(b=True) # handle resizing of any of the elements self._update_plot_views() self._plot_item.vb.sigResized.connect(self._update_plot_views) self._pw.setLabel('left', 'Fluorescence', units='counts/s') self._pw.setLabel('right', 'Number of Points', units='#') self._pw.setLabel('bottom', 'Wavelength', units='nm') self._pw.setLabel('top', 'Relative Frequency', units='Hz') self._mw.actionStop_resume_scan.triggered.connect( self.stop_resume_clicked) self._mw.actionSave_histogram.triggered.connect(self.save_clicked) self._mw.actionStart_scan.triggered.connect(self.start_clicked) self._mw.actionAuto_range.triggered.connect(self.set_auto_range) # defining the parameters to edit self._mw.binSpinBox.setValue(self._wm_logger_logic.get_bins()) self._mw.binSpinBox.editingFinished.connect(self.recalculate_histogram) self._mw.minDoubleSpinBox.setValue( self._wm_logger_logic.get_min_wavelength()) self._mw.minDoubleSpinBox.editingFinished.connect( self.recalculate_histogram) self._mw.maxDoubleSpinBox.setValue( self._wm_logger_logic.get_max_wavelength()) self._mw.maxDoubleSpinBox.editingFinished.connect( self.recalculate_histogram) self._mw.show() ## Create an empty plot curve to be filled later, set its pen self.curve_data_points = pg.PlotDataItem(pen=pg.mkPen(palette.c1), symbol=None) self.curve_nm_counts = pg.PlotDataItem(pen=pg.mkPen( palette.c2, style=QtCore.Qt.DotLine), symbol=None) self.curve_hz_counts = pg.PlotDataItem(pen=pg.mkPen( palette.c6, style=QtCore.Qt.DotLine), symbol=None) self.curve_envelope = pg.PlotDataItem(pen=pg.mkPen( palette.c3, style=QtCore.Qt.DotLine), symbol=None) self.curve_fit = pg.PlotDataItem(pen=pg.mkPen(palette.c2, width=3), symbol=None) self._pw.addItem(self.curve_data_points) self._pw.addItem(self.curve_envelope) self._right_axis.addItem(self.curve_nm_counts) self._top_axis.addItem(self.curve_hz_counts) self._save_PNG = True # scatter plot for time series self._spw = self._mw.scatterPlotWidget self._spi = self._spw.plotItem self._spw.setLabel('bottom', 'Wavelength', units='nm') self._spw.setLabel('left', 'Time', units='s') self._scatterplot = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush( 255, 255, 255, 20)) self._spw.addItem(self._scatterplot) self._spw.setXLink(self._plot_item) self._wm_logger_logic.sig_new_data_point.connect(self.add_data_point) self._wm_logger_logic.sig_data_updated.connect(self.updateData) # fit settings self._fsd = FitSettingsDialog(self._wm_logger_logic.fc) self._fsd.sigFitsUpdated.connect( self._mw.fit_methods_ComboBox.setFitFunctions) self._fsd.applySettings() self._mw.actionFit_settings.triggered.connect(self._fsd.show) self._mw.do_fit_PushButton.clicked.connect(self.doFit) self.sigDoFit.connect(self._wm_logger_logic.do_fit) self.sigFitChanged.connect(self._wm_logger_logic.fc.set_current_fit) self._wm_logger_logic.sig_fit_updated.connect(self.updateFit)
def __init__(self, data_filename, bgimg, delta_video_filename, load_original=False, clickable_width=6, draw_interesting_time_points=True, draw_config_function=False): self.load_original = load_original TemplateBaseClass.__init__(self) self.setWindowTitle('Trajectory Viewer GUI v2') # Create the main window #self.app = QtGui.QApplication([]) self.ui = WindowTemplate() self.ui.setupUi(self) #self.show() # options self.draw_interesting_time_points = draw_interesting_time_points self.draw_config_function = draw_config_function # Buttons self.ui.save_trajecs.clicked.connect(self.save_trajectories) self.ui.movie_save.clicked.connect(self.save_image_sequence) self.ui.movie_speed.sliderMoved.connect(self.set_movie_speed) self.ui.trajec_undo.clicked.connect(self.trajec_undo) self.ui.movie_play.clicked.connect(self.movie_play) self.ui.movie_pause.clicked.connect(self.movie_pause) self.ui.trajec_delete.clicked.connect(self.toggle_trajec_delete) self.ui.trajec_cut.clicked.connect(self.toggle_trajec_cut) self.ui.trajec_join_collect.clicked.connect( self.toggle_trajec_join_collect) self.ui.trajec_select_all.clicked.connect(self.select_all_trajecs) self.ui.trajec_join_add_data.clicked.connect( self.toggle_trajec_join_add_data) self.ui.trajec_join_save.clicked.connect(self.trajec_join_save) self.ui.trajec_join_clear.clicked.connect( self.toggle_trajec_join_clear) self.ui.save_annotation.clicked.connect(self.save_annotation) self.ui.load_annotations.clicked.connect(self.load_annotations) self.ui.annotated_color_checkbox.stateChanged.connect( self.toggle_annotated_colors) self.ui.annotated_hide_checkbox.stateChanged.connect( self.toggle_annotated_hide) if not SMALL: self.ui.get_original_objid.clicked.connect( self.trajec_get_original_objid) self.ui.save_colors.clicked.connect(self.save_trajec_colors) self.ui.min_selection_length.setPlainText(str(0)) self.ui.max_selection_length.setPlainText(str(-1)) # -1 means all # parameters self.data_filename = data_filename self.load_data() self.backgroundimg_filename = bgimg self.backgroundimg = None self.binsx = None self.binsy = None trange = np.float( np.max(self.pd.time_epoch.values) - np.min(self.pd.time_epoch.values)) self.troi = [ np.min(self.pd.time_epoch.values), np.min(self.pd.time_epoch.values) + trange * 0.1 ] self.skip_frames = 1 self.frame_delay = 0.03 self.path = os.path.dirname(data_filename) self.clickable_width = clickable_width # load delta video bag if delta_video_filename != 'none': self.dvbag = rosbag.Bag(delta_video_filename) else: self.dvbag = None # Initialize self.trajec_width_dict = {} try: fname = os.path.join(self.path, 'trajec_to_color_dict.pickle') f = open(fname, 'r+') self.trajec_to_color_dict = pickle.load(f) f.close() except: self.trajec_to_color_dict = {} for key in self.pd.objid.unique(): color = get_random_color() self.trajec_to_color_dict.setdefault(key, color) self.plotted_traces_keys = [] self.plotted_traces = [] self.trajectory_ends_vlines = [] self.data_to_add = [] self.selected_trajectory_ends = [] self.object_id_numbers = [] self.annotations = os.path.join(self.path, 'annotations.pickle') if os.path.exists(self.annotations): f = open(self.annotations, 'r+') data = pickle.load(f) f.close() self.annotated_keys = data.keys() else: self.annotated_keys = [] self.time_mouse_click = time.time() self.cut_objects = False self.delete_objects = False self.join_objects = False self.add_data = False self.crosshair_pen = pg.mkPen('w', width=1) self.ui.qtplot_timetrace.enableAutoRange('xy', False) if self.config is not None: print('**** Sensory stimulus: ', self.config.sensory_stimulus_on) for r, row in enumerate(self.config.sensory_stimulus_on): v1 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][0], self.config.sensory_stimulus_on[r][0] ], [0, 10]) v2 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][-1], self.config.sensory_stimulus_on[r][-1] ], [0, 10]) try: f12 = pg.FillBetweenItem( curve1=v1, curve2=v2, brush=pg.mkBrush(self.config.sensory_stimulus_rgba[r])) except: f12 = pg.FillBetweenItem(curve1=v1, curve2=v2, brush=pg.mkBrush( (255, 0, 0, 150))) self.ui.qtplot_timetrace.addItem(f12) lr = pg.LinearRegionItem(values=self.troi) f = 'update_time_region' lr.sigRegionChanged.connect(self.__getattribute__(f)) self.ui.qtplot_timetrace.addItem(lr) print('drawing interesting time points') self.draw_timeseries_vlines_for_interesting_timepoints() print('done drawing interesting time points') self.ui.qtplot_timetrace.setRange(xRange=[ np.min(self.time_epoch_continuous), np.max(self.time_epoch_continuous) ], yRange=[0, np.max(self.nflies)]) self.ui.qtplot_timetrace.setLimits(yMin=0, yMax=np.max(self.nflies)) self.ui.qtplot_timetrace.setLimits(minYRange=np.max(self.nflies), maxYRange=np.max(self.nflies)) self.current_time_vline = pg.InfiniteLine(angle=90, movable=False) self.ui.qtplot_timetrace.addItem(self.current_time_vline, ignoreBounds=True) self.current_time_vline.setPos(0) pen = pg.mkPen((255, 255, 255), width=2) self.current_time_vline.setPen(pen) # hide a bunch of the axes self.ui.qtplot_timetrace.hideAxis('left') self.ui.qtplot_timetrace.hideAxis('bottom') self.ui.qtplot_trajectory.hideAxis('left') self.ui.qtplot_trajectory.hideAxis('bottom')
x_scale_vals=x_scale_vals, auto_run=False) if show_ecp_definition: win = o3plot.create_scaled_window_for_tds(tds, title='ECP definition') o3plot.plot_two_d_system(tds, win) o3plot.show() ##% fc.get_special_coords_and_slopes() # Step 1 if show_get_special_coords_and_slopes: win = o3plot.create_scaled_window_for_tds( tds, title='get_special_coords_and_slopes') leg = win.addLegend(offset=(70, 30), brush=0.3, labelTextColor='w') o3plot.plot_two_d_system(tds, win, c2='w', cs='w') leg.addItem(pg.PlotDataItem([0], [0], pen='w'), name='2D system definition') for i in range(len(fc.sds)): win.plot(fc.sds[i][0], fc.sds[i][1], pen='b', symbol='x', symbolPen='b', symbolBrush='b', symbolSize=10, name='Important slope') xcs = fc.xcs_sorted for i in range(len(xcs)): xc = xcs[i] xn = xc * np.ones_like(list(fc.yd[xc])) win.plot(xn,
def __init__(self): # Load an instance of the Digitizer control object # Load the ui file for GUI QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.mutex = QtCore.QMutex() # Window for real time streaming pg.setConfigOption('background','w') pg.setConfigOption('foreground','k') self.pen=pg.mkPen(color=(0,0,0)) self.pen2=pg.mkPen(color=(255,0,0)) #self.pen=pg.mkPen(1) #self.streamwindow=pg.LayoutWidget() self.plotchannels = pg.GraphicsLayoutWidget() self.StreamWindow.addWidget(self.plotchannels,row=0,col=0,rowspan=1,colspan=1) self.plt_chA =self.plotchannels.addPlot(row=0,col=0) self.plt_chA.setLabel(axis='left',text='Signal') self.plt_chA.setLabel(axis='bottom',text='Tof (x0.5ns)') self.plt_chA.showGrid(1,1,alpha=0.5) self.plt_datachA=pg.PlotDataItem(np.arange(2000),np.zeros((2000))) self.plt_chA.addItem(self.plt_datachA) self.roiA = pg.LinearRegionItem(values=(500,1000),bounds=(-30000,30000)) # first vector =[x0,y0], second vector =[lx,ly] self.plt_chA.addItem(self.roiA) self.roiA.setZValue(10) # make sure ROI is drawn above image #self.roiA.sigRegionChanged.connect(self.UpdatePlot) self.plt_intchA =self.plotchannels.addPlot(row=1,col=0) self.plt_intchA.setLabel(axis='left',text='Integrated Signal') self.plt_intchA.setLabel(axis='bottom',text='real time (ms)') self.plt_intchA.showGrid(1,1,alpha=0.5) self.ROIRate_button.display(0) self.plotchannelsSCTDC = pg.GraphicsLayoutWidget() self.StreamWindow_SCTDC.addWidget(self.plotchannelsSCTDC,row=0,col=0,rowspan=1,colspan=1) self.plotScan=self.plotchannelsSCTDC.addPlot(row=0,col=0) self.imgSCTDC = pg.ImageItem() self.plotScan.addItem(self.imgSCTDC) self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.imgSCTDC) self.plotchannelsSCTDC.addItem(self.hist,row=0,col=1) self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls #Digitizer stream parameters self.StartStream_button.clicked.connect(self.StartStream) self.StopStream_button.clicked.connect(self.StopStream) self.SignalThresh_button.valueChanged.connect(self.setAcquisitionParameters) self.TOFT0_button.valueChanged.connect(self.setAcquisitionParameters) #self.ChA_broadcast_button.stateChanged.connect(self. # Digitizer record parameters self.RecSS_button.clicked.connect(self.setAcquisitionParameters) self.RecAvg_button.clicked.connect(self.setAcquisitionParameters) self.progress=0.0 self.Nsamples_button.valueChanged.connect(self.setAcquisitionParameters) self.Nseconds_button.valueChanged.connect(self.setAcquisitionParameters) self.Reprate_button.activated.connect(self.setAcquisitionParameters) self.PretriggerVal_button.valueChanged.connect(self.setAcquisitionParameters) self.HoldoffVal_button.valueChanged.connect(self.setAcquisitionParameters) self.RecRef_button.clicked.connect(self.SaveTrace) # Metadata record parameters # Voltages self.Vtofmcpf_button.valueChanged.connect(self.setMetadata) self.Vgrid_button.valueChanged.connect(self.setMetadata) self.Vtofdtube_button.valueChanged.connect(self.setMetadata) self.Vrep_button.valueChanged.connect(self.setMetadata) self.Vext_button.valueChanged.connect(self.setMetadata) self.Vcorr_button.valueChanged.connect(self.setMetadata) self.Vvmimcpf_button.valueChanged.connect(self.setMetadata) self.Vvmimcpb_button.valueChanged.connect(self.setMetadata) self.Vph_button.valueChanged.connect(self.setMetadata) # Channels labels #self.ChAlabel_button.textChanged.connect(self.setMetadata) #self.ChBlabel_button.textChanged.connect(self.setMetadata) #delay value for single tof (no dscan) self.Singledelay_button.valueChanged.connect(self.setMetadata) # Comments on the scan self.Comments_button.textChanged.connect(self.setMetadata) # Path for file saving self.FilePath_button.textChanged.connect(self.setAcquisitionParameters) self.FilePath='//sb1files.epfl.ch/lsu/LSU_DATA/Wetlab/Data/Photoelectrons/20180809' self.FilePathBrowser_button.clicked.connect(self.setDir) # self.DscanMode_button.stateChanged.connect(self.setAcquisitionParameters) self.DscanStart_button.valueChanged.connect(self.setAcquisitionParameters) self.DscanStop_button.valueChanged.connect(self.setAcquisitionParameters) self.DscanStep_button.valueChanged.connect(self.setAcquisitionParameters) #self.FilePath_button.textChanged.connect(self.setAcquisitionParameters) self.Delayfile=[] self.DelayfilePath='' self.DelayfileBrowser_button.clicked.connect(self.setDelayfile) # Start/Stop self.data_chA = np.zeros((self.Nsamples_button.value()),dtype=np.int64) self.RecData_chA=np.zeros((self.Nsamples_button.value()*2),dtype=np.int64) self.diff_data=0 self.prev_data=0 self.rolling_dataA = np.zeros((500,2)) # rolling array for integrated signal in real time from CHA self.rolling_count = 0 self.t0 = 0 # first timeStamp recording self.SavedData_chA = np.zeros((self.Nsamples_button.value()),dtype=np.int64) self.StartAcq_button.clicked.connect(self.StartAcquisition) self.StopAcq_button.clicked.connect(self.StopAcquisition) self.AcqStart=0 print 'GUI loaded' f.write('GUI loaded') self.timer=QtCore.QTimer() self.timer.timeout.connect(self.UpdateRecording) self.MetadataDict=[] self.thread=[] self.SCTDCthread=[] self.TDCthread=[] self.broadcastthread=[] self.DAQ=DAQ() self.SCTDC=[] self.Dstage=DelayStage() self.KineticEnergy=np.zeros((self.Nsamples_button.value())) self.delaylist=np.zeros((1)) f.write('init digitizer done') print 'init digitizer done'
def _show_calculation_button_fired(self): d = self.FFx[1] - self.FFx[0] FFx = np.zeros((len(self.time), len(self.FFx))) FFy = np.zeros((len(self.time), len(self.FFx))) for i in range(len(self.time)): self._fourier_transform(self.time[i]) # now we have self.FFx and self.FFy FFx[i][:] = self.FFx FFy[i][:] = self.FFy ** 2 self._mw.a.setValue(self.a) self._mw.g.setValue(self.g) self.S = (self.a / np.pi) * self.g / ((self.FFx - self.x0) ** 2 + self.g ** 2) + ( self.k * self.FFx + self.b) * 1e-18 self._mw.spin_noise_plot.clear() self.noise_spectrum_image = pg.PlotDataItem(self.FFx, self.S * 1e18, pen=pg.mkPen(palette.c5, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c5, symbolBrush=palette.c5, symbolSize=7) self._mw.spin_noise_plot.addItem(self.noise_spectrum_image) self._mw.spin_noise_plot.setLabel(axis='left', text='Intensity', units='arb.u.') self._mw.spin_noise_plot.setLabel(axis='bottom', text='Frequency', units='Hz') self._mw.spin_noise_plot.showGrid(x=True, y=True, alpha=0.8) hi = [] hi1 = [] for i in range(len(self.time)): Int = trapz(self.S * FFy[i][:], dx=d) * 1e+18 # integration hi.append(Int) Int1 = trapz((self.k * self.FFx + self.b) * FFy[i][:], dx=d) # integration hi1.append(Int1) hi = [-x for x in hi] hi1 = [-x for x in hi1] calculated_counts = np.exp(hi) self._mw.error_approximation.display(100 * np.sum( np.abs(calculated_counts - self.normalized_counts) / calculated_counts) / len(self.normalized_counts)) try: self._mw.processeddataplot.removeItem(self.fit_image) self._mw.processeddataplot.removeItem(self.baseline_image) except: print(1) self.fit_image = pg.PlotDataItem(self.time, calculated_counts, pen=pg.mkPen(palette.c6, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c6, symbolBrush=palette.c6, symbolSize=7 ) self._mw.processeddataplot.addItem(self.fit_image) self.baseline_image = pg.PlotDataItem(self.time, np.exp(hi1), pen=pg.mkPen(palette.c6, style=QtCore.Qt.DotLine), symbol='o', symbolPen=palette.c6, symbolBrush=palette.c6, symbolSize=7 ) self._mw.processeddataplot.addItem(self.baseline_image)
def _get_sel_range_curve(self): color = QColor(self.color) color.setAlpha(LinePlotStyle.SELECTED_RANGE_ALPHA) curve1 = curve2 = pg.PlotDataItem(x=self.x_data, y=self.__mean) return pg.FillBetweenItem(curve1, curve2, brush=color)
def peakdetection(self, blueThresh, redThresh, bluePeakThresh, redPeakThresh): markers = ['C', 'A', 'G', 'T'] colors = ['r', 'b'] score = ascore = gscore = tscore = spseries = pd.Series() df = pd.DataFrame({ "ident": [], 'stimes': [], 'etimes': [], 'peaks': [], 'mins': [] }) seqdf = pd.DataFrame({'base': [], 'times': []}) time1, intensity1 = self.p1.roiCurve1.getData() time2, intensity2 = self.p1.roiCurve2.getData() intensities = [intensity1, intensity2] self.firingplotlist = [] peakseries = pd.Series() minseries = pd.Series() for ind, intensity in enumerate(intensities): if ind == 0: thresh = redThresh noise = redPeakThresh if ind == 1: thresh = blueThresh noise = bluePeakThresh firing = np.where( ((intensity > thresh) & (intensity > intensities[ind - 1])))[0] startandend = np.diff(firing) startpoints = np.insert(startandend, 0, 2) endpoints = np.insert(startandend, -1, 2) startpoints = np.where(startpoints > 1)[0] endpoints = np.where(endpoints > 1)[0] startpoints = firing[startpoints] endpoints = firing[endpoints] df = df.append(pd.DataFrame({ "ident": [ind] * len(startpoints), 'stimes': startpoints, 'etimes': endpoints }), ignore_index=True) for i, x in enumerate(startpoints): sp = startpoints[i] ep = endpoints[i] + 1 curve = pg.PlotDataItem(x=np.linspace(sp, ep, ep - sp), y=intensity[sp:ep], pen=pg.mkPen(colors[ind], width=2)) self.firingplotlist.append(curve) self.p1.getRoiPlot().addItem(curve) try: peaks, mins = peakdet(v=intensity[sp:ep], delta=noise, x=np.arange(sp, ep)) if len(peaks) == 0 or len(mins) == 0: peaks = np.NAN substack = np.mean(self.stack[sp:ep], 0) if ind == 0: cscore = np.dot(substack.ravel(), self.czpro[0].ravel()) ascore = np.dot(substack.ravel(), self.czpro[1].ravel()) if cscore > ascore: call = 'C' else: call = 'A' if ind == 1: gscore = np.dot(substack.ravel(), self.czpro[2].ravel()) tscore = np.dot(substack.ravel(), self.czpro[3].ravel()) if gscore > tscore: call = 'G' else: call = 'T' seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [sp] }), ignore_index=True) else: # point = pg.PlotDataItem(peaks, pen = None, symbol = 'o', symbolBrush = 'g') # self.p1.getRoiPlot().addItem(point) # self.firingplotlist.append(point) # point = pg.PlotDataItem(mins, pen = None, symbol = 'o', symbolBrush = 'r') # self.p1.getRoiPlot().addItem(point) # self.firingplotlist.append(point) for i, x in enumerate(peaks): if i == 0: ssp = sp sep = int(mins[i][0]) elif i == len(peaks) - 1: ssp = int(mins[i - 1][0]) sep = ep else: ssp = int(mins[i - 1][0]) sep = int(mins[i][0]) substack = np.mean(self.stack[ssp:sep + 1], 0) if ind == 0: cscore = np.dot(substack.ravel(), self.czpro[0].ravel()) ascore = np.dot(substack.ravel(), self.czpro[1].ravel()) if cscore > ascore: call = 'C' else: call = 'A' if ind == 1: gscore = np.dot(substack.ravel(), self.czpro[2].ravel()) tscore = np.dot(substack.ravel(), self.czpro[3].ravel()) if gscore > tscore: call = 'G' else: call = 'T' seqdf = seqdf.append(pd.DataFrame({ 'base': [call], 'times': [ssp] }), ignore_index=True) peakseries = peakseries.append(pd.Series([peaks])) minseries = minseries.append(pd.Series([mins])) except: ValueError seqdf = seqdf.sort(['times', 'base']) for i, x in enumerate(seqdf.index): base = seqdf.base[i] if base == 'C': color = 'r' intensity = intensities[0][int(seqdf.times[i])] if base == 'A': color = 'y' intensity = intensities[0][int(seqdf.times[i])] if base == 'G': color = 'g' intensity = intensities[1][int(seqdf.times[i])] if base == 'T': color = 'b' intensity = intensities[1][int(seqdf.times[i])] text = pg.TextItem(base, color=color) seqplot = self.p1.getRoiPlot().addItem(text) if i == 0: self.seqplotlist = [text] else: self.seqplotlist.append(text) text.setPos(seqdf.times[i], intensity) print(seqdf.base.str.cat()) return seqdf
def __init__(self, data_filename, bgimg, delta_video_filename, skip_frames=5): ''' skip_frames - when playing back movie, how many frames to skip between updates (to speed up viewing) ''' self.data_filename = data_filename self.load_data() self.backgroundimg_filename = bgimg self.backgroundimg = None self.binsx = None self.binsy = None trange = np.max(self.pd.time_epoch.values) - np.min( self.pd.time_epoch.values) self.troi = [ np.min(self.pd.time_epoch.values), np.min(self.pd.time_epoch.values) + trange * 0.1 ] self.skip_frames = skip_frames self.path = os.path.dirname(delta_video_filename) # load delta video bag if delta_video_filename != 'none': self.dvbag = rosbag.Bag(delta_video_filename) else: self.dvbag = None # trajectory colors self.trajec_to_color_dict = {} self.trajec_width_dict = {} self.plotted_traces_keys = [] self.plotted_traces = [] self.trajectory_ends_vlines = [] ## create GUI self.app = QtGui.QApplication([]) self.w = QtGui.QWidget() self.layout = QtGui.QGridLayout() self.w.setLayout(self.layout) self.w.show() # play movie button play_btn = QtGui.QPushButton('play video sequence') play_btn.pressed.connect(self.play_movie) self.layout.addWidget(play_btn, 0, 0) # stop movie button stop_btn = QtGui.QPushButton('stop video sequence') stop_btn.pressed.connect(self.stop_movie) self.layout.addWidget(stop_btn, 1, 0) # toggle delete trajectory button toggle_delete_object_id_btn = QtGui.QPushButton( 'delete objects\ncrosshair = red') toggle_delete_object_id_btn.pressed.connect( self.toggle_delete_object_id_numbers) self.layout.addWidget(toggle_delete_object_id_btn, 3, 0) self.delete_objects = False # toggle cut trajectory button toggle_cut_object_id_btn = QtGui.QPushButton( 'cut objects\ncrosshair = yellow') toggle_cut_object_id_btn.pressed.connect( self.toggle_cut_object_id_numbers) self.layout.addWidget(toggle_cut_object_id_btn, 4, 0) self.cut_objects = False # start collecting object ids button start_collecting_object_id_btn = QtGui.QPushButton( 'select objects to join\ncrosshair = green') start_collecting_object_id_btn.pressed.connect( self.start_collecting_object_id_numbers) self.layout.addWidget(start_collecting_object_id_btn, 5, 0) self.join_objects = False # save collected object ids button save_collected_object_id_btn = QtGui.QPushButton( 'join selected\nobject id numbers') save_collected_object_id_btn.pressed.connect( self.save_collected_object_id_numbers) self.layout.addWidget(save_collected_object_id_btn, 6, 0) # undo undo_btn = QtGui.QPushButton('undo last action') undo_btn.pressed.connect(self.undo) self.layout.addWidget(undo_btn, 7, 0) self.p1 = pg.PlotWidget(title="Basic array plotting") self.p1.enableAutoRange('xy', False) self.layout.addWidget(self.p1, 1, 1) if self.config is not None: print '**** Sensory stimulus: ', self.config.sensory_stimulus_on for r, row in enumerate(self.config.sensory_stimulus_on): v1 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][0], self.config.sensory_stimulus_on[r][0] ], [0, 10]) v2 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][-1], self.config.sensory_stimulus_on[r][-1] ], [0, 10]) f12 = pg.FillBetweenItem(curve1=v1, curve2=v2, brush=pg.mkBrush('r')) self.p1.addItem(f12) self.p2 = pg.PlotWidget() self.layout.addWidget(self.p2, 0, 1) lr = pg.LinearRegionItem(values=self.troi) f = 'update_time_region' lr.sigRegionChanged.connect(self.__getattribute__(f)) self.p1.addItem(lr) self.draw_timeseries_vlines_for_interesting_timepoints() self.current_time_vline = pg.InfiniteLine(angle=90, movable=False) self.p1.addItem(self.current_time_vline, ignoreBounds=True) self.current_time_vline.setPos(0) pen = pg.mkPen((255, 255, 255), width=2) self.current_time_vline.setPen(pen)