def gui_docks_p2_04_02(d_area, _, title=None): d1 = Dock(title, size=(1, 1), closable=True) tab_1 = pg.TableWidget() d1.addWidget(tab_1) d_area.addDock(d1, 'right') c = np.arange(2.0, 0.0, -0.1) def solve_for_r(conc, start_r): return root( lambda r: -r + 1.5 * (conc - 0.8 * r) / (1 + 0.3 * np.sqrt(conc - 0.8 * r) + 0.1 * (conc - 0.8 * r))**2.0, np.array([start_r])).x r_calc = np.array([solve_for_r(conc, 0.1) for conc in c]).flatten() simple_t = -np.gradient(c) * 1 / r_calc simple_t[0] = 0 simple_t = np.cumsum(simple_t) quad_t = np.array([ quad(lambda conc: 1 / solve_for_r(conc, 0.1), c_min, 2.0) for c_min in c ])[:, 0] data = np.array([c, 1 / r_calc, simple_t, quad_t]).T tab_1.setData(data) tab_1.setHorizontalHeaderLabels(['c', '1/r', 't_simple', 't_quadfunc']) tab_1.sortByColumn(2, QtCore.Qt.AscendingOrder) tab_1.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
def __init__(self, title, mode="PLOT", size=None, closable=False): if mode not in modes: raise Exception("INvalid Mode Specified. PSecify PLOT or TABLE") self.mode = mode Dock.__init__(self, title, size=size, closable=closable) self.newdata = [] self.data = [] self.refdata = [] self.startindex = 0 self.endindex = 0 self.legenditem = None self.updateinfo = True self.control = controlDock(title) self.control.paused.connect(self.pausePlot) self.control.showLegend.connect(self.showLegend) if mode == "PLOT": self.wid = pg.PlotWidget(title="") self.addWidget(self.wid) self.plotList = [] elif mode == "TABLE": self.wid = pg.TableWidget() self.addWidget(self.wid) self.wid.setColumnCount(len(tableoptkeys)) self.wid.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.tabList = []
def __init__(self, mol, parent, **kwargs): super(TableWindow, self).__init__(parent) kind = kwargs.get('kind', None) if kind == 'distance': self.setWindowTitle('Molviewer :: Distance matrix :: {:s}'.format( mol.filename)) data = distance_matrix(mol) table = pg.TableWidget(sortable=False) table.setData(data) # elif kind == 'info': # self.setWindowTitle('MolViewer :: Info table :: {:s}'.format(mol.filename)) # data = moleculeinfo(mol) # table = pg.TableWidget(sortable=False) # table.setData(data) closebutton = QtGui.QPushButton("&Close") closebutton.setFocus() closebutton.clicked.connect(self.close) buttonbox = QtGui.QDialogButtonBox() buttonbox.addButton(closebutton, QtGui.QDialogButtonBox.ActionRole) verticalLayout = QtGui.QVBoxLayout(self) verticalLayout.addWidget(table) verticalLayout.addWidget(buttonbox)
def __init__(self, topics=None, terms=None, addr=None, parent=None, **kwargs): super().__init__(parent) self.terms = terms self.update_rate = kwargs.get('update_rate', 30) self.grid = QtGui.QGridLayout(self) self.table = pg.TableWidget() self.last_updated = QtWidgets.QLabel(parent=self) self.grid.addWidget(self.table, 0, 0) self.grid.setRowStretch(0, 10) self.grid.addWidget(self.last_updated, 1, 0) self.fetcher = None if addr: self.fetcher = AsyncFetcher(topics, terms, addr, parent=self, ratelimit=1.0 / self.update_rate) self.fetcher.start()
def set_up(self): layout = QtGui.QHBoxLayout() self.setLayout(layout) # Graph self.graph_widget = self.create_graph_widget() self.color_map = pg.ColorMap([0, 0.5, 1], [(1., 1., 1.), (1., 1., 0.), (1., 0.5, 0.)]) # Enriched GO terms go_table = pg.TableWidget() go_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) go_table.clicked.connect(self.select_term) data = np.array([(term[0], float(term[1]), len(term[2])) for term in self.analysis.go_terms.values()], dtype=[('GO ID', object), ('P-waarde', float), ('Eiwitten', int)]) go_table.setData(data) # Proteins in selected GO term proteins_container = QtGui.QWidget() proteins_container.setLayout(QtGui.QVBoxLayout()) self.proteins_table = pg.TableWidget() self.proteins_table.setSelectionBehavior( QtGui.QAbstractItemView.SelectRows) self.proteins_table.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)) self.graph_title = QtGui.QLabel('') self.graph_title.setAlignment(QtCore.Qt.AlignHCenter) self.graph_title.setOpenExternalLinks(True) font = QtGui.QFont() font.setBold(True) self.graph_title.setFont(font) self.graph_title.setWordWrap(True) self.show_graph_button = QtGui.QPushButton('Graph') self.show_graph_button.clicked.connect(self.show_graph) proteins_container.layout().addWidget(self.graph_title) proteins_container.layout().addWidget(self.proteins_table) proteins_container.layout().addWidget(self.show_graph_button) # Splitter with widgets splitter = QtGui.QSplitter(self) splitter.addWidget(go_table) splitter.addWidget(proteins_container) splitter.setSizes([1, 1, 1]) layout.addWidget(splitter)
def __init__(self): QtGui.QWidget.__init__(self) self.win = pg.TableWidget(editable=True, sortable=False) self.layout = QtGui.QVBoxLayout() self.layout.addWidget(self.win) self.setLayout(self.layout) self.win.setData([]) data.updateState.connect(self.replot) self.win.setFormat("%.3f")
def showMetadata(self): """ Show Metadata information in the table """ self.w = pg.TableWidget() self.w.show() self.w.resize(500, 900) self.w.setData(self.file['Metadata/Metadata'][:])
def setupUi(self): """Set up the UI for tomography plugin""" self.toolbar = Toolbar() self.centerwidget = QtGui.QTabWidget() self.centerwidget.setDocumentMode(True) self.centerwidget.setTabsClosable(True) self.bottomwidget = viewers.RunConsole() self.functionwidget = QUiLoader().load('xicam/gui/tomographyleft.ui') self.functionwidget.functionsList.setAlignment(QtCore.Qt.AlignBottom) self.functionwidget.addFunctionButton.setToolTip('Add function to pipeline') self.functionwidget.clearButton.setToolTip('Clear pipeline') self.functionwidget.fileButton.setToolTip('Save/Load pipeline') self.functionwidget.moveDownButton.setToolTip('Move selected function down') self.functionwidget.moveUpButton.setToolTip('Move selected function up') self.addfunctionmenu = QtGui.QMenu() self.functionwidget.addFunctionButton.setMenu(self.addfunctionmenu) self.functionwidget.addFunctionButton.setPopupMode(QtGui.QToolButton.ToolButtonPopupMode.InstantPopup) self.functionwidget.addFunctionButton.setArrowType(QtCore.Qt.NoArrow) filefuncmenu = QtGui.QMenu() icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("xicam/gui/icons_55.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.openaction = QtGui.QAction(icon, 'Open', filefuncmenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("xicam/gui/icons_59.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.saveaction = QtGui.QAction(icon, 'Save', filefuncmenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("xicam/gui/icons_56.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.refreshaction = QtGui.QAction(icon, 'Reset', filefuncmenu) filefuncmenu.addActions([self.openaction, self.saveaction, self.refreshaction]) self.functionwidget.fileButton.setMenu(filefuncmenu) self.functionwidget.fileButton.setPopupMode(QtGui.QToolButton.ToolButtonPopupMode.InstantPopup) self.functionwidget.fileButton.setArrowType(QtCore.Qt.NoArrow) leftwidget = QtGui.QSplitter(QtCore.Qt.Vertical) paramtree = pt.ParameterTree() self.param_form = QtGui.QStackedWidget() self.param_form.addWidget(paramtree) self.property_table = pg.TableWidget() self.property_table.verticalHeader().hide() self.property_table.horizontalHeader().setStretchLastSection(True) self.property_table.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding) leftwidget.addWidget(self.param_form) leftwidget.addWidget(self.functionwidget) icon_functions = QtGui.QIcon(QtGui.QPixmap("xicam/gui/icons_49.png")) icon_properties = QtGui.QIcon(QtGui.QPixmap("xicam/gui/icons_61.png")) #metadata icon self.leftmodes = [(leftwidget, icon_functions),(self.property_table,icon_properties)]
def __init__(self): QtGui.QStackedWidget.__init__(self) self.widgets = {} self.widgets['empty'] = QtGui.QWidget() self.widgets['table'] = pg.TableWidget() self.widgets['text'] = QtGui.QTextBrowser() self.widgets['plot'] = pg.PlotWidget() self.widgets['image'] = pg.ImageView() for w in self.widgets.values(): self.addWidget(w) self.clear()
def __init__(self,parent=None,pvType='Motor'): QWidget.__init__(self,parent) self.pvType=pvType self.layout=pg.LayoutWidget() self.addPVButton=QPushButton('Add '+self.pvType) self.addPVButton.clicked.connect(self.addPV) self.removePVButton=QPushButton('Remove '+self.pvType) self.removePVButton.clicked.connect(self.removePVs) self.layout.addWidget(self.addMotorButton,row=0,col=0) self.layout.addWidget(self.removeMotorButton,row=0,col=1) self.PVTable=pg.TableWidget(editable=True,sortable=True) self.layout.addWidget(self.PVTable,row=1,col=0,colspan=2)
def __init__(self, data): col_selection_TemplateBaseClass.__init__(self) # Create the param window self.ui = col_selection_WindowTemplate() self.ui.setupUi(self) self.ui.done_pushButton.clicked.connect(self.done) self.table_widget = pg.TableWidget() self.ui.data_preview_groupBox.layout().addWidget(self.table_widget) self.table_widget.setData(data) #self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) self.show()
def __init__(self, parent=None): super(DetailFirstrowdata, self).__init__(parent) # self.resize(400,500) # 设置好的布局 已经保证可以完全填充窗体 self.mylayout = QGridLayout(self) self.mylayout.setObjectName("gridLayout") self.firstrow = pg.TableWidget() # 下面是手动添加信息,需要改变 self.firstrowdata = [(1156, '0.001001', '192.168.0.101', '221.15.13.15', 'Tcp', '62', 'syn = 2123'), (1157, '0.101001', '192.168.0.101', '221.15.13.15', 'Tcp', '62', 'syn = 2235'), (1158, '1.001001', '92.168.0.101', '221.15.13.15', 'Tcp', '15', 'syn = 2152'), (1159, '10.001001', '192.168.0.101', '121.15.13.15', 'Tcp', '25', 'syn = 2365'), (1160, '2.001001', '192.168.0.101', '58.15.13.15', 'Tcp', '85', 'syn = 2155')] # np 可以不用,这个更方便的定义了数据格式 self.showfirstrowdata = np.array(self.firstrowdata, dtype=[('No', int), ('Time', object), ('Source', object), ('Destination', object), ('Protocol', object), ('Length', object), ('Info', object)]) self.firstrow.setData(self.showfirstrowdata) self.mylayout.addWidget(self.firstrow) self.firstrow.setShowGrid(False) # 是否显示网格线 self.firstrow.verticalHeader().setHidden(True) # 垂直方向的表头删除 # self.bottomwindow.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch()) TypeError: 'ResizeMode' object is not callable self.firstrow.setColumnWidth(0, 130) # 设置列宽 self.firstrow.setColumnWidth(1, 180) self.firstrow.setColumnWidth(2, 300) self.firstrow.setColumnWidth(3, 300) self.firstrow.setColumnWidth(4, 130) self.firstrow.setColumnWidth(5, 130) self.firstrow.horizontalHeader().setStretchLastSection( True) # 最后一个随机全部占满剩余空间 self.firstrow.setSelectionBehavior( QAbstractItemView.SelectRows) # 选中一个 选中整行 self.firstrow.setFrameShape(QFrame.NoFrame) # self.bottomwindow.horizontalHeader().setSectionResizeMode(1,QHeaderView.Stretch()) # self.bottomwindow.horizontalHeader().setResizeMode(1,QHeaderView.ResizeToContents()Stretch) self.setLayout(self.mylayout) self.timer1 = threading.Timer( 0.4, self.putnumofdecode) # 这个是为了显示那个,第一栏显示数据的速度的 self.timer1.start()
def __init__(self, title, **kwargs): super().__init__(**kwargs) self.table = pg.TableWidget() self.bottom.addWidget(self.table) self.desciption = pg.LayoutWidget() self.title = QtGui.QLabel() self.title.setAlignment(QtCore.Qt.AlignCenter) self.title.setText('<h2>' + title + ' <\h2>') self.warning = QtGui.QLabel() self.warning.setAlignment(QtCore.Qt.AlignCenter) self.desciption.addWidget(self.title) self.desciption.nextRow() self.desciption.addWidget(self.warning) self.bottom.addWidget(self.desciption)
def __init__(self, path, sequence_length): QWidget.__init__(self) bowtie_result_file = path found_primer_data, header, query_name = self.create_data(bowtie_result_file) # Set title and size self.setWindowTitle('Primers found for query ' + query_name) self.resize(1000, 793) # Table table_window = pg.TableWidget() table_window.setData(found_primer_data) table_window.setHorizontalHeaderLabels(header) table_window.setColumnWidth(0, 200) table_window.setColumnWidth(1, 150) table_window.setColumnWidth(2, 150) table_window.setColumnWidth(3, 250) table_window.setColumnWidth(4, 150) graphic_window = GraphDisplay(found_primer_data, query_name, sequence_length) layout = QVBoxLayout(self) layout.addWidget(table_window) layout.addWidget(graphic_window) self.setLayout(layout)
def __init__(self, parent=None): self.sweeps = [] self.channels = [] self.current_event_set = None self.event_sets = [] QtGui.QWidget.__init__(self, parent) self.layout = QtGui.QGridLayout() self.setLayout(self.layout) self.layout.setContentsMargins(0, 0, 0, 0) self.vsplit = QtGui.QSplitter(QtCore.Qt.Vertical) self.layout.addWidget(self.vsplit, 0, 0) self.pre_plot = pg.PlotWidget() self.post_plot = pg.PlotWidget() for plt in (self.pre_plot, self.post_plot): plt.setClipToView(True) plt.setDownsampling(True, True, 'peak') self.post_plot.setXLink(self.pre_plot) self.vsplit.addWidget(self.pre_plot) self.vsplit.addWidget(self.post_plot) self.response_plots = PlotGrid() self.vsplit.addWidget(self.response_plots) self.event_splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) self.vsplit.addWidget(self.event_splitter) self.event_table = pg.TableWidget() self.event_splitter.addWidget(self.event_table) self.event_widget = QtGui.QWidget() self.event_widget_layout = QtGui.QGridLayout() self.event_widget.setLayout(self.event_widget_layout) self.event_splitter.addWidget(self.event_widget) self.event_splitter.setSizes([600, 100]) self.event_set_list = QtGui.QListWidget() self.event_widget_layout.addWidget(self.event_set_list, 0, 0, 1, 2) self.event_set_list.addItem("current") self.event_set_list.itemSelectionChanged.connect( self.event_set_selected) self.add_set_btn = QtGui.QPushButton('add') self.event_widget_layout.addWidget(self.add_set_btn, 1, 0, 1, 1) self.add_set_btn.clicked.connect(self.add_set_clicked) self.remove_set_btn = QtGui.QPushButton('del') self.event_widget_layout.addWidget(self.remove_set_btn, 1, 1, 1, 1) self.remove_set_btn.clicked.connect(self.remove_set_clicked) self.fit_btn = QtGui.QPushButton('fit all') self.event_widget_layout.addWidget(self.fit_btn, 2, 0, 1, 2) self.fit_btn.clicked.connect(self.fit_clicked) self.fit_plot = PlotGrid() self.fit_explorer = None self.artifact_remover = ArtifactRemover(user_width=True) self.baseline_remover = BaselineRemover() self.filter = SignalFilter() self.params = pg.parametertree.Parameter( name='params', type='group', children=[{ 'name': 'pre', 'type': 'list', 'values': [] }, { 'name': 'post', 'type': 'list', 'values': [] }, self.artifact_remover.params, self.baseline_remover.params, self.filter.params, { 'name': 'time constant', 'type': 'float', 'suffix': 's', 'siPrefix': True, 'value': 10e-3, 'dec': True, 'minStep': 100e-6 }]) self.params.sigTreeStateChanged.connect(self._update_plots)
def spikesort_gui(load_previous_dataset=True): def load_config(): global raw_data global sampling_frequency global number_of_channels_in_binary_file global prb_file global duration_of_time_plot global spike_info global channel_map global num_of_shanks_for_vis config = configparser.ConfigParser() config.read( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'defaults.ini')) if not 'SPIKES' in config: return all_exist = True spike_info_file = config['SPIKES']['spike_info_file'] if 'spike_info.df' in spike_info_file: spike_info = pd.read_pickle(spike_info_file) update_templates_table() generate_scater_plot() file_name = config['BINARY DATA FILE']['binary_data_filename'] if not os.path.isfile(file_name): all_exist = False prb_file = config['PROBE']['prb_file'] if not os.path.isfile(prb_file): all_exist = False channel_map_file = config['PROBE']['channel_map_file'] if not os.path.isfile(channel_map_file): all_exist = False else: channel_map = np.squeeze(np.load(channel_map_file)) if all_exist: type = config['BINARY DATA FILE']['type'] types = { 'int16': np.int16, 'uint16': np.uint16, 'int32': np.int32, 'uint32': np.uint32, 'int64': np.int64, 'uint32': np.uint64, 'float16': np.float16, 'float32': np.float32, 'float64': np.float64 } number_of_channels_in_binary_file = int( config['BINARY DATA FILE'] ['number_of_channels_in_binary_file']) order = config['BINARY DATA FILE']['order'] raw_data = np.memmap(file_name, mode='r', dtype=types[type]) raw_data = np.reshape(raw_data, (number_of_channels_in_binary_file, int(raw_data.shape[0] / number_of_channels_in_binary_file)), order=order) sampling_frequency = int( config['BINARY DATA FILE']['sampling_frequency']) electrodes = len(channel_map) for i in range(electrodes): electrode_curve = pg.PlotCurveItem() spikes_time_plot.addItem(electrode_curve) avg_electrode_curves.append(electrode_curve) duration_of_time_plot = float( config['TIME PLOT']['duration_of_time_plot']) num_of_shanks_for_vis = config['PROBE'][ 'num_of_shanks_for_vis'] if num_of_shanks_for_vis != 'None': num_of_shanks_for_vis = int(num_of_shanks_for_vis) else: num_of_shanks_for_vis = None else: print( 'Some file paths in the configuration file do not point to existing files. ' 'Load your data manually') elif spike_info_file == 'empty': print('Configuration file is empty. Load your data manually') def action_load_new_data(): config = configparser.ConfigParser() config.read( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'defaults.ini')) if config['SPIKES']['spike_info_file'] == 'empty': directory = None else: directory = os.path.dirname(config['SPIKES']['spike_info_file']) fname = QtWidgets.QFileDialog.getOpenFileName( caption='Load spike_info.df file', directory=directory) spike_info_file = fname[0] if 'spike_info.df' in spike_info_file: config['SPIKES']['spike_info_file'] = spike_info_file else: print('Point to a file named spike_info.df') return fname = QtWidgets.QFileDialog.getOpenFileName( caption='Load binary data file', directory=directory) binary_data_filename = fname[0] config['BINARY DATA FILE'][ 'binary_data_filename'] = binary_data_filename fname = QtWidgets.QFileDialog.getOpenFileName(caption='Load prb file', directory=directory) prb_file = fname[0] config['PROBE']['prb_file'] = prb_file fname = QtWidgets.QFileDialog.getOpenFileName( caption='Load channel map file', directory=directory) channel_map_file = fname[0] config['PROBE']['channel_map_file'] = channel_map_file types = { 'int16': np.int16, 'uint16': np.uint16, 'int32': np.int32, 'uint32': np.uint32, 'int64': np.int64, 'uint64': np.uint64, 'float16': np.float16, 'float32': np.float32, 'float64': np.float64 } type, ok = QtWidgets.QInputDialog.getItem( central_window, 'Binary Data Type', 'Input the type of the binary data file', sorted(list(types.keys()))) if ok: config['BINARY DATA FILE']['type'] = type order, ok = QtWidgets.QInputDialog.getItem( central_window, 'Binary Data Order', 'Input the order of the binary data file', ['F', 'C']) if ok: config['BINARY DATA FILE']['order'] = order sampling_frequency, ok = QtWidgets.QInputDialog.getInt( central_window, 'Sampling Frequency', 'Input the sampling frequency of the binary data', 30000, 1000, 100000, 1) if ok: config['BINARY DATA FILE']['sampling_frequency'] = str( sampling_frequency) number_of_channels_in_binary_file, ok = QtWidgets.QInputDialog.getInt( central_window, 'Number of Channels in Binary File', 'Input the total number of channels in ' 'the binary data', 128, 4, 10000, 1) if ok: config['BINARY DATA FILE'][ 'number_of_channels_in_binary_file'] = str( number_of_channels_in_binary_file) duration_of_time_plot, ok = QtWidgets.QInputDialog.getInt( central_window, 'Duration of Time Plot', 'Input the duration of the time plot in ms', 4, 1, 20, 1) if ok: config['TIME PLOT']['duration_of_time_plot'] = str( duration_of_time_plot / 1000) num_of_shanks_for_vis, ok = QtWidgets.QInputDialog.getItem( central_window, 'Number of Shanks for Visual', 'Input the number of pieces the probe should be ' 'visualized in (for long single shank probes). ' 'Use None for multi-shank probes with shanks ' 'defined in the prb file', ['None', '1', '2', '3', '4', '5', '6']) if ok: config['PROBE']['num_of_shanks_for_vis'] = num_of_shanks_for_vis with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'defaults.ini'), 'w') as configfile: config.write(configfile) load_config() def action_save_info(): global spike_info fname = QtWidgets.QFileDialog.getExistingDirectory( caption='Select directory to save the new ' 'spike_info.pd file. Any existing' ' spike_info.pd file will be overwritten.') print(fname) spike_info.to_pickle(os.path.join(fname, 'spike_info.df')) config = configparser.ConfigParser() config.read('defaults.ini') config.set('SPIKES', 'spike_info_file', os.path.join(fname, 'spike_info.df')) with open('defaults.ini', 'w') as configfile: config.write(configfile) def action_undo_template_assignment(): global currently_selected_spikes global currently_selected_templates spike_info.loc[currently_selected_spikes, 'template_after_sorting'] = spike_info.loc[ currently_selected_spikes, 'template_after_cleaning'] spike_info.loc[currently_selected_spikes, 'type_after_sorting'] = spike_info.loc[ currently_selected_spikes, 'type_after_cleaning'] update_templates_table() def on_roi_selection(all_rois, freeform=False): global currently_selected_spikes global currently_selected_templates global selectable_spikes global on_spikes global tsne_spots global spike_info currently_selected_spikes = np.empty(0) points = np.array( [tsne_spots[i]['pos'] for i in range(len(tsne_spots))]) for i in range(len(all_rois)): if not freeform: shape = all_rois[i].parentBounds() bounds = shape else: shape = all_rois[i].shape() bounds = shape.boundingRect() selected = np.argwhere( (points[:, 0] > bounds.x()) * (points[:, 0] < bounds.x() + bounds.width()) * (points[:, 1] > bounds.y()) * (points[:, 1] < bounds.y() + bounds.height())).flatten() if freeform: currently_selected_spikes = np.append( currently_selected_spikes, [ i for i in selected if shape.contains( QtCore.QPointF(points[i][0], points[i][1])) ]) else: currently_selected_spikes = np.append( currently_selected_spikes, selected) all_selectable_spikes = np.intersect1d(selectable_spikes, on_spikes) currently_selected_spikes = currently_selected_spikes[np.in1d( currently_selected_spikes, all_selectable_spikes)] currently_selected_templates = hf.find_templates_of_spikes( spike_info, currently_selected_spikes) selected_templates_text_box.setText('Selected templates: ' + ', '.join( str(template) for template in currently_selected_templates)) print('Number of spikes selected: ' + str(len(currently_selected_spikes))) show_selected_points() def on_roi_deletion(): global currently_selected_spikes global currently_selected_templates currently_selected_spikes = np.empty(0) currently_selected_templates = np.empty(0) def show_selected_points(): global spike_info scatter_selected_item.clear() scatter_selected_item.setData(pos=np.array([ spike_info['tsne_x'].iloc[currently_selected_spikes].values, spike_info['tsne_y'].iloc[currently_selected_spikes].values ]).T) scatter_selected_item.setBrush((255, 255, 255)) def generate_scater_plot(): global number_of_spikes global selectable_spikes global on_spikes global tsne_spots global spike_info global all_points_brush global all_points_symbols scatter_item.clear() scatter_selected_item.clear() number_of_spikes = len(spike_info) selectable_spikes = np.arange(number_of_spikes) on_spikes = selectable_spikes number_of_templates = len( np.unique(spike_info['template_after_sorting'])) progdialog = QtWidgets.QProgressDialog() progdialog.setGeometry(500, 500, 400, 40) progdialog.setWindowTitle('Loading t-sne plot') progdialog.setMinimum(0) progdialog.setMaximum(5) progdialog.setWindowModality(QtCore.Qt.WindowModal) progdialog.setLabelText( 'Generating colors _____________________________________') progdialog.show() progdialog.setValue(0) QtWidgets.QApplication.processEvents() color = [ pg.intColor(spike_info['template_after_sorting'].iloc[i], hues=number_of_templates, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255) for i in range(number_of_spikes) ] progdialog.setLabelText( 'Generating brushes ____________________________________') progdialog.setValue(1) brush = [pg.mkBrush(color[i]) for i in range(number_of_spikes)] all_points_brush = brush progdialog.setLabelText( 'Generating positions __________________________________') progdialog.setValue(2) tsne_spots = [{ 'pos': [spike_info['tsne_x'].iloc[i], spike_info['tsne_y'].iloc[i]], 'data': 1, 'brush': brush[i], 'size': 2 } for i in range(number_of_spikes)] progdialog.setLabelText( 'Adding points to plot __________________________________') progdialog.setValue(3) scatter_item.addPoints(tsne_spots) progdialog.setLabelText( 'Generating symbols ... Almost done ______________________') progdialog.setValue(4) symbol = [] for i in range(number_of_spikes): symbol.append( hf.symbol_from_type(spike_info['type_after_sorting'].iloc[i])) scatter_item.setSymbol(symbol) all_points_symbols = symbol progdialog.setValue(5) progdialog.close() def update_average_spikes_plot(): global currently_selected_spikes global data_of_selected_spikes global spike_info global channel_map electrodes = len(channel_map) half_duration = duration_of_time_plot / 2 time_points = int(half_duration * sampling_frequency) time_axis = np.arange(-half_duration, half_duration, 1 / sampling_frequency) data_of_selected_spikes = np.zeros((electrodes, 2 * time_points)) times = spike_info['times'].iloc[currently_selected_spikes] progdialog = QtWidgets.QProgressDialog() progdialog.setMinimum(0) progdialog.setMaximum(len(times)) progdialog.setWindowTitle('Loading spikes') progdialog.setGeometry(500, 500, 400, 40) progdialog.setWindowModality(QtCore.Qt.WindowModal) progdialog.show() prog = 0 for t in times: add_data = raw_data[channel_map, int(t - time_points):int(t + time_points)] data_of_selected_spikes = data_of_selected_spikes + add_data prog += 1 if prog % 100 == 0: progdialog.setValue(prog) progdialog.setLabelText('Loading spike: ' + str(prog) + ' of ' + str(len(times))) QtWidgets.QApplication.processEvents() data_of_selected_spikes = data_of_selected_spikes / len(times) for i in np.arange(electrodes): avg_electrode_curves[i].setData(time_axis, data_of_selected_spikes[i, :]) avg_electrode_curves[i].setPen( pg.mkPen(color=(i, number_of_channels_in_binary_file * 1.3), width=0.5)) progdialog.setValue(len(times)) progdialog.close() def update_templates_table(): global number_of_spikes global spike_info templates_table.setData( hf.get_templates_with_number_of_spikes_from_spike_info(spike_info)) templates_table.setHorizontalHeaderLabels( ['Template number', 'Number of spikes in template']) templates_table.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection) templates_table.setSelectionBehavior( QtGui.QAbstractItemView.SelectRows) header = templates_table.horizontalHeader() header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents) header.setResizeMode(1, QtGui.QHeaderView.ResizeToContents) def update_heatmap_plot(): global data_of_selected_spikes global channel_map global number_of_channels_in_binary_file global num_of_shanks_for_vis connected = channel_map connected_binary = np.in1d( np.arange(number_of_channels_in_binary_file), connected) bad_channels = np.squeeze( np.argwhere(connected_binary == False).astype(np.int)) sh.create_heatmap_on_matplotlib_widget( heatmap_plot, data_of_selected_spikes, prb_file, window_size=60, bad_channels=bad_channels, num_of_shanks=num_of_shanks_for_vis, rotate_90=True, flip_ud=False, flip_lr=False) heatmap_plot.draw() def update_autocorelogram(): global currently_selected_spikes global spike_info spike_times = spike_info['times'].iloc[ currently_selected_spikes].values.astype(np.int64) diffs, norm = hf.crosscorrelate_spike_trains(spike_times, spike_times, lag=1000) hist, edges = np.histogram(diffs, bins=50) autocorelogram_curve.setData(x=edges, y=hist, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150)) # On press button functions --------- def on_press_button_update(): update_average_spikes_plot() update_autocorelogram() update_heatmap_plot() def on_tsne_filter_for_type_combo_box_change(index): global number_of_spikes global spike_info global on_spikes global all_points_brush state = tsne_color_scheme_combo_box.currentIndex() if state == 0: type_state = 'type_after_sorting' template_state = 'template_after_sorting' else: type_state = 'type_after_cleaning' template_state = 'template_after_cleaning' if index > 0: type_to_show = hf.template_types[index] spikes_to_show = np.array(spike_info[spike_info[type_state] == type_to_show].index.values) elif index == 0: spikes_to_show = range(number_of_spikes) on_spikes = spikes_to_show progdialog = QtWidgets.QProgressDialog() progdialog.setGeometry(500, 500, 400, 40) progdialog.setWindowTitle('Filtering t-SNE according to type') progdialog.setMinimum(0) progdialog.setWindowModality(QtCore.Qt.WindowModal) progdialog.setLabelText( 'Generating colors and symbols ... ') progdialog.show() progdialog.setValue(0) QtWidgets.QApplication.processEvents() color_scheme = spike_info[template_state] brush = list(all_points_brush) spikes_to_hide = np.array( range(number_of_spikes) )[~np.in1d(np.array(range(number_of_spikes)), spikes_to_show)] i = 0 progdialog.setMaximum(len(spikes_to_hide)) for s in spikes_to_hide: brush[s] = pg.intColor(color_scheme.iloc[s], hues=50, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=0) if i % 10000 == 0: progdialog.setValue(i) progdialog.setLabelText('Hiding spikes ' + str(i) + ' of ' + str(len(spikes_to_hide)) + ' spikes.') QtWidgets.QApplication.processEvents() i = i + 1 progdialog.setMaximum(2) progdialog.setLabelText( 'Applying colors ... ') progdialog.setValue(1) QtWidgets.QApplication.processEvents() scatter_item.setBrush(brush) progdialog.setValue(2) progdialog.close() def on_tsne_color_scheme_combo_box_change(index): global number_of_spikes global spike_info global all_points_brush progdialog = QtWidgets.QProgressDialog() progdialog.setGeometry(500, 500, 400, 40) progdialog.setWindowTitle('Changing spike color scheme') progdialog.setMinimum(0) progdialog.setMaximum(2) progdialog.setWindowModality(QtCore.Qt.WindowModal) progdialog.setLabelText( 'Generating colors and symbols ... ') progdialog.show() progdialog.setValue(0) QtWidgets.QApplication.processEvents() spikes_to_change = range(number_of_spikes) print(index) if index == 0: number_of_templates = len( np.unique(spike_info['template_after_sorting'])) color_scheme = spike_info['template_after_sorting'] brush = [ pg.intColor(color_scheme.iloc[i], hues=number_of_templates, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255) for i in spikes_to_change ] symbol = [] for i in spikes_to_change: symbol.append( hf.symbol_from_type( spike_info['type_after_sorting'].iloc[i])) elif index == 1: number_of_templates = len( np.unique(spike_info['template_after_cleaning'])) color_scheme = spike_info['template_after_cleaning'] brush = [ pg.intColor(color_scheme.iloc[i], hues=number_of_templates, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255) for i in spikes_to_change ] symbol = [] for i in spikes_to_change: symbol.append( hf.symbol_from_type( spike_info['type_after_cleaning'].iloc[i])) progdialog.setValue(1) progdialog.setLabelText( 'Applying colors and symbols ... ') QtWidgets.QApplication.processEvents() all_points_brush = brush scatter_item.setBrush(brush) scatter_item.setSymbol(symbol) progdialog.setValue(2) progdialog.close() def on_press_button_freeze_spikes(): global selectable_spikes global currently_selected_spikes global number_of_spikes selectable_spikes = np.array(range(number_of_spikes))[~np.in1d( np.array(range(number_of_spikes)), currently_selected_spikes)] def on_press_button_unfreeze_all(): global selectable_spikes global number_of_spikes selectable_spikes = np.array(range(number_of_spikes)) def on_templates_table_selection(): global currently_selected_templates global currently_selected_spikes global spike_info currently_selected_templates = [] rows_selected = templates_table.selectedItems() for i in np.arange(0, len(rows_selected), 2): currently_selected_templates.append(int(rows_selected[i].text())) currently_selected_templates = np.array(currently_selected_templates) currently_selected_spikes = np.empty(0) for selected_template in currently_selected_templates: currently_selected_spikes = np.append( currently_selected_spikes, spike_info.loc[spike_info['template_after_sorting'] == selected_template].index) show_selected_points() def on_press_button_show_cross_correlograms(): global currently_selected_templates global spike_info num_of_templates = len(currently_selected_templates) if num_of_templates > 1: cross_cor_window.show() num_of_windows = (num_of_templates**2 - num_of_templates) / 2 + num_of_templates cross_corelogram_plots = [] column = 0 row = 0 width = 1 height = 1 progdialog = QtWidgets.QProgressDialog() progdialog.setMinimum(0) progdialog.setMaximum(num_of_windows) progdialog.setWindowTitle('Making cross correlograms') progdialog.setGeometry(500, 500, 400, 40) progdialog.setWindowModality(QtCore.Qt.WindowModal) progdialog.show() prog = 0 for window_index in np.arange(num_of_windows): cross_corelogram_plots.append(pg.PlotWidget()) cross_cor_grid_layout.addWidget(cross_corelogram_plots[-1], column, row, height, width) spike_times_a = spike_info['times'].loc[ spike_info['template_after_sorting'] == currently_selected_templates[column]].values.astype( np.int64) spike_times_b = spike_info['times'].loc[ spike_info['template_after_sorting'] == currently_selected_templates[row]].values.astype(np.int64) diffs, norm = hf.crosscorrelate_spike_trains(spike_times_a, spike_times_b, lag=3000) cross_corelogram_curve = pg.PlotCurveItem() cross_corelogram_plots[-1].addItem(cross_corelogram_curve) hist, edges = np.histogram(diffs, bins=100) cross_corelogram_curve.setData(x=edges, y=hist, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150)) row += width if row > column: column += height row = 0 prog += 1 progdialog.setValue(prog) progdialog.setLabelText('Making cross correlogram: ' + str(prog) + ' of ' + str(num_of_windows)) QtWidgets.QApplication.processEvents() progdialog.setValue(num_of_windows) progdialog.close() def on_press_button_remove_from_template(): global currently_selected_spikes global spike_info if len(currently_selected_spikes) > 0: spike_info.loc[currently_selected_spikes, 'template_after_sorting'] = 0 update_templates_table() def on_press_button_make_template(): global currently_selected_spikes global spike_info global all_points_brush if len(currently_selected_spikes) > 0: all_templates = spike_info['template_after_sorting'].values max_template = np.max(all_templates) index, ok = QtWidgets.QInputDialog.getInt( central_window, 'New Template Index', 'Input the index of the new template', max_template + 1, 1, max_template + 10000, 1) if ok: spike_info.loc[currently_selected_spikes, 'template_after_sorting'] = index list_of_types = [ 'Noise', 'Single Unit', 'Single Unit Contaminated', 'Single Unit Putative', 'MUA', 'Unspecified 1', 'Unspecified 2', 'Unspecified 3' ] item, ok = QtWidgets.QInputDialog.getItem( central_window, 'New Template Type', 'Input the type of the new template', list_of_types) if ok: spike_info.loc[currently_selected_spikes, 'type_after_sorting'] = hf.template_types[ list_of_types.index(item)] update_templates_table() # ---------------------------------- # Main Window ---------------------- app = QtGui.QApplication([]) main_window = QtGui.QMainWindow() main_toolbar = main_window.addToolBar('Tools') main_window.setWindowTitle('Spikesort on T-sne') main_window.resize(1300, 900) central_window = pg.GraphicsLayoutWidget() main_window.setCentralWidget(central_window) grid_layout = QtGui.QGridLayout() central_window.setLayout(grid_layout) # ---------------------------------- # T-sne Scatter Plot --------------- custom_viewbox = cv.CustomViewBox() scatter_plot = pg.PlotWidget(title='T-sne plot', viewBox=custom_viewbox) grid_layout.addWidget(scatter_plot, 0, 0, 2, 4) scatter_plot.plotItem.ctrlMenu = None scatter_plot.scene().contextMenu = None scatter_item = pg.ScatterPlotItem(size=7, pen=None, pxMode=True) scatter_plot.addItem(scatter_item) scatter_selected_item = pg.ScatterPlotItem(size=8, pen=None, pxMode=True) scatter_plot.addItem(scatter_selected_item) # --------------------------------- # Average spike time course plot -- spikes_time_plot = pg.PlotWidget( title='Average time plot of selected spikes') grid_layout.addWidget(spikes_time_plot, 2, 0, 2, 2) # --------------------------------- # Autocorelogram plot ------------- autocorelogram_plot = pg.PlotWidget(title='Autocorrelogram') grid_layout.addWidget(autocorelogram_plot, 2, 2, 2, 2) autocorelogram_curve = pg.PlotCurveItem() autocorelogram_plot.addItem(autocorelogram_curve) # --------------------------------- # Heatmap plot -------------------- heatmap_plot = matplotlib_widget.MatplotlibWidget(toolbar_on=False) grid_layout.addWidget(heatmap_plot, 0, 4, 6, 2) # --------------------------------- # Templates Table widget ----------- templates_table = pg.TableWidget(editable=False, sortable=True) templates_table.cellClicked.connect(on_templates_table_selection) grid_layout.addWidget(templates_table, 0, 6, 3, 1) # ---------------------------------- # Cross correlogram window --------- cross_cor_window = QtGui.QMainWindow() cross_cor_window.setWindowTitle('Cross correlograms') cross_cor_window.resize(1300, 900) central_cross_cor_window = pg.GraphicsLayoutWidget() cross_cor_window.setCentralWidget(central_cross_cor_window) cross_cor_grid_layout = QtGui.QGridLayout() central_cross_cor_window.setLayout(cross_cor_grid_layout) # ---------------------------------- # Tool bar ------------------------- current_path = os.path.dirname(os.path.realpath(__file__)) scroll_icon_file = os.path.join(current_path, 'Icons', 'scroll_icon.png') zoom_icon_file = os.path.join(current_path, 'Icons', 'zoom_icon.png') select_icon_file = os.path.join(current_path, 'Icons', 'select_icon.png') select_freeform_icon_file = os.path.join(current_path, 'Icons', 'select_freeform_icon.png') undo_icon_file = os.path.join(current_path, 'Icons', 'undo_icon.jpg') menu_bar = main_window.menuBar() file_menu = menu_bar.addMenu('File') load_data = QtWidgets.QAction('Load Data', main_window) load_data.triggered.connect(action_load_new_data) file_menu.addAction(load_data) save_info = QtWidgets.QAction('Save spike info', main_window) save_info.triggered.connect(action_save_info) file_menu.addAction(save_info) scroll = QtWidgets.QAction(QtGui.QIcon(scroll_icon_file), "scroll", main_window) scroll.triggered.connect(custom_viewbox.set_to_pan_mode) main_toolbar.addAction(scroll) zoom = QtWidgets.QAction(QtGui.QIcon(zoom_icon_file), "zoom", main_window) zoom.triggered.connect(custom_viewbox.set_to_rect_mode) main_toolbar.addAction(zoom) select = QtWidgets.QAction(QtGui.QIcon(select_icon_file), "select", main_window) select.triggered.connect(custom_viewbox.draw_square_roi) main_toolbar.addAction(select) select_freeform = QtWidgets.QAction(QtGui.QIcon(select_freeform_icon_file), 'select freeform', main_window) select_freeform.triggered.connect(custom_viewbox.draw_freeform_roi) custom_viewbox.connect_on_roi_select = on_roi_selection custom_viewbox.connect_on_roi_delete = on_roi_deletion main_toolbar.addAction(select_freeform) undo_assignment = QtWidgets.QAction( QtGui.QIcon(undo_icon_file), 'assign selected spikes back to their original templates', main_window) undo_assignment.triggered.connect(action_undo_template_assignment) main_toolbar.addAction(undo_assignment) # ---------------------------------- # Buttons -------------------------- button_update = QtGui.QPushButton('Update') button_update.setStyleSheet("font-size:20px; font-family: Helvetica") button_update.clicked.connect(on_press_button_update) grid_layout.addWidget(button_update, 7, 0, 1, 1) button_show_cross_correlograms = QtGui.QPushButton( 'Show Crosscorrelograms') button_show_cross_correlograms.setStyleSheet( "font-size:20px; font-family: Helvetica") button_show_cross_correlograms.clicked.connect( on_press_button_show_cross_correlograms) grid_layout.addWidget(button_show_cross_correlograms, 7, 1, 1, 1) tsne_color_scheme_combo_box = QtGui.QComboBox() tsne_color_scheme_combo_box.setStyleSheet( "font-size:20px; font-family: Helvetica") tsne_color_scheme_combo_box.addItem('After sorting') tsne_color_scheme_combo_box.addItem('Before sorting') tsne_color_scheme_combo_box.activated.connect( on_tsne_color_scheme_combo_box_change) grid_layout.addWidget(tsne_color_scheme_combo_box, 7, 2, 1, 1) tsne_filter_for_type_combo_box = QtGui.QComboBox() tsne_filter_for_type_combo_box.setStyleSheet( "font-size:20px; font-family: Helvetica") tsne_filter_for_type_combo_box.addItem('All') tsne_filter_for_type_combo_box.addItem('Single Unit') tsne_filter_for_type_combo_box.addItem('Single Unit Contaminated') tsne_filter_for_type_combo_box.addItem('Single Unit Putative') tsne_filter_for_type_combo_box.addItem('Multi Unit') tsne_filter_for_type_combo_box.addItem('Unspecified 1') tsne_filter_for_type_combo_box.addItem('Unspecified 2') tsne_filter_for_type_combo_box.addItem('Unspecified 3') tsne_filter_for_type_combo_box.activated.connect( on_tsne_filter_for_type_combo_box_change) grid_layout.addWidget(tsne_filter_for_type_combo_box, 6, 2, 1, 1) button_freeze_spikes = QtGui.QPushButton('Freeze selected spikes') button_freeze_spikes.setStyleSheet( "font-size:20px; font-family: Helvetica") button_freeze_spikes.clicked.connect(on_press_button_freeze_spikes) grid_layout.addWidget(button_freeze_spikes, 5, 3, 1, 1) button_unfreeze_all = QtGui.QPushButton('Unfreeze all spikes') button_unfreeze_all.setStyleSheet("font-size:20px; font-family: Helvetica") button_unfreeze_all.clicked.connect(on_press_button_unfreeze_all) grid_layout.addWidget(button_unfreeze_all, 6, 3, 1, 1) button_remove_from_template = QtGui.QPushButton( 'Remove selected spikes from template') button_remove_from_template.setStyleSheet( "font-size:20px; font-family: Helvetica") button_remove_from_template.clicked.connect( on_press_button_remove_from_template) grid_layout.addWidget(button_remove_from_template, 4, 6, 1, 1) button_make_template = QtGui.QPushButton('Make new template from spikes') button_make_template.setStyleSheet( "font-size:20px; font-family: Helvetica") button_make_template.clicked.connect(on_press_button_make_template) grid_layout.addWidget(button_make_template, 5, 6, 1, 1) # ---------------------------------- # Text Box ------------------------- selected_templates_text_box = QtWidgets.QLineEdit() selected_templates_text_box.setReadOnly(True) selected_templates_text_box.setWindowTitle('Selected Templates') selected_templates_text_box.setStyleSheet( "font-size:20px; font-family: Helvetica") grid_layout.addWidget(selected_templates_text_box, 7, 3, 1, 2) # ---------------------------------- if load_previous_dataset: load_config() main_window.show() if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): sys.exit(app.exec_())
def __init__(self): super(Stereography_window, self).__init__() self.setWindowTitle('Tracker 5') self.setMinimumWidth(1600) self.setMinimumHeight(1000) pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.cur = QtGui.QCursor # Create the QVBoxLayout that lays out the whole form w = QtGui.QWidget() self.layout = QtGui.QVBoxLayout(w) self.setCentralWidget(w) ### top row, imageview widgets self.images_hbox = QtGui.QHBoxLayout() self.iml = pg.ImageView() self.imr = pg.ImageView() # self.iml.setMouseTracking(True) # self.imr.setMouseTracking(True) # self.imr_load = QtGui.QPushButton('Load right directory') self.iml_load = QtGui.QPushButton('Load left Directory') self.lfns, self.rfns = [], [] self.randim = n.random.randint(256, size=(640, 480)) self.iml.setImage(self.randim) self.iml.setMinimumHeight(400) self.iml.getHistogramWidget().setMaximumWidth(100) self.iml.scene.sigMouseMoved.connect(self.lmouseMoved) self.imr.setImage(self.randim) self.imr.setMinimumHeight(400) self.imr.getHistogramWidget().setMaximumWidth(100) self.imr.scene.sigMouseMoved.connect(self.rmouseMoved) self.images_hbox.addWidget(self.iml) self.ltools = QtGui.QToolBar(self.iml) self.ltools.setStyleSheet('QToolBar{spacing:0px;}') self.loadl = self.ltools.addAction(QtGui.QIcon(), 'load', self.load) self.ltools.show() self.images_hbox.addWidget(self.imr) self.rtools = QtGui.QToolBar(self.imr) self.rtools.setStyleSheet('QToolBar{spacing:0px;}') # self.loadr = self.rtools.addAction(QtGui.QIcon(), 'load', self.load_right) self.rtools.show() ### middle row # frame slider self.frame_hbox = QtGui.QHBoxLayout() self.frame_slider = QtGui.QSlider(QtCore.Qt.Horizontal) self.frame_slider.setMinimum(1) self.frame_slider.setMaximum(1) self.frame_slider.valueChanged.connect(self.change_frame) # self.frame_value = pg.ValueLabel() self.frame_value = QtGui.QLabel('1/1') self.frame_hbox.addWidget(self.frame_slider) self.frame_hbox.addWidget(self.frame_value) ### bottom row self.bottom_hbox = QtGui.QHBoxLayout() # camera layout self.camera_view = pg.PlotWidget() self.camera_view.setAspectLocked(True) self.camera_view.setMaximumWidth(400) self.camera_view.setMaximumHeight(400) self.tab = pg.TableWidget(editable=True, sortable=False) self.tab.setData([[-14.13, 0, 14.13, 0.], [-15, 0, 15, 0.], [53.5, 41.41, 53.5, 41.41]]) self.tab.setVerticalHeaderLabels(['pos', 'ang', 'fov']) self.tab.setHorizontalHeaderLabels( ['cam1 x', 'cam1 y', 'cam2 x', 'cam2 y']) self.tab.cellChanged.connect(self.update_camera_parameters) self.update_camera_parameters(dist=100) vbox = QtGui.QVBoxLayout() vbox.addWidget(self.camera_view) vbox.addWidget(self.tab) self.bottom_hbox.addItem(vbox) # 3d plot self.flight_view = gl.GLViewWidget() self.flight_view.setBackgroundColor((0, 0, .5)) self.flight_view.setWindowTitle('pyqtgraph example: GLLinePlotItem') self.flight_view.opts['distance'] = 40 gx = gl.GLGridItem(color=pg.mkColor([255, 0, 0, 255])) gx.rotate(90, 0, 1, 0) gx.translate(-10, 0, 0) self.flight_view.addItem(gx) gy = gl.GLGridItem() gy.rotate(90, 1, 0, 0) gy.translate(0, -10, 0) self.flight_view.addItem(gy) gz = gl.GLGridItem() gz.translate(0, 0, -10) self.flight_view.addItem(gz) # self.flight_view.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) # self.flight_view.show() self.flight_lines = [] self.flight_pts = [] self.bottom_hbox.addWidget(self.flight_view) ### set the layout self.layout.addLayout(self.images_hbox) # self.layout.addWidget(self.frame_slider) self.layout.addLayout(self.frame_hbox) self.layout.addLayout(self.bottom_hbox) ### now the markers self.num_cams = 2 #left and right self.num_markers = 9 #1-9 self.num_frames = 1 #until we load a dir self.marker_keys = [str(i + 1) for i in range(self.num_markers) ] # keyboard strings for each marker self.shift_marker_keys = ['!', '@', '#', '$', '%', '^', '&', '*', '('] # keyboard strings for each marker alpha = 200 width = 4 self.colors = [ (255, 100, 100, alpha), #red (100, 255, 100, alpha), #green (60, 60, 255, alpha), #blue (245, 245, 30, alpha), #yellow (30, 245, 245, alpha), #cyan (255, 0, 255, alpha), #magenta (255, 195, 0, alpha), #orange (150, 150, 255, alpha), #indigo (215, 120, 255, alpha) ] #purple # first the markers for the image self.data_markers = [[], []] for cam_ind in range(self.num_cams): for marker_ind in range(self.num_markers): # left data_marker = pg.PolyLineROI([[0., 0.] ]) #roi with only a single point data_marker.getHandles()[0].pen.setColor( QtGui.QColor(*self.colors[marker_ind]) ) #make each handle a different color data_marker.getHandles()[0].pen.setWidth(width) #thicken lines data_marker.sigRegionChanged.connect(self.marker_moved) data_marker.hide() #initially invisible self.data_markers[cam_ind].append(data_marker) if cam_ind == 0: self.iml.addItem(data_marker) if cam_ind == 1: self.imr.addItem(data_marker) self.data = n.zeros( (self.num_cams + 1, self.num_markers, 3, self.num_frames)) self.data[:, :, :, :] = n.NaN # data positions interpolated self.null_interp = InterpolatedUnivariateSpline([0, 0], [n.NaN, n.NaN], k=1) # self.data_interp = [[[self.null_interp]*2]*self.num_markers]*self.num_sides #[2 sides][num markers][x y] ##no t needed self.data_interp = [[[self.null_interp for xy in range(2)] for m in range(self.num_markers)] for s in range(self.num_cams)] # now the lines for marker_ind in range(self.num_markers): line = gl.GLLinePlotItem(pos=n.array([[0, 0, 0.], [1, 1, 1.]]), color=pg.glColor(self.colors[marker_ind]), width=2., antialias=True) line.hide() self.flight_lines.append(line) self.flight_view.addItem(line) pt = gl.GLScatterPlotItem(pos=n.array([[0, 0, 0.]]), color=pg.glColor( self.colors[marker_ind]), size=10.) pt.hide() self.flight_pts.append(pt) self.flight_view.addItem(pt)
def update_plots(self): """Checks the signal slots and changes the plotting attributes to be evaluated by PlotWindow_lib. This function coordinates the changing input from the signal slots and updates the attributes that are parsed to the plotting lib functions. update_plots() is either periodically called e.g. by the timer or once on startup. Args: self: Object of the PlotWindow class. Returns: No return variable. The function operates on the given object. """ #print "PWL update_plots:", self.obj_parent.h5file try: self.ds = self.obj_parent.h5file[self.dataset_url] except ValueError as e: print(str(self.dataset_url)+": "+str(e)) return self.ds_type = self.ds.attrs.get('ds_type', -1) # The axis names are parsed to plot_view's Ui_Form class to label the UI selectors x_ds_name = _get_name(_get_ds(self.ds, self.ds.attrs.get('x_ds_url', ''))) y_ds_name = _get_name(_get_ds(self.ds, self.ds.attrs.get('y_ds_url', ''))) z_ds_name = _get_name(_get_ds(self.ds, self.ds.attrs.get('z_ds_url', ''))) try: if self.ds.attrs.get('xy_0', ''): x_ds_name_view = _get_name(_get_ds(self.ds,_get_ds(self.ds, self.ds.attrs.get('xy_0', '').decode().split(':')[1]).attrs.get('x_ds_url', ''))) y_ds_name_view = _get_name(_get_ds(self.ds,_get_ds(self.ds, self.ds.attrs.get('xy_0', '').decode().split(':')[1]).attrs.get('y_ds_url', ''))) else: raise AttributeError except AttributeError: x_ds_name_view = '_none_' y_ds_name_view = '_none_' selector_label = [x_ds_name, y_ds_name, z_ds_name, x_ds_name_view, y_ds_name_view] ## At first window creation the attributes are set to state zero. if self._windowJustCreated: # A few state variables: self._onPlotTypeChanged = True self._windowJustCreated = False self.graphicsView = None self.TraceValueChanged = False self.TraceZValueChanged = False self.TraceXValueChanged = False self.TraceYValueChanged = False self.VTraceZValueChanged = False self.VTraceXValueChanged = False self.VTraceYValueChanged = False # the following calls rely on ds_type and setup the layout of the plot window. self.setupUi(self,self.ds_type, selector_label) window_title = str(self.dataset_url.split('/')[-1]) +" "+ str(self.DATA.filename) self.setWindowTitle(window_title) self._setDefaultView() self._setup_signal_slots() ## We check here for the view type given by either default setting or ## user input. Creates the canvas and calls the associated plot ## function from the lib. For code constistence the variable names are ## the same in all view types. try: if self.view_type == view_types['1D-V']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.PlotWidget(name=self.dataset_url) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu() self.graphicsView.sceneObj.contextMenu[:0] = [self.qvkMenu] self.gridLayout.addWidget(self.graphicsView,0,0) _display_1D_view(self,self.graphicsView) elif self.view_type == view_types['1D']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.PlotWidget(name=self.dataset_url) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu() self.graphicsView.sceneObj.contextMenu[:0] = [self.qvkMenu] self.gridLayout.addWidget(self.graphicsView,0,0) _display_1D_data(self,self.graphicsView) elif self.view_type == view_types['2D']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = ImageViewMplColorMaps(self.obj_parent, view = pg.PlotItem()) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu() self.graphicsView.scene.contextMenu[:0] = [self.qvkMenu] self.graphicsView.view.setAspectLocked(False) self.gridLayout.addWidget(self.graphicsView,0,0) self.linestyle_selector.setDisabled(True) _display_2D_data(self,self.graphicsView) elif self.view_type == view_types['table']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.TableWidget(sortable=False) self.graphicsView.setWindowTitle(self.dataset_url+'_table') self.graphicsView.setObjectName(self.dataset_url) self.graphicsView.setFormat("%.6g") self.gridLayout.addWidget(self.graphicsView,0,0) _display_table(self,self.graphicsView) elif self.view_type == view_types['txt']: if not self.graphicsView or self._onPlotTypeChangeBox: self._onPlotTypeChangeBox = False self.graphicsView = QPlainTextEdit() self.graphicsView.setObjectName(self.dataset_url) self.gridLayout.addWidget(self.graphicsView,0,0) self.graphicsView.clear() _display_text(self,self.graphicsView) else: print("This should not be here: View Type:"+str(self.view_type)) except ValueError as e: print("PlotWindow: Value Error; Dataset not yet available", self.dataset_url) print(e)
cal["number_of_quads"])) print("pulse_repetition_interval_hr_us={}".format( cal["pulse_repetition_interval_hr_us"])) n = 24072 w = 332 a = np.fromfile("/home/martin/sat-data/chunk0", dtype=np.complex64, count=((w) * (n))).reshape(( w, n, )) win = np.hamming(n) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui app = QtGui.QApplication([]) widget = pg.TableWidget(sortable=False) widget.show() widget.resize(500, 500) widget.setWindowTitle("satellite data header") font = QtGui.QFont() font.setPointSize(5) widget.setFont(font) type_header = [] short_names = [] for c in list(df.columns): example = df[c][0] example_type = type(example) short_name = "".join(map(lambda x: x[0], c.split("_"))) new_short_name = short_name count = 0 while ((new_short_name in short_names)):
def __init__(self, mask, xsize=1000, ysize=1000, version='carpy'): self.mask = mask self.xsize = xsize self.ysize = ysize self.dW = 15.0 self.degree = 4 self.lines = Table.read('HeNeAr_check.dat', format='ascii') lines_fit = np.copy(self.lines) lines_fit = Table(lines_fit) lines_fit['a'] = 0.0 lines_fit['b'] = 0.0 lines_fit['wave_fit'] = 0.0 lines_fit['amplitude'] = 0.0 lines_fit['sigma'] = 0.0 lines_fit['dW'] = 0.0 self.lines_fit = lines_fit self.path = '{}_spec1D'.format(mask) self.objects = Table.read('{}/{}_objects.fits'.format( self.path, self.mask)) print(self.objects) # Set the initial row number to zero self.row = 1 self.nRows = len(self.objects) self.smoothing = 1 # Get the GUI ready self.app = QtGui.QApplication([]) # Always start by initializing Qt self.widget = QtGui.QWidget() # Define a top-level widget # Set the widget size self.widget.resize(self.xsize, self.ysize) # Set the background plotting widget self.plot_solution = pg.PlotWidget() self.plot_solution.getAxis('bottom').setPen(pg.mkPen('w', width=2)) self.plot_solution.getAxis('top').setPen(pg.mkPen('w', width=2)) self.plot_solution.getAxis('left').setPen(pg.mkPen('w', width=2)) self.plot_solution.getAxis('right').setPen(pg.mkPen('w', width=2)) self.plot_solution.getAxis('bottom').setStyle(tickLength=-15) self.plot_solution.getAxis('top').setStyle(tickLength=-15) self.plot_solution.getAxis('left').setStyle(tickLength=-15) self.plot_solution.getAxis('right').setStyle(tickLength=-15) self.plot_solution.showAxis('right') self.plot_solution.showAxis('top') self.plot_solution.setLabel('bottom', 'wavelength') self.plot_solution.setLabel('left', 'dW [Å]') # Set the 1D spectrum self.plot_spec1D = pg.PlotWidget() self.plot_spec1D.getAxis('bottom').setPen(pg.mkPen('w', width=2)) self.plot_spec1D.getAxis('top').setPen(pg.mkPen('w', width=2)) self.plot_spec1D.getAxis('left').setPen(pg.mkPen('w', width=2)) self.plot_spec1D.getAxis('right').setPen(pg.mkPen('w', width=2)) self.plot_spec1D.getAxis('bottom').setStyle(tickLength=-15) self.plot_spec1D.getAxis('top').setStyle(tickLength=-15) self.plot_spec1D.getAxis('left').setStyle(tickLength=-15) self.plot_spec1D.getAxis('right').setStyle(tickLength=-15) self.plot_spec1D.showAxis('right') self.plot_spec1D.showAxis('top') self.plot_spec1D.setLabel('bottom', 'Wavelength [Å]') self.plot_spec1D.setLabel('bottom', 'arc flux') self.plot_spec1D.setXLink(self.plot_solution) self.mouse_x_spec1D = 0.0 self.mouse_y_spec1D = 0.0 self.mouse_x_solution = 0.0 self.mouse_y_solution = 0.0 # Setup the layout self.layout = QtGui.QGridLayout() self.widget.setLayout(self.layout) # Add listeners self.plot_spec1D.scene().sigMouseMoved.connect(self.mouseMoved_spec1D) self.plot_spec1D.keyPressEvent = self.keypress_spec1D self.plot_solution.scene().sigMouseMoved.connect( self.mouseMoved_solution) self.plot_solution.keyPressEvent = self.keypress_solution self.objectsTable = pg.TableWidget(editable=False, sortable=False) self.objectsTable.setFormat('%0.5f', 2) self.setTable() self.objectsTable.setSelectionBehavior( QtGui.QAbstractItemView.SelectRows) self.objectsTable.setSelectionMode( QtGui.QAbstractItemView.SingleSelection) self.objectsTable.doubleClicked.connect(self.goToObject) self.linesTable_fit = pg.TableWidget(editable=False, sortable=False) self.linesTable_fit.setFormat('%0.2f', 0) self.linesTable_fit.setFormat('%0.2f', 1) self.linesTable_fit.setFormat('%0.2f', 2) self.linesTable_fit.setFormat('%0.2f', 3) self.linesTable_fit.setFormat('%0.2f', 4) self.linesTable_fit.setFormat('%0.2f', 5) self.linesTable_fit.setFormat('%0.2f', 6) self.setTable_lines() # Add plot_bg to the layout self.layout.addWidget(self.plot_solution, 0, 0) self.layout.addWidget(self.linesTable_fit, 0, 1) self.layout.addWidget(self.objectsTable, 1, 1) self.layout.addWidget(self.plot_spec1D, 1, 0) #self.layout.addWidget(self.comment_text, 4, 0) self.layout.setColumnStretch(0, 0) self.layout.setColumnStretch(0, 1) self.layout.setColumnStretch(1, 0) #self.layout.setColumnStretch(1, 1) self.layout.setRowStretch(0, 0) self.layout.setRowStretch(0, 1) self.layout.setRowStretch(1, 0) self.layout.setRowStretch(1, 1) self.setSpec() self.fitAll() self.fitResiduals() dW = self.lines_fit['dW'] - getpolyfit(self.lines_fit['wave'], self.poly) sigma_robust = stats.median_absolute_deviation(dW) print('robust_sigma = {}'.format(sigma_robust)) index = np.where(np.abs(dW) > 5.0 * sigma_robust) self.lines_fit['a'][index] = 0.0 self.lines_fit['b'][index] = 0.0 self.lines_fit['wave_fit'][index] = 0.0 self.lines_fit['amplitude'][index] = 0.0 self.lines_fit['sigma'][index] = 0.0 self.fitResiduals() self.draw() self.widget.show() self.app.exec_()
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1261, 838) MainWindow.setWindowTitle('Analytic Tool') self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.scrollArea = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea.setFrameShape(QtWidgets.QFrame.NoFrame) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 541, 765)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.gridLayout_2 = QtWidgets.QGridLayout( self.scrollAreaWidgetContents) self.gridLayout_2.setObjectName("gridLayout_2") self.gridLayout_2.setColumnMinimumWidth(4, 1) self.rowLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.rowLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.rowLabel.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.rowLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.rowLabel.setScaledContents(False) self.rowLabel.setObjectName("rowLabel") self.rowLabel.setText("Rows") self.gridLayout_2.addWidget(self.rowLabel, 4, 1) self.rowListWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.rowListWidget.setObjectName("rowListWidget") self.rowListWidget.setDefaultDropAction(QtCore.Qt.MoveAction) self.rowListWidget.setDragDropMode( QtWidgets.QAbstractItemView.DragDrop) self.rowListWidget.currentItemChanged.connect(self.displayRowsFilter) self.gridLayout_2.addWidget(self.rowListWidget, 5, 1) self.columnLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.columnLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.columnLabel.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.columnLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.columnLabel.setScaledContents(False) self.columnLabel.setObjectName("columnLabel") self.columnLabel.setText("Columns") self.gridLayout_2.addWidget(self.columnLabel, 2, 1, 1, 1) self.columnListWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.columnListWidget.setObjectName("columnListWidget") self.columnListWidget.setDefaultDropAction(QtCore.Qt.MoveAction) self.columnListWidget.setDragDropMode( QtWidgets.QAbstractItemView.DragDrop) self.columnListWidget.currentItemChanged.connect( self.displayColumnFilter) self.gridLayout_2.addWidget(self.columnListWidget, 3, 1) self.filterLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.filterLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.filterLabel.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.filterLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.filterLabel.setScaledContents(False) self.filterLabel.setObjectName("filterLabel") self.filterLabel.setText("Filter") self.gridLayout_2.addWidget(self.filterLabel, 0, 1) self.filterListWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.filterListWidget.setObjectName("filterListWidget") self.gridLayout_2.addWidget(self.filterListWidget, 1, 1) self.sheetLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.sheetLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.sheetLabel.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.sheetLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.sheetLabel.setScaledContents(False) self.sheetLabel.setObjectName("sheetLabel") self.sheetLabel.setText("Sheets") self.gridLayout_2.addWidget(self.sheetLabel, 0, 0) # Set sheet list widget self.sheetListWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.sheetListWidget.setObjectName("sheetList") self.sheetListWidget.itemActivated.connect( self.displayDimensionsMeasurements) self.gridLayout_2.addWidget(self.sheetListWidget, 1, 0) self.measurementLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.measurementLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.measurementLabel.setStyleSheet( "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.measurementLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.measurementLabel.setScaledContents(False) self.measurementLabel.setObjectName("measurementLabel") self.measurementLabel.setText("Measurements") self.gridLayout_2.addWidget(self.measurementLabel, 4, 0) self.measurementWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.measurementWidget.setObjectName("measurementsList") self.measurementWidget.setDefaultDropAction(QtCore.Qt.MoveAction) self.measurementWidget.setDragDropMode( QtWidgets.QAbstractItemView.DragDrop) self.gridLayout_2.addWidget(self.measurementWidget, 5, 0) self.dimensionLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.dimensionLabel.setLayoutDirection(QtCore.Qt.LeftToRight) self.dimensionLabel.setStyleSheet( "\n" "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(181, 181, 181, 255), stop:1 rgba(255, 255, 255, 255));" ) self.dimensionLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.dimensionLabel.setScaledContents(False) self.dimensionLabel.setObjectName("dimensionLabel") self.dimensionLabel.setText("Dimensions") self.gridLayout_2.addWidget(self.dimensionLabel, 2, 0) self.dimensionWidget = QtWidgets.QListWidget( self.scrollAreaWidgetContents) self.dimensionWidget.setObjectName("dimensionList") self.dimensionWidget.setDefaultDropAction(QtCore.Qt.MoveAction) self.dimensionWidget.setDragDropMode( QtWidgets.QAbstractItemView.DragDrop) self.gridLayout_2.addWidget(self.dimensionWidget, 3, 0) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gridLayout.addWidget(self.scrollArea, 0, 0) self.scrollArea_2 = QtWidgets.QScrollArea(self.centralwidget) self.scrollArea_2.setFrameShape(QtWidgets.QFrame.NoFrame) self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName("scrollArea_2") self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() self.scrollAreaWidgetContents_2.setGeometry( QtCore.QRect(0, 0, 342, 765)) self.scrollAreaWidgetContents_2.setObjectName( "scrollAreaWidgetContents_2") self.gridLayout_3 = QtWidgets.QGridLayout( self.scrollAreaWidgetContents_2) self.gridLayout_3.setObjectName("gridLayout_3") self.continuousChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.continuousChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.continuousChart.setToolButtonStyle( 3) # Set text position under icon self.continuousChart.setText("Continuous") continuousChartIcon = QtGui.QIcon() continuousChartIcon.addPixmap( QtGui.QPixmap(":/resource/continuousChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.continuousChart.setIcon(continuousChartIcon) self.continuousChart.setIconSize(QtCore.QSize(70, 70)) self.continuousChart.setObjectName("continuousChart") self.gridLayout_3.addWidget(self.continuousChart, 4, 0) self.blockChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.blockChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.blockChart.setToolButtonStyle(3) # Set text position under icon self.blockChart.setText("Block") blockChartIcon = QtGui.QIcon() blockChartIcon.addPixmap(QtGui.QPixmap(":/resource/blockChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.blockChart.setIcon(blockChartIcon) self.blockChart.setIconSize(QtCore.QSize(70, 70)) self.blockChart.setObjectName("blockChart") self.gridLayout_3.addWidget(self.blockChart, 2, 0) self.horizontalBarChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.horizontalBarChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.horizontalBarChart.setToolButtonStyle( 3) # Set text position under icon self.horizontalBarChart.setText("Horizontal Bar") horizontalBarIcon = QtGui.QIcon() horizontalBarIcon.addPixmap( QtGui.QPixmap(":/resource/horizontalBarChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.horizontalBarChart.setIcon(horizontalBarIcon) self.horizontalBarChart.setIconSize(QtCore.QSize(70, 70)) self.horizontalBarChart.setObjectName("horizontalBarChart") self.gridLayout_3.addWidget(self.horizontalBarChart, 3, 0) self.pieChart = QtWidgets.QToolButton(self.scrollAreaWidgetContents_2) self.pieChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.pieChart.setToolButtonStyle(3) # Set text position under icon self.pieChart.setText("Pie Chart") pieChartIcon = QtGui.QIcon() pieChartIcon.addPixmap(QtGui.QPixmap(":/resource/pieChart.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pieChart.setIcon(pieChartIcon) self.pieChart.setIconSize(QtCore.QSize(70, 70)) self.pieChart.setObjectName("pieChart") self.gridLayout_3.addWidget(self.pieChart, 0, 0) self.circleChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.circleChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.circleChart.setToolButtonStyle(3) # Set text position under icon self.circleChart.setText("Circle") circleChartIcon = QtGui.QIcon() circleChartIcon.addPixmap(QtGui.QPixmap(":/resource/circleView.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.circleChart.setIcon(circleChartIcon) self.circleChart.setIconSize(QtCore.QSize(70, 70)) self.circleChart.setObjectName("circleChart") self.gridLayout_3.addWidget(self.circleChart, 5, 0) self.table = QtWidgets.QToolButton(self.scrollAreaWidgetContents_2) self.table.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.table.setToolButtonStyle(3) # Set text position under icon self.table.setText("Table") tableIcon = QtGui.QIcon() tableIcon.addPixmap(QtGui.QPixmap(":/resource/tableChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.table.setIcon(tableIcon) self.table.setIconSize(QtCore.QSize(70, 70)) self.table.setObjectName("table") self.gridLayout_3.addWidget(self.table, 1, 0) self.histogram = QtWidgets.QToolButton(self.scrollAreaWidgetContents_2) self.histogram.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.histogram.setToolButtonStyle(3) # Set text position under icon self.histogram.setText("Histogram") histrogramIcon = QtGui.QIcon() histrogramIcon.addPixmap( QtGui.QPixmap(":/resource/histrogramChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.histogram.setIcon(histrogramIcon) self.histogram.setIconSize(QtCore.QSize(70, 70)) self.histogram.setObjectName("histogram") self.gridLayout_3.addWidget(self.histogram, 0, 1) self.scatter = QtWidgets.QToolButton(self.scrollAreaWidgetContents_2) scatterIcon = QtGui.QIcon() self.scatter.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.scatter.setToolButtonStyle(3) # Set text position under icon self.scatter.setText("Scatter") scatterIcon.addPixmap(QtGui.QPixmap(":/resource/scatterChart.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.scatter.setIcon(scatterIcon) self.scatter.setIconSize(QtCore.QSize(70, 70)) self.scatter.setObjectName("scatter") self.gridLayout_3.addWidget(self.scatter, 1, 1) self.stackBarChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.stackBarChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.stackBarChart.setToolButtonStyle( 3) # Set text position under icon self.stackBarChart.setText("Stack Bar") stackBarIcon = QtGui.QIcon() stackBarIcon.addPixmap(QtGui.QPixmap(":/resource/stackBarChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.stackBarChart.setIcon(stackBarIcon) self.stackBarChart.setIconSize(QtCore.QSize(70, 70)) self.stackBarChart.setObjectName("stackBarChart") self.gridLayout_3.addWidget(self.stackBarChart, 2, 1) self.sidebysideBarChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.sidebysideBarChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sidebysideBarChart.setToolButtonStyle( 3) # Set text position under icon self.sidebysideBarChart.setText("Side By Side") sidebysideIcon = QtGui.QIcon() sidebysideIcon.addPixmap( QtGui.QPixmap(":/resource/sidebysideBarChart.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.sidebysideBarChart.setIcon(sidebysideIcon) self.sidebysideBarChart.setIconSize(QtCore.QSize(70, 70)) self.sidebysideBarChart.setObjectName("sidebysideBarChart") self.gridLayout_3.addWidget(self.sidebysideBarChart, 3, 1) self.bubbleChart = QtWidgets.QToolButton( self.scrollAreaWidgetContents_2) self.bubbleChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.bubbleChart.setToolButtonStyle(3) # Set text position under icon self.bubbleChart.setText("Bubble") bubbleChartIcon = QtGui.QIcon() bubbleChartIcon.addPixmap(QtGui.QPixmap(":/resource/bubbleChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.bubbleChart.setIcon(bubbleChartIcon) self.bubbleChart.setIconSize(QtCore.QSize(70, 70)) self.bubbleChart.setObjectName("bubbleChart") self.gridLayout_3.addWidget(self.bubbleChart, 4, 1) self.dualChart = QtWidgets.QToolButton(self.scrollAreaWidgetContents_2) self.dualChart.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.dualChart.setToolButtonStyle(3) # Set text position under icon self.dualChart.setText("Dual Chart") dualChartIcon = QtGui.QIcon() dualChartIcon.addPixmap(QtGui.QPixmap(":/resource/dualChart.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.dualChart.setIcon(dualChartIcon) self.dualChart.setIconSize(QtCore.QSize(70, 70)) self.dualChart.setObjectName("dualChart") self.gridLayout_3.addWidget(self.dualChart, 5, 1) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.gridLayout.addWidget(self.scrollArea_2, 0, 2) self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setBaseSize(QtCore.QSize(2000, 2000)) self.tabWidget.setObjectName("tabWidget") self.chartTab = QtWidgets.QWidget() self.chartTab.setObjectName("chartTab") self.plotLayout = QtWidgets.QVBoxLayout() self.plotWidget = pg.PlotWidget(name='Plot') self.plotLayout.addWidget(self.plotWidget) self.chartTab.setLayout(self.plotLayout) self.tabWidget.addTab(self.chartTab, "") self.tabWidget.setTabText(self.tabWidget.indexOf(self.chartTab), "Chart") self.tableTab = QtWidgets.QWidget() self.tableTab.setObjectName("tableTab") self.tableLayout = QtWidgets.QVBoxLayout() self.tableWidget = pg.TableWidget() self.tableLayout.addWidget(self.tableWidget) self.tableTab.setLayout(self.tableLayout) self.tabWidget.addTab(self.tableTab, "") self.gridLayout.addWidget(self.tabWidget, 0, 1) self.tabWidget.setTabText(self.tabWidget.indexOf(self.chartTab), "Chart") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tableTab), "Table") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1261, 26)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuFile.setTitle("File") self.actionOpen = QtWidgets.QAction(MainWindow) self.actionOpen.setObjectName("actionImport") self.actionOpen.setText("Open") self.actionOpen.setShortcut("Ctrl+O") self.actionOpen.triggered.connect(self.openFileDialog) self.actionImport = QtWidgets.QAction(MainWindow) self.actionImport.setObjectName("actionImport") self.actionImport.setText("Import") self.actionImport.setShortcut("Ctrl+O") self.actionImport.triggered.connect(self.openFileDialog) self.actionSave = QtWidgets.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionSave.setText("Save") self.actionSave.setShortcut("Ctrl+S") self.actionSave.triggered.connect(self.saveFileDialog) self.actionExport = QtWidgets.QAction(MainWindow) self.actionExport.setObjectName("actionExport") self.actionExport.setText("Export") self.actionExport.setShortcut("Ctrl+E") self.actionExport.triggered.connect(self.exportFileDialog) self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionImport) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionExport) self.menubar.addAction(self.menuFile.menuAction()) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow)
curve4 = fig2.plot(pen=(120,120,20),name="M4") curve5 = fig2.plot(pen=(160, 80,20),name="M5") curve6 = fig2.plot(pen=(200, 40,20),name="M6") curve1.setData(pData[0]) curve2.setData(pData[1]) curve3.setData(pData[2]) curve4.setData(pData[3]) curve5.setData(pData[4]) curve6.setData(pData[5]) textMax = pg.TextItem(html='<div style="text-align: center;"><span style="color: #FF0; font-size: 12pt;">Presione Inicio</span></div>', anchor=(-0.3,1), angle=0, fill=(0, 0, 255, 100)) fig2.addItem(textMax) tab1 = pg.TableWidget() items = ["M1(mm)","M2(mm)","M3(mm)","M4(mm)","M5(mm)","M6(mm)","Fx(Kg)"] tab1.setRowCount(1000) tab1.setColumnCount(7) tab1.setHorizontalHeaderLabels(items) softlabel = QtGui.QLabel('<div style="text-align: center;"><span style="color: #FFF; font-size: 14pt;">Ensayo de Compresion Axial y Diagonal</span></div>') loadlabel = QtGui.QLabel('<div style="text-align: center;"><span style="color: #FF0; font-size: 16pt;">Carga: %s Kg</span></div>'%(uData[6])) microlabel = QtGui.QLabel('<div style="text-align: center;"><span style="color: #FF0; font-size: 16pt;">Deformaciones: M1: %s, M2: %s, M3: %s, M4: %s, M5: %s, M6: %s,</span></div>'%(uData[0],uData[1],uData[2],uData[3],uData[4],uData[5])) plotBtn = QtGui.QPushButton('Plot') portlabel = QtGui.QLabel("Puerto:") portSel = QtGui.QComboBox()
def test_TableWidget(): w = pg.TableWidget(sortable=False) # Test all input data types w.setData(listOfTuples) assertTableData(w, listOfTuples) w.setData(listOfLists) assertTableData(w, listOfTuples) w.setData(plainArray) assertTableData(w, listOfTuples) w.setData(recordArray) assertTableData(w, listOfTuples) w.setData(dictOfLists) assertTableData(w, transposed) w.appendData(dictOfLists) assertTableData(w, transposed * 2) w.setData(listOfDicts) assertTableData(w, listOfTuples) w.appendData(listOfDicts) assertTableData(w, listOfTuples * 2) # Test sorting w.setData(listOfTuples) w.sortByColumn(0, pg.QtCore.Qt.AscendingOrder) assertTableData(w, sorted(listOfTuples, key=lambda a: a[0])) w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder) assertTableData(w, sorted(listOfTuples, key=lambda a: a[1])) w.sortByColumn(2, pg.QtCore.Qt.AscendingOrder) assertTableData(w, sorted(listOfTuples, key=lambda a: a[2])) w.setSortMode(1, 'text') w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder) assertTableData(w, sorted(listOfTuples, key=lambda a: str(a[1]))) w.setSortMode(1, 'index') w.sortByColumn(1, pg.QtCore.Qt.AscendingOrder) assertTableData(w, listOfTuples) # Test formatting item = w.item(0, 2) assert item.text() == ('%0.3g' % item.value) w.setFormat('%0.6f') assert item.text() == ('%0.6f' % item.value) w.setFormat('X%0.7f', column=2) assert isinstance(item.value, float) assert item.text() == ('X%0.7f' % item.value) # test setting items that do not exist yet w.setFormat('X%0.7f', column=3) # test append uses correct formatting w.appendRow(('x', 10, 7.3)) item = w.item(w.rowCount() - 1, 2) assert isinstance(item.value, float) assert item.text() == ('X%0.7f' % item.value) # test reset back to defaults w.setFormat(None, column=2) assert isinstance(item.value, float) assert item.text() == ('%0.6f' % item.value) w.setFormat(None) assert isinstance(item.value, float) assert item.text() == ('%0.3g' % item.value) # test function formatter def fmt(item): if isinstance(item.value, float): return "%d %f" % (item.index, item.value) else: return pg.asUnicode(item.value) w.setFormat(fmt) assert isinstance(item.value, float) assert isinstance(item.index, int) assert item.text() == ("%d %f" % (item.index, item.value))
assert isinstance(item.value, float) assert item.text() == ('X%0.7f' % item.value) # test reset back to defaults w.setFormat(None, column=2) assert isinstance(item.value, float) assert item.text() == ('%0.6f' % item.value) w.setFormat(None) assert isinstance(item.value, float) assert item.text() == ('%0.3g' % item.value) # test function formatter def fmt(item): if isinstance(item.value, float): return "%d %f" % (item.index, item.value) else: return pg.asUnicode(item.value) w.setFormat(fmt) assert isinstance(item.value, float) assert isinstance(item.index, int) assert item.text() == ("%d %f" % (item.index, item.value)) if __name__ == '__main__': w = pg.TableWidget(editable=True) w.setData(listOfTuples) w.resize(600, 600) w.show()
def update_plots(self): """ This brings up everything and is therefore the main function. Update Plots is either periodically called e.g. by the timer or once on startup. """ #print "PWL update_plots:", self.obj_parent.h5file self.ds = self.obj_parent.h5file[self.dataset_url] self.ds_type = self.ds.attrs.get('ds_type', -1) if self._windowJustCreated: # A few state variables: self._onPlotTypeChanged = True self._windowJustCreated = False self.graphicsView = None self.TraceValueChanged = False self.TraceZValueChanged = False self.TraceXValueChanged = False self.TraceYValueChanged = False self.VTraceZValueChanged = False self.VTraceXValueChanged = False self.VTraceYValueChanged = False # the following calls rely on ds_type and setup the layout of the plot window. self.setupUi(self, self.ds_type) window_title = str(self.dataset_url.split('/')[-1]) + " " + str( self.DATA.filename) self.setWindowTitle(window_title) self._setDefaultView() self._setup_signal_slots() try: if self.view_type == view_types['1D-V']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.PlotWidget(name=self.dataset_url) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu(self.graphicsView.plotItem.getMenu()) self.gridLayout.addWidget(self.graphicsView, 0, 0) _display_1D_view(self, self.graphicsView) elif self.view_type == view_types['1D']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.PlotWidget(name=self.dataset_url) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu(self.graphicsView.plotItem.getMenu()) self.gridLayout.addWidget(self.graphicsView, 0, 0) _display_1D_data(self, self.graphicsView) elif self.view_type == view_types['2D']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.ImageView(self.obj_parent, view=pg.PlotItem()) self.graphicsView.setObjectName(self.dataset_url) self.addQvkMenu(self.graphicsView.view.getMenu()) #self.addQvkMenu(self..graphicsView.getImageItem().getMenu()) self.graphicsView.view.setAspectLocked(False) self.gridLayout.addWidget(self.graphicsView, 0, 0) _display_2D_data(self, self.graphicsView) elif self.view_type == view_types['table']: if not self.graphicsView or self._onPlotTypeChanged: self._onPlotTypeChanged = False self.graphicsView = pg.TableWidget(sortable=False) self.graphicsView.setWindowTitle(self.dataset_url + '_table') self.graphicsView.setObjectName(self.dataset_url) self.gridLayout.addWidget(self.graphicsView, 0, 0) _display_table(self, self.graphicsView) elif self.view_type == view_types['txt']: if not self.graphicsView or self._onPlotTypeChangeBox: self._onPlotTypeChangeBox = False self.graphicsView = QPlainTextEdit() self.graphicsView.setObjectName(self.dataset_url) self.gridLayout.addWidget(self.graphicsView, 0, 0) #self.graphicsView.setObjectName(self.dataset_url) self.gridLayout.addWidget(self.graphicsView, 0, 0) self.graphicsView.clear() _display_text(self, self.graphicsView) else: print("This should not be here: View Type:" + str(self.view_type)) except ValueError as e: print("PlotWindow: Value Error; Dataset not yet available", self.dataset_url) print(e)
def __init__(self, group, parent=None): super(GroupAnalyzer, self).__init__(parent) ## Create window with ImageView widget # self=QWidget() self.group = group nPuffs = len(self.group.puffs) self.offsets = [puff.kinetics['t_start'] for puff in self.group.puffs] cmap = matplotlib.cm.gist_rainbow self.colors = [cmap(int(i * 255. / nPuffs)) for i in np.arange(nPuffs)] self.colors = [ tuple([int(c * 255) for c in col]) for col in self.colors ] self.setGeometry(QRect(1065, 121, 749, 948)) self.setWindowTitle('Group Analyzer') self.hbox = QGridLayout() self.setLayout(self.hbox) self.area = DockArea() self.hbox.addWidget(self.area) self.d1 = Dock("Measured amplitude over time", size=(500, 300)) self.d2 = Dock("Variables", size=(146, 400)) self.d3 = Dock("Event View", size=(500, 400)) self.d4 = Dock("X over time", size=(500, 300)) self.d5 = Dock("Y over time", size=(500, 300)) self.d6 = Dock("Fitted amplitude over time", size=(500, 300)) self.d7 = Dock("Sigma over time", size=(500, 300)) self.d8 = Dock("3D fit", size=(500, 400)) self.d9 = Dock("Puff Data", size=(500, 400)) self.area.addDock( self.d6, 'left' ) ## place d1 at left edge of dock area (it will fill the whole space since there are no other docks yet) self.area.addDock(self.d2, 'right', self.d6) ## place d2 at right edge of dock area self.area.addDock(self.d8, 'bottom') self.area.addDock(self.d9, 'below', self.d8) self.area.addDock(self.d3, 'above', self.d8) ## place d3 at bottom edge of d1 self.area.addDock(self.d4, 'below', self.d6) self.area.addDock(self.d5, 'below', self.d4) self.area.addDock(self.d7, 'below', self.d5) self.area.addDock(self.d1, 'above', self.d6) self.p1 = pg.PlotWidget(title="Measured amplitude over time") self.d1.addWidget(self.p1) self.p2 = pg.PlotWidget(title="Fitted amplitude over time") self.d6.addWidget(self.p2) self.p3 = pg.PlotWidget(title="Fitted X over time") self.d4.addWidget(self.p3) self.p4 = pg.PlotWidget(title="Fitted Y over time") self.d5.addWidget(self.p4) self.p5 = pg.PlotWidget(title="Fitted Sigma over time") self.d7.addWidget(self.p5) self.puff_3D = puff_3D() self.d8.addWidget(self.puff_3D) self.table = pg.TableWidget() self.d9.addWidget(self.table) self.formlayout = QFormLayout() self.puffCheckBoxes = [QCheckBox() for puff in group.puffs] for i in np.arange(nPuffs): self.puffCheckBoxes[i].setChecked(True) self.puffCheckBoxes[i].stateChanged.connect(self.replot) self.formlayout.addRow('Puff ' + str(i), self.puffCheckBoxes[i]) self.alignAverageCheckBox = QCheckBox() self.formlayout.addRow('Align Average', self.alignAverageCheckBox) self.currentPuff = QComboBox() for i in np.arange(nPuffs): self.currentPuff.addItem('Puff ' + str(i)) self.currentPuff.currentIndexChanged.connect(self.changeCurrentPuff) self.formlayout.addRow('Current Puff', self.currentPuff) # self.exportButton=QPushButton("Export") # self.exportButton.clicked.connect(self.export) # self.formlayout.addWidget(self.exportButton) self.formWidget = QWidget() self.formWidget.setLayout(self.formlayout) self.d2.addWidget(self.formWidget) self.imageview = pg.ImageView() puff = self.group.puffs[self.currentPuff.currentIndex()] self.bounds = np.copy(puff.bounds) self.bounds[0, 0] = puff.kinetics['before'] self.bounds[0, 1] = puff.kinetics['after'] bb = self.bounds self.I = self.group.puffs[0].puffs.normalized_window.image[ bb[0][0]:bb[0][1] + 1, bb[1][0]:bb[1][1] + 1, bb[2][0]:bb[2][1] + 1] self.imageview.setImage(self.I) self.addedItems = [] self.sigTimeChanged.connect(self.updateTime) self.imageview.timeLine.sigPositionChanged.connect(self.updateindex) self.d3.addWidget(self.imageview) self.params = [] self.I_fits = [] for puff in self.group.puffs: param, I_fit = self.getParamsOverTime(puff) self.params.append(param) self.I_fits.append(I_fit) self.previousframe = -1 self.replot() self.updatePuffTable() self.updateTime(0) self.show()
# -*- coding: utf-8 -*- """ Simple demonstration of TableWidget, which is an extension of QTableWidget that automatically displays a variety of tabluar data formats. """ import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np app = QtGui.QApplication([]) w = pg.TableWidget() w.show() w.resize(500,500) w.setWindowTitle('pyqtgraph example: TableWidget') data = np.array([ (1, 1.6, 'x'), (3, 5.4, 'y'), (8, 12.5, 'z'), (443, 1e-12, 'w'), ], dtype=[('Column 1', int), ('Column 2', float), ('Column 3', object)]) w.setData(data) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__':
def initUI(self): # self.area = DockArea() # self.setCentralWidget(self.area) # self.resize(1000,500) self.resize(self.screen_size.width(), self.screen_size.height()) self.setWindowTitle('Display widget') self.setWindowIcon(QIcon('DigitalPulses\display_image_icon.jpg')) self.setWindowState(Qt.WindowMaximized) self.d1 = da.Dock("Image", size=(self.screen_size.width() / 2, self.screen_size.height() )) ## give this dock the minimum possible size self.d3 = da.Dock("Number of atoms", size=(self.screen_size.width() / 2, self.screen_size.height() / 3)) self.d2 = da.Dock("Image data", size=(self.screen_size.width() / 2, self.screen_size.height() / 3)) self.d4 = da.Dock("Cloud width", size=(self.screen_size.width() / 2, self.screen_size.height() / 3)) self.area.addDock( self.d1, 'left' ) ## place d1 at left edge of dock area (it will fill the whole space since there are no other docks yet) self.area.addDock(self.d2, 'right', self.d1) ## place d3 at bottom edge of d1 self.area.addDock(self.d4, 'bottom', self.d2) ## place d4 at right edge of dock area self.area.addDock(self.d3, 'bottom', self.d4) ## place d5 at left edge of d1 # #old version # self.imv = pg.ImageView() # self.imv.setColorMap(pg.ColorMap(np.array([ 0. , 0.25, 0.5 , 0.75, 1. ]), np.array([[ 255, 255, 255, 255], [ 0, 0, 255, 255], [ 0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255]], dtype=np.uint8))) # self.imv.setImage(imread(r"D:\!Data\2016_04_22\01 T no_ramp a=-6 f=363.9 b=0.8\0ms\1_1.png")) # # self.imv.getHistogramWidget().setHistogramRange(0,0.6) # self.imv.getHistogramWidget().setLevels(0, 0.6) # self.d1.addWidget # new version with ROI win = pg.GraphicsLayoutWidget() p1 = win.addPlot() self.img = pg.ImageItem() self.img.setZValue(1) p1.addItem(self.img) self.globals['image'] = imread( r"D:\!Data\2016_04_22\01 T no_ramp a=-6 f=363.9 b=0.8\0ms\1_1.png") self.img.setImage(self.globals['image']) self.roi = pg.ROI(self.roi_center, self.roi_size, pen=pg.mkPen('g', width=1)) #, style=pg.QtCore.Qt.DotLine self.roi.addScaleHandle([1, 1], [0, 0]) # self.roi.addScaleHandle([1, 0.5], [0, 1]) p1.addItem(self.roi) self.roi.setZValue(100) self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.hist.setHistogramRange(0, 0.6) self.hist.setLevels(0, 0.6) self.hist.gradient.setColorMap( pg.ColorMap( np.array([0., 0.25, 0.5, 0.75, 1.]), np.array( [[255, 255, 255, 255], [0, 0, 255, 255], [0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255]], dtype=np.uint8))) win.addItem(self.hist) # self.hist.sigLookupTableChanged.connect(self.LUTChanged) self.img.setLookupTable(self.hist.getLookupTable(n=256)) self.roi.sigRegionChangeFinished.connect(self.updateROI) self.d1.addWidget(win, col=0, row=0) win2 = pg.GraphicsLayoutWidget() p1_2 = win2.addPlot() self.img2 = pg.ImageItem() self.img2.setZValue(1) # self.img2.setPxMode(True) p1_2.addItem(self.img2) self.globals['image2'] = imread( r"D:\!Data\2016_04_22\01 T no_ramp a=-6 f=363.9 b=0.8\0ms\1_1.png") self.img2.setImage(self.globals['image2']) self.roi2 = pg.ROI(self.roi_center, self.roi_size, pen=pg.mkPen( 'g', width=1)) # , style=pg.QtCore.Qt.DotLine self.roi2.addScaleHandle([1, 1], [0, 0]) # self.roi.addScaleHandle([1, 0.5], [0, 1]) p1_2.addItem(self.roi2) self.roi2.setZValue(100) self.hist2 = pg.HistogramLUTItem() self.hist2.setImageItem(self.img2) self.hist2.setHistogramRange(0, 0.6) self.hist2.setLevels(0, 0.6) self.hist2.gradient.setColorMap( pg.ColorMap( np.array([0., 0.25, 0.5, 0.75, 1.]), np.array( [[255, 255, 255, 255], [0, 0, 255, 255], [0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255]], dtype=np.uint8))) win2.addItem(self.hist2) # self.hist.sigLookupTableChanged.connect(self.LUTChanged) self.img2.setLookupTable(self.hist2.getLookupTable(n=256)) self.roi2.sigRegionChangeFinished.connect(self.updateROI2) self.d1.addWidget(win2, col=0, row=1) self.w2 = pg.PlotWidget() self.w2.addLegend() # self.w2.setYRange(0,100) self.curve11 = self.w2.plot(np.array([]), pen=(255, 0, 0), name='Nx') self.curve12 = self.w2.plot(np.array([]), pen=(0, 255, 0), name='Ny') self.curve13 = self.w2.plot(np.array([]), pen=(0, 0, 255), name='N') self.d2.addWidget(self.w2) self.w3 = pg.TableWidget() self.w3.setFont(QFont('Arial', 20)) self.w3.setData(self.image_data_to_display) self.d3.addWidget(self.w3) # w6 = QHBoxLayout() # w6.addWidget(QLabel('fit1D_x')) chbx_widget = QWidget() chbx_layout = QHBoxLayout() chbx_layout.addWidget(QLabel('fit1D_x')) self.fit1D_x_chbx = QCheckBox() self.fit1D_x_chbx.setChecked(self.do_fit1D_x) self.fit1D_x_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit1D_x', state)) chbx_layout.addWidget(self.fit1D_x_chbx) chbx_layout.addWidget(QLabel('fit1D_y')) self.fit1D_y_chbx = QCheckBox() self.fit1D_y_chbx.setChecked(self.do_fit1D_y) self.fit1D_y_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit1D_y', state)) chbx_layout.addWidget(self.fit1D_y_chbx) chbx_layout.addWidget(QLabel('fit2D')) self.fit2D_chbx = QCheckBox() self.fit2D_chbx.setChecked(self.do_fit2D) self.fit2D_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit2D', state)) chbx_layout.addWidget(self.fit2D_chbx) chbx_layout.addWidget(QLabel('substract background')) self.fit2D_chbx = QCheckBox() self.fit2D_chbx.setChecked(self.subs_bgnd) self.fit2D_chbx.stateChanged.connect( lambda state: self.chbxClicked('subs_bgnd', state)) chbx_layout.addWidget(self.fit2D_chbx) chbx_layout.addWidget(QLabel('N points to show')) self.n_points_spin_box = QSpinBox() self.n_points_spin_box.setRange(10, 1000) self.n_points_spin_box.setValue(self.N_point_to_plot) self.n_points_spin_box.valueChanged.connect(self.nPointsChanged) chbx_layout.addWidget(self.n_points_spin_box) # w6.addWidget(self.fit1D_x_chbx) # self.d3.addWidget(QLabel('fit1D_x'),row=1,col=0) # self.d3.addWidget(self.fit1D_x_chbx,row=1,col=1) chbx_layout.addStretch(1) chbx_widget.setLayout(chbx_layout) self.d3.addWidget(chbx_widget) self.w5 = pg.TableWidget(editable=True, sortable=False) self.w5.setFont(QFont('Arial', 20)) self.w5.setData(self.getROITableData()) self.w5.cellChanged.connect(self.roiTableChanged) self.d3.addWidget(self.w5, row=0, col=1) self.w4 = pg.PlotWidget() # self.w2.setYRange(0,100) self.w4.addLegend(size=(5, 20)) self.curve21 = self.w4.plot(np.array([]), pen=(255, 0, 0), name="w_x1") self.curve22 = self.w4.plot(np.array([]), pen=(0, 255, 0), name="w_x2") self.curve23 = self.w4.plot(np.array([]), pen=(0, 0, 255), name="w_y1") self.curve24 = self.w4.plot(np.array([]), pen='y', name="w_y2") self.d4.addWidget(self.w4) self.signals.newImageRead.connect(self.routine)
def __init__(self, parent=None): super(DetailThirdrowdata, self).__init__(parent) self.layout = QGridLayout(self) self.table = pg.TableWidget() self.table.horizontalHeader().setHidden(True) self.table.setShowGrid(False) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.layout.addWidget(self.table) self.thirdrowdata = [ (4, 56, 85, 5, 4, 56, 85, 5, " ", 4, 56, 85, 5, 4, 56, 85, 5, " ", 4, 56, 85, 5, 4, 56, 85, 5, " ", 4, 56, 85, 5, 4, 56, 85, 55), (1, 20, 33, 8, 1, 20, 33, 8, " ", 1, 20, 33, 8, 1, 20, 33, 8, " ", 1, 20, 33, 8, 1, 20, 33, 8, " ", 1, 20, 33, 8, 1, 20, 33, 8), (45, 4, 56, 85, 45, 4, 56, 85, " ", 45, 4, 56, 85, 45, 4, 56, 85, " ", 45, 4, 56, 85, 45, 4, 56, 85, " ", 45, 4, 56, 85, 45, 4, 56, 85), (1, 20, 33, 85, 1, 20, 33, 85, " ", 1, 20, 33, 85, 1, 20, 33, 85, " ", 1, 20, 33, 85, 1, 20, 33, 85, " ", 1, 20, 33, 85, 1, 20, 33, 85), (4, 56, 85, 6, 4, 56, 85, 6, " ", 4, 56, 85, 6, 4, 56, 85, 6, " ", 4, 56, 85, 6, 4, 56, 85, 6, " ", 4, 56, 85, 6, 4, 56, 85, 6), (1, 2, 12, 33, 1, 2, 12, 33, " ", 1, 2, 12, 33, 1, 2, 12, 33, " ", 1, 2, 12, 33, 1, 2, 12, 33, " ", 1, 2, 12, 33, 1, 2, 12, 33) ] self.showthirdrowdata = np.array(self.thirdrowdata, dtype=[('No', int), ('Time', object), ('Source', object), ('Destination', object), ('object1', object), ('object2', object), ('object3', object), ('object4', object), ('object5', object), ('object6', object), ('object7', object), ('object8', object), ('object9', object), ('object10', object), ('object11', object), ('object12', object), ('object13', object), ('object14', object), ('object15', object), ('object16', object), ('object17', object), ('object18', object), ('object19', object), ('object20', object), ('object21', object), ('object22', object), ('object23', object), ('object24', object), ('object25', object), ('object26', object), ('object27', object), ('object28', object), ('object29', object), ('object30', object), ('object31', object)]) self.table.verticalHeader().setDefaultSectionSize(20) self.table.setData(self.thirdrowdata) self.setLayout(self.layout)
def __init__(self, parent=None, config_file='cam_config.json', image_name='image', default_image=r"default_camera.tiff", image_stack_name='image_stack'): self.config_file = config_file # where to save config self.image_name = image_name # name of the image in parent.globals self.image_stack_name = image_stack_name # name of image stack in parent globals (array of filenames to save) self.parent = parent self.config = {} super().__init__() # default. All theese will be downloaded from config file self.do_fit1D_x = True self.do_fit1D_y = True self.do_fit2D = False self.subs_bgnd = True self.nAtoms = impr.N_atoms(gain=324, exposure=909, power=2.42, width=2.43, delta=7e6) self.realSize = impr.real_size self.n_sigmas = 3 self.roi_center = [200, 200] self.roi_size = [100, 100] # image data to show in table self.image_data_to_display = np.array([('N0', 0, 0), ("X0", 0, 0), ('N', 0, 0), ('W', 0, 0), ('n,T', 0, 0)], dtype=[(' ', object), ('x', object), ('y', object)]) self.load() # config loading main_layout = QHBoxLayout() self.win = pg.GraphicsLayoutWidget() p1 = self.win.addPlot() self.img = pg.ImageItem() self.img.setZValue(1) p1.addItem(self.img) self.parent.globals[self.image_name] = imread( default_image).T #initialise picture self.img.setImage(self.parent.globals[self.image_name]) self.roi = pg.ROI(self.roi_center, self.roi_size, pen=pg.mkPen( 'g', width=1)) # , style=pg.QtCore.Qt.DotLine self.roi.addScaleHandle([1, 1], [0, 0]) # self.roi.addScaleHandle([1, 0.5], [0, 1]) p1.addItem(self.roi) self.roi.setZValue(100) self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.hist.setHistogramRange(0, 0.6) self.hist.setLevels(0, 0.6) self.hist.gradient.setColorMap( pg.ColorMap( np.array([0., 0.25, 0.5, 0.75, 1.]), np.array( [[255, 255, 255, 255], [0, 0, 255, 255], [0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255]], dtype=np.uint8))) self.win.addItem(self.hist) self.img.setLookupTable(self.hist.getLookupTable(n=256)) self.roi.sigRegionChangeFinished.connect(self.updateROI) main_layout.addWidget(self.win) chbx_layout = QVBoxLayout() # basically config and info layout chbx_layout.addWidget(QLabel('fit1D_x')) self.fit1D_x_chbx = QCheckBox() self.fit1D_x_chbx.setChecked(self.do_fit1D_x) self.fit1D_x_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit1D_x', state)) chbx_layout.addWidget(self.fit1D_x_chbx) chbx_layout.addWidget(QLabel('fit1D_y')) self.fit1D_y_chbx = QCheckBox() self.fit1D_y_chbx.setChecked(self.do_fit1D_y) self.fit1D_y_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit1D_y', state)) chbx_layout.addWidget(self.fit1D_y_chbx) chbx_layout.addWidget(QLabel('fit2D')) self.fit2D_chbx = QCheckBox() self.fit2D_chbx.setChecked(self.do_fit2D) self.fit2D_chbx.stateChanged.connect( lambda state: self.chbxClicked('do_fit2D', state)) chbx_layout.addWidget(self.fit2D_chbx) chbx_layout.addWidget(QLabel('substract background')) self.fit2D_chbx = QCheckBox() self.fit2D_chbx.setChecked(self.subs_bgnd) self.fit2D_chbx.stateChanged.connect( lambda state: self.chbxClicked('subs_bgnd', state)) chbx_layout.addWidget(self.fit2D_chbx) self.w3 = pg.TableWidget() self.w3.setFixedWidth(160) self.w3.setFont(QFont('Arial', 12)) self.w3.setData(self.image_data_to_display) chbx_layout.addWidget(self.w3) self.w3.horizontalHeader().setDefaultSectionSize(40) self.w3.verticalHeader().setDefaultSectionSize(30) self.w3.horizontalHeader().setResizeMode(QHeaderView.Fixed) self.w3.verticalHeader().setResizeMode(QHeaderView.Fixed) self.exp = QLineEdit('909') self.exp.setFixedWidth(60) chbx_layout.addWidget(self.exp) self.exp.textChanged.connect(self.newCameraSettings) self.gain = QLineEdit('324') self.gain.setFixedWidth(60) chbx_layout.addWidget(self.gain) self.gain.textChanged.connect(self.newCameraSettings) self.binn = QLineEdit('2') self.binn.setFixedWidth(60) chbx_layout.addWidget(self.binn) self.binn.textChanged.connect(self.newCameraSettings) self.power = QLineEdit('2.55') self.power.setFixedWidth(60) chbx_layout.addWidget(self.power) self.power.textChanged.connect(self.newCameraSettings) self.delta = QLineEdit('7.0') self.delta.setFixedWidth(60) chbx_layout.addWidget(self.delta) self.delta.textChanged.connect(self.newCameraSettings) chbx_layout.addStretch(1) main_layout.addLayout(chbx_layout) self.setLayout(main_layout)