class ApBbaDlg(QDialog): def __init__(self, parent=None, **kwargs): super(ApBbaDlg, self).__init__(parent) self.bpms = [] self.quads = [] self.corrs = [] self.quad_dkicks = [] self.cor_dkicks = [] self.bba = ap.bba.BbaBowtie() self.table = QTableWidget(0, 5) self.table.setMinimumHeight(120) self.table.setMinimumWidth(500) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) hdview = QHeaderView(Qt.Horizontal) self.table.setHorizontalHeaderLabels( ['QUAD', 'BPM.field', 'BPM center', "Corr", "Kick"]) fmbox = QFormLayout() self.subprogress = QProgressBar() self.subprogress.setTextVisible(True) self.subprogress.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.progress = QProgressBar() self.progress.setTextVisible(True) self.progress.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) fmbox.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) fmbox.addRow("Current BPM", self.subprogress) fmbox.addRow("All Alignment", self.progress) #self.progress.setMaximum(self.repeatbox.value()) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(fmbox) #hbox.addStretch() self.widtab = QTabWidget() vbox.addWidget(self.widtab) self.setLayout(vbox) self.connect(self.widtab, SIGNAL("currentChanged(int)"), self.activateResult) self.connect(self.table, SIGNAL("cellClicked(int, int)"), self.activateResult) #self.bbathread = ApBbaThread() #self.connect(self.bbathread, # SIGNAL("aligned(QString, QString, float, float)"), # self.setResult) #self.connect(self.bbathread, # SIGNAL("startAlign(QString, QString, QString)"), # self.appendRecord) #self.connect(self.bbathread, # SIGNAL("aligned(QString, QString, float, float)"), # self.bbadlg.appendResult) def setInput(self, **kwargs): self.bpms = kwargs.get('bpms', []) self.quads = kwargs.get('quads', []) self.cors = kwargs.get('cors', []) self.quad_dkicks = kwargs.get('quad_dkicks', []) self.cor_dkicks = kwargs.get('cor_dkicks', []) def runAlignment(self, **kwargs): self.setInput(**kwargs) #self.bbathread.start() print "Starting %d measurements" % len(self.bpms) self.progress.setMaximum(len(self.bpms)) self.subprogress.setMaximum(100) from cothread.catools import caget, caput print __file__, "BBA align", caget('V:2-SR:C30-BI:G2{PH1:11}SA:X') self.table.setRowCount(len(self.bpms)) for i, bpmrec in enumerate(self.bpms): print i, bpmrec[0].name, self.quads[i][0].name self.bba.setInput(bpmrec, self.quads[i], self.cors[i], self.quad_dkicks[i], self.cor_dkicks[i]) #self.emit(SIGNAL("startAlign(QString, QString, QString)"), # self.quads[i][0].name, bpmrec[0].name, bpmrec[1]) self.setNames(i, self.quads[i][0].name, bpmrec[0].name, bpmrec[1], self.cors[i][0].name) self.bba.align(verbose=2, guihook=QApplication.processEvents, logger=None, progress=self.subprogress) cv1 = BbaMplCanvas() cv2 = BbaMplCanvas() self.bba.plot(cv1.axes, cv2.axes, factor=(1e6, 1e6)) cv1.draw() cv2.draw() wid = QWidget(self) hbox = QHBoxLayout() hbox.addWidget(cv1) hbox.addWidget(cv2) wid.setLayout(hbox) self.widtab.addTab(wid, "%s.%s" % (bpmrec[0].name, bpmrec[1])) self.widtab.setCurrentIndex(i) #time.sleep(.1) #self.emit(SIGNAL("aligned(QString, QString, float, float)"), # bpmrec[0].name, bpmrec[1], 0.0, 0.0) self.setResult(i, bpmrec[0].name, bpmrec[1], self.bba.bpm_fitted, self.bba.cor_fitted) self.progress.setValue(i + 1) def activateResult(self, i=0, j=0): if i < self.widtab.count() and i != self.widtab.currentIndex(): self.widtab.setCurrentIndex(i) if i < self.table.rowCount() and i != self.table.currentRow(): self.table.setCurrentCell(i, 1) def setNames(self, i, quadname, bpmname, fld, corname): self.table.setItem(i, 0, QTableWidgetItem(quadname)) self.table.setItem(i, 1, QTableWidgetItem("{0}.{1}".format(bpmname, fld))) self.table.setItem(i, 3, QTableWidgetItem(corname)) def setResult(self, i, bpmname, fld, bpmval, corval): #self.table.setItem(n, 1, QTableWidgetItem(bpmname)) #self.table.setItem(n, 2, QTableWidgetItem(fld)) self.table.setItem(i, 2, QTableWidgetItem("%g" % bpmval)) self.table.setItem(i, 4, QTableWidgetItem("%g" % corval)) self.table.setCurrentCell(i, 1)
class ScanRecordTable(QGroupBox): """ GUI component. Displays a list of previous scan results. Selecting a scan causes details of the scan to appear in other GUI components (list of barcodes in the barcode table and image of the puck in the image frame). """ COLUMNS = [ 'Date', 'Time', 'Plate Barcode', 'Plate Type', 'Valid', 'Invalid', 'Empty' ] def __init__(self, barcode_table, image_frame, options, to_run_on_table_clicked): super(ScanRecordTable, self).__init__() # Read the store from file self._store = Store(options.store_directory.value(), options.store_capacity, FileManager()) self._options = options self._barcodeTable = barcode_table self._imageFrame = image_frame self.setTitle("Scan Records") self._init_ui(to_run_on_table_clicked) self._load_store_records() def _init_ui(self, to_run_on_table_clicked): # Create record table - lists all the records in the store self._table = QTableWidget() self._table.setFixedWidth(440) self._table.setFixedHeight(600) self._table.setColumnCount(len(self.COLUMNS)) self._table.setHorizontalHeaderLabels(self.COLUMNS) self._table.setColumnWidth(0, 70) self._table.setColumnWidth(1, 55) self._table.setColumnWidth(2, 85) self._table.setColumnWidth(3, 70) self._table.setColumnWidth(4, 45) self._table.setColumnWidth(5, 50) self._table.setColumnWidth(6, 45) self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self._table.cellPressed.connect(to_run_on_table_clicked) self._table.cellPressed.connect(self._record_selected) # Delete button - deletes selected records btn_delete = QtGui.QPushButton('Delete') btn_delete.setToolTip('Delete selected scan/s') btn_delete.resize(btn_delete.sizeHint()) btn_delete.clicked.connect(self._delete_selected_records) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(btn_delete) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def add_record_frame(self, holder_barcode, plate, holder_img, pins_img): """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record""" self._store.merge_record(holder_barcode, plate, holder_img, pins_img) self._load_store_records() if self._options.scan_clipboard.value(): self._barcodeTable.copy_to_clipboard() def _load_store_records(self): """ Populate the record table with all of the records in the store. """ self._table.clearContents() self._table.setRowCount(self._store.size()) for n, record in enumerate(self._store.records): items = [ record.date, record.time, record.holder_barcode, record.plate_type, record.num_valid_barcodes, record.num_unread_slots, record.num_empty_slots ] if (record.num_valid_barcodes + record.num_empty_slots) == record.num_slots: color = self._options.col_ok() else: color = self._options.col_bad() color.a = 192 for m, item in enumerate(items): new_item = QtGui.QTableWidgetItem(str(item)) new_item.setBackgroundColor(color.to_qt()) new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(n, m, new_item) # Display the first (most recent) record self._table.setCurrentCell(0, 0) self._record_selected() def _record_selected(self): """ Called when a row is selected, causes details of the selected record to be displayed (list of barcodes in the barcode table and image of the scan in the image frame). """ try: row = self._table.selectionModel().selectedRows()[0].row() record = self._store.get_record(row) self._barcodeTable.populate(record.holder_barcode, record.barcodes) marked_image = record.marked_image(self._options) self._imageFrame.display_puck_image(marked_image) except IndexError: self._barcodeTable.clear() self._imageFrame.clear_frame( "Record table empty\nNothing to display") def _delete_selected_records(self): """ Called when the 'Delete' button is pressed. Deletes all of the selected records (and the associated images) from the store and from disk. Asks for user confirmation. """ # Display a confirmation dialog to check that user wants to proceed with deletion quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?" reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # If yes, find the appropriate records and delete them if reply == QtGui.QMessageBox.Yes: rows = self._table.selectionModel().selectedRows() records_to_delete = [] for row in rows: index = row.row() record = self._store.get_record(index) records_to_delete.append(record) self._store.delete_records(records_to_delete) self._load_store_records() def is_latest_holder_barcode(self, holder_barcode): return self._store.is_latest_holder_barcode(holder_barcode)
class ImportDataDlg(QDialog): __isJy = False # 数据校验成功的标志 __mlist = [] # 定义一个列表用于保存从excel表中取出的数据 def __init__(self, iface, parent=None, impType=ImpDateType.SITEANDCELL): super(ImportDataDlg, self).__init__() self.iface = iface self.parent = parent self.impType = impType self.initView() def initView(self): if self.impType == ImpDateType.SERVINGCELL: self.setWindowTitle(u'相邻小区数据导入') else: self.setWindowTitle(u'基站和小区数据导入') self.setWindowIcon(QIcon('images/logo.png')) self.resize(620, 480) # 数据表格 self.tableWidget = QTableWidget(self) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setRowCount(7) # 设置当前Table不能编辑 self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 初始化表格上下文菜单 self.initTableContextMenu() # 初始化表头 self.initTableHeader() # 导入出错列表 self.listWidget = QListWidget(self) # 按钮组 impBtn = QPushButton(u"导入EXCEL表", self) yzBtn = QPushButton(u"数据检验", self) impdateBtn = QPushButton(u"导入数据", self) btnVBox = QVBoxLayout() btnVBox.addWidget(impBtn) btnVBox.addWidget(yzBtn) btnVBox.addWidget(impdateBtn) # 错误列表与按钮组 hBox = QHBoxLayout() hBox.setMargin(20) hBox.addWidget(self.listWidget) hBox.addLayout(btnVBox) self.mbar = QStatusBar(self) self.mbar.showMessage(u'准备就绪...') self.maction = QToolBar(self) self.editAction = QAction(u'编辑', self.maction) self.editAction.setCheckable(True) self.combox = QComboBox(self) self.combox.addItems(HeadsConfig.ImpExcelName) self.maction.addWidget(self.combox) self.maction.addAction(self.editAction) vBox = QVBoxLayout() vBox.addWidget(self.maction) vBox.addWidget(self.tableWidget) vBox.addLayout(hBox) vBox.addWidget(self.mbar) vBox.setStretchFactor(self.tableWidget, 9) vBox.setStretchFactor(hBox, 5) vBox.setStretchFactor(self.mbar, 1) self.setLayout(vBox) QObject.connect(impBtn, SIGNAL('clicked()'), self.impClick) QObject.connect(yzBtn, SIGNAL('clicked()'), self.yzClick) QObject.connect(impdateBtn, SIGNAL('clicked()'), self.impdateClick) QObject.connect(self.editAction, SIGNAL('triggered()'), self.editClick) QObject.connect(self.combox, SIGNAL('currentIndexChanged(int)'), self.comboxChange) self.listWidget.doubleClicked.connect(self.mlistClicked) # self.connect(self.listWidget, SIGNAL("itemDoubleClicked (QListWidgetItem)"), self.mlistClicked) def initTableContextMenu(self): self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.popMenu = QMenu(self.tableWidget) delAction = QAction(u'删除', self) # 删除 self.popMenu.addAction(delAction) # 设置表格可以双击修改数据 def setEditTriggers(self, isTrigger): if isTrigger: self.tableWidget.setEditTriggers(QAbstractItemView.DoubleClicked) else: self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 提供给外部修改状态栏消息 def setStatusBarMsg(self, msg): self.mbar.showMessage(msg) # 选框改变时,清空当前表格的全部内容,包括表格头 def updateType(self, mtype): self.impType = mtype self.tableWidget.clear() # 清空表格所有内容 self.initTableHeader() # 初始化表格的每个Item def initTable(self, mlist): self.tableWidget.setRowCount(len(mlist)) for (i, v) in enumerate(mlist): for (j, item) in enumerate(v): if type(item) != str: item = unicode(item) if item == None: item = u"" tabItem = QTableWidgetItem(item) tabItem.setTextAlignment(Qt.AlignCenter) self.tableWidget.setItem(i, j, tabItem) # 初始化错误信息列表 def initListView(self, mlist): for iv in mlist: lisItm = QListWidgetItem(self.listWidget) lisItm.setTextColor(Qt.red) lisItm.setData(Qt.UserRole, iv) if isinstance(iv, basestring): # 如果错误信息是一行字符串 lisItm.setText(iv) else: lisItm.setText(u'第' + unicode(str(iv['row'] + 1)) + u'行,第' + unicode(str(iv['col'] + 1)) + u'列:' + iv['msg']) # 初始化Table的头 def initTableHeader(self): self.heads = [] if self.impType == ImpDateType.SITEANDCELL: # 获取当前项目图层的字段名 cell_layer = getLayerByName(u"小区", self.iface) for head in HeadsConfig.SiteANDCellHead: self.heads.append(head) if len(cell_layer.pendingFields()) > 55: for (index, field) in enumerate(cell_layer.pendingFields()): if index > 54: field_name = field.name().strip() self.heads.append(field_name) else: self.heads = HeadsConfig.ServingCellHead self.tableWidget.setColumnCount(len(self.heads)) # 设置表格的列数 for (i, h) in enumerate(self.heads): tabItem = QTableWidgetItem(h) self.tableWidget.setHorizontalHeaderItem(i, tabItem) # 自定义为Table添加Item def addTableItem(self, row, col, content): tabItem = QTableWidgetItem(content) self.tableWidget.setItem(row, col, tabItem) # 修改Item的内容 def editTableItem(self, row, col, content): tabItem = self.tableWidget.item(row, col) tabItem.setText(content) self.tableWidget.setItem(row, col, tabItem) # 从Excel表读取数据(导入Excel表) def impClick(self): fileName = QFileDialog.getOpenFileName(self, u'基站小区数据导入', '/', 'Excel Files (*.xls *.xlsx)') if fileName.strip() != "": self.setStatusBarMsg(u'选择完毕:' + fileName) importData = GetDataFromExcel(fileName, self.impType, self.heads) self.__mlist = [] self.__mlist.extend(importData.getData()) self.tableWidget.clearContents() self.listWidget.clear() self.initTable(self.__mlist) self.setStatusBarMsg(u'数据导入完成...') self.__isJy = False # 导入完数据后,说明需要重新验证数据的正确性 else: QMessageBox.information(self.parent, u"错误", u"请选中文件") # 数据验证按钮点击事件处理 def yzClick(self): if len(self.__mlist) > 0: self.erlist = [] # 定义一个列表用于保存数据验证错误的数据 # 清楚全部的Item if self.listWidget.count() > 0: self.listWidget.clear() # 根据tableWidget更新self.__mlist for (r, items) in enumerate(self.__mlist): for (v, item) in enumerate(self.__mlist[r]): if self.tableWidget.item(r, v).text() == u"": continue else: # 跟据self.__mlist[r][v]数据类型进行比对 if type(self.__mlist[r][v]) == int: if unicode(self.__mlist[r][v]) != ( self.tableWidget.item(r, v).text()): self.__mlist[r][v] = int( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == float: if unicode(self.__mlist[r][v]) != ( self.tableWidget.item(r, v).text()): self.__mlist[r][v] = float( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == str: if unicode(self.__mlist[r][v] ) != self.tableWidget.item(r, v).text(): self.__mlist[r][v] = str( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == unicode: if (self.__mlist[r][v]) != self.tableWidget.item( r, v).text(): self.__mlist[r][v] = self.tableWidget.item( r, v).text() else: print type(self.__mlist[r][v]) # 执行数据校验函数 self.erlist = checkDataByDataType(self.__mlist, self.impType) if len(self.erlist) > 0: self.initListView(self.erlist) QMessageBox.information(self.parent, u'数据校验', u'数据校验失败,请检查数据正确性后,再导入到地图中') self.__isJy = False else: QMessageBox.information(self.parent, u'数据校验', u'数据校验成功,没有错误数据') self.__isJy = True else: QMessageBox.warning(self.parent, u'数据校验', u'请先导入Excel数据后再操作!') # 导入数据到地图中 def impdateClick(self): if self.__isJy: # 如果数据校验成功 if self.impType == ImpDateType.SITEANDCELL: # 导入基站小区 importDataToLayer = ImportDataToLayer(self.iface, self.__mlist, self.parent) if importDataToLayer.importSiteAndCellData(): QMessageBox.information(self.parent, u"导入数据", u"导入数据成功!") else: QMessageBox.critical(self.parent, u"导入数据", u"导入数据失败!") else: # 导入相邻小区 importDataToLayer = ImportDataToLayer(self.iface, self.__mlist, self.parent) if importDataToLayer.importSCellData(): QMessageBox.information(self.parent, u"导入数据", u"导入数据成功!") else: QMessageBox.critical(self.parent, u"导入数据", u"导入数据失败!") else: QMessageBox.warning(self.parent, u'数据导入', u'请确保校验数据成功后,再导入到地图中') # 编辑Action点击事件 def editClick(self): self.setEditTriggers(self.editAction.isChecked()) # 错误列表双击事件处理 def mlistClicked(self, listItem): itemData = listItem.data(Qt.UserRole) self.tableWidget.setFocus() self.tableWidget.setCurrentCell(itemData['row'], itemData['col']) # 选框改变事件 def comboxChange(self, index): self.updateType(index) # 字段验证是否为空 def __validNull(self, name, col, row, itm, rowitm): if itm is None or itm == '': tmpMap = {} tmpMap['col'] = col tmpMap['row'] = row tmpMap['msg'] = unicode(name) + u'不能为空' tmpMap['item'] = rowitm return tmpMap else: return None # 导入数据线程开始信号 绑定函数 def impStart(self): self.setStatusBarMsg(u'准备导入...') # 导入数据线程发生异常信号 绑定函数 def impError(self, e, exception_string): self.setStatusBarMsg(u'发生错误:' + unicode(e)) QMessageBox.warning(self.parent, u'Excel数据导入', u'发生错误:' + unicode(e)) # 导入数据线程完成信号 绑定函数 def impFinish(self, mylist): self.__mlist = [] self.__mlist.extend(mylist) self.mthread.quit() self.mthread.wait() self.mthread.deleteLater() self.impDateThread.deleteLater() self.tableWidget.clearContents() self.listWidget.clear() self.initTable(self.__mlist) self.setStatusBarMsg(u'数据导入完成...') self.__isJy = False # 导入完数据后,说明需要重新验证数据的正确性 # 导入数据到地图线程发生异常信号 绑定函数 def impError1(self, e, exception_string): self.setStatusBarMsg(u"导入数据发生错误") QMessageBox.critical(self, u'数据导入', u"发生错误:" + unicode(e)) # 导入数据到地图线程完成信号 绑定函数 def impFinish1(self, mylist): self.threadImp.quit() self.threadImp.wait() self.threadImp.deleteLater() self.impFeatureThread.deleteLater() remsg = u'数据导入完成!' layer = None if self.impType == LayerType.SITE: # remsg = u'基站' + remsg layer = getLayerByName(u'基站', self.iface) elif self.impType == LayerType.CELL: # remsg = u'小区' + remsg layer = getLayerByName(u'小区', self.iface) else: remsg = u'相邻小区' + remsg layer = getLayerByName(u'相邻小区', self.iface) self.setStatusBarMsg(remsg) layer.updateExtents() # 更新地图数据 self.iface.actionDraw().trigger() QMessageBox.information(self, u'数据导入', remsg) merlist = [] for eritm in self.erlist: merlist.append(eritm['item']) self.tableWidget.clearContents() # 先清楚表格的内容,再将错误的行显示到表格中 self.initTable(merlist)
class OWxsh_waviness(widget.OWWidget): name = "xsh_waviness" id = "orange.widgets.preprocessor.xsh_waviness" description = "xoppy application to compute..." icon = "icons/waviness.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 10 category = "" keywords = ["xoppy", "xsh_waviness"] outputs = [{"name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data"}] want_main_area = 1 want_control_area = 1 WIDGET_WIDTH = 1100 WIDGET_HEIGHT = 650 xx = None yy = None zz = None number_of_points_x = Setting(10) number_of_points_y = Setting(100) dimension_x = Setting(20.1) dimension_y = Setting(113.1) estimated_slope_error = Setting(0.9) montecarlo_seed = Setting(2387427) waviness_file_name = Setting('waviness.dat') harmonic_maximum_index = Setting(60) data = Setting({'c': ['0.3', '0.1', '0.1', '0.0', '0.0', '0.0', '0.3', '0.0', '0.0', '0.3', '0.0', '0.0', '0.5', '0.0', '0.0', '0.2', '0.2', '0.2', '0.9', '0.0', '0.0', '0.0', '0.0', '0.0', '0.4', '0.0', '0.0', '0.4', '0.0', '0.0', '0.0', '0.6', '0.6', '0.0', '0.4', '0.4', '0.0', '0.4', '0.4', '0.1', '0.4', '0.4', '0.1', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0'], 'y': ['0.0', '-0.1', '-0.1', '0.0', '0.0', '0.0', '0.03', '0.0', '0.0', '0.2', '0.0', '0.0', '0.2', '0.0', '0.0', '0.1', '0.1', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.0', '0.01', '0.0', '0.0', '0.03', '0.0', '0.0', '0.0', '0.02', '0.02', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.3', '0.3', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.0', '0.0', '0.0'], 'g': ['0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.05', '0.0', '0.0', '0.05', '0.0', '0.0', '0.1', '0.0', '0.0', '0.05', '0.05', '0.05', '0.2', '0.0', '0.0', '0.0', '0.0', '0.0', '0.1', '0.0', '0.0', '0.1', '0.0', '0.0', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.1', '0.1', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0']}) def __init__(self): super().__init__() geom = QApplication.desktop().availableGeometry() self.setGeometry(QRect(round(geom.width() * 0.05), round(geom.height() * 0.05), round(min(geom.width() * 0.98, self.WIDGET_WIDTH)), round(min(geom.height() * 0.95, self.WIDGET_HEIGHT)))) gen_box = ShadowGui.widgetBox(self.controlArea, "Waviness Parameters", addSpace=True, orientation="horizontal", width=500) tabs_setting = gui.tabWidget(gen_box) tab_input = ShadowGui.createTabPage(tabs_setting, "Input Parameter") tab_harmonics = ShadowGui.createTabPage(tabs_setting, "Harmonics") tab_out = ShadowGui.createTabPage(tabs_setting, "Output") self.input_box = ShadowGui.widgetBox(tab_input, "Inputs", addSpace=True, orientation="vertical", width=470) gui.button(self.input_box, self, "Load xsh_waviness input file ...", callback=self.load_inp_file) gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "number_of_points_x", "Number of Points (<201) X (width)", labelWidth=300, valueType=int, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "number_of_points_y", " Y (length)", labelWidth=300, valueType=int, orientation="horizontal") gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "dimension_x", "Dimensions [cm] X (width)", labelWidth=300, valueType=float, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "dimension_y", " Y (length)", labelWidth=300, valueType=float, orientation="horizontal") gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "estimated_slope_error", "Estimated slope error [arcsec]", labelWidth=300, valueType=float, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "montecarlo_seed", "Monte Carlo initial seed", labelWidth=300, valueType=int, orientation="horizontal") self.output_box = ShadowGui.widgetBox(tab_input, "Outputs", addSpace=True, orientation="vertical", width=470) self.select_file_box = ShadowGui.widgetBox(self.output_box, "", addSpace=True, orientation="horizontal") gui.separator(self.output_box) gui.button(self.output_box, self, "Write xsh_waviness input file (optional) ...", callback=self.write_inp_file) ShadowGui.lineEdit(self.select_file_box, self, "waviness_file_name", "Output File Name", labelWidth=120, valueType=str, orientation="horizontal") self.harmonics_box = ShadowGui.widgetBox(tab_harmonics, "Harmonics", addSpace=True, orientation="vertical", width=470, height=690) ShadowGui.lineEdit(self.harmonics_box, self, "harmonic_maximum_index", "Harmonic Maximum Index", labelWidth=300, valueType=int, orientation="horizontal", callback=self.set_harmonics) gui.separator(self.harmonics_box) self.scrollarea = QScrollArea() self.scrollarea.setMaximumWidth(400) self.harmonics_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter) self.shadow_output = QTextEdit() self.shadow_output.setReadOnly(True) out_box = ShadowGui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=600) out_box.layout().addWidget(self.shadow_output) button_box = ShadowGui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Calculate Waviness", callback=self.calculate_waviness) button.setFixedHeight(45) button.setFixedWidth(170) button = gui.button(button_box, self, "Generate Waviness File", callback=self.generate_waviness_file) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(200) button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(120) gui.rubber(self.controlArea) self.figure = Figure(figsize=(600, 600)) self.figure.patch.set_facecolor('white') self.axis = self.figure.add_subplot(111, projection='3d') self.axis.set_xlabel("X (cm)") self.axis.set_ylabel("Y (cm)") self.axis.set_zlabel("Z (µm)") self.figure_canvas = FigureCanvasQTAgg(self.figure) self.mainArea.layout().addWidget(self.figure_canvas) gui.rubber(self.mainArea) def restoreWidgetPosition(self): super().restoreWidgetPosition() self.table = QTableWidget(self.harmonic_maximum_index + 1, 3) self.table.setAlternatingRowColors(True) self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed) for i in range(0, 3): self.table.setColumnWidth(i, 70) horHeaders = [] verHeaders = [] for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() self.table.itemChanged.connect(self.table_item_changed) self.scrollarea.setWidget(self.table) self.scrollarea.setWidgetResizable(1) gui.rubber(self.controlArea) def reload_harmonics_table(self): horHeaders = [] verHeaders = [] self.table.itemChanged.disconnect(self.table_item_changed) self.table.clear() row_count = self.table.rowCount() for n in range(0, row_count): self.table.removeRow(0) for index in range(0, self.harmonic_maximum_index + 1): self.table.insertRow(0) for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() for i in range(0, 3): self.table.setColumnWidth(i, 70) self.table.itemChanged.connect(self.table_item_changed) def table_item_changed(self): dict = {} message = "" error_row_index = -1 error_column_index = -1 previous_value = "" try: row_count = self.harmonic_maximum_index + 1 for column_index in range(0, self.table.columnCount()): column_name = self.table.horizontalHeaderItem(column_index).data(0) row_content = [] for row_index in range(0, row_count): if not self.table.item(row_index, column_index) is None: message = "Value at row " + str( row_index) + " and column \'" + column_name + "\' is not numeric" error_row_index = row_index error_column_index = column_index previous_value = self.data[column_name][row_index] value = float(self.table.item(row_index, column_index).data(0)) # to raise exception row_content.append(str(value)) dict[column_name] = row_content self.data = dict except ValueError: QMessageBox.critical(self, "QMessageBox.critical()", message + "\nValue is reset to previous value", QMessageBox.Ok) table_item = QTableWidgetItem(previous_value) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(error_row_index, error_column_index, table_item) self.table.setCurrentCell(error_row_index, error_column_index) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def set_harmonics(self): if self.harmonic_maximum_index < 0: QMessageBox.critical(self, "QMessageBox.critical()", "Harmonic Maximum Index should be a positive integer number", QMessageBox.Ok) else: row_count = len(self.data["c"]) if self.harmonic_maximum_index + 1 > row_count: for n, key in enumerate(sorted(self.data.keys())): for m in range(row_count, self.harmonic_maximum_index + 1): self.data[key].append('0.0') else: for n, key in enumerate(sorted(self.data.keys())): self.data[key] = copy.deepcopy(self.data[key][0: self.harmonic_maximum_index + 1]) self.reload_harmonics_table() def load_inp_file(self): file_name = QFileDialog.getOpenFileName(self, "Select a input file for XSH_WAVINESS", ".", "*.inp") if not file_name is None: sys.stdout = EmittingStream(textWritten=self.writeStdOut) if not file_name.strip() == "": dict = ST.waviness_read(file=file_name) self.number_of_points_x = dict["npointx"] self.number_of_points_y = dict["npointy"] self.dimension_y = dict["xlength"] self.dimension_x = dict["width"] self.estimated_slope_error = dict["slp"] self.montecarlo_seed = dict["iseed"] self.waviness_file_name = dict["file"].strip('\n\r').strip() self.harmonic_maximum_index = dict["nharmonics"] self.data["c"] = self.to_str_array(dict["c"]) self.data["y"] = self.to_str_array(dict["y"]) self.data["g"] = self.to_str_array(dict["g"]) self.reload_harmonics_table() def write_inp_file(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() file_name = self.waviness_file_name.strip().split(sep=".dat")[0] + ".inp" dict = {} dict["npointx"] = self.number_of_points_x dict["npointy"] = self.number_of_points_y dict["xlength"] = self.dimension_y dict["width"] = self.dimension_x dict["slp"] = self.estimated_slope_error dict["iseed"] = self.montecarlo_seed dict["file"] = self.waviness_file_name.strip('\n\r') dict["nharmonics"] = self.harmonic_maximum_index dict["c"] = self.to_float_array(self.data["c"]) dict["y"] = self.to_float_array(self.data["y"]) dict["g"] = self.to_float_array(self.data["g"]) ST.waviness_write(dict, file=file_name) QMessageBox.information(self, "QMessageBox.information()", "File \'" + file_name + "\' written to disk", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def calculate_waviness(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() xx, yy, zz = ST.waviness_calc(npointx=self.number_of_points_x, npointy=self.number_of_points_y, width=self.dimension_x, xlength=self.dimension_y, slp=self.estimated_slope_error, nharmonics=self.harmonic_maximum_index, iseed=self.montecarlo_seed, c=self.to_float_array(self.data["c"]), y=self.to_float_array(self.data["y"]), g=self.to_float_array(self.data["g"])) self.xx = xx self.yy = yy self.zz = zz self.axis.clear() x_to_plot, y_to_plot = numpy.meshgrid(xx, yy) z_to_plot = [] for y_index in range(0, len(yy)): z_array = [] for x_index in range(0, len(xx)): z_array.append(1e4 * float(zz[x_index][y_index])) # to micron z_to_plot.append(z_array) z_to_plot = numpy.array(z_to_plot) self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot, rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True) slope, sloperms = ST.slopes(zz, xx, yy) title = ' Slope error rms in X direction: %f arcsec' % (sloperms[0]) + '\n' + \ ' : %f urad' % (sloperms[2]) + '\n' + \ ' Slope error rms in Y direction: %f arcsec' % (sloperms[1]) + '\n' + \ ' : %f urad' % (sloperms[3]) self.axis.set_xlabel("X (cm)") self.axis.set_ylabel("Y (cm)") self.axis.set_zlabel("Z (µm)") self.axis.set_title(title) self.axis.mouse_init() self.figure_canvas.draw() QMessageBox.information(self, "QMessageBox.information()", "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def generate_waviness_file(self): if not self.zz is None and not self.yy is None and not self.xx is None: if not self.waviness_file_name is None: self.waviness_file_name = self.waviness_file_name.strip() if self.waviness_file_name == "": raise Exception("Output File Name missing") else: raise Exception("Output File Name missing") sys.stdout = EmittingStream(textWritten=self.writeStdOut) ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=self.waviness_file_name) QMessageBox.information(self, "QMessageBox.information()", "Waviness file " + self.waviness_file_name + " written on disk", QMessageBox.Ok) self.send("PreProcessor_Data", ShadowPreProcessorData(waviness_data_file=self.waviness_file_name)) def call_reset_settings(self): if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"): try: self.resetSettings() self.reload_harmonics_table() except: pass def check_fields(self): self.number_of_points_x = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_x, "Number of Points X") self.number_of_points_y = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_y, "Number of Points Y") self.dimension_x = ShadowGui.checkStrictlyPositiveNumber(self.dimension_x, "Dimension X") self.dimension_y = ShadowGui.checkStrictlyPositiveNumber(self.dimension_y, "Dimension Y") self.estimated_slope_error = ShadowGui.checkPositiveNumber(self.estimated_slope_error, "Estimated slope error") self.montecarlo_seed = ShadowGui.checkPositiveNumber(self.montecarlo_seed, "Monte Carlo initial seed") self.harmonic_maximum_index = ShadowGui.checkPositiveNumber(self.harmonic_maximum_index, "Harmonic Maximum Index") if not self.waviness_file_name is None: self.waviness_file_name = self.waviness_file_name.strip() if self.waviness_file_name == "": raise Exception("Output File Name missing") else: raise Exception("Output File Name missing") def to_float_array(self, string_array): float_array = [] for index in range(len(string_array)): float_array.append(float(string_array[index])) return float_array def to_str_array(self, float_array): string_array = [] for index in range(len(float_array)): string_array.append(str(float_array[index])) return string_array def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
class ApBbaDlg(QDialog): def __init__(self, parent=None, **kwargs): super(ApBbaDlg, self).__init__(parent) self.bpms = [] self.quads = [] self.corrs = [] self.quad_dkicks = [] self.cor_dkicks = [] self.bba = ap.bba.BbaBowtie() self.table = QTableWidget(0, 5) self.table.setMinimumHeight(120) self.table.setMinimumWidth(500) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) hdview = QHeaderView(Qt.Horizontal) self.table.setHorizontalHeaderLabels(["QUAD", "BPM.field", "BPM center", "Corr", "Kick"]) fmbox = QFormLayout() self.subprogress = QProgressBar() self.subprogress.setTextVisible(True) self.subprogress.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.progress = QProgressBar() self.progress.setTextVisible(True) self.progress.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) fmbox.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) fmbox.addRow("Current BPM", self.subprogress) fmbox.addRow("All Alignment", self.progress) # self.progress.setMaximum(self.repeatbox.value()) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(fmbox) # hbox.addStretch() self.widtab = QTabWidget() vbox.addWidget(self.widtab) self.setLayout(vbox) self.connect(self.widtab, SIGNAL("currentChanged(int)"), self.activateResult) self.connect(self.table, SIGNAL("cellClicked(int, int)"), self.activateResult) # self.bbathread = ApBbaThread() # self.connect(self.bbathread, # SIGNAL("aligned(QString, QString, float, float)"), # self.setResult) # self.connect(self.bbathread, # SIGNAL("startAlign(QString, QString, QString)"), # self.appendRecord) # self.connect(self.bbathread, # SIGNAL("aligned(QString, QString, float, float)"), # self.bbadlg.appendResult) def setInput(self, **kwargs): self.bpms = kwargs.get("bpms", []) self.quads = kwargs.get("quads", []) self.cors = kwargs.get("cors", []) self.quad_dkicks = kwargs.get("quad_dkicks", []) self.cor_dkicks = kwargs.get("cor_dkicks", []) def runAlignment(self, **kwargs): self.setInput(**kwargs) # self.bbathread.start() print "Starting %d measurements" % len(self.bpms) self.progress.setMaximum(len(self.bpms)) self.subprogress.setMaximum(100) from cothread.catools import caget, caput print __file__, "BBA align", caget("V:2-SR:C30-BI:G2{PH1:11}SA:X") self.table.setRowCount(len(self.bpms)) for i, bpmrec in enumerate(self.bpms): print i, bpmrec[0].name, self.quads[i][0].name self.bba.setInput(bpmrec, self.quads[i], self.cors[i], self.quad_dkicks[i], self.cor_dkicks[i]) # self.emit(SIGNAL("startAlign(QString, QString, QString)"), # self.quads[i][0].name, bpmrec[0].name, bpmrec[1]) self.setNames(i, self.quads[i][0].name, bpmrec[0].name, bpmrec[1], self.cors[i][0].name) self.bba.align(verbose=2, guihook=QApplication.processEvents, logger=None, progress=self.subprogress) cv1 = BbaMplCanvas() cv2 = BbaMplCanvas() self.bba.plot(cv1.axes, cv2.axes, factor=(1e6, 1e6)) cv1.draw() cv2.draw() wid = QWidget(self) hbox = QHBoxLayout() hbox.addWidget(cv1) hbox.addWidget(cv2) wid.setLayout(hbox) self.widtab.addTab(wid, "%s.%s" % (bpmrec[0].name, bpmrec[1])) self.widtab.setCurrentIndex(i) # time.sleep(.1) # self.emit(SIGNAL("aligned(QString, QString, float, float)"), # bpmrec[0].name, bpmrec[1], 0.0, 0.0) self.setResult(i, bpmrec[0].name, bpmrec[1], self.bba.bpm_fitted, self.bba.cor_fitted) self.progress.setValue(i + 1) def activateResult(self, i=0, j=0): if i < self.widtab.count() and i != self.widtab.currentIndex(): self.widtab.setCurrentIndex(i) if i < self.table.rowCount() and i != self.table.currentRow(): self.table.setCurrentCell(i, 1) def setNames(self, i, quadname, bpmname, fld, corname): self.table.setItem(i, 0, QTableWidgetItem(quadname)) self.table.setItem(i, 1, QTableWidgetItem("{0}.{1}".format(bpmname, fld))) self.table.setItem(i, 3, QTableWidgetItem(corname)) def setResult(self, i, bpmname, fld, bpmval, corval): # self.table.setItem(n, 1, QTableWidgetItem(bpmname)) # self.table.setItem(n, 2, QTableWidgetItem(fld)) self.table.setItem(i, 2, QTableWidgetItem("%g" % bpmval)) self.table.setItem(i, 4, QTableWidgetItem("%g" % corval)) self.table.setCurrentCell(i, 1)
class ScanRecordTable(QGroupBox): """ GUI component. Displays a list of previous scan results. Selecting a scan causes details of the scan to appear in other GUI components (list of barcodes in the barcode table and image of the puck in the image frame). """ COLUMNS = ['Date', 'Time', 'Plate Type', 'Valid', 'Invalid', 'Empty'] def __init__(self, barcode_table, image_frame, options): super(ScanRecordTable, self).__init__() # Read the store from file self._store = Store(options.store_directory.value(), options) self._options = options self._barcodeTable = barcode_table self._imageFrame = image_frame self.setTitle("Scan Records") self._init_ui() self._load_store_records() def _init_ui(self): # Create record table - lists all the records in the store self._table = QTableWidget() self._table.setFixedWidth(440) self._table.setFixedHeight(600) self._table.setColumnCount(len(self.COLUMNS)) self._table.setHorizontalHeaderLabels(self.COLUMNS) self._table.setColumnWidth(0, 70) self._table.setColumnWidth(1, 55) self._table.setColumnWidth(2, 85) self._table.setColumnWidth(3, 60) self._table.setColumnWidth(4, 60) self._table.setColumnWidth(5, 60) self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self._table.cellPressed.connect(self._record_selected) # Delete button - deletes selected records btn_delete = QtGui.QPushButton('Delete') btn_delete.setToolTip('Delete selected scan/s') btn_delete.resize(btn_delete.sizeHint()) btn_delete.clicked.connect(self._delete_selected_records) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(btn_delete) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def add_record(self, plate, image): """ Add a new scan record to the store and display it. """ self._store.add_record(plate, image) self._load_store_records() def add_record_frame(self, plate, image): """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record""" self._store.merge_record(plate, image) self._load_store_records() if self._options.scan_clipboard.value(): self._barcodeTable.copy_selected_to_clipboard() def _load_store_records(self): """ Populate the record table with all of the records in the store. """ self._table.clearContents() self._table.setRowCount(self._store.size()) for n, record in enumerate(self._store.records): items = [record.date, record.time, record.plate_type, record.num_valid_barcodes, record.num_unread_slots, record.num_empty_slots] if (record.num_valid_barcodes + record.num_empty_slots) == record.num_slots: color = self._options.col_ok() else: color = self._options.col_bad() color.a = 192 for m, item in enumerate(items): new_item = QtGui.QTableWidgetItem(str(item)) new_item.setBackgroundColor(color.to_qt()) new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(n, m, new_item) # Display the first (most recent) record self._table.setCurrentCell(0, 0) self._record_selected() def _record_selected(self): """ Called when a row is selected, causes details of the selected record to be displayed (list of barcodes in the barcode table and image of the scan in the image frame). """ try: row = self._table.selectionModel().selectedRows()[0].row() record = self._store.get_record(row) self._barcodeTable.populate(record.barcodes) marked_image = record.marked_image(self._options) self._imageFrame.display_puck_image(marked_image) except IndexError: pass self._barcodeTable.populate([]) self._imageFrame.clear_frame() def _delete_selected_records(self): """ Called when the 'Delete' button is pressed. Deletes all of the selected records (and the associated images) from the store and from disk. Asks for user confirmation. """ # Display a confirmation dialog to check that user wants to proceed with deletion quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?" reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # If yes, find the appropriate records and delete them if reply == QtGui.QMessageBox.Yes: rows = self._table.selectionModel().selectedRows() records_to_delete = [] for row in rows: index = row.row() record = self._store.get_record(index) records_to_delete.append(record) self._store.delete_records(records_to_delete) self._load_store_records()